From 3dc846bf9309aac2fcc3c0620339ffe18c6a4ce9 Mon Sep 17 00:00:00 2001 From: Sukadia <37813632+Sukadia@users.noreply.github.com> Date: Sun, 7 Jan 2024 01:29:26 -0800 Subject: [PATCH] Update Next to v14.0.4 --- .next/BUILD_ID | 2 +- .next/app-build-manifest.json | 96 +- .next/app-path-routes-manifest.json | 2 +- .next/build-manifest.json | 24 +- .next/next-server.js.nft.json | 2 +- .next/prerender-manifest.js | 2 +- .next/prerender-manifest.json | 2 +- .next/required-server-files.json | 2 +- .next/routes-manifest.json | 2 +- .next/server/app-paths-manifest.json | 2 +- .next/server/app/_not-found.html | 2 +- .next/server/app/_not-found.js | 2 +- .next/server/app/_not-found.js.nft.json | 2 +- .next/server/app/_not-found.rsc | 20 +- .../_not-found_client-reference-manifest.js | 2 +- .next/server/app/everyone-votes/privacy.html | 2 +- .next/server/app/everyone-votes/privacy.rsc | 12 +- .../server/app/everyone-votes/privacy/page.js | 2 +- .../everyone-votes/privacy/page.js.nft.json | 2 +- .../privacy/page_client-reference-manifest.js | 2 +- .next/server/app/everyone-votes/terms.html | 2 +- .next/server/app/everyone-votes/terms.rsc | 12 +- .next/server/app/everyone-votes/terms/page.js | 2 +- .../app/everyone-votes/terms/page.js.nft.json | 2 +- .../terms/page_client-reference-manifest.js | 2 +- .next/server/app/favicon.ico/route.js | 13 +- .../server/app/favicon.ico/route.js.nft.json | 2 +- .next/server/app/index.html | 2 +- .next/server/app/index.rsc | 17 +- .next/server/app/page.js | 2 +- .next/server/app/page.js.nft.json | 2 +- .../app/page_client-reference-manifest.js | 2 +- .next/server/app/space.html | 2 +- .next/server/app/space.rsc | 16 +- .next/server/app/space/page.js | 11703 +++++++++++++++- .next/server/app/space/page.js.nft.json | 2 +- .../space/page_client-reference-manifest.js | 2 +- .next/server/app/wiston.html | 2 +- .next/server/app/wiston.rsc | 12 +- .next/server/app/wiston/page.js | 2 +- .next/server/app/wiston/page.js.nft.json | 2 +- .../wiston/page_client-reference-manifest.js | 2 +- .next/server/chunks/106.js | 113 - .next/server/chunks/2.js | 1 - .next/server/chunks/201.js | 12 - .next/server/chunks/310.js | 1 - .next/server/chunks/323.js | 6 - .next/server/chunks/329.js | 6 + .next/server/chunks/337.js | 6 + .next/server/chunks/622.js | 1 - .next/server/chunks/638.js | 1 + .next/server/chunks/676.js | 6 - .next/server/chunks/837.js | 1 - .next/server/chunks/840.js | 1 - .next/server/chunks/862.js | 1 - .next/server/chunks/969.js | 1 + .next/server/chunks/984.js | 11502 --------------- .next/server/middleware-build-manifest.js | 2 +- .next/server/pages/404.html | 2 +- .next/server/pages/500.html | 2 +- .next/server/pages/_app.js | 2 +- .next/server/pages/_app.js.nft.json | 2 +- .next/server/pages/_document.js | 2 +- .next/server/pages/_document.js.nft.json | 2 +- .next/server/pages/_error.js | 2 +- .next/server/pages/_error.js.nft.json | 2 +- .next/server/server-reference-manifest.js | 2 +- .next/server/server-reference-manifest.json | 2 +- .next/server/webpack-runtime.js | 2 +- .../P9X42g8nWZ62i2biioMqg/_buildManifest.js | 1 - .next/static/chunks/173-2ffa9652644381a8.js | 11507 --------------- .../chunks/1f3d3139-8a75094e9a213384.js | 1 + .../chunks/1f3d3139-f107a678ff6361e9.js | 1 - .next/static/chunks/255.f5115df174538d84.js | 1 + .next/static/chunks/472-51fd3a56159f1e5b.js | 25 - .../chunks/537cd76e-7aba1cf7a4752418.js | 2 +- .../chunks/604a08ec-59af37265fb99b3d.js | 4 - .../chunks/604a08ec-edbc4bb5c67ea975.js | 4 + .next/static/chunks/751.591370f90aaa22a6.js | 1 - .next/static/chunks/938-d733aaafb07bca99.js | 1 + .next/static/chunks/973-5f61489a82d0bbab.js | 11699 +++++++++++++++ .next/static/chunks/986-37229c658d9b7b30.js | 9 - .next/static/chunks/986-72006aa1051e30d3.js | 1 + .../chunks/app/_not-found-954fefd8bb45a1c0.js | 1 + .../chunks/app/_not-found-fbdfab077d258bb2.js | 1 - ...94605199e6.js => page-7a71bbf2f721c35f.js} | 2 +- ...88d7e5e9ae.js => page-2d2b3d1433737a22.js} | 2 +- .../chunks/app/layout-2a5e75b3a17431fd.js | 1 + .../chunks/app/layout-ca25527909104096.js | 1 - .../chunks/app/page-39b6caed82efc627.js | 1 - .../chunks/app/page-8af0c2c4af65d19c.js | 1 + .../app/space/loading-a22e96181fd3eee8.js | 1 - .../app/space/loading-b8903409900b99fa.js | 1 + .../chunks/app/space/page-185302d4e0f787e8.js | 1 + .../chunks/app/space/page-b8120f6d5470d1c7.js | 1 - .../app/wiston/page-3411783e09c6cfc5.js | 1 + .../app/wiston/page-a6df78ceae8d716e.js | 1 - .../chunks/d67c510a-4a8f7a6a0c1c3e2a.js | 1 + .../chunks/d67c510a-e497b3cd5bf43bb4.js | 1 - .../chunks/e1206f8c-1ba69cf5e736c266.js | 1 + .../chunks/e1206f8c-ab5b5541f866e530.js | 1 - .../chunks/fd9d1056-519edff8920177a7.js | 1 + .../chunks/fd9d1056-ba10bf844a47945b.js | 9 - .../chunks/framework-8883d1e9be70c3da.js | 8 +- .next/static/chunks/main-07bf56c05aa7cd6e.js | 1 - .next/static/chunks/main-556b0a2270f92b03.js | 1 + .../chunks/main-app-76ef2d05c58d6354.js | 1 + .../chunks/main-app-cf3eb22ffef632f7.js | 1 - .../chunks/pages/_app-1534f180665c857f.js | 1 - .../chunks/pages/_app-98cb51ec6f9f135f.js | 1 + ...40c4f0a8.js => _error-e87e5963ec1b8011.js} | 2 +- .../static/chunks/webpack-c42a79c5d8b7c910.js | 1 - .../static/chunks/webpack-d8e064491704869d.js | 1 + .../xSz9x0FW88Rb7utFdR6Fp/_buildManifest.js | 1 + .../_ssgManifest.js | 0 .next/trace | 83 +- .next/types/app/layout.ts | 79 + package-lock.json | 617 +- package.json | 2 +- 119 files changed, 24236 insertions(+), 23523 deletions(-) delete mode 100644 .next/server/chunks/106.js delete mode 100644 .next/server/chunks/2.js delete mode 100644 .next/server/chunks/201.js delete mode 100644 .next/server/chunks/310.js delete mode 100644 .next/server/chunks/323.js create mode 100644 .next/server/chunks/329.js create mode 100644 .next/server/chunks/337.js delete mode 100644 .next/server/chunks/622.js create mode 100644 .next/server/chunks/638.js delete mode 100644 .next/server/chunks/676.js delete mode 100644 .next/server/chunks/837.js delete mode 100644 .next/server/chunks/840.js delete mode 100644 .next/server/chunks/862.js create mode 100644 .next/server/chunks/969.js delete mode 100644 .next/server/chunks/984.js delete mode 100644 .next/static/P9X42g8nWZ62i2biioMqg/_buildManifest.js delete mode 100644 .next/static/chunks/173-2ffa9652644381a8.js create mode 100644 .next/static/chunks/1f3d3139-8a75094e9a213384.js delete mode 100644 .next/static/chunks/1f3d3139-f107a678ff6361e9.js create mode 100644 .next/static/chunks/255.f5115df174538d84.js delete mode 100644 .next/static/chunks/472-51fd3a56159f1e5b.js delete mode 100644 .next/static/chunks/604a08ec-59af37265fb99b3d.js create mode 100644 .next/static/chunks/604a08ec-edbc4bb5c67ea975.js delete mode 100644 .next/static/chunks/751.591370f90aaa22a6.js create mode 100644 .next/static/chunks/938-d733aaafb07bca99.js create mode 100644 .next/static/chunks/973-5f61489a82d0bbab.js delete mode 100644 .next/static/chunks/986-37229c658d9b7b30.js create mode 100644 .next/static/chunks/986-72006aa1051e30d3.js create mode 100644 .next/static/chunks/app/_not-found-954fefd8bb45a1c0.js delete mode 100644 .next/static/chunks/app/_not-found-fbdfab077d258bb2.js rename .next/static/chunks/app/everyone-votes/privacy/{page-29a62894605199e6.js => page-7a71bbf2f721c35f.js} (62%) rename .next/static/chunks/app/everyone-votes/terms/{page-c0da9088d7e5e9ae.js => page-2d2b3d1433737a22.js} (62%) create mode 100644 .next/static/chunks/app/layout-2a5e75b3a17431fd.js delete mode 100644 .next/static/chunks/app/layout-ca25527909104096.js delete mode 100644 .next/static/chunks/app/page-39b6caed82efc627.js create mode 100644 .next/static/chunks/app/page-8af0c2c4af65d19c.js delete mode 100644 .next/static/chunks/app/space/loading-a22e96181fd3eee8.js create mode 100644 .next/static/chunks/app/space/loading-b8903409900b99fa.js create mode 100644 .next/static/chunks/app/space/page-185302d4e0f787e8.js delete mode 100644 .next/static/chunks/app/space/page-b8120f6d5470d1c7.js create mode 100644 .next/static/chunks/app/wiston/page-3411783e09c6cfc5.js delete mode 100644 .next/static/chunks/app/wiston/page-a6df78ceae8d716e.js create mode 100644 .next/static/chunks/d67c510a-4a8f7a6a0c1c3e2a.js delete mode 100644 .next/static/chunks/d67c510a-e497b3cd5bf43bb4.js create mode 100644 .next/static/chunks/e1206f8c-1ba69cf5e736c266.js delete mode 100644 .next/static/chunks/e1206f8c-ab5b5541f866e530.js create mode 100644 .next/static/chunks/fd9d1056-519edff8920177a7.js delete mode 100644 .next/static/chunks/fd9d1056-ba10bf844a47945b.js delete mode 100644 .next/static/chunks/main-07bf56c05aa7cd6e.js create mode 100644 .next/static/chunks/main-556b0a2270f92b03.js create mode 100644 .next/static/chunks/main-app-76ef2d05c58d6354.js delete mode 100644 .next/static/chunks/main-app-cf3eb22ffef632f7.js delete mode 100644 .next/static/chunks/pages/_app-1534f180665c857f.js create mode 100644 .next/static/chunks/pages/_app-98cb51ec6f9f135f.js rename .next/static/chunks/pages/{_error-b646007f40c4f0a8.js => _error-e87e5963ec1b8011.js} (74%) delete mode 100644 .next/static/chunks/webpack-c42a79c5d8b7c910.js create mode 100644 .next/static/chunks/webpack-d8e064491704869d.js create mode 100644 .next/static/xSz9x0FW88Rb7utFdR6Fp/_buildManifest.js rename .next/static/{P9X42g8nWZ62i2biioMqg => xSz9x0FW88Rb7utFdR6Fp}/_ssgManifest.js (100%) create mode 100644 .next/types/app/layout.ts diff --git a/.next/BUILD_ID b/.next/BUILD_ID index 91865d4..05ed909 100644 --- a/.next/BUILD_ID +++ b/.next/BUILD_ID @@ -1 +1 @@ -P9X42g8nWZ62i2biioMqg \ No newline at end of file +xSz9x0FW88Rb7utFdR6Fp \ No newline at end of file diff --git a/.next/app-build-manifest.json b/.next/app-build-manifest.json index 1a3ceb7..054c82f 100644 --- a/.next/app-build-manifest.json +++ b/.next/app-build-manifest.json @@ -1,69 +1,69 @@ { "pages": { "/_not-found": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js", - "static/chunks/app/_not-found-fbdfab077d258bb2.js" + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js", + "static/chunks/app/_not-found-954fefd8bb45a1c0.js" ], "/layout": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js", + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js", "static/css/1d2d59615145af7d.css", - "static/chunks/app/layout-ca25527909104096.js" - ], - "/everyone-votes/privacy/page": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js", - "static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js" + "static/chunks/app/layout-2a5e75b3a17431fd.js" ], "/everyone-votes/terms/page": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js", - "static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js" + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js", + "static/chunks/app/everyone-votes/terms/page-2d2b3d1433737a22.js" + ], + "/everyone-votes/privacy/page": [ + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js", + "static/chunks/app/everyone-votes/privacy/page-7a71bbf2f721c35f.js" ], "/page": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js", - "static/chunks/986-37229c658d9b7b30.js", + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js", + "static/chunks/986-72006aa1051e30d3.js", "static/css/60c69e914bf8dd4b.css", - "static/chunks/app/page-39b6caed82efc627.js" + "static/chunks/app/page-8af0c2c4af65d19c.js" ], "/space/page": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js", - "static/chunks/e1206f8c-ab5b5541f866e530.js", - "static/chunks/1f3d3139-f107a678ff6361e9.js", - "static/chunks/604a08ec-59af37265fb99b3d.js", - "static/chunks/d67c510a-e497b3cd5bf43bb4.js", + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js", + "static/chunks/e1206f8c-1ba69cf5e736c266.js", + "static/chunks/1f3d3139-8a75094e9a213384.js", + "static/chunks/604a08ec-edbc4bb5c67ea975.js", + "static/chunks/d67c510a-4a8f7a6a0c1c3e2a.js", "static/chunks/537cd76e-7aba1cf7a4752418.js", - "static/chunks/173-2ffa9652644381a8.js", - "static/chunks/app/space/page-b8120f6d5470d1c7.js" + "static/chunks/973-5f61489a82d0bbab.js", + "static/chunks/app/space/page-185302d4e0f787e8.js" ], "/space/loading": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js", - "static/chunks/app/space/loading-a22e96181fd3eee8.js" + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js", + "static/chunks/app/space/loading-b8903409900b99fa.js" ], "/wiston/page": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js", - "static/chunks/app/wiston/page-a6df78ceae8d716e.js" + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js", + "static/chunks/app/wiston/page-3411783e09c6cfc5.js" ] } } \ No newline at end of file diff --git a/.next/app-path-routes-manifest.json b/.next/app-path-routes-manifest.json index ff03eba..e5fc0ac 100644 --- a/.next/app-path-routes-manifest.json +++ b/.next/app-path-routes-manifest.json @@ -1 +1 @@ -{"/_not-found":"/_not-found","/everyone-votes/privacy/page":"/everyone-votes/privacy","/everyone-votes/terms/page":"/everyone-votes/terms","/favicon.ico/route":"/favicon.ico","/page":"/","/space/page":"/space","/wiston/page":"/wiston"} \ No newline at end of file +{"/_not-found":"/_not-found","/everyone-votes/terms/page":"/everyone-votes/terms","/everyone-votes/privacy/page":"/everyone-votes/privacy","/favicon.ico/route":"/favicon.ico","/page":"/","/space/page":"/space","/wiston/page":"/wiston"} \ No newline at end of file diff --git a/.next/build-manifest.json b/.next/build-manifest.json index f69a1da..2b2759a 100644 --- a/.next/build-manifest.json +++ b/.next/build-manifest.json @@ -5,27 +5,27 @@ "devFiles": [], "ampDevFiles": [], "lowPriorityFiles": [ - "static/P9X42g8nWZ62i2biioMqg/_buildManifest.js", - "static/P9X42g8nWZ62i2biioMqg/_ssgManifest.js" + "static/xSz9x0FW88Rb7utFdR6Fp/_buildManifest.js", + "static/xSz9x0FW88Rb7utFdR6Fp/_ssgManifest.js" ], "rootMainFiles": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", - "static/chunks/fd9d1056-ba10bf844a47945b.js", - "static/chunks/472-51fd3a56159f1e5b.js", - "static/chunks/main-app-cf3eb22ffef632f7.js" + "static/chunks/webpack-d8e064491704869d.js", + "static/chunks/fd9d1056-519edff8920177a7.js", + "static/chunks/938-d733aaafb07bca99.js", + "static/chunks/main-app-76ef2d05c58d6354.js" ], "pages": { "/_app": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/webpack-d8e064491704869d.js", "static/chunks/framework-8883d1e9be70c3da.js", - "static/chunks/main-07bf56c05aa7cd6e.js", - "static/chunks/pages/_app-1534f180665c857f.js" + "static/chunks/main-556b0a2270f92b03.js", + "static/chunks/pages/_app-98cb51ec6f9f135f.js" ], "/_error": [ - "static/chunks/webpack-c42a79c5d8b7c910.js", + "static/chunks/webpack-d8e064491704869d.js", "static/chunks/framework-8883d1e9be70c3da.js", - "static/chunks/main-07bf56c05aa7cd6e.js", - "static/chunks/pages/_error-b646007f40c4f0a8.js" + "static/chunks/main-556b0a2270f92b03.js", + "static/chunks/pages/_error-e87e5963ec1b8011.js" ] }, "ampFirstPages": [] diff --git a/.next/next-server.js.nft.json b/.next/next-server.js.nft.json index 16ff2f4..fad7542 100644 --- a/.next/next-server.js.nft.json +++ b/.next/next-server.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../node_modules/styled-jsx/index.js","../node_modules/styled-jsx/package.json","../node_modules/styled-jsx/dist/index/index.js","../node_modules/react/package.json","../node_modules/react/index.js","../node_modules/client-only/package.json","../node_modules/react/cjs/react.production.min.js","../node_modules/client-only/index.js","../node_modules/styled-jsx/style.js","../node_modules/next/dist/server/next-server.js","../node_modules/next/package.json","../node_modules/next/dist/server/node-environment.js","../node_modules/next/dist/server/require-hook.js","../node_modules/next/dist/server/base-server.js","../node_modules/next/dist/server/node-polyfill-crypto.js","../node_modules/next/dist/server/request-meta.js","../node_modules/next/dist/lib/find-pages-dir.js","../node_modules/next/dist/server/send-payload.js","../node_modules/next/dist/server/load-components.js","../node_modules/next/dist/server/require.js","../node_modules/next/dist/lib/is-error.js","../node_modules/next/dist/server/body-streams.js","../node_modules/next/dist/server/setup-http-agent-env.js","../node_modules/next/dist/lib/constants.js","../node_modules/next/dist/server/pipe-readable.js","../node_modules/next/dist/server/load-manifest.js","../node_modules/next/dist/server/image-optimizer.js","../node_modules/next/dist/lib/format-server-error.js","../node_modules/next/dist/lib/picocolors.js","../node_modules/next/dist/server/serve-static.js","../node_modules/next/dist/shared/lib/utils.js","../node_modules/next/dist/server/base-http/node.js","../node_modules/next/dist/shared/lib/constants.js","../node_modules/next/dist/build/output/log.js","../node_modules/next/dist/server/web/utils.js","../node_modules/next/dist/server/lib/node-fs-methods.js","../node_modules/next/dist/client/components/app-router-headers.js","../node_modules/next/dist/server/lib/mock-request.js","../node_modules/next/dist/experimental/testmode/server.js","../node_modules/next/dist/server/lib/trace/tracer.js","../node_modules/next/dist/server/lib/trace/constants.js","../node_modules/next/dist/server/future/route-matches/pages-api-route-match.js","../node_modules/next/dist/server/lib/server-ipc/invoke-request.js","../node_modules/next/dist/server/lib/server-ipc/utils.js","../node_modules/next/dist/shared/lib/page-path/normalize-page-path.js","../node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js","../node_modules/next/dist/shared/lib/router/utils/route-matcher.js","../node_modules/next/dist/shared/lib/router/utils/parse-url.js","../node_modules/next/dist/shared/lib/router/utils/querystring.js","../node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js","../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js","../node_modules/next/dist/server/web/spec-extension/adapters/next-request.js","../node_modules/next/dist/server/future/helpers/module-loader/route-module-loader.js","../node_modules/next/dist/server/future/route-modules/app-page/module.render.js","../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../node_modules/next/dist/shared/lib/router/utils/route-regex.js","../node_modules/next/dist/server/future/route-modules/pages/module.render.js","../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../node_modules/next/dist/client/components/request-async-storage.external.js","../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../node_modules/next/dist/server/api-utils/index.js","../node_modules/next/dist/server/response-cache/index.js","../node_modules/next/dist/server/lib/incremental-cache/index.js","../node_modules/next/dist/server/web/sandbox/index.js","../node_modules/next/dist/lib/interop-default.js","../node_modules/next/dist/lib/wait.js","../node_modules/next/dist/lib/detached-promise.js","../node_modules/@next/env/package.json","../node_modules/next/dist/shared/lib/is-plain-object.js","../node_modules/next/dist/server/lib/revalidate.js","../node_modules/next/dist/server/lib/etag.js","../node_modules/next/dist/shared/lib/match-remote-pattern.js","../node_modules/next/dist/shared/lib/image-blur-svg.js","../node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js","../node_modules/next/dist/server/lib/squoosh/main.js","../node_modules/next/dist/server/base-http/index.js","../node_modules/next/dist/shared/lib/modern-browserslist-target.js","../node_modules/next/dist/lib/redirect-status.js","../node_modules/next/dist/lib/is-edge-runtime.js","../node_modules/next/dist/server/utils.js","../node_modules/next/dist/server/render-result.js","../node_modules/next/dist/server/server-utils.js","../node_modules/next/dist/server/send-response.js","../node_modules/next/dist/server/internal-utils.js","../node_modules/next/dist/server/lib/format-hostname.js","../node_modules/next/dist/shared/lib/runtime-config.external.js","../node_modules/next/dist/shared/lib/get-hostname.js","../node_modules/next/dist/server/future/route-kind.js","../node_modules/next/dist/server/lib/match-next-data-pathname.js","../node_modules/next/dist/server/future/route-matcher-managers/default-route-matcher-manager.js","../node_modules/next/dist/server/future/normalizers/locale-route-normalizer.js","../node_modules/next/dist/server/future/route-matcher-providers/pages-api-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/app-page-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/app-route-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/pages-route-matcher-provider.js","../node_modules/next/dist/server/future/helpers/i18n-provider.js","../node_modules/next/dist/server/api-utils/node/try-get-preview-data.js","../node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js","../node_modules/@next/env/dist/index.js","../node_modules/next/dist/client/components/async-local-storage.js","../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js","../node_modules/next/dist/shared/lib/segment.js","../node_modules/next/dist/shared/lib/escape-regexp.js","../node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js","../node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js","../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../node_modules/next/dist/lib/batcher.js","../node_modules/next/dist/lib/scheduler.js","../node_modules/next/dist/server/future/route-modules/helpers/response-handlers.js","../node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js","../node_modules/next/dist/server/future/normalizers/request/rsc.js","../node_modules/next/dist/server/future/normalizers/request/postponed.js","../node_modules/next/dist/server/web/spec-extension/request.js","../node_modules/next/dist/server/future/helpers/interception-routes.js","../node_modules/next/dist/server/response-cache/types.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader.js","../node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js","../node_modules/next/dist/server/future/route-modules/app-page/module.compiled.js","../node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js","../node_modules/next/dist/server/future/helpers/module-loader/node-module-loader.js","../node_modules/next/dist/shared/lib/router/utils/prepare-destination.js","../node_modules/next/dist/server/future/route-modules/pages/module.compiled.js","../node_modules/next/dist/server/web/spec-extension/adapters/headers.js","../node_modules/next/dist/shared/lib/isomorphic/path.js","../node_modules/next/dist/server/lib/incremental-cache/fetch-cache.js","../node_modules/next/dist/server/lib/incremental-cache/file-system-cache.js","../node_modules/next/dist/server/lib/server-ipc/request-utils.js","../node_modules/next/dist/server/web/sandbox/sandbox.js","../node_modules/next/dist/server/web/sandbox/context.js","../node_modules/next/dist/shared/lib/router/utils/index.js","../node_modules/next/dist/compiled/ws/package.json","../node_modules/next/dist/compiled/lru-cache/package.json","../node_modules/next/dist/compiled/fresh/package.json","../node_modules/next/dist/compiled/get-orientation/package.json","../node_modules/next/dist/compiled/image-size/package.json","../node_modules/next/dist/compiled/content-disposition/package.json","../node_modules/next/dist/compiled/send/package.json","../node_modules/react-dom/package.json","../node_modules/next/dist/compiled/is-animated/package.json","../node_modules/next/dist/server/stream-utils/node-web-streams-helper.js","../node_modules/next/dist/server/api-utils/get-cookie-parser.js","../node_modules/next/dist/compiled/@hapi/accept/package.json","../node_modules/@swc/helpers/_/_interop_require_default/package.json","../node_modules/next/dist/server/lib/is-ipv6.js","../node_modules/next/dist/lib/is-api-route.js","../node_modules/next/dist/lib/is-app-page-route.js","../node_modules/next/dist/lib/is-app-route-route.js","../node_modules/next/dist/server/crypto-utils.js","../node_modules/next/dist/server/accept-header.js","../node_modules/next/dist/shared/lib/router/utils/path-match.js","../node_modules/react-dom/server.browser.js","../node_modules/next/dist/server/future/route-matchers/locale-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/pages-api-route-matcher.js","../node_modules/next/dist/server/future/route-matcher-providers/manifest-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matchers/app-page-route-matcher.js","../node_modules/next/dist/server/web/spec-extension/cookies.js","../node_modules/next/dist/server/future/route-matchers/app-route-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/pages-route-matcher.js","../node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js","../node_modules/next/dist/compiled/ws/index.js","../node_modules/next/dist/compiled/lru-cache/index.js","../node_modules/next/dist/server/web/next-url.js","../node_modules/next/dist/server/web/error.js","../node_modules/next/dist/compiled/fresh/index.js","../node_modules/next/dist/compiled/get-orientation/index.js","../node_modules/next/dist/compiled/image-size/index.js","../node_modules/next/dist/compiled/content-disposition/index.js","../node_modules/next/dist/compiled/send/index.js","../node_modules/next/dist/compiled/@mswjs/interceptors/ClientRequest/package.json","../node_modules/next/dist/compiled/is-animated/index.js","../node_modules/next/dist/shared/lib/router/utils/format-url.js","../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../node_modules/@swc/helpers/package.json","../node_modules/next/dist/compiled/node-html-parser/package.json","../node_modules/next/dist/compiled/jsonwebtoken/package.json","../node_modules/next/dist/compiled/cookie/package.json","../node_modules/next/dist/shared/lib/router/utils/is-dynamic.js","../node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js","../node_modules/next/dist/lib/pick.js","../node_modules/next/dist/compiled/@hapi/accept/index.js","../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../node_modules/next/dist/server/web/sandbox/resource-managers.js","../node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js","../node_modules/next/dist/server/web/spec-extension/adapters/reflect.js","../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../node_modules/next/dist/compiled/node-html-parser/index.js","../node_modules/next/dist/compiled/jsonwebtoken/index.js","../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../node_modules/next/dist/compiled/cookie/index.js","../node_modules/next/dist/compiled/@mswjs/interceptors/ClientRequest/index.js","../node_modules/next/dist/shared/lib/router/utils/sorted-routes.js","../node_modules/next/dist/server/future/normalizers/built/pages/index.js","../node_modules/next/dist/server/future/normalizers/built/app/index.js","../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../node_modules/next/dist/server/stream-utils/encode-decode.js","../node_modules/next/dist/compiled/micromatch/package.json","../node_modules/next/dist/server/future/route-matchers/route-matcher.js","../node_modules/next/dist/compiled/micromatch/index.js","../node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js","../node_modules/next/dist/compiled/next-server/app-page-experimental.runtime.prod.js","../node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js","../node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/cached-route-matcher-provider.js","../node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js","../node_modules/next/dist/server/future/route-modules/app-page/module.js","../node_modules/next/dist/server/future/route-modules/pages/module.js","../node_modules/next/dist/compiled/path-browserify/package.json","../node_modules/next/dist/compiled/edge-runtime/package.json","../node_modules/next/dist/compiled/path-to-regexp/index.js","../node_modules/next/dist/compiled/path-browserify/index.js","../node_modules/next/dist/compiled/edge-runtime/index.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-pathname-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-bundle-path-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-page-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-bundle-path-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-page-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-pathname-normalizer.js","../node_modules/next/dist/compiled/debug/package.json","../node_modules/next/dist/compiled/@edge-runtime/cookies/package.json","../node_modules/next/dist/lib/semver-noop.js","../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../node_modules/next/dist/server/render.js","../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../node_modules/next/dist/shared/lib/router/utils/add-locale.js","../node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js","../node_modules/next/dist/server/app-render/app-render.js","../node_modules/next/dist/compiled/debug/index.js","../node_modules/next/dist/server/future/route-modules/route-module.js","../node_modules/next/dist/compiled/@edge-runtime/cookies/index.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/ssr/entrypoints.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/entrypoints.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/rsc/entrypoints.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/entrypoints.js","../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../node_modules/next/dist/server/future/normalizers/absolute-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/normalizers.js","../node_modules/next/dist/server/future/normalizers/prefixing-normalizer.js","../node_modules/next/dist/server/future/normalizers/wrap-normalizer-fn.js","../node_modules/next/dist/server/future/normalizers/underscore-normalizer.js","../node_modules/next/dist/lib/is-serializable-props.js","../node_modules/next/dist/server/post-process.js","../node_modules/next/dist/shared/lib/amp-mode.js","../node_modules/next/dist/shared/lib/head.js","../node_modules/next/dist/shared/lib/amp-context.shared-runtime.js","../node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js","../node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js","../node_modules/next/dist/shared/lib/router-context.shared-runtime.js","../node_modules/next/dist/shared/lib/loadable.shared-runtime.js","../node_modules/next/dist/shared/lib/html-context.shared-runtime.js","../node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js","../node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js","../node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js","../node_modules/next/dist/shared/lib/router/adapters.js","../node_modules/next/dist/server/app-render/create-server-components-renderer.js","../node_modules/next/dist/server/async-storage/static-generation-async-storage-wrapper.js","../node_modules/next/dist/lib/metadata/metadata.js","../node_modules/next/dist/server/async-storage/request-async-storage-wrapper.js","../node_modules/next/dist/client/components/match-segments.js","../node_modules/next/dist/client/components/redirect.js","../node_modules/next/dist/client/components/get-redirect-status-code-from-error.js","../node_modules/next/dist/client/components/not-found.js","../node_modules/next/dist/server/lib/patch-fetch.js","../node_modules/next/dist/server/app-render/get-script-nonce-from-header.js","../node_modules/next/dist/server/app-render/create-error-handler.js","../node_modules/next/dist/server/app-render/flight-render-result.js","../node_modules/next/dist/server/app-render/validate-url.js","../node_modules/next/dist/server/app-render/get-segment-param.js","../node_modules/next/dist/server/app-render/get-short-dynamic-param-type.js","../node_modules/next/dist/server/app-render/parse-and-validate-flight-router-state.js","../node_modules/next/dist/server/app-render/server-inserted-html.js","../node_modules/next/dist/server/app-render/create-flight-router-state-from-loader-tree.js","../node_modules/next/dist/server/app-render/required-scripts.js","../node_modules/next/dist/server/app-render/make-get-server-inserted-html.js","../node_modules/next/dist/server/app-render/action-handler.js","../node_modules/next/dist/server/app-render/walk-tree-with-flight-router-state.js","../node_modules/next/dist/server/app-render/action-encryption-utils.js","../node_modules/next/dist/server/app-render/create-component-tree.js","../node_modules/next/dist/client/components/dev-root-not-found-boundary.js","../node_modules/next/dist/server/app-render/get-asset-query-string.js","../node_modules/next/dist/shared/lib/lazy-dynamic/no-ssr-error.js","../node_modules/next/dist/server/app-render/static/static-renderer.js","../node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js","../node_modules/next/dist/lib/non-nullable.js","../node_modules/next/dist/server/optimize-amp.js","../node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js","../node_modules/next/dist/shared/lib/side-effect.js","../node_modules/next/dist/shared/lib/image-config.js","../node_modules/next/dist/server/htmlescape.js","../node_modules/next/dist/lib/client-reference.js","../node_modules/next/dist/compiled/strip-ansi/package.json","../node_modules/next/dist/compiled/react-is/package.json","../node_modules/next/dist/shared/lib/utils/warn-once.js","../node_modules/next/dist/server/app-render/use-flight-response.js","../node_modules/next/dist/server/async-storage/draft-mode-provider.js","../node_modules/next/dist/lib/metadata/resolve-metadata.js","../node_modules/next/dist/lib/metadata/default-metadata.js","../node_modules/next/dist/client/components/hooks-server-context.js","../node_modules/next/dist/server/dev/log-app-dir-error.js","../node_modules/next/dist/client/components/maybe-postpone.js","../node_modules/next/dist/server/app-render/types.js","../node_modules/next/dist/server/app-render/react-server.node.js","../node_modules/next/dist/server/app-render/get-css-inlined-link-tags.js","../node_modules/next/dist/server/app-render/get-preloadable-fonts.js","../node_modules/next/dist/server/app-render/get-layer-assets.js","../node_modules/next/dist/server/app-render/has-loading-component-in-tree.js","../node_modules/next/dist/server/app-render/parse-loader-tree.js","../node_modules/next/dist/client/components/not-found-boundary.js","../node_modules/next/dist/server/app-render/preload-component.js","../node_modules/next/dist/server/lib/app-dir-module.js","../node_modules/next/dist/server/app-render/interop-default.js","../node_modules/next/dist/server/app-render/create-component-styles-and-scripts.js","../node_modules/next/dist/lib/metadata/generate/icons.js","../node_modules/next/dist/lib/metadata/generate/alternate.js","../node_modules/next/dist/lib/metadata/generate/opengraph.js","../node_modules/next/dist/lib/metadata/generate/basic.js","../node_modules/next/dist/lib/metadata/generate/meta.js","../node_modules/next/dist/compiled/nanoid/package.json","../node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js","../node_modules/next/dist/compiled/strip-ansi/index.js","../node_modules/next/dist/compiled/react-is/index.js","../node_modules/next/dist/compiled/nanoid/index.cjs","../node_modules/react/jsx-runtime.js","../node_modules/react/jsx-dev-runtime.js","../node_modules/next/dist/lib/metadata/get-metadata-route.js","../node_modules/busboy/package.json","../node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js","../node_modules/next/dist/lib/metadata/clone-metadata.js","../node_modules/next/dist/client/components/navigation.js","../node_modules/next/dist/lib/metadata/generate/utils.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-opengraph.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-title.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-basics.js","../node_modules/busboy/lib/index.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-icons.js","../node_modules/next/dist/compiled/string-hash/package.json","../node_modules/next/dist/compiled/superstruct/package.json","../node_modules/next/dist/lib/metadata/constants.js","../node_modules/next/dist/compiled/bytes/package.json","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react-jsx-dev-runtime.production.min.js","../node_modules/react-dom/index.js","../node_modules/next/dist/compiled/react-is/cjs/react-is.production.min.js","../node_modules/next/dist/compiled/react-is/cjs/react-is.development.js","../node_modules/next/dist/compiled/string-hash/index.js","../node_modules/next/dist/compiled/superstruct/index.cjs","../node_modules/next/dist/compiled/bytes/index.js","../node_modules/next/dist/shared/lib/hash.js","../node_modules/next/dist/lib/metadata/is-metadata-route.js","../node_modules/busboy/lib/utils.js","../node_modules/busboy/lib/types/urlencoded.js","../node_modules/busboy/lib/types/multipart.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/next/dist/client/components/client-hook-in-server-component-error.js","../node_modules/next/dist/client/components/bailout-to-client-rendering.js","../node_modules/next/dist/client/components/router-reducer/reducers/get-segment-value.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-url.js","../node_modules/scheduler/package.json","../node_modules/streamsearch/package.json","../node_modules/scheduler/index.js","../node_modules/streamsearch/lib/sbmh.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/cjs/scheduler.development.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/amp-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/app-router-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/head-manager-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/hooks-client-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/html-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/image-config-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/loadable-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/loadable.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/router-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/server-inserted-html.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/amp-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/app-router-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/head-manager-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/hooks-client-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/html-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/image-config-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/loadable-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/loadable.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/router-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/server-inserted-html.js"]} \ No newline at end of file +{"version":1,"files":["../node_modules/styled-jsx/index.js","../node_modules/styled-jsx/package.json","../node_modules/styled-jsx/dist/index/index.js","../node_modules/react/package.json","../node_modules/react/index.js","../node_modules/client-only/package.json","../node_modules/react/cjs/react.production.min.js","../node_modules/client-only/index.js","../node_modules/styled-jsx/style.js","../node_modules/next/dist/server/next-server.js","../node_modules/next/package.json","../node_modules/next/dist/server/request-meta.js","../node_modules/next/dist/server/node-environment.js","../node_modules/next/dist/server/require-hook.js","../node_modules/next/dist/server/node-polyfill-crypto.js","../node_modules/next/dist/server/base-server.js","../node_modules/next/dist/lib/find-pages-dir.js","../node_modules/next/dist/server/send-payload.js","../node_modules/next/dist/server/require.js","../node_modules/next/dist/server/load-components.js","../node_modules/next/dist/lib/is-error.js","../node_modules/next/dist/server/body-streams.js","../node_modules/next/dist/server/setup-http-agent-env.js","../node_modules/next/dist/lib/constants.js","../node_modules/next/dist/server/pipe-readable.js","../node_modules/next/dist/server/load-manifest.js","../node_modules/next/dist/server/serve-static.js","../node_modules/next/dist/lib/format-server-error.js","../node_modules/next/dist/lib/picocolors.js","../node_modules/next/dist/server/image-optimizer.js","../node_modules/next/dist/shared/lib/utils.js","../node_modules/next/dist/shared/lib/constants.js","../node_modules/next/dist/server/base-http/node.js","../node_modules/next/dist/build/output/log.js","../node_modules/next/dist/server/web/utils.js","../node_modules/next/dist/server/lib/node-fs-methods.js","../node_modules/next/dist/server/lib/mock-request.js","../node_modules/next/dist/client/components/app-router-headers.js","../node_modules/next/dist/shared/lib/page-path/denormalize-page-path.js","../node_modules/next/dist/shared/lib/page-path/normalize-page-path.js","../node_modules/next/dist/server/future/route-matches/pages-api-route-match.js","../node_modules/next/dist/server/lib/trace/tracer.js","../node_modules/next/dist/server/lib/trace/constants.js","../node_modules/next/dist/server/lib/server-ipc/utils.js","../node_modules/next/dist/server/lib/server-ipc/invoke-request.js","../node_modules/next/dist/shared/lib/router/utils/route-matcher.js","../node_modules/next/dist/shared/lib/router/utils/parse-url.js","../node_modules/next/dist/shared/lib/router/utils/remove-trailing-slash.js","../node_modules/next/dist/shared/lib/router/utils/middleware-route-matcher.js","../node_modules/next/dist/shared/lib/router/utils/get-next-pathname-info.js","../node_modules/next/dist/shared/lib/router/utils/querystring.js","../node_modules/next/dist/shared/lib/router/utils/app-paths.js","../node_modules/next/dist/shared/lib/router/utils/route-regex.js","../node_modules/next/dist/server/web/spec-extension/adapters/next-request.js","../node_modules/next/dist/server/future/helpers/module-loader/route-module-loader.js","../node_modules/next/dist/server/future/route-modules/app-page/module.render.js","../node_modules/next/dist/server/future/route-modules/pages/module.render.js","../node_modules/next/dist/client/components/action-async-storage.external.js","../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../node_modules/next/dist/client/components/request-async-storage.external.js","../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../node_modules/next/dist/server/api-utils/index.js","../node_modules/next/dist/server/response-cache/index.js","../node_modules/next/dist/server/lib/incremental-cache/index.js","../node_modules/next/dist/server/web/sandbox/index.js","../node_modules/next/dist/lib/interop-default.js","../node_modules/next/dist/lib/wait.js","../node_modules/next/dist/lib/detached-promise.js","../node_modules/@next/env/package.json","../node_modules/next/dist/server/lib/revalidate.js","../node_modules/next/dist/server/lib/etag.js","../node_modules/next/dist/shared/lib/is-plain-object.js","../node_modules/next/dist/experimental/testmode/server.js","../node_modules/next/dist/shared/lib/image-blur-svg.js","../node_modules/next/dist/shared/lib/match-remote-pattern.js","../node_modules/next/dist/shared/lib/i18n/normalize-locale-path.js","../node_modules/next/dist/server/lib/squoosh/main.js","../node_modules/next/dist/lib/redirect-status.js","../node_modules/next/dist/lib/is-edge-runtime.js","../node_modules/next/dist/server/utils.js","../node_modules/next/dist/server/render-result.js","../node_modules/next/dist/server/server-utils.js","../node_modules/next/dist/server/send-response.js","../node_modules/next/dist/server/internal-utils.js","../node_modules/next/dist/shared/lib/modern-browserslist-target.js","../node_modules/next/dist/server/base-http/index.js","../node_modules/next/dist/client/components/redirect-status-code.js","../node_modules/next/dist/server/lib/format-hostname.js","../node_modules/next/dist/shared/lib/runtime-config.external.js","../node_modules/next/dist/shared/lib/get-hostname.js","../node_modules/next/dist/server/lib/match-next-data-pathname.js","../node_modules/next/dist/server/app-render/strip-flight-headers.js","../node_modules/next/dist/server/lib/server-action-request-meta.js","../node_modules/next/dist/server/future/route-kind.js","../node_modules/next/dist/server/future/normalizers/locale-route-normalizer.js","../node_modules/next/dist/server/future/route-matcher-managers/default-route-matcher-manager.js","../node_modules/next/dist/server/future/route-matcher-providers/app-page-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/pages-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/app-route-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matcher-providers/pages-api-route-matcher-provider.js","../node_modules/next/dist/server/future/route-modules/checks.js","../node_modules/next/dist/server/future/helpers/i18n-provider.js","../node_modules/next/dist/server/api-utils/node/try-get-preview-data.js","../node_modules/next/dist/shared/lib/i18n/get-locale-redirect.js","../node_modules/next/dist/shared/lib/page-path/ensure-leading-slash.js","../node_modules/next/dist/shared/lib/page-path/normalize-path-sep.js","../node_modules/@next/env/dist/index.js","../node_modules/next/dist/client/components/async-local-storage.js","../node_modules/next/dist/shared/lib/segment.js","../node_modules/next/dist/shared/lib/escape-regexp.js","../node_modules/next/dist/shared/lib/router/utils/is-bot.js","../node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js","../node_modules/next/dist/shared/lib/router/utils/remove-path-prefix.js","../node_modules/next/dist/server/future/route-modules/helpers/response-handlers.js","../node_modules/next/dist/shared/lib/router/utils/get-route-from-asset-path.js","../node_modules/next/dist/server/future/normalizers/request/rsc.js","../node_modules/next/dist/server/future/normalizers/request/postponed.js","../node_modules/next/dist/server/future/normalizers/request/prefetch-rsc.js","../node_modules/next/dist/server/future/normalizers/request/next-data.js","../node_modules/next/dist/lib/scheduler.js","../node_modules/next/dist/lib/batcher.js","../node_modules/next/dist/server/future/helpers/interception-routes.js","../node_modules/next/dist/server/web/spec-extension/request.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader.js","../node_modules/next/dist/server/response-cache/types.js","../node_modules/next/dist/server/response-cache/utils.js","../node_modules/next/dist/shared/lib/router/utils/parse-relative-url.js","../node_modules/next/dist/shared/lib/router/utils/prepare-destination.js","../node_modules/next/dist/shared/lib/router/utils/path-has-prefix.js","../node_modules/next/dist/server/future/helpers/module-loader/node-module-loader.js","../node_modules/next/dist/server/future/route-modules/app-page/module.compiled.js","../node_modules/next/dist/server/future/route-modules/pages/module.compiled.js","../node_modules/next/dist/server/web/spec-extension/adapters/headers.js","../node_modules/next/dist/shared/lib/isomorphic/path.js","../node_modules/next/dist/server/lib/incremental-cache/file-system-cache.js","../node_modules/next/dist/server/lib/incremental-cache/fetch-cache.js","../node_modules/next/dist/server/lib/server-ipc/request-utils.js","../node_modules/next/dist/server/web/sandbox/context.js","../node_modules/next/dist/server/web/sandbox/sandbox.js","../node_modules/next/dist/shared/lib/router/utils/index.js","../node_modules/next/dist/experimental/testmode/context.js","../node_modules/next/dist/experimental/testmode/fetch.js","../node_modules/next/dist/experimental/testmode/httpget.js","../node_modules/next/dist/compiled/ws/package.json","../node_modules/next/dist/compiled/fresh/package.json","../node_modules/next/dist/compiled/lru-cache/package.json","../node_modules/next/dist/compiled/send/package.json","../node_modules/next/dist/compiled/get-orientation/package.json","../node_modules/next/dist/compiled/image-size/package.json","../node_modules/next/dist/compiled/is-animated/package.json","../node_modules/next/dist/compiled/content-disposition/package.json","../node_modules/react-dom/package.json","../node_modules/next/dist/server/stream-utils/node-web-streams-helper.js","../node_modules/next/dist/server/api-utils/get-cookie-parser.js","../node_modules/next/dist/compiled/@hapi/accept/package.json","../node_modules/next/dist/server/lib/is-ipv6.js","../node_modules/@swc/helpers/_/_interop_require_default/package.json","../node_modules/next/dist/lib/is-app-page-route.js","../node_modules/next/dist/lib/is-api-route.js","../node_modules/next/dist/lib/is-app-route-route.js","../node_modules/next/dist/server/crypto-utils.js","../node_modules/next/dist/server/accept-header.js","../node_modules/next/dist/shared/lib/router/utils/path-match.js","../node_modules/react-dom/server.browser.js","../node_modules/next/dist/server/future/route-matchers/locale-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/app-page-route-matcher.js","../node_modules/next/dist/server/future/route-matcher-providers/manifest-route-matcher-provider.js","../node_modules/next/dist/server/future/route-matchers/pages-route-matcher.js","../node_modules/next/dist/server/future/route-matchers/app-route-route-matcher.js","../node_modules/next/dist/server/web/spec-extension/cookies.js","../node_modules/next/dist/server/future/route-matchers/pages-api-route-matcher.js","../node_modules/next/dist/shared/lib/i18n/detect-domain-locale.js","../node_modules/next/dist/compiled/ws/index.js","../node_modules/next/dist/compiled/fresh/index.js","../node_modules/next/dist/compiled/lru-cache/index.js","../node_modules/next/dist/compiled/send/index.js","../node_modules/next/dist/server/web/error.js","../node_modules/next/dist/server/web/next-url.js","../node_modules/next/dist/compiled/image-size/index.js","../node_modules/next/dist/compiled/get-orientation/index.js","../node_modules/next/dist/compiled/is-animated/index.js","../node_modules/next/dist/compiled/content-disposition/index.js","../node_modules/next/dist/shared/lib/router/utils/format-url.js","../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../node_modules/@swc/helpers/package.json","../node_modules/next/dist/compiled/node-html-parser/package.json","../node_modules/next/dist/compiled/jsonwebtoken/package.json","../node_modules/next/dist/compiled/cookie/package.json","../node_modules/next/dist/server/web/spec-extension/adapters/request-cookies.js","../node_modules/next/dist/shared/lib/router/utils/is-dynamic.js","../node_modules/next/dist/server/future/normalizers/request/suffix.js","../node_modules/next/dist/server/future/normalizers/request/prefix.js","../node_modules/next/dist/compiled/@hapi/accept/index.js","../node_modules/next/dist/lib/pick.js","../node_modules/next/dist/shared/lib/router/utils/parse-path.js","../node_modules/next/dist/server/web/sandbox/resource-managers.js","../node_modules/next/dist/server/web/sandbox/fetch-inline-assets.js","../node_modules/next/dist/server/web/spec-extension/adapters/reflect.js","../node_modules/@swc/helpers/cjs/_interop_require_default.cjs","../node_modules/next/dist/compiled/node-html-parser/index.js","../node_modules/next/dist/compiled/jsonwebtoken/index.js","../node_modules/next/dist/compiled/cookie/index.js","../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../node_modules/next/dist/shared/lib/router/utils/sorted-routes.js","../node_modules/next/dist/server/future/normalizers/built/app/index.js","../node_modules/next/dist/server/future/normalizers/built/pages/index.js","../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../node_modules/next/dist/server/stream-utils/encode-decode.js","../node_modules/next/dist/compiled/micromatch/package.json","../node_modules/next/dist/server/future/route-matchers/route-matcher.js","../node_modules/next/dist/compiled/micromatch/index.js","../node_modules/next/dist/server/future/route-matcher-providers/helpers/cached-route-matcher-provider.js","../node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js","../node_modules/next/dist/compiled/next-server/app-page-experimental.runtime.prod.js","../node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js","../node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js","../node_modules/next/dist/shared/lib/router/utils/format-next-pathname-info.js","../node_modules/next/dist/server/future/route-modules/app-page/module.js","../node_modules/next/dist/server/future/route-modules/pages/module.js","../node_modules/next/dist/compiled/path-browserify/package.json","../node_modules/next/dist/compiled/edge-runtime/package.json","../node_modules/next/dist/compiled/path-to-regexp/index.js","../node_modules/next/dist/compiled/path-browserify/index.js","../node_modules/next/dist/compiled/edge-runtime/index.js","../node_modules/next/dist/server/future/normalizers/built/app/app-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-page-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-bundle-path-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/app/app-pathname-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-pathname-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-bundle-path-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-filename-normalizer.js","../node_modules/next/dist/server/future/normalizers/built/pages/pages-page-normalizer.js","../node_modules/next/dist/compiled/@mswjs/interceptors/ClientRequest/package.json","../node_modules/next/dist/compiled/debug/package.json","../node_modules/next/dist/compiled/@edge-runtime/cookies/package.json","../node_modules/@swc/helpers/_/_interop_require_wildcard/package.json","../node_modules/next/dist/lib/semver-noop.js","../node_modules/next/dist/server/render.js","../node_modules/next/dist/compiled/@mswjs/interceptors/ClientRequest/index.js","../node_modules/next/dist/shared/lib/router/utils/add-locale.js","../node_modules/next/dist/shared/lib/router/utils/add-path-suffix.js","../node_modules/next/dist/shared/lib/router/utils/add-path-prefix.js","../node_modules/next/dist/server/app-render/app-render.js","../node_modules/next/dist/compiled/debug/index.js","../node_modules/next/dist/server/future/route-modules/route-module.js","../node_modules/next/dist/compiled/@edge-runtime/cookies/index.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/entrypoints.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/ssr/entrypoints.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/rsc/entrypoints.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/entrypoints.js","../node_modules/@swc/helpers/cjs/_interop_require_wildcard.cjs","../node_modules/next/dist/server/future/normalizers/prefixing-normalizer.js","../node_modules/next/dist/server/future/normalizers/normalizers.js","../node_modules/next/dist/server/future/normalizers/wrap-normalizer-fn.js","../node_modules/next/dist/server/future/normalizers/underscore-normalizer.js","../node_modules/next/dist/server/future/normalizers/absolute-filename-normalizer.js","../node_modules/next/dist/lib/is-serializable-props.js","../node_modules/next/dist/server/post-process.js","../node_modules/next/dist/shared/lib/head.js","../node_modules/next/dist/shared/lib/amp-context.shared-runtime.js","../node_modules/next/dist/shared/lib/amp-mode.js","../node_modules/next/dist/shared/lib/head-manager-context.shared-runtime.js","../node_modules/next/dist/shared/lib/loadable.shared-runtime.js","../node_modules/next/dist/shared/lib/router-context.shared-runtime.js","../node_modules/next/dist/shared/lib/loadable-context.shared-runtime.js","../node_modules/next/dist/shared/lib/html-context.shared-runtime.js","../node_modules/next/dist/shared/lib/image-config-context.shared-runtime.js","../node_modules/next/dist/shared/lib/hooks-client-context.shared-runtime.js","../node_modules/next/dist/shared/lib/app-router-context.shared-runtime.js","../node_modules/next/dist/shared/lib/router/adapters.js","../node_modules/next/dist/server/app-render/create-server-components-renderer.js","../node_modules/next/dist/client/components/match-segments.js","../node_modules/next/dist/lib/metadata/metadata.js","../node_modules/next/dist/server/async-storage/request-async-storage-wrapper.js","../node_modules/next/dist/server/async-storage/static-generation-async-storage-wrapper.js","../node_modules/next/dist/server/lib/patch-fetch.js","../node_modules/next/dist/client/components/not-found.js","../node_modules/next/dist/client/components/redirect.js","../node_modules/next/dist/server/app-render/create-error-handler.js","../node_modules/next/dist/server/app-render/flight-render-result.js","../node_modules/next/dist/server/app-render/get-short-dynamic-param-type.js","../node_modules/next/dist/server/app-render/get-segment-param.js","../node_modules/next/dist/server/app-render/get-script-nonce-from-header.js","../node_modules/next/dist/server/app-render/parse-and-validate-flight-router-state.js","../node_modules/next/dist/server/app-render/validate-url.js","../node_modules/next/dist/client/components/hooks-server-context.js","../node_modules/next/dist/server/app-render/create-flight-router-state-from-loader-tree.js","../node_modules/next/dist/server/app-render/action-handler.js","../node_modules/next/dist/server/app-render/server-inserted-html.js","../node_modules/next/dist/server/app-render/required-scripts.js","../node_modules/next/dist/server/app-render/walk-tree-with-flight-router-state.js","../node_modules/next/dist/server/app-render/create-component-tree.js","../node_modules/next/dist/server/app-render/make-get-server-inserted-html.js","../node_modules/next/dist/server/app-render/get-asset-query-string.js","../node_modules/next/dist/server/app-render/is-missing-postpone-error.js","../node_modules/next/dist/server/app-render/action-encryption-utils.js","../node_modules/next/dist/client/components/dev-root-not-found-boundary.js","../node_modules/next/dist/shared/lib/lazy-dynamic/no-ssr-error.js","../node_modules/next/dist/server/app-render/static/static-renderer.js","../node_modules/next/dist/shared/lib/server-inserted-html.shared-runtime.js","../node_modules/next/dist/lib/non-nullable.js","../node_modules/next/dist/server/optimize-amp.js","../node_modules/next/dist/shared/lib/page-path/absolute-path-to-page.js","../node_modules/next/dist/shared/lib/side-effect.js","../node_modules/next/dist/shared/lib/image-config.js","../node_modules/next/dist/server/htmlescape.js","../node_modules/next/dist/lib/client-reference.js","../node_modules/next/dist/compiled/strip-ansi/package.json","../node_modules/next/dist/compiled/react-is/package.json","../node_modules/next/dist/shared/lib/utils/warn-once.js","../node_modules/next/dist/server/app-render/use-flight-response.js","../node_modules/next/dist/lib/metadata/resolve-metadata.js","../node_modules/next/dist/lib/metadata/default-metadata.js","../node_modules/next/dist/server/async-storage/draft-mode-provider.js","../node_modules/next/dist/server/dev/log-app-dir-error.js","../node_modules/next/dist/export/helpers/is-dynamic-usage-error.js","../node_modules/next/dist/server/app-render/types.js","../node_modules/next/dist/server/app-render/react-server.node.js","../node_modules/next/dist/server/app-render/get-css-inlined-link-tags.js","../node_modules/next/dist/server/app-render/get-preloadable-fonts.js","../node_modules/next/dist/server/app-render/get-layer-assets.js","../node_modules/next/dist/server/app-render/parse-loader-tree.js","../node_modules/next/dist/server/lib/app-dir-module.js","../node_modules/next/dist/server/app-render/has-loading-component-in-tree.js","../node_modules/next/dist/server/app-render/interop-default.js","../node_modules/next/dist/server/app-render/create-component-styles-and-scripts.js","../node_modules/next/dist/client/components/not-found-boundary.js","../node_modules/next/dist/lib/metadata/generate/basic.js","../node_modules/next/dist/lib/metadata/generate/alternate.js","../node_modules/next/dist/lib/metadata/generate/opengraph.js","../node_modules/next/dist/lib/metadata/generate/meta.js","../node_modules/next/dist/lib/metadata/generate/icons.js","../node_modules/next/dist/compiled/nanoid/package.json","../node_modules/next/dist/shared/lib/router/utils/as-path-to-search-params.js","../node_modules/next/dist/compiled/strip-ansi/index.js","../node_modules/next/dist/compiled/react-is/index.js","../node_modules/next/dist/compiled/nanoid/index.cjs","../node_modules/react/jsx-runtime.js","../node_modules/react/jsx-dev-runtime.js","../node_modules/next/dist/lib/metadata/get-metadata-route.js","../node_modules/busboy/package.json","../node_modules/next/dist/shared/lib/page-path/remove-page-path-tail.js","../node_modules/next/dist/lib/metadata/clone-metadata.js","../node_modules/next/dist/client/components/navigation.js","../node_modules/next/dist/lib/metadata/generate/utils.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-opengraph.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-title.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-basics.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-icons.js","../node_modules/busboy/lib/index.js","../node_modules/next/dist/lib/metadata/constants.js","../node_modules/next/dist/compiled/string-hash/package.json","../node_modules/next/dist/compiled/superstruct/package.json","../node_modules/next/dist/compiled/bytes/package.json","../node_modules/react-dom/index.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/cjs/react-jsx-dev-runtime.production.min.js","../node_modules/next/dist/compiled/react-is/cjs/react-is.development.js","../node_modules/next/dist/compiled/react-is/cjs/react-is.production.min.js","../node_modules/next/dist/compiled/string-hash/index.js","../node_modules/next/dist/compiled/superstruct/index.cjs","../node_modules/next/dist/compiled/bytes/index.js","../node_modules/next/dist/lib/metadata/is-metadata-route.js","../node_modules/next/dist/shared/lib/hash.js","../node_modules/busboy/lib/utils.js","../node_modules/busboy/lib/types/urlencoded.js","../node_modules/busboy/lib/types/multipart.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/next/dist/client/components/client-hook-in-server-component-error.js","../node_modules/next/dist/client/components/bailout-to-client-rendering.js","../node_modules/next/dist/client/components/router-reducer/reducers/get-segment-value.js","../node_modules/next/dist/lib/metadata/resolvers/resolve-url.js","../node_modules/scheduler/package.json","../node_modules/streamsearch/package.json","../node_modules/scheduler/index.js","../node_modules/streamsearch/lib/sbmh.js","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/cjs/scheduler.development.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/amp-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/app-router-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/head-manager-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/hooks-client-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/html-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/image-config-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/loadable-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/loadable.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/router-context.js","../node_modules/next/dist/server/future/route-modules/app-page/vendored/contexts/server-inserted-html.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/amp-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/app-router-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/head-manager-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/hooks-client-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/html-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/image-config-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/loadable-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/loadable.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/router-context.js","../node_modules/next/dist/server/future/route-modules/pages/vendored/contexts/server-inserted-html.js"]} \ No newline at end of file diff --git a/.next/prerender-manifest.js b/.next/prerender-manifest.js index 34b30fb..7d0ddb1 100644 --- a/.next/prerender-manifest.js +++ b/.next/prerender-manifest.js @@ -1 +1 @@ -self.__PRERENDER_MANIFEST="{\"version\":4,\"routes\":{\"/favicon.ico\":{\"initialHeaders\":{\"cache-control\":\"public, max-age=0, must-revalidate\",\"content-type\":\"image/x-icon\",\"x-next-cache-tags\":\"_N_T_/layout,_N_T_/favicon.ico/layout,_N_T_/favicon.ico/route,_N_T_/favicon.ico\"},\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/favicon.ico\",\"dataRoute\":null},\"/wiston\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/wiston\",\"dataRoute\":\"/wiston.rsc\"},\"/everyone-votes/privacy\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/everyone-votes/privacy\",\"dataRoute\":\"/everyone-votes/privacy.rsc\"},\"/everyone-votes/terms\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/everyone-votes/terms\",\"dataRoute\":\"/everyone-votes/terms.rsc\"},\"/\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/\",\"dataRoute\":\"/index.rsc\"},\"/space\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/space\",\"dataRoute\":\"/space.rsc\"}},\"dynamicRoutes\":{},\"notFoundRoutes\":[],\"preview\":{\"previewModeId\":\"20c20528d0e40b20b60128854326961a\",\"previewModeSigningKey\":\"be5a411f2fc596e12c07c744c5b3765b33f359d9cdf1e50e4b4f3df77d3c000a\",\"previewModeEncryptionKey\":\"bde2fed56fa844159ab0b012a2c003096b59e91c0745138ec7a9e1c4ddc660e3\"}}" \ No newline at end of file +self.__PRERENDER_MANIFEST="{\"version\":4,\"routes\":{\"/favicon.ico\":{\"initialHeaders\":{\"cache-control\":\"public, max-age=0, must-revalidate\",\"content-type\":\"image/x-icon\",\"x-next-cache-tags\":\"_N_T_/layout,_N_T_/favicon.ico/layout,_N_T_/favicon.ico/route,_N_T_/favicon.ico\"},\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/favicon.ico\",\"dataRoute\":null},\"/everyone-votes/terms\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/everyone-votes/terms\",\"dataRoute\":\"/everyone-votes/terms.rsc\"},\"/everyone-votes/privacy\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/everyone-votes/privacy\",\"dataRoute\":\"/everyone-votes/privacy.rsc\"},\"/\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/\",\"dataRoute\":\"/index.rsc\"},\"/wiston\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/wiston\",\"dataRoute\":\"/wiston.rsc\"},\"/space\":{\"experimentalBypassFor\":[{\"type\":\"header\",\"key\":\"Next-Action\"},{\"type\":\"header\",\"key\":\"content-type\",\"value\":\"multipart/form-data\"}],\"initialRevalidateSeconds\":false,\"srcRoute\":\"/space\",\"dataRoute\":\"/space.rsc\"}},\"dynamicRoutes\":{},\"notFoundRoutes\":[],\"preview\":{\"previewModeId\":\"ef8045dd883b24c46f5e1dcb17f6a42f\",\"previewModeSigningKey\":\"e3c0026f0a2f05041186a8da9f09ebf1526584f3b0b71d4d87445128b115dea0\",\"previewModeEncryptionKey\":\"351af1c9275cb83cd1aec2a8e439d55c46e618c1f41a594d0c81feda4bd9eb35\"}}" \ No newline at end of file diff --git a/.next/prerender-manifest.json b/.next/prerender-manifest.json index b57720c..932636f 100644 --- a/.next/prerender-manifest.json +++ b/.next/prerender-manifest.json @@ -1 +1 @@ -{"version":4,"routes":{"/favicon.ico":{"initialHeaders":{"cache-control":"public, max-age=0, must-revalidate","content-type":"image/x-icon","x-next-cache-tags":"_N_T_/layout,_N_T_/favicon.ico/layout,_N_T_/favicon.ico/route,_N_T_/favicon.ico"},"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/favicon.ico","dataRoute":null},"/wiston":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/wiston","dataRoute":"/wiston.rsc"},"/everyone-votes/privacy":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/privacy","dataRoute":"/everyone-votes/privacy.rsc"},"/everyone-votes/terms":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/terms","dataRoute":"/everyone-votes/terms.rsc"},"/":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/","dataRoute":"/index.rsc"},"/space":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/space","dataRoute":"/space.rsc"}},"dynamicRoutes":{},"notFoundRoutes":[],"preview":{"previewModeId":"20c20528d0e40b20b60128854326961a","previewModeSigningKey":"be5a411f2fc596e12c07c744c5b3765b33f359d9cdf1e50e4b4f3df77d3c000a","previewModeEncryptionKey":"bde2fed56fa844159ab0b012a2c003096b59e91c0745138ec7a9e1c4ddc660e3"}} \ No newline at end of file +{"version":4,"routes":{"/favicon.ico":{"initialHeaders":{"cache-control":"public, max-age=0, must-revalidate","content-type":"image/x-icon","x-next-cache-tags":"_N_T_/layout,_N_T_/favicon.ico/layout,_N_T_/favicon.ico/route,_N_T_/favicon.ico"},"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/favicon.ico","dataRoute":null},"/everyone-votes/terms":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/terms","dataRoute":"/everyone-votes/terms.rsc"},"/everyone-votes/privacy":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/everyone-votes/privacy","dataRoute":"/everyone-votes/privacy.rsc"},"/":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/","dataRoute":"/index.rsc"},"/wiston":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/wiston","dataRoute":"/wiston.rsc"},"/space":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/space","dataRoute":"/space.rsc"}},"dynamicRoutes":{},"notFoundRoutes":[],"preview":{"previewModeId":"ef8045dd883b24c46f5e1dcb17f6a42f","previewModeSigningKey":"e3c0026f0a2f05041186a8da9f09ebf1526584f3b0b71d4d87445128b115dea0","previewModeEncryptionKey":"351af1c9275cb83cd1aec2a8e439d55c46e618c1f41a594d0c81feda4bd9eb35"}} \ No newline at end of file diff --git a/.next/required-server-files.json b/.next/required-server-files.json index c35d7d7..3d69a46 100644 --- a/.next/required-server-files.json +++ b/.next/required-server-files.json @@ -1 +1 @@ -{"version":1,"config":{"env":{},"webpack":null,"eslint":{"ignoreDuringBuilds":false},"typescript":{"ignoreBuildErrors":false,"tsconfigPath":"tsconfig.json"},"distDir":".next","cleanDistDir":true,"assetPrefix":"","configOrigin":"next.config.js","useFileSystemPublicRoutes":true,"generateEtags":true,"pageExtensions":["tsx","ts","jsx","js"],"poweredByHeader":true,"compress":true,"analyticsId":"","images":{"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","loaderFile":"","domains":[],"disableStaticImages":false,"minimumCacheTTL":60,"formats":["image/webp"],"dangerouslyAllowSVG":false,"contentSecurityPolicy":"script-src 'none'; frame-src 'none'; sandbox;","contentDispositionType":"inline","remotePatterns":[],"unoptimized":false},"devIndicators":{"buildActivity":true,"buildActivityPosition":"bottom-right"},"onDemandEntries":{"maxInactiveAge":60000,"pagesBufferLength":5},"amp":{"canonicalBase":""},"basePath":"","sassOptions":{},"trailingSlash":false,"i18n":null,"productionBrowserSourceMaps":false,"optimizeFonts":true,"excludeDefaultMomentLocales":true,"serverRuntimeConfig":{},"publicRuntimeConfig":{},"reactProductionProfiling":false,"reactStrictMode":null,"httpAgentOptions":{"keepAlive":true},"outputFileTracing":true,"staticPageGenerationTimeout":60,"swcMinify":true,"modularizeImports":{"@mui/icons-material":{"transform":"@mui/icons-material/{{member}}"},"date-fns":{"transform":"date-fns/{{member}}"},"lodash":{"transform":"lodash/{{member}}"},"lodash-es":{"transform":"lodash-es/{{member}}"},"ramda":{"transform":"ramda/es/{{member}}"},"react-bootstrap":{"transform":{"useAccordionButton":"modularize-import-loader?name=useAccordionButton&from=named&as=default!react-bootstrap/AccordionButton","*":"react-bootstrap/{{member}}"}},"antd":{"transform":"antd/lib/{{kebabCase member}}"},"ahooks":{"transform":{"createUpdateEffect":"modularize-import-loader?name=createUpdateEffect&from=named&as=default!ahooks/es/createUpdateEffect","*":"ahooks/es/{{member}}"}},"@ant-design/icons":{"transform":{"IconProvider":"modularize-import-loader?name=IconProvider&from=named&as=default!@ant-design/icons","createFromIconfontCN":"@ant-design/icons/es/components/IconFont","getTwoToneColor":"modularize-import-loader?name=getTwoToneColor&from=named&as=default!@ant-design/icons/es/components/twoTonePrimaryColor","setTwoToneColor":"modularize-import-loader?name=setTwoToneColor&from=named&as=default!@ant-design/icons/es/components/twoTonePrimaryColor","*":"@ant-design/icons/lib/icons/{{member}}"}},"next/server":{"transform":"next/dist/server/web/exports/{{ kebabCase member }}"}},"experimental":{"serverMinification":true,"serverSourceMaps":false,"caseSensitiveRoutes":false,"useDeploymentId":false,"useDeploymentIdServerActions":false,"clientRouterFilter":true,"clientRouterFilterRedirects":false,"fetchCacheKeyPrefix":"","middlewarePrefetch":"flexible","optimisticClientCache":true,"manualClientBasePath":false,"cpus":15,"memoryBasedWorkersCount":false,"isrFlushToDisk":true,"workerThreads":false,"optimizeCss":false,"nextScriptWorkers":false,"scrollRestoration":false,"externalDir":false,"disableOptimizedLoading":false,"gzipSize":true,"craCompat":false,"esmExternals":true,"isrMemoryCacheSize":52428800,"fullySpecified":false,"outputFileTracingRoot":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev","swcTraceProfiling":false,"forceSwcTransforms":false,"largePageDataBytes":128000,"adjustFontFallbacks":false,"adjustFontFallbacksWithSizeAdjust":false,"typedRoutes":false,"instrumentationHook":false,"bundlePagesExternals":false,"optimizePackageImports":["lucide-react","@headlessui/react","@headlessui-float/react","@heroicons/react/20/solid","@heroicons/react/24/solid","@heroicons/react/24/outline","@visx/visx","@tremor/react","rxjs","@mui/material","@mui/icons-material","recharts","react-use","@material-ui/core","@material-ui/icons","@tabler/icons-react","mui-core","react-icons/ai","react-icons/bi","react-icons/bs","react-icons/cg","react-icons/ci","react-icons/di","react-icons/fa","react-icons/fa6","react-icons/fc","react-icons/fi","react-icons/gi","react-icons/go","react-icons/gr","react-icons/hi","react-icons/hi2","react-icons/im","react-icons/io","react-icons/io5","react-icons/lia","react-icons/lib","react-icons/lu","react-icons/md","react-icons/pi","react-icons/ri","react-icons/rx","react-icons/si","react-icons/sl","react-icons/tb","react-icons/tfi","react-icons/ti","react-icons/vsc","react-icons/wi"],"trustHostHeader":false,"isExperimentalCompile":false},"configFileName":"next.config.js","_originalRedirects":[{"source":"/:slug(yt|youtube)","destination":"https://www.youtube.com/Sukadia","permanent":false},{"source":"/:slug(vod|vods)","destination":"https://www.youtube.com/channel/UC8S8l4sY8YsVcngSBTVyoSA","permanent":false},{"source":"/:slug(dev|update|updates)","destination":"https://www.youtube.com/channel/UCbzmy3xP2E0rLhCPFktbwAQ","permanent":false},{"source":"/:slug(ttv|twitch)","destination":"https://www.twitch.tv/Sukadia","permanent":false},{"source":"/:slug(hub|discord)","destination":"https://discord.gg/ReSCjYpXnK","permanent":false},{"source":"/:slug(ev|everyonevotes|everyone-votes)","destination":"https://top.gg/bot/805922495705251891","permanent":false},{"source":"/:slug(kofi|ko-fi)","destination":"https://ko-fi.com/sukadia/tiers","permanent":false},{"source":"/poster","destination":"https://ko-fi.com/s/3cf296742e","permanent":false},{"source":"/dark","destination":"https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark","permanent":false},{"source":"/banner","destination":"https://www.youtube.com/watch?v=tvq5aBROV_s","permanent":false},{"source":"/nsfw","destination":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","permanent":false}]},"appDir":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev","relativeAppDir":"","files":[".next\\routes-manifest.json",".next\\server\\pages-manifest.json",".next\\build-manifest.json",".next\\prerender-manifest.json",".next\\prerender-manifest.js",".next\\server\\middleware-manifest.json",".next\\server\\middleware-build-manifest.js",".next\\server\\middleware-react-loadable-manifest.js",".next\\server\\app-paths-manifest.json",".next\\app-path-routes-manifest.json",".next\\app-build-manifest.json",".next\\server\\server-reference-manifest.js",".next\\server\\server-reference-manifest.json",".next\\react-loadable-manifest.json",".next\\server\\font-manifest.json",".next\\BUILD_ID",".next\\server\\next-font-manifest.js",".next\\server\\next-font-manifest.json"],"ignore":["node_modules\\next\\dist\\compiled\\@ampproject\\toolbox-optimizer\\**\\*"]} \ No newline at end of file +{"version":1,"config":{"env":{},"webpack":null,"eslint":{"ignoreDuringBuilds":false},"typescript":{"ignoreBuildErrors":false,"tsconfigPath":"tsconfig.json"},"distDir":".next","cleanDistDir":true,"assetPrefix":"","configOrigin":"next.config.js","useFileSystemPublicRoutes":true,"generateEtags":true,"pageExtensions":["tsx","ts","jsx","js"],"poweredByHeader":true,"compress":true,"analyticsId":"","images":{"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","loaderFile":"","domains":[],"disableStaticImages":false,"minimumCacheTTL":60,"formats":["image/webp"],"dangerouslyAllowSVG":false,"contentSecurityPolicy":"script-src 'none'; frame-src 'none'; sandbox;","contentDispositionType":"inline","remotePatterns":[],"unoptimized":false},"devIndicators":{"buildActivity":true,"buildActivityPosition":"bottom-right"},"onDemandEntries":{"maxInactiveAge":60000,"pagesBufferLength":5},"amp":{"canonicalBase":""},"basePath":"","sassOptions":{},"trailingSlash":false,"i18n":null,"productionBrowserSourceMaps":false,"optimizeFonts":true,"excludeDefaultMomentLocales":true,"serverRuntimeConfig":{},"publicRuntimeConfig":{},"reactProductionProfiling":false,"reactStrictMode":null,"httpAgentOptions":{"keepAlive":true},"outputFileTracing":true,"staticPageGenerationTimeout":60,"swcMinify":true,"modularizeImports":{"@mui/icons-material":{"transform":"@mui/icons-material/{{member}}"},"lodash":{"transform":"lodash/{{member}}"},"next/server":{"transform":"next/dist/server/web/exports/{{ kebabCase member }}"}},"experimental":{"windowHistorySupport":false,"serverMinification":true,"serverSourceMaps":false,"caseSensitiveRoutes":false,"useDeploymentId":false,"useDeploymentIdServerActions":false,"clientRouterFilter":true,"clientRouterFilterRedirects":false,"fetchCacheKeyPrefix":"","middlewarePrefetch":"flexible","optimisticClientCache":true,"manualClientBasePath":false,"cpus":15,"memoryBasedWorkersCount":false,"isrFlushToDisk":true,"workerThreads":false,"optimizeCss":false,"nextScriptWorkers":false,"scrollRestoration":false,"externalDir":false,"disableOptimizedLoading":false,"gzipSize":true,"craCompat":false,"esmExternals":true,"isrMemoryCacheSize":52428800,"fullySpecified":false,"outputFileTracingRoot":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev","swcTraceProfiling":false,"forceSwcTransforms":false,"largePageDataBytes":128000,"adjustFontFallbacks":false,"adjustFontFallbacksWithSizeAdjust":false,"typedRoutes":false,"instrumentationHook":false,"bundlePagesExternals":false,"ppr":false,"webpackBuildWorker":false,"optimizePackageImports":["lucide-react","date-fns","lodash-es","ramda","antd","react-bootstrap","ahooks","@ant-design/icons","@headlessui/react","@headlessui-float/react","@heroicons/react/20/solid","@heroicons/react/24/solid","@heroicons/react/24/outline","@visx/visx","@tremor/react","rxjs","@mui/material","@mui/icons-material","recharts","react-use","@material-ui/core","@material-ui/icons","@tabler/icons-react","mui-core","react-icons/ai","react-icons/bi","react-icons/bs","react-icons/cg","react-icons/ci","react-icons/di","react-icons/fa","react-icons/fa6","react-icons/fc","react-icons/fi","react-icons/gi","react-icons/go","react-icons/gr","react-icons/hi","react-icons/hi2","react-icons/im","react-icons/io","react-icons/io5","react-icons/lia","react-icons/lib","react-icons/lu","react-icons/md","react-icons/pi","react-icons/ri","react-icons/rx","react-icons/si","react-icons/sl","react-icons/tb","react-icons/tfi","react-icons/ti","react-icons/vsc","react-icons/wi"],"trustHostHeader":false,"isExperimentalCompile":false},"configFileName":"next.config.js","_originalRedirects":[{"source":"/:slug(yt|youtube)","destination":"https://www.youtube.com/Sukadia","permanent":false},{"source":"/:slug(vod|vods)","destination":"https://www.youtube.com/channel/UC8S8l4sY8YsVcngSBTVyoSA","permanent":false},{"source":"/:slug(dev|update|updates)","destination":"https://www.youtube.com/channel/UCbzmy3xP2E0rLhCPFktbwAQ","permanent":false},{"source":"/:slug(ttv|twitch)","destination":"https://www.twitch.tv/Sukadia","permanent":false},{"source":"/:slug(hub|discord)","destination":"https://discord.gg/ReSCjYpXnK","permanent":false},{"source":"/:slug(ev|everyonevotes|everyone-votes)","destination":"https://top.gg/bot/805922495705251891","permanent":false},{"source":"/:slug(kofi|ko-fi)","destination":"https://ko-fi.com/sukadia/tiers","permanent":false},{"source":"/poster","destination":"https://ko-fi.com/s/3cf296742e","permanent":false},{"source":"/dark","destination":"https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark","permanent":false},{"source":"/banner","destination":"https://www.youtube.com/watch?v=tvq5aBROV_s","permanent":false},{"source":"/nsfw","destination":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","permanent":false}]},"appDir":"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev","relativeAppDir":"","files":[".next\\routes-manifest.json",".next\\server\\pages-manifest.json",".next\\build-manifest.json",".next\\prerender-manifest.json",".next\\prerender-manifest.js",".next\\server\\middleware-manifest.json",".next\\server\\middleware-build-manifest.js",".next\\server\\middleware-react-loadable-manifest.js",".next\\server\\app-paths-manifest.json",".next\\app-path-routes-manifest.json",".next\\app-build-manifest.json",".next\\server\\server-reference-manifest.js",".next\\server\\server-reference-manifest.json",".next\\react-loadable-manifest.json",".next\\server\\font-manifest.json",".next\\BUILD_ID",".next\\server\\next-font-manifest.js",".next\\server\\next-font-manifest.json"],"ignore":["node_modules\\next\\dist\\compiled\\@ampproject\\toolbox-optimizer\\**\\*"]} \ No newline at end of file diff --git a/.next/routes-manifest.json b/.next/routes-manifest.json index d0ad8ac..56ead9d 100644 --- a/.next/routes-manifest.json +++ b/.next/routes-manifest.json @@ -1 +1 @@ -{"version":3,"pages404":true,"caseSensitive":false,"basePath":"","redirects":[{"source":"/:path+/","destination":"/:path+","internal":true,"statusCode":308,"regex":"^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$"},{"source":"/:slug(yt|youtube)","destination":"https://www.youtube.com/Sukadia","statusCode":307,"regex":"^(?!/_next)(?:/(yt|youtube))(?:/)?$"},{"source":"/:slug(vod|vods)","destination":"https://www.youtube.com/channel/UC8S8l4sY8YsVcngSBTVyoSA","statusCode":307,"regex":"^(?!/_next)(?:/(vod|vods))(?:/)?$"},{"source":"/:slug(dev|update|updates)","destination":"https://www.youtube.com/channel/UCbzmy3xP2E0rLhCPFktbwAQ","statusCode":307,"regex":"^(?!/_next)(?:/(dev|update|updates))(?:/)?$"},{"source":"/:slug(ttv|twitch)","destination":"https://www.twitch.tv/Sukadia","statusCode":307,"regex":"^(?!/_next)(?:/(ttv|twitch))(?:/)?$"},{"source":"/:slug(hub|discord)","destination":"https://discord.gg/ReSCjYpXnK","statusCode":307,"regex":"^(?!/_next)(?:/(hub|discord))(?:/)?$"},{"source":"/:slug(ev|everyonevotes|everyone-votes)","destination":"https://top.gg/bot/805922495705251891","statusCode":307,"regex":"^(?!/_next)(?:/(ev|everyonevotes|everyone-votes))(?:/)?$"},{"source":"/:slug(kofi|ko-fi)","destination":"https://ko-fi.com/sukadia/tiers","statusCode":307,"regex":"^(?!/_next)(?:/(kofi|ko-fi))(?:/)?$"},{"source":"/poster","destination":"https://ko-fi.com/s/3cf296742e","statusCode":307,"regex":"^(?!/_next)/poster(?:/)?$"},{"source":"/dark","destination":"https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark","statusCode":307,"regex":"^(?!/_next)/dark(?:/)?$"},{"source":"/banner","destination":"https://www.youtube.com/watch?v=tvq5aBROV_s","statusCode":307,"regex":"^(?!/_next)/banner(?:/)?$"},{"source":"/nsfw","destination":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","statusCode":307,"regex":"^(?!/_next)/nsfw(?:/)?$"}],"headers":[],"dynamicRoutes":[],"staticRoutes":[{"page":"/","regex":"^/(?:/)?$","routeKeys":{},"namedRegex":"^/(?:/)?$"},{"page":"/_not-found","regex":"^/_not\\-found(?:/)?$","routeKeys":{},"namedRegex":"^/_not\\-found(?:/)?$"},{"page":"/everyone-votes/privacy","regex":"^/everyone\\-votes/privacy(?:/)?$","routeKeys":{},"namedRegex":"^/everyone\\-votes/privacy(?:/)?$"},{"page":"/everyone-votes/terms","regex":"^/everyone\\-votes/terms(?:/)?$","routeKeys":{},"namedRegex":"^/everyone\\-votes/terms(?:/)?$"},{"page":"/favicon.ico","regex":"^/favicon\\.ico(?:/)?$","routeKeys":{},"namedRegex":"^/favicon\\.ico(?:/)?$"},{"page":"/space","regex":"^/space(?:/)?$","routeKeys":{},"namedRegex":"^/space(?:/)?$"},{"page":"/wiston","regex":"^/wiston(?:/)?$","routeKeys":{},"namedRegex":"^/wiston(?:/)?$"}],"dataRoutes":[],"rsc":{"header":"RSC","varyHeader":"RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url","prefetchHeader":"Next-Router-Prefetch","contentTypeHeader":"text/x-component"},"rewrites":[]} \ No newline at end of file +{"version":3,"pages404":true,"caseSensitive":false,"basePath":"","redirects":[{"source":"/:path+/","destination":"/:path+","internal":true,"statusCode":308,"regex":"^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$"},{"source":"/:slug(yt|youtube)","destination":"https://www.youtube.com/Sukadia","statusCode":307,"regex":"^(?!/_next)(?:/(yt|youtube))(?:/)?$"},{"source":"/:slug(vod|vods)","destination":"https://www.youtube.com/channel/UC8S8l4sY8YsVcngSBTVyoSA","statusCode":307,"regex":"^(?!/_next)(?:/(vod|vods))(?:/)?$"},{"source":"/:slug(dev|update|updates)","destination":"https://www.youtube.com/channel/UCbzmy3xP2E0rLhCPFktbwAQ","statusCode":307,"regex":"^(?!/_next)(?:/(dev|update|updates))(?:/)?$"},{"source":"/:slug(ttv|twitch)","destination":"https://www.twitch.tv/Sukadia","statusCode":307,"regex":"^(?!/_next)(?:/(ttv|twitch))(?:/)?$"},{"source":"/:slug(hub|discord)","destination":"https://discord.gg/ReSCjYpXnK","statusCode":307,"regex":"^(?!/_next)(?:/(hub|discord))(?:/)?$"},{"source":"/:slug(ev|everyonevotes|everyone-votes)","destination":"https://top.gg/bot/805922495705251891","statusCode":307,"regex":"^(?!/_next)(?:/(ev|everyonevotes|everyone-votes))(?:/)?$"},{"source":"/:slug(kofi|ko-fi)","destination":"https://ko-fi.com/sukadia/tiers","statusCode":307,"regex":"^(?!/_next)(?:/(kofi|ko-fi))(?:/)?$"},{"source":"/poster","destination":"https://ko-fi.com/s/3cf296742e","statusCode":307,"regex":"^(?!/_next)/poster(?:/)?$"},{"source":"/dark","destination":"https://marketplace.visualstudio.com/items?itemName=Sukadia.sukadia-dev-dark","statusCode":307,"regex":"^(?!/_next)/dark(?:/)?$"},{"source":"/banner","destination":"https://www.youtube.com/watch?v=tvq5aBROV_s","statusCode":307,"regex":"^(?!/_next)/banner(?:/)?$"},{"source":"/nsfw","destination":"https://www.youtube.com/watch?v=dQw4w9WgXcQ","statusCode":307,"regex":"^(?!/_next)/nsfw(?:/)?$"}],"headers":[],"dynamicRoutes":[],"staticRoutes":[{"page":"/","regex":"^/(?:/)?$","routeKeys":{},"namedRegex":"^/(?:/)?$"},{"page":"/_not-found","regex":"^/_not\\-found(?:/)?$","routeKeys":{},"namedRegex":"^/_not\\-found(?:/)?$"},{"page":"/everyone-votes/privacy","regex":"^/everyone\\-votes/privacy(?:/)?$","routeKeys":{},"namedRegex":"^/everyone\\-votes/privacy(?:/)?$"},{"page":"/everyone-votes/terms","regex":"^/everyone\\-votes/terms(?:/)?$","routeKeys":{},"namedRegex":"^/everyone\\-votes/terms(?:/)?$"},{"page":"/favicon.ico","regex":"^/favicon\\.ico(?:/)?$","routeKeys":{},"namedRegex":"^/favicon\\.ico(?:/)?$"},{"page":"/space","regex":"^/space(?:/)?$","routeKeys":{},"namedRegex":"^/space(?:/)?$"},{"page":"/wiston","regex":"^/wiston(?:/)?$","routeKeys":{},"namedRegex":"^/wiston(?:/)?$"}],"dataRoutes":[],"rsc":{"header":"RSC","varyHeader":"RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url","prefetchHeader":"Next-Router-Prefetch","didPostponeHeader":"x-nextjs-postponed","contentTypeHeader":"text/x-component","suffix":".rsc","prefetchSuffix":".prefetch.rsc"},"rewrites":[]} \ No newline at end of file diff --git a/.next/server/app-paths-manifest.json b/.next/server/app-paths-manifest.json index 86103ec..e1286d6 100644 --- a/.next/server/app-paths-manifest.json +++ b/.next/server/app-paths-manifest.json @@ -1,7 +1,7 @@ { "/_not-found": "app/_not-found.js", - "/everyone-votes/privacy/page": "app/everyone-votes/privacy/page.js", "/everyone-votes/terms/page": "app/everyone-votes/terms/page.js", + "/everyone-votes/privacy/page": "app/everyone-votes/privacy/page.js", "/favicon.ico/route": "app/favicon.ico/route.js", "/page": "app/page.js", "/space/page": "app/space/page.js", diff --git a/.next/server/app/_not-found.html b/.next/server/app/_not-found.html index de3baee..f051e9e 100644 --- a/.next/server/app/_not-found.html +++ b/.next/server/app/_not-found.html @@ -1 +1 @@ -404: This page could not be found.sukadia.dev

404

This page could not be found.

\ No newline at end of file +404: This page could not be found.sukadia.dev

404

This page could not be found.

\ No newline at end of file diff --git a/.next/server/app/_not-found.js b/.next/server/app/_not-found.js index 23a8d9c..ac45a1d 100644 --- a/.next/server/app/_not-found.js +++ b/.next/server/app/_not-found.js @@ -1 +1 @@ -"use strict";(()=>{var e={};e.id=165,e.ids=[165],e.modules={5403:e=>{e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},6813:(e,t,n)=>{n.r(t),n.d(t,{GlobalError:()=>a.a,__next_app__:()=>c,originalPathname:()=>u,pages:()=>p,routeModule:()=>x,tree:()=>d});var r=n(7096),o=n(6132),s=n(7284),a=n.n(s),i=n(2564),l={};for(let e in i)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>i[e]);n.d(t,l);let d=["",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(n.t.bind(n,9291,23)),"next/dist/client/components/not-found-error"]}]},{layout:[()=>Promise.resolve().then(n.bind(n,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(n.t.bind(n,9291,23)),"next/dist/client/components/not-found-error"]}],p=[],u="/_not-found",c={require:n,loadChunk:()=>Promise.resolve()},x=new r.AppPageRouteModule({definition:{kind:o.x.APP_PAGE,page:"/_not-found",pathname:"/_not-found",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:d}})}};var t=require("../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),n=t.X(0,[862,622],()=>__webpack_exec__(6813));module.exports=n})(); \ No newline at end of file +(()=>{var e={};e.id=165,e.ids=[165],e.modules={7849:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external")},5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},6813:(e,t,n)=>{"use strict";n.r(t),n.d(t,{GlobalError:()=>i.a,__next_app__:()=>p,originalPathname:()=>c,pages:()=>u,routeModule:()=>m,tree:()=>l});var r=n(482),s=n(9108),o=n(2563),i=n.n(o),a=n(8300),d={};for(let e in a)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(d[e]=()=>a[e]);n.d(t,d);let l=["",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(n.t.bind(n,9361,23)),"next/dist/client/components/not-found-error"]}]},{layout:[()=>Promise.resolve().then(n.bind(n,2917)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(n.t.bind(n,9361,23)),"next/dist/client/components/not-found-error"]}],u=[],c="/_not-found",p={require:n,loadChunk:()=>Promise.resolve()},m=new r.AppPageRouteModule({definition:{kind:s.x.APP_PAGE,page:"/_not-found",pathname:"/_not-found",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:l}})},6254:(e,t,n)=>{Promise.resolve().then(n.t.bind(n,2583,23)),Promise.resolve().then(n.t.bind(n,6840,23)),Promise.resolve().then(n.t.bind(n,8771,23)),Promise.resolve().then(n.t.bind(n,3225,23)),Promise.resolve().then(n.t.bind(n,9295,23)),Promise.resolve().then(n.t.bind(n,3982,23))},2731:()=>{},2917:(e,t,n)=>{"use strict";n.r(t),n.d(t,{default:()=>a,metadata:()=>i});var r=n(5036),s=n(265),o=n.n(s);n(3440);let i={title:"sukadia.dev",description:"I code, stream, and create videos."};function a({children:e}){return r.jsx("html",{lang:"en",children:r.jsx("body",{className:o().className,children:e})})}},3440:()=>{}};var t=require("../webpack-runtime.js");t.C(e);var n=e=>t(t.s=e),r=t.X(0,[638,969],()=>n(6813));module.exports=r})(); \ No newline at end of file diff --git a/.next/server/app/_not-found.js.nft.json b/.next/server/app/_not-found.js.nft.json index 3eecb82..5751a45 100644 --- a/.next/server/app/_not-found.js.nft.json +++ b/.next/server/app/_not-found.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../node_modules/next/dist/client/components/async-local-storage.js","../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js","_not-found_client-reference-manifest.js"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../node_modules/next/dist/client/components/async-local-storage.js","../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../package.json","../chunks/329.js","../chunks/337.js","../chunks/638.js","../chunks/969.js","../chunks/font-manifest.json","../webpack-runtime.js","_not-found_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/_not-found.rsc b/.next/server/app/_not-found.rsc index 09dcf51..6eea5e2 100644 --- a/.next/server/app/_not-found.rsc +++ b/.next/server/app/_not-found.rsc @@ -1,11 +1,9 @@ -1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] -0:["P9X42g8nWZ62i2biioMqg",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] -4:I[6954,[],""] -5:I[7264,[],""] -7:{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"} -8:{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"} -9:{"display":"inline-block"} -a:{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0} -2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$L6",[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$7","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$8","children":"404"}],["$","div",null,{"style":"$9","children":["$","h2",null,{"style":"$a","children":"This page could not be found."}]}]]}]}]],null],"segment":"__PAGE__"},"styles":null}]}]}],null] -3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}]] -6:null +2:I[5613,[],""] +3:I[1778,[],""] +4:{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"} +5:{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"} +6:{"display":"inline-block"} +7:{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0} +0:["xSz9x0FW88Rb7utFdR6Fp",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$4","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$5","children":"404"}],["$","div",null,{"style":"$6","children":["$","h2",null,{"style":"$7","children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"styles":null}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L8"]]]] +8:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}]] +1:null diff --git a/.next/server/app/_not-found_client-reference-manifest.js b/.next/server/app/_not-found_client-reference-manifest.js index 18ebb4c..f1bbf4a 100644 --- a/.next/server/app/_not-found_client-reference-manifest.js +++ b/.next/server/app/_not-found_client-reference-manifest.js @@ -1 +1 @@ -globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/_not-found"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"]}} \ No newline at end of file +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/_not-found"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"326":{"*":{"id":"2079","name":"*","chunks":[],"async":false}},"1778":{"*":{"id":"9295","name":"*","chunks":[],"async":false}},"1902":{"*":{"id":"3225","name":"*","chunks":[],"async":false}},"5613":{"*":{"id":"8771","name":"*","chunks":[],"async":false}},"7690":{"*":{"id":"2583","name":"*","chunks":[],"async":false}},"7831":{"*":{"id":"3982","name":"*","chunks":[],"async":false}},"8955":{"*":{"id":"6840","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":3445,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":9989,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":326,"name":"*","chunks":["986","static/chunks/986-72006aa1051e30d3.js","931","static/chunks/app/page-8af0c2c4af65d19c.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"]}} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy.html b/.next/server/app/everyone-votes/privacy.html index e2a34a6..5438086 100644 --- a/.next/server/app/everyone-votes/privacy.html +++ b/.next/server/app/everyone-votes/privacy.html @@ -1 +1 @@ -sukadia.dev

Everyone Votes Privacy Policy

Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:


What We Store

By voting on a poll with Everyone Votes, we store:

This data is stored for up to 24 hours, and is wiped every day at UTC midnight.

A cumulative count of the number of votes for each poll option is saved indefinitely.


By setting up Everyone Votes, we store:

This data is stored for as long as Everyone Votes is setup within the server.


By adding server-wide polls on Everyone Votes, we store:

This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command.


In summary, I don't use your data for anything malicious, just for getting poll result counts.


Removal of Data

Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure.

User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data.


Contact

If you have questions or concerns about these terms, please join the support server on Discord, or email contact@sukadia.dev.

\ No newline at end of file +sukadia.dev

Everyone Votes Privacy Policy

Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:


What We Store

By voting on a poll with Everyone Votes, we store:

This data is stored for up to 24 hours, and is wiped every day at UTC midnight.

A cumulative count of the number of votes for each poll option is saved indefinitely.


By setting up Everyone Votes, we store:

This data is stored for as long as Everyone Votes is setup within the server.


By adding server-wide polls on Everyone Votes, we store:

This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command.


In summary, I don't use your data for anything malicious, just for getting poll result counts.


Removal of Data

Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure.

User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data.


Contact

If you have questions or concerns about these terms, please join the support server on Discord, or email contact@sukadia.dev.

\ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy.rsc b/.next/server/app/everyone-votes/privacy.rsc index 5f0b4ad..72f0214 100644 --- a/.next/server/app/everyone-votes/privacy.rsc +++ b/.next/server/app/everyone-votes/privacy.rsc @@ -1,7 +1,5 @@ -1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] -0:["P9X42g8nWZ62i2biioMqg",[[["",{"children":["everyone-votes",{"children":["privacy",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] -4:I[6954,[],""] -5:I[7264,[],""] -2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children","privacy","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L6",["$","main",null,{"className":"ml-[10%] mt-[5%] mr-[10%]","children":[["$","h1",null,{"className":"text-3xl","children":"Everyone Votes Privacy Policy"}],["$","p",null,{"children":"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"What We Store"}],["$","h3",null,{"className":"text-xl","children":"By voting on a poll with Everyone Votes, we store:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- The poll option(s) you voted on"}],["$","p",null,{"children":"- Your Discord user id"}]]}],["$","p",null,{"children":"This data is stored for up to 24 hours, and is wiped every day at UTC midnight."}],["$","p",null,{"children":"A cumulative count of the number of votes for each poll option is saved indefinitely."}],["$","br",null,{}],["$","h3",null,{"className":"text-xl","children":"By setting up Everyone Votes, we store:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- The server id, poll channel ids, and current poll messages"}],["$","p",null,{"children":"- Config settings"}]]}],["$","p",null,{"children":"This data is stored for as long as Everyone Votes is setup within the server."}],["$","br",null,{}],["$","h3",null,{"className":"text-xl","children":"By adding server-wide polls on Everyone Votes, we store:"}],["$","ul",null,{"children":["$","p",null,{"children":"- All of those polls' data"}]}],["$","p",null,{"children":"This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command."}],["$","br",null,{}],["$","p",null,{"children":"In summary, I don't use your data for anything malicious, just for getting poll result counts."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Removal of Data"}],["$","p",null,{"children":"Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure."}],["$","p",null,{"children":"User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Contact"}],["$","p",null,{"children":["If you have questions or concerns about these terms, please join the ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," on Discord, or email ",["$","span",null,{"className":"font-mono","children":"contact@sukadia.dev"}],"."]}]]}],null],"segment":"__PAGE__"},"styles":null}],"segment":"privacy"},"styles":null}],"segment":"everyone-votes"},"styles":null}]}]}],null] -3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] -6:null +2:I[5613,[],""] +3:I[1778,[],""] +0:["xSz9x0FW88Rb7utFdR6Fp",[[["",{"children":["everyone-votes",{"children":["privacy",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true],["",{"children":["everyone-votes",{"children":["privacy",{"children":["__PAGE__",{},["$L1",["$","main",null,{"className":"ml-[10%] mt-[5%] mr-[10%]","children":[["$","h1",null,{"className":"text-3xl","children":"Everyone Votes Privacy Policy"}],["$","p",null,{"children":"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"What We Store"}],["$","h3",null,{"className":"text-xl","children":"By voting on a poll with Everyone Votes, we store:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- The poll option(s) you voted on"}],["$","p",null,{"children":"- Your Discord user id"}]]}],["$","p",null,{"children":"This data is stored for up to 24 hours, and is wiped every day at UTC midnight."}],["$","p",null,{"children":"A cumulative count of the number of votes for each poll option is saved indefinitely."}],["$","br",null,{}],["$","h3",null,{"className":"text-xl","children":"By setting up Everyone Votes, we store:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- The server id, poll channel ids, and current poll messages"}],["$","p",null,{"children":"- Config settings"}]]}],["$","p",null,{"children":"This data is stored for as long as Everyone Votes is setup within the server."}],["$","br",null,{}],["$","h3",null,{"className":"text-xl","children":"By adding server-wide polls on Everyone Votes, we store:"}],["$","ul",null,{"children":["$","p",null,{"children":"- All of those polls' data"}]}],["$","p",null,{"children":"This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command."}],["$","br",null,{}],["$","p",null,{"children":"In summary, I don't use your data for anything malicious, just for getting poll result counts."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Removal of Data"}],["$","p",null,{"children":"Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure."}],["$","p",null,{"children":"User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Contact"}],["$","p",null,{"children":["If you have questions or concerns about these terms, please join the ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," on Discord, or email ",["$","span",null,{"className":"font-mono","children":"contact@sukadia.dev"}],"."]}]]}],null]]},["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children","privacy","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","styles":null}]]},["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","styles":null}]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"styles":null}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +4:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +1:null diff --git a/.next/server/app/everyone-votes/privacy/page.js b/.next/server/app/everyone-votes/privacy/page.js index 1c827f1..4e4fe34 100644 --- a/.next/server/app/everyone-votes/privacy/page.js +++ b/.next/server/app/everyone-votes/privacy/page.js @@ -1 +1 @@ -(()=>{var e={};e.id=369,e.ids=[369],e.modules={5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},2668:(e,t,s)=>{"use strict";s.r(t),s.d(t,{GlobalError:()=>i.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>c,routeModule:()=>x,tree:()=>d});var r=s(7096),a=s(6132),o=s(7284),i=s.n(o),n=s(2564),l={};for(let e in n)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>n[e]);s.d(t,l);let d=["",{children:["everyone-votes",{children:["privacy",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(s.bind(s,2330)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page.tsx"]}]},{}]},{metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(s.bind(s,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(s.t.bind(s,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],c=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page.tsx"],p="/everyone-votes/privacy/page",u={require:s,loadChunk:()=>Promise.resolve()},x=new r.AppPageRouteModule({definition:{kind:a.x.APP_PAGE,page:"/everyone-votes/privacy/page",pathname:"/everyone-votes/privacy",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:d}})},5303:()=>{},2330:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>Privacy});var r=s(4656);function Privacy(){return(0,r.jsxs)("main",{className:"ml-[10%] mt-[5%] mr-[10%]",children:[r.jsx("h1",{className:"text-3xl",children:"Everyone Votes Privacy Policy"}),r.jsx("p",{children:"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"What We Store"}),r.jsx("h3",{className:"text-xl",children:"By voting on a poll with Everyone Votes, we store:"}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- The poll option(s) you voted on"}),r.jsx("p",{children:"- Your Discord user id"})]}),r.jsx("p",{children:"This data is stored for up to 24 hours, and is wiped every day at UTC midnight."}),r.jsx("p",{children:"A cumulative count of the number of votes for each poll option is saved indefinitely."}),r.jsx("br",{}),r.jsx("h3",{className:"text-xl",children:"By setting up Everyone Votes, we store:"}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- The server id, poll channel ids, and current poll messages"}),r.jsx("p",{children:"- Config settings"})]}),r.jsx("p",{children:"This data is stored for as long as Everyone Votes is setup within the server."}),r.jsx("br",{}),r.jsx("h3",{className:"text-xl",children:"By adding server-wide polls on Everyone Votes, we store:"}),r.jsx("ul",{children:r.jsx("p",{children:"- All of those polls' data"})}),r.jsx("p",{children:"This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command."}),r.jsx("br",{}),r.jsx("p",{children:"In summary, I don't use your data for anything malicious, just for getting poll result counts."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Removal of Data"}),r.jsx("p",{children:"Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure."}),r.jsx("p",{children:"User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Contact"}),(0,r.jsxs)("p",{children:["If you have questions or concerns about these terms, please join the ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," on Discord, or email ",r.jsx("span",{className:"font-mono",children:"contact@sukadia.dev"}),"."]})]})}},7481:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var r=s(8531);let __WEBPACK_DEFAULT_EXPORT__=e=>{let t=(0,r.fillMetadataSegment)(".",e.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:t+""}]}}};var t=require("../../../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),s=t.X(0,[862,323,622],()=>__webpack_exec__(2668));module.exports=s})(); \ No newline at end of file +(()=>{var e={};e.id=369,e.ids=[369],e.modules={7849:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external")},5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},2668:(e,t,s)=>{"use strict";s.r(t),s.d(t,{GlobalError:()=>i.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>c,routeModule:()=>h,tree:()=>d});var r=s(482),o=s(9108),a=s(2563),i=s.n(a),n=s(8300),l={};for(let e in n)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>n[e]);s.d(t,l);let d=["",{children:["everyone-votes",{children:["privacy",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(s.bind(s,8898)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page.tsx"]}]},{}]},{metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(s.bind(s,2917)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(s.t.bind(s,9361,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],c=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page.tsx"],p="/everyone-votes/privacy/page",u={require:s,loadChunk:()=>Promise.resolve()},h=new r.AppPageRouteModule({definition:{kind:o.x.APP_PAGE,page:"/everyone-votes/privacy/page",pathname:"/everyone-votes/privacy",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:d}})},6254:(e,t,s)=>{Promise.resolve().then(s.t.bind(s,2583,23)),Promise.resolve().then(s.t.bind(s,6840,23)),Promise.resolve().then(s.t.bind(s,8771,23)),Promise.resolve().then(s.t.bind(s,3225,23)),Promise.resolve().then(s.t.bind(s,9295,23)),Promise.resolve().then(s.t.bind(s,3982,23))},2731:()=>{},5303:()=>{},8898:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>o});var r=s(5036);function o(){return(0,r.jsxs)("main",{className:"ml-[10%] mt-[5%] mr-[10%]",children:[r.jsx("h1",{className:"text-3xl",children:"Everyone Votes Privacy Policy"}),r.jsx("p",{children:"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following use of your data:"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"What We Store"}),r.jsx("h3",{className:"text-xl",children:"By voting on a poll with Everyone Votes, we store:"}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- The poll option(s) you voted on"}),r.jsx("p",{children:"- Your Discord user id"})]}),r.jsx("p",{children:"This data is stored for up to 24 hours, and is wiped every day at UTC midnight."}),r.jsx("p",{children:"A cumulative count of the number of votes for each poll option is saved indefinitely."}),r.jsx("br",{}),r.jsx("h3",{className:"text-xl",children:"By setting up Everyone Votes, we store:"}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- The server id, poll channel ids, and current poll messages"}),r.jsx("p",{children:"- Config settings"})]}),r.jsx("p",{children:"This data is stored for as long as Everyone Votes is setup within the server."}),r.jsx("br",{}),r.jsx("h3",{className:"text-xl",children:"By adding server-wide polls on Everyone Votes, we store:"}),r.jsx("ul",{children:r.jsx("p",{children:"- All of those polls' data"})}),r.jsx("p",{children:"This data is stored up until the results are tallied for it. Moderators can also manually remove the poll by using the corresponding command."}),r.jsx("br",{}),r.jsx("p",{children:"In summary, I don't use your data for anything malicious, just for getting poll result counts."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Removal of Data"}),r.jsx("p",{children:"Server data is erased once Everyone Votes is kicked from the server. Any server moderator can kick the bot to trigger this erasure."}),r.jsx("p",{children:"User vote data is erased at UTC midnight every day. Since user vote data lasts such a small window of time, erasure requests cannot be fulfilled for this data."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Contact"}),(0,r.jsxs)("p",{children:["If you have questions or concerns about these terms, please join the ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," on Discord, or email ",r.jsx("span",{className:"font-mono",children:"contact@sukadia.dev"}),"."]})]})}},2917:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>n,metadata:()=>i});var r=s(5036),o=s(265),a=s.n(o);s(3440);let i={title:"sukadia.dev",description:"I code, stream, and create videos."};function n({children:e}){return r.jsx("html",{lang:"en",children:r.jsx("body",{className:a().className,children:e})})}},7481:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>o});var r=s(337);let o=e=>[{type:"image/x-icon",sizes:"16x16",url:(0,r.fillMetadataSegment)(".",e.params,"favicon.ico")+""}]},3440:()=>{}};var t=require("../../../webpack-runtime.js");t.C(e);var s=e=>t(t.s=e),r=t.X(0,[638,969,337],()=>s(2668));module.exports=r})(); \ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy/page.js.nft.json b/.next/server/app/everyone-votes/privacy/page.js.nft.json index 1bff456..074ce4e 100644 --- a/.next/server/app/everyone-votes/privacy/page.js.nft.json +++ b/.next/server/app/everyone-votes/privacy/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../../node_modules/next/package.json","../../../../../package.json","../../../../package.json","../../../chunks/106.js","../../../chunks/2.js","../../../chunks/201.js","../../../chunks/310.js","../../../chunks/323.js","../../../chunks/622.js","../../../chunks/676.js","../../../chunks/837.js","../../../chunks/840.js","../../../chunks/862.js","../../../chunks/984.js","../../../chunks/font-manifest.json","../../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file +{"version":1,"files":["../../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../../node_modules/next/package.json","../../../../../package.json","../../../../package.json","../../../chunks/329.js","../../../chunks/337.js","../../../chunks/638.js","../../../chunks/969.js","../../../chunks/font-manifest.json","../../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/privacy/page_client-reference-manifest.js b/.next/server/app/everyone-votes/privacy/page_client-reference-manifest.js index 747de8d..38ffae1 100644 --- a/.next/server/app/everyone-votes/privacy/page_client-reference-manifest.js +++ b/.next/server/app/everyone-votes/privacy/page_client-reference-manifest.js @@ -1 +1 @@ -globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/everyone-votes/privacy/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page":[]}} \ No newline at end of file +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/everyone-votes/privacy/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"326":{"*":{"id":"2079","name":"*","chunks":[],"async":false}},"1778":{"*":{"id":"9295","name":"*","chunks":[],"async":false}},"1902":{"*":{"id":"3225","name":"*","chunks":[],"async":false}},"5613":{"*":{"id":"8771","name":"*","chunks":[],"async":false}},"7690":{"*":{"id":"2583","name":"*","chunks":[],"async":false}},"7831":{"*":{"id":"3982","name":"*","chunks":[],"async":false}},"8955":{"*":{"id":"6840","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":3445,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":9989,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":326,"name":"*","chunks":["986","static/chunks/986-72006aa1051e30d3.js","931","static/chunks/app/page-8af0c2c4af65d19c.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\privacy\\page":[]}} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms.html b/.next/server/app/everyone-votes/terms.html index e1a5d8e..b78e026 100644 --- a/.next/server/app/everyone-votes/terms.html +++ b/.next/server/app/everyone-votes/terms.html @@ -1 +1 @@ -sukadia.dev

Everyone Votes Terms of Service

Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:


User Conduct

"Users" include any Discord user interacting with Everyone Votes through Discord's slash commands or buttons. Users must adhere to the following guidelines:

Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer.


Paid Content

Everyone Votes offers certain features that require supporting the bot monthly on Ko-fi. In order to gain access to these features, the supporter must be in the Discord support server to properly track subscription status.

Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion.

Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)


Contact

If you have questions or concerns about these terms, please join the support server on Discord, or email contact@sukadia.dev.

I appreciate you for reading these terms, not many do that!

\ No newline at end of file +sukadia.dev

Everyone Votes Terms of Service

Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:


User Conduct

"Users" include any Discord user interacting with Everyone Votes through Discord's slash commands or buttons. Users must adhere to the following guidelines:

Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer.


Paid Content

Everyone Votes offers certain features that require supporting the bot monthly on Ko-fi. In order to gain access to these features, the supporter must be in the Discord support server to properly track subscription status.

Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion.

Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)


Contact

If you have questions or concerns about these terms, please join the support server on Discord, or email contact@sukadia.dev.

I appreciate you for reading these terms, not many do that!

\ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms.rsc b/.next/server/app/everyone-votes/terms.rsc index 4f0bdac..2dc7fd6 100644 --- a/.next/server/app/everyone-votes/terms.rsc +++ b/.next/server/app/everyone-votes/terms.rsc @@ -1,7 +1,5 @@ -1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] -0:["P9X42g8nWZ62i2biioMqg",[[["",{"children":["everyone-votes",{"children":["terms",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] -4:I[6954,[],""] -5:I[7264,[],""] -2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children","terms","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L6",["$","main",null,{"className":"ml-[10%] mt-[5%] mr-[10%]","children":[["$","h1",null,{"className":"text-3xl","children":"Everyone Votes Terms of Service"}],["$","p",null,{"children":"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"User Conduct"}],["$","p",null,{"children":"\"Users\" include any Discord user interacting with Everyone Votes through Discord's slash commands or buttons. Users must adhere to the following guidelines:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- Spamming bot interactions is not allowed."}],["$","p",null,{"children":"- Only one account per person may vote on polls."}],["$","p",null,{"children":["- Follow ",["$","a",null,{"href":"https://discord.com/terms","className":"text-blue-500","children":"Discord's Terms of Service"}],"."]}]]}],["$","p",null,{"children":"Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Paid Content"}],["$","p",null,{"children":["Everyone Votes offers certain features that require supporting the bot monthly on ",["$","a",null,{"href":"https://ko-fi.com/everyonevotes/tiers","className":"text-blue-500","children":"Ko-fi"}],". In order to gain access to these features, the supporter must be in the Discord ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," to properly track subscription status."]}],["$","p",null,{"children":"Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion."}],["$","p",null,{"children":"Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Contact"}],["$","p",null,{"children":["If you have questions or concerns about these terms, please join the ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," on Discord, or email ",["$","span",null,{"className":"font-mono","children":"contact@sukadia.dev"}],"."]}],["$","p",null,{"children":"I appreciate you for reading these terms, not many do that!"}]]}],null],"segment":"__PAGE__"},"styles":null}],"segment":"terms"},"styles":null}],"segment":"everyone-votes"},"styles":null}]}]}],null] -3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] -6:null +2:I[5613,[],""] +3:I[1778,[],""] +0:["xSz9x0FW88Rb7utFdR6Fp",[[["",{"children":["everyone-votes",{"children":["terms",{"children":["__PAGE__",{}]}]}]},"$undefined","$undefined",true],["",{"children":["everyone-votes",{"children":["terms",{"children":["__PAGE__",{},["$L1",["$","main",null,{"className":"ml-[10%] mt-[5%] mr-[10%]","children":[["$","h1",null,{"className":"text-3xl","children":"Everyone Votes Terms of Service"}],["$","p",null,{"children":"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"User Conduct"}],["$","p",null,{"children":"\"Users\" include any Discord user interacting with Everyone Votes through Discord's slash commands or buttons. Users must adhere to the following guidelines:"}],["$","ul",null,{"children":[["$","p",null,{"children":"- Spamming bot interactions is not allowed."}],["$","p",null,{"children":"- Only one account per person may vote on polls."}],["$","p",null,{"children":["- Follow ",["$","a",null,{"href":"https://discord.com/terms","className":"text-blue-500","children":"Discord's Terms of Service"}],"."]}]]}],["$","p",null,{"children":"Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer."}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Paid Content"}],["$","p",null,{"children":["Everyone Votes offers certain features that require supporting the bot monthly on ",["$","a",null,{"href":"https://ko-fi.com/everyonevotes/tiers","className":"text-blue-500","children":"Ko-fi"}],". In order to gain access to these features, the supporter must be in the Discord ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," to properly track subscription status."]}],["$","p",null,{"children":"Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion."}],["$","p",null,{"children":"Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)"}],["$","br",null,{}],["$","h2",null,{"className":"text-2xl","children":"Contact"}],["$","p",null,{"children":["If you have questions or concerns about these terms, please join the ",["$","a",null,{"href":"https://discord.gg/pc6EcNjuZU","className":"text-blue-500","children":"support server"}]," on Discord, or email ",["$","span",null,{"className":"font-mono","children":"contact@sukadia.dev"}],"."]}],["$","p",null,{"children":"I appreciate you for reading these terms, not many do that!"}]]}],null]]},["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children","terms","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","styles":null}]]},["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children","everyone-votes","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","styles":null}]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"styles":null}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +4:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +1:null diff --git a/.next/server/app/everyone-votes/terms/page.js b/.next/server/app/everyone-votes/terms/page.js index e6dc224..cede584 100644 --- a/.next/server/app/everyone-votes/terms/page.js +++ b/.next/server/app/everyone-votes/terms/page.js @@ -1 +1 @@ -(()=>{var e={};e.id=181,e.ids=[181],e.modules={5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},9167:(e,t,s)=>{"use strict";s.r(t),s.d(t,{GlobalError:()=>a.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>d,routeModule:()=>m,tree:()=>c});var r=s(7096),o=s(6132),n=s(7284),a=s.n(n),i=s(2564),l={};for(let e in i)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>i[e]);s.d(t,l);let c=["",{children:["everyone-votes",{children:["terms",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(s.bind(s,4182)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page.tsx"]}]},{}]},{metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(s.bind(s,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(s.t.bind(s,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],d=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page.tsx"],p="/everyone-votes/terms/page",u={require:s,loadChunk:()=>Promise.resolve()},m=new r.AppPageRouteModule({definition:{kind:o.x.APP_PAGE,page:"/everyone-votes/terms/page",pathname:"/everyone-votes/terms",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:c}})},5303:()=>{},4182:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>Terms});var r=s(4656);function Terms(){return(0,r.jsxs)("main",{className:"ml-[10%] mt-[5%] mr-[10%]",children:[r.jsx("h1",{className:"text-3xl",children:"Everyone Votes Terms of Service"}),r.jsx("p",{children:"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"User Conduct"}),r.jsx("p",{children:'"Users" include any Discord user interacting with Everyone Votes through Discord\'s slash commands or buttons. Users must adhere to the following guidelines:'}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- Spamming bot interactions is not allowed."}),r.jsx("p",{children:"- Only one account per person may vote on polls."}),(0,r.jsxs)("p",{children:["- Follow ",r.jsx("a",{href:"https://discord.com/terms",className:"text-blue-500",children:"Discord's Terms of Service"}),"."]})]}),r.jsx("p",{children:"Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Paid Content"}),(0,r.jsxs)("p",{children:["Everyone Votes offers certain features that require supporting the bot monthly on ",r.jsx("a",{href:"https://ko-fi.com/everyonevotes/tiers",className:"text-blue-500",children:"Ko-fi"}),". In order to gain access to these features, the supporter must be in the Discord ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," to properly track subscription status."]}),r.jsx("p",{children:"Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion."}),r.jsx("p",{children:"Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Contact"}),(0,r.jsxs)("p",{children:["If you have questions or concerns about these terms, please join the ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," on Discord, or email ",r.jsx("span",{className:"font-mono",children:"contact@sukadia.dev"}),"."]}),r.jsx("p",{children:"I appreciate you for reading these terms, not many do that!"})]})}},7481:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var r=s(8531);let __WEBPACK_DEFAULT_EXPORT__=e=>{let t=(0,r.fillMetadataSegment)(".",e.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:t+""}]}}};var t=require("../../../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),s=t.X(0,[862,323,622],()=>__webpack_exec__(9167));module.exports=s})(); \ No newline at end of file +(()=>{var e={};e.id=181,e.ids=[181],e.modules={7849:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external")},5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},9167:(e,t,s)=>{"use strict";s.r(t),s.d(t,{GlobalError:()=>a.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>d,routeModule:()=>m,tree:()=>c});var r=s(482),o=s(9108),n=s(2563),a=s.n(n),i=s(8300),l={};for(let e in i)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>i[e]);s.d(t,l);let c=["",{children:["everyone-votes",{children:["terms",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(s.bind(s,5447)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page.tsx"]}]},{}]},{metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(s.bind(s,2917)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(s.t.bind(s,9361,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],d=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page.tsx"],p="/everyone-votes/terms/page",u={require:s,loadChunk:()=>Promise.resolve()},m=new r.AppPageRouteModule({definition:{kind:o.x.APP_PAGE,page:"/everyone-votes/terms/page",pathname:"/everyone-votes/terms",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:c}})},6254:(e,t,s)=>{Promise.resolve().then(s.t.bind(s,2583,23)),Promise.resolve().then(s.t.bind(s,6840,23)),Promise.resolve().then(s.t.bind(s,8771,23)),Promise.resolve().then(s.t.bind(s,3225,23)),Promise.resolve().then(s.t.bind(s,9295,23)),Promise.resolve().then(s.t.bind(s,3982,23))},2731:()=>{},5303:()=>{},5447:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>o});var r=s(5036);function o(){return(0,r.jsxs)("main",{className:"ml-[10%] mt-[5%] mr-[10%]",children:[r.jsx("h1",{className:"text-3xl",children:"Everyone Votes Terms of Service"}),r.jsx("p",{children:"Everyone Votes is an application on Discord that delivers and tallies daily polls to Discord servers. By being a user, you agree to the following terms:"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"User Conduct"}),r.jsx("p",{children:'"Users" include any Discord user interacting with Everyone Votes through Discord\'s slash commands or buttons. Users must adhere to the following guidelines:'}),(0,r.jsxs)("ul",{children:[r.jsx("p",{children:"- Spamming bot interactions is not allowed."}),r.jsx("p",{children:"- Only one account per person may vote on polls."}),(0,r.jsxs)("p",{children:["- Follow ",r.jsx("a",{href:"https://discord.com/terms",className:"text-blue-500",children:"Discord's Terms of Service"}),"."]})]}),r.jsx("p",{children:"Failure to follow these terms may result in the user being blacklisted from using Everyone Vote's features, either automatically or at the discretion of the developer."}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Paid Content"}),(0,r.jsxs)("p",{children:["Everyone Votes offers certain features that require supporting the bot monthly on ",r.jsx("a",{href:"https://ko-fi.com/everyonevotes/tiers",className:"text-blue-500",children:"Ko-fi"}),". In order to gain access to these features, the supporter must be in the Discord ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," to properly track subscription status."]}),r.jsx("p",{children:"Benefits may not immediately appear for the supporter, and may not work fully as expected. Please follow the contact information below to report any issues so they may be resolved in a timely fashion."}),r.jsx("p",{children:"Refunds are not guaranteed and will be given at the discretion of the developer. (I'm a pretty reasonable person though!)"}),r.jsx("br",{}),r.jsx("h2",{className:"text-2xl",children:"Contact"}),(0,r.jsxs)("p",{children:["If you have questions or concerns about these terms, please join the ",r.jsx("a",{href:"https://discord.gg/pc6EcNjuZU",className:"text-blue-500",children:"support server"})," on Discord, or email ",r.jsx("span",{className:"font-mono",children:"contact@sukadia.dev"}),"."]}),r.jsx("p",{children:"I appreciate you for reading these terms, not many do that!"})]})}},2917:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>i,metadata:()=>a});var r=s(5036),o=s(265),n=s.n(o);s(3440);let a={title:"sukadia.dev",description:"I code, stream, and create videos."};function i({children:e}){return r.jsx("html",{lang:"en",children:r.jsx("body",{className:n().className,children:e})})}},7481:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>o});var r=s(337);let o=e=>[{type:"image/x-icon",sizes:"16x16",url:(0,r.fillMetadataSegment)(".",e.params,"favicon.ico")+""}]},3440:()=>{}};var t=require("../../../webpack-runtime.js");t.C(e);var s=e=>t(t.s=e),r=t.X(0,[638,969,337],()=>s(9167));module.exports=r})(); \ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms/page.js.nft.json b/.next/server/app/everyone-votes/terms/page.js.nft.json index 1bff456..074ce4e 100644 --- a/.next/server/app/everyone-votes/terms/page.js.nft.json +++ b/.next/server/app/everyone-votes/terms/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../../node_modules/next/package.json","../../../../../package.json","../../../../package.json","../../../chunks/106.js","../../../chunks/2.js","../../../chunks/201.js","../../../chunks/310.js","../../../chunks/323.js","../../../chunks/622.js","../../../chunks/676.js","../../../chunks/837.js","../../../chunks/840.js","../../../chunks/862.js","../../../chunks/984.js","../../../chunks/font-manifest.json","../../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file +{"version":1,"files":["../../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../../node_modules/next/package.json","../../../../../package.json","../../../../package.json","../../../chunks/329.js","../../../chunks/337.js","../../../chunks/638.js","../../../chunks/969.js","../../../chunks/font-manifest.json","../../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/everyone-votes/terms/page_client-reference-manifest.js b/.next/server/app/everyone-votes/terms/page_client-reference-manifest.js index dbee375..6d2bbc0 100644 --- a/.next/server/app/everyone-votes/terms/page_client-reference-manifest.js +++ b/.next/server/app/everyone-votes/terms/page_client-reference-manifest.js @@ -1 +1 @@ -globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/everyone-votes/terms/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page":[]}} \ No newline at end of file +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/everyone-votes/terms/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"326":{"*":{"id":"2079","name":"*","chunks":[],"async":false}},"1778":{"*":{"id":"9295","name":"*","chunks":[],"async":false}},"1902":{"*":{"id":"3225","name":"*","chunks":[],"async":false}},"5613":{"*":{"id":"8771","name":"*","chunks":[],"async":false}},"7690":{"*":{"id":"2583","name":"*","chunks":[],"async":false}},"7831":{"*":{"id":"3982","name":"*","chunks":[],"async":false}},"8955":{"*":{"id":"6840","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":3445,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":9989,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":326,"name":"*","chunks":["986","static/chunks/986-72006aa1051e30d3.js","931","static/chunks/app/page-8af0c2c4af65d19c.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\everyone-votes\\terms\\page":[]}} \ No newline at end of file diff --git a/.next/server/app/favicon.ico/route.js b/.next/server/app/favicon.ico/route.js index 8a36246..6ef3918 100644 --- a/.next/server/app/favicon.ico/route.js +++ b/.next/server/app/favicon.ico/route.js @@ -1 +1,12 @@ -"use strict";(()=>{var A={};A.id=155,A.ids=[155],A.modules={517:A=>{A.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},8837:(A,v,f)=>{f.r(v),f.d(v,{headerHooks:()=>t,originalPathname:()=>p,requestAsyncStorage:()=>j,routeModule:()=>L,serverHooks:()=>o,staticGenerationAsyncStorage:()=>u,staticGenerationBailout:()=>a});var P={};f.r(P),f.d(P,{GET:()=>GET,dynamic:()=>b});var r=f(884),n=f(6132),e=f(1057);let z=Buffer.from("AAABAAMAEBAAAAEAIABoBAAANgAAACAgAAABACAAKBEAAJ4EAAAwMAAAAQAgAGgmAADGFQAAKAAAABAAAAAgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADg1Ukx1stHl7asSdmmoF75uLcS+bGvQtmppyCXsbF9MQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPGOQnCuEeaxL10/q6qjf9aW5L/S02N/29xb/+9vbz/3tzR/7a0k/6hnxea4+PGCQAAAAAAAAAAAAAAAOPGOQnFu0PCr9DM/+H7/v/8/v//9PT8/3N44/9qcPb/s7f0///////d3f//mZaR/3h9U8Jxxv8JAAAAAAAAAADHu0Sag6Ka/5Xj+/+k8v7/qfL+/936/v/+/v//h4rv/56h8///////+/v//83N9/9visX/Uaf6mgAAAADg1UkxpLF+/p7u/v9wvfL/kOP+/4bc/f+V7v3/u8bP/8yfqP/Trrv/8ufp/87X+f+Al+//oqX7/1+F7v4+h+8x4tVKl5i+sP+c7/7/cMD0/2S39v9swfj/ku78/8aWov/ZkZz/9NDT/9yzuP98lO3/FTvi/2Rt9P9MdOr/PX31l+LVS9mOsKj/lur9/3LJ/P94we3/Wanz/4Le+/+7Wmf/5be8//nq7P/bkZr/1czk/3R89/94qe7/Tn/r/zx7+tm4r0P6q9rv/4vW9/9uxv3/idb0/2Kx8v9gt/z/ilZt/6EyOf/KXmP/s1dq/5aU+P9zh+7/eNf0/1Cj9f87ePT6uK9E+qbq9f+Z3vb/d8n3/3/P8/93yvb/TJv4/0+F4f+OlbP/hcno/3fE7f9twez/eeH4/1iw8P9DiPr/U4Dr+uLVS9mXr47/m/D9/5br/f93zPr/cMf8/0+c9P9xwPL/eOT7/3Hi+/9r2vn/cOP7/1aw8P8/gPf/Pnz0/4WF+NnczkmXqKhc/42+zf+H1/b/eMv9/3PC/P9wt/z/XK37/1iw+/9Sp/v/Uqb3/02Q8v8+gPb/Pn/4/3SN7f+YkfeXjZKxMZiu7P6i2fP/pev6/5fk+P99xfj/fr76/1uo+/9PoPv/TJv7/0qX+f9IkvT/Uo3r/7/R9P/4+P/+29v/MQAAAAC00fOavfT+/5rb9f+V3PX/gMry/3C79P9oxvv/cN37/125+/9So/L/b9P6/3HU+f+MwvD//Pz9mgAAAAAAAAAA4///CbT3/8Kr9v//pvb//5DV8v93yfL/h9f2/3fp+/935vv/XK/y/4LZ9f981fP/cszvwlVxxgkAAAAAAAAAAAAAAACq//8JqfX/mqb2//6R4/r/b63t/1ye9f+C1/X/fOr7/2a/8v+Z8/7+nfX/mo7j/wkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACn9f8xit3/l12n/9lWn//5gaKB+ZG7p9mAyeeXp/X/MQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAACAAAABAAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADdzEQPk4swWmNcIZuGg2LLnpqM6a+qiv2loxD9uLcS6by7Esu9vBCbtbMOWoiIEQ8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADk10om49VLnePVS/Xj1Uv/49VL/+PVS//czkn/cGsg/8/OFv+3tRL/nJhP/7m2ev+opTf/qaUQ9aumcJ3d3bwmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj41UJ49VLi+LUSvrSxEX/q6E4/4+GNv99d0H/dG9F/3hyQ/94cjH/RkQO/4iIDf+zsGf///////Tz7/+dmW7/1dO3/5WRLfqenA+Ljo4ACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA49VHJN/RSdSZkUL/oqCI/7y8vP/W1t7/qKro/1pg4v8dJeD/HCTj/yIs3P9udd//f4TB/2Rnmf/e3vL/9PT7//Py7v/V08b/mpig/6+sGP+Vkx/U4+O/JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAODRRzLd0EnrgX1X/+/v7////////////////////////////9LU8/9JUNr/GSHY/1lf8v+jqf//hozw/+vr+f/////////////////Pz///kY15/8K/jf+EezfrR1xmMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj1Uck49VL65GLNv+g4uz/q/P+/7f1/v/P+P7/8v3///////////////////r7/v9wdN3/QUfp/2pv//+co/r/wcPu////////////+fn//6ys//+Libv/h4OC/4Z1Df9oj7XratX4JAAAAAAAAAAAAAAAAAAAAAAAAAAA4+NVCePWS9Sglzr/VHCC/57t/v+m8/7/pfL+/6Ty/v+j8v7/wvb+//X9//////////////39/v90eeL/VVn8/3h++P/Exe//////////////////8fH+/7e39P+NjfD/fXiB/1qOzP9YtPrUceP/CQAAAAAAAAAAAAAAAAAAAADj1UuLoJg6/5W3uv+EzPL/br3z/6Hv/v+l8v7/pPL+/6Hx/v+e8f7/oPH9/+D6/v////////////j4/f9cYOP/Sk7p//Pz/P////////////////////////////Pz+v+foOb/RoHi/0qZ+f9TqfuLAAAAAAAAAAAAAAAA5NdKJtPGRfp9kYr/q/P+/5Pm/v9ipub/hNj+/6Xy/v+b6/7/f9X+/5nt/f+Y7/3/k+79/9T4/v/y6ev/yJ2k/7ODl/+ZbZP/5dLV//////////////////z8/v/Y3/r/7/L9/+Tk//+PlPn/Unvi/0WP9PpDlPgmAAAAAAAAAADj1UudiYM3/7nr8/+f8f7/ne7+/3vK9v9frO7/i9/+/3fQ/v90zf7/jeP9/5fv/f+R7v3/id3t/59baP/FipP/8dHU//bU1//Xpqz/yqGo///////3+f7/Rmno/xlE4v8hSeP/hY33/5GR//+Oj/7/WXnk/0GF8p0AAAAA3cxED+PVS/V/h17/tPT9/57w/v+h8v7/etL+/2Cm6P9rxf7/cMn+/3DH/P9+1v3/l+/9/5Dt/P+VlqT/6aaw/+ihq/+9eoT/9tTX//fV2P/mvcH/z6yy/8fR+P8ZROL/GUTi/xlE4v88Uev/fYLz/1Bw4v9Qdeb/O3rs9UR37g/j1Upa49VL/3+KaP+v8/3/m+/+/5jq/v+K3/7/Xaru/1qy+P9anuT/V6Ls/23G/f+U7v3/j+38/7eFkf/lmKT/+bjB/8VzgP/txcn/9tLW//bU1//Gj5b/6uz3/yZO4/8UOOL/EC3i/1Rg8v+Dg///VHHn/zt6+f8+fvr/PoD5WuPUSpvj1Uv/goNK/7Lz/f+c8P3/i+D+/5Pm/v9ht/j/RIPb/5jo+v9Pmen/Yrv9/4Te/f+N6fn/wHB8/9hzgv/rr7f/+e/x//vz9P/43+L/8MDF/9+vtf/jz9L/ydH5/05g7f9aZvL/b4Lt/2mI6P9hc+r/OHLx/zt6+v8/f/qb49ZLzN/SSv9jc2n/oNfy/5vw/f+W6v7/bsf+/2W//v9mp+P/nvH+/1ig6P9asf3/bMT9/43s+/+sXmr/qCk2/75ZZP/05OX///////PZ3P/RbHj/y2t2/9rBxv/Ozv//np7//4uN/f99sOj/jOz7/2ao6f86cen/O3j6/z5++szk1kvqnZQ1/7DZ3/+Fs+X/n+z8/4/k/v9wyP7/aMD8/3i/7P+d8P7/abDp/1Sp+/9XrP3/ftz8/5l8iv+ZICr/nyUu/6AyPv/KX2j/y15n/8xgaf+1T1v/o5nn/5ub//+QkP//bYHs/5vn+f9x5/r/VrD6/0qT5/86dvb/Pn376uPVS/+BgkX/vPT9/7zq+v+BtOf/ftP9/3LL/v9ux/7/dLvr/5zw/f+E2Pj/SZPr/1Km/f9Zrfz/YozM/5UvNP+fNDT/pT1F/8pcXf/KXmD/v1tj/45Sgv+Nj/v/jIz+/3iC9P9XiNv/arfo/2nX9P9YtPr/Spf4/zl15/89fPr/49VL/4GCRv+49P3/nO/8/7Ln+P96tuj/fdL8/3DI/v9ster/m/D9/4jf/f9ZoOf/UKP8/06e/P9Mmvz/YWOj/4Q4Tf+Ea5f/hJrH/4K15P+Lxez/h8Tr/1mN2P9tquT/f9Hx/4fp+v9pxe3/aNT0/0qY+v9Chfr/Qofl/zt28f/k1kvqnZQ1/63Y3v+Y7vz/l+/9/6Pu/P99xe7/dMTz/2m58f+N3vT/lO39/2e79/9Jkev/Spn8/0iT/P9Ihuj/isHs/6bw/P+P7fz/fur7/27b9v9bref/e+X5/3Lo+/9x5/r/buL6/0mX5f9Gj/r/P4D6/0KE+v9Xg+L/e4D06uPWS8zf0kr/cYBq/7Hz/f+X7/3/mfD9/5vw/f+I3v3/ftX8/3vL8f+I3/n/asH9/1Gd7/9GkPT/SYbo/5zg9v+H6/v/duf7/3To+/9z6Pv/XsD0/3Hn+/9y6Pv/cuj7/2/i+v9Xs+7/Pn/v/0GC+v8+fvr/QYP3/2p66/+Qiv/M49RKm+PVS/+8sT7/gJmT/6Px/f+Z8P3/mvD9/5rv/f92zv3/bMT9/2rC/f9kuv3/XLD8/0mT8f9isfD/fer7/3bl+/9t2Pv/dOj7/2jS+/9s2/v/cuj7/3Lo+/9p1vv/VKzx/z5/6P9Agvr/Pn/6/z59+v89cuf/jIn8/5SM/5vj1Upa49VL/+PVS/+wpTr/W29r/5fn+P+Z8P3/luz9/3XM/f9sxP3/aL/9/2+//P91vfz/Vqf8/1Wo+/9lw/v/Vqz7/2zW+/9o0Pv/TZ77/2DC+/9kyvr/Wqr3/z195/88e+v/PoD6/z1++v8/gPr/Pn3z/2d24f+Wjvn/nJP/Wt3MRA/QxEX1hoZI/4aiov+y3+f/ksLr/3u66v9zxfb/dc39/4zQ/f9xwv3/hcf8/4bE/P9xtvz/VqP7/1+l+/9Onfv/UKD7/0ya+/9IlPv/RY36/z6A7/9bkvH/Qob6/0CE+v8+gfr/P4H6/z5+8v92kOf/t7L5/5yV8PV3d90PAAAAAHV7n52BneL/k77q/7vy/P+l8v3/nvD9/4vZ9P9/z/H/ouL4/47Y/f+Cxfz/hsT8/3y7/P9Ypfv/bq/7/0+e+/9NnPv/TJn7/0mW+/9IlPv/SJL5/0iU+/9Ik/v/RpD6/0GH9v9OhOb/t8nu////////////5eL/nQAAAAAAAAAA8vL/JsTD/fqInOn/j7no/5rG7P++8vz/r/P9/6Dw/f+c7vz/fcjy/2mw9P+Fw/z/c7X1/1Om+v9Tpvv/UaT7/1Ci+/9PoPv/Tp77/06e+/9MmfX/SZPv/0aN6/8+fd7/haLg//n6/f///////////+Pi//rDvP8mAAAAAAAAAAAAAAAAqbD2i6LF7f/Z+v//oOj6/4XA6/+LwOv/hsHr/4DE7P93tOf/bcb8/2m4/P9ytO7/V6r7/2XH+/9t2Pv/Z8z7/1as+/9SpPr/VKf3/1So+/9kw/v/dN37/23Q+/9ZrvP/bJ3l/+nu+f//////////iwAAAAAAAAAAAAAAAAAAAAA5VcYJ2fn/1NL6//+r9v//rPb//6v2//+p9v//pvb//4a/6v+V7vz/cdD8/3Oy6/9rvvv/eOn7/3bo+/926Pv/dOT7/1mx+/9TpfL/T5nk/2fF+P9+6Pv/f+r7/37p+/902fv/aaXm//f4/dT///8JAAAAAAAAAAAAAAAAAAAAAAAAAADc+P8kyfr/66v2//+s9v//q/b//6j2//+l9v//er3q/6ft+/+A5vz/YKPp/5bY+/956fv/d+n7/3bo+/946fv/ctz7/1aq+/9fr+j/dMbu/2e46f9ov+v/eNr1/3/p+v974vjrXIDVJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACt9f8yq/b/66v2//+q9v//qPb//6X2//+Z6/v/h77q/4rs/P9yrun/dqzo/5bu/P936fv/d+n7/3np+/976fv/Ybz7/1mo6v+U8f7/mPT//5Ls/P9+zvH/ZKfj61eK1jIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACq+P8kq/f/1Kr2//+o9v//pPb//6D1//95w+z/ot/1/3Cp6f9RlvX/fbbp/5Dt+/946fv/een7/3zq+/9v0Pv/Wajr/5Pu/P+b9f//nPX//5z1/9Sc8f8kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACq//8Jqfb/i6f2//qk9v//oPX//4vh//9amen/UZLu/1Wc//9Okff/aKDm/5ro+f9/6vv/fer7/3bc+/9cqen/mvX//531//qg9v+Lqv//CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAqPj/JqT3/52f9v/1fc///2Gt//9Zov//U5f//1CU//9wx+3/WmVL/4Sytv+V7vz/fOL4/4C15fWm9f+dofj/JgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJnu/w9xwf9aYa3/m1mh/8tRlv/pZrj//WKPf/3f0UnpraM6y3aWlJuTzNVaRGZ3DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAADAAAABgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//gALSw0sReHAlIlRNG0yOimeDyMWztNfVxdTj4M/uta+E/oqHDf6hoA/upaQO1KemELSnpRCDq6sNTLy8DyKlpQ8RgIAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//0AE5dVJMeHUTHbf0UmxtKk85qOZNv+fljT/mZA0/5SMP/+Ri1T/XVor/8jHFf/FwxT/s7AS/6ShFP+npBn/qKUQ/7W0EebCwRGxs7MRdnhyCjG/v4AEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/XSCDi1Uqe49RL4+LUSvrj1Uv/49VL/+PVS//j1Uv/49VL/+LUS//WyEb/SkcS/8nIFf/QzxX/yMcU/5OPMP/j4tD/1NK1/6mla/+OiRr/nJcO+pKMU+Ps7NKdv7ePIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAHm2U0U4tNLc+LUSvDi1Ev/281I/9LFRf/Lv0P/xblF/8G2R/++s0j/vLFJ/72ySP/BtUb/oJc3/0E/Dv+RkA//vr0T/6CcLf/r6uP///////n59v+vq4r/sa6H/+jn0P/Fwp7/iIUe8JmXDXOMjA0U//8AAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPTTEDj1Uu31slG+qidOf+clEr/nZdg/5iUcP9vbnX/OTp7/xsfhv8WG5T/ExmV/xQZkf8dIYj/LjR7/z5AcP9HSGH/UVI7/2VjLv/Kyc///Pz+///////n5tz/uLWX/7i0lP+SjnD/mZUe/7i2EfqioA+3fX0MPwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/AAAB4tVLYuHTS+ijmjf+cm5R/8LBt//j4uD/6+vr//Ly8//s7Pb/3d73/56h6v89Q9f/HCTf/x0l5P8cJOD/HifZ/2Fo4P+jqfT/mqDn/32Cy/+bndP/0tLu/+Xl9f/7+/3/+Pj1//Dv6v/e3e7/mpm8/4uGIf+7uRL+ioY56Ojow2IAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANvbSQfk1kpx4NJK9JqRPP+OjYb/9vb2///////////////////////////////////////z8/z/lJfi/zE41v8dJd3/GSHX/0xR6v+WnP//qbD//5ui+f+go+r/+/z+///////////////////////8/P//s7P//3x3dP+JhD//ycaa/62ocfRdVhdxSW1tBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wAAAeTWSnHj1UrtoZg1/22Egf/N8PX/2Pn+/+H7/v/u/P7//f///////////////////////////////////9PU8/9hZtz/HSTU/z1C5P9nbP//mJ7//6Kp/P+Sl+r/8PD7///////////////////////x8f//ra3//4mGof+5to//q6dx/31wGf9iYTrteqnJcQD//wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4tVLYuPVS/Tj1Uv/TFAs/6Ho8/+n8/7/qPP+/6vz/v+v8/7/uvX+/+D6/v/8///////////////////////////////t7fr/am7Z/ysy1v9aXv//Zmv//6Kp/v+Kj+n/6er5//////////////////v7///Nzf//oKD//5ST7v+HhLD/f3yg/3ZpEf9zc0f/grfh9GvY+mIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAHj00xA5NVL6NLFRv+Bfjr/NU9j/6Hv/v+m8/7/pvP+/6bz/v+l8v7/pPL+/6Py/v+19P7/5Pv///n+////////////////////////+/v+/2lu3P9OU/P/V1v//3p//f+Ijen/6ur5///////////////////////+/v//29v8/6Gh8/+Vlfj/kpL6/4B8mP9eZ1j/ca7p/1av+uhp2/s/AP//AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAObZTRTj1Uu3zcBD/m5uQP+JrbL/W5TZ/3/R+f+f7f7/pvP+/6by/v+l8v7/pPL+/6Ly/v+g8f7/ofH+/7/1/v/q/P7//v///////////////////+jp+f9pbeL/Ulb5/1lc+v+Giuf/8vL7//////////////////////////////////f3/f/T0/H/ra3q/4aG2/9adK7/Upvx/0yd+v5Zt/m3Wb/yFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOLTS3PYy0f6V1Qq/6bGy/+n7fz/fcTv/1ie5v+J3f7/o/D+/6by/v+l8v7/pPL+/6Ly/v+g8f7/nfD9/5rw/f+m8f3/4/v+//////////////////7+///P0PL/R0zf/09T8/+doOf//v7/////////////////////////////////////////////+Pj9/9HR9v9vguD/QHvh/0mW+P9Mnvr6Tp34cwAAAAAAAAAAAAAAAAAAAAAAAAAA39dIIOHTSvCOhzX/k6yq/7n1/v+h8v7/i9/+/1yb4P9twPb/leX+/6Xy/v+k8v7/n+/+/4zg/v+M4f7/nO/9/5nw/f+V7v3/le/9/9z5/v/8////+PP0/+TR1P/Koaf/hVaD/2lHkv/Yytn/+vf3/////////////////////////////f3///P1/f/z9f3//f3///b2//+ys///fIrv/0Vz2v9Fi/D/SZf68EiP/yAAAAAAAAAAAAAAAAD//0AE4tVKntDDRf93f17/uuXs/6Lx/v+h8v7/juH+/3/M9f9epef/eM78/57t/v+Y6f7/gNf+/3XO/v9/1v7/me39/5nw/f+V7v3/kO79/5Tu/P/D3OT/toKM/72Ejf/ftLr/5bzA/9iorv/FjZX/wpKa/+jY2//////////////////t8P3/mq3y/2iE7P9ohOz/lKfx/9fZ/f+np///lZX//4iO+P9YeuT/QYLr/0aR+p1AgP8EAAAAAAAAAADl1Ukx49RL47mvQ/9+lZX/s/L9/5/x/v+h8f7/n+/+/3fO/f9nq+f/aLz3/4HX/v980/7/dc7+/3XN/v93z/7/luv9/5jw/f+U7v3/j+79/4rk8/+Lf47/ql1p/7Jlcv/Ikpn/89PW//bV2P/00dT/573B/7Z5g//fyMz///////v8/v+QpfH/IUrj/xlE4v8ZROL/HETj/0td7P+Ulf//jo7//4yM//+JjPv/U3Tf/z1+7ONEjfoxAAAAAP//gALh1Ex24tRK+o6KPv+bu7//pvL9/57x/v+g8f7/ovL+/3/V/v9vvfP/V5/o/2zG/v9wyf7/csv+/3LK/f9yyv7/jOP9/5jw/f+U7v3/j+38/4vH1v+9gY3/6aOu/+igqv+9bnr/1aWr//bU1//31dj/99XY/+7Hy/+8hI3/7+Tm/+3w/f9Wdun/GUTi/xlE4v8ZROL/GUTi/yJA5f92evL/dH3s/2B26P9jeev/YHno/zVs2fpBhvl2AID/AuHSSxHk1Uux49VL/3h3PP+oztP/o/H9/5zw/v+b7f7/ofH+/5Hk/v9vx/3/To3e/2O+/f9mv/z/WqXs/1uo7f9ux/7/e9P9/5fv/f+T7v3/ju38/5CMm//bmKP/6J+q//e1v//poq3/qlxo//TQ1P/209f/9tTX//bU1//brLH/w5ad/+/y/f9dfOr/GUTi/xhC4v8VO+L/FDji/yA55v97fvv/gIP8/0ps3f82b+f/OXbu/z199f8/gvuxPHjwEejaSyLi1Uvm49VL/358Pf+jytD/ofH9/5zx/v+S5v7/nO7+/5vs/v9vyf7/Wp/n/1Om8v9Omuj/dbvr/0iK4P9pwv3/bMT9/5Ps/f+S7v3/ju38/5tjcf/noKv/5pmk//Svuv/zrLf/sFdl/+Cyt//20dX/9tLW//bT1v/00dT/rGhy//Tv8f+arvL/IErj/xU64v8RLuL/Dyri/0JS7v+Ghv//goL//3B79P85bub/O3r6/z19+v8+gPnmPID/IuHTSkzj1Uv/49VL/52XQf+PsbT/ovH9/5zw/f+W6v7/iN3+/5vt/v950f7/X7Dz/0KH4P9mq+b/mur7/0SE3f9ivP3/ZL39/4Da/f+R7v3/jOj3/6pea//cgI3/44qX/+6msP/01Nj/8uLl//Xq6//66On/9tPX//TLzv/1z9L/y5Oa/9a6vv/3+P7/hpvw/ydC5v8kPOb/RVTu/4CG+f9pfuv/cX7y/3N69v9Gb+b/OXb3/zt5+v89ffr/PID4TOLVS4Xj1Uv/49VL/6SeQP90kJ7/p/D8/5vw/f+d8P7/hdz+/37U/v9yy/7/YLn7/z1z0f+K1PP/nvH+/06N3f9asvv/X7b9/2zE/f+O6/3/jOf3/6hbaP/IXmz/vkVU/8hib//78/T/////////////////9d/i/92Nl//imqL/0o2V/8Wco///////1NT//5ye/f+Pkvz/j4///2eA5/+Cvur/dLrp/2SN4/9BbN//OXT2/zp4+v88fPr/P4D5hePVS7Xj1Uv/2cxI/01XTf9/qtj/rOb4/5rw/f+d8P3/len+/2/I/v9rxP7/ZL7+/02G2P+d7v3/nvH+/2et5/9PoPP/WbD9/1+2/f+A3P3/jO38/5VWZP+1SVX/picz/6wwPP/OhIz/9Obn///////9+vr/5a+1/9Bpdv/Ra3f/w2Fu/8SZof/v7///srL//56e//+UlP//g4f6/2SW3v+e7fv/eun6/2i69v9XkOH/OnPw/zp3+v88e/r/P3/5teTVS9fj1Uv/hHws/4yttP+cyu7/lcLr/6Lw/f+a7v3/kOX+/3HJ/v9txv7/Zb37/12c3/+e8f7/nPD+/4HP9P9Jken/Vaz9/1et/f9qw/z/iOr8/4p/jv+pQkz/nCEr/6AkLv+mKjX/mjNB/8hgav/NZG7/zF9q/81ha//NY23/rklW/6aNx/+lpf//nJz//5SU//+MjP//XXjk/5ra9P+J6/v/cef6/2PM+v9PmfX/PXrb/zt2+P88e/r/P3761+PVS/Lf0kr/TU4s/8Hv9v/D8vz/hLHl/4/H7v+N3/3/etH+/3LK/v9vyP7/acH8/16e4P+e8f7/nPD9/4LV+P9VnOf/Uqb6/1So/f9YrPz/dtP8/3yw0P+TO0n/mSYs/5wpLv+jMjn/nDQ//8lYXv/JWmD/ylxh/8tdYv/FWWD/lEVk/5qW9/+Wlv//kpL//42N//99hPf/bqDl/6Dw/P915/r/cef6/2jW+v9Chfr/UaXr/zZu5f88evr/Pn368uPVS//SxUb/V2JQ/8H1/f+08/3/w/D8/4Ow5f+FxvD/etH+/3PL/v9xyv7/bsb+/1eX3/+c8P7/m/D9/4rh/P9jquf/UJ/1/1Km/f9RpPz/Vaj8/1af8v9xUnz/lzEy/583Nf+ZMzn/t01Q/8tdXf/MX17/yGBh/7tdaP+bRVn/g2m4/4aL9f+LjP7/iYr+/3J/8P9Obtv/ToXW/1qW3P9VpOH/bd73/2fU+v8/f/r/Uab5/zt42v88evn/Pn36/+PVS//RxEX/WGNS/8H1/f+d7/z/rPH9/7/v+/+AsuX/gs3y/3rQ/f9zy/7/cMf+/12i5f+R4/j/mvD9/5Pp/f9wwPP/S5Dl/1Gl/f9Pofz/T5/8/02c/P9ShNv/ez9b/5U5PP+WQlH/oGZ//31xpP9kfMH/YJHY/22j4P91reP/dKzj/2GW2/9JedL/VYva/3e35/+R2/T/lez7/4Hh9/9dtef/bd73/1q4+v8+ffr/Ro76/0aR4P87d/P/PXr3/+PVS/Lf0Un/TU8t/7/v9v+m8f3/lO79/6Hw/f+r6vr/iMHr/3m/7P95zPj/csr9/2q68v99x+z/me/9/5Xt/f960vz/Vpvj/0qX8v9On/z/S5r8/0qY/P9IlPv/SnfV/15Vk/99lsj/i8Hq/5/f9f+k7vv/nfD8/5bv/P+M4Pb/eLfn/2605v980vL/hur7/3vp+v9y5/r/cef6/2XP8v9Nnef/Wrn6/0SJ+v8+fvr/Q4b6/0uV3/9IceX/UHTq8uTVS9fj1Uv/g3ss/4qrsP+08/3/lu79/5bu/f+a8P3/nu/8/5De9/93wO3/cb7v/3HG+v9tt+n/kuf4/5fv/f+A2P3/aL35/0eI3/9Mm/n/SZb8/0eS/P9BhO//V43f/6Ha9P+s7fv/le77/4Dq+/966fv/dun7/3Dh+P9Wquf/aczy/3Xm+v9z6Pv/cuj7/3Hn+v9x5/r/atn6/0yd4/9Ag/H/Qof6/0CA+v8+ffr/Roz6/0yH3v+Agvf/iIb71+PVS7Xj1Uv/2cxI/0xUQv+35ez/nvD9/5bu/f+Y8P3/mvD9/5vw/f+R5/3/gdj8/4bb+/96zvf/fMfq/4/n+/+F3v3/Zbv9/1mp8/9Eien/SJX7/0OK9P9gl+P/q+n5/5rv/P996vv/duf7/3Xo+/9z6Pv/c+j7/2XO9f9dvfL/cuf7/3Lo+/9y6Pv/cuj7/3Hm+v9q2vr/Wbbv/zl14f9Ch/r/QIL6/z9/+v8+ffr/SI/4/0xv3P+OiP//kIr/teLVS4Xj1Uv/49VL/6WdPf96j4f/tOz1/5jv/f+Y8P3/mvD9/5vw/f+b8P3/j+X9/3PL/f91zP3/d8z4/3jM9v9sw/3/Y7n9/1uv+/9LlO//Qonu/0iG4P+I1PX/h+z7/3rp+/915fv/cuH7/3To+/9z6Pv/cOL7/2DF+v9w4/v/cuj7/3Lo+/9y6Pv/cuj7/2jV+v9YtfH/P4Lg/0CD9/9Bg/r/P4D6/z59+v8+fPr/OnTo/2166/+Riv//kor/heHTSkzj1Uv/49VL/97QSf+Jgzj/f5iX/7Tz/f+Y8P3/mvD9/5rw/f+a8P3/mvD9/3/W/f9uxv3/a8P9/2nB/f9nvv3/Y7n9/16z/P9WqPv/SpX0/1ak8P953vv/fOr7/3jn+/9pz/v/ceD7/3Xo+/9y5Pv/W7n7/2zb+/9y6Pv/cuj7/3Lo+/9w5Pv/Xbz7/1Gn9f9BhuH/Pn/z/0CC+v8/gPr/Pn76/z5++v8+fPf/Q23c/4+L/f+Ujf//lI3/TOjaSyLj1Uvm49VL/+PVS//g0kr/d3Ao/2J3dv+b3ej/me/8/5rw/f+a8P3/mO79/33U/f9uxv3/a8P9/2nA/f9mvv3/a7z8/227/P9er/z/UqL8/1Ki/P9u0Pv/cdj7/1+7+/9ct/v/cuL7/3Hi+/9fv/v/TZz7/2TJ+/9v4Pv/bd37/2fM+v9Lmff/RY7t/zt53f87fPP/PoD6/z5/+v8+f/r/P4D6/0CA+f89c+X/d4Dt/5eP/P+Zkf7mnpb/IuHSSxHk1Uux49VL/9rNSP+flzn/h4lR/2R0a/93nrn/e73q/5Hg+P+L4v3/f9b9/3HI/f9zyP3/fcn9/2zB/f9tv/3/hcf8/4fF/P96vfz/Wqn8/1Cf/P9Tn/v/T577/1Cg+/9Vqfv/YsX7/1q0+/9Nnfv/SZX7/0mW+/9Nnfb/RIzt/1SK7f9Mgun/Onjq/z+A+P8+gPr/Pn/6/z1++v8+f/r/QYL6/z966/9keeH/jIbr/46G6/+Qh+6xlofwEf//gALf0kl2sKY6+mJjOP+MqaX/td3j/7vs8/+37Pn/rdv0/3yu5P9mqOT/e832/3zU/f+Bz/3/j9H9/33I/f90wv3/icj8/4fF/P+Ewfz/bLL8/1Sj+/9srfv/W6P7/02c+/9Onfv/Tp37/0ya+/9Jlvv/R5L7/0aP+/9Eivn/QYb3/1CO9/9Vk/n/Qof7/0GG+/8/g/r/P4L6/z+C+v9Ag/n/OXbl/3mU5P/Dwvv/zMn9/6+q+/qel/Z2gID/AgAAAAA5OSoxUV+H416F0/+Wwez/uOX4/7zz/P+l8v3/nPD9/6Dx/f+b5vn/eL/r/2626P+Fye7/n932/57j/f9/y/z/h8f8/4bF/P+Ewfz/d7j8/1Wk+/9vr/v/Z6r7/06d+/9Onfv/TJv7/0ya+/9Klvv/SJT7/0eS+/9Hkfv/R5H7/0eR+/9Hkfv/R5D7/0WO+/9Di/r/QYb4/0GC8v9ShOL/sMLr/////////////////+/u/+Osp/8xAAAAAAAAAAD///8E09P8nbi6+P+Wo+3/cJPe/4q35/+z4fb/u/T9/6vz/f+d8P3/mPD9/5fv/f+b7/3/q/D9/57l/f91xvv/gL/4/4bE/P+Ewfz/dLX4/1Ok+v9dqfv/XKj7/1Ci+/9QoPv/Tp77/02d+/9Mm/v/TJr7/0uZ+/9Kl/n/R5Dy/0WN8P9GjfD/Ro3w/0OI7v9Ihej/aJbo/5m06f/b4/X//f7/////////////9/b//+Df/56/v/8EAAAAAAAAAAAAAAAA9/f/IM/P/vCusvn/b5He/7fe9f+BruT/hrLm/8Hu+v/F9v7/ufT9/6ny/f+f8P3/lur8/3fB7/9Wn+n/cLf3/4bE/P+Dwfz/Za3t/1Sn+/9Up/v/VKb7/1Kl+/9RpPv/UKP7/1Ch+/9PoPv/T5/7/0+f+/9Qofv/T5/4/0+f9/9NmvP/SJLt/0KF4/9Rgtn/pbrn//n7/f/////////////////19P//zMn/8L+3/yAAAAAAAAAAAAAAAAAAAAAAAAAAALy8+3OIner6utz0/9r7///A9v7/kNTy/2yf3/91puH/hbXn/3+x5f9uo+D/Z6Xh/2Wh4P9vvfT/Zbz8/266/P9nrPX/gsLw/1eq+/9Yrfv/YL37/2fM+/9lyfv/W7b7/1Oo+/9RpPv/UaP7/1Ol+f9Tpvv/VKf7/1mw+/9s0fv/b9T7/2bF+/9asfn/SpTq/2OQ3v/T3vT//f3+///////////6//3/cwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHOM2RScvO231PT9/tr7///A+P//qvX//6r1/v+p7vz/oOT4/57n+v+l8v3/pvb//3Gv5f+Y3/j/g+P8/2zI/P9Qm+//ltT0/12v+/9nyfv/d+f7/3fp+/926Pv/dOX7/2rS+/9Zsvv/U6b6/1Ki8P9VpvH/Wa76/2C7+/975/v/fur7/33q+/965Pv/cNT6/2C59v9ineb/x9Xx//////7///+3////FAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wHO8/s/2/v/6Nj7//+59///rPb//6z2//+s9v//q/b//6r2//+o9v//pfb//3q86v+e2vP/je38/3/j/P9WpfD/jcfv/3i//P9w2fv/eOn7/3bo+/926fv/duj7/3fo+/9t1/v/WK37/1Wo+f9NluT/S5Hd/2O88/912/v/f+n7/4Dq+/9/6vv/fun7/3zm+/9v0fj/WZPf/+fs+Oj///9A////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2/z/YtX7//Sz9///rPb//6z2//+s9v//q/b//6n2//+n9v//pfb//47a9P+MwOr/lu78/4Pp/P9ow/j/ZqDi/5zV/P963/v/eOn7/3fp+/936Pv/duj7/3fp+/946fv/aMr7/1aq+/9ZrvL/Y7Hm/2ez5/9apeL/b8rw/3jb9v974fj/fub5/4Dp+/9/6vv/cdP19FuC1WIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AdD9/3Gu9v/tq/b//6z2//+r9v//q/b//6n2//+n9v//pPb//5np+/98t+f/p+r5/4Tr/P9/2vz/Vo3b/4zB7v+W5fz/e+n7/3fp+/936fv/d+n7/3jp+/956fv/eeb7/1y0+/9guvr/UZbe/5Tz//+O6Pr/eMjv/2686v9quen/aLjp/2W36P9mt+jteNv2cQD//wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALb//wes+P9xq/b/9Kv2//+r9v//qvb//6n2//+n9v//pPb//6D0//93vuv/ntPx/5bu/P+W6/z/VYze/1SO4v+e2fT/ke77/3fp+/936fv/eOn7/3jp+/966fv/fOr7/23P+/9ft/v/T5bf/5Ht/P+X9P//mPX//5j0//+U7fz/j+b6/4bZ9fRhmd1xbbbbBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8BrPf/Yqv2/+ir9v/+qvb//6j2//+m9v//pPb//6H1//+W6/v/YZze/63n+P+l5/j/U4zi/1ac+f9dl+P/o9/2/4zt+/956fv/eOn7/3np+/966fv/fOr7/3jg+/9hufz/Upvh/47n+v+Z9f//mvX//5v1//+c9f/+m/X/6Jz1/2IA//8BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKr3/z+q9/+3qfb/+qj2//+m9v//o/b//6H1//+d9f//fc71/2ad4v+DuOf/VZbw/1if//9PkvX/WZPl/47L7v+W7fv/fer7/3np+/976fv/fer7/3vk+/9oxfz/TpLe/5bx/f+b9f//nPX//531//qd9f+3m/P/QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wGm8v8UqfT/c6j2//Cm9v//o/b//6D1//+d9f//e87//1uj9f9Ni+X/Vp36/1ac//9TmP//T5P7/02J6P96s+f/p+77/4fr+/976fv/fur7/3zm+/9uzPr/VZje/5r1//+c9f//nvX/8J30/3Om8v8U////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/3/yCm9/+do/b/45/1//qb8v//cL7//2Ku//9eqP//WKH//1SZ//9Rlf//UJP//2a4/P9Tj6X/V21n/53R1/+W6vb/hOv7/37n+/9mu+3/k8Tt+qP2/+Od9f+en/f/IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC///8EofX/MaD0/3aT6f+xbLn/5mKu//9dp///WJ///1OY//9Qk///Xan//3rX5v9yhVb/tKg7/3p7QP94l4//ouLr/5Xo9eZfocexsdrudsb6/zG///8EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID//wKH0v8Rabz/ImGr/0xdp/+DVqD/tFKY/9RRl//ue9z//mGdmf6nnzru49VL1NnMSLSKhjqDeZeXTKzo+CJah5YRgICAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==","base64");function GET(){return new e.NextResponse(z,{headers:{"Content-Type":"image/x-icon","Cache-Control":"public, max-age=0, must-revalidate"}})}let b="force-static",L=new r.AppRouteRouteModule({definition:{kind:n.x.APP_ROUTE,page:"/favicon.ico/route",pathname:"/favicon.ico",filename:"favicon",bundlePath:"app/favicon.ico/route"},resolvedPagePath:"next-metadata-route-loader?page=%2Ffavicon.ico%2Froute&isDynamic=0!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\favicon.ico?__next_metadata_route__",nextConfigOutput:"",userland:P}),{requestAsyncStorage:j,staticGenerationAsyncStorage:u,serverHooks:o,headerHooks:t,staticGenerationBailout:a}=L,p="/favicon.ico/route"}};var v=require("../../webpack-runtime.js");v.C(A);var __webpack_exec__=A=>v(v.s=A),f=v.X(0,[201],()=>__webpack_exec__(8837));module.exports=f})(); \ No newline at end of file +(()=>{var A={};A.id=155,A.ids=[155],A.modules={517:A=>{"use strict";A.exports=require("next/dist/compiled/next-server/app-route.runtime.prod.js")},8837:(A,e,t)=>{"use strict";t.r(e),t.d(e,{headerHooks:()=>b,originalPathname:()=>p,patchFetch:()=>h,requestAsyncStorage:()=>l,routeModule:()=>u,serverHooks:()=>c,staticGenerationAsyncStorage:()=>d,staticGenerationBailout:()=>P});var r={};t.r(r),t.d(r,{GET:()=>f,dynamic:()=>v});var i=t(5419),n=t(9108),o=t(9678),a=t(9647);let s=Buffer.from("AAABAAMAEBAAAAEAIABoBAAANgAAACAgAAABACAAKBEAAJ4EAAAwMAAAAQAgAGgmAADGFQAAKAAAABAAAAAgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADg1Ukx1stHl7asSdmmoF75uLcS+bGvQtmppyCXsbF9MQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPGOQnCuEeaxL10/q6qjf9aW5L/S02N/29xb/+9vbz/3tzR/7a0k/6hnxea4+PGCQAAAAAAAAAAAAAAAOPGOQnFu0PCr9DM/+H7/v/8/v//9PT8/3N44/9qcPb/s7f0///////d3f//mZaR/3h9U8Jxxv8JAAAAAAAAAADHu0Sag6Ka/5Xj+/+k8v7/qfL+/936/v/+/v//h4rv/56h8///////+/v//83N9/9visX/Uaf6mgAAAADg1UkxpLF+/p7u/v9wvfL/kOP+/4bc/f+V7v3/u8bP/8yfqP/Trrv/8ufp/87X+f+Al+//oqX7/1+F7v4+h+8x4tVKl5i+sP+c7/7/cMD0/2S39v9swfj/ku78/8aWov/ZkZz/9NDT/9yzuP98lO3/FTvi/2Rt9P9MdOr/PX31l+LVS9mOsKj/lur9/3LJ/P94we3/Wanz/4Le+/+7Wmf/5be8//nq7P/bkZr/1czk/3R89/94qe7/Tn/r/zx7+tm4r0P6q9rv/4vW9/9uxv3/idb0/2Kx8v9gt/z/ilZt/6EyOf/KXmP/s1dq/5aU+P9zh+7/eNf0/1Cj9f87ePT6uK9E+qbq9f+Z3vb/d8n3/3/P8/93yvb/TJv4/0+F4f+OlbP/hcno/3fE7f9twez/eeH4/1iw8P9DiPr/U4Dr+uLVS9mXr47/m/D9/5br/f93zPr/cMf8/0+c9P9xwPL/eOT7/3Hi+/9r2vn/cOP7/1aw8P8/gPf/Pnz0/4WF+NnczkmXqKhc/42+zf+H1/b/eMv9/3PC/P9wt/z/XK37/1iw+/9Sp/v/Uqb3/02Q8v8+gPb/Pn/4/3SN7f+YkfeXjZKxMZiu7P6i2fP/pev6/5fk+P99xfj/fr76/1uo+/9PoPv/TJv7/0qX+f9IkvT/Uo3r/7/R9P/4+P/+29v/MQAAAAC00fOavfT+/5rb9f+V3PX/gMry/3C79P9oxvv/cN37/125+/9So/L/b9P6/3HU+f+MwvD//Pz9mgAAAAAAAAAA4///CbT3/8Kr9v//pvb//5DV8v93yfL/h9f2/3fp+/935vv/XK/y/4LZ9f981fP/cszvwlVxxgkAAAAAAAAAAAAAAACq//8JqfX/mqb2//6R4/r/b63t/1ye9f+C1/X/fOr7/2a/8v+Z8/7+nfX/mo7j/wkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACn9f8xit3/l12n/9lWn//5gaKB+ZG7p9mAyeeXp/X/MQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAACAAAABAAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADdzEQPk4swWmNcIZuGg2LLnpqM6a+qiv2loxD9uLcS6by7Esu9vBCbtbMOWoiIEQ8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADk10om49VLnePVS/Xj1Uv/49VL/+PVS//czkn/cGsg/8/OFv+3tRL/nJhP/7m2ev+opTf/qaUQ9aumcJ3d3bwmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj41UJ49VLi+LUSvrSxEX/q6E4/4+GNv99d0H/dG9F/3hyQ/94cjH/RkQO/4iIDf+zsGf///////Tz7/+dmW7/1dO3/5WRLfqenA+Ljo4ACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA49VHJN/RSdSZkUL/oqCI/7y8vP/W1t7/qKro/1pg4v8dJeD/HCTj/yIs3P9udd//f4TB/2Rnmf/e3vL/9PT7//Py7v/V08b/mpig/6+sGP+Vkx/U4+O/JAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAODRRzLd0EnrgX1X/+/v7////////////////////////////9LU8/9JUNr/GSHY/1lf8v+jqf//hozw/+vr+f/////////////////Pz///kY15/8K/jf+EezfrR1xmMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj1Uck49VL65GLNv+g4uz/q/P+/7f1/v/P+P7/8v3///////////////////r7/v9wdN3/QUfp/2pv//+co/r/wcPu////////////+fn//6ys//+Libv/h4OC/4Z1Df9oj7XratX4JAAAAAAAAAAAAAAAAAAAAAAAAAAA4+NVCePWS9Sglzr/VHCC/57t/v+m8/7/pfL+/6Ty/v+j8v7/wvb+//X9//////////////39/v90eeL/VVn8/3h++P/Exe//////////////////8fH+/7e39P+NjfD/fXiB/1qOzP9YtPrUceP/CQAAAAAAAAAAAAAAAAAAAADj1UuLoJg6/5W3uv+EzPL/br3z/6Hv/v+l8v7/pPL+/6Hx/v+e8f7/oPH9/+D6/v////////////j4/f9cYOP/Sk7p//Pz/P////////////////////////////Pz+v+foOb/RoHi/0qZ+f9TqfuLAAAAAAAAAAAAAAAA5NdKJtPGRfp9kYr/q/P+/5Pm/v9ipub/hNj+/6Xy/v+b6/7/f9X+/5nt/f+Y7/3/k+79/9T4/v/y6ev/yJ2k/7ODl/+ZbZP/5dLV//////////////////z8/v/Y3/r/7/L9/+Tk//+PlPn/Unvi/0WP9PpDlPgmAAAAAAAAAADj1UudiYM3/7nr8/+f8f7/ne7+/3vK9v9frO7/i9/+/3fQ/v90zf7/jeP9/5fv/f+R7v3/id3t/59baP/FipP/8dHU//bU1//Xpqz/yqGo///////3+f7/Rmno/xlE4v8hSeP/hY33/5GR//+Oj/7/WXnk/0GF8p0AAAAA3cxED+PVS/V/h17/tPT9/57w/v+h8v7/etL+/2Cm6P9rxf7/cMn+/3DH/P9+1v3/l+/9/5Dt/P+VlqT/6aaw/+ihq/+9eoT/9tTX//fV2P/mvcH/z6yy/8fR+P8ZROL/GUTi/xlE4v88Uev/fYLz/1Bw4v9Qdeb/O3rs9UR37g/j1Upa49VL/3+KaP+v8/3/m+/+/5jq/v+K3/7/Xaru/1qy+P9anuT/V6Ls/23G/f+U7v3/j+38/7eFkf/lmKT/+bjB/8VzgP/txcn/9tLW//bU1//Gj5b/6uz3/yZO4/8UOOL/EC3i/1Rg8v+Dg///VHHn/zt6+f8+fvr/PoD5WuPUSpvj1Uv/goNK/7Lz/f+c8P3/i+D+/5Pm/v9ht/j/RIPb/5jo+v9Pmen/Yrv9/4Te/f+N6fn/wHB8/9hzgv/rr7f/+e/x//vz9P/43+L/8MDF/9+vtf/jz9L/ydH5/05g7f9aZvL/b4Lt/2mI6P9hc+r/OHLx/zt6+v8/f/qb49ZLzN/SSv9jc2n/oNfy/5vw/f+W6v7/bsf+/2W//v9mp+P/nvH+/1ig6P9asf3/bMT9/43s+/+sXmr/qCk2/75ZZP/05OX///////PZ3P/RbHj/y2t2/9rBxv/Ozv//np7//4uN/f99sOj/jOz7/2ao6f86cen/O3j6/z5++szk1kvqnZQ1/7DZ3/+Fs+X/n+z8/4/k/v9wyP7/aMD8/3i/7P+d8P7/abDp/1Sp+/9XrP3/ftz8/5l8iv+ZICr/nyUu/6AyPv/KX2j/y15n/8xgaf+1T1v/o5nn/5ub//+QkP//bYHs/5vn+f9x5/r/VrD6/0qT5/86dvb/Pn376uPVS/+BgkX/vPT9/7zq+v+BtOf/ftP9/3LL/v9ux/7/dLvr/5zw/f+E2Pj/SZPr/1Km/f9Zrfz/YozM/5UvNP+fNDT/pT1F/8pcXf/KXmD/v1tj/45Sgv+Nj/v/jIz+/3iC9P9XiNv/arfo/2nX9P9YtPr/Spf4/zl15/89fPr/49VL/4GCRv+49P3/nO/8/7Ln+P96tuj/fdL8/3DI/v9ster/m/D9/4jf/f9ZoOf/UKP8/06e/P9Mmvz/YWOj/4Q4Tf+Ea5f/hJrH/4K15P+Lxez/h8Tr/1mN2P9tquT/f9Hx/4fp+v9pxe3/aNT0/0qY+v9Chfr/Qofl/zt28f/k1kvqnZQ1/63Y3v+Y7vz/l+/9/6Pu/P99xe7/dMTz/2m58f+N3vT/lO39/2e79/9Jkev/Spn8/0iT/P9Ihuj/isHs/6bw/P+P7fz/fur7/27b9v9bref/e+X5/3Lo+/9x5/r/buL6/0mX5f9Gj/r/P4D6/0KE+v9Xg+L/e4D06uPWS8zf0kr/cYBq/7Hz/f+X7/3/mfD9/5vw/f+I3v3/ftX8/3vL8f+I3/n/asH9/1Gd7/9GkPT/SYbo/5zg9v+H6/v/duf7/3To+/9z6Pv/XsD0/3Hn+/9y6Pv/cuj7/2/i+v9Xs+7/Pn/v/0GC+v8+fvr/QYP3/2p66/+Qiv/M49RKm+PVS/+8sT7/gJmT/6Px/f+Z8P3/mvD9/5rv/f92zv3/bMT9/2rC/f9kuv3/XLD8/0mT8f9isfD/fer7/3bl+/9t2Pv/dOj7/2jS+/9s2/v/cuj7/3Lo+/9p1vv/VKzx/z5/6P9Agvr/Pn/6/z59+v89cuf/jIn8/5SM/5vj1Upa49VL/+PVS/+wpTr/W29r/5fn+P+Z8P3/luz9/3XM/f9sxP3/aL/9/2+//P91vfz/Vqf8/1Wo+/9lw/v/Vqz7/2zW+/9o0Pv/TZ77/2DC+/9kyvr/Wqr3/z195/88e+v/PoD6/z1++v8/gPr/Pn3z/2d24f+Wjvn/nJP/Wt3MRA/QxEX1hoZI/4aiov+y3+f/ksLr/3u66v9zxfb/dc39/4zQ/f9xwv3/hcf8/4bE/P9xtvz/VqP7/1+l+/9Onfv/UKD7/0ya+/9IlPv/RY36/z6A7/9bkvH/Qob6/0CE+v8+gfr/P4H6/z5+8v92kOf/t7L5/5yV8PV3d90PAAAAAHV7n52BneL/k77q/7vy/P+l8v3/nvD9/4vZ9P9/z/H/ouL4/47Y/f+Cxfz/hsT8/3y7/P9Ypfv/bq/7/0+e+/9NnPv/TJn7/0mW+/9IlPv/SJL5/0iU+/9Ik/v/RpD6/0GH9v9OhOb/t8nu////////////5eL/nQAAAAAAAAAA8vL/JsTD/fqInOn/j7no/5rG7P++8vz/r/P9/6Dw/f+c7vz/fcjy/2mw9P+Fw/z/c7X1/1Om+v9Tpvv/UaT7/1Ci+/9PoPv/Tp77/06e+/9MmfX/SZPv/0aN6/8+fd7/haLg//n6/f///////////+Pi//rDvP8mAAAAAAAAAAAAAAAAqbD2i6LF7f/Z+v//oOj6/4XA6/+LwOv/hsHr/4DE7P93tOf/bcb8/2m4/P9ytO7/V6r7/2XH+/9t2Pv/Z8z7/1as+/9SpPr/VKf3/1So+/9kw/v/dN37/23Q+/9ZrvP/bJ3l/+nu+f//////////iwAAAAAAAAAAAAAAAAAAAAA5VcYJ2fn/1NL6//+r9v//rPb//6v2//+p9v//pvb//4a/6v+V7vz/cdD8/3Oy6/9rvvv/eOn7/3bo+/926Pv/dOT7/1mx+/9TpfL/T5nk/2fF+P9+6Pv/f+r7/37p+/902fv/aaXm//f4/dT///8JAAAAAAAAAAAAAAAAAAAAAAAAAADc+P8kyfr/66v2//+s9v//q/b//6j2//+l9v//er3q/6ft+/+A5vz/YKPp/5bY+/956fv/d+n7/3bo+/946fv/ctz7/1aq+/9fr+j/dMbu/2e46f9ov+v/eNr1/3/p+v974vjrXIDVJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACt9f8yq/b/66v2//+q9v//qPb//6X2//+Z6/v/h77q/4rs/P9yrun/dqzo/5bu/P936fv/d+n7/3np+/976fv/Ybz7/1mo6v+U8f7/mPT//5Ls/P9+zvH/ZKfj61eK1jIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACq+P8kq/f/1Kr2//+o9v//pPb//6D1//95w+z/ot/1/3Cp6f9RlvX/fbbp/5Dt+/946fv/een7/3zq+/9v0Pv/Wajr/5Pu/P+b9f//nPX//5z1/9Sc8f8kAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACq//8Jqfb/i6f2//qk9v//oPX//4vh//9amen/UZLu/1Wc//9Okff/aKDm/5ro+f9/6vv/fer7/3bc+/9cqen/mvX//531//qg9v+Lqv//CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAqPj/JqT3/52f9v/1fc///2Gt//9Zov//U5f//1CU//9wx+3/WmVL/4Sytv+V7vz/fOL4/4C15fWm9f+dofj/JgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJnu/w9xwf9aYa3/m1mh/8tRlv/pZrj//WKPf/3f0UnpraM6y3aWlJuTzNVaRGZ3DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKAAAADAAAABgAAAAAQAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//gALSw0sReHAlIlRNG0yOimeDyMWztNfVxdTj4M/uta+E/oqHDf6hoA/upaQO1KemELSnpRCDq6sNTLy8DyKlpQ8RgIAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//0AE5dVJMeHUTHbf0UmxtKk85qOZNv+fljT/mZA0/5SMP/+Ri1T/XVor/8jHFf/FwxT/s7AS/6ShFP+npBn/qKUQ/7W0EebCwRGxs7MRdnhyCjG/v4AEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAN/XSCDi1Uqe49RL4+LUSvrj1Uv/49VL/+PVS//j1Uv/49VL/+LUS//WyEb/SkcS/8nIFf/QzxX/yMcU/5OPMP/j4tD/1NK1/6mla/+OiRr/nJcO+pKMU+Ps7NKdv7ePIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAHm2U0U4tNLc+LUSvDi1Ev/281I/9LFRf/Lv0P/xblF/8G2R/++s0j/vLFJ/72ySP/BtUb/oJc3/0E/Dv+RkA//vr0T/6CcLf/r6uP///////n59v+vq4r/sa6H/+jn0P/Fwp7/iIUe8JmXDXOMjA0U//8AAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPTTEDj1Uu31slG+qidOf+clEr/nZdg/5iUcP9vbnX/OTp7/xsfhv8WG5T/ExmV/xQZkf8dIYj/LjR7/z5AcP9HSGH/UVI7/2VjLv/Kyc///Pz+///////n5tz/uLWX/7i0lP+SjnD/mZUe/7i2EfqioA+3fX0MPwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD/AAAB4tVLYuHTS+ijmjf+cm5R/8LBt//j4uD/6+vr//Ly8//s7Pb/3d73/56h6v89Q9f/HCTf/x0l5P8cJOD/HifZ/2Fo4P+jqfT/mqDn/32Cy/+bndP/0tLu/+Xl9f/7+/3/+Pj1//Dv6v/e3e7/mpm8/4uGIf+7uRL+ioY56Ojow2IAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANvbSQfk1kpx4NJK9JqRPP+OjYb/9vb2///////////////////////////////////////z8/z/lJfi/zE41v8dJd3/GSHX/0xR6v+WnP//qbD//5ui+f+go+r/+/z+///////////////////////8/P//s7P//3x3dP+JhD//ycaa/62ocfRdVhdxSW1tBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wAAAeTWSnHj1UrtoZg1/22Egf/N8PX/2Pn+/+H7/v/u/P7//f///////////////////////////////////9PU8/9hZtz/HSTU/z1C5P9nbP//mJ7//6Kp/P+Sl+r/8PD7///////////////////////x8f//ra3//4mGof+5to//q6dx/31wGf9iYTrteqnJcQD//wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4tVLYuPVS/Tj1Uv/TFAs/6Ho8/+n8/7/qPP+/6vz/v+v8/7/uvX+/+D6/v/8///////////////////////////////t7fr/am7Z/ysy1v9aXv//Zmv//6Kp/v+Kj+n/6er5//////////////////v7///Nzf//oKD//5ST7v+HhLD/f3yg/3ZpEf9zc0f/grfh9GvY+mIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AAHj00xA5NVL6NLFRv+Bfjr/NU9j/6Hv/v+m8/7/pvP+/6bz/v+l8v7/pPL+/6Py/v+19P7/5Pv///n+////////////////////////+/v+/2lu3P9OU/P/V1v//3p//f+Ijen/6ur5///////////////////////+/v//29v8/6Gh8/+Vlfj/kpL6/4B8mP9eZ1j/ca7p/1av+uhp2/s/AP//AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAObZTRTj1Uu3zcBD/m5uQP+JrbL/W5TZ/3/R+f+f7f7/pvP+/6by/v+l8v7/pPL+/6Ly/v+g8f7/ofH+/7/1/v/q/P7//v///////////////////+jp+f9pbeL/Ulb5/1lc+v+Giuf/8vL7//////////////////////////////////f3/f/T0/H/ra3q/4aG2/9adK7/Upvx/0yd+v5Zt/m3Wb/yFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOLTS3PYy0f6V1Qq/6bGy/+n7fz/fcTv/1ie5v+J3f7/o/D+/6by/v+l8v7/pPL+/6Ly/v+g8f7/nfD9/5rw/f+m8f3/4/v+//////////////////7+///P0PL/R0zf/09T8/+doOf//v7/////////////////////////////////////////////+Pj9/9HR9v9vguD/QHvh/0mW+P9Mnvr6Tp34cwAAAAAAAAAAAAAAAAAAAAAAAAAA39dIIOHTSvCOhzX/k6yq/7n1/v+h8v7/i9/+/1yb4P9twPb/leX+/6Xy/v+k8v7/n+/+/4zg/v+M4f7/nO/9/5nw/f+V7v3/le/9/9z5/v/8////+PP0/+TR1P/Koaf/hVaD/2lHkv/Yytn/+vf3/////////////////////////////f3///P1/f/z9f3//f3///b2//+ys///fIrv/0Vz2v9Fi/D/SZf68EiP/yAAAAAAAAAAAAAAAAD//0AE4tVKntDDRf93f17/uuXs/6Lx/v+h8v7/juH+/3/M9f9epef/eM78/57t/v+Y6f7/gNf+/3XO/v9/1v7/me39/5nw/f+V7v3/kO79/5Tu/P/D3OT/toKM/72Ejf/ftLr/5bzA/9iorv/FjZX/wpKa/+jY2//////////////////t8P3/mq3y/2iE7P9ohOz/lKfx/9fZ/f+np///lZX//4iO+P9YeuT/QYLr/0aR+p1AgP8EAAAAAAAAAADl1Ukx49RL47mvQ/9+lZX/s/L9/5/x/v+h8f7/n+/+/3fO/f9nq+f/aLz3/4HX/v980/7/dc7+/3XN/v93z/7/luv9/5jw/f+U7v3/j+79/4rk8/+Lf47/ql1p/7Jlcv/Ikpn/89PW//bV2P/00dT/573B/7Z5g//fyMz///////v8/v+QpfH/IUrj/xlE4v8ZROL/HETj/0td7P+Ulf//jo7//4yM//+JjPv/U3Tf/z1+7ONEjfoxAAAAAP//gALh1Ex24tRK+o6KPv+bu7//pvL9/57x/v+g8f7/ovL+/3/V/v9vvfP/V5/o/2zG/v9wyf7/csv+/3LK/f9yyv7/jOP9/5jw/f+U7v3/j+38/4vH1v+9gY3/6aOu/+igqv+9bnr/1aWr//bU1//31dj/99XY/+7Hy/+8hI3/7+Tm/+3w/f9Wdun/GUTi/xlE4v8ZROL/GUTi/yJA5f92evL/dH3s/2B26P9jeev/YHno/zVs2fpBhvl2AID/AuHSSxHk1Uux49VL/3h3PP+oztP/o/H9/5zw/v+b7f7/ofH+/5Hk/v9vx/3/To3e/2O+/f9mv/z/WqXs/1uo7f9ux/7/e9P9/5fv/f+T7v3/ju38/5CMm//bmKP/6J+q//e1v//poq3/qlxo//TQ1P/209f/9tTX//bU1//brLH/w5ad/+/y/f9dfOr/GUTi/xhC4v8VO+L/FDji/yA55v97fvv/gIP8/0ps3f82b+f/OXbu/z199f8/gvuxPHjwEejaSyLi1Uvm49VL/358Pf+jytD/ofH9/5zx/v+S5v7/nO7+/5vs/v9vyf7/Wp/n/1Om8v9Omuj/dbvr/0iK4P9pwv3/bMT9/5Ps/f+S7v3/ju38/5tjcf/noKv/5pmk//Svuv/zrLf/sFdl/+Cyt//20dX/9tLW//bT1v/00dT/rGhy//Tv8f+arvL/IErj/xU64v8RLuL/Dyri/0JS7v+Ghv//goL//3B79P85bub/O3r6/z19+v8+gPnmPID/IuHTSkzj1Uv/49VL/52XQf+PsbT/ovH9/5zw/f+W6v7/iN3+/5vt/v950f7/X7Dz/0KH4P9mq+b/mur7/0SE3f9ivP3/ZL39/4Da/f+R7v3/jOj3/6pea//cgI3/44qX/+6msP/01Nj/8uLl//Xq6//66On/9tPX//TLzv/1z9L/y5Oa/9a6vv/3+P7/hpvw/ydC5v8kPOb/RVTu/4CG+f9pfuv/cX7y/3N69v9Gb+b/OXb3/zt5+v89ffr/PID4TOLVS4Xj1Uv/49VL/6SeQP90kJ7/p/D8/5vw/f+d8P7/hdz+/37U/v9yy/7/YLn7/z1z0f+K1PP/nvH+/06N3f9asvv/X7b9/2zE/f+O6/3/jOf3/6hbaP/IXmz/vkVU/8hib//78/T/////////////////9d/i/92Nl//imqL/0o2V/8Wco///////1NT//5ye/f+Pkvz/j4///2eA5/+Cvur/dLrp/2SN4/9BbN//OXT2/zp4+v88fPr/P4D5hePVS7Xj1Uv/2cxI/01XTf9/qtj/rOb4/5rw/f+d8P3/len+/2/I/v9rxP7/ZL7+/02G2P+d7v3/nvH+/2et5/9PoPP/WbD9/1+2/f+A3P3/jO38/5VWZP+1SVX/picz/6wwPP/OhIz/9Obn///////9+vr/5a+1/9Bpdv/Ra3f/w2Fu/8SZof/v7///srL//56e//+UlP//g4f6/2SW3v+e7fv/eun6/2i69v9XkOH/OnPw/zp3+v88e/r/P3/5teTVS9fj1Uv/hHws/4yttP+cyu7/lcLr/6Lw/f+a7v3/kOX+/3HJ/v9txv7/Zb37/12c3/+e8f7/nPD+/4HP9P9Jken/Vaz9/1et/f9qw/z/iOr8/4p/jv+pQkz/nCEr/6AkLv+mKjX/mjNB/8hgav/NZG7/zF9q/81ha//NY23/rklW/6aNx/+lpf//nJz//5SU//+MjP//XXjk/5ra9P+J6/v/cef6/2PM+v9PmfX/PXrb/zt2+P88e/r/P3761+PVS/Lf0kr/TU4s/8Hv9v/D8vz/hLHl/4/H7v+N3/3/etH+/3LK/v9vyP7/acH8/16e4P+e8f7/nPD9/4LV+P9VnOf/Uqb6/1So/f9YrPz/dtP8/3yw0P+TO0n/mSYs/5wpLv+jMjn/nDQ//8lYXv/JWmD/ylxh/8tdYv/FWWD/lEVk/5qW9/+Wlv//kpL//42N//99hPf/bqDl/6Dw/P915/r/cef6/2jW+v9Chfr/UaXr/zZu5f88evr/Pn368uPVS//SxUb/V2JQ/8H1/f+08/3/w/D8/4Ow5f+FxvD/etH+/3PL/v9xyv7/bsb+/1eX3/+c8P7/m/D9/4rh/P9jquf/UJ/1/1Km/f9RpPz/Vaj8/1af8v9xUnz/lzEy/583Nf+ZMzn/t01Q/8tdXf/MX17/yGBh/7tdaP+bRVn/g2m4/4aL9f+LjP7/iYr+/3J/8P9Obtv/ToXW/1qW3P9VpOH/bd73/2fU+v8/f/r/Uab5/zt42v88evn/Pn36/+PVS//RxEX/WGNS/8H1/f+d7/z/rPH9/7/v+/+AsuX/gs3y/3rQ/f9zy/7/cMf+/12i5f+R4/j/mvD9/5Pp/f9wwPP/S5Dl/1Gl/f9Pofz/T5/8/02c/P9ShNv/ez9b/5U5PP+WQlH/oGZ//31xpP9kfMH/YJHY/22j4P91reP/dKzj/2GW2/9JedL/VYva/3e35/+R2/T/lez7/4Hh9/9dtef/bd73/1q4+v8+ffr/Ro76/0aR4P87d/P/PXr3/+PVS/Lf0Un/TU8t/7/v9v+m8f3/lO79/6Hw/f+r6vr/iMHr/3m/7P95zPj/csr9/2q68v99x+z/me/9/5Xt/f960vz/Vpvj/0qX8v9On/z/S5r8/0qY/P9IlPv/SnfV/15Vk/99lsj/i8Hq/5/f9f+k7vv/nfD8/5bv/P+M4Pb/eLfn/2605v980vL/hur7/3vp+v9y5/r/cef6/2XP8v9Nnef/Wrn6/0SJ+v8+fvr/Q4b6/0uV3/9IceX/UHTq8uTVS9fj1Uv/g3ss/4qrsP+08/3/lu79/5bu/f+a8P3/nu/8/5De9/93wO3/cb7v/3HG+v9tt+n/kuf4/5fv/f+A2P3/aL35/0eI3/9Mm/n/SZb8/0eS/P9BhO//V43f/6Ha9P+s7fv/le77/4Dq+/966fv/dun7/3Dh+P9Wquf/aczy/3Xm+v9z6Pv/cuj7/3Hn+v9x5/r/atn6/0yd4/9Ag/H/Qof6/0CA+v8+ffr/Roz6/0yH3v+Agvf/iIb71+PVS7Xj1Uv/2cxI/0xUQv+35ez/nvD9/5bu/f+Y8P3/mvD9/5vw/f+R5/3/gdj8/4bb+/96zvf/fMfq/4/n+/+F3v3/Zbv9/1mp8/9Eien/SJX7/0OK9P9gl+P/q+n5/5rv/P996vv/duf7/3Xo+/9z6Pv/c+j7/2XO9f9dvfL/cuf7/3Lo+/9y6Pv/cuj7/3Hm+v9q2vr/Wbbv/zl14f9Ch/r/QIL6/z9/+v8+ffr/SI/4/0xv3P+OiP//kIr/teLVS4Xj1Uv/49VL/6WdPf96j4f/tOz1/5jv/f+Y8P3/mvD9/5vw/f+b8P3/j+X9/3PL/f91zP3/d8z4/3jM9v9sw/3/Y7n9/1uv+/9LlO//Qonu/0iG4P+I1PX/h+z7/3rp+/915fv/cuH7/3To+/9z6Pv/cOL7/2DF+v9w4/v/cuj7/3Lo+/9y6Pv/cuj7/2jV+v9YtfH/P4Lg/0CD9/9Bg/r/P4D6/z59+v8+fPr/OnTo/2166/+Riv//kor/heHTSkzj1Uv/49VL/97QSf+Jgzj/f5iX/7Tz/f+Y8P3/mvD9/5rw/f+a8P3/mvD9/3/W/f9uxv3/a8P9/2nB/f9nvv3/Y7n9/16z/P9WqPv/SpX0/1ak8P953vv/fOr7/3jn+/9pz/v/ceD7/3Xo+/9y5Pv/W7n7/2zb+/9y6Pv/cuj7/3Lo+/9w5Pv/Xbz7/1Gn9f9BhuH/Pn/z/0CC+v8/gPr/Pn76/z5++v8+fPf/Q23c/4+L/f+Ujf//lI3/TOjaSyLj1Uvm49VL/+PVS//g0kr/d3Ao/2J3dv+b3ej/me/8/5rw/f+a8P3/mO79/33U/f9uxv3/a8P9/2nA/f9mvv3/a7z8/227/P9er/z/UqL8/1Ki/P9u0Pv/cdj7/1+7+/9ct/v/cuL7/3Hi+/9fv/v/TZz7/2TJ+/9v4Pv/bd37/2fM+v9Lmff/RY7t/zt53f87fPP/PoD6/z5/+v8+f/r/P4D6/0CA+f89c+X/d4Dt/5eP/P+Zkf7mnpb/IuHSSxHk1Uux49VL/9rNSP+flzn/h4lR/2R0a/93nrn/e73q/5Hg+P+L4v3/f9b9/3HI/f9zyP3/fcn9/2zB/f9tv/3/hcf8/4fF/P96vfz/Wqn8/1Cf/P9Tn/v/T577/1Cg+/9Vqfv/YsX7/1q0+/9Nnfv/SZX7/0mW+/9Nnfb/RIzt/1SK7f9Mgun/Onjq/z+A+P8+gPr/Pn/6/z1++v8+f/r/QYL6/z966/9keeH/jIbr/46G6/+Qh+6xlofwEf//gALf0kl2sKY6+mJjOP+MqaX/td3j/7vs8/+37Pn/rdv0/3yu5P9mqOT/e832/3zU/f+Bz/3/j9H9/33I/f90wv3/icj8/4fF/P+Ewfz/bLL8/1Sj+/9srfv/W6P7/02c+/9Onfv/Tp37/0ya+/9Jlvv/R5L7/0aP+/9Eivn/QYb3/1CO9/9Vk/n/Qof7/0GG+/8/g/r/P4L6/z+C+v9Ag/n/OXbl/3mU5P/Dwvv/zMn9/6+q+/qel/Z2gID/AgAAAAA5OSoxUV+H416F0/+Wwez/uOX4/7zz/P+l8v3/nPD9/6Dx/f+b5vn/eL/r/2626P+Fye7/n932/57j/f9/y/z/h8f8/4bF/P+Ewfz/d7j8/1Wk+/9vr/v/Z6r7/06d+/9Onfv/TJv7/0ya+/9Klvv/SJT7/0eS+/9Hkfv/R5H7/0eR+/9Hkfv/R5D7/0WO+/9Di/r/QYb4/0GC8v9ShOL/sMLr/////////////////+/u/+Osp/8xAAAAAAAAAAD///8E09P8nbi6+P+Wo+3/cJPe/4q35/+z4fb/u/T9/6vz/f+d8P3/mPD9/5fv/f+b7/3/q/D9/57l/f91xvv/gL/4/4bE/P+Ewfz/dLX4/1Ok+v9dqfv/XKj7/1Ci+/9QoPv/Tp77/02d+/9Mm/v/TJr7/0uZ+/9Kl/n/R5Dy/0WN8P9GjfD/Ro3w/0OI7v9Ihej/aJbo/5m06f/b4/X//f7/////////////9/b//+Df/56/v/8EAAAAAAAAAAAAAAAA9/f/IM/P/vCusvn/b5He/7fe9f+BruT/hrLm/8Hu+v/F9v7/ufT9/6ny/f+f8P3/lur8/3fB7/9Wn+n/cLf3/4bE/P+Dwfz/Za3t/1Sn+/9Up/v/VKb7/1Kl+/9RpPv/UKP7/1Ch+/9PoPv/T5/7/0+f+/9Qofv/T5/4/0+f9/9NmvP/SJLt/0KF4/9Rgtn/pbrn//n7/f/////////////////19P//zMn/8L+3/yAAAAAAAAAAAAAAAAAAAAAAAAAAALy8+3OIner6utz0/9r7///A9v7/kNTy/2yf3/91puH/hbXn/3+x5f9uo+D/Z6Xh/2Wh4P9vvfT/Zbz8/266/P9nrPX/gsLw/1eq+/9Yrfv/YL37/2fM+/9lyfv/W7b7/1Oo+/9RpPv/UaP7/1Ol+f9Tpvv/VKf7/1mw+/9s0fv/b9T7/2bF+/9asfn/SpTq/2OQ3v/T3vT//f3+///////////6//3/cwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHOM2RScvO231PT9/tr7///A+P//qvX//6r1/v+p7vz/oOT4/57n+v+l8v3/pvb//3Gv5f+Y3/j/g+P8/2zI/P9Qm+//ltT0/12v+/9nyfv/d+f7/3fp+/926Pv/dOX7/2rS+/9Zsvv/U6b6/1Ki8P9VpvH/Wa76/2C7+/975/v/fur7/33q+/965Pv/cNT6/2C59v9ineb/x9Xx//////7///+3////FAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/wHO8/s/2/v/6Nj7//+59///rPb//6z2//+s9v//q/b//6r2//+o9v//pfb//3q86v+e2vP/je38/3/j/P9WpfD/jcfv/3i//P9w2fv/eOn7/3bo+/926fv/duj7/3fo+/9t1/v/WK37/1Wo+f9NluT/S5Hd/2O88/912/v/f+n7/4Dq+/9/6vv/fun7/3zm+/9v0fj/WZPf/+fs+Oj///9A////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2/z/YtX7//Sz9///rPb//6z2//+s9v//q/b//6n2//+n9v//pfb//47a9P+MwOr/lu78/4Pp/P9ow/j/ZqDi/5zV/P963/v/eOn7/3fp+/936Pv/duj7/3fp+/946fv/aMr7/1aq+/9ZrvL/Y7Hm/2ez5/9apeL/b8rw/3jb9v974fj/fub5/4Dp+/9/6vv/cdP19FuC1WIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP//AdD9/3Gu9v/tq/b//6z2//+r9v//q/b//6n2//+n9v//pPb//5np+/98t+f/p+r5/4Tr/P9/2vz/Vo3b/4zB7v+W5fz/e+n7/3fp+/936fv/d+n7/3jp+/956fv/eeb7/1y0+/9guvr/UZbe/5Tz//+O6Pr/eMjv/2686v9quen/aLjp/2W36P9mt+jteNv2cQD//wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALb//wes+P9xq/b/9Kv2//+r9v//qvb//6n2//+n9v//pPb//6D0//93vuv/ntPx/5bu/P+W6/z/VYze/1SO4v+e2fT/ke77/3fp+/936fv/eOn7/3jp+/966fv/fOr7/23P+/9ft/v/T5bf/5Ht/P+X9P//mPX//5j0//+U7fz/j+b6/4bZ9fRhmd1xbbbbBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8BrPf/Yqv2/+ir9v/+qvb//6j2//+m9v//pPb//6H1//+W6/v/YZze/63n+P+l5/j/U4zi/1ac+f9dl+P/o9/2/4zt+/956fv/eOn7/3np+/966fv/fOr7/3jg+/9hufz/Upvh/47n+v+Z9f//mvX//5v1//+c9f/+m/X/6Jz1/2IA//8BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKr3/z+q9/+3qfb/+qj2//+m9v//o/b//6H1//+d9f//fc71/2ad4v+DuOf/VZbw/1if//9PkvX/WZPl/47L7v+W7fv/fer7/3np+/976fv/fer7/3vk+/9oxfz/TpLe/5bx/f+b9f//nPX//531//qd9f+3m/P/QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///wGm8v8UqfT/c6j2//Cm9v//o/b//6D1//+d9f//e87//1uj9f9Ni+X/Vp36/1ac//9TmP//T5P7/02J6P96s+f/p+77/4fr+/976fv/fur7/3zm+/9uzPr/VZje/5r1//+c9f//nvX/8J30/3Om8v8U////AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJ/3/yCm9/+do/b/45/1//qb8v//cL7//2Ku//9eqP//WKH//1SZ//9Rlf//UJP//2a4/P9Tj6X/V21n/53R1/+W6vb/hOv7/37n+/9mu+3/k8Tt+qP2/+Od9f+en/f/IAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAC///8EofX/MaD0/3aT6f+xbLn/5mKu//9dp///WJ///1OY//9Qk///Xan//3rX5v9yhVb/tKg7/3p7QP94l4//ouLr/5Xo9eZfocexsdrudsb6/zG///8EAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID//wKH0v8Rabz/ImGr/0xdp/+DVqD/tFKY/9RRl//ue9z//mGdmf6nnzru49VL1NnMSLSKhjqDeZeXTKzo+CJah5YRgICAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==","base64");function f(){return new a.NextResponse(s,{headers:{"Content-Type":"image/x-icon","Cache-Control":"public, max-age=0, must-revalidate"}})}let v="force-static",u=new i.AppRouteRouteModule({definition:{kind:n.x.APP_ROUTE,page:"/favicon.ico/route",pathname:"/favicon.ico",filename:"favicon",bundlePath:"app/favicon.ico/route"},resolvedPagePath:"next-metadata-route-loader?page=%2Ffavicon.ico%2Froute&isDynamic=0!X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\favicon.ico?__next_metadata_route__",nextConfigOutput:"",userland:r}),{requestAsyncStorage:l,staticGenerationAsyncStorage:d,serverHooks:c,headerHooks:b,staticGenerationBailout:P}=u,p="/favicon.ico/route";function h(){return(0,o.patchFetch)({serverHooks:c,staticGenerationAsyncStorage:d})}},2491:A=>{"use strict";var e=Object.defineProperty,t=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,n={};function o(A){var e;let t=["path"in A&&A.path&&`Path=${A.path}`,"expires"in A&&(A.expires||0===A.expires)&&`Expires=${("number"==typeof A.expires?new Date(A.expires):A.expires).toUTCString()}`,"maxAge"in A&&"number"==typeof A.maxAge&&`Max-Age=${A.maxAge}`,"domain"in A&&A.domain&&`Domain=${A.domain}`,"secure"in A&&A.secure&&"Secure","httpOnly"in A&&A.httpOnly&&"HttpOnly","sameSite"in A&&A.sameSite&&`SameSite=${A.sameSite}`,"priority"in A&&A.priority&&`Priority=${A.priority}`].filter(Boolean);return`${A.name}=${encodeURIComponent(null!=(e=A.value)?e:"")}; ${t.join("; ")}`}function a(A){let e=new Map;for(let t of A.split(/; */)){if(!t)continue;let A=t.indexOf("=");if(-1===A){e.set(t,"true");continue}let[r,i]=[t.slice(0,A),t.slice(A+1)];try{e.set(r,decodeURIComponent(null!=i?i:"true"))}catch{}}return e}function s(A){var e,t;if(!A)return;let[[r,i],...n]=a(A),{domain:o,expires:s,httponly:u,maxage:l,path:d,samesite:c,secure:b,priority:P}=Object.fromEntries(n.map(([A,e])=>[A.toLowerCase(),e]));return function(A){let e={};for(let t in A)A[t]&&(e[t]=A[t]);return e}({name:r,value:decodeURIComponent(i),domain:o,...s&&{expires:new Date(s)},...u&&{httpOnly:!0},..."string"==typeof l&&{maxAge:Number(l)},path:d,...c&&{sameSite:f.includes(e=(e=c).toLowerCase())?e:void 0},...b&&{secure:!0},...P&&{priority:v.includes(t=(t=P).toLowerCase())?t:void 0}})}((A,t)=>{for(var r in t)e(A,r,{get:t[r],enumerable:!0})})(n,{RequestCookies:()=>u,ResponseCookies:()=>l,parseCookie:()=>a,parseSetCookie:()=>s,stringifyCookie:()=>o}),A.exports=((A,n,o,a)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let o of r(n))i.call(A,o)||void 0===o||e(A,o,{get:()=>n[o],enumerable:!(a=t(n,o))||a.enumerable});return A})(e({},"__esModule",{value:!0}),n);var f=["strict","lax","none"],v=["low","medium","high"],u=class{constructor(A){this._parsed=new Map,this._headers=A;let e=A.get("cookie");if(e)for(let[A,t]of a(e))this._parsed.set(A,{name:A,value:t})}[Symbol.iterator](){return this._parsed[Symbol.iterator]()}get size(){return this._parsed.size}get(...A){let e="string"==typeof A[0]?A[0]:A[0].name;return this._parsed.get(e)}getAll(...A){var e;let t=Array.from(this._parsed);if(!A.length)return t.map(([A,e])=>e);let r="string"==typeof A[0]?A[0]:null==(e=A[0])?void 0:e.name;return t.filter(([A])=>A===r).map(([A,e])=>e)}has(A){return this._parsed.has(A)}set(...A){let[e,t]=1===A.length?[A[0].name,A[0].value]:A,r=this._parsed;return r.set(e,{name:e,value:t}),this._headers.set("cookie",Array.from(r).map(([A,e])=>o(e)).join("; ")),this}delete(A){let e=this._parsed,t=Array.isArray(A)?A.map(A=>e.delete(A)):e.delete(A);return this._headers.set("cookie",Array.from(e).map(([A,e])=>o(e)).join("; ")),t}clear(){return this.delete(Array.from(this._parsed.keys())),this}[Symbol.for("edge-runtime.inspect.custom")](){return`RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(A=>`${A.name}=${encodeURIComponent(A.value)}`).join("; ")}},l=class{constructor(A){var e,t,r;this._parsed=new Map,this._headers=A;let i=null!=(r=null!=(t=null==(e=A.getSetCookie)?void 0:e.call(A))?t:A.get("set-cookie"))?r:[];for(let A of Array.isArray(i)?i:function(A){if(!A)return[];var e,t,r,i,n,o=[],a=0;function s(){for(;a=A.length)&&o.push(A.substring(e,A.length))}return o}(i)){let e=s(A);e&&this._parsed.set(e.name,e)}}get(...A){let e="string"==typeof A[0]?A[0]:A[0].name;return this._parsed.get(e)}getAll(...A){var e;let t=Array.from(this._parsed.values());if(!A.length)return t;let r="string"==typeof A[0]?A[0]:null==(e=A[0])?void 0:e.name;return t.filter(A=>A.name===r)}has(A){return this._parsed.has(A)}set(...A){let[e,t,r]=1===A.length?[A[0].name,A[0].value,A[0]]:A,i=this._parsed;return i.set(e,function(A={name:"",value:""}){return"number"==typeof A.expires&&(A.expires=new Date(A.expires)),A.maxAge&&(A.expires=new Date(Date.now()+1e3*A.maxAge)),(null===A.path||void 0===A.path)&&(A.path="/"),A}({name:e,value:t,...r})),function(A,e){for(let[,t]of(e.delete("set-cookie"),A)){let A=o(t);e.append("set-cookie",A)}}(i,this._headers),this}delete(...A){let[e,t,r]="string"==typeof A[0]?[A[0]]:[A[0].name,A[0].path,A[0].domain];return this.set({name:e,path:t,domain:r,value:"",expires:new Date(0)})}[Symbol.for("edge-runtime.inspect.custom")](){return`ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(o).join("; ")}}},3825:(A,e,t)=>{var r;(()=>{var i={226:function(i,n){!function(o,a){"use strict";var s="function",f="undefined",v="object",u="string",l="major",d="model",c="name",b="type",P="vendor",p="version",h="architecture",m="console",w="mobile",g="tablet",x="smarttv",y="wearable",j="embedded",z="Amazon",L="Apple",O="ASUS",k="BlackBerry",S="Browser",T="Chrome",q="Firefox",D="Google",U="Huawei",H="Microsoft",R="Motorola",X="Opera",C="Samsung",V="Sharp",N="Sony",I="Xiaomi",W="Zebra",M="Facebook",E="Chromium OS",_="Mac OS",Z=function(A,e){var t={};for(var r in A)e[r]&&e[r].length%2==0?t[r]=e[r].concat(A[r]):t[r]=A[r];return t},K=function(A){for(var e={},t=0;t0?2===n.length?typeof n[1]==s?this[n[0]]=n[1].call(this,f):this[n[0]]=n[1]:3===n.length?typeof n[1]!==s||n[1].exec&&n[1].test?this[n[0]]=f?f.replace(n[1],n[2]):a:this[n[0]]=f?n[1].call(this,f,n[2]):a:4===n.length&&(this[n[0]]=f?n[3].call(this,f.replace(n[1],n[2])):a):this[n]=f||a;u+=2}},B=function(A,e){for(var t in e)if(typeof e[t]===v&&e[t].length>0){for(var r=0;r2&&(A[d]="iPad",A[b]=g),A},this.getEngine=function(){var A={};return A[c]=a,A[p]=a,Y.call(A,r,n.engine),A},this.getOS=function(){var A={};return A[c]=a,A[p]=a,Y.call(A,r,n.os),m&&!A[c]&&i&&"Unknown"!=i.platform&&(A[c]=i.platform.replace(/chrome os/i,E).replace(/macos/i,_)),A},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return r},this.setUA=function(A){return r=typeof A===u&&A.length>350?Q(A,350):A,this},this.setUA(r),this};AA.VERSION="1.0.35",AA.BROWSER=K([c,p,l]),AA.CPU=K([h]),AA.DEVICE=K([d,P,b,m,w,x,g,y,j]),AA.ENGINE=AA.OS=K([c,p]),typeof n!==f?(i.exports&&(n=i.exports=AA),n.UAParser=AA):t.amdO?void 0!==(r=(function(){return AA}).call(e,t,e,A))&&(A.exports=r):typeof o!==f&&(o.UAParser=AA);var Ae=typeof o!==f&&(o.jQuery||o.Zepto);if(Ae&&!Ae.ua){var At=new AA;Ae.ua=At.getResult(),Ae.ua.get=function(){return At.getUA()},Ae.ua.set=function(A){At.setUA(A);var e=At.getResult();for(var t in e)Ae.ua[t]=e[t]}}}(this)}},n={};function o(A){var e=n[A];if(void 0!==e)return e.exports;var t=n[A]={exports:{}},r=!0;try{i[A].call(t.exports,t,t.exports,o),r=!1}finally{r&&delete n[A]}return t.exports}o.ab=__dirname+"/";var a=o(226);A.exports=a})()},5419:(A,e,t)=>{"use strict";A.exports=t(517)},3457:(A,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(A,e){for(var t in e)Object.defineProperty(A,t,{enumerable:!0,get:e[t]})}(e,{PageSignatureError:function(){return t},RemovedPageError:function(){return r},RemovedUAError:function(){return i}});class t extends Error{constructor({page:A}){super(`The middleware "${A}" accepts an async API directly with the form: + + export function middleware(request, event) { + return NextResponse.redirect('/new-location') + } + + Read more: https://nextjs.org/docs/messages/middleware-new-signature + `)}}class r extends Error{constructor(){super(`The request.page has been deprecated in favour of \`URLPattern\`. + Read more: https://nextjs.org/docs/messages/middleware-request-page + `)}}class i extends Error{constructor(){super(`The request.ua has been removed in favour of \`userAgent\` function. + Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent + `)}}},2778:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"NextURL",{enumerable:!0,get:function(){return v}});let r=t(7567),i=t(1219),n=t(1513),o=t(6993),a=/(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)/;function s(A,e){return new URL(String(A).replace(a,"localhost"),e&&String(e).replace(a,"localhost"))}let f=Symbol("NextURLInternal");class v{constructor(A,e,t){let r,i;"object"==typeof e&&"pathname"in e||"string"==typeof e?(r=e,i=t||{}):i=t||e||{},this[f]={url:s(A,r??i.base),options:i,basePath:""},this.analyze()}analyze(){var A,e,t,i,a;let s=(0,o.getNextPathnameInfo)(this[f].url.pathname,{nextConfig:this[f].options.nextConfig,parseData:!0,i18nProvider:this[f].options.i18nProvider}),v=(0,n.getHostname)(this[f].url,this[f].options.headers);this[f].domainLocale=this[f].options.i18nProvider?this[f].options.i18nProvider.detectDomainLocale(v):(0,r.detectDomainLocale)(null==(e=this[f].options.nextConfig)?void 0:null==(A=e.i18n)?void 0:A.domains,v);let u=(null==(t=this[f].domainLocale)?void 0:t.defaultLocale)||(null==(a=this[f].options.nextConfig)?void 0:null==(i=a.i18n)?void 0:i.defaultLocale);this[f].url.pathname=s.pathname,this[f].defaultLocale=u,this[f].basePath=s.basePath??"",this[f].buildId=s.buildId,this[f].locale=s.locale??u,this[f].trailingSlash=s.trailingSlash}formatPathname(){return(0,i.formatNextPathnameInfo)({basePath:this[f].basePath,buildId:this[f].buildId,defaultLocale:this[f].options.forceLocale?void 0:this[f].defaultLocale,locale:this[f].locale,pathname:this[f].url.pathname,trailingSlash:this[f].trailingSlash})}formatSearch(){return this[f].url.search}get buildId(){return this[f].buildId}set buildId(A){this[f].buildId=A}get locale(){return this[f].locale??""}set locale(A){var e,t;if(!this[f].locale||!(null==(t=this[f].options.nextConfig)?void 0:null==(e=t.i18n)?void 0:e.locales.includes(A)))throw TypeError(`The NextURL configuration includes no locale "${A}"`);this[f].locale=A}get defaultLocale(){return this[f].defaultLocale}get domainLocale(){return this[f].domainLocale}get searchParams(){return this[f].url.searchParams}get host(){return this[f].url.host}set host(A){this[f].url.host=A}get hostname(){return this[f].url.hostname}set hostname(A){this[f].url.hostname=A}get port(){return this[f].url.port}set port(A){this[f].url.port=A}get protocol(){return this[f].url.protocol}set protocol(A){this[f].url.protocol=A}get href(){let A=this.formatPathname(),e=this.formatSearch();return`${this.protocol}//${this.host}${A}${e}${this.hash}`}set href(A){this[f].url=s(A),this.analyze()}get origin(){return this[f].url.origin}get pathname(){return this[f].url.pathname}set pathname(A){this[f].url.pathname=A}get hash(){return this[f].url.hash}set hash(A){this[f].url.hash=A}get search(){return this[f].url.search}set search(A){this[f].url.search=A}get password(){return this[f].url.password}set password(A){this[f].url.password=A}get username(){return this[f].url.username}set username(A){this[f].url.username=A}get basePath(){return this[f].basePath}set basePath(A){this[f].basePath=A.startsWith("/")?A:`/${A}`}toString(){return this.href}toJSON(){return this.href}[Symbol.for("edge-runtime.inspect.custom")](){return{href:this.href,origin:this.origin,protocol:this.protocol,username:this.username,password:this.password,host:this.host,hostname:this.hostname,port:this.port,pathname:this.pathname,search:this.search,searchParams:this.searchParams,hash:this.hash}}clone(){return new v(String(this),this[f].options)}}},7770:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(A,e){for(var t in e)Object.defineProperty(A,t,{enumerable:!0,get:e[t]})}(e,{RequestCookies:function(){return r.RequestCookies},ResponseCookies:function(){return r.ResponseCookies}});let r=t(2491)},7054:(A,e)=>{"use strict";function t(){throw Error('ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead')}Object.defineProperty(e,"E",{enumerable:!0,get:function(){return t}})},7699:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(A,e){for(var t in e)Object.defineProperty(A,t,{enumerable:!0,get:e[t]})}(e,{INTERNALS:function(){return a},NextRequest:function(){return s}});let r=t(2778),i=t(952),n=t(3457),o=t(7770),a=Symbol("internal request");class s extends Request{constructor(A,e={}){let t="string"!=typeof A&&"url"in A?A.url:String(A);(0,i.validateURL)(t),A instanceof Request?super(A,e):super(t,e);let n=new r.NextURL(t,{headers:(0,i.toNodeOutgoingHttpHeaders)(this.headers),nextConfig:e.nextConfig});this[a]={cookies:new o.RequestCookies(this.headers),geo:e.geo||{},ip:e.ip,nextUrl:n,url:n.toString()}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,geo:this.geo,ip:this.ip,nextUrl:this.nextUrl,url:this.url,bodyUsed:this.bodyUsed,cache:this.cache,credentials:this.credentials,destination:this.destination,headers:Object.fromEntries(this.headers),integrity:this.integrity,keepalive:this.keepalive,method:this.method,mode:this.mode,redirect:this.redirect,referrer:this.referrer,referrerPolicy:this.referrerPolicy,signal:this.signal}}get cookies(){return this[a].cookies}get geo(){return this[a].geo}get ip(){return this[a].ip}get nextUrl(){return this[a].nextUrl}get page(){throw new n.RemovedPageError}get ua(){throw new n.RemovedUAError}get url(){return this[a].url}}},4704:(A,e,t)=>{"use strict";Object.defineProperty(e,"x",{enumerable:!0,get:function(){return f}});let r=t(2778),i=t(952),n=t(7770),o=Symbol("internal response"),a=new Set([301,302,303,307,308]);function s(A,e){var t;if(null==A?void 0:null==(t=A.request)?void 0:t.headers){if(!(A.request.headers instanceof Headers))throw Error("request.headers must be an instance of Headers");let t=[];for(let[r,i]of A.request.headers)e.set("x-middleware-request-"+r,i),t.push(r);e.set("x-middleware-override-headers",t.join(","))}}class f extends Response{constructor(A,e={}){super(A,e),this[o]={cookies:new n.ResponseCookies(this.headers),url:e.url?new r.NextURL(e.url,{headers:(0,i.toNodeOutgoingHttpHeaders)(this.headers),nextConfig:e.nextConfig}):void 0}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,url:this.url,body:this.body,bodyUsed:this.bodyUsed,headers:Object.fromEntries(this.headers),ok:this.ok,redirected:this.redirected,status:this.status,statusText:this.statusText,type:this.type}}get cookies(){return this[o].cookies}static json(A,e){let t=Response.json(A,e);return new f(t.body,t)}static redirect(A,e){let t="number"==typeof e?e:(null==e?void 0:e.status)??307;if(!a.has(t))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');let r="object"==typeof e?e:{},n=new Headers(null==r?void 0:r.headers);return n.set("Location",(0,i.validateURL)(A)),new f(null,{...r,headers:n,status:t})}static rewrite(A,e){let t=new Headers(null==e?void 0:e.headers);return t.set("x-middleware-rewrite",(0,i.validateURL)(A)),s(e,t),new f(null,{...e,headers:t})}static next(A){let e=new Headers(null==A?void 0:A.headers);return e.set("x-middleware-next","1"),s(A,e),new f(null,{...A,headers:e})}}},1172:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),function(A,e){for(var t in e)Object.defineProperty(A,t,{enumerable:!0,get:e[t]})}(e,{isBot:function(){return i},userAgentFromString:function(){return n},userAgent:function(){return o}});let r=function(A){return A&&A.__esModule?A:{default:A}}(t(3825));function i(A){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(A)}function n(A){return{...(0,r.default)(A),isBot:void 0!==A&&i(A)}}function o({headers:A}){return n(A.get("user-agent")||void 0)}},952:(A,e)=>{"use strict";function t(A){let e=new Headers;for(let[t,r]of Object.entries(A))for(let A of Array.isArray(r)?r:[r])void 0!==A&&("number"==typeof A&&(A=A.toString()),e.append(t,A));return e}function r(A){var e,t,r,i,n,o=[],a=0;function s(){for(;a=A.length)&&o.push(A.substring(e,A.length))}return o}function i(A){let e={},t=[];if(A)for(let[i,n]of A.entries())"set-cookie"===i.toLowerCase()?(t.push(...r(n)),e[i]=1===t.length?t[0]:t):e[i]=n;return e}function n(A){try{return String(new URL(String(A)))}catch(e){throw Error(`URL is malformed "${String(A)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,{cause:e})}}Object.defineProperty(e,"__esModule",{value:!0}),function(A,e){for(var t in e)Object.defineProperty(A,t,{enumerable:!0,get:e[t]})}(e,{fromNodeOutgoingHttpHeaders:function(){return t},splitCookiesString:function(){return r},toNodeOutgoingHttpHeaders:function(){return i},validateURL:function(){return n}})},1513:(A,e)=>{"use strict";function t(A,e){let t;if((null==e?void 0:e.host)&&!Array.isArray(e.host))t=e.host.toString().split(":",1)[0];else{if(!A.hostname)return;t=A.hostname}return t.toLowerCase()}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"getHostname",{enumerable:!0,get:function(){return t}})},7567:(A,e)=>{"use strict";function t(A,e,t){if(A)for(let n of(t&&(t=t.toLowerCase()),A)){var r,i;if(e===(null==(r=n.domain)?void 0:r.split(":",1)[0].toLowerCase())||t===n.defaultLocale.toLowerCase()||(null==(i=n.locales)?void 0:i.some(A=>A.toLowerCase()===t)))return n}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"detectDomainLocale",{enumerable:!0,get:function(){return t}})},1111:(A,e)=>{"use strict";function t(A,e){let t;let r=A.split("/");return(e||[]).some(e=>!!r[1]&&r[1].toLowerCase()===e.toLowerCase()&&(t=e,r.splice(1,1),A=r.join("/")||"/",!0)),{pathname:A,detectedLocale:t}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"normalizeLocalePath",{enumerable:!0,get:function(){return t}})},1763:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"addLocale",{enumerable:!0,get:function(){return n}});let r=t(1963),i=t(3312);function n(A,e,t,n){if(!e||e===t)return A;let o=A.toLowerCase();return!n&&((0,i.pathHasPrefix)(o,"/api")||(0,i.pathHasPrefix)(o,"/"+e.toLowerCase()))?A:(0,r.addPathPrefix)(A,"/"+e)}},1963:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"addPathPrefix",{enumerable:!0,get:function(){return i}});let r=t(7711);function i(A,e){if(!A.startsWith("/")||!e)return A;let{pathname:t,query:i,hash:n}=(0,r.parsePath)(A);return""+e+t+i+n}},8929:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"addPathSuffix",{enumerable:!0,get:function(){return i}});let r=t(7711);function i(A,e){if(!A.startsWith("/")||!e)return A;let{pathname:t,query:i,hash:n}=(0,r.parsePath)(A);return""+t+e+i+n}},1219:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"formatNextPathnameInfo",{enumerable:!0,get:function(){return a}});let r=t(6915),i=t(1963),n=t(8929),o=t(1763);function a(A){let e=(0,o.addLocale)(A.pathname,A.locale,A.buildId?void 0:A.defaultLocale,A.ignorePrefix);return(A.buildId||!A.trailingSlash)&&(e=(0,r.removeTrailingSlash)(e)),A.buildId&&(e=(0,n.addPathSuffix)((0,i.addPathPrefix)(e,"/_next/data/"+A.buildId),"/"===A.pathname?"index.json":".json")),e=(0,i.addPathPrefix)(e,A.basePath),!A.buildId&&A.trailingSlash?e.endsWith("/")?e:(0,n.addPathSuffix)(e,"/"):(0,r.removeTrailingSlash)(e)}},6993:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"getNextPathnameInfo",{enumerable:!0,get:function(){return o}});let r=t(1111),i=t(6034),n=t(3312);function o(A,e){var t,o;let{basePath:a,i18n:s,trailingSlash:f}=null!=(t=e.nextConfig)?t:{},v={pathname:A,trailingSlash:"/"!==A?A.endsWith("/"):f};a&&(0,n.pathHasPrefix)(v.pathname,a)&&(v.pathname=(0,i.removePathPrefix)(v.pathname,a),v.basePath=a);let u=v.pathname;if(v.pathname.startsWith("/_next/data/")&&v.pathname.endsWith(".json")){let A=v.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/"),t=A[0];v.buildId=t,u="index"!==A[1]?"/"+A.slice(1).join("/"):"/",!0===e.parseData&&(v.pathname=u)}if(s){let A=e.i18nProvider?e.i18nProvider.analyze(v.pathname):(0,r.normalizeLocalePath)(v.pathname,s.locales);v.locale=A.detectedLocale,v.pathname=null!=(o=A.pathname)?o:v.pathname,!A.detectedLocale&&v.buildId&&(A=e.i18nProvider?e.i18nProvider.analyze(u):(0,r.normalizeLocalePath)(u,s.locales)).detectedLocale&&(v.locale=A.detectedLocale)}return v}},7711:(A,e)=>{"use strict";function t(A){let e=A.indexOf("#"),t=A.indexOf("?"),r=t>-1&&(e<0||t-1?{pathname:A.substring(0,r?t:e),query:r?A.substring(t,e>-1?e:void 0):"",hash:e>-1?A.slice(e):""}:{pathname:A,query:"",hash:""}}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"parsePath",{enumerable:!0,get:function(){return t}})},3312:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"pathHasPrefix",{enumerable:!0,get:function(){return i}});let r=t(7711);function i(A,e){if("string"!=typeof A)return!1;let{pathname:t}=(0,r.parsePath)(A);return t===e||t.startsWith(e+"/")}},6034:(A,e,t)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"removePathPrefix",{enumerable:!0,get:function(){return i}});let r=t(3312);function i(A,e){if(!(0,r.pathHasPrefix)(A,e))return A;let t=A.slice(e.length);return t.startsWith("/")?t:"/"+t}},6915:(A,e)=>{"use strict";function t(A){return A.replace(/\/$/,"")||"/"}Object.defineProperty(e,"__esModule",{value:!0}),Object.defineProperty(e,"removeTrailingSlash",{enumerable:!0,get:function(){return t}})},9647:(A,e,t)=>{let r={NextRequest:t(7699).NextRequest,NextResponse:t(4704).x,ImageResponse:t(7054).E,userAgentFromString:t(1172).userAgentFromString,userAgent:t(1172).userAgent};"undefined"!=typeof URLPattern&&(r.URLPattern=URLPattern),A.exports=r,e.NextRequest=r.NextRequest,e.NextResponse=r.NextResponse,e.ImageResponse=r.ImageResponse,e.userAgentFromString=r.userAgentFromString,e.userAgent=r.userAgent,e.URLPattern=r.URLPattern}};var e=require("../../webpack-runtime.js");e.C(A);var t=A=>e(e.s=A),r=e.X(0,[638],()=>t(8837));module.exports=r})(); \ No newline at end of file diff --git a/.next/server/app/favicon.ico/route.js.nft.json b/.next/server/app/favicon.ico/route.js.nft.json index ce8b1e2..8ff3ef3 100644 --- a/.next/server/app/favicon.ico/route.js.nft.json +++ b/.next/server/app/favicon.ico/route.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/106.js","../../chunks/2.js","../../chunks/201.js","../../chunks/310.js","../../chunks/323.js","../../chunks/622.js","../../chunks/676.js","../../chunks/837.js","../../chunks/840.js","../../chunks/862.js","../../chunks/984.js","../../chunks/font-manifest.json","../../webpack-runtime.js"]} \ No newline at end of file +{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/329.js","../../chunks/337.js","../../chunks/638.js","../../chunks/969.js","../../chunks/font-manifest.json","../../webpack-runtime.js"]} \ No newline at end of file diff --git a/.next/server/app/index.html b/.next/server/app/index.html index 1e6ad68..37401ef 100644 --- a/.next/server/app/index.html +++ b/.next/server/app/index.html @@ -1 +1 @@ -sukadia.dev
sukadia
.
dev
\ No newline at end of file +sukadia.dev
sukadia
.
dev
\ No newline at end of file diff --git a/.next/server/app/index.rsc b/.next/server/app/index.rsc index b65b543..ca14b43 100644 --- a/.next/server/app/index.rsc +++ b/.next/server/app/index.rsc @@ -1,10 +1,7 @@ -1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] -0:["P9X42g8nWZ62i2biioMqg",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] -4:HL["/_next/static/css/60c69e914bf8dd4b.css","style",{"crossOrigin":""}] -5:I[6954,[],""] -6:I[7264,[],""] -8:I[8297,[],""] -9:I[6916,["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],""] -2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L5",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L6",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$L7",["$","$L8",null,{"propsForComponent":{"params":{}},"Component":"$9","isStaticGeneration":true}],null],"segment":"__PAGE__"},"styles":[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/60c69e914bf8dd4b.css","precedence":"next","crossOrigin":""}]]}]}]}],null] -3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] -7:null +2:I[7831,[],""] +3:I[326,["986","static/chunks/986-72006aa1051e30d3.js","931","static/chunks/app/page-8af0c2c4af65d19c.js"],""] +4:I[5613,[],""] +5:I[1778,[],""] +0:["xSz9x0FW88Rb7utFdR6Fp",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",["$","$L2",null,{"propsForComponent":{"params":{}},"Component":"$3","isStaticGeneration":true}],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"styles":[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/60c69e914bf8dd4b.css","precedence":"next","crossOrigin":""}]]}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L6"]]]] +6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +1:null diff --git a/.next/server/app/page.js b/.next/server/app/page.js index 11b5551..8216544 100644 --- a/.next/server/app/page.js +++ b/.next/server/app/page.js @@ -1 +1 @@ -(()=>{var e={};e.id=931,e.ids=[931],e.modules={5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},4345:(e,t,s)=>{"use strict";s.r(t),s.d(t,{GlobalError:()=>n.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>c,routeModule:()=>x,tree:()=>d});var a=s(7096),i=s(6132),o=s(7284),n=s.n(o),r=s(2564),l={};for(let e in r)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>r[e]);s.d(t,l);let d=["",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(s.bind(s,3982)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(s.bind(s,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(s.t.bind(s,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(s.bind(s,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],c=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx"],p="/page",u={require:s,loadChunk:()=>Promise.resolve()},x=new a.AppPageRouteModule({definition:{kind:i.x.APP_PAGE,page:"/page",pathname:"/",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:d}})},8530:(e,t,s)=>{Promise.resolve().then(s.bind(s,5698))},5698:(e,t,s)=>{"use strict";let a;s.r(t),s.d(t,{default:()=>Home});var i=s(784),o=s(9885);s(8294);var n=s(2451),r=s.n(n);function Card(e){return(0,i.jsxs)("a",{className:`w-[20rem] h-[8rem] p-2 rounded-2xl bg-slate-800 shadow-lg ${e.shadow} flex flex-col flex-shrink-0 ease-out duration-300 hover:scale-105 hover:-translate-y-1 transition-all`,href:e.link,target:"_blank",children:[(0,i.jsxs)("div",{className:"flex flex-row items-center gap-1 ml-2 h-[2rem] w-full rounded-2xl",children:[i.jsx("span",{className:"text-l font-bold text-cyan-500",children:"sukadia.dev"}),(0,i.jsxs)("span",{className:"text-xl font-bold dark:text-white",children:["/ ",e.title]})]}),(0,i.jsxs)("div",{className:"flex flex-row w-full overflow-clip h-[84px]",children:[i.jsx("div",{className:"h-full aspect-square rounded-2xl relative",children:i.jsx("div",{className:"h-full w-full aspect-square relative rounded-2xl overflow-hidden",children:i.jsx(r(),{fill:!0,src:e.icon,sizes:"128px",alt:"thumbnail",className:""})})}),i.jsx("div",{className:"h-full w-full m-2 ml-4 rounded-2xl",children:i.jsx("p",{children:e.description})})]})]})}function Home(){let[e,t]=(0,o.useState)(""),s=(0,o.useRef)("undefined"!=typeof Audio?new Audio("audio/the-fabled-period-button.mp3"):void 0).current,n=0;return(0,i.jsxs)("main",{className:"select-none",children:[i.jsx("div",{className:"flex flex-col items-center h-screen overflow-hidden",children:(0,i.jsxs)("div",{className:("sukadia"==e||"dev"==e?"-translate-y-24":"")+" flex flex-row w-screen items-center justify-center overflow-hidden text-6xl min-[437px]:text-7xl min-[577px]:text-8xl md:text-9xl m-auto transition-all duration-500 z-20",children:[i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:s=>{t("sukadia"==e?"":"sukadia")},children:i.jsx("div",{id:"sukadia",className:("sukadia"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"sukadia"})}),i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:i=>{t("."==e?"":".");let o=++n;a=setTimeout(()=>{n==o&&s?.cloneNode().play()},100)},onMouseUp:e=>{t(""),clearTimeout(a)},children:i.jsx("div",{id:".",className:("."==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"."})}),i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:s=>{t("dev"==e?"":"dev")},children:i.jsx("div",{id:"dev",className:("dev"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"dev"})})]})}),i.jsx("div",{className:("sukadia"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("sukadia"==e?"opacity-100 z-10":"opacity-0 pointer-events-none -translate-y-12 z-1")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[i.jsx(Card,{title:"Youtube",description:"Lots of VRChat videos focusing on roleplay.",icon:"/images/YoutubeIcon.png",link:"/youtube",shadow:"shadow-red-950"}),i.jsx(Card,{title:"Twitch",description:"Occasional streams for whatever seems fun at the moment.",icon:"/images/TwitchIcon.png",link:"/twitch",shadow:"shadow-violet-950"}),i.jsx(Card,{title:"Discord",description:"The hub for all my socials & projects. Join to stay updated!",icon:"/images/DiscordIcon.png",link:"/discord",shadow:"shadow-blue-900"}),i.jsx(Card,{title:"Ko-fi",description:"Support me monthly to help me make more content.",icon:"/images/KofiIcon.png",link:"/ko-fi",shadow:"shadow-sky-900"})]})}),i.jsx("div",{className:("dev"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("dev"==e?"opacity-100 z-10":"opacity-0 -translate-y-12 z-0")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[i.jsx(Card,{title:"Everyone-Votes",description:"A Discord bot that sends and tallies daily polls from thousands of servers.",icon:"/images/EveryoneVotesIcon.png",link:"/everyone-votes",shadow:"shadow-blue-900"}),i.jsx(Card,{title:"Space",description:"A WebGPU space/nebula image generator with lots of parameters to modify.",icon:"/images/SpaceIcon.png",link:"/space",shadow:"shadow-violet-950"}),i.jsx(Card,{title:"Dark",description:"A VSCode color theme based off of Brackets Dark.",icon:"/images/DarkIcon.png",link:"/dark",shadow:"shadow-yellow-950"})]})})]})}},3982:(e,t,s)=>{"use strict";s.r(t),s.d(t,{$$typeof:()=>n,__esModule:()=>o,default:()=>l});var a=s(5153);let i=(0,a.createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\page.tsx`),{__esModule:o,$$typeof:n}=i,r=i.default,l=r},7481:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var a=s(8531);let __WEBPACK_DEFAULT_EXPORT__=e=>{let t=(0,a.fillMetadataSegment)(".",e.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:t+""}]}},8294:()=>{}};var t=require("../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),s=t.X(0,[862,323,837,622],()=>__webpack_exec__(4345));module.exports=s})(); \ No newline at end of file +(()=>{var e={};e.id=931,e.ids=[931],e.modules={7849:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external")},5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},4345:(e,t,r)=>{"use strict";r.r(t),r.d(t,{GlobalError:()=>s.a,__next_app__:()=>f,originalPathname:()=>c,pages:()=>u,routeModule:()=>p,tree:()=>d});var n=r(482),i=r(9108),o=r(2563),s=r.n(o),a=r(8300),l={};for(let e in a)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>a[e]);r.d(t,l);let d=["",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(r.bind(r,751)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx"],metadata:{icon:[async e=>(await Promise.resolve().then(r.bind(r,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(r.bind(r,2917)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(r.t.bind(r,9361,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(r.bind(r,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],u=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx"],c="/page",f={require:r,loadChunk:()=>Promise.resolve()},p=new n.AppPageRouteModule({definition:{kind:i.x.APP_PAGE,page:"/page",pathname:"/",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:d}})},8530:(e,t,r)=>{Promise.resolve().then(r.bind(r,2079))},6254:(e,t,r)=>{Promise.resolve().then(r.t.bind(r,2583,23)),Promise.resolve().then(r.t.bind(r,6840,23)),Promise.resolve().then(r.t.bind(r,8771,23)),Promise.resolve().then(r.t.bind(r,3225,23)),Promise.resolve().then(r.t.bind(r,9295,23)),Promise.resolve().then(r.t.bind(r,3982,23))},2731:()=>{},2079:(e,t,r)=>{"use strict";let n;r.r(t),r.d(t,{default:()=>d});var i=r(2295),o=r(3729);r(8294);var s=r(1223),a=r.n(s);function l(e){return(0,i.jsxs)("a",{className:`w-[20rem] h-[8rem] p-2 rounded-2xl bg-slate-800 shadow-lg ${e.shadow} flex flex-col flex-shrink-0 ease-out duration-300 hover:scale-105 hover:-translate-y-1 transition-all`,href:e.link,target:"_blank",children:[(0,i.jsxs)("div",{className:"flex flex-row items-center gap-1 ml-2 h-[2rem] w-full rounded-2xl",children:[i.jsx("span",{className:"text-l font-bold text-cyan-500",children:"sukadia.dev"}),(0,i.jsxs)("span",{className:"text-xl font-bold dark:text-white",children:["/ ",e.title]})]}),(0,i.jsxs)("div",{className:"flex flex-row w-full overflow-clip h-[84px]",children:[i.jsx("div",{className:"h-full aspect-square rounded-2xl relative",children:i.jsx("div",{className:"h-full w-full aspect-square relative rounded-2xl overflow-hidden",children:i.jsx(a(),{fill:!0,src:e.icon,sizes:"128px",alt:"thumbnail",className:""})})}),i.jsx("div",{className:"h-full w-full m-2 ml-4 rounded-2xl",children:i.jsx("p",{children:e.description})})]})]})}function d(){let[e,t]=(0,o.useState)(""),r=(0,o.useRef)("undefined"!=typeof Audio?new Audio("audio/the-fabled-period-button.mp3"):void 0).current,s=0;return(0,i.jsxs)("main",{className:"select-none",children:[i.jsx("div",{className:"flex flex-col items-center h-screen overflow-hidden",children:(0,i.jsxs)("div",{className:("sukadia"==e||"dev"==e?"-translate-y-24":"")+" flex flex-row w-screen items-center justify-center overflow-hidden text-6xl min-[437px]:text-7xl min-[577px]:text-8xl md:text-9xl m-auto transition-all duration-500 z-20",children:[i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:r=>{t("sukadia"==e?"":"sukadia")},children:i.jsx("div",{id:"sukadia",className:("sukadia"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"sukadia"})}),i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:i=>{t("."==e?"":".");let o=++s;n=setTimeout(()=>{s==o&&r?.cloneNode().play()},100)},onMouseUp:e=>{t(""),clearTimeout(n)},children:i.jsx("div",{id:".",className:("."==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"."})}),i.jsx("div",{className:"overflow-hidden flex-shrink",onMouseDown:r=>{t("dev"==e?"":"dev")},children:i.jsx("div",{id:"dev",className:("dev"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"dev"})})]})}),i.jsx("div",{className:("sukadia"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("sukadia"==e?"opacity-100 z-10":"opacity-0 pointer-events-none -translate-y-12 z-1")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[i.jsx(l,{title:"Youtube",description:"Lots of VRChat videos focusing on roleplay.",icon:"/images/YoutubeIcon.png",link:"/youtube",shadow:"shadow-red-950"}),i.jsx(l,{title:"Twitch",description:"Occasional streams for whatever seems fun at the moment.",icon:"/images/TwitchIcon.png",link:"/twitch",shadow:"shadow-violet-950"}),i.jsx(l,{title:"Discord",description:"The hub for all my socials & projects. Join to stay updated!",icon:"/images/DiscordIcon.png",link:"/discord",shadow:"shadow-blue-900"}),i.jsx(l,{title:"Ko-fi",description:"Support me monthly to help me make more content.",icon:"/images/KofiIcon.png",link:"/ko-fi",shadow:"shadow-sky-900"})]})}),i.jsx("div",{className:("dev"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("dev"==e?"opacity-100 z-10":"opacity-0 -translate-y-12 z-0")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[i.jsx(l,{title:"Everyone-Votes",description:"A Discord bot that sends and tallies daily polls from thousands of servers.",icon:"/images/EveryoneVotesIcon.png",link:"/everyone-votes",shadow:"shadow-blue-900"}),i.jsx(l,{title:"Space",description:"A WebGPU space/nebula image generator with lots of parameters to modify.",icon:"/images/SpaceIcon.png",link:"/space",shadow:"shadow-violet-950"}),i.jsx(l,{title:"Dark",description:"A VSCode color theme based off of Brackets Dark.",icon:"/images/DarkIcon.png",link:"/dark",shadow:"shadow-yellow-950"})]})})]})}},1900:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Image",{enumerable:!0,get:function(){return x}});let n=r(9694),i=r(7824)._(r(3729)),o=n._(r(1202)),s=n._(r(1758)),a=r(3855),l=r(3053),d=r(4187);r(837);let u=r(6150),c=n._(r(4931)),f={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1};function p(e,t,r,n,i,o){let s=null==e?void 0:e.src;e&&e["data-loaded-src"]!==s&&(e["data-loaded-src"]=s,("decode"in e?e.decode():Promise.resolve()).catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&i(!0),null==r?void 0:r.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let n=!1,i=!1;r.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>n,isPropagationStopped:()=>i,persist:()=>{},preventDefault:()=>{n=!0,t.preventDefault()},stopPropagation:()=>{i=!0,t.stopPropagation()}})}(null==n?void 0:n.current)&&n.current(e)}}))}function m(e){let[t,r]=i.version.split(".",2),n=parseInt(t,10),o=parseInt(r,10);return n>18||18===n&&o>=3?{fetchPriority:e}:{fetchpriority:e}}globalThis.__NEXT_IMAGE_IMPORTED=!0;let h=(0,i.forwardRef)((e,t)=>{let{src:r,srcSet:n,sizes:o,height:s,width:a,decoding:l,className:d,style:u,fetchPriority:c,placeholder:f,loading:h,unoptimized:g,fill:x,onLoadRef:v,onLoadingCompleteRef:y,setBlurComplete:w,setShowAltText:b,onLoad:_,onError:j,...P}=e;return i.default.createElement("img",{...P,...m(c),loading:h,width:a,height:s,decoding:l,"data-nimg":x?"fill":"1",className:d,style:u,sizes:o,srcSet:n,src:r,ref:(0,i.useCallback)(e=>{t&&("function"==typeof t?t(e):"object"==typeof t&&(t.current=e)),e&&(j&&(e.src=e.src),e.complete&&p(e,f,v,y,w,g))},[r,f,v,y,w,j,g,t]),onLoad:e=>{p(e.currentTarget,f,v,y,w,g)},onError:e=>{b(!0),"empty"!==f&&w(!0),j&&j(e)}})});function g(e){let{isAppRouter:t,imgAttributes:r}=e,n={as:"image",imageSrcSet:r.srcSet,imageSizes:r.sizes,crossOrigin:r.crossOrigin,referrerPolicy:r.referrerPolicy,...m(r.fetchPriority)};return t&&o.default.preload?(o.default.preload(r.src,n),null):i.default.createElement(s.default,null,i.default.createElement("link",{key:"__nimg-"+r.src+r.srcSet+r.sizes,rel:"preload",href:r.srcSet?void 0:r.src,...n}))}let x=(0,i.forwardRef)((e,t)=>{let r=(0,i.useContext)(u.RouterContext),n=(0,i.useContext)(d.ImageConfigContext),o=(0,i.useMemo)(()=>{let e=f||n||l.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),r=e.deviceSizes.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:r}},[n]),{onLoad:s,onLoadingComplete:p}=e,m=(0,i.useRef)(s);(0,i.useEffect)(()=>{m.current=s},[s]);let x=(0,i.useRef)(p);(0,i.useEffect)(()=>{x.current=p},[p]);let[v,y]=(0,i.useState)(!1),[w,b]=(0,i.useState)(!1),{props:_,meta:j}=(0,a.getImgProps)(e,{defaultLoader:c.default,imgConf:o,blurComplete:v,showAltText:w});return i.default.createElement(i.default.Fragment,null,i.default.createElement(h,{..._,unoptimized:j.unoptimized,placeholder:j.placeholder,fill:j.fill,onLoadRef:m,onLoadingCompleteRef:x,setBlurComplete:y,setShowAltText:b,ref:t}),j.priority?i.default.createElement(g,{isAppRouter:!r,imgAttributes:_}):null)});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7637:(e,t,r)=>{"use strict";e.exports=r(6372).vendored.contexts.AmpContext},2158:(e,t,r)=>{"use strict";e.exports=r(6372).vendored.contexts.HeadManagerContext},4187:(e,t,r)=>{"use strict";e.exports=r(6372).vendored.contexts.ImageConfigContext},6150:(e,t,r)=>{"use strict";e.exports=r(6372).vendored.contexts.RouterContext},2295:(e,t,r)=>{"use strict";e.exports=r(6372).vendored["react-ssr"].ReactJsxRuntime},3126:(e,t)=>{"use strict";function r(e){let{ampFirst:t=!1,hybrid:r=!1,hasQuery:n=!1}=void 0===e?{}:e;return t||r&&n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return r}})},3855:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImgProps",{enumerable:!0,get:function(){return a}}),r(837);let n=r(3990),i=r(3053);function o(e){return void 0!==e.default}function s(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function a(e,t){var r;let a,l,d,{src:u,sizes:c,unoptimized:f=!1,priority:p=!1,loading:m,className:h,quality:g,width:x,height:v,fill:y=!1,style:w,onLoad:b,onLoadingComplete:_,placeholder:j="empty",blurDataURL:P,fetchPriority:S,layout:k,objectFit:C,objectPosition:E,lazyBoundary:M,lazyRoot:O,...z}=e,{imgConf:I,showAltText:A,blurComplete:N,defaultLoader:R}=t,D=I||i.imageConfigDefault;if("allSizes"in D)a=D;else{let e=[...D.deviceSizes,...D.imageSizes].sort((e,t)=>e-t),t=D.deviceSizes.sort((e,t)=>e-t);a={...D,allSizes:e,deviceSizes:t}}let q=z.loader||R;delete z.loader,delete z.srcSet;let U="__next_img_default"in q;if(U){if("custom"===a.loader)throw Error('Image with src "'+u+'" is missing "loader" prop.\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader')}else{let e=q;q=t=>{let{config:r,...n}=t;return e(n)}}if(k){"fill"===k&&(y=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[k];e&&(w={...w,...e});let t={responsive:"100vw",fill:"100vw"}[k];t&&!c&&(c=t)}let G="",T=s(x),W=s(v);if("object"==typeof(r=u)&&(o(r)||void 0!==r.src)){let e=o(u)?u.default:u;if(!e.src)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "+JSON.stringify(e));if(!e.height||!e.width)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received "+JSON.stringify(e));if(l=e.blurWidth,d=e.blurHeight,P=P||e.blurDataURL,G=e.src,!y){if(T||W){if(T&&!W){let t=T/e.width;W=Math.round(e.height*t)}else if(!T&&W){let t=W/e.height;T=Math.round(e.width*t)}}else T=e.width,W=e.height}}let L=!p&&("lazy"===m||void 0===m);(!(u="string"==typeof u?u:G)||u.startsWith("data:")||u.startsWith("blob:"))&&(f=!0,L=!1),a.unoptimized&&(f=!0),U&&u.endsWith(".svg")&&!a.dangerouslyAllowSVG&&(f=!0),p&&(S="high");let B=s(g),V=Object.assign(y?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:C,objectPosition:E}:{},A?{}:{color:"transparent"},w),F=N||"empty"===j?null:"blur"===j?'url("data:image/svg+xml;charset=utf-8,'+(0,n.getImageBlurSvg)({widthInt:T,heightInt:W,blurWidth:l,blurHeight:d,blurDataURL:P||"",objectFit:V.objectFit})+'")':'url("'+j+'")',X=F?{backgroundSize:V.objectFit||"cover",backgroundPosition:V.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:F}:{},$=function(e){let{config:t,src:r,unoptimized:n,width:i,quality:o,sizes:s,loader:a}=e;if(n)return{src:r,srcSet:void 0,sizes:void 0};let{widths:l,kind:d}=function(e,t,r){let{deviceSizes:n,allSizes:i}=e;if(r){let e=/(^|\s)(1?\d?\d)vw/g,t=[];for(let n;n=e.exec(r);n)t.push(parseInt(n[2]));if(t.length){let e=.01*Math.min(...t);return{widths:i.filter(t=>t>=n[0]*e),kind:"w"}}return{widths:i,kind:"w"}}return"number"!=typeof t?{widths:n,kind:"w"}:{widths:[...new Set([t,2*t].map(e=>i.find(t=>t>=e)||i[i.length-1]))],kind:"x"}}(t,i,s),u=l.length-1;return{sizes:s||"w"!==d?s:"100vw",srcSet:l.map((e,n)=>a({config:t,src:r,quality:o,width:e})+" "+("w"===d?e:n+1)+d).join(", "),src:a({config:t,src:r,quality:o,width:l[u]})}}({config:a,src:u,unoptimized:f,width:T,quality:B,sizes:c,loader:q});return{props:{...z,loading:L?"lazy":m,fetchPriority:S,width:T,height:W,decoding:"async",className:h,style:{...V,...X},sizes:$.sizes,srcSet:$.srcSet,src:$.src},meta:{unoptimized:f,priority:p,placeholder:j,fill:y}}}},1758:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{defaultHead:function(){return d},default:function(){return p}});let n=r(9694),i=r(7824)._(r(3729)),o=n._(r(7984)),s=r(7637),a=r(2158),l=r(3126);function d(e){void 0===e&&(e=!1);let t=[i.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(i.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function u(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===i.default.Fragment?e.concat(i.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}r(837);let c=["name","httpEquiv","charSet","itemProp"];function f(e,t){let{inAmpMode:r}=t;return e.reduce(u,[]).reverse().concat(d(r).reverse()).filter(function(){let e=new Set,t=new Set,r=new Set,n={};return i=>{let o=!0,s=!1;if(i.key&&"number"!=typeof i.key&&i.key.indexOf("$")>0){s=!0;let t=i.key.slice(i.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(i.type){case"title":case"base":t.has(i.type)?o=!1:t.add(i.type);break;case"meta":for(let e=0,t=c.length;e{let n=e.key||t;if(!r&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,i.default.cloneElement(e,t)}return i.default.cloneElement(e,{key:n})})}let p=function(e){let{children:t}=e,r=(0,i.useContext)(s.AmpStateContext),n=(0,i.useContext)(a.HeadManagerContext);return i.default.createElement(o.default,{reduceComponentsToState:f,headManager:n,inAmpMode:(0,l.isInAmpMode)(r)},t)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3990:(e,t)=>{"use strict";function r(e){let{widthInt:t,heightInt:r,blurWidth:n,blurHeight:i,blurDataURL:o,objectFit:s}=e,a=n?40*n:t,l=i?40*i:r,d=a&&l?"viewBox='0 0 "+a+" "+l+"'":"";return"%3Csvg xmlns='http://www.w3.org/2000/svg' "+d+"%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='"+(d?"none":"contain"===s?"xMidYMid":"cover"===s?"xMidYMid slice":"none")+"' style='filter: url(%23b);' href='"+o+"'/%3E%3C/svg%3E"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImageBlurSvg",{enumerable:!0,get:function(){return r}})},3053:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{VALID_LOADERS:function(){return r},imageConfigDefault:function(){return n}});let r=["default","imgix","cloudinary","akamai","custom"],n={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},7412:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{unstable_getImgProps:function(){return l},default:function(){return d}});let n=r(9694),i=r(3855),o=r(837),s=r(1900),a=n._(r(4931)),l=e=>{(0,o.warnOnce)("Warning: unstable_getImgProps() is experimental and may change or be removed at any time. Use at your own risk.");let{props:t}=(0,i.getImgProps)(e,{defaultLoader:a.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}});for(let[e,r]of Object.entries(t))void 0===r&&delete t[e];return{props:t}},d=s.Image},4931:(e,t)=>{"use strict";function r(e){let{config:t,src:r,width:n,quality:i}=e;return t.path+"?url="+encodeURIComponent(r)+"&w="+n+"&q="+(i||75)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}}),r.__next_img_default=!0;let n=r},7984:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return s}});let n=r(3729),i=()=>{},o=()=>{};function s(e){var t;let{headManager:r,reduceComponentsToState:s}=e;function a(){if(r&&r.mountedInstances){let t=n.Children.toArray(Array.from(r.mountedInstances).filter(Boolean));r.updateHead(s(t,e))}}return null==r||null==(t=r.mountedInstances)||t.add(e.children),a(),i(()=>{var t;return null==r||null==(t=r.mountedInstances)||t.add(e.children),()=>{var t;null==r||null==(t=r.mountedInstances)||t.delete(e.children)}}),i(()=>(r&&(r._pendingUpdate=a),()=>{r&&(r._pendingUpdate=a)})),o(()=>(r&&r._pendingUpdate&&(r._pendingUpdate(),r._pendingUpdate=null),()=>{r&&r._pendingUpdate&&(r._pendingUpdate(),r._pendingUpdate=null)})),null}},837:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return r}});let r=e=>{}},1223:(e,t,r)=>{e.exports=r(7412)},2917:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>a,metadata:()=>s});var n=r(5036),i=r(265),o=r.n(i);r(3440);let s={title:"sukadia.dev",description:"I code, stream, and create videos."};function a({children:e}){return n.jsx("html",{lang:"en",children:n.jsx("body",{className:o().className,children:e})})}},751:(e,t,r)=>{"use strict";r.r(t),r.d(t,{$$typeof:()=>o,__esModule:()=>i,default:()=>s});let n=(0,r(6843).createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\page.tsx`),{__esModule:i,$$typeof:o}=n,s=n.default},7481:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>i});var n=r(337);let i=e=>[{type:"image/x-icon",sizes:"16x16",url:(0,n.fillMetadataSegment)(".",e.params,"favicon.ico")+""}]},3440:()=>{},8294:()=>{}};var t=require("../webpack-runtime.js");t.C(e);var r=e=>t(t.s=e),n=t.X(0,[638,969,337],()=>r(4345));module.exports=n})(); \ No newline at end of file diff --git a/.next/server/app/page.js.nft.json b/.next/server/app/page.js.nft.json index d933c24..4e95267 100644 --- a/.next/server/app/page.js.nft.json +++ b/.next/server/app/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../node_modules/next/dist/client/components/async-local-storage.js","../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../node_modules/next/dist/client/components/async-local-storage.js","../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../package.json","../../package.json","../chunks/329.js","../chunks/337.js","../chunks/638.js","../chunks/969.js","../chunks/font-manifest.json","../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/page_client-reference-manifest.js b/.next/server/app/page_client-reference-manifest.js index 0143196..04531b1 100644 --- a/.next/server/app/page_client-reference-manifest.js +++ b/.next/server/app/page_client-reference-manifest.js @@ -1 +1 @@ -globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"]}} \ No newline at end of file +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"326":{"*":{"id":"2079","name":"*","chunks":[],"async":false}},"1778":{"*":{"id":"9295","name":"*","chunks":[],"async":false}},"1902":{"*":{"id":"3225","name":"*","chunks":[],"async":false}},"5613":{"*":{"id":"8771","name":"*","chunks":[],"async":false}},"7690":{"*":{"id":"2583","name":"*","chunks":[],"async":false}},"7831":{"*":{"id":"3982","name":"*","chunks":[],"async":false}},"8955":{"*":{"id":"6840","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":3445,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":9989,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":326,"name":"*","chunks":["986","static/chunks/986-72006aa1051e30d3.js","931","static/chunks/app/page-8af0c2c4af65d19c.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"]}} \ No newline at end of file diff --git a/.next/server/app/space.html b/.next/server/app/space.html index f2c5379..87a40a8 100644 --- a/.next/server/app/space.html +++ b/.next/server/app/space.html @@ -1 +1 @@ -sukadia.dev
\ No newline at end of file +sukadia.dev
\ No newline at end of file diff --git a/.next/server/app/space.rsc b/.next/server/app/space.rsc index a902af3..5769bcc 100644 --- a/.next/server/app/space.rsc +++ b/.next/server/app/space.rsc @@ -1,9 +1,7 @@ -1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] -0:["P9X42g8nWZ62i2biioMqg",[[["",{"children":["space",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] -4:I[6954,[],""] -5:I[7264,[],""] -7:I[8297,[],""] -8:I[341,["732","static/chunks/e1206f8c-ab5b5541f866e530.js","105","static/chunks/1f3d3139-f107a678ff6361e9.js","735","static/chunks/604a08ec-59af37265fb99b3d.js","790","static/chunks/d67c510a-e497b3cd5bf43bb4.js","116","static/chunks/537cd76e-7aba1cf7a4752418.js","173","static/chunks/173-2ffa9652644381a8.js","514","static/chunks/app/space/page-b8120f6d5470d1c7.js"],""] -2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","space","children"],"loading":["$","div",null,{"className":"flex h-screen justify-center items-center","children":["$","div",null,{"className":"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin","children":["$","div",null,{"className":"h-10 w-10 rounded-full bg-black"}]}]}],"loadingStyles":[],"loadingScripts":[],"hasLoading":true,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L6",["$","$L7",null,{"propsForComponent":{"params":{}},"Component":"$8","isStaticGeneration":true}],null],"segment":"__PAGE__"},"styles":null}],"segment":"space"},"styles":null}]}]}],null] -3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] -6:null +2:I[7831,[],""] +3:I[7846,["732","static/chunks/e1206f8c-1ba69cf5e736c266.js","105","static/chunks/1f3d3139-8a75094e9a213384.js","735","static/chunks/604a08ec-edbc4bb5c67ea975.js","790","static/chunks/d67c510a-4a8f7a6a0c1c3e2a.js","116","static/chunks/537cd76e-7aba1cf7a4752418.js","973","static/chunks/973-5f61489a82d0bbab.js","514","static/chunks/app/space/page-185302d4e0f787e8.js"],""] +4:I[5613,[],""] +5:I[1778,[],""] +0:["xSz9x0FW88Rb7utFdR6Fp",[[["",{"children":["space",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["space",{"children":["__PAGE__",{},["$L1",["$","$L2",null,{"propsForComponent":{"params":{}},"Component":"$3","isStaticGeneration":true}],null]]},["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","space","children"],"loading":["$","div",null,{"className":"flex h-screen justify-center items-center","children":["$","div",null,{"className":"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin","children":["$","div",null,{"className":"h-10 w-10 rounded-full bg-black"}]}]}],"loadingStyles":[],"loadingScripts":[],"hasLoading":true,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","styles":null}]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"styles":null}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L6"]]]] +6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"sukadia.dev"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +1:null diff --git a/.next/server/app/space/page.js b/.next/server/app/space/page.js index dfd8869..445f77e 100644 --- a/.next/server/app/space/page.js +++ b/.next/server/app/space/page.js @@ -1 +1,11702 @@ -(()=>{var e={};e.id=514,e.ids=[514],e.modules={5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},8899:(e,t,a)=>{"use strict";a.r(t),a.d(t,{GlobalError:()=>i.a,__next_app__:()=>u,originalPathname:()=>p,pages:()=>c,routeModule:()=>h,tree:()=>l});var n=a(7096),r=a(6132),s=a(7284),i=a.n(s),o=a(2564),d={};for(let e in o)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(d[e]=()=>o[e]);a.d(t,d);let l=["",{children:["space",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(a.bind(a,5237)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx"]}]},{loading:[()=>Promise.resolve().then(a.bind(a,9771)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\loading.tsx"],metadata:{icon:[async e=>(await Promise.resolve().then(a.bind(a,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(a.bind(a,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(a.t.bind(a,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(a.bind(a,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],c=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx"],p="/space/page",u={require:a,loadChunk:()=>Promise.resolve()},h=new n.AppPageRouteModule({definition:{kind:r.x.APP_PAGE,page:"/space/page",pathname:"/space",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:l}})},4038:(e,t,a)=>{Promise.resolve().then(a.bind(a,9663))},5303:()=>{},7690:(e,t,a)=>{"use strict";let n,r,s,i,o,d,l;a.d(t,{Z:()=>BabylonInteractivity});var c=a(4494),p=a(102);let u=[];function hashString(e){var t,a=0;for(t=0;t>>15,1|t),(((t^=t+Math.imul(t^t>>>7,61|t))^t>>>14)>>>0)/4294967296}let BabylonInteractivity=class BabylonInteractivity{static generateFrame(){if(!n)return;let e=performance.now(),t=(0,p.g)();(n.width!=t.width||n.height!=t.height)&&this.resizeFrame(t.width,t.height),d!=t.seed&&(l=mulberry32(hashString(t.seed)),d=t.seed,console.log(1)),o.onApply=e=>{e.setFloat("seed",l+5),e.setFloat("density",t.density/100),e.setFloat("brightness",t.brightness/100)};for(let e=0;e{a.setFloat("seed",1e3*l*(e+1)),a.setFloat4("color",t[`color${e+1}`].r/255,t[`color${e+1}`].g/255,t[`color${e+1}`].b/255,1),a.setUInt("nebulascale",t.scale),a.setUInt("depth",t.depth),a.setFloat("intensity",t.intensity/100-1),a.setFloat("falloff",t.falloff),a.setFloat("persistence",t.persistence)},u[e].onApplyObservable.add(t=>{t.setTextureSampler("textureSamplerSampler",u[e].inputTexture.texture)});s.onAfterRenderObservable.addOnce(()=>{console.log(`Rendered in ${Math.round((performance.now()-e)*100)/100}ms`)}),r.beginFrame(),s.render(),r.endFrame()}static resizeFrame(e,t){n.style.width=e.toString()+"px",n.style.height=t.toString()+"px",r.resize()}static async exportFrame(){let e=(0,p.g)();c.w1W.CreateScreenshotUsingRenderTarget(r,i,{width:n.width,height:n.height},void 0,void 0,void 0,void 0,`nebula-${e.seed}`),this.generateFrame()}static setTransparency(e){e?s.clearColor=new c.HEv(0,0,0,0):s.clearColor=new c.HEv(0,0,0,1)}static initialize(e,t,a,d){n=e,r=t,s=a,i=d,o=new c.Dso("StarShader","stars",null,null,1,i,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL),i.attachPostProcess(o);for(let e=0;e<10;e++)u.push(new c.Dso("NebulaShader","nebulas",null,null,1,i,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL))}}},102:(e,t,a)=>{"use strict";let n;a.d(t,{Z:()=>ParameterPanel,g:()=>getParameters});var r=a(6224),s=a(7690);function ParameterPanel(){n=new r.Pane({title:"Parameters",container:document.getElementById("TweakPane")||void 0});let e={width:window.innerWidth,height:window.innerHeight,transparent:!1,autoupdate:!1},t=n.addFolder({title:"Canvas",expanded:!0});t.addInput(e,"width",{min:100,max:7680,step:1}),t.addInput(e,"height",{min:100,max:4320,step:1}),t.addInput(e,"transparent").on("change",()=>{console.log(1),s.Z.setTransparency(e.transparent)});let a={density:1.5,brightness:100},i=n.addFolder({title:"Stars",expanded:!0});i.addInput(a,"density",{min:0,max:10,step:.01,format:e=>e.toFixed(2)+"%"}),i.addInput(a,"brightness",{min:0,max:200,step:.1,format:e=>e.toFixed(1)+"%"});let o={count:2,scale:5,depth:2,intensity:100,falloff:2,persistence:.5},d=n.addFolder({title:"Nebula",expanded:!0});d.addInput(o,"count",{min:0,max:3,step:1}).on("change",()=>{if(0==o.count)c.hidden=!0;else{c.hidden=!1;for(let e=0;eo.count-1&&(p[e].hidden=!0);d.addInput(o,"scale",{min:1,max:50,step:1}),d.addInput(o,"depth",{min:0,max:20,step:1}),d.addInput(o,"intensity",{min:50,max:150,step:1,format:e=>e+"%"}),d.addInput(o,"falloff",{min:1,max:10,step:.1}),d.addInput(o,"persistence",{min:0,max:1,step:.01});let u={seed:""+Math.floor(1e12*Math.random())},h=n.addFolder({title:"Seed",expanded:!1});h.addInput(u,"seed",{format:e=>e.toFixed(0)}),h.addButton({title:"Randomize seed"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString(),n.refresh(),s.Z.generateFrame()}),n.addSeparator(),n.addButton({title:"Render"}).on("click",()=>{s.Z.generateFrame()}),n.addButton({title:"Render Random"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString();for(let e=0;e<3;e++)l["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())};n.refresh(),s.Z.generateFrame()}),n.addSeparator(),n.addButton({title:"Save Image"}).on("click",()=>{s.Z.exportFrame()}),n.addSeparator(),n.addInput(e,"autoupdate"),n.on("change",t=>{let a=t.presetKey;e.autoupdate&&(("width"==a||"height"==a)&&s.Z.resizeFrame(e.width,e.height),s.Z.generateFrame())})}function getParameters(){return n.exportPreset()}},9663:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>Sp});var n=a(784),r=a(9885),s=a(3642),i=a.n(s);function Loading(){return n.jsx("div",{className:"flex h-screen justify-center items-center",children:n.jsx("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:n.jsx("div",{className:"h-10 w-10 rounded-full bg-black"})})})}var o=a(102);let d=i()(()=>a.e(106).then(a.bind(a,4106)),{loadableGenerated:{modules:["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx -> ./BabylonScene"]},ssr:!1});function Sp(){let[e,t]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{t(!0),(0,o.Z)()},[]),(0,n.jsxs)("main",{children:[n.jsx("div",{id:"TweakPane",className:"fixed top-2.5 right-2.5"}),e&&n.jsx(d,{}),!e&&n.jsx(Loading,{})]})}},9771:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>Loading});var n=a(4656);function Loading(){return n.jsx("div",{className:"flex h-screen justify-center items-center",children:n.jsx("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:n.jsx("div",{className:"h-10 w-10 rounded-full bg-black"})})})}},5237:(e,t,a)=>{"use strict";a.r(t),a.d(t,{$$typeof:()=>i,__esModule:()=>s,default:()=>d});var n=a(5153);let r=(0,n.createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\space\page.tsx`),{__esModule:s,$$typeof:i}=r,o=r.default,d=o},7481:(e,t,a)=>{"use strict";a.r(t),a.d(t,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var n=a(8531);let __WEBPACK_DEFAULT_EXPORT__=e=>{let t=(0,n.fillMetadataSegment)(".",e.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:t+""}]}}};var t=require("../../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),a=t.X(0,[862,323,984,622],()=>__webpack_exec__(8899));module.exports=a})(); \ No newline at end of file +(()=>{var e={};e.id=514,e.ids=[514],e.modules={7849:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external")},5403:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external")},4749:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:e=>{"use strict";e.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:e=>{"use strict";e.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:e=>{"use strict";e.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:e=>{"use strict";e.exports=require("path")},7310:e=>{"use strict";e.exports=require("url")},8899:(e,t,i)=>{"use strict";i.r(t),i.d(t,{GlobalError:()=>a.a,__next_app__:()=>d,originalPathname:()=>c,pages:()=>u,routeModule:()=>p,tree:()=>h});var r=i(482),s=i(9108),n=i(2563),a=i.n(n),o=i(8300),l={};for(let e in o)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>o[e]);i.d(t,l);let h=["",{children:["space",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(i.bind(i,926)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx"]}]},{loading:[()=>Promise.resolve().then(i.bind(i,8187)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\loading.tsx"],metadata:{icon:[async e=>(await Promise.resolve().then(i.bind(i,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(i.bind(i,2917)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(i.t.bind(i,9361,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(i.bind(i,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],u=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx"],c="/space/page",d={require:i,loadChunk:()=>Promise.resolve()},p=new r.AppPageRouteModule({definition:{kind:s.x.APP_PAGE,page:"/space/page",pathname:"/space",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:h}})},4038:(e,t,i)=>{Promise.resolve().then(i.bind(i,2018))},6254:(e,t,i)=>{Promise.resolve().then(i.t.bind(i,2583,23)),Promise.resolve().then(i.t.bind(i,6840,23)),Promise.resolve().then(i.t.bind(i,8771,23)),Promise.resolve().then(i.t.bind(i,3225,23)),Promise.resolve().then(i.t.bind(i,9295,23)),Promise.resolve().then(i.t.bind(i,3982,23))},2731:()=>{},5303:()=>{},2018:(e,t,i)=>{"use strict";let r,s,n,a,o,l,h,u,c,d,p;i.r(t),i.d(t,{default:()=>yM});var _,f,m,g,v,x,T,b,E,S,C,y,A,R,I,P,M,D,O,N,F,w,L,B,U,V,k,G,z,W,H,X,Y,j,K,$,q,Q,Z,J,ee,et,ei,er,es,en,ea,eo,el,eh,eu,ec,ed,ep,e_,ef,em,eg,ev,ex,eT,eb,eE,eS,eC,ey,eA,eR,eI,eP,eM,eD,eO,eN,eF,ew,eL,eB,eU,eV,ek,eG,ez,eW,eH,eX,eY,ej,eK,e$,eq,eQ,eZ,eJ,e0,e1,e2,e3,e4,e5,e6,e8,e7,e9,te,tt,ti,tr,ts,tn,ta,to,tl,th,tu,tc,td,tp,t_,tf,tm,tg,tv,tx,tT,tb,tE,tS,tC,ty,tA,tR,tI,tP,tM,tD,tO,tN,tF,tw,tL,tB=i(2295),tU=i(3729),tV=i(3267),tk=i.n(tV);function tG(){return tB.jsx("div",{className:"flex h-screen justify-center items-center",children:tB.jsx("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:tB.jsx("div",{className:"h-10 w-10 rounded-full bg-black"})})})}var tz=i(9652);class tW{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,i,r){for(let s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,r)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=(e=(e=(e=e.concat(this.meshes)).concat(this.lights)).concat(this.cameras)).concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}}tW._BabylonFileParsers={},tW._IndividualBabylonFileParsers={};class tH{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(let e in tH.Triggers)if(Object.prototype.hasOwnProperty.call(tH.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in tH.Triggers)if(Object.prototype.hasOwnProperty.call(tH.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in tH.Triggers)if(Object.prototype.hasOwnProperty.call(tH.Triggers,t)&&parseInt(t)===e)return!0;return!1}}tH.Triggers={};class tX{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}}class tY{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class tj{static FromPromise(e,t){let i=new tj;return e.then(e=>{i.notifyObservers(e)}).catch(e=>{if(t)t.notifyObservers(e);else throw e}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=[],this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new tX(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;let n=new tY(e,t,r);return n.unregisterOnNextCall=s,i?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){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return -1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,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,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let n=this._eventState;for(let a of(n.mask=t,n.target=i,n.currentTarget=r,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=s,this._observers))if(!a._willBeUnregistered&&(a.mask&t&&(a.unregisterOnNextCall&&this._deferUnregister(a),a.scope?n.lastReturnValue=a.callback.apply(a.scope,[e,n]):n.lastReturnValue=a.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let 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(){let e=new tj;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}class tK{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){let t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}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,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=tK.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){let i=tK.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let r=tK.Clamp(i);return t*(r=-2*r*r*r+3*r*r)+e*(1-r)}static MoveTowards(e,t,i){return Math.abs(t-e)<=i?t:e+tK.Sign(t-e)*i}static MoveTowardsAngle(e,t,i){let r=tK.DeltaAngle(e,t),s=0;return-i180&&(r-=360),e+r*tK.Clamp(i)}static InverseLerp(e,t,i){return e!=t?tK.Clamp((i-e)/(t-e)):0}static Hermite(e,t,i,r,s){let n=s*s,a=s*n;return e*(2*a-3*n+1)+i*(-2*a+3*n)+t*(a-2*n+s)+r*(a-n)}static Hermite1stDerivative(e,t,i,r,s){let n=s*s;return(n-s)*6*e+(3*n-4*s+1)*t+(-n+s)*6*i+(3*n-2*s)*r}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=tK.TwoPi*Math.floor((e+Math.PI)/tK.TwoPi)}static HCF(e,t){let i=e%t;return 0===i?t:tK.HCF(t,i)}}tK.TwoPi=2*Math.PI;let t$=1/2.2,tq=(1+Math.sqrt(5))/2;class tQ{static BuildArray(e,t){let i=[];for(let r=0;r(function(e,t,i){let r=e[t];if("function"!=typeof r)return null;let s=function(){let r=e.length,n=s.previous.apply(e,arguments);return i(t,r),n};return r.next=s,s.previous=r,e[t]=s,()=>{let i=s.previous;if(!i)return;let r=s.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}})(e,i,t));return()=>{i.forEach(e=>{null==e||e()})}}let t0={};class t1{static SetMatrixPrecision(e){if(t1.MatrixTrackPrecisionChange=!1,e&&!t1.MatrixUse64Bits&&t1.MatrixTrackedMatrices)for(let e=0;eparseInt(e.toString().replace(/\W/g,""));class t4{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=t3(this.x),t=t3(this.y);return 397*e^t}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return t4.FromArrayToRef(e,t,this),this}asArray(){let e=[];return this.toArray(e,0),e}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)}add(e){return new this.constructor(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}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(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 this.constructor(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 this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(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.divideToRef(e,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){let t=new this.constructor(0,0);return this.scaleToRef(e,t),t}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=.001){return e&&tK.WithinEpsilon(this.x,e.x,t)&&tK.WithinEpsilon(this.y,e.y,t)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(e,t){let i=Math.cos(e),r=Math.sin(e),s=i*this.x-r*this.y,n=r*this.x+i*this.y;return t.x=s,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(){let e=new this.constructor(0,0);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return 0===t||1===t?e.copyFromFloats(this.x,this.y):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new t4(0,0)}static One(){return new t4(1,1)}static Random(e=0,t=1){return new t4(tK.RandomRange(e,t),tK.RandomRange(e,t))}static get ZeroReadOnly(){return t4._ZeroReadOnly}static FromArray(e,t=0){return new t4(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static CatmullRom(e,t,i,r,s){let n=s*s,a=s*n,o=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*n+(-e.x+3*t.x-3*i.x+r.x)*a),l=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*n+(-e.y+3*t.y-3*i.y+r.y)*a);return new e.constructor(o,l)}static Clamp(e,t,i){let r=e.x;r=(r=r>i.x?i.x:r)i.y?i.y:s)t.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new e.constructor(i,r)}static Transform(e,t){let i=new e.constructor;return t4.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],n=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=n,i}static PointInTriangle(e,t,i,r){let s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),n=s<0?-1:1,a=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*n,o=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*n;return a>0&&o>0&&a+o<2*s*n}static Distance(e,t){return Math.sqrt(t4.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){let i=new e.constructor;return t4.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){let r=t4.DistanceSquared(t,i);if(0===r)return t4.Distance(e,t);let s=i.subtract(t),n=Math.max(0,Math.min(1,t4.Dot(e.subtract(t),s)/r)),a=t.add(s.multiplyByFloats(n,n));return t4.Distance(e,a)}}t4._ZeroReadOnly=t4.Zero();class t5{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,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=t3(this._x),t=t3(this._y),i=t3(this._z),r=e;return 397*(r=397*r^t)^i}asArray(){let e=[];return this.toArray(e,0),e}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 t5.FromArrayToRef(e,t,this),this}toQuaternion(){return t8.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this.addInPlaceFromFloats(e._x,e._y,e._z)}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(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,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-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.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){let t=this.length(),i=Math.acos(this.y/t),r=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;let s=t*Math.sin(i)*Math.cos(r),n=t*Math.cos(i),a=t*Math.sin(i)*Math.sin(r);return e.set(s,n,a),e}applyRotationQuaternionToRef(e,t){let i=this._x,r=this._y,s=this._z,n=e._x,a=e._y,o=e._z,l=e._w,h=2*(a*s-o*r),u=2*(o*i-n*s),c=2*(n*r-a*i);return t._x=i+l*h+a*c-o*u,t._y=r+l*u+o*h-n*c,t._z=s+l*c+n*u-a*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){let i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){let r=e.normal,s=e.d,n=t9.Vector3[0];this.subtractToRef(t,n),n.normalize();let a=t5.Dot(n,r);if(1e-10>Math.abs(a))i.setAll(1/0);else{let e=-(t5.Dot(t,r)+s)/a,o=n.scaleInPlace(e);t.addToRef(o,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=.001){return e&&tK.WithinEpsilon(this._x,e._x,t)&&tK.WithinEpsilon(this._y,e._y,t)&&tK.WithinEpsilon(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}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.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new this.constructor(this._x*e,this._y*t,this._z*i)}divide(e){return new this.constructor(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this.divideToRef(e,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,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){let t=Math.abs(this._x),i=Math.abs(this._y);if(!tK.WithinEpsilon(t,i,e))return!0;let r=Math.abs(this._z);return!(tK.WithinEpsilon(t,r,e)&&tK.WithinEpsilon(i,r,e))}get isNonUniform(){let e=Math.abs(this._x);return e!==Math.abs(this._y)||e!==Math.abs(this._z)}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}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;let t=t9.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(t9.Matrix[0]),t5.TransformCoordinatesToRef(this,t9.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,t9.Vector3[0]),t9.Vector3[0].rotateByQuaternionToRef(e,t9.Vector3[0]),t.addToRef(t9.Vector3[0],i),i}cross(e){let t=new this.constructor;return t5.CrossToRef(this,e,t)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){let s=t5.Dot(e,i);return(s-r)/(s-t5.Dot(t,i))}static GetAngleBetweenVectors(e,t,i){let r=e.normalizeToRef(t9.Vector3[1]),s=t.normalizeToRef(t9.Vector3[2]),n=t5.Dot(r,s),a=Math.acos(n=tK.Clamp(n,-1,1)),o=t9.Vector3[3];return(t5.CrossToRef(r,s,o),t5.Dot(o,i)>0)?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,i){t9.Vector3[0].copyFrom(e);let r=t9.Vector3[0];t9.Vector3[1].copyFrom(t);let s=t9.Vector3[1];t9.Vector3[2].copyFrom(i);let n=t9.Vector3[2],a=t9.Vector3[3],o=t9.Vector3[4];r.normalize(),s.normalize(),n.normalize(),t5.CrossToRef(n,r,a),t5.CrossToRef(a,n,o);let l=Math.atan2(t5.Dot(s,a),t5.Dot(s,o));return tK.NormalizeRadians(l)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){let r=ie.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){let i=t5.Zero();return t5.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){let s,n;i=tK.Clamp(i,0,1);let a=t9.Vector3[0],o=t9.Vector3[1];a.copyFrom(e);let l=a.length();a.normalizeFromLength(l),o.copyFrom(t);let h=o.length();o.normalizeFromLength(h);let u=t5.Dot(a,o);if(u<.999){let e=Math.acos(u),t=1/Math.sin(e);s=Math.sin((1-i)*e)*t,n=Math.sin(i*e)*t}else s=1-i,n=i;return a.scaleInPlace(s),o.scaleInPlace(n),r.copyFrom(a).addInPlace(o),r.scaleInPlace(tK.Lerp(l,h,i)),r}static SmoothToRef(e,t,i,r,s){return t5.SlerpToRef(e,t,0===r?1:i/r,s),s}static FromArray(e,t=0){return new t5(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return t5.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return t5.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new t5(0,0,0)}static One(){return new t5(1,1,1)}static Up(){return new t5(0,1,0)}static get UpReadOnly(){return t5._UpReadOnly}static get DownReadOnly(){return t5._DownReadOnly}static get RightReadOnly(){return t5._RightReadOnly}static get LeftReadOnly(){return t5._LeftReadOnly}static get LeftHandedForwardReadOnly(){return t5._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return t5._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return t5._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return t5._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return t5._ZeroReadOnly}static get OneReadOnly(){return t5._OneReadOnly}static Down(){return new t5(0,-1,0)}static Forward(e=!1){return new t5(0,0,e?-1:1)}static Backward(e=!1){return new t5(0,0,e?1:-1)}static Right(){return new t5(1,0,0)}static Left(){return new t5(-1,0,0)}static Random(e=0,t=1){return new t5(tK.RandomRange(e,t),tK.RandomRange(e,t),tK.RandomRange(e,t))}static TransformCoordinates(e,t){let i=t5.Zero();return t5.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return t5.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let n=r.m,a=e*n[0]+t*n[4]+i*n[8]+n[12],o=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=1/(e*n[3]+t*n[7]+i*n[11]+n[15]);return s._x=a*h,s._y=o*h,s._z=l*h,s._isDirty=!0,s}static TransformNormal(e,t){let i=t5.Zero();return t5.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){let n=r.m;return s._x=e*n[0]+t*n[4]+i*n[8],s._y=e*n[1]+t*n[5]+i*n[9],s._z=e*n[2]+t*n[6]+i*n[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){let n=s*s,a=s*n,o=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*n+(-e._x+3*t._x-3*i._x+r._x)*a),l=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*n+(-e._y+3*t._y-3*i._y+r._y)*a),h=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*n+(-e._z+3*t._z-3*i._z+r._z)*a);return new e.constructor(o,l,h)}static Clamp(e,t,i){let r=new e.constructor;return t5.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=(s=s>i._x?i._x:s)i._y?i._y:n)i._z?i._z:a)0&&A<0?(I.copyFrom(o),n=t,a=i):A>0&&R<0?(I.copyFrom(h),n=i,a=r):(I.copyFrom(l).scaleInPlace(-1),n=r,a=t);let P=t9.Vector3[9],M=t9.Vector3[4];if(n.subtractToRef(x,S),a.subtractToRef(x,P),t5.CrossToRef(S,P,M),!(0>t5.Dot(M,u)))return s.copyFrom(x),Math.abs(m*g);let D=t9.Vector3[5];t5.CrossToRef(I,M,D),D.normalize();let O=t9.Vector3[9];O.copyFrom(n).subtractInPlace(x);let N=O.length();if(N<.001)return s.copyFrom(n),t5.Distance(e,n);O.normalizeFromLength(N);let F=t5.Dot(D,O),w=t9.Vector3[7];w.copyFrom(x).addInPlace(D.scaleInPlace(N*F)),S.copyFrom(w).subtractInPlace(n),m=I.length(),I.normalizeFromLength(m);let L=t5.Dot(S,I)/Math.max(m,.001);return L=tK.Clamp(L,0,1),w.copyFrom(n).addInPlace(I.scaleInPlace(L*m)),s.copyFrom(w),t5.Distance(e,w)}static Center(e,t){return t5.CenterToRef(e,t,t5.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,i){let r=new e.constructor;return t5.RotationFromAxisToRef(e,t,i,r),r}static RotationFromAxisToRef(e,t,i,r){let s=t9.Quaternion[0];return t8.RotationQuaternionFromAxisToRef(e,t,i,s),s.toEulerAnglesToRef(r),r}}t5._UpReadOnly=t5.Up(),t5._DownReadOnly=t5.Down(),t5._LeftHandedForwardReadOnly=t5.Forward(!1),t5._RightHandedForwardReadOnly=t5.Forward(!0),t5._LeftHandedBackwardReadOnly=t5.Backward(!1),t5._RightHandedBackwardReadOnly=t5.Backward(!0),t5._RightReadOnly=t5.Right(),t5._LeftReadOnly=t5.Left(),t5._ZeroReadOnly=t5.Zero(),t5._OneReadOnly=t5.One();class t6{constructor(e=0,t=0,i=0,r=0){this.x=e,this.y=t,this.z=i,this.w=r}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let e=t3(this.x),t=t3(this.y),i=t3(this.z),r=t3(this.w),s=e;return 397*(s=397*(s=397*s^t)^i)^r}asArray(){let e=[];return this.toArray(e,0),e}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 t6.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}add(e){return new this.constructor(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 this.constructor(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,i,r){return new this.constructor(this.x-e,this.y-t,this.z-i,this.w-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.x=this.x-e,s.y=this.y-t,s.z=this.z-i,s.w=this.w-r,s}negate(){return new this.constructor(-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.copyFromFloats(-1*this.x,-1*this.y,-1*this.z,-1*this.w)}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new this.constructor(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=.001){return e&&tK.WithinEpsilon(this.x,e.x,t)&&tK.WithinEpsilon(this.y,e.y,t)&&tK.WithinEpsilon(this.z,e.z,t)&&tK.WithinEpsilon(this.w,e.w,t)}equalsToFloats(e,t,i,r){return this.x===e&&this.y===t&&this.z===i&&this.w===r}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new this.constructor(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,i,r){return new this.constructor(this.x*e,this.y*t,this.z*i,this.w*r)}divide(e){return new this.constructor(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.xthis.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}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(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(){let e=new this.constructor(0,0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return 0===t||1===t?e.copyFromFloats(this.x,this.y,this.z,this.w):this.scaleToRef(1/t,e)}toVector3(){return new t5(this.x,this.y,this.z)}clone(){return new this.constructor(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,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}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 t6(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return t6.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new t6(0,0,0,0)}static One(){return new t6(1,1,1,1)}static Random(e=0,t=1){return new t6(tK.RandomRange(e,t),tK.RandomRange(e,t),tK.RandomRange(e,t),tK.RandomRange(e,t))}static get ZeroReadOnly(){return t6._ZeroReadOnly}static Normalize(e){let t=t6.Zero();return t6.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){let i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){let i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(t6.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,n=e.w-t.w;return i*i+r*r+s*s+n*n}static Center(e,t){return t6.CenterToRef(e,t,t6.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}static TransformCoordinates(e,t){let i=t6.Zero();return t6.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return t6.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let n=r.m,a=e*n[0]+t*n[4]+i*n[8]+n[12],o=e*n[1]+t*n[5]+i*n[9]+n[13],l=e*n[2]+t*n[6]+i*n[10]+n[14],h=e*n[3]+t*n[7]+i*n[11]+n[15];return s.x=a,s.y=o,s.z=l,s.w=h,s}static TransformNormal(e,t){let i=new e.constructor;return t6.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],n=e.x*r[1]+e.y*r[5]+e.z*r[9],a=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=n,i.z=a,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,n){let a=s.m;return n.x=e*a[0]+t*a[4]+i*a[8],n.y=e*a[1]+t*a[5]+i*a[9],n.z=e*a[2]+t*a[6]+i*a[10],n.w=r,n}static FromVector3(e,t=0){return new t6(e._x,e._y,e._z,t)}static Dot(e,t){return e.dot(t)}}t6._ZeroReadOnly=t6.Zero();class t8{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,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=t3(this._x),t=t3(this._y),i=t3(this._z),r=t3(this._w),s=e;return 397*(s=397*(s=397*s^t)^i)^r}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}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=.001){return e&&tK.WithinEpsilon(this._x,e._x,t)&&tK.WithinEpsilon(this._y,e._y,t)&&tK.WithinEpsilon(this._z,e._z,t)&&tK.WithinEpsilon(this._w,e._w,t)}clone(){return new this.constructor(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,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}add(e){return new this.constructor(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}subtract(e){return new this.constructor(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 this.constructor(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){let t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){let i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=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(i,r,s,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}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 this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){let e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();let 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(){let e=new this.constructor(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){let e=t5.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,n=r*t-i*s;if(n<-.4999999)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>.4999999)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{let a=s*s,o=t*t,l=i*i,h=r*r;e._z=Math.atan2(2*(i*r+t*s),-o-l+h+a),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*i+r*s),o-l-h+a),e._isDirty=!0}return e}toRotationMatrix(e){return t7.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return t8.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){let t=new t8;return t8.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){let i;let r=e.m,s=r[0],n=r[4],a=r[8],o=r[1],l=r[5],h=r[9],u=r[2],c=r[6],d=r[10],p=s+l+d;return p>0?(i=.5/Math.sqrt(p+1),t._w=.25/i,t._x=(c-h)*i,t._y=(a-u)*i,t._z=(o-n)*i):s>l&&s>d?(i=2*Math.sqrt(1+s-l-d),t._w=(c-h)/i,t._x=.25*i,t._y=(n+o)/i,t._z=(a+u)/i):l>d?(i=2*Math.sqrt(1+l-s-d),t._w=(a-u)/i,t._x=(n+o)/i,t._y=.25*i,t._z=(h+c)/i):(i=2*Math.sqrt(1+d-s-l),t._w=(o-n)/i,t._x=(a+u)/i,t._y=(h+c)/i,t._z=.25*i),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,i=.1){let r=t8.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let n=0===r?1:i/r;return n=tK.Clamp(n,0,1),t8.SlerpToRef(e,t,n,s),s}static Zero(){return new t8(0,0,0,0)}static Inverse(e){return new e.constructor(-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 t8(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 t8.RotationAxisToRef(e,t,new t8)}static RotationAxisToRef(e,t,i){let r=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new t8(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromEulerAngles(e,t,i){let r=new t8;return t8.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return t8.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){let t=new t8;return t8.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return t8.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,r=.001){let s=t5.Dot(e,t)+1;return sMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(t5.CrossToRef(e,t,ie.Vector3[0]),i.set(ie.Vector3[0].x,ie.Vector3[0].y,ie.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){let r=new t8;return t8.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){let s=.5*i,n=.5*t,a=.5*e,o=Math.sin(s),l=Math.cos(s),h=Math.sin(n),u=Math.cos(n),c=Math.sin(a),d=Math.cos(a);return r._x=d*h*l+c*u*o,r._y=c*u*l-d*h*o,r._z=d*u*o-c*h*l,r._w=d*u*l+c*h*o,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){let r=new t8;return t8.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){let s=(i+e)*.5,n=(i-e)*.5,a=.5*t;return r._x=Math.cos(n)*Math.sin(a),r._y=Math.sin(n)*Math.sin(a),r._z=Math.sin(s)*Math.cos(a),r._w=Math.cos(s)*Math.cos(a),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){let r=new t8(0,0,0,0);return t8.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){let s=t9.Matrix[0];return t7.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),s),t8.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){let i=new t8;return t8.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){let r=t9.Matrix[0];return t7.LookDirectionLHToRef(e,t,r),t8.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){let i=new t8;return t8.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){let r=t9.Matrix[0];return t7.LookDirectionRHToRef(e,t,r),t8.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){let r=t8.Identity();return t8.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,n;let 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-i,s=o?-i:i;else{let e=Math.acos(a),t=1/Math.sin(e);n=Math.sin((1-i)*e)*t,s=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return r._x=n*e._x+s*t._x,r._y=n*e._y+s*t._y,r._z=n*e._z+s*t._z,r._w=n*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,c=e._x*o+i._x*l+t._x*h+r._x*u,d=e._y*o+i._y*l+t._y*h+r._y*u,p=e._z*o+i._z*l+t._z*h+r._z*u,_=e._w*o+i._w*l+t._w*h+r._w*u;return new e.constructor(c,d,p,_)}static Hermite1stDerivative(e,t,i,r,s){let n=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;return n._x=(a-s)*6*e._x+(3*a-4*s+1)*t._x+(-a+s)*6*i._x+(3*a-2*s)*r._x,n._y=(a-s)*6*e._y+(3*a-4*s+1)*t._y+(-a+s)*6*i._y+(3*a-2*s)*r._y,n._z=(a-s)*6*e._z+(3*a-4*s+1)*t._z+(-a+s)*6*i._z+(3*a-2*s)*r._z,n._w=(a-s)*6*e._w+(3*a-4*s+1)*t._w+(-a+s)*6*i._w+(3*a-2*s)*r._w,n._isDirty=!0,n}static Normalize(e){let t=t8.Zero();return t8.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}}class t7{static get Use64Bits(){return t1.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=t7._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,t1.MatrixTrackPrecisionChange&&t1.MatrixTrackedMatrices.push(this),this._m=new t1.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let 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]?this._isIdentity3x2=!1: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;let e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],n=e[4],a=e[5],o=e[6],l=e[7],h=e[8],u=e[9],c=e[10],d=e[11],p=e[12],_=e[13],f=e[14],m=e[15],g=c*m-f*d,v=u*m-_*d,x=u*f-_*c,T=h*m-p*d,b=h*f-c*p,E=h*_-p*u;return t*+(a*g-o*v+l*x)+-(i*(n*g-o*T+l*b))+r*+(n*v-a*T+l*E)+-(s*(n*x-a*b+o*E))}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} +${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} +${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} +${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return t7.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){let t=new this.constructor;return this.addToRef(e,t),t}addToRef(e,t){let i=this._m,r=t._m,s=e.m;for(let e=0;e<16;e++)r[e]=i[e]+s[e];return t.markAsUpdated(),t}addToSelf(e){let t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}invertToRef(e){if(!0===this._isIdentity)return t7.IdentityToRef(e),e;let t=this._m,i=t[0],r=t[1],s=t[2],n=t[3],a=t[4],o=t[5],l=t[6],h=t[7],u=t[8],c=t[9],d=t[10],p=t[11],_=t[12],f=t[13],m=t[14],g=t[15],v=d*g-m*p,x=c*g-f*p,T=c*m-f*d,b=u*g-_*p,E=u*m-d*_,S=u*f-_*c,C=+(o*v-l*x+h*T),y=-(a*v-l*b+h*E),A=+(a*x-o*b+h*S),R=-(a*T-o*E+l*S),I=i*C+r*y+s*A+n*R;if(0===I)return e.copyFrom(this),e;let P=1/I,M=l*g-m*h,D=o*g-f*h,O=o*m-f*l,N=a*g-_*h,F=a*m-_*l,w=a*f-_*o,L=l*p-d*h,B=o*p-c*h,U=o*d-c*l,V=a*p-u*h,k=a*d-u*l,G=a*c-u*o;return t7.FromValuesToRef(C*P,-(r*v-s*x+n*T)*P,+(r*M-s*D+n*O)*P,-(r*L-s*B+n*U)*P,y*P,+(i*v-s*b+n*E)*P,-(i*M-s*N+n*F)*P,+(i*L-s*V+n*k)*P,A*P,-(i*x-r*b+n*S)*P,+(i*D-r*N+n*w)*P,-(i*B-r*V+n*G)*P,R*P,+(i*T-r*E+s*S)*P,-(i*O-r*F+s*w)*P,+(i*U-r*k+s*G)*P,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,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new t5(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(){let e=this.m;return t7.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}multiply(e){let t=new this.constructor;return this.multiplyToRef(e,t),t}copyFrom(e){return e.copyToArray(this._m),this.updateFlag=e.updateFlag,this._updateIdentityStatus(e._isIdentity,e._isIdentityDirty,e._isIdentity3x2,e._isIdentity3x2Dirty),this}copyToArray(e,t=0){let i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiplyToRef(e,t){return this._isIdentity?t.copyFrom(e):e._isIdentity?t.copyFrom(this):(this.multiplyToArray(e,t._m,0),t.markAsUpdated()),t}multiplyToArray(e,t,i){let r=this._m,s=e.m,n=r[0],a=r[1],o=r[2],l=r[3],h=r[4],u=r[5],c=r[6],d=r[7],p=r[8],_=r[9],f=r[10],m=r[11],g=r[12],v=r[13],x=r[14],T=r[15],b=s[0],E=s[1],S=s[2],C=s[3],y=s[4],A=s[5],R=s[6],I=s[7],P=s[8],M=s[9],D=s[10],O=s[11],N=s[12],F=s[13],w=s[14],L=s[15];return t[i]=n*b+a*y+o*P+l*N,t[i+1]=n*E+a*A+o*M+l*F,t[i+2]=n*S+a*R+o*D+l*w,t[i+3]=n*C+a*I+o*O+l*L,t[i+4]=h*b+u*y+c*P+d*N,t[i+5]=h*E+u*A+c*M+d*F,t[i+6]=h*S+u*R+c*D+d*w,t[i+7]=h*C+u*I+c*O+d*L,t[i+8]=p*b+_*y+f*P+m*N,t[i+9]=p*E+_*A+f*M+m*F,t[i+10]=p*S+_*R+f*D+m*w,t[i+11]=p*C+_*I+f*O+m*L,t[i+12]=g*b+v*y+x*P+T*N,t[i+13]=g*E+v*A+x*M+T*F,t[i+14]=g*S+v*R+x*D+T*w,t[i+15]=g*C+v*I+x*O+T*L,this}equals(e){if(!e)return!1;if((this._isIdentity||e._isIdentity)&&!this._isIdentityDirty&&!e._isIdentityDirty)return this._isIdentity&&e._isIdentity;let t=this.m,i=e.m;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]}clone(){let e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=t3(this._m[0]);for(let t=1;t<16;t++)e=397*e^t3(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new t8,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r,s=!0){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;let n=this._m;if(i&&i.copyFromFloats(n[12],n[13],n[14]),(e=e||t9.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]),r){let t=(s?r.absoluteScaling.x:r.scaling.x)<0?-1:1,i=(s?r.absoluteScaling.y:r.scaling.y)<0?-1:1,n=(s?r.absoluteScaling.z:r.scaling.z)<0?-1:1;e.x*=t,e.y*=i,e.z*=n}else 0>=this.determinant()&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){let i=1/e._x,r=1/e._y,s=1/e._z;t7.FromValuesToRef(n[0]*i,n[1]*i,n[2]*i,0,n[4]*r,n[5]*r,n[6]*r,0,n[8]*s,n[9]*s,n[10]*s,0,0,0,0,1,t9.Matrix[0]),t8.FromRotationMatrixToRef(t9.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;let t=4*e;return new t6(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){let i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){let e=new this.constructor;return t7.TransposeToRef(this,e),e}transposeToRef(e){return t7.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;let n=4*e;return this._m[n+0]=t,this._m[n+1]=i,this._m[n+2]=r,this._m[n+3]=s,this.markAsUpdated(),this}scale(e){let t=new this.constructor;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}toNormalMatrix(e){let t=t9.Matrix[0];this.invertToRef(t),t.transposeToRef(e);let i=e._m;return t7.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){let e=new this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){let t=t9.Vector3[0];if(!this.decompose(t))return t7.IdentityToRef(e),e;let i=this._m,r=1/t._x,s=1/t._y,n=1/t._z;return t7.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,0,i[8]*n,i[9]*n,i[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){let e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){let i=new t7;return t7.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){for(let s=0;s<16;s++)r._m[s]=e[s+t]*i;return r.markAsUpdated(),r}static get IdentityReadOnly(){return t7._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m){let g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=s,g[5]=n,g[6]=a,g[7]=o,g[8]=l,g[9]=h,g[10]=u,g[11]=c,g[12]=d,g[13]=p,g[14]=_,g[15]=f,m.markAsUpdated()}static FromValues(e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f){let m=new t7,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=s,g[5]=n,g[6]=a,g[7]=o,g[8]=l,g[9]=h,g[10]=u,g[11]=c,g[12]=d,g[13]=p,g[14]=_,g[15]=f,m.markAsUpdated(),m}static Compose(e,t,i){let r=new t7;return t7.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){let s=r._m,n=t._x,a=t._y,o=t._z,l=t._w,h=n+n,u=a+a,c=o+o,d=n*h,p=n*u,_=n*c,f=a*u,m=a*c,g=o*c,v=l*h,x=l*u,T=l*c,b=e._x,E=e._y,S=e._z;return s[0]=(1-(f+g))*b,s[1]=(p+T)*b,s[2]=(_-x)*b,s[3]=0,s[4]=(p-T)*E,s[5]=(1-(d+g))*E,s[6]=(m+v)*E,s[7]=0,s[8]=(_+x)*S,s[9]=(m-v)*S,s[10]=(1-(d+f))*S,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){let e=t7.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 t7.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){let e=t7.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){let t=new t7;return t7.RotationXToRef(e,t),t}static Invert(e){let t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return t7.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationY(e){let t=new t7;return t7.RotationYToRef(e,t),t}static RotationYToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return t7.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationZ(e){let t=new t7;return t7.RotationZToRef(e,t),t}static RotationZToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return t7.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationAxis(e,t){let i=new t7;return t7.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){let r=Math.sin(-t),s=Math.cos(-t),n=1-s;e.normalize();let a=i._m;return a[0]=e._x*e._x*n+s,a[1]=e._x*e._y*n-e._z*r,a[2]=e._x*e._z*n+e._y*r,a[3]=0,a[4]=e._y*e._x*n+e._z*r,a[5]=e._y*e._y*n+s,a[6]=e._y*e._z*n-e._x*r,a[7]=0,a[8]=e._z*e._x*n-e._y*r,a[9]=e._z*e._y*n+e._x*r,a[10]=e._z*e._z*n+s,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,r=!1){let s=t5.Dot(t,e),n=i._m;if(s<-.999)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=r?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=r?-1:1,n[11]=0;else{let i=t5.Cross(t,e),r=1/(1+s);n[0]=i._x*i._x*r+s,n[1]=i._y*i._x*r-i._z,n[2]=i._z*i._x*r+i._y,n[3]=0,n[4]=i._x*i._y*r+i._z,n[5]=i._y*i._y*r+s,n[6]=i._z*i._y*r-i._x,n[7]=0,n[8]=i._x*i._z*r-i._y,n[9]=i._y*i._z*r+i._x,n[10]=i._z*i._z*r+s,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){let r=new t7;return t7.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return t8.RotationYawPitchRollToRef(e,t,i,t9.Quaternion[0]),t9.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){let r=new t7;return t7.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return t7.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(1===e&&1===t&&1===i),r}static Translation(e,t,i){let r=new t7;return t7.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return t7.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(0===e&&0===t&&0===i),r}static Lerp(e,t,i){let r=new e.constructor;return t7.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){let s=r._m,n=e.m,a=t.m;for(let e=0;e<16;e++)s[e]=n[e]*(1-i)+a[e]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){let r=new e.constructor;return t7.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){let s=t9.Vector3[0],n=t9.Quaternion[0],a=t9.Vector3[1];e.decompose(s,n,a);let o=t9.Vector3[2],l=t9.Quaternion[1],h=t9.Vector3[3];t.decompose(o,l,h);let u=t9.Vector3[4];t5.LerpToRef(s,o,i,u);let c=t9.Quaternion[2];t8.SlerpToRef(n,l,i,c);let d=t9.Vector3[5];return t5.LerpToRef(a,h,i,d),t7.ComposeToRef(u,c,d,r),r}static LookAtLH(e,t,i){let r=new t7;return t7.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){let s=t9.Vector3[0],n=t9.Vector3[1],a=t9.Vector3[2];t.subtractToRef(e,a),a.normalize(),t5.CrossToRef(i,a,s);let o=s.lengthSquared();0===o?s.x=1:s.normalizeFromLength(Math.sqrt(o)),t5.CrossToRef(a,s,n),n.normalize();let l=-t5.Dot(s,e),h=-t5.Dot(n,e),u=-t5.Dot(a,e);return t7.FromValuesToRef(s._x,n._x,a._x,0,s._y,n._y,a._y,0,s._z,n._z,a._z,0,l,h,u,1,r),r}static LookAtRH(e,t,i){let r=new t7;return t7.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){let s=t9.Vector3[0],n=t9.Vector3[1],a=t9.Vector3[2];e.subtractToRef(t,a),a.normalize(),t5.CrossToRef(i,a,s);let o=s.lengthSquared();0===o?s.x=1:s.normalizeFromLength(Math.sqrt(o)),t5.CrossToRef(a,s,n),n.normalize();let l=-t5.Dot(s,e),h=-t5.Dot(n,e),u=-t5.Dot(a,e);return t7.FromValuesToRef(s._x,n._x,a._x,0,s._y,n._y,a._y,0,s._z,n._z,a._z,0,l,h,u,1,r),r}static LookDirectionLH(e,t){let i=new t7;return t7.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){let r=t9.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);let s=t9.Vector3[1];return t5.CrossToRef(t,r,s),t7.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){let i=new t7;return t7.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){let r=t9.Vector3[2];return t5.CrossToRef(t,e,r),t7.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){let n=new t7;return t7.OrthoLHToRef(e,t,i,r,n,s),n}static OrthoLHToRef(e,t,i,r,s,n){let a=2/e,o=2/t,l=2/(r-i),h=-(r+i)/(r-i);return t7.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,l,0,0,0,h,1,s),n&&s.multiplyToRef(it,s),s._updateIdentityStatus(1===a&&1===o&&1===l&&0===h),s}static OrthoOffCenterLH(e,t,i,r,s,n,a){let o=new t7;return t7.OrthoOffCenterLHToRef(e,t,i,r,s,n,o,a),o}static OrthoOffCenterLHToRef(e,t,i,r,s,n,a,o){return t7.FromValuesToRef(2/(t-e),0,0,0,0,2/(r-i),0,0,0,0,2/(n-s),0,(e+t)/(e-t),(r+i)/(i-r),-(n+s)/(n-s),1,a),o&&a.multiplyToRef(it,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,i,r,s,n,a,o,l,h,u){let c=-a*Math.cos(o),d=-a*Math.sin(o);return t7.TranslationToRef(0,0,-l,t9.Matrix[1]),t7.FromValuesToRef(1,0,0,0,0,1,0,0,c,d,1,0,0,0,0,1,t9.Matrix[0]),t9.Matrix[1].multiplyToRef(t9.Matrix[0],t9.Matrix[0]),t7.TranslationToRef(0,0,l,t9.Matrix[1]),t9.Matrix[0].multiplyToRef(t9.Matrix[1],t9.Matrix[0]),t7.OrthoOffCenterLHToRef(e,t,i,r,s,n,h,u),t9.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,r,s,n,a){let o=new t7;return t7.OrthoOffCenterRHToRef(e,t,i,r,s,n,o,a),o}static OrthoOffCenterRHToRef(e,t,i,r,s,n,a,o){return t7.OrthoOffCenterLHToRef(e,t,i,r,s,n,a,o),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,i,r,s,n,a,o,l,h,u){let c=a*Math.cos(o),d=a*Math.sin(o);return t7.TranslationToRef(0,0,l,t9.Matrix[1]),t7.FromValuesToRef(1,0,0,0,0,1,0,0,c,d,1,0,0,0,0,1,t9.Matrix[0]),t9.Matrix[1].multiplyToRef(t9.Matrix[0],t9.Matrix[0]),t7.TranslationToRef(0,0,-l,t9.Matrix[1]),t9.Matrix[0].multiplyToRef(t9.Matrix[1],t9.Matrix[0]),t7.OrthoOffCenterRHToRef(e,t,i,r,s,n,h,u),t9.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,r,s,n=0){let a=new t7;return t7.FromValuesToRef(2*i/e,0,0,0,0,2*i/t,0,Math.tan(n),0,0,(r+i)/(r-i),1,0,0,-2*r*i/(r-i),0,a),s&&a.multiplyToRef(it,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,i,r,s,n=0,a=!1){let o=new t7;return t7.PerspectiveFovLHToRef(e,t,i,r,o,!0,s,n,a),o}static PerspectiveFovLHToRef(e,t,i,r,s,n=!0,a,o=0,l=!1){let h=1/Math.tan(.5*e),u=n?h/t:h,c=n?h:h*t,d=l&&0===i?-1:0!==r?(r+i)/(r-i):1,p=l&&0===i?2*r:0!==r?-2*r*i/(r-i):-2*i;return t7.FromValuesToRef(u,0,0,0,0,c,0,Math.tan(o),0,0,d,1,0,0,p,0,s),a&&s.multiplyToRef(it,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,n=!0,a,o=0){let l=1/Math.tan(.5*e),h=n?l/t:l,u=n?l:l*t;return t7.FromValuesToRef(h,0,0,0,0,u,0,Math.tan(o),0,0,-i,1,0,0,1,0,s),a&&s.multiplyToRef(it,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,n=0,a=!1){let o=new t7;return t7.PerspectiveFovRHToRef(e,t,i,r,o,!0,s,n,a),o}static PerspectiveFovRHToRef(e,t,i,r,s,n=!0,a,o=0,l=!1){let h=1/Math.tan(.5*e),u=n?h/t:h,c=n?h:h*t,d=l&&0===i?1:0!==r?-(r+i)/(r-i):-1,p=l&&0===i?2*r:0!==r?-2*r*i/(r-i):-2*i;return t7.FromValuesToRef(u,0,0,0,0,c,0,Math.tan(o),0,0,d,-1,0,0,p,0,s),a&&s.multiplyToRef(it,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,n=!0,a,o=0){let l=1/Math.tan(.5*e),h=n?l/t:l,u=n?l:l*t;return t7.FromValuesToRef(h,0,0,0,0,u,0,Math.tan(o),0,0,-i,-1,0,0,-1,0,s),a&&s.multiplyToRef(it,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,n){let a=e.width,o=e.height,l=e.x,h=e.y,u=t7.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,n-s,0,l+a/2,o/2+h,s,1),c=new t.constructor;return t.multiplyToRef(i,c),c.multiplyToRef(r,c),c.multiplyToRef(u,c)}static GetAsMatrix2x2(e){let t=e.m,i=[t[0],t[1],t[4],t[5]];return t1.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){let t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return t1.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){let t=new e.constructor;return t7.TransposeToRef(e,t),t}static TransposeToRef(e,t){let i=e.m,r=i[0],s=i[4],n=i[8],a=i[12],o=i[1],l=i[5],h=i[9],u=i[13],c=i[2],d=i[6],p=i[10],_=i[14],f=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=r,x[1]=s,x[2]=n,x[3]=a,x[4]=o,x[5]=l,x[6]=h,x[7]=u,x[8]=c,x[9]=d,x[10]=p,x[11]=_,x[12]=f,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){let t=new t7;return t7.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();let i=e.normal.x,r=e.normal.y,s=e.normal.z,n=-2*i,a=-2*r,o=-2*s;return t7.FromValuesToRef(n*i+1,a*i,o*i,0,n*r,a*r+1,o*r,0,n*s,a*s,o*s+1,0,n*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return t7.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){let i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,n=e._x*e._y,a=e._z*e._w,o=e._z*e._x,l=e._y*e._w,h=e._y*e._z,u=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(n+a),t._m[2]=2*(o-l),t._m[3]=0,t._m[4]=2*(n-a),t._m[5]=1-2*(s+i),t._m[6]=2*(h+u),t._m[7]=0,t._m[8]=2*(o+l),t._m[9]=2*(h-u),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}t7._UpdateFlagSeed=0,t7._IdentityReadOnly=t7.Identity();class t9{}t9.Vector3=tQ.BuildTuple(11,t5.Zero),t9.Matrix=tQ.BuildTuple(2,t7.Identity),t9.Quaternion=tQ.BuildTuple(3,t8.Zero);class ie{}ie.Vector2=tQ.BuildTuple(3,t4.Zero),ie.Vector3=tQ.BuildTuple(13,t5.Zero),ie.Vector4=tQ.BuildTuple(3,t6.Zero),ie.Quaternion=tQ.BuildTuple(2,t8.Zero),ie.Matrix=tQ.BuildTuple(8,t7.Identity),t0["BABYLON.Vector2"]=t4,t0["BABYLON.Vector3"]=t5,t0["BABYLON.Vector4"]=t6,t0["BABYLON.Matrix"]=t7;let it=t7.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);function ii(e){return Math.pow(e,2.2)}function ir(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function is(e){return Math.pow(e,t$)}function ia(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}class io{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return 397*(e=397*e^(255*this.g|0))^(255*this.b|0)}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 io.FromArrayToRef(e,t,this),this}toColor4(e=1){return new il(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 io(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,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new io(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=tK.Clamp(this.r,e,t),i.g=tK.Clamp(this.g,e,t),i.b=tK.Clamp(this.b,e,t),this}add(e){return new io(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new io(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,this}clone(){return new io(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,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}toHexString(){let e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+tK.ToHex(e)+tK.ToHex(t)+tK.ToHex(i)}toHSV(){let e=new io;return this.toHSVToRef(e),e}toHSVToRef(e){let t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),n=Math.min(t,i,r),a=0,o=0,l=s-n;0!==s&&(o=l/s),s!=n&&(s==t?(a=(i-r)/l,i=0&&n<=1?(o=s,l=a):n>=1&&n<=2?(o=a,l=s):n>=2&&n<=3?(l=s,h=a):n>=3&&n<=4?(l=a,h=s):n>=4&&n<=5?(o=a,h=s):n>=5&&n<=6&&(o=s,h=a);let u=i-s;r.set(o+u,l+u,h+u)}static FromHSV(e,t,i){let r=new io(0,0,0);return io.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new io(0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return io.FromInts(t,i,r)}static FromArray(e,t=0){return new io(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new io(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new io(0,0,0);return io.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n;return new io(e.r*o+i.r*l+t.r*h+r.r*u,e.g*o+i.g*l+t.g*h+r.g*u,e.b*o+i.b*l+t.b*h+r.b*u)}static Hermite1stDerivative(e,t,i,r,s){let n=io.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b}static Red(){return new io(1,0,0)}static Green(){return new io(0,1,0)}static Blue(){return new io(0,0,1)}static Black(){return new io(0,0,0)}static get BlackReadOnly(){return io._BlackReadOnly}static White(){return new io(1,1,1)}static Purple(){return new io(.5,0,.5)}static Magenta(){return new io(1,0,1)}static Yellow(){return new io(1,1,0)}static Gray(){return new io(.5,.5,.5)}static Teal(){return new io(0,1,1)}static Random(){return new io(Math.random(),Math.random(),Math.random())}}io._BlackReadOnly=io.Black();class il{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}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 il.FromArrayToRef(e,t,this),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 il(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new il(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,this}scale(e){return new il(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=tK.Clamp(this.r,e,t),i.g=tK.Clamp(this.g,e,t),i.b=tK.Clamp(this.b,e,t),i.a=tK.Clamp(this.a,e,t),this}multiply(e){return new il(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}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 397*(e=397*(e=397*e^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)}clone(){return new il(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}toHexString(e=!1){let t=Math.round(255*this.r),i=Math.round(255*this.g),r=Math.round(255*this.b);if(e)return"#"+tK.ToHex(t)+tK.ToHex(i)+tK.ToHex(r);let s=Math.round(255*this.a);return"#"+tK.ToHex(t)+tK.ToHex(i)+tK.ToHex(r)+tK.ToHex(s)}toLinearSpace(e=!1){let t=new il;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=ir(this.r),e.g=ir(this.g),e.b=ir(this.b)):(e.r=ii(this.r),e.g=ii(this.g),e.b=ii(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new il;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=ia(this.r),e.g=ia(this.g),e.b=ia(this.b)):(e.r=is(this.r),e.g=is(this.g),e.b=is(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new il(0,0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return il.FromInts(t,i,r,s)}static Lerp(e,t,i){let r=new il(0,0,0,0);return il.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,c=e.r*o+i.r*l+t.r*h+r.r*u;return new il(c,e.g*o+i.g*l+t.g*h+r.g*u,e.b*o+i.b*l+t.b*h+r.b*u,e.a*o+i.a*l+t.a*h+r.a*u)}static Hermite1stDerivative(e,t,i,r,s){let n=new il;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b,n.a=(a-s)*6*e.a+(3*a-4*s+1)*t.a+(-a+s)*6*i.a+(3*a-2*s)*r.a}static FromColor3(e,t=1){return new il(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new il(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new il(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){let t=[];for(let i=0;inew il(0,0,0,0)),t0["BABYLON.Color3"]=io,t0["BABYLON.Color4"]=il;class iu{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new tj,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){let e=this._condition;if(!e)return!0;let t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){}_serialize(e,t){let i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){let e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}iu._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof t4?e.x+", "+e.y:e instanceof t5?e.x+", "+e.y+", "+e.z:e instanceof io?e.r+", "+e.g+", "+e.b:e instanceof il?e.r+", "+e.g+", "+e.b+", "+e.a:e,iu._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),t0["BABYLON.Action"]=iu;class ic{constructor(e,t,i,r,s,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=n}static CreateNew(e,t,i){let r=e.getScene();return new ic(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new ic(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new ic(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new ic(e,t.x,t.y,null,i,r)}}class id{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class ip extends id{static get IsEqual(){return ip._IsEqual}static get IsDifferent(){return ip._IsDifferent}static get IsGreater(){return ip._IsGreater}static get IsLesser(){return ip._IsLesser}constructor(e,t,i,r,s=ip.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case ip.IsGreater:return this._effectiveTarget[this._property]>this.value;case ip.IsLesser:return this._effectiveTarget[this._property]e<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){let r=Array.isArray(t)?t[0]:t;if(void 0!==i&&!ig._CheckLimit(r,i))return;let s=ig._FormatMessage(r),n=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+s,...a);let o=`
${s}

`;ig._AddLogEntry(o),ig._GenerateLimitMessage(r,e)}static get LogCache(){return ig._LogCache}static ClearLogCache(){ig._LogCache="",ig._LogLimitOutputs={},ig.errorsCount=0}static set LogLevels(e){ig.Log=ig._LogDisabled,ig.Warn=ig._LogDisabled,ig.Error=ig._LogDisabled,[ig.MessageLogLevel,ig.WarningLogLevel,ig.ErrorLogLevel].forEach(t=>{(e&t)===t&&(ig[this._Levels[t].name]=ig._LogEnabled.bind(ig,t))})}}ig.NoneLogLevel=0,ig.MessageLogLevel=1,ig.WarningLogLevel=2,ig.ErrorLogLevel=4,ig.AllLogLevel=7,ig.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",ig._LogCache="",ig._LogLimitOutputs={},ig._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],ig.errorsCount=0,ig.Log=ig._LogEnabled.bind(ig,ig.MessageLogLevel),ig.Warn=ig._LogEnabled.bind(ig,ig.WarningLogLevel),ig.Error=ig._LogEnabled.bind(ig,ig.ErrorLogLevel);class iv extends iu{constructor(e,t,i,r){super(e,r),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[iu._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}}class ix extends iu{constructor(e,t,i,r){super(e,r),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[iu._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}}class iT extends iu{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[iu._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:iu._SerializeValueAsString(this.value)}]},e)}}class ib extends iu{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&ig.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[iu._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:iu._SerializeValueAsString(this.value)}]},e)}}class iE extends iu{constructor(e,t,i,r,s,n){super(e,n),this.from=i,this.to=r,this.loop=s,this._target=t}_prepare(){}execute(){this._actionManager.getScene().beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[iu._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:iu._SerializeValueAsString(this.loop)||!1}]},e)}}class iS extends iu{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){this._actionManager.getScene().stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[iu._GetTargetProperty(this._target)]},e)}}class iC extends iu{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}}class iy extends iu{constructor(e,t,i,r=!0){super(e,i),this.children=t,this.enableChildrenConditions=r}_prepare(){for(let e=0;e!e||e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&("SubMesh"===e.getClassName()||"PhysicsBody"===e.getClassName())?e.clone(t):e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?Object.assign({},e):null;class iP{static DeepCopy(e,t,i,r,s=!1){for(let n of function(e){let t=[];do Object.getOwnPropertyNames(e).forEach(function(e){-1===t.indexOf(e)&&t.push(e)});while(e=Object.getPrototypeOf(e));return t}(e)){if("_"===n[0]&&(!r||-1===r.indexOf(n))||n.endsWith("Observable")||i&&-1!==i.indexOf(n))continue;let a=e[n],o=typeof a;if("function"!==o)try{if("object"===o){if(a instanceof Uint8Array)t[n]=Uint8Array.from(a);else if(a instanceof Array){if(t[n]=[],a.length>0){if("object"==typeof a[0])for(let e=0;e-1&&this._scene.actionManagers.splice(e,1),this._scene.meshes.filter(e=>e.actionManager===this)))t.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=iM.OnPickTrigger&&t.trigger<=iM.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=iM.OnPickTrigger&&t.trigger<=iM.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===iM.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(ig.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,iM.Triggers[e.trigger]?iM.Triggers[e.trigger]++:iM.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){let t=this.actions.indexOf(e);return -1!==t&&(this.actions.splice(t,1),iM.Triggers[e.trigger]-=1,0===iM.Triggers[e.trigger]&&delete iM.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{let i=t0["BABYLON."+e];return i&&new i(...t)},n=(e,t,i,r)=>{if(null===r){let e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}let s=r.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;let u=[],c=null,d=null,p=e.combine&&e.combine.length>0;if(2===e.type?u.push(r):u.push(t),p){let t=[];for(let i=0;i0){let e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:iM[s.name],parameter:t}}else r=iM[s.name];for(let e=0;e(e=e.slice(1,e.length-1),iN._HandleParenthesisContent(e,t))):iN._HandleParenthesisContent(e,t))||"false"!==e&&iN.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);let r=e.split("||");for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e)){let s=iN._SimplifyNegation(r[e].trim()),n=s.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,()=>"")).length%2?"!":"")).trim())?e="false":"!false"===e&&(e="true"),e}}class iF{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>iF.HasTags(e),e.addTags=t=>iF.AddTagsTo(e,t),e.removeTags=t=>iF.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>iF.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;let t=e._tags;for(let 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)return e._tags;{let t=[];for(let i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach(function(t){iF._AddTagTo(e,t)})}static _AddTagTo(e,t){""===(t=t.trim())||"true"===t||"false"===t||t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(iF.EnableFor(e),e._tags[t]=!0)}static RemoveTagsFrom(e,t){if(!iF.HasTags(e))return;let i=t.split(" ");for(let t in i)iF._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?iF.HasTags(e):iN.Eval(t,t=>iF.HasTags(e)&&e._tags[t]))}}let iw={};function iL(e,t=!1){if(!t||!iw[e])return iw[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}let iB={},iU={},iV=function(e,t,i,r={}){let s=e();iF&&iF.HasTags(t)&&iF.AddTagsTo(s,iF.GetTags(t,!0));let n=ik(s),a={};for(let e in n){let o=n[e],l=t[e],h=o.type;if(null!=l&&("uniqueId"!==e||i$.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:s[e]=l;break;case 1:r.cloneTexturesOnlyOnce&&a[l.uniqueId]?s[e]=a[l.uniqueId]:(s[e]=i||l.isRenderTarget?l:l.clone(),a[l.uniqueId]=s[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[e]=i?l:l.clone()}}return s};function ik(e){let t=e.getClassName();if(iU[t])return iU[t];iU[t]={};let i=iU[t],r=e,s=t;for(;s;){let e;let t=iB[s];for(let e in t)i[e]=t[e];let n=!1;do{if(!(e=Object.getPrototypeOf(r)).getClassName){n=!0;break}if(e.getClassName()!==s)break;r=e}while(e);if(n)break;s=e.getClassName(),r=e}return i}function iG(e,t){return(i,r)=>{let s=function(e){let t=e.getClassName();return iB[t]||(iB[t]={}),iB[t]}(i);s[r]||(s[r]={type:e,sourceName:t})}}function iz(e,t=null){return function(e,t=null){return(i,r)=>{let s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]===t||(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function iW(e){return iG(0,e)}function iH(e){return iG(1,e)}function iX(e){return iG(2,e)}function iY(e){return iG(3,e)}function ij(e){return iG(5,e)}function iK(e){return iG(6,e)}class i${static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{let n=s;if("undefined"!=typeof _native&&_native[t]){let e=_native[t];n=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=n,n(...i)}}i$.AllowLoadingUniqueId=!1,i$._ImageProcessingConfigurationParser=e=>{throw iL("ImageProcessingConfiguration")},i$._FresnelParametersParser=e=>{throw iL("FresnelParameters")},i$._ColorCurvesParser=e=>{throw iL("ColorCurves")},i$._TextureParser=(e,t,i)=>{throw iL("Texture")},iq.filter=function(e){return(t,i,r)=>iq(t,i,r,e)},function(e){e[e.NONE=0]="NONE",e[e.STEP=1]="STEP"}(_||(_={}));class iQ{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new iQ(this.name,this.from,this.to)}}function iZ(e,t,i,r){var s,n=arguments.length,a=n<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,i,r);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(a=(n<3?s(a):n>3?s(t,i,a):s(t,i))||a);return n>3&&a&&Object.defineProperty(t,i,a),a}Object.create,Object.create;class iJ{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new tj,this._onClonedObservable=new tj}}class i0{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):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;let t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){let t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&((void 0===this._parentNode._children||null===this._parentNode._children)&&(this._parentNode._children=[]),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){let 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){this._isDirty=!1,this._nodeDataStorage=new iJ,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new tj,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=t7.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new tj,this._onDisposeObserver=null,this._behaviors=[],this.name=e,this.id=e,this._scene=t||t2.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}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){let 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(let 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={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,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._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):(!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,i){if(this._children)for(let r=0;r(!t||t(e))&&void 0!==e.cullingStrategy),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew i0(e,this.getScene()),this);if(t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i{throw iL("AnimationRange")},i0._NodeConstructors={},iZ([iW()],i0.prototype,"name",void 0),iZ([iW()],i0.prototype,"id",void 0),iZ([iW()],i0.prototype,"uniqueId",void 0),iZ([iW()],i0.prototype,"state",void 0),iZ([iW()],i0.prototype,"metadata",void 0);class i1{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){return 397*(0|this.width)^(0|this.height)}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 i1(this.width*e,this.height*t)}clone(){return new i1(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 i1(0,0)}add(e){return new i1(this.width+e.width,this.height+e.height)}subtract(e){return new i1(this.width-e.width,this.height-e.height)}scale(e){return new i1(this.width*e,this.height*e)}static Lerp(e,t,i){return new i1(e.width+(t.width-e.width)*i,e.height+(t.height-e.height)*i)}}class i2{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(i2.CustomRequestHeaders).length>0||i2.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(let e in i2.CustomRequestHeaders){let t=i2.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return i2.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,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){i2.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(let e of i2.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}return 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)}}i2.CustomRequestHeaders={},i2.CustomRequestModifiers=[],i2.SkipRequestModificationForBabylonCDN=!0;let i3=Object.freeze(new t8(0,0,0,0)),i4=Object.freeze(t5.Zero()),i5=Object.freeze(t4.Zero()),i6=Object.freeze(i1.Zero()),i8=Object.freeze(io.Black()),i7=Object.freeze(new il(0,0,0,0)),i9={key:0,repeatCount:0,loopMode:2};class re{static _PrepareAnimation(e,t,i,r,s,n,a,o){let l;if(!isNaN(parseFloat(s))&&isFinite(s)?l=re.ANIMATIONTYPE_FLOAT:s instanceof t8?l=re.ANIMATIONTYPE_QUATERNION:s instanceof t5?l=re.ANIMATIONTYPE_VECTOR3:s instanceof t4?l=re.ANIMATIONTYPE_VECTOR2:s instanceof io?l=re.ANIMATIONTYPE_COLOR3:s instanceof il?l=re.ANIMATIONTYPE_COLOR4:s instanceof i1&&(l=re.ANIMATIONTYPE_SIZE),void 0==l)return null;let h=new re(e,t,i,l,a);return h.setKeys([{frame:0,value:s},{frame:r,value:n}]),void 0!==o&&h.setEasingFunction(o),h}static CreateAnimation(e,t,i,r){let s=new re(e+"Animation",e,i,t,re.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,n,a,o,l,h,u){let c=re._PrepareAnimation(e,i,r,s,n,a,o,l);return c&&(t.getScene&&(u=t.getScene()),u)?u.beginDirectAnimation(t,[c],0,s,1===c.loopMode,1,h):null}static CreateAndStartHierarchyAnimation(e,t,i,r,s,n,a,o,l,h,u){let c=re._PrepareAnimation(e,r,s,n,a,o,l,h);return c?t.getScene().beginDirectHierarchyAnimation(t,i,[c],0,n,1===c.loopMode,1,u):null}static CreateMergeAndStartAnimation(e,t,i,r,s,n,a,o,l,h){let u=re._PrepareAnimation(e,i,r,s,n,a,o,l);return u?(t.animations.push(u),t.getScene().beginAnimation(t,0,s,1===u.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,r=!1,s){var n,a;let o;let l=e;if((o="object"==typeof t?t:{referenceFrame:null!=t?t:0,range:i,cloneOriginalAnimation:r,clonedAnimationName:s}).cloneOriginalAnimation&&((l=e.clone()).name=o.clonedAnimationName||l.name),!l._keys.length)return l;let h=o.referenceFrame&&o.referenceFrame>=0?o.referenceFrame:0,u=0,c=l._keys[0],d=l._keys.length-1,p=l._keys[d],_={referenceValue:c.value,referencePosition:ie.Vector3[0],referenceQuaternion:ie.Quaternion[0],referenceScaling:ie.Vector3[1],keyPosition:ie.Vector3[2],keyQuaternion:ie.Quaternion[1],keyScaling:ie.Vector3[3]},f=c.frame,m=p.frame;if(o.range){let e=l.getRange(o.range);e&&(f=e.from,m=e.to)}else f=null!==(n=o.fromFrame)&&void 0!==n?n:f,m=null!==(a=o.toFrame)&&void 0!==a?a:m;if(f!==c.frame&&(u=l.createKeyForFrame(f)),m!==p.frame&&(d=l.createKeyForFrame(m)),1===l._keys.length){let e=l._getKeyValue(l._keys[0]);_.referenceValue=e.clone?e.clone():e}else if(h<=c.frame){let e=l._getKeyValue(c.value);_.referenceValue=e.clone?e.clone():e}else if(h>=p.frame){let e=l._getKeyValue(p.value);_.referenceValue=e.clone?e.clone():e}else{i9.key=0;let e=l._interpolate(h,i9);_.referenceValue=e.clone?e.clone():e}l.dataType===re.ANIMATIONTYPE_QUATERNION?_.referenceValue.normalize().conjugateInPlace():l.dataType===re.ANIMATIONTYPE_MATRIX&&(_.referenceValue.decompose(_.referenceScaling,_.referenceQuaternion,_.referencePosition),_.referenceQuaternion.normalize().conjugateInPlace());let g=Number.MAX_VALUE,v=o.clipKeys?[]:null;for(let e=u;e<=d;e++){let t=l._keys[e];if(v&&(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},g===Number.MAX_VALUE&&(g=t.frame),t.frame-=g,v.push(t)),!e||l.dataType===re.ANIMATIONTYPE_FLOAT||t.value!==c.value)switch(l.dataType){case re.ANIMATIONTYPE_MATRIX:t.value.decompose(_.keyScaling,_.keyQuaternion,_.keyPosition),_.keyPosition.subtractInPlace(_.referencePosition),_.keyScaling.divideInPlace(_.referenceScaling),_.referenceQuaternion.multiplyToRef(_.keyQuaternion,_.keyQuaternion),t7.ComposeToRef(_.keyScaling,_.keyQuaternion,_.keyPosition,t.value);break;case re.ANIMATIONTYPE_QUATERNION:_.referenceValue.multiplyToRef(t.value,t.value);break;case re.ANIMATIONTYPE_VECTOR2:case re.ANIMATIONTYPE_VECTOR3:case re.ANIMATIONTYPE_COLOR3:case re.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(_.referenceValue,t.value);break;case re.ANIMATIONTYPE_SIZE:t.value.width-=_.referenceValue.width,t.value.height-=_.referenceValue.height;break;default:t.value-=_.referenceValue}}return v&&l.setKeys(v,!0),l}static TransitionTo(e,t,i,r,s,n,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;let l=a/1e3*s;n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);let h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=o,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=[],this._events=[],this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=void 0===s?re.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=re._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType]+", nKeys: "+(this._keys?this._keys.length:"none")+", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;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=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let s=this._keys,n=s.length,a=t.key;for(;a>=0&&e=s[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(s[0].value);if(a+1>n-1)return i?void 0:this._getKeyValue(s[n-1].value);let o=s[a],l=s[a+1];if(i&&(e===o.frame||e===l.frame))return;let h=this._getKeyValue(o.value),u=this._getKeyValue(l.value);if(o.interpolation===_.STEP)return l.frame>e?h:u;let c=void 0!==o.outTangent&&void 0!==l.inTangent,d=l.frame-o.frame,p=(e-o.frame)/d,f=o.easingFunction||this.getEasingFunction();switch(null!==f&&(p=f.ease(p)),this.dataType){case re.ANIMATIONTYPE_FLOAT:{let e=c?this.floatInterpolateFunctionWithTangents(h,o.outTangent*d,u,l.inTangent*d,p):this.floatInterpolateFunction(h,u,p);switch(t.loopMode){case re.ANIMATIONLOOPMODE_CYCLE:case re.ANIMATIONLOOPMODE_CONSTANT:case re.ANIMATIONLOOPMODE_YOYO:return e;case re.ANIMATIONLOOPMODE_RELATIVE:case re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(null!==(r=t.offsetValue)&&void 0!==r?r:0)*t.repeatCount+e}break}case re.ANIMATIONTYPE_QUATERNION:{let e=c?this.quaternionInterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.quaternionInterpolateFunction(h,u,p);switch(t.loopMode){case re.ANIMATIONLOOPMODE_CYCLE:case re.ANIMATIONLOOPMODE_CONSTANT:case re.ANIMATIONLOOPMODE_YOYO:break;case re.ANIMATIONLOOPMODE_RELATIVE:case re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||i3).scale(t.repeatCount))}return e}case re.ANIMATIONTYPE_VECTOR3:{let e=c?this.vector3InterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.vector3InterpolateFunction(h,u,p);switch(t.loopMode){case re.ANIMATIONLOOPMODE_CYCLE:case re.ANIMATIONLOOPMODE_CONSTANT:case re.ANIMATIONLOOPMODE_YOYO:return e;case re.ANIMATIONLOOPMODE_RELATIVE:case re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||i4).scale(t.repeatCount))}break}case re.ANIMATIONTYPE_VECTOR2:{let e=c?this.vector2InterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.vector2InterpolateFunction(h,u,p);switch(t.loopMode){case re.ANIMATIONLOOPMODE_CYCLE:case re.ANIMATIONLOOPMODE_CONSTANT:case re.ANIMATIONLOOPMODE_YOYO:return e;case re.ANIMATIONLOOPMODE_RELATIVE:case re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||i5).scale(t.repeatCount))}break}case re.ANIMATIONTYPE_SIZE:switch(t.loopMode){case re.ANIMATIONLOOPMODE_CYCLE:case re.ANIMATIONLOOPMODE_CONSTANT:case re.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(h,u,p);case re.ANIMATIONLOOPMODE_RELATIVE:case re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(h,u,p).add((t.offsetValue||i6).scale(t.repeatCount))}break;case re.ANIMATIONTYPE_COLOR3:{let e=c?this.color3InterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.color3InterpolateFunction(h,u,p);switch(t.loopMode){case re.ANIMATIONLOOPMODE_CYCLE:case re.ANIMATIONLOOPMODE_CONSTANT:case re.ANIMATIONLOOPMODE_YOYO:return e;case re.ANIMATIONLOOPMODE_RELATIVE:case re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||i8).scale(t.repeatCount))}break}case re.ANIMATIONTYPE_COLOR4:{let e=c?this.color4InterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.color4InterpolateFunction(h,u,p);switch(t.loopMode){case re.ANIMATIONLOOPMODE_CYCLE:case re.ANIMATIONLOOPMODE_CONSTANT:case re.ANIMATIONLOOPMODE_YOYO:return e;case re.ANIMATIONLOOPMODE_RELATIVE:case re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||i7).scale(t.repeatCount))}break}case re.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case re.ANIMATIONLOOPMODE_CYCLE:case re.ANIMATIONLOOPMODE_CONSTANT:case re.ANIMATIONLOOPMODE_YOYO:if(re.AllowMatricesInterpolation)return this.matrixInterpolateFunction(h,u,p,t.workValue);return h;case re.ANIMATIONLOOPMODE_RELATIVE:case re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return h}}return 0}matrixInterpolateFunction(e,t,i,r){return re.AllowMatrixDecomposeForInterpolation?r?(t7.DecomposeLerpToRef(e,t,i,r),r):t7.DecomposeLerp(e,t,i):r?(t7.LerpToRef(e,t,i,r),r):t7.Lerp(e,t,i)}clone(){let e=new re(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)for(let t in e._ranges={},this._ranges){let i=this._ranges[t];i&&(e._ranges[t]=i.clone())}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){i9.key=0;let t=this._interpolate(e,i9,!0);if(!t)return this._keys[i9.key].frame===e?i9.key:i9.key+1;let i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(i9.key+1,0,i),i9.key+1}serialize(){let 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;let t=this.dataType;e.keys=[];let i=this.getKeys();for(let r=0;r=2&&(r=l.values[1]),l.values.length>=3&&(a=l.values[2]),l.values.length>=4&&(o=l.values[3]);break;case re.ANIMATIONTYPE_QUATERNION:if(t=t8.FromArray(l.values),l.values.length>=8){let e=t8.FromArray(l.values.slice(4,8));e.equals(t8.Zero())||(r=e)}if(l.values.length>=12){let e=t8.FromArray(l.values.slice(8,12));e.equals(t8.Zero())||(a=e)}l.values.length>=13&&(o=l.values[12]);break;case re.ANIMATIONTYPE_MATRIX:t=t7.FromArray(l.values),l.values.length>=17&&(o=l.values[16]);break;case re.ANIMATIONTYPE_COLOR3:t=io.FromArray(l.values),l.values[3]&&(r=io.FromArray(l.values[3])),l.values[4]&&(a=io.FromArray(l.values[4])),l.values[5]&&(o=l.values[5]);break;case re.ANIMATIONTYPE_COLOR4:t=il.FromArray(l.values),l.values[4]&&(r=il.FromArray(l.values[4])),l.values[5]&&(a=il.FromArray(l.values[5])),l.values[6]&&(o=il.FromArray(l.values[6]));break;case re.ANIMATIONTYPE_VECTOR3:default:t=t5.FromArray(l.values),l.values[3]&&(r=t5.FromArray(l.values[3])),l.values[4]&&(a=t5.FromArray(l.values[4])),l.values[5]&&(o=l.values[5])}let h={};h.frame=l.frame,h.value=t,void 0!=r&&(h.inTangent=r),void 0!=a&&(h.outTangent=a),void 0!=o&&(h.interpolation=o),n.push(h)}if(r.setKeys(n),e.ranges)for(i=0;i{let s=new i2;s.addEventListener("readystatechange",()=>{if(4==s.readyState){if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){let e=[];for(let i of t)e.push(this.Parse(i));i(e)}else{let r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")}}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{let r=new i2;r.addEventListener("readystatechange",()=>{if(4==r.readyState){if(200==r.status){let i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){let r=JSON.parse(i.animations),s=[];for(let t of r.animations){let i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{let r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)}}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}}re._UniqueIdGenerator=0,re.AllowMatricesInterpolation=!1,re.AllowMatrixDecomposeForInterpolation=!0,re.SnippetUrl="https://snippet.babylonjs.com",re.ANIMATIONTYPE_FLOAT=0,re.ANIMATIONTYPE_VECTOR3=1,re.ANIMATIONTYPE_QUATERNION=2,re.ANIMATIONTYPE_MATRIX=3,re.ANIMATIONTYPE_COLOR3=4,re.ANIMATIONTYPE_COLOR4=7,re.ANIMATIONTYPE_VECTOR2=5,re.ANIMATIONTYPE_SIZE=6,re.ANIMATIONLOOPMODE_RELATIVE=0,re.ANIMATIONLOOPMODE_CYCLE=1,re.ANIMATIONLOOPMODE_CONSTANT=2,re.ANIMATIONLOOPMODE_YOYO=4,re.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,re.CreateFromSnippetAsync=re.ParseFromSnippetAsync,t0["BABYLON.Animation"]=re,i0._AnimationRangeFactory=(e,t,i)=>new iQ(e,t,i);class rt extends iu{constructor(e,t,i,r,s=1e3,n,a,o){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new tj,this.propertyPath=i,this.value=r,this.duration=s,this.stopOtherAnimations=a,this.onInterpolationDone=o,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){let e;let t=this._actionManager.getScene(),i=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=re.ANIMATIONTYPE_FLOAT;else if(this.value instanceof io)e=re.ANIMATIONTYPE_COLOR3;else if(this.value instanceof t5)e=re.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof t7)e=re.ANIMATIONTYPE_MATRIX;else if(this.value instanceof t8)e=re.ANIMATIONTYPE_QUATERNION;else{ig.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}let r=new re("InterpolateValueAction",this._property,1e3/this.duration*100,e,re.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(i),this.stopOtherAnimations&&t.stopAnimation(this._effectiveTarget),t.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()})}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[iu._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:iu._SerializeValueAsString(this.value)},{name:"duration",value:iu._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:iu._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}t0["BABYLON.InterpolateValueAction"]=rt;class ri{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,i,r){if(this._events=[],this._currentFrame=0,this._originalValue=[],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._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===re.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=t7.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){let e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(let 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];let s=t.getEvents();s&&s.length>0&&s.forEach(e=>{this._events.push(e._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e[i[0]];for(let e=1;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);let i=this._events;if(i.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);let c=i-t,d=l.framePerSecond*s*e/1e3+this._absoluteFrameOffset,p=0;if(r&&this._animationState.loopMode===re.ANIMATIONLOOPMODE_YOYO&&(d=Math.abs(Math.sin((d-t)/c*Math.PI))*c+t),this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&d>=c)u=!1,p=l._getKeyValue(this._maxValue);else if(!r&&t>=i&&d<=c)u=!1,p=l._getKeyValue(this._minValue);else if(this._animationState.loopMode!==re.ANIMATIONLOOPMODE_CYCLE){let e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=re.ANIMATIONLOOPMODE_CYCLE;let r=l._interpolate(t,this._animationState),s=l._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),l.dataType){case re.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-r;break;case re.ANIMATIONTYPE_QUATERNION:case re.ANIMATIONTYPE_VECTOR3:case re.ANIMATIONTYPE_VECTOR2:case re.ANIMATIONTYPE_SIZE:case re.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(r)}this._highLimitsCache[e]=s}p=this._highLimitsCache[e],a=this._offsetsCache[e]}if(void 0===a)switch(l.dataType){case re.ANIMATIONTYPE_FLOAT:a=0;break;case re.ANIMATIONTYPE_QUATERNION:a=i3;break;case re.ANIMATIONTYPE_VECTOR3:a=i4;break;case re.ANIMATIONTYPE_VECTOR2:a=i5;break;case re.ANIMATIONTYPE_SIZE:a=i6;break;case re.ANIMATIONTYPE_COLOR3:a=i8;break;case re.ANIMATIONTYPE_COLOR4:a=i7}if(this._host&&this._host.syncRoot){let e=this._host.syncRoot,i=(e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame);o=t+c*i}else o=d>0&&t>i||d<0&&t0&&this.currentFrame>o||s<0&&this.currentFrame0?0:l.getKeys().length-1}this._currentFrame=o,this._animationState.repeatCount=0===c?0:d/c>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=a;let f=l._interpolate(o,this._animationState);if(this.setValue(f,n),_.length){for(let e=0;e<_.length;e++)if(c>0&&o>=_[e].frame&&_[e].frame>=t||c<0&&o<=_[e].frame&&_[e].frame<=t){let t=_[e];t.isDone||(t.onlyOnce&&(_.splice(e,1),e--),t.isDone=!0,t.action(o))}}return u||(this._stopped=!0),u}}function rr(){return"undefined"!=typeof navigator}function rs(){return"undefined"!=typeof document}function rn(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}class ra{static get Now(){return Date.now()}}class ro{}ro.FilesToLoad={};class rl{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}class rh extends Error{}rh._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));let ru={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class rc extends rh{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",rh._setPrototypeOf(this,rc.prototype)}}let rd=e=>{let t,i,r,s,n,a,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",u=0,c=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;u>2,n=(3&t)<<4|i>>4,a=(15&i)<<2|r>>6,o=63&r,isNaN(i)?a=o=64:isNaN(r)&&(o=64),h+=l.charAt(s)+l.charAt(n)+l.charAt(a)+l.charAt(o);return h},rp=e=>atob(e),r_=e=>{let t=rp(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;e{h+=i.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}}class rm{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{let e=t.split(";");for(let t=0;t{""!==(h=h.trim())&&(i.push(h),h="")},n=e=>{rrx._Stack[r],o=()=>-1===r?"!!INVALID EXPRESSION!!":rx._Stack[r--],l=0,h="";for(;l1){for(s();-1!==r&&rx._OperatorPriority[a()]>=rx._OperatorPriority[u];)i.push(o());n(u),l++}else h+=t;l++}for(s();-1!==r;)"("===a()?o():i.push(o());return rx._InfixToPostfixCache.size>=rx.InfixToPostfixCacheLimitSize&&rx.ClearCache(),rx._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(rx._InfixToPostfixCache.entries()).sort((e,t)=>e[1].accessTime-t[1].accessTime);for(let t=0;t":i=r>s;break;case"<":i=r=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}}!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(f||(f={}));let rC=/defined\s*?\((.+?)\)/g,ry=/defined\s*?\[(.+?)\]/g,rA=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,rR=/__decl__/,rI=/light\{X\}.(\w*)/g,rP=/\{X\}/g,rM=[];class rD{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,r){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e)),i(this._ProcessShaderConversion(e,t,r),e)})}static PreProcess(e,t,i,r){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e)),i(this._ApplyPreProcessing(e,t,r),e)})}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;let r=t.shouldUseHighPrecisionShader;return -1===e.indexOf("precision highp float")?e=r?"precision highp float;\n"+e:"precision mediump float;\n"+e:r||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){let t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new rT(t[1].trim(),"!"===e[0]);let i="",r=0;for(i of["==","!=",">=","<=","<",">"])if((r=e.indexOf(i))>-1)break;if(-1===r)return new rT(e);let s=e.substring(0,r).trim(),n=e.substring(r+i.length).trim();return new rS(s,i,n)}static _BuildSubExpression(e){e=e.replace(rC,"defined[$1]");let t=rx.infixToPostfix(e),i=[];for(let e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;let s="&&"==e?new rE:new rb;"string"==typeof t&&(t=t.replace(ry,"defined($1)")),"string"==typeof r&&(r=r.replace(ry,"defined($1)")),s.leftOperand="string"==typeof r?this._ExtractOperation(r):r,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(ry,"defined($1)")),"string"==typeof r?this._ExtractOperation(r):r}static _BuildExpression(e,t){let i=new rv,r=e.substring(0,t),s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),"#ifdef"===r?i.testExpression=new rT(s):"#ifndef"===r?i.testExpression=new rT(s,!0):i.testExpression=this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let r=e.currentLine;for(;this._MoveCursor(e,i);){let s=(r=e.currentLine).substring(0,5).toLowerCase();if("#else"===s){let i=new rf;t.children.push(i),this._MoveCursor(e,i);return}if("#elif"===s){let e=this._BuildExpression(r,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;let i=e.currentLine;if(i.indexOf("#")>=0){let r=rD._MoveCursorRegex.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{let r=new rg;t.children.push(r);let s=this._BuildExpression(i,6);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let r=new rg;t.children.push(r);let s=this._BuildExpression(i,7);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#if":{let r=new rg,s=this._BuildExpression(i,3);t.children.push(r),r.children.push(s),this._MoveCursorWithinIf(e,r,s)}}continue}}let r=new rf;if(r.line=i,t.children.push(r),"#"===i[0]&&"d"===i[1]){let e=i.replace(";","").split(" ");r.additionalDefineKey=e[1],3===e.length&&(r.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){let r=new rf,s=new rm;return s.lineIndex=-1,s.lines=e.split("\n"),this._MoveCursor(s,r),r.process(t,i)}static _PreparePreProcessors(e,t){var i;let r=e.defines,s={};for(let e of r){let t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===f.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let r=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===f.GLSL&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;let s=t.defines,n=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,s,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,n,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ApplyPreProcessing(e,t,i){var r,s;let n=e,a=t.defines,o=this._PreparePreProcessors(t,i);return(null===(r=t.processor)||void 0===r?void 0:r.preProcessor)&&(n=t.processor.preProcessor(n,a,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,o,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ProcessIncludes(e,t,i){let r;for(rM.length=0;null!==(r=rA.exec(e));)rM.push(r);let s=String(e),n=[e],a=!1;for(let e of rM){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(rR,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),t.includesShadersStore[r]){let i=t.includesShadersStore[r];if(e[2]){let t=e[3].split(",");for(let e=0;et+"{X}")),i+=a.replace(rP,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(rI,(e,t)=>t+"{X}")),i=i.replace(rP,r)}let s=[];for(let t of n){let r=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}else{let e=t.shadersRepository+"ShadersInclude/"+r+".fx";rD._FileToolsLoadFile(e,e=>{t.includesShadersStore[r]=e,this._ProcessIncludes(n.join(""),t,i)});return}}rM.length=0,s=n.join(""),a?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,r,s,n){throw iL("FileTools")}}rD._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;class rO{static GetShadersRepository(e=f.GLSL){return e===f.GLSL?rO.ShadersRepository:rO.ShadersRepositoryWGSL}static GetShadersStore(e=f.GLSL){return e===f.GLSL?rO.ShadersStore:rO.ShadersStoreWGSL}static GetIncludesShadersStore(e=f.GLSL){return e===f.GLSL?rO.IncludesShadersStore:rO.IncludesShadersStoreWGSL}}rO.ShadersRepository="src/Shaders/",rO.ShadersStore={},rO.IncludesShadersStore={},rO.ShadersRepositoryWGSL="src/ShadersWGSL/",rO.ShadersStoreWGSL={},rO.IncludesShadersStoreWGSL={};class rN{static get ShadersRepository(){return rO.ShadersRepository}static set ShadersRepository(e){rO.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new tj),this._onBindObservable}constructor(e,t,i,r=null,s,n=null,a=null,o=null,l=null,h,u="",c=f.GLSL){var d,p,_;if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new tj,this.onErrorObservable=new tj,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!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=u,t.attributes){if(this._engine=i,this._attributesNames=t.attributes,this._uniformsNames=t.uniformsNames.concat(t.samplers),this._samplerList=t.samplers.slice(),this.defines=t.defines,this.onError=t.onError,this.onCompiled=t.onCompiled,this._fallbacks=t.fallbacks,this._indexParameters=t.indexParameters,this._transformFeedbackVaryings=t.transformFeedbackVaryings||null,this._multiTarget=!!t.multiTarget,this._shaderLanguage=null!==(d=t.shaderLanguage)&&void 0!==d?d:f.GLSL,t.uniformBuffersNames){this._uniformBuffersNamesList=t.uniformBuffersNames.slice();for(let e=0;e{if(a[0]&&a[1]){n.isFragment=!0;let[e,i]=a;rD.Process(i,n,(i,r)=>{this._fragmentSourceCodeBeforeMigration=r,this._processFinalCode&&(i=this._processFinalCode("fragment",i));let a=rD.Finalize(e,i,n);n=null,this._useFinalCode(a.vertexCode,a.fragmentCode,s,t)},this._engine)}};this._loadShader(i,"Vertex","",e=>{rD.Initialize(n),rD.Process(e,n,(t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,this._processFinalCode&&(t=this._processFinalCode("vertex",t)),a[0]=t,o()},this._engine)}),this._loadShader(r,"Fragment","Pixel",e=>{this._rawFragmentSourceCode=e,a[1]=e,o()})}_useFinalCode(e,t,i,r=!1){if(i){let r=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===f.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===f.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(r)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){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){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){r(rn(e));return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){r(window.atob(e.substr(7)));return}let n=rO.GetShadersStore(this._shaderLanguage);if(n[e+t+"Shader"]){r(n[e+t+"Shader"]);return}if(i&&n[e+i+"Shader"]){r(n[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:rO.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{let e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,r);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?n._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,null,this._transformFeedbackVaryings,this._key):n._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,r,this._transformFeedbackVaryings,this._key),n._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,i,this._attributes),i)for(let e=0;e=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,r,s;this._compilationError=e.message;let n=this._attributesNames,a=this._fallbacks;if(ig.Error("Unable to compile effect:"),ig.Error("Uniforms: "+this._uniformsNames.map(function(e){return" "+e})),ig.Error("Attributes: "+n.map(function(e){return" "+e})),ig.Error("Defines:\n"+this.defines),rN.LogShaderCodeOnCompilationError){let e=null,t=null,n=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([n,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),n&&(ig.Error("Vertex code:"),ig.Error(n))),(null===(r=this._pipelineContext)||void 0===r?void 0:r._getFragmentShaderCode())&&([n,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),n&&(ig.Error("Fragment code:"),ig.Error(n))),e&&ig.Error(e),t&&ig.Error(t)}ig.Error("Error: "+this._compilationError);let o=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,o()),a?(this._pipelineContext=null,a.hasMoreFallbacks?(this._allFallbacksProcessed=!1,ig.Error("Trying next fallback."),this.defines=a.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,o(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||o())}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)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){let i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){let r=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};e.isAsync?e.proxy.then(t):t(e.proxy);return}switch(this.source){case m.Temp:break;case m.Url:i=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e: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);return;case m.Raw:(i=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))._swapAndDie(this,!1),this.isReady=!0;break;case m.Raw3D:(i=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case m.Raw2DArray:(i=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case m.Dynamic:(i=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case m.Cube:i=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{i._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case m.CubeRaw:(i=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,null!==(t=this._originalFormat)&&void 0!==t?t:this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this,!1),this.isReady=!0;break;case m.CubeRawRGBD:return;case m.CubePrefiltered:(i=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,e=>{e&&e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension))._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var i;null===(i=this._hardwareTexture)||void 0===i||i.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);let r=this._engine.getLoadedTexturesCache(),s=r.indexOf(this);-1!==s&&r.splice(s,1),-1===(s=r.indexOf(e))&&r.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}rU._Counter=0;class rV{constructor(){this.shaderLanguage=f.GLSL}postProcessor(e,t,i,r,s){return s.getCaps().drawBuffersExtension||(e=e.replace(/#extension.+GL_EXT_draw_buffers.+(enable|require)/g,"")),e}}let rk=/(flat\s)?\s*varying\s*.*/;class rG{constructor(){this.shaderLanguage=f.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return rk.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){let r=-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("),i){let 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,(r||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 rz{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=rz._Counter++}}rz._Counter=0;class rW extends rz{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class rH{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)}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this.engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);for(this.engine.getUniforms(this,i).forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l{n[e]=t}),h.getAttributes(this,a)))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setInt4(this._uniforms[e],t,i,r,s)&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setUInt4(this._uniforms[e],t,i,r,s)&&(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.toArray())&&(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){let i=this._valueCache[e];(void 0===i||i!==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,i){this._cacheFloat2(e,t,i)&&!this.engine.setFloat2(this._uniforms[e],t,i)&&(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,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setFloat3(this._uniforms[e],t,i,r)&&(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,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setFloat4(this._uniforms[e],t,i,r,s)&&(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(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}}class rX{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw 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(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return null!==(i=null===(t=this._MSAARenderBuffers)||void 0===t?void 0:t[e])&&void 0!==i?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class rY{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(r=this.drawContext)||void 0===r||r.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}}class rj{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(){var e;this.stencilMaterial=void 0,null===(e=this.stencilGlobal)||void 0===e||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var t;if(!e)return;let i=!this.useStencilGlobalOnly&&!!(null===(t=this.stencilMaterial)||void 0===t?void 0:t.enabled);this.enabled=i?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=i?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=i?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=i?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=i?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=i?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=i?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=i?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 rK{}class r${static get NpmPackage(){return"babylonjs@6.37.1"}static get Version(){return"6.37.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return rN.ShadersRepository}static set ShadersRepository(e){rN.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4);this._emptyCubeTexture=this.createRawCubeTexture([e,e,e,e,e,e],1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);let i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return r$._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new tj,this._frameId=0,this._uniformBuffers=[],this._storageBuffers=[],this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.onContextLostObservable=new tj,this.onContextRestoredObservable=new tj,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new rF,this._stencilStateComposer=new rj,this._stencilState=new rw,this._alphaState=new rL,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=[],this._renderTargetWrapperCache=[],this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._currentRenderTarget=null,this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=[],this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=[],this._currentInstanceLocations=[],this._currentInstanceBuffers=[],this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=[],this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=[],this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new tj,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=ra.Now;let f=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=null!=r&&r,this._stencilStateComposer.stencilGlobal=this._stencilState,t1.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=null!=t?t:i.antialias,i.deterministicLockstep=null!==(s=i.deterministicLockstep)&&void 0!==s&&s,i.lockstepMaxSteps=null!==(n=i.lockstepMaxSteps)&&void 0!==n?n:4,i.timeStep=null!==(a=i.timeStep)&&void 0!==a?a:1/60,i.audioEngine=null===(o=i.audioEngine)||void 0===o||o,i.stencil=null===(l=i.stencil)||void 0===l||l,this._audioContext=null!==(u=null===(h=i.audioEngineOptions)||void 0===h?void 0:h.audioContext)&&void 0!==u?u:null,this._audioDestination=null!==(d=null===(c=i.audioEngineOptions)||void 0===c?void 0:c.audioDestination)&&void 0!==d?d:null,this.premultipliedAlpha=null===(p=i.premultipliedAlpha)||void 0===p||p,this.useExactSrgbConversions=null!==(_=i.useExactSrgbConversions)&&void 0!==_&&_,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,r=r||i.adaptToDeviceRatio||!1;let m=i.limitDeviceRatio||1;if(this._hardwareScalingLevel=r?1/Math.min(m,1):1,this._lastDevicePixelRatio=1,!e)return;if(e.getContext){if(f=e,this._renderingCanvas=f,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();let e=navigator.userAgent;for(let t of r$.ExceptionList){let r=t.key,s=t.targets;if(new RegExp(r).test(e)){if(t.capture&&t.captureConstraint){let i=t.capture,r=t.captureConstraint,s=new RegExp(i).exec(e);if(s&&s.length>0&&parseInt(s[s.length-1])>=r)continue}for(let e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,ig.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},f.addEventListener("webglcontextlost",this._onContextLost,!1),f.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=f.getContext("webgl2",i)||f.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!f)throw Error("The provided canvas is null or undefined.");try{this._gl=f.getContext("webgl",i)||f.getContext("experimental-webgl",i)}catch(e){throw Error("WebGL not supported")}}if(!this._gl)throw 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";let t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new rG:new rV,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);let g=`Babylon.js v${r$.Version}`;ig.Log(g+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",g)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{let e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&rs()&&"ontouchend"in document},this._checkForMobile())}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null,this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null;let i=this._depthCullingState.depthTest,r=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=i,this._depthCullingState.depthFunc=r,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=n,ig.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){for(let e of this._internalTexturesCache.slice())e._rebuild()}_rebuildRenderTargetWrappers(){for(let e of this._renderTargetWrapperCache.slice())e._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}rN.ResetCache()}areAllEffectsReady(){for(let e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuildAfterContextLost()}_rebuildTextures(){}_initGLContext(){var e;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);let t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.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=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e: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{let 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{let 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{let 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{let 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){let 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{let 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{let 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=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler)return(this._renderingQueueLaunched=!1,"function"==typeof cancelAnimationFrame)?cancelAnimationFrame(this._frameHandler):clearTimeout(this._frameHandler)}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return null}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}_queueNewFrame(e,t){return r$.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=()=>this._renderLoop(),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,r=!1){var s,n;let a=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=a;let o=0;if(t&&e){let t=!0;if(this._currentRenderTarget){let i=null===(s=this._currentRenderTarget.texture)||void 0===s?void 0:s.format;if(8===i||9===i||10===i||11===i){let i=null===(n=this._currentRenderTarget.texture)||void 0===n?void 0:n.type;7===i||5===i?(r$._TempClearColorUint32[0]=255*e.r,r$._TempClearColorUint32[1]=255*e.g,r$._TempClearColorUint32[2]=255*e.b,r$._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,r$._TempClearColorUint32)):(r$._TempClearColorInt32[0]=255*e.r,r$._TempClearColorInt32[1]=255*e.g,r$._TempClearColorInt32[2]=255*e.b,r$._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,r$._TempClearColorInt32)),t=!1}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),o|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),o|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),o|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(o)}_viewport(e,t,i,r){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||r!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))}setViewport(e,t,i){let r=t||this.getRenderWidth(),s=i||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*r,a*s,r*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){let e=this._lastDevicePixelRatio/1;this._lastDevicePixelRatio=1,this._hardwareScalingLevel*=e}t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100,this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){return!!this._renderingCanvas&&(e|=0,t|=0,(!!i||this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)&&(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0))}bindFramebuffer(e,t=0,i,r,s,n=0,a=0){var o,l,h,u,c,d;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer);let p=this._gl;e.isMulti||(e.is2DArray?p.framebufferTextureLayer(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,null===(o=e.texture._hardwareTexture)||void 0===o?void 0:o.underlyingResource,n,a):e.isCube?p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,n):e._currentLOD===n||(p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,null===(h=e.texture._hardwareTexture)||void 0===h?void 0:h.underlyingResource,n),e._currentLOD=n));let _=e._depthStencilTexture;if(_){let i=e._depthStencilTextureWithStencil?p.DEPTH_STENCIL_ATTACHMENT:p.DEPTH_ATTACHMENT;e.is2DArray?p.framebufferTextureLayer(p.FRAMEBUFFER,i,null===(u=_._hardwareTexture)||void 0===u?void 0:u.underlyingResource,n,a):e.isCube?p.framebufferTexture2D(p.FRAMEBUFFER,i,p.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(c=_._hardwareTexture)||void 0===c?void 0:c.underlyingResource,n):p.framebufferTexture2D(p.FRAMEBUFFER,i,p.TEXTURE_2D,null===(d=_._hardwareTexture)||void 0===d?void 0:d.underlyingResource,n)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,r):(!i&&(i=e.width,n&&(i/=Math.pow(2,n))),!r&&(r=e.height,n&&(r/=Math.pow(2,n))),this._viewport(0,0,i,r)),this.wipeCaches()}setState(e,t=0,i,r=!1,s,n,a=0){var o,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);let h=null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(a);let u=r?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==u||i)&&(this._depthCullingState.frontFace=u),this._stencilStateComposer.stencilMaterial=n}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){let e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){let e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,i){var r;this._currentRenderTarget=null;let s=this._gl;if(e._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}s.bindFramebuffer(s.READ_FRAMEBUFFER,e._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,e._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}(null===(r=e.texture)||void 0===r?void 0:r.generateMipMaps)&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),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,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create vertex buffer");let r=new rW(i);return this.bindArrayBuffer(r),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),r.references=1,r}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){let r=this._gl.createBuffer(),s=new rW(r);if(!r)throw Error("Unable to create index buffer");this.bindIndexBuffer(s);let 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(),s.references=1,s.is32Bits=4===n.BYTES_PER_ELEMENT,s}_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=65535)return new Uint32Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}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,i,r,s,n,a){let o=this._currentBufferPointers[t];if(!o)return;let l=!1;o.active?(o.buffer!==e&&(o.buffer=e,l=!0),o.size!==i&&(o.size=i,l=!0),o.type!==r&&(o.type=r,l=!0),o.normalized!==s&&(o.normalized=s,l=!0),o.stride!==n&&(o.stride=n,l=!0),o.offset!==a&&(o.offset=a,l=!0)):(l=!0,o.active=!0,o.index=t,o.size=i,o.type=r,o.normalized=s,o.stride=n,o.offset=a,o.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,n,a):this._gl.vertexAttribPointer(t,i,r,s,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){let r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){let t=r[s],a=null;if(i&&(a=i[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);let 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,i,r){let s=this._gl.createVertexArray();if(!s)throw Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}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,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[a],this._gl.FLOAT,!1,r,n)),n+=4*i[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",o=this._compileShader(t,"vertex",r,a),l=this._compileShader(i,"fragment",r,a);return this._createShaderProgram(e,o,l,s,n)}inlineShaderCode(e){return e}createPipelineContext(e){let t=new rH;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,r,s=null){let n=r.createProgram();if(e.program=n,!n)throw Error("Unable to create program");return r.attachShader(n,t),r.attachShader(n,i),r.linkProgram(n),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){let t=e.context,i=e.vertexShader,r=e.fragmentShader,s=e.program;if(!t.getProgramParameter(s,t.LINK_STATUS)){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(i);if(t)throw e.vertexCompilationError=t,Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(r,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(r);if(t)throw e.fragmentCompilationError=t,Error("FRAGMENT SHADER "+t)}let n=t.getProgramInfoLog(s);if(n)throw e.programLinkError=n,Error(n)}if(this.validateShaderPrograms&&(t.validateProgram(s),!t.getProgramParameter(s,t.VALIDATE_STATUS))){let i=t.getProgramInfoLog(s);if(i)throw e.programValidationError=i,Error(i)}t.deleteShader(i),t.deleteShader(r),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,r,s,n,a,o,l,h){r?e.program=this.createRawShaderProgram(e,t,i,void 0,l):e.program=this.createShaderProgram(e,t,i,o,void 0,l),e.program.__SPECTOR_rebuildProgram=a}_isRenderingStateCompiled(e){return!this._isDisposed&&!e._isDisposed&&!!this._gl.getProgramParameter(e.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(e),!0)}_executeWhenRenderingStateIsCompiled(e,t){if(!e.isParallelCompiled){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}getUniforms(e,t){let i=[];for(let r=0;r1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==o||this._caps.textureFloat||(o=0,ig.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let d=this._gl,p=new rU(this,r),_=e.width||e,f=e.height||e,g=e.layers||0,v=this._getSamplingParameters(l,a),x=0!==g?d.TEXTURE_2D_ARRAY:d.TEXTURE_2D,T=this._getRGBABufferInternalSizedFormat(o,h,u),b=this._getInternalFormat(h),E=this._getWebGLTextureType(o);return this._bindTextureDirectly(x,p),0!==g?(p.is2DArray=!0,d.texImage3D(x,0,T,_,f,g,0,b,E,null)):d.texImage2D(x,0,T,_,f,0,b,E,null),d.texParameteri(x,d.TEXTURE_MAG_FILTER,v.mag),d.texParameteri(x,d.TEXTURE_MIN_FILTER,v.min),d.texParameteri(x,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(x,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(x),this._bindTextureDirectly(x,null),p._useSRGBBuffer=u,p.baseWidth=_,p.baseHeight=f,p.width=_,p.height=f,p.depth=g,p.isReady=!0,p.samples=c,p.generateMipMaps=a,p.samplingMode=l,p.type=o,p.format=h,p.label=n,this._internalTexturesCache.push(p),p}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,r,s=3,n=null,a=null,o,l,h=null,u=null,c=null,d=null,p,_,f){let g="data:"===(e=e||"").substr(0,5),v="blob:"===e.substr(0,5),x=g&&-1!==e.indexOf(";base64,"),T=u||new rU(this,m.Url);T!==u&&(T.label=e.substring(0,60));let b=e;!this._transformTextureUrl||x||u||h||(e=this._transformTextureUrl(e)),b!==e&&(T._originalUrl=b);let E=e.lastIndexOf("."),S=d||(E>-1?e.substring(E).toLowerCase():""),C=null;for(let e of(S.indexOf("?")>-1&&(S=S.split("?")[0]),r$._TextureLoaders))if(e.canLoad(S,p)){C=e;break}r&&r.addPendingData(T),T.url=e,T.generateMipMaps=!t,T.samplingMode=s,T.invertY=i,T._useSRGBBuffer=this._getUseSRGBBuffer(!!f,t),this._doNotHandleContextLost||(T._buffer=h);let y=null;n&&!u&&(y=T.onLoadedObservable.add(n)),u||this._internalTexturesCache.push(T);let A=(i,u)=>{r&&r.removePendingData(T),e===b?(y&&T.onLoadedObservable.remove(y),t2.UseFallbackTexture&&this._createTextureBase(t2.FallbackTexture,t,T.invertY,r,s,null,a,o,l,h,T),i=(i||"Unknown error")+(t2.UseFallbackTexture?" - Fallback texture was used":""),T.onErrorObservable.notifyObservers({message:i,exception:u}),a&&a(i,u)):(ig.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,T.invertY,r,s,n,a,o,l,h,T,c,d,p,_,f))};if(C){let t=e=>{C.loadData(e,T,(e,t,i,n,a,l)=>{l?A("TextureLoader failed to load data"):o(T,S,r,{width:e,height:t},T.invertY,!i,n,()=>(a(),!1),s)},_)};h?h instanceof ArrayBuffer?t(new Uint8Array(h)):ArrayBuffer.isView(h)?t(h):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,e=>t(new Uint8Array(e)),void 0,r?r.offlineProvider:void 0,!0,(e,t)=>{A("Unable to load "+(e&&e.responseURL,t))})}else{let i=e=>{v&&!this._doNotHandleContextLost&&(T._buffer=e),o(T,S,r,e,T.invertY,t,!1,l,s)};!g||x?h&&("string"==typeof h.decoding||h.close)?i(h):r$._FileToolsLoadImage(e,i,A,r?r.offlineProvider:null,p,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?r$._FileToolsLoadImage(h,i,A,r?r.offlineProvider:null,p,T.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&i(h)}return T}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_){return this._createTextureBase(e,t,i,r,s,n,a,this._prepareWebGLTexture.bind(this),(e,t,i,s,n,a)=>{let o=this._gl,l=i.width===e&&i.height===t;n._creationFlags=null!=p?p:0;let u=this._getTexImageParametersForCreateTexture(h,s,n._useSRGBBuffer);if(l)return o.texImage2D(o.TEXTURE_2D,0,u.internalFormat,u.format,u.type,i),!1;let c=this._caps.maxTextureSize;if(i.width>c||i.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!!this._workingCanvas&&!!this._workingContext&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),o.texImage2D(o.TEXTURE_2D,0,u.internalFormat,u.format,u.type,this._workingCanvas),n.width=e,n.height=t,!1);{let e=new rU(this,m.Temp);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,u.internalFormat,u.format,u.type,i),this._rescaleTexture(e,n,r,u.format,()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,n,!0),a()})}return!0},o,l,h,u,c,d,_)}_getTexImageParametersForCreateTexture(e,t,i){let r,s;return null==e&&(e=".jpg"!==t||i?5:4),1===this.webGLVersion?s=r=this._getInternalFormat(e,i):(r=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,i)),{internalFormat:s,format:r,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,i,r,s,n){throw iL("FileTools")}_rescaleTexture(e,t,i,r,s){}createRawTexture(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){throw iL("Engine.RawTexture")}createRawCubeTexture(e,t,i,r,s,n,a,o=null){throw iL("Engine.RawTexture")}createRawTexture3D(e,t,i,r,s,n,a,o,l=null,h=0){throw iL("Engine.RawTexture")}createRawTexture2DArray(e,t,i,r,s,n,a,o,l=null,h=0){throw iL("Engine.RawTexture")}_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,i=!1){let r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){let s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,i,r,s,n=1){let a=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=0,e._comparisonFunction=s;let h=this._gl,u=this._getTextureTarget(e),c=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(u,h.TEXTURE_MAG_FILTER,c.mag),h.texParameteri(u,h.TEXTURE_MIN_FILTER,c.min),h.texParameteri(u,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(u,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(u,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(u,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(u,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(u,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,a=0){let o=this._gl,l=o.TEXTURE_2D;if(e.isCube&&(l=o.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,a,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,n=!1){let a=this._gl,o=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let u=a.TEXTURE_2D;e.isCube&&(u=a.TEXTURE_CUBE_MAP_POSITIVE_X+i);let c=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),p=n?e.width:Math.pow(2,Math.max(c-r,0)),_=n?e.height:Math.pow(2,Math.max(d-r,0));a.texImage2D(u,r,h,p,_,0,l,o,t)}updateTextureData(e,t,i,r,s,n,a=0,o=0,l=!1){let h=this._gl,u=this._getWebGLTextureType(e.type),c=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,p=h.TEXTURE_2D;e.isCube&&(p=h.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(p,o,i,r,s,n,c,u,t),l&&this._gl.generateMipmap(p),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){let s=this._gl,n=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){let n=this._gl;if(!n)return;let a=this._getSamplingParameters(s,!i);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),i||r||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,i,r,s,n,a,o,l=3){let h=this.getCaps().maxTextureSize,u=Math.min(h,this.needPOTTextures?r$.GetExponentOfTwo(r.width,h):r.width),c=Math.min(h,this.needPOTTextures?r$.GetExponentOfTwo(r.height,h):r.height),d=this._gl;if(d){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=u,e.height=c,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:".jpg"!==t||e._useSRGBBuffer?5:4,o(u,c,r,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,n,a,l)})||this._prepareWebGLTextureContinuation(e,i,n,a,l)}}_setupFramebufferDepthAttachments(e,t,i,r,s=1){let n=this._gl;if(e&&t)return this._createRenderBuffer(i,r,s,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(i,r,s,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,r,s,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,n,a=!0){let o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,i,r,s,n,a)}_updateRenderBuffer(e,t,i,r,s,n,a,o=!0){let l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),r>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,r,n,t,i):l.renderbufferStorage(l.RENDERBUFFER,s,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,a,l.RENDERBUFFER,e),o&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();let i=this._internalTexturesCache.indexOf(e);-1!==i&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){let t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let i=e.getSamplers();for(let t=0;t-1;if(i&&o&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw ig.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(n=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==n?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(a=!0,this._activateCurrentTexture());return o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;let r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){let i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:break;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){let n;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;let i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;n=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(i||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;let o=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(o,n,i),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;let e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;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,i,r){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs)&&this._vertexAttribArraysEnabled[e]&&this.disableAttributeByIndex(e)}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e,t;for(let t of(this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,rN.ResetCache(),this._activeRequests))t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&(null===(t=this._gl.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext())}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(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),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);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);let n=t.checkFramebufferStatus(t.FRAMEBUFFER);if((i=(i=i&&n===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);let e=t.RGBA,r=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,r,s),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:break;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:break;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_loadFile(e,t,i,r,s,n){let a=r$._FileToolsLoadFile(e,t,i,r,s,n);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}static _FileToolsLoadFile(e,t,i,r,s,n){throw iL("FileTools")}readPixels(e,t,i,r,s=!0,n=!0){let a=s?this._gl.RGBA:this._gl.RGB,o=new Uint8Array(r*i*(s?4:3));return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,a,this._gl.UNSIGNED_BYTE,o),Promise.resolve(o)}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{let e=this._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{let e=this._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}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){let t=r$.CeilingPOT(e),i=r$.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let r;switch(i){case 1:r=r$.FloorPOT(e);break;case 2:r=r$.NearestPOT(e);break;default:r=r$.CeilingPOT(e)}return Math.min(r,t)}static QueueNewFrame(e,t){return"function"==typeof requestAnimationFrame?requestAnimationFrame(e):setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:rs()?document:null}}r$._TempClearColorUint32=new Uint32Array(4),r$._TempClearColorInt32=new Int32Array(4),r$.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"]}],r$._TextureLoaders=[],r$.CollisionsEpsilon=.001,r$._IsSupported=null,r$._HasMajorPerformanceCaveat=null;class rq{static SetImmediate(e){setTimeout(e,1)}}let rQ=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class rZ extends rc{constructor(e,t){super(e,ru.LoadFileError),this.name="LoadFileError",rh._setPrototypeOf(this,rZ.prototype),t instanceof i2?this.request=t:this.file=t}}class rJ extends rc{constructor(e,t){super(e,ru.RequestFileError),this.request=t,this.name="RequestFileError",rh._setPrototypeOf(this,rJ.prototype)}}class r0 extends rc{constructor(e,t){super(e,ru.ReadFileError),this.file=t,this.name="ReadFileError",rh._setPrototypeOf(this,r0.prototype)}}let r1={DefaultRetryStrategy:rl.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e},r2=e=>e=e.replace(/#/gm,"%23"),r3=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&r1.CorsBehavior){if("string"==typeof r1.CorsBehavior||r1.CorsBehavior instanceof String)t.crossOrigin=r1.CorsBehavior;else{let i=r1.CorsBehavior(e);i&&(t.crossOrigin=i)}}},r4=(e,t,i,r,s="",n)=>{let a;let o=t2.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!(null==o?void 0:o._features.forceBitmapOverHTMLImageElement))return i("LoadImage is only supported in web or BabylonNative environments."),null;let l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(a=URL.createObjectURL(new Blob([e],{type:s})),l=!0):a=`data:${s};base64,`+rd(e):e instanceof Blob?(a=URL.createObjectURL(e),l=!0):(a=r2(e),a=r1.PreprocessUrl(e));let h=t=>{if(i){let r=a||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if(null==o?void 0:o._features.forceBitmapOverHTMLImageElement)return r6(a,r=>{o.createImageBitmap(new Blob([r],{type:s}),Object.assign({premultiplyAlpha:"none"},n)).then(e=>{t(e),l&&URL.revokeObjectURL(a)}).catch(t=>{i&&i("Error while trying to load image: "+e,t)})},void 0,r||void 0,!0,(e,t)=>{h(t)}),null;let u=new Image;r3(a,u);let c=[],d=()=>{c.forEach(e=>{e.target.removeEventListener(e.name,e.handler)}),c.length=0};c.push({target:u,name:"load",handler:()=>{d(),t(u),l&&u.src&&URL.revokeObjectURL(u.src)}}),c.push({target:u,name:"error",handler:e=>{d(),h(e),l&&u.src&&URL.revokeObjectURL(u.src)}}),c.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==u.src)return;d();let t=Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);t2.UseFallbackTexture=!1,h(t),l&&u.src&&URL.revokeObjectURL(u.src),u.src=""}}),c.forEach(e=>{e.target.addEventListener(e.name,e.handler)});let p="blob:"===a.substring(0,5),_="data:"===a.substring(0,5),f=()=>{p||_||!i2.IsCustomRequestAvailable?u.src=a:r6(a,(e,t,i)=>{let r=!s&&i?i:s,n=new Blob([e],{type:r}),a=URL.createObjectURL(n);l=!0,u.src=a},void 0,r||void 0,!0,(e,t)=>{h(t)})};if(!p&&!_&&r&&r.enableTexturesOffline)r.open(()=>{r&&r.loadImage(a,u)},f);else{if(-1!==a.indexOf("file:")){let e=decodeURIComponent(a.substring(5).toLowerCase());if(ro.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(ro.FilesToLoad[e])}catch(i){t=URL.createObjectURL(ro.FilesToLoad[e])}u.src=t,l=!0}catch(e){u.src=""}return u}}f()}return u},r5=(e,t,i,r,s)=>{let n=new FileReader,a={onCompleteObservable:new tj,abort:()=>n.abort()};return n.onloadend=()=>a.onCompleteObservable.notifyObservers(a),s&&(n.onerror=()=>{s(new r0(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),r?n.readAsArrayBuffer(e):n.readAsText(e),a},r6=(e,t,i,r,s,n,a)=>{if(e.name)return r5(e,t,i,s,n?e=>{n(void 0,e)}:void 0);if(-1!==e.indexOf("file:")){let r=decodeURIComponent(e.substring(5).toLowerCase());0===r.indexOf("./")&&(r=r.substring(2));let a=ro.FilesToLoad[r];if(a)return r5(a,t,i,s,n?e=>n(void 0,new rZ(e.message,e.file)):void 0)}let{match:o,type:l}=r9(e);if(o){let i={onCompleteObservable:new tj,abort:()=>()=>{}};try{let i=s?se(e):st(e);t(i,void 0,l)}catch(e){n?n(void 0,e):ig.Error(e.message||"Failed to parse the Data URL")}return rq.SetImmediate(()=>{i.onCompleteObservable.notifyObservers(i)}),i}return r8(e,(e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))},i,r,s,n?e=>{n(e.request,new rZ(e.message,e.request))}:void 0,a)},r8=(e,t,i,r,s,n,a)=>{e=r2(e),e=r1.PreprocessUrl(e);let o=r1.BaseUrl+e,l=!1,h={onCompleteObservable:new tj,abort:()=>l=!0},u=()=>{let e,r=new i2,u=null,c=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",d))},d=()=>{c(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,d=null,n=void 0,a=void 0,t=void 0};h.abort=()=>{l=!0,d&&d(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==u&&(clearTimeout(u),u=null),r=null};let p=e=>{let t=e.message||"Unknown error";n&&r?n(new rJ(t,r)):ig.Error(t)},_=h=>{if(r){if(r.open("GET",o),a)try{a(r)}catch(e){p(e);return}s&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),d&&r.addEventListener("loadend",d),e=()=>{if(!l&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status){try{t&&t(s?r.response:r.responseText,r)}catch(e){p(e)}return}let i=r1.DefaultRetryStrategy;if(i){let e=i(o,r,h);if(-1!==e){c(),r=new i2,u=setTimeout(()=>_(h+1),e);return}}let a=new rJ("Error status: "+r.status+" "+r.statusText+" - Unable to load "+o,r);n&&n(a)}},r.addEventListener("readystatechange",e),r.send()}};_(0)};if(r&&r.enableSceneOffline){let a=e=>{e&&e.status>400?n&&n(e):u()};r.open(()=>{r&&r.loadFile(r1.BaseUrl+e,e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)},i?e=>{!l&&i&&i(e)}:void 0,a,s)},a)}else u();return h},r7=e=>rQ.test(e),r9=e=>{let t=rQ.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function se(e){return r_(e.split(",")[1])}let st=e=>rp(e.split(",")[1]);r$._FileToolsLoadImage=r4,r$._FileToolsLoadFile=r6,rD._FileToolsLoadFile=r6,((e,t,i,s,n,a,o,l,h,u)=>{Object.defineProperty(r={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:n,LoadFile:a,LoadImage:o,ReadFile:l,RequestFile:h,SetCorsBehavior:u},"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(r,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(r,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(r,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(se,st,r1,r7,()=>"undefined"!=typeof location&&"file:"===location.protocol,r6,r4,r5,r8,r3);class si{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=t0[e];if(t)return t;ig.Warn(e+" not found, you may have missed an import.");let i=e.split("."),r=window||this;for(let e=0,t=i.length;e{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}si.RegisteredExternalClasses={};class ss{static get BaseUrl(){return r1.BaseUrl}static set BaseUrl(e){r1.BaseUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||!(-1===e.indexOf("://")||-1===e.indexOf(".")||-1===e.indexOf("/")||e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){r6(e,e=>{i(e)},void 0,void 0,t,(e,t)=>{r(t)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(ss.ScriptBaseUrl&&e.startsWith(ss._DefaultCdnUrl)){let t="/"===ss.ScriptBaseUrl[ss.ScriptBaseUrl.length-1]?ss.ScriptBaseUrl.substring(0,ss.ScriptBaseUrl.length-1):ss.ScriptBaseUrl;e=e.replace(ss._DefaultCdnUrl,t)}return e=ss.ScriptPreprocessUrl(e),t&&(e=ss.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=ss.GetBabylonScriptURL(e),ss.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=ss.GetBabylonScriptURL(e),ss.LoadScriptAsync(e)}static LoadScript(e,t,i,r){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}null==i||i(`Cannot load script '${e}' outside of a window or a worker`)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(e,t)=>{i(t||Error(e))})})}static ReadFileAsDataURL(e,t,i){let r=new FileReader,s={onCompleteObservable:new tj,abort:()=>r.abort()};return r.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},r.onload=e=>{t(e.target.result)},r.onprogress=i,r.readAsDataURL(e),s}static ReadFile(e,t,i,r,s){return r5(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){iP.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{let r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,n=new Uint8Array(s);for(let e=0;et(e)):e.toBlob(function(e){t(e)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let e=new Date;t="screenshot_"+((e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours())+"-"+("0"+e.getMinutes()).slice(-2)+".png"}ss.Download(e,t)}else if(e&&"undefined"!=typeof URL){let t=URL.createObjectURL(e),i=window.open("");if(!i)return;let r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(ss._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(e=>{let i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{t(i.result)}});return}t(e.toDataURL(i,s))}}else this.ToBlob(e,function(e){e&&ss.DownloadBlob(e,r),t&&t("")},i,s)}static Download(e,t){if("undefined"==typeof URL)return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",n=!1,a){throw iL("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw iL("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,a=!1,o,l=!1,h=!1,u=!0,c){throw iL("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,a,o=!1,l=!1,h=!0,u){throw iL("ScreenshotTools")}static RandomId(){return sr()}static IsBase64(e){return r7(e)}static DecodeBase64(e){return se(e)}static get errorsCount(){return ig.errorsCount}static Log(e){ig.Log(e)}static Warn(e){ig.Warn(e)}static Error(e){ig.Error(e)}static get LogCache(){return ig.LogCache}static ClearLogCache(){ig.ClearLogCache()}static set LogLevels(e){ig.LogLevels=e}static set PerformanceLogLevel(e){if((e&ss.PerformanceUserMarkLogLevel)===ss.PerformanceUserMarkLogLevel){ss.StartPerformanceCounter=ss._StartUserMark,ss.EndPerformanceCounter=ss._EndUserMark;return}if((e&ss.PerformanceConsoleLogLevel)===ss.PerformanceConsoleLogLevel){ss.StartPerformanceCounter=ss._StartPerformanceConsole,ss.EndPerformanceCounter=ss._EndPerformanceConsole;return}ss.StartPerformanceCounter=ss._StartPerformanceCounterDisabled,ss.EndPerformanceCounter=ss._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){ss._Performance&&t&&ss._Performance.mark&&ss._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&ss._Performance.mark&&(ss._Performance.mark(e+"-End"),ss._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(ss._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(ss._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return ra.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return!!rr()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}ss.UseCustomRequestHeaders=!1,ss.CustomRequestHeaders=i2.CustomRequestHeaders,ss.GetDOMTextContent=rn,ss._DefaultCdnUrl="https://cdn.babylonjs.com",ss.GetAbsoluteUrl="object"==typeof document?e=>{let t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},ss.NoneLogLevel=ig.NoneLogLevel,ss.MessageLogLevel=ig.MessageLogLevel,ss.WarningLogLevel=ig.WarningLogLevel,ss.ErrorLogLevel=ig.ErrorLogLevel,ss.AllLogLevel=ig.AllLogLevel,ss.IsWindowObjectExist=function(){return!1},ss.PerformanceNoneLogLevel=0,ss.PerformanceUserMarkLogLevel=1,ss.PerformanceConsoleLogLevel=2,ss.StartPerformanceCounter=ss._StartPerformanceCounterDisabled,ss.EndPerformanceCounter=ss._EndPerformanceCounterDisabled;class sn{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?r.breakLoop():setTimeout(()=>{for(let n=0;n=e)break;if(i(a),s&&s()){r.breakLoop();break}}r.executeNext()},n)},r)}}t2.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 sa{constructor(e){this.length=0,this.data=Array(e),this._id=sa._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return -1!==this.indexOf(e)}}sa._GlobalId=0;class so extends sa{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=(this.length+e.length)*2);for(let t=0;tthis.add(e,t))}get(e){let t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e))&&this.add(e,i),i}getOrAdd(e,t){let i=this.get(e);return void 0!==i?i:(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){let 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(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}}class sh{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(let 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(){for(let e of(this._keys.length=0,Object.keys(this)))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(let 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;tthis._setDefaultValue(e))}_setDefaultValue(e){var t,i,r,s,n;let a=null!==(r=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==r?r:typeof this[e],o=null===(n=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===n?void 0:n.default;switch(a){case"number":this[e]=null!=o?o:0;break;case"string":this[e]=null!=o?o:"";break;default:this[e]=null!=o&&o}}toString(){let e="";for(let t=0;tnew su,this)}serialize(){return i$.Serialize(this)}static Parse(e){return i$.Parse(()=>new su,e,null,null)}}iZ([iW()],su.prototype,"_globalHue",void 0),iZ([iW()],su.prototype,"_globalDensity",void 0),iZ([iW()],su.prototype,"_globalSaturation",void 0),iZ([iW()],su.prototype,"_globalExposure",void 0),iZ([iW()],su.prototype,"_highlightsHue",void 0),iZ([iW()],su.prototype,"_highlightsDensity",void 0),iZ([iW()],su.prototype,"_highlightsSaturation",void 0),iZ([iW()],su.prototype,"_highlightsExposure",void 0),iZ([iW()],su.prototype,"_midtonesHue",void 0),iZ([iW()],su.prototype,"_midtonesDensity",void 0),iZ([iW()],su.prototype,"_midtonesSaturation",void 0),iZ([iW()],su.prototype,"_midtonesExposure",void 0),i$._ColorCurvesParser=su.Parse;class sc extends sh{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class sd{constructor(){this.colorCurves=new su,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=sd.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new il(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=sd.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new tj}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"}static PrepareUniforms(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&&su.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,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,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===sd._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===sd.TONEMAPPING_ACES)?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,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&&su.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){let i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){let s=null!=t?t:r/i,n=Math.tan(.5*this.vignetteCameraFov),a=n*s,o=Math.sqrt(a*n);a=ss.Mix(a,o,this.vignetteStretch),n=ss.Mix(n,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);let l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);let t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return i$.Clone(()=>new sd,this)}serialize(){return i$.Serialize(this)}static Parse(e){let t=i$.Parse(()=>new sd,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}}sd.TONEMAPPING_STANDARD=0,sd.TONEMAPPING_ACES=1,sd._VIGNETTEMODE_MULTIPLY=0,sd._VIGNETTEMODE_OPAQUE=1,iZ([iG(7,void 0)],sd.prototype,"colorCurves",void 0),iZ([iW()],sd.prototype,"_colorCurvesEnabled",void 0),iZ([iH("colorGradingTexture")],sd.prototype,"_colorGradingTexture",void 0),iZ([iW()],sd.prototype,"_colorGradingEnabled",void 0),iZ([iW()],sd.prototype,"_colorGradingWithGreenDepth",void 0),iZ([iW()],sd.prototype,"_colorGradingBGR",void 0),iZ([iW()],sd.prototype,"_exposure",void 0),iZ([iW()],sd.prototype,"_toneMappingEnabled",void 0),iZ([iW()],sd.prototype,"_toneMappingType",void 0),iZ([iW()],sd.prototype,"_contrast",void 0),iZ([iW()],sd.prototype,"vignetteStretch",void 0),iZ([iW()],sd.prototype,"vignetteCenterX",void 0),iZ([iW()],sd.prototype,"vignetteCenterY",void 0),iZ([iW()],sd.prototype,"vignetteWeight",void 0),iZ([iG(8,void 0)],sd.prototype,"vignetteColor",void 0),iZ([iW()],sd.prototype,"vignetteCameraFov",void 0),iZ([iW()],sd.prototype,"_vignetteBlendMode",void 0),iZ([iW()],sd.prototype,"_vignetteEnabled",void 0),iZ([iW()],sd.prototype,"_ditheringEnabled",void 0),iZ([iW()],sd.prototype,"_ditheringIntensity",void 0),iZ([iW()],sd.prototype,"_skipFinalColorClamp",void 0),iZ([iW()],sd.prototype,"_applyByPostProcess",void 0),iZ([iW()],sd.prototype,"_isEnabled",void 0),i$._ImageProcessingConfigurationParser=sd.Parse,r$.prototype.createUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create uniform buffer");let r=new rW(i);return this.bindUniformBuffer(r),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),r.references=1,r},r$.prototype.createDynamicUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create dynamic uniform buffer");let r=new rW(i);return this.bindUniformBuffer(r),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),r.references=1,r},r$.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},r$.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},r$.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},r$.prototype.bindUniformBlock=function(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)};class sp{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=r?r:"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){let e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let i=this._uniformLocationPointer-e;for(let e=0;e0){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:i},16==t)t*=i;else{let e=4-t;t=t*i+e*i}r=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(sp._UpdatedUbosInFrame[this._name]||(sp._UpdatedUbosInFrame[this._name]=0),sp._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(void 0===r){if(this._buffer){ig.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;ea[t]=e),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==r||e.length!==h){if(e instanceof Array){let t=r/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,r,h);{let t=e.byteOffset+r;if(o){let i=new Float32Array(h),r=new Float32Array(e.buffer,t,h);return i.set(r),i}let i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return o?e.slice():e}}sf._Counter=0,sf.BYTE=5120,sf.UNSIGNED_BYTE=5121,sf.SHORT=5122,sf.UNSIGNED_SHORT=5123,sf.INT=5124,sf.UNSIGNED_INT=5125,sf.FLOAT=5126,sf.PositionKind="position",sf.NormalKind="normal",sf.TangentKind="tangent",sf.UVKind="uv",sf.UV2Kind="uv2",sf.UV3Kind="uv3",sf.UV4Kind="uv4",sf.UV5Kind="uv5",sf.UV6Kind="uv6",sf.ColorKind="color",sf.ColorInstanceKind="instanceColor",sf.MatricesIndicesKind="matricesIndices",sf.MatricesWeightsKind="matricesWeights",sf.MatricesIndicesExtraKind="matricesIndicesExtra",sf.MatricesWeightsExtraKind="matricesWeightsExtra";class sm{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){let i;if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(sf.NormalKind))return null;let r=this.pickedMesh.getIndices();(null==r?void 0:r.length)===0&&(r=null);let s=ie.Vector3[0],n=ie.Vector3[1],a=ie.Vector3[2];if(t){let e=this.pickedMesh.getVerticesData(sf.NormalKind),t=r?t5.FromArrayToRef(e,3*r[3*this.faceId],s):s.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),o=r?t5.FromArrayToRef(e,3*r[3*this.faceId+1],n):n.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),l=r?t5.FromArrayToRef(e,3*r[3*this.faceId+2],a):a.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]);t=t.scale(this.bu),o=o.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new t5(t.x+o.x+l.x,t.y+o.y+l.y,t.z+o.z+l.z)}else{let e=this.pickedMesh.getVerticesData(sf.PositionKind),t=r?t5.FromArrayToRef(e,3*r[3*this.faceId],s):s.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),o=r?t5.FromArrayToRef(e,3*r[3*this.faceId+1],n):n.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),l=r?t5.FromArrayToRef(e,3*r[3*this.faceId+2],a):a.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]),h=t.subtract(o),u=l.subtract(o);i=t5.Cross(h,u)}let o=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(ie.Matrix[0].copyFrom(i),(i=ie.Matrix[0]).setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(ie.Matrix[1]),i=ie.Matrix[1]),t5.TransformNormalToRef(t,i,t)};if(e&&o(this.pickedMesh,i),this.ray){let t=ie.Vector3[0].copyFrom(i);e||o(this.pickedMesh,t),t5.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=sf.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=t4.FromArray(i,2*t[3*this.faceId]),s=t4.FromArray(i,2*t[3*this.faceId+1]),n=t4.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(this.bu),s=s.scale(this.bv),n=n.scale(1-this.bu-this.bv),new t4(r.x+s.x+n.x,r.y+s.y+n.y)}}class sg{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[sf.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[sf.PositionKind]=new sf(this._scene.getEngine(),e,sf.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let 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(){let e=this._vertexBuffers[sf.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){let i=this._scene.activeCamera;return!!(i&&(t=t||i._postProcesses.filter(e=>null!=e))&&0!==t.length&&this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0)}directRender(e,t=null,i=!1,r=0,s=0,n=!1){var a;let o=this._scene.getEngine();for(let l=0;lnull!=e)).length||!this._scene.postProcessesEnabled)return;let o=this._scene.getEngine();for(let l=0,h=r.length;lt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.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,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&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;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=v.LeftClick&&i<=v.RightClick&&(l.type=1===r?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,r,s,n){let a=this._CreateMouseEvent(e,t,i,r,s,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=sM.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,i){case v.MouseWheelX:a.deltaX=r;break;case v.MouseWheelY:a.deltaY=r;break;case v.MouseWheelZ:a.deltaZ=r}return a}static _CreateMouseEvent(e,t,i,r,s,n){let a=this._CreateEvent(n),o=s.pollInput(e,t,v.Horizontal),l=s.pollInput(e,t,v.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=s.pollInput(e,t,x.DeltaHorizontal),a.movementY=s.pollInput(e,t,x.DeltaVertical),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,s),a.clientX=o,a.clientY=l,a.x=o,a.y=l,a.deviceType=e,a.deviceSlot=t,a.inputIndex=i,a}static _CreateKeyboardEvent(e,t,i,r){let s=this._CreateEvent(r);return this._CheckNonCharacterKeys(s,i),s.deviceType=g.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=1===t?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(g.Keyboard),r=i&&1===t.pollInput(g.Keyboard,0,18),s=i&&1===t.pollInput(g.Keyboard,0,17),n=i&&(1===t.pollInput(g.Keyboard,0,91)||1===t.pollInput(g.Keyboard,0,92)||1===t.pollInput(g.Keyboard,0,93)),a=i&&1===t.pollInput(g.Keyboard,0,16);e.altKey=r,e.ctrlKey=s,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}}class sO{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(e,t,r,s)=>{let n=sD.CreateDeviceEvent(e,t,r,s,this);i(e,t,n)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===g.Mouse||e===g.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}let sN=Object.keys(v).length/2;class sF{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=ss.IsSafari(),this._usingMacOS=rr()&&/(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=rr()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=rr()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=ss.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let r=this._inputs[e][t];if(!r)throw`Unable to find device ${g[e]}`;e>=g.DualShock&&e<=g.DualSense&&this._updateDevice(e,t,i);let s=r[i];if(void 0===s)throw`Unable to find input ${i} for device ${g[e]} in slot ${t}`;return i===v.Move&&ss.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this===null||void 0===this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let e of this._inputs)if(e)for(let t in e){let i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(g.Keyboard,0,255));let t=this._inputs[g.Keyboard][0];t&&(t[e.keyCode]=1,e.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&!this._metaKeys.includes(e.keyCode)&&this._metaKeys.push(e.keyCode),this._onInputChanged(g.Keyboard,0,e))},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(g.Keyboard,0,255));let t=this._inputs[g.Keyboard][0];if(t){if(t[e.keyCode]=0,e.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(let e of this._metaKeys){let i=sD.CreateDeviceEvent(g.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(g.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(g.Keyboard,0,e)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[g.Keyboard][0];for(let t=0;t{let t=this._getPointerType(e),i=t===g.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===g.Touch&&-1===i){let r=this._activeTouchIds.indexOf(-1);if(r>=0)i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i);else{ss.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);let r=this._inputs[t][i];r&&(e.inputIndex=v.Move,r[v.Horizontal]=e.clientX,r[v.Vertical]=e.clientY,t===g.Touch&&0===r[v.LeftClick]&&(r[v.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,e),this._usingSafari||-1===e.button||(e.inputIndex=e.button+2,r[e.button+2]=r[e.button+2]?0:1,this._onInputChanged(t,i,e)))},this._pointerDownEvent=e=>{let t=this._getPointerType(e),i=t===g.Mouse?0:e.pointerId;if(t===g.Touch){let t=this._activeTouchIds.indexOf(-1);if(t>=0)i=t,this._activeTouchIds[t]=e.pointerId;else{ss.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===g.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);let r=this._inputs[t][i];if(r){let s=r[v.Horizontal],n=r[v.Vertical];if(t===g.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){}r[v.Horizontal]=e.clientX,r[v.Vertical]=e.clientY,r[e.button+2]=1,e.inputIndex=e.button+2,this._onInputChanged(t,i,e),(s!==e.clientX||n!==e.clientY)&&(e.inputIndex=v.Move,this._onInputChanged(t,i,e))}},this._pointerUpEvent=e=>{var t,i,r,s,n;let a=this._getPointerType(e),o=a===g.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(a===g.Touch){if(-1===o)return;this._activeTouchIds[o]=-1}let l=null===(t=this._inputs[a])||void 0===t?void 0:t[o];if(l&&0!==l[e.button+2]){let t=l[v.Horizontal],h=l[v.Vertical];l[v.Horizontal]=e.clientX,l[v.Vertical]=e.clientY,l[e.button+2]=0,void 0===e.pointerId&&(e.pointerId=this._mouseId),(t!==e.clientX||h!==e.clientY)&&(e.inputIndex=v.Move,this._onInputChanged(a,o,e)),e.inputIndex=e.button+2,a===g.Mouse&&this._mouseId>=0&&(null===(r=(i=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(n=(s=this._elementToAttachTo).hasPointerCapture)||void 0===n?void 0:n.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(a,o,e),a===g.Touch&&this._onDeviceDisconnected(a,o)}},this._pointerCancelEvent=e=>{var t,i,r,s;if("mouse"===e.pointerType){let e=this._inputs[g.Mouse][0];this._mouseId>=0&&(null===(i=(t=this._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=v.LeftClick;t<=v.BrowserForward;t++)if(1===e[t]){e[t]=0;let i=sD.CreateDeviceEvent(g.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(g.Mouse,0,i)}}else{let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;(null===(s=(r=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(r,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[g.Touch][t][v.LeftClick]=0;let i=sD.CreateDeviceEvent(g.Touch,t,v.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(g.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(g.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1,t=function(){};try{let i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{var e,t,i,r,s;if(this.isDeviceAvailable(g.Mouse)){let i=this._inputs[g.Mouse][0];this._mouseId>=0&&(null===(t=(e=this._elementToAttachTo).hasPointerCapture)||void 0===t?void 0:t.call(e,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let e=v.LeftClick;e<=v.BrowserForward;e++)if(1===i[e]){i[e]=0;let t=sD.CreateDeviceEvent(g.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(g.Mouse,0,t)}}if(this.isDeviceAvailable(g.Touch)){let e=this._inputs[g.Touch];for(let t=0;t{let t=g.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,sN));let i=this._inputs[t][0];i&&(i[v.MouseWheelX]=e.deltaX||0,i[v.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[v.MouseWheelZ]=e.deltaZ||0,void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[v.MouseWheelX]&&(e.inputIndex=v.MouseWheelX,this._onInputChanged(t,0,e)),0!==i[v.MouseWheelY]&&(e.inputIndex=v.MouseWheelY,this._onInputChanged(t,0,e)),0!==i[v.MouseWheelZ]&&(e.inputIndex=v.MouseWheelZ,this._onInputChanged(t,0,e)))},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(g.Mouse)){let e=this._inputs[g.Mouse][0];e[v.MouseWheelX]=0,e[v.MouseWheelY]=0,e[v.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return -1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?g.DualSense:g.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?g.Xbox:-1!==e.indexOf("057e")?g.Switch:g.Generic}_getPointerType(e){let t=g.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=g.Touch),t}}class sw{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new tj,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class sL{constructor(e){this._registeredManagers=[],this._refCount=0,this.registerManager=e=>{for(let t=0;t{let t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};let t=Object.keys(g).length/2;this._devices=Array(t);let i=(e,t)=>{for(let i of(this._devices[e]||(this._devices[e]=[]),this._devices[e][t]||(this._devices[e][t]=t),this._registeredManagers)){let r=new sw(this._deviceInputSystem,e,t);i._addDevice(r)}},r=(e,t)=>{var i;for(let r of((null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t],this._registeredManagers))r._removeDevice(e,t)},s=(e,t,i)=>{if(i)for(let r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new sO(i,r,s):this._deviceInputSystem=new sF(e,i,r,s)}dispose(){this._deviceInputSystem.dispose()}}class sB{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){let t=Object.keys(g).length/2;this._devices=Array(t),this._firstDevice=Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new sL(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new tj(e=>{for(let t of this._devices)if(t)for(let i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)}),this.onDeviceDisconnectedObservable=new tj,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]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,r;let s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(r=this._devices[e])||void 0===r?void 0:r[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;null===(s=null===(r=this._devices[e])||void 0===r?void 0:r[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case g.Keyboard:case g.Mouse:this._firstDevice[e]=0;break;case g.Touch:case g.DualSense:case g.DualShock:case g.Xbox:case g.Switch:case g.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i=v.MouseWheelX&&t.inputIndex<=v.MouseWheelZ?sS.POINTERWHEEL:sS.POINTERMOVE;r.onPointerMove&&(e=e||this._pickMove(t),r.onPointerMove(t,e,a)),e?(i=new sA(a,t,e),this._setRayOnPointerInfo(e,t)):(i=new sA(a,t,null,this),this._movePointerInfo=i),r.onPointerObservable.hasObservers()&&r.onPointerObservable.notifyObservers(i,a)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&i._pickingAvailable&&!e.ray&&(e.ray=i.createPickingRay(t.offsetX,t.offsetY,t7.Identity(),i.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,i){let r=this._scene,s=new sy(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){let t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){let r=i.getEngine().getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){let e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(r.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=v.Move,this._checkPrePointerObservable(e,i,sS.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,sS.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){let i;let r=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(5,ic.CreateNew(e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(2,ic.CreateNew(e.pickedMesh,t,e));break;case 1:i.processTrigger(4,ic.CreateNew(e.pickedMesh,t,e));break;case 2:i.processTrigger(3,ic.CreateNew(e.pickedMesh,t,e))}i.hasSpecificTrigger(8)&&window.setTimeout(()=>{let e=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh,!1,r.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&i&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>sV.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(8,ic.CreateNew(e.pickedMesh,t)))},sV.LongPressDelay)}}else for(let i of r._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s=sS.POINTERDOWN;e?(r.onPointerDown&&r.onPointerDown(t,e,s),i=new sA(s,t,e),this._setRayOnPointerInfo(e,t)):i=new sA(s,t,null,this),r.onPointerObservable.hasObservers()&&r.onPointerObservable.notifyObservers(i,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let r=new PointerEvent("pointerup",t);r.inputIndex=v.Move;let s=new sU;i?s.doubleClick=!0:s.singleClick=!0,this._checkPrePointerObservable(e,r,sS.POINTERUP)||this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){let r=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){let i=sS.POINTERPICK,s=new sA(i,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,i)}let s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,ic.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,ic.CreateNew(e.pickedMesh,t,e));let r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,ic.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,ic.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let s=new sA(sS.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,sS.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,sS.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let s=0;if(i.singleClick?s=sS.POINTERTAP:i.doubleClick&&(s=sS.POINTERDOUBLETAP),s){let i=new sA(s,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(s)&&r.onPointerObservable.notifyObservers(i,s)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){let s=this._scene,n=s.getEngine();r||(r=n.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new sB(n),this._initActionManager=e=>{if(!this._meshPickProceed){let t=!s.skipPointerUpPicking&&(0!==s._registeredActions||this._checkForPicking()||s.onPointerUp)?s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers):null;this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>sV.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){let t=this._delayedClicks[e].evt,i=sS.POINTERTAP,r=new sA(i,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(i)&&s.onPointerObservable.notifyObservers(r,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,r)=>{var s,n;let a=new sU;this._currentPickResult=null;let o=null,l=e.hasSpecificMask(sS.POINTERPICK)||t.hasSpecificMask(sS.POINTERPICK)||e.hasSpecificMask(sS.POINTERTAP)||t.hasSpecificMask(sS.POINTERTAP)||e.hasSpecificMask(sS.POINTERDOUBLETAP)||t.hasSpecificMask(sS.POINTERDOUBLETAP);!l&&tH&&(o=this._initActionManager(o,a))&&(l=o.hasPickTriggers);let h=!1;if(l){let l=i.button;if(a.hasSwiped=this._isPointerSwiping(),!a.hasSwiped){let u=!sV.ExclusiveDoubleClickMode;if(!u&&(u=!e.hasSpecificMask(sS.POINTERDOUBLETAP)&&!t.hasSpecificMask(sS.POINTERDOUBLETAP))&&!tH.HasSpecificTrigger(6)&&(o=this._initActionManager(o,a))&&(u=!o.hasSpecificTrigger(6)),u)(Date.now()-this._previousStartingPointerTime>sV.DoubleClickDelay||l!==this._previousButtonPressed)&&(a.singleClick=!0,r(a,this._currentPickResult),h=!0);else{let e={evt:i,clickInfo:a,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,l,a,r),sV.DoubleClickDelay)};this._delayedClicks[l]=e}let c=e.hasSpecificMask(sS.POINTERDOUBLETAP)||t.hasSpecificMask(sS.POINTERDOUBLETAP);!c&&tH.HasSpecificTrigger(6)&&(o=this._initActionManager(o,a))&&(c=o.hasSpecificTrigger(6)),c&&(l===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>sV.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>sV.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=v.MouseWheelX&&e.inputIndex<=v.MouseWheelZ?sS.POINTERWHEEL:sS.POINTERMOVE)||!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking){this._processPointerMove(new sm,e);return}s.pointerMovePredicate||(s.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0));let t=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;let i;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,sV.ExclusiveDoubleClickMode){for(let i=0;ie.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0)),this._pickedDownMesh=null,i=!s.skipPointerDownPicking&&(0!==s._registeredActions||this._checkForPicking()||s.onPointerDown)?s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers):new sm,this._processPointerDown(i,e))},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),s.preventDefaultOnPointerUp&&r&&(e.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,e,(t,i)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,sS.POINTERUP)){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1);return}!t.hasSwiped&&(t.singleClick&&s.onPrePointerObservable.hasSpecificMask(sS.POINTERTAP)&&this._checkPrePointerObservable(null,e,sS.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&s.onPrePointerObservable.hasSpecificMask(sS.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,sS.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[e.pointerId]){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(s.cameraToUseForPointers||s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0)),!this._meshPickProceed&&(tH&&tH.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=e=>{let t=sR.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){let i=new sP(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let i=new sI(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(14,ic.CreateNewFromScene(s,e))},this._onKeyUp=e=>{let t=sR.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){let i=new sP(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let i=new sI(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(15,ic.CreateNewFromScene(s,e))},this._deviceSourceManager.onDeviceConnectedObservable.add(r=>{r.deviceType===g.Mouse?r.onInputChangedObservable.add(s=>{s.inputIndex===v.LeftClick||s.inputIndex===v.MiddleClick||s.inputIndex===v.RightClick||s.inputIndex===v.BrowserBack||s.inputIndex===v.BrowserForward?t&&1===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===v.Move?this._onPointerMove(s):(s.inputIndex===v.MouseWheelX||s.inputIndex===v.MouseWheelY||s.inputIndex===v.MouseWheelZ)&&this._onPointerMove(s))}):r.deviceType===g.Touch?r.onInputChangedObservable.add(s=>{s.inputIndex===v.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===v.Move&&this._onPointerMove(s)}):r.deviceType===g.Keyboard&&r.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,i,r){let s;if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let n=this._meshUnderPointerId[t];n&&(s=n._getActionManagerForTrigger(10))&&s.processTrigger(10,ic.CreateNew(n,r,{pointerId:t})),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,(s=e._getActionManagerForTrigger(9))&&s.processTrigger(9,ic.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){for(let t in this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null),this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}sV.DragMovementThreshold=10,sV.LongPressDelay=500,sV.DoubleClickDelay=300,sV.ExclusiveDoubleClickMode=!1;class sk{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){sk.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){sk.Enabled&&(this._startMonitoringTime=ra.Now)}endMonitoring(e=!0){if(!sk.Enabled)return;e&&this.fetchNewFrame();let t=ra.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;let e=ra.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}sk.Enabled=!0;class sG{constructor(e,t,i,r){this.normal=new t5(e,t,i),this.d=r}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new sG(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){return 397*this.normal.getHashCode()^(0|this.d)}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),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){let t=sG._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,s=this.normal.y,n=this.normal.z,a=this.d,o=r*i[0]+s*i[1]+n*i[2]+a*i[3];return new sG(o,r*i[4]+s*i[5]+n*i[6]+a*i[7],r*i[8]+s*i[9]+n*i[10]+a*i[11],r*i[12]+s*i[13]+n*i[14]+a*i[15])}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r;let s=t.x-e.x,n=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,u=n*h-a*l,c=a*o-s*h,d=s*l-n*o,p=Math.sqrt(u*u+c*c+d*d);return r=0!==p?1/p:0,this.normal.x=u*r,this.normal.y=c*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return t5.Dot(this.normal,e)<=t}signedDistanceTo(e){return t5.Dot(e,this.normal)+this.d}static FromArray(e){return new sG(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new sG(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new sG(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){let r=-(t.x*e.x+t.y*e.y+t.z*e.z);return t5.Dot(i,t)+r}}sG._TmpMatrix=t7.Identity();class sz{static GetPlanes(e){let t=[];for(let e=0;e<6;e++)t.push(new sG(0,0,0,0));return sz.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){sz.GetNearPlaneToRef(e,t[0]),sz.GetFarPlaneToRef(e,t[1]),sz.GetLeftPlaneToRef(e,t[2]),sz.GetRightPlaneToRef(e,t[3]),sz.GetTopPlaneToRef(e,t[4]),sz.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(0>t[i].dotCoordinate(e))return!1;return!0}}class sW{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}sW._UniqueIdCounter=1;class sH{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}sH.FALLOFF_DEFAULT=0,sH.FALLOFF_PHYSICAL=1,sH.FALLOFF_GLTF=2,sH.FALLOFF_STANDARD=3,sH.LIGHTMAP_DEFAULT=0,sH.LIGHTMAP_SPECULAR=1,sH.LIGHTMAP_SHADOWSONLY=2,sH.INTENSITYMODE_AUTOMATIC=0,sH.INTENSITYMODE_LUMINOUSPOWER=1,sH.INTENSITYMODE_LUMINOUSINTENSITY=2,sH.INTENSITYMODE_ILLUMINANCE=3,sH.INTENSITYMODE_LUMINANCE=4,sH.LIGHTTYPEID_POINTLIGHT=0,sH.LIGHTTYPEID_DIRECTIONALLIGHT=1,sH.LIGHTTYPEID_SPOTLIGHT=2,sH.LIGHTTYPEID_HEMISPHERICLIGHT=3;class sX{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(y||(y={}));class sY extends tW{static DefaultMaterialFactory(e){throw iL("StandardMaterial")}static CollisionCoordinatorFactory(){throw iL("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case y.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case y.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case y.Aggressive: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(16))}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(16))}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 sV.DragMovementThreshold}static set DragMovementThreshold(e){sV.DragMovementThreshold=e}static get LongPressDelay(){return sV.LongPressDelay}static set LongPressDelay(e){sV.LongPressDelay=e}static get DoubleClickDelay(){return sV.DoubleClickDelay}static set DoubleClickDelay(e){sV.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return sV.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){sV.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){let r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,s=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return ie.Vector4[0].set(r.x,r.y,r.z,s?-1:1),e&&(i?e.setFloat3(t,ie.Vector4[0].x,ie.Vector4[0].y,ie.Vector4[0].z):e.setVector4(t,ie.Vector4[0])),ie.Vector4[0]}finalizeSceneUbo(){let 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(16))}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(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}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(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=tJ(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=sY.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=sY.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e),e.addFromContainer&&e.serialize&&this._serializableComponents.push(e)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new sV(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new il(.2,.2,.3,1),this.ambientColor=new io(0,0,0),this.environmentIntensity=1,this._performancePriority=y.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new tj,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 tj,this._onDisposeObserver=null,this.onBeforeRenderObservable=new tj,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new tj,this.onAfterRenderCameraObservable=new tj,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new tj,this.onAfterAnimationsObservable=new tj,this.onBeforeDrawPhaseObservable=new tj,this.onAfterDrawPhaseObservable=new tj,this.onReadyObservable=new tj,this.onBeforeCameraRenderObservable=new tj,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new tj,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new tj,this.onAfterActiveMeshesEvaluationObservable=new tj,this.onBeforeParticlesRenderingObservable=new tj,this.onAfterParticlesRenderingObservable=new tj,this.onDataLoadedObservable=new tj,this.onNewCameraAddedObservable=new tj,this.onCameraRemovedObservable=new tj,this.onNewLightAddedObservable=new tj,this.onLightRemovedObservable=new tj,this.onNewGeometryAddedObservable=new tj,this.onGeometryRemovedObservable=new tj,this.onNewTransformNodeAddedObservable=new tj,this.onTransformNodeRemovedObservable=new tj,this.onNewMeshAddedObservable=new tj,this.onMeshRemovedObservable=new tj,this.onNewSkeletonAddedObservable=new tj,this.onSkeletonRemovedObservable=new tj,this.onNewMaterialAddedObservable=new tj,this.onNewMultiMaterialAddedObservable=new tj,this.onMaterialRemovedObservable=new tj,this.onMultiMaterialRemovedObservable=new tj,this.onNewTextureAddedObservable=new tj,this.onTextureRemovedObservable=new tj,this.onBeforeRenderTargetsRenderObservable=new tj,this.onAfterRenderTargetsRenderObservable=new tj,this.onBeforeStepObservable=new tj,this.onAfterStepObservable=new tj,this.onActiveCameraChanged=new tj,this.onActiveCamerasChanged=new tj,this.onBeforeRenderingGroupObservable=new tj,this.onAfterRenderingGroupObservable=new tj,this.onMeshImportedObservable=new tj,this.onAnimationFileImportedObservable=new tj,this._registeredForLateAnimationBindings=new so(256),this._pointerPickingConfiguration=new sX,this.onPrePointerObservable=new tj,this.onPointerObservable=new tj,this.onPreKeyboardObservable=new tj,this.onKeyboardObservable=new tj,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=sY.FOGMODE_NONE,this.fogColor=new io(.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 t5(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new so(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new sk,this._activeIndices=new sk,this._activeParticles=new sk,this._activeBones=new sk,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=Array(256),this._activeRequests=[],this._pendingData=[],this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new sa(256),this._processedMaterials=new sa(256),this._renderTargets=new so(256),this._materialsRenderTargets=new so(256),this._activeParticleSystems=new sa(256),this._activeSkeletons=new so(32),this._softwareSkinnedMeshes=new so(32),this._activeAnimatables=[],this._transformMatrix=t7.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=sE.Create(),this._beforeClearStage=sE.Create(),this._beforeRenderTargetClearStage=sE.Create(),this._gatherRenderTargetsStage=sE.Create(),this._gatherActiveCameraRenderTargetsStage=sE.Create(),this._isReadyForMeshStage=sE.Create(),this._beforeEvaluateActiveMeshStage=sE.Create(),this._evaluateSubMeshStage=sE.Create(),this._preActiveMeshStage=sE.Create(),this._cameraDrawRenderTargetStage=sE.Create(),this._beforeCameraDrawStage=sE.Create(),this._beforeRenderTargetDrawStage=sE.Create(),this._beforeRenderingGroupDrawStage=sE.Create(),this._beforeRenderingMeshStage=sE.Create(),this._afterRenderingMeshStage=sE.Create(),this._afterRenderingGroupDrawStage=sE.Create(),this._afterCameraDrawStage=sE.Create(),this._afterCameraPostProcessStage=sE.Create(),this._afterRenderTargetDrawStage=sE.Create(),this._afterRenderTargetPostProcessStage=sE.Create(),this._afterRenderStage=sE.Create(),this._pointerMoveStage=sE.Create(),this._pointerDownStage=sE.Create(),this._pointerUpStage=sE.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=[];let i=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);e=this._engine=e||t2.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(t2._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new sT(this),sg&&(this.postProcessManager=new sg(this)),this._createUbo(),sd&&(this._imageProcessingConfiguration=new sd),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.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,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}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,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var t,i,r;let s;if(this._isDisposed)return!1;let n=this.getEngine(),a=n.currentRenderPassId;n.currentRenderPassId=null!==(i=null===(t=this.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==i?i:a;let o=!0;for(this._pendingData.length>0&&(o=!1),null===(r=this.prePassRenderer)||void 0===r||r.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&o&&(o=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),s=0;s0;for(let e of this._isReadyForMeshStage)e.action(t,i)||(o=!1);if(!e)continue;let r=t.material||this.defaultMaterial;if(r){if(r._storeEffectOnSubMeshes)for(let e of t.subMeshes){let t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else r.hasRenderTargetTextures&&null!=r.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(r)&&(this._processedMaterials.push(r),this._materialsRenderTargets.concatWithNoDuplicate(r.getRenderTargetTextures()))}}if(e)for(s=0;s0)for(let e of this.activeCameras)e.isReady(!0)||(o=!1);else this.activeCamera&&!this.activeCamera.isReady(!0)&&(o=!1);for(let e of this.particleSystems)e.isReady()||(o=!1);if(this.layers)for(let e of this.layers)e.isReady()||(o=!1);return n.areAllEffectsReady()||(o=!1),n.currentRenderPassId=a,o}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){let 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){let t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,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){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=ra.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){i||r||!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?sz.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=sz.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):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){let t=new sp(this._engine,void 0,!1,null!=e?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 sW.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){let i=this.meshes.indexOf(e);return -1===i||(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(e=>{this.removeMesh(e)}),i}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){let t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){let 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){let t=this.skeletons.indexOf(e);return -1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return -1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(-1!==t){for(let 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){let t=this.cameras.indexOf(e);if(-1===t||(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let 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){let t=this.particleSystems.indexOf(e);return -1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){let t=this.animations.indexOf(e);return -1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return -1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return -1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(-1!==t&&tt.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=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){let t=this.getMeshById(e);if(t)return t;let i=this.getTransformNodeById(e);if(i)return i;let r=this.getLightById(e);if(r)return r;let s=this.getCameraById(e);return s?s:this.getBoneById(e)||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let i=this.getTransformNodeByName(e);if(i)return i;let r=this.getLightByName(e);if(r)return r;let s=this.getCameraByName(e);return s?s:this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let e=0;ee.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode){this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let e=this._activeMeshes.length;for(let t=0;t0&&(i.layerMask&this.activeCamera.layerMask)!=0&&(this._skipFrustumClipping||i.alwaysSelectAsActiveMesh||i.isInFrustum(this._frustumPlanes)))){for(let e of(this._activeMeshes.push(i),this.activeCamera._activeMeshes.push(i),r!==i&&r._activate(this._renderId,!1),this._preActiveMeshStage))e.action(i);i._activate(this._renderId,!1)&&(i.isAnInstance?i._internalAbstractMeshDataInfo._actAsRegularMesh&&(r=i):r._internalAbstractMeshDataInfo._onlyForInstances=!1,r._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(i,r)),i._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){let r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||1===s;for(let n=0;n0&&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),this._gatherActiveCameraRenderTargetsStage))i.action(this._renderTargets);let o=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){ss.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(let e of this._cameraDrawRenderTargetStage)o=e.action(this.activeCamera)||o;this._intermediateRendering=!1}for(let t of(this._engine.currentRenderPassId=null!==(n=null!==(s=null===(r=e.outputRenderTarget)||void 0===r?void 0:r.renderPassId)&&void 0!==s?s:e.renderPassId)&&void 0!==n?n:0,o&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame(),this._beforeCameraDrawStage))t.action(this.activeCamera);for(let e of(this.onBeforeDrawPhaseObservable.notifyObservers(this),a.snapshotRendering&&1===a.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this),this._afterCameraDrawStage))e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(let e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1)||(13===i.trigger&&i._executeCurrent(ic.CreateNew(t,void 0,r)),t.actionManager.hasSpecificTrigger(13,e=>r===(e.mesh?e.mesh:e))&&13!==i.trigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(sY.MinDeltaTime,Math.min(this._engine.getDeltaTime(),sY.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),i=1e3/t/1e3,r=0,s=this._engine.getLockstepMaxSteps(),n=Math.floor(e/t);for(n=Math.min(n,s);e>0&&r0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}for(let e of(this._engine.currentRenderPassId=null!==(s=null==a?void 0:a.renderPassId)&&void 0!==s?s:0,this.activeCamera=a,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this._beforeClearStage))e.action();for(let e of(this._clearFrameBuffer(this.activeCamera),this._gatherRenderTargetsStage))e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}for(let e of(this._checkIntersections(),this._afterRenderStage))e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;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,this._activeRequests.slice()))e.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){ig.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0)),this._disposeList(this.transformNodes,e=>e.dispose(!0));let e=this.cameras;this._disposeList(e),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 t=this._engine.scenes.indexOf(this);t>-1&&this._engine.scenes.splice(t,1),t2._LastCreatedScene===this&&(this._engine.scenes.length>0?t2._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:t2._LastCreatedScene=null),(t=this._engine._virtualScenes.indexOf(this))>-1&&this._engine._virtualScenes.splice(t,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){let i=e.slice(0);for(let e of(t=null!=t?t:e=>e.dispose(),i))t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;let r=e.getBoundingInfo(),s=r.boundingBox.minimumWorld,n=r.boundingBox.maximumWorld;t5.CheckExtends(s,t,i),t5.CheckExtends(n,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw iL("Ray")}createPickingRayToRef(e,t,i,r,s,n=!1,a=!1){throw iL("Ray")}createPickingRayInCameraSpace(e,t,i){throw iL("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw iL("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,r,s,n){let a=iL("Ray",!0);return a&&ig.Warn(a),new sm}pickWithBoundingInfo(e,t,i,r,s){let n=iL("Ray",!0);return n&&ig.Warn(n),new sm}pickWithRay(e,t,i,r){throw iL("Ray")}multiPick(e,t,i,r,s){throw iL("Ray")}multiPickWithRay(e,t,i){throw iL("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of(this.postProcessManager&&this.postProcessManager._rebuild(),this._components))e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;let r=[];for(let s in e){let n=e[s];iF&&iF.MatchesQuery(n,t)&&(!i||i(n))&&r.push(n)}return r}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,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}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(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let i of this.materials)(!t||t(i))&&i.markAsDirty(e)}_loadFile(e,t,i,r,s,n,a){let o=r6(e,t,i,r?this.offlineProvider:void 0,s,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_loadFileAsync(e,t,i,r,s){return new Promise((n,a)=>{this._loadFile(e,e=>{n(e)},t,i,r,(e,t)=>{a(t)},s)})}_requestFile(e,t,i,r,s,n,a){let o=r8(e,t,i,r?this.offlineProvider:void 0,s,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_requestFileAsync(e,t,i,r,s){return new Promise((n,a)=>{this._requestFile(e,e=>{n(e)},t,i,r,e=>{a(e)},s)})}_readFile(e,t,i,r,s){let n=r5(e,t,i,r,s);return this._activeRequests.push(n),n.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),n}_readFileAsync(e,t,i){return new Promise((r,s)=>{this._readFile(e,e=>{r(e)},t,i,e=>{s(e)})})}getPerfCollector(){throw iL("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)}}sY.FOGMODE_NONE=0,sY.FOGMODE_EXP=1,sY.FOGMODE_EXP2=2,sY.FOGMODE_LINEAR=3,sY.MinDeltaTime=1,sY.MaxDeltaTime=1e3,function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(A||(A={}));class sj{}sj.X=new t5(1,0,0),sj.Y=new t5(0,1,0),sj.Z=new t5(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(R||(R={}));class sK extends i0{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,i=null,r=null,s=null,n=null,a=null){var o;super(e,t.getScene()),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=null!==(o=null==r?void 0:r.clone())&&void 0!==o?o:t7.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=n?n:this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new t7,this._absoluteBindMatrix=new t7,this._absoluteInverseBindMatrix=new t7,this._finalMatrix=new t7,t.bones.push(this),this.setParent(i,!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){let 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(){var e;if(this._linkedTransformNode){let t=ie.Vector3[0],i=ie.Quaternion[0],r=ie.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:t8.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}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=t5.Zero(),this._localRotation=t8.Zero(),this._localPosition=t5.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,t7.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?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;ethis._absoluteBindMatrix.determinant()?-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=A.LOCAL,i,r=!0){let s=this.getLocalMatrix();if(t==A.LOCAL)r?(s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z)):s.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let n=sK._TmpMats[0],a=sK._TmpVecs[0];this.parent?i&&t?(n.copyFrom(this.parent.getAbsoluteMatrix()),n.multiplyToRef(t,n)):n.copyFrom(this.parent.getAbsoluteMatrix()):t7.IdentityToRef(n),r&&n.setTranslationFromFloats(0,0,0),n.invert(),t5.TransformCoordinatesToRef(e,n,a),r?(s.addAtIndex(12,a.x),s.addAtIndex(13,a.y),s.addAtIndex(14,a.z)):s.setTranslationFromFloats(a.x,a.y,a.z)}this._markAsDirtyAndDecompose()}translate(e,t=A.LOCAL,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=A.LOCAL,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,A.WORLD,t)}scale(e,t,i,r=!1){let s=this.getLocalMatrix(),n=sK._TmpMats[0];for(let r of(t7.ScalingToRef(e,t,i,n),n.multiplyToRef(s,s),n.invert(),this.children)){let s=r.getLocalMatrix();s.multiplyToRef(n,s),s.multiplyAtIndex(12,e),s.multiplyAtIndex(13,t),s.multiplyAtIndex(14,i),r._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(let s of this.children)s.scale(e,t,i,r)}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,i,r=A.LOCAL,s){if(r===A.LOCAL){let n=sK._TmpQuat;t8.RotationYawPitchRollToRef(e,t,i,n),this.setRotationQuaternion(n,r,s);return}let n=sK._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,s))return;let a=sK._TmpMats[1];t7.RotationYawPitchRollToRef(e,t,i,a),n.multiplyToRef(a,a),this._rotateWithMatrix(a,r,s)}rotate(e,t,i=A.LOCAL,r){let s=sK._TmpMats[0];s.setTranslationFromFloats(0,0,0),t7.RotationAxisToRef(e,t,s),this._rotateWithMatrix(s,i,r)}setAxisAngle(e,t,i=A.LOCAL,r){if(i===A.LOCAL){let s=sK._TmpQuat;t8.RotationAxisToRef(e,t,s),this.setRotationQuaternion(s,i,r);return}let s=sK._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;let n=sK._TmpMats[1];t7.RotationAxisToRef(e,t,n),s.multiplyToRef(n,n),this._rotateWithMatrix(n,i,r)}setRotation(e,t=A.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=A.LOCAL,i){if(t===A.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}let r=sK._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=sK._TmpMats[1];t7.FromQuaternionToRef(e,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,t,i)}setRotationMatrix(e,t=A.LOCAL,i){if(t===A.LOCAL){let r=sK._TmpQuat;t8.FromRotationMatrixToRef(e,r),this.setRotationQuaternion(r,t,i);return}let r=sK._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=sK._TmpMats[1];s.copyFrom(e),r.multiplyToRef(e,s),this._rotateWithMatrix(s,t,i)}_rotateWithMatrix(e,t=A.LOCAL,i){let r=this.getLocalMatrix(),s=r.m[12],n=r.m[13],a=r.m[14],o=this.getParent(),l=sK._TmpMats[3],h=sK._TmpMats[4];o&&t==A.WORLD?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):t==A.WORLD&&i?(l.copyFrom(i.getWorldMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(s,n,a),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){let i=sK._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),t7.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):t7.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=A.LOCAL,t=null){let i=t5.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=A.LOCAL,t,i){if(e==A.LOCAL){let e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let r=sK._TmpMats[0];t&&e?(r.copyFrom(this.getAbsoluteMatrix()),r.multiplyToRef(e,r)):r=this.getAbsoluteMatrix(),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){let t=t5.Zero();return this.getPositionToRef(A.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(A.WORLD,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);let e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}let e=this.children,t=e.length;for(let i=0;i-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i-1){let s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){let r=s[i];(!e||r.animation.name==e)&&(!t||t(r.target))&&(r.dispose(),s.splice(i,1))}0==s.length&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else{let e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);let t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){let t;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 i=!1,r=this._runtimeAnimations;for(t=0;t0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;let t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;let i=this._animationTime;for(let e=0;ee.playOrder-t.playOrder)},sY.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,n=1,a,o,l,h,u=!1){let c=this.beginAnimation(e,t,i,s,n,a,o,!1,l,h,u);return c.weight=r,c},sY.prototype.beginAnimation=function(e,t,i,r,s=1,n,a,o=!0,l,h,u=!1){t>i&&s>0&&(s*=-1),o&&this.stopAnimation(e,void 0,l),a||(a=new s$(this,e,t,i,r,s,n,void 0,h,u));let c=!l||l(e);if(e.animations&&c&&a.appendAnimations(e,e.animations),e.getAnimatables){let u=e.getAnimatables();for(let e=0;er&&n>0)n*=-1;else if(r>i&&n<0){let e=r;r=i,i=e}return new s$(this,e,i,r,s,n,a,t,o,l)},sY.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,n,a,o,l,h=!1){let u=e.getDescendants(t),c=[];for(let t of(c.push(this.beginDirectAnimation(e,i,r,s,n,a,o,l,h)),u))c.push(this.beginDirectAnimation(t,i,r,s,n,a,o,l,h));return c},sY.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,s),o.scaleAndAddToRef(l,i)}s.normalize()}for(let t=0;t0)s.copyFrom(r);else if(1===e.animations.length){if(t8.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,n,a=1;if(e.totalWeight<1){let t=1-e.totalWeight;n=[],(i=[]).push(r),n.push(t)}else{if(2===e.animations.length&&(t8.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],a=e.totalWeight}for(let t=0;t=h&&n.frame<=u&&(r?(o=n.value.clone(),f?(a=o.getTranslation(),o.setTranslation(a.scaleInPlace(m))):g&&s?(a=o.getTranslation(),o.setTranslation(a.multiplyInPlace(s))):o=n.value):o=n.value,v.push({frame:n.frame+i,value:o}));return this.animations[0].createRange(t,h+i,u+i),!0},function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(I||(I={}));class sq{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){let i=t.subtract(e);return new sq(Math.atan2(i.y,i.x))}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new sq(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;return new sq(Math.acos(r=tK.Clamp(r,-1,1)))}static FromRadians(e){return new sq(e)}static FromDegrees(e){return new sq(e*Math.PI/180)}}class sQ{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,n=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new t4((s*(t.y-i.y)-n*(e.y-t.y))/a,((e.x-t.x)*n-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=sq.BetweenTwoPoints(this.centerPoint,this.startPoint);let o=this.startAngle.degrees(),l=sq.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=sq.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-o>180&&(l-=360),l-o<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-o<0?I.CW:I.CCW,this.angle=sq.FromDegrees(this.orientation===I.CW?o-h:h-o)}}class sZ{constructor(e,t){this._points=[],this._length=0,this.closed=!1,this._points.push(new t4(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new t4(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let n=new sQ(this._points[this._points.length-1],new t4(e,t),new t4(i,r)),a=n.angle.radians()/s;n.orientation===I.CW&&(a*=-1);let o=n.startAngle.radians()+a;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r,a=this._points[this._points.length-1];for(let o=0;o<=s;o++){let l=o/s,h=n(l,a.x,e,i),u=n(l,a.y,t,r);this.addLineTo(h,u)}return this}addBezierCurveTo(e,t,i,r,s,n,a=36){if(this.closed)return this;let o=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s,l=this._points[this._points.length-1];for(let h=0;h<=a;h++){let u=h/a,c=o(u,l.x,e,i,s),d=o(u,l.y,t,r,n);this.addLineTo(c,d)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(o<0&&(i=this._points[s],a=-a,n=this._points[r],o=-o),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{let r=o*(e.x-i.x)-a*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r1)return t4.Zero();let t=e*this.length(),i=0;for(let e=0;e=i&&t<=a){let e=n.normalize(),r=t-i;return new t4(s.x+e.x*r,s.y+e.y*r)}i=a}return t4.Zero()}static StartingAt(e,t){return new sZ(e,t)}}class sJ{constructor(e,t=null,i,r=!1){this.path=e,this._curve=[],this._distances=[],this._tangents=[],this._normals=[],this._binormals=[],this._pointAtData={id:0,point:t5.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:t7.Identity()};for(let t=0;tt){let i=e;e=t,t=i}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),n=this.getPointAt(t),a=this.getPreviousPointIndexAt(t)+1,o=[];return 0!==e&&(s++,o.push(r)),o.push(...i.slice(s,a)),(1!==t||1===e)&&o.push(n),new sJ(o,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i;let r=e.length();if(0===r&&(r=1),null==t){let t;t=tK.WithinEpsilon(Math.abs(e.y)/r,1,.001)?tK.WithinEpsilon(Math.abs(e.x)/r,1,.001)?tK.WithinEpsilon(Math.abs(e.z)/r,1,.001)?t5.Zero():new t5(0,0,1):new t5(1,0,0):new t5(0,-1,0),i=t5.Cross(e,t)}else i=t5.Cross(e,t),t5.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){let i;if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let r=this.getPoints();if(e<=0)return this._setPointAtData(0,0,r[0],0,t);if(e>=1)return this._setPointAtData(1,1,r[r.length-1],r.length-1,t);let s=r[0],n=0,a=e*this.length();for(let o=1;oa){let r=(n-a)/l,h=s.subtract(i),u=i.add(h.scaleInPlace(r));return this._setPointAtData(e,1-r,u,o-1,t)}s=i}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=t7.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),n=this._tangents[t].clone(),a=this._normals[t].clone(),o=this._binormals[t].clone(),l=t8.RotationQuaternionFromAxis(r,s,i),h=t8.RotationQuaternionFromAxis(a,o,n);t8.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class s0{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;let s=[],n=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let a=0;a<=r;a++)s.push(new t5(n(a/r,e.x,t.x,i.x),n(a/r,e.y,t.y,i.y),n(a/r,e.z,t.z,i.z)));return new s0(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;let n=[],a=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let o=0;o<=s;o++)n.push(new t5(a(o/s,e.x,t.x,i.x,r.x),a(o/s,e.y,t.y,i.y,r.y),a(o/s,e.z,t.z,i.z,r.z)));return new s0(n)}static CreateHermiteSpline(e,t,i,r,s){let n=[],a=1/s;for(let o=0;o<=s;o++)n.push(t5.Hermite(e,t,i,r,o*a));return new s0(n)}static CreateCatmullRomSpline(e,t,i){let r=[],s=1/t,n=0;if(i){let i=e.length;for(let a=0;a=.5?(1-this.easeInCore((1-e)*2))*.5+.5:.5*this.easeInCore(2*e)}}s1.EASINGMODE_EASEIN=0,s1.EASINGMODE_EASEOUT=1,s1.EASINGMODE_EASEINOUT=2;class s2 extends s1{easeInCore(e){return 1-Math.sqrt(1-(e=Math.max(0,Math.min(1,e)))*e)}}class s3 extends s1{constructor(e=1){super(),this.amplitude=e}easeInCore(e){return Math.pow(e,3)-e*Math.max(0,this.amplitude)*Math.sin(3.141592653589793*e)}}class s4 extends s1{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)}}class s5 extends s1{easeInCore(e){return e*e}}class s6 extends s1{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}class s8{getClassName(){return"TargetedAnimation"}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class s7{syncWithMask(){if(!this.mask){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);let a=new s7(e[0].name+"_merged",e[0]._scene,r);for(let r of e){for(let e of(i&&r.normalize(s,n),r.targetedAnimations))a.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return a}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=[],this._animatables=[],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._parentContainer=null,this.onAnimationEndObservable=new tj,this.onAnimationLoopObservable=new tj,this.onAnimationGroupLoopObservable=new tj,this.onAnimationGroupEndObservable=new tj,this.onAnimationGroupPauseObservable=new tj,this.onAnimationGroupPlayObservable=new tj,this.metadata=null,this._animationLoopFlags=[],this._scene=t||t2.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new s8;i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-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 i=0;ie){let t={frame:e,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};r.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount!==this._numActiveAnimatables||(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{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;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){let 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){let t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){let r=new s7(e||this.name,this._scene,this._weight,this._playOrder);for(let e of(r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask,this._targetedAnimations))r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){let 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;ts[0].frame&&(e=s[0].frame),t=t&&e<=i||s&&r.frame>=t&&r.frame<=i){let e={frame:r.frame,value:r.value.clone?r.value.clone():r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation,lockedTangent:r.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,c.push(e)}}if(0===c.length){o.splice(e,1),e--;continue}n>c[0].frame&&(n=c[0].frame),a{r.value=void 0,t(r)},i):t(r)}catch(e){i(e)}}function ne(e,t,i,r,s){let n=()=>{let a;let o=e=>{e.done?i(e.value):void 0===a?a=!0:n()};do a=void 0,s&&s.aborted?r(Error("Aborted")):t(e,o,r),void 0===a&&(a=!1);while(a)};n()}function nt(e,t){let i;return ne(e,s9,e=>i=e,e=>{throw e},t),i}function ni(e,t,i){return new Promise((r,s)=>{ne(e,t,r,s,i)})}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(P||(P={}));class nr{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new nr(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new nr(this.x,this.y,this.width,this.height)}}class ns extends i0{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,r;let s=0,n=0;if(this.mode===ns.PERSPECTIVE_CAMERA)this.fovMode===ns.FOVMODE_VERTICAL_FIXED?(n=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*n):n=(s=2*this.minZ*Math.tan(this.fov/2))/this.getEngine().getAspectRatio(this);else{let a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:a)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-a),n=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(r=this.orthoBottom)&&void 0!==r?r:-o)}return s*n}set orthoLeft(e){for(let t of(this._orthoLeft=e,this._rigCameras))t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){for(let t of(this._orthoRight=e,this._rigCameras))t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){for(let t of(this._orthoBottom=e,this._rigCameras))t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){for(let t of(this._orthoTop=e,this._rigCameras))t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){for(let t of(this._mode=e,this._rigCameras))t.mode=e}get mode(){return this._mode}constructor(e,t,i,r=!0){super(e,i),this._position=t5.Zero(),this._upVector=t5.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=ns.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new nr(0,0,1,1),this.layerMask=268435455,this.fovMode=ns.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ns.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new tj,this.onProjectionMatrixChangedObservable=new tj,this.onAfterCheckInputsObservable=new tj,this.onRestoreStateObservable=new tj,this.isRigCamera=!1,this._rigCameras=[],this._skipRendering=!1,this._projectionMatrix=new t7,this._postProcesses=[],this._activeMeshes=new sa(256),this._globalPosition=t5.Zero(),this._computedViewMatrix=t7.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=t7.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=t8.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!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}_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 i=0;i-1?(ig.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){let 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 t7.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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){var t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x;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;let T=this.getEngine(),b=this.getScene(),E=T.useReverseDepthBuffer;if(this.mode===ns.PERSPECTIVE_CAMERA)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),(b.useRightHandedSystem?t7.PerspectiveFovRHToRef:t7.PerspectiveFovLHToRef)(this.fov,T.getAspectRatio(this),E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ns.FOVMODE_VERTICAL_FIXED,T.isNDCHalfZRange,this.projectionPlaneTilt,E);else{let e=T.getRenderWidth()/2,S=T.getRenderHeight()/2;b.useRightHandedSystem?this.oblique?t7.ObliqueOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(r=this.orthoBottom)&&void 0!==r?r:-S,null!==(s=this.orthoTop)&&void 0!==s?s:S,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,T.isNDCHalfZRange):t7.OrthoOffCenterRHToRef(null!==(n=this.orthoLeft)&&void 0!==n?n:-e,null!==(a=this.orthoRight)&&void 0!==a?a:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-S,null!==(l=this.orthoTop)&&void 0!==l?l:S,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this._projectionMatrix,T.isNDCHalfZRange):this.oblique?t7.ObliqueOffCenterLHToRef(null!==(h=this.orthoLeft)&&void 0!==h?h:-e,null!==(u=this.orthoRight)&&void 0!==u?u:e,null!==(c=this.orthoBottom)&&void 0!==c?c:-S,null!==(d=this.orthoTop)&&void 0!==d?d:S,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,T.isNDCHalfZRange):t7.OrthoOffCenterLHToRef(null!==(p=this.orthoLeft)&&void 0!==p?p:-e,null!==(_=this.orthoRight)&&void 0!==_?_:e,null!==(f=this.orthoBottom)&&void 0!==f?f:-S,null!==(m=this.orthoTop)&&void 0!==m?m:S,E?this.maxZ:this.minZ,E?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=null===(g=this.oblique)||void 0===g?void 0:g.angle,this._cache.obliqueLength=null===(v=this.oblique)||void 0===v?void 0:v.length,this._cache.obliqueOffset=null===(x=this.oblique)||void 0===x?void 0:x.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?t5.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?sz.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=sz.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),!t||!(this.rigCameras.length>0))return e.isInFrustum(this._frustumPlanes);{let t=!1;return this.rigCameras.forEach(i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)}),t}}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw iL("Ray")}getForwardRayToRef(e,t=100,i,r){throw iL("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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){let 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!==ns.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){let t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=ss.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ns.RIG_MODE_NONE){let e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);let 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 t7.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=ss.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;ens._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=ns.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=i$.Parse(r,e,t);if(void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=t5.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(t5.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(t5.FromArray(e.target)),e.cameraRigMode){let t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;tthis.parent._getWorldMatrixDeterminant()&&(e*=-1),e}}ns._CreateDefaultParsedCamera=(e,t)=>{throw iL("UniversalCamera")},ns.PERSPECTIVE_CAMERA=0,ns.ORTHOGRAPHIC_CAMERA=1,ns.FOVMODE_VERTICAL_FIXED=0,ns.FOVMODE_HORIZONTAL_FIXED=1,ns.RIG_MODE_NONE=0,ns.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,ns.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,ns.RIG_MODE_STEREOSCOPIC_INTERLACED=14,ns.RIG_MODE_VR=20,ns.RIG_MODE_CUSTOM=22,ns.ForceAttachControlToAlwaysPreventDefault=!1,iZ([ij("position")],ns.prototype,"_position",void 0),iZ([ij("upVector")],ns.prototype,"_upVector",void 0),iZ([iW()],ns.prototype,"orthoLeft",null),iZ([iW()],ns.prototype,"orthoRight",null),iZ([iW()],ns.prototype,"orthoBottom",null),iZ([iW()],ns.prototype,"orthoTop",null),iZ([iW()],ns.prototype,"fov",void 0),iZ([iW()],ns.prototype,"projectionPlaneTilt",void 0),iZ([iW()],ns.prototype,"minZ",void 0),iZ([iW()],ns.prototype,"maxZ",void 0),iZ([iW()],ns.prototype,"inertia",void 0),iZ([iW()],ns.prototype,"mode",null),iZ([iW()],ns.prototype,"layerMask",void 0),iZ([iW()],ns.prototype,"fovMode",void 0),iZ([iW()],ns.prototype,"cameraRigMode",void 0),iZ([iW()],ns.prototype,"interaxialDistance",void 0),iZ([iW()],ns.prototype,"isStereoscopicSideBySide",void 0);class nn{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}class na{constructor(e,t,i){this.vectors=tQ.BuildArray(8,t5.Zero),this.center=t5.Zero(),this.centerWorld=t5.Zero(),this.extendSize=t5.Zero(),this.extendSizeWorld=t5.Zero(),this.directions=tQ.BuildArray(3,t5.Zero),this.vectorsWorld=tQ.BuildArray(8,t5.Zero),this.minimumWorld=t5.Zero(),this.maximumWorld=t5.Zero(),this.minimum=t5.Zero(),this.maximum=t5.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){let r=e.x,s=e.y,n=e.z,a=t.x,o=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(r,s,n),this.maximum.copyFromFloats(a,o,l),h[0].copyFromFloats(r,s,n),h[1].copyFromFloats(a,o,l),h[2].copyFromFloats(a,s,n),h[3].copyFromFloats(r,o,n),h[4].copyFromFloats(r,s,l),h[5].copyFromFloats(a,o,n),h[6].copyFromFloats(r,o,l),h[7].copyFromFloats(a,s,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||t7.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){let t=na._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,n=i.scaleInPlace(.5*s),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){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)s[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){let a=s[r];t5.TransformCoordinatesToRef(n[r],e,a),t.minimizeInPlace(a),i.maximizeInPlace(a)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}t5.FromArrayToRef(e.m,0,r[0]),t5.FromArrayToRef(e.m,4,r[1]),t5.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return na.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return na.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,n=t.z,a=i.x,o=i.y,l=i.z,h=e.x,u=e.y,c=e.z;return!(a-h<-.001)&&!(-.001>h-r)&&!(o-u<-.001)&&!(-.001>u-s)&&!(l-c<-.001)&&!(-.001>c-n)}intersectsSphere(e){return na.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,n=i.y,a=i.z,o=r.x,l=r.y,h=r.z,u=e.x,c=e.y,d=e.z,p=t.x,_=t.y,f=t.z;return!(op)&&!(l_)&&!(hf)}dispose(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){let s=na._TmpVector3[0];return t5.ClampToRef(i,e,t,s),t5.DistanceSquared(i,s)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let t=0;t<8;++t)if(0>r.dotCoordinate(e[t]))return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}}na._TmpVector3=tQ.BuildArray(3,t5.Zero);class no{constructor(e,t,i){this.center=t5.Zero(),this.centerWorld=t5.Zero(),this.minimum=t5.Zero(),this.maximum=t5.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);let r=t5.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||t7.IdentityReadOnly)}scale(e){let t=this.radius*e,i=no._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),n=this.center.addToRef(r,i[2]);return this.reConstruct(s,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{t5.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=no._TmpVector3[0];t5.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){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(0>e[i].dotCoordinate(t))return!1;return!0}intersectsPoint(e){let t=t5.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{let r=t5.Dot(t.centerWorld,e),s=Math.abs(t5.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(t5.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(t5.Dot(t.directions[2],e))*t.extendSize.z;i.min=r-s,i.max=r+s},nc=(e,t,i)=>(nu(e,t,nl),nu(e,i,nh),!(nl.min>nh.max||nh.min>nl.max));class nd{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new na(e,t,i),this.boundingSphere=new no(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}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){let i=nd._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=nd._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let t=t5.Minimize(this.minimum,e),i=t5.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){let t=ie.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let i=ie.Vector3[0];return t5.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),t5.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!!((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(1===t||3===t||this.boundingBox.isInFrustum(e))}get diagonalLength(){let e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,nd._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(!no.Intersects(this.boundingSphere,e.boundingSphere)||!na.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!!(nc(i.directions[0],i,r)&&nc(i.directions[1],i,r)&&nc(i.directions[2],i,r)&&nc(r.directions[0],i,r)&&nc(r.directions[1],i,r)&&nc(r.directions[2],i,r)&&nc(t5.Cross(i.directions[0],r.directions[0]),i,r)&&nc(t5.Cross(i.directions[0],r.directions[1]),i,r)&&nc(t5.Cross(i.directions[0],r.directions[2]),i,r)&&nc(t5.Cross(i.directions[1],r.directions[0]),i,r)&&nc(t5.Cross(i.directions[1],r.directions[1]),i,r)&&nc(t5.Cross(i.directions[1],r.directions[2]),i,r)&&nc(t5.Cross(i.directions[2],r.directions[0]),i,r)&&nc(t5.Cross(i.directions[2],r.directions[1]),i,r)&&nc(t5.Cross(i.directions[2],r.directions[2]),i,r))}}nd._TmpVector3=tQ.BuildArray(2,t5.Zero);class np{static extractMinAndMaxIndexed(e,t,i,r,s,n){for(let a=i;a!Array.isArray(e)&&!Array.isArray(t))],np,"extractMinAndMaxIndexed",null),iZ([iq.filter((...[e])=>!Array.isArray(e))],np,"extractMinAndMax",null);class nf{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines}set materialDefines(e){var t;(null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=null!=e?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new rY(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null}get _drawWrapper(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e){this._removeDrawWrapper(e);return}for(let e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,n,a,o=!0){return new nf(e,t,i,r,s,n,a,o)}constructor(e,t,i,r,s,n,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,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,l&&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(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){var t;let i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){let e=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return i}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){let t;if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(sf.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){let e=this._renderingMesh.getBoundingInfo();t={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else t=function(e,t,i,r,s=null){let n=new t5(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new t5(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return np.extractMinAndMaxIndexed(e,t,i,r,n,a),s&&(n.x-=n.x*s.x+s.y,n.y-=n.y*s.x+s.y,n.z-=n.z*s.x+s.y,a.x+=a.x*s.x+s.y,a.y+=a.y*s.x+s.y,a.z+=a.z*s.x+s.y),{minimum:n,maximum:a}}(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new nd(t.minimum,t.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){let t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){let 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){let i=[];for(let t=this.indexStart;to&&(o=t)}return new nf(e,a,o-a+1,t,i,r,s,n)}}class nm{}class ng{constructor(){var e;this.uniqueId=0,this.metadata={},this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>nt(e(...t),void 0)),this.uniqueId=ng._UniqueIDGenerator,ng._UniqueIDGenerator++}set(e,t){switch(e.length||ig.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case sf.PositionKind:this.positions=e;break;case sf.NormalKind:this.normals=e;break;case sf.TangentKind:this.tangents=e;break;case sf.UVKind:this.uvs=e;break;case sf.UV2Kind:this.uvs2=e;break;case sf.UV3Kind:this.uvs3=e;break;case sf.UV4Kind:this.uvs4=e;break;case sf.UV5Kind:this.uvs5=e;break;case sf.UV6Kind:this.uvs6=e;break;case sf.ColorKind:this.colors=e;break;case sf.MatricesIndicesKind:this.matricesIndices=e;break;case sf.MatricesWeightsKind:this.matricesWeights=e;break;case sf.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case sf.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,i){if(this.positions&&(e.setVerticesData(sf.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(sf.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(sf.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(sf.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(sf.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(sf.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(sf.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(sf.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(sf.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(sf.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(sf.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(sf.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(sf.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(sf.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1)for(let t of(e.subMeshes=[],this.materialInfos))new nf(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,e);return this}_update(e,t,i){return this.positions&&e.updateVerticesData(sf.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(sf.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(sf.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(sf.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(sf.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(sf.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(sf.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(sf.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(sf.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(sf.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(sf.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(sf.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(sf.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(sf.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let s=ie.Vector3[0],n=ie.Vector3[1];for(let a=i;ae.determinant();return this.positions&&ng._TransformVector3Coordinates(this.positions,e),this.normals&&ng._TransformVector3Normals(this.normals,e),this.tangents&&ng._TransformVector4Normals(this.tangents,e),t&&this.indices&&ng._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];let e=[];for(let t of this.materialInfos){let i=new ng;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let e=t.indexStart;e({vertexData:e})):[{vertexData:e}];return nt(this._mergeCoroutine(void 0,n,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,n=!1,a=!1){var o,l,h,u;this._validate();let c=t.map(e=>e.vertexData),d=this;if(a)for(let e of c)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(let e of c)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 Error("Cannot merge vertex data that do not have the same set of attributes")}if(n){let i=0,r=0,s=0,n=[],a=null,o=[];for(let t of this.splitBasedOnMaterialID())o.push({vertexData:t,transform:e});for(let e of t)if(e.vertexData)for(let t of e.vertexData.splitBasedOnMaterialID())o.push({vertexData:t,transform:e.transform});for(let e of(o.sort((e,t)=>{let i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}),o)){let t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{let e=new nm;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,n.push(e),a=e}r+=t.indices.length,s+=t.positions.length/3}let l=o.splice(0,1)[0];d=l.vertexData,e=l.transform,c=o.map(e=>e.vertexData),t=o,this.materialInfos=n}let p=c.reduce((e,t)=>{var i,r;return e+(null!==(r=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==r?r:0)},null!==(l=null===(o=d.indices)||void 0===o?void 0:o.length)&&void 0!==l?l:0),_=s||c.some(e=>e.indices===d.indices)?null===(h=d.indices)||void 0===h?void 0:h.slice():d.indices;if(p>0){let s=null!==(u=null==_?void 0:_.length)&&void 0!==u?u:0;if(_||(_=Array(p)),_.length!==p){if(Array.isArray(_))_.length=p;else{let e=i||_ instanceof Uint32Array?new Uint32Array(p):new Uint16Array(p);e.set(_),_=e}e&&0>e.determinant()&&ng._FlipFaces(_,0,s)}let n=d.positions?d.positions.length/3:0;for(let{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;ti.determinant()&&ng._FlipFaces(_,s,e.indices.length),n+=e.positions.length/3,s+=e.indices.length,r&&(yield)}}return this.indices=_,this.positions=ng._MergeElement(sf.PositionKind,d.positions,e,t.map(e=>[e.vertexData.positions,e.transform])),r&&(yield),d.normals&&(this.normals=ng._MergeElement(sf.NormalKind,d.normals,e,t.map(e=>[e.vertexData.normals,e.transform])),r&&(yield)),d.tangents&&(this.tangents=ng._MergeElement(sf.TangentKind,d.tangents,e,t.map(e=>[e.vertexData.tangents,e.transform])),r&&(yield)),d.uvs&&(this.uvs=ng._MergeElement(sf.UVKind,d.uvs,e,t.map(e=>[e.vertexData.uvs,e.transform])),r&&(yield)),d.uvs2&&(this.uvs2=ng._MergeElement(sf.UV2Kind,d.uvs2,e,t.map(e=>[e.vertexData.uvs2,e.transform])),r&&(yield)),d.uvs3&&(this.uvs3=ng._MergeElement(sf.UV3Kind,d.uvs3,e,t.map(e=>[e.vertexData.uvs3,e.transform])),r&&(yield)),d.uvs4&&(this.uvs4=ng._MergeElement(sf.UV4Kind,d.uvs4,e,t.map(e=>[e.vertexData.uvs4,e.transform])),r&&(yield)),d.uvs5&&(this.uvs5=ng._MergeElement(sf.UV5Kind,d.uvs5,e,t.map(e=>[e.vertexData.uvs5,e.transform])),r&&(yield)),d.uvs6&&(this.uvs6=ng._MergeElement(sf.UV6Kind,d.uvs6,e,t.map(e=>[e.vertexData.uvs6,e.transform])),r&&(yield)),d.colors&&(this.colors=ng._MergeElement(sf.ColorKind,d.colors,e,t.map(e=>[e.vertexData.colors,e.transform])),r&&(yield)),d.matricesIndices&&(this.matricesIndices=ng._MergeElement(sf.MatricesIndicesKind,d.matricesIndices,e,t.map(e=>[e.vertexData.matricesIndices,e.transform])),r&&(yield)),d.matricesWeights&&(this.matricesWeights=ng._MergeElement(sf.MatricesWeightsKind,d.matricesWeights,e,t.map(e=>[e.vertexData.matricesWeights,e.transform])),r&&(yield)),d.matricesIndicesExtra&&(this.matricesIndicesExtra=ng._MergeElement(sf.MatricesIndicesExtraKind,d.matricesIndicesExtra,e,t.map(e=>[e.vertexData.matricesIndicesExtra,e.transform])),r&&(yield)),d.matricesWeightsExtra&&(this.matricesWeightsExtra=ng._MergeElement(sf.MatricesWeightsExtraKind,d.matricesWeightsExtra,e,t.map(e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(e=>null!==e[0]&&void 0!==e[0]);if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let n=s.reduce((e,t)=>e+t[0].length,t.length),a=e===sf.PositionKind?ng._TransformVector3Coordinates:e===sf.NormalKind?ng._TransformVector3Normals:e===sf.TangentKind?ng._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let e=new Float32Array(n);e.set(t),i&&a(e,i,0,t.length);let r=t.length;for(let[t,i]of s)e.set(t,r),i&&a(e,i,r,t.length),r+=t.length;return e}{let e=Array(n);for(let i=0;i{let i=sf.DeduceStride(e);if(t.length%i!=0)throw Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(sf.PositionKind,this.positions),i=(i,r)=>{let s=e(i,r);if(s!==t)throw Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(sf.NormalKind,this.normals),this.tangents&&i(sf.TangentKind,this.tangents),this.uvs&&i(sf.UVKind,this.uvs),this.uvs2&&i(sf.UV2Kind,this.uvs2),this.uvs3&&i(sf.UV3Kind,this.uvs3),this.uvs4&&i(sf.UV4Kind,this.uvs4),this.uvs5&&i(sf.UV5Kind,this.uvs5),this.uvs6&&i(sf.UV6Kind,this.uvs6),this.colors&&i(sf.ColorKind,this.colors),this.matricesIndices&&i(sf.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(sf.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(sf.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(sf.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return ng.Parse(e)}serialize(){let 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)),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)for(let t of(e.materialInfos=[],this.materialInfos)){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}return e}static ExtractFromMesh(e,t,i){return ng._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return ng._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new ng;return e.isVerticesDataPresent(sf.PositionKind)&&(r.positions=e.getVerticesData(sf.PositionKind,t,i)),e.isVerticesDataPresent(sf.NormalKind)&&(r.normals=e.getVerticesData(sf.NormalKind,t,i)),e.isVerticesDataPresent(sf.TangentKind)&&(r.tangents=e.getVerticesData(sf.TangentKind,t,i)),e.isVerticesDataPresent(sf.UVKind)&&(r.uvs=e.getVerticesData(sf.UVKind,t,i)),e.isVerticesDataPresent(sf.UV2Kind)&&(r.uvs2=e.getVerticesData(sf.UV2Kind,t,i)),e.isVerticesDataPresent(sf.UV3Kind)&&(r.uvs3=e.getVerticesData(sf.UV3Kind,t,i)),e.isVerticesDataPresent(sf.UV4Kind)&&(r.uvs4=e.getVerticesData(sf.UV4Kind,t,i)),e.isVerticesDataPresent(sf.UV5Kind)&&(r.uvs5=e.getVerticesData(sf.UV5Kind,t,i)),e.isVerticesDataPresent(sf.UV6Kind)&&(r.uvs6=e.getVerticesData(sf.UV6Kind,t,i)),e.isVerticesDataPresent(sf.ColorKind)&&(r.colors=e.getVerticesData(sf.ColorKind,t,i)),e.isVerticesDataPresent(sf.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(sf.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(sf.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(sf.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(sf.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(sf.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(sf.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(sf.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw iL("ribbonBuilder")}static CreateBox(e){throw iL("boxBuilder")}static CreateTiledBox(e){throw iL("tiledBoxBuilder")}static CreateTiledPlane(e){throw iL("tiledPlaneBuilder")}static CreateSphere(e){throw iL("sphereBuilder")}static CreateCylinder(e){throw iL("cylinderBuilder")}static CreateTorus(e){throw iL("torusBuilder")}static CreateLineSystem(e){throw iL("linesBuilder")}static CreateDashedLines(e){throw iL("linesBuilder")}static CreateGround(e){throw iL("groundBuilder")}static CreateTiledGround(e){throw iL("groundBuilder")}static CreateGroundFromHeightMap(e){throw iL("groundBuilder")}static CreatePlane(e){throw iL("planeBuilder")}static CreateDisc(e){throw iL("discBuilder")}static CreatePolygon(e,t,i,r,s,n,a){throw iL("polygonBuilder")}static CreateIcoSphere(e){throw iL("icoSphereBuilder")}static CreatePolyhedron(e){throw iL("polyhedronBuilder")}static CreateCapsule(e={orientation:t5.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw iL("capsuleBuilder")}static CreateTorusKnot(e){throw iL("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let s=0,n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=0,x=0,T=0,b=0,E=0,S=0,C=!1,y=!1,A=!1,R=!1,I=1,P=0,M=null;r&&(C=!!r.facetNormals,y=!!r.facetPositions,A=!!r.facetPartitioning,I=!0===r.useRightHandedSystem?-1:1,P=r.ratio||0,R=!!r.depthSort,M=r.distanceTo,R&&void 0===M&&(M=t5.Zero()));let D=0,O=0,N=0,F=0;for(A&&r&&r.bbSize&&(D=r.subDiv.X*P/r.bbSize.x,O=r.subDiv.Y*P/r.bbSize.y,N=r.subDiv.Z*P/r.bbSize.z,F=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),s=0;s!Array.isArray(e))],ng,"_TransformVector3Coordinates",null),iZ([iq.filter((...[e])=>!Array.isArray(e))],ng,"_TransformVector3Normals",null),iZ([iq.filter((...[e])=>!Array.isArray(e))],ng,"_TransformVector4Normals",null),iZ([iq.filter((...[e])=>!Array.isArray(e))],ng,"_FlipFaces",null);class nv{static get ForceFullSceneLoadingForIncremental(){return nv._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){nv._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return nv._ShowLoadingScreen}static set ShowLoadingScreen(e){nv._ShowLoadingScreen=e}static get loggingLevel(){return nv._LoggingLevel}static set loggingLevel(e){nv._LoggingLevel=e}static get CleanBoneMatrixWeights(){return nv._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){nv._CleanBoneMatrixWeights=e}}nv._ForceFullSceneLoadingForIncremental=!1,nv._ShowLoadingScreen=!0,nv._CleanBoneMatrixWeights=!1,nv._LoggingLevel=0;class nx{}nx.UseOpenGLOrientationForUV=!1;class nT{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){let t=new nT(nT.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){if(this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||t2.LastCreatedScene,!this._scene)return;this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e65535),this._meshes))r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){for(let r of(this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),void 0!=t&&(this._totalVertices=t),this._meshes))r._createGlobalSubMesh(!0),r.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;let i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}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){let i=this._meshes,r=i.indexOf(e);-1!==r&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;let t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();let i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.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(sf.PositionKind)))return;this._extend=n_(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){let t=this._meshes.length;for(let i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===sf.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){for(let t of(this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects(),this._meshes))t._markSubMeshesAsAttributesDirty()}load(e,t){if(2!==this.delayLoadState){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t;let i=new ng;i.indices=[];let r=this.getIndices();if(r)for(let e=0;e0){let r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(sf.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){let r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(sf.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){let r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(sf.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){let r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(nx.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(nx.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(nx.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(nx.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(nx.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(nx.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(sf.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(sf.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(sf.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){let r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(sf.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){let r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){let r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(sf.MatricesIndicesKind,i,e.matricesIndices._updatable)}}if(e.matricesIndicesExtra){if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(sf.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{let i=[];for(let t=0;t>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(sf.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}}e.matricesWeights&&(nT._CleanMatricesWeights(e,t),t.setVerticesData(sf.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(sf.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{let r=t.getScene().getLastSkeletonById(e.skeletonId);if(!r)return;i=r.bones.length}let r=t.getVerticesData(sf.MatricesIndicesKind),s=t.getVerticesData(sf.MatricesIndicesExtraKind),n=e.matricesWeights,a=e.matricesWeightsExtra,o=e.numBoneInfluencer,l=n.length;for(let e=0;eo-1)&&(l=o-1),t>.001){let i=1/t;for(let t=0;t<4;t++)n[e+t]*=i;if(a)for(let t=0;t<4;t++)a[e+t]*=i}else l>=4?(a[e+l-4]=1-t,s[e+l-4]=i):(n[e+l]=1-t,r[e+l]=i)}t.setVerticesData(sf.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(sf.MatricesIndicesExtraKind,s)}static Parse(e,t,i){let r=new nT(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,iF&&iF.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new nd(t5.FromArray(e.boundingBoxMinimum),t5.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(sf.UVKind),e.hasUVs2&&r._delayInfo.push(sf.UV2Kind),e.hasUVs3&&r._delayInfo.push(sf.UV3Kind),e.hasUVs4&&r._delayInfo.push(sf.UV4Kind),e.hasUVs5&&r._delayInfo.push(sf.UV5Kind),e.hasUVs6&&r._delayInfo.push(sf.UV6Kind),e.hasColors&&r._delayInfo.push(sf.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(sf.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(sf.MatricesWeightsKind),r._delayLoadingFunction=ng.ImportVertexData):ng.ImportVertexData(e,r),t.pushGeometry(r,!0),r}}class nb{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new nE(e)}sampleFrame(e=ra.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){let 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(){let 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 nE{constructor(e){this._samples=Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let 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;let 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){let t=this._samples.length;return(e%t+t)%t}}function nS(e,t,i=!1,r){switch(e){case 3:{let e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{let e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{let e=new Int16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{let e=new Uint16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{let e=new Int32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{let e=new Uint32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{let e=new Float32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Float32Array(r)),e}}let s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}r$.prototype.setAlphaConstants=function(e,t,i,r){this._alphaState.setAlphaBlendConstants(e,t,i,r)},r$.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e){if(!t){let t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14: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 2: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 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5: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 9: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 10: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 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13: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 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16: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 17: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=0===e),this._alphaMode=e},r$.prototype.getAlphaMode=function(){return this._alphaMode},r$.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},r$.prototype.getAlphaEquation=function(){return this._alphaEquation},r$.prototype._readTexturePixelsSync=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){var u,c;let d=this._gl;if(!d)throw Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let e=d.createFramebuffer();if(!e)throw Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),r>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+r,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,s):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,s);let p=void 0!==e.type?this._getWebGLTextureType(e.type):d.UNSIGNED_BYTE;return o?n||(n=nS(e.type,4*t*i)):p===d.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),p=d.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),p=d.FLOAT),a&&this.flushFramebuffer(),d.readPixels(l,h,t,i,d.RGBA,p,n),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),n},r$.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,n,a,o,l,h))},r$.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},r$.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0);let s=t.byteLength||t.length;void 0===r||r>=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()};class nC extends r${static get NpmPackage(){return r$.NpmPackage}static get Version(){return r$.Version}static get Instances(){return t2.Instances}static get LastCreatedEngine(){return t2.LastCreatedEngine}static get LastCreatedScene(){return t2.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{this.createImageBitmap(s,t).then(e=>{i(e)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e})}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){let r=this.createCanvas(t,i).getContext("2d");if(!r)throw Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(e,0,0),r.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};let t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!nC.audioEngine&&this._creationOptions.audioEngine&&nC.AudioEngineFactory&&(nC.audioEngine=nC.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),rs()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&nC._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==nC.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;null===(e=this._onPointerLockChange)||void 0===e||e.call(this)}getAspectRatio(e,t=!1){let i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){let i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}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)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){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()}restoreStencilState(){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)}setDirectViewport(e,t,i,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((r,s)=>{this._loadFile(e,e=>{r(e)},void 0,t,i,(e,t)=>{s(t)})})}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))}setTextureFromPostProcess(e,t,i){var r;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==s?void 0:s.texture)&&void 0!==r?r:null,i)}setTextureFromPostProcessOutput(e,t,i){var r,s;this._bindTexture(e,null!==(s=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}_rebuildTextures(){for(let e of this.scenes)e._rebuildTextures();for(let e of this._virtualScenes)e._rebuildTextures();super._rebuildTextures()}_renderFrame(){for(let e=0;e0?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()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){!this.isFullscreen&&(this._pointerLockRequested=e,this._renderingCanvas&&nC._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&nC._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&nC._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){nC._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this.onEndFrameObservable.notifyObservers(this)}setSize(e,t,i=!1){if(!this._renderingCanvas||!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e1&&s){let t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,s),e.transformFeedback=t}return r.linkProgram(n),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,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)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){let t=++nC._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;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,r,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),s&&s()}))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,r=0,s=0){let n=new rX(e,this._gl),a=new rU(this,m.Unknown,!0);return a._hardwareTexture=n,a.baseWidth=r,a.baseHeight=s,a.width=r,a.height=s,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(i,a),a}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,o,a,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion){ig.Error("WebGL 1 does not support texture comparison.");return}let i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create instance buffer");let i=new rW(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){let r=this._gl;return new Promise((s,n)=>{let a=()=>{let o=r.clientWaitSync(e,t,0);if(o==r.WAIT_FAILED){n();return}if(o==r.TIMEOUT_EXPIRED){setTimeout(a,i);return}s()};a()})}_readPixelsAsync(e,t,i,r,s,n,a){if(this._webGLVersion<2)throw Error("_readPixelsAsync only work on WebGL2+");let o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,r,s,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);let h=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(o.flush(),this._clientWaitAsync(h,0,10).then(()=>(o.deleteSync(h),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),a))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===t2.Instances.length&&nC.audioEngine&&(nC.audioEngine.dispose(),nC.audioEngine=null);let e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),rs()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();let t=t2.Instances.indexOf(this);t>=0&&t2.Instances.splice(t,1),nC.Instances.length||t2.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){}hideLoadingUI(){}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=nC.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){let t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){let e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){let t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);let i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";let r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:n,descent:n-s}}}nC.ALPHA_DISABLE=0,nC.ALPHA_ADD=1,nC.ALPHA_COMBINE=2,nC.ALPHA_SUBTRACT=3,nC.ALPHA_MULTIPLY=4,nC.ALPHA_MAXIMIZED=5,nC.ALPHA_ONEONE=6,nC.ALPHA_PREMULTIPLIED=7,nC.ALPHA_PREMULTIPLIED_PORTERDUFF=8,nC.ALPHA_INTERPOLATE=9,nC.ALPHA_SCREENMODE=10,nC.DELAYLOADSTATE_NONE=0,nC.DELAYLOADSTATE_LOADED=1,nC.DELAYLOADSTATE_LOADING=2,nC.DELAYLOADSTATE_NOTLOADED=4,nC.NEVER=512,nC.ALWAYS=519,nC.LESS=513,nC.EQUAL=514,nC.LEQUAL=515,nC.GREATER=516,nC.GEQUAL=518,nC.NOTEQUAL=517,nC.KEEP=7680,nC.REPLACE=7681,nC.INCR=7682,nC.DECR=7683,nC.INVERT=5386,nC.INCR_WRAP=34055,nC.DECR_WRAP=34056,nC.TEXTURE_CLAMP_ADDRESSMODE=0,nC.TEXTURE_WRAP_ADDRESSMODE=1,nC.TEXTURE_MIRROR_ADDRESSMODE=2,nC.TEXTUREFORMAT_ALPHA=0,nC.TEXTUREFORMAT_LUMINANCE=1,nC.TEXTUREFORMAT_LUMINANCE_ALPHA=2,nC.TEXTUREFORMAT_RGB=4,nC.TEXTUREFORMAT_RGBA=5,nC.TEXTUREFORMAT_RED=6,nC.TEXTUREFORMAT_R=6,nC.TEXTUREFORMAT_RG=7,nC.TEXTUREFORMAT_RED_INTEGER=8,nC.TEXTUREFORMAT_R_INTEGER=8,nC.TEXTUREFORMAT_RG_INTEGER=9,nC.TEXTUREFORMAT_RGB_INTEGER=10,nC.TEXTUREFORMAT_RGBA_INTEGER=11,nC.TEXTURETYPE_UNSIGNED_BYTE=0,nC.TEXTURETYPE_UNSIGNED_INT=0,nC.TEXTURETYPE_FLOAT=1,nC.TEXTURETYPE_HALF_FLOAT=2,nC.TEXTURETYPE_BYTE=3,nC.TEXTURETYPE_SHORT=4,nC.TEXTURETYPE_UNSIGNED_SHORT=5,nC.TEXTURETYPE_INT=6,nC.TEXTURETYPE_UNSIGNED_INTEGER=7,nC.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,nC.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,nC.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,nC.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,nC.TEXTURETYPE_UNSIGNED_INT_24_8=12,nC.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,nC.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,nC.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,nC.TEXTURE_NEAREST_SAMPLINGMODE=1,nC.TEXTURE_BILINEAR_SAMPLINGMODE=2,nC.TEXTURE_TRILINEAR_SAMPLINGMODE=3,nC.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,nC.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,nC.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,nC.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,nC.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,nC.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,nC.TEXTURE_NEAREST_LINEAR=7,nC.TEXTURE_NEAREST_NEAREST=1,nC.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,nC.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,nC.TEXTURE_LINEAR_LINEAR=2,nC.TEXTURE_LINEAR_NEAREST=12,nC.TEXTURE_EXPLICIT_MODE=0,nC.TEXTURE_SPHERICAL_MODE=1,nC.TEXTURE_PLANAR_MODE=2,nC.TEXTURE_CUBIC_MODE=3,nC.TEXTURE_PROJECTION_MODE=4,nC.TEXTURE_SKYBOX_MODE=5,nC.TEXTURE_INVCUBIC_MODE=6,nC.TEXTURE_EQUIRECTANGULAR_MODE=7,nC.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,nC.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,nC.SCALEMODE_FLOOR=1,nC.SCALEMODE_NEAREST=2,nC.SCALEMODE_CEILING=3,nC._RescalePostProcessFactory=null,nC._RenderPassIdCounter=0;let ny=t7.Compose(t5.One(),t8.FromEulerAngles(0,Math.PI,0),t5.Zero());class nA extends i0{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&nA.BILLBOARDMODE_USE_POSITION)!=0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==nA.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new t5(0,0,1),this._up=new t5(0,1,0),this._right=new t5(1,0,0),this._position=t5.Zero(),this._rotation=t5.Zero(),this._rotationQuaternion=null,this._scaling=t5.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=nA.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=t7.Zero(),this._usePivotMatrix=!1,this._absolutePosition=t5.Zero(),this._absoluteScaling=t5.Zero(),this._absoluteRotationQuaternion=t8.Identity(),this._pivotMatrix=t7.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new tj,this._nonUniformScaling=!1,i&&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 t5.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return t5.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return t5.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._poseMatrix=e.clone(),this}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=t7.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===nA.BILLBOARDMODE_NONE&&!e.pivotMatrixUpdated&&!this._infiniteDistance&&!this._position._isDirty&&!this._scaling._isDirty&&(!this._rotationQuaternion||!this._rotationQuaternion._isDirty)&&!this._rotation._isDirty}_initCache(){super._initCache();let 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=t7.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||t8.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){let t,i,r;if(!e)return this;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let e=ie.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),t5.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=t5.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=ie.Matrix[0];return this._localMatrix.invertToRef(e),t5.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=t5.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=A.LOCAL){let n=nA._LookAtVectorCache,a=s===A.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,n),this.setDirection(n,t,i,r),s===A.WORLD&&this.parent){if(this.rotationQuaternion){let e=ie.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);let t=ie.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{let e=ie.Quaternion[0];t8.FromEulerVectorToRef(this.rotation,e);let t=ie.Matrix[0];e.toRotationMatrix(t);let i=ie.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}}return this}getDirection(e){let t=t5.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return t5.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-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?t8.RotationYawPitchRollToRef(s+t,a+i,r,this.rotationQuaternion):(this.rotation.x=a+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=A.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==A.WORLD){let t=ie.Matrix[0];i.invertToRef(t),e=t5.TransformCoordinates(e,t)}return this.setPivotMatrix(t7.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=t5.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(){let e=t5.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),t5.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=ie.Quaternion[0],s=ie.Vector3[0],n=ie.Vector3[1],a=ie.Matrix[1];t7.IdentityToRef(a);let o=ie.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=nA._TmpRotation,t8.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),t7.ComposeToRef(this.scaling,l,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,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(t7.Identity()),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),0>e.getFinalMatrix().determinant()&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(0>this.parent.getWorldMatrix().determinant()&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null):e&&(this.parent=this._currentParentWhenAttachingToBone),this}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==A.LOCAL){if(this.parent){let i=this.parent.getWorldMatrix(),r=ie.Matrix[0];i.invertToRef(r),e=t5.TransformNormal(e,r),0>i.determinant()&&(t*=-1)}(r=t8.RotationAxisToRef(e,t,nA._RotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=t8.RotationAxisToRef(e,t,nA._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=t8.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=ie.Vector3[0],s=ie.Vector3[1],n=ie.Vector3[2],a=ie.Quaternion[0],o=ie.Matrix[0],l=ie.Matrix[1],h=ie.Matrix[2],u=ie.Matrix[3];return e.subtractToRef(this.position,r),t7.TranslationToRef(r.x,r.y,r.z,o),t7.TranslationToRef(-r.x,-r.y,-r.z,l),t7.RotationAxisToRef(t,i,h),l.multiplyToRef(h,u),u.multiplyToRef(o,u),u.decompose(s,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(i&&i!==A.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{let e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=ie.Quaternion[1],t8.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=ie.Quaternion[0];return t8.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==nA.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){let i;if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let r=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===r||this.isSynchronized()))return this._currentRenderId=r,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=r,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let n=this._getEffectiveParent(),a=nA._TmpScaling,o=this._position;if(this._infiniteDistance&&!this.parent&&t){let e=t.getWorldMatrix(),i=new t5(e.m[12],e.m[13],e.m[14]);(o=nA._TmpTranslation).copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(a.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,i=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(t8.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(i=nA._TmpRotation,t8.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,i)),this._usePivotMatrix){let e=ie.Matrix[1];t7.ScalingToRef(a.x,a.y,a.z,e);let t=ie.Matrix[0];i.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,ie.Matrix[4]),ie.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 t7.ComposeToRef(a,i,o,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),ie.Matrix[7])}else ie.Matrix[7].copyFrom(n.getWorldMatrix());let e=ie.Vector3[5],t=ie.Vector3[6],i=ie.Quaternion[0];ie.Matrix[7].decompose(t,i,e),t7.ScalingToRef(t.x,t.y,t.z,ie.Matrix[7]),ie.Matrix[7].setTranslation(e),nA.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(ie.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),ie.Matrix[6]),ie.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){let e=ie.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),ie.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&ie.Matrix[1].multiplyToRef(ny,ie.Matrix[1]),ie.Matrix[1].setTranslationFromFloats(0,0,0),ie.Matrix[1].invertToRef(ie.Matrix[0]),(this.billboardMode&nA.BILLBOARDMODE_ALL)!==nA.BILLBOARDMODE_ALL){ie.Matrix[0].decompose(void 0,ie.Quaternion[0],void 0);let e=ie.Vector3[1];ie.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&nA.BILLBOARDMODE_X)!==nA.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&nA.BILLBOARDMODE_Y)!==nA.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&nA.BILLBOARDMODE_Z)!==nA.BILLBOARDMODE_Z&&(e.z=0),t7.RotationYawPitchRollToRef(e.y,e.x,e.z,ie.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ie.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ie.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){let e=ie.Vector3[0];this._worldMatrix.getTranslationToRef(e);let i=t.globalPosition;this._worldMatrix.invertToRef(ie.Matrix[1]);let r=ie.Vector3[1];t5.TransformCoordinatesToRef(i,ie.Matrix[1],r),r.normalize();let s=-Math.atan2(r.z,r.x)+Math.PI/2,n=Math.sqrt(r.x*r.x+r.z*r.z),a=-Math.atan2(r.y,n);if(t8.RotationYawPitchRollToRef(s,a,0,ie.Quaternion[0]),(this.billboardMode&nA.BILLBOARDMODE_ALL)!==nA.BILLBOARDMODE_ALL){let e=ie.Vector3[1];ie.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&nA.BILLBOARDMODE_X)!==nA.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&nA.BILLBOARDMODE_Y)!==nA.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&nA.BILLBOARDMODE_Z)!==nA.BILLBOARDMODE_Z&&(e.z=0),t7.RotationYawPitchRollToRef(e.y,e.x,e.z,ie.Matrix[0])}else t7.FromQuaternionToRef(ie.Quaternion[0],ie.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(ie.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(ie.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._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=t7.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let e=this.getChildren();for(let t=0;tnew nA(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;inew nA(e.name,t),e,t,i);return e.localMatrix?r.setPreTransformMatrix(t7.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(t7.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r}getChildTransformNodes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&e instanceof nA),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e)for(let e of this.getChildTransformNodes(!0))e.parent=null,e.computeWorldMatrix(!0);super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);return 0===o||(this.scaling.scaleInPlace(1/o),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r))),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}nA.BILLBOARDMODE_NONE=0,nA.BILLBOARDMODE_X=1,nA.BILLBOARDMODE_Y=2,nA.BILLBOARDMODE_Z=4,nA.BILLBOARDMODE_ALL=7,nA.BILLBOARDMODE_USE_POSITION=128,nA.BillboardUseParentOrientation=!1,nA._TmpRotation=t8.Zero(),nA._TmpScaling=t5.Zero(),nA._TmpTranslation=t5.Zero(),nA._LookAtVectorCache=new t5(0,0,0),nA._RotationAxisCache=new t8,iZ([ij("position")],nA.prototype,"_position",void 0),iZ([ij("rotation")],nA.prototype,"_rotation",void 0),iZ([iG(10,"rotationQuaternion")],nA.prototype,"_rotationQuaternion",void 0),iZ([ij("scaling")],nA.prototype,"_scaling",void 0),iZ([iW("billboardMode")],nA.prototype,"_billboardMode",void 0),iZ([iW()],nA.prototype,"scalingDeterminant",void 0),iZ([iW("infiniteDistance")],nA.prototype,"_infiniteDistance",void 0),iZ([iW()],nA.prototype,"ignoreNonUniformScaling",void 0),iZ([iW()],nA.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class nR{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new t5(0,0,0),this._diffPositionForCollisions=new t5(0,0,0),this._collisionResponse=!0}}class nI{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=t5.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class nP{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new nI,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 nR,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class nM extends nA{static get BILLBOARDMODE_NONE(){return nA.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return nA.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return nA.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return nA.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return nA.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return nA.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;let t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty(e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()})}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._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){var t;return null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[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}get _positions(){return null}set skeleton(e){let 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 nP,this._waitingMaterialId=null,this.cullingStrategy=nM.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new tj,this.onCollisionPositionChangeObservable=new tj,this.onMaterialChangedObservable=new tj,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=io.Red(),this.outlineWidth=.02,this.overlayColor=io.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 t5(.5,1,.5),this.ellipsoidOffset=new t5(0,0,0),this.edgesWidth=1,this.edgesColor=new il(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=[],this._unIndexed=!1,this._lightSources=[],this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new tj,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>nC.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new sp(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case y.Aggressive:this.doNotSyncBoundingInfo=!0;case y.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){let 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);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode]+", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==nA.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){return this.actionManager&&(t||this.actionManager.isRecursive)&&(!e||this.actionManager.hasSpecificTrigger(e))?this.actionManager: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(let e of this.subMeshes)e._rebuild()}_resyncLightSources(){for(let e of(this._lightSources.length=0,this.getScene().lights))e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;it.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(let 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,i,r){return this}updateVerticesData(e,t,i,r){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(){var e;return null!==(e=this.rawBoundingInfo)&&void 0!==e?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new nd(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(sf.MatricesIndicesKind)&&this.isVerticesDataPresent(sf.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===nA.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,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){let r=new t7;(this.rotationQuaternion?this.rotationQuaternion:t8.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);let s=t5.Zero(),n=this.definedFacingForward?-1:1;return t5.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,r,s),s}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new t5(e*r,t,i*r)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){let i=n_(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new nd(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,n=s?this.getVerticesData(sf.MatricesIndicesExtraKind):null,a=s?this.getVerticesData(sf.MatricesWeightsExtraKind):null,o=this.skeleton.getTransformMatrices(this),l=ie.Vector3[0],h=ie.Matrix[0],u=ie.Matrix[1],c=0;for(let d=0;d0&&(t7.FromFloat32ArrayToRefScaled(o,Math.floor(16*e[c+p]),_,u),h.addToSelf(u));if(s)for(p=0;p<4;p++)(_=a[c+p])>0&&(t7.FromFloat32ArrayToRefScaled(o,Math.floor(16*n[c+p]),_,u),h.addToSelf(u));r===sf.NormalKind?t5.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):t5.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),r===sf.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,sf.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,sf.PositionKind)}_getPositionData(e,t){var i;let r=this.getVerticesData(sf.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),r&&(e&&this.skeleton||t&&this.morphTargetManager)){if(r=r.slice(),this._generatePointsArray(),this._positions){let e=this._positions;this._internalAbstractMeshDataInfo._positions=Array(e.length);for(let t=0;t1||!r.IsGlobal)&&r.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,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let i of this.getChildMeshes())if(i.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);let 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,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s1)||n._checkCollision(e))&&this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=ie.Matrix[0],i=ie.Matrix[1];return t7.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,n=!1){let a=new sm,o=this.getClassName(),l="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes||!n&&(!e.intersectsSphere(h.boundingSphere,l)||!e.intersectsBox(h.boundingBox,l)))return a;if(r)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:t5.Distance(e.origin,h.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let u=null,c=this._scene.getIntersectingSubMeshCandidates(this,e),d=c.length,p=!1;for(let e=0;e1&&!n&&!s.canIntersects(e))continue;let a=s.intersects(e,this._positions,this.getIndices(),t,i);if(a&&(t||!u||a.distancee!==this&&e.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(this))&&e.excludedMeshes.splice(t,1);let i=e.getShadowGenerators();if(i){let e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){let e=i.value.getShadowMap();e&&e.renderList&&-1!==(t=e.renderList.indexOf(this))&&e.renderList.splice(t,1)}}}),("InstancedMesh"!==this.getClassName()||"InstancedLinesMesh"!==this.getClassName())&&this.releaseSubMeshes();let s=r.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,s.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),s.wipeCaches(),r.removeMesh(this),this._parentContainer){let 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(i=0;i65535){t=!0;break}t?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){let t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:t5.Zero()}e.depthSortedFacets=[];for(let t=0;t.001?s.maximum.x-s.minimum.x:.001,e.bbSize.y=s.maximum.y-s.minimum.y>.001?s.maximum.y-s.minimum.y:.001,e.bbSize.z=s.maximum.z-s.minimum.z>.001?s.maximum.z-s.minimum.z:.001;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=s,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),t5.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&ng.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let t=e.depthSortedIndices.length/3|0;for(let r=0;rs.subDiv.max||a<0||a>s.subDiv.max||o<0||o>s.subDiv.max?null:s.facetPartitioning[n+s.subDiv.max*a+s.subDiv.max*s.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,n=!0){let a=this.getWorldMatrix(),o=ie.Matrix[5];a.invertToRef(o);let l=ie.Vector3[8];t5.TransformCoordinatesFromFloatsToRef(e,t,i,o,l);let h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,r,s,n);return r&&t5.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,a,r),h}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,n=!0){let a,o,l,h=null,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=this.getFacetLocalPositions(),x=this.getFacetLocalNormals(),T=this.getFacetsAtLocalCoordinates(e,t,i);if(!T)return null;let b=Number.MAX_VALUE,E=b;for(let S=0;S=0||s&&!n&&p<=0)&&(p=o.x*l.x+o.y*l.y+o.z*l.z,_=-(o.x*e+o.y*t+o.z*i-p)/(o.x*o.x+o.y*o.y+o.z*o.z),f=e+o.x*_,m=t+o.y*_,g=i+o.z*_,(E=(u=f-e)*u+(c=m-t)*c+(d=g-i)*d)e.emitter===this)}}function nD(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")}function nO(e,t,i){var r,s,n,a,o,l;let h=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),u=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),c=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),d=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),p=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),u&&i.push("#define CLIPPLANE2"),c&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),_&&i.push("#define CLIPPLANE6")}function nN(e,t,i){var r,s,n,a,o,l;let h=null!==(r=t.clipPlane)&&void 0!==r?r:i.clipPlane;nF(e,"vClipPlane",h),nF(e,"vClipPlane2",h=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2),nF(e,"vClipPlane3",h=null!==(n=t.clipPlane3)&&void 0!==n?n:i.clipPlane3),nF(e,"vClipPlane4",h=null!==(a=t.clipPlane4)&&void 0!==a?a:i.clipPlane4),nF(e,"vClipPlane5",h=null!==(o=t.clipPlane5)&&void 0!==o?o:i.clipPlane5),nF(e,"vClipPlane6",h=null!==(l=t.clipPlane6)&&void 0!==l?l:i.clipPlane6)}function nF(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}nM.OCCLUSION_TYPE_NONE=0,nM.OCCLUSION_TYPE_OPTIMISTIC=1,nM.OCCLUSION_TYPE_STRICT=2,nM.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,nM.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,nM.CULLINGSTRATEGY_STANDARD=0,nM.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,nM.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,nM.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,t0["BABYLON.AbstractMesh"]=nM;class nw{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){let r=e.getTextureMatrix();t.updateMatrix(i+"Matrix",r)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==sY.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,r,s,n,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=i,a.POINTSIZE=r,a.FOG=s&&this.GetFogState(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){let r=t.CAMERA_ORTHOGRAPHIC?1:0,s=t.CAMERA_PERSPECTIVE?1:0,n=e.activeCamera.mode===ns.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===ns.PERSPECTIVE_CAMERA?1:0;(r^n||s^a)&&(t.CAMERA_ORTHOGRAPHIC=1===n,t.CAMERA_PERSPECTIVE=1===a,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,r,s,n=null,a=!1){let o=nw.PrepareDefinesForCamera(e,r);!1!==n&&(o=function(e,t,i){var r,s,n,a,o,l;let h=!1,u=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),p=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),_=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==u&&(i.CLIPPLANE=u,h=!0),i.CLIPPLANE2!==c&&(i.CLIPPLANE2=c,h=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,h=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,h=!0),i.CLIPPLANE5!==_&&(i.CLIPPLANE5=_,h=!0),i.CLIPPLANE6!==f&&(i.CLIPPLANE6=f,h=!0),h}(i,e,r)),!t.getColorWrite()!==r.DEPTHPREPASS&&(r.DEPTHPREPASS=!r.DEPTHPREPASS,o=!0),r.INSTANCES!==s&&(r.INSTANCES=s,o=!0),r.THIN_INSTANCES!==a&&(r.THIN_INSTANCES=a,o=!0),o&&r.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;let i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;let r=e.getScene().prePassRenderer;if(r&&r.enabled){let i=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){let i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){let i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!i&&!!i.isEnabled}static PrepareDefinesForAttributes(e,t,i,r,s=!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(sf.NormalKind),t._needNormals&&e.isVerticesDataPresent(sf.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){let i=e.useVertexColors&&e.isVerticesDataPresent(sf.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent(sf.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){let i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){let r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(r!==t.ORDER_INDEPENDENT_TRANSPARENCY||s!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){let r=t.PREPASS;if(!t._arePrePassDirty)return;let s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i0&&(a.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=sH.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==sH.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}static PrepareDefinesForLights(e,t,i,r,s=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0,o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(let n of t.lightSources)if(this.PrepareDefinesForLight(e,t,n,a,i,r,o),++a===s)break}i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e0&&(s=r+n,t.addFallback(s,"LIGHT"+n)),!e.SHADOWS&&(e["SHADOW"+n]&&t.addFallback(r,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(r,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(r,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(r,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(r,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(r,"SHADOWCLOSEESM"+n));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){let r=i.NUM_MORPH_INFLUENCERS;if(r>0&&t2.LastCreatedEngine){let s=t2.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(null==n?void 0:n.isUsingTextureForTargets)return;let a=n&&n.supportsNormals&&i.NORMAL,o=n&&n.supportsTangents&&i.TANGENT,l=n&&n.supportsUVs&&i.UV1;for(let i=0;is&&ig.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,r){i.NUM_BONE_INFLUENCERS>0&&(r.addCPUSkinningFallback(0,t),e.push(sf.MatricesIndicesKind),e.push(sf.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(sf.MatricesIndicesExtraKind),e.push(sf.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(sf.ColorInstanceKind)}static PushAttributesForInstances(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"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,r,s,n=!0){e._bindLight(t,i,r,s,n)}static BindLights(e,t,i,r,s=4){let n=Math.min(t.lightSources.length,s);for(let s=0;s-1){let i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{let s=r.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),nw._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){let i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){let e=i.activeCamera;e.mode===ns.ORTHOGRAPHIC_CAMERA&&ig.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}}nw._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},nw._TempFogColor=io.Black();class nL{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}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){i$.Clone(()=>e,this)}serialize(){return i$.Serialize(this)}parse(e,t,i){i$.Parse(()=>this,e,t,i)}}iZ([iW()],nL.prototype,"func",null),iZ([iW()],nL.prototype,"funcRef",null),iZ([iW()],nL.prototype,"funcMask",null),iZ([iW()],nL.prototype,"opStencilFail",null),iZ([iW()],nL.prototype,"opDepthFail",null),iZ([iW()],nL.prototype,"opStencilDepthPass",null),iZ([iW()],nL.prototype,"mask",null),iZ([iW()],nL.prototype,"enabled",null),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(M||(M={}));class nB{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(1===t||1===e)&&this.markAsDirty(nB.MiscDirtyFlag+nB.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(nB.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(nB.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 tj),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 tj),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new tj),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(nB.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(nB.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case nB.WireFrameFillMode:case nB.LineListDrawMode:case nB.LineLoopDrawMode:case nB.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?nB.WireFrameFillMode:nB.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case nB.PointFillMode:case nB.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?nB.PointFillMode:nB.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(nB.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){let t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&ig.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,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!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.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new tj,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,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 nL,this._useUBO=!1,this._fillMode=nB.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=()=>void 0,this._callbackPluginEventIsReadyForSubMesh=()=>void 0,this._callbackPluginEventPrepareDefines=()=>void 0,this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>void 0,this._callbackPluginEventHardBindForSubMesh=()=>void 0,this._callbackPluginEventBindForSubMesh=()=>void 0,this._callbackPluginEventHasRenderTargetTextures=()=>void 0,this._callbackPluginEventFillRenderTargetTextures=()=>void 0,this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;let r=t||t2.LastCreatedScene;if(!r)return;this._scene=r,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||ss.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new rY(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=nB.ClockWiseSideOrientation:this.sideOrientation=nB.CounterClockWiseSideOrientation,this._uniformBuffer=new sp(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),nB.OnEventObservable.notifyObservers(this,M.Created)}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,i){let r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===nB.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===nB.MATERIAL_OPAQUE||this._transparencyMode===nB.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){for(let t of this.getScene().meshes)if(t.subMeshes)for(let i of t.subMeshes)i.getMaterial()===this&&i.effect&&(i.effect._wasPreviouslyReady=!1,i.effect._wasPreviouslyUsingInstances=null,i.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(nB.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),r=(null==t?this.sideOrientation:t)===nB.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,r,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),r}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(M.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i.effect;r&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,nw.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){let e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){let e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(M.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(M.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(M.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),nB._parsePlugins(i,e,this._scene,t),this.pluginManager)for(let t of this.pluginManager._plugins){let i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(!this.meshMap)return this._scene.meshes.filter(e=>e.material===this);{let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}}forceCompilation(e,t,i,r){let s=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let o=()=>{if(!this._scene||!this._scene.getEngine())return;let i=n.clipPlane;if(s.clipPlane&&(n.clipPlane=new sG(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){let t=new nf(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,n&&r&&r(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);s.clipPlane&&(n.clipPlane=i)};o()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,e=>{r(e)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(nB._DirtyCallbackArray.length=0,e&nB.TextureDirtyFlag&&nB._DirtyCallbackArray.push(nB._TextureDirtyCallBack),e&nB.LightDirtyFlag&&nB._DirtyCallbackArray.push(nB._LightsDirtyCallBack),e&nB.FresnelDirtyFlag&&nB._DirtyCallbackArray.push(nB._FresnelDirtyCallBack),e&nB.AttributesDirtyFlag&&nB._DirtyCallbackArray.push(nB._AttributeDirtyCallBack),e&nB.MiscDirtyFlag&&nB._DirtyCallbackArray.push(nB._MiscDirtyCallBack),e&nB.PrePassDirtyFlag&&nB._DirtyCallbackArray.push(nB._PrePassDirtyCallBack),nB._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(nB._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){for(let e of this.getScene().meshes)if(e.subMeshes)for(let t of e.subMeshes)t.getMaterial()===this&&t.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(!this.getScene().blockMaterialDirtyMechanism&&!this._blockDirtyMechanism){for(let t of this.getScene().meshes)if(t.subMeshes){for(let i of t.subMeshes)if(i.getMaterial(!1)===this)for(let t of i._drawWrappers)t&&t.defines&&t.defines.markAllAsDirty&&this._materialContext===t.materialContext&&e(t.defines)}}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(nB._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(nB._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(nB._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(nB._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(nB._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(nB._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(nB._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(nB._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(nB._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(nB._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==y.BackwardCompatible){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(M.Disposed,this._eventInfo),this._parentContainer){let e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i){if(this.meshMap)for(let t in this.meshMap){let i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else for(let t of r.meshes)t.material!==this||t.sourceMesh||(t.material=null,this.releaseVertexArrayObject(t,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){let i=e.geometry;if(i){if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(let r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){let e=i$.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(let t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return ig.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";let r=ss.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _parsePlugins(e,t,i,r){var s;if(e.plugins)for(let n in e.plugins){let a=e.plugins[n],o=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(a.name);if(!o){let e=ss.Instantiate("BABYLON."+n);e&&(o=new e(t))}null==o||o.parse(a,i,r)}}}nB.TriangleFillMode=0,nB.WireFrameFillMode=1,nB.PointFillMode=2,nB.PointListDrawMode=3,nB.LineListDrawMode=4,nB.LineLoopDrawMode=5,nB.LineStripDrawMode=6,nB.TriangleStripDrawMode=7,nB.TriangleFanDrawMode=8,nB.ClockWiseSideOrientation=0,nB.CounterClockWiseSideOrientation=1,nB.TextureDirtyFlag=1,nB.LightDirtyFlag=2,nB.FresnelDirtyFlag=4,nB.AttributesDirtyFlag=8,nB.MiscDirtyFlag=16,nB.PrePassDirtyFlag=32,nB.AllDirtyFlag=63,nB.MATERIAL_OPAQUE=0,nB.MATERIAL_ALPHATEST=1,nB.MATERIAL_ALPHABLEND=2,nB.MATERIAL_ALPHATESTANDBLEND=3,nB.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,nB.MATERIAL_NORMALBLENDMETHOD_RNM=1,nB.OnEventObservable=new tj,nB._AllDirtyCallBack=e=>e.markAllAsDirty(),nB._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),nB._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),nB._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),nB._MiscDirtyCallBack=e=>e.markAsMiscDirty(),nB._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),nB._LightsDirtyCallBack=e=>e.markAsLightDirty(),nB._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),nB._FresnelAndMiscDirtyCallBack=e=>{nB._FresnelDirtyCallBack(e),nB._MiscDirtyCallBack(e)},nB._TextureAndMiscDirtyCallBack=e=>{nB._TextureDirtyCallBack(e),nB._MiscDirtyCallBack(e)},nB._DirtyCallbackArray=[],nB._RunDirtyCallBacks=e=>{for(let t of nB._DirtyCallbackArray)t(e)},iZ([iW()],nB.prototype,"id",void 0),iZ([iW()],nB.prototype,"uniqueId",void 0),iZ([iW()],nB.prototype,"name",void 0),iZ([iW()],nB.prototype,"metadata",void 0),iZ([iW()],nB.prototype,"checkReadyOnEveryCall",void 0),iZ([iW()],nB.prototype,"checkReadyOnlyOnce",void 0),iZ([iW()],nB.prototype,"state",void 0),iZ([iW("alpha")],nB.prototype,"_alpha",void 0),iZ([iW("backFaceCulling")],nB.prototype,"_backFaceCulling",void 0),iZ([iW("cullBackFaces")],nB.prototype,"_cullBackFaces",void 0),iZ([iW()],nB.prototype,"sideOrientation",void 0),iZ([iW("alphaMode")],nB.prototype,"_alphaMode",void 0),iZ([iW()],nB.prototype,"_needDepthPrePass",void 0),iZ([iW()],nB.prototype,"disableDepthWrite",void 0),iZ([iW()],nB.prototype,"disableColorWrite",void 0),iZ([iW()],nB.prototype,"forceDepthWrite",void 0),iZ([iW()],nB.prototype,"depthFunction",void 0),iZ([iW()],nB.prototype,"separateCullingPass",void 0),iZ([iW("fogEnabled")],nB.prototype,"_fogEnabled",void 0),iZ([iW()],nB.prototype,"pointSize",void 0),iZ([iW()],nB.prototype,"zOffset",void 0),iZ([iW()],nB.prototype,"zOffsetUnits",void 0),iZ([iW()],nB.prototype,"pointsCloud",null),iZ([iW()],nB.prototype,"fillMode",null),iZ([iW()],nB.prototype,"useLogarithmicDepth",null),iZ([iW()],nB.prototype,"transparencyMode",null);class nU extends nB{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){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}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){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new nU(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,iF&&iF.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(e=>i.subMaterials.push(t.getLastMaterialById(e))),i}}t0["BABYLON.MultiMaterial"]=nU;class nV{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class nk{}class nG{constructor(){this.visibleInstances={},this.batchCache=new nz,this.batchCacheReplacementModeInFrozenMode=new nz,this.instancesBufferSize=2048}}class nz{constructor(){this.mustReturn=!1,this.visibleInstances=[],this.renderSelf=[],this.hardwareInstancedRendering=[]}}class nW{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class nH{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=[],this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class nX extends nM{static _GetDefaultSideOrientation(e){return e||nX.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(sf.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(sf.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 tj),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new tj),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new tj),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new tj),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new tj),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 overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=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}constructor(e,t=null,i=null,r=null,s,n=!0){if(super(e,t),this._internalMeshDataInfo=new nH,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new nG,this._thinInstanceDataStorage=new nW,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=nX.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},r){if(r._geometry&&r._geometry.applyToMesh(this),iP.DeepCopy(r,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=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){let e=r._ranges;for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,this._internalMetadata=r._internalMetadata,iF&&iF.HasTags(r)&&iF.AddTagsTo(this,iF.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix()),this.id=e+"."+r.id,this.material=r.material,!s){let t=r.getDescendants(!0);for(let i=0;i{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 tj(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){let r=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));for(let s of(r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r),this.getChildTransformNodes(!0)))"InstancedMesh"===s.getClassName()&&"Mesh"===r.getClassName()&&s.sourceMesh===this?s.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):s.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices()+", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return ig.Warn("You cannot use a mesh as LOD level twice"),this;let i=new nV(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let i=0;ia*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();let d=this.material||u.defaultMaterial;if(d){if(d._storeEffectOnSubMeshes)for(let e of this.subMeshes){let t=e.getMaterial();if(t){if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,c))return!1}else if(!t.isReady(this,c))return!1}}else if(!d.isReady(this,c))return!1}let p=h.currentRenderPassId;for(let e of this.lightSources){let t=e.getShadowGenerators();if(!t)continue;let u=t.values();for(let e=u.next();!0!==e.done;e=u.next()){let t=e.value;if(t&&(!(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)||(null===(r=t.getShadowMap())||void 0===r?void 0:r.renderList)&&(null===(n=null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||void 0===n?void 0:n.indexOf(this))!==-1)){let e=null!==(a=t.getShadowMap().renderPassIds)&&void 0!==a?a:[h.currentRenderPassId];for(let i=0;i0){let i=this.getIndices();if(!i)return null;let r=i.length,s=!1;if(e)s=!0;else for(let e of this.subMeshes)if(e.indexStart+e.indexCount>r||e.verticesStart+e.verticesCount>t){s=!0;break}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new nf(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),i=t/e|0,r=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)nf.CreateFromIndices(0,r,s===e-1?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{let r=new ng;r.set(t,e);let s=this.getScene();new nT(nT.RandomId(),s,r,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=nT.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,r){return this._geometry&&(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i)),this}updateMeshPositions(e,t=!0){let i=this.getVerticesData(sf.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(sf.PositionKind,i,!1,!1),t){let e=this.getIndices(),t=this.getVerticesData(sf.NormalKind);if(!t)return this;ng.ComputeNormals(i,e,t),this.updateVerticesData(sf.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry||1===this._geometry.meshes.length)return this;let e=this._geometry,t=this._geometry.copy(nT.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,i){let r=this._geometry;r||(r=new nT(nT.RandomId(),this.getScene(),void 0,void 0,this)),r.setIndexBuffer(e,t,i)}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{let t=new ng;t.indices=e;let r=this.getScene();new nT(nT.RandomId(),r,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry&&this._geometry.updateIndices(e,t,i),this}toLeftHanded(){return this._geometry&&this._geometry.toLeftHanded(),this}_bind(e,t,i,r=!0){let s;if(!this._geometry)return this;let n=this.getScene().getEngine();if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)s=null;else switch(this._getRenderingFillMode(i)){case nB.PointFillMode:s=null;break;case nB.WireFrameFillMode:s=e._getLinesIndexBuffer(this.getIndices(),n);break;default:case nB.TriangleFillMode:s=this._geometry.getIndexBuffer()}return r&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,s,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,s),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);let r=this.getScene().getEngine();return this._unIndexed||t==nB.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==nB.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):r.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),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}let i=this.getScene(),r=i._isInIntermediateRendering(),s=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){let t=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),a=r?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[s],!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,i,r,s){var n;let a=i.visibleInstances[e._id],o=a?a.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize,u=l.instancesBuffer,c=l.instancesPreviousBuffer,d=64*(o+1);for(;l.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&u.activeCamera===u.activeCameras[0]||c<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let d=this._getInstancesRenderList(e._id,!!i);if(d.mustReturn||!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let p=u.getEngine(),_=0,f=null;this.ignoreCameraMaxZ&&u.activeCamera&&!u._isInIntermediateRendering()&&(_=u.activeCamera.maxZ,f=u.activeCamera,u.activeCamera.maxZ=0,u.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let m=e.getRenderingMesh(),g=d.hardwareInstancedRendering[e._id]||m.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,v=this._instanceDataStorage,x=e.getMaterial();if(!x)return f&&(f.maxZ=_,u.updateTransformMatrix(!0)),this;if(v.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===x){if(x._storeEffectOnSubMeshes&&!(null===(n=e.effect)||void 0===n?void 0:n._wasPreviouslyReady)||!x._storeEffectOnSubMeshes&&!(null===(a=x.getEffect())||void 0===a?void 0:a._wasPreviouslyReady))return f&&(f.maxZ=_,u.updateTransformMatrix(!0)),this}else{if(x._storeEffectOnSubMeshes){if(!x.isReadyForSubMesh(this,e,g))return f&&(f.maxZ=_,u.updateTransformMatrix(!0)),this}else if(!x.isReady(this,g))return f&&(f.maxZ=_,u.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=x}t&&p.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let T=null!==(o=null==(l=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper())?void 0:l.effect)&&void 0!==o?o:null;for(let t of u._beforeRenderingMeshStage)t.action(this,e,d,T);if(!l||!T)return f&&(f.maxZ=_,u.updateTransformMatrix(!0)),this;let b=i||this;if(!v.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||null!==this.overrideMaterialSideOrientation||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){let e=b._getWorldMatrixDeterminant();null==(h=this.overrideMaterialSideOrientation)&&(h=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(h=h===nB.ClockWiseSideOrientation?nB.CounterClockWiseSideOrientation:nB.ClockWiseSideOrientation),v.sideOrientation=h}else h=v.sideOrientation;let E=this._internalMeshDataInfo._effectiveMaterial._preBind(l,h);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&p.setDepthWrite(!0);let S=this._internalMeshDataInfo._effectiveMaterial,C=S.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),g||this._bind(e,T,C,!1);let A=b.getWorldMatrix();for(let t of(S._storeEffectOnSubMeshes?S.bindForSubMesh(A,this,e):S.bind(A,this),!S.backFaceCulling&&S.separateCullingPass&&(p.setState(!0,S.zOffset,!1,!E,S.cullBackFaces,S.stencil,S.zOffsetUnits),this._processRendering(this,e,T,C,d,g,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),p.setState(!0,S.zOffset,!1,E,S.cullBackFaces,S.stencil,S.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,T,C,d,g,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind(),u._afterRenderingMeshStage))t.action(this,e,d,T);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),f&&(f.maxZ=_,u.updateTransformMatrix(!0)),u.performancePriority!==y.Aggressive||v.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(sf.MatricesWeightsKind)&&(this.isVerticesDataPresent(sf.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){let e=this.getVerticesData(sf.MatricesWeightsKind),t=e.length;for(let i=0;ii&&r++,0!==n&&c++,u+=n,i=n}if(l[c]++,c>n&&(n=c),0===u)s++;else{let i=1/u,r=0;for(let s=0;s.001&&a++}}let h=this.skeleton.bones.length,u=this.getVerticesData(sf.MatricesIndicesKind),c=this.getVerticesData(sf.MatricesIndicesExtraKind),d=0;for(let e=0;e=h||i<0)&&d++}let p="Number of Weights = "+i/4+"\nMaximum influences = "+n+"\nMissing Weights = "+s+"\nNot Sorted = "+r+"\nNot Normalized = "+a+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d;return{skinned:!0,valid:0===s&&0===a&&0===d,report:p}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return ss.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=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return!!(2!==this.delayLoadState&&super.isInFrustum(e))&&(this._checkDelayState(),!0)}setMaterialById(e){let t;let i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;let r=this.getScene().multiMaterials;for(t=r.length-1;t>-1;t--)if(r[t].id===e){this.material=r[t];break}return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){let t;if(!this.isVerticesDataPresent(sf.PositionKind))return this;let i=this.subMeshes.splice(0);this._resetPointsArrayCache();let r=this.getVerticesData(sf.PositionKind),s=t5.Zero();for(t=0;te.determinant()&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=i,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?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,i,r=!0){return new nX(e,this.getScene(),t,this,i,r)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);let i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(let e in i.meshMap){let t=i.meshMap[e];t&&(t._internalMeshDataInfo._source=null,i.meshMap[e]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else for(let e of this.getScene().meshes)e._internalMeshDataInfo&&e._internalMeshDataInfo._source&&e._internalMeshDataInfo._source===this&&(e._internalMeshDataInfo._source=null);i._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,i,r,s,n,a=!1,o){let l=this.getScene();return ss.LoadImage(e,e=>{let o=e.width,l=e.height,h=this.getEngine().createCanvas(o,l).getContext("2d");h.drawImage(e,0,0);let u=h.getImageData(0,0,o,l).data;this.applyDisplacementMapFromBuffer(u,o,l,t,i,s,n,a),r&&r(this)},o||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,n,a,o=!1){if(!this.isVerticesDataPresent(sf.PositionKind)||!this.isVerticesDataPresent(sf.NormalKind)||!this.isVerticesDataPresent(sf.UVKind))return ig.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let l=this.getVerticesData(sf.PositionKind,!0,!0),h=this.getVerticesData(sf.NormalKind),u=this.getVerticesData(sf.UVKind),c=t5.Zero(),d=t5.Zero(),p=t4.Zero();n=n||t4.Zero(),a=a||new t4(1,1);for(let o=0;o{let r=new Float32Array(i.length*t),s=0;for(let n=0;nMath.abs(r[3*u[e]+t])&&(r[3*u[e]+t]=0),x[e]+=r[3*u[e]+t]+"|"}if(!(x[0]==x[1]||x[0]==x[2]||x[1]==x[2]))for(let e=0;e<3;e++){if(void 0===(h=b[x[e]])){b[x[e]]=T,h=T++;for(let t=0;t<3;t++)c.push(r[3*u[e]+t]);if(null!=s)for(let t=0;t<4;t++)_.push(s[4*u[e]+t]);if(null!=t)for(let i=0;i<2;i++)p.push(t[2*u[e]+i]);if(null!=n)for(let t=0;t<4;t++)f.push(n[4*u[e]+t]);if(null!=a)for(let t=0;t<4;t++)m.push(a[4*u[e]+t]);if(null!=o)for(let t=0;t<4;t++)g.push(o[4*u[e]+t]);if(null!=l)for(let t=0;t<4;t++)v.push(l[4*u[e]+t])}d.push(h)}}let E=[];ng.ComputeNormals(c,d,E),e.positions=c,e.indices=d,e.normals=E,null!=t&&(e.uvs=p),null!=s&&(e.colors=_),null!=n&&(e.matricesIndices=f),null!=a&&(e.matricesWeights=m),null!=o&&(e.matricesIndicesExtra=g),null!=a&&(e.matricesWeightsExtra=v),e.applyToMesh(this,this.isVertexBufferUpdatable(sf.PositionKind))}}static _instancedMeshFactory(e,t){throw iL("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw iL("PhysicsImpostor")}createInstance(e){return nX._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e{let t=r.length-1-e,i=r[t];for(let e=0;e{for(let e=0;e-1&&(r.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,h=l?this.getVerticesData(sf.MatricesIndicesExtraKind):null,u=l?this.getVerticesData(sf.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),d=t5.Zero(),p=new t7,_=new t7,f=0;for(let e=0;e0&&(t7.FromFloat32ArrayToRefScaled(c,Math.floor(16*a[f+t]),m,_),p.addToSelf(_));if(l)for(t=0;t<4;t++)(m=u[f+t])>0&&(t7.FromFloat32ArrayToRefScaled(c,Math.floor(16*h[f+t]),m,_),p.addToSelf(_));t5.TransformCoordinatesFromFloatsToRef(r._sourcePositions[e],r._sourcePositions[e+1],r._sourcePositions[e+2],p,d),d.toArray(s,e),i&&(t5.TransformNormalFromFloatsToRef(r._sourceNormals[e],r._sourceNormals[e+1],r._sourceNormals[e+2],p,d),d.toArray(n,e)),p.reset()}return this.updateVerticesData(sf.PositionKind,s),i&&this.updateVerticesData(sf.NormalKind,n),this}static MinMax(e){let t=null,i=null;return(e.forEach(function(e){let r=e.getBoundingInfo().boundingBox;t&&i?(t.minimizeInPlace(r.minimumWorld),i.maximizeInPlace(r.maximumWorld)):(t=r.minimumWorld,i=r.maximumWorld)}),t&&i)?{min:t,max:i}:{min:t5.Zero(),max:t5.Zero()}}static Center(e){let t=e instanceof Array?nX.MinMax(e):e;return t5.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,n){return nt(nX._MergeMeshesCoroutine(e,t,i,r,s,n,!1))}static MergeMeshesAsync(e,t=!0,i,r,s,n){return ni(nX._MergeMeshesCoroutine(e,t,i,r,s,n,!0),function(e=25){let t;return(i,r,s)=>{let n=performance.now();void 0===t||n-t>e?(t=n,setTimeout(()=>{s9(i,r,s)},0)):s9(i,r,s)}}())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,n,a){let o;if(0===(e=e.filter(Boolean)).length)return null;if(!i){let t=0;for(o=0;o=65536)return ig.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(s=!1);let l=[],h=[],u=[],c=e[0].overrideMaterialSideOrientation;for(o=0;ol.indexOf(e.subMaterials[t])&&l.push(e.subMaterials[t]);for(let i=0;il.indexOf(e)&&l.push(e);for(let i=0;i{let t=e.computeWorldMatrix(!0);return{vertexData:ng.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:_,transform:f}=p(d);a&&(yield);let m=Array(e.length-1);for(let t=1;t{throw iL("GroundMesh")},nX._GoldbergMeshParser=(e,t)=>{throw iL("GoldbergMesh")},nX._LinesMeshParser=(e,t)=>{throw iL("LinesMesh")},nX._GreasedLineMeshParser=(e,t)=>{throw iL("GreasedLineMesh")},nX._GreasedLineRibbonMeshParser=(e,t)=>{throw iL("GreasedLineRibbonMesh")},nX._TrailMeshParser=(e,t)=>{throw iL("TrailMesh")},t0["BABYLON.Mesh"]=nX,nX._instancedMeshFactory=(e,t)=>{let i=new nY(e,t);if(t.instancedBuffers)for(let e in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e];return i};class nY extends nM{constructor(e,t){for(let i of(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(),t.getAnimationRanges()))null!=i&&this.createAnimationRange(i.name,i.from,i.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){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.receiveShadows)!==e&&ss.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.material)!==e&&ss.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.visibility)!==e&&ss.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.skeleton)!==e&&ss.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&&ig.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,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),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 i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||ig.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!==nA.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new t7);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,ie.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(ie.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){let 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;e0)||-1!==this.includedOnlyMeshes.indexOf(e))&&(!this.excludedMeshes||!(this.excludedMeshes.length>0)||-1===this.excludedMeshes.indexOf(e))&&(0===this.includeOnlyWithLayerMask||(this.includeOnlyWithLayerMask&e.layerMask)!=0)&&(0===this.excludeWithLayerMask||!(this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){let 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){let e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(let 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){let i=nj.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=i$.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=i$.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)})),i$.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return i0.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){let i=nj.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=i$.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{let r=t.apply(e,i);for(let e of i)e._resyncLightSource(this);return r};let i=e.splice;for(let t of(e.splice=(t,r)=>{let s=i.apply(e,[t,r]);for(let e of s)e._resyncLightSource(this);return s},e))t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._resyncMeshes(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===nj.INTENSITYMODE_AUTOMATIC&&(i=t===nj.LIGHTTYPEID_DIRECTIONALLIGHT?nj.INTENSITYMODE_ILLUMINANCE:nj.INTENSITYMODE_LUMINOUSINTENSITY),t){case nj.LIGHTTYPEID_POINTLIGHT:case nj.LIGHTTYPEID_SPOTLIGHT:switch(i){case nj.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case nj.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case nj.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case nj.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case nj.INTENSITYMODE_ILLUMINANCE:e=1;break;case nj.INTENSITYMODE_LUMINANCE:{let t=this.radius;e=2*Math.PI*(1-Math.cos(t=Math.max(t,.001)))}}break;case nj.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){let e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}nj.FALLOFF_DEFAULT=sH.FALLOFF_DEFAULT,nj.FALLOFF_PHYSICAL=sH.FALLOFF_PHYSICAL,nj.FALLOFF_GLTF=sH.FALLOFF_GLTF,nj.FALLOFF_STANDARD=sH.FALLOFF_STANDARD,nj.LIGHTMAP_DEFAULT=sH.LIGHTMAP_DEFAULT,nj.LIGHTMAP_SPECULAR=sH.LIGHTMAP_SPECULAR,nj.LIGHTMAP_SHADOWSONLY=sH.LIGHTMAP_SHADOWSONLY,nj.INTENSITYMODE_AUTOMATIC=sH.INTENSITYMODE_AUTOMATIC,nj.INTENSITYMODE_LUMINOUSPOWER=sH.INTENSITYMODE_LUMINOUSPOWER,nj.INTENSITYMODE_LUMINOUSINTENSITY=sH.INTENSITYMODE_LUMINOUSINTENSITY,nj.INTENSITYMODE_ILLUMINANCE=sH.INTENSITYMODE_ILLUMINANCE,nj.INTENSITYMODE_LUMINANCE=sH.INTENSITYMODE_LUMINANCE,nj.LIGHTTYPEID_POINTLIGHT=sH.LIGHTTYPEID_POINTLIGHT,nj.LIGHTTYPEID_DIRECTIONALLIGHT=sH.LIGHTTYPEID_DIRECTIONALLIGHT,nj.LIGHTTYPEID_SPOTLIGHT=sH.LIGHTTYPEID_SPOTLIGHT,nj.LIGHTTYPEID_HEMISPHERICLIGHT=sH.LIGHTTYPEID_HEMISPHERICLIGHT,iZ([iX()],nj.prototype,"diffuse",void 0),iZ([iX()],nj.prototype,"specular",void 0),iZ([iW()],nj.prototype,"falloffType",void 0),iZ([iW()],nj.prototype,"intensity",void 0),iZ([iW()],nj.prototype,"range",null),iZ([iW()],nj.prototype,"intensityMode",null),iZ([iW()],nj.prototype,"radius",null),iZ([iW()],nj.prototype,"_renderPriority",void 0),iZ([iz("_reorderLightsInScene")],nj.prototype,"renderPriority",void 0),iZ([iW("shadowEnabled")],nj.prototype,"_shadowEnabled",void 0),iZ([iW("excludeWithLayerMask")],nj.prototype,"_excludeWithLayerMask",void 0),iZ([iW("includeOnlyWithLayerMask")],nj.prototype,"_includeOnlyWithLayerMask",void 0),iZ([iW("lightmapMode")],nj.prototype,"_lightmapMode",void 0);class nK extends tW{}class n${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 nq extends tW{constructor(e){if(super(),this._wasAddedToScene=!1,!(e=e||t2.LastCreatedScene))return;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(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of this.particleSystems)e.rebuild();for(let e of this.textures)e._rebuild()})}_topologicalSort(e){let t=new Map;for(let i of e)t.set(i.uniqueId,i);let i={dependsOn:new Map,dependedBy:new Map};for(let t of e){let e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(let r of e){let e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof nY){let n=r.sourceMesh;t.has(n.uniqueId)&&(s.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}let n=i.dependedBy.get(e);for(let s of r.getDescendants()){let r=s.uniqueId;t.has(r)&&(n.add(r),i.dependsOn.get(r).add(e))}}let r=[],s=[];for(let r of e){let e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}for(;s.length>0;){let e=s.shift();for(let n of(r.push(e),Array.from(i.dependedBy.get(e.uniqueId).values()))){let r=i.dependsOn.get(n);r.delete(e.uniqueId),0===r.size&&t.get(n)&&(s.push(t.get(n)),t.delete(n))}}return t.size>0&&(ig.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(e=>ig.Error(e.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId)))for(let s of(e.push(i),t.add(i.uniqueId),i.getDescendants(!0)))this._addNodeAndDescendantsToList(e,t,s,r)}_isNodeInContainer(e){return e instanceof nX&&-1!==this.meshes.indexOf(e)||e instanceof nA&&-1!==this.transformNodes.indexOf(e)||e instanceof nj&&-1!==this.lights.indexOf(e)||e instanceof ns&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return ig.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return ig.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return ig.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return ig.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||ss.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},n=new n$,a=[],o=[],l=Object.assign({doNotInstantiate:!0},i),h=(t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof nX&&i.morphTargetManager){let e=t.morphTargetManager;i.morphTargetManager=e.clone();for(let t=0;t{if(h(i,a),i.parent){let e=s[r[i.parent.uniqueId]];e?a.parent=e:a.parent=i.parent}if(a.position&&i.position&&a.position.copyFrom(i.position),a.rotationQuaternion&&i.rotationQuaternion&&a.rotationQuaternion.copyFrom(i.rotationQuaternion),a.rotation&&i.rotation&&a.rotation.copyFrom(i.rotation),a.scaling&&i.scaling&&a.scaling.copyFrom(i.scaling),a.material&&a.material){if(t){let t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){for(let n of t.subMaterials)n&&(i=n.clone(e?e(n.name):"Clone of "+n.name),o.push(n),r[n.uniqueId]=i.uniqueId,s[i.uniqueId]=i);t.subMaterials=t.subMaterials.map(e=>e&&s[r[e.uniqueId]])}}"InstancedMesh"!==a.getClassName()&&(a.material=s[r[t.uniqueId]])}else"MultiMaterial"===a.material.getClassName()?-1===this.scene.multiMaterials.indexOf(a.material)&&this.scene.addMultiMaterial(a.material):-1===this.scene.materials.indexOf(a.material)&&this.scene.addMaterial(a.material)}null===a.parent&&n.rootNodes.push(a)};return d.forEach(e=>{if("InstancedMesh"===e.getClassName()){let t=e.sourceMesh,i=r[t.uniqueId],n=("number"==typeof i?s[i]:t).createInstance(e.name);p(e,n)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);let i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw Error(`Could not clone or instantiate node on Asset Container ${e.name}`);p(e,i)}}),this.skeletons.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name);for(let e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){let t=s[r[e.uniqueId]];if(!t||t.isAnInstance||(t.skeleton=i,-1!==a.indexOf(i)))continue;for(let e of(a.push(i),i.bones))e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)}),this.animationGroups.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name,e=>s[r[e.uniqueId]]||e);n.animationGroups.push(i)}),n}addAllToScene(){if(!this._wasAddedToScene){for(let e of(this._isValidHierarchy()||ss.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture),this.scene._serializableComponents))e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of(this.cameras.forEach(i=>{(!e||e(i))&&(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{(!e||e(i))&&(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{(!e||e(i))&&(this.scene.addMesh(i),t.push(i))}),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(i=>{(!e||e(i))&&(this.scene.addTransformNode(i),t.push(i))}),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)}),t))i.parent&&-1===this.scene.getNodes().indexOf(i.parent)&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){for(let e of(this._isValidHierarchy()||ss.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),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(){for(let e of(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),this.scene._serializableComponents))e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(let r of e){let e=!0;if(i){for(let t of i)if(r===t){e=!1;break}}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){for(let t in this._wasAddedToScene=!1,void 0===e&&(e=new nK),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(){let e=new nX("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=t2.LastCreatedScene,t,i=null){if(!e)return ig.Error("No scene available to merge animations to"),[];let r=i||(t=>{let i=null,r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i});this.getNodes().forEach(e=>{let t=r(e);if(null!==t){for(let i of e.animations)for(let e of t.animations.filter(e=>e.targetProperty===i.targetProperty)){let i=t.animations.indexOf(e,0);i>-1&&t.animations.splice(i,1)}t.animations=t.animations.concat(e.animations)}});let s=[];return this.animationGroups.slice().forEach(e=>{s.push(e.clone(e.name,r)),e.animatables.forEach(e=>{e.stop()})}),t.forEach(t=>{let i=r(t.target);i&&(e.beginAnimation(i,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))}),s}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;let t=[],i=new Set;for(t.push(e);t.length>0;){let e=t.pop();if(e instanceof nX?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof nA?this.transformNodes.push(e):e instanceof nj?this.lights.push(e):e instanceof ns&&this.cameras.push(e),e instanceof nM){if(e.material&&-1===this.materials.indexOf(e.material))for(let t of(this.materials.push(e.material),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(let r of e.getChildren())i.has(r)||t.push(r);i.add(e)}this.populateRootNodes()}}nC.AudioEngineFactory=(e,t,i)=>new nQ(e,t,i);class nQ{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=null){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 tj,this.onAudioLockedObservable=new tj,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()};return}lock(){this._triggerSuspendedState()}unlock(){var e,t;if((null===(e=this._audioContext)||void 0===e?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?null===(t=this._audioContext)||void 0===t||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(null===(e=this._audioContext)||void 0===e?void 0:e.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,ig.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";let e=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",t=document.createElement("style");t.appendChild(document.createTextNode(".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }")),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 nZ{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((null===(e=nC.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){let e=this.isPaused?0:nC.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;let t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){var n,a,o,l,h;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 tj,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=t5.Zero(),this._localDirection=new t5(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,!(i=i||t2.LastCreatedScene))return;if(this._scene=i,nZ._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{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&&ig.Error("XHR "+e.status+" error on: "+t+"."),ig.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:e=!1}e?!r&&(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):ig.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){ig.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),nC.audioEngine&&!nC.audioEngine.WarnedWebAudioUnsupported&&(ig.Error("Web Audio is not supported by your browser."),nC.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(null===(e=nC.audioEngine)||void 0===e?void 0:e.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){var t;(null===(t=nC.audioEngine)||void 0===t?void 0:t.audioContext)&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(null===(t=nC.audioEngine)||void 0===t?void 0:t.audioContext)&&nC.audioEngine.audioContext.decodeAudioData(e,e=>{this._audioBufferLoaded(e)},e=>{ig.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)})}setAudioBuffer(e){var t;(null===(t=nC.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,r,s,n,a,o,l,h,u,c;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(r=e.useCustomAttenuation)&&void 0!==r?r:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(n=e.refDistance)&&void 0!==n?n:this.refDistance,this.distanceModel=null!==(a=e.distanceModel)&&void 0!==a?a:this.distanceModel,this._playbackRate=null!==(o=e.playbackRate)&&void 0!==o?o:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this.spatialSound=null!==(h=e.spatialSound)&&void 0!==h?h:this._spatialSound,this._setOffset(null!==(u=e.offset)&&void 0!==u?u:void 0),this.setVolume(null!==(c=e.volume)&&void 0!==c?c: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(){var e,t;(null===(e=nC.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&nC.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:nC.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,null===(e=this._soundPanner)||void 0===e||e.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.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(){var e;(null===(e=nC.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=nC.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){let e=()=>{var t,i;if(null===(t=nC.audioEngine)||void 0===t?void 0:t.unlocked){let t=this._htmlAudioElement.play();void 0!==t&&t.catch(()=>{var t,i;null===(t=nC.audioEngine)||void 0===t||t.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(i=nC.audioEngine)||void 0===i?void 0:i.onAudioUnlockedObservable.addOnce(()=>{e()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(i=nC.audioEngine)||void 0===i?void 0:i.onAudioUnlockedObservable.addOnce(()=>{e()}))};e()}}else{let s=()=>{var s,n,a,o;if(null===(s=nC.audioEngine)||void 0===s?void 0:s.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){let e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=null===(n=nC.audioEngine)||void 0===n?void 0:n.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!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?(null===(a=nC.audioEngine)||void 0===a?void 0:a.audioContext.currentTime)+e:nC.audioEngine.audioContext.currentTime;let s=((this.isPaused?this.currentTime:0)+(null!==(o=this._offset)&&void 0!==o?o:0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};(null===(a=nC.audioEngine)||void 0===a?void 0:a.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var e;(null===(e=nC.audioEngine)||void 0===e?void 0:e.audioContext.state)==="suspended"?(nC.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=nC.audioEngine.onAudioUnlockedObservable.addOnce(()=>{s()}))):s()},500):s()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){ig.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){var t;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((null===(t=nC.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){let t=e?nC.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=()=>void 0),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1}else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=nC.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>void 0,this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=nC.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=nC.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&nC.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(nC.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,nC.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,nC.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){var t;if(e.getBoundingInfo){let t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=nC.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{let e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.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},i=new nZ(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){let 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,i,r){let s,n;let a=e.name;s=e.url?i+e.url:i+a;let o={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};if(r){let e=()=>{r._isReadyToPlay?(n._audioBuffer=r.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play(0,n._offset,n._length)):setTimeout(e,300)};n=new nZ(a,new ArrayBuffer(0),t,null,o),e()}else n=new nZ(a,s,t,()=>{t.removePendingData(n)},o),t.addPendingData(n);if(e.position){let t=t5.FromArray(e.position);n.setPosition(t)}if(e.isDirectional&&(n.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){let t=t5.FromArray(e.localDirectionToMesh);n.setLocalDirectionToMesh(t)}if(e.connectedMeshId){let i=t.getMeshById(e.connectedMeshId);i&&n.attachToMesh(i)}return e.metadata&&(n.metadata=e.metadata),n}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(null===(e=nC.audioEngine)||void 0===e||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}nZ._SceneComponentInitialization=e=>{throw iL("AudioSceneComponent")};class nJ{constructor(e,t={}){if(this.id=-1,this._isInitialized=!1,!(e=e||t2.LastCreatedScene))return;this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}_initializeSoundTrackAudioGraph(){var e;(null===(e=nC.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&nC.audioEngine.audioContext&&(this._outputAudioNode=nC.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(nC.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(nC.audioEngine&&nC.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(null===(t=nC.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){let t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=nC.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=nC.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e{var s;let n;let a=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,l=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)})}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach(e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()})}dispose(){let e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){let e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){let e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),t5.TransformNormalToRef(n0._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(sb.NAME_AUDIO);t||(t=new n0(e),e._addComponent(t))};class n1{constructor(e){if(this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,!(e=e||t2.LastCreatedScene))return;this._scene=e,this.animationParameters=new t6(0,0,0,30)}_markSubMeshesAsAttributesDirty(){for(let e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;let i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){let e=new n1(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,r=30){this.animationParameters=new t6(e,t,i,r)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){i$.Clone(()=>e,this)}serialize(){return i$.Serialize(this)}parse(e,t,i){i$.Parse(()=>this,e,t,i)}}iZ([iH(),iz("_markSubMeshesAsAttributesDirty")],n1.prototype,"texture",void 0),iZ([iW(),iz("_markSubMeshesAsAttributesDirty")],n1.prototype,"isEnabled",void 0),iZ([iW()],n1.prototype,"animationParameters",void 0),iZ([iW()],n1.prototype,"time",void 0);class n2{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(null==e?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=i1.Zero(),this._cachedBaseSize=i1.Zero(),this._initialSamplingMode=2,this._texture=n2._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(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;this._texture._size&&(this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size)}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.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight):(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)}}class n3 extends n2{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,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){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,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=sr()),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=0,this.wrapR=1,this.anisotropicFilteringLevel=n3.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 tj,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?n3._IsScene(e)?this._scene=e:this._engine=e:this._scene=t2.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}checkTransformsAreIdentical(e){return null!==e}getTextureMatrix(){return t7.IdentityReadOnly}getReflectionTextureMatrix(){return t7.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,n){let a=this._getEngine();if(!a)return null;let o=a._getUseSRGBBuffer(!!s,t),l=a.getLoadedTexturesCache();for(let a=0;a=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let 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;let t=i$.Serialize(this);return i$.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0===i){t();return}for(let r=0;r{0==--i&&t()}):0==--i&&t()}}}static _IsScene(e){return"Scene"===e.getClassName()}}function n4(e,t,i=!1){let r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT,i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}let n=document.createElement("canvas");n.width=r,n.height=s;let a=n.getContext("2d");if(!a)return null;let o=a.createImageData(r,s);if(o.data.set(e),a.putImageData(o,0,0),i){let e=document.createElement("canvas");e.width=r,e.height=s;let t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}async function n5(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=await e.readPixels(t,i);return s?n4(s,e.getSize(),r.invertY):null}n3.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,iZ([iW()],n3.prototype,"uniqueId",void 0),iZ([iW()],n3.prototype,"name",void 0),iZ([iW()],n3.prototype,"metadata",void 0),iZ([iW("hasAlpha")],n3.prototype,"_hasAlpha",void 0),iZ([iW("getAlphaFromRGB")],n3.prototype,"_getAlphaFromRGB",void 0),iZ([iW()],n3.prototype,"level",void 0),iZ([iW("coordinatesIndex")],n3.prototype,"_coordinatesIndex",void 0),iZ([iW()],n3.prototype,"optimizeUVAllocation",void 0),iZ([iW("coordinatesMode")],n3.prototype,"_coordinatesMode",void 0),iZ([iW()],n3.prototype,"wrapU",null),iZ([iW()],n3.prototype,"wrapV",null),iZ([iW()],n3.prototype,"wrapR",void 0),iZ([iW()],n3.prototype,"anisotropicFilteringLevel",void 0),iZ([iW()],n3.prototype,"isCube",null),iZ([iW()],n3.prototype,"is3D",null),iZ([iW()],n3.prototype,"is2DArray",null),iZ([iW()],n3.prototype,"gammaSpace",null),iZ([iW()],n3.prototype,"invertZ",void 0),iZ([iW()],n3.prototype,"lodLevelInAlpha",void 0),iZ([iW()],n3.prototype,"lodGenerationOffset",null),iZ([iW()],n3.prototype,"lodGenerationScale",null),iZ([iW()],n3.prototype,"linearSpecularLOD",null),iZ([iH()],n3.prototype,"irradianceTexture",null),iZ([iW()],n3.prototype,"isRenderTarget",void 0);class n6 extends n3{static _CreateVideoTexture(e,t,i,r=!1,s=!1,n=n6.TRILINEAR_SAMPLINGMODE,a={},o,l=5){throw iL("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,i,r,s=n6.TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,l=!1,h,u,c,d,p){var _,f,m,g,v,x,T,b,E,S;let C;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._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 tj,this._isBlocking=!0,this.name=e||"",this.url=e;let y=!1,A=null,R=!0;"object"==typeof i&&null!==i?(C=null!==(_=i.noMipmap)&&void 0!==_&&_,r=null!==(f=i.invertY)&&void 0!==f?f:!nx.UseOpenGLOrientationForUV,s=null!==(m=i.samplingMode)&&void 0!==m?m:n6.TRILINEAR_SAMPLINGMODE,n=null!==(g=i.onLoad)&&void 0!==g?g:null,a=null!==(v=i.onError)&&void 0!==v?v:null,o=null!==(x=i.buffer)&&void 0!==x?x:null,l=null!==(T=i.deleteBuffer)&&void 0!==T&&T,h=i.format,u=i.mimeType,c=i.loaderOptions,d=i.creationFlags,y=null!==(b=i.useSRGBBuffer)&&void 0!==b&&b,A=null!==(E=i.internalTexture)&&void 0!==E?E:null,R=null!==(S=i.gammaSpace)&&void 0!==S?S:R):C=!!i,this._gammaSpace=R,this._noMipmap=C,this._invertY=void 0===r?!nx.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=o,this._deleteBuffer=l,this._mimeType=u,this._loaderOptions=c,this._creationFlags=d,this._useSRGBBuffer=y,this._forcedExtension=p,h&&(this._format=h);let I=this.getScene(),P=this._getEngine();if(!P)return;P.onBeforeTextureInitObservable.notifyObservers(this);let M=()=>{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&&I&&I.resetCachedMaterial()},D=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),n6.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!A){this._delayedOnLoad=M,this._delayedOnError=D;return}if(this._texture=null!=A?A:this._getFromCache(this.url,C,s,this._invertY,y,this.isCube),this._texture){if(this._texture.isReady)rq.SetImmediate(()=>M());else{let e=this._texture.onLoadedObservable.add(M);this._texture.onErrorObservable.add(t=>{var i;D(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)})}}else if(I&&I.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=M,this._delayedOnError=D;else{try{this._texture=P.createTexture(this.url,C,this._invertY,I,s,M,D,this._buffer,void 0,this._format,this._forcedExtension,u,c,d,y)}catch(e){throw D("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,e=>e.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;let e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?rq.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,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,t5.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}checkTransformsAreIdentical(e){return null!==e&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}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=t7.Zero(),this._rowGenerationMatrix=new t7,this._t0=t5.Zero(),this._t1=t5.Zero(),this._t2=t5.Zero()),t7.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(t7.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,ie.Matrix[0]),t7.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,ie.Matrix[1]),t7.ScalingToRef(this._cachedUScale,this._cachedVScale,0,ie.Matrix[2]),t7.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,ie.Matrix[3]),ie.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ie.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ie.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(ie.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),t7.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));let t=this.getScene();return t&&this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e||this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode&&(this.coordinatesMode!==n6.PROJECTION_MODE||this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag))return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=t7.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=t7.Zero());let 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 n6.PLANAR_MODE:t7.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 n6.PROJECTION_MODE:{t7.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:t7.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let 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 i$.Clone(()=>new n6(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;let i=this.name;!n6.SerializeBuffers&&this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let r=super.serialize(n6._SerializeInternalTextureUniqueId);return r?((n6.SerializeBuffers||n6.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(r.base64String=this._buffer,r.name=r.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?r.base64String="data:image/png;base64,"+rd(this._buffer):(n6.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(r.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=e._readPixelsSync(t,i);return s?n4(s,e.getSize(),r.invertY):null}(this):n5(this))),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r._creationFlags=this._creationFlags,r._useSRGBBuffer=this._useSRGBBuffer,n6._SerializeInternalTextureUniqueId&&(r.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),r.noMipmap=this._noMipmap,this.name=i,r):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){let r;if(e.customType){let r=si.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&r.updateSamplingMode&&r._samplingMode&&r._samplingMode!==e.samplingMode&&r.updateSamplingMode(e.samplingMode),r}if(e.isCube&&!e.isRenderTarget)return n6._CubeTextureParser(e,t,i);let s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;if(s){for(let i of t.getEngine().getLoadedTexturesCache())if(i.uniqueId===e.internalTextureUniqueId){r=i;break}}let n=t=>{var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){let i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{var s,a,o;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){let i=n6._CreateMirror(e.name,e.renderTargetSize,t,l);return i._waitingRenderList=e.renderList,i.mirrorPlane=sG.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(s)},null!==(a=e._creationFlags)&&void 0!==a?a:0,null!==(o=e._useSRGBBuffer)&&void 0!==o&&o)).name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||n6.UseSerializedUrlIfAny)&&(a=e.url),s=new n6(a,t,{noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(s)},internalTexture:r})}return s}},e,t)}static CreateFromBase64String(e,t,i,r,s,n=n6.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=5,h){return new n6("data:"+t,i,r,s,n,a,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,r=!1,s,n=!0,a=n6.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new n6(e,i,s,n,a,o,l,t,r,h,void 0,void 0,u)}}function n8(e,t,i,r){let s;let n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r{throw iL("CubeTexture")},n6._CreateMirror=(e,t,i,r)=>{throw iL("MirrorTexture")},n6._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw iL("RenderTargetTexture")},n6.NEAREST_SAMPLINGMODE=1,n6.NEAREST_NEAREST_MIPLINEAR=8,n6.BILINEAR_SAMPLINGMODE=2,n6.LINEAR_LINEAR_MIPNEAREST=11,n6.TRILINEAR_SAMPLINGMODE=3,n6.LINEAR_LINEAR_MIPLINEAR=3,n6.NEAREST_NEAREST_MIPNEAREST=4,n6.NEAREST_LINEAR_MIPNEAREST=5,n6.NEAREST_LINEAR_MIPLINEAR=6,n6.NEAREST_LINEAR=7,n6.NEAREST_NEAREST=1,n6.LINEAR_NEAREST_MIPNEAREST=9,n6.LINEAR_NEAREST_MIPLINEAR=10,n6.LINEAR_LINEAR=2,n6.LINEAR_NEAREST=12,n6.EXPLICIT_MODE=0,n6.SPHERICAL_MODE=1,n6.PLANAR_MODE=2,n6.CUBIC_MODE=3,n6.PROJECTION_MODE=4,n6.SKYBOX_MODE=5,n6.INVCUBIC_MODE=6,n6.EQUIRECTANGULAR_MODE=7,n6.FIXED_EQUIRECTANGULAR_MODE=8,n6.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,n6.CLAMP_ADDRESSMODE=0,n6.WRAP_ADDRESSMODE=1,n6.MIRROR_ADDRESSMODE=2,n6.UseSerializedUrlIfAny=!1,iZ([iW()],n6.prototype,"url",void 0),iZ([iW()],n6.prototype,"uOffset",void 0),iZ([iW()],n6.prototype,"vOffset",void 0),iZ([iW()],n6.prototype,"uScale",void 0),iZ([iW()],n6.prototype,"vScale",void 0),iZ([iW()],n6.prototype,"uAng",void 0),iZ([iW()],n6.prototype,"vAng",void 0),iZ([iW()],n6.prototype,"wAng",void 0),iZ([iW()],n6.prototype,"uRotationCenter",void 0),iZ([iW()],n6.prototype,"vRotationCenter",void 0),iZ([iW()],n6.prototype,"wRotationCenter",void 0),iZ([iW()],n6.prototype,"homogeneousRotationInUVTransform",void 0),iZ([iW()],n6.prototype,"isBlocking",null),t0["BABYLON.Texture"]=n6,i$._TextureParser=n6.Parse,r$.prototype.updateRawTexture=function(e,t,i,r,s=null,n=0,a=!1){if(!e)return;let o=this._getRGBABufferInternalSizedFormat(n,i,a),l=this._getInternalFormat(i),h=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=n,e.invertY=r,e._compression=s),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},r$.prototype.createRawTexture=function(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new rU(this,m.Raw);c.baseWidth=t,c.baseHeight=i,c.width=t,c.height=i,c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c._compression=o,c.type=l,c._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this._doNotHandleContextLost||(c._bufferView=e),this.updateRawTexture(c,e,r,n,o,l,c._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,c,!0);let d=this._getSamplingParameters(a,s);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),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(c),c},r$.prototype.createRawCubeTexture=function(e,t,i,r,s,n,a,o=null){let l=this._gl,h=new rU(this,m.CubeRaw);h.isCube=!0,h.format=i,h.type=r,this._doNotHandleContextLost||(h._bufferViewArray=e);let u=this._getWebGLTextureType(r),c=this._getInternalFormat(i);if(c===l.RGB&&(c=l.RGBA),u!==l.FLOAT||this._caps.textureFloatLinearFiltering?u!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?u!==l.FLOAT||this._caps.textureFloatRender?u!==l.HALF_FLOAT||this._caps.colorBufferFloat||(s=!1,ig.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,ig.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,a=1,ig.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,a=1,ig.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),h.width=t,h.height=t,h.invertY=n,h._compression=o,!this.needPOTTextures||ss.IsExponentOfTwo(h.width)&&ss.IsExponentOfTwo(h.height)||(s=!1),e)this.updateRawCubeTexture(h,e,i,r,n,o);else{let e=this._getRGBABufferInternalSizedFormat(r);this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let t=0;t<6;t++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this.getCaps().s3tc[o],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,e,h.width,h.height,0,c,u,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);let d=this._getSamplingParameters(a,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,d.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,d.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=s,h.samplingMode=a,h.isReady=!0,h},r$.prototype.updateRawCubeTexture=function(e,t,i,r,s,n=null,a=0){e._bufferViewArray=t,e.format=i,e.type=r,e.invertY=s,e._compression=n;let o=this._gl,l=this._getWebGLTextureType(r),h=this._getInternalFormat(i),u=this._getRGBABufferInternalSizedFormat(r),c=!1;h===o.RGB&&(h=o.RGBA,c=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===s||!!s),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let s=t[i];n?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,this.getCaps().s3tc[n],e.width,e.height,0,s):(c&&(s=n8(s,e.width,e.height,r)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,a,u,e.width,e.height,0,h,l,s))}(!this.needPOTTextures||ss.IsExponentOfTwo(e.width)&&ss.IsExponentOfTwo(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},r$.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,s,n,a,o,l=null,h=null,u=3,c=!1){let d=this._gl,p=this.createRawCubeTexture(null,i,r,s,!n,c,u,null);null==t||t.addPendingData(p),p.url=e,p.isReady=!1,this._internalTexturesCache.push(p);let _=e=>{let i=p.width,n=a(e);if(n){if(o){let e=this._getWebGLTextureType(s),t=this._getInternalFormat(r),a=this._getRGBABufferInternalSizedFormat(s),l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);let h=o(n);for(let r=0;r>r;for(let i=0;i<6;i++){let o=h[r][i];l&&(o=n8(o,n,n,s)),d.texImage2D(i,r,a,n,n,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,n,r,s,c);p.isReady=!0,null==t||t.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,e=>{_(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(p),h&&e&&h(e.status+" "+e.statusText,i)}),p},r$.prototype.createRawTexture2DArray=n7(!1),r$.prototype.createRawTexture3D=n7(!0),r$.prototype.updateRawTexture2DArray=n9(!1),r$.prototype.updateRawTexture3D=n9(!0);class ae extends n6{constructor(e,t,i,r,s,n=!0,a=!1,o=3,l=0,h,u){if(super(null,s,!n,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,!this._engine)return;this._engine._caps.textureFloatLinearFiltering||1!==l||(o=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(o=1),this._texture=this._engine.createRawTexture(e,t,i,r,n,a,o,null,l,null!=h?h:0,null!=u&&u),this.wrapU=n6.CLAMP_ADDRESSMODE,this.wrapV=n6.CLAMP_ADDRESSMODE}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,r,s=!0,n=!1,a=3){return new ae(e,t,i,1,r,s,n,a)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new ae(e,t,i,2,r,s,n,a)}static CreateAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new ae(e,t,i,0,r,s,n,a)}static CreateRGBTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new ae(e,t,i,4,r,s,n,a,o,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new ae(e,t,i,5,r,s,n,a,o,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=!1){return new ae(e,t,i,5,r,s,n,a,o,1,l)}static CreateRTexture(e,t,i,r,s=!0,n=!1,a=n6.TRILINEAR_SAMPLINGMODE,o=1){return new ae(e,t,i,6,r,s,n,a,o)}static CreateRStorageTexture(e,t,i,r,s=!0,n=!1,a=n6.TRILINEAR_SAMPLINGMODE,o=1){return new ae(e,t,i,6,r,s,n,a,o,1)}}class at{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;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===sS.POINTERDOWN){this._isPointerDown=!0;return}e.type===sS.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let e=ra.Now,t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();let i=Math.max(Math.min((e-this._lastInteractionTime-this._idleRotationWaitTime)/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*i,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=null!=e?e:ra.Now}_reachTargetAlpha(){return!!this._attachedCamera&&!!this.targetAlpha&&.001>Math.abs(this._attachedCamera.alpha-this.targetAlpha)}_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=ra.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)}}class ai{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=[]}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;let t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(e=>{if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){let 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||(ai.EasingFunction.setEasingMode(ai.EasingMode),this._radiusBounceTransition=re.CreateAnimation("radius",re.ANIMATIONTYPE_FLOAT,60,ai.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=re.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()}}ai.EasingFunction=new s3(.3),ai.EasingMode=s1.EASINGMODE_EASEOUT;class ar{constructor(){this.onTargetFramingAnimationEndObservable=new tj,this._mode=ar.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=[],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;let t=this._attachedCamera.getScene();ar.EasingFunction.setEasingMode(ar.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===sS.POINTERDOWN){this._isPointerDown=!0;return}e.type===sS.POINTERUP&&(this._isPointerDown=!1)}),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;let 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,i=null){e.computeWorldMatrix(!0);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new t5(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new t5(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}))&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===ar.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=ra.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>.5*Math.PI&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=re.CreateAnimation("beta",re.ANIMATIONTYPE_FLOAT,60,ar.EasingFunction));let e=re.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=ra.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)}}ar.EasingFunction=new s4,ar.EasingMode=s1.EASINGMODE_EASEINOUT,ar.IgnoreBoundsSizeMode=0,ar.FitFrustumSidesMode=1;class as{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new as(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r,s,n,a;let o=as._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),l=as._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),h=0,u=Number.MAX_VALUE;if(1e-7>Math.abs(this.direction.x)){if(this.origin.xl.x)return!1}else if(r=1/this.direction.x,s=(o.x-this.origin.x)*r,(n=(l.x-this.origin.x)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.y)){if(this.origin.yl.y)return!1}else if(r=1/this.direction.y,s=(o.y-this.origin.y)*r,(n=(l.y-this.origin.y)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.z)){if(this.origin.zl.z)return!1}else if(r=1/this.direction.z,s=(o.z-this.origin.z)*r,(n=(l.z-this.origin.z)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,n=i*i+r*r+s*s,a=e.radius+t,o=a*a;if(n<=o)return!0;let l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&n-l*l<=o}intersectsTriangle(e,t,i){let r=as._TmpVector3[0],s=as._TmpVector3[1],n=as._TmpVector3[2],a=as._TmpVector3[3],o=as._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),t5.CrossToRef(this.direction,s,n);let l=t5.Dot(r,n);if(0===l)return null;let h=1/l;this.origin.subtractToRef(e,a);let u=t5.Dot(a,n)*h;if(u<0||u>1)return null;t5.CrossToRef(a,r,o);let c=t5.Dot(this.direction,o)*h;if(c<0||u+c>1)return null;let d=t5.Dot(s,o)*h;return d>this.length?null:new nn(1-u-c,u,d)}intersectsPlane(e){let t;let i=t5.Dot(e.normal,this.direction);if(999999997475243e-21>Math.abs(i))return null;{let r=t5.Dot(e.normal,this.origin);return(t=(-e.d-r)/i)<0?t<-.000000999999997475243?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let e=(this.origin.y-t)/this.direction.y;if(e>0)return null;return new t5(this.origin.x+-(this.direction.x*e),t,this.origin.z+-(this.direction.z*e))}case"x":{let e=(this.origin.x-t)/this.direction.x;if(e>0)return null;return new t5(t,this.origin.y+-(this.direction.y*e),this.origin.z+-(this.direction.z*e))}case"z":{let e=(this.origin.z-t)/this.direction.z;if(e>0)return null;return new t5(this.origin.x+-(this.direction.x*e),this.origin.y+-(this.direction.y*e),t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,n=!1){let a=ie.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?as.TransformToRef(this,a,this._tmpRay):this._tmpRay=as.Transform(this,a),e.intersects(this._tmpRay,t,i,r,s,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=ie.Vector3[0],n=ie.Vector3[1],a=ie.Vector3[2],o=ie.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(as._Rayl,a),r.addToRef(a,n),e.subtractToRef(r,o);let l=t5.Dot(s,s),h=t5.Dot(s,a),u=t5.Dot(a,a),c=t5.Dot(s,o),d=t5.Dot(a,o),p=l*u-h*h,_,f=p,m,g=p;pf&&(_=f,m=d+h,g=u)),m<0?(m=0,0>-c?_=0:-c>l?_=f:(_=-c,f=l)):m>g&&(m=g,-c+h<0?_=0:-c+h>l?_=f:(_=-c+h,f=l));let v=Math.abs(_)0&&x<=this.length&&E.lengthSquared()=e.distance))?h:null},sY.prototype._internalPick=function(e,t,i,r,s){let n=null,a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=as.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay),i,r,!0);return n&&(n.ray=this.createPickingRay(e,t,t7.Identity(),s||null)),n},Object.defineProperty(sY.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),sY.prototype.pick=function(e,t,i,r,s,n,a=!1){let o=this._internalPick((i,r)=>(this._tempPickingRay||(this._tempPickingRay=as.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,r),this._tempPickingRay),i,r,!1,n);return o&&(o.ray=this.createPickingRay(e,t,t7.Identity(),s||null)),o},sY.prototype.pickWithRay=function(e,t,i,r){let s=this._internalPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=t7.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=as.Zero()),as.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s},sY.prototype.multiPick=function(e,t,i,r,s){return this._internalMultiPick(i=>this.createPickingRay(e,t,i,r||null),i,s)},sY.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=t7.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=as.Zero()),as.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i)},ns.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new as(t5.Zero(),t5.Zero(),e),e,t,i)},ns.prototype.getForwardRayToRef=function(e,t=100,i,r){i||(i=this.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(this.position);let s=ie.Vector3[2];s.set(0,0,this._scene.useRightHandedSystem?-1:1);let n=ie.Vector3[3];return t5.TransformNormalToRef(s,i,n),t5.NormalizeToRef(n,e.direction),e};class an{static _RemoveAndStorePivotPoint(e){e&&0===an._PivotCached&&(e.getPivotPointToRef(an._OldPivotPoint),an._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,an._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(t7.IdentityReadOnly),an._OldPivotPoint.subtractToRef(e.getPivotPoint(),an._PivotTranslation),an._PivotTmpVector.copyFromFloats(1,1,1),an._PivotTmpVector.subtractInPlace(e.scaling),an._PivotTmpVector.multiplyInPlace(an._PivotTranslation),e.position.addInPlace(an._PivotTmpVector))),an._PivotCached++}static _RestorePivotPoint(e){e&&!an._OldPivotPoint.equalsToFloats(0,0,0)&&1===an._PivotCached&&(e.setPivotPoint(an._OldPivotPoint),e._postMultiplyPivotMatrix=an._PivotPostMultiplyPivotMatrix,an._PivotTmpVector.copyFromFloats(1,1,1),an._PivotTmpVector.subtractInPlace(e.scaling),an._PivotTmpVector.multiplyInPlace(an._PivotTranslation),e.position.subtractInPlace(an._PivotTmpVector)),this._PivotCached--}}function aa(e){let t=[],i=[],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE,l=n/2,h=a/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,nx.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,nx.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,nx.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,nx.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),ng._ComputeSides(o,i,t,r,s,e.frontUVs,e.backUVs);let u=new ng;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function ao(e,t={},i=null){let r=new nX(e,i);return t.sideOrientation=nX._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,aa(t).applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}an._PivotCached=0,an._OldPivotPoint=new t5,an._PivotTranslation=new t5,an._PivotTmpVector=new t5,an._PivotPostMultiplyPivotMatrix=!1,ng.CreatePlane=aa,nX.CreatePlane=(e,t,i,r,s)=>ao(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);class al{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new tj,this.onDragStartObservable=new tj,this.onDragEndObservable=new tj,this.onEnabledObservable=new tj,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new t5(0,0,0),this._alternatePickedPoint=new t5(0,0,0),this._worldDragAxis=new t5(0,0,0),this._targetPosition=new t5(0,0,0),this._attachedToElement=!1,this._startDragRay=new as(new t5,new t5),this._lastPointerRay={},this._dragDelta=new t5,this._pointA=new t5(0,0,0),this._pointC=new t5(0,0,0),this._localAxis=new t5(0,0,0),this._lookAt=new t5(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,al._PlaneScene||(this._debugMode?al._PlaneScene=this._scene:(al._PlaneScene=new sY(this._scene.getEngine(),{virtual:!0}),al._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{al._PlaneScene.dispose(),al._PlaneScene=null}))),this._dragPlane=ao("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:nX.DOUBLESIDE},al._PlaneScene),this.lastDragPosition=new t5(0,0,0);let i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(e=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(e.type==sS.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==sS.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==e.event.pointerId&&(this._activeDragButton===e.event.button||-1===this._activeDragButton)&&this.releaseDrag();else if(e.type==sS.POINTERMOVE){let t=e.event.pointerId;if(this.currentDraggingPointerId===al._AnyMouseId&&t!==al._AnyMouseId){let i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new as(new t5,new t5)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let e=!1;an._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),an._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}})}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){let e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=al._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===al._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;an._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);let r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),an._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;let t=this._pickWithRayOnDragPlane(e);if(t){an._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?t5.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=t5.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),an._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(t5.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(!this._useAlternatePickedPointAboveMaxDragAngle)return null;{this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*t5.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);let t=t5.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}}let i=this._dragPlane.forward,r=this._dragPlane.position,s=e.direction.dot(i);if(.001>Math.abs(s))return null;r.subtractToRef(e.origin,ie.Vector3[0]);let n=ie.Vector3[0].dot(i)/s;return n<0?null:(e.direction.scaleToRef(n,ie.Vector3[0]),e.origin.add(ie.Vector3[0]))}_updateDragPlanePosition(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?t5.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),e.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(t5.Dot(this._localAxis,this._pointC))>.999?Math.abs(t5.Dot(t5.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(t5.Right()):this._lookAt.copyFrom(t5.UpReadOnly):(t5.CrossToRef(this._localAxis,this._pointC,this._lookAt),t5.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?t5.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}al._AnyMouseId=-2;class ah{}ah.ANCHOR_SYSTEM="xr-anchor-system",ah.BACKGROUND_REMOVER="xr-background-remover",ah.HIT_TEST="xr-hit-test",ah.MESH_DETECTION="xr-mesh-detection",ah.PHYSICS_CONTROLLERS="xr-physics-controller",ah.PLANE_DETECTION="xr-plane-detection",ah.POINTER_SELECTION="xr-controller-pointer-selection",ah.TELEPORTATION="xr-controller-teleportation",ah.FEATURE_POINTS="xr-feature-points",ah.HAND_TRACKING="xr-hand-tracking",ah.IMAGE_TRACKING="xr-image-tracking",ah.NEAR_INTERACTION="xr-near-interaction",ah.DOM_OVERLAY="xr-dom-overlay",ah.MOVEMENT="xr-controller-movement",ah.LIGHT_ESTIMATION="xr-light-estimation",ah.EYE_TRACKING="xr-eye-tracking",ah.WALKING_LOCOMOTION="xr-walking-locomotion",ah.LAYERS="xr-layers",ah.DEPTH_SENSING="xr-depth-sensing",ah.SPACE_WARP="xr-space-warp",ah.RAW_CAMERA_ACCESS="xr-raw-camera-access";class au{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){let s=this._AvailableFeatures[e][t];if(!s)throw Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){let t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){let t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){let t="string"==typeof e?e:e.Name,i=this._features[t];return!!i&&!!i.enabled&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,s=!0){let n="string"==typeof e?e:e.Name,a=0;if("string"==typeof t){if(!t)throw Error(`Error in provided version - ${n} (${t})`);if(-1===(a="stable"===t?au.GetStableVersionOfFeature(n):"latest"===t?au.GetLatestVersionOfFeature(n):+t)||isNaN(a))throw Error(`feature not found - ${n} (${t})`)}else a=t;let o=au._ConflictingFeatures[n];if(void 0!==o&&-1!==this.getEnabledFeatures().indexOf(o))throw Error(`Feature ${n} cannot be enabled while ${o} is enabled.`);let l=this._features[n],h=au.ConstructFeature(n,a,this._xrSessionManager,i);if(!h)throw Error(`feature not found - ${n}`);l&&this.disableFeature(n);let u=h();if(u.dependsOn&&!u.dependsOn.every(e=>!!this._features[e]))throw Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`);if(u.isCompatible())return this._features[n]={featureImplementation:u,enabled:!0,version:a,required:s},r?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(!s)return ss.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),u;throw Error("required feature not compatible")}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){for(let t of this.getEnabledFeatures()){let i=this._features[t],r=i.featureImplementation.xrNativeFeatureName;if(r&&(i.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),i.featureImplementation.getXRSessionInitExtension){let t=await i.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),t)}}return e}}au._AvailableFeatures={},au._ConflictingFeatures={[ah.TELEPORTATION]:ah.MOVEMENT,[ah.MOVEMENT]:ah.TELEPORTATION};class ac{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName="",this.onFeatureAttachObservable=new tj,this.onFeatureDetachObservable=new tj}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,e=>this._onXRFrame(e)),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(e=>{e.observable.remove(e.observer)}),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}class ad{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}ad.DistanceJoint=0,ad.HingeJoint=1,ad.BallAndSocketJoint=2,ad.WheelJoint=3,ad.SliderJoint=4,ad.PrismaticJoint=5,ad.UniversalJoint=6,ad.Hinge2Joint=ad.WheelJoint,ad.PointToPointJoint=8,ad.SpringJoint=9,ad.LockJoint=10,nX._PhysicsImpostorParser=function(e,t,i){return new ap(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class ap{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=[],this._onAfterPhysicsStepCallbacks=[],this._onPhysicsCollideCallbacks=[],this._deltaPosition=t5.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new t8,this._tmpQuat2=new t8,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new t8),!this._options.disableBidirectionalTransformation&&this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(e=>{e(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(e=>{e(this)}),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,ap._TmpVecs[0]),this.object.translate(ap._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;let t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter(e=>-1!==e.otherImpostors.indexOf(t)).forEach(i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)}))},!this.object){ig.Error("No object was provided. A physics object is obligatory");return}if(this.object.parent&&0!==i.mass&&ig.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),!this._scene)return;this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=t8.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new t8),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&ig.Warn("You must affect impostors to children before affecting impostor to parent.")):ig.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof nM?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(!this.object.getBoundingInfo)return ap.DEFAULT_OBJECT_SIZE;{let e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=ap.IDENTITY_QUATERNION;let i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);let r=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return r.x=Math.abs(r.x),r.y=Math.abs(r.y),r.z=Math.abs(r.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),r}}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):t5.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):t5.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){let t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):ig.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){let t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):ig.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:e instanceof Array?e:[e]})}unregisterOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e],r=-1;this._onPhysicsCollideCallbacks.some((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){let t=e.otherImpostors.every(e=>i.indexOf(e)>-1);return t&&(r=s),t}return!1})?this._onPhysicsCollideCallbacks.splice(r,1):ig.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):t8.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){let r=new ad(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;let n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor&&this._physicsEngine&&n.appendAnchor(this,e,t,i,r,s),this}addHook(e,t,i,r){if(!this._physicsEngine)return this;let s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor&&this._physicsEngine&&s.appendHook(this,e,t,i,r),this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new ap(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach(e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new t8),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,s){let n=ap._TmpVecs[0],a=this.object;if(a.rotationQuaternion){if(s){let i=ap._TmpQuat;a.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,A.WORLD,t)}else e.setRotationQuaternion(a.rotationQuaternion,A.WORLD,t)}n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==r&&(r=i.length()),n.x*=r,n.y*=r,n.z*=r),e.getParent()?(n.addInPlace(a.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(a.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,r,s,n){let a=this.object;if(a.rotationQuaternion){if(s){let i=ap._TmpQuat;e.getRotationQuaternionToRef(A.WORLD,t,i),i.multiplyToRef(s,a.rotationQuaternion)}else e.getRotationQuaternionToRef(A.WORLD,t,a.rotationQuaternion)}let o=ap._TmpVecs[0],l=ap._TmpVecs[1];n||((n=ap._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,o),null==r&&i&&(r=i.length()),null!=r&&(o.x+=l.x*r,o.y+=l.y*r,o.z+=l.z*r),a.setAbsolutePosition(o)}}ap.DEFAULT_OBJECT_SIZE=new t5(1,1,1),ap.IDENTITY_QUATERNION=t8.Identity(),ap._TmpVecs=tQ.BuildArray(3,t5.Zero),ap._TmpQuat=t8.Identity(),ap.NoImpostor=0,ap.SphereImpostor=1,ap.BoxImpostor=2,ap.PlaneImpostor=3,ap.MeshImpostor=4,ap.CapsuleImpostor=6,ap.CylinderImpostor=7,ap.ParticleImpostor=8,ap.HeightmapImpostor=9,ap.ConvexHullImpostor=10,ap.CustomImpostor=100,ap.RopeImpostor=101,ap.ClothImpostor=102,ap.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(D||(D={}));class a_{static get ForceFullSceneLoadingForIncremental(){return nv.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){nv.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return nv.ShowLoadingScreen}static set ShowLoadingScreen(e){nv.ShowLoadingScreen=e}static get loggingLevel(){return nv.loggingLevel}static set loggingLevel(e){nv.loggingLevel=e}static get CleanBoneMatrixWeights(){return nv.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){nv.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return a_._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return a_._RegisteredPlugins[e]||(ig.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"),a_.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(let t in a_._RegisteredPlugins){let i=a_._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return a_._RegisteredPlugins[t]}return a_.GetDefaultPlugin()}static _GetPluginForFilename(e){let t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));let i=e.lastIndexOf("."),r=e.substring(i,e.length).toLowerCase();return a_._GetPluginForExtension(r)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r="Unable to load from "+(e.rawData?"binary data":e.url);return t?r+=`: ${t}`:i&&(r+=`: ${i}`),r}static _LoadData(e,t,i,r,s,n,a,o){let l;let h=a_._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";let u=a?a_._GetPluginForExtension(a):h?a_._GetPluginForDirectLoad(e.url):a_._GetPluginForFilename(e.url);if(e.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";if(!(l=void 0!==u.plugin.createPlugin?u.plugin.createPlugin():u.plugin))throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(a_.OnPluginActivatedObservable.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!r7(e.url))){if(l.directLoad){let e=l.directLoad(t,h);e.then?e.then(e=>{i(l,e)}).catch(e=>{s("Error in directLoad of _loadData: "+e,e)}):i(l,e)}else i(l,h);return l}let c=u.isBinary,d=(e,r)=>{if(t.isDisposed){s("Scene has been disposed");return}i(l,e,r)},p=null,_=!1,f=l.onDisposeObservable;f&&f.add(()=>{_=!0,p&&(p.abort(),p=null),n()});let m=()=>{if(_)return;let i=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,r,c,i,o):t._loadFile(e.file||e.url,d,r,!0,c,i)},g=t.getEngine(),v=g.enableOfflineSupport;if(v){let i=!1;for(let r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}v=!i}return v&&nC.OfflineProviderFactory?t.offlineProvider=nC.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),l}static _GetFileInfo(e,t){let i,r;let s=null,n=null;if(t){if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r="arrayBuffer",n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,r="";else{if("/"===t.substr(0,1))return ss.Error("Wrong sceneFilename parameter"),null;i=e+t,r=t}}else i=e,r=ss.GetFilename(e),e=ss.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:n}}static GetPluginForExtension(e){return a_._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!a_._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){let t=e.extensions;a_._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{let t=e.extensions;Object.keys(t).forEach(i=>{a_._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",r=t2.LastCreatedScene,s=null,n=null,a=null,o=null,l=""){if(!r)return ig.Error("No scene available to import mesh to"),null;let h=a_._GetFileInfo(t,i);if(!h)return null;let u={};r.addPendingData(u);let c=()=>{r.removePendingData(u)},d=(e,t)=>{let i=a_._FormatErrorMessage(h,e,t);a?a(r,i,new rc(i,ru.SceneLoaderError,t)):ig.Error(i),c()},p=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,_=(e,t,i,n,a,o,l)=>{if(r.importedMeshesFiles.push(h.url),s)try{s(e,t,i,n,a,o,l)}catch(e){d("Error in onSuccess callback: "+e,e)}r.removePendingData(u)};return a_._LoadData(h,r,(t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){let s=[],n=[],a=[];t.importMesh(e,r,i,h.rootUrl,s,n,a,d)&&(r.loadingPluginName=t.name,_(s,n,a,[],[],[],[]))}else t.importMeshAsync(e,r,i,h.rootUrl,p,h.name).then(e=>{r.loadingPluginName=t.name,_(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)}).catch(e=>{d(e.message,e)})},p,d,c,o,l)}static ImportMeshAsync(e,t,i="",r=t2.LastCreatedScene,s=null,n=null,a=""){return new Promise((o,l)=>{a_.ImportMesh(e,t,i,r,(e,t,i,r,s,n,a)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:n,lights:a})},s,(e,t,i)=>{l(i||Error(t))},n,a)})}static Load(e,t="",i=t2.LastCreatedEngine,r=null,s=null,n=null,a=null,o=""){return i?a_.Append(e,t,new sY(i),r,s,n,a,o):(ss.Error("No engine available"),null)}static LoadAsync(e,t="",i=t2.LastCreatedEngine,r=null,s=null,n=""){return new Promise((a,o)=>{a_.Load(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static Append(e,t="",i=t2.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return ig.Error("No scene available to append to"),null;let l=a_._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let u=()=>{i.removePendingData(h)};a_.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));let c=(e,t)=>{let r=a_._FormatErrorMessage(l,e,t);n?n(i,r,new rc(r,ru.SceneLoaderError,t)):ig.Error(r),u()},d=s?e=>{try{s(e)}catch(e){c("Error in onProgress callback",e)}}:void 0,p=()=>{if(r)try{r(i)}catch(e){c("Error in onSuccess callback",e)}i.removePendingData(h)};return a_._LoadData(l,i,(e,t)=>{e.load?!e.load(i,t,l.rootUrl,c)||(i.loadingPluginName=e.name,p()):e.loadAsync(i,t,l.rootUrl,d,l.name).then(()=>{i.loadingPluginName=e.name,p()}).catch(e=>{c(e.message,e)})},d,c,u,a,o)}static AppendAsync(e,t="",i=t2.LastCreatedScene,r=null,s=null,n=""){return new Promise((a,o)=>{a_.Append(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static LoadAssetContainer(e,t="",i=t2.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return ig.Error("No scene available to load asset container to"),null;let l=a_._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let u=()=>{i.removePendingData(h)},c=(e,t)=>{let r=a_._FormatErrorMessage(l,e,t);n?n(i,r,new rc(r,ru.SceneLoaderError,t)):ig.Error(r),u()},d=s?e=>{try{s(e)}catch(e){c("Error in onProgress callback",e)}}:void 0,p=e=>{if(r)try{r(e)}catch(e){c("Error in onSuccess callback",e)}i.removePendingData(h)};return a_._LoadData(l,i,(e,t)=>{if(e.loadAssetContainer){let r=e.loadAssetContainer(i,t,l.rootUrl,c);r&&(r.populateRootNodes(),i.loadingPluginName=e.name,p(r))}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then(t=>{t.populateRootNodes(),i.loadingPluginName=e.name,p(t)}).catch(e=>{c(e.message,e)}):c("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},d,c,u,a,o)}static LoadAssetContainerAsync(e,t="",i=t2.LastCreatedScene,r=null,s=null){return new Promise((n,a)=>{a_.LoadAssetContainer(e,t,i,e=>{n(e)},r,(e,t,i)=>{a(i||Error(t))},s)})}static ImportAnimations(e,t="",i=t2.LastCreatedScene,r=!0,s=D.Clean,n=null,a=null,o=null,l=null,h=null){if(!i){ig.Error("No scene available to load animations to");return}if(r){for(let e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(e=>{e.dispose()}),i.getNodes().forEach(e=>{e.animations&&(e.animations=[])})}else switch(s){case D.Clean:i.animationGroups.slice().forEach(e=>{e.dispose()});break;case D.Stop:i.animationGroups.forEach(e=>{e.stop()});break;case D.Sync:i.animationGroups.forEach(e=>{e.reset(),e.restart()});break;case D.NoSync:break;default:ig.Error("Unknown animation group loading mode value '"+s+"'");return}let u=i.animatables.length;this.LoadAssetContainer(e,t,i,e=>{e.mergeAnimationsTo(i,i.animatables.slice(u),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)},o,l,h)}static ImportAnimationsAsync(e,t="",i=t2.LastCreatedScene,r=!0,s=D.Clean,n=null,a=null,o=null,l=null,h=null){return new Promise((a,l)=>{a_.ImportAnimations(e,t,i,r,s,n,e=>{a(e)},o,(e,t,i)=>{l(i||Error(t))},h)})}}a_.NO_LOGGING=0,a_.MINIMAL_LOGGING=1,a_.SUMMARY_LOGGING=2,a_.DETAILED_LOGGING=3,a_.OnPluginActivatedObservable=new tj,a_._RegisteredPlugins={},a_._ShowingLoadingScreen=!1;class af extends nB{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new t7,this._storeEffectOnSubMeshes=i}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){let 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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}(function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"})(O||(O={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(N||(N={}));class am{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){let t=e.sharedData.emitComments,i=this.target===N.Fragment;this.compilationString=` +${t?"//Entry point\n":""}void main(void) { +${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` +${t?"//Constants\n":""}${this._constantDeclaration} +${this.compilationString}`);let r="";for(let e in this.functions)r+=this.functions[e]+` +`;for(let e in this.compilationString=` +${r} +${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} +${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} +${this._injectAtEnd}`),this.compilationString=`${this.compilationString} +}`,this.sharedData.varyingDeclaration&&(this.compilationString=` +${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration} +${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` +${t?"//Samplers\n":""}${this._samplerDeclaration} +${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` +${t?"//Uniforms\n":""}${this._uniformDeclaration} +${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` +${t?"//Attributes\n":""}${this._attributeDeclaration} +${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString),this.extensions){let t=this.extensions[e];this.compilationString=` +${t} +${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return(e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e])?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e)?e+this.sharedData.variableNames[e]:e:(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2D ${e}; +`,this.samplers.push(e))}_emit2DArraySampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; +`,this.samplers.push(e))}_getGLType(e){switch(e){case O.Float:return"float";case O.Int:return"int";case O.Vector2:return"vec2";case O.Color3:case O.Vector3:return"vec3";case O.Color4:case O.Vector4:return"vec4";case O.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} +${t} +#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` +`+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`;let r=rN.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(r=t+` +`+r),!i)return r;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""} +`,this.sharedData.emitComments&&(this.functions[s]=t+` +`+this.functions[s]);return}if(this.functions[s]=rN.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+` +`+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;ee.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===N.Vertex||(e.ownerBlock.target===N.Neutral||e.ownerBlock.target===N.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===N.Vertex)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===N.Vertex||e.target===N.Vertex||(e.ownerBlock.target===N.Neutral||e.ownerBlock.target===N.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===N.Fragment)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===N.Fragment||(e.ownerBlock.target===N.Neutral||e.ownerBlock.target===N.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=[],this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=O.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new tj,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=N.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===F.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(t.target===N.Fragment){if(i.target===N.Vertex)return F.TargetIncompatible;for(let e of i.outputs)if(e.ownerBlock.target!=N.Neutral&&e.isConnectedInVertexShader)return F.TargetIncompatible}if(this.type!==e.type&&e.innerType!==O.AutoDetect)return av.AreEquivalentTypes(this.type,e.type)?F.Compatible:e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&av.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?F.Compatible:F.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return F.TypeIncompatible;let r=i,s=t;return(this.direction===w.Input&&(r=t,s=i),r.isAnAncestorOf(s))?F.HierarchyIssue:F.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}class ax{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){(this._target&e)==0&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}constructor(e,t=N.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=[],this._outputs=[],this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===N.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=sW.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===N.Neutral}initialize(e){}bind(e,t,i,r){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return -1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,s){return(s=null!=s?s:new av(e,this,w.Input)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=null!=r?r:new av(e,this,w.Output)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(let t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===O.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(let t of this._outputs)if(!e||!e.target||e.target===N.Neutral||(e.target&t.target)!=0)return t;return null}getSiblingOutput(e){let t=this._outputs.indexOf(e);return -1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){let s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput))&&this.target!==N.Vertex&&!!((this.target===N.VertexAndFragment||this.target===N.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);let s=null!=t._vertexState,n=e._buildTarget===N.Vertex&&e.target!==N.VertexAndFragment;if(s&&((e.target&e._buildTarget)==0||(e.target&i.target)==0||this.target!==N.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){let e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName}; +`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){for(let t of["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"])if(e===t)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(let t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(let i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==N.Neutral&&((i.target&this.target)==0||(i.target&e.target)==0))continue;let r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&ig.Log(`${e.target===N.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case N.Vertex:e.sharedData.checks.emitVertex=!0;break;case N.Fragment:e.sharedData.checks.emitFragment=!0}for(let i of(!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` +//${this.name} +`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target,this._outputs))if((i.target&e.target)!=0)for(let r of i.endpoints){let i=r.ownerBlock;i&&(i.target&e.target)!=0&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; +${e}.visibleOnFrame = ${this.visibleOnFrame}; +${e}.target = ${this.target}; +`}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` +// ${this.getClassName()} +`;for(let i of(this.comments&&(r+=`// ${this.comments} +`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}clone(e,t=""){let i=this.serialize(),r=t0[i.customType];if(r){let s=new r;return s._deserialize(i,e,t),s}return null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var r;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(r=e.target)&&void 0!==r?r:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose()}}class aT extends ax{constructor(e){super(e,N.Neutral),this.complementW=1,this.complementZ=0,this.target=N.Vertex,this.registerInput("vector",O.AutoDetect),this.registerInput("transform",O.Matrix),this.registerOutput("output",O.Vector4),this.registerOutput("xyz",O.Vector3),this._inputs[0].onConnectionObservable.add(e=>{if(e.ownerBlock.isInput){let t=e.ownerBlock;("normal"===t.name||"tangent"===t.name)&&(this.complementW=0)}})}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){let r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),e.sharedData.blocksWithDefines.push(this);let s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName}); +`,e.compilationString+=`#ifdef NONUNIFORMSCALING +`,e.compilationString+=`${s} = transposeMat3(inverseMat3(${s})); +`,e.compilationString+=`#endif +`,t.connectedPoint.type){case O.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); +`;break;case O.Vector3:case O.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); +`}}else{let r=i.associatedVariableName;switch(t.connectedPoint.type){case O.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); +`;break;case O.Vector3:case O.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * ${t.associatedVariableName}; +`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; +`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){let e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; +`+`${this._codeVariableName}.complementW = ${this.complementW}; +`}}t0["BABYLON.TransformBlock"]=aT;class ab extends ax{constructor(e){super(e,N.Vertex,!0),this.registerInput("vector",O.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(let t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);let t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName}; +`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; +`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; +`),this}}function aE(e,t=L.Boolean,i="PROPERTIES",r){return(s,n)=>{let a=s._propStore;a||(a=[],s._propStore=a),a.push({propertyName:n,displayName:e,type:t,groupName:i,options:null!=r?r:{}})}}t0["BABYLON.VertexOutputBlock"]=ab,function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(L||(L={}));class aS extends ax{constructor(e){super(e,N.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",O.Color4,!0),this.registerInput("rgb",O.AutoDetect,!0),this.registerInput("a",O.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&nw.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);let t=this.rgba,i=this.rgb,r=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||r.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");let s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)r.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); +`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; +`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===O.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t}); +`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t}); +`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor); +`,e.compilationString+=`#endif +`,(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; +`),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`gl_FragData[0] = gl_FragColor;\r +`,e.compilationString+=`#endif\r +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; +`}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(r=e.useLogarithmicDepth)&&void 0!==r&&r}}iZ([aE("Convert to gamma space",L.Boolean,"PROPERTIES",{notifiers:{update:!0}})],aS.prototype,"convertToGammaSpace",void 0),iZ([aE("Convert to linear space",L.Boolean,"PROPERTIES",{notifiers:{update:!0}})],aS.prototype,"convertToLinearSpace",void 0),iZ([aE("Use logarithmic depth",L.Boolean,"PROPERTIES")],aS.prototype,"useLogarithmicDepth",void 0),t0["BABYLON.FragmentOutputBlock"]=aS,function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(B||(B={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(U||(U={})),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(V||(V={}));let aC={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},ay={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},aA={particle_texturemask:!0};class aR extends ax{get type(){if(this._type===O.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=O.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=O.Vector2,this._type;case"Vector3":return this._type=O.Vector3,this._type;case"Vector4":return this._type=O.Vector4,this._type;case"Color3":return this._type=O.Color3,this._type;case"Color4":return this._type=O.Color4,this._type;case"Matrix":return this._type=O.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=O.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=O.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=O.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=O.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case U.World:case U.WorldView:case U.WorldViewProjection:case U.View:case U.ViewProjection:case U.Projection:this._type=O.Matrix;break;case U.CameraPosition:this._type=O.Vector3;break;case U.FogColor:this._type=O.Color3;break;case U.DeltaTime:case U.MaterialAlpha:this._type=O.Float;break;case U.CameraParameters:this._type=O.Vector4}}return this._type}constructor(e,t=N.Vertex,i=O.AutoDetect){super(e,t,!1),this._mode=B.Undefined,this._animationType=V.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new tj,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=B.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===O.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=B.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=B.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===B.Undefined}get isUniform(){return this._mode===B.Uniform}set isUniform(e){this._mode=e?B.Uniform:B.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===B.Attribute}set isAttribute(e){this._mode=e?B.Attribute:B.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===B.Varying}set isVarying(e){this._mode=e?B.Varying:B.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=B.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case V.Time:this.type===O.Float&&(this.value+=.01*e.getAnimationRatio());break;case V.RealTime:this.type===O.Float&&(this.value=(ra.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)} +`:`#ifdef ${e} +`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case O.Float:this.value=0;break;case O.Vector2:this.value=t4.Zero();break;case O.Vector3:this.value=t5.Zero();break;case O.Vector4:this.value=t6.Zero();break;case O.Color3:this.value=io.White();break;case O.Color4:this.value=new il(1,1,1,1);break;case O.Matrix:this.value=t7.Identity()}}_emitConstant(e){switch(this.type){case O.Float:return`${e._emitFloat(this.value)}`;case O.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case O.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case O.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case O.Color3:return ih.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&ih.Color3[0].toGammaSpaceToRef(ih.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&ih.Color3[0].toLinearSpaceToRef(ih.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${ih.Color3[0].r}, ${ih.Color3[0].g}, ${ih.Color3[0].b})`;case O.Color4:return ih.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&ih.Color4[0].toGammaSpaceToRef(ih.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&ih.Color4[0].toLinearSpaceToRef(ih.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${ih.Color4[0].r}, ${ih.Color4[0].g}, ${ih.Color4[0].b}, ${ih.Color4[0].a})`}return""}get _noContextSwitch(){return ay[this.name]}_emit(e,t){var i;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)}; +`;return}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName}; +`,t&&(e._uniformDeclaration+=`#endif +`);let i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case U.WorldView:i.needWorldViewMatrix=!0;break;case U.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==V.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=null!==(i=aC[this.name])&&void 0!==i?i:this.name,this.target===N.Vertex&&e._vertexState){ay[this.name]?aA[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t);return}if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),ay[this.name]?aA[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName}; +`,t&&(e._attributeDeclaration+=`#endif +`))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;let s=this.associatedVariableName;switch(this._systemValue){case U.World:e.setMatrix(s,t);break;case U.WorldView:e.setMatrix(s,i);break;case U.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;let r=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case U.World:case U.WorldView:case U.WorldViewProjection:break;case U.View:e.setMatrix(r,t.getViewMatrix());break;case U.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case U.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case U.CameraPosition:t.bindEyePosition(e,r,!0);break;case U.FogColor:e.setColor3(r,t.fogColor);break;case U.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case U.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case U.MaterialAlpha:e.setFloat(r,i.alpha)}return}let s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case O.Float:e.setFloat(r,s);break;case O.Int:e.setInt(r,s);break;case O.Color3:ih.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&ih.Color3[0].toGammaSpaceToRef(ih.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&ih.Color3[0].toLinearSpaceToRef(ih.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,ih.Color3[0]);break;case O.Color4:ih.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&ih.Color4[0].toGammaSpaceToRef(ih.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&ih.Color4[0].toLinearSpaceToRef(ih.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,ih.Color4[0]);break;case O.Vector2:e.setVector2(r,s);break;case O.Vector3:e.setVector3(r,s);break;case O.Vector4:e.setVector4(r,s);break;case O.Matrix:e.setMatrix(r,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); +`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${U[this._systemValue]}); +`;if(this.isUniform){let t=[],i="";switch(this.type){case O.Float:i=`${this.value}`;break;case O.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case O.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case O.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case O.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case O.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case O.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===O.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${V[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){let e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===B.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===B.Attribute&&e.type===O.Vector3&&(this._type=O.Vector4),e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=t0[e.valueType];t&&(this._storedValue=t.FromArray(e.value))}}}}t0["BABYLON.InputBlock"]=aR;class aI extends ax{constructor(e){super(e,N.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",O.AutoDetect,!1,N.VertexAndFragment),this.registerOutput("rgba",O.Color4,N.Neutral),this.registerOutput("rgb",O.Color3,N.Neutral),this.registerOutput("r",O.Float,N.Neutral),this.registerOutput("g",O.Float,N.Neutral),this.registerOutput("b",O.Float,N.Neutral),this.registerOutput("a",O.Float,N.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Vector2|O.Vector3|O.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?N.VertexAndFragment:N.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&!t.connectedPoint.ownerBlock.isAttribute&&e._emitUniformFromString(t.associatedVariableName,"vec2"),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===N.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}if(this.uv.ownerBlock.target===N.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===N.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===N.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.blockingBlocks.indexOf(this)&&e.sharedData.blockingBlocks.push(this),0>e.sharedData.textureBlocks.indexOf(this)&&e.sharedData.textureBlocks.push(this),0>e.sharedData.blocksWithDefines.indexOf(this)&&e.sharedData.blocksWithDefines.push(this),e.target!==N.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e),this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=n6.Parse(e.texture,t,i))}}t0["BABYLON.CurrentScreenBlock"]=aI;class aP extends ax{constructor(e){super(e,N.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",O.AutoDetect,!1,N.VertexAndFragment),this.registerOutput("rgba",O.Color4,N.Neutral),this.registerOutput("rgb",O.Color3,N.Neutral),this.registerOutput("r",O.Float,N.Neutral),this.registerOutput("g",O.Float,N.Neutral),this.registerOutput("b",O.Float,N.Neutral),this.registerOutput("a",O.Float,N.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Vector2|O.Vector3|O.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"particle_uv"===e.name&&t(e));i||(i=new aR("uv")).setAsAttribute("particle_uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`}_buildBlock(e){if(super._buildBlock(e),e.target===N.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); +`,this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=n6.Parse(e.texture,t,i))}}t0["BABYLON.ParticleTextureBlock"]=aP;class aM extends ax{constructor(e){super(e,N.Fragment),this._isUnique=!0,this.registerInput("color",O.Color4,!1,N.Fragment),this.registerOutput("rampColor",O.Color4,N.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==N.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` + #ifdef RAMPGRADIENT + vec4 baseColor = ${this.color.associatedVariableName}; + float alpha = ${this.color.associatedVariableName}.a; + + float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); + + vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); + baseColor.rgb *= rampColor.rgb; + + // Remapped alpha + float finalAlpha = baseColor.a; + baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); + + ${this._declareOutput(this.rampColor,e)} = baseColor; + #else + ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; + #endif + `,this}}t0["BABYLON.ParticleRampGradientBlock"]=aM;class aD extends ax{constructor(e){super(e,N.Fragment),this._isUnique=!0,this.registerInput("color",O.Color4,!1,N.Fragment),this.registerInput("alphaTexture",O.Float,!1,N.Fragment),this.registerInput("alphaColor",O.Float,!1,N.Fragment),this.registerOutput("blendColor",O.Color4,N.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==N.Vertex)return e.compilationString+=` + #ifdef BLENDMULTIPLYMODE + ${this._declareOutput(this.blendColor,e)}; + float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; + ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); + ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; + #else + ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; + #endif + `,this}}t0["BABYLON.ParticleBlendMultiplyBlock"]=aD;class aO{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=[]),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._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;let i=this._mesh.getScene();for(let e=0;e0&&(r.computeBonesUsingShaders=!1);continue}if(r.computeBonesUsingShaders&&0!==r.numBoneInfluencers){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes){for(let e of r.subMeshes)if(e.effect===t){r.computeBonesUsingShaders=!1;break}}}}}else{let t=this._defines[this._currentRank];if(t)for(let i=0;i0}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 texture(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t: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,i=!1){if(this.samples===e&&!i)return e;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){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=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){var a;return null===(a=this._depthStencilTexture)||void 0===a||a.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:n},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var e,t,i,r,s,n,a,o;let l=null;if(this._isMulti){let i=this.textures;if(i&&i.length>0){let r=!1,s=i.length,n=i[i.length-1]._source;(n===m.Depth||n===m.DepthStencil)&&(r=!0,s--);let a=[],o=[],h=[],u=[],c=[],d=[],p=[],_={};for(let r=0;r1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let t=0;t<(null===(e=this._textures)||void 0===e?void 0:e.length);++t)this._textures[t].dispose();this._textures=null}dispose(e=!1){var t;e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class aw extends aF{constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height)).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}_shareDepth(e){super._shareDepth(e);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let s=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,s,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var s,n,a,o;if(!e._hardwareTexture)return;let l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){let l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(n=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==n?n:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=null!==(o=null!=i?i:null===(a=this.faceIndices)||void 0===a?void 0:a[t])&&void 0!==o?o:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{let s=this._context,n=s["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,n,a,e._hardwareTexture.underlyingResource,r)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let s=null!==(r=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==r?r:this.textures.length;for(let e=0;e1&&(15===a.format?c=r.DEPTH_COMPONENT16:16===a.format?c=r.DEPTH_COMPONENT24:17===a.format||13===a.format?c=r.DEPTH24_STENCIL8:14===a.format?c=r.DEPTH_COMPONENT32F:18===a.format&&(c=r.DEPTH32F_STENCIL8)),a.is2DArray?r.texImage3D(n,0,c,a.width,a.height,s,0,u,h,null):r.texImage2D(n,0,c,a.width,a.height,0,u,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),i._depthStencilBuffer){let e=this._currentFramebuffer;this._bindUnboundFramebuffer(i._framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null}return a},r$.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);let r=e.texture._hardwareTexture;if(r.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){let s=i.createFramebuffer();if(!s)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);let n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw Error("Unable to create multi sampled framebuffer");r.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};class aL{static RegisterShaderCodeProcessing(e,t){if(!t){delete aL._CustomShaderCodeProcessing[null!=e?e:""];return}aL._CustomShaderCodeProcessing[null!=e?e:""]=t}static _GetShaderCodeProcessing(e){var t;return null!==(t=aL._CustomShaderCodeProcessing[e])&&void 0!==t?t:aL._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)})}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,i,r,s,n,a=1,o,l,h=null,u=0,c="postprocess",d,p=!1,_=5,m=f.GLSL){var g,v,x,T,b,E,S,C,y,A,R,I;this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new sa(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new t4(1,1),this._texelSize=t4.Zero(),this.onActivateObservable=new tj,this.onSizeChangedObservable=new tj,this.onApplyObservable=new tj,this.onBeforeRenderObservable=new tj,this.onAfterRenderObservable=new tj,this.name=e;let P=1,M=null;if(i&&!Array.isArray(i)){let e=i;i=null!==(g=e.uniforms)&&void 0!==g?g:null,r=null!==(v=e.samplers)&&void 0!==v?v:null,P=null!==(x=e.size)&&void 0!==x?x:1,n=null!==(T=e.camera)&&void 0!==T?T:null,a=null!==(b=e.samplingMode)&&void 0!==b?b:1,o=e.engine,l=e.reusable,h=null!==(E=e.defines)&&void 0!==E?E:null,u=null!==(S=e.textureType)&&void 0!==S?S:0,c=null!==(C=e.vertexUrl)&&void 0!==C?C:"postprocess",d=e.indexParameters,p=null!==(y=e.blockCompilation)&&void 0!==y&&y,_=null!==(A=e.textureFormat)&&void 0!==A?A:5,m=null!==(R=e.shaderLanguage)&&void 0!==R?R:f.GLSL,M=null!==(I=e.uniformBuffers)&&void 0!==I?I:null}else s&&(P="number"==typeof s?s:{width:s.width,height:s.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=P,this.renderTargetSamplingMode=a||1,this._reusable=l||!1,this._textureType=u,this._textureFormat=_,this._shaderLanguage=m,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=c,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=M||[],this._indexParameters=d,this._drawWrapper=new rY(this._engine),p||this.updateEffect(h)}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 sa(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,n,a,o){var l,h;let u=aL._GetShaderCodeProcessing(this.name);if(null==u?void 0:u.defineCustomBindings){let r=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];r.push(...this._parameters);let s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=u.defineCustomBindings(this.name,e,r,s),t=r,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=a?a:this._vertexUrl,fragment:null!=o?o:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:null!=s?s:null,onError:null!=n?n:null,indexParameters:r||this._indexParameters,processCodeAfterIncludes:(null==u?void 0:u.processCodeAfterIncludes)?(e,t)=>u.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==u?void 0:u.processFinalCode)?(e,t)=>u.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i){for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)}),this._flushTextureCache(),this._renderId++}return p||(p=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(l/u,h/c),this._engine.bindFramebuffer(p,0,l,h,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(p,0,void 0,void 0,this.forceFullscreenViewport)),null===(s=(r=this._engine)._debugInsertMarker)||void 0===s||s.call(r,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:n.clearColor,n._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),p}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(){var e,t;return null!==(t=null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}apply(){var e,t,i;let r;return(null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())?(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),r=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",null==r?void 0:r.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),null===(i=null===(t=aL._GetShaderCodeProcessing(this.name))||void 0===t?void 0:t.bindCustomBindings)||void 0===i||i.call(t,this.name,this._drawWrapper.effect),this._drawWrapper.effect):null}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}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&&-1!==(t=this._scene.postProcesses.indexOf(this))&&this._scene.postProcesses.splice(t,1),this._parentContainer){let e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(-1!==(t=this._engine.postProcesses.indexOf(this))&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),0===(t=e._postProcesses.indexOf(this))&&e._postProcesses.length>0){let e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){let e=i$.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(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=aL.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,i){let r=t0[e.customType];if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return i$.Parse(()=>new aL(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,i,r)}}aL._CustomShaderCodeProcessing={},iZ([iW()],aL.prototype,"uniqueId",void 0),iZ([iW()],aL.prototype,"name",void 0),iZ([iW()],aL.prototype,"width",void 0),iZ([iW()],aL.prototype,"height",void 0),iZ([iW()],aL.prototype,"renderTargetSamplingMode",void 0),iZ([iG(8,void 0)],aL.prototype,"clearColor",void 0),iZ([iW()],aL.prototype,"autoClear",void 0),iZ([iW()],aL.prototype,"forceAutoClearInAlphaMode",void 0),iZ([iW()],aL.prototype,"alphaMode",void 0),iZ([iW()],aL.prototype,"alphaConstants",void 0),iZ([iW()],aL.prototype,"enablePixelPerfectMode",void 0),iZ([iW()],aL.prototype,"forceFullscreenViewport",void 0),iZ([iW()],aL.prototype,"scaleMode",void 0),iZ([iW()],aL.prototype,"alwaysForcePOT",void 0),iZ([iW("samples")],aL.prototype,"_samples",void 0),iZ([iW()],aL.prototype,"adaptScaleToCurrentViewport",void 0),t0["BABYLON.PostProcess"]=aL;class aB extends ax{constructor(e){super(e,N.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",O.Vector4,!0),this.registerInput("xyz ",O.Vector3,!0),this.registerInput("xy ",O.Vector2,!0),this.registerInput("zw ",O.Vector2,!0),this.registerInput("x",O.Float,!0),this.registerInput("y",O.Float,!0),this.registerInput("z",O.Float,!0),this.registerInput("w",O.Float,!0),this.registerOutput("xyzw",O.Vector4),this.registerOutput("xyz",O.Vector3),this.registerOutput("xy",O.Vector2),this.registerOutput("zw",O.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.x,i=this.y,r=this.z,s=this.w,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],u=this._outputs[1],c=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; +`)):o.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${o.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; +`)):(n.isConnected?(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${a.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; +`)):(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${a.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; +`)),d.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; +`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; +`)),this}serialize(){let e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){var r,s,n,a;super._deserialize(e,t,i),this.xSwizzle=null!==(r=e.xSwizzle)&&void 0!==r?r:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(n=e.zSwizzle)&&void 0!==n?n:"z",this.wSwizzle=null!==(a=e.wSwizzle)&&void 0!==a?a:"w"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; +${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; +${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; +${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; +`}}t0["BABYLON.VectorMergerBlock"]=aB;class aU extends ax{constructor(e){super(e,N.Neutral),this.sourceRange=new t4(-1,1),this.targetRange=new t4(0,1),this.registerInput("input",O.AutoDetect),this.registerInput("sourceMin",O.Float,!0),this.registerInput("sourceMax",O.Float,!0),this.registerInput("targetMin",O.Float,!0),this.registerInput("targetMax",O.Float,!0),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${s}) / (${r} - ${i}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); +`+`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); +`}serialize(){let e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=t4.FromArray(e.sourceRange),this.targetRange=t4.FromArray(e.targetRange)}}iZ([aE("From",L.Vector2)],aU.prototype,"sourceRange",void 0),iZ([aE("To",L.Vector2)],aU.prototype,"targetRange",void 0),t0["BABYLON.RemapBlock"]=aU;class aV extends ax{constructor(e){super(e,N.Neutral),this.registerInput("left",O.AutoDetect),this.registerInput("right",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(O.Float),this._inputs[1].acceptedConnectionPointTypes.push(O.Float)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; +`,this}}t0["BABYLON.MultiplyBlock"]=aV,function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(k||(k={}));class ak{constructor(){this.direction1=new t5(0,1,0),this.direction2=new t5(0,1,0),this.minEmitBox=new t5(-.5,-.5,-.5),this.maxEmitBox=new t5(.5,.5,.5)}startDirectionFunction(e,t,i,r){let s=tK.RandomRange(this.direction1.x,this.direction2.x),n=tK.RandomRange(this.direction1.y,this.direction2.y),a=tK.RandomRange(this.direction1.z,this.direction2.z);if(r){t.x=s,t.y=n,t.z=a;return}t5.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){let s=tK.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),n=tK.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=tK.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=s,t.y=n,t.z=a;return}t5.TransformCoordinatesFromFloatsToRef(s,n,a,e,t)}clone(){let e=new ak;return iP.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){t5.FromArrayToRef(e.direction1,0,this.direction1),t5.FromArrayToRef(e.direction2,0,this.direction2),t5.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),t5.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class aG{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?ie.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),ie.Vector3[0]).normalize();let s=tK.RandomRange(0,this.directionRandomizer),n=tK.RandomRange(0,this.directionRandomizer),a=tK.RandomRange(0,this.directionRandomizer);t.x=ie.Vector3[0].x+s,t.y=ie.Vector3[0].y+n,t.z=ie.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,r){let s;let n=tK.RandomRange(0,2*Math.PI);s=this.emitFromSpawnPointOnly?1e-4:1-(s=tK.RandomRange(0,this.heightRange))*s;let a=this._radius-tK.RandomRange(0,this._radius*this.radiusRange),o=(a*=s)*Math.sin(n),l=a*Math.cos(n),h=s*this._height;if(r){t.x=o,t.y=h,t.z=l;return}t5.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){let e=new aG(this._radius,this._angle,this.directionRandomizer);return iP.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class az{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=t5.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),t5.TransformNormalToRef(this._tempVector,s,this._tempVector);let n=tK.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),a=Math.atan2(this._tempVector.x,this._tempVector.z);if(a+=tK.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}t5.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){let s=tK.RandomRange(-this.height/2,this.height/2),n=tK.RandomRange(0,2*Math.PI),a=Math.sqrt(tK.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1))*this.radius,o=a*Math.cos(n),l=a*Math.sin(n);if(r){t.copyFromFloats(o,s,l);return}t5.TransformCoordinatesFromFloatsToRef(o,s,l,e,t)}clone(){let e=new az(this.radius,this.directionRandomizer);return iP.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class aW extends az{constructor(e=1,t=1,i=1,r=new t5(0,1,0),s=new t5(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t){let i=tK.RandomRange(this.direction1.x,this.direction2.x),r=tK.RandomRange(this.direction1.y,this.direction2.y),s=tK.RandomRange(this.direction1.z,this.direction2.z);t5.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new aW(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return iP.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){let e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class aH{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=tK.RandomRange(0,this.directionRandomizer),a=tK.RandomRange(0,this.directionRandomizer),o=tK.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}t5.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-tK.RandomRange(0,this.radius*this.radiusRange),n=tK.RandomRange(0,1),a=tK.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,Math.abs(h),u);return}t5.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),u,e,t)}clone(){let e=new aH(this.radius,this.directionRandomizer);return iP.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class aX{constructor(){this.direction1=new t5(0,1,0),this.direction2=new t5(0,1,0)}startDirectionFunction(e,t,i,r){let s=tK.RandomRange(this.direction1.x,this.direction2.x),n=tK.RandomRange(this.direction1.y,this.direction2.y),a=tK.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}t5.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}t5.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){let e=new aX;return iP.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){t5.FromArrayToRef(e.direction1,0,this.direction1),t5.FromArrayToRef(e.direction2,0,this.direction2)}}class aY{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=tK.RandomRange(0,this.directionRandomizer),a=tK.RandomRange(0,this.directionRandomizer),o=tK.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}t5.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-tK.RandomRange(0,this.radius*this.radiusRange),n=tK.RandomRange(0,1),a=tK.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,h,u);return}t5.TransformCoordinatesFromFloatsToRef(l,h,u,e,t)}clone(){let e=new aY(this.radius,this.directionRandomizer);return iP.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class aj extends aY{constructor(e=1,t=new t5(0,1,0),i=new t5(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){let i=tK.RandomRange(this.direction1.x,this.direction2.x),r=tK.RandomRange(this.direction1.y,this.direction2.y),s=tK.RandomRange(this.direction1.z,this.direction2.z);t5.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new aj(this.radius,this.direction1,this.direction2);return iP.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){let e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class aK{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){let s=ie.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);let e=ie.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(r){t.copyFrom(s);return}t5.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){let s=ie.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r){t.copyFrom(s);return}t5.TransformCoordinatesToRef(s,e,t)}clone(){let e=new aK;return iP.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e}parse(e){}}class a${get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(sf.PositionKind),this._normals=e.getVerticesData(sf.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=t5.Zero(),this._mesh=null,this.direction1=new t5(0,1,0),this.direction2=new t5(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){t5.TransformNormalToRef(this._storedNormal,e,t);return}let s=tK.RandomRange(this.direction1.x,this.direction2.x),n=tK.RandomRange(this.direction1.y,this.direction2.y),a=tK.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}t5.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;let s=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),a=Math.random()*(1-n),o=1-n-a,l=this._indices[s],h=this._indices[s+1],u=this._indices[s+2],c=ie.Vector3[0],d=ie.Vector3[1],p=ie.Vector3[2],_=ie.Vector3[3];t5.FromArrayToRef(this._positions,3*l,c),t5.FromArrayToRef(this._positions,3*h,d),t5.FromArrayToRef(this._positions,3*u,p),_.x=n*c.x+a*d.x+o*p.x,_.y=n*c.y+a*d.y+o*p.y,_.z=n*c.z+a*d.z+o*p.z,r?t.copyFromFloats(_.x,_.y,_.z):t5.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(t5.FromArrayToRef(this._normals,3*l,c),t5.FromArrayToRef(this._normals,3*h,d),t5.FromArrayToRef(this._normals,3*u,p),this._storedNormal.x=n*c.x+a*d.x+o*p.x,this._storedNormal.y=n*c.y+a*d.y+o*p.y,this._storedNormal.z=n*c.z+a*d.z+o*p.z)}clone(){let e=new a$(this.mesh);return iP.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;let t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){t5.FromArrayToRef(e.direction1,0,this.direction1),t5.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}class aq{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:t5.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:t5.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:t5.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:t5.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(let i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=t5.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new t5(10,10,10),this.onAnimationEnd=null,this.blendMode=aq.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new t4(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new t5(0,0,0),this._useLogarithmicDepth=!1,this.gravity=t5.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new il(1,1,1,1),this.color2=new il(1,1,1,1),this.colorDead=new il(0,0,0,1),this.textureMask=new il(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new sc,this.id=e,this.name=e}createPointEmitter(e,t){let i=new aX;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){let i=new aH(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){let i=new aY(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new t5(0,1,0),i=new t5(0,1,0)){let r=new aj(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){let s=new az(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new t5(0,1,0),s=new t5(0,1,0)){let n=new aW(e,t,i,r,s);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){let i=new aG(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){let s=new ak;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}}aq.BLENDMODE_ONEONE=0,aq.BLENDMODE_STANDARD=1,aq.BLENDMODE_ADD=2,aq.BLENDMODE_MULTIPLY=3,aq.BLENDMODE_MULTIPLYADD=4;class aQ extends ax{constructor(e){super(e,N.Neutral),this.registerInput("rgba",O.Color4,!0),this.registerInput("rgb ",O.Color3,!0),this.registerOutput("rgb",O.Color3),this.registerOutput("r",O.Float),this.registerOutput("g",O.Float),this.registerOutput("b",O.Float),this.registerOutput("a",O.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);let t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;let i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],a=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; +`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.r; +`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b; +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.a; +`),this}}t0["BABYLON.ColorSplitterBlock"]=aQ,r$.prototype.createRenderTargetCubeTexture=function(e,t){let i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);let s=this._gl,n=new rU(this,m.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);let a=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,ig.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,a.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,a.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);let o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n.format=r.format,this._internalTexturesCache.push(n),i.setTextures(n),i};let aZ={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class aJ{constructor(e,t=aZ){var i,r;this._fullscreenViewport=new nr(0,0,1,1);let s=null!==(i=t.positions)&&void 0!==i?i:aZ.positions,n=null!==(r=t.indices)&&void 0!==r?r:aZ.indices;this.engine=e,this._vertexBuffers={[sf.PositionKind]:new sf(e,s,sf.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{for(let t in this._indexBuffer=e.createIndexBuffer(n),this._vertexBuffers)this._vertexBuffers[t]._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(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){let e=this._vertexBuffers[sf.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[sf.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class a0{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new tj;let i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)}));let r=e.defines?e.defines.join("\n"):"";this._drawWrapper=new rY(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"],i,e.samplerNames,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new rN(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._wasPreviouslyReady=!1,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}let a1="passPixelShader",a2=`varying vec2 vUV;uniform sampler2D textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);}`;rO.ShadersStore[a1]=a2;let a3={name:a1,shader:a2};class a4{static _CreateDumpRenderer(){if(!a4._DumpToolsEngine){let e;let t=null,i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new r$(e,!1,i)}catch(r){t=new r$(e=document.createElement("canvas"),!1,i)}t.getCaps().parallelShaderCompile=void 0;let r=new aJ(t),s=new a0({engine:t,name:a3.name,fragmentShader:a3.shader,samplerNames:["textureSampler"]});a4._DumpToolsEngine={canvas:e,engine:t,renderer:r,wrapper:s}}return a4._DumpToolsEngine}static async DumpFramebuffer(e,t,i,r,s="image/png",n,a){let o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);a4.DumpData(e,t,l,r,s,n,!0,void 0,a)}static DumpDataAsync(e,t,i,r="image/png",s,n=!1,a=!1,o){return new Promise(l=>{a4.DumpData(e,t,i,e=>l(e),r,s,n,a,o)})}static DumpData(e,t,i,r,s="image/png",n,a=!1,o=!1,l){let h=a4._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){let e=new Uint8Array(i.length),t=i.length;for(;t--;){let r=i[t];e[t]=Math.round(255*tK.Clamp(r))}i=e}let u=h.engine.createRawTexture(i,e,t,5,!1,!a,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",u),h.renderer.draw(),o?ss.ToBlob(h.canvas,e=>{let t=new FileReader;t.onload=e=>{let t=e.target.result;r&&r(t)},t.readAsArrayBuffer(e)},s,l):ss.EncodeScreenshotCanvasData(h.canvas,r,s,n,l),u.dispose()}static Dispose(){a4._DumpToolsEngine&&(a4._DumpToolsEngine.wrapper.dispose(),a4._DumpToolsEngine.renderer.dispose(),a4._DumpToolsEngine.engine.dispose()),a4._DumpToolsEngine=null}}ss.DumpData=a4.DumpData,ss.DumpDataAsync=a4.DumpDataAsync,ss.DumpFramebuffer=a4.DumpFramebuffer;class a5 extends n6{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=tJ(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 i;i=Array.isArray(e)?e:[e];for(let e=0;e{var i;let r=this._renderList?this._renderList.length:0;(0===t&&r>0||0===r)&&(null===(i=this.getScene())||void 0===i||i.meshes.forEach(e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new tj,this.onAfterUnbindObservable=new tj,this.onBeforeRenderObservable=new tj,this.onAfterRenderObservable=new tj,this.onClearObservable=new tj,this.onResizeObservable=new tj,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=t5.Zero(),!(i=this.getScene()))return;let A=this.getScene().getEngine();if(this._gammaSpace=y,this._coordinatesMode=n6.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=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new sT(i),this._renderingManager._useSceneAutoClearSetup=!0,u)return;this._renderTargetOptions={generateMipMaps:r,type:n,format:null!==(S=this._format)&&void 0!==S?S:void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:p,creationFlags:_,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:C,label:this.name},this.samplingMode===n6.NEAREST_SAMPLINGMODE&&(this.wrapU=n6.CLAMP_ADDRESSMODE,this.wrapV=n6.CLAMP_ADDRESSMODE),d||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=n6.INVCUBIC_MODE,this._textureMatrix=t7.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0===p||(this.samples=p))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14){var n;null===(n=this._renderTarget)||void 0===n||n.createDepthStencilTexture(e,t,i,r,s)}_releaseRenderPassId(){if(this._scene){let e=this._scene.getEngine();for(let t=0;t0&&(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(){return this._size.layers||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;let i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;let r=this.getScene();r&&(this._processSizeParameter(e,!1),i?this._renderTarget=r.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=r.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,i=!1){var r;let s=this.getScene();if(!s)return i;let n=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,s=null){var n,a,o,l,h,u;let c=this.getScene();if(!c)return;let d=c.getEngine();if(null===(n=d._debugPushGroup)||void 0===n||n.call(d,`render to face #${e} layer #${r}`,1),this._prepareFrame(c,e,r,t),this.is2DArray?(d.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(d.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),d.snapshotRendering&&1===d.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0);else{let n=null,u=this.renderList?this.renderList:c.getActiveMeshes().data,p=this.renderList?this.renderList.length:c.getActiveMeshes().length;for(let t of(this.getCustomRenderList&&(n=this.getCustomRenderList(this.is2DArray?r:e,u,p)),n?this._prepareRenderingManager(n,n.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(u,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),n=u),c._beforeRenderTargetClearStage))t.action(this,e,r);for(let t of(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),c._beforeRenderTargetDrawStage))t.action(this,e,r);for(let t of(this._renderingManager.render(this.customRenderFunction,n,this.renderParticles,this.renderSprites),c._afterRenderTargetDrawStage))t.action(this,e,r);let _=null!==(o=null===(a=this._texture)||void 0===a?void 0:a.generateMipMaps)&&void 0!==o&&o;for(let i of(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&c.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e),c._afterRenderTargetPostProcessStage))i.action(this,e,r);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),i&&a4.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),d)}this._unbindFrameBuffer(d,e),this._texture&&this.isCube&&5===e&&d.generateMipMapsForCubemap(this._texture),null===(u=d._debugPopGroup)||void 0===u||u.call(d,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){let e=this.getSize(),t=new a5(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;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&t.customRenderTargets.splice(i,1),t.cameras))(i=e.customRenderTargets.indexOf(this))>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===a5.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=a5.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}a5.REFRESHRATE_RENDER_ONCE=0,a5.REFRESHRATE_RENDER_ONEVERYFRAME=1,a5.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,n6._CreateRenderTargetTexture=(e,t,i,r,s)=>new a5(e,t,i,r);class a6{constructor(e){this.name=sb.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(sb.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){ss.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}let a8=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.proceduralVertexShader=a8;class a7 extends n6{constructor(e,t,i,r,s=null,n=!0,a=!1,o=0){var l;super(null,r,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new tj,this.onBeforeGenerationObservable=new tj,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=[],this._samplers=[],this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===s||s instanceof n6?(this._options={},this._fallbackTexture=s):(this._options=s,this._fallbackTexture=null!==(l=s.fallbackTexture)&&void 0!==l?l:null);let h=(r=this.getScene()||t2.LastCreatedScene)._getComponent(sb.NAME_PROCEDURALTEXTURE);h||(h=new a6(r),r._addComponent(h)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=o,this._generateMipMaps=n,this._drawWrapper=new rY(this._fullEngine),this.setFragment(i);let u=this._createRtWrapper(a,t,n,o);this._texture=u.texture;let c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[sf.PositionKind]=new sf(this._fullEngine,c,sf.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,Object.assign({generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r},this._options)),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,Object.assign({generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r},this._options)),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then(e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){let e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){let e=this._vertexBuffers[sf.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===a5.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=a5.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady()){e(this);return}let t=this.getEffect();t&&t.executeWhenCompiled(()=>{e(this)})}isReady(){let e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;let t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;let i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[sf.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var e;null===(e=this._rtWrapper)||void 0===e||e.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0})),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;let i=this._texture.isCube;this._rtWrapper.dispose();let r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return -1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;let r=this.getScene();if(!r)return;let s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(let e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(let e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(let e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(let e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(let e in this._colors4){let t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(let e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(let e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;null===(t=s._debugPushGroup)||void 0===t||t.call(s,`procedural texture generation for ${this.name}`,1);let n=s.currentViewport;if(this.isCube)for(let e=0;e<6;e++)s.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(nB.TriangleFillMode,0,6);else s.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(nB.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),n&&s.setViewport(n),this.isCube&&s.generateMipMapsForCubemap(this._texture),null===(i=s._debugPopGroup)||void 0===i||i.call(s,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){let e=this.getSize(),t=new a7(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){let e=this.getScene();if(!e)return;let t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);let i=this._vertexBuffers[sf.PositionKind];i&&(i.dispose(),this._vertexBuffers[sf.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}iZ([iW()],a7.prototype,"isEnabled",void 0),iZ([iW()],a7.prototype,"autoClear",void 0),iZ([iW()],a7.prototype,"_generateMipMaps",void 0),iZ([iW()],a7.prototype,"_size",void 0),iZ([iW()],a7.prototype,"refreshRate",null),t0["BABYLON.ProceduralTexture"]=a7,function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(G||(G={}));class a9 extends ax{constructor(e){super(e,N.Neutral),this.operation=G.Cos,this.registerInput("input",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="";switch(this.operation){case G.Cos:i="cos";break;case G.Sin:i="sin";break;case G.Abs:i="abs";break;case G.Exp:i="exp";break;case G.Exp2:i="exp2";break;case G.Round:i="round";break;case G.Floor:i="floor";break;case G.Ceiling:i="ceil";break;case G.Sqrt:i="sqrt";break;case G.Log:i="log";break;case G.Tan:i="tan";break;case G.ArcTan:i="atan";break;case G.ArcCos:i="acos";break;case G.ArcSin:i="asin";break;case G.Fract:i="fract";break;case G.Sign:i="sign";break;case G.Radians:i="radians";break;case G.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); +`,this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${G[this.operation]}; +`}}t0["BABYLON.TrigonometryBlock"]=a9;let oe={effect:null,subMesh:null};class ot extends sh{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!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=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class oi extends af{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||t2.LastCreatedScene),this._buildId=oi._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new t7,this._cachedWorldViewProjectionMatrix=new t7,this._optimizers=[],this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new tj,this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[],this._mode=k.Material,this.forceAlphaBlending=!1,this._options=Object.assign({emitComments:!1},i),this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){ss.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(let t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){let t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return(e.target&N.Vertex)!=0&&this._addVertexOutputNode(e),(e.target&N.Fragment)!=0&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||((e.target&N.Vertex)!=0&&this._removeVertexOutputNode(e),(e.target&N.Fragment)!=0&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=N.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){let t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=N.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){let t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){e.target===N.VertexAndFragment?i.push(e):t.target===N.Fragment&&e.target===N.Vertex&&e._preparationId!==this._buildId&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){let t=e.getClassName();for(let e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(let s of e.inputs){s.associatedVariableName="";let n=s.connectedPoint;if(n){let s=n.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}for(let s of(e.isTeleportOut&&e.entryPoint&&this._processInitializeOnLink(e.entryPoint,t,i,r),e.outputs))s.associatedVariableName=""}_resetDualBlocks(e,t){for(let i of(e.target===N.VertexAndFragment&&(e.buildId=t),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._resetDualBlocks(e.entryPoint,t)}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;let r=this.getScene().getEngine(),s=this._mode===k.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new am,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=N.Vertex,this._fragmentCompilationState=new am,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=N.Fragment,this._sharedData=new ag,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;let n=[],a=[];for(let e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,a,i);for(let e of this._fragmentOutputNodes)a.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);for(let e of(this.optimize(),n))e.build(this._vertexCompilationState,n);for(let e of(this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState,a))this._resetDualBlocks(e,this._buildId-1);for(let e of a)e.build(this._fragmentCompilationState,a);for(let i of(this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=oi._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(ig.Log("Vertex shader:"),ig.Log(this._vertexCompilationState.compilationString),ig.Log("Fragment shader:"),ig.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this),this.getScene().meshes))if(i.subMeshes)for(let e of i.subMeshes){if(e.getMaterial()!==this||!e.materialDefines)continue;let t=e.materialDefines;t.markAllAsDirty(),t.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();let o=this.getScene().prePassRenderer;o&&o.markAsDirty()}optimize(){for(let e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){let i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(sf.NormalKind),t.TANGENT=e.isVerticesDataPresent(sf.TangentKind);let n=e.useVertexColors&&e.isVerticesDataPresent(sf.ColorKind);t.VERTEXCOLOR_NME=n;let a=!1;for(let i=1;i<=6;++i){let r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),a=a||t["UV"+i]!==r}let o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;nw.PrepareDefinesForPrePass(this.getScene(),t,!o),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||a)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){let e=this.getBlockByPredicate(e=>"PrePassOutputBlock"===e.getClassName()),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){let e=this.getAllTextureBlocks().filter(e=>"PrePassTextureBlock"===e.getClassName()),t=[];for(let i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){let t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");for(let r of(i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]})),t))i.texturesRequired.includes(r)||i.texturesRequired.push(r);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,n=0,a=5){return this.mode!==k.PostProcess?(ig.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,n,a)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,n,a=0,o=5){let l=this.name+this._buildId,h=new ot,u=new nM(l+"PostProcess",this.getScene()),c=this._buildId;return this._processDefines(u,h),rN.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new aL(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,n,h.toString(),a,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,o),e.nodeMaterialSource=this,e.onApplyObservable.add(t=>{c!==this._buildId&&(delete rN.ShadersStore[l+"VertexShader"],delete rN.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),c=this._buildId),this._processDefines(u,h)&&(rN.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),rq.SetImmediate(()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l))),this._checkInternals(t)}),e}createProceduralTexture(e,t){if(this.mode!==k.ProceduralTexture)return ig.Log("Incompatible material mode"),null;let i=this.name+this._buildId,r=new a7(i,e,null,t),s=new nM(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};let n=new ot,a=this._processDefines(s,n);rN.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[sf.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==a?void 0:a.fallbacks,void 0);r.nodeMaterialSource=this,r._setEffect(o);let l=this._buildId;return r.onBeforeGenerationObservable.add(()=>{l!==this._buildId&&(delete rN.ShadersStore[i+"VertexShader"],delete rN.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);let e=this._processDefines(s,n);e&&(rN.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),rq.SetImmediate(()=>{o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[sf.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==e?void 0:e.fallbacks,void 0),r._setEffect(o)})),this._checkInternals(o)}),r}_createEffectForParticles(e,t,i,r,s,n,a,o=""){let l=this.name+this._buildId+"_"+t;n||(n=new ot),a||(a=this.getScene().getMeshByName(this.name+"Particle"))||((a=new nM(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId,u=[],c=o;if(!s){let o=this._processDefines(a,n);rN.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),c=u.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==o?void 0:o.fallbacks,i,r,e),e.setCustomEffect(s,t)}s.onBindObservable.add(s=>{h!==this._buildId&&(delete rN.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),u.length=0,e.fillDefines(u,t);let d=u.join("\n");d!==c&&(n.markAllAsDirty(),c=d);let p=this._processDefines(a,n);if(p){rN.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==p?void 0:p.fallbacks,i,r,e),e.setCustomEffect(s,t),this._createEffectForParticles(e,t,i,r,s,n,a,o);return}this._checkInternals(s)})}_checkInternals(e){if(this._sharedData.animatedInputs){let e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(let t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(let t of this._sharedData.bindableBlocks)t.bind(e,this);for(let t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==k.Particle){ig.Log("Incompatible material mode");return}this._createEffectForParticles(e,aq.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,aq.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==k.Material){ig.Log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let s=null,n=this.getScene();if(nw.PrepareDefinesForCamera(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(r=>{r.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(s=>{s.prepareDefines(e,this,t,i,r)}),t.isDirty){let i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)});let r=[];this._sharedData.dynamicUniformBlocks.forEach(e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)});let n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(e=>{-1===n.indexOf(e)&&n.push(e)});let a=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(e=>{-1===a.indexOf(e)&&a.push(e)});let o=new aO;this._sharedData.blocksWithFallbacks.forEach(t=>{t.provideFallbacks(e,o)}),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:n,mergedSamplers:a,fallbacks:o}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;let r=this.getScene();if(this._sharedData.animatedInputs){let e=r.getFrameId();if(this._animationFrame!==e){for(let e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new ot);let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some(t=>!t.isReady(e,this,s,i)))return!1;let a=this._processDefines(e,s,i,t);if(a){let e=t.effect,i=s.toString(),o=n.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:s.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},n);if(o){if(this._onEffectCreatedObservable&&(oe.effect=o,oe.subMesh=t,this._onEffectCreatedObservable.notifyObservers(oe)),this.allowShaderHotSwapping&&e&&!o.isReady()){if(o=e,s.markAsUnprocessed(),a.lightDisposed)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(o,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader +${this._vertexCompilationState.compilationString} + +// Fragment shader +${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){let t=this.getScene();if(!this._activeEffect)return;let i=this._sharedData.hints;for(let r of(i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._sharedData.inputBlocks))r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);let n=this._mustRebind(r,s,t.visibility),a=this._sharedData;if(n){for(let e of a.bindableBlocks)e.bind(s,this,t,i);for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);for(let e of a.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){let e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter(e=>e.texture).map(e=>e.texture)),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){let e=[];for(let t of this.attachedBlocks)oi._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(let t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(let e of this.getTextureBlocks().filter(e=>e.texture).map(e=>e.texture))e.dispose();for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){let t=Object.assign({nodeMaterial:this},e);this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise(t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){let i=e&&e.editorURL?e.editorURL:oi.EditorURL;ss.LoadBabylonScript(i,()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()})}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;let e=new aR("Position");e.setAsAttribute("position");let t=new aR("World");t.setAsSystemValue(U.World);let i=new aT("WorldPos");e.connectTo(i),t.connectTo(i);let r=new aR("ViewProjection");r.setAsSystemValue(U.ViewProjection);let s=new aT("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);let n=new ab("VertexOutput");s.connectTo(n);let a=new aR("color");a.value=new il(.8,.8,.8,1);let o=new aS("FragmentOutput");a.connectTo(o),this.addOutputNode(n),this.addOutputNode(o),this._mode=k.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;let e=new aR("Position");e.setAsAttribute("position2d");let t=new aR("Constant1");t.isConstant=!0,t.value=1;let i=new aB("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new ab("VertexOutput");i.connectTo(r);let s=new aR("Scale");s.visibleInInspector=!0,s.value=new t4(1,1);let n=new aU("uv0");e.connectTo(n);let a=new aV("UV scale");n.connectTo(a),s.connectTo(a);let o=new aI("CurrentScreen");a.connectTo(o),o.texture=new n6("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());let l=new aS("FragmentOutput");o.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=k.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;let e=new aR("Position");e.setAsAttribute("position2d");let t=new aR("Constant1");t.isConstant=!0,t.value=1;let i=new aB("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new ab("VertexOutput");i.connectTo(r);let s=new aR("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=V.Time,s.isConstant=!1;let n=new aR("Color3");n.value=new io(1,1,1),n.isConstant=!1;let a=new aS("FragmentOutput"),o=new aB("VectorMerger");o.visibleInInspector=!1;let l=new a9("Cos");l.operation=G.Cos,e.connectTo(o),s.output.connectTo(l.input),l.output.connectTo(o.z),o.xyzOut.connectTo(a.rgb),this.addOutputNode(r),this.addOutputNode(a),this._mode=k.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;let e=new aR("uv");e.setAsAttribute("particle_uv");let t=new aP("ParticleTexture");e.connectTo(t);let i=new aR("Color");i.setAsAttribute("particle_color");let r=new aV("Texture * Color");t.connectTo(r),i.connectTo(r);let s=new aM("ParticleRampGradient");r.connectTo(s);let n=new aQ("ColorSplitter");i.connectTo(n);let a=new aD("ParticleBlendMultiply");s.connectTo(a),t.connectTo(a,{output:"a"}),n.connectTo(a,{output:"a"});let o=new aS("FragmentOutput");a.connectTo(o),this.addOutputNode(o),this._mode=k.Particle}async loadAsync(e,t=""){return oi.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}generateCode(){let e=[],t=[],i=["const","var","let"];for(let e of this._vertexOutputNodes)this._gatherBlocks(e,t);let r=[];for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); +`;for(let r of(s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${k[this.mode]}; +`,t))r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(let t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));for(let t of(e=[],s+="\n// Connections\n",this._vertexOutputNodes))s+=t._dumpCodeForOutputConnections(e);for(let t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(let e of(s+="\n// Output nodes\n",this._vertexOutputNodes))s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); +`;for(let e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); +`;return s+`nodeMaterial.build(); +`}serialize(e){let t=e?{}:i$.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{for(let e of(t.customType="BABYLON.NodeMaterial",t.outputNodes=[],this._vertexOutputNodes))this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}for(let e of(t.blocks=[],i))t.blocks.push(e.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var r;i||this.clear();let s={};for(let i of e.blocks){let e=t0[i.customType];if(e){let r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;t&&s[t].attachToEndpoint(e)}for(let t=0;tnew oi(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){let e=[];return this.getActiveTextures().forEach(t=>{let i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((e,t)=>{i.onLoadedObservable.addOnce(()=>{e()}),i.onErrorObservable.addOnce(e=>{t(e)})}))}),Promise.all(e)}static Parse(e,t,i=""){let r=i$.Parse(()=>new oi(e.name,t),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,r="",s=!1,n){let a=null!=n?n:new oi(e,i),o=JSON.parse(await i._loadFileAsync(t));return a.parseSerializedObject(o,r),s||a.build(),a}static ParseFromSnippetAsync(e,t=t2.LastCreatedScene,i="",r,s=!1,n=!1){return"_BLANK"===e?Promise.resolve(oi.CreateDefault("blank",t)):new Promise((a,o)=>{let l=new i2;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let h=JSON.parse(JSON.parse(JSON.parse(l.responseText).jsonPayload).nodeMaterial);r||((r=i$.Parse(()=>new oi(e,t),h,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(h),r.snippetId=e;try{s||r.build()}catch(e){o(e)}n?r.whenTexturesReadyAsync().then(()=>{a(r)}).catch(e=>{o(e)}):a(r)}else o("Unable to load the snippet "+e)}}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}static CreateDefault(e,t){let i=new oi(e,t);return i.setToDefault(),i.build(),i}}function or(e){let t;let i=e.sideOrientation||ng.DEFAULTSIDE,r=e.radius||1,s=void 0===e.flat||e.flat,n=0|(e.subdivisions||4),a=e.radiusX||r,o=e.radiusY||r,l=e.radiusZ||r,h=(1+Math.sqrt(5))/2,u=[-1,h,-0,1,h,0,-1,-h,0,1,-h,0,0,-1,-h,0,1,-h,0,-1,h,0,1,h,h,0,1,h,0,-1,-h,0,1,-h,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],p=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=138/1024,f=239/1024,m=60/1024,g=26/1024,v=-40/1024,x=20/1024,T=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],b=[],E=[],S=[],C=[],y=0,A=[,,,],R=[,,,];for(t=0;t<3;t++)A[t]=t5.Zero(),R[t]=t4.Zero();for(let e=0;e<20;e++){for(t=0;t<3;t++){let i=c[3*e+t];A[t].copyFromFloats(u[3*d[i]],u[3*d[i]+1],u[3*d[i]+2]),A[t].normalize(),R[t].copyFromFloats(p[2*i]*_+m+T[e]*v,p[2*i+1]*f+g+T[e]*x)}let i=(e,t,i,r)=>{let h;let u=t5.Lerp(A[0],A[2],t/n),c=t5.Lerp(A[1],A[2],t/n),d=n===t?A[2]:t5.Lerp(u,c,e/(n-t));if(d.normalize(),s){let e=t5.Lerp(A[0],A[2],r/n),t=t5.Lerp(A[1],A[2],r/n);h=t5.Lerp(e,t,i/(n-r))}else h=new t5(d.x,d.y,d.z);h.x/=a,h.y/=o,h.z/=l,h.normalize();let p=t4.Lerp(R[0],R[2],t/n),_=t4.Lerp(R[1],R[2],t/n),f=n===t?R[2]:t4.Lerp(p,_,e/(n-t));E.push(d.x*a,d.y*o,d.z*l),S.push(h.x,h.y,h.z),C.push(f.x,nx.UseOpenGLOrientationForUV?1-f.y:f.y),b.push(y),y++};for(let e=0;eos(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(z||(z={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(W||(W={}));let on=[W.WRIST,W.THUMB_METACARPAL,W.THUMB_PHALANX_PROXIMAL,W.THUMB_PHALANX_DISTAL,W.THUMB_TIP,W.INDEX_FINGER_METACARPAL,W.INDEX_FINGER_PHALANX_PROXIMAL,W.INDEX_FINGER_PHALANX_INTERMEDIATE,W.INDEX_FINGER_PHALANX_DISTAL,W.INDEX_FINGER_TIP,W.MIDDLE_FINGER_METACARPAL,W.MIDDLE_FINGER_PHALANX_PROXIMAL,W.MIDDLE_FINGER_PHALANX_INTERMEDIATE,W.MIDDLE_FINGER_PHALANX_DISTAL,W.MIDDLE_FINGER_TIP,W.RING_FINGER_METACARPAL,W.RING_FINGER_PHALANX_PROXIMAL,W.RING_FINGER_PHALANX_INTERMEDIATE,W.RING_FINGER_PHALANX_DISTAL,W.RING_FINGER_TIP,W.PINKY_FINGER_METACARPAL,W.PINKY_FINGER_PHALANX_PROXIMAL,W.PINKY_FINGER_PHALANX_INTERMEDIATE,W.PINKY_FINGER_PHALANX_DISTAL,W.PINKY_FINGER_TIP],oa={[z.WRIST]:[W.WRIST],[z.THUMB]:[W.THUMB_METACARPAL,W.THUMB_PHALANX_PROXIMAL,W.THUMB_PHALANX_DISTAL,W.THUMB_TIP],[z.INDEX]:[W.INDEX_FINGER_METACARPAL,W.INDEX_FINGER_PHALANX_PROXIMAL,W.INDEX_FINGER_PHALANX_INTERMEDIATE,W.INDEX_FINGER_PHALANX_DISTAL,W.INDEX_FINGER_TIP],[z.MIDDLE]:[W.MIDDLE_FINGER_METACARPAL,W.MIDDLE_FINGER_PHALANX_PROXIMAL,W.MIDDLE_FINGER_PHALANX_INTERMEDIATE,W.MIDDLE_FINGER_PHALANX_DISTAL,W.MIDDLE_FINGER_TIP],[z.RING]:[W.RING_FINGER_METACARPAL,W.RING_FINGER_PHALANX_PROXIMAL,W.RING_FINGER_PHALANX_INTERMEDIATE,W.RING_FINGER_PHALANX_DISTAL,W.RING_FINGER_TIP],[z.LITTLE]:[W.PINKY_FINGER_METACARPAL,W.PINKY_FINGER_PHALANX_PROXIMAL,W.PINKY_FINGER_PHALANX_INTERMEDIATE,W.PINKY_FINGER_PHALANX_DISTAL,W.PINKY_FINGER_TIP]};class oo{get handMesh(){return this._handMesh}getHandPartMeshes(e){return oa[e].map(e=>this._jointMeshes[on.indexOf(e)])}getJointMesh(e){return this._jointMeshes[on.indexOf(e)]}constructor(e,t,i,r,s=!1,n=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=n,this._jointScaleFactor=a,this._jointTransforms=Array(on.length),this._jointTransformMatrices=new Float32Array(16*on.length),this._tempJointMatrix=new t7,this._jointRadii=new Float32Array(on.length),this._scene=t[0].getScene();for(let e=0;e{e.rootMesh&&e.rootMesh.setEnabled(!1)})),this.xrController.onMotionControllerInitObservable.add(e=>{e.onModelLoadedObservable.add(e=>{e.rootMesh&&e.rootMesh.setEnabled(!1)}),e.rootMesh&&e.rootMesh.setEnabled(!1)})}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(e=>e.alwaysSelectAsActiveMesh=!0),this._handMesh.skeleton){let e=this._handMesh.skeleton;on.forEach((i,r)=>{let s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){let i=this.xrController.inputSource.hand;if(!i)return;let r=on.map(e=>i[e]||i.get(e)),s=!1;if(e.fillPoses&&e.fillJointRadii)s=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){s=!0;for(let i=0;i{let i=this._jointTransforms[t];t7.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);let r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),!this._scene.useRightHandedSystem&&(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}}class ol extends ac{static _GenerateTrackedJointMeshes(e){let t={};return["left","right"].map(i=>{var r,s,n,a,o;let l=[],h=(null===(r=e.jointMeshes)||void 0===r?void 0:r.sourceMesh)||os("jointParent",ol._ICOSPHERE_PARAMS);h.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t{var r,s,n,a,o;let l={};(null===(s=null===(r=ol._RightHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===s?void 0:s.isDisposed())&&(ol._RightHandGLB=null),(null===(a=null===(n=ol._LeftHandGLB)||void 0===n?void 0:n.meshes[1])||void 0===a?void 0:a.isDisposed())&&(ol._LeftHandGLB=null);let h=!!(ol._RightHandGLB&&ol._LeftHandGLB),u=await Promise.all([ol._RightHandGLB||a_.ImportMeshAsync("",ol.DEFAULT_HAND_MODEL_BASE_URL,ol.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),ol._LeftHandGLB||a_.ImportMeshAsync("",ol.DEFAULT_HAND_MODEL_BASE_URL,ol.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);ol._RightHandGLB=u[0],ol._LeftHandGLB=u[1];let c=new oi("handShader",e,{emitComments:!1});await c.loadAsync(ol.DEFAULT_HAND_MODEL_SHADER_URL),c.needDepthPrePass=!0,c.transparencyMode=nB.MATERIAL_ALPHABLEND,c.alphaMode=2,c.build(!1);let d=Object.assign({base:io.FromInts(116,63,203),fresnel:io.FromInts(149,102,229),fingerColor:io.FromInts(177,130,255),tipFresnel:io.FromInts(220,200,255)},null===(o=null==t?void 0:t.handMeshes)||void 0===o?void 0:o.customColors),p={base:c.getBlockByName("baseColor"),fresnel:c.getBlockByName("fresnelColor"),fingerColor:c.getBlockByName("fingerColor"),tipFresnel:c.getBlockByName("tipFresnelColor")};p.base.value=d.base,p.fresnel.value=d.fresnel,p.fingerColor.value=d.fingerColor,p.tipFresnel.value=d.tipFresnel,["left","right"].forEach(t=>{let i="left"==t?ol._LeftHandGLB:ol._RightHandGLB;if(!i)throw Error("Could not load hand model");let r=i.meshes[1];r._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,r.material=c.clone(`${t}HandShaderClone`,!0),r.isVisible=!1,l[t]=r,h||e.useRightHandedSystem||i.meshes[1].rotate(sj.Y,Math.PI)}),c.dispose(),i({left:l.left,right:l.right})})}static _GenerateDefaultHandMeshRigMapping(e){let t="right"==e?"R":"L";return{[W.WRIST]:`wrist_${t}`,[W.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[W.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[W.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[W.THUMB_TIP]:`thumb_tip_${t}`,[W.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[W.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[W.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[W.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[W.INDEX_FINGER_TIP]:`index_tip_${t}`,[W.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[W.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[W.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[W.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[W.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[W.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[W.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[W.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[W.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[W.RING_FINGER_TIP]:`ring_tip_${t}`,[W.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[W.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[W.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[W.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[W.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this.onHandAddedObservable=new tj,this.onHandRemovedObservable=new tj,this._attachHand=e=>{var t,i,r;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;let s=e.inputSource.handedness,n=new oo(e,this._handResources.jointMeshes[s],this._handResources.handMeshes&&this._handResources.handMeshes[s],this._handResources.rigMappings&&this._handResources.rigMappings[s],null===(t=this.options.handMeshes)||void 0===t?void 0:t.meshesUseLeftHandedCoordinates,null===(i=this.options.jointMeshes)||void 0===i?void 0:i.invisible,null===(r=this.options.jointMeshes)||void 0===r?void 0:r.scaleFactor);this._attachedHands[e.uniqueId]=n,this._trackingHands[s]=n,this.onHandAddedObservable.notifyObservers(n)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";let i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};let e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach(e=>{let t=e[0],i=e[1];t.forEach((e,t)=>{i[on[t]]=e})}),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){var e,t,i,r;return!!super.attach()&&(this._handResources={jointMeshes:ol._GenerateTrackedJointMeshes(this.options),handMeshes:(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||null,rigMappings:(null===(t=this.options.handMeshes)||void 0===t?void 0:t.customRigMappings)||null},(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)||(null===(r=this.options.handMeshes)||void 0===r?void 0:r.disableDefaultMeshes)||ol._GenerateDefaultHandMeshesAsync(t2.LastCreatedScene,this.options).then(e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:ol._GenerateDefaultHandMeshRigMapping("left"),right:ol._GenerateDefaultHandMeshRigMapping("right")},null===(t=this._trackingHands.left)||void 0===t||t.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),null===(i=this._trackingHands.right)||void 0===i||i.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)}),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){var t,i;null===(t=this._trackingHands.left)||void 0===t||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),null===(i=this._trackingHands.right)||void 0===i||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;let i=this.getHandByControllerId(e);if(i){let r="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[r])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[r]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach(e=>this._detachHandById(e)),!0)}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),!this._handResources.handMeshes||(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),ol._RightHandGLB=null,ol._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(e=>e.dispose()),this._handResources.jointMeshes.right.forEach(e=>e.dispose()))}}ol.Name=ah.HAND_TRACKING,ol.Version=1,ol.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",ol.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",ol.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",ol.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",ol._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},ol._RightHandGLB=null,ol._LeftHandGLB=null,au.AddWebXRFeature(ol.Name,(e,t)=>()=>new ol(e,t),ol.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(H||(H={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(X||(X={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(Y||(Y={}));class oh{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=t5.Zero(),this.poleTargetPosition=t5.Zero(),this.poleTargetLocalOffset=t5.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=t8.Identity(),this._bone1Mat=t7.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=t5.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;let r=t.getParent();if(!r){this._notEnoughInformation=!0,ig.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length){this._notEnoughInformation=!0,ig.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();let s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){let e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);let t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=t5.Distance(t,i),this._bone1Length=t5.Distance(i,r)}else{e.computeWorldMatrix(!0);let t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;let i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=t5.Distance(i,r)}this._bone1.getRotationMatrixToRef(A.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;let t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;let e=this.targetPosition,t=this.poleTargetPosition,i=oh._TmpMats[0],r=oh._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&t5.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);let s=oh._TmpVecs[0],n=oh._TmpVecs[1],a=oh._TmpVecs[2],o=oh._TmpVecs[3],l=oh._TmpVecs[4],h=oh._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,o),o.normalize(),t5.CrossToRef(o,l,n),n.normalize(),t5.CrossToRef(o,n,a),a.normalize(),t7.FromXYZAxesToRef(a,o,n,i);let u=this._bone1Length,c=this._bone2Length,d=t5.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let p=(c*c+d*d-u*u)/(2*c*d),_=(d*d+u*u-c*c)/(2*d*u);p>1&&(p=1),_>1&&(_=1),p<-1&&(p=-1),_<-1&&(_=-1);let f=Math.acos(_),m=-Math.acos(p)-f;if(this._rightHandedSystem)t7.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),t7.RotationAxisToRef(this._bendAxis,f,r),r.multiplyToRef(i,i);else{let e=oh._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,t7.RotationAxisToRef(e,-f,r),r.multiplyToRef(i,i)}this.poleAngle&&(t7.RotationAxisToRef(o,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||t8.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),t8.FromRotationMatrixToRef(i,h),t8.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),m=this._bone2Ang*(1-this.slerpAmount)+m*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,A.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,A.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,m,A.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=m}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new t8),e.getRotationQuaternionToRef(A.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}oh._TmpVecs=[t5.Zero(),t5.Zero(),t5.Zero(),t5.Zero(),t5.Zero(),t5.Zero()],oh._TmpQuat=t8.Identity(),oh._TmpMats=[t7.Identity(),t7.Identity()];class ou{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=t5.Up(),this.upAxisSpace=A.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=t8.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=t5.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=sj.Y,t=sj.X;null!=r.yawAxis&&(e=r.yawAxis.clone()).normalize(),null!=r.pitchAxis&&(t=r.pitchAxis.clone()).normalize();let i=t5.Cross(t,e);this._transformYawPitch=t7.Identity(),t7.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=A.BONE||(this.upAxisSpace=A.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}let e=this.bone,t=ou._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target,r=ou._TmpMats[0],s=ou._TmpMats[1],n=this.mesh,a=e.getParent(),o=ou._TmpVecs[1];o.copyFrom(this.upAxis),this.upAxisSpace==A.BONE&&a?(this._transformYawPitch&&t5.TransformCoordinatesToRef(o,this._transformYawPitchInv,o),a.getDirectionToRef(o,this.mesh,o)):this.upAxisSpace==A.LOCAL&&(n.getDirectionToRef(o,o),(1!=n.scaling.x||1!=n.scaling.y||1!=n.scaling.z)&&o.normalize());let l=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(l=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),l||h){let e=ou._TmpMats[2],r=ou._TmpMats[3];if(this.upAxisSpace==A.BONE&&1==o.y&&a)a.getRotationMatrixToRef(A.WORLD,this.mesh,e);else if(this.upAxisSpace!=A.LOCAL||1!=o.y||a){let t=ou._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&t5.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),a?a.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);let i=t5.Cross(o,t);i.normalize(),t=t5.Cross(i,o),t7.FromXYZAxesToRef(i,o,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(r);let s=null;if(h){let n=ou._TmpVecs[3];i.subtractToRef(t,n),t5.TransformCoordinatesToRef(n,r,n),s=Math.sqrt(n.x*n.x+n.z*n.z);let a=Math.atan2(n.y,s),o=a;a>this._maxPitch?(n.y=this._maxPitchTan*s,o=this._maxPitch):athis._maxYaw||oMath.PI?this._isAngleBetween(a,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(a,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,l=this._minYaw):o>this._maxYaw?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):oMath.PI){let e=ou._TmpVecs[8];e.copyFrom(sj.Z),this._transformYawPitch&&t5.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);let t=ou._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),t5.TransformCoordinatesToRef(e,t,e),t5.TransformCoordinatesToRef(e,r,e);let i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,a)>this._getAngleBetween(i,this._midYawConstraint)){null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z));let e=this._getAngleBetween(i,this._maxYaw);l=this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI;let i=0;return(i=e<(t=t<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,t<(i=i<0?i+2*Math.PI:i)){if(e>t&&ei&&e0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):((!this._transformMatrices||this._isDirty)&&this.prepare(),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(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){for(let e of this.bones)if(e._linkedTransformNode){let 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(let e of this._meshesWithPoseMatrix){let t=e.getPoseMatrix(),i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){for(let i of(this._synchronizedWithMesh=e,this.bones))i.getParent()||(i.getBindMatrix().multiplyToRef(t,ie.Matrix[1]),i._updateAbsoluteBindMatrices(ie.Matrix[1]));if(this.isUsingTextureForMatrices){let t=(this.bones.length+1)*4;e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=ae.CreateRGBATexture(e._bonesTransformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))}}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=ae.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),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{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){let 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(){var e;let t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(n.animation=r.animations[0].serialize()),t.ranges=[],this._ranges){let i=this._ranges[e];if(!i)continue;let r={};r.name=e,r.from=i.from,r.to=i.to,t.ranges.push(r)}}return t}static Parse(e,t){let i;let r=new oc(e.name,e.id,t);for(e.dimensionsAtRest&&(r.dimensionsAtRest=t5.FromArray(e.dimensionsAtRest)),r.needInitialSkinMatrix=e.needInitialSkinMatrix,i=0;i-1&&(n=r.bones[t.parentBoneIndex]);let a=t.rest?t7.FromArray(t.rest):null,o=new sK(t.name,r,n,t7.FromArray(t.matrix),a,null,s);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(re.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(r._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(i=0;i0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}class od{constructor(e,t,i=3,r){this._engine=e,this._label=r,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i,r){return this._engine.readFromStorageBuffer(this._buffer,e,t,i,r)}dispose(){let e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}let op=(()=>{let e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(sf.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(sf.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(sf.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),sf.prototype._rebuild=function(){var e,t;null===(e=this._buffer)||void 0===e||e._rebuild(),null===(t=this._alignedBuffer)||void 0===t||t._rebuild()},sf.prototype.dispose=function(){var e;this._ownsBuffer&&this._buffer.dispose(),null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},sf.prototype._alignBuffer=function(){var e,t;let i,r;let s=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideMultiple4Bytes||this.byteStride%4==0||!s)return;let n=sf.GetTypeByteLength(this.type),a=this.byteStride+3&-4,o=a/n,l=this.totalVertices,h=l*a/n;if(Array.isArray(s)){let e=new Float32Array(s);i=new DataView(e.buffer,e.byteOffset,e.byteLength)}else i=s instanceof ArrayBuffer?new DataView(s,0,s.byteLength):new DataView(s.buffer,s.byteOffset,s.byteLength);r=this.type===sf.BYTE?new Int8Array(h):this.type===sf.UNSIGNED_BYTE?new Uint8Array(h):this.type===sf.SHORT?new Int16Array(h):this.type===sf.UNSIGNED_SHORT?new Uint16Array(h):this.type===sf.INT?new Int32Array(h):this.type===sf.UNSIGNED_INT?new Uint32Array(h):new Float32Array(h);let u=this.getSize(),c=this.byteOffset;for(let e=0;e{if(t.type!==sS.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===sM.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,sS.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"}}iZ([iW()],o_.prototype,"wheelPrecisionX",void 0),iZ([iW()],o_.prototype,"wheelPrecisionY",void 0),iZ([iW()],o_.prototype,"wheelPrecisionZ",void 0);class of{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=ss.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=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=>{var a,o;let l=n.event,h="touch"===l.pointerType;if(n.type!==sS.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;let u=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else if(n.type!==sS.POINTERDOWN&&h&&(null===(a=this._pointA)||void 0===a?void 0:a.pointerId)!==l.pointerId&&(null===(o=this._pointB)||void 0===o?void 0:o.pointerId)!==l.pointerId)return;else if(n.type===sS.POINTERDOWN&&(-1===this._currentActiveButton||h)){try{null==u||u.setPointerCapture(l.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else{if(null!==this._pointB)return;this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType}}-1!==this._currentActiveButton||h||(this._currentActiveButton=l.button),this.onButtonDown(l),!e&&(l.preventDefault(),i&&i.focus())}else if(n.type===sS.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(n.type===sS.POINTERUP&&(this._currentActiveButton===l.button||h)){try{null==u||u.releasePointerCapture(l.pointerId)}catch(e){}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(n.type===sS.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&null===this._pointB){let e=l.clientX-this._pointA.x,t=l.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){let e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;let t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,o={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,r,a,s,o),s=o,r=a}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,sS.POINTERDOWN|sS.POINTERUP|sS.POINTERMOVE|sS.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let n=this.camera.getScene().getEngine().getHostWindow();n&&ss.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&ss.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let 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,i){}onMultiTouch(e,t,i,r,s,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}iZ([iW()],of.prototype,"buttons",void 0);var om={};class og{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){ig.Warn("camera input of type "+t+" already exists on camera");return}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(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement)for(let t in e=!ns.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e,this.attached)this.attached[t].attachControl(e)}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){for(let e in this.checkInputs=()=>{},this.attached){let 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){let t={};for(let e in this.attached){let i=this.attached[e],r=i$.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t)for(let e in this.clear(),t){let i=om[e];if(i){let r=t[e],s=i$.Parse(()=>new i,r,null);this.add(s)}}else for(let t in this.attached){let i=om[this.attached[t].getClassName()];if(i){let r=i$.Parse(()=>new i,e,null);this.remove(this.attached[t]),this.add(r)}}}}class ov{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=1,n=2,a=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=ov.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,this._rightStickAxisX=n,this._rightStickAxisY=a,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){this._onleftstickchanged&&(this._leftStick.x!==e.x||this._leftStick.y!==e.y)&&this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){this._onrightstickchanged&&(this._rightStick.x!==e.x||this._rightStick.y!==e.y)&&this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}ov.GAMEPAD=0,ov.GENERIC=1,ov.XBOX=2,ov.POSE_ENABLED=3,ov.DUALSHOCK=4;class ox extends ov{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new tj,this.onButtonUpObservable=new tj,this.type=ov.GENERIC,this._buttons=Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type===ov.POSE_ENABLED||this.gamepad&&e.type!==ov.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(ov.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){let e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){let i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){let i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}let i=this.gamepad.leftStick;if(i&&0!=i.y){let e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}iZ([iW()],oT.prototype,"gamepadRotationSensibility",void 0),iZ([iW()],oT.prototype,"gamepadMoveSensibility",void 0),om.ArcRotateCameraGamepadInput=oT;class ob{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=[]}attachControl(e){e=ss.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=>{let i=t.event;if(!i.metaKey){if(t.type===sR.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&!e&&i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&!e&&i.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){let e=this.camera;for(let t=0;t0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)}attachControl(e){e=ss.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==sS.POINTERWHEEL)return;let i=t.event,r=0,s=i.deltaMode===sM.DOM_DELTA_LINE?40:1,n=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if((r=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius))>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=tK.Clamp(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else r=n/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,sS.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;let 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(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=sG.FromPositionAndNormal(e.target,t)}_getPosition(){var e;let t=this.camera,i=t.getScene(),r=i.createPickingRay(i.pointerX,i.pointerY,t7.Identity(),t,!1);(0!==t.targetScreenOffset.x||0!==t.targetScreenOffset.y)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=t5.TransformNormal(this._viewOffset,t._cameraTransformMatrix),r.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=null!==(e=r.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),r.origin.addInPlace(r.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;let r=this.camera,s=1-r.inertia;if(r.lowerRadiusLimit){let i=null!==(t=r.lowerRadiusLimit)&&void 0!==t?t:0;r.radius-(r.inertialRadiusOffset+e)/st&&(e=(r.radius-t)*s-r.inertialRadiusOffset)}let n=e/s/r.radius,a=this._getPosition(),o=ie.Vector3[6];a.subtractToRef(r.target,o),o.scaleInPlace(n),o.scaleInPlace(s),this._inertialPanning.addInPlace(o),r.inertialRadiusOffset+=e}_zeroIfClose(e){.001>Math.abs(e.x)&&(e.x=0),.001>Math.abs(e.y)&&(e.y=0),.001>Math.abs(e.z)&&(e.z=0)}}iZ([iW()],oE.prototype,"wheelPrecision",void 0),iZ([iW()],oE.prototype,"zoomToMouseLocation",void 0),iZ([iW()],oE.prototype,"wheelDeltaPercentage",void 0),om.ArcRotateCameraMouseWheelInput=oE;class oS extends of{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){let i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}}_computePinchZoom(e,t){let i=this.camera.radius||oS.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,r,s,n){(0!==i||null!==s)&&(0!==r||null!==n)&&(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(s,n)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,n)):this.multiTouchPanning?this._computeMultiTouchPanning(s,n):this.pinchZoom&&this._computePinchZoom(i,r))}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}}oS.MinimumRadiusForPinch=.001,iZ([iW()],oS.prototype,"buttons",void 0),iZ([iW()],oS.prototype,"angularSensibilityX",void 0),iZ([iW()],oS.prototype,"angularSensibilityY",void 0),iZ([iW()],oS.prototype,"pinchPrecision",void 0),iZ([iW()],oS.prototype,"pinchDeltaPercentage",void 0),iZ([iW()],oS.prototype,"useNaturalPinchZoom",void 0),iZ([iW()],oS.prototype,"pinchZoom",void 0),iZ([iW()],oS.prototype,"panningSensibility",void 0),iZ([iW()],oS.prototype,"multiTouchPanning",void 0),iZ([iW()],oS.prototype,"multiTouchPanAndZoom",void 0),om.ArcRotateCameraPointersInput=oS;class oC extends og{constructor(e){super(e)}addMouseWheel(){return this.add(new oE),this}addPointers(){return this.add(new oS),this}addKeyboard(){return this.add(new ob),this}}oC.prototype.addVRDeviceOrientation=function(){return this.add(new oy),this};class oy{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=ss.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);let t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):ss.Warn("Permission not granted.")}).catch(e=>{ss.Error(e)}):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}om.ArcRotateCameraVRDeviceOrientationInput=oy;class oA{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=[]}attachControl(e){e=ss.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=>{let i=t.event;if(t.type===sR.KEYDOWN)-1===this.keysForward.indexOf(i.keyCode)&&-1===this.keysBackward.indexOf(i.keyCode)&&-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t{this._pointerInput(e)},sS.POINTERDOWN|sS.POINTERUP|sS.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add(()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)})}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){let t=e.event,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType||e.type!==sS.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;let r=t.target;if(e.type===sS.POINTERDOWN){try{null==r||r.setPointerCapture(t.pointerId)}catch(e){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===sS.POINTERUP){try{null==r||r.releasePointerCapture(t.pointerId)}catch(e){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===sS.POINTERMOVE){if(!this._previousPosition){i.isPointerLock&&this._onMouseMove(e.event);return}let r=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(r,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;let t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){let i;let r=this.camera,s=r._calculateHandednessMultiplier(),n=(e*=s)/this.angularSensibility,a=t/this.angularSensibility,o=t8.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z);if(this.buttonsPitch.some(e=>e===this.activeButton)&&(i=t8.RotationAxis(sj.X,a),o.multiplyInPlace(i)),this.buttonsYaw.some(e=>e===this.activeButton)){i=t8.RotationAxis(sj.Y,n),o.multiplyInPlace(i);let e=r.bankedTurnLimit+r._trackRoll;if(r.bankedTurn&&-ee===this.activeButton)&&(i=t8.RotationAxis(sj.Z,-n),r._trackRoll-=n,o.multiplyInPlace(i)),o.toEulerAnglesToRef(r.rotation)}}iZ([iW()],oR.prototype,"buttons",void 0),iZ([iW()],oR.prototype,"angularSensibility",void 0),om.FlyCameraMouseInput=oR;class oI{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=[]}attachControl(e){e=ss.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=>{let i=t.event;if(!i.metaKey){if(t.type===sR.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&!e&&i.preventDefault());else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&!e&&i.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(){this._onKeyboardObserver&&this._keys.forEach(e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)})}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}iZ([iW()],oI.prototype,"keysHeightOffsetIncr",void 0),iZ([iW()],oI.prototype,"keysHeightOffsetDecr",void 0),iZ([iW()],oI.prototype,"keysHeightOffsetModifierAlt",void 0),iZ([iW()],oI.prototype,"keysHeightOffsetModifierCtrl",void 0),iZ([iW()],oI.prototype,"keysHeightOffsetModifierShift",void 0),iZ([iW()],oI.prototype,"keysRotationOffsetIncr",void 0),iZ([iW()],oI.prototype,"keysRotationOffsetDecr",void 0),iZ([iW()],oI.prototype,"keysRotationOffsetModifierAlt",void 0),iZ([iW()],oI.prototype,"keysRotationOffsetModifierCtrl",void 0),iZ([iW()],oI.prototype,"keysRotationOffsetModifierShift",void 0),iZ([iW()],oI.prototype,"keysRadiusIncr",void 0),iZ([iW()],oI.prototype,"keysRadiusDecr",void 0),iZ([iW()],oI.prototype,"keysRadiusModifierAlt",void 0),iZ([iW()],oI.prototype,"keysRadiusModifierCtrl",void 0),iZ([iW()],oI.prototype,"keysRadiusModifierShift",void 0),iZ([iW()],oI.prototype,"heightSensibility",void 0),iZ([iW()],oI.prototype,"rotationSensibility",void 0),iZ([iW()],oI.prototype,"radiusSensibility",void 0),om.FollowCameraKeyboardMoveInput=oI;class oP{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=ss.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==sS.POINTERWHEEL)return;let i=t.event,r=0,s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&ig.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,sS.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}iZ([iW()],oP.prototype,"axisControlRadius",void 0),iZ([iW()],oP.prototype,"axisControlHeight",void 0),iZ([iW()],oP.prototype,"axisControlRotation",void 0),iZ([iW()],oP.prototype,"wheelPrecision",void 0),iZ([iW()],oP.prototype,"wheelDeltaPercentage",void 0),om.FollowCameraMouseWheelInput=oP;class oM extends of{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,n){if(0===i&&null===s||0===r&&null===n)return;let a=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;let e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&ig.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&ig.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&ig.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}iZ([iW()],oM.prototype,"angularSensibilityX",void 0),iZ([iW()],oM.prototype,"angularSensibilityY",void 0),iZ([iW()],oM.prototype,"pinchPrecision",void 0),iZ([iW()],oM.prototype,"pinchDeltaPercentage",void 0),iZ([iW()],oM.prototype,"axisXControlRadius",void 0),iZ([iW()],oM.prototype,"axisXControlHeight",void 0),iZ([iW()],oM.prototype,"axisXControlRotation",void 0),iZ([iW()],oM.prototype,"axisYControlRadius",void 0),iZ([iW()],oM.prototype,"axisYControlHeight",void 0),iZ([iW()],oM.prototype,"axisYControlRotation",void 0),iZ([iW()],oM.prototype,"axisPinchControlRadius",void 0),iZ([iW()],oM.prototype,"axisPinchControlHeight",void 0),iZ([iW()],oM.prototype,"axisPinchControlRotation",void 0),om.FollowCameraPointersInput=oM;class oD{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=[]}attachControl(e){e=ss.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=>{let i=t.event;if(!i.metaKey){if(t.type===sR.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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){let e=this.camera;for(let t=0;t{let s=r.event,n="touch"===s.pointerType;if(!this.touchEnabled&&n||r.type!==sS.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;let a=s.target;if(r.type===sS.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==a||a.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},!e&&(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===sS.POINTERUP){if(n&&this._activePointerId!==s.pointerId||!n&&this._currentActiveButton!==s.button)return;try{null==a||a.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===sS.POINTERMOVE&&(this._activePointerId===s.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let t=this.camera._calculateHandednessMultiplier(),i=(s.clientX-this._previousPosition.x)*t,r=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=r/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:r}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;let r=this.camera._calculateHandednessMultiplier(),s=i.movementX*r;this.camera.cameraRotation.y+=s/this.angularSensibility;let n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,sS.POINTERDOWN|sS.POINTERUP|sS.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let 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"}}iZ([iW()],oO.prototype,"buttons",void 0),iZ([iW()],oO.prototype,"angularSensibility",void 0),om.FreeCameraMouseInput=oO,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(j||(j={}));class oN extends o_{constructor(){super(...arguments),this._moveRelative=t5.Zero(),this._rotateRelative=t5.Zero(),this._moveScene=t5.Zero(),this._wheelXAction=j.MoveRelative,this._wheelXActionCoordinate=R.X,this._wheelYAction=j.MoveRelative,this._wheelYActionCoordinate=R.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){(null!==e||this._wheelXAction===j.MoveRelative)&&(this._wheelXAction=j.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==j.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){(null!==e||this._wheelYAction===j.MoveRelative)&&(this._wheelYAction=j.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==j.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){(null!==e||this._wheelZAction===j.MoveRelative)&&(this._wheelZAction=j.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==j.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){(null!==e||this._wheelXAction===j.RotateRelative)&&(this._wheelXAction=j.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==j.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){(null!==e||this._wheelYAction===j.RotateRelative)&&(this._wheelYAction=j.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==j.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){(null!==e||this._wheelZAction===j.RotateRelative)&&(this._wheelZAction=j.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==j.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){(null!==e||this._wheelXAction===j.MoveScene)&&(this._wheelXAction=j.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==j.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){(null!==e||this._wheelYAction===j.MoveScene)&&(this._wheelYAction=j.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==j.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){(null!==e||this._wheelZAction===j.MoveScene)&&(this._wheelZAction=j.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==j.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);let e=t7.Zero();this.camera.getViewMatrix().invertToRef(e);let t=t5.Zero();t5.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,i){if(0===e||null===t||null===i)return;let r=null;switch(t){case j.MoveRelative:r=this._moveRelative;break;case j.RotateRelative:r=this._rotateRelative;break;case j.MoveScene:r=this._moveScene}switch(i){case R.X:r.set(e,0,0);break;case R.Y:r.set(0,e,0);break;case R.Z:r.set(0,0,e)}}}iZ([iW()],oN.prototype,"wheelXMoveRelative",null),iZ([iW()],oN.prototype,"wheelYMoveRelative",null),iZ([iW()],oN.prototype,"wheelZMoveRelative",null),iZ([iW()],oN.prototype,"wheelXRotateRelative",null),iZ([iW()],oN.prototype,"wheelYRotateRelative",null),iZ([iW()],oN.prototype,"wheelZRotateRelative",null),iZ([iW()],oN.prototype,"wheelXMoveScene",null),iZ([iW()],oN.prototype,"wheelYMoveScene",null),iZ([iW()],oN.prototype,"wheelZMoveScene",null),om.FreeCameraMouseWheelInput=oN;class oF{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=[],this._isSafari=ss.IsSafari()}attachControl(e){e=ss.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s){if(i.type===sS.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===sS.POINTERUP){e||r.preventDefault();let i=this._pointerPressed.indexOf(r.pointerId);if(-1===i||(this._pointerPressed.splice(i,1),0!=i))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===sS.POINTERMOVE){if(e||r.preventDefault(),!t||0!=this._pointerPressed.indexOf(r.pointerId))return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,sS.POINTERDOWN|sS.POINTERUP|sS.POINTERMOVE),this._onLostFocus){let 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){let 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||0===this._offsetX&&0===this._offsetY)return;let e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{let t=e._computeLocalCameraSpeed(),i=new t5(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);t7.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(t5.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}iZ([iW()],oF.prototype,"touchAngularSensibility",void 0),iZ([iW()],oF.prototype,"touchMoveSensibility",void 0),om.FreeCameraTouchInput=oF;class ow extends og{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new oD),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new oO(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new oN,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new oF),this}clear(){super.clear(),this._mouseInput=null}}ow.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new oL,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class oL{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1,s=()=>{window.removeEventListener("deviceorientation",s),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))},e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"==e?window.addEventListener("deviceorientation",s):ss.Warn("Permission not granted.")}).catch(e=>{ss.Error(e)}):window.addEventListener("deviceorientation",s)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new t8,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new tj,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-ss.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?ss.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?ss.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?ss.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new t8(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new t8),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){let e=this.camera.getScene().getEngine().getHostWindow();if(e){let t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e?t():ss.Warn("Permission not granted.")}).catch(e=>{ss.Error(e)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(t8.RotationYawPitchRollToRef(ss.ToRadians(this._alpha),ss.ToRadians(this._beta),-ss.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}om.FreeCameraDeviceOrientationInput=oL;class oB{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=t7.Identity(),this._deltaTransform=t5.Zero(),this._vector3=t5.Zero(),this._vector2=t4.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===ov.POSE_ENABLED||this.gamepad&&e.type!==ov.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(ov.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){let e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):t7.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);let r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),t5.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}iZ([iW()],oB.prototype,"gamepadAngularSensibility",void 0),iZ([iW()],oB.prototype,"gamepadMoveSensibility",void 0),om.FreeCameraGamepadInput=oB,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(K||(K={}));class oU{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;let i=Object.assign(Object.assign({},oU._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,oU._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=K.X,this._axisTargetedByUpAndDown=K.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new sl,this.deltaPosition=t5.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{oU._VJCanvasWidth=window.innerWidth,oU._VJCanvasHeight=window.innerHeight,oU.Canvas&&(oU.Canvas.width=oU._VJCanvasWidth,oU.Canvas.height=oU._VJCanvasHeight),oU._HalfWidth=oU._VJCanvasWidth/2},!oU.Canvas){window.addEventListener("resize",this._onResize,!1),oU.Canvas=document.createElement("canvas"),oU._VJCanvasWidth=window.innerWidth,oU._VJCanvasHeight=window.innerHeight,oU.Canvas.width=window.innerWidth,oU.Canvas.height=window.innerHeight,oU.Canvas.style.width="100%",oU.Canvas.style.height="100%",oU.Canvas.style.position="absolute",oU.Canvas.style.backgroundColor="transparent",oU.Canvas.style.top="0px",oU.Canvas.style.left="0px",oU.Canvas.style.zIndex="5",oU.Canvas.style.touchAction="none",oU.Canvas.setAttribute("touch-action","none");let e=oU.Canvas.getContext("2d");if(!e)throw Error("Unable to create canvas for virtual joystick");oU._VJCanvasContext=e,oU._VJCanvasContext.strokeStyle="#ffffff",oU._VJCanvasContext.lineWidth=2,document.body.appendChild(oU.Canvas)}oU._HalfWidth=oU.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&oU._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new t4(0,0),this._joystickPreviousPointerPos=new t4(0,0),this._joystickPointerStartPos=new t4(0,0),this._deltaJoystickVector=new t4(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},oU.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),oU.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),oU.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),oU.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),oU.Canvas.addEventListener("contextmenu",e=>{e.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){e.preventDefault(),(!0===this._leftJoystick?e.clientXoU._HalfWidth)&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):oU._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){let t=new t4(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){let t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){let e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?oU._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(oU._VJCanvasContext.beginPath(),oU._VJCanvasContext.strokeStyle=this._joystickColor,oU._VJCanvasContext.lineWidth=2,oU._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),oU._VJCanvasContext.stroke(),oU._VJCanvasContext.closePath(),oU._VJCanvasContext.beginPath(),oU._VJCanvasContext.lineWidth=6,oU._VJCanvasContext.strokeStyle=this._joystickColor,oU._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),oU._VJCanvasContext.stroke(),oU._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?oU._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(oU._VJCanvasContext.beginPath(),oU._VJCanvasContext.strokeStyle=this._joystickColor,oU._VJCanvasContext.lineWidth=2,oU._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),oU._VJCanvasContext.stroke(),oU._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(oU._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),oU._VJCanvasContext.beginPath(),oU._VJCanvasContext.fillStyle="white",oU._VJCanvasContext.beginPath(),oU._VJCanvasContext.strokeStyle="red",oU._VJCanvasContext.lineWidth=6,oU._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),oU._VJCanvasContext.stroke(),oU._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){oU.Canvas&&(oU.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),oU.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),oU.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),oU.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(oU.Canvas),oU.Canvas=null),this._released=!0}}oU._GlobalJoystickIndex=0,oU._AlwaysVisibleSticks=0,ow.prototype.addVirtualJoystick=function(){return this.add(new oV),this};class oV{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){let e=this.camera,t=50*e._computeLocalCameraSpeed(),i=t7.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=t5.TransformCoordinates(new t5(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new oU(!0),this._leftjoystick.setAxisForUpDown(K.Z),this._leftjoystick.setAxisForLeftRight(K.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new oU(!1),this._rightjoystick.setAxisForUpDown(K.X),this._rightjoystick.setAxisForLeftRight(K.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}om.FreeCameraVirtualJoystickInput=oV;class ok extends ns{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=t5.Zero(),this._tmpTargetVector=t5.Zero(),this.cameraDirection=new t5(0,0,0),this.cameraRotation=new t4(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new t8,this.rotation=new t5(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=t5.Zero(),this._initialFocalDistance=1,this._viewMatrix=t7.Zero(),this._camMatrix=t7.Zero(),this._cameraTransformMatrix=t7.Zero(),this._cameraRotationMatrix=t7.Zero(),this._referencePoint=new t5(0,0,1),this._transformedReferencePoint=t5.Zero(),this._deferredPositionUpdate=new t5,this._deferredRotationQuaternionUpdate=new t8,this._deferredRotationUpdate=new t5,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=t5.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();let 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){let 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 t5(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new t5(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new t8(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let 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;let 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(){let 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+=.001),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),t7.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);let 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&&t8.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){this.parent.getWorldMatrix().invertToRef(ie.Matrix[0]),t5.TransformNormalToRef(this.cameraDirection,ie.Matrix[0],ie.Vector3[0]),this._deferredPositionUpdate.addInPlace(ie.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint&&(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(t8.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)<.001*this.speed&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<.001*this.speed&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<.001*this.speed&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<.001*this.speed&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<.001*this.speed&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):t7.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return t5.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),t5.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?sj.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(t8.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),sj.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){let r=this.parent.getWorldMatrix();t5.TransformCoordinatesToRef(e,r,this._globalPosition),t5.TransformCoordinatesToRef(t,r,this._tmpTargetVector),t5.TransformNormalToRef(i,r,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?t7.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):t7.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix);return}if(this.getScene().useRightHandedSystem?t7.LookAtRHToRef(e,t,i,this._viewMatrix):t7.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){let 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!==ns.RIG_MODE_NONE){let t=new ok(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,this.cameraRigMode===ns.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new t8),t._cameraRigParams={},t.rotationQuaternion=new t8),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case ns.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case ns.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ns.RIG_MODE_STEREOSCOPIC_INTERLACED:{let i=this.cameraRigMode===ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,r=this.cameraRigMode===ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*r,t);break}case ns.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,ok._TargetFocalPoint),ok._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);let i=ok._TargetFocalPoint.addInPlace(this.position);t7.TranslationToRef(-i.x,-i.y,-i.z,ok._TargetTransformMatrix),ok._TargetTransformMatrix.multiplyToRef(t7.RotationAxis(t.upVector,e),ok._RigCamTransformMatrix),t7.TranslationToRef(i.x,i.y,i.z,ok._TargetTransformMatrix),ok._RigCamTransformMatrix.multiplyToRef(ok._TargetTransformMatrix,ok._RigCamTransformMatrix),t5.TransformCoordinatesToRef(this.position,ok._RigCamTransformMatrix,t.position),t.setTarget(i)}getClassName(){return"TargetCamera"}}ok._RigCamTransformMatrix=new t7,ok._TargetTransformMatrix=new t7,ok._TargetFocalPoint=new t5,iZ([ij()],ok.prototype,"rotation",void 0),iZ([iW()],ok.prototype,"speed",void 0),iZ([iK("lockedTargetId")],ok.prototype,"lockedTarget",void 0);class oG extends ok{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){let e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){let t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){let e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){let t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){let e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){let e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){let e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){let e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new t5(.5,1,.5),this.ellipsoidOffset=new t5(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=t5.Zero(),this._diffPosition=t5.Zero(),this._newPosition=t5.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>nC.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new ow(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=ss.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new t5(0,0,0),this.cameraRotation=new t4(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?t5.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=t5.Zero(),this._transformedDirection=t5.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"}}iZ([ij()],oG.prototype,"ellipsoid",void 0),iZ([ij()],oG.prototype,"ellipsoidOffset",void 0),iZ([iW()],oG.prototype,"checkCollisions",void 0),iZ([iW()],oG.prototype,"applyGravity",void 0),i0.AddNodeConstructor("TouchCamera",(e,t)=>()=>new oz(e,t5.Zero(),t));class oz extends oG{get touchAngularSensibility(){let e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){let e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){let e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}i0.AddNodeConstructor("ArcRotateCamera",(e,t)=>()=>new oW(e,0,0,1,t5.Zero(),t));class oW extends ok{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 t7,this._upToYMatrix=new t7,this._upVector=t5.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){t7.RotationAlignToRef(t5.UpReadOnly,this._upVector,this._yToUpMatrix),t7.RotationAlignToRef(this._upVector,t5.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let 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 ai,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 ar,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 at,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,n,a=!0){super(e,t5.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=t5.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=t4.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new t7,this.panningAxis=new t5(1,1,0),this._transformedDirection=new t5,this.mapPanning=!1,this.onMeshTargetChangedObservable=new tj,this.checkCollisions=!1,this.collisionRadius=new t5(.5,.5,.5),this._previousPosition=t5.Zero(),this._collisionVelocity=t5.Zero(),this._newPosition=t5.Zero(),this._computationVector=t5.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);let r=Math.cos(this.alpha),s=Math.sin(this.alpha),n=Math.cos(this.beta),a=Math.sin(this.beta);0===a&&(a=1e-4);let o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*a,this.radius*n,this.radius*s*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=(l=l.clone()).negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=t5.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new oC(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new t5(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=t4.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){let e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||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!!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,i=!0,r=2){let s=arguments;t=ss.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[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(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){let e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier(),i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,.001>Math.abs(this.inertialAlphaOffset)&&(this.inertialAlphaOffset=0),.001>Math.abs(this.inertialBetaOffset)&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<.001*this.speed&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){let e=new t5(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),t5.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){let e=this.upVector,t=t5.CrossToRef(this._transformedDirection,e,this._transformedDirection);t5.CrossToRef(e,t,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);!this._targetHost&&(this.panningDistanceLimit?(this._transformedDirection.addInPlace(this._target),t5.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)):this._target.addInPlace(this._transformedDirection)),this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<.001*this.speed&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<.001*this.speed&&(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.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.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)&&t5.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);let 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);let 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,i=!1,r=!1){var s;if(r=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:r,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{let t=this._getTargetPosition();if(t&&!i&&t.equals(e))return;this._targetHost=null,this._target=e,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&t5.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let 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&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=nX.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){let t=e||this.getScene().meshes;i=nX.MinMax(t),r=t5.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=nX.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case ns.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ns.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ns.RIG_MODE_STEREOSCOPIC_INTERLACED:case ns.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}let r=new oW(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case ns.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ns.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ns.RIG_MODE_STEREOSCOPIC_INTERLACED:case ns.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=t5.Distance(e,t),s=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),a=n*s,o=.5*r*i;return Math.max(o*Math.sqrt(1+1/(a*a)),o*Math.sqrt(1+1/(n*n)))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}iZ([iW()],oW.prototype,"alpha",void 0),iZ([iW()],oW.prototype,"beta",void 0),iZ([iW()],oW.prototype,"radius",void 0),iZ([iW()],oW.prototype,"overrideCloneAlphaBetaRadius",void 0),iZ([ij("target")],oW.prototype,"_target",void 0),iZ([iK("targetHost")],oW.prototype,"_targetHost",void 0),iZ([iW()],oW.prototype,"inertialAlphaOffset",void 0),iZ([iW()],oW.prototype,"inertialBetaOffset",void 0),iZ([iW()],oW.prototype,"inertialRadiusOffset",void 0),iZ([iW()],oW.prototype,"lowerAlphaLimit",void 0),iZ([iW()],oW.prototype,"upperAlphaLimit",void 0),iZ([iW()],oW.prototype,"lowerBetaLimit",void 0),iZ([iW()],oW.prototype,"upperBetaLimit",void 0),iZ([iW()],oW.prototype,"lowerRadiusLimit",void 0),iZ([iW()],oW.prototype,"upperRadiusLimit",void 0),iZ([iW()],oW.prototype,"inertialPanningX",void 0),iZ([iW()],oW.prototype,"inertialPanningY",void 0),iZ([iW()],oW.prototype,"pinchToPanMaxDistance",void 0),iZ([iW()],oW.prototype,"panningDistanceLimit",void 0),iZ([ij()],oW.prototype,"panningOriginTarget",void 0),iZ([iW()],oW.prototype,"panningInertia",void 0),iZ([iW()],oW.prototype,"zoomToMouseLocation",null),iZ([iW()],oW.prototype,"zoomOnFactor",void 0),iZ([iG(4,void 0)],oW.prototype,"targetScreenOffset",void 0),iZ([iW()],oW.prototype,"allowUpsideDown",void 0),iZ([iW()],oW.prototype,"useInputToRestoreState",void 0),i0.AddNodeConstructor("DeviceOrientationCamera",(e,t)=>()=>new oH(e,t5.Zero(),t));class oH extends oG{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new t8,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new t8,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add(e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new t8),t8.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))}))})}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=sj.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new t8),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class oX extends og{constructor(e){super(e)}addKeyboard(){return this.add(new oA),this}addMouse(){return this.add(new oR),this}}class oY extends ok{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){let e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){let t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){let e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){let t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new t5(1,1,1),this.ellipsoidOffset=new t5(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=t5.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=t5.Zero(),this._diffPosition=t5.Zero(),this._newPosition=t5.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>nC.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new oX(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=ss.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new t5(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?t5.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=t5.Zero(),this._transformedDirection=t5.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()}restoreRoll(e){let t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,.001>=Math.abs(t-this.rotation.z)&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}iZ([ij()],oY.prototype,"ellipsoid",void 0),iZ([ij()],oY.prototype,"ellipsoidOffset",void 0),iZ([iW()],oY.prototype,"checkCollisions",void 0),iZ([iW()],oY.prototype,"applyGravity",void 0);class oj extends og{constructor(e){super(e)}addKeyboard(){return this.add(new oI),this}addMouseWheel(){return this.add(new oP),this}addPointers(){return this.add(new oM),this}addVRDeviceOrientation(){return ig.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}i0.AddNodeConstructor("FollowCamera",(e,t)=>()=>new oK(e,t5.Zero(),t)),i0.AddNodeConstructor("ArcFollowCamera",(e,t)=>()=>new o$(e,0,0,1,null,t));class oK extends ok{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new oj(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;let t=ie.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);let i=Math.atan2(t.m[8],t.m[10]),r=ss.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),n=s.x+Math.sin(r)*this.radius,a=s.z+Math.cos(r)*this.radius,o=n-this.position.x,l=s.y+this.heightOffset-this.position.y,h=a-this.position.z,u=o*this.cameraAcceleration*2,c=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new t5(this.position.x+u,this.position.y+c,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=ss.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}iZ([iW()],oK.prototype,"radius",void 0),iZ([iW()],oK.prototype,"lowerRadiusLimit",void 0),iZ([iW()],oK.prototype,"upperRadiusLimit",void 0),iZ([iW()],oK.prototype,"rotationOffset",void 0),iZ([iW()],oK.prototype,"lowerRotationOffsetLimit",void 0),iZ([iW()],oK.prototype,"upperRotationOffsetLimit",void 0),iZ([iW()],oK.prototype,"heightOffset",void 0),iZ([iW()],oK.prototype,"lowerHeightOffsetLimit",void 0),iZ([iW()],oK.prototype,"upperHeightOffsetLimit",void 0),iZ([iW()],oK.prototype,"cameraAcceleration",void 0),iZ([iW()],oK.prototype,"maxCameraSpeed",void 0),iZ([iK("lockedTargetId")],oK.prototype,"lockedTarget",void 0);class o$ extends ok{constructor(e,t,i,r,s,n){super(e,t5.Zero(),n),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=t5.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);let e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}(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.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"})($||($={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(q||(q={}));class oq extends ov{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new tj,this.onButtonUpObservable=new tj,this.onPadDownObservable=new tj,this.onPadUpObservable=new tj,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=ov.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,$.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,$.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,$.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,$.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,$.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,$.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,$.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,$.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,$.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,$.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,q.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,q.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,q.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,q.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}(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.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"})(Q||(Q={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(Z||(Z={}));class oQ extends ov{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new tj,this.onButtonUpObservable=new tj,this.onPadDownObservable=new tj,this.onPadUpObservable=new tj,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=ov.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,Q.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,Q.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,Q.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,Q.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,Q.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,Q.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,Q.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,Q.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,Q.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,Q.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,Z.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,Z.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,Z.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,Z.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class oZ{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new tj,this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new tj(e=>{for(let t in this._babylonGamepads){let i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}}),this._onGamepadConnectedEvent=e=>{let t;let i=e.gamepad;i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected||(this._babylonGamepads[i.index]?((t=this._babylonGamepads[i.index]).browserGamepad=i,t._isConnected=!0):t=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(t),this._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=e=>{let t=e.gamepad;for(let e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){let t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport){if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){let e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}}get gamepads(){return this._babylonGamepads}getGamepadByType(e=ov.XBOX){for(let t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(e=>{e.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);let i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new oq(e.id,e.index,e,r):i?new oQ(e.id,e.index,e):new ox(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){for(let e in this._updateGamepadObjects(),this._babylonGamepads){let t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch(e){-1===this._loggedErrors.indexOf(t.index)&&(ss.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&nC.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new o0(e,t5.Zero(),t));class o0 extends oz{get gamepadAngularSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}ns._CreateDefaultParsedCamera=(e,t)=>new o0(e,t5.Zero(),t),i0.AddNodeConstructor("GamepadCamera",(e,t)=>()=>new o1(e,t5.Zero(),t));class o1 extends o0{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}let o2=`varying vec2 vUV;uniform samplerCube textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 uv=vUV*2.0-1.0; +#ifdef POSITIVEX +gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); +#endif +#ifdef NEGATIVEX +gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); +#endif +#ifdef POSITIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); +#endif +#ifdef NEGATIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); +#endif +#ifdef POSITIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); +#endif +#ifdef NEGATIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); +#endif +}`;rO.ShadersStore.passCubePixelShader=o2;class o3 extends aL{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,n,a=0,o=!1){super(e,"pass",null,null,t,i,r,s,n,void 0,a,void 0,null,o)}static _Parse(e,t,i,r){return i$.Parse(()=>new o3(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}}t0["BABYLON.PassPostProcess"]=o3,nC._RescalePostProcessFactory=e=>new o3("rescale",1,null,2,e,!1,0);let o4=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;rO.ShadersStore.anaglyphPixelShader=o4;class o5 extends aL{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}function o6(e){e._rigCameras[0]._rigPostProcess=new o3(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new o5(e.name+"_anaglyph",1,e._rigCameras)}t0["BABYLON.AnaglyphPostProcess"]=o5,i0.AddNodeConstructor("AnaglyphArcRotateCamera",(e,t,i)=>()=>new o8(e,0,0,1,t5.Zero(),i.interaxial_distance,t));class o8 extends oW{constructor(e,t,i,r,s,n,a){super(e,t,i,r,s,a),this._setRigMode=()=>o6(this),this.interaxialDistance=n,this.setCameraRigMode(ns.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}i0.AddNodeConstructor("AnaglyphFreeCamera",(e,t,i)=>()=>new o7(e,t5.Zero(),i.interaxial_distance,t));class o7 extends oG{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>o6(this),this.interaxialDistance=i,this.setCameraRigMode(ns.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}i0.AddNodeConstructor("AnaglyphGamepadCamera",(e,t,i)=>()=>new o9(e,t5.Zero(),i.interaxial_distance,t));class o9 extends o1{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>o6(this),this.interaxialDistance=i,this.setCameraRigMode(ns.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}i0.AddNodeConstructor("AnaglyphUniversalCamera",(e,t,i)=>()=>new le(e,t5.Zero(),i.interaxial_distance,t));class le extends o0{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>o6(this),this.interaxialDistance=i,this.setCameraRigMode(ns.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}let lt=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; +#ifdef IS_STEREOSCOPIC_HORIZ +useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); +#else +#ifdef IS_STEREOSCOPIC_INTERLACED +float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); +#else +useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); +#endif +#endif +if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} +gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} +`;rO.ShadersStore.stereoscopicInterlacePixelShader=lt;class li extends aL{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,n,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,n,a,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new t4(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new t4(1/this.width,1/this.height)}),this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}function lr(e){let t=e.cameraRigMode===ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===ns.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new o3(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new li(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new nr(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new nr(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}i0.AddNodeConstructor("StereoscopicArcRotateCamera",(e,t,i)=>()=>new ls(e,0,0,1,t5.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class ls extends oW{constructor(e,t,i,r,s,n,a,o){super(e,t,i,r,s,o),this._setRigMode=()=>lr(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=a,this.setCameraRigMode(a?ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ns.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}i0.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new ln(e,t5.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class ln extends oG{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>lr(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ns.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}i0.AddNodeConstructor("StereoscopicGamepadCamera",(e,t,i)=>()=>new la(e,t5.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class la extends o1{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>lr(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ns.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}i0.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new lo(e,t5.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class lo extends o0{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>lr(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?ns.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:ns.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}i0.AddNodeConstructor("VirtualJoysticksCamera",(e,t)=>()=>new ll(e,t5.Zero(),t));class ll extends oG{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class lh{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){let e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return t7.Translation(e,0,0)}get rightHMatrix(){let e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return t7.Translation(-e,0,0)}get leftPreViewMatrix(){return t7.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return t7.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){let e=new lh;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}let lu=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; +float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) +gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;rO.ShadersStore.vrDistortionCorrectionPixelShader=lu;class lc extends aL{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,n6.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new t4(2,2/this.aspectRatio),this._scaleFactor=new t4(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new t4(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)}),this.onApplyObservable.add(e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}}let ld=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;rO.ShadersStore.vrMultiviewToSingleviewPixelShader=ld;class lp extends a5{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function l_(e,t){let i=new sp(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}nC.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){let s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";let n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=s.createFramebuffer();let a=new rU(this,m.Unknown,!0);return a.width=e,a.height=t,a.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),n._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=r,a.isReady=!0,n.setTextures(a),n._depthStencilTexture=a,n},nC.prototype.bindMultiviewFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"},nC.prototype.bindSpaceWarpFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw Error("Invalid Space Warp framebuffer")},ns.prototype._useMultiviewToSingleView=!1,ns.prototype._multiviewTexture=null,ns.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=e||this._multiviewTexture.getRenderHeight()!=t)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new lp(this.getScene(),{width:e,height:t})):this._multiviewTexture=new lp(this.getScene(),{width:e,height:t})};let lf=sY.prototype.createSceneUniformBuffer;sY.prototype._transformMatrixR=t7.Zero(),sY.prototype._multiviewSceneUbo=null,sY.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=l_(this.getEngine(),"scene_multiview")},sY.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?l_(this.getEngine(),e):lf.bind(this)(e)},sY.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,ie.Matrix[0]),sz.GetRightPlaneToRef(ie.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},sY.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{}),this.onApplyObservable.add(e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)})}}function lg(e,t){let i=t.vrCameraMetrics||lh.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new nr(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new t7,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new nr(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new t7,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new lm("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(ig.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new lc("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new lc("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}i0.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(e,t)=>()=>new lv(e,0,0,1,t5.Zero(),t));class lv extends oW{constructor(e,t,i,r,s,n,a=!0,o=lh.GetDefault()){super(e,t,i,r,s,n),this._setRigMode=e=>lg(this,e),o.compensateDistortion=a,this.setCameraRigMode(ns.RIG_MODE_VR,{vrCameraMetrics:o}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}i0.AddNodeConstructor("VRDeviceOrientationFreeCamera",(e,t)=>()=>new lx(e,t5.Zero(),t));class lx extends oH{constructor(e,t,i,r=!0,s=lh.GetDefault()){super(e,t,i),this._setRigMode=e=>lg(this,e),s.compensateDistortion=r,this.setCameraRigMode(ns.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}i0.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(e,t)=>()=>new lT(e,t5.Zero(),t));class lT extends lx{constructor(e,t,i,r=!0,s=lh.GetDefault()){super(e,t,i,r,s),this._setRigMode=e=>lg(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class lb{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}class lE{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,nC.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,nC.MarkAllMaterialsAsDirty(1))}}lE._DiffuseTextureEnabled=!0,lE._DetailTextureEnabled=!0,lE._DecalMapEnabled=!0,lE._AmbientTextureEnabled=!0,lE._OpacityTextureEnabled=!0,lE._ReflectionTextureEnabled=!0,lE._EmissiveTextureEnabled=!0,lE._SpecularTextureEnabled=!0,lE._BumpTextureEnabled=!0,lE._LightmapTextureEnabled=!0,lE._RefractionTextureEnabled=!0,lE._ColorGradingTextureEnabled=!0,lE._FresnelEnabled=!0,lE._ClearCoatTextureEnabled=!0,lE._ClearCoatBumpTextureEnabled=!0,lE._ClearCoatTintTextureEnabled=!0,lE._SheenTextureEnabled=!0,lE._AnisotropicTextureEnabled=!0,lE._ThicknessTextureEnabled=!0,lE._RefractionIntensityTextureEnabled=!0,lE._TranslucencyIntensityTextureEnabled=!0,lE._IridescenceTextureEnabled=!0;let lS=`#ifdef DECAL +uniform vec4 vDecalInfos; +#endif +`;rO.IncludesShadersStore.decalFragmentDeclaration=lS;let lC=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +#ifdef SPECULARTERM +uniform vec4 vSpecularColor; +#endif +uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef ALPHATEST +uniform float alphaCutOff; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFRACTION +uniform vec4 vRefractionInfos; +#ifndef REFRACTIONMAP_3D +uniform mat4 refractionMatrix; +#endif +#ifdef REFRACTIONFRESNEL +uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; +#endif +#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos; +#endif +#ifdef DIFFUSEFRESNEL +uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; +#endif +#ifdef OPACITYFRESNEL +uniform vec4 opacityParts; +#endif +#ifdef EMISSIVEFRESNEL +uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) +uniform mat4 reflectionMatrix; +#endif +#ifndef REFLECTIONMAP_SKYBOX +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include +#define ADDITIONAL_FRAGMENT_DECLARATION +`;rO.IncludesShadersStore.defaultFragmentDeclaration=lC;let ly=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +mat4 view;mat4 projection;vec4 vEyePosition;}; +`;rO.IncludesShadersStore.sceneUboDeclaration=ly;let lA=`#ifdef WEBGL2 +uniform mat4 world;uniform float visibility; +#else +layout(std140,column_major) uniform;uniform Mesh +{mat4 world;float visibility;}; +#endif +#define WORLD_UBO +`;rO.IncludesShadersStore.meshUboDeclaration=lA;let lR=`layout(std140,column_major) uniform;uniform Material +{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; +#define ADDITIONAL_UBO_DECLARATION +}; +#include +#include +`;rO.IncludesShadersStore.defaultUboDeclaration=lR;let lI=`#ifdef PREPASS +#extension GL_EXT_draw_buffers : require +layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; +#ifdef PREPASS_DEPTH +varying highp vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; +#endif +#endif +`;rO.IncludesShadersStore.prePassDeclaration=lI;let lP=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +#extension GL_EXT_draw_buffers : require +layout(location=0) out vec2 depth; +layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; +#define MAX_DEPTH 99999.0 +highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; +#endif +`;rO.IncludesShadersStore.oitDeclaration=lP;let lM=`#ifdef MAINUV{X} +varying vec2 vMainUV{X}; +#endif +`;rO.IncludesShadersStore.mainUVVaryingDeclaration=lM;let lD=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; +const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; +#define saturate(x) clamp(x,0.0,1.0) +#define absEps(x) abs(x)+Epsilon +#define maxEps(x) max(x,Epsilon) +#define saturateEps(x) clamp(x,Epsilon,1.0) +mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( +vec3(i0.x,i1.x,i2.x), +vec3(i0.y,i1.y,i2.y), +vec3(i0.z,i1.z,i2.z) +);return outMatrix;} +mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), +b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), +b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} +#if USE_EXACT_SRGB_CONVERSIONS +vec3 toLinearSpaceExact(vec3 color) +{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); +#else +return +vec3( +color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, +color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, +color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); +#endif +} +vec3 toGammaSpaceExact(vec3 color) +{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); +#else +return +vec3( +color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, +color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, +color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); +#endif +} +#endif +float toLinearSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; +#else +return pow(color,LinearEncodePowerApprox); +#endif +} +vec3 toLinearSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toLinearSpaceExact(color); +#else +return pow(color,vec3(LinearEncodePowerApprox)); +#endif +} +vec4 toLinearSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toLinearSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); +#endif +} +float toGammaSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; +#else +return pow(color,GammaEncodePowerApprox); +#endif +} +vec3 toGammaSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toGammaSpaceExact(color); +#else +return pow(color,vec3(GammaEncodePowerApprox)); +#endif +} +vec4 toGammaSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toGammaSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); +#endif +} +float square(float value) +{return value*value;} +vec3 square(vec3 value) +{return value*value;} +float pow5(float value) {float sq=value*value;return sq*sq*value;} +float getLuminance(vec3 color) +{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} +float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} +float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} +const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } +vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} +vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} +`;rO.IncludesShadersStore.helperFunctions=lD;let lO=`#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; +#endif +#endif +`;rO.IncludesShadersStore.lightFragmentDeclaration=lO;let lN=`#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;rO.IncludesShadersStore.lightUboDeclaration=lN;let lF=`struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef NDOTL +float ndl; +#endif +};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) +{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} +else +{lightVectorW=normalize(-lightData.xyz);} +float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) +{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +result.diffuse=vec3(0.); +#ifdef SPECULARTERM +result.specular=vec3(0.); +#endif +#ifdef NDOTL +result.ndl=0.; +#endif +return result;} +lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=mix(groundColor,diffuseColor,ndl); +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; +#endif +return result;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;rO.IncludesShadersStore.lightsFragmentFunctions=lF;let lw=`#ifdef SHADOWS +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +#ifndef SHADOWFLOAT +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} +#endif +float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) +{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} +#define inline +float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadow=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadow=textureCube(shadowSampler,directionToLight).x; +#endif +return depth>shadow ? darkness : 1.0;} +#define inline +float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); +#ifndef SHADOWFLOAT +if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} +#endif +#define inline +float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} +#define inline +float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); +#ifndef SHADOWFLOAT +if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#ifdef IS_NDC_HALF_ZRANGE +#define ZINCLIP clipSpace.z +#else +#define ZINCLIP uvDepth.z +#endif +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define GREATEST_LESS_THAN_ONE 0.99999994 +/* disable_uniformity_analysis */ +#define inline +float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +const vec3 PoissonSamplers32[64]=vec3[64]( +vec3(0.06407013,0.05409927,0.), +vec3(0.7366577,0.5789394,0.), +vec3(-0.6270542,-0.5320278,0.), +vec3(-0.4096107,0.8411095,0.), +vec3(0.6849564,-0.4990818,0.), +vec3(-0.874181,-0.04579735,0.), +vec3(0.9989998,0.0009880066,0.), +vec3(-0.004920578,-0.9151649,0.), +vec3(0.1805763,0.9747483,0.), +vec3(-0.2138451,0.2635818,0.), +vec3(0.109845,0.3884785,0.), +vec3(0.06876755,-0.3581074,0.), +vec3(0.374073,-0.7661266,0.), +vec3(0.3079132,-0.1216763,0.), +vec3(-0.3794335,-0.8271583,0.), +vec3(-0.203878,-0.07715034,0.), +vec3(0.5912697,0.1469799,0.), +vec3(-0.88069,0.3031784,0.), +vec3(0.5040108,0.8283722,0.), +vec3(-0.5844124,0.5494877,0.), +vec3(0.6017799,-0.1726654,0.), +vec3(-0.5554981,0.1559997,0.), +vec3(-0.3016369,-0.3900928,0.), +vec3(-0.5550632,-0.1723762,0.), +vec3(0.925029,0.2995041,0.), +vec3(-0.2473137,0.5538505,0.), +vec3(0.9183037,-0.2862392,0.), +vec3(0.2469421,0.6718712,0.), +vec3(0.3916397,-0.4328209,0.), +vec3(-0.03576927,-0.6220032,0.), +vec3(-0.04661255,0.7995201,0.), +vec3(0.4402924,0.3640312,0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.) +);const vec3 PoissonSamplers64[64]=vec3[64]( +vec3(-0.613392,0.617481,0.), +vec3(0.170019,-0.040254,0.), +vec3(-0.299417,0.791925,0.), +vec3(0.645680,0.493210,0.), +vec3(-0.651784,0.717887,0.), +vec3(0.421003,0.027070,0.), +vec3(-0.817194,-0.271096,0.), +vec3(-0.705374,-0.668203,0.), +vec3(0.977050,-0.108615,0.), +vec3(0.063326,0.142369,0.), +vec3(0.203528,0.214331,0.), +vec3(-0.667531,0.326090,0.), +vec3(-0.098422,-0.295755,0.), +vec3(-0.885922,0.215369,0.), +vec3(0.566637,0.605213,0.), +vec3(0.039766,-0.396100,0.), +vec3(0.751946,0.453352,0.), +vec3(0.078707,-0.715323,0.), +vec3(-0.075838,-0.529344,0.), +vec3(0.724479,-0.580798,0.), +vec3(0.222999,-0.215125,0.), +vec3(-0.467574,-0.405438,0.), +vec3(-0.248268,-0.814753,0.), +vec3(0.354411,-0.887570,0.), +vec3(0.175817,0.382366,0.), +vec3(0.487472,-0.063082,0.), +vec3(-0.084078,0.898312,0.), +vec3(0.488876,-0.783441,0.), +vec3(0.470016,0.217933,0.), +vec3(-0.696890,-0.549791,0.), +vec3(-0.149693,0.605762,0.), +vec3(0.034211,0.979980,0.), +vec3(0.503098,-0.308878,0.), +vec3(-0.016205,-0.872921,0.), +vec3(0.385784,-0.393902,0.), +vec3(-0.146886,-0.859249,0.), +vec3(0.643361,0.164098,0.), +vec3(0.634388,-0.049471,0.), +vec3(-0.688894,0.007843,0.), +vec3(0.464034,-0.188818,0.), +vec3(-0.440840,0.137486,0.), +vec3(0.364483,0.511704,0.), +vec3(0.034028,0.325968,0.), +vec3(0.099094,-0.308023,0.), +vec3(0.693960,-0.366253,0.), +vec3(0.678884,-0.204688,0.), +vec3(0.001801,0.780328,0.), +vec3(0.145177,-0.898984,0.), +vec3(0.062655,-0.611866,0.), +vec3(0.315226,-0.604297,0.), +vec3(-0.780145,0.486251,0.), +vec3(-0.371868,0.882138,0.), +vec3(0.200476,0.494430,0.), +vec3(-0.494552,-0.711051,0.), +vec3(0.612476,0.705252,0.), +vec3(-0.578845,-0.768792,0.), +vec3(-0.772454,-0.090976,0.), +vec3(0.504440,0.372295,0.), +vec3(0.155736,0.065157,0.), +vec3(0.391522,0.849605,0.), +vec3(-0.620106,-0.328104,0.), +vec3(0.789239,-0.419965,0.), +vec3(-0.545396,0.538133,0.), +vec3(-0.178564,-0.596057,0.) +); +#define inline +float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) +#endif +#if defined(DETAIL) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) +#endif +#if defined(BUMP) && defined(PARALLAX) +const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; icurrRayHeight) +{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} +else +{currRayHeight-=stepSize;vLastOffset=vCurrOffset; +#ifdef PARALLAX_RHS +vCurrOffset-=stepSize*vMaxOffset; +#else +vCurrOffset+=stepSize*vMaxOffset; +#endif +lastSampledHeight=currSampledHeight;}} +return vCurrOffset;} +vec2 parallaxOffset(vec3 viewDir,float heightScale) +{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; +#ifdef PARALLAX_RHS +return texCoordOffset; +#else +return -texCoordOffset; +#endif +} +#endif +`;rO.IncludesShadersStore.bumpFragmentFunctions=lz;let lW=`#ifdef CLIPPLANE +varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +varying float fClipDistance6; +#endif +`;rO.IncludesShadersStore.clipPlaneFragmentDeclaration=lW;let lH=`#ifdef LOGARITHMICDEPTH +uniform float logarithmicDepthConstant;varying float vFragmentDepth; +#endif +`;rO.IncludesShadersStore.logDepthDeclaration=lH;let lX=`#ifdef FOG +#define FOGMODE_NONE 0. +#define FOGMODE_EXP 1. +#define FOGMODE_EXP2 2. +#define FOGMODE_LINEAR 3. +#define E 2.71828 +uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() +{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) +{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} +else if (FOGMODE_EXP==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} +else if (FOGMODE_EXP2==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} +return clamp(fogCoeff,0.0,1.0);} +#endif +`;rO.IncludesShadersStore.fogFragmentDeclaration=lX;let lY=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fClipDistance6>0.0) +{discard;} +#endif +`;rO.IncludesShadersStore.clipPlaneFragment=lY;let lj=`vec2 uvOffset=vec2(0.0,0.0); +#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) +#ifdef NORMALXYSCALE +float normalScale=1.0; +#elif defined(BUMP) +float normalScale=vBumpInfos.y; +#else +float normalScale=1.0; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#elif defined(BUMP) +vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); +#else +vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#elif defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#else +vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#endif +#ifdef PARALLAX +mat3 invTBN=transposeMat3(TBN); +#ifdef PARALLAXOCCLUSION +uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); +#else +uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); +#endif +#endif +#ifdef DETAIL +vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); +#endif +#ifdef BUMP +#ifdef OBJECTSPACE_NORMALMAP +#define CUSTOM_FRAGMENT_BUMP_FRAGMENT +normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); +#elif !defined(DETAIL) +normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); +#else +vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; +#if DETAIL_NORMALBLENDMETHOD==0 +detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); +#elif DETAIL_NORMALBLENDMETHOD==1 +detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; +#endif +normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); +#endif +#elif defined(DETAIL) +detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); +#endif +`;rO.IncludesShadersStore.bumpFragment=lj;let lK=`#ifdef DECAL +#ifdef GAMMADECAL +decalColor.rgb=toLinearSpace(decalColor.rgb); +#endif +#ifdef DECAL_SMOOTHALPHA +decalColor.a*=decalColor.a; +#endif +surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); +#endif +`;rO.IncludesShadersStore.decalFragment=lK;let l$=`#ifdef DEPTHPREPASS +gl_FragColor=vec4(0.,0.,0.,1.0);return; +#endif +`;rO.IncludesShadersStore.depthPrePass=l$;let lq=`#ifdef LIGHT{X} +#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) +#else +#ifdef PBR +#ifdef SPOTLIGHT{X} +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(POINTLIGHT{X}) +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(HEMILIGHT{X}) +preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(DIRLIGHT{X}) +preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#endif +preInfo.NdotV=NdotV; +#ifdef SPOTLIGHT{X} +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#endif +#elif defined(POINTLIGHT{X}) +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); +#endif +#else +preInfo.attenuation=1.0; +#endif +#ifdef HEMILIGHT{X} +preInfo.roughness=roughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#ifdef IRIDESCENCE +preInfo.iridescenceIntensity=iridescenceIntensity; +#endif +#ifdef HEMILIGHT{X} +info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); +#elif defined(SS_TRANSLUCENCY) +info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); +#else +info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); +#endif +#ifdef SPECULARTERM +#ifdef ANISOTROPIC +info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#else +info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#endif +#endif +#ifdef SHEEN +#ifdef SHEEN_LINKWITHALBEDO +preInfo.roughness=sheenOut.sheenIntensity; +#else +#ifdef HEMILIGHT{X} +preInfo.roughness=sheenOut.sheenRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#endif +info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#endif +#ifdef CLEARCOAT +#ifdef HEMILIGHT{X} +preInfo.roughness=clearcoatOut.clearCoatRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); +#ifdef CLEARCOAT_TINT +absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; +#ifdef SPECULARTERM +info.specular*=absorption; +#endif +#endif +info.diffuse*=info.clearCoat.w; +#ifdef SPECULARTERM +info.specular*=info.clearCoat.w; +#endif +#ifdef SHEEN +info.sheen*=info.clearCoat.w; +#endif +#endif +#else +#ifdef SPOTLIGHT{X} +info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); +#elif defined(HEMILIGHT{X}) +info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); +#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) +info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); +#endif +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); +#endif +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +for (int i=0; i=0.) {index{X}=i;break;}} +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +if (index{X}>=0) +#endif +{ +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; +#endif +#ifndef SHADOWCSMNOBLEND{X} +float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) +{index{X}+=1;float nextShadow=0.; +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +shadow=mix(nextShadow,shadow,diffRatio); +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); +#endif +} +#endif +} +#elif defined(SHADOWCLOSEESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPOISSON{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#else +#if defined(SHADOWCUBE{X}) +shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#endif +#ifdef SHADOWONLY +#ifndef SHADOWINUSE +#define SHADOWINUSE +#endif +globalShadow+=shadow;shadowLightCount+=1.0; +#endif +#else +shadow=1.; +#endif +aggShadow+=shadow;numLights+=1.0; +#ifndef SHADOWONLY +#ifdef CUSTOMUSERLIGHTING +diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); +#ifdef SPECULARTERM +specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); +#endif +#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) +diffuseBase+=lightmapColor.rgb*shadow; +#ifdef SPECULARTERM +#ifndef LIGHTMAPNOSPECULAR{X} +specularBase+=info.specular*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef CLEARCOAT +#ifndef LIGHTMAPNOSPECULAR{X} +clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef SHEEN +#ifndef LIGHTMAPNOSPECULAR{X} +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#else +#ifdef SHADOWCSMDEBUG{X} +diffuseBase+=info.diffuse*shadowDebug{X}; +#else +diffuseBase+=info.diffuse*shadow; +#endif +#ifdef SPECULARTERM +specularBase+=info.specular*shadow; +#endif +#ifdef CLEARCOAT +clearCoatBase+=info.clearCoat.rgb*shadow; +#endif +#ifdef SHEEN +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#endif +#endif +`;rO.IncludesShadersStore.lightFragment=lq;let lQ=`#ifdef LOGARITHMICDEPTH +gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; +#endif +`;rO.IncludesShadersStore.logDepthFragment=lQ;let lZ=`#ifdef FOG +float fog=CalcFogFactor(); +#ifdef PBR +fog=toLinearSpace(fog); +#endif +color.rgb=mix(vFogColor,color.rgb,fog); +#endif +`;rO.IncludesShadersStore.fogFragment=lZ;let lJ=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +float fragDepth=gl_FragCoord.z; +#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS +uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; +#endif +ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); +#ifdef USE_REVERSE_DEPTHBUFFER +float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; +#else +float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; +#endif +float alphaMultiplier=1.0-lastFrontColor.a; +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepth>nearestDepth || fragDepthfurthestDepth) { +#endif +return;} +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepthfurthestDepth) { +#else +if (fragDepth>nearestDepth && fragDepth +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +#include[SCENE_MRT_COUNT] +#include +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include[1..7] +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef REFRACTION +#ifdef REFRACTIONMAP_3D +uniform samplerCube refractionCubeSampler; +#else +uniform sampler2D refraction2DSampler; +#endif +#endif +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) +#endif +#include +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +uniform samplerCube reflectionCubeSampler; +#else +uniform sampler2D reflection2DSampler; +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); +#endif +#include +#ifdef TWOSIDEDLIGHTING +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +#ifdef DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); +#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) +if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +#ifdef DETAIL +baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); +#endif +#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE +vec3 baseAmbientColor=vec3(1.,1.,1.); +#ifdef AMBIENT +baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; +#endif +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; +#ifdef SPECULAR +vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; +#ifdef GLOSSINESS +glossiness=glossiness*specularMapColor.a; +#endif +#endif +#else +float glossiness=0.; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +float shadow=1.;float aggShadow=0.;float numLights=0.; +#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +#include[0..maxSimultaneousLights] +aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); +#ifdef REFRACTION +vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); +#ifdef REFRACTIONMAP_3D +#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); +#endif +#ifdef RGBDREFRACTION +refractionColor.rgb=fromRGBD(refractionColor); +#endif +#ifdef IS_REFRACTION_LINEAR +refractionColor.rgb=toGammaSpace(refractionColor.rgb); +#endif +refractionColor.rgb*=vRefractionInfos.x; +#endif +vec4 reflectionColor=vec4(0.,0.,0.,1.); +#ifdef REFLECTION +vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +vReflectionUVW.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +#ifdef ROUGHNESS +float bias=vReflectionInfos.y; +#ifdef SPECULARTERM +#ifdef SPECULAR +#ifdef GLOSSINESS +bias*=(1.0-specularMapColor.a); +#endif +#endif +#endif +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); +#else +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); +#endif +#else +vec2 coords=vReflectionUVW.xy; +#ifdef REFLECTIONMAP_PROJECTION +coords/=vReflectionUVW.z; +#endif +coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef IS_REFLECTION_LINEAR +reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#ifdef REFLECTIONFRESNEL +float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); +#ifdef REFLECTIONFRESNELFROMSPECULAR +#ifdef SPECULARTERM +reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#endif +#endif +#ifdef REFRACTIONFRESNEL +float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#ifdef OPACITYRGB +opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; +#else +alpha*=opacityMap.a*vOpacityInfos.y; +#endif +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef OPACITYFRESNEL +float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; +#endif +#ifdef ALPHATEST +#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS +if (alpha +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +color.rgb=toLinearSpace(color.rgb); +#else +#ifdef IMAGEPROCESSING +color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); +#endif +#endif +color.a*=visibility; +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_IRRADIANCE +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#if defined(SPECULARTERM) +#if defined(SPECULAR) +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; +#endif +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=color; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} +#endif +#define CUSTOM_FRAGMENT_MAIN_END +} +`;rO.ShadersStore.defaultPixelShader=l0;let l1=`#ifdef DECAL +uniform vec4 vDecalInfos;uniform mat4 decalMatrix; +#endif +`;rO.IncludesShadersStore.decalVertexDeclaration=l1;let l2=`uniform mat4 viewProjection;uniform mat4 view; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef REFLECTION +uniform mat4 reflectionMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include +#define ADDITIONAL_VERTEX_DECLARATION +`;rO.IncludesShadersStore.defaultVertexDeclaration=l2;let l3=`#ifdef UV{X} +attribute vec2 uv{X}; +#endif +`;rO.IncludesShadersStore.uvAttributeDeclaration=l3;let l4=`#if NUM_BONE_INFLUENCERS>0 +attribute vec4 matricesIndices;attribute vec4 matricesWeights; +#if NUM_BONE_INFLUENCERS>4 +attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +uniform highp sampler2D boneSampler;uniform float boneTextureWidth; +#else +uniform mat4 mBones[BonesPerMesh]; +#endif +#ifdef BONES_VELOCITY_ENABLED +uniform mat4 mPreviousBones[BonesPerMesh]; +#endif +#ifdef BONETEXTURE +#define inline +mat4 readMatrixFromRawSampler(sampler2D smp,float index) +{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} +#endif +#endif +#endif +`;rO.IncludesShadersStore.bonesDeclaration=l4;let l5=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; +#ifdef INSTANCES +attribute vec4 bakedVertexAnimationSettingsInstanced; +#endif +#define inline +mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) +{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} +#endif +`;rO.IncludesShadersStore.bakedVertexAnimationDeclaration=l5;let l6=`#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#ifdef INSTANCESCOLOR +attribute vec4 instanceColor; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; +#ifdef THIN_INSTANCES +uniform mat4 previousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform mat4 previousWorld; +#endif +#endif +`;rO.IncludesShadersStore.instancesDeclaration=l6;let l8=`#ifdef PREPASS +#ifdef PREPASS_DEPTH +varying vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#endif +`;rO.IncludesShadersStore.prePassVertexDeclaration=l8;let l7=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +varying vec2 v_VARYINGNAME_UV; +#endif +`;rO.IncludesShadersStore.samplerVertexDeclaration=l7;let l9=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#endif +`;rO.IncludesShadersStore.bumpVertexDeclaration=l9;let he=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;varying float fClipDistance6; +#endif +`;rO.IncludesShadersStore.clipPlaneVertexDeclaration=he;let ht=`#ifdef FOG +varying vec3 vFogDistance; +#endif +`;rO.IncludesShadersStore.fogVertexDeclaration=ht;let hi=`#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#endif +`;rO.IncludesShadersStore.lightVxFragmentDeclaration=hi;let hr=`#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;rO.IncludesShadersStore.lightVxUboDeclaration=hr;let hs=`#ifdef MORPHTARGETS +uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; +#ifdef MORPHTARGETS_TEXTURE +uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) +{ +float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} +#endif +#endif +`;rO.IncludesShadersStore.morphTargetsVertexGlobalDeclaration=hs;let hn=`#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +attribute vec3 position{X}; +#ifdef MORPHTARGETS_NORMAL +attribute vec3 normal{X}; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute vec3 tangent{X}; +#endif +#ifdef MORPHTARGETS_UV +attribute vec2 uv_{X}; +#endif +#endif +#endif +`;rO.IncludesShadersStore.morphTargetsVertexDeclaration=hn;let ha=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +float vertexID; +#endif +#endif +`;rO.IncludesShadersStore.morphTargetsVertexGlobal=ha;let ho=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#else +positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;rO.IncludesShadersStore.morphTargetsVertex=ho;let hl=`#ifdef INSTANCES +mat4 finalWorld=mat4(world0,world1,world2,world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +finalWorld=world*finalWorld; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +mat4 finalWorld=world; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=previousWorld; +#endif +#endif +`;rO.IncludesShadersStore.instancesVertex=hl;let hh=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +mat4 influence; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; +#endif +#else +influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`;rO.IncludesShadersStore.bonesVertex=hh;let hu=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +#define BVASNAME bakedVertexAnimationSettingsInstanced +#else +#define BVASNAME bakedVertexAnimationSettings +#endif +float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`;rO.IncludesShadersStore.bakedVertexAnimation=hu;let hc=`#ifdef PREPASS_DEPTH +vViewPos=(view*worldPos).rgb; +#endif +#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*worldPos; +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +`;rO.IncludesShadersStore.prePassVertex=hc;let hd=`#if !defined(UV{X}) && defined(MAINUV{X}) +vec2 uv{X}=vec2(0.,0.); +#endif +#ifdef MAINUV{X} +vMainUV{X}=uv{X}; +#endif +`;rO.IncludesShadersStore.uvVariableDeclaration=hd;let hp=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +if (v_INFONAME_==0.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} +#ifdef UV2 +else if (v_INFONAME_==1.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} +#endif +#ifdef UV3 +else if (v_INFONAME_==2.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} +#endif +#ifdef UV4 +else if (v_INFONAME_==3.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} +#endif +#ifdef UV5 +else if (v_INFONAME_==4.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} +#endif +#ifdef UV6 +else if (v_INFONAME_==5.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} +#endif +#endif +`;rO.IncludesShadersStore.samplerVertexImplementation=hp;let h_=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); +#endif +#endif +`;rO.IncludesShadersStore.bumpVertex=h_;let hf=`#ifdef CLIPPLANE +fClipDistance=dot(worldPos,vClipPlane); +#endif +#ifdef CLIPPLANE2 +fClipDistance2=dot(worldPos,vClipPlane2); +#endif +#ifdef CLIPPLANE3 +fClipDistance3=dot(worldPos,vClipPlane3); +#endif +#ifdef CLIPPLANE4 +fClipDistance4=dot(worldPos,vClipPlane4); +#endif +#ifdef CLIPPLANE5 +fClipDistance5=dot(worldPos,vClipPlane5); +#endif +#ifdef CLIPPLANE6 +fClipDistance6=dot(worldPos,vClipPlane6); +#endif +`;rO.IncludesShadersStore.clipPlaneVertex=hf;let hm=`#ifdef FOG +vFogDistance=(view*worldPos).xyz; +#endif +`;rO.IncludesShadersStore.fogVertex=hm;let hg=`#ifdef SHADOWS +#if defined(SHADOWCSM{X}) +vPositionFromCamera{X}=view*worldPos;for (int i=0; i +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include[2..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#include +#include[1..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +vPositionW=vec3(worldPos); +#include +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include[2..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#include +#include +#define CUSTOM_VERTEX_MAIN_END +} +`;rO.ShadersStore.defaultVertexShader=hb;let hE=RegExp("^([gimus]+)!");class hS{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;tthis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort((e,t)=>e.priority-t.priority),this._codeInjectionPoints={};let i={};for(let e of(i[hS._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0},this._plugins))e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!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;t0&&t.uniforms.push(...this._uniformList),this._samplerList.length>0&&t.samplers.push(...this._samplerList),this._uboList.length>0&&t.uniformBuffersNames.push(...this._uboList),t.customCode=this._injectCustomCode(t,t.customCode);break;case M.PrepareUniformBuffer:for(let e of(this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[],this._plugins)){let r=e.getUniforms();if(r){if(r.ubo)for(let e of r.ubo){if(e.size&&e.type){let r=null!==(i=e.arraySize)&&void 0!==i?i:0;t.ubo.addUniform(e.name,e.size,r),this._uboDeclaration+=`${e.type} ${e.name}${r>0?`[${r}]`:""}; +`}this._uniformList.push(e.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}e.getSamplers(this._samplerList),e.getUniformBuffersNames(this._uboList)}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var s,n;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let a=null===(s=this._codeInjectionPoints)||void 0===s?void 0:s[i];if(!a)return r;let o=null;for(let t in a){let s="";for(let r of this._activePlugins){let a=null===(n=r.getCustomCode(i))||void 0===n?void 0:n[t];if(a){if(r.resolveIncludes){if(null===o){let t=f.GLSL;o={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:rO.GetShadersRepository(t),includesShadersStore:rO.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}o.isFragment="fragment"===i,rD._ProcessIncludes(a,o,e=>a=e)}s+=a+"\n"}}if(s.length>0){if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{let i=hE.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}0>e.indexOf("g")&&(e+="g");let i=r,n=new RegExp(t,e),a=n.exec(i);for(;null!==a;){let e=s;for(let t=0;t{hC.length=0,nB.OnEventObservable.remove(hy),hy=null});let hC=[],hy=null;class hA{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new hS(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;let i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){i$.Clone(()=>e,this)}serialize(){return i$.Serialize(this)}parse(e,t,i){i$.Parse(()=>this,e,t,i)}}iZ([iW()],hA.prototype,"name",void 0),iZ([iW()],hA.prototype,"priority",void 0),iZ([iW()],hA.prototype,"resolveIncludes",void 0),iZ([iW()],hA.prototype,"registerForExtraEvents",void 0);class hR extends sh{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class hI extends hA{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new hR,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=nB.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||!i.getCaps().standardDerivatives||!this._texture||!lE.DetailTextureEnabled||!!this._texture.isReady()}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&lE.DetailTextureEnabled&&this._isEnabled?(nw.PrepareDefinesForMergedUV(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||!this._texture||!lE.DetailTextureEnabled||(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),nw.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&lE.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){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}iZ([iH("detailTexture"),iz("_markAllSubMeshesAsTexturesDirty")],hI.prototype,"texture",void 0),iZ([iW()],hI.prototype,"diffuseBlendLevel",void 0),iZ([iW()],hI.prototype,"roughnessBlendLevel",void 0),iZ([iW()],hI.prototype,"bumpLevel",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],hI.prototype,"normalBlendMethod",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],hI.prototype,"isEnabled",void 0);let hP={effect:null,subMesh:null};class hM extends sh{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_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.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!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.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,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_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){for(let t of["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"])this[t]=t===e}}class hD extends af{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}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}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new io(0,0,0),this.diffuseColor=new io(1,1,1),this.specularColor=new io(1,1,1),this.emissiveColor=new io(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new sa(16),this._worldViewProjectionMatrix=t7.Zero(),this._globalAmbientColor=new io(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new hI(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new lb,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),hD.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),hD.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!hD.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||!!hD.RefractionTextureEnabled&&!!this._refractionTexture&&!!this._refractionTexture.isRenderTarget||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===nB.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==nB.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(M.GetDefineNames,this._eventInfo),t.materialDefines=new hM(this._eventInfo.defineNames));let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();s._needNormals=nw.PrepareDefinesForLights(r,e,s,!0,this._maxSimultaneousLights,this._disableLighting),nw.PrepareDefinesForMultiview(r,s);let a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(nw.PrepareDefinesForPrePass(r,s,this.canRenderToMRT&&!a),nw.PrepareDefinesForOIT(r,s,a),s._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s._needUVs=!1;for(let e=1;e<=6;++e)s["MAINUV"+e]=!1;if(r.texturesEnabled){if(s.DIFFUSEDIRECTUV=0,s.BUMPDIRECTUV=0,s.AMBIENTDIRECTUV=0,s.OPACITYDIRECTUV=0,s.EMISSIVEDIRECTUV=0,s.SPECULARDIRECTUV=0,s.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&hD.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;nw.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&hD.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;nw.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&hD.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;nw.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&hD.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===n6.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,s.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case n6.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case n6.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case n6.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case n6.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case n6.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case n6.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case n6.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case n6.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case n6.CUBIC_MODE:case n6.INVCUBIC_MODE:default:s.setReflectionMode("REFLECTIONMAP_CUBIC")}s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else s.REFLECTION=!1,s.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&hD.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;nw.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&hD.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;nw.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&hD.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;nw.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&hD.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;nw.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAX_RHS=r.useRightHandedSystem,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAX_RHS=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&hD.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube,s.RGBDREFRACTION=this._refractionTexture.isRGBD,s.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha,s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,s.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}s._areFresnelDirty&&(hD.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),nw.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s,this._applyDecalMapAfterDetailMap),nw.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),nw.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(s.isDirty){let i=s._areLightsDisposed;s.markAsProcessed();let a=new aO;s.REFLECTION&&a.addFallback(0,"REFLECTION"),s.SPECULAR&&a.addFallback(0,"SPECULAR"),s.BUMP&&a.addFallback(0,"BUMP"),s.PARALLAX&&a.addFallback(1,"PARALLAX"),s.PARALLAX_RHS&&a.addFallback(1,"PARALLAX_RHS"),s.PARALLAXOCCLUSION&&a.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&a.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&a.addFallback(1,"FOG"),s.POINTSIZE&&a.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&a.addFallback(0,"LOGARITHMICDEPTH"),nw.HandleFallbacksForShadows(s,a,this._maxSimultaneousLights),s.SPECULARTERM&&a.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&a.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&a.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&a.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&a.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&a.addFallback(4,"FRESNEL"),s.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");let l=[sf.PositionKind];s.NORMAL&&l.push(sf.NormalKind),s.TANGENT&&l.push(sf.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(sf.ColorKind),nw.PrepareAttributesForBones(l,e,s,a),nw.PrepareAttributesForInstances(l,s),nw.PrepareAttributesForMorphTargets(l,e,s),nw.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default",u=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],c=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=a,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=u,this._eventInfo.attributes=l,this._eventInfo.samplers=c,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(M.PrepareEffect,this._eventInfo),lb.AddUniforms(u),lb.AddSamplers(c),sd&&(sd.PrepareUniforms(u,s),sd.PrepareSamplers(c,s)),nw.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),nD(u);let _={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,u,d,c,s,l,_));let f=s.toString(),m=t.effect,g=r.getEngine().createEffect(h,{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:f,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},n);if(this._eventInfo.customCode=void 0,g){if(this._onEffectCreatedObservable&&(hP.effect=g,hP.subMesh=t,this._onEffectCreatedObservable.notifyObservers(hP)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,s.markAsUnprocessed(),o=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var r;let s=this.getScene(),n=i.materialDefines;if(!n)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let o=a._forceRebindOnNextCall||this._mustRebind(s,a,t.visibility);nw.BindBonesParameters(t,a);let l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||a._forceRebindOnNextCall){if(hD.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new io(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&hD.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),nw.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&hD.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),nw.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&hD.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),nw.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&hD.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){let e=this._reflectionTexture;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&hD.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),nw.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&hD.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),nw.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&hD.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),nw.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&hD.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),nw.BindTextureMatrix(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&hD.RefractionTextureEnabled){let e=1;if(!this._refractionTexture.isCube&&(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let e=this._refractionTexture;l.updateVector3("vRefractionPosition",e.boundingBoxPosition),l.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",hD.EmissiveTextureEnabled?this.emissiveColor:io.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&hD.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&hD.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&hD.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&hD.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&hD.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&hD.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&hD.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&hD.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&hD.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),nN(a,this,s),this.bindEyePosition(a)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&nw.BindLights(s,t,a,n,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==sY.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),nw.BindFogParameters(s,t,a),n.NUM_MORPH_INFLUENCERS&&nw.BindMorphTargetParameters(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(r=t.bakedVertexAnimationManager)||void 0===r||r.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&nw.BindLogDepth(n,a,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),l.update()}getAnimatables(){let e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),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._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),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._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){let e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),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._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){var i,r,s,n,a,o,l,h,u;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._specularTexture)||void 0===o||o.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(u=this._refractionTexture)||void 0===u||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=i$.Clone(()=>new hD(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=i$.Parse(()=>new hD(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),nB._parsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return lE.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){lE.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return lE.DetailTextureEnabled}static set DetailTextureEnabled(e){lE.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return lE.AmbientTextureEnabled}static set AmbientTextureEnabled(e){lE.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return lE.OpacityTextureEnabled}static set OpacityTextureEnabled(e){lE.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return lE.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){lE.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return lE.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){lE.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return lE.SpecularTextureEnabled}static set SpecularTextureEnabled(e){lE.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return lE.BumpTextureEnabled}static set BumpTextureEnabled(e){lE.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return lE.LightmapTextureEnabled}static set LightmapTextureEnabled(e){lE.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return lE.RefractionTextureEnabled}static set RefractionTextureEnabled(e){lE.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return lE.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){lE.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return lE.FresnelEnabled}static set FresnelEnabled(e){lE.FresnelEnabled=e}}iZ([iH("diffuseTexture")],hD.prototype,"_diffuseTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesAndMiscDirty")],hD.prototype,"diffuseTexture",void 0),iZ([iH("ambientTexture")],hD.prototype,"_ambientTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"ambientTexture",void 0),iZ([iH("opacityTexture")],hD.prototype,"_opacityTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesAndMiscDirty")],hD.prototype,"opacityTexture",void 0),iZ([iH("reflectionTexture")],hD.prototype,"_reflectionTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"reflectionTexture",void 0),iZ([iH("emissiveTexture")],hD.prototype,"_emissiveTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"emissiveTexture",void 0),iZ([iH("specularTexture")],hD.prototype,"_specularTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"specularTexture",void 0),iZ([iH("bumpTexture")],hD.prototype,"_bumpTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"bumpTexture",void 0),iZ([iH("lightmapTexture")],hD.prototype,"_lightmapTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"lightmapTexture",void 0),iZ([iH("refractionTexture")],hD.prototype,"_refractionTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"refractionTexture",void 0),iZ([iX("ambient")],hD.prototype,"ambientColor",void 0),iZ([iX("diffuse")],hD.prototype,"diffuseColor",void 0),iZ([iX("specular")],hD.prototype,"specularColor",void 0),iZ([iX("emissive")],hD.prototype,"emissiveColor",void 0),iZ([iW()],hD.prototype,"specularPower",void 0),iZ([iW("useAlphaFromDiffuseTexture")],hD.prototype,"_useAlphaFromDiffuseTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesAndMiscDirty")],hD.prototype,"useAlphaFromDiffuseTexture",void 0),iZ([iW("useEmissiveAsIllumination")],hD.prototype,"_useEmissiveAsIllumination",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"useEmissiveAsIllumination",void 0),iZ([iW("linkEmissiveWithDiffuse")],hD.prototype,"_linkEmissiveWithDiffuse",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"linkEmissiveWithDiffuse",void 0),iZ([iW("useSpecularOverAlpha")],hD.prototype,"_useSpecularOverAlpha",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"useSpecularOverAlpha",void 0),iZ([iW("useReflectionOverAlpha")],hD.prototype,"_useReflectionOverAlpha",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"useReflectionOverAlpha",void 0),iZ([iW("disableLighting")],hD.prototype,"_disableLighting",void 0),iZ([iz("_markAllSubMeshesAsLightsDirty")],hD.prototype,"disableLighting",void 0),iZ([iW("useObjectSpaceNormalMap")],hD.prototype,"_useObjectSpaceNormalMap",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"useObjectSpaceNormalMap",void 0),iZ([iW("useParallax")],hD.prototype,"_useParallax",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"useParallax",void 0),iZ([iW("useParallaxOcclusion")],hD.prototype,"_useParallaxOcclusion",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"useParallaxOcclusion",void 0),iZ([iW()],hD.prototype,"parallaxScaleBias",void 0),iZ([iW("roughness")],hD.prototype,"_roughness",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"roughness",void 0),iZ([iW()],hD.prototype,"indexOfRefraction",void 0),iZ([iW()],hD.prototype,"invertRefractionY",void 0),iZ([iW()],hD.prototype,"alphaCutOff",void 0),iZ([iW("useLightmapAsShadowmap")],hD.prototype,"_useLightmapAsShadowmap",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"useLightmapAsShadowmap",void 0),iZ([iY("diffuseFresnelParameters")],hD.prototype,"_diffuseFresnelParameters",void 0),iZ([iz("_markAllSubMeshesAsFresnelDirty")],hD.prototype,"diffuseFresnelParameters",void 0),iZ([iY("opacityFresnelParameters")],hD.prototype,"_opacityFresnelParameters",void 0),iZ([iz("_markAllSubMeshesAsFresnelAndMiscDirty")],hD.prototype,"opacityFresnelParameters",void 0),iZ([iY("reflectionFresnelParameters")],hD.prototype,"_reflectionFresnelParameters",void 0),iZ([iz("_markAllSubMeshesAsFresnelDirty")],hD.prototype,"reflectionFresnelParameters",void 0),iZ([iY("refractionFresnelParameters")],hD.prototype,"_refractionFresnelParameters",void 0),iZ([iz("_markAllSubMeshesAsFresnelDirty")],hD.prototype,"refractionFresnelParameters",void 0),iZ([iY("emissiveFresnelParameters")],hD.prototype,"_emissiveFresnelParameters",void 0),iZ([iz("_markAllSubMeshesAsFresnelDirty")],hD.prototype,"emissiveFresnelParameters",void 0),iZ([iW("useReflectionFresnelFromSpecular")],hD.prototype,"_useReflectionFresnelFromSpecular",void 0),iZ([iz("_markAllSubMeshesAsFresnelDirty")],hD.prototype,"useReflectionFresnelFromSpecular",void 0),iZ([iW("useGlossinessFromSpecularMapAlpha")],hD.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"useGlossinessFromSpecularMapAlpha",void 0),iZ([iW("maxSimultaneousLights")],hD.prototype,"_maxSimultaneousLights",void 0),iZ([iz("_markAllSubMeshesAsLightsDirty")],hD.prototype,"maxSimultaneousLights",void 0),iZ([iW("invertNormalMapX")],hD.prototype,"_invertNormalMapX",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"invertNormalMapX",void 0),iZ([iW("invertNormalMapY")],hD.prototype,"_invertNormalMapY",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"invertNormalMapY",void 0),iZ([iW("twoSidedLighting")],hD.prototype,"_twoSidedLighting",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],hD.prototype,"twoSidedLighting",void 0),iZ([iW("applyDecalMapAfterDetailMap")],hD.prototype,"_applyDecalMapAfterDetailMap",void 0),iZ([iz("_markAllSubMeshesAsMiscDirty")],hD.prototype,"applyDecalMapAfterDetailMap",void 0),t0["BABYLON.StandardMaterial"]=hD,sY.DefaultMaterialFactory=e=>new hD("default material",e),r$.prototype.createDynamicTexture=function(e,t,i,r){let s=new rU(this,m.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?r$.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?r$.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},r$.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n=!1,a=!1){if(!e)return;let o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let u=this._getWebGLTextureType(e.type),c=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,c);o.texImage2D(l,0,d,c,u,t),e.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(e.format=s),e._dynamicTextureSource=t,e._premulAlpha=r,e.invertY=i||!1,e.isReady=!0};class hO extends n6{constructor(e,t,i=null,r=!1,s=3,n=5,a){super(null,i,!r,a,s,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=n6.CLAMP_ADDRESSMODE,this.wrapV=n6.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let o=this._getEngine();if(!o)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=o.createDynamicTexture(t.width,t.height,r,s)):(this._canvas=o.createCanvas(1,1),this._ownCanvas=!0,t.width||0===t.width?this._texture=o.createDynamicTexture(t.width,t.height,r,s):this._texture=o.createDynamicTexture(t,t,r,s));let l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){let t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,n,a,o=!0){let l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){let i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){let e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),o&&this.update(a)}dispose(){var e;super.dispose(),this._ownCanvas&&(null===(e=this._canvas)||void 0===e||e.remove()),this._canvas=null,this._context=null}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new hO(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){let e=this.getScene();e&&!e.isReady()&&ig.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return hO._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class hN{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){this.isFixedFoveationSupported&&(this.layer.fixedFoveation=Math.max(0,Math.min(1,e||0)))}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.createRenderTargetTextureProvider=s}}class hF{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=[],this._engine=e.getEngine()}_createInternalTexture(e,t){let i=new rU(this._engine,m.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new rX(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,n){if(!this._engine)throw Error("Engine is disposed");let a={width:e,height:t},o=n?new lp(this._scene,a):new a5("XR renderTargetTexture",a,this._scene),l=o.renderTarget;if(l._samples=o.samples,(i||!r)&&(l._framebuffer=i),r){if(n)l._colorTextureArray=r;else{let e=this._createInternalTexture(a,r);l.setTexture(e,0),o._texture=e}}return s&&(n?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(a,s)),o.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(o.skipInitialClear=!0),this._renderTargetTextures.push(o),o}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.length=0}}class hw extends hN{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new hL(e.scene,this)),this.layer=e}}class hL extends hF{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){let i=this._layer.getViewport(t);if(!i)return!1;let r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){let t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class hB{static GetDefaults(e){let t=new hB;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class hU{constructor(e,t=hB.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new tj,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{let e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add(()=>{this._addCanvas()}),e.onXRSessionEnded.add(()=>{this._removeCanvas()})}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){let t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new hw(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{ss.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>t()):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(()=>{this._setCanvasSize(!0)})}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class hV extends hN{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new hk(e,this)),this.layer=e}}class hk extends hF{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class hG{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class hz{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new tj,this.onXRReferenceSpaceChanged=new tj,this.onXRSessionEnded=new tj,this.onXRSessionInit=new tj,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch(()=>{ig.Warn("Could not end XR session.")})):Promise.resolve()}trySetViewportForView(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){let t=this.scene.getEngine();return this._xrNavigator.xr.native?new hG(this):((e=e||hB.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new hU(this,e))}initializeAsync(){return(this._xrNavigator=navigator,this._xrNavigator.xr)?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then(t=>(this.session=t,this._sessionMode=e,this.onXRSessionInit.notifyObservers(t),this.inXRSession=!0,this.session.addEventListener("end",()=>{var e;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&(null===(e=this._baseLayerRTTProvider)||void 0===e||e.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return hz.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{var i;this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then(e=>e,e=>(ig.Error("XR.requestReferenceSpace failed for the following reason: "),ig.Error(e),ig.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(e=>{let t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)},e=>{throw ig.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))).then(e=>this.session.requestReferenceSpace("viewer").then(t=>(this.viewerReferenceSpace=t,e))).then(e=>(this.referenceSpace=this.baseReferenceSpace=e,this.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new hV(e.baseLayer):new hw(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);let t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(e=>Promise.resolve(void 0===e||e)).catch(e=>(ig.Warn(e),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e}get currentFrameRate(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate}get supportedFrameRates(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():(this.inXRSession||!t)&&this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null}set fixedFoveation(e){this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=Math.max(0,Math.min(1,e||0)))}get enabledFeatures(){var e,t;return null!==(t=null===(e=this.session)||void 0===e?void 0:e.enabledFeatures)&&void 0!==t?t:null}}(function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"})(J||(J={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(ee||(ee={})),nX._GroundMeshParser=(e,t)=>hW.Parse(e,t);class hW extends nX{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),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=ie.Matrix[5];i.invertToRef(r);let s=ie.Vector3[8];if(t5.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return t5.TransformCoordinatesFromFloatsToRef(0,a,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new t5(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=ie.Matrix[5];r.invertToRef(s);let n=ie.Vector3[8];if(t5.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t);return t5.TransformNormalFromFloatsToRef(a.x,a.y,a.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];return te.maxHeight){h=!0;let t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){let r=new t5(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),u=(((r.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(r.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth)*4,c=e.buffer[u]/255,d=e.buffer[u+1]/255,p=e.buffer[u+2]/255,_=e.buffer[u+3]/255;h&&(c=1-c,d=1-d,p=1-p);let f=c*o.r+d*o.g+p*o.b;_>=l?r.y=e.minHeight+(e.maxHeight-e.minHeight)*f:r.y=e.minHeight-.001,s.push(r.x,r.y,r.z),n.push(0,0,0),a.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t=e.minHeight,u=s[3*a+1]>=e.minHeight,c=s[3*o+1]>=e.minHeight;h&&u&&c&&(r.push(n),r.push(a),r.push(o)),s[3*l+1]>=e.minHeight&&h&&c&&(r.push(l),r.push(n),r.push(o))}ng.ComputeNormals(s,r,n);let u=new ng;return u.indices=r,u.positions=s,u.normals=n,u.uvs=a,u}function hj(e,t={},i){let r=new hW(e,i);return r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ,hH(t).applyToMesh(r,t.updatable),r._setReady(!0),r}function hK(e){let t=[],i=[],r=[],s=[],n=e.diameter||1,a=e.thickness||.5,o=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE,h=o+1;for(let e=0;e<=o;e++){let l=e/o,u=e*Math.PI*2/o-Math.PI/2,c=t7.Translation(n/2,0,0).multiply(t7.RotationY(u));for(let n=0;n<=o;n++){let u=1-n/o,d=n*Math.PI*2/o+Math.PI,p=new t5(Math.cos(d),Math.sin(d),0),_=p.scale(a/2),f=new t4(l,u);_=t5.TransformCoordinates(_,c),p=t5.TransformNormal(p,c),i.push(_.x,_.y,_.z),r.push(p.x,p.y,p.z),s.push(f.x,nx.UseOpenGLOrientationForUV?1-f.y:f.y);let m=(e+1)%h,g=(n+1)%h;t.push(e*h+n),t.push(e*h+g),t.push(m*h+n),t.push(e*h+g),t.push(m*h+g),t.push(m*h+n)}}ng._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);let u=new ng;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function h$(e,t={},i){let r=new nX(e,i);return t.sideOrientation=nX._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,hK(t).applyToMesh(r,t.updatable),r}ng.CreateGround=hH,ng.CreateTiledGround=hX,ng.CreateGroundFromHeightMap=hY,nX.CreateGround=(e,t,i,r,s,n)=>hj(e,{width:t,height:i,subdivisions:r,updatable:n},s),nX.CreateTiledGround=(e,t,i,r,s,n,a,o,l)=>(function(e,t,i=null){let r=new nX(e,i);return hX(t).applyToMesh(r,t.updatable),r})(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:n,precision:a,updatable:l},o),nX.CreateGroundFromHeightMap=(e,t,i,r,s,n,a,o,l,h,u)=>(function(e,t,i={},r=null){let s=i.width||10,n=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new io(.3,.59,.11),u=i.alphaFilter||0,c=i.updatable,d=i.onReady,p=new hW(e,r=r||t2.LastCreatedScene);p._subdivisionsX=a,p._subdivisionsY=a,p._width=s,p._height=n,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1);let _=(e,t,i)=>{hY({width:s,height:n,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:u}).applyToMesh(p,c),d&&d(p),p._setReady(!0)};return"string"==typeof t?ss.LoadImage(t,e=>{let t=e.width,i=e.height;r.isDisposed||_(null==r?void 0:r.getEngine().resizeImageBitmap(e,t,i),t,i)},i.onError?i.onError:()=>{},r.offlineProvider):_(t.data,t.width,t.height),p})(e,t,{width:i,height:r,subdivisions:s,minHeight:n,maxHeight:a,updatable:l,onReady:h,alphaFilter:u},o),ng.CreateTorus=hK,nX.CreateTorus=(e,t,i,r,s,n,a)=>h$(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:a,updatable:n},s);class hq{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=hq._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=h$("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;let t=new hD("targetMat",e);t.specularColor=io.Black(),t.emissiveColor=new io(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new as(t5.Zero(),new t5(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}hq._IdCounter=0;class hQ extends hq{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){let t=this._getCamera();return t?t.getForwardRay(e):new as(t5.Zero(),t5.Forward())}}class hZ{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new tj,this.onAfterEnteringVRObservable=new tj,this.onExitingVRObservable=new tj,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=hZ.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new t5(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new t5(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new io(.2,.2,1),this._pickedGazeColor=new io(0,0,1),this.onNewMeshSelected=new tj,this.onNewMeshPicked=new tj,this.onBeforeCameraTeleport=new tj,this.onAfterCameraTeleport=new tj,this.onSelectedMeshUnselected=new tj,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==ov.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged(e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))}),e.rightStick&&e.onrightstickchanged(e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)}),e.type===ov.XBOX&&(e.onbuttondown(e=>{this._interactionsEnabled&&e===$.A&&this._cameraGazer._selectionPointerDown()}),e.onbuttonup(e=>{this._interactionsEnabled&&e===$.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=t5.Zero(),this._workingQuaternion=t8.Identity(),this._workingMatrix=t7.Identity(),ig.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new t5(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new oH("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof ok&&this._scene.activeCamera.rotation)){let e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(t8.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?hz.IsSessionSupportedAsync("immersive-vr").then(i=>{i?(ig.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new hQ(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(e=>{switch(e){case J.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case J.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case J.IN_XR:this._hasEnteredVR=!0;break;case J.NOT_IN_XR:this._hasEnteredVR=!1}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new lx("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new hQ(()=>this.currentVRCamera,e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";let t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});let i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},sS.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new s2,this._circleEase.setEasingMode(s1.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===sS.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===sS.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===J.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){let e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){ig.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=t8.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){ig.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===J.IN_XR&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>(!!this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e)}removeFloorMesh(e){if(!this._floorMeshesCollection)return;let t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){let t=e.floorMeshes||[];if(!t.length){let i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr){t.forEach(e=>{this.xr.teleportation.addFloorMesh(e)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}if(!this.xrTestDone){let t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(t);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);let t=new sd;t.vignetteColor=new il(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){(!this._teleportationRequestInitiated||t._teleportationRequestInitiated)&&(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated){if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;let e=t8.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,t8.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),t5.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);let r=new as(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}}_createTeleportationCircles(){this._teleportationTarget=hj("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;let e=new hO("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;let t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();let i=new hD("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;let r=h$("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;let s=new re("animationInnerCircle","position.y",30,re.ANIMATIONTYPE_FLOAT,re.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),s.setKeys(n);let a=new s6;a.setEasingMode(s1.EASINGMODE_EASEINOUT),s.setEasingFunction(a),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof oG))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];let t=t8.FromRotationMatrix(t7.RotationY(Math.PI/4*this._rotationAngle)),i=new re("animationRotation","rotationQuaternion",90,re.ANIMATIONTYPE_QUATERNION,re.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];let s=new re("animationPP","vignetteWeight",90,re.ANIMATIONTYPE_FLOAT,re.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),s.setKeys(n),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);let a=new re("animationPP2","vignetteStretch",90,re.ANIMATIONTYPE_FLOAT,re.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:10}),o.push({frame:6,value:0}),a.setKeys(o),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){let t,i;if(!(this.currentVRCamera instanceof oG))return;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==hZ.TELEPORTATIONMODE_CONSTANTSPEED){i=90;let e=t5.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];let r=new re("animationCameraTeleportation","position",90,re.ANIMATIONTYPE_VECTOR3,re.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];let n=Math.round(i/2),a=new re("animationPP","vignetteWeight",90,re.ANIMATIONTYPE_FLOAT,re.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:n,value:8}),o.push({frame:i,value:0}),a.setKeys(o),this._postProcessMove.animations.push(a);let l=new re("animationPP2","vignetteStretch",90,re.ANIMATIONTYPE_FLOAT,re.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){if(!this.updateControllerLaserColor)return}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}hZ.TELEPORTATIONMODE_CONSTANTTIME=0,hZ.TELEPORTATIONMODE_CONSTANTSPEED=1;let hJ=(e,t,i,r)=>!(e.x>i.x+r)&&!(i.x-r>t.x)&&!(e.y>i.y+r)&&!(i.y-r>t.y)&&!(e.z>i.z+r)&&!(i.z-r>t.z),h0=function(){let e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;let n=i*i-4*t*r;if(n<0)return e;let a=Math.sqrt(n),o=(-i-a)/(2*t),l=(-i+a)/(2*t);if(o>l){let e=l;l=o,o=e}return o>0&&o0&&l=0))}_canDoCollision(e,t,i,r){let s=t5.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+n+t)&&!!hJ(i,r,this._basePointWorld,this._velocityWorldLength+n)}_testTriangle(e,t,i,r,s,n,a){let o;let l=!1;t||(t=[]),t[e]||(t[e]=new sG(0,0,0,0),t[e].copyFromPoints(i,r,s));let h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;let u=h.signedDistanceTo(this._basePoint),c=t5.Dot(h.normal,this._velocity);if(h1.DoubleSidedCheck&&c>1e-4)return;if(0==c){if(Math.abs(u)>=1)return;l=!0,o=0}else{o=(-1-u)/c;let e=(1-u)/c;if(o>e){let t=e;e=o,o=t}if(o>1||e<0)return;o<0&&(o=0),o>1&&(o=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,p=1;if(!l&&(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(o,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,p=o,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*t5.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,a=h0(e,t,n,p);a.found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),(a=h0(e,t=2*t5.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),(a=h0(e,t=2*t5.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let o=this._edge.lengthSquared(),l=t5.Dot(this._edge,this._velocity),h=t5.Dot(this._edge,this._baseToVertex);if((a=h0(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*t5.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=t5.Dot(this._edge,this._velocity),h=t5.Dot(this._edge,this._baseToVertex),(a=h0(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*t5.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=t5.Dot(this._edge,this._velocity),h=t5.Dot(this._edge,this._baseToVertex),(a=h0(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*t5.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){let e=p*p*this._velocitySquaredLength;(!this.collisionFound||e=r){s.copyFrom(e);return}let o=n?n.collisionMask:i.collisionMask;i._initialize(e,t,a);let l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew h2;class h3{constructor(e,t,i,r=""){var s,n;let a;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new tj,this.onErrorObservable=new tj,this.onBindObservable=new tj,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=f.WGSL,this.name=e,this._key=r,this._engine=i,this.uniqueId=h3._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(n=t.entryPoint)&&void 0!==n?n:"main",this._shaderStore=rO.GetShadersStore(this._shaderLanguage),this._shaderRepository=rO.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=rO.GetIncludesShadersStore(this._shaderLanguage),e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=null,a=e.computeElement):a=e.compute||e;let o={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(a,"Compute","",i=>{rD.Initialize(o),rD.PreProcess(i,o,r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));let s=rD.Finalize(r,"",o);this._useFinalCode(s.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){let i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){r(rn(e));return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){r(window.atob(e.substr(7)));return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getComputeShaderCode())&&void 0!==t?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){let e=this.defines,t=this._pipelineContext;this._isReady=!1;try{let i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,()=>{this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)}),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t){let i=null;if(t&&e){let r=t.match(/COMPUTE SHADER ERROR: 0:(\d+?):/);if(r&&2===r.length){let t=parseInt(r[1]),s=e.split("\n",-1);s.length>=t&&(i=`Offending line [${t}] in compute code: ${s[t-1]}`)}}return[e,i]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,ig.Error("Unable to compile compute effect:"),ig.Error("Defines:\n"+this.defines),h3.LogShaderCodeOnCompilationError){let e=null,t=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getComputeShaderCode())&&([t,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),t&&(ig.Error("Compute code:"),ig.Error(t))),e&&ig.Error(e)}ig.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){rO.GetShadersStore(f.WGSL)[`${e}ComputeShader`]=t}}h3._UniqueIdSeed=0,h3.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture"}(et||(et={})),r$.prototype.createComputeEffect=function(e,t){throw Error("createComputeEffect: This engine does not support compute shaders!")},r$.prototype.createComputePipelineContext=function(){throw Error("createComputePipelineContext: This engine does not support compute shaders!")},r$.prototype.createComputeContext=function(){},r$.prototype.computeDispatch=function(e,t,i,r,s,n,a){throw Error("computeDispatch: This engine does not support compute shaders!")},r$.prototype.areAllComputeEffectsReady=function(){return!0},r$.prototype.releaseComputeEffects=function(){},r$.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},r$.prototype._rebuildComputeEffects=function(){},r$.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},r$.prototype._releaseComputeEffect=function(e){},r$.prototype._deleteComputePipelineContext=function(e){};class h4{constructor(){this._gpuTimeInFrameId=-1,this.counter=new sk}_addDuration(e,t){e{let n=()=>{this.dispatch(e,t,i)?s():setTimeout(n,r)};n()})}serialize(){let e=i$.Serialize(this);for(let t in e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={},this._bindings){let i=this._bindings[t],r=i.object;switch(i.type){case et.Texture:case et.TextureWithoutSampler:case et.StorageTexture:{let s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type})}case et.UniformBuffer:}}return e}static Parse(e,t,i){let r=i$.Parse(()=>new h5(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(let s in e.textures){let n=e.bindings[s],a=n6.Parse(e.textures[s],t,i);n.type===et.Texture?r.setTexture(s,a):n.type===et.TextureWithoutSampler?r.setTexture(s,a,!1):r.setStorageTexture(s,a)}return r}}iZ([iW()],h5.prototype,"name",void 0),iZ([iW()],h5.prototype,"fastMode",void 0),t0["BABYLON.ComputeShader"]=h5;class h6{constructor(e,t,i,r,s,n){this.entries=[],this._boundingVectors=[],this._capacity=i,this._depth=r,this._maxDepth=s,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{let i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},h8.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},sY.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(sb.NAME_OCTREE);i||(i=new h7(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new h8(h8.CreationFuncForMeshes,e,t));let r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(sY.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),nM.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){let i=this.getScene(),r=i._getComponent(sb.NAME_OCTREE);r||(r=new h7(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new h8(h8.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);let s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class h7{constructor(e){if(this.name=sb.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new as(t5.Zero(),new t5(1,1,1)),!(e=e||t2.LastCreatedScene))return;this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t)}register(){this.scene.onMeshRemovedObservable.add(e=>{let t=this.scene.selectionOctree;if(null!=t){let i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{let t=this.scene.selectionOctree;null!=t&&t.addMesh(e)})}getActiveMeshCandidates(){var e;return(null===(e=this.scene._selectionOctree)||void 0===e?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(as.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){let i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function h9(e){let t,i,r,s,n,a,o;let l=e.height||2,h=0===e.diameterTop?0:e.diameterTop||e.diameter||1,u=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;h=h||1e-5,u=u||1e-5;let c=0|(e.tessellation||24),d=0|(e.subdivisions||1),p=!!e.hasRings,_=!!e.enclose,f=0===e.cap?0:e.cap||nX.CAP_ALL,m=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,g=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE,v=e.faceUV||[,,,],x=e.faceColors,T=2+(1+(1!==m&&_?2:0))*(p?d:1);for(t=0;t{let t,i,r;let s=e?h/2:u/2;if(0===s)return;let n=e?v[T-1]:v[0],a=null;x&&(a=e?x[T-1]:x[0]);let o=E.length/3,d=e?l/2:-l/2,p=new t5(0,d,0);E.push(p.x,p.y,p.z),S.push(0,e?1:-1,0);let _=n.y+(n.w-n.y)*.5;C.push(n.x+(n.z-n.x)*.5,nx.UseOpenGLOrientationForUV?1-_:_),a&&y.push(a.r,a.g,a.b,a.a);let f=new t4(.5,.5);for(r=0;r<=c;r++){let o=Math.cos(-(t=2*Math.PI*r*m/c)),l=Math.sin(-t);i=new t5(o*s,d,l*s);let h=new t4(o*f.x+.5,l*f.y+.5);E.push(i.x,i.y,i.z),S.push(0,e?1:-1,0);let u=n.y+(n.w-n.y)*h.y;C.push(n.x+(n.z-n.x)*h.x,nx.UseOpenGLOrientationForUV?1-u:u),a&&y.push(a.r,a.g,a.b,a.a)}for(r=0;r(void 0!==a&&a instanceof sY||(void 0!==a&&(l=o||nX.DEFAULTSIDE,o=a),a=n,n=1),ue(e,{height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:n,sideOrientation:l,updatable:o},a)),i0.AddNodeConstructor("Light_Type_3",(e,t)=>()=>new ut(e,t5.Zero(),t));class ut extends nj{constructor(e,t,i){super(e,i),this.groundColor=new io(0,0,0),this.direction=t||t5.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=t5.Normalize(e.subtract(t5.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=t5.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){let i=t5.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=t7.Identity()),this._worldMatrix}getTypeID(){return nj.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}iZ([iX()],ut.prototype,"groundColor",void 0),iZ([ij()],ut.prototype,"direction",void 0);class ui{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return(t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera)?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new ut("shared gizmo light",new t5(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=io.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==ui._DefaultUtilityLayer?ui._CreateDefaultUtilityLayerFromScene(t2.LastCreatedScene):ui._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return ui._DefaultUtilityLayer=new ui(e),ui._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{ui._DefaultUtilityLayer=null}),ui._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==ui._DefaultKeepDepthUtilityLayer&&(ui._DefaultKeepDepthUtilityLayer=new ui(t2.LastCreatedScene),ui._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,ui._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{ui._DefaultKeepDepthUtilityLayer=null})),ui._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new tj,this.utilityLayerScene=new sY(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(t=>{if(!this.utilityLayerScene.activeCamera||!this.pickingEnabled||!this.processAllEvents&&t.type!==sS.POINTERMOVE&&t.type!==sS.POINTERUP&&t.type!==sS.POINTERDOWN&&t.type!==sS.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;let i=t.event;if(e.isPointerCaptured(i.pointerId)){this._pointerCaptures[i.pointerId]=!1;return}let r=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new sm;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},s=r(this.utilityLayerScene);if(!t.ray&&s&&(t.ray=s.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=sS.POINTERDOWN){t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new sA(t.type,t.event,s),t.type),t.type===sS.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)s&&s.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new sA(t.type,t.event,s),t.type),t.skipOnPointerObservable=!0);else{let i=r(e),n=t.event;i&&s&&(0===s.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===sS.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:(t.type===sS.POINTERMOVE||t.type===sS.POINTERUP)&&(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(s.distance0)):!this._pointerCaptures[n.pointerId]&&s.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):((t.type===sS.POINTERMOVE||t.type===sS.POINTERUP)&&this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,s,n))),t.type===sS.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new sA(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){let e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}ui._DefaultUtilityLayer=null,ui._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(ei||(ei={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(er||(er={}));class ur{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach(e=>{e.dispose()}),e.parent=this._rootMesh,this._customMeshSet=!0}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;let t=e==er.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=ui.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=ei.Origin,this._updateScale=!0,this._coordinatesMode=er.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=t7.RotationY(Math.PI),this._rootMesh=new nX("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=t8.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(()=>{this._update()})}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh){if(this.anchorPoint==ei.Pivot&&e.getAbsolutePivotPoint){let t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{let t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new t5(0,0,0);this._rootMesh.position.copyFrom(i)}}if(this.updateGizmoRotationToMatchAttachedMesh){let t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,ur.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){let t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,ie.Vector3[0]);let r=this.scaleRatio;if(t.mode==ns.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(r*=t.orthoTop-t.orthoBottom);else{let e=t.getScene().useRightHandedSystem?t5.RightHandedForwardReadOnly:t5.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=t5.Dot(ie.Vector3[0],i)}this._rootMesh.scaling.setAll(r),0>e._getWorldMatrixDeterminant()&&!ur.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix()){e.getPivotMatrix().invertToRef(ie.Matrix[5]),ie.Matrix[5].multiplyToRef(t,i);return}i.copyFrom(t)}_matrixChanged(){if(this._attachedNode){if(this._attachedNode._isCamera){let e,t;let i=this._attachedNode;if(i.parent){let t=ie.Matrix[1];i.parent._worldMatrix.invertToRef(t),this._attachedNode._worldMatrix.multiplyToRef(t,ie.Matrix[0]),e=ie.Matrix[0]}else e=this._attachedNode._worldMatrix;if(i.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(e,ie.Matrix[1]),t=ie.Matrix[1]):t=e,t.decompose(ie.Vector3[1],ie.Quaternion[0],ie.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){let e=this._attachedNode;e.rotation=ie.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(ie.Quaternion[0]),e.rotationQuaternion.normalize())}i.position.copyFrom(ie.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){let e=this._attachedNode;if(e.parent){let t=ie.Matrix[0],i=ie.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);let r=ie.Matrix[4];if(this._handlePivotMatrixInverse(e,i,r),r.decompose(ie.Vector3[0],ie.Quaternion[0],e.position,ur.PreserveScaling?e:void 0,ur.UseAbsoluteScaling),ie.Quaternion[0].normalize(),e.isUsingPivotMatrix()){let t=ie.Quaternion[1];t8.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);let i=ie.Matrix[2];t7.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);let r=ie.Matrix[2];t.toRotationMatrix(r);let s=e.getPivotMatrix(),n=ie.Matrix[3];s.invertToRef(n),s.multiplyToRef(i,ie.Matrix[4]),ie.Matrix[4].multiplyToRef(r,ie.Matrix[5]),ie.Matrix[5].multiplyToRef(n,ie.Matrix[6]),ie.Matrix[6].getTranslationToRef(ie.Vector3[1]),e.position.subtractInPlace(ie.Vector3[1])}}else{let t=ie.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(ie.Vector3[0],ie.Quaternion[0],e.position,ur.PreserveScaling?e:void 0,ur.UseAbsoluteScaling)}ie.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(ie.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(ie.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=ie.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){let e=this._attachedNode,t=e.getParent();if(t){let i=ie.Matrix[0],r=ie.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r),e.getLocalMatrix().copyFrom(r)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{let e=this._attachedNode;if(e.getTypeID){let t=e.getTypeID();if(t===nj.LIGHTTYPEID_DIRECTIONALLIGHT||t===nj.LIGHTTYPEID_SPOTLIGHT||t===nj.LIGHTTYPEID_POINTLIGHT){let t=e.parent;if(t){let i=ie.Matrix[0],r=ie.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,ie.Quaternion[0],ie.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,ie.Quaternion[0],ie.Vector3[0]);e.position=new t5(ie.Vector3[0].x,ie.Vector3[0].y,ie.Vector3[0].z),e.direction&&(e.direction=new t5(e.direction.x,e.direction.y,e.direction.z))}}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach(e=>{e.material=t,e.color&&(e.color=t.diffuseColor)})}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add(e=>{var r,s;if(e.pickInfo){if(e.type===sS.POINTERMOVE){if(i)return;t.forEach(t=>{var i,r;if(t.colliderMeshes&&t.gizmoMeshes){let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,n=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=n,e.color&&(e.color=n.diffuseColor)})}})}e.type===sS.POINTERDOWN&&t.has(null===(r=e.pickInfo.pickedMesh)||void 0===r?void 0:r.parent)&&(i=!0,t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent).active=!0,t.forEach(t=>{var i,r;let s=((null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=s,e.color&&(e.color=s.diffuseColor)})})),e.type===sS.POINTERUP&&t.forEach(e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach(t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)})})}})}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}ur.PreserveScaling=!1,ur.UseAbsoluteScaling=!0,Object.defineProperty(sY.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new us(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(es||(es={}));class us{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new tj),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new tj),this._onSelectionChangedObservable)}constructor(e){if(this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||t2.LastCreatedScene,!this._scene)return;this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(let e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(let e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}let t=Object.assign(Object.assign({},us.Config),e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise(t=>{if(void 0===this.BJSINSPECTOR){let i=e&&e.inspectorURL?e.inspectorURL:us.InspectorURL;ss.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}function un(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],i=[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],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1,h=void 0===e.topBaseAt?1:e.topBaseAt,u=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,u=(u+4)%4;let c=[2,0,3,1][h],d=[2,0,1,3][u],p=[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(l){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],p=[-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]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],r=[17,18,19,16],s=[22,23,20,21];for(;c>0;)e.unshift(e.pop()),r.unshift(r.pop()),c--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),p=p.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}let _=[n/2,a/2,o/2];s=p.reduce((e,t,i)=>e.concat(t*_[i%3]),[]);let f=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE,m=e.faceUV||Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new t6(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new il(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,nx.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,nx.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,nx.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),r.push(m[e].z,nx.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);ng._ComputeSides(f,s,t,i,r,e.frontUVs,e.backUVs);let x=new ng;if(x.indices=t,x.positions=s,x.normals=i,x.uvs=r,g){let e=f===ng.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function ua(e,t={},i=null){let r=new nX(e,i);return t.sideOrientation=nX._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,un(t).applyToMesh(r,t.updatable),r}function uo(e){let t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,o=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new t5(i/2,r/2,s/2),u=2+t,c=2*u,d=[],p=[],_=[],f=[];for(let e=0;e<=u;e++){let t=e/u,i=t*Math.PI*a;for(let e=0;e<=c;e++){let r=e/c,s=r*Math.PI*2*n,a=t7.RotationZ(-i),o=t7.RotationY(s),l=t5.TransformCoordinates(t5.Up(),a),u=t5.TransformCoordinates(l,o),d=u.multiply(h),m=u.divide(h).normalize();p.push(d.x,d.y,d.z),_.push(m.x,m.y,m.z),f.push(r,nx.UseOpenGLOrientationForUV?1-t:t)}if(e>0){let t=p.length/3;for(let i=t-2*(c+1);i+c+21&&(d.push(i),d.push(i+1),d.push(i+c+1)),(em?m:Math.floor(g);let v=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE,x=e.uvs,T=e.colors,b=[],E=[],S=[],C=[],y=[],A=[],R=[],I=[],P=[],M=[];if(d.length<2){let e=[],t=[];for(r=0;r0&&(o=n[s].subtract(n[s-1]).length()+R[i],y[i].push(o),R[i]=o),s++;_&&(s--,b.push(n[0].x,n[0].y,n[0].z),o=n[s].subtract(n[0]).length()+R[i],y[i].push(o),R[i]=o),P[i]=a+O,M[i]=D,D+=a+O}let N=null,F=null;for(r=0;r{let s=r[0].length,n=0,a=o._originalBuilderSideOrientation===nX.DOUBLESIDE?2:1;for(let l=1;l<=a;++l)for(let a=0;a1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);let h=2*Math.PI*o,u=1===o?h/a:h/(a-1),c=0;for(let e=0;e0||c>0){switch(m=-d,g=-p,v=d,x=p,s){case nX.CENTER:l/=2,m-=l,v+=l;break;case nX.LEFT:v+=l,_=-l/2;break;case nX.RIGHT:m-=l,_=l/2}switch(n){case nX.CENTER:c/=2,g-=c,x+=c;break;case nX.BOTTOM:x+=c,f=-c/2;break;case nX.TOP:g-=c,f=c/2}}let T=[],b=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],(t===nX.ROTATE_TILE||t===nX.ROTATE_ROW)&&(E[1]=[1,1,0,1,0,0,1,0]),(t===nX.FLIP_TILE||t===nX.FLIP_ROW)&&(E[1]=[1,0,0,0,0,1,1,1]),(t===nX.FLIP_N_ROTATE_TILE||t===nX.FLIP_N_ROTATE_ROW)&&(E[1]=[0,1,1,1,1,0,0,0]);let S=[],C=[],y=[],A=0;for(let e=0;e0||c>0){let e,a,h,E;let R=c>0&&(n===nX.CENTER||n===nX.TOP),I=c>0&&(n===nX.CENTER||n===nX.BOTTOM),P=l>0&&(s===nX.CENTER||s===nX.RIGHT),M=l>0&&(s===nX.CENTER||s===nX.LEFT),D=[];if(R&&P&&(T.push(m+_,g+f,0),T.push(-d+_,g+f,0),T.push(-d+_,g+c+f,0),T.push(m+_,g+c+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,h=1,E=1,D=[e=1-l/i,a=1-c/r,h,a,h,E,e,E],t===nX.ROTATE_ROW&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),t===nX.FLIP_ROW&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),t===nX.FLIP_N_ROTATE_ROW&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),S=S.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R&&M&&(T.push(d+_,g+f,0),T.push(v+_,g+f,0),T.push(v+_,g+c+f,0),T.push(d+_,g+c+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,E=1,D=[e=0,a=1-c/r,h=l/i,a,h,E,e,E],(t===nX.ROTATE_ROW||t===nX.ROTATE_TILE&&o%2==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===nX.FLIP_ROW||t===nX.FLIP_TILE&&o%2==0)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===nX.FLIP_N_ROTATE_ROW||t===nX.FLIP_N_ROTATE_TILE&&o%2==0)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),S=S.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),I&&P&&(T.push(m+_,p+f,0),T.push(-d+_,p+f,0),T.push(-d+_,x+f,0),T.push(m+_,x+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,a=0,h=1,D=[e=1-l/i,a,h,a,h,E=c/r,e,E],(t===nX.ROTATE_ROW&&u%2==1||t===nX.ROTATE_TILE&&u%1==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===nX.FLIP_ROW&&u%2==1||t===nX.FLIP_TILE&&u%2==0)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===nX.FLIP_N_ROTATE_ROW&&u%2==1||t===nX.FLIP_N_ROTATE_TILE&&u%2==0)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),S=S.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),I&&M&&(T.push(d+_,p+f,0),T.push(v+_,p+f,0),T.push(v+_,x+f,0),T.push(d+_,x+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,D=[e=0,a=0,h=l/i,a,h,E=c/r,e,E],(t===nX.ROTATE_ROW&&u%2==1||t===nX.ROTATE_TILE&&(u+o)%2==1)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===nX.FLIP_ROW&&u%2==1||t===nX.FLIP_TILE&&(u+o)%2==1)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===nX.FLIP_N_ROTATE_ROW&&u%2==1||t===nX.FLIP_N_ROTATE_TILE&&(u+o)%2==1)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),S=S.concat(D),C.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),b.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R){let s=[];e=0,a=1-c/r,h=1,E=1,s[0]=[e,a,h,a,h,E,e,E],s[1]=[e,a,h,a,h,E,e,E],(t===nX.ROTATE_TILE||t===nX.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===nX.FLIP_TILE||t===nX.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===nX.FLIP_N_ROTATE_TILE||t===nX.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-E,e,1-E]);for(let e=0;e{let t=d/c*e,i=Math.cos(t);return new t5(o*(2+i)*.5*Math.cos(e),o*(2+i)*Math.sin(e)*.5,o*Math.sin(t)*.5)};for(t=0;t<=h;t++){let e=t%h/h*2*c*Math.PI,r=_(e),n=_(e+.01),o=n.subtract(r),d=n.add(r),p=t5.Cross(o,d);for(d=t5.Cross(p,o),p.normalize(),d.normalize(),i=0;iua(e,{size:t,sideOrientation:s,updatable:r},i),ng.CreateSphere=uo,nX.CreateSphere=(e,t,i,r,s,n)=>ul(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:s},r),nX.CreateCapsule=(e,t,i)=>(function(e,t={orientation:t5.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},i=null){let r=new nX(e,i);return uh(t).applyToMesh(r,t.updatable),r})(e,t,i),ng.CreateCapsule=uh,ng.CreateRibbon=uu,nX.CreateRibbon=(e,t,i=!1,r,s,n,a=!1,o,l)=>uc(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:a,sideOrientation:o,instance:l},n),ng.CreateDisc=ud,nX.CreateDisc=(e,t,i,r=null,s,n)=>up(e,{radius:t,tessellation:i,sideOrientation:n,updatable:s},r),ng.CreateTiledPlane=u_,ng.CreateTiledBox=function(e){let t=e.faceUV||Array(6),i=e.faceColors,r=e.pattern||nX.NO_FLIP,s=e.width||e.size||1,n=e.height||e.size||1,a=e.depth||e.size||1,o=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,u=e.alignVertical||0,c=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new t6(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new il(1,1,1,1));let d=[];for(let e=0;e<2;e++)d[e]=u_({pattern:r,tileWidth:o,tileHeight:l,width:s,height:n,alignVertical:u,alignHorizontal:h,sideOrientation:c});for(let e=2;e<4;e++)d[e]=u_({pattern:r,tileWidth:o,tileHeight:l,width:a,height:n,alignVertical:u,alignHorizontal:h,sideOrientation:c});let p=u;u===nX.BOTTOM?p=nX.TOP:u===nX.TOP&&(p=nX.BOTTOM);for(let e=4;e<6;e++)d[e]=u_({pattern:r,tileWidth:o,tileHeight:l,width:s,height:a,alignVertical:p,alignHorizontal:h,sideOrientation:c});let _=[],f=[],m=[],g=[],v=[],x=[],T=[],b=[],E=0,S=0;for(let e=0;e<6;e++){let r=d[e].positions.length;x[e]=[],T[e]=[];for(let t=0;te+S)),S+=x[e].length,i)for(let t=0;t<4;t++)v.push(i[e].r,i[e].g,i[e].b,i[e].a)}let C=new t5(0,0,a/2),y=t7.RotationY(Math.PI);_=x[0].map(e=>t5.TransformNormal(e,y).add(C)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),f=T[0].map(e=>t5.TransformNormal(e,y)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),_=_.concat(x[1].map(e=>e.subtract(C)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[1].map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let A=new t5(s/2,0,0),R=t7.RotationY(-Math.PI/2);_=_.concat(x[2].map(e=>t5.TransformNormal(e,R).add(A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[2].map(e=>t5.TransformNormal(e,R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let I=t7.RotationY(Math.PI/2);_=_.concat(x[3].map(e=>t5.TransformNormal(e,I).subtract(A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[3].map(e=>t5.TransformNormal(e,I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let P=new t5(0,n/2,0),M=t7.RotationX(Math.PI/2);_=_.concat(x[4].map(e=>t5.TransformNormal(e,M).add(P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[4].map(e=>t5.TransformNormal(e,M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let D=t7.RotationX(-Math.PI/2);_=_.concat(x[5].map(e=>t5.TransformNormal(e,D).subtract(P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[5].map(e=>t5.TransformNormal(e,D)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),ng._ComputeSides(c,_,g,f,m);let O=new ng;if(O.indices=g,O.positions=_,O.normals=f,O.uvs=m,i){let e=c===ng.DOUBLESIDE?v.concat(v):v;O.colors=e}return O},ng.CreateTorusKnot=uf,nX.CreateTorusKnot=(e,t,i,r,s,n,a,o,l,h)=>(function(e,t={},i){let r=new nX(e,i);return t.sideOrientation=nX._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,uf(t).applyToMesh(r,t.updatable),r})(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:n,q:a,sideOrientation:h,updatable:l},o);let um={effect:null,subMesh:null};class ug extends af{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new t7,this._cachedWorldViewProjectionMatrix=new t7,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},r)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return -1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);let i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var r,s,n;let a=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){if(a){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{let e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}}let o=this.getScene(),l=o.getEngine(),h=[],u=[],c=new aO,d=this._shaderPath,p=this._options.uniforms,_=this._options.uniformBuffers,f=this._options.samplers;l.getCaps().multiview&&o.activeCamera&&o.activeCamera.outputRenderTarget&&o.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,h.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e4&&(u.push(sf.MatricesIndicesExtraKind),u.push(sf.MatricesWeightsExtraKind));let t=e.skeleton;h.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(h.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(h.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else h.push("#define NUM_BONE_INFLUENCERS 0");let m=0,g=e?e.morphTargetManager:null;if(g){let e=g.supportsUVs&&-1!==h.indexOf("#define UV1"),t=g.supportsTangents&&-1!==h.indexOf("#define TANGENT"),i=g.supportsNormals&&-1!==h.indexOf("#define NORMAL");m=g.numInfluencers,e&&h.push("#define MORPHTARGETS_UV"),t&&h.push("#define MORPHTARGETS_TANGENT"),i&&h.push("#define MORPHTARGETS_NORMAL"),m>0&&h.push("#define MORPHTARGETS"),g.isUsingTextureForTargets&&(h.push("#define MORPHTARGETS_TEXTURE"),-1===this._options.uniforms.indexOf("morphTargetTextureIndices")&&this._options.uniforms.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),h.push("#define NUM_MORPH_INFLUENCERS "+m);for(let r=0;r0&&((p=p.slice()).push("morphTargetInfluences"),p.push("morphTargetTextureInfo"),p.push("morphTargetTextureIndices"))}else h.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(h.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===this._options.uniforms.indexOf("bakedVertexAnimationSettings")&&this._options.uniforms.push("bakedVertexAnimationSettings"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTime")&&this._options.uniforms.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),nw.PrepareAttributesForBakedVertexAnimation(u,e,h)}for(let e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&h.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(nD(p),nO(this,o,h)),this._useLogarithmicDepth&&(h.push("#define LOGARITHMICDEPTH"),-1===this._options.uniforms.indexOf("logarithmicDepthConstant")&&this._options.uniforms.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(p=p.slice(),_=_.slice(),f=f.slice(),d=this.customShaderNameResolve(d,p,_,f,h,u));let v=a?i._getDrawWrapper():this._drawWrapper,x=null!==(r=null==v?void 0:v.effect)&&void 0!==r?r:null,T=null!==(s=null==v?void 0:v.defines)&&void 0!==s?s:null,b=h.join("\n"),E=x;return T!==b&&(E=l.createEffect(d,{attributes:u,uniformsNames:p,uniformBuffersNames:_,samplers:f,defines:b,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},l),a?i.setEffect(E,b,this._materialContext):v&&v.setEffect(E,b),this._onEffectCreatedObservable&&(um.effect=E,um.subMesh=null!==(n=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==n?n:null,this._onEffectCreatedObservable.notifyObservers(um))),E._wasPreviouslyUsingInstances=!!t,!!(null==E?void 0:E.isReady())&&(x!==E&&o.resetCachedMaterial(),E._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){let i=this.getScene(),r=null!=t?t:this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var r;this.bind(e,t,null===(r=i._drawWrapperOverride)||void 0===r?void 0:r.effect,i)}bind(e,t,i,r){var s;let n=r&&this._storeEffectOnSubMeshes,a=null!=i?i:n?r.effect:this.getEffect();if(!a)return;let o=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);let l=this._options.uniformBuffers,h=!1;if(a&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&nw.BindMorphTargetParameters(t,a);let i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._textures)e.push(this._textures[t]);for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;tnew ug(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);for(let i in t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach(e=>{let t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))}),this.stencil.copyTo(t.stencil),this._textures)t.setTexture(i,this._textures[i]);for(let e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(let e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(let e in this._ints)t.setInt(e,this._ints[e]);for(let e in this._uints)t.setUInt(e,this._uints[e]);for(let e in this._floats)t.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(let e in this._colors3)t.setColor3(e,this._colors3[e]);for(let e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(let e in this._colors4)t.setColor4(e,this._colors4[e]);for(let e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(let e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(let e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(let e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(let e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(let e in this._matrices)t.setMatrix(e,this._matrices[e]);for(let e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(let e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(let e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(let e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(let e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(let e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(let e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(let e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(let e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){let t=this._textureArrays[e];for(let e=0;enew ug(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,n6.Parse(e.textures[r],t,i));for(r in e.textureArrays){let n=e.textureArrays[r],a=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>io.FromArray(e));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,il.FromArray(e.colors4[r]));for(r in e.colors4Arrays){let t=e.colors4Arrays[r].reduce((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>il.FromArray(e));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,t4.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,t5.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,t6.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,t8.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,t7.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,n)=>{let a=new i2;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=this.Parse(t,i||t2.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the ShaderMaterial")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,s)=>{let n=new i2;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(JSON.parse(n.responseText).jsonPayload).shaderMaterial),a=this.Parse(s,t||t2.LastCreatedScene,i);a.snippetId=e,r(a)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}ug.SnippetUrl="https://snippet.babylonjs.com",ug.CreateFromSnippetAsync=ug.ParseFromSnippetAsync,t0["BABYLON.ShaderMaterial"]=ug;let uv=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +#define VERTEXCOLOR +varying vec4 vColor; +#else +uniform vec4 color; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +gl_FragColor=vColor; +#else +gl_FragColor=color; +#endif +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.colorPixelShader=uv;let ux=`attribute vec3 position; +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.colorVertexShader=ux,nX._LinesMeshParser=(e,t)=>uT.Parse(e,t);class uT extends nX{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,r=null,s,n,a,o){super(e,t,i,r,s),this.useVertexColor=n,this.useVertexAlpha=a,this.color=new io(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let l={attributes:[sf.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===a?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(sf.ColorKind)):(l.uniforms.push("color"),this._color4=new il),o?this.material=o:(this.material=new ug("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=nB.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){let{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(nB.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(nB.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new uT(e,this.getScene(),t,this,i)}createInstance(e){let t=new ub(e,this);if(this.instancedBuffers)for(let e in t.instancedBuffers={},this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e];return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){let i=new uT(e.name,t);return i.color=io.FromArray(e.color),i.alpha=e.alpha,i}}class ub extends nY{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function uE(e){let t=[],i=[],r=e.lines,s=e.colors,n=[],a=0;for(let e=0;e0&&(t.push(a-1),t.push(a)),a++}}let o=new ng;return o.indices=t,o.positions=i,s&&(o.colors=n),o}function uS(e){let t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,n=[],a=[],o=t5.Zero(),l=0,h=0,u=0,c=0,d=0,p=0,_=0;for(_=0;_uy(e,{points:t,updatable:r,instance:s},i),nX.CreateDashedLines=(e,t,i,r,s,n=null,a,o)=>(function(e,t,i=null){let r=t.points,s=t.instance,n=t.gapSize||1,a=t.dashSize||3;if(s)return(t.dashNb||t.dashSize||t.gapSize||t.useVertexAlpha||t.material)&&ig.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),s.updateMeshPositions(e=>{let t=t5.Zero(),i=e.length/6,n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0;for(c=0;c{let i=new uA(e,this.elements.length);t.push(i),this.elements.push(i)}),t}computeBounds(){let e=new t4(this.elements[0].x,this.elements[0].y),t=new t4(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class uI{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new uR,this._outlinepoints=new uR,this._holes=[],this._epoints=[],this._eholes=[],this.bjsEarcut=r,this._name=e,this._scene=i||t2.LastCreatedScene,s=t instanceof sZ?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&ig.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new uR;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){let r=new nX(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(sf.PositionKind,s.positions,e),r.setVerticesData(sf.NormalKind,s.normals,e),r.setVerticesData(sf.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new ng,r=[],s=[],n=[],a=this._points.computeBounds();this._points.elements.forEach(e=>{r.push(0,1,0),s.push(e.x,0,e.y),n.push((e.x-a.min.x)/a.width,(e.y-a.min.y)/a.height)});let o=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){let i=s.length/3;this._points.elements.forEach(t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),n.push(1-(t.x-a.min.x)/a.width,1-(t.y-a.min.y)/a.height)});let l=o.length;for(let e=0;e{this._addSide(s,r,n,o,a,i,e,!0,t)})}return i.indices=o,i.positions=s,i.normals=r,i.uvs=n,i}_addSide(e,t,i,r,s,n,a,o,l){let h=e.length/3,u=0;for(let c=0;cl?E<-.999?new t5(d.x,0,d.y).subtract(new t5(p.x,0,p.y)).normalize():g.add(m).normalize():x;let S=t5.Dot(v,m);b=S>l?S<-.999?new t5(p.x,0,p.y).subtract(new t5(d.x,0,d.y)).normalize():v.add(m).normalize():x,i.push(u/s.width,0),i.push(u/s.width,1),u+=m.length(),i.push(u/s.width,0),i.push(u/s.width,1),t.push(T.x,T.y,T.z),t.push(T.x,T.y,T.z),t.push(b.x,b.y,b.z),t.push(b.x,b.y,b.z),o?(r.push(h),r.push(h+2),r.push(h+1),r.push(h+1),r.push(h+2),r.push(h+3)):(r.push(h),r.push(h+1),r.push(h+2),r.push(h+1),r.push(h+3),r.push(h+2)),h+=4}}}function uP(e,t,i,r,s,n,a){let o=i||[,,,],l=[],h=a||!1;for(let e=0;e<3;e++)void 0===o[e]&&(o[e]=new t6(0,0,1,1)),r&&void 0===r[e]&&(r[e]=new il(1,1,1,1));let u=e.getVerticesData(sf.PositionKind),c=e.getVerticesData(sf.NormalKind),d=e.getVerticesData(sf.UVKind),p=e.getIndices(),_=u.length/9,f=0,m=0,g=0,v=0,x=[0];if(h)for(let e=_;eMath.abs(c[e+1])&&(b=1),.001>Math.abs(c[e+1]-1)&&(b=0),.001>Math.abs(c[e+1]+1)&&(b=2),T=e/3,1===b?((f=T-_)%4<1.5?h?d[2*T]=o[b].x+(o[b].z-o[b].x)*x[Math.floor(f/4)]/v:d[2*T]=o[b].x:h?d[2*T]=o[b].x+(o[b].z-o[b].x)*x[Math.floor(f/4)+1]/v:d[2*T]=o[b].z,f%2==0?d[2*T+1]=nx.UseOpenGLOrientationForUV?1-o[b].w:o[b].w:d[2*T+1]=nx.UseOpenGLOrientationForUV?1-o[b].y:o[b].y):(d[2*T]=(1-d[2*T])*o[b].x+d[2*T]*o[b].z,d[2*T+1]=(1-d[2*T+1])*o[b].y+d[2*T+1]*o[b].w,nx.UseOpenGLOrientationForUV&&(d[2*T+1]=1-d[2*T+1])),r&&l.push(r[b].r,r[b].g,r[b].b,r[b].a);ng._ComputeSides(t,u,p,c,d,s,n);let E=new ng;if(E.indices=p,E.positions=u,E.normals=c,E.uvs=d,r){let e=t===ng.DOUBLESIDE?l.concat(l):l;E.colors=e}return E}function uM(e,t,i=null,r=earcut){t.sideOrientation=nX._GetDefaultSideOrientation(t.sideOrientation);let s=t.shape,n=t.holes||[],a=t.depth||0,o=t.smoothingThreshold||2,l=[],h=[];for(let e=0;e1),a=t.rotationFunction||(()=>0),o=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||nX.NO_CAP,u=t.updatable,c=t.firstNormal||null,d=t.adjustFrame||!1;return uN(e,s,r,null,null,n,a,o,l,h,!0,i,!!u,nX._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,c,d)}function uN(e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x){let T,b;let E=(e,t,i,r,s,n,a,o,l,h,u)=>{let c=i.getTangents(),d=i.getNormals(),p=i.getBinormals(),_=i.getDistances();if(u){for(let e=0;e0){let t=c[e-1];0>t5.Dot(t,c[e])&&c[e].scaleInPlace(-1),t=d[e-1],0>t5.Dot(t,d[e])&&d[e].scaleInPlace(-1),t=p[e-1],0>t5.Dot(t,p[e])&&p[e].scaleInPlace(-1)}}let f=0,m=h&&o?o:()=>null!==n?n:0,g=h&&a?a:()=>null!==s?s:1,v=l===nX.NO_CAP||l===nX.CAP_END?0:2,x=ie.Matrix[0];for(let i=0;i{let t;let i=[],r=t5.Zero();for(t=0;t3?0:h,u,x),closeArray:o,closePath:l,updatable:d,sideOrientation:p,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},c);return S._creationDataStorage.pathArray=b,S._creationDataStorage.path3D=T,S._creationDataStorage.cap=h,S}function uF(e){let t,i,r,s,n,a;let o=[];o[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},o[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},o[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},o[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},o[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},o[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},o[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},o[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},o[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},o[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},o[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},o[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},o[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},o[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},o[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};let l=e.type&&(e.type<0||e.type>=o.length)?0:e.type||0,h=e.size,u=e.sizeX||h||1,c=e.sizeY||h||1,d=e.sizeZ||h||1,p=e.custom||o[l],_=p.face.length,f=e.faceUV||Array(_),m=e.faceColors,g=void 0===e.flat||e.flat,v=0===e.sideOrientation?0:e.sideOrientation||ng.DEFAULTSIDE,x=[],T=[],b=[],E=[],S=[],C=0,y=0,A=[],R=0,I=0;if(g)for(I=0;I<_;I++)m&&void 0===m[I]&&(m[I]=new il(1,1,1,1)),f&&void 0===f[I]&&(f[I]=new t6(0,0,1,1));if(g)for(I=0;I<_;I++){let e=p.face[I].length;for(R=0,s=.5*Math.tan((r=2*Math.PI/e)/2),n=.5;RuM(e,{shape:t,holes:r,updatable:s,sideOrientation:n},i,a),nX.ExtrudePolygon=(e,t,i,r,s,n,a,o=earcut)=>(function(e,t,i=null,r=earcut){return uM(e,t,i,r)})(e,{shape:t,holes:s,depth:i,updatable:n,sideOrientation:a},r,o),nX.ExtrudeShape=(e,t,i,r,s,n,a=null,o,l,h)=>uD(e,{shape:t,path:i,scale:r,rotation:s,cap:0===n?0:n||nX.NO_CAP,sideOrientation:l,instance:h,updatable:o},a),nX.ExtrudeShapeCustom=(e,t,i,r,s,n,a,o,l,h,u,c)=>uO(e,{shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:a,cap:0===o?0:o||nX.NO_CAP,sideOrientation:u,instance:c,updatable:h},l),nX.CreateLathe=(e,t,i,r,s,n,a)=>(function(e,t,i=null){let r,s;let n=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,a=void 0===t.closed||t.closed,o=t.shape,l=t.radius||1,h=t.tessellation||64,u=t.clip||0,c=t.updatable,d=nX._GetDefaultSideOrientation(t.sideOrientation),p=t.cap||nX.NO_CAP,_=[],f=t.invertUV||!1,m=0,g=0,v=2*Math.PI/h*n;for(m=0;m<=h-u;m++){for(s=[],(p==nX.CAP_START||p==nX.CAP_ALL)&&(s.push(new t5(0,o[0].y,0)),s.push(new t5(Math.cos(m*v)*o[0].x*l,o[0].y,Math.sin(m*v)*o[0].x*l))),g=0;g(function(e,t,i=null){let r,s;let n=t.path,a=t.instance,o=1;void 0!==t.radius?o=t.radius:a&&(o=a._creationDataStorage.radius);let l=t.tessellation||64,h=t.radiusFunction||null,u=t.cap||nX.NO_CAP,c=t.invertUV||!1,d=t.updatable,p=nX._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;let _=(e,t,i,r,s,n,a,o)=>{let l,h,u,c;let d=t.getTangents(),p=t.getNormals(),_=t.getDistances(),f=2*Math.PI/s*o,m=n||(()=>r),g=ie.Matrix[0],v=a===nX.NO_CAP||a===nX.CAP_END?0:2;for(let t=0;t{let r=[];for(let s=0;s3?0:u,t.arc),closePath:!0,closeArray:!1,updatable:d,sideOrientation:p,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return f._creationDataStorage.pathArray=s,f._creationDataStorage.path3D=r,f._creationDataStorage.tessellation=l,f._creationDataStorage.cap=u,f._creationDataStorage.arc=t.arc,f._creationDataStorage.radius=o,f})(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:n,updatable:o,sideOrientation:l,instance:h},a),ng.CreatePolyhedron=uF,nX.CreatePolyhedron=(e,t,i)=>(function(e,t={},i=null){let r=new nX(e,i);return t.sideOrientation=nX._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,uF(t).applyToMesh(r,t.updatable),r})(e,t,i);let uw=new t5(1,0,0),uL=new t5(-1,0,0),uB=new t5(0,1,0),uU=new t5(0,-1,0),uV=new t5(0,0,1),uk=new t5(0,0,-1);class uG{constructor(e=t5.Zero(),t=t5.Up(),i=t4.Zero(),r=0,s=0,n=null,a=null,o=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=n,this.localNormalOverride=a,this.matrixIndicesOverride=o,this.matrixWeightsOverride=l}clone(){var e,t,i,r;return new uG(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,null===(e=this.localPositionOverride)||void 0===e?void 0:e.slice(),null===(t=this.localNormalOverride)||void 0===t?void 0:t.slice(),null===(i=this.matrixIndicesOverride)||void 0===i?void 0:i.slice(),null===(r=this.matrixWeightsOverride)||void 0===r?void 0:r.slice())}}nX.CreateDecal=(e,t,i,r,s,n)=>(function(e,t,i){var r,s,n,a;let o=!!t.skeleton,l=i.localMode||o,h=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,u=t.getIndices(),c=o?t.getPositionData(!0,!0):t.getVerticesData(sf.PositionKind),d=o?t.getNormalsData(!0,!0):t.getVerticesData(sf.NormalKind),p=l?o?t.getVerticesData(sf.PositionKind):c:null,_=l?o?t.getVerticesData(sf.NormalKind):d:null,f=t.getVerticesData(sf.UVKind),m=o?t.getVerticesData(sf.MatricesIndicesKind):null,g=o?t.getVerticesData(sf.MatricesWeightsKind):null,v=o?t.getVerticesData(sf.MatricesIndicesExtraKind):null,x=o?t.getVerticesData(sf.MatricesWeightsExtraKind):null,T=i.position||t5.Zero(),b=i.normal||t5.Up(),E=i.size||t5.One(),S=i.angle||0;if(!b){let e=new t5(0,0,1),i=t.getScene().activeCamera,r=t5.TransformCoordinates(e,i.getWorldMatrix());b=i.globalPosition.subtract(r)}let C=-Math.atan2(b.z,b.x)-Math.PI/2,y=Math.sqrt(b.x*b.x+b.z*b.z),A=Math.atan2(b.y,y),R=new ng;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=o?[]:null,R.matricesWeights=o?[]:null,R.matricesIndicesExtra=v?[]:null,R.matricesWeightsExtra=x?[]:null;let I=0,P=(e,t)=>{let r=new uG;if(!u||!c||!d)return r;let s=u[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new t5(c[3*s],c[3*s+1],c[3*s+2]),t5.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new t5(d[3*s],d[3*s+1],d[3*s+2]),t5.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&f){let e=f[2*s+1];r.uv=new t4(f[2*s],nx.UseOpenGLOrientationForUV?1-e:e)}return r},M=[0,0,0,0],D=(e,t)=>{if(0===e.length)return e;let i=.5*Math.abs(t5.Dot(E,t)),r=(e,t,i,r)=>{for(let s=0;s{var n,a,o,l,h,u,c,d,f,v,x,T,b,E,S,C;let y=t5.GetClipFactor(e.position,s.position,t,i),A=M,R=M;if(m&&g){let t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(n=e.matrixIndicesOverride)&&void 0!==n?n:m,h=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:g,u=s.matrixIndicesOverride?0:s.vertexIdxForBones,c=null!==(o=s.matrixIndicesOverride)&&void 0!==o?o:m,d=null!==(l=s.matrixWeightsOverride)&&void 0!==l?l:g;A=[0,0,0,0],R=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(h[t+e]>0){let s=r(c,i[t+e],u,4);A[p]=i[t+e],R[p]=tK.Lerp(h[t+e],s>=0?d[s]:0,y),p++}for(let e=0;e<4&&p<4;++e){let s=c[u+e];-1===r(i,s,t,4)&&(A[p]=s,R[p]=tK.Lerp(0,d[u+e],y),p++)}let _=R[0]+R[1]+R[2]+R[3];R[0]/=_,R[1]/=_,R[2]/=_,R[3]/=_}let I=e.localPositionOverride?e.localPositionOverride[0]:null!==(h=null==p?void 0:p[e.vertexIdx])&&void 0!==h?h:0,P=e.localPositionOverride?e.localPositionOverride[1]:null!==(u=null==p?void 0:p[e.vertexIdx+1])&&void 0!==u?u:0,D=e.localPositionOverride?e.localPositionOverride[2]:null!==(c=null==p?void 0:p[e.vertexIdx+2])&&void 0!==c?c:0,O=s.localPositionOverride?s.localPositionOverride[0]:null!==(d=null==p?void 0:p[s.vertexIdx])&&void 0!==d?d:0,N=s.localPositionOverride?s.localPositionOverride[1]:null!==(f=null==p?void 0:p[s.vertexIdx+1])&&void 0!==f?f:0,F=s.localPositionOverride?s.localPositionOverride[2]:null!==(v=null==p?void 0:p[s.vertexIdx+2])&&void 0!==v?v:0,w=e.localNormalOverride?e.localNormalOverride[0]:null!==(x=null==_?void 0:_[e.vertexIdx])&&void 0!==x?x:0,L=e.localNormalOverride?e.localNormalOverride[1]:null!==(T=null==_?void 0:_[e.vertexIdx+1])&&void 0!==T?T:0,B=e.localNormalOverride?e.localNormalOverride[2]:null!==(b=null==_?void 0:_[e.vertexIdx+2])&&void 0!==b?b:0,U=s.localNormalOverride?s.localNormalOverride[0]:null!==(E=null==_?void 0:_[s.vertexIdx])&&void 0!==E?E:0,V=s.localNormalOverride?s.localNormalOverride[1]:null!==(S=null==_?void 0:_[s.vertexIdx+1])&&void 0!==S?S:0,k=s.localNormalOverride?s.localNormalOverride[2]:null!==(C=null==_?void 0:_[s.vertexIdx+2])&&void 0!==C?C:0,G=w+(U-w)*y,z=L+(V-L)*y,W=B+(k-B)*y,H=Math.sqrt(G*G+z*z+W*W);return new uG(t5.Lerp(e.position,s.position,y),t5.Lerp(e.normal,s.normal,y).normalize(),t4.Lerp(e.uv,s.uv,y),-1,-1,p?[I+(O-I)*y,P+(N-P)*y,D+(F-D)*y]:null,_?[G/H,z/H,W/H]:null,A,R)},n=null;e.length>3&&(n=[]);for(let r=0;r0,_=c>0,f=d>0;switch((p?1:0)+(_?1:0)+(f?1:0)){case 0:e.length>3?(n.push(e[r]),n.push(e[r+1]),n.push(e[r+2])):n=e;break;case 1:if(n=null!=n?n:[],p&&(a=e[r+1],o=e[r+2],l=s(e[r],a),h=s(e[r],o)),_){a=e[r],o=e[r+2],l=s(e[r+1],a),h=s(e[r+1],o),n.push(l),n.push(o.clone()),n.push(a.clone()),n.push(o.clone()),n.push(l.clone()),n.push(h);break}f&&(a=e[r],o=e[r+1],l=s(e[r+2],a),h=s(e[r+2],o)),a&&o&&l&&h&&(n.push(a.clone()),n.push(o.clone()),n.push(l),n.push(h),n.push(l.clone()),n.push(o.clone()));break;case 2:n=null!=n?n:[],p||(o=s(a=e[r].clone(),e[r+1]),l=s(a,e[r+2]),n.push(a),n.push(o),n.push(l)),_||(o=s(a=e[r+1].clone(),e[r+2]),l=s(a,e[r]),n.push(a),n.push(o),n.push(l)),f||(o=s(a=e[r+2].clone(),e[r]),l=s(a,e[r+1]),n.push(a),n.push(o),n.push(l))}}return n},O=t instanceof nX?t:null,N=null==O?void 0:O._thinInstanceDataStorage.matrixData,F=(null==O?void 0:O.thinInstanceCount)||1,w=ie.Matrix[0];w.copyFrom(t7.IdentityReadOnly);for(let e=0;e=-t[0].normal.z&&0>=-t[1].normal.z&&0>=-t[2].normal.z)&&(t=D(t,uw))&&(t=D(t,uL))&&(t=D(t,uB))&&(t=D(t,uU))&&(t=D(t,uV))&&(t=D(t,uk)))for(let e=0;et.vecToidx[e+i]))}mapABOBtoDATA(e,t){let i=t.IDATA.edgematch[e][0];for(let r=0;r-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);let r=[];for(let e=0;e<12;e++)r[e]=e;let s=12;for(let e=0;e<12;e++){t[e].sort((e,t)=>e[1]-t[1]);for(let i=0;ie[3]-t[3]);for(let e=0;e0;)s=t[o],this.face[s].indexOf(a)>-1?(n=(this.face[s].indexOf(a)+1)%3,a=this.face[s][n],i.push(a),r.push(s),t.splice(o,1),o=0):o++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){let e=new uW("GeoDual","Goldberg",[],[]);e.name="GD dual";let t=this.vertex.length,i=Array(t);for(let e=0;e{r=0,s=0,n=0,a=this.face[t];for(let e=0;e<3;e++)o=this.vertex[a[e]],r+=o[0],s+=o[1],n+=o[2];e.vertex[t]=[r/3,s/3,n/3]});return e}static BuildGeodesicData(e){let t=new uH("Geodesic-m-n","Geodesic",[[0,tq,-1],[-tq,1,0],[-1,0,-tq],[1,0,-tq],[tq,1,0],[0,tq,1],[-1,0,tq],[-tq,-1,0],[0,-tq,-1],[tq,-1,0],[1,0,tq],[0,-tq,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;iuX.Parse(e,t);class uX extends nX{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(ig.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(ig.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(ig.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(r=1),u.push(r,s);for(let e=0;e<6;e++)r=o.x+l*Math.cos(h+e*Math.PI/3),s=o.y+l*Math.sin(h+e*Math.PI/3),r<0&&(r=0),r>1&&(r=1),c.push(r,s);for(let e=n;eil.FromArray(e)),i.faceCenters=i.faceCenters.map(e=>t5.FromArray(e)),i.faceZaxis=i.faceZaxis.map(e=>t5.FromArray(e)),i.faceXaxis=i.faceXaxis.map(e=>t5.FromArray(e)),i.faceYaxis=i.faceYaxis.map(e=>t5.FromArray(e));let r=new uX(e.name,t);return r.goldbergData=i,r}}class uY{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new sZ(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,n){this._currentPath.addBezierCurveTo(e,t,i,r,s,n,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}class uj{static CreateBoneWeightShader(e,t){var i,r,s,n,a,o;let l=e.skeleton,h=null!==(i=e.colorBase)&&void 0!==i?i:io.Black(),u=null!==(r=e.colorZero)&&void 0!==r?r:io.Blue(),c=null!==(s=e.colorQuarter)&&void 0!==s?s:io.Green(),d=null!==(n=e.colorHalf)&&void 0!==n?n:io.Yellow(),p=null!==(a=e.colorFull)&&void 0!==a?a:io.Red(),_=null!==(o=e.targetBoneIndex)&&void 0!==o?o:0;rN.ShadersStore["boneWeights:"+l.name+"VertexShader"]=`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + + #include + #if NUM_BONE_INFLUENCERS == 0 + attribute vec4 matricesIndices; + attribute vec4 matricesWeights; + #endif + #include + + #include + + varying vec3 vColor; + + uniform vec3 colorBase; + uniform vec3 colorZero; + uniform vec3 colorQuarter; + uniform vec3 colorHalf; + uniform vec3 colorFull; + + uniform float targetBoneIndex; + + void main() { + vec3 positionUpdated = position; + + #include + #include + #include + + vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); + + vec3 color = colorBase; + float totalWeight = 0.; + if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ + totalWeight += matricesWeights[0]; + } + if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ + totalWeight += matricesWeights[1]; + } + if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ + totalWeight += matricesWeights[2]; + } + if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ + totalWeight += matricesWeights[3]; + } + + color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); + color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); + color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); + color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); + vColor = color; + + gl_Position = projection * view * worldPos; + }`,rN.ShadersStore["boneWeights:"+l.name+"FragmentShader"]=` + precision highp float; + varying vec3 vPosition; + + varying vec3 vColor; + + void main() { + vec4 color = vec4(vColor, 1.0); + gl_FragColor = color; + } + `;let f=new ug("boneWeight:"+l.name,t,{vertex:"boneWeights:"+l.name,fragment:"boneWeights:"+l.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return f.setColor3("colorBase",h),f.setColor3("colorZero",u),f.setColor3("colorQuarter",c),f.setColor3("colorHalf",d),f.setColor3("colorFull",p),f.setFloat("targetBoneIndex",_),f.getClassName=()=>"BoneWeightShader",f.transparencyMode=nB.MATERIAL_OPAQUE,f}static CreateSkeletonMapShader(e,t){var i;let r=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new io(1,.38,.18),location:0},{color:new io(.59,.18,1),location:.2},{color:new io(.59,1,.18),location:.4},{color:new io(1,.87,.17),location:.6},{color:new io(1,.17,.42),location:.8},{color:new io(.17,.68,1),location:1}],n=r.bones.length+1,a=uj._CreateBoneMapColorBuffer(n,s,t),o=new ug("boneWeights:"+r.name,t,{vertexSource:`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + uniform float colorMap[`+4*r.bones.length+`]; + + #include + #if NUM_BONE_INFLUENCERS == 0 + attribute vec4 matricesIndices; + attribute vec4 matricesWeights; + #endif + #include + #include + + varying vec3 vColor; + + void main() { + vec3 positionUpdated = position; + + #include + #include + #include + + vec3 color = vec3(0.); + bool first = true; + + for (int i = 0; i < 4; i++) { + int boneIdx = int(matricesIndices[i]); + float boneWgt = matricesWeights[i]; + + vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); + + if (boneWgt > 0.) { + if (first) { + first = false; + color = c; + } else { + color = mix(color, c, boneWgt); + } + } + } + + vColor = color; + + vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); + + gl_Position = projection * view * worldPos; + }`,fragmentSource:` + precision highp float; + varying vec3 vColor; + + void main() { + vec4 color = vec4( vColor, 1.0 ); + gl_FragColor = color; + } + `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",a),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=nB.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){let r=new hO("temp",{width:e,height:1},i,!1),s=r.getContext(),n=s.createLinearGradient(0,0,e,0);t.forEach(e=>{n.addColorStop(e.location,e.color.toHexString())}),s.fillStyle=n,s.fillRect(0,0,e,1),r.update();let a=[],o=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;euj.DISPLAY_SPHERE_AND_SPURS&&(e=uj.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,n={}){var a,o,l,h,u,c,d,p,_,f,m,g,v,x;if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=n,this.color=io.White(),this._debugLines=[],this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=null===(a=n.pauseAnimations)||void 0===a||a,n.returnToRest=null!==(o=n.returnToRest)&&void 0!==o&&o,n.displayMode=null!==(l=n.displayMode)&&void 0!==l?l:uj.DISPLAY_LINES,n.displayOptions=null!==(h=n.displayOptions)&&void 0!==h?h:{},n.displayOptions.midStep=null!==(u=n.displayOptions.midStep)&&void 0!==u?u:.235,n.displayOptions.midStepFactor=null!==(c=n.displayOptions.midStepFactor)&&void 0!==c?c:.155,n.displayOptions.sphereBaseSize=null!==(d=n.displayOptions.sphereBaseSize)&&void 0!==d?d:.15,n.displayOptions.sphereScaleUnit=null!==(p=n.displayOptions.sphereScaleUnit)&&void 0!==p?p:2,n.displayOptions.sphereFactor=null!==(_=n.displayOptions.sphereFactor)&&void 0!==_?_:.865,n.displayOptions.spurFollowsChild=null!==(f=n.displayOptions.spurFollowsChild)&&void 0!==f&&f,n.displayOptions.showLocalAxes=null!==(m=n.displayOptions.showLocalAxes)&&void 0!==m&&m,n.displayOptions.localAxesSize=null!==(g=n.displayOptions.localAxesSize)&&void 0!==g?g:.075,n.computeBonesUsingShaders=null===(v=n.computeBonesUsingShaders)||void 0===v||v,n.useAllBones=null===(x=n.useAllBones)||void 0===x||x,this._boneIndices=new Set,!n.useAllBones){let e=null==t?void 0:t.getVerticesData(sf.MatricesIndicesKind),i=null==t?void 0:t.getVerticesData(sf.MatricesWeightsKind);if(e&&i)for(let t=0;tuj.DISPLAY_SPHERE_AND_SPURS&&(T=uj.DISPLAY_LINES),this.displayMode=T,this.update(),this._bindObs()}_bindObs(){this.displayMode===uj.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case uj.DISPLAY_LINES:this._displayLinesUpdate();break;case uj.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case uj.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,n=0){let a=ie.Matrix[0],o=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==n){let e=ie.Matrix[1];t7.IdentityToRef(e),e.setTranslationFromFloats(r,s,n),e.multiplyToRef(a,a)}o&&a.multiplyToRef(o.getAbsoluteMatrix(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]}_getLinesForBonesWithLength(e,t){let i,r;let s=e.length;t?(i=t.getWorldMatrix(),r=t.position):(i=new t7,r=e[0].position);let n=0;for(let t=0;t=0;n--){let r=e[n],a=r.getParent();if(!a||!this._boneIndices.has(r.getIndex())&&!this.options.useAllBones)continue;let o=this._debugLines[s];o||(o=[t5.Zero(),t5.Zero()],this._debugLines[s]=o),r.getAbsolutePositionToRef(t,o[0]),a.getAbsolutePositionToRef(t,o[1]),o[0].subtractInPlace(i),o[1].subtractInPlace(i),s++}n||t.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(null===e||-1===e._index){t.copyFrom(t7.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;let r=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,n=[],a=[],o=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,r.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY,l=this.options.displayOptions||{};for(let i=0;i{let s=new t7;i.getLocalMatrix().multiplyToRef(h,s);let n=new t5;s.decompose(void 0,void 0,n);let c=t5.Distance(u,n);if(c>t&&(t=c),e)return;let d=n.clone().subtract(u.clone()),p=d.length(),_=d.normalize().scale(p),f=l.midStep||.165,m=l.midStepFactor||.215,g=_.scale(f),v=uO("skeletonViewer",{shape:[new t5(1,-1,0),new t5(1,1,0),new t5(-1,1,0),new t5(-1,-1,0),new t5(1,-1,0)],path:[t5.Zero(),g,_],scaleFunction:e=>{switch(e){case 0:case 2:break;case 1:return p*m}return 0},sideOrientation:nX.DEFAULTSIDE,updatable:!1},r),x=v.getTotalVertices(),T=[],b=[];for(let e=0;e9?b.push(i.getIndex(),0,0,0):b.push(o.getIndex(),0,0,0);v.position=u.clone(),v.setVerticesData(sf.MatricesWeightsKind,T,!1),v.setVerticesData(sf.MatricesIndicesKind,b,!1),v.convertToFlatShadedMesh(),a.push(v)});let c=l.sphereBaseSize||.2,d=ul("skeletonViewer",{segments:6,diameter:c,updatable:!0},r),p=d.getTotalVertices(),_=[],f=[];for(let e=0;e{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;let e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))})):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},nC.prototype._getGlAlgorithmType=function(e){return e===nM.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(nM.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(nM.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new uq),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(nM.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(nM.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(nM.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(nM.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(nM.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),nM.prototype._checkOcclusionQuery=function(){let e=this._occlusionDataStorage;if(e.occlusionType===nM.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;let t=this.getEngine();if(!t.getCaps().supportOcclusionQuery||!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery){if(t.isQueryResultAvailable(this._occlusionQuery)){let i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,-1===e.occlusionRetryCount||!(e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==nM.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==nM.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}let i=this.getScene();if(i.getBoundingBoxRenderer){let r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded},nC.prototype.createTransformFeedback=function(){let e=this._gl.createTransformFeedback();if(!e)throw Error("Unable to create Transform Feedback");return e},nC.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},nC.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},nC.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},nC.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},nC.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},nC.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},r$.prototype.createExternalTexture=function(e){return null},r$.prototype.setExternalTexture=function(e,t){throw Error("setExternalTexture: This engine does not support external textures!")},r$.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;let r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);let t=e._workingCanvas.getContext("2d");if(!t)throw Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},r$.prototype.restoreSingleAttachment=function(){let e=this._gl;this.bindAttachments([e.BACK])},r$.prototype.restoreSingleAttachmentForRenderTarget=function(){let e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},r$.prototype.buildTextureLayout=function(e){let t=this._gl,i=[];for(let r=0;r1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(h=t.depthTextureFormat)),T.label=null!==(r=null==t?void 0:t.label)&&void 0!==r?r:"MultiRenderTargetWrapper";let b=this._gl,E=b.createFramebuffer();this._bindUnboundFramebuffer(E);let S=e.width||e,C=e.height||e,y=[],A=[],R=this.webGLVersion>1&&l&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),I=this._setupFramebufferDepthAttachments(!R&&o,!l&&a,S,C);T._framebuffer=E,T._depthStencilBuffer=I,T._generateDepthBuffer=!l&&a,T._generateStencilBuffer=!R&&o,T._attachments=A;for(let e=0;e1||this.isWebGPU);let u=this.webGLVersion>1,g=b[u?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(A.push(g),-1===o)continue;let v=new rU(this,m.MultiRenderTarget);y[e]=v,b.activeTexture(b["TEXTURE"+e]),b.bindTexture(o,v._hardwareTexture.underlyingResource),b.texParameteri(o,b.TEXTURE_MAG_FILTER,h.mag),b.texParameteri(o,b.TEXTURE_MIN_FILTER,h.min),b.texParameteri(o,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(o,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE);let T=this._getRGBABufferInternalSizedFormat(i,a,r),E=this._getInternalFormat(a),R=this._getWebGLTextureType(i);if(u&&(35866===o||32879===o))35866===o?v.is2DArray=!0:v.is3D=!0,v.baseDepth=v.depth=l,b.texImage3D(o,0,T,S,C,l,0,E,R,null);else if(34067===o){for(let e=0;e<6;e++)b.texImage2D(b.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,T,S,C,0,E,R,null);v.isCube=!0}else b.texImage2D(b.TEXTURE_2D,0,T,S,C,0,E,R,null);n&&b.generateMipmap(o),this._bindTextureDirectly(o,null),v.baseWidth=S,v.baseHeight=C,v.width=S,v.height=C,v.isReady=!0,v.samples=1,v.generateMipMaps=n,v.samplingMode=t,v.type=i,v._useSRGBBuffer=r,v.format=a,this._internalTexturesCache.push(v)}if(l&&this._caps.depthTextureExtension){let e=new rU(this,m.Depth),t=5,i=b.DEPTH_COMPONENT16,r=b.DEPTH_COMPONENT,s=b.UNSIGNED_SHORT,a=b.DEPTH_ATTACHMENT;this.webGLVersion<2?i=b.DEPTH_COMPONENT:14===h?(t=1,s=b.FLOAT,i=b.DEPTH_COMPONENT32F):18===h?(t=0,s=b.FLOAT_32_UNSIGNED_INT_24_8_REV,i=b.DEPTH32F_STENCIL8,r=b.DEPTH_STENCIL,a=b.DEPTH_STENCIL_ATTACHMENT):16===h?(t=0,s=b.UNSIGNED_INT,i=b.DEPTH_COMPONENT24,a=b.DEPTH_ATTACHMENT):(13===h||17===h)&&(t=12,s=b.UNSIGNED_INT_24_8,i=b.DEPTH24_STENCIL8,r=b.DEPTH_STENCIL,a=b.DEPTH_STENCIL_ATTACHMENT),b.activeTexture(b.TEXTURE0),b.bindTexture(b.TEXTURE_2D,e._hardwareTexture.underlyingResource),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MAG_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_MIN_FILTER,b.NEAREST),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_S,b.CLAMP_TO_EDGE),b.texParameteri(b.TEXTURE_2D,b.TEXTURE_WRAP_T,b.CLAMP_TO_EDGE),b.texImage2D(b.TEXTURE_2D,0,i,S,C,0,r,s,null),b.framebufferTexture2D(b.FRAMEBUFFER,a,b.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=S,e.baseHeight=C,e.width=S,e.height=C,e.isReady=!0,e.samples=1,e.generateMipMaps=n,e.samplingMode=1,e.format=h,e.type=t,y[u]=e,this._internalTexturesCache.push(e)}return T.setTextures(y),i&&b.drawBuffers(A),this._bindUnboundFramebuffer(null),T.setLayerAndFaceIndices(v,g),this.resetTextureCache(),T},r$.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let r=e._attachments.length;if(0===r)return 1;let s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);let n=!!e._depthStencilBuffer;if(n&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){let n=s.createFramebuffer();if(!n)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);let a=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(r.width,r.height,t,-1,this._getRGBABufferInternalSizedFormat(r.type,r.format,r._useSRGBBuffer),o);if(!l)throw Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),r.samples=t,a.push(o)}i&&s.drawBuffers(a)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},r$.prototype._createDepthStencilCubeTexture=function(e,t,i){let r=new rU(this,m.DepthStencil);if(r.isCube=!0,1===this.webGLVersion)return ig.Error("Depth cube texture is not supported by WebGL 1."),r;let s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),n=this._gl;this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=r,i._depthStencilTextureWithStencil=s.generateStencil;for(let t=0;t<6;t++)s.generateStencil?n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH24_STENCIL8,e,e,0,n.DEPTH_STENCIL,n.UNSIGNED_INT_24_8,null):n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH_COMPONENT24,e,e,0,n.DEPTH_COMPONENT,n.UNSIGNED_INT,null);return this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(r),r},r$.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)},void 0,void 0,!0,(e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)})},r$.prototype._cascadeLoadFiles=function(e,t,i,r=null){let s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},r$.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,n){let a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(r[o],o,a,e,t,i,s,n)},r$.prototype._partialLoadImg=function(e,t,i,r,s,n,a=null,o){let l=sr();r4(e,e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(l),6===i._internalCount&&n&&n(s,i)},(e,t)=>{r&&r.removePendingData(l),a&&a(e,t)},r?r.offlineProvider:null,o),r&&r.addPendingData(l)},r$.prototype._setCubeMapTextureParams=function(e,t,i){let r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),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),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},r$.prototype.createCubeTextureBase=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=null,p=null,_=!1){let f=c||new rU(this,m.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!r,f._lodGenerationScale=h,f._lodGenerationOffset=u,f._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!r),f!==c&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=o,f._files=i);let g=e;this._transformTextureUrl&&!c&&(e=this._transformTextureUrl(e));let v=e.split("?")[0],x=v.lastIndexOf("."),T=o||(x>-1?v.substring(x).toLowerCase():""),b=null;for(let e of r$._TextureLoaders)if(e.canLoad(T)){b=e;break}if(b){let c=e=>{d&&d(f,e),b.loadCubeData(e,f,l,s,n)};i&&6===i.length?b.supportCascades?this._cascadeLoadFiles(t,e=>c(e.map(e=>new Uint8Array(e))),i,n):n?n("Textures type does not support cascades."):ig.Warn("Texture loader does not support cascades."):this._loadFile(e,e=>c(new Uint8Array(e)),void 0,void 0,!0,(c,m)=>{e===g?n&&c&&n(c.status+" "+c.statusText,m):(ig.Warn(`Failed to load ${e}, falling back to the ${g}`),this.createCubeTextureBase(g,t,i,!!r,s,n,a,o,l,h,u,f,d,p,_))})}else{if(!i||0===i.length)throw Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,f,(e,t)=>{p&&p(e,t)},i,n)}return this._internalTexturesCache.push(f),f},r$.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),(e,t)=>{let i=this.needPOTTextures?r$.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);let o=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA,l=a?this._getInternalFormat(a):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(l=o);for(let e=0;ee&&(e===t||e.match(RegExp("\\b"+t+"\\b","g")))))return e;let t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}Object.defineProperty(nC.prototype,"onBeforeViewRenderObservable",{get:function(){return uQ}}),Object.defineProperty(nC.prototype,"onAfterViewRenderObservable",{get:function(){return uZ}}),Object.defineProperty(nC.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){var t;this._inputElement!==e&&(this._inputElement=e,null===(t=this._onEngineViewChanged)||void 0===t||t.call(this))}}),nC.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},nC.prototype.registerView=function(e,t,i){for(let t of(this.views||(this.views=[]),this.views))if(t.target===e)return t;let r=this.getRenderingCanvas();r&&(e.width=r.width,e.height=r.height);let s={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(s),t&&!Array.isArray(t)&&t.onDisposeObservable.add(()=>{this.unRegisterView(e)}),s},nC.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(let t of this.views)if(t.target===e){let e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},nC.prototype._renderViewStep=function(e){let t=e.target,i=t.getContext("2d");if(!i)return!0;let r=this.getRenderingCanvas();uQ.notifyObservers(e);let s=e.camera,n=null,a=null,o=null;if(s&&(n=(o=Array.isArray(s)?s[0].getScene():s.getScene()).activeCamera,a=o.activeCameras,this.activeView=e,Array.isArray(s)?o.activeCameras=s:(o.activeCamera=s,o.activeCameras=null)),e.customResize)e.customResize(t);else{let e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!!r.width&&!!r.height&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),o&&(o.activeCameras=a,o.activeCamera=n),uZ.notifyObservers(e),!0)},nC.prototype._renderViews=function(){let e;if(!this.views||0===this.views.length||!this.getRenderingCanvas())return!1;for(let t of this.views)if(t.enabled){if(t.target===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return(!e||!!this._renderViewStep(e))&&(this.activeView=null,!0)},r$.prototype.createStorageBuffer=function(e,t){throw Error("createStorageBuffer: Unsupported method in this engine!")},r$.prototype.updateStorageBuffer=function(e,t,i,r){},r$.prototype.readFromStorageBuffer=function(e,t,i,r){throw Error("readFromStorageBuffer: Unsupported method in this engine!")},r$.prototype.setStorageBuffer=function(e,t){throw Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(nC.prototype,"texturesSupported",{get:function(){let e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(nC.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),nC.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},nC.prototype.setTextureFormatToUse=function(e){let t=this.texturesSupported;for(let i=0,r=t.length;i{this._flush()})}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}u0.DEFAULT_BUFFER_SIZE=65536;let u1=[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))],u2=[()=>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],u3=(e,t)=>u1[e]*u2[e](t),u4=[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 u5{constructor(){this.preScaled=!1,this.l00=t5.Zero(),this.l1_1=t5.Zero(),this.l10=t5.Zero(),this.l11=t5.Zero(),this.l2_2=t5.Zero(),this.l2_1=t5.Zero(),this.l20=t5.Zero(),this.l21=t5.Zero(),this.l22=t5.Zero()}addLight(e,t,i){ie.Vector3[0].set(t.r,t.g,t.b);let r=ie.Vector3[0],s=ie.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(u3(0,e),ie.Vector3[2]),this.l00.addInPlace(ie.Vector3[2]),s.scaleToRef(u3(1,e),ie.Vector3[2]),this.l1_1.addInPlace(ie.Vector3[2]),s.scaleToRef(u3(2,e),ie.Vector3[2]),this.l10.addInPlace(ie.Vector3[2]),s.scaleToRef(u3(3,e),ie.Vector3[2]),this.l11.addInPlace(ie.Vector3[2]),s.scaleToRef(u3(4,e),ie.Vector3[2]),this.l2_2.addInPlace(ie.Vector3[2]),s.scaleToRef(u3(5,e),ie.Vector3[2]),this.l2_1.addInPlace(ie.Vector3[2]),s.scaleToRef(u3(6,e),ie.Vector3[2]),this.l20.addInPlace(ie.Vector3[2]),s.scaleToRef(u3(7,e),ie.Vector3[2]),this.l21.addInPlace(ie.Vector3[2]),s.scaleToRef(u3(8,e),ie.Vector3[2]),this.l22.addInPlace(ie.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(u4[0]),this.l1_1.scaleInPlace(u4[1]),this.l10.scaleInPlace(u4[2]),this.l11.scaleInPlace(u4[3]),this.l2_2.scaleInPlace(u4[4]),this.l2_1.scaleInPlace(u4[5]),this.l20.scaleInPlace(u4[6]),this.l21.scaleInPlace(u4[7]),this.l22.scaleInPlace(u4[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(u1[0]),this.l1_1.scaleInPlace(u1[1]),this.l10.scaleInPlace(u1[2]),this.l11.scaleInPlace(u1[3]),this.l2_2.scaleInPlace(u1[4]),this.l2_1.scaleInPlace(u1[5]),this.l20.scaleInPlace(u1[6]),this.l21.scaleInPlace(u1[7]),this.l22.scaleInPlace(u1[8])}updateFromArray(e){return t5.FromArrayToRef(e[0],0,this.l00),t5.FromArrayToRef(e[1],0,this.l1_1),t5.FromArrayToRef(e[2],0,this.l10),t5.FromArrayToRef(e[3],0,this.l11),t5.FromArrayToRef(e[4],0,this.l2_2),t5.FromArrayToRef(e[5],0,this.l2_1),t5.FromArrayToRef(e[6],0,this.l20),t5.FromArrayToRef(e[7],0,this.l21),t5.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return t5.FromFloatsToRef(e[0],e[1],e[2],this.l00),t5.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),t5.FromFloatsToRef(e[6],e[7],e[8],this.l10),t5.FromFloatsToRef(e[9],e[10],e[11],this.l11),t5.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),t5.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),t5.FromFloatsToRef(e[18],e[19],e[20],this.l20),t5.FromFloatsToRef(e[21],e[22],e[23],this.l21),t5.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new u5().updateFromArray(e)}static FromPolynomial(e){let t=new u5;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 u6{constructor(){this.x=t5.Zero(),this.y=t5.Zero(),this.z=t5.Zero(),this.xx=t5.Zero(),this.yy=t5.Zero(),this.zz=t5.Zero(),this.xy=t5.Zero(),this.yz=t5.Zero(),this.zx=t5.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=u5.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){ie.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=ie.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),ie.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),ie.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(ie.Vector3[0]).addInPlace(ie.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(ie.Vector3[0]).subtractInPlace(ie.Vector3[1]),this.zz.copyFrom(e.l00),ie.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(ie.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 u6().updateFromHarmonics(e)}static FromArray(e){let t=new u6;return t5.FromArrayToRef(e[0],0,t.x),t5.FromArrayToRef(e[1],0,t.y),t5.FromArrayToRef(e[2],0,t.z),t5.FromArrayToRef(e[3],0,t.xx),t5.FromArrayToRef(e[4],0,t.yy),t5.FromArrayToRef(e[5],0,t.zz),t5.FromArrayToRef(e[6],0,t.yz),t5.FromArrayToRef(e[7],0,t.zx),t5.FromArrayToRef(e[8],0,t.xy),t}}let u8=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;function u7(e,t,i,r,s,n,a,o){let l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,r=null!=r?r:t.type,n=null!=n?n:t.format,a=null!=a?a:t.width,o=null!=o?o:t.height,-1===r&&(r=0),new Promise(h=>{let u=new aL("postprocess",e,null,null,1,null,s,l,!1,void 0,r,void 0,null,!1,n);u.externalTextureSamplerBinding=!0;let c=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:n});u.getEffect().executeWhenCompiled(()=>{u.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([u],c,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),u&&u.dispose(),c._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,h(t)})})}function u9(e){s||(s=new Float32Array(1),n=new Int32Array(s.buffer)),s[0]=e;let t=n[0],i=t>>16&32768,r=t>>12&2047,a=t>>23&255;return a<103?i:a>142?(i|=31744,i|=(255==a?0:1)&&8388607&t):a<113?(r|=2048,i|=(r>>114-a)+(r>>113-a&1)):(i|=a-112<<10|r>>1,i+=1&r)}function ce(e){let t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*6103515625e-14*(r/1024):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/1024)}rO.ShadersStore.rgbdDecodePixelShader=u8;let ct=async(e,t,i,r,s)=>{let n;let a=e.getScene(),o=a.getEngine();n=e.isCube?new aL("lodCube","lodCube",["lod","gamma"],null,1,null,n6.NEAREST_NEAREST_MIPNEAREST,o,!1,["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"][r]):new aL("lod","lod",["lod","gamma"],null,1,null,n6.NEAREST_NEAREST_MIPNEAREST,o),await new Promise(e=>{n.getEffect().executeWhenCompiled(()=>{e(0)})});let l=new a5("temp",{width:t,height:i},a,!1);n.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",s),t.setBool("gamma",e.gammaSpace)};let h=e.getInternalTexture();try{if(l.renderTarget&&h){let r=h.samplingMode;0!==s?e.updateSamplingMode(n6.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(n6.NEAREST_NEAREST),a.postProcessManager.directRender([n],l.renderTarget,!0),e.updateSamplingMode(r);let u=await o.readPixels(0,0,t,i),c=new Uint8Array(u.buffer,0,u.byteLength);return o.unBindFramebuffer(l.renderTarget),c}throw Error("Render to texture failed.")}finally{l.dispose(),n.dispose()}},ci={CreateResizedCopy:function(e,t,i,r=!0){let s=e.getScene(),n=s.getEngine(),a=new a5("resized"+e.name,{width:t,height:i},s,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);a.wrapU=e.wrapU,a.wrapV=e.wrapV,a.uOffset=e.uOffset,a.vOffset=e.vOffset,a.uScale=e.uScale,a.vScale=e.vScale,a.uAng=e.uAng,a.vAng=e.vAng,a.wAng=e.wAng,a.coordinatesIndex=e.coordinatesIndex,a.level=e.level,a.anisotropicFilteringLevel=e.anisotropicFilteringLevel,a._texture.isReady=!1,e.wrapU=n6.CLAMP_ADDRESSMODE,e.wrapV=n6.CLAMP_ADDRESSMODE;let o=new o3("pass",1,null,r?n6.BILINEAR_SAMPLINGMODE:n6.NEAREST_SAMPLINGMODE,n,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(t){t.setTexture("textureSampler",e)};let t=a.renderTarget;t&&(s.postProcessManager.directRender([o],t),n.unBindFramebuffer(t),a.disposeFramebufferObjects(),o.dispose(),a.getInternalTexture().isReady=!0)}),a},ApplyPostProcess:u7,ToHalfFloat:u9,FromHalfFloat:ce,GetTextureDataAsync:async function(e,t,i,r=0,s=0){return!e.isReady()&&e._texture&&await new Promise((t,i)=>{if(null===e._texture){i(0);return}e._texture.onLoadedObservable.addOnce(()=>{t(0)})}),await ct(e,t,i,r,s)}};class cr{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,n=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(n=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let a=()=>{let r=new aL("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);r.externalTextureSamplerBinding=!0;let s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});r.getEffect().executeWhenCompiled(()=>{r.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([r],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),r&&r.dispose(),s._swapAndDie(t),t.isReady=!0})};n&&(s?a():e.onLoadObservable.addOnce(a))}static EncodeTextureToRGBD(e,t,i=0){return u7("rgbdEncode",e,t,i,1,5)}}class cs{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}}class cn{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;let i,r;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();let s=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),a=e.readPixels(1,void 0,void 0,!1);e.isRenderTarget?(i=e.readPixels(3,void 0,void 0,!1),r=e.readPixels(2,void 0,void 0,!1)):(i=e.readPixels(2,void 0,void 0,!1),r=e.readPixels(3,void 0,void 0,!1));let o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,u=0;return(1==e.textureType||2==e.textureType)&&(u=1),new Promise(e=>{Promise.all([a,n,i,r,o,l]).then(([t,i,r,n,a,o])=>{let l={size:s,right:i,left:t,up:r,down:n,front:a,back:o,format:5,type:u,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(l))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){let t=new u5,i=0,r=2/e.size,s=.5*r,n=s-1;for(let a=0;a<6;a++){let o=this._FileFaces[a],l=e[o.name],h=n,u=5===e.format?4:3;for(let a=0;ag){let t=g/e;_*=t,f*=t,m*=t}}else _=tK.Clamp(_,0,g),f=tK.Clamp(f,0,g),m=tK.Clamp(m,0,g);let v=new io(_,f,m);t.addLight(d,v,p),i+=p,c+=r}h+=r}}let a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),u6.FromHarmonics(t)}}cn._FileFaces=[new cs("right",new t5(1,0,0),new t5(0,0,-1),new t5(0,-1,0)),new cs("left",new t5(-1,0,0),new t5(0,0,1),new t5(0,-1,0)),new cs("up",new t5(0,1,0),new t5(1,0,0),new t5(0,0,1)),new cs("down",new t5(0,-1,0),new t5(1,0,0),new t5(0,0,-1)),new cs("front",new t5(0,0,1),new t5(1,0,0),new t5(0,-1,0)),new cs("back",new t5(0,0,-1),new t5(-1,0,0),new t5(0,-1,0))],cn.MAX_HDRI_VALUE=4096,cn.PRESERVE_CLAMPED_COLORS=!1,n3.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(n3.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;this._texture.isReady&&!this._texture._sphericalPolynomialPromise&&(this._texture._sphericalPolynomialPromise=cn.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});let ca=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;rO.ShadersStore.rgbdEncodePixelShader=ca;let co="image/png",cl=[134,22,135,150,246,214,150,54];function ch(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(let e=0;e2)throw Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "2".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:co})}function cc(e,t){let i=(t=cu(t)).specular,r=tK.Log2(t.width);if(r=Math.round(r)+1,i.mipmaps.length!==6*r)throw Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);let s=Array(r);for(let t=0;t{if(i){let i=t.createTexture(null,!0,!0,null,1,null,e=>{d(e)},e);r.getEffect().executeWhenCompiled(()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,n,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),c())})}else{if(t._uploadImageToTexture(u,e,n,a),o){let i=l[a];i&&t._uploadImageToTexture(i._texture,e,n,0)}c()}})}function cp(e,t){let i=(t=cu(t)).irradiance;if(!i)return;let r=new u6;t5.FromArrayToRef(i.x,0,r.x),t5.FromArrayToRef(i.y,0,r.y),t5.FromArrayToRef(i.z,0,r.z),t5.FromArrayToRef(i.xx,0,r.xx),t5.FromArrayToRef(i.yy,0,r.yy),t5.FromArrayToRef(i.zz,0,r.zz),t5.FromArrayToRef(i.yz,0,r.yz),t5.FromArrayToRef(i.zx,0,r.zx),t5.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function c_(e,t,i,r){let s=r,n=0,a="";for(;s=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function cg(e){let t=0,i="",r=!1,s=[];for(;t=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:n,type:s,parameters:d,body:u,callIndex:0}),e=h+1;let p=t>0?this._sourceCode.substring(0,t):"",_=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&ig.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(let t of this._functionDescr){let{name:i,type:r,parameters:s,body:n}=t,a=0;for(;a{let t=[],i=0,r=0;for(;i0?this._sourceCode.substring(0,o):"",m=h+1=0&&"\n"!==e.charAt(t)&&(!r||e.charAt(t)!==r);)t--;return t}(this._sourceCode,o-1,0,"{");f=this._sourceCode.substring(0,e+1);let t=this._sourceCode.substring(e+1,o);this._sourceCode=f+r+" "+p+";\n"+_+"\n"+t+p+m,this.debug&&ig.Log(`Replace function call by code. Function '${i}' (type=${r}). injectDeclarationIndex=${e}, call parameters=${d}`)}else this._sourceCode=f+_+m,a+=_.length-(h+1-o),this.debug&&ig.Log(`Replace function call by code. Function '${i}' (type=${r}). functionCallIndex=${o}, call parameters=${d}`);e=!0}}return e}_replaceNames(e,t,i){for(let r=0;r{let o=s[0];return cm(e.charAt(o-1))||cm(e.charAt(o+n))?t[r]:a})}return e}}cv._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;class cx{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){let e=this.compilationError.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this._engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);for(this._engine.getUniforms(this,i).forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l{n[e]=t}),o.push(...h.getAttributes(this,a))}dispose(){this._uniforms={}}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setInt4(this._uniforms[e],t,i,r,s)&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setUInt4(this._uniforms[e],t,i,r,s)&&(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)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(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.toArray())&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}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,i){this._cacheFloat2(e,t,i)&&!this._engine.setFloat2(this._uniforms[e],t,i)&&(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,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setFloat3(this._uniforms[e],t,i,r)&&(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,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setFloat4(this._uniforms[e],t,i,r,s)&&(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(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)}}class cT extends aF{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class cb{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function cE(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new rc(`Unsupported texture format or type: format ${e}, type ${t}.`,ru.UnsupportedTextureError)}function cS(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw Error(`Unsupported sampling mode: ${e}.`)}}function cC(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw Error("Unexpected wrap mode: "+e+".")}}let cy=new tj;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{(e=t)&&cy.notifyObservers(e)}})}async function cA(e,t){(await new Promise(e=>{"undefined"==typeof _native?cy.addOnce(t=>e(t)):e(_native)}))[e]=t}class cR extends rz{}class cI{constructor(e){this._engine=e,this._pending=[],this._isCommandBufferScopeActive=!1,this._commandStream=cP._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}class cP extends nC{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new cI(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==cP.PROTOCOL_VERSION)throw Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${cP.PROTOCOL_VERSION} (JS)`);this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},ss.Log("Babylon Native (v"+nC.Version+") launched"),ss.LoadScript=function(e,t,i,r){ss.LoadFile(e,e=>{Function(e).apply(null),t&&t()},void 0,void 0,!1,(e,t)=>{i&&i("LoadScript Error",t)})},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){let t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,function(i,r){return Array.isArray(r)?i.push.apply(i,e.call(r,t-1)):i.push(r),i},[]):Array.prototype.slice.call(this)},writable:!0});let t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();let i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new rG,this.onNewSceneAddedObservable.add(e=>{let t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new u0}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,r=!1){if(this.useReverseDepthBuffer)throw Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){let r=this._normalizeIndexData(e),s=new cR;return s.references=1,s.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,null!=t&&t)),s}createVertexBuffer(e,t,i){let r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new cR;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,null!=t&&t)),s}_recordVertexArrayObject(e,t,i,r,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);let n=r.getAttributesNames();for(let i=0;i=0){let r=n[i],o=null;if(s&&(o=s[r]),o||(o=t[r]),o){let t=o.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,a,o.byteOffset,o.byteStride,o.getSize(),function(e){switch(e){case sf.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case sf.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case sf.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case sf.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case sf.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw Error(`Unsupported attribute type: ${e}.`)}}(o.type),o.normalized,o.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){let s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){return this._engine.getAttributes(e.nativeProgram,t)}drawElementsType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){return new cx(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,r,s,n,a,o){r?e.nativeProgram=this.createRawShaderProgram():e.nativeProgram=this.createShaderProgram(e,t,i,o)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){if(!this.isAsync(e)){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}createRawShaderProgram(){throw Error("Not Supported")}createShaderProgram(e,t,i,r){if(e.nativeProgram)throw Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=new cv(t);s.processCode(),t=s.code;let n=new cv(i);n.processCode(),i=n.code,t=r$._ConcatenateShader(t,r),i=r$._ConcatenateShader(i,r);let a=()=>{var t;e.isCompiled=!0,null===(t=e.onCompiled)||void 0===t||t.call(e),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,a,t=>{e.compilationError=t});try{let r=e.nativeProgram=this._engine.createProgram(t,i);return a(),r}catch(t){let e=null==t?void 0:t.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){let t=new cv(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){e&&e.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){return this._engine.getUniforms(e.nativeProgram,t)}bindUniformBlock(e,t,i){throw Error("Not Implemented")}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.nativeProgram);let i=e.getSamplers();for(let t=0;t{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw Error(`Unsupported stencil OpFail mode: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw Error(`Unsupported stencil depthFail mode: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw Error(`Unsupported stencil opPass mode: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw Error(`Unsupported stencil func mode: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;let i=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw Error(`Unsupported alpha mode: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){let i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){let r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new rU(this,m.Raw);if(c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c.baseWidth=t,c.baseHeight=i,c.width=c.baseWidth,c.height=c.baseHeight,c._compression=o,c.type=l,c._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this.updateRawTexture(c,e,r,n,o,l,c._useSRGBBuffer),c._hardwareTexture){let e=c._hardwareTexture.underlyingResource,t=cS(a);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(c),c}createRawTexture2DArray(e,t,i,r,s,n,a,o,l=null,h=0){let u=new rU(this,m.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=o,u.is2DArray=!0,u._hardwareTexture){let l=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,cE(s,h),n,a);let c=cS(o);this._setTextureSampling(l,c)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,r,s=null,n=0,a=!1){if(e){if(t&&e._hardwareTexture){let r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,cE(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_=!1){let f="data:"===(e=e||"").substr(0,5),g=f&&-1!==e.indexOf(";base64,"),v=l||new rU(this,m.Url),x=e;!this._transformTextureUrl||g||l||o||(e=this._transformTextureUrl(e));let T=e.lastIndexOf("."),b=u||(T>-1?e.substring(T).toLowerCase():""),E=null;for(let e of nC._TextureLoaders)if(e.canLoad(b)){E=e;break}r&&r.addPendingData(v),v.url=e,v.generateMipMaps=!t,v.samplingMode=s,v.invertY=i,v._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(v._buffer=o);let S=null;n&&!l&&(S=v.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(v);let C=(i,l)=>{r&&r.removePendingData(v),e===x?(S&&v.onLoadedObservable.remove(S),t2.UseFallbackTexture&&this.createTexture(t2.FallbackTexture,t,v.invertY,r,s,null,a,o,v),a&&a((i||"Unknown error")+(t2.UseFallbackTexture?" - Fallback texture was used":""),l)):(ig.Warn(`Failed to load ${e}, falling back to ${x}`),this.createTexture(x,t,v.invertY,r,s,n,a,o,v,h,u,c,d))};if(E)throw Error("Loading textures from IInternalTextureLoader not yet implemented.");{let n=e=>{if(!v._hardwareTexture){r&&r.removePendingData(v);return}let n=v._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,v._useSRGBBuffer,()=>{v.baseWidth=this._engine.getTextureWidth(n),v.baseHeight=this._engine.getTextureHeight(n),v.width=v.baseWidth,v.height=v.baseHeight,v.isReady=!0;let e=cS(s);this._setTextureSampling(n,e),r&&r.removePendingData(v),v.onLoadedObservable.notifyObservers(v),v.onLoadedObservable.clear()},()=>{throw Error("Could not load a native texture.")})};if(f&&o){if(o instanceof ArrayBuffer)n(new Uint8Array(o));else if(ArrayBuffer.isView(o))n(o);else if("string"==typeof o)n(new Uint8Array(ss.DecodeBase64(o)));else throw Error("Unsupported buffer type")}else g?n(new Uint8Array(ss.DecodeBase64(e))):this._loadFile(e,e=>n(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{C("Unable to load "+(e&&e.responseURL,t))})}return v}wrapNativeTexture(e,t=!1,i=3){let r=new cb(e,this._engine),s=new rU(this,m.Unknown,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){var r,s;let n=t.generateStencil||!1,a=t.samples||1,o=new rU(this,m.DepthStencil),l=null!==(r=e.width)&&void 0!==r?r:e,h=null!==(s=e.height)&&void 0!==s?s:e,u=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,n,!0,a);return i._framebufferDepthStencil=u,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise((t,i)=>{let r=this.createCanvasImage();r.onload=()=>{try{let e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e})}createImageBitmap(e,t){return new Promise((t,i)=>{if(Array.isArray(e)&&e.length){let i=this._engine.createImageBitmap(e[0]);if(i){t(i);return}}i("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=c||new rU(this,m.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!r,_._lodGenerationScale=h,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(p,!!r),this._doNotHandleContextLost||(_._extension=o,_._files=i);let f=e.lastIndexOf(".");if(".env"===(o||(f>-1?e.substring(f).toLowerCase():""))){let t=e=>{let t=ch(e);_.width=t.width,_.height=t.width,cp(_,t);let i=t.specular;if(!i)throw Error("Nothing else parsed so far");_._lodGenerationScale=i.lodGenerationScale;let r=cc(e,t);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(n6.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,r,!1,_._useSRGBBuffer,()=>{_.isReady=!0,s&&s()},()=>{throw Error("Could not load a native cube texture.")})};if(i&&6===i.length)throw Error("Multi-file loading not allowed on env files.");this._loadFile(e,e=>{t(new Uint8Array(e,0,e.byteLength))},void 0,void 0,!0,(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)})}else{if(!i||6!==i.length)throw Error("Cannot load cubemap because 6 files were not defined");Promise.all([i[0],i[3],i[1],i[4],i[2],i[5]].map(e=>this._loadFileAsync(e,void 0,!0).then(e=>new Uint8Array(e,0,e.byteLength)))).then(e=>new Promise((t,i)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,e,!r,!0,_._useSRGBBuffer,t,i)})).then(()=>{_.isReady=!0,s&&s()},e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new cb(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){let r=new cT(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=m.Unknown){var s,n,a;let o;let l=!1,h=0,u=3,c=5,d=!1,p=1;void 0!==t&&"object"==typeof t?(l=!!t.generateMipMaps,h=void 0===t.type?0:t.type,u=void 0===t.samplingMode?3:t.samplingMode,c=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,p=null!==(s=t.samples)&&void 0!==s?s:1,o=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(1!==h||this._caps.textureFloatLinearFiltering)&&(2!==h||this._caps.textureHalfFloatLinearFiltering)||(u=1),1!==h||this._caps.textureFloat||(h=0,ig.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let _=new rU(this,r),f=null!==(n=e.width)&&void 0!==n?n:e,g=null!==(a=e.height)&&void 0!==a?a:e,v=e.layers||0;if(0!==v)throw Error("Texture layers are not supported in Babylon Native");let x=_._hardwareTexture.underlyingResource,T=cE(c,h);return this._engine.initializeTexture(x,f,g,l,T,!0,d,p),this._setTextureSampling(x,cS(u)),_._useSRGBBuffer=d,_.baseWidth=f,_.baseHeight=g,_.width=f,_.height=g,_.depth=v,_.isReady=!0,_.samples=p,_.generateMipMaps=l,_.samplingMode=u,_.type=h,_.format=c,_.label=o,this._internalTexturesCache.push(_),_}createRenderTargetTexture(e,t){var i,r,s,n;let a;let o=this._createHardwareRenderTargetWrapper(!1,!1,e),l=!0,h=!1,u=!1,c=1;void 0!==t&&"object"==typeof t&&(l=null===(i=t.generateDepthBuffer)||void 0===i||i,h=!!t.generateStencilBuffer,u=!!t.noColorAttachment,a=t.colorAttachment,c=null!==(r=t.samples)&&void 0!==r?r:1);let d=a||(u?null:this._createInternalTexture(e,t,!0,m.RenderTarget)),p=null!==(s=e.width)&&void 0!==s?s:e,_=null!==(n=e.height)&&void 0!==n?n:e,f=this._engine.createFrameBuffer(d?d._hardwareTexture.underlyingResource:null,p,_,h,l,c);return o._framebuffer=f,o._generateDepthBuffer=l,o._generateStencilBuffer=h,o._samples=c,o.setTextures(d),o}updateRenderTargetTextureSampleCount(e,t){return ig.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){let i=cS(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw Error("Required width/height for frame buffers not yet supported in NativeEngine.");e._framebufferDepthStencil?this._bindUnboundFramebuffer(e._framebufferDepthStencil):this._bindUnboundFramebuffer(e._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){let r=this._normalizeIndexData(t);e.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(e.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i,r){let s=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(e.nativeVertexBuffer,s.buffer,s.byteOffset+(null!=i?i:0),null!=r?r:s.byteLength)}_setTexture(e,t,i=!1,r=!1){let s;let n=this._boundUniforms[e];if(!n)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;return s=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!!s&&!!s._hardwareTexture&&(this._setTextureWrapMode(s._hardwareTexture.underlyingResource,cC(t.wrapU),cC(t.wrapV),cC(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(n,s._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){let t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){let i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){let e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,r,s,n,a=0,o=0,l=!1){throw Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,a=0){throw Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,r,s,n,a,o,l,h){var u,c,d,p;if(void 0!==r&&-1!==r)throw Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture(null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(c=null==n?void 0:n.buffer)&&void 0!==c?c:null,null!==(d=null==n?void 0:n.byteOffset)&&void 0!==d?d:0,null!==(p=null==n?void 0:n.byteLength)&&void 0!==p?p:0).then(e=>(n||(n=new Uint8Array(e)),n))}}cP.PROTOCOL_VERSION=8,cP._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new cM:new u0};class cM extends u0{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}(function(e){e.LowPower="low-power",e.HighPerformance="high-performance"})(en||(en={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(ea||(ea={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(eo||(eo={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(el||(el={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(eh||(eh={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(eu||(eu={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(ec||(ec={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(ed||(ed={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(ep||(ep={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(e_||(e_={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(ef||(ef={})),function(e){e.Nearest="nearest",e.Linear="linear"}(em||(em={})),function(e){e.Nearest="nearest",e.Linear="linear"}(eg||(eg={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(ev||(ev={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(ex||(ex={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(eT||(eT={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(eb||(eb={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(eE||(eE={})),(eS||(eS={})).WriteOnly="write-only",function(e){e.Error="error",e.Warning="warning",e.Info="info"}(eC||(eC={})),function(e){e.Validation="validation",e.Internal="internal"}(ey||(ey={})),(eA||(eA={})).Auto="auto",function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(eR||(eR={})),function(e){e.CCW="ccw",e.CW="cw"}(eI||(eI={})),function(e){e.None="none",e.Front="front",e.Back="back"}(eP||(eP={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(eM||(eM={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(eD||(eD={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(eO||(eO={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(eN||(eN={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(eF||(eF={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(ew||(ew={})),function(e){e.Vertex="vertex",e.Instance="instance"}(eL||(eL={})),function(e){e.Beginning="beginning",e.End="end"}(eB||(eB={})),function(e){e.Beginning="beginning",e.End="end"}(eU||(eU={})),function(e){e.Load="load",e.Clear="clear"}(eV||(eV={})),function(e){e.Store="store",e.Discard="discard"}(ek||(ek={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(eG||(eG={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(ez||(ez={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(eW||(eW={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(eH||(eH={}));class cD{constructor(){this.shaderLanguage=f.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let t=0;t=0&&(c.push(a[l]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=c,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){for(let e of(this.uniformBuffer=new sp(this.engine,void 0,void 0,"leftOver-"+this._name),this.shaderProcessingContext.leftOverUniforms)){let t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=cD.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.vertex}_getFragmentShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.fragment}}let cN={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class cF{static get KnownUBOs(){return cF._SimplifiedKnownBindings?cF._SimplifiedKnownUBOs:cF._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){let e=cF.KnownUBOs,t=[];for(let i in e){let r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;let r=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=cN[e])&&void 0!==i?i:1)*(t||1),r}getVaryingNextLocation(e,t=0){var i;let r=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=cN[e])&&void 0!==i?i:1)*(t||1),r}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";let t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}cF._SimplifiedKnownBindings=!0,cF._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},cF._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class cw extends cD{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=f.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0,s=e.indexOf("["),n=e.indexOf("]");if(s>0&&n>0){let t=e.substring(s+1,n);isNaN(r=+t)&&(r=+i[t.trim()]),e=e.substr(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){let i=`// Internals UBO +uniform ${cD.InternalsUBOName} { +float yFactor_; +float textureOutputHeight_; +}; +`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){var r;this._preProcessors=i;let s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){let n;let a=null!==(r=s[1])&&void 0!==r?r:"",o=s[2],l=s[3];t?(n=this._webgpuProcessingContext.availableVaryings[l],this._missingVaryings[n]="",void 0===n&&ig.Warn(`Invalid fragment shader: The varying named "${l}" is not declared in the vertex shader! This declaration will be ignored.`)):(n=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(l,o,i)[2]),this._webgpuProcessingContext.availableVaryings[l]=n,this._missingVaryings[n]=`layout(location = ${n}) ${a} in ${o} ${l};`),e=e.replace(s[0],void 0===n?"":`layout(location = ${n}) ${a} ${t?"in":"out"} ${o} ${l};`)}return e}attributeProcessor(e,t){this._preProcessors=t;let i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){let r=i[1],s=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;let a=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==a){let t=`_int_${s}_`;e=e.replace(i[0],`layout(location = ${n}) in ${a<0?-1===a?"int":"ivec"+-a:1===a?"uint":"uvec"+a} ${t}; ${r} ${s} = ${r}(${t});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${r} ${s};`)}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;let s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let n=s[1],a=s[2];if(0===n.indexOf("sampler")||1===n.indexOf("sampler")){let s=0;[a,n,s]=this._getArraySize(a,n,i);let o=this._webgpuProcessingContext.availableTextures[a];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:eE.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}let l=null!==(r=cD._SamplerTypeByWebGLSamplerType[n])&&void 0!==r?r:"sampler",h=!!cD._IsComparisonSamplerByWebGPUSamplerType[l],u=h?eb.Comparison:eb.Filtering,c=a+cD.AutoSamplerSuffix,d=this._webgpuProcessingContext.availableSamplers[c];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:u});let p="u"===n.charAt(0)?"u":"i"===n.charAt(0)?"i":"";p&&(n=n.substr(1));let _=h?eE.Depth:"u"===p?eE.Uint:"i"===p?eE.Sint:eE.Float;o.sampleType=_;let f=s>0,m=d.binding.groupIndex,g=d.binding.bindingIndex,v=cD._SamplerFunctionByWebGLSamplerType[n],x=cD._TextureTypeByWebGLSamplerType[n],T=cD._GpuTextureViewDimensionByWebGPUTextureType[x];if(f){let t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${c};`),e=` +`;for(let i=0;i0?"\n":""}#define ${a}${i} ${p}${v}(${a}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(a)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${l} ${c}; + layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${p}${x} ${a}Texture; + #define ${a} ${p}${v}(${a}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[a]=o,this._webgpuProcessingContext.availableSamplers[c]=d,this._addSamplerBindingDescription(c,d,!t);for(let e=0;e=0,i=` + glFragCoord_ = gl_FragCoord; + if (yFactor_ == 1.) { + glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; + } + `,r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(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(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){let t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",t?"vec4 glFragCoord_;\n":""),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){let t=e.lastIndexOf("}");e=e.substring(0,t)+"gl_Position.y *= yFactor_;\n",s.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){let i=RegExp(t+"\\s*\\[(.+)?\\]","gm"),r=i.exec(e);for(;null!==r;){let s=r[1],n=+s;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+n),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { + `;for(let e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}]; +`:i+=` ${e.type} ${e.name}; +`;return i+"};\n\n"}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}let i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}let cL=`#if NUM_BONE_INFLUENCERS>0 +attribute matricesIndices : vec4;attribute matricesWeights : vec4; +#if NUM_BONE_INFLUENCERS>4 +attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +var boneSampler : texture_2d;uniform boneTextureWidth : f32; +#else +uniform mBones : array; +#ifdef BONES_VELOCITY_ENABLED +uniform mPreviousBones : array; +#endif +#endif +#ifdef BONETEXTURE +fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 +{let offset=i32(index) *4; +let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} +#endif +#endif +#endif +`;rO.IncludesShadersStoreWGSL.bonesDeclaration=cL;let cB=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +var influence : mat4x4; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; +#endif +#else +influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`;rO.IncludesShadersStoreWGSL.bonesVertex=cB;let cU=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; +#ifdef INSTANCES +attribute bakedVertexAnimationSettingsInstanced : vec4; +#endif +fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 +{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} +#endif +`;rO.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration=cU;let cV=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; +#else +let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; +#endif +let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`;rO.IncludesShadersStoreWGSL.bakedVertexAnimation=cV;let ck=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fragmentInputs.fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fragmentInputs.fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fragmentInputs.fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fragmentInputs.fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fragmentInputs.fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fragmentInputs.fClipDistance6>0.0) +{discard;} +#endif +`;rO.IncludesShadersStoreWGSL.clipPlaneFragment=ck;let cG=`#ifdef CLIPPLANE +varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +varying fClipDistance6: f32; +#endif +`;rO.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration=cG;let cz=`#ifdef CLIPPLANE +vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); +#endif +#ifdef CLIPPLANE2 +vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); +#endif +#ifdef CLIPPLANE3 +vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); +#endif +#ifdef CLIPPLANE4 +vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); +#endif +#ifdef CLIPPLANE5 +vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); +#endif +#ifdef CLIPPLANE6 +vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); +#endif +`;rO.IncludesShadersStoreWGSL.clipPlaneVertex=cz;let cW=`#ifdef CLIPPLANE +uniform vClipPlane: vec4;varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +uniform vClipPlane2: vec4;varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +uniform vClipPlane3: vec4;varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +uniform vClipPlane4: vec4;varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +uniform vClipPlane5: vec4;varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +uniform vClipPlane6: vec4;varying fClipDistance6: f32; +#endif +`;rO.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration=cW;let cH=`#ifdef INSTANCES +attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; +#ifdef INSTANCESCOLOR +attribute instanceColor : vec4; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform world : mat4x4; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; +#ifdef THIN_INSTANCES +uniform previousWorld : mat4x4; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform world : mat4x4; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform previousWorld : mat4x4; +#endif +#endif +`;rO.IncludesShadersStoreWGSL.instancesDeclaration=cH;let cX=`#ifdef INSTANCES +var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +#if !defined(WORLD_UBO) +finalWorld=uniforms.world*finalWorld; +#else +finalWorld=mesh.world*finalWorld; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +var finalWorld=uniforms.world; +#else +var finalWorld=mesh.world; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=previousWorld; +#endif +#endif +`;rO.IncludesShadersStoreWGSL.instancesVertex=cX;let cY=`struct Mesh {world : mat4x4, +visibility : f32,};var mesh : Mesh; +#define WORLD_UBO +`;rO.IncludesShadersStoreWGSL.meshUboDeclaration=cY;let cj=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#else +positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;rO.IncludesShadersStoreWGSL.morphTargetsVertex=cj;let cK=`#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +attribute position{X} : vec3; +#ifdef MORPHTARGETS_NORMAL +attribute normal{X} : vec3; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute tangent{X} : vec3; +#endif +#ifdef MORPHTARGETS_UV +attribute uv_{X} : vec2; +#endif +#endif +#endif +`;rO.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration=cK;let c$=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +var vertexID : f32; +#endif +#endif +`;rO.IncludesShadersStoreWGSL.morphTargetsVertexGlobal=c$;let cq=`#ifdef MORPHTARGETS +uniform morphTargetInfluences : array; +#ifdef MORPHTARGETS_TEXTURE +uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 +{ +let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} +#endif +#endif +`;rO.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration=cq;let cQ=`struct Scene {viewProjection : mat4x4, +#ifdef MULTIVIEW +viewProjectionR : mat4x4, +#endif +view : mat4x4, +projection : mat4x4, +vEyePosition : vec4,};var scene : Scene; +`;rO.IncludesShadersStoreWGSL.sceneUboDeclaration=cQ;let cZ="fragmentOutputs.fragDepth",cJ={texture_1d:ed.E1d,texture_2d:ed.E2d,texture_2d_array:ed.E2dArray,texture_3d:ed.E3d,texture_cube:ed.Cube,texture_cube_array:ed.CubeArray,texture_multisampled_2d:ed.E2d,texture_depth_2d:ed.E2d,texture_depth_2d_array:ed.E2dArray,texture_depth_cube:ed.Cube,texture_depth_cube_array:ed.CubeArray,texture_depth_multisampled_2d:ed.E2d,texture_storage_1d:ed.E1d,texture_storage_2d:ed.E2d,texture_storage_2d_array:ed.E2dArray,texture_storage_3d:ed.E3d,texture_external:null};class c0 extends cD{constructor(){super(...arguments),this.shaderLanguage=f.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let r=0,s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;let n=t.substring(e+1,s);for(isNaN(r=+n)&&(r=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${cD.InternalsUBOName} { + yFactor_: f32, + textureOutputHeight_: f32, +}; +var internals : ${cD.InternalsUBOName}; +`+cg(e)}varyingProcessor(e,t,i){let r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==r){let s;let n=r[2],a=r[1];t?void 0===(s=this._webgpuProcessingContext.availableVaryings[a])&&ig.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`):(s=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(a,n,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=s,this._varyingsWGSL.push(` @location(${s}) ${a} : ${n},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){let i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){let r=i[2],s=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;let a=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==a){let e=`_int_${s}_`;this._attributesInputWGSL.push(`@location(${n}) ${e} : ${a<0?-1===a?"i32":"vec"+-a+"":1===a?"u32":"vec"+a+""},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = ${r}(vertexInputs_.${e});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${s} : ${r},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = vertexInputs_.${s};`);e=""}return e}uniformProcessor(e,t,i){let r=this.uniformRegexp.exec(e);if(null!==r){let t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){let r=this.textureRegexp.exec(e);if(null!==r){let s=r[1],n=r[2],a=!!r[3],o=r[4],l=o.indexOf("storage")>0,h=r[6],u=l?h.substring(0,h.indexOf(",")).trim():null,c=a?this._getArraySize(s,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)c=d.textures.length;else{d={isTextureArray:c>0,isStorageTexture:l,textures:[],sampleType:eE.Float},c=c||1;for(let e=0;e0,_=cJ[o],f=p?eE.Depth:"u32"===h?eE.Uint:"i32"===h?eE.Sint:eE.Float;if(d.sampleType=f,void 0===_)throw`Can't get the texture dimension corresponding to the texture function "${o}"!`;for(let i=0;i=0?` + if (internals.yFactor_ == 1.) { + fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; + } + `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);let r=this._buildLeftOverUBO();e=r+e,t=r+t,e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join("\n")),s+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(s+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n"+this._attributesWGSL.join("\n")+"\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=s+n+e;let a=` + vertexInputs${this._hasNonFloatAttribute?"_":""} = input; +`;this._hasNonFloatAttribute&&(a+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n"+this._attributesConversionCodeWGSL.join("\n")+"\n");let o=` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; + return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",a,o),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4,\n",u=!1,c=0;for(;!u&&!((c=t.indexOf(cZ,c))<0);){let e=c;for(u=!0;c>1&&"\n"!==t.charAt(c);){if("/"===t.charAt(c)&&"/"===t.charAt(c-1)){u=!1;break}c--}c=e+cZ.length}return u&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=l+h+t,t=this._injectStartingAndEndingCode(t,"fn main"," fragmentInputs = input;\n "+i," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { +`;for(let t of this._webgpuProcessingContext.leftOverUniforms){let s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=cD.UniformSizes[s];if(t.length>0){if(n<=2){let n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} { + @size(16) + el: ${s}, + }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${n}, ${t.length}>, +`}else r+=` ${t.name} : array<${t.type}, ${t.length}>, +`}else r+=` ${t.name} : ${t.type}, +`}return r+="};\n",r=`${i} +${r}@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e}; +`}_processSamplers(e,t){let i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[2],a=s.indexOf(cD.AutoSamplerSuffix)===s.length-cD.AutoSamplerSuffix.length?s.substring(0,s.indexOf(cD.AutoSamplerSuffix)):null,o="sampler_comparison"===n?eb.Comparison:eb.Filtering;if(a){let e=this._webgpuProcessingContext.availableTextures[a];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:o},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);let h=e.substring(0,r.index),u=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `;e=h+u+e.substring(r.index),i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){let i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[3],a=r[4],o=r[5],l=this._webgpuProcessingContext.availableBuffers[a];if(!l){let e;let t="uniform"===s?cF.KnownUBOs[o]:null;t?(a=o,-1===(e=t.binding).groupIndex&&(e=this._webgpuProcessingContext.getNextFreeUBOBinding())):e=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:e},this._webgpuProcessingContext.availableBuffers[a]=l}this._addBufferBindingDescription(a,this._webgpuProcessingContext.availableBuffers[a],"read_write"===n?eT.Storage:"storage"===s?eT.ReadOnlyStorage:eT.Uniform,t);let h=l.binding.groupIndex,u=l.binding.bindingIndex,c=e.substring(0,r.index),d=`@group(${h}) @binding(${u}) `;e=c+d+e.substring(r.index),i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(let t of this._stridedUniformArrays)e=e.replace(RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class c1{static ComputeNumMipmapLevels(e,t){return tK.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case e_.R8Unorm:case e_.R8Snorm:case e_.R8Uint:case e_.R8Sint:case e_.RG8Unorm:case e_.RG8Snorm:case e_.RG8Uint:case e_.RG8Sint:case e_.RGBA8Unorm:case e_.RGBA8UnormSRGB:case e_.RGBA8Snorm:case e_.RGBA8Uint:case e_.RGBA8Sint:case e_.BGRA8Unorm:case e_.BGRA8UnormSRGB:case e_.RGB10A2UINT:case e_.RGB10A2Unorm:case e_.RGB9E5UFloat:case e_.RG11B10UFloat:case e_.BC7RGBAUnorm:case e_.BC7RGBAUnormSRGB:case e_.BC6HRGBUFloat:case e_.BC6HRGBFloat:case e_.BC5RGUnorm:case e_.BC5RGSnorm:case e_.BC3RGBAUnorm:case e_.BC3RGBAUnormSRGB:case e_.BC2RGBAUnorm:case e_.BC2RGBAUnormSRGB:case e_.BC4RUnorm:case e_.BC4RSnorm:case e_.BC1RGBAUnorm:case e_.BC1RGBAUnormSRGB:case e_.ETC2RGB8Unorm:case e_.ETC2RGB8UnormSRGB:case e_.ETC2RGB8A1Unorm:case e_.ETC2RGB8A1UnormSRGB:case e_.ETC2RGBA8Unorm:case e_.ETC2RGBA8UnormSRGB:case e_.EACR11Unorm:case e_.EACR11Snorm:case e_.EACRG11Unorm:case e_.EACRG11Snorm:case e_.ASTC4x4Unorm:case e_.ASTC4x4UnormSRGB:case e_.ASTC5x4Unorm:case e_.ASTC5x4UnormSRGB:case e_.ASTC5x5Unorm:case e_.ASTC5x5UnormSRGB:case e_.ASTC6x5Unorm:case e_.ASTC6x5UnormSRGB:case e_.ASTC6x6Unorm:case e_.ASTC6x6UnormSRGB:case e_.ASTC8x5Unorm:case e_.ASTC8x5UnormSRGB:case e_.ASTC8x6Unorm:case e_.ASTC8x6UnormSRGB:case e_.ASTC8x8Unorm:case e_.ASTC8x8UnormSRGB:case e_.ASTC10x5Unorm:case e_.ASTC10x5UnormSRGB:case e_.ASTC10x6Unorm:case e_.ASTC10x6UnormSRGB:case e_.ASTC10x8Unorm:case e_.ASTC10x8UnormSRGB:case e_.ASTC10x10Unorm:case e_.ASTC10x10UnormSRGB:case e_.ASTC12x10Unorm:case e_.ASTC12x10UnormSRGB:case e_.ASTC12x12Unorm:case e_.ASTC12x12UnormSRGB:case e_.Stencil8:break;case e_.R16Uint:case e_.R16Sint:case e_.RG16Uint:case e_.RG16Sint:case e_.RGBA16Uint:case e_.RGBA16Sint:case e_.Depth16Unorm:return 5;case e_.R16Float:case e_.RG16Float:case e_.RGBA16Float:return 2;case e_.R32Uint:case e_.R32Sint:case e_.RG32Uint:case e_.RG32Sint:case e_.RGBA32Uint:case e_.RGBA32Sint:return 7;case e_.R32Float:case e_.RG32Float:case e_.RGBA32Float:case e_.Depth32Float:case e_.Depth32FloatStencil8:case e_.Depth24Plus:case e_.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case e_.R8Unorm:case e_.R8Snorm:case e_.R8Uint:case e_.R8Sint:return{width:1,height:1,length:1};case e_.R16Uint:case e_.R16Sint:case e_.R16Float:case e_.RG8Unorm:case e_.RG8Snorm:case e_.RG8Uint:case e_.RG8Sint:return{width:1,height:1,length:2};case e_.R32Uint:case e_.R32Sint:case e_.R32Float:case e_.RG16Uint:case e_.RG16Sint:case e_.RG16Float:case e_.RGBA8Unorm:case e_.RGBA8UnormSRGB:case e_.RGBA8Snorm:case e_.RGBA8Uint:case e_.RGBA8Sint:case e_.BGRA8Unorm:case e_.BGRA8UnormSRGB:case e_.RGB9E5UFloat:case e_.RGB10A2UINT:case e_.RGB10A2Unorm:case e_.RG11B10UFloat:break;case e_.RG32Uint:case e_.RG32Sint:case e_.RG32Float:case e_.RGBA16Uint:case e_.RGBA16Sint:case e_.RGBA16Float:return{width:1,height:1,length:8};case e_.RGBA32Uint:case e_.RGBA32Sint:case e_.RGBA32Float:return{width:1,height:1,length:16};case e_.Stencil8:throw"No fixed size for Stencil8 format!";case e_.Depth16Unorm:return{width:1,height:1,length:2};case e_.Depth24Plus:throw"No fixed size for Depth24Plus format!";case e_.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case e_.Depth32Float:break;case e_.Depth32FloatStencil8:return{width:1,height:1,length:5};case e_.BC7RGBAUnorm:case e_.BC7RGBAUnormSRGB:case e_.BC6HRGBUFloat:case e_.BC6HRGBFloat:case e_.BC5RGUnorm:case e_.BC5RGSnorm:case e_.BC3RGBAUnorm:case e_.BC3RGBAUnormSRGB:case e_.BC2RGBAUnorm:case e_.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case e_.BC4RUnorm:case e_.BC4RSnorm:case e_.BC1RGBAUnorm:case e_.BC1RGBAUnormSRGB:case e_.ETC2RGB8Unorm:case e_.ETC2RGB8UnormSRGB:case e_.ETC2RGB8A1Unorm:case e_.ETC2RGB8A1UnormSRGB:case e_.EACR11Unorm:case e_.EACR11Snorm:return{width:4,height:4,length:8};case e_.ETC2RGBA8Unorm:case e_.ETC2RGBA8UnormSRGB:case e_.EACRG11Unorm:case e_.EACRG11Snorm:case e_.ASTC4x4Unorm:case e_.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case e_.ASTC5x4Unorm:case e_.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case e_.ASTC5x5Unorm:case e_.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case e_.ASTC6x5Unorm:case e_.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case e_.ASTC6x6Unorm:case e_.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case e_.ASTC8x5Unorm:case e_.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case e_.ASTC8x6Unorm:case e_.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case e_.ASTC8x8Unorm:case e_.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case e_.ASTC10x5Unorm:case e_.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case e_.ASTC10x6Unorm:case e_.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case e_.ASTC10x8Unorm:case e_.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case e_.ASTC10x10Unorm:case e_.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case e_.ASTC12x10Unorm:case e_.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case e_.ASTC12x12Unorm:case e_.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case e_.BC7RGBAUnormSRGB:case e_.BC7RGBAUnorm:case e_.BC6HRGBFloat:case e_.BC6HRGBUFloat:case e_.BC5RGSnorm:case e_.BC5RGUnorm:case e_.BC4RSnorm:case e_.BC4RUnorm:case e_.BC3RGBAUnormSRGB:case e_.BC3RGBAUnorm:case e_.BC2RGBAUnormSRGB:case e_.BC2RGBAUnorm:case e_.BC1RGBAUnormSRGB:case e_.BC1RGBAUnorm:case e_.ETC2RGB8Unorm:case e_.ETC2RGB8UnormSRGB:case e_.ETC2RGB8A1Unorm:case e_.ETC2RGB8A1UnormSRGB:case e_.ETC2RGBA8Unorm:case e_.ETC2RGBA8UnormSRGB:case e_.EACR11Unorm:case e_.EACR11Snorm:case e_.EACRG11Unorm:case e_.EACRG11Snorm:case e_.ASTC4x4Unorm:case e_.ASTC4x4UnormSRGB:case e_.ASTC5x4Unorm:case e_.ASTC5x4UnormSRGB:case e_.ASTC5x5Unorm:case e_.ASTC5x5UnormSRGB:case e_.ASTC6x5Unorm:case e_.ASTC6x5UnormSRGB:case e_.ASTC6x6Unorm:case e_.ASTC6x6UnormSRGB:case e_.ASTC8x5Unorm:case e_.ASTC8x5UnormSRGB:case e_.ASTC8x6Unorm:case e_.ASTC8x6UnormSRGB:case e_.ASTC8x8Unorm:case e_.ASTC8x8UnormSRGB:case e_.ASTC10x5Unorm:case e_.ASTC10x5UnormSRGB:case e_.ASTC10x6Unorm:case e_.ASTC10x6UnormSRGB:case e_.ASTC10x8Unorm:case e_.ASTC10x8UnormSRGB:case e_.ASTC10x10Unorm:case e_.ASTC10x10UnormSRGB:case e_.ASTC12x10Unorm:case e_.ASTC12x10UnormSRGB:case e_.ASTC12x12Unorm:case e_.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return e_.Depth16Unorm;case 16:return e_.Depth24Plus;case 13:return e_.Depth24PlusStencil8;case 14:return e_.Depth32Float;case 18:return e_.Depth32FloatStencil8;case 19:return e_.Stencil8;case 36492:return i?e_.BC7RGBAUnormSRGB:e_.BC7RGBAUnorm;case 36495:return e_.BC6HRGBUFloat;case 36494:return e_.BC6HRGBFloat;case 33779:return i?e_.BC3RGBAUnormSRGB:e_.BC3RGBAUnorm;case 33778:return i?e_.BC2RGBAUnormSRGB:e_.BC2RGBAUnorm;case 33777:case 33776:return i?e_.BC1RGBAUnormSRGB:e_.BC1RGBAUnorm;case 37808:return i?e_.ASTC4x4UnormSRGB:e_.ASTC4x4Unorm;case 36196:case 37492:return i?e_.ETC2RGB8UnormSRGB:e_.ETC2RGB8Unorm;case 37496:return i?e_.ETC2RGBA8UnormSRGB:e_.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return e_.R8Snorm;case 7:return e_.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return e_.R8Sint;case 9:return e_.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return e_.RGBA8Sint;default:return e_.RGBA8Snorm}case 0:switch(t){case 6:return e_.R8Unorm;case 7:return e_.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?e_.RGBA8UnormSRGB:e_.RGBA8Unorm;case 12:return i?e_.BGRA8UnormSRGB:e_.BGRA8Unorm;case 8:return e_.R8Uint;case 9:return e_.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return e_.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return e_.RGBA8Unorm}case 4:switch(t){case 8:return e_.R16Sint;case 9:return e_.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return e_.RGBA16Sint}case 5:switch(t){case 8:return e_.R16Uint;case 9:return e_.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return e_.RGBA16Uint}case 6:switch(t){case 8:return e_.R32Sint;case 9:return e_.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return e_.RGBA32Sint}case 7:switch(t){case 8:return e_.R32Uint;case 9:return e_.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return e_.RGBA32Uint}case 1:switch(t){case 6:return e_.R32Float;case 7:return e_.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return e_.RGBA32Float}case 2:switch(t){case 6:return e_.R16Float;case 7:return e_.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return e_.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return e_.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return e_.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return e_.RGB10A2Unorm;case 11:return e_.RGB10A2UINT}}return i?e_.RGBA8UnormSRGB:e_.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case e_.R8Unorm:case e_.R8Snorm:case e_.R8Uint:case e_.R8Sint:case e_.BC4RUnorm:case e_.BC4RSnorm:case e_.R16Uint:case e_.R16Sint:case e_.Depth16Unorm:case e_.R16Float:case e_.R32Uint:case e_.R32Sint:case e_.R32Float:case e_.Depth32Float:case e_.Stencil8:case e_.Depth24Plus:case e_.EACR11Unorm:case e_.EACR11Snorm:return 1;case e_.RG8Unorm:case e_.RG8Snorm:case e_.RG8Uint:case e_.RG8Sint:case e_.Depth32FloatStencil8:case e_.BC5RGUnorm:case e_.BC5RGSnorm:case e_.RG16Uint:case e_.RG16Sint:case e_.RG16Float:case e_.RG32Uint:case e_.RG32Sint:case e_.RG32Float:case e_.Depth24PlusStencil8:case e_.EACRG11Unorm:case e_.EACRG11Snorm:return 2;case e_.RGB9E5UFloat:case e_.RG11B10UFloat:case e_.BC6HRGBUFloat:case e_.BC6HRGBFloat:case e_.ETC2RGB8Unorm:case e_.ETC2RGB8UnormSRGB:return 3;case e_.RGBA8Unorm:case e_.RGBA8UnormSRGB:case e_.RGBA8Snorm:case e_.RGBA8Uint:case e_.RGBA8Sint:case e_.BGRA8Unorm:case e_.BGRA8UnormSRGB:case e_.RGB10A2UINT:case e_.RGB10A2Unorm:case e_.BC7RGBAUnorm:case e_.BC7RGBAUnormSRGB:case e_.BC3RGBAUnorm:case e_.BC3RGBAUnormSRGB:case e_.BC2RGBAUnorm:case e_.BC2RGBAUnormSRGB:case e_.BC1RGBAUnorm:case e_.BC1RGBAUnormSRGB:case e_.RGBA16Uint:case e_.RGBA16Sint:case e_.RGBA16Float:case e_.RGBA32Uint:case e_.RGBA32Sint:case e_.RGBA32Float:case e_.ETC2RGB8A1Unorm:case e_.ETC2RGB8A1UnormSRGB:case e_.ETC2RGBA8Unorm:case e_.ETC2RGBA8UnormSRGB:case e_.ASTC4x4Unorm:case e_.ASTC4x4UnormSRGB:case e_.ASTC5x4Unorm:case e_.ASTC5x4UnormSRGB:case e_.ASTC5x5Unorm:case e_.ASTC5x5UnormSRGB:case e_.ASTC6x5Unorm:case e_.ASTC6x5UnormSRGB:case e_.ASTC6x6Unorm:case e_.ASTC6x6UnormSRGB:case e_.ASTC8x5Unorm:case e_.ASTC8x5UnormSRGB:case e_.ASTC8x6Unorm:case e_.ASTC8x6UnormSRGB:case e_.ASTC8x8Unorm:case e_.ASTC8x8UnormSRGB:case e_.ASTC10x5Unorm:case e_.ASTC10x5UnormSRGB:case e_.ASTC10x6Unorm:case e_.ASTC10x6UnormSRGB:case e_.ASTC10x8Unorm:case e_.ASTC10x8UnormSRGB:case e_.ASTC10x10Unorm:case e_.ASTC10x10UnormSRGB:case e_.ASTC12x10Unorm:case e_.ASTC12x10UnormSRGB:case e_.ASTC12x12Unorm:case e_.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case e_.Stencil8:case e_.Depth32FloatStencil8:case e_.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case e_.Depth32FloatStencil8:case e_.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case e_.Depth16Unorm:return e_.Depth16Unorm;case e_.Depth24Plus:case e_.Depth24PlusStencil8:return e_.Depth24Plus;case e_.Depth32Float:case e_.Depth32FloatStencil8:return e_.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class c2{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return null!==(i=null===(t=this._webgpuMSAATexture)||void 0===t?void 0:t[e])&&void 0!==i?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(let e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=e_.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s,n,a,o){let l=ed.E2d,h=1;r?(l=i?ed.CubeArray:ed.Cube,h=6*(o||1)):s?l=ed.E3d:i&&(l=ed.E2dArray,h=o);let u=c1.GetDepthFormatOnly(this.format),c=c1.HasDepthAndStencilAspects(this.format)?ep.DepthOnly:ep.All;this.createView({label:`TextureView${s?"3D":r?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${a}_${t?"wmips":"womips"}_${this.format}_${l}`,format:u,dimension:l,mipLevelCount:t?tK.ILog2(Math.max(n,a))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:c})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){let t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;null===(e=this._webgpuTexture)||void 0===e||e.destroy(),this.releaseMSAATexture(),null===(t=this._copyInvertYTempTexture)||void 0===t||t.destroy(),this.reset()}}let c3=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(location = 0) out vec2 vTex; + + void main() { + vTex = tex[gl_VertexIndex]; + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,c4=` + layout(set = 0, binding = 0) uniform sampler imgSampler; + layout(set = 0, binding = 1) uniform texture2D img; + + layout(location = 0) in vec2 vTex; + layout(location = 0) out vec4 outColor; + + void main() { + outColor = texture(sampler2D(img, imgSampler), vTex); + } + `,c5=` + #extension GL_EXT_samplerless_texture_functions : enable + + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) out flat ivec2 vTextureSize; + #endif + + void main() { + #ifdef INVERTY + vTextureSize = textureSize(img, 0); + #endif + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,c6=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,c8=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + layout(set = 0, binding = 1) uniform Params { + float ofstX; + float ofstY; + float width; + float height; + }; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { + discard; + } + if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { + discard; + } + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,c7=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + + void main() { + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,c9=` + layout(set = 0, binding = 0) uniform Uniforms { + uniform vec4 color; + }; + + layout(location = 0) out vec4 outColor; + + void main() { + outColor = color; + } + `,de=` + struct VertexOutput { + @builtin(position) Position : vec4, + @location(0) fragUV : vec2 + } + + @vertex + fn main( + @builtin(vertex_index) VertexIndex : u32 + ) -> VertexOutput { + var pos = array, 4>( + vec2(-1.0, 1.0), + vec2( 1.0, 1.0), + vec2(-1.0, -1.0), + vec2( 1.0, -1.0) + ); + var tex = array, 4>( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(1.0, 1.0) + ); + + var output: VertexOutput; + + output.Position = vec4(pos[VertexIndex], 0.0, 1.0); + output.fragUV = tex[VertexIndex]; + + return output; + } + `,dt=` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2 + ) -> @location(0) vec4 { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); + } + `,di=` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2 + ) -> @location(0) vec4 { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y)); + } + `;(function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(eX||(eX={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(eY||(eY={}));let dr=[{vertex:c3,fragment:c4},{vertex:c5,fragment:c6},{vertex:c7,fragment:c9},{vertex:c5,fragment:c8}],ds={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class dn{constructor(e,t,i,r,s,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=r,this._bufferManager=s,-1!==n.indexOf(ea.RG11B10UFloatRenderable)){let e=Object.keys(ds);ds[e_.RG11B10UFloat]=ds[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:em.Linear}),this._videoSampler=t.createSampler({minFilter:em.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,el.Uniform|el.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(e_.RGBA8Unorm),this._getVideoPipeline(e_.RGBA8Unorm)}_getPipeline(e,t=eX.MipMap,i){let r=t===eX.MipMap?1:t===eX.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===eX.Clear?8:t===eX.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let n="#version 450\n";(t===eX.InvertYPremultiplyAlpha||t===eX.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let a=this._compiledShaders[r];if(!a){let e=this._glslang.compileGLSL(n+dr[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+dr[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));let s=this._device.createShaderModule({code:e}),o=this._device.createShaderModule({code:i});a=this._compiledShaders[r]=[s,o]}let o=this._device.createRenderPipeline({layout:eA.Auto,vertex:{module:a[0],entryPoint:"main"},fragment:{module:a[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:eR.TriangleStrip,stripIndexFormat:eF.Uint16}});s=this._pipelines[e][r]=[o,o.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=eY.DontInvertY){let i=t===eY.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){let e=this._device.createShaderModule({code:de}),r=this._device.createShaderModule({code:0===i?dt:di});t=this._videoCompiledShaders[i]=[e,r]}let s=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:eA.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:eR.TriangleStrip,stripIndexFormat:eF.Uint16}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,r=!1,s){var n,a,o,l;let h=void 0===s,[u,c]=this._getVideoPipeline(i,r?eY.InvertY:eY.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`copy video to texture - invertY=${r}`);let d={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:ed.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:ep.All}),loadOp:eV.Load,storeOp:ek.Store}]},p=s.beginRenderPass(d),_={layout:c,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},f=this._device.createBindGroup(_);p.setPipeline(u),p.setBindGroup(0,f),p.draw(4,1,0,0),p.end(),null===(l=(o=s).popDebugGroup)||void 0===l||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,n=!1,a=0,o=0,l=1,h=0,u=0,c=0,d=0,p,_){var f,m,g,v,x,T;let b;let E=0!==c,S=void 0===p,[C,y]=this._getPipeline(r,E?eX.InvertYPremultiplyAlphaWithOfst:eX.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:n});if(a=Math.max(a,0),S&&(p=this._device.createCommandEncoder({})),null===(m=(f=p).pushDebugGroup)||void 0===m||m.call(f,`internal process texture - invertY=${s} premultiplyAlpha=${n}`),c1.IsHardwareTexture(e)?(b=e.underlyingResource,s&&!n&&1===l&&0===a||(e=void 0)):(b=e,e=void 0),!b)return;E&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,u,c,d]),0,16);let A=e,R=null!==(g=null==A?void 0:A._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,p,ec.CopySrc|ec.RenderAttachment|ec.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),I=null!==(v=null==A?void 0:A._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:R.createView({format:r,dimension:ed.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:eV.Load,storeOp:ek.Store}]},P=p.beginRenderPass(I),M=E?null==A?void 0:A._copyInvertYBindGroupWithOfst:null==A?void 0:A._copyInvertYBindGroup;if(!M){let e={layout:y,entries:[{binding:0,resource:b.createView({format:r,dimension:ed.E2d,baseMipLevel:o,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:a})}]};E&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),M=this._device.createBindGroup(e)}P.setPipeline(C),P.setBindGroup(0,M),P.draw(4,1,0,0),P.end(),p.copyTextureToTexture({texture:R},{texture:b,mipLevel:o,origin:{x:0,y:0,z:a}},{width:t,height:i,depthOrArrayLayers:1}),A?(A._copyInvertYTempTexture=R,A._copyInvertYRenderPassDescr=I,E?A._copyInvertYBindGroupWithOfst=M:A._copyInvertYBindGroup=M):this._deferredReleaseTextures.push([R,null]),null===(T=(x=p).popDebugGroup)||void 0===T||T.call(x),S&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,r){var s,n,a,o;let l=void 0===r,[h,u]=this._getPipeline(t,eX.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,"internal copy texture with invertY");let c=r.beginRenderPass(i),d=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});c.setPipeline(h),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,n=!1,a=e_.RGBA8Unorm,o=1,l,h=-1,u=0,c){o=c1.GetSample(o);let d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},_=ds[a]?ec.RenderAttachment:0,f=c1.IsCompressedFormat(a),m=t?c1.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:ec.CopySrc|ec.CopyDst|ec.TextureBinding;u|=t&&!f?ec.CopySrc|_:0,f||n||(u|=_|ec.CopyDst);let v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${c?c+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${a}_samples${o}`,size:p,dimension:n?eu.E3d:eu.E2d,format:a,usage:g|u,sampleCount:o,mipLevelCount:m});return c1.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,a,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,a,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,n=e_.RGBA8Unorm,a=1,o,l=-1,h=0,u){a=c1.GetSample(a);let c=c1.IsImageBitmapArray(e)?e[0].width:e.width,d=c1.IsImageBitmapArray(e)?e[0].height:e.height,p=ds[n]?ec.RenderAttachment:0,_=c1.IsCompressedFormat(n),f=t?c1.ComputeNumMipmapLevels(c,d):1,m=l>=0?l:ec.CopySrc|ec.CopyDst|ec.TextureBinding;h|=t&&!_?ec.CopySrc|p:0,_||(h|=p|ec.CopyDst);let g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${u?u+"_":""}${c}x${d}x6_${t?"wmips":"womips"}_${n}_samples${a}`,size:{width:c,height:d,depthOrArrayLayers:6},dimension:eu.E2d,format:n,usage:m|h,sampleCount:a,mipLevelCount:f});return c1.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,c,d,n,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,o)),g}generateCubeMipmaps(e,t,i,r){var s,n,a,o;let l=void 0===r;l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,r);null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s){var n,a,o,l,h,u,c,d;let p;let _=void 0===s,[f,m]=this._getPipeline(t);if(r=Math.max(r,0),_&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`create mipmaps for face #${r} - ${i} levels`),c1.IsHardwareTexture(e)?(p=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(p=e,e=void 0),!p)return;let g=e;for(let e=1;e15728640;)this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,15728640),h+=15728640;this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,s-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));let r=new Uint16Array(t);for(;e--;)i[e]=ce(r[e]);return i}readDataFromBuffer(e,t,i,r,s,n,a=0,o=0,l=null,h=!0,u=!1){let c=1===a?2:2===a?1:0,d=this._engine.uniqueId;return new Promise((i,p)=>{e.mapAsync(eh.Read,o,t).then(()=>{let d=e.getMappedRange(o,t),p=l;if(u)p=null===p?nS(a,t,!0,d):nS(a,p.buffer,void 0,d);else if(null===p)switch(c){case 0:(p=new Uint8Array(t)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:(p=new Float32Array(t/4)).set(new Float32Array(d))}else switch(c){case 0:(p=new Uint8Array(p.buffer)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:(p=new Float32Array(p.buffer)).set(new Float32Array(d))}if(s!==n){1!==c||u||(s*=2,n*=2);let e=new Uint8Array(p.buffer),t=s,i=0;for(let a=1;a{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):p(e)})})}releaseBuffer(e){return dl._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return dh[e.samplingMode]+du[(e._comparisonFunction||514)-512+1]+dc[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(r=e._cachedWrapR)&&void 0!==r?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15)}static _GetSamplerFilterDescriptor(e,t){let i,r,s,n,a;let o=e.useMipMaps;switch(e.samplingMode){case 11:i=em.Linear,r=em.Linear,s=em.Nearest,o||(n=a=0);break;case 3:case 3:i=em.Linear,r=em.Linear,o?s=em.Linear:(s=em.Nearest,n=a=0);break;case 8:i=em.Nearest,r=em.Nearest,o?s=em.Linear:(s=em.Nearest,n=a=0);break;case 4:i=em.Nearest,r=em.Nearest,s=em.Nearest,o||(n=a=0);break;case 5:i=em.Nearest,r=em.Linear,s=em.Nearest,o||(n=a=0);break;case 6:i=em.Nearest,r=em.Linear,o?s=em.Linear:(s=em.Nearest,n=a=0);break;case 7:i=em.Nearest,r=em.Linear,s=em.Nearest,n=a=0;break;case 1:case 1:default:i=em.Nearest,r=em.Nearest,s=em.Nearest,n=a=0;break;case 9:i=em.Linear,r=em.Nearest,s=em.Nearest,o||(n=a=0);break;case 10:i=em.Linear,r=em.Nearest,o?s=em.Linear:(s=em.Nearest,n=a=0);break;case 2:case 2:i=em.Linear,r=em.Linear,s=em.Nearest,n=a=0;break;case 12:i=em.Linear,r=em.Nearest,s=em.Nearest,n=a=0}return t>1&&(0!==n||0!==a)&&s!==em.Nearest?{magFilter:em.Linear,minFilter:em.Linear,mipmapFilter:em.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:n,lodMaxClamp:a}}static _GetWrappingMode(e){switch(e){case 1:break;case 0:return ef.ClampToEdge;case 2:return ef.MirrorRepeat}return ef.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){let i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,r=this._GetSamplerFilterDescriptor(e,i);return Object.assign(Object.assign(Object.assign({label:t},r),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?dd.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:r.anisotropyEnabled?i:1})}static GetCompareFunction(e){switch(e){case 519:return ev.Always;case 514:return ev.Equal;case 516:return ev.Greater;case 518:return ev.GreaterEqual;case 513:default:return ev.Less;case 515:return ev.LessEqual;case 512:return ev.Never;case 517:return ev.NotEqual}}getSampler(e,t=!1,i=0,r){if(this.disabled)return this._device.createSampler(dd._GetSamplerDescriptor(e,r));t?i=0:0===i&&(i=dd.GetSamplerHashCode(e));let s=t?void 0:this._samplers[i];return s||(s=this._device.createSampler(dd._GetSamplerDescriptor(e,r)),t||(this._samplers[i]=s)),s}}!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(ej||(ej={}));let dp={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},d_={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},df={[sf.PositionKind]:!0,[sf.NormalKind]:!0,[sf.TangentKind]:!0,[sf.UVKind]:!0,[sf.UV2Kind]:!0,[sf.UV3Kind]:!0,[sf.UV4Kind]:!0,[sf.UV5Kind]:!0,[sf.UV6Kind]:!0,[sf.ColorKind]:!0,[sf.ColorInstanceKind]:!0,[sf.MatricesIndicesKind]:!0,[sf.MatricesWeightsKind]:!0,[sf.MatricesIndicesExtraKind]:!0,[sf.MatricesWeightsExtraKind]:!0};class dm{static _IsSignedType(e){switch(e){case sf.BYTE:case sf.SHORT:case sf.INT:case sf.FLOAT:return!0;case sf.UNSIGNED_BYTE:case sf.UNSIGNED_SHORT:case sf.UNSIGNED_INT:return!1;default:throw Error(`Invalid type '${e}'`)}}constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[e_.BGRA8Unorm],this.setColorFormat(e_.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(e_.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,r=0){if(i=c1.GetSample(i),this.disabled){let s=dm._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),dm.NumCacheMiss++,dm._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,dm.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return dm.NumCacheHitWithHash++,this._parameter.pipeline;let s=dm._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),dm.NumCacheMiss++,dm._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){dm.NumPipelineCreationLastFrame=dm._NumPipelineCreationCurrentFrame,dm._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,n,a,o){this._depthWriteEnabled=a,this._depthTestEnabled=n,this._depthCompare=(null!=o?o:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[ej.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[ej.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=ds[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;let s=[0,0],n=0,a=0,o=0;for(let l=0;l=32&&(a=0,n++)}this._mrtFormats.length=o,(this._mrtAttachments1!==s[0]||this._mrtAttachments2!==s[1])&&(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[ej.MRTAttachments1]=s[0],this._states[ej.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:ds[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(null!=e?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(null!=e?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:d_[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:d_[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:d_[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[ej.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[ej.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,n,a){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:d_[i],this._stencilFrontPassOp=null===r?2:d_[r],this._stencilFrontFailOp=null===s?1:d_[s],this.setStencilReadMask(n),this.setStencilWriteMask(a)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return eR.TriangleList;case 2:case 3:return eR.PointList;case 1:case 4:return eR.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return eR.LineStrip;case 7:return eR.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return eO.Add;case 32778:return eO.Subtract;case 32779:return eO.ReverseSubtract;case 32775:return eO.Min;case 32776:return eO.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return eD.Zero;case 1:default:return eD.One;case 768:return eD.Src;case 769:return eD.OneMinusSrc;case 770:return eD.SrcAlpha;case 771:return eD.OneMinusSrcAlpha;case 772:return eD.DstAlpha;case 773:return eD.OneMinusDstAlpha;case 774:return eD.Dst;case 775:return eD.OneMinusDst;case 776:return eD.SrcAlphaSaturated;case 32769:case 32771:return eD.Constant;case 32770:case 32772:return eD.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:break;case 1:return ev.Less;case 2:return ev.Equal;case 3:return ev.LessEqual;case 4:return ev.Greater;case 5:return ev.NotEqual;case 6:return ev.GreaterEqual;case 7:return ev.Always}return ev.Never}static _GetStencilOpFunction(e){switch(e){case 0:return eN.Zero;case 1:break;case 2:return eN.Replace;case 3:return eN.IncrementClamp;case 4:return eN.DecrementClamp;case 5:return eN.Invert;case 6:return eN.IncrementWrap;case 7:return eN.DecrementWrap}return eN.Keep}static _GetVertexInputDescriptorFormat(e){let t=e.type,i=e.normalized,r=e.getSize();switch(t){case sf.BYTE:switch(r){case 1:case 2:return i?ew.Snorm8x2:ew.Sint8x2;case 3:case 4:return i?ew.Snorm8x4:ew.Sint8x4}break;case sf.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?ew.Unorm8x2:ew.Uint8x2;case 3:case 4:return i?ew.Unorm8x4:ew.Uint8x4}break;case sf.SHORT:switch(r){case 1:case 2:return i?ew.Snorm16x2:ew.Sint16x2;case 3:case 4:return i?ew.Snorm16x4:ew.Sint16x4}break;case sf.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?ew.Unorm16x2:ew.Uint16x2;case 3:case 4:return i?ew.Unorm16x4:ew.Uint16x4}break;case sf.INT:switch(r){case 1:return ew.Sint32;case 2:return ew.Sint32x2;case 3:return ew.Sint32x3;case 4:return ew.Sint32x4}break;case sf.UNSIGNED_INT:switch(r){case 1:return ew.Uint32;case 2:return ew.Uint32x2;case 3:return ew.Uint32x3;case 4:return ew.Uint32x4}break;case sf.FLOAT:switch(r){case 1:return ew.Float32;case 2:return ew.Float32x2;case 3:return ew.Float32x3;case 4:return ew.Float32x4}}throw Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:dm._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:dm._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:dm._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:dm._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:dm._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:dm._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[ej.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.ShaderStage))}_setRasterizationState(e,t){let i=this._frontFace,r=i-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==r&&(this._rasterizationState=r,this._states[ej.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((null===this._alphaBlendFuncParams[0]?2:dp[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:dp[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:dp[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:dp[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[ej.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.ColorStates))}_setDepthStencilState(){let e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[ej.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,ej.DepthStencilState))}_setVertexState(e){var t,i;let r;let s=this._statesLength,n=ej.VertexState,a=e._pipelineContext,o=a.shaderProcessingContext.attributeNamesFromEffect,l=a.shaderProcessingContext.attributeLocationsFromEffect,h=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class dE{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=dE._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?dd.GetSamplerHashCode(t):0;let s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,r,s;let n=this.textures[e],a=-1;n?a=null!==(r=null===(i=n.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:-1:this.textures[e]=n={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},n.isExternalTexture&&this._numExternalTextures--,n.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(n.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,n.isExternalTexture=db.IsExternalTexture(t),n.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,n.isExternalTexture&&this._numExternalTextures++):(n.isFloatOrDepthTexture=!1,n.isExternalTexture=!1),n.texture=t;let o=a!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);o&&this.updateId++,this.isDirty||(this.isDirty=o)}}dE._Counter=0;class dS{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,el.CopyDst|el.Indirect|el.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=dS._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(null==t?void 0:t.uniqueId)!==(null===(i=this.buffers[e])||void 0===i?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}dS._Counter=0;class dC{constructor(){this.values={}}}class dy{static get Statistics(){return{totalCreated:dy.NumBindGroupsCreatedTotal,lastFrameCreated:dy.NumBindGroupsCreatedLastFrame,lookupLastFrame:dy.NumBindGroupsLookupLastFrame,noLookupLastFrame:dy.NumBindGroupsNoLookupLastFrame}}static ResetCache(){dy._Cache=new dC,dy.NumBindGroupsCreatedTotal=0,dy.NumBindGroupsCreatedLastFrame=0,dy.NumBindGroupsLookupLastFrame=0,dy.NumBindGroupsNoLookupLastFrame=0,dy._NumBindGroupsCreatedCurrentFrame=0,dy._NumBindGroupsLookupCurrentFrame=0,dy._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){dy.NumBindGroupsCreatedLastFrame=dy._NumBindGroupsCreatedCurrentFrame,dy.NumBindGroupsLookupLastFrame=dy._NumBindGroupsLookupCurrentFrame,dy.NumBindGroupsNoLookupLastFrame=dy._NumBindGroupsNoLookupCurrentFrame,dy._NumBindGroupsCreatedCurrentFrame=0,dy._NumBindGroupsLookupCurrentFrame=0,dy._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var r,s,n,a,o,l,h,u,c,d;let p;let _=dy._Cache,f=this.disabled||i.forceBindGroupCreation;if(!f){if(!t.isDirty(i.updateId)&&!i.isDirty)return dy._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(let i of e.shaderProcessingContext.bufferNames){let e=null!==(s=null===(r=t.buffers[i])||void 0===r?void 0:r.uniqueId)&&void 0!==s?s:0,n=_.values[e];n||(n=new dC,_.values[e]=n),_=n}for(let t of e.shaderProcessingContext.samplerNames){let e=null!==(a=null===(n=i.samplers[t])||void 0===n?void 0:n.hashCode)&&void 0!==a?a:0,r=_.values[e];r||(r=new dC,_.values[e]=r),_=r}for(let t of e.shaderProcessingContext.textureNames){let e=null!==(h=null===(l=null===(o=i.textures[t])||void 0===o?void 0:o.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0,r=_.values[e];r||(r=new dC,_.values[e]=r),_=r}p=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,p)return t.bindGroups=p,dy._NumBindGroupsLookupCurrentFrame++,p;p=[],t.bindGroups=p,f||(_.bindGroups=p),dy.NumBindGroupsCreatedTotal++,dy._NumBindGroupsCreatedCurrentFrame++;let m=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else ig.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.texture||s.storageTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){ig.Error(`Trying to bind a null texture! entry=${JSON.stringify(s)}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||s.texture&&!t.view||s.storageTexture&&!t.viewForWriting)){ig.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, isReady=${null===(c=e.texture)||void 0===c?void 0:c.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=s.storageTexture?t.viewForWriting:t.view}else ig.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.externalTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){ig.Error(`Trying to bind a null external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){ig.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._device.importExternalTexture({source:t})}else ig.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.buffer){let e=t.buffers[l];if(e){let t=e.underlyingResource;n[a].resource.buffer=t,n[a].resource.size=e.capacity}else ig.Error(`Can't find buffer "${l}". entry=${JSON.stringify(s)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}let a=m[r];p[r]=this._device.createBindGroup({layout:a,entries:n})}return p}}dy.NumBindGroupsCreatedTotal=0,dy.NumBindGroupsCreatedLastFrame=0,dy.NumBindGroupsLookupLastFrame=0,dy.NumBindGroupsNoLookupLastFrame=0,dy._Cache=new dC,dy._NumBindGroupsCreatedCurrentFrame=0,dy._NumBindGroupsLookupCurrentFrame=0,dy._NumBindGroupsNoLookupCurrentFrame=0;let dA=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), +vec2(1.0,1.0), +vec2(-1.0,-1.0), +vec2(1.0,-1.0)}; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`;rO.ShadersStore.clearQuadVertexShader=dA;let dR=`uniform vec4 color;void main() {gl_FragColor=color;} +`;rO.ShadersStore.clearQuadPixelShader=dR;class dI{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new dv(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,r,s=1){var n,a;let o,l;let h=null,u=!!this._engine._currentRenderTarget;if(e)o=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?68719476736:0)+137438953472*c,l=this._keyTemp.join("_"),h=this._bundleCache[l])return h;o=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:c1.GetSample(s)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&c1.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);let c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),d=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),d.uniformBuffer.update();let p=u?this._engine._ubInvertY:this._engine._ubDontInvertY,_=d.uniformBuffer.getBuffer(),f=_.uniqueId+"-"+p.uniqueId,m=this._bindGroups[f];if(!m){let e=d.bindGroupLayouts[0];(m=this._bindGroups[f]=[]).push(this._device.createBindGroup({layout:e[0],entries:[]})),cF._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[cF._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:_.underlyingResource,size:_.capacity}}]}))}o.setPipeline(c);for(let e=0;e{let e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e},e=>{if(this._engine.isDisposed||this._engine.uniqueId!==r)return null;throw e})}async readValue(e=0){let t=this._getBuffer(e,1);if(null===t)return null;let i=this._engine.uniqueId;return t.mapAsync(eh.Read).then(()=>{let e=Number(new BigUint64Array(t.getMappedRange())[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,e},e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e})}async readTwoValuesAndSubtract(e=0){let t=this._getBuffer(e,2);if(null===t)return null;let i=this._engine.uniqueId;return t.mapAsync(eh.Read).then(()=>{let e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i},e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;let i=this._engine.frameId;this._measureDuration.stopPass(e).then(e=>{t._addDuration(i,null!==e&&e>0?e:0)})}dispose(){var e;null===(e=this._measureDuration)||void 0===e||e.dispose()}}class dV{constructor(e,t,i,r=2,s){this._count=r,this._querySet=new dB(e,r,eG.Timestamp,t,i,!0,s)}start(e){var t;null===(t=e.writeTimestamp)||void 0===t||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return null===(t=e.writeTimestamp)||void 0===t||t.call(e,this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class dk{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;let t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();let e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e}))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}}class dG{async initTwgsl(e){return dG._twgsl?void 0:(e=e||{},(e=Object.assign(Object.assign({},dG._TWgslDefaultOptions),e)).twgsl)?(dG._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await ss.LoadBabylonScriptAsync(e.jsPath),self.twgsl)?(dG._twgsl=await self.twgsl(ss.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available.")}convertSpirV2WGSL(e,t=!1){let i=dG._twgsl.convertSpirV2WGSL(e,dG.DisableUniformityAnalysis||t);return dG.ShowWGSLShaderCode&&(ig.Log(i),ig.Log("***********************************************")),dG.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}dG._TWgslDefaultOptions={jsPath:`${ss._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${ss._DefaultCdnUrl}/twgsl/twgsl.wasm`},dG.ShowWGSLShaderCode=!1,dG.DisableUniformityAnalysis=!1,dG._twgsl=null;class dz{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){let t;if(!this._record&&!this._play)return!1;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}let dW=`attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`;rO.ShadersStoreWGSL.postprocessVertexShader=dW;let dH={label:"TextureView_SwapChain_ResolveTarget",dimension:eu.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},dX={label:"TextureView_SwapChain",dimension:eu.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},dY="/* disable_uniformity_analysis */",dj=new il;class dK extends nC{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return ig.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new h4:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){let i=new dK(e,t);return new Promise(e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>e(i))})}constructor(e,t={}){var i,r;if(super(null,null===(i=t.antialias)||void 0===i||i,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=null!==(r=t.enableGPUDebugMarkers)&&void 0!==r&&r,ig.Log(`Babylon.js v${nC.Version} - ${this.description} engine`),!navigator.gpu){ig.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new cw,this._shaderProcessorWGSL=new c0}initAsync(e,t){var i;return this.uniqueId=dK._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(null!=e?e:null===(i=this._options)||void 0===i?void 0:i.glslangOptions).then(e=>{var i;return this._glslang=e,this._tintWASM=dK.UseTWGSL?new dG:null,this._tintWASM?this._tintWASM.initTwgsl(null!=t?t:null===(i=this._options)||void 0===i?void 0:i.twgslOptions).then(()=>navigator.gpu.requestAdapter(this._options),e=>{throw ig.Error("Can not initialize twgsl!"),ig.Error(e),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},e=>{throw ig.Error("Can not initialize glslang!"),ig.Error(e),Error("WebGPU initializations stopped.")}).then(e=>{var t,i,r;if(e){this._adapter=e,this._adapterSupportedExtensions=[],null===(t=this._adapter.features)||void 0===t||t.forEach(e=>this._adapterSupportedExtensions.push(e)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(e=>{this._adapterInfo=e});let s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},n=null!==(r=null==s?void 0:s.requiredFeatures)&&void 0!==r?r:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(n){let e=[];for(let t of n)-1!==this._adapterSupportedExtensions.indexOf(t)&&e.push(t);s.requiredFeatures=e}if(this._options.setMaximumLimits&&!s.requiredLimits)for(let e in s.requiredLimits={},this._adapterSupportedLimits)s.requiredLimits[e]=this._adapterSupportedLimits[e];return s.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(s)}throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(e=>{var t,i;this._device=e,this._deviceEnabledExtensions=[],null===(t=this._device.features)||void 0===t||t.forEach(e=>this._deviceEnabledExtensions.push(e)),this._deviceLimits=e.limits;let r=-1;this._device.addEventListener("uncapturederror",e=>{++r{this._isDisposed||(this._contextWasLost=!0,ig.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var e,t,i,r;let s=this.snapshotRenderingMode,n=this.snapshotRendering,a=this.disableCacheSamplers,o=this.disableCacheRenderPipelines,l=this.disableCacheBindGroups,h=this.enableGPUTimingMeasurements;await this.initAsync(null!==(e=this._glslangOptions)&&void 0!==e?e:null===(t=this._options)||void 0===t?void 0:t.glslangOptions,null!==(i=this._twgslOptions)&&void 0!==i?i:null===(r=this._options)||void 0===r?void 0:r.twgslOptions),this.snapshotRenderingMode=s,this.snapshotRendering=n,this.disableCacheSamplers=a,this.disableCacheRenderPipelines=o,this.disableCacheBindGroups=l,this.enableGPUTimingMeasurements=h,this._currentRenderPass=null}))})},e=>{ig.Error("Could not retrieve a WebGPU device."),ig.Error(e)}).then(()=>{this._bufferManager=new dl(this,this._device),this._textureHelper=new dn(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new dd(this._device),this._cacheBindGroups=new dy(this._device,this._cacheSampler,this),this._timestampQuery=new dU(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new dk(this,this._device,this._bufferManager):void 0,this._bundleList=new dL(this._device),this._snapshotRendering=new dz(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),el.Uniform|el.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),el.Uniform|el.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,ig.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new sf(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new dv(this._device,this._emptyVertexBuffer),this._depthCullingState=new dT(this._cacheRenderPipeline),this._stencilStateComposer=new dx(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new dI(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(e=>{var t;ig.Error("Can not create WebGPU Device and/or context."),ig.Error(e),null===(t=null==console?void 0:console.trace)||void 0===t||t.call(console)})}_initGlslang(e){return(e=e||{},(e=Object.assign(Object.assign({},dK._GLSLslangDefaultOptions),e)).glslang)?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?ss.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(ss.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(ea.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(ea.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(ea.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(ea.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(ea.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(ea.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(ea.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._caps.parallelShaderCompile=null,this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new c2],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){let e;if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};let t=new Float32Array([this.getRenderHeight(!0)]);if(this._bufferManager.setSubData(this._ubInvertY,4,t),this._bufferManager.setSubData(this._ubDontInvertY,4,t),this._options.antialias){let t={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:eu.E2d,format:this._options.swapChainFormat,usage:ec.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(t),e=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:eu.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new il(0,0,0,1),loadOp:eV.Clear,storeOp:ek.Store}]}else e=[{view:void 0,clearValue:new il(0,0,0,1),loadOp:eV.Clear,storeOp:ek.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?e_.Depth24PlusStencil8:e_.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);let i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:eu.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:ec.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);let r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:eu.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:eV.Clear,depthStoreOp:ek.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?eV.Clear:void 0,stencilStoreOp:this.isStencilEnable?ek.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:e,depthStencilAttachment:r}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:ec.RenderAttachment|ec.CopySrc,alphaMode:this.premultipliedAlpha?ez.Premultiplied:ez.Opaque})}_rebuildBuffers(){for(let e of(super._rebuildBuffers(),this._storageBuffers))e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){dv.ResetCache(),dy.ResetCache();let t=e=>{var t;for(let i of e){for(let e of i.meshes){let t=e.subMeshes;if(t)for(let e of t)e._drawWrappers=[]}for(let e of i.materials)null===(t=e._materialContext)||void 0===t||t.reset()}};t(this.scenes),t(this._virtualScenes);let i=[];for(let e of this._uniformBuffers)0>e.name.indexOf("leftOver")&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,s=t.indexOf(dY)>=0,n=i===f.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,a=i===f.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,a,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=e.indexOf(dY)>=0,n=t.indexOf(dY)>=0,a="#version 450\n",o=r===f.GLSL?this._compileShaderToSpirV(e,"vertex",i,a):this._getWGSLShader(e,"vertex",i),l=r===f.GLSL?this._compileShaderToSpirV(t,"fragment",i,a):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(o,l,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){let t=new cv(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new cO(e,this)}createMaterialContext(){return new dE}createDrawContext(){return new dS(this._bufferManager)}_preparePipelineContext(e,t,i,r,s,n,a,o){let l=e.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(ig.Log(["defines",o]),ig.Log(t),ig.Log(i),ig.Log("***********************************************")),e.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:n},r?e.stages=this._compileRawPipelineStageDescriptor(t,i,l):e.stages=this._compilePipelineStageDescriptor(t,i,o,l)}getAttributes(e,t){let i=Array(t.length);for(let r=0;r0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=o.useSRGBBuffer,l.label=o.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,u,c||1,o.creationFlags),l}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_){return this._createTextureBase(e,t,i,r,s,n,a,(e,t,i,r,s,n,a,o)=>{var l;if(e.baseWidth=r.width,e.baseHeight=r.height,e.width=r.width,e.height=r.height,e.format=-1!==e.format?e.format:null!=h?h:5,e.type=-1!==e.type?e.type:0,e._creationFlags=null!=p?p:0,o(e.width,e.height,r,t,e,()=>{}),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)n||a||this._generateMipmaps(e,this._uploadEncoder);else{let t=this._textureHelper.createGPUTextureForInternalTexture(e,r.width,r.height,void 0,p);!c1.IsImageBitmap(r)||(this._textureHelper.updateTexture(r,e,r.width,r.height,e.depth,t.format,0,0,s,!1,0,0),n||a||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()},()=>!1,o,l,h,u,c,d,_)}wrapWebGPUTexture(e){let t=new c2(e),i=new rU(this,m.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;e.generateMipMaps&&((null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource)||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e))}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;let s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){let r=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),r&&r.autoBindSampler){let e=i+cD.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e0;for(let t in e){let s=e[t],n=i[t],a=n.group,o=n.binding,l=s.type,h=s.object,u=s.indexInGroupEntries,c=this._bindGroupEntries[a];switch(c||(c=this._bindGroupEntries[a]=[]),l){case et.Sampler:void 0!==u&&r?c[u].resource=this._cacheSampler.getSampler(h):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._cacheSampler.getSampler(h)}));break;case et.Texture:case et.TextureWithoutSampler:{let e=h._texture._hardwareTexture;void 0!==u&&r?(l===et.Texture&&(c[u++].resource=this._cacheSampler.getSampler(h._texture)),c[u].resource=e.view):(s.indexInGroupEntries=c.length,l===et.Texture&&c.push({binding:o-1,resource:this._cacheSampler.getSampler(h._texture)}),c.push({binding:o,resource:e.view}));break}case et.StorageTexture:{let e=h._texture._hardwareTexture;(e.textureAdditionalUsages&ec.StorageBinding)==0&&ig.Error(`computeDispatch: The texture (name=${h.name}, uniqueId=${h.uniqueId}) is not a storage texture!`,50),void 0!==u&&r?c[u].resource=e.viewForWriting:(s.indexInGroupEntries=c.length,c.push({binding:o,resource:e.viewForWriting}));break}case et.ExternalTexture:{let e=h.underlyingResource;void 0!==u&&r?c[u].resource=this._device.importExternalTexture({source:e}):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._device.importExternalTexture({source:e})}));break}case et.UniformBuffer:case et.StorageBuffer:{let e=(et.UniformBuffer,h).getBuffer(),t=e.underlyingResource;void 0!==u&&r?(c[u].resource.buffer=t,c[u].resource.size=e.capacity):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:{buffer:t,offset:0,size:e.capacity}}))}}}for(let e=0;e0&&h.dispatchWorkgroups(r,s,n),h.end(),o&&(this._timestampQuery.endPass(this._timestampIndex,o),this._timestampIndex+=2)},dK.prototype.releaseComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},dK.prototype._prepareComputePipelineContext=function(e,t,i,r,s){this.dbgShowShaderCode&&(ig.Log(r),ig.Log(t)),e.sources={compute:t,rawCompute:i},e.stage=this._createComputePipelineStageDescriptor(t,r,s)},dK.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},dK.prototype._rebuildComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},dK.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},dK.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},dK.prototype._createDepthStencilCubeTexture=function(e,t){let i=new rU(this,m.DepthStencil);i.isCube=!0;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1},t);return i.format=r.generateStencil?13:14,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},dK.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=!1){return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,null,(e,t)=>{let i=t[0].width;this._setCubeMapTextureParams(e,!r),e.format=null!=a?a:-1;let n=this._textureHelper.createGPUTextureForInternalTexture(e,i,i);this._textureHelper.updateCubeTextures(t,n.underlyingResource,i,i,n.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!d)},dK.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},dK.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},dK.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},dK.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},dK.prototype._debugFlushPendingCommands=function(){for(let e=0;e{let i=d.width,n=a(e);if(!n)return;let h=[0,2,4,1,3,5];if(o){let e=4===r,t=o(n),a=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r>r,o=[];for(let i=0;i<6;i++){let a=t[r][l[i]];e&&(a=dJ(a,n,n,s)),o.push(new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}this._textureHelper.updateCubeTextures(o,a.underlyingResource,n,n,a.format,c,!1,0,0)}}else{let e=[];for(let t=0;t<6;t++)e.push(n[h[t]]);this.updateRawCubeTexture(d,e,r,s,c)}d.isReady=!0,null==t||t.removePendingData(d),l&&l()};return this._loadFile(e,e=>{p(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)}),d},dK.prototype.createRawTexture3D=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=new rU(this,m.Raw3D);return c.baseWidth=t,c.baseHeight=i,c.baseDepth=r,c.width=t,c.height=i,c.depth=r,c.format=s,c.type=h,c.generateMipMaps=n,c.samplingMode=o,c.is3D=!0,c._creationFlags=u,this._doNotHandleContextLost||(c._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(c,t,i,void 0,u),this.updateRawTexture3D(c,e,s,a,l,h),this._internalTexturesCache.push(c),c},dK.prototype.updateRawTexture3D=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture;4===i&&(t=dJ(t,e.width,e.height,n));let a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(a,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},dK.prototype.createRawTexture2DArray=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=new rU(this,m.Raw2DArray);return c.baseWidth=t,c.baseHeight=i,c.baseDepth=r,c.width=t,c.height=i,c.depth=r,c.format=s,c.type=h,c.generateMipMaps=n,c.samplingMode=o,c.is2DArray=!0,c._creationFlags=u,this._doNotHandleContextLost||(c._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(c,t,i,r,u),this.updateRawTexture2DArray(c,e,s,a,l,h),this._internalTexturesCache.push(c),c},dK.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture;4===i&&(t=dJ(t,e.width,e.height,n));let a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(a,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},dK.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){let u=e._hardwareTexture;return a&&this.flushFramebuffer(),this._textureHelper.readPixels(u.underlyingResource,l,h,t,i,u.format,r,s,n,o)},dK.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class d0 extends aF{constructor(e,t,i,r,s){super(e,t,i,r,s),r.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new h4)}}dK.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new d0(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},dK.prototype.createRenderTargetTexture=function(e,t){var i,r,s;let n=this._createHardwareRenderTargetWrapper(!1,!1,e),a={};void 0!==t&&"object"==typeof t?(a.generateMipMaps=t.generateMipMaps,a.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,a.generateStencilBuffer=a.generateDepthBuffer&&t.generateStencilBuffer,a.samplingMode=void 0===t.samplingMode?3:t.samplingMode,a.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,a.noColorAttachment=!!t.noColorAttachment,a.samples=t.samples,a.label=t.label):(a.generateMipMaps=t,a.generateDepthBuffer=!0,a.generateStencilBuffer=!1,a.samplingMode=3,a.creationFlags=0,a.noColorAttachment=!1);let o=a.noColorAttachment?null:this._createInternalTexture(e,t,!0,m.RenderTarget);return n.label=null!==(r=a.label)&&void 0!==r?r:"RenderTargetWrapper",n._samples=null!==(s=a.samples)&&void 0!==s?s:1,n._generateDepthBuffer=a.generateDepthBuffer,n._generateStencilBuffer=!!a.generateStencilBuffer,n.setTextures(o),(n._generateDepthBuffer||n._generateStencilBuffer)&&n.createDepthStencilTexture(0,!1,n._generateStencilBuffer,n.samples,a.generateStencilBuffer?13:14,a.label?a.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,a.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(o.generateMipMaps=!1)),n},dK.prototype._createDepthStencilTexture=function(e,t){let i=new rU(this,m.DepthStencil);i.label=t.label;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i);let s=i._hardwareTexture;return i.type=c1.GetTextureTypeFromFormat(s.format),this._internalTexturesCache.push(i),i},dK.prototype._setupDepthStencilTexture=function(e,t,i,r,s,n=1){let a=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},dK.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t&&(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t),t},dK.prototype.createRenderTargetCubeTexture=function(e,t){var i;let r=this._createHardwareRenderTargetWrapper(!1,!0,e),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,r.label=null!==(i=s.label)&&void 0!==i?i:"RenderTargetWrapper",r._generateDepthBuffer=s.generateDepthBuffer,r._generateStencilBuffer=s.generateStencilBuffer;let n=new rU(this,m.RenderTarget);return n.width=e,n.height=e,n.depth=0,n.isReady=!0,n.isCube=!0,n.samples=s.samples,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),r.setTextures(n),(r._generateDepthBuffer||r._generateStencilBuffer)&&r.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,r._generateStencilBuffer,r.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(n.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(n),t&&t.createMipMaps&&!s.generateMipMaps&&(n.generateMipMaps=!1),r},rN.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},dK.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},rN.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},dK.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,32|t,i)},dK.prototype.updateStorageBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},dK.prototype.readFromStorageBuffer=function(e,t,i,r,s){i=i||e.capacity;let n=this._bufferManager.createRawBuffer(i,el.MapRead|el.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,n,0,i),new Promise((e,t)=>{let a=()=>{n.mapAsync(eh.Read,0,i).then(()=>{let t=n.getMappedRange(0,i),s=r;if(void 0===s)(s=new Uint8Array(i)).set(new Uint8Array(t));else{let e=s.constructor;(s=new e(s.buffer)).set(new e(t))}n.unmap(),this._bufferManager.releaseBuffer(n),e(s)},i=>{this.isDisposed?e(new Uint8Array):t(i)})};s?(this.flushFramebuffer(),a()):this.onEndFrameObservable.addOnce(()=>{a()})})},dK.prototype.setStorageBuffer=function(e,t){var i,r;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(r=null==t?void 0:t.getBuffer())&&void 0!==r?r:null)},dK.prototype.updateVideoTexture=function(e,t,i){var r;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;((null===(r=e._hardwareTexture)||void 0===r?void 0:r.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),t&&void 0!==t.underlyingResource)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then(t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0}).catch(()=>{e.isReady=!0})};class d1{}d1.COPY=1,d1.CUT=2,d1.PASTE=3;class d2 extends ur{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=io.Gray(),i=ui.DefaultUtilityLayer,r=null,s=1,n=io.Yellow(),a=io.Gray()){var o,l,h,u,c,d,p;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new tj,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new t5(0,0,0),this._incrementalStartupValue=t5.Zero(),this._parent=r,this._coloredMaterial=new hD("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new io(.1,.1,.1)),this._hoverMaterial=new hD("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new hD("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a,this._disableMaterial.alpha=.4,this._gizmoMesh=new nX("axis",i.utilityLayerScene);let{arrowMesh:_,arrowTail:f}=this._createGizmoMesh(this._gizmoMesh,s),m=this._createGizmoMesh(this._gizmoMesh,s+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ur.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);let g=_.position.clone(),v=f.position.clone(),x=f.scaling.clone(),T=e=>{let t=3/this._rootMesh.scaling.length()*e*6;_.position.z+=t/3.5,f.scaling.y+=t,this.dragScale=f.scaling.y,f.position.z=_.position.z/2},b=()=>{_.position.set(g.x,g.y,g.z),f.position.set(v.x,v.y,v.z),f.scaling.set(x.x,x.y,x.z),this.dragScale=f.scaling.y,this._dragging=!1};this.dragBehavior=new al({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let E=0,S=0,C={snapDistance:0};this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),r=this._tmpVector,s=!1,n=0;if(this.uniformScaling?r.setAll(.57735):r.copyFrom(e),0==this.snapDistance)r.scaleToRef(i,r);else{E+=i,S+=i;let e=this.incrementalSnap?S:E;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),E%=this.snapDistance,r.scaleToRef(this.snapDistance*n,r),s=!0):r.scaleInPlace(0)}r.addInPlaceFromFloats(1,1,1),r.x=Math.abs(r.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,ie.Quaternion[0],ie.Vector3[2],ur.PreserveScaling?a:void 0),r.addInPlace(this._incrementalStartupValue),r.addInPlaceFromFloats(-1,-1,-1),r.x=Math.abs(r.x)*(this._incrementalStartupValue.x>0?1:-1),r.y=Math.abs(r.y)*(this._incrementalStartupValue.y>0?1:-1),r.z=Math.abs(r.z)*(this._incrementalStartupValue.z>0?1:-1),t7.ComposeToRef(r,ie.Quaternion[0],ie.Vector3[2],ie.Matrix[1])):(t7.ScalingToRef(r.x,r.y,r.z,ie.Matrix[2]),ie.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),ie.Matrix[1])),ie.Matrix[1].decompose(ie.Vector3[1],void 0,void 0,ur.PreserveScaling?a:void 0),1e5>Math.abs(ie.Vector3[1].x)&&1e5>Math.abs(ie.Vector3[1].y)&&1e5>Math.abs(ie.Vector3[1].z)&&this.attachedNode.getWorldMatrix().copyFrom(ie.Matrix[1]),s&&(C.snapDistance=this.snapDistance*n,this.onSnapObservable.notifyObservers(C)),this._matrixChanged()}}),this.dragBehavior.onDragStartObservable.add(()=>{var e;this._dragging=!0;let t=this.attachedNode._isMesh?this.attachedNode:void 0;null===(e=this.attachedNode)||void 0===e||e.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,ur.PreserveScaling?t:void 0),E=0,S=0}),this.dragBehavior.onDragObservable.add(e=>T(e.dragDistance)),this.dragBehavior.onDragEndObservable.add(b),null===(h=null===(l=null===(o=null==r?void 0:r.uniformScaleGizmo)||void 0===o?void 0:o.dragBehavior)||void 0===l?void 0:l.onDragObservable)||void 0===h||h.add(e=>T(e.delta.y)),null===(d=null===(c=null===(u=null==r?void 0:r.uniformScaleGizmo)||void 0===u?void 0:u.dragBehavior)||void 0===c?void 0:c.onDragEndObservable)||void 0===d||d.add(b);let y={gizmoMeshes:[_,f],colliderMeshes:[m.arrowMesh,m.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(p=this._parent)||void 0===p||p.addToAxisCache(this._gizmoMesh,y),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this._isHovered=-1!=y.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(y.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(y.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)});let A=i._getSharedGizmoLight();A.includedOnlyMeshes=A.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){let r=ua("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),s=ue("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return r.scaling.scaleInPlace(.1),r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,r.position.z+=.3,s.material=this._coloredMaterial,s.position.z+=.1375,s.rotation.x=Math.PI/2,i&&(r.visibility=0,s.visibility=0),e.addChild(r),e.addChild(s),{arrowMesh:r,arrowTail:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach(e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)}),this._customMeshSet=!1)}}d2.MinimumAbsoluteScale=.001;class d3 extends ur{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=io.Gray(),i=ui.DefaultUtilityLayer,r=32,s=null,n=!1,a=1,o=io.Yellow(),l=io.Gray()){var h;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new tj,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new t5,this._parent=s,this._coloredMaterial=new hD("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new io(.1,.1,.1)),this._hoverMaterial=new hD("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=o,this._hoverMaterial.specularColor=o,this._disableMaterial=new hD("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new nX("",i.utilityLayerScene);let{rotationMesh:u,collider:c}=this._createGizmoMesh(this._gizmoMesh,a,r);this._rotationDisplayPlane=ao("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),rN.ShadersStore.rotationGizmoVertexShader=d3._RotationGizmoVertexShader,rN.ShadersStore.rotationGizmoFragmentShader=d3._RotationGizmoFragmentShader,this._rotationShaderMaterial=new ug("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=o,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,ur.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new al({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=d3.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);let d=new t5,p=new t7,_=new t5,f=new t5;this.dragBehavior.onDragStartObservable.add(e=>{this.attachedNode&&(d.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(p),t5.TransformCoordinatesToRef(e.dragPlanePoint,p,d),this._angles.x=Math.atan2(d.y,d.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,d.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});let m={snapDistance:0},g=0,v=new t7,x=new t8;this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let r=new t5(1,1,1),s=new t8(0,0,0,1),n=new t5(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(r,s,n),!(.001>=Math.abs(Math.abs(r.x)-Math.abs(r.y))&&.001>=Math.abs(Math.abs(r.x)-Math.abs(r.z)))&&this.updateGizmoRotationToMatchAttachedMesh){ig.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}s.normalize();let a=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,o=t.dragPlanePoint.subtract(a).normalize(),l=d.subtract(a).normalize(),h=t5.Cross(o,l),u=t5.Dot(o,l),c=Math.atan2(h.length(),u)*this.sensitivity;_.copyFrom(e),f.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(p),f=t5.TransformCoordinates(_,p));let T=!1;if(i.utilityLayerScene.activeCamera){let e=i.utilityLayerScene.activeCamera.position.subtract(a).normalize();t5.Dot(e,f)>0&&(_.scaleInPlace(-1),f.scaleInPlace(-1),T=!0)}t5.Dot(f,h)>0&&(c=-c),ie.Vector3[0].set(c,0,0),this.dragBehavior.validateDrag(ie.Vector3[0])||(c=0);let b=!1;if(0!=this.snapDistance){if(Math.abs(g+=c)>this.snapDistance){let e=Math.floor(Math.abs(g)/this.snapDistance);g<0&&(e*=-1),g%=this.snapDistance,c=this.snapDistance*e,b=!0}else c=0}let E=Math.sin(c/2);if(x.set(_.x*E,_.y*E,_.z*E,Math.cos(c/2)),v.determinant()>0){let e=new t5;x.toEulerAnglesToRef(e),t8.RotationYawPitchRollToRef(e.y,-e.x,-e.z,x)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(x,s),s.normalize(),t7.ComposeToRef(r,s,n,this.attachedNode.getWorldMatrix());else{x.toRotationMatrix(ie.Matrix[0]);let e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(ie.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}d.copyFrom(t.dragPlanePoint),b&&(m.snapDistance=c,this.onSnapObservable.notifyObservers(m)),this._angles.y+=c,this.angle+=T?-c:c,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});let T=i._getSharedGizmoLight();T.includedOnlyMeshes=T.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));let b={colliderMeshes:[c],gizmoMeshes:[u],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(h=this._parent)||void 0===h||h.addToAxisCache(this._gizmoMesh,b),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=d3.MaxDragAngle,this._isHovered=-1!=b.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=b.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(b.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(b.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){let r=h$("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;let s=h$("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,ur.PreserveScaling),e.addChild(r,ur.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}}d3.MaxDragAngle=9*Math.PI/20,d3._RotationGizmoVertexShader=` + precision highp float; + attribute vec3 position; + attribute vec2 uv; + uniform mat4 worldViewProjection; + varying vec3 vPosition; + varying vec2 vUV; + + void main(void) { + gl_Position = worldViewProjection * vec4(position, 1.0); + vUV = uv; + }`,d3._RotationGizmoFragmentShader=` + precision highp float; + varying vec2 vUV; + varying vec3 vPosition; + uniform vec3 angles; + uniform vec3 rotationColor; + + #define twopi 6.283185307 + + void main(void) { + vec2 uv = vUV - vec2(0.5); + float angle = atan(uv.y, uv.x) + 3.141592; + float delta = gl_FrontFacing ? angles.y : -angles.y; + float begin = angles.x - delta * angles.z; + float start = (begin < (begin + delta)) ? begin : (begin + delta); + float end = (begin > (begin + delta)) ? begin : (begin + delta); + float len = sqrt(dot(uv,uv)); + float opacity = 1. - step(0.5, len); + + float base = abs(floor(start / twopi)) * twopi; + start += base; + end += base; + + float intensity = 0.; + for (int i = 0; i < 5; i++) + { + intensity += max(step(start, angle) - step(end, angle), 0.); + angle += twopi; + } + gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity; + } + `;class d4 extends nj{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=t7.Identity(),this._projectionMatrix=t7.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=t5.Zero()),t5.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=t5.Zero()),t5.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=t5.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=t5.Cross(this.direction,sj.Y),t=t5.Cross(e,this.direction);return t5.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=t5.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?this._currentRenderId=this.getScene().getRenderId():(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=t7.Identity()),t7.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,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){let t=ie.Vector3[0],i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),t5.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(t5.Dot(t,t5.Up()))&&(t.z=1e-13);let r=ie.Vector3[1];return i.addToRef(t,r),t7.LookAtLHToRef(i,r,t5.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,null!=e?e:this._viewMatrix,null!=t?t:[]),this._projectionMatrix}}iZ([ij()],d4.prototype,"position",null),iZ([ij()],d4.prototype,"direction",null),iZ([iW()],d4.prototype,"shadowMinZ",null),iZ([iW()],d4.prototype,"shadowMaxZ",null),i0.AddNodeConstructor("Light_Type_1",(e,t)=>()=>new d5(e,t5.Zero(),t));class d5 extends d4{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,i){super(e,i),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 nj.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;t&&t7.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,i){let r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let e=t5.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}let s=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;t7.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?o:a,l?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._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):e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function d6(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);let r=ul("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=up("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;let n=nX.MergeMeshes([s,r],!0);return n.name=e,n}iZ([iW()],d5.prototype,"shadowFrustumSize",null),iZ([iW()],d5.prototype,"shadowOrthoScale",null),iZ([iW()],d5.prototype,"autoUpdateExtends",void 0),iZ([iW()],d5.prototype,"autoCalcShadowZBounds",void 0),iZ([iW("orthoLeft")],d5.prototype,"_orthoLeft",void 0),iZ([iW("orthoRight")],d5.prototype,"_orthoRight",void 0),iZ([iW("orthoTop")],d5.prototype,"_orthoTop",void 0),iZ([iW("orthoBottom")],d5.prototype,"_orthoBottom",void 0),nX.CreateHemisphere=(e,t,i,r)=>d6(e,{segments:t,diameter:i},r),i0.AddNodeConstructor("Light_Type_2",(e,t)=>()=>new d8(e,t5.Zero(),t5.Zero(),0,0,t));class d8 extends d4{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()&&(d8._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):d8._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,i,r,s,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=t7.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=t5.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=t5.Zero(),this._projectionTextureViewLightMatrix=t7.Zero(),this._projectionTextureProjectionLightMatrix=t7.Zero(),this._projectionTextureScalingMatrix=t7.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return nj.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;t7.PerspectiveFovLHToRef(s,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.direction,this._projectionTextureViewTargetVector),t7.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=1/Math.tan(this._angle/2);t7.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,-i*t,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof n6){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;t7.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("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=t5.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=t5.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?t5.Normalize(this.transformedDirection):t5.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){let t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){let t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady())}}iZ([iW()],d8.prototype,"angle",null),iZ([iW()],d8.prototype,"innerAngle",null),iZ([iW()],d8.prototype,"shadowAngleScale",null),iZ([iW()],d8.prototype,"exponent",void 0),iZ([iW()],d8.prototype,"projectionTextureLightNear",null),iZ([iW()],d8.prototype,"projectionTextureLightFar",null),iZ([iW()],d8.prototype,"projectionTextureUpDirection",null),iZ([iH("projectedLightTexture")],d8.prototype,"_projectionTexture",void 0);class d7 extends ur{constructor(e=ui.DefaultUtilityLayer){super(e),this._cachedPosition=new t5,this._cachedForward=new t5(0,0,1),this._pointerObserver=null,this.onClickedObservable=new tj,this._light=null,this.attachedMesh=new nM("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new nA("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new hD("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new io(.5,.5,.5),this._material.specularColor=new io(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(e=>{this._light&&(this._isHovered=!!(e.pickInfo&&-1!=this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))},sS.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){ig.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof ut?this._lightMesh=d7._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof d5?this._lightMesh=d7._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof d8?this._lightMesh=d7._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=d7._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._lightMesh.parent=this._rootMesh;let t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new t8,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);let t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(ie.Vector3[0]),e=ie.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position){if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{let e=this.attachedMesh.position;this._light.position=new t5(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}}if(this._light.direction){let e=this._getMeshForward();t5.DistanceSquared(e,this._cachedForward)>1e-4?(this._light.direction=new t5(e.x,e.y,e.z),this._cachedForward.copyFrom(e)):t5.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){let t=new nX("hemisphereLight",e),i=d6(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(d7._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){let t=new nX("pointLight",e),i=ul(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(d7._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){let t=new nX("spotLight",e);ul(t.name,{segments:10,diameter:1},e).parent=t;let i=d6(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(d7._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){let t=new nX("directionalLight",e),i=new nX(t.name,e);i.parent=t,ul(t.name,{diameter:1.2,segments:10},e).parent=i;let r=ue(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);r.parent=i;let s=r.clone(t.name);s.scaling.y=.5,s.position.x+=1.25;let n=r.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;let a=ue(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return a.position.y+=3,a.parent=i,(s=a.clone(t.name)).position.y=1.5,s.position.x+=1.25,(n=a.clone(t.name)).position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(d7._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}d7._Scale=.007,d7._CreateLightLines=(e,t)=>{let i=new nX("root",t);i.rotation.x=Math.PI/2;let r=new nX("linePivot",t);r.parent=i;let s=ue("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){let t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(r.clone("linePivotClone").rotation.z=Math.PI),i};class d9 extends ur{constructor(e=ui.DefaultUtilityLayer,t){super(e),this._pointerObserver=null,this.onClickedObservable=new tj,this._camera=null,this._invProjection=new t7,this._material=new hD("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._gizmoColor=t,this._material.diffuseColor=null!=t?t:new io(.5,.5,.5),this._material.specularColor=new io(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(e=>{this._camera&&(this._isHovered=!!(e.pickInfo&&-1!=this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))},sS.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){var t,i;if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=d9._CreateCameraMesh(this.gizmoLayer.utilityLayerScene);let r=null!==(i=null===(t=this._gizmoColor)||void 0===t?void 0:t.toColor4(1))&&void 0!==i?i:new il(1,1,1,1);this._cameraLinesMesh=d9._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,r),this._cameraMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._cameraMesh.parent=this._rootMesh,this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;let s=this.gizmoLayer._getSharedGizmoLight();s.includedOnlyMeshes=s.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){let t=new nX("rootCameraGizmo",e),i=new nX(t.name,e);i.parent=t,ua(t.name,{width:1,height:.8,depth:.5},e).parent=i;let r=ue(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);r.parent=i,r.position.y=.3,r.position.x=-.6,r.rotation.x=.5*Math.PI;let s=ue(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);s.parent=i,s.position.y=.5,s.position.x=.4,s.rotation.x=.5*Math.PI;let n=ue(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(d9._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){let i=new nX("rootCameraGizmo",e),r=new nX(i.name,e);r.parent=i;for(let i=0;i<4;i+=2)for(let s=0;s<4;s+=2){let n=uy("lines",{points:[new t5(-1+s,-1+i,-1),new t5(-1+s,-1+i,1)],colors:[t,t]},e);n.parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,(n=uy("lines",{points:[new t5(-1,-1+s,-1+i),new t5(1,-1+s,-1+i)],colors:[t,t]},e)).parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,(n=uy("lines",{points:[new t5(-1+s,-1,-1+i),new t5(-1+s,1,-1+i)],colors:[t,t]},e)).parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}d9._Scale=.05,rO.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";let pe=`vec4 pack(float depth) +{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;rO.IncludesShadersStore.packingFunctions=pe;let pt=`#ifdef DOF +factor=sampleCoC(sampleCoord{X}); +computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; +#endif +`;rO.IncludesShadersStore.kernelBlurFragment=pt;let pi=`#ifdef DOF +factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_DEP_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; +#endif +`;rO.IncludesShadersStore.kernelBlurFragment2=pi;let pr=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; +#ifdef DOF +uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } +#endif +#include[0..varyingCount] +#ifdef PACKEDFLOAT +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float computedWeight=0.0; +#ifdef PACKEDFLOAT +float blend=0.; +#else +vec4 blend=vec4(0.); +#endif +#ifdef DOF +float sumOfWeights=CENTER_WEIGHT; +float factor=0.0; +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; +#else +blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; +#endif +#endif +#include[0..varyingCount] +#include[0..depCount] +#ifdef PACKEDFLOAT +gl_FragColor=pack(blend); +#else +gl_FragColor=blend; +#endif +#ifdef DOF +gl_FragColor/=sumOfWeights; +#endif +}`;rO.ShadersStore.kernelBlurPixelShader=pr,rO.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";let ps=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; +#include[0..varyingCount] +const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +sampleCenter=(position*madd+madd); +#include[0..varyingCount] +gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.kernelBlurVertexShader=ps;class pn extends aL{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s,n=n6.BILINEAR_SAMPLINGMODE,a,o,l=0,h="",u=!1,c=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],r,s,n,a,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,c),this._blockCompilation=u,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add(e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,n){this._updateParameters(s,n)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],n=[],a=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){return 1/(1/3*Math.sqrt(2*Math.PI))*Math.exp(-(e*e/(1/3*2*(1/3))))}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return i$.Parse(()=>new pn(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}}iZ([iW("kernel")],pn.prototype,"_kernel",void 0),iZ([iW("packedFloat")],pn.prototype,"_packedFloat",void 0),iZ([iG(4,void 0)],pn.prototype,"direction",void 0),t0["BABYLON.BlurPostProcess"]=pn;class pa extends a5{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){let e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){let e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,n=n6.BILINEAR_SAMPLINGMODE,a=!0){let o;if(super(e,t,i,r,!0,s,!1,n,a),this.mirrorPlane=new sG(0,1,0,1),this._transformMatrix=t7.Zero(),this._mirrorMatrix=t7.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateGammaSpace()});let l=i.getEngine();l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add(()=>{var t;null===(t=l._debugPushGroup)||void 0===t||t.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)}),this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),t7.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),o=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=t5.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=o})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){let e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new pn("horizontal blur",new t4(1,0),this._blurKernelX,this._blurRatio,null,n6.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new pn("vertical blur",new t4(0,1),this._blurKernelY,this._blurRatio,null,n6.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new pa(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;let e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();let t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}}n6._CreateMirror=(e,t,i,r)=>new pa(e,t,i,r);class po extends n3{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(t7.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach(e=>r+=e),new po(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){let s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;let n=new po(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,n}constructor(e,t,i=null,r=!1,s=null,n=null,a=null,o=5,l=!1,h=null,u=!1,c=.8,d=0,p,_){var f;if(super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new tj,this.boundingBoxPosition=t5.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new t7,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this._format=o,this.isCube=!0,this._textureMatrix=t7.Identity(),this._createPolynomials=u,this.coordinatesMode=n6.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=h,this._loaderOptions=p,this._useSRGBBuffer=_,this._lodScale=c,this._lodOffset=d,!e&&!s)return;this.updateURL(e,h,n,l,a,i,null===(f=this.getScene())||void 0===f?void 0:f.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,r=!1,s=null,n=null,a=!1,o=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);let l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),u=0===h.indexOf(".dds"),c=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(c?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(d||c||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-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem)))return;let r=ie.Vector3[0],s=ie.Quaternion[0],n=ie.Vector3[1];this._textureMatrix.decompose(r,s,n),s.z*=-1,s.w*=-1,t7.ComposeToRef(r,s,n,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(null===(e=this.getScene())||void 0===e?void 0:e.useRightHandedSystem)?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;let r=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);let n=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},a=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),n6.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?ss.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(()=>n()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,r,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,r,this._files,this._noMipmap,e,a,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){let r=i$.Parse(()=>{var r;let s=!1;return e.prefiltered&&(s=e.prefiltered),new po(i+(null!==(r=e.url)&&void 0!==r?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=t5.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=t5.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{let t=new po(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t},this);return t.uniqueId=e,t}}iZ([iW()],po.prototype,"url",void 0),iZ([ij()],po.prototype,"boundingBoxPosition",void 0),iZ([ij()],po.prototype,"boundingBoxSize",null),iZ([iW("rotationY")],po.prototype,"rotationY",null),iZ([iW("files")],po.prototype,"_files",void 0),iZ([iW("forcedExtension")],po.prototype,"_forcedExtension",void 0),iZ([iW("extensions")],po.prototype,"_extensions",void 0),iZ([iG(12,"textureMatrix")],po.prototype,"_textureMatrix",void 0),iZ([iG(12,"textureMatrixRefraction")],po.prototype,"_textureMatrixRefraction",void 0),n6._CubeTextureParser=po.Parse,t0["BABYLON.CubeTexture"]=po;let pl=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +uniform vec4 vPrimaryColorShadow; +#endif +uniform float shadowLevel;uniform float alpha; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#endif +#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) +uniform vec3 vBackgroundCenter; +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 vReflectionControl; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) +uniform mat4 view; +#endif +#ifdef PROJECTED_GROUND +uniform vec2 projectedGroundInfos; +#endif +`;rO.IncludesShadersStore.backgroundFragmentDeclaration=pl;let ph=`layout(std140,column_major) uniform;uniform Material +{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; +#include +`;rO.IncludesShadersStore.backgroundUboDeclaration=ph;let pu=`#ifdef TEXTURELODSUPPORT +#extension GL_EXT_shader_texture_lod : enable +#endif +precision highp float; +#include<__decl__backgroundFragment> +#include +varying vec3 vPositionW; +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef DIFFUSE +#if DIFFUSEDIRECTUV==1 +#define vDiffuseUV vMainUV1 +#elif DIFFUSEDIRECTUV==2 +#define vDiffuseUV vMainUV2 +#else +varying vec2 vDiffuseUV; +#endif +uniform sampler2D diffuseSampler; +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include +#endif +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE; +#endif +#ifndef SHADOWONLY +#define SHADOWONLY; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include +#include +#include +#ifdef REFLECTIONFRESNEL +#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#ifdef PROJECTED_GROUND +float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; } +vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q) +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(0.0,1.0,0.0); +#endif +float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; +#include[0..maxSimultaneousLights] +#ifdef SHADOWINUSE +globalShadow/=shadowLightCount; +#else +globalShadow=1.0; +#endif +#ifndef BACKMAT_SHADOWONLY +vec4 reflectionColor=vec4(1.,1.,1.,1.); +#ifdef REFLECTION +#ifdef PROJECTED_GROUND +vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=reflectionVector; +#else +vec2 reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +#ifdef REFLECTIONBLUR +float reflectionLOD=vReflectionInfos.y; +#ifdef TEXTURELODSUPPORT +reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#else +float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +reflectionSpecularMid, +lodReflectionNormalizedDoubled +);} else {reflectionColor=mix( +reflectionSpecularMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#else +vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef GAMMAREFLECTION +reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); +#endif +#ifdef REFLECTIONBGR +reflectionColor.rgb=reflectionColor.bgr; +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#endif +vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; +#ifdef DIFFUSE +vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); +#ifdef GAMMADIFFUSE +diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); +#endif +diffuseMap.rgb*=vDiffuseInfos.y; +#ifdef DIFFUSEHASALPHA +finalAlpha*=diffuseMap.a; +#endif +diffuseColor=diffuseMap.rgb; +#endif +#ifdef REFLECTIONFRESNEL +vec3 colorBase=diffuseColor; +#else +vec3 colorBase=reflectionColor.rgb*diffuseColor; +#endif +colorBase=max(colorBase,0.0); +#ifdef USERGBCOLOR +vec3 finalColor=colorBase; +#else +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); +#else +vec3 mainColor=vPrimaryColor.rgb; +#endif +vec3 finalColor=colorBase*mainColor; +#endif +#ifdef REFLECTIONFRESNEL +vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; +#ifdef REFLECTIONFALLOFF +float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; +#endif +finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); +#endif +#ifdef OPACITYFRESNEL +float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; +#endif +#ifdef SHADOWINUSE +finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); +#endif +vec4 color=vec4(finalColor,finalAlpha); +#else +vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); +#endif +#include +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +#if !defined(SKIPFINALCOLORCLAMP) +color.rgb=clamp(color.rgb,0.,30.0); +#endif +#else +color=applyImageProcessing(color); +#endif +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#ifdef NOISE +color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); +#endif +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +} +`;rO.ShadersStore.backgroundPixelShader=pu;let pc=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +`;rO.IncludesShadersStore.backgroundVertexDeclaration=pc;let pd=`precision highp float; +#include<__decl__backgroundVertex> +#include +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include +#include +#include +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +varying vec2 vDiffuseUV; +#endif +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=position; +#endif +#include +#include +#include +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} +#else +gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#endif +vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normal); +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); +#ifdef EQUIRECTANGULAR_RELFECTION_FOV +mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} +#endif +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uv; +#endif +#ifdef MAINUV2 +vMainUV2=uv2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +if (vDiffuseInfos.x==0.) +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} +else +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} +#endif +#include +#include +#include[0..maxSimultaneousLights] +#ifdef VERTEXCOLOR +vColor=color; +#endif +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +} +`;rO.ShadersStore.backgroundVertexShader=pd;class pp extends sh{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.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.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!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.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class p_ extends af{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=p_.StandardReflectance0*t,this.reflectionReflectance90=p_.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=p_.StandardReflectance0+(1-p_.StandardReflectance0)*t,this.reflectionReflectance90=p_.StandardReflectance90+(1-p_.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}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){super(e,t),this.primaryColor=io.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=t5.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new sa(16),this._reflectionControls=t6.Zero(),this._white=io.White(),this._primaryShadowColor=io.Black(),this._primaryHighlightColor=io.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!!this._diffuseTexture&&!!this._diffuseTexture.isRenderTarget||!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new pp);let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(nw.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,nw.PrepareDefinesForMultiview(r,s),s._areTexturesDirty){if(s._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&lE.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;nw.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE"),s.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,s.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,s.OPACITYFRESNEL=this._opacityFresnel}else s.DIFFUSE=!1,s.DIFFUSEDIRECTUV=0,s.DIFFUSEHASALPHA=!1,s.GAMMADIFFUSE=!1,s.OPACITYFRESNEL=!1;let e=this._reflectionTexture;if(e&&lE.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(s.REFLECTION=!0,s.GAMMAREFLECTION=e.gammaSpace,s.RGBDREFLECTION=e.isRGBD,s.REFLECTIONBLUR=this._reflectionBlur>0,s.LODINREFLECTIONALPHA=e.lodLevelInAlpha,s.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,s.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===n6.INVCUBIC_MODE&&(s.INVERTCUBICMAP=!0),s.REFLECTIONMAP_3D=e.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case n6.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case n6.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case n6.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case n6.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case n6.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case n6.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case n6.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case n6.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case n6.CUBIC_MODE:case n6.INVCUBIC_MODE:default:s.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(s.REFLECTIONFRESNEL=!0,s.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1)}else s.REFLECTION=!1,s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1,s.REFLECTIONBLUR=!1,s.REFLECTIONMAP_3D=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.INVERTCUBICMAP=!1,s.REFLECTIONMAP_OPPOSITEZ=!1,s.LODINREFLECTIONALPHA=!1,s.GAMMAREFLECTION=!1,s.RGBDREFLECTION=!1}s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.USERGBCOLOR=this._useRGBColor,s.NOISE=this._enableNoise}if(s._areLightsDirty&&(s.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),s.BACKMAT_SHADOWONLY=this._shadowOnly),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(s._areMiscDirty&&(s.REFLECTIONMAP_3D&&this._enableGroundProjection?(s.PROJECTED_GROUND=!0,s.REFLECTIONMAP_SKYBOX=!0):s.PROJECTED_GROUND=!1),nw.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),nw.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),nw.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(sf.NormalKind)&&(e.createNormals(!0),ig.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();let i=new aO;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),nw.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);let a=[sf.PositionKind];s.NORMAL&&a.push(sf.NormalKind),s.UV1&&a.push(sf.UVKind),s.UV2&&a.push(sf.UV2Kind),nw.PrepareAttributesForBones(a,e,s,i),nw.PrepareAttributesForInstances(a,s);let o=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];nD(o);let l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];sd&&(sd.PrepareUniforms(o,s),sd.PrepareSamplers(l,s)),nw.PrepareUniformsAndSamplersList({uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});let u=s.toString(),c=r.getEngine().createEffect("background",{attributes:a,uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:u,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n);t.setEffect(c,s,this._materialContext),this.buildUniformLayout()}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)&&(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.materialDefines;if(!s)return;let n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),nw.BindBonesParameters(t,this._activeEffect);let a=this._mustRebind(r,n,t.visibility);if(a){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);let e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(r.texturesEnabled&&(this._diffuseTexture&&lE.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),nw.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&lE.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&lE.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&lE.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),nN(this._activeEffect,this,r),r.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(a||!this.isFrozen)&&(r.lightsEnabled&&nw.BindLights(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(n),nw.BindFogParameters(r,t,this._activeEffect,!0),this._useLogarithmicDepth&&nw.BindLogDepth(s,n,r),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return i$.Clone(()=>new p_(e,this.getScene()),this)}serialize(){let e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return i$.Parse(()=>new p_(e.name,t),e,t,i)}}p_.StandardReflectance0=.05,p_.StandardReflectance90=.5,iZ([iX()],p_.prototype,"_primaryColor",void 0),iZ([iz("_markAllSubMeshesAsLightsDirty")],p_.prototype,"primaryColor",void 0),iZ([iX()],p_.prototype,"__perceptualColor",void 0),iZ([iW()],p_.prototype,"_primaryColorShadowLevel",void 0),iZ([iW()],p_.prototype,"_primaryColorHighlightLevel",void 0),iZ([iz("_markAllSubMeshesAsLightsDirty")],p_.prototype,"primaryColorHighlightLevel",null),iZ([iH()],p_.prototype,"_reflectionTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"reflectionTexture",void 0),iZ([iW()],p_.prototype,"_reflectionBlur",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"reflectionBlur",void 0),iZ([iH()],p_.prototype,"_diffuseTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"diffuseTexture",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"shadowLights",void 0),iZ([iW()],p_.prototype,"_shadowLevel",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"shadowLevel",void 0),iZ([ij()],p_.prototype,"_sceneCenter",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"sceneCenter",void 0),iZ([iW()],p_.prototype,"_opacityFresnel",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"opacityFresnel",void 0),iZ([iW()],p_.prototype,"_reflectionFresnel",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"reflectionFresnel",void 0),iZ([iW()],p_.prototype,"_reflectionFalloffDistance",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"reflectionFalloffDistance",void 0),iZ([iW()],p_.prototype,"_reflectionAmount",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"reflectionAmount",void 0),iZ([iW()],p_.prototype,"_reflectionReflectance0",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"reflectionReflectance0",void 0),iZ([iW()],p_.prototype,"_reflectionReflectance90",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"reflectionReflectance90",void 0),iZ([iW()],p_.prototype,"_useRGBColor",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"useRGBColor",void 0),iZ([iW()],p_.prototype,"_enableNoise",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"enableNoise",void 0),iZ([iW()],p_.prototype,"_maxSimultaneousLights",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],p_.prototype,"maxSimultaneousLights",void 0),iZ([iW()],p_.prototype,"_shadowOnly",void 0),iZ([iz("_markAllSubMeshesAsLightsDirty")],p_.prototype,"shadowOnly",void 0),iZ([iG(9,void 0)],p_.prototype,"_imageProcessingConfiguration",void 0),iZ([iW(),iz("_markAllSubMeshesAsMiscDirty")],p_.prototype,"enableGroundProjection",void 0),iZ([iW()],p_.prototype,"projectedGroundRadius",void 0),iZ([iW()],p_.prototype,"projectedGroundHeight",void 0),t0["BABYLON.BackgroundMaterial"]=p_;class pf{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new io(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new io(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:t5.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=Object.assign(Object.assign({},pf._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new tj,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){let t=Object.assign(Object.assign({},this._options),e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new il(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof n3){this._scene.environmentTexture=this._options.environmentTexture;return}let e=po.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new nX("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;let e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};let r=this._scene.getWorldExtends(e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof oW&&this._scene.activeCamera.upperRadiusLimit&&(t=e=2*this._scene.activeCamera.upperRadiusLimit);let n=s.length();n>e&&(t=e=2*n),e*=1.1,t*=1.5,(i=r.min.add(s.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=ao("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(()=>{this._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new p_("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof n3){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new n6(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture}}_setupGroundMirrorTexture(e){let t=n6.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new pa("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,n6.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new sG(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new p_("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof n3){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new po(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=n6.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture}}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}pf._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",pf._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",pf._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class pm extends nA{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=n6.CLAMP_ADDRESSMODE,this._texture.wrapV=n6.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=n6.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=n6.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=pm.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new tj,this.onLoadObservable=new tj,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=void 0===i.autoPlay||!!i.autoPlay,i.loop=void 0===i.loop||!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=ul(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:nX.BACKSIDE},r);let n=this._material=new p_(e+"_material",r);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;let a=this._initTexture(t,r,i);if(this.texture=a,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=ul("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:nX.BACKSIDE},r),this._halfDomeMask.rotate(sj.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce(()=>{this._setReady(!0)}),i.faceForward&&r.activeCamera){let e=r.activeCamera,t=t5.Forward(),i=t5.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(t5.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case pm.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case pm.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;let e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=e:this._texture.uOffset=t});break}case pm.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0})}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}pm.MODE_MONOSCOPIC=0,pm.MODE_TOPBOTTOM=1,pm.MODE_SIDEBYSIDE=2;class pg extends pm{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new n6(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)})}}pg.MODE_MONOSCOPIC=pm.MODE_MONOSCOPIC,pg.MODE_TOPBOTTOM=pm.MODE_TOPBOTTOM,pg.MODE_SIDEBYSIDE=pm.MODE_SIDEBYSIDE;let pv=0,px=e=>{if(!e.environmentBRDFTexture){let t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;let i=e._blockEntityCollection;e._blockEntityCollection=!1;let r=n6.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"+pv++,e,!0,!1,n6.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;let s=e.getEngine().getLoadedTexturesCache(),n=s.indexOf(r.getInternalTexture());-1!==n&&s.splice(n,1),r.isRGBD=!0,r.wrapU=n6.CLAMP_ADDRESSMODE,r.wrapV=n6.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,cr.ExpandRGBDTexture(r);let a=e.getEngine().onContextRestoredObservable.add(()=>{r.isRGBD=!0;let t=e.onBeforeRenderObservable.add(()=>{r.isReady()&&(e.onBeforeRenderObservable.remove(t),cr.ExpandRGBDTexture(r))})});e.onDisposeObservable.add(()=>{e.getEngine().onContextRestoredObservable.remove(a)})}return e.environmentBRDFTexture};class pT extends sh{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 pb extends hA{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new pT,t),this._useEnergyConservation=pb.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=pb.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=pb.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=pb.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=pb.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=pb.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=pb.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=pb.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],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"}}pb.DEFAULT_USE_ENERGY_CONSERVATION=!0,pb.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,pb.DEFAULT_USE_SPHERICAL_HARMONICS=!0,pb.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,iZ([iW(),iz("_markAllSubMeshesAsMiscDirty")],pb.prototype,"useEnergyConservation",void 0),iZ([iW(),iz("_markAllSubMeshesAsMiscDirty")],pb.prototype,"useSmithVisibilityHeightCorrelated",void 0),iZ([iW(),iz("_markAllSubMeshesAsMiscDirty")],pb.prototype,"useSphericalHarmonics",void 0),iZ([iW(),iz("_markAllSubMeshesAsMiscDirty")],pb.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);let pE=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; +#ifdef ALBEDO +uniform vec2 vAlbedoInfos; +#endif +#ifdef AMBIENT +uniform vec4 vAmbientInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#ifdef REALTIME_FILTERING +uniform vec2 vReflectionFilteringInfo; +#endif +uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#ifdef CLEARCOAT +uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT +uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#endif +#ifdef IRIDESCENCE +uniform vec4 vIridescenceParams; +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +uniform vec3 vAnisotropy; +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +uniform vec4 vSheenColor; +#ifdef SHEEN_ROUGHNESS +uniform float vSheenRoughness; +#endif +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#ifdef REALTIME_FILTERING +uniform vec2 vRefractionFilteringInfo; +#endif +#ifdef SS_DISPERSION +uniform float dispersion; +#endif +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; +#endif +#ifdef PREPASS +#ifdef SS_SCATTERING +uniform float scatteringDiffusionProfile; +#endif +#endif +#if DEBUGMODE>0 +uniform vec2 vDebugMode; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#define ADDITIONAL_FRAGMENT_DECLARATION +`;rO.IncludesShadersStore.pbrFragmentDeclaration=pE;let pS=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; +#define ADDITIONAL_UBO_DECLARATION +}; +#include +#include +`;rO.IncludesShadersStore.pbrUboDeclaration=pS;let pC=`varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#include[1..7] +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +`;rO.IncludesShadersStore.pbrFragmentExtraDeclaration=pC;let py=`#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying vec2 v_VARYINGNAME_UV; +#endif +#endif +`;rO.IncludesShadersStore.samplerFragmentAlternateDeclaration=py;let pA=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) +uniform sampler2D clearCoatRoughnessSampler; +#endif +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) +uniform sampler2D sheenRoughnessSampler; +#endif +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform samplerCube irradianceSampler; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform sampler2D irradianceSampler; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#endif +#ifdef ENVIRONMENTBRDF +uniform sampler2D environmentBrdfSampler; +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#ifdef SS_REFRACTIONMAP_3D +#define sampleRefraction(s,c) textureCube(s,c) +uniform samplerCube refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; +#endif +#else +#define sampleRefraction(s,c) texture2D(s,c) +uniform sampler2D refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; +#endif +#endif +#endif +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) +#endif +`;rO.IncludesShadersStore.pbrFragmentSamplersDeclaration=pA;let pR=`bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`;rO.IncludesShadersStore.subSurfaceScatteringFunctions=pR;let pI=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { +float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;rO.IncludesShadersStore.importanceSampling=pI;let pP=`#define MINIMUMVARIANCE 0.0005 +float convertRoughnessToAverageSlope(float roughness) +{return square(roughness)+MINIMUMVARIANCE;} +float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} +vec2 getAARoughnessFactors(vec3 normalVector) { +#ifdef SPECULARAA +vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); +#else +return vec2(0.); +#endif +} +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_LEGACY +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} +#else +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} +#endif +#endif +#if defined(CLEARCOAT) || defined(SS_REFRACTION) +vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} +vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} +vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} +vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), +cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), +clearCoatIntensity);return clearCoatAbsorption;} +#endif +#ifdef MICROSURFACEAUTOMATIC +float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) +{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} +#endif +`;rO.IncludesShadersStore.pbrHelperFunctions=pP;let pM=`#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 ++ vSphericalL1_1*(normal.y) ++ vSphericalL10*(normal.z) ++ vSphericalL11*(normal.x) ++ vSphericalL2_2*(normal.y*normal.x) ++ vSphericalL2_1*(normal.y*normal.z) ++ vSphericalL20*((3.0*normal.z*normal.z)-1.0) ++ vSphericalL21*(normal.z*normal.x) ++ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} +#else +vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} +#endif +#endif +`;rO.IncludesShadersStore.harmonicsFunctions=pM;let pD=`struct preLightingInfo +{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; +#ifdef IRIDESCENCE +float iridescenceIntensity; +#endif +};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; +#ifdef SPECULARTERM +result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); +#endif +return result;}`;rO.IncludesShadersStore.pbrDirectLightingSetupFunctions=pD;let pO=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) +{return max(0.,1.0-length(lightOffset)/range);} +float computeDistanceLightFalloff_Physical(float lightDistanceSquared) +{return 1.0/maxEps(lightDistanceSquared);} +float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) +{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} +float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDistanceLightFalloff_Physical(lightDistanceSquared); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); +#else +return computeDistanceLightFalloff_Standard(lightOffset,range); +#endif +} +float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) +{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) +{falloff=max(0.,pow(cosAngle,exponent));} +return falloff;} +float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) +{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; +float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} +float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) +{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} +float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); +#else +return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); +#endif +}`;rO.IncludesShadersStore.pbrDirectLightingFalloffFunctions=pO;let pN=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} +#endif +#ifdef ENVIRONMENTBRDF +vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); +#ifdef ENVIRONMENTBRDF_RGBD +brdfLookup.rgb=fromRGBD(brdfLookup.rgba); +#endif +return brdfLookup.rgb;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; +#endif +return reflectance;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; +#endif +return reflectance;} +#endif +/* NOT USED +#if defined(SHEEN) && defined(SHEEN_SOFTER) +float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) +{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} +#endif +*/ +#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) +vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +/** +* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. +* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table +*/ +vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} +#endif +vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +#ifdef CLEARCOAT +vec3 getR0RemappedForClearCoat(vec3 f0) { +#ifdef CLEARCOAT_DEFAULTIOR +#ifdef MOBILE +return saturate(f0*(f0*0.526868+0.529324)-0.0482256); +#else +return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); +#endif +#else +vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); +#endif +} +#endif +#ifdef IRIDESCENCE +const mat3 XYZ_TO_REC709=mat3( +3.2404542,-0.9692660, 0.0556434, +-1.5371385, 1.8760108,-0.2040259, +-0.4985314, 0.0415560, 1.0572252 +);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} +vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} +float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} +vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} +vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} +float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0 +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +float radicalInverse_VdC(uint bits) +{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } +vec2 hammersley(uint i,uint N) +{return vec2(float(i)/float(N),radicalInverse_VdC(i));} +#else +float vanDerCorpus(int n,int base) +{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) +{if(n>0) +{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} +return result;} +vec2 hammersley(int i,int N) +{return vec2(float(i)/float(N),vanDerCorpus(i,2));} +#endif +float log4(float x) {return log2(x)/2.;} +const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; +#define inline +vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c;}} +result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} +#define inline +vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; +if (alphaG==0.) { +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c*NoL;}} +result=result/weight;return result;}} +#endif +#endif +`;rO.IncludesShadersStore.hdrFilteringFunctions=pF;let pw=`#define CLEARCOATREFLECTANCE90 1.0 +struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef CLEARCOAT +vec4 clearCoat; +#endif +#ifdef SHEEN +vec3 sheen; +#endif +};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { +#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) +float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; +#else +return roughness; +#endif +} +vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} +vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} +#ifdef SS_TRANSLUCENCY +vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} +#endif +#ifdef SPECULARTERM +vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); +#ifdef BRDF_V_HEIGHT_CORRELATED +float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); +#else +float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); +#endif +vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef ANISOTROPIC +vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef CLEARCOAT +vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( +clearCoatTerm*info.attenuation*NccdotL*lightColor, +1.0-fresnel +);} +vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} +#endif +#ifdef SHEEN +vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER +float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); +#else */ +float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ +float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} +#endif +`;rO.IncludesShadersStore.pbrDirectLightingFunctions=pw;let pL=`#if defined(REFLECTION) || defined(SS_REFRACTION) +float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} +float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} +#endif +#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) +float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} +#endif +#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) +float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} +#endif +#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) +#define UNPACK_LOD(x) (1.0-x)*255.0 +float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} +#endif +`;rO.IncludesShadersStore.pbrIBLFunctions=pL;let pB=`struct albedoOpacityOutParams +{vec3 surfaceAlbedo;float alpha;}; +#define pbr_inline +void albedoOpacityBlock( +in vec4 vAlbedoColor, +#ifdef ALBEDO +in vec4 albedoTexture, +in vec2 albedoInfos, +#endif +#ifdef OPACITY +in vec4 opacityMap, +in vec2 vOpacityInfos, +#endif +#ifdef DETAIL +in vec4 detailColor, +in vec4 vDetailInfos, +#endif +#ifdef DECAL +in vec4 decalColor, +in vec4 vDecalInfos, +#endif +out albedoOpacityOutParams outParams +) +{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; +#ifdef ALBEDO +#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) +alpha*=albedoTexture.a; +#endif +#ifdef GAMMAALBEDO +surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); +#else +surfaceAlbedo*=albedoTexture.rgb; +#endif +surfaceAlbedo*=albedoInfos.y; +#endif +#ifndef DECAL_AFTER_DETAIL +#include +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +surfaceAlbedo*=vColor.rgb; +#endif +#ifdef DETAIL +float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; +#endif +#ifdef DECAL_AFTER_DETAIL +#include +#endif +#define CUSTOM_FRAGMENT_UPDATE_ALBEDO +#ifdef OPACITY +#ifdef OPACITYRGB +alpha=getLuminance(opacityMap.rgb); +#else +alpha*=opacityMap.a; +#endif +alpha*=vOpacityInfos.y; +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) +#ifdef ALPHATEST +#if DEBUGMODE != 88 +if (alpha0 +#ifdef METALLICWORKFLOW +vec2 metallicRoughness; +#ifdef REFLECTIVITY +vec4 surfaceMetallicColorMap; +#endif +#ifndef FROSTBITE_REFLECTANCE +vec3 metallicF0; +#endif +#else +#ifdef REFLECTIVITY +vec4 surfaceReflectivityColorMap; +#endif +#endif +#endif +}; +#define pbr_inline +void reflectivityBlock( +in vec4 vReflectivityColor, +#ifdef METALLICWORKFLOW +in vec3 surfaceAlbedo, +in vec4 metallicReflectanceFactors, +#endif +#ifdef REFLECTIVITY +in vec3 reflectivityInfos, +in vec4 surfaceMetallicOrReflectivityColorMap, +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +in vec3 ambientOcclusionColorIn, +#endif +#ifdef MICROSURFACEMAP +in vec4 microSurfaceTexel, +#endif +#ifdef DETAIL +in vec4 detailColor, +in vec4 vDetailInfos, +#endif +out reflectivityOutParams outParams +) +{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec2 metallicRoughness=surfaceReflectivityColor.rg; +#ifdef REFLECTIVITY +#if DEBUGMODE>0 +outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef AOSTOREINMETALMAPRED +vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); +#endif +#ifdef METALLNESSSTOREINMETALMAPBLUE +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; +#else +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; +#endif +#ifdef ROUGHNESSSTOREINMETALMAPALPHA +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; +#else +#ifdef ROUGHNESSSTOREINMETALMAPGREEN +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; +#endif +#endif +#endif +#ifdef DETAIL +float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); +#endif +#ifdef MICROSURFACEMAP +metallicRoughness.g*=microSurfaceTexel.r; +#endif +#if DEBUGMODE>0 +outParams.metallicRoughness=metallicRoughness; +#endif +#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS +microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; +#ifdef FROSTBITE_REFLECTANCE +outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); +#else +vec3 metallicF0=metallicReflectanceFactors.rgb; +#if DEBUGMODE>0 +outParams.metallicF0=metallicF0; +#endif +outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); +#endif +#else +#ifdef REFLECTIVITY +surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; +#if DEBUGMODE>0 +outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef MICROSURFACEFROMREFLECTIVITYMAP +microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; +#else +#ifdef MICROSURFACEAUTOMATIC +microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); +#endif +#ifdef MICROSURFACEMAP +microSurface*=microSurfaceTexel.r; +#endif +#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE +#endif +#endif +#endif +microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} +`;rO.IncludesShadersStore.pbrBlockReflectivity=pU;let pV=`struct ambientOcclusionOutParams +{vec3 ambientOcclusionColor; +#if DEBUGMODE>0 && defined(AMBIENT) +vec3 ambientOcclusionColorMap; +#endif +}; +#define pbr_inline +void ambientOcclusionBlock( +#ifdef AMBIENT +in vec3 ambientOcclusionColorMap_, +in vec4 vAmbientInfos, +#endif +out ambientOcclusionOutParams outParams +) +{vec3 ambientOcclusionColor=vec3(1.,1.,1.); +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; +#ifdef AMBIENTINGRAYSCALE +ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); +#endif +ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); +#if DEBUGMODE>0 +outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; +#endif +#endif +outParams.ambientOcclusionColor=ambientOcclusionColor;} +`;rO.IncludesShadersStore.pbrBlockAmbientOcclusion=pV;let pk=`#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +struct alphaFresnelOutParams +{float alpha;}; +#define pbr_inline +void alphaFresnelBlock( +in vec3 normalW, +in vec3 viewDirectionW, +in float alpha, +in float microSurface, +out alphaFresnelOutParams outParams +) +{float opacityPerceptual=alpha; +#ifdef LINEARALPHAFRESNEL +float opacity0=opacityPerceptual; +#else +float opacity0=opacityPerceptual*opacityPerceptual; +#endif +float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; +#ifdef ALPHATEST +if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) +vec3 anisotropyMapData; +#endif +}; +#define pbr_inline +void anisotropicBlock( +in vec3 vAnisotropy, +in float roughness, +#ifdef ANISOTROPIC_TEXTURE +in vec3 anisotropyMapData, +#endif +in mat3 TBN, +in vec3 normalW, +in vec3 viewDirectionW, +out anisotropicOutParams outParams +) +{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); +#ifdef ANISOTROPIC_TEXTURE +anisotropy*=anisotropyMapData.b; +#if DEBUGMODE>0 +outParams.anisotropyMapData=anisotropyMapData; +#endif +anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; +#ifdef ANISOTROPIC_LEGACY +anisotropyDirection.rg*=anisotropyMapData.rg; +#else +anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); +#endif +#endif +mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} +#endif +`;rO.IncludesShadersStore.pbrBlockAnisotropic=pG;let pz=`#ifdef REFLECTION +struct reflectionOutParams +{vec4 environmentRadiance;vec3 environmentIrradiance; +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords; +#else +vec2 reflectionCoords; +#endif +#ifdef SS_TRANSLUCENCY +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +vec3 irradianceVector; +#endif +#endif +#endif +}; +#define pbr_inline +void createReflectionCoords( +in vec3 vPositionW, +in vec3 normalW, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REFLECTIONMAP_3D +out vec3 reflectionCoords +#else +out vec2 reflectionCoords +#endif +) +{ +#ifdef ANISOTROPIC +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +reflectionCoords=reflectionVector; +#else +reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +} +#define pbr_inline +#define inline +void sampleReflectionTexture( +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +const vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +const vec2 reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out vec4 environmentRadiance +) +{ +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); +#elif defined(LINEARSPECULARREFLECTION) +float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); +#else +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); +#endif +#ifdef LODBASEDMICROSFURACE +reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; +#ifdef LODINREFLECTIONALPHA +float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); +#else +float requestedReflectionLOD=reflectionLOD; +#endif +#ifdef REALTIME_FILTERING +environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); +#else +environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#endif +#else +float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +environmentMid, +lodReflectionNormalizedDoubled +);} else {environmentRadiance=mix( +environmentMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#ifdef RGBDREFLECTION +environmentRadiance.rgb=fromRGBD(environmentRadiance); +#endif +#ifdef GAMMAREFLECTION +environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); +#endif +environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} +#define pbr_inline +#define inline +void reflectionBlock( +in vec3 vPositionW, +in vec3 normalW, +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +#else +in sampler2D reflectionSampler, +#endif +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +in vec3 vEnvironmentIrradiance, +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +in mat4 reflectionMatrix, +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +in samplerCube irradianceSampler, +#else +in sampler2D irradianceSampler, +#endif +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out reflectionOutParams outParams +) +{vec4 environmentRadiance=vec4(0.,0.,0.,0.); +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=vec3(0.); +#else +vec2 reflectionCoords=vec2(0.); +#endif +createReflectionCoords( +vPositionW, +normalW, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +reflectionCoords +);sampleReflectionTexture( +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +#ifdef REFLECTIONMAP_3D +reflectionSampler, +reflectionCoords, +#else +reflectionSampler, +reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentRadiance +);vec3 environmentIrradiance=vec3(0.,0.,0.); +#ifdef USESPHERICALFROMREFLECTIONMAP +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +environmentIrradiance=vEnvironmentIrradiance; +#else +#ifdef ANISOTROPIC +vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; +#else +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#if defined(REALTIME_FILTERING) +environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); +#else +environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); +#endif +#ifdef SS_TRANSLUCENCY +outParams.irradianceVector=irradianceVector; +#endif +#endif +#elif defined(USEIRRADIANCEMAP) +vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; +#ifdef RGBDREFLECTION +environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); +#endif +#ifdef GAMMAREFLECTION +environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); +#endif +#endif +environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} +#endif +`;rO.IncludesShadersStore.pbrBlockReflection=pz;let pW=`#ifdef SHEEN +struct sheenOutParams +{float sheenIntensity;vec3 sheenColor;float sheenRoughness; +#ifdef SHEEN_LINKWITHALBEDO +vec3 surfaceAlbedo; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +float sheenAlbedoScaling; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 finalSheenRadianceScaled; +#endif +#if DEBUGMODE>0 +#ifdef SHEEN_TEXTURE +vec4 sheenMapData; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 sheenEnvironmentReflectance; +#endif +#endif +}; +#define pbr_inline +#define inline +void sheenBlock( +in vec4 vSheenColor, +#ifdef SHEEN_ROUGHNESS +in float vSheenRoughness, +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +in vec4 sheenMapRoughnessData, +#endif +#endif +in float roughness, +#ifdef SHEEN_TEXTURE +in vec4 sheenMapData, +in float sheenMapLevel, +#endif +in float reflectance, +#ifdef SHEEN_LINKWITHALBEDO +in vec3 baseColor, +in vec3 surfaceAlbedo, +#endif +#ifdef ENVIRONMENTBRDF +in float NdotV, +in vec3 environmentBrdf, +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +in vec2 AARoughnessFactors, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +in vec4 vLightingIntensity, +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +in vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +in vec2 reflectionCoords, +#endif +in float NdotVUnclamped, +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +in float seo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +in float eho, +#endif +#endif +out sheenOutParams outParams +) +{float sheenIntensity=vSheenColor.a; +#ifdef SHEEN_TEXTURE +#if DEBUGMODE>0 +outParams.sheenMapData=sheenMapData; +#endif +#endif +#ifdef SHEEN_LINKWITHALBEDO +float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#else +vec3 sheenColor=vSheenColor.rgb; +#ifdef SHEEN_TEXTURE +#ifdef SHEEN_GAMMATEXTURE +sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); +#else +sheenColor.rgb*=sheenMapData.rgb; +#endif +sheenColor.rgb*=sheenMapLevel; +#endif +#ifdef SHEEN_ROUGHNESS +float sheenRoughness=vSheenRoughness; +#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE +#if defined(SHEEN_TEXTURE) +sheenRoughness*=sheenMapData.a; +#endif +#elif defined(SHEEN_TEXTURE_ROUGHNESS) +#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL +sheenRoughness*=sheenMapData.a; +#else +sheenRoughness*=sheenMapRoughnessData.a; +#endif +#endif +#else +float sheenRoughness=roughness; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#endif +#if !defined(SHEEN_ALBEDOSCALING) +sheenIntensity*=(1.-reflectance); +#endif +sheenColor*=sheenIntensity; +#endif +#ifdef ENVIRONMENTBRDF +/*#ifdef SHEEN_SOFTER +vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); +#else*/ +#ifdef SHEEN_ROUGHNESS +vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); +#else +vec3 environmentSheenBrdf=environmentBrdf; +#endif +/*#endif*/ +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); +#ifdef SPECULARAA +sheenAlphaG+=AARoughnessFactors.y; +#endif +vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( +sheenAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +sheenRoughness, +#endif +reflectionSampler, +reflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentSheenRadiance +);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +sheenEnvironmentReflectance*=seo; +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +sheenEnvironmentReflectance*=eho; +#endif +#if DEBUGMODE>0 +outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; +#endif +outParams.finalSheenRadianceScaled= +environmentSheenRadiance.rgb * +sheenEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; +#endif +outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} +#endif +`;rO.IncludesShadersStore.pbrBlockSheen=pW;let pH=`struct clearcoatOutParams +{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; +#ifdef REFLECTION +vec3 finalClearCoatRadianceScaled; +#endif +#ifdef CLEARCOAT_TINT +vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; +#endif +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +vec3 energyConservationFactorClearCoat; +#endif +#if DEBUGMODE>0 +#ifdef CLEARCOAT_BUMP +mat3 TBNClearCoat; +#endif +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData; +#endif +#ifdef REFLECTION +vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; +#endif +float clearCoatNdotV; +#endif +}; +#ifdef CLEARCOAT +#define pbr_inline +#define inline +void clearcoatBlock( +in vec3 vPositionW, +in vec3 geometricNormalW, +in vec3 viewDirectionW, +in vec2 vClearCoatParams, +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +in vec4 clearCoatMapRoughnessData, +#endif +in vec3 specularEnvironmentR0, +#ifdef CLEARCOAT_TEXTURE +in vec2 clearCoatMapData, +#endif +#ifdef CLEARCOAT_TINT +in vec4 vClearCoatTintParams, +in float clearCoatColorAtDistance, +in vec4 vClearCoatRefractionParams, +#ifdef CLEARCOAT_TINT_TEXTURE +in vec4 clearCoatTintMapData, +#endif +#endif +#ifdef CLEARCOAT_BUMP +in vec2 vClearCoatBumpInfos, +in vec4 clearCoatBumpMapData, +in vec2 vClearCoatBumpUV, +#if defined(TANGENT) && defined(NORMAL) +in mat3 vTBN, +#else +in vec2 vClearCoatTangentSpaceParams, +#endif +#ifdef OBJECTSPACE_NORMALMAP +in mat4 normalMatrix, +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +in vec3 faceNormal, +#endif +#ifdef REFLECTION +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +in vec4 vLightingIntensity, +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +#else +in sampler2D reflectionSampler, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +in float ambientMonochrome, +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +in float frontFacingMultiplier, +#endif +out clearcoatOutParams outParams +) +{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE +clearCoatRoughness*=clearCoatMapData.y; +#endif +#if DEBUGMODE>0 +outParams.clearCoatMapData=clearCoatMapData; +#endif +#endif +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL +clearCoatRoughness*=clearCoatMapData.y; +#else +clearCoatRoughness*=clearCoatMapRoughnessData.y; +#endif +#endif +outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; +#ifdef CLEARCOAT_TINT +vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; +#ifdef CLEARCOAT_TINT_TEXTURE +#ifdef CLEARCOAT_TINT_GAMMATEXTURE +clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); +#else +clearCoatColor*=clearCoatTintMapData.rgb; +#endif +clearCoatThickness*=clearCoatTintMapData.a; +#if DEBUGMODE>0 +outParams.clearCoatTintMapData=clearCoatTintMapData; +#endif +#endif +outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; +#endif +#ifdef CLEARCOAT_REMAP_F0 +vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); +#else +vec3 specularEnvironmentR0Updated=specularEnvironmentR0; +#endif +outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; +#ifdef CLEARCOAT_BUMP +#ifdef NORMALXYSCALE +float clearCoatNormalScale=1.0; +#else +float clearCoatNormalScale=vClearCoatBumpInfos.y; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBNClearCoat=vTBN; +#else +vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); +#endif +#if DEBUGMODE>0 +outParams.TBNClearCoat=TBNClearCoat; +#endif +#ifdef OBJECTSPACE_NORMALMAP +clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); +#else +clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; +#endif +outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); +#if DEBUGMODE>0 +outParams.clearCoatNdotV=clearCoatNdotV; +#endif +#ifdef CLEARCOAT_TINT +vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); +#endif +#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) +vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); +#endif +#if defined(REFLECTION) +float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); +#ifdef SPECULARAA +clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; +#endif +vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +clearCoatReflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 clearCoatReflectionCoords=clearCoatReflectionVector; +#else +vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +clearCoatReflectionCoords/=clearCoatReflectionVector.z; +#endif +clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; +#endif +sampleReflectionTexture( +clearCoatAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +clearCoatNdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +clearCoatRoughness, +#endif +reflectionSampler, +clearCoatReflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentClearCoatRadiance +); +#if DEBUGMODE>0 +outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; +#endif +#endif +#endif +#else +vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); +#endif +clearCoatEnvironmentReflectance*=clearCoatIntensity; +#if DEBUGMODE>0 +outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; +#endif +outParams.finalClearCoatRadianceScaled= +environmentClearCoatRadiance.rgb * +clearCoatEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(CLEARCOAT_TINT) +outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); +#endif +float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); +#endif +} +#endif +`;rO.IncludesShadersStore.pbrBlockClearcoat=pH;let pX=`struct iridescenceOutParams +{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; +#ifdef IRIDESCENCE +#define pbr_inline +#define inline +void iridescenceBlock( +in vec4 vIridescenceParams, +in float viewAngle, +in vec3 specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +in vec2 iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +in vec2 iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +in float NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +in vec2 clearCoatMapData, +#endif +#endif +out iridescenceOutParams outParams +) +{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; +#ifdef IRIDESCENCE_TEXTURE +iridescenceIntensity*=iridescenceMapData.x; +#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE +iridescenceThicknessWeight=iridescenceMapData.g; +#endif +#endif +#if defined(IRIDESCENCE_THICKNESS_TEXTURE) +iridescenceThicknessWeight=iridescenceThicknessMapData.g; +#endif +float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; +#ifdef CLEARCOAT +float clearCoatIntensity=vClearCoatParams.x; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#endif +topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); +#endif +vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} +#endif +`;rO.IncludesShadersStore.pbrBlockIridescence=pX;let pY=`struct subSurfaceOutParams +{vec3 specularEnvironmentReflectance; +#ifdef SS_REFRACTION +vec3 finalRefraction;vec3 surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +float alpha; +#endif +#ifdef REFLECTION +float refractionFactorForIrradiance; +#endif +#endif +#ifdef SS_TRANSLUCENCY +vec3 transmittance;float translucencyIntensity; +#ifdef REFLECTION +vec3 refractionIrradiance; +#endif +#endif +#if DEBUGMODE>0 +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction;vec3 refractionTransmittance; +#endif +#endif +}; +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#define pbr_inline +#define inline +vec4 sampleEnvironmentRefraction( +in float ior +,in float thickness +,in float refractionLOD +,in vec3 normalW +,in vec3 vPositionW +,in vec3 viewDirectionW +,in mat4 view +,in vec4 vRefractionInfos +,in mat4 refractionMatrix +,in vec4 vRefractionMicrosurfaceInfos +,in float alphaG +#ifdef SS_REFRACTIONMAP_3D +,in samplerCube refractionSampler +#ifndef LODBASEDMICROSFURACE +,in samplerCube refractionSamplerLow +,in samplerCube refractionSamplerHigh +#endif +#else +,in sampler2D refractionSampler +#ifndef LODBASEDMICROSFURACE +,in sampler2D refractionSamplerLow +,in sampler2D refractionSamplerHigh +#endif +#endif +#ifdef ANISOTROPIC +,in anisotropicOutParams anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,in vec2 vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,in vec3 refractionPosition +,in vec3 refractionSize +#endif +) {vec4 environmentRefraction=vec4(0.,0.,0.,0.); +#ifdef ANISOTROPIC +vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior); +#else +vec3 refractionVector=refract(-viewDirectionW,normalW,ior); +#endif +#ifdef SS_REFRACTIONMAP_OPPOSITEZ +refractionVector.z*=-1.0; +#endif +#ifdef SS_REFRACTIONMAP_3D +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); +#else +#ifdef SS_USE_THICKNESS_AS_DEPTH +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); +#endif +vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; +#endif +#ifdef LODBASEDMICROSFURACE +refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; +#ifdef SS_LODINREFRACTIONALPHA +float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); +#else +float requestedRefractionLOD=refractionLOD; +#endif +#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) +environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); +#else +environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); +#endif +#else +float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( +sampleRefraction(refractionSamplerHigh,refractionCoords), +environmentRefractionMid, +lodRefractionNormalizedDoubled +);} else {environmentRefraction=mix( +environmentRefractionMid, +sampleRefraction(refractionSamplerLow,refractionCoords), +lodRefractionNormalizedDoubled-1.0 +);} +#endif +#ifdef SS_RGBDREFRACTION +environmentRefraction.rgb=fromRGBD(environmentRefraction); +#endif +#ifdef SS_GAMMAREFRACTION +environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); +#endif +return environmentRefraction;} +#endif +#define pbr_inline +#define inline +void subSurfaceBlock( +in vec3 vSubSurfaceIntensity, +in vec2 vThicknessParam, +in vec4 vTintColor, +in vec3 normalW, +in vec3 specularEnvironmentReflectance, +#ifdef SS_THICKNESSANDMASK_TEXTURE +in vec4 thicknessMap, +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +in vec4 refractionIntensityMap, +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +in vec4 translucencyIntensityMap, +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +in mat4 reflectionMatrix, +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +in vec3 irradianceVector_, +#endif +#if defined(REALTIME_FILTERING) +in samplerCube reflectionSampler, +in vec2 vReflectionFilteringInfo, +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +in samplerCube irradianceSampler, +#else +in sampler2D irradianceSampler, +#endif +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +in vec3 surfaceAlbedo, +#endif +#ifdef SS_REFRACTION +in vec3 vPositionW, +in vec3 viewDirectionW, +in mat4 view, +in vec4 vRefractionInfos, +in mat4 refractionMatrix, +in vec4 vRefractionMicrosurfaceInfos, +in vec4 vLightingIntensity, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +in float alpha, +#endif +#ifdef SS_LODINREFRACTIONALPHA +in float NdotVUnclamped, +#endif +#ifdef SS_LINEARSPECULARREFRACTION +in float roughness, +#endif +in float alphaG, +#ifdef SS_REFRACTIONMAP_3D +in samplerCube refractionSampler, +#ifndef LODBASEDMICROSFURACE +in samplerCube refractionSamplerLow, +in samplerCube refractionSamplerHigh, +#endif +#else +in sampler2D refractionSampler, +#ifndef LODBASEDMICROSFURACE +in sampler2D refractionSamplerLow, +in sampler2D refractionSamplerHigh, +#endif +#endif +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REALTIME_FILTERING +in vec2 vRefractionFilteringInfo, +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +in vec3 refractionPosition, +in vec3 refractionSize, +#endif +#ifdef SS_DISPERSION +in float dispersion, +#endif +#endif +#ifdef SS_TRANSLUCENCY +in vec3 vDiffusionDistance, +#endif +out subSurfaceOutParams outParams +) +{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; +#ifdef SS_REFRACTION +float refractionIntensity=vSubSurfaceIntensity.x; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; +#endif +#endif +#ifdef SS_TRANSLUCENCY +float translucencyIntensity=vSubSurfaceIntensity.y; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +#if defined(SS_USE_GLTF_TEXTURES) +float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; +#else +float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; +#endif +#if DEBUGMODE>0 +outParams.thicknessMap=thicknessMap; +#endif +#ifdef SS_MASK_FROM_THICKNESS_TEXTURE +#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) +#if defined(SS_USE_GLTF_TEXTURES) +refractionIntensity*=thicknessMap.r; +#else +refractionIntensity*=thicknessMap.g; +#endif +#endif +#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) +translucencyIntensity*=thicknessMap.b; +#endif +#endif +#else +float thickness=vThicknessParam.y; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +#ifdef SS_USE_GLTF_TEXTURES +refractionIntensity*=refractionIntensityMap.r; +#else +refractionIntensity*=refractionIntensityMap.g; +#endif +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +translucencyIntensity*=translucencyIntensityMap.b; +#endif +#ifdef SS_TRANSLUCENCY +thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction=vec4(0.,0.,0.,0.); +#ifdef SS_HAS_THICKNESS +float ior=vRefractionInfos.y; +#else +float ior=vRefractionMicrosurfaceInfos.w; +#endif +#ifdef SS_LODINREFRACTIONALPHA +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); +#elif defined(SS_LINEARSPECULARREFRACTION) +float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); +#else +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); +#endif +float refraction_ior=vRefractionInfos.y; +#ifdef SS_DISPERSION +float realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i]; +#endif +vec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG +#ifdef SS_REFRACTIONMAP_3D +,refractionSampler +#ifndef LODBASEDMICROSFURACE +,refractionSamplerLow +,refractionSamplerHigh +#endif +#else +,refractionSampler +#ifndef LODBASEDMICROSFURACE +,refractionSamplerLow +,refractionSamplerHigh +#endif +#endif +#ifdef ANISOTROPIC +,anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,refractionPosition +,refractionSize +#endif +); +#ifdef SS_DISPERSION +environmentRefraction[i]=envSample[i];} +#else +environmentRefraction=envSample; +#endif +environmentRefraction.rgb*=vRefractionInfos.x; +#endif +#ifdef SS_REFRACTION +vec3 refractionTransmittance=vec3(refractionIntensity); +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); +#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) +float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; +#else +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); +#endif +#ifdef SS_ALBEDOFORREFRACTIONTINT +environmentRefraction.rgb*=surfaceAlbedo.rgb; +#endif +outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); +#ifdef REFLECTION +outParams.refractionFactorForIrradiance=(1.-refractionIntensity); +#endif +#ifdef UNUSED_MULTIPLEBOUNCES +vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); +#endif +refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; +#if DEBUGMODE>0 +outParams.refractionTransmittance=refractionTransmittance; +#endif +outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; +#if DEBUGMODE>0 +outParams.environmentRefraction=environmentRefraction; +#endif +#endif +#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#else +vec3 irradianceVector=irradianceVector_; +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) +#if defined(REALTIME_FILTERING) +vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); +#else +vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); +#endif +#elif defined(USEIRRADIANCEMAP) +#ifdef REFLECTIONMAP_3D +vec3 irradianceCoords=irradianceVector; +#else +vec2 irradianceCoords=irradianceVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +irradianceCoords/=irradianceVector.z; +#endif +irradianceCoords.y=1.0-irradianceCoords.y; +#endif +vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); +#ifdef RGBDREFLECTION +refractionIrradiance.rgb=fromRGBD(refractionIrradiance); +#endif +#ifdef GAMMAREFLECTION +refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); +#endif +#else +vec4 refractionIrradiance=vec4(0.); +#endif +refractionIrradiance.rgb*=transmittance; +#ifdef SS_ALBEDOFORTRANSLUCENCYTINT +refractionIrradiance.rgb*=surfaceAlbedo.rgb; +#endif +outParams.refractionIrradiance=refractionIrradiance.rgb; +#endif +} +#endif +`;rO.IncludesShadersStore.pbrBlockSubSurface=pY;let pj=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#endif +vec3 geometricNormalW=normalW; +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; +#endif +`;rO.IncludesShadersStore.pbrBlockNormalGeometric=pj;let pK=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#if defined(TWOSIDEDLIGHTING) +faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; +#endif +normalW*=sign(dot(normalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +`;rO.IncludesShadersStore.pbrBlockNormalFinal=pK;let p$=`#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +#ifdef GAMMALIGHTMAP +lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +`;rO.IncludesShadersStore.pbrBlockLightmapInit=p$;let pq=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); +#ifdef SPECULARAA +alphaG+=AARoughnessFactors.y; +#endif +#if defined(ENVIRONMENTBRDF) +vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +#ifdef AMBIENTINGRAYSCALE +float ambientMonochrome=aoOut.ambientOcclusionColor.r; +#else +float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); +#endif +float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); +#endif +#endif +#endif +#endif +`;rO.IncludesShadersStore.pbrBlockGeometryInfo=pq;let pQ=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); +#else +vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); +#endif +#ifdef ALPHAFRESNEL +float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; +#endif +`;rO.IncludesShadersStore.pbrBlockReflectance0=pQ;let pZ=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); +#ifdef RADIANCEOCCLUSION +specularEnvironmentReflectance*=seo; +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +specularEnvironmentReflectance*=eho; +#endif +#endif +#endif +#else +vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); +#endif +#ifdef CLEARCOAT +specularEnvironmentReflectance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +specularEnvironmentReflectance*=clearcoatOut.absorption; +#endif +#endif +`;rO.IncludesShadersStore.pbrBlockReflectance=pZ;let pJ=`vec3 diffuseBase=vec3(0.,0.,0.); +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#ifdef CLEARCOAT +vec3 clearCoatBase=vec3(0.,0.,0.); +#endif +#ifdef SHEEN +vec3 sheenBase=vec3(0.,0.,0.); +#endif +preLightingInfo preInfo;lightingInfo info;float shadow=1.; +float aggShadow=0.;float numLights=0.; +#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +vec3 absorption=vec3(0.); +#endif +`;rO.IncludesShadersStore.pbrBlockDirectLighting=pJ;let p0=`aggShadow=aggShadow/numLights; +#if defined(ENVIRONMENTBRDF) +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); +#endif +#endif +#ifndef METALLICWORKFLOW +#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION +surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; +#endif +#endif +#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) +surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; +#endif +#ifdef REFLECTION +vec3 finalIrradiance=reflectionOut.environmentIrradiance; +#if defined(CLEARCOAT) +finalIrradiance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +finalIrradiance*=clearcoatOut.absorption; +#endif +#endif +#if defined(SS_REFRACTION) +finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; +#endif +#if defined(SS_TRANSLUCENCY) +finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; +#endif +finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalSpecularScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalSpecularScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef REFLECTION +vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalRadianceScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalRadianceScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef SHEEN +vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; +#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef CLEARCOAT +vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; +#ifdef CLEARCOAT_TINT +subSurfaceOut.finalRefraction*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef ALPHABLEND +float luminanceOverAlpha=0.0; +#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) +luminanceOverAlpha+=getLuminance(finalRadianceScaled); +#if defined(CLEARCOAT) +luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); +#endif +#endif +#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) +luminanceOverAlpha+=getLuminance(finalSpecularScaled); +#endif +#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) +luminanceOverAlpha+=getLuminance(finalClearCoatScaled); +#endif +#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) +alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); +#endif +#endif +`;rO.IncludesShadersStore.pbrBlockFinalLitComponents=p0;let p1=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; +#ifdef EMISSIVE +vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; +#ifdef GAMMAEMISSIVE +finalEmissive*=toLinearSpace(emissiveColorTex.rgb); +#else +finalEmissive*=emissiveColorTex.rgb; +#endif +finalEmissive*= vEmissiveInfos.y; +#endif +finalEmissive*=vLightingIntensity.y; +#ifdef AMBIENT +vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); +#else +vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; +#endif +finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; +`;rO.IncludesShadersStore.pbrBlockFinalUnlitComponents=p1;let p2=`vec4 finalColor=vec4( +#ifndef UNLIT +#ifdef REFLECTION +finalIrradiance + +#endif +#ifdef SPECULARTERM +finalSpecularScaled + +#endif +#ifdef SHEEN +finalSheenScaled + +#endif +#ifdef CLEARCOAT +finalClearCoatScaled + +#endif +#ifdef REFLECTION +finalRadianceScaled + +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled + +#endif +#ifdef CLEARCOAT +clearcoatOut.finalClearCoatRadianceScaled + +#endif +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction + +#endif +#endif +finalAmbient + +finalDiffuse, +alpha); +#ifdef LIGHTMAP +#ifndef LIGHTMAPEXCLUDED +#ifdef USELIGHTMAPASSHADOWMAP +finalColor.rgb*=lightmapColor.rgb; +#else +finalColor.rgb+=lightmapColor.rgb; +#endif +#endif +#endif +finalColor.rgb+=finalEmissive; +#define CUSTOM_FRAGMENT_BEFORE_FOG +finalColor=max(finalColor,0.0); +`;rO.IncludesShadersStore.pbrBlockFinalColorComposition=p2;let p3=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +#if !defined(SKIPFINALCOLORCLAMP) +finalColor.rgb=clamp(finalColor.rgb,0.,30.0); +#endif +#else +finalColor=applyImageProcessing(finalColor); +#endif +finalColor.a*=visibility; +#ifdef PREMULTIPLYALPHA +finalColor.rgb*=finalColor.a; +#endif +`;rO.IncludesShadersStore.pbrBlockImageProcessing=p3;let p4=`#if DEBUGMODE>0 +if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { +#if DEBUGMODE==1 +gl_FragColor.rgb=vPositionW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==2 && defined(NORMAL) +gl_FragColor.rgb=vNormalW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==5 +gl_FragColor.rgb=normalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==6 && defined(MAINUV1) +gl_FragColor.rgb=vec3(vMainUV1,0.0); +#elif DEBUGMODE==7 && defined(MAINUV2) +gl_FragColor.rgb=vec3(vMainUV2,0.0); +#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==10 && defined(CLEARCOAT) +gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==11 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicNormal; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==12 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicTangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==13 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==20 && defined(ALBEDO) +gl_FragColor.rgb=albedoTexture.rgb; +#ifndef GAMMAALBEDO +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==21 && defined(AMBIENT) +gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; +#elif DEBUGMODE==22 && defined(OPACITY) +gl_FragColor.rgb=opacityMap.rgb; +#elif DEBUGMODE==23 && defined(EMISSIVE) +gl_FragColor.rgb=emissiveColorTex.rgb; +#ifndef GAMMAEMISSIVE +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==24 && defined(LIGHTMAP) +gl_FragColor.rgb=lightmapColor.rgb; +#ifndef GAMMALIGHTMAP +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; +#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); +#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; +#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) +gl_FragColor.rgb=sheenOut.sheenMapData.rgb; +#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) +gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; +#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) +gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; +#elif DEBUGMODE==32 && defined(BUMP) +gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; +#elif DEBUGMODE==40 && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==41 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) +gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==50 +gl_FragColor.rgb=diffuseBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==51 && defined(SPECULARTERM) +gl_FragColor.rgb=specularBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==52 && defined(CLEARCOAT) +gl_FragColor.rgb=clearCoatBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==53 && defined(SHEEN) +gl_FragColor.rgb=sheenBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==54 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==60 +gl_FragColor.rgb=surfaceAlbedo.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==61 +gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); +#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.metallicF0; +#elif DEBUGMODE==63 +gl_FragColor.rgb=vec3(roughness); +#elif DEBUGMODE==64 +gl_FragColor.rgb=vec3(alphaG); +#elif DEBUGMODE==65 +gl_FragColor.rgb=vec3(NdotV); +#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==67 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); +#elif DEBUGMODE==68 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); +#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) +gl_FragColor.rgb=subSurfaceOut.transmittance; +#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; +#elif DEBUGMODE==72 +gl_FragColor.rgb=vec3(microSurface); +#elif DEBUGMODE==73 +gl_FragColor.rgb=vAlbedoColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=vReflectivityColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==75 +gl_FragColor.rgb=vEmissiveColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) +gl_FragColor.rgb=vec3(seo); +#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) +gl_FragColor.rgb=vec3(eho); +#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) +gl_FragColor.rgb=vec3(energyConservationFactor); +#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=specularEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) +gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==86 && defined(ALPHABLEND) +gl_FragColor.rgb=vec3(luminanceOverAlpha); +#elif DEBUGMODE==87 +gl_FragColor.rgb=vec3(alpha); +#elif DEBUGMODE==88 && defined(ALBEDO) +gl_FragColor.rgb=vec3(albedoTexture.a); +#else +float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); +#endif +gl_FragColor.rgb*=vDebugMode.y; +#ifdef DEBUGMODE_NORMALIZE +gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; +#endif +#ifdef DEBUGMODE_GAMMA +gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); +#endif +gl_FragColor.a=1.0; +#ifdef PREPASS +gl_FragData[0]=toLinearSpace(gl_FragColor); +gl_FragData[1]=vec4(0.,0.,0.,0.); +#endif +#ifdef DEBUGMODE_FORCERETURN +return; +#endif +} +#endif +`;rO.IncludesShadersStore.pbrDebug=p4;let p5=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#extension GL_OES_standard_derivatives : enable +#endif +#ifdef LODBASEDMICROSFURACE +#extension GL_EXT_shader_texture_lod : enable +#endif +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include[SCENE_MRT_COUNT] +precision highp float; +#include +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE +#endif +#include<__decl__pbrFragment> +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef REFLECTION +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#include +#include +#include +albedoOpacityOutParams albedoOpacityOut; +#ifdef ALBEDO +vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#endif +#ifdef DECAL +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#endif +albedoOpacityBlock( +vAlbedoColor, +#ifdef ALBEDO +albedoTexture, +vAlbedoInfos, +#endif +#ifdef OPACITY +opacityMap, +vOpacityInfos, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +#ifdef DECAL +decalColor, +vDecalInfos, +#endif +albedoOpacityOut +);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; +#define CUSTOM_FRAGMENT_UPDATE_ALPHA +#include +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +ambientOcclusionOutParams aoOut; +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; +#endif +ambientOcclusionBlock( +#ifdef AMBIENT +ambientOcclusionColorMap, +vAmbientInfos, +#endif +aoOut +); +#include +#ifdef UNLIT +vec3 diffuseBase=vec3(1.,1.,1.); +#else +vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; +#if defined(REFLECTIVITY) +vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; +#ifndef METALLICWORKFLOW +#ifdef REFLECTIVITY_GAMMA +surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); +#endif +surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; +#endif +#endif +#if defined(MICROSURFACEMAP) +vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; +#endif +#ifdef METALLICWORKFLOW +vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; +#ifdef REFLECTANCE +vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); +#ifdef REFLECTANCE_GAMMA +reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); +#endif +metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; +#endif +#ifdef METALLIC_REFLECTANCE +vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); +#ifdef METALLIC_REFLECTANCE_GAMMA +metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); +#endif +#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY +metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; +#endif +metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; +#endif +#endif +reflectivityBlock( +vReflectivityColor, +#ifdef METALLICWORKFLOW +surfaceAlbedo, +metallicReflectanceFactors, +#endif +#ifdef REFLECTIVITY +vReflectivityInfos, +surfaceMetallicOrReflectivityColorMap, +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor, +#endif +#ifdef MICROSURFACEMAP +microSurfaceTexel, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +reflectivityOut +);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; +#ifdef METALLICWORKFLOW +surfaceAlbedo=reflectivityOut.surfaceAlbedo; +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; +#endif +#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( +normalW, +viewDirectionW, +alpha, +microSurface, +alphaFresnelOut +);alpha=alphaFresnelOut.alpha; +#endif +#endif +#include +#ifdef ANISOTROPIC +anisotropicOutParams anisotropicOut; +#ifdef ANISOTROPIC_TEXTURE +vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; +#endif +anisotropicBlock( +vAnisotropy, +roughness, +#ifdef ANISOTROPIC_TEXTURE +anisotropyMapData, +#endif +TBN, +normalW, +viewDirectionW, +anisotropicOut +); +#endif +#ifdef REFLECTION +reflectionOutParams reflectionOut; +#ifndef USE_CUSTOM_REFLECTION +reflectionBlock( +vPositionW, +normalW, +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +reflectionSampler, +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +vEnvironmentIrradiance, +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +reflectionMatrix, +#endif +#endif +#ifdef USEIRRADIANCEMAP +irradianceSampler, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +reflectionOut +); +#else +#define CUSTOM_REFLECTION +#endif +#endif +#include +#ifdef SHEEN +sheenOutParams sheenOut; +#ifdef SHEEN_TEXTURE +vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); +#endif +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; +#endif +sheenBlock( +vSheenColor, +#ifdef SHEEN_ROUGHNESS +vSheenRoughness, +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +sheenMapRoughnessData, +#endif +#endif +roughness, +#ifdef SHEEN_TEXTURE +sheenMapData, +vSheenInfos.y, +#endif +reflectance, +#ifdef SHEEN_LINKWITHALBEDO +baseColor, +surfaceAlbedo, +#endif +#ifdef ENVIRONMENTBRDF +NdotV, +environmentBrdf, +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +AARoughnessFactors, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +vLightingIntensity, +reflectionSampler, +reflectionOut.reflectionCoords, +NdotVUnclamped, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +seo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +eho, +#endif +#endif +sheenOut +); +#ifdef SHEEN_LINKWITHALBEDO +surfaceAlbedo=sheenOut.surfaceAlbedo; +#endif +#endif +#ifdef CLEARCOAT +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; +#endif +#endif +#ifdef IRIDESCENCE +iridescenceOutParams iridescenceOut; +#ifdef IRIDESCENCE_TEXTURE +vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; +#endif +iridescenceBlock( +vIridescenceParams, +NdotV, +specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#endif +iridescenceOut +);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; +#endif +clearcoatOutParams clearcoatOut; +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); +#endif +#ifdef CLEARCOAT_BUMP +vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); +#endif +clearcoatBlock( +vPositionW, +geometricNormalW, +viewDirectionW, +vClearCoatParams, +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +clearCoatMapRoughnessData, +#endif +specularEnvironmentR0, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#ifdef CLEARCOAT_TINT +vClearCoatTintParams, +clearCoatColorAtDistance, +vClearCoatRefractionParams, +#ifdef CLEARCOAT_TINT_TEXTURE +clearCoatTintMapData, +#endif +#endif +#ifdef CLEARCOAT_BUMP +vClearCoatBumpInfos, +clearCoatBumpMapData, +vClearCoatBumpUV, +#if defined(TANGENT) && defined(NORMAL) +vTBN, +#else +vClearCoatTangentSpaceParams, +#endif +#ifdef OBJECTSPACE_NORMALMAP +normalMatrix, +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +faceNormal, +#endif +#ifdef REFLECTION +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +vLightingIntensity, +reflectionSampler, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +ambientMonochrome, +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +(gl_FrontFacing ? 1. : -1.), +#endif +clearcoatOut +); +#else +clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; +#endif +#include +subSurfaceOutParams subSurfaceOut; +#ifdef SUBSURFACE +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); +#endif +subSurfaceBlock( +vSubSurfaceIntensity, +vThicknessParam, +vTintColor, +normalW, +specularEnvironmentReflectance, +#ifdef SS_THICKNESSANDMASK_TEXTURE +thicknessMap, +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +refractionIntensityMap, +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +translucencyIntensityMap, +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +reflectionMatrix, +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +reflectionOut.irradianceVector, +#endif +#if defined(REALTIME_FILTERING) +reflectionSampler, +vReflectionFilteringInfo, +#endif +#endif +#ifdef USEIRRADIANCEMAP +irradianceSampler, +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +surfaceAlbedo, +#endif +#ifdef SS_REFRACTION +vPositionW, +viewDirectionW, +view, +vRefractionInfos, +refractionMatrix, +vRefractionMicrosurfaceInfos, +vLightingIntensity, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha, +#endif +#ifdef SS_LODINREFRACTIONALPHA +NdotVUnclamped, +#endif +#ifdef SS_LINEARSPECULARREFRACTION +roughness, +#endif +alphaG, +refractionSampler, +#ifndef LODBASEDMICROSFURACE +refractionSamplerLow, +refractionSamplerHigh, +#endif +#ifdef ANISOTROPIC +anisotropicOut, +#endif +#ifdef REALTIME_FILTERING +vRefractionFilteringInfo, +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +vRefractionPosition, +vRefractionSize, +#endif +#ifdef SS_DISPERSION +dispersion, +#endif +#endif +#ifdef SS_TRANSLUCENCY +vDiffusionDistance, +#endif +subSurfaceOut +); +#ifdef SS_REFRACTION +surfaceAlbedo=subSurfaceOut.surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha=subSurfaceOut.alpha; +#endif +#endif +#else +subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; +#endif +#include +#include[0..maxSimultaneousLights] +#include +#endif +#include +#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION +#include +#include +#include(color,finalColor) +#include +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +vec3 sqAlbedo=sqrt(surfaceAlbedo); +#endif +#ifdef PREPASS_IRRADIANCE +vec3 irradiance=finalDiffuse; +#ifndef UNLIT +#ifdef REFLECTION +irradiance+=finalIrradiance; +#endif +#endif +#ifdef SS_SCATTERING +gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); +irradiance/=sqAlbedo; +#else +gl_FragData[0]=finalColor; +float scatteringDiffusionProfile=255.; +#endif +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); +#else +gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#ifndef UNLIT +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=finalColor; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} +#endif +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;rO.ShadersStore.pbrPixelShader=p5;let p6=`uniform mat4 view;uniform mat4 viewProjection; +#ifdef ALBEDO +uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; +#endif +#ifdef METALLIC_REFLECTANCE +uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; +#endif +#ifdef REFLECTANCE +uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; +#endif +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#ifdef IRIDESCENCE +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +#endif +#ifdef NORMAL +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include +#define ADDITIONAL_VERTEX_DECLARATION +`;rO.IncludesShadersStore.pbrVertexDeclaration=p6;let p8=`precision highp float; +#include<__decl__pbrVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include[2..7] +#include[1..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#include +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) +#endif +varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#include +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); +#include +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#if DEBUGMODE>0 +vClipSpacePosition=gl_Position; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include[2..7] +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) +#endif +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.pbrVertexShader=p8;class p7 extends sh{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_TEXTURE_ROUGHNESS_IDENTICAL=!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 p9 extends hA{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new p7,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=p9._DefaultIndexOfRefraction,this.indexOfRefraction=p9._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=io.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!lE.ClearCoatTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!lE.ClearCoatTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())&&(!i.getCaps().standardDerivatives||!this._bumpTexture||!lE.ClearCoatBumpTextureEnabled||!!r||!!this._bumpTexture.isReady())&&(!this._isTintEnabled||!this._tintTexture||!lE.ClearCoatTintTextureEnabled||!!this._tintTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lE.ClearCoatTextureEnabled?nw.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&lE.ClearCoatTextureEnabled?nw.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&lE.ClearCoatBumpTextureEnabled?nw.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===p9._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&lE.ClearCoatTintTextureEnabled?(nw.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!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,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=this._material._disableBumpMap,f=this._material._invertNormalMapX,m=this._material._invertNormalMapY,g=d.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!p||!e.isSync){g&&lE.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),nw.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&lE.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&nw.BindTextureMatrix(this._texture,e,"clearCoat"),!this._textureRoughness||g||d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE||nw.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&lE.ClearCoatTextureEnabled&&!_&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),nw.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",f?1:-1,m?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",f?-1:1,m?-1:1)),this._tintTexture&&lE.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),nw.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let r=1-this._indexOfRefraction,p=1+this._indexOfRefraction,v=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",Math.pow(-r/p,2),v,r,p),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&&lE.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!g&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&lE.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&lE.ClearCoatBumpTextureEnabled&&!_&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&lE.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){var t,i,r,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(r=this._bumpTexture)||void 0===r||r.dispose(),null===(s=this._tintTexture)||void 0===s||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}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"}]}}}p9._DefaultIndexOfRefraction=1.5,iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"isEnabled",void 0),iZ([iW()],p9.prototype,"intensity",void 0),iZ([iW()],p9.prototype,"roughness",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"indexOfRefraction",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"texture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"useRoughnessFromMainTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"textureRoughness",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"remapF0OnInterfaceChange",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"bumpTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"isTintEnabled",void 0),iZ([iX()],p9.prototype,"tintColor",void 0),iZ([iW()],p9.prototype,"tintColorAtDistance",void 0),iZ([iW()],p9.prototype,"tintThickness",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],p9.prototype,"tintTexture",void 0);class _e extends sh{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}}class _t extends hA{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new _e,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=_t._DefaultMinimumThickness,this.maximumThickness=_t._DefaultMaximumThickness,this.indexOfRefraction=_t._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!lE.IridescenceTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._thicknessTexture||!lE.IridescenceTextureEnabled||!!this._thicknessTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=null!==this._texture&&this._texture._texture===(null===(i=this._thicknessTexture)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lE.IridescenceTextureEnabled?nw.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&lE.IridescenceTextureEnabled?nw.PrepareDefinesForMergedUV(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_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&p&&e.isSync||(_&&lE.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),nw.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&lE.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._thicknessTexture)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&nw.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||_||d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||nw.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&lE.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&lE.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}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"}]}}}_t._DefaultMinimumThickness=100,_t._DefaultMaximumThickness=400,_t._DefaultIndexOfRefraction=1.3,iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"isEnabled",void 0),iZ([iW()],_t.prototype,"intensity",void 0),iZ([iW()],_t.prototype,"minimumThickness",void 0),iZ([iW()],_t.prototype,"maximumThickness",void 0),iZ([iW()],_t.prototype,"indexOfRefraction",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"texture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_t.prototype,"thicknessTexture",void 0);class _i extends sh{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class _r extends hA{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()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new _i,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new t4(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||!this._texture||!lE.AnisotropicTextureEnabled||!!this._texture.isReadyOrNotBlocking()}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(sf.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lE.AnisotropicTextureEnabled?nw.PrepareDefinesForMergedUV(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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&lE.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),nw.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&lE.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,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}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,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_r.prototype,"isEnabled",void 0),iZ([iW()],_r.prototype,"intensity",void 0),iZ([iG(4,void 0)],_r.prototype,"direction",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_r.prototype,"texture",void 0),iZ([iW(),iz("_markAllSubMeshesAsMiscDirty")],_r.prototype,"legacy",void 0);class _s extends sh{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,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}}class _n extends hA{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new _s,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=io.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[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!lE.SheenTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!lE.SheenTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;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.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&lE.SheenTextureEnabled?(nw.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&lE.SheenTextureEnabled?nw.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&p&&e.isSync||(_&&lE.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),nw.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&lE.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&nw.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||_||d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||nw.BindTextureMatrix(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&&lE.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&lE.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}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"}]}}}iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_n.prototype,"isEnabled",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_n.prototype,"linkSheenWithAlbedo",void 0),iZ([iW()],_n.prototype,"intensity",void 0),iZ([iX()],_n.prototype,"color",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_n.prototype,"texture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_n.prototype,"useRoughnessFromMainTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_n.prototype,"roughness",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_n.prototype,"textureRoughness",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_n.prototype,"albedoScaling",void 0);class _a extends sh{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_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_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class _o extends hA{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){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new _a,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=io.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=io.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&lE.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;let e=this._getRefractionTexture(t);if(e&&lE.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){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_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1;return}if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!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;let i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,r=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(r||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&lE.ThicknessTextureEnabled&&nw.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&lE.RefractionIntensityTextureEnabled&&!s&&nw.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&lE.TranslucencyIntensityTextureEnabled&&!s&&nw.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){let i=this._getRefractionTexture(t);i&&lE.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;r.getRenderingMesh().getWorldMatrix().decompose(ie.Vector3[0]);let s=Math.max(Math.abs(ie.Vector3[0].x),Math.abs(ie.Vector3[0].y),Math.abs(ie.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,n=this._material.isFrozen,a=this._material.realTimeFiltering,o=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&lE.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),nw.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&lE.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),nw.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&lE.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),nw.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&lE.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;!l.isCube&&l.depth&&(t=l.depth);let i=l.getSize().width,r=this.volumeIndexOfRefraction;e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",i,tK.Log2(i)),l.boundingBoxSize&&(e.updateVector3("vRefractionPosition",l.boundingBoxPosition),e.updateVector3("vRefractionSize",l.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.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&lE.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&lE.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&lE.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&lE.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){lE.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!lE.RefractionTextureEnabled&&!!this._refractionTexture&&!!this._refractionTexture.isRenderTarget}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}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)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")}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"}]}}}iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"isRefractionEnabled",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"isTranslucencyEnabled",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"isDispersionEnabled",void 0),iZ([iW(),iz("_markScenePrePassDirty")],_o.prototype,"isScatteringEnabled",void 0),iZ([iW()],_o.prototype,"_scatteringDiffusionProfileIndex",void 0),iZ([iW()],_o.prototype,"refractionIntensity",void 0),iZ([iW()],_o.prototype,"translucencyIntensity",void 0),iZ([iW()],_o.prototype,"useAlbedoToTintRefraction",void 0),iZ([iW()],_o.prototype,"useAlbedoToTintTranslucency",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"thicknessTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"refractionTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"indexOfRefraction",void 0),iZ([iW()],_o.prototype,"_volumeIndexOfRefraction",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"volumeIndexOfRefraction",null),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"invertRefractionY",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"linkRefractionWithTransparency",void 0),iZ([iW()],_o.prototype,"minimumThickness",void 0),iZ([iW()],_o.prototype,"maximumThickness",void 0),iZ([iW()],_o.prototype,"useThicknessAsDepth",void 0),iZ([iX()],_o.prototype,"tintColor",void 0),iZ([iW()],_o.prototype,"tintColorAtDistance",void 0),iZ([iW()],_o.prototype,"dispersion",void 0),iZ([iX()],_o.prototype,"diffusionDistance",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"useMaskFromThicknessTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"refractionIntensityTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"translucencyIntensityTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_o.prototype,"useGltfStyleTextures",void 0);let _l={effect:null,subMesh:null};class _h extends sh{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_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_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=!1,this.TONEMAPPING_ACES=!1,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 _u extends af{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new t6(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=_u.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=io.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new io(0,0,0),this._albedoColor=new io(1,1,1),this._reflectivityColor=new io(1,1,1),this._reflectionColor=new io(1,1,1),this._emissiveColor=new io(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=_u.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=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new sa(16),this._globalAmbientColor=new io(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new pb(this),this.clearCoat=new p9(this),this.iridescence=new _t(this),this.anisotropy=new _r(this),this.sheen=new _n(this),this.subSurface=new _o(this),this.detailMap=new hI(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),lE.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=px(this.getScene()),this.prePassConfiguration=new lb}get hasRenderTargetTextures(){return!!lE.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===_u.PBRMATERIAL_OPAQUE||this._transparencyMode===_u.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){var e;return!!this._forceAlphaTest||(null===(e=this.subSurface)||void 0===e||!e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===_u.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==_u.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var r;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(M.GetDefineNames,this._eventInfo),t.materialDefines=new _h(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=this.getScene(),a=n.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&lE.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&lE.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&lE.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let e=this._getReflectionTexture();if(e&&lE.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(r=e.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&lE.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&lE.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(lE.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()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(a.getCaps().standardDerivatives&&this._bumpTexture&&lE.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&lE.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;a.getCaps().standardDerivatives||e.isVerticesDataPresent(sf.NormalKind)||(e.createNormals(!0),ig.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));let o=t.effect,l=s._areLightsDisposed,h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(h){if(this._onEffectCreatedObservable&&(_l.effect=h,_l.subMesh=t,this._onEffectCreatedObservable.notifyObservers(_l)),this.allowShaderHotSwapping&&o&&!h.isReady()){if(h=o,s.markAsUnprocessed(),u=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,s,this._materialContext)}return!!(t.effect&&t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!u,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return null!=this._metallic||null!=this._roughness||!!this._metallicTexture}_prepareEffect(e,t,i=null,r=null,s=null,n=null,a){if(this._prepareDefines(e,t,s,n,a),!t.isDirty)return null;t.markAsProcessed();let o=this.getScene().getEngine(),l=new aO,h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=nw.HandleFallbacksForShadows(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");let u=[sf.PositionKind];t.NORMAL&&u.push(sf.NormalKind),t.TANGENT&&u.push(sf.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&u.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&u.push(sf.ColorKind),nw.PrepareAttributesForBones(u,e,t,l),nw.PrepareAttributesForInstances(u,t),nw.PrepareAttributesForMorphTargets(u,e,t),nw.PrepareAttributesForBakedVertexAnimation(u,e,t);let c="pbr",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"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],_=["Material","Scene","Mesh"],f={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=u,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=f,this._callbackPluginEventGeneric(M.PrepareEffect,this._eventInfo),lb.AddUniforms(d),lb.AddSamplers(p),nD(d),sd&&(sd.PrepareUniforms(d,t),sd.PrepareSamplers(p,t)),nw.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:_,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});let m={};this.customShaderNameResolve&&(c=this.customShaderNameResolve(c,d,_,p,t,u,m));let g=t.toString(),v=o.createEffect(c,{attributes:u,uniformsNames:d,uniformBuffersNames:_,samplers:p,defines:g,fallbacks:l,onCompiled:i,onError:r,indexParameters:f,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},o);return this._eventInfo.customCode=void 0,v}_prepareDefines(e,t,i=null,r=null,s=!1){var n;let a=this.getScene(),o=a.getEngine();nw.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,nw.PrepareDefinesForMultiview(a,t);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(nw.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!l),nw.PrepareDefinesForOIT(a,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(a.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,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&lE.DiffuseTextureEnabled?(nw.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&lE.AmbientTextureEnabled?(nw.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&lE.OpacityTextureEnabled?(nw.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;let e=this._getReflectionTexture();if(e&&lE.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,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===n6.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 n6.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case n6.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case n6.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case n6.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case n6.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case n6.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case n6.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case n6.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case n6.CUBIC_MODE:case n6.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==n6.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.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;if(this._lightmapTexture&&lE.LightmapTextureEnabled?(nw.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&lE.EmissiveTextureEnabled?(nw.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,lE.SpecularTextureEnabled){if(this._metallicTexture?(nw.PrepareDefinesForMergedUV(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?(nw.PrepareDefinesForMergedUV(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){let e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(n=this._reflectanceTexture)||void 0===n?void 0:n._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(nw.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(nw.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?nw.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&lE.BumpTextureEnabled&&!this._disableBumpMap?(nw.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&lE.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=a.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&&lE.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===_u.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===_u.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=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,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&&(nw.PrepareDefinesForMisc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(sf.NormalKind),t.DEBUGMODE=this._debugMode),nw.PrepareDefinesForFrameBoundValues(a,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),nw.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==_u.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(M.GetDefineNames,this._eventInfo);let s=new _h(this._eventInfo.defineNames),n=this._prepareEffect(e,s,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(_l.effect=n,_l.subMesh=null,this._onEffectCreatedObservable.notifyObservers(_l)),n.isReady()?t&&t(this):n.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){let 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,i){var r,s,n,a;let o=this.getScene(),l=i.materialDefines;if(!l)return;let h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);let u=o.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);nw.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let d=null,p=this._uniformBuffer;if(c){if(this.bindViewProjection(h),d=this._getReflectionTexture(),!p.useUbo||!this.isFrozen||!p.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&lE.DiffuseTextureEnabled&&(p.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),nw.BindTextureMatrix(this._albedoTexture,p,"albedo")),this._ambientTexture&&lE.AmbientTextureEnabled&&(p.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),nw.BindTextureMatrix(this._ambientTexture,p,"ambient")),this._opacityTexture&&lE.OpacityTextureEnabled&&(p.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),nw.BindTextureMatrix(this._opacityTexture,p,"opacity")),d&&lE.ReflectionTextureEnabled){if(p.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),p.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){let e=d;p.updateVector3("vReflectionPosition",e.boundingBoxPosition),p.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){let e=d.getSize().width;p.updateFloat2("vReflectionFilteringInfo",e,tK.Log2(e))}if(!l.USEIRRADIANCEMAP){let e=d.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&e){if(l.SPHERICAL_HARMONICS){let t=e.preScaledHarmonics;p.updateVector3("vSphericalL00",t.l00),p.updateVector3("vSphericalL1_1",t.l1_1),p.updateVector3("vSphericalL10",t.l10),p.updateVector3("vSphericalL11",t.l11),p.updateVector3("vSphericalL2_2",t.l2_2),p.updateVector3("vSphericalL2_1",t.l2_1),p.updateVector3("vSphericalL20",t.l20),p.updateVector3("vSphericalL21",t.l21),p.updateVector3("vSphericalL22",t.l22)}else p.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),p.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),p.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),p.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),p.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),p.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),p.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),p.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),p.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}}p.updateFloat3("vReflectionMicrosurfaceInfos",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&lE.EmissiveTextureEnabled&&(p.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),nw.BindTextureMatrix(this._emissiveTexture,p,"emissive")),this._lightmapTexture&&lE.LightmapTextureEnabled&&(p.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),nw.BindTextureMatrix(this._lightmapTexture,p,"lightmap")),lE.SpecularTextureEnabled&&(this._metallicTexture?(p.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),nw.BindTextureMatrix(this._metallicTexture,p,"reflectivity")):this._reflectivityTexture&&(p.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),nw.BindTextureMatrix(this._reflectivityTexture,p,"reflectivity")),this._metallicReflectanceTexture&&(p.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),nw.BindTextureMatrix(this._metallicReflectanceTexture,p,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(p.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),nw.BindTextureMatrix(this._reflectanceTexture,p,"reflectance")),this._microSurfaceTexture&&(p.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),nw.BindTextureMatrix(this._microSurfaceTexture,p,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&lE.BumpTextureEnabled&&!this._disableBumpMap&&(p.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),nw.BindTextureMatrix(this._bumpTexture,p,"bump"),o._mirroredCameraPosition?p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&p.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){ih.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,ih.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,p.updateColor4("vReflectivityColor",ih.Color3[0],1);let e=null!==(s=null===(r=this.subSurface)||void 0===r?void 0:r._indexOfRefraction)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((e-1)/(e+1),2)*this._metallicF0Factor,ih.Color3[0]);let t=this._metallicF0Factor;p.updateColor4("vMetallicReflectanceFactors",ih.Color3[0],t)}else p.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);p.updateColor3("vEmissiveColor",lE.EmissiveTextureEnabled?this._emissiveColor:io.BlackReadOnly),p.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(n=this.subSurface)||void 0===n?void 0:n._linkRefractionWithTransparency)?p.updateColor4("vAlbedoColor",this._albedoColor,1):p.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*o.environmentIntensity,this._lightingInfos.w=this._specularIntensity,p.updateVector4("vLightingIntensity",this._lightingInfos),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),p.updateColor3("vAmbientColor",this._globalAmbientColor),p.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}o.texturesEnabled&&(this._albedoTexture&&lE.DiffuseTextureEnabled&&p.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&lE.AmbientTextureEnabled&&p.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&lE.OpacityTextureEnabled&&p.setTexture("opacitySampler",this._opacityTexture),d&&lE.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?p.setTexture("reflectionSampler",d):(p.setTexture("reflectionSampler",d._lodTextureMid||d),p.setTexture("reflectionSamplerLow",d._lodTextureLow||d),p.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&p.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&p.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&lE.EmissiveTextureEnabled&&p.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&lE.LightmapTextureEnabled&&p.setTexture("lightmapSampler",this._lightmapTexture),lE.SpecularTextureEnabled&&(this._metallicTexture?p.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&p.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&p.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&p.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&p.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&lE.BumpTextureEnabled&&!this._disableBumpMap&&p.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),nN(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(o.lightsEnabled&&!this._disableLighting&&nw.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==sY.FOGMODE_NONE||d||this.subSurface.refractionTexture||t.receiveShadows||l.PREPASS)&&this.bindView(h),nw.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&nw.BindMorphTargetParameters(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(a=t.bakedVertexAnimationManager)||void 0===a||a.bind(h,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),nw.BindLogDepth(l,this._activeEffect,o)),this._afterBind(t,this._activeEffect),p.update()}getAnimatables(){let 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(){let 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(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;let t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,r,s,n,a,o,l,h,u,c,d,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._metallicTexture)||void 0===o||o.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(u=this._lightmapTexture)||void 0===u||u.dispose(),null===(c=this._metallicReflectanceTexture)||void 0===c||c.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.dispose(),null===(p=this._microSurfaceTexture)||void 0===p||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}_u.PBRMATERIAL_OPAQUE=nB.MATERIAL_OPAQUE,_u.PBRMATERIAL_ALPHATEST=nB.MATERIAL_ALPHATEST,_u.PBRMATERIAL_ALPHABLEND=nB.MATERIAL_ALPHABLEND,_u.PBRMATERIAL_ALPHATESTANDBLEND=nB.MATERIAL_ALPHATESTANDBLEND,_u.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,_u.LIGHTFALLOFF_PHYSICAL=0,_u.LIGHTFALLOFF_GLTF=1,_u.LIGHTFALLOFF_STANDARD=2,iZ([iG(9,void 0)],_u.prototype,"_imageProcessingConfiguration",void 0),iZ([iz("_markAllSubMeshesAsMiscDirty")],_u.prototype,"debugMode",void 0);class _c extends _u{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===_u.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=_u.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=_u.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===_u.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=_u.LIGHTFALLOFF_GLTF:this._lightFalloff=_u.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){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=_c.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=io.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new io(0,0,0),this.albedoColor=new io(1,1,1),this.reflectivityColor=new io(1,1,1),this.reflectionColor=new io(1,1,1),this.emissiveColor=new io(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=px(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=i$.Clone(()=>new _c(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=i$.Parse(()=>new _c(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),nB._parsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}function _d(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}_c.PBRMATERIAL_OPAQUE=_u.PBRMATERIAL_OPAQUE,_c.PBRMATERIAL_ALPHATEST=_u.PBRMATERIAL_ALPHATEST,_c.PBRMATERIAL_ALPHABLEND=_u.PBRMATERIAL_ALPHABLEND,_c.PBRMATERIAL_ALPHATESTANDBLEND=_u.PBRMATERIAL_ALPHATESTANDBLEND,_c.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=_u.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"directIntensity",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"emissiveIntensity",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"environmentIntensity",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"specularIntensity",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"disableBumpMap",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"albedoTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"ambientTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"ambientTextureStrength",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesAndMiscDirty")],_c.prototype,"opacityTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"reflectionTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"emissiveTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"reflectivityTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"metallicTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"metallic",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"roughness",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"metallicF0Factor",void 0),iZ([iX(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"metallicReflectanceColor",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"metallicReflectanceTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"reflectanceTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"microSurfaceTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"bumpTexture",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty",null)],_c.prototype,"lightmapTexture",void 0),iZ([iX("ambient"),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"ambientColor",void 0),iZ([iX("albedo"),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"albedoColor",void 0),iZ([iX("reflectivity"),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"reflectivityColor",void 0),iZ([iX("reflection"),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"reflectionColor",void 0),iZ([iX("emissive"),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"emissiveColor",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"microSurface",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useLightmapAsShadowmap",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesAndMiscDirty")],_c.prototype,"useAlphaFromAlbedoTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesAndMiscDirty")],_c.prototype,"forceAlphaTest",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesAndMiscDirty")],_c.prototype,"alphaCutOff",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useSpecularOverAlpha",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useRoughnessFromMetallicTextureGreen",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useMetallnessFromMetallicTextureBlue",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useAmbientInGrayScale",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),iZ([iW()],_c.prototype,"usePhysicalLightFalloff",null),iZ([iW()],_c.prototype,"useGLTFLightFalloff",null),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useRadianceOverAlpha",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useObjectSpaceNormalMap",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useParallax",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useParallaxOcclusion",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"parallaxScaleBias",void 0),iZ([iW(),iz("_markAllSubMeshesAsLightsDirty")],_c.prototype,"disableLighting",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"forceIrradianceInFragment",void 0),iZ([iW(),iz("_markAllSubMeshesAsLightsDirty")],_c.prototype,"maxSimultaneousLights",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"invertNormalMapX",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"invertNormalMapY",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"twoSidedLighting",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useAlphaFresnel",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useLinearAlphaFresnel",void 0),iZ([iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"environmentBRDFTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"forceNormalForward",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"enableSpecularAntiAliasing",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useHorizonOcclusion",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],_c.prototype,"useRadianceOcclusion",void 0),iZ([iW(),iz("_markAllSubMeshesAsMiscDirty")],_c.prototype,"unlit",void 0),iZ([iW(),iz("_markAllSubMeshesAsMiscDirty")],_c.prototype,"applyDecalMapAfterDetailMap",void 0),t0["BABYLON.PBRMaterial"]=_c;let _p=_d("DXT1"),__=_d("DXT3"),_f=_d("DXT5"),_m=_d("DX10");class _g{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),r=1;131072&t[2]&&(r=Math.max(1,t[7]));let s=t[21],n=s===_m?i[32]:0,a=0;switch(s){case 113:a=2;break;case 116:a=1;break;case _m:if(10===n){a=2;break}2===n&&(a=1)}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:(4&t[20])==4,isRGB:(64&t[20])==64,isLuminance:(131072&t[20])==131072,isCube:(512&t[28])==512,isCompressed:s===_p||s===__||s===_f,dxgiFormat:n,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,n){let a=new Float32Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,r,s,n,a,o){let l=new Uint8Array(r),h=new Uint8Array(s,i),u=0;for(let i=0;i>8&255,f>>16&255,f>>24&255)]);return}let C=_g._ExtractLongWordOrder(_[23]),y=_g._ExtractLongWordOrder(_[24]),A=_g._ExtractLongWordOrder(_[25]),R=_g._ExtractLongWordOrder(_[26]);S&&(T=e._getRGBABufferInternalSizedFormat(r.textureType)),u=1,131072&_[2]&&!1!==s&&(u=Math.max(1,_[7]));let I=o||0,P=e.getCaps();for(let s=I;s0?r.sphericalPolynomial=cn.ConvertCubeMapToSphericalPolynomial({size:_[4],right:d[0],left:d[1],up:d[2],down:d[3],front:d[4],back:d[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}}_g.StoreLODInAlphaChannel=!1,r$.prototype.createPrefilteredCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,e=>{if(!e){s&&s(null);return}let n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new u6,n._source=m.CubePrefiltered,this.getCaps().textureLOD){s&&s(n);return}let a=this._gl,o=e.width;if(!o)return;let h=[];for(let s=0;s<3;s++){let l=1-s/2,u=tK.Log2(o)*i+r,c=Math.round(Math.min(Math.max(r+(u-r)*l,0),u)),d=new rU(this,m.Temp);if(d.type=n.type,d.format=n.format,d.width=Math.pow(2,Math.max(tK.Log2(o)-c,0)),d.height=d.width,d.isCube=!0,d._cachedWrapU=0,d._cachedWrapV=0,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,d,!0),d.samplingMode=2,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){let t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),_g.UploadDDSLevels(this,d,i,t,!0,6,c)}else ig.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);let p=new n3(t);p._isCube=!0,p._texture=d,d.isReady=!0,h.push(p)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],s&&s(n)},n,a,o,l,i,r)};class _v{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,r){let s;let n=t.getEngine(),a=!1,o=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),_g.UploadDDSLevels(n,t,r,s,a,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t)}else s=_g.GetDDSInfo(e),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new u6),a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),_g.UploadDDSLevels(n,t,e,s,a,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t,!1);n._setCubeMapTextureParams(t,a,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){let r=_g.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1==1;i(r.width,r.height,s,r.isFourCC,()=>{_g.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}}nC._TextureLoaders.push(new _v);class _x{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=ch(e);if(n){t.width=n.width,t.height=n.width;try{cp(t,n),(function(e,t,i){let r=(i=cu(i)).specular;return r?(e._lodGenerationScale=r.lodGenerationScale,function(e,t,i=co){if(!ss.IsExponentOfTwo(e.width))throw Error("Texture size must be a power of two");let r=tK.ILog2(e.width)+1,s=e.getEngine(),n=!1,a=!1,o=null,l=null,h=null,u=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),u.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(n=!0,e.type=2):u.textureFloatRender&&u.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,a=!0,h={}),n)o=new aL("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=s.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,a){let t=e._lodGenerationScale,i=e._lodGenerationOffset;for(let n=0;n<3;n++){let a=(r-1)*t+i,o=Math.round(Math.min(Math.max(i+(a-i)*(1-n/2),0),a)),l=new rU(s,m.Temp);l.isCube=!0,l.invertY=!0,l.generateMipMaps=!1,s.updateTextureSamplingMode(2,l);let u=new n3(null);switch(u._isCube=!0,u._texture=l,h[o]=u,n){case 0:e._lodTextureLow=u;break;case 1:e._lodTextureMid=u;break;case 2:e._lodTextureHigh=u}}}let c=[];for(let r=0;rcd(t,s,n,o,f,u,r,a,h,l,e));else{let t=new Image;t.src=f,d=new Promise((i,c)=>{t.onload=()=>{cd(t,s,n,o,f,u,r,a,h,l,e).then(()=>i()).catch(e=>{c(e)})},t.onerror=e=>{c(e)}})}c.push(d)}if(t.length{l&&(s._releaseTexture(e),l._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))})}(e,cc(t,i),i.imageType)):Promise.resolve()})(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},e=>{null==s||s("Can not upload environment levels",e)})}catch(e){null==s||s("Can not upload environment file",e)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}nC._TextureLoaders.push(new _x);class _T{constructor(e,t){if(this.data=e,this.isInvalid=!1,!_T.IsValid(e)){this.isInvalid=!0,ig.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=67305985===r.getUint32(0,!0);if(this.glType=r.getUint32(1*i,s),this.glTypeSize=r.getUint32(2*i,s),this.glFormat=r.getUint32(3*i,s),this.glInternalFormat=r.getUint32(4*i,s),this.glBaseInternalFormat=r.getUint32(5*i,s),this.pixelWidth=r.getUint32(6*i,s),this.pixelHeight=r.getUint32(7*i,s),this.pixelDepth=r.getUint32(8*i,s),this.numberOfArrayElements=r.getUint32(9*i,s),this.numberOfFaces=r.getUint32(10*i,s),this.numberOfMipmapLevels=r.getUint32(11*i,s),this.bytesOfKeyValueData=r.getUint32(12*i,s),0!==this.glType){ig.Error("only compressed formats currently supported"),this.isInvalid=!0;return}if(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth){ig.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(0!==this.numberOfArrayElements){ig.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){ig.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=_T.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case _T.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case _T.TEX_2D:case _T.COMPRESSED_3D:case _T.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=_T.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}_T.HEADER_LEN=64,_T.COMPRESSED_2D=0,_T.COMPRESSED_3D=1,_T.TEX_2D=2,_T.TEX_3D=3;class _b{constructor(e){this._pendingActions=[],this._workerInfos=e.map(e=>({workerPromise:Promise.resolve(e),idle:!0}))}dispose(){for(let 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(let t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{let t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0})})}}class _E extends _b{constructor(e,t,i=_E.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e)){if(this._workerInfos.length{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(e=>{e.terminate()});let t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)},this._options.idleTimeElapsedBeforeRelease))})})}}function _S(e){e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}_E.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(eK||(eK={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(e$||(e$={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(eq||(eq={}));class _C{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;let e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[e$.BC1_RGB,e$.BC3_RGBA],yes:{transcodeFormat:e$.RGBA32,engineFormat:eq.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class _y{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(_y._WorkerPoolPromise||_y._DecoderModulePromise)return;let t={jsDecoderModule:ss.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:ss.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:ss.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:ss.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:ss.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:ss.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:ss.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:ss.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:ss.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:ss.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?_y._WorkerPoolPromise=new Promise(i=>{let r=`${_S}(${_A})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new _E(e,()=>new Promise((e,i)=>{let r=new Worker(s),n=e=>{r.removeEventListener("error",n),r.removeEventListener("message",a),i(e)},a=t=>{"init"===t.data.action&&(r.removeEventListener("error",n),r.removeEventListener("message",a),e(r))};r.addEventListener("error",n),r.addEventListener("message",a),r.postMessage({action:"init",urls:t})})))}):"undefined"==typeof KTX2DECODER?_y._DecoderModulePromise=ss.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,_S(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,_y._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=_y.DefaultNumWorkers){this._engine=e,_y._Initialize(t)}uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(_y._WorkerPoolPromise)return _y._WorkerPoolPromise.then(r=>new Promise((n,a)=>{r.push((r,o)=>{let l=e=>{r.removeEventListener("error",l),r.removeEventListener("message",h),a(e),o()},h=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",l),r.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){a({message:e})}else a({message:e.data.msg});o()}};r.addEventListener("error",l),r.addEventListener("message",h),r.postMessage({action:"setDefaultDecoderOptions",options:_y.DefaultDecoderOptions._getKTX2DecoderOptions()});let u=new Uint8Array(e.byteLength);u.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:u,caps:s,options:i},[u.buffer])})}));if(_y._DecoderModulePromise)return _y._DecoderModulePromise.then(i=>(_y.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=_y.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((s,n)=>{i.decode(e,r).then(e=>{this._createTexture(e,t),s()}).catch(e=>{n({message:e})})})));throw Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let r=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,r=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}function _A(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;importScripts(i.jsDecoderModule),_S(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=t.data.options;break;case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(e=>{let t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})})}}}_y.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},_y.DefaultNumWorkers=_y.GetDefaultNumWorkers(),_y.DefaultDecoderOptions=new _C;class _R{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),n=new _T(e,6),a=n.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,s._setCubeMapTextureParams(t,a,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(_T.IsValid(e)){t._invertVScale=!t.invertY;let r=new _T(e,1),s=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(r.glInternalFormat);s?(t.format=s,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else _y.IsValid(e)?new _y(t.getEngine()).uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},e=>{ig.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,()=>{},!0)}):(ig.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}nC._TextureLoaders.unshift(new _R);class _I extends oG{constructor(e,t,i){super(e,t5.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=t8.Identity(),this._referencedPosition=new t5,this._trackingState=ee.NOT_TRACKING,this.onXRCameraInitializedObservable=new tj,this.onBeforeCameraTeleport=new tj,this.onAfterCameraTeleport=new tj,this.onTrackingStateChanged=new tj,this.compensateOnFirstFrame=!0,this._rotate180=new t8(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new t8,this.cameraRigMode=ns.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new nr(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new nr(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,t8.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){let t=ie.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();let i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),t8.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(ee.NOT_TRACKING);return}let t=e.emulatedPosition?ee.TRACKING_LOST:ee.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){let e={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(e),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){let t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;let i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach((e,t)=>{var i;let r=this.rigCameras[t];r.isLeftCamera||r.isRightCamera||("right"===e.eye?r._isRightCamera=!0:"left"!==e.eye||(r._isLeftCamera=!0));let s=e.transform.position,n=e.transform.orientation;r.parent=this.parent,r.position.set(s.x,s.y,s.z),r.rotationQuaternion.set(n.x,n.y,n.z,n.w),this._scene.useRightHandedSystem?r.rotationQuaternion.multiplyInPlace(this._rotate180):(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1),t7.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,r._projectionMatrix),this._scene.useRightHandedSystem||r._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(r._projectionMatrix);let a=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==a?void 0:a._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=a):(this._xrSessionManager.trySetViewportForView(r.viewport,e),r.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),r.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){let e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){let e=ie.Matrix[0],t=ie.Matrix[1],i=ie.Matrix[2];t7.ComposeToRef(_I._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),t7.ComposeToRef(_I._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);let r=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(r)}}}_I._ScaleReadOnly=t5.One();class _P{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new tj,this.onStateChangedObservable=new tj,this.state=J.NOT_IN_XR,this.sessionManager=new hz(e),this.camera=new _I("webxr",e,this.sessionManager),this.featuresManager=new au(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){let t=new _P(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(e=>{throw t._setState(J.NOT_IN_XR),t.dispose(),e})}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),r={}){var s,n,a;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(J.ENTERING_XR),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&ig.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);let o=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(ah.LAYERS)||(l.baseLayer=o),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(n=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===n?void 0:n.attachedToElement),null===(a=this._nonVRCamera)||void 0===a||a.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce(()=>{this.state!==J.EXITING_XR&&this._setState(J.EXITING_XR),this.camera.rigCameras.forEach(e=>{e.outputRenderTarget=null}),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(J.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(J.IN_XR)}),this.sessionManager}catch(e){throw ig.Log(e),ig.Log(e.message),this._setState(J.NOT_IN_XR),e}}exitXRAsync(){return this.state!==J.IN_XR?Promise.resolve():(this._setState(J.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){let t=1/((null==e?void 0:e.fps)?e.fps:1e3)*1e3,i=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,r=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw Error("the preferred camera index is beyond the length of rig camera array.");let e=()=>{this.state===J.IN_XR?(this._spectatorCamera=new o0("webxr-spectator",t5.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new t8,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add(e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===J.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class _M{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new tj,this.onButtonStateChangedObservable=new tj}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return -1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){let i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}_M.BUTTON_TYPE="button",_M.SQUEEZE_TYPE="squeeze",_M.THUMBSTICK_TYPE="thumbstick",_M.TOUCHPAD_TYPE="touchpad",_M.TRIGGER_TYPE="trigger";class _D{constructor(e,t,i,r,s=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=n,this._initComponent=e=>{if(!e)return;let t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new _M(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new tj,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach(e=>this.getComponent(e).dispose()),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach(e=>{e.setEnabled(!1)}),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map(e=>this.components[e]).filter(t=>t.type===e)}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){let e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath();return e?ig.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{let s=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){let e=this._controllerCache.filter(e=>e.filename===t.filename&&e.path===t.path);if(e[0]){e[0].meshes.forEach(e=>e.setEnabled(!0)),s(e[0].meshes);return}}a_.ImportMesh("",t.path,t.filename,this.scene,e=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:e})),s(e)},null,(e,i)=>{ig.Log(i),ig.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)})})}updateFromXRFrame(e){this.getComponentIds().forEach(e=>this.getComponent(e).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(e=>e.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(e=>e.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;let r=i?.5*t+.5:t;t8.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),t5.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new nX(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=t8.FromEulerAngles(0,Math.PI,0)}}class _O extends _D{constructor(e,t,i){super(e,_N[i],t,i),this.profileId=_O.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new nX(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=t8.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}_O.ProfileId="generic-trigger";let _N={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class _F extends _D{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){let e=a_.IsPluginForExtensionAvailable(".glb");return e||ig.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach(i=>{let r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{let s=t.type===_M.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===_M.TOUCHPAD_TYPE&&!this._touchDots[i]){let t=ul(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new hD(i+"mat",this.scene),t.material.diffuseColor=io.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}})})}_setRootMesh(e){let t;this.rootMesh=new nX(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{let t=this.getComponent(e);if(!t.hasChanges)return;let i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach(e=>{let s=r.visualResponses[e],n=t.value;if("xAxis"===s.componentProperty?n=t.axes.x:"yAxis"===s.componentProperty&&(n=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==s.componentProperty);else{let r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}})})}}let _w=[];class _L{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){let t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){let r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");let s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),!this.UseOnlineRepository)return this._LoadProfilesFromAvailableControllers(r,e,t);{let i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch(()=>s.call(this,r,e,t))}}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=ss.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){_w.forEach(e=>{e.meshes.forEach(e=>{e.dispose(!1,!0)})}),_w.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=ss.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then(e=>JSON.parse(e))),this._ProfileLoadingPromises[e])).then(e=>new _F(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:_w))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;rnew _O(t,e.gamepad,e.handedness)),_L.DefaultFallbacks();let _B=0;class _U{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new t5,this._disposed=!1,this.onDisposeObservable=new tj,this.onMeshLoadedObservable=new tj,this.onMotionControllerInitObservable=new tj,this._uniqueId=`controller-${_B++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new nM(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new t8,this.inputSource.gripSpace&&(this.grip=new nM(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new t8),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&_L.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then(e=>{var t;e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach(e=>e.renderingGroupId=this._options.renderingGroupId)),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&(null===(t=this.motionController)||void 0===t||t.dispose())})},()=>{ss.Warn("Could not find a matching motion controller for the registered input source")})}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){let i=t&&this.grip?this.grip:this.pointer;t5.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){let r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){let e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z);let t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){let r=e.getPose(this.inputSource.gripSpace,t);if(r){let e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}}class _V{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new tj,this.onControllerRemovedObservable=new tj,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(e=>e.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(e=>{this.controllers.forEach(t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera)})}),this._options.customControllersRepositoryURL&&(_L.BaseRepositoryUrl=this._options.customControllersRepositoryURL),_L.UseOnlineRepository=!this._options.disableOnlineControllerRepository,_L.UseOnlineRepository)try{_L.UpdateProfilesList().catch(()=>{_L.UseOnlineRepository=!1})}catch(e){_L.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){let i=this.controllers.map(e=>e.inputSource);for(let t of e)if(-1===i.indexOf(t)){let e=new _U(this.xrSessionManager.scene,t,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}let r=[],s=[];this.controllers.forEach(e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)}),this.controllers=r,s.forEach(e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),_L.ClearControllerCache()}}class _k extends ac{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new as(new t5,new t5),disabledByNearInteraction:!1,id:_k._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new t5,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new io(.9,.9,.9),this.laserPointerDefaultColor=new io(.7,.7,.7),this.selectionMeshDefaultColor=new io(.8,.8,.8),this.selectionMeshPickedColor=new io(.3,.3,1),this._identityMatrix=t7.Identity(),this._screenCoordinatesRef=t5.Zero(),this._viewportRef=new nr(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){let e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new as(new t5,new t5),disabledByNearInteraction:!1,id:_k._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;i{let t;let i=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}if(i.laserPointer.isVisible=this.displayLaserPointer,i.xrController)t=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);else{if(!i.webXRCamera)return;t=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay)}if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&t){let e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;!r||(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),t5.ProjectToRef(t,this._identityMatrix,e.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));let s=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit){if(this._pickingMoved(s,t.pick))o&&!this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),o=!1,a=0;else if(a>i/10&&(n.isVisible=!0),(a+=this._scene.getEngine().getDeltaTime())>=i)this._scene.simulatePointerDown(t.pick,l),o=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{let e=1-a/i;n.scaling.set(e,e,e)}}else o=!1,a=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}}),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&o&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()})}_attachScreenRayMode(e){let t=this._controllers[e.uniqueId],i=!1,r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),t.pick&&(!this._options.disablePointerUpOnTouchOut||!i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){let t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);let i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))}),e.inputSource.gamepad){let r=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(r=>{if(r.changes.pressed){let s=r.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)):!s||this._options.enablePointerSelectionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)}})};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{let e=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)},r=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)};t.eventListeners={selectend:r,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(t5.Dot(e,t.direction)){let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){let e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new sm,e),t.finalPointerUpTriggered=!0})}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){ss.Warn("controller already detached.")}})}}_generateNewMeshPair(e){let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ui.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():ue("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;let r=new hD("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;let s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():h$("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;let n=new hD("targetMat",t);return n.specularColor=io.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,s.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));let r=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>r}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}_k._IdCounter=200,_k.Name=ah.POINTER_SELECTION,_k.Version=1,au.AddWebXRFeature(_k.Name,(e,t)=>()=>new _k(e,t),_k.Version,!0),nf.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,n){let a=ie.Vector3[0],o=ie.Vector3[1],l=Infinity;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;let{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:eQ.DEHYDRATED,grabRay:new as(new t5,new t5),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:_G._IdCounter++,pickedPointVisualCue:s},this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new io(.8,.8,.8),this.selectionMeshPickedColor=new io(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=eZ.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case eQ.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===eQ.HOVER)break;case eQ.HOVER:e.touchCollisionMeshFunction(!0),eQ.TOUCH}else switch(e.currentAnimationState){case eQ.TOUCH:if(e.touchCollisionMeshFunction(!1),t===eQ.HOVER)break;case eQ.HOVER:e.hydrateCollisionMeshFunction(!1),eQ.DEHYDRATED}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;let s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(ie.Vector3[0]),s.grabRay.direction.copyFrom(ie.Vector3[0]),this._options.nearInteractionControllerMode!==eZ.CENTERED_IN_FRONT||(null===(r=s.xrController)||void 0===r?void 0:r.inputSource.hand)||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var i;let r=this._controllers[t],s=null===(i=r.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!r.xrController||!s&&(!this._options.nearInteractionControllerMode||!r.xrController.inputSource.gamepad)){r.pick=null;return}if(r.hoverInteraction=!1,r.nearInteraction=!1,!r.xrController)return;if(s){let i=s.get("index-finger-tip");if(i){let r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){let e=this._scene.useRightHandedSystem?1:-1;ie.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),ie.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,ie.Vector3[0],ie.Quaternion[0])}}}else if(r.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==eZ.DISABLED){let e=r.xrController.pointer;r.xrController.grip&&this._options.nearInteractionControllerMode===eZ.CENTERED_ON_CONTROLLER&&(e=r.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}let n=(e,t)=>t&&t.hit?e&&e.hit?t.distance{let t=new sm,i=!1,r=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),r&&!i&&(t=e),t};if(!r.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,this._hoverRadius,this._utilityLayerScene,e=>this._nearInteractionPredicate(e)));let i=n(this._pickWithSphere(r,this._hoverRadius,this._scene,e=>this._nearInteractionPredicate(e)),t);if(i&&i.hit&&(e=a(i)).hit&&(r.hoverInteraction=!0),r.hoverInteraction){let t=null,i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,i,this._utilityLayerScene,e=>this._nearPickPredicate(e)));let o=a(n(this._pickWithSphere(r,i,this._scene,e=>this._nearPickPredicate(e)),t));o.hit&&(e=o,r.nearInteraction=!0)}r.stalePick=r.pick,r.pick=e,r.pick&&r.pick.pickedPoint&&r.pick.hit?(r.meshUnderPointer=r.pick.pickedMesh,r.pickedPointVisualCue.position.copyFrom(r.pick.pickedPoint),r.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!0)):(r.meshUnderPointer=null,r.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!1))}let o=eQ.DEHYDRATED;r.grabInteraction||r.nearInteraction?o=eQ.TOUCH:r.hoverInteraction&&(o=eQ.HOVER),this._handleTransitionAnimation(r,o)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||ui.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ui.DefaultUtilityLayer.utilityLayerScene:this._scene,t=ul("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=t8.Identity();let i=new hD("targetMat",e);return i.specularColor=io.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){let t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))});let r=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!r||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){let i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(e=>{e.changes.pressed&&r(e.changes.pressed.current)}):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(e=>{e.changes.pressed&&r(e.changes.pressed.current)}))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{let e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},r=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:r,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_detachController(e){let t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach(e=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{let e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new sm,e)}),delete this._controllers[e],this._attachedController===e)){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ui.DefaultUtilityLayer.utilityLayerScene:this._scene,t=ul("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:oi.ParseFromSnippetAsync("8RUNKL#3",e).then(e=>{t.material=e});let i=new s5;i.setEasingMode(s1.EASINGMODE_EASEINOUT);let r=new t5(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),n=new t5(s,s,s),a=this._controllerPickRadius*(7/6),o=new t5(a,a,a),l=.8*this._controllerPickRadius,h=new t5(l,l,l),u=1.5*this._controllerPickRadius,c=[{frame:0,value:r},{frame:10,value:new t5(u,u,u)},{frame:18,value:n}],d=[{frame:0,value:n},{frame:10,value:h},{frame:18,value:r}],p=[{frame:0,value:t5.ZeroReadOnly},{frame:12,value:o},{frame:15,value:r}],_=[{frame:0,value:r},{frame:10,value:t5.ZeroReadOnly},{frame:15,value:t5.ZeroReadOnly}],f=new re("touch","scaling",60,re.ANIMATIONTYPE_VECTOR3,re.ANIMATIONLOOPMODE_CONSTANT),m=new re("release","scaling",60,re.ANIMATIONTYPE_VECTOR3,re.ANIMATIONLOOPMODE_CONSTANT),g=new re("hydrate","scaling",60,re.ANIMATIONTYPE_VECTOR3,re.ANIMATIONLOOPMODE_CONSTANT),v=new re("dehydrate","scaling",60,re.ANIMATIONTYPE_VECTOR3,re.ANIMATIONLOOPMODE_CONSTANT);return f.setEasingFunction(i),m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),f.setKeys(c),m.setKeys(d),g.setKeys(p),v.setKeys(_),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{e.beginDirectAnimation(t,[i?f:m],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{i&&(t.isVisible=!0),e.beginDirectAnimation(t,[i?g:v],0,15,!1,1,()=>{i||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){let s=new sm;if(s.distance=Infinity,e.touchCollisionMesh&&e.xrController){let n=e.touchCollisionMesh.position,a=no.CreateFromCenterAndRadius(n,t);for(let t=0;ts&&(r=0,u.copyFrom(t.center)),-1!==r&&r()=>new _G(e,t),_G.Version,!0);class _z{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class _W{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new tj,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";let e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor",r=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";r+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';let s=document.createElement("style");s.appendChild(document.createTextNode(r)),document.getElementsByTagName("head")[0].appendChild(s);let n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new _z(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}let i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce(()=>{this.dispose()}))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;let i=this._buttons.map(t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode));e.onStateChangedObservable.add(e=>{e==J.NOT_IN_XR&&this._updateButtons(null)}),(await Promise.all(i)).forEach((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):ss.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){let r=new _W(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==J.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==J.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(r){this._updateButtons(null);let t=this._buttons[e].element,i=t.title;t.title="Error entering XR session : "+i,t.classList.add("xr-error"),this.options.onError&&this.options.onError(r)}}dispose(){let e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach(e=>{e.update(this._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function _H(e){var t;let i=0,r=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};let s=e.contextObservable.add(t=>{let n=Date.now();i=n-r;let a={startTime:r,currentTime:n,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(a),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(a)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(a))},e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(eJ||(eJ={}));class _X{constructor(e){var t,i;this.onEachCountObservable=new tj,this.onTimerAbortedObservable=new tj,this.onTimerEndedObservable=new tj,this.onStateChangedObservable=new tj,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{let t=Date.now();this._timer=t-this._startTime;let i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},r=this._breakOnNextTick||this._breakCondition(i);r||this._timer>=this._timeToEnd?this._stop(i,r):this.onEachCountObservable.notifyObservers(i)},this._setState(eJ.INIT),this._contextObservable=e.contextObservable,this._observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{},this._breakCondition=null!==(i=e.breakCondition)&&void 0!==i?i:()=>!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(this._state===eJ.STARTED)throw 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(eJ.STARTED)}stop(){this._state===eJ.STARTED&&(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(eJ.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class _Y extends ac{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){let t=this._options.teleportationTargetMesh.getChildMeshes(!1,e=>"rotationCone"===e.name);t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new il(1,1,1,1),this._tmpRay=new as(new t5,new t5),this._tmpVector=new t5,this._tmpQuaternion=new t8,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new tj,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new tj,this.onAfterCameraTeleportRotation=new tj,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1}};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let i=()=>{if(e.motionController){let i=e.motionController.getComponentOfType(_M.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(_M.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){let i=e.motionController.getMainComponent();if(!i)return;t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add(()=>{this.teleportationEnabled&&i.changes.pressed&&(i.changes.pressed.current?(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,_H({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})):(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))})}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add(i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,t8.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);let e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,e=>-1!==this._floorMeshes.indexOf(e));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;let e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),t8.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))})}};e.motionController?i():e.onMotionControllerInitObservable.addOnce(()=>{i()})}else this._xrSessionManager.scene.onPointerObservable.add(i=>{i.type===sS.POINTERDOWN?(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,_H({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})):i.type===sS.POINTERUP&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="")})},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new il(1,0,0,.75),this._setTargetMeshVisibility(!1)}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)}removeFloorMesh(e){let t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];let t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){let t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t){for(let i=0;i{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;let t=this._floorMeshes.indexOf(e);return -1!==t&&this._floorMeshes[t].absolutePosition.y!!this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e)||-1!==this._floorMeshes.indexOf(e));if(n&&n.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(n.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(n);return}n&&n.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(n),this._setTargetMeshVisibility(!0),this._showParabolicPath(n))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ui.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=hj("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{let i=new hO("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;let r=i.getContext();r.beginPath(),r.arc(256,256,200,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),i.update();let s=new hD("teleportationPlaneMaterial",e);s.diffuseTexture=i,t.material=s}let i=h$("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){let t=new re("animationInnerCircle","position.y",30,re.ANIMATIONTYPE_FLOAT,re.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);let s=new s6;s.setEasingMode(s1.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}let r=ue("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(sj.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{let t=new hD("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new io(.3,.3,1):t.diffuseColor=new io(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){let t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){let s=t*t;this._snapToPositions.forEach(t=>{let n=t5.DistanceSquared(t,e);n<=s&&n{t.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||ui.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=s0.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,n=Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=uy("teleportation path line",{points:r.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){let t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint)){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){let e=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,t8.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}}_Y.Name=ah.TELEPORTATION,_Y.Version=1,au.AddWebXRFeature(_Y.Name,(e,t)=>()=>new _Y(e,t),_Y.Version,!0);class _j{constructor(){}static CreateAsync(e,t={}){let i=new _j;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){let r=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new _W(e,r)}return _P.CreateAsync(e).then(e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new _V(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){let e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(_k.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(_Y.Name,t.useStablePlugins?"stable":"latest",Object.assign({floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId},t.teleportationOptions)),i.teleportation.setSelectionFeature(i.pointerSelection))}return(t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(_G.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI)?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(e=>(ig.Error("Error initializing XR"),ig.Error(e),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}function _K(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}sY.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled()),s=r.max.subtract(r.min),n=r.min.add(s.scale(.5)),a=1.5*s.length();if(isFinite(a)||(a=1,n.copyFromFloats(0,0,0)),e){let e=new oW("default camera",-(Math.PI/2),Math.PI/2,a,n,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,t=e}else{let e=new oG("default camera",new t5(n.x,n.y,-a),this);e.setTarget(n),t=e}t.minZ=.01*a,t.maxZ=1e3*a,t.speed=.2*a,this.activeCamera=t,i&&t.attachControl()}},sY.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},sY.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return ig.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);let n=ua("hdrSkyBox",{size:i},this);if(t){let t=new _c("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=n6.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{let t=new hD("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=n6.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},sY.prototype.createDefaultEnvironment=function(e){return pf?new pf(e,this):null},sY.prototype.createDefaultVRExperience=function(e={}){return new hZ(this,e)},sY.prototype.createDefaultXRExperienceAsync=function(e={}){return _j.CreateAsync(this,e).then(e=>e)};class _$ extends n6{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new tj),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):ig.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((null==e?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}if(!this.video.muted){ig.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(e=>{this._processError(e)});return}}this._processError(e)})}constructor(e,t,i,r=!1,s=!1,n=n6.TRILINEAR_SAMPLINGMODE,a={},o,l=5){var h;super(null,i,!r,s),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||ss.IsExponentOfTwo(this.video.videoWidth)&&ss.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=n6.WRAP_ADDRESSMODE,this.wrapV=n6.WRAP_ADDRESSMODE):(this.wrapU=n6.CLAMP_ADDRESSMODE,this.wrapV=n6.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=null!==(e=this._format)&&void 0!==e?e:5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{let e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture||this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return ss.SetCorsBehavior(e.currentSrc,e),e;let t=document.createElement("video");return"string"==typeof e?(ss.SetCorsBehavior(e,t),t.src=e):(ss.SetCorsBehavior(e[0],t),e.forEach(e=>{let i=document.createElement("source");i.src=e,t.appendChild(i)})),this.onDisposeObservable.addOnce(()=>{_K(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){!e||this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture())}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new _$(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),null===(e=this._externalTexture)||void 0===e||e.dispose()}static CreateFromStreamAsync(e,t,i,r=!0){let s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(void 0!==s.mozSrcObject?s.mozSrcObject=t:"object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise(t=>{let i=()=>{let n=new _$("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce(()=>{s.remove()}),n.onDisposeObservable.addOnce(()=>{_K(s)}),t(n),s.removeEventListener("playing",i)};s.addEventListener("playing",i),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){let s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,s,t,r);return n.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(e=>{e.stop()})}),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then(function(e){t&&t(e)}).catch(function(e){ig.Error(e.name)})}}iZ([iW("settings")],_$.prototype,"_settings",void 0),iZ([iW("src")],_$.prototype,"_currentSrc",void 0),iZ([iW()],_$.prototype,"isVideo",void 0),n6._CreateVideoTexture=(e,t,i,r=!1,s=!1,n=n6.TRILINEAR_SAMPLINGMODE,a={},o,l=5)=>new _$(e,t,i,r,s,n,a,o,l),t0["BABYLON.VideoTexture"]=_$;class _q extends pm{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){let r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new _$((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,n6.TRILINEAR_SAMPLINGMODE,r);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(e=>{var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===this.mesh&&this._texture.video.play()},sS.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}_q.MODE_MONOSCOPIC=pm.MODE_MONOSCOPIC,_q.MODE_TOPBOTTOM=pm.MODE_TOPBOTTOM,_q.MODE_SIDEBYSIDE=pm.MODE_SIDEBYSIDE;let _Q=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +#include +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; +#endif +#ifdef VERTEXALPHA +varying vec4 vColor; +#endif +uniform vec4 glowColor;uniform float glowIntensity; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +vec4 finalColor=glowColor; +#ifdef DIFFUSE +vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); +#ifdef DIFFUSE_ISLINEAR +albedoTexture=toGammaSpace(albedoTexture); +#endif +#ifdef GLOW +finalColor.a*=albedoTexture.a; +#endif +#ifdef HIGHLIGHT +finalColor.a=albedoTexture.a; +#endif +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); +#ifdef OPACITYRGB +finalColor.a*=getLuminance(opacityMap.rgb); +#else +finalColor.a*=opacityMap.a; +#endif +finalColor.a*=opacityIntensity; +#endif +#ifdef VERTEXALPHA +finalColor.a*=vColor.a; +#endif +#ifdef ALPHATEST +if (finalColor.a +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +uniform mat4 viewProjection;varying vec4 vPosition; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform mat4 opacityMatrix; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; +#endif +#ifdef VERTEXALPHA +attribute vec4 color;varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef CUBEMAP +vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#else +vPosition=viewProjection*worldPos;gl_Position=vPosition; +#endif +#ifdef DIFFUSE +#ifdef DIFFUSEUV1 +vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef DIFFUSEUV2 +vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef OPACITY +#ifdef OPACITYUV1 +vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef OPACITYUV2 +vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef EMISSIVE +#ifdef EMISSIVEUV1 +vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef EMISSIVEUV2 +vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef VERTEXALPHA +vColor=color; +#endif +#include +}`;rO.ShadersStore.glowMapGenerationVertexShader=_Z;class _J{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);let n=this._scene.getEngine();if(r.length){for(n.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){let e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=e})}}_addCustomEffectDefines(e){}_isReady(e,t,i){var r;let s=this._scene.getEngine(),n=e.getMesh(),a=null===(r=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[s.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);let o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);let l=[],h=[sf.PositionKind],u=!1,c=!1;if(o){let e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),n.isVerticesDataPresent(sf.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),c=!0):n.isVerticesDataPresent(sf.UVKind)&&(l.push("#define DIFFUSEUV1"),u=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));let r=o.opacityTexture;r&&(l.push("#define OPACITY"),n.isVerticesDataPresent(sf.UV2Kind)&&1===r.coordinatesIndex?(l.push("#define OPACITYUV2"),c=!0):n.isVerticesDataPresent(sf.UVKind)&&(l.push("#define OPACITYUV1"),u=!0))}i&&(l.push("#define EMISSIVE"),n.isVerticesDataPresent(sf.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),c=!0):n.isVerticesDataPresent(sf.UVKind)&&(l.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(sf.ColorKind)&&n.hasVertexAlpha&&o.transparencyMode!==nB.MATERIAL_OPAQUE&&(h.push(sf.ColorKind),l.push("#define VERTEXALPHA")),u&&(h.push(sf.UVKind),l.push("#define UV1")),c&&(h.push(sf.UV2Kind),l.push("#define UV2"));let d=new aO;if(n.useBones&&n.computeBonesUsingShaders){h.push(sf.MatricesIndicesKind),h.push(sf.MatricesWeightsKind),n.numBoneInfluencers>4&&(h.push(sf.MatricesIndicesExtraKind),h.push(sf.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);let e=n.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),n.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,n)}else l.push("#define NUM_BONE_INFLUENCERS 0");let p=n.morphTargetManager,_=0;p&&p.numInfluencers>0&&(l.push("#define MORPHTARGETS"),_=p.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+_),p.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),nw.PrepareAttributesForMorphTargetsInfluencers(h,n,_)),t&&(l.push("#define INSTANCES"),nw.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),nO(o,this._scene,l),this._addCustomEffectDefines(l);let f=e._getDrawWrapper(void 0,!0),m=f.defines,g=l.join("\n");if(m!==g){let e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];nD(e),f.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:_}),g)}return f.effect.isReady()}render(){for(let e=0;el._getWorldMatrixDeterminant()&&(c=c===nB.ClockWiseSideOrientation?nB.CounterClockWiseSideOrientation:nB.ClockWiseSideOrientation);let d=c===nB.ClockWiseSideOrientation;u.setState(s.backFaceCulling,s.zOffset,void 0,d,s.cullBackFaces,void 0,s.zOffsetUnits);let p=o._getInstancesRenderList(e._id,!!a);if(p.mustReturn||!this._shouldRenderMesh(o))return;let _=p.hardwareInstancedRendering[e._id]||o.hasThinInstances;if(this._setEmissiveTextureAndColor(o,e,s),this.onBeforeRenderMeshToEffect.notifyObservers(n),this._useMeshMaterial(o))o.render(e,t,a||void 0);else if(this._isReady(e,_,this._emissiveTextureAndColor.texture)){let i=null===(r=l._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[u.currentRenderPassId],n=e._getDrawWrapper();if(!n&&i&&(n=i._getDrawWrapper()),!n)return;let a=n.effect;if(u.enableEffect(n),_||o._bind(e,a,s.fillMode),i?i.bindForSubMesh(l.getWorldMatrix(),l,e):(a.setMatrix("viewProjection",h.getTransformMatrix()),a.setMatrix("world",l.getWorldMatrix()),a.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!i){let e=s.needAlphaTesting(),i=s.getAlphaTestTexture(),r=i&&i.hasAlpha&&(s.useAlphaFromDiffuseTexture||s._useAlphaFromAlbedoTexture);if(i&&(e||r)){a.setTexture("diffuseSampler",i);let e=i.getTextureMatrix();e&&a.setMatrix("diffuseMatrix",e)}let n=s.opacityTexture;if(n){a.setTexture("opacitySampler",n),a.setFloat("opacityIntensity",n.level);let e=n.getTextureMatrix();e&&a.setMatrix("opacityMatrix",e)}if(this._emissiveTextureAndColor.texture&&(a.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),a.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),o.useBones&&o.computeBonesUsingShaders&&o.skeleton){let e=o.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(o);if(!t)return;a.setTexture("boneSampler",t),a.setFloat("boneTextureWidth",4*(e.bones.length+1))}else a.setMatrices("mBones",e.getTransformMatrices(o))}nw.BindMorphTargetParameters(o,a),o.morphTargetManager&&o.morphTargetManager.isUsingTextureForTargets&&o.morphTargetManager._bind(a),t&&u.setAlphaMode(s.alphaMode),a.setFloat("glowIntensity",this.getEffectIntensity(o)),nN(a,s,h)}o._processRendering(l,e,a,s.fillMode,p,_,(e,t)=>a.setMatrix("world",t))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[sf.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return ss.Instantiate(e.customType).Parse(e,t,i)}}_J._SceneComponentInitialization=e=>{throw iL("EffectLayerSceneComponent")},iZ([iW()],_J.prototype,"name",void 0),iZ([iG(8,void 0)],_J.prototype,"neutralColor",void 0),iZ([iW()],_J.prototype,"isEnabled",void 0),iZ([iG(11,void 0)],_J.prototype,"camera",null),iZ([iW()],_J.prototype,"renderingGroupId",null),iZ([iW()],_J.prototype,"disableBoundingBoxesFromEffectLayer",void 0),tW.AddParser(sb.NAME_EFFECTLAYER,(e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(e)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.removeEffectLayer(e),t&&e.dispose()})}dispose(){let e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){let i=this._engine.currentRenderPassId;for(let r of this.scene.effectLayers){if(!r.hasMesh(e))continue;let s=r._mainTexture;for(let n of(this._engine.currentRenderPassId=s.renderPassId,e.subMeshes))if(!r.isReady(n,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1,i=this.scene.effectLayers;if(i&&i.length>0){for(let r of(this._previousStencilState=this._engine.getStencilBuffer(),i))if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===ns.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==ns.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(sb.NAME_EFFECTLAYER);t||(t=new _0(e),e._addComponent(t))};let _1=`varying vec2 vUV;uniform sampler2D textureSampler; +#ifdef EMISSIVE +uniform sampler2D textureSampler2; +#endif +uniform float offset; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef EMISSIVE +baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; +#else +baseColor.a=abs(offset-baseColor.a); +#ifdef STROKE +float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; +#endif +#endif +#if LDR +baseColor=clamp(baseColor,0.,1.0); +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.glowMapMergePixelShader=_1;let _2=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.glowMapMergeVertexShader=_2,tW.prototype.getGlowLayerByName=function(e){var t;for(let i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===_3.EffectName)return this.effectLayers[i];return null};class _3 extends _J{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;let t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new il(0,0,0,1),this._options=Object.assign({mainTextureRatio:_3.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return _3.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[sf.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?nC.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?nC.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new a5("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=n6.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=n6.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(n6.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;let r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new a5("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=n6.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=n6.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(n6.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];let n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new pn("GlowLayerHBP1",new t4(1,0),n,{width:e,height:t},null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new pn("GlowLayerVBP1",new t4(0,1),n,{width:e,height:t},null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new pn("GlowLayerHBP2",new t4(1,0),n,{width:r,height:s},null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new pn("GlowLayerVBP2",new t4(0,1),n,{width:r,height:s},null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(()=>{let e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);let t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(null!=t?t:e,!0)}}),this._postProcesses.map(e=>{e.autoClear=!1})}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;let s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);let t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(nB.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var r;let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=null!==(r=i.emissiveIntensity)&&void 0!==r?r:1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){let t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){let t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(()=>{this._disposeMesh(e)})}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){let e;let t=i$.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;enew _3(e.name,t,e.options),e,t,i);for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)})}}class _6 extends _J{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new tj,this.onAfterBlurObservable=new tj,this._instanceGlowingMeshStencilReference=_6.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=_6.NeutralColor,this._engine.isStencilEnable||ig.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return _6.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[sf.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?nC.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?nC.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new a5("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=n6.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=n6.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(n6.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new o3("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new _5("HighlightLayerHBP",new t4(1,0),this._options.blurHorizontalSize,1,null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new _5("HighlightLayerVBP",new t4(0,1),this._options.blurVerticalSize,1,null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new pn("HighlightLayerHBP",new t4(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new pn("HighlightLayerVBP",new t4(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(e=>{e.autoClear=!1})}needStencil(){return!0}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,n=this._meshes[r.uniqueId];return n&&n.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);let i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(nB.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(nB.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return(!this._excludedMeshes||!this._excludedMeshes[e.uniqueId])&&!!super.hasMesh(e)}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){let t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add(e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)}),t.afterRender=e.onAfterRenderObservable.add(e=>{e.getEngine().setStencilBuffer(t.stencilState)}),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!(this._meshes&&super.hasMesh(e))&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(e=>{this.isEnabled&&this._defaultStencilReference(e)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];for(let i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(_6.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(let e in this._excludedMeshes){let t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){let e=i$.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(let t in this._meshes){let i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(let t in this._excludedMeshes){let i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){let r;let s=i$.Parse(()=>new _6(e.name,t,e.options),e,t,i);for(r=0;r +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef LINEAR +baseColor.rgb=toGammaSpace(baseColor.rgb); +#endif +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.layerPixelShader=_8;let _7=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.layerVertexShader=_7;class _9{static AddFlare(e,t,i,r,s){return new _9(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new io(1,1,1),this.texture=r?new n6(r,s.getScene(),!0):null,this._system=s;let n=s.scene.getEngine();this._drawWrapper=new rY(n),this._drawWrapper.effect=n.createEffect("lensFlare",[sf.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();let e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}let fe=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.lensFlarePixelShader=fe;let ft=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.lensFlareVertexShader=ft;class fi{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||t2.LastCreatedScene,fi._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&(e.layerMask&i.activeCamera.layerMask)!=0;let r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[sf.PositionKind]=new sf(r,s,sf.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){let 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)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=t5.Project(t,t7.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=t5.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);let i=this._scene.useRightHandedSystem;return(t.z>0&&!i||t.z<0&&!!i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;let e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();let i=new as(this._scene.activeCamera.globalPosition,e),r=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!r||!r.hit||r.distance>t}render(){let e,t;if(!this._scene.activeCamera)return!1;let i=this._scene.getEngine(),r=this._scene.activeCamera.viewport.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(r)||!this._isVisible())return!1;let s=(e=this._positionXr.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0)>(t=this._positionYr.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0)?e:t;(s-=this.viewportBorder)>this.borderLimit&&(s=this.borderLimit);let n=1-tK.Clamp(s/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);let a=r.x+r.width/2,o=r.y+r.height/2,l=a-this._positionX,h=o-this._positionY;i.setState(!1),i.setDepthBuffer(!1);for(let e=0;e{throw iL("LensFlareSystemSceneComponent")},tW.AddParser(sb.NAME_LENSFLARESYSTEM,(e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,n=e.lensFlareSystems.length;s{this.scene.addLensFlareSystem(e)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()})}serialize(e){for(let t of(e.lensFlareSystems=[],this.scene.lensFlareSystems))e.lensFlareSystems.push(t.serialize())}dispose(){let e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){let t=this.scene.lensFlareSystems;for(let i of(ss.StartPerformanceCounter("Lens flares",t.length>0),t))(e.layerMask&i.layerMask)!=0&&i.render();ss.EndPerformanceCounter("Lens flares",t.length>0)}}}fi._SceneComponentInitialization=e=>{let t=e._getComponent(sb.NAME_LENSFLARESYSTEM);t||(t=new fr(e),e._addComponent(t))};let fs=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} +float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5*mod(_P,4.0)); +return 4.0*bayerDither2(P1)+bayerDither2(P2);} +float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5 *mod(_P,4.0)); +vec2 P4=floor(0.25*mod(_P,8.0)); +return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} +`;rO.IncludesShadersStore.bayerDitherFunctions=fs;let fn=`#if SM_FLOAT==0 +#include +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#include +uniform float softTransparentShadowSM; +#endif +varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +uniform vec3 lightDataSM;varying vec3 vPositionWSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`;rO.IncludesShadersStore.shadowMapFragmentExtraDeclaration=fn;let fa=`float depthSM=vDepthMetricSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +#if SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); +#else +gl_FragDepth=clamp(depthSM,0.0,1.0); +#endif +#elif SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#if SM_ESM==1 +depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); +#endif +#if SM_FLOAT==1 +gl_FragColor=vec4(depthSM,1.0,1.0,1.0); +#else +gl_FragColor=pack(depthSM); +#endif +return;`;rO.IncludesShadersStore.shadowMapFragment=fa;let fo=`#include +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +#ifdef ALPHATEXTURE +float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; +#ifdef ALPHATESTVALUE +if (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard; +#else +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; +#endif +#endif +#include +}`;rO.ShadersStore.shadowMapPixelShader=fo;let fl=`uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; +`;rO.IncludesShadersStore.sceneVertexDeclaration=fl;let fh=`uniform mat4 world;uniform float visibility; +`;rO.IncludesShadersStore.meshVertexDeclaration=fh;let fu=`#include +#include +`;rO.IncludesShadersStore.shadowMapVertexDeclaration=fu;let fc=`layout(std140,column_major) uniform; +#include +#include +`;rO.IncludesShadersStore.shadowMapUboDeclaration=fc;let fd=`#if SM_NORMALBIAS==1 +uniform vec3 lightDataSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +varying vec3 vPositionWSM; +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`;rO.IncludesShadersStore.shadowMapVertexExtraDeclaration=fd;let fp=`#if SM_NORMALBIAS==1 +#if SM_DIRECTIONINLIGHTDATA==1 +vec3 worldLightDirSM=normalize(-lightDataSM.xyz); +#else +vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); +#endif +float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; +#endif +`;rO.IncludesShadersStore.shadowMapVertexNormalBias=fp;let f_=`#if SM_USEDISTANCE==1 +vPositionWSM=worldPos.xyz; +#endif +#if SM_DEPTHTEXTURE==1 +#ifdef IS_NDC_HALF_ZRANGE +#define BIASFACTOR 0.5 +#else +#define BIASFACTOR 1.0 +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#else +gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#endif +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +zSM=gl_Position.z;gl_Position.z=0.0; +#elif SM_USEDISTANCE==0 +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +`;rO.IncludesShadersStore.shadowMapVertexMetric=f_;let ff=`attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#endif +#include +#include<__decl__shadowMapVertex> +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normWorldSM=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vec3 vNormalW=normalize(normWorldSM*normalUpdated); +#endif +#endif +#include +gl_Position=viewProjection*worldPos; +#include +#ifdef ALPHATEXTURE +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include +}`;rO.ShadersStore.shadowMapVertexShader=ff;let fm=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) +for (int y=-OFFSET; y<=OFFSET; y++) +colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;rO.ShadersStore.depthBoxBlurPixelShader=fm;let fg=`#if SM_SOFTTRANSPARENTSHADOW==1 +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; +#endif +`;rO.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=fg;class fv{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===fv.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}if(e===fv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}if(e===fv.FILTER_PCF||e===fv.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===fv.FILTER_PCF||e===fv.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===fv.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(fv.FILTER_POISSONSAMPLING);(e||this.filter===fv.FILTER_POISSONSAMPLING)&&(this.filter=e?t:fv.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===fv.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(fv.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===fv.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:fv.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===fv.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(fv.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===fv.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:fv.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===fv.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(fv.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===fv.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:fv.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===fv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(fv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===fv.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:fv.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===fv.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(fv.FILTER_PCF);(e||this.filter===fv.FILTER_PCF)&&(this.filter=e?t:fv.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===fv.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(fv.FILTER_PCSS);(e||this.filter===fv.FILTER_PCSS)&&(this.filter=e?t:fv.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return fv.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(let t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(let t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,r,s){this.onBeforeShadowMapRenderObservable=new tj,this.onAfterShadowMapRenderObservable=new tj,this.onBeforeShadowMapRenderMeshObservable=new tj,this.onAfterShadowMapRenderMeshObservable=new tj,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=fv.FILTER_NONE,this._filteringQuality=fv.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=t5.Zero(),this._viewMatrix=t7.Zero(),this._projectionMatrix=t7.Zero(),this._transformMatrix=t7.Zero(),this._cachedPosition=new t5(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new t5(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=t7.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=r?r:null,this._useRedTextureType=!!s;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),fv._SceneComponentInitialization(this._scene);let a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){let e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new a5(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new a5(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=n6.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=n6.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(n6.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,r)=>this._renderForShadowMap(e,t,i,r),this._shadowMap.customIsReadyFunction=()=>!0;let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===fv.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var t,i;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===fv.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){null===(t=e._debugPopGroup)||void 0===t||t.call(e,1);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))});let t=new il(0,0,0,0),i=new il(1,1,1,1);this._shadowMap.onClearObservable.add(e=>{this._filter===fv.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let e=sT.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new pn(this._light.name+"KernelBlurY",new t4(0,1),this.blurKernel,1,null,n6.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new aL(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,n6.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;sn._getWorldMatrixDeterminant(),u=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;h&&(u=0===u?1:0);let c=0===u;o.setState(l.backFaceCulling,void 0,void 0,c,l.cullBackFaces);let d=s._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;let p=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||s.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e)){if(this.isReady(e,p,t)){e._renderId=a.getRenderId();let i=l.shadowDepthWrapper,h=null!==(r=null==i?void 0:i.getEffect(e,this,o.currentRenderPassId))&&void 0!==r?r:e._getDrawWrapper(),u=rY.GetEffect(h);o.enableEffect(h),p||s._bind(e,u,l.fillMode),this.getTransformMatrix(),u.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===nj.LIGHTTYPEID_DIRECTIONALLIGHT?u.setVector3("lightDataSM",this._cachedDirection):u.setVector3("lightDataSM",this._cachedPosition);let c=this._getCamera();if(c&&u.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(c),this.getLight().getDepthMinZ(c)+this.getLight().getDepthMaxZ(c)),t&&this.enableSoftTransparentShadow&&u.setFloat("softTransparentShadowSM",n.visibility*l.alpha),i)e._setMainDrawWrapperOverride(h),i.standalone?i.baseMaterial.bindForSubMesh(n.getWorldMatrix(),s,e):l.bindForSubMesh(n.getWorldMatrix(),s,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(u.setTexture("diffuseSampler",this._opacityTexture),u.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){let e=s.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(s);if(!t)return;u.setTexture("boneSampler",t),u.setFloat("boneTextureWidth",4*(e.bones.length+1))}else u.setMatrices("mBones",e.getTransformMatrices(s))}nw.BindMorphTargetParameters(s,u),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(u),nN(u,l,a)}this._useUBO||i||this._bindCustomEffectForRenderSubMeshForShadowMap(e,u,n),nw.BindSceneUniformBuffer(u,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();let _=n.getWorldMatrix();p&&(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(_)),this.forceBackFacesOnly&&o.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(s),this.onBeforeShadowMapRenderObservable.notifyObservers(u),s._processRendering(n,e,u,l.fillMode,d,p,(e,t)=>{n===s||e?(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(e?t:_)):(s.getMeshUniformBuffer().bindToEffect(u,"Mesh"),s.transferToEffect(t))}),this.forceBackFacesOnly&&o.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(u),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}_applyFilterValues(){this._shadowMap&&(this.filter===fv.FILTER_NONE||this.filter===fv.FILTER_PCSS?this._shadowMap.updateSamplingMode(n6.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(n6.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i=Object.assign({useInstances:!1},t),r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let n=[];for(let e of s)n.push(...e.subMeshes);if(0===n.length){e&&e(this);return}let a=0,o=()=>{var t,r;if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[a],i.useInstances,null!==(r=null===(t=n[a].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(n[a].getMesh()))&&void 0!==r&&r);)if(++a>=n.length){e&&e(this);return}setTimeout(o,16)}};o()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(sf.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===nj.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var r;let s=e.getMaterial(),n=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;let a=[];if(this._prepareShadowDefines(e,t,a,i),n){if(!n.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let i=e._getDrawWrapper(void 0,!0),n=i.effect,o=i.defines,l=[sf.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(sf.NormalKind)&&(l.push(sf.NormalKind),a.push("#define NORMAL"),h.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));let u=s.needAlphaTesting();if((u||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let e=null!==(r=s.alphaCutOff)&&void 0!==r?r:fv.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),u&&a.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(sf.UVKind)&&(l.push(sf.UVKind),a.push("#define UV1")),h.isVerticesDataPresent(sf.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(sf.UV2Kind),a.push("#define UV2"))}let c=new aO;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(sf.MatricesIndicesKind),l.push(sf.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(sf.MatricesIndicesExtraKind),l.push(sf.MatricesWeightsExtraKind));let e=h.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");let d=h.morphTargetManager,p=0;if(d&&d.numInfluencers>0&&(a.push("#define MORPHTARGETS"),p=d.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),nw.PrepareAttributesForMorphTargetsInfluencers(l,h,p)),nO(s,this._scene,a),t&&(a.push("#define INSTANCES"),nw.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let e of this.customShaderOptions.defines)-1===a.indexOf(e)&&a.push(e);let _=a.join("\n");if(o!==_){o=_;let e="shadowMap",t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],r=["diffuseSampler","boneSampler","morphTargets"];if(nD(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(let e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(let e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}let s=this._scene.getEngine();n=s.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:["Scene","Mesh"],samplers:r,defines:_,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},s),i.setEffect(n,o)}if(!n.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),(!this._kernelBlurXPostprocess||!!this._kernelBlurXPostprocess.isReady())&&(!this._kernelBlurYPostprocess||!!this._kernelBlurYPostprocess.isReady())&&(!this._boxBlurPostprocess||!!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){let i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===fv.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===fv.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===fv.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===fv.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;let r=this._getCamera();if(!r)return;let s=this.getShadowMap();s&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===fv.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===fv.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e))}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){let e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),t5.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(t5.Dot(this._lightDirection,t5.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),t7.LookAtLHToRef(t,t.add(this._lightDirection),t5.Up(),this._viewMatrix);let e=this.getShadowMap();if(e){let t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t)for(let e of(this._shadowMap.renderList||(this._shadowMap.renderList=[]),t))this._shadowMap.renderList.push(e);else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){let[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var e;let t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=null===(e=this._camera)||void 0===e?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let e=0;e{throw iL("ShadowGeneratorSceneComponent")};let fx=`#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +varying float vDepthMetric; +#ifdef PACKED +#include +#endif +#ifdef STORE_CAMERASPACE_Z +varying vec4 vViewPos; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#ifdef STORE_CAMERASPACE_Z +#ifdef PACKED +gl_FragColor=pack(vViewPos.z); +#else +gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); +#endif +#else +#ifdef NONLINEARDEPTH +#ifdef PACKED +gl_FragColor=pack(gl_FragCoord.z); +#else +gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); +#endif +#else +#ifdef PACKED +gl_FragColor=pack(vDepthMetric); +#else +gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); +#endif +#endif +#endif +}`;rO.ShadersStore.depthPixelShader=fx;let fT=`#ifdef POINTSIZE +uniform float pointSize; +#endif +`;rO.IncludesShadersStore.pointCloudVertexDeclaration=fT;let fb=`attribute vec3 position; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef STORE_CAMERASPACE_Z +uniform mat4 view;varying vec4 vViewPos; +#endif +#include +varying float vDepthMetric; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#include +gl_Position=viewProjection*worldPos; +#ifdef STORE_CAMERASPACE_Z +vViewPos=view*worldPos; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); +#else +vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); +#endif +#endif +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include +} +`;rO.ShadersStore.depthVertexShader=fb;class fE{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=n6.TRILINEAR_SAMPLINGMODE,n=!1,a){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new il(1,1,1,1):this.clearColor=new il(n?1e8:1,0,0,1),fE._SceneComponentInitialization(this._scene);let o=e.getEngine();this._camera=i,s===n6.NEAREST_SAMPLINGMODE||(1!==t||o._caps.textureFloatLinearFiltering||(s=n6.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(s=n6.NEAREST_SAMPLINGMODE));let l=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new a5(null!=a?a:"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=n6.CLAMP_ADDRESSMODE,this._depthMap.wrapV=n6.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(e=>{e.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{var e;null===(e=o._debugPushGroup)||void 0===e||e.call(o,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)}),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{var t,i;let r=e.getRenderingMesh(),s=e.getEffectiveMesh(),n=this._scene,a=n.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||s.infiniteDistance||o.disableDepthWrite||0===e.verticesCount||e._renderId===n.getRenderId())return;let l=0>s._getWorldMatrixDeterminant(),h=null!==(t=r.overrideMaterialSideOrientation)&&void 0!==t?t:o.sideOrientation;l&&(h=0===h?1:0);let u=0===h;a.setState(o.backFaceCulling,0,!1,u,this.reverseCulling?!o.cullBackFaces:o.cullBackFaces);let c=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(c.mustReturn)return;let d=a.getCaps().instancedArrays&&(null!==c.visibleInstances[e._id]&&void 0!==c.visibleInstances[e._id]||r.hasThinInstances),p=this._camera||n.activeCamera;if(this.isReady(e,d)&&p){let t,l;e._renderId=n.getRenderId();let h=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[a.currentRenderPassId],u=e._getDrawWrapper();!u&&h&&(u=h._getDrawWrapper());let _=p.mode===ns.ORTHOGRAPHIC_CAMERA;if(!u)return;let f=u.effect;if(a.enableEffect(u),d||r._bind(e,f,o.fillMode),h?h.bindForSubMesh(s.getWorldMatrix(),s,e):(f.setMatrix("viewProjection",n.getTransformMatrix()),f.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&f.setMatrix("view",n.getViewMatrix())),_?(t=!a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1):(t=a.useReverseDepthBuffer&&a.isNDCHalfZRange?p.minZ:a.isNDCHalfZRange?0:p.minZ,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:p.maxZ),f.setFloat2("depthValues",t,t+l),!h){if(o.needAlphaTesting()){let e=o.getAlphaTestTexture();e&&(f.setTexture("diffuseSampler",e),f.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){let e=r.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(r);if(!t)return;f.setTexture("boneSampler",t),f.setFloat("boneTextureWidth",4*(e.bones.length+1))}else f.setMatrices("mBones",e.getTransformMatrices(r))}nN(f,o,n),nw.BindMorphTargetParameters(r,f),r.morphTargetManager&&r.morphTargetManager.isUsingTextureForTargets&&r.morphTargetManager._bind(f),o.pointsCloud&&f.setFloat("pointSize",o.pointSize)}r._processRendering(s,e,f,o.fillMode,c,d,(e,t)=>f.setMatrix("world",t))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s4&&(h.push(sf.MatricesIndicesExtraKind),h.push(sf.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));let t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");let u=s.morphTargetManager,c=0;u&&u.numInfluencers>0&&(c=u.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+c),u.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),nw.PrepareAttributesForMorphTargetsInfluencers(h,s,c)),o.pointsCloud&&l.push("#define POINTSIZE"),t&&(l.push("#define INSTANCES"),nw.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),nO(o,n,l);let d=e._getDrawWrapper(void 0,!0),p=d.defines,_=l.join("\n");if(p!==_){let e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];nD(e),d.setEffect(r.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0)for(let t of(this._depthMap.dispose(),e))delete this._scene._depthRenderer[t]}}fE._SceneComponentInitialization=e=>{throw iL("DepthRendererSceneComponent")};let fS=`varying vec2 vUV;uniform sampler2D textureSampler; +#if defined(INITIAL) +uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); +#ifdef DEPTH_REDUX +float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); +#else +float maxz=max(max(max(f1,f2),f3),f4); +#endif +glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(MAIN) +uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(ONEBEFORELAST) +uniform ivec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(LAST) +void main(void) +{glFragColor=vec4(0.);if (true) { +discard;}} +#endif +`;rO.ShadersStore.minmaxReduxPixelShader=fS;class fC{constructor(e){this.onAfterReductionPerformed=new tj,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new sg(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){var s,n,a,o;if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;let l=this._camera.getScene(),h=new aL("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,l.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);h.autoClear=!1,h.forceFullscreenViewport=r;let u=this._sourceTexture.getRenderWidth(),c=this._sourceTexture.getRenderHeight();h.onApply=(s=u,n=c,e=>{e.setTexture("sourceTexture",this._sourceTexture),e.setFloat2("texSize",s,n)}),this._reductionSteps.push(h);let d=1;for(;u>1||c>1;){let e=new aL("Reduction phase "+d,"minmaxRedux",["texSize"],null,{width:u=Math.max(Math.round(u/2),1),height:c=Math.max(Math.round(c/2),1)},null,1,l.getEngine(),!1,"#define "+(1==u&&1==c?"LAST":1==u||1==c?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=(a=u,o=c,e=>{1==a||1==o?e.setInt2("texSize",a,o):e.setFloat2("texSize",a,o)}),this._reductionSteps.push(e),d++,1==u&&1==c){let t=(e,t,i)=>{let r=new Float32Array(4*e*t),s={min:0,max:0};return()=>{l.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),s.min=r[0],s.max=r[1],this.onAfterReductionPerformed.notifyObservers(s)}};e.onAfterRenderObservable.add(t(u,c,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var e,t;let i=this._camera.getScene().getEngine();null===(e=i._debugPushGroup)||void 0===e||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),null===(t=i._debugPopGroup)||void 0===t||t.call(i,1)}),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return fD.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),(t!=this._minDistance||i!=this._maxDistance)&&this.setMinMaxDistance(t,i)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return null!==(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)&&void 0!==i?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(null===(t=this._depthReducer)||void 0===t?void 0:t.depthRenderer)&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,n=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,a=t+s*r,o=t+n*r,l=o-a,h=o/a;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===fv.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==fv.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;let r=this._getCamera();if(!r)return;let s=this.getShadowMap();if(!s)return;let n=s.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===fv.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,s),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===fv.FILTER_PCSS){for(let e=0;enew fD(e,t,void 0,i));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}fD._FrustumCornersNDCSpace=[new t5(-1,1,-1),new t5(1,1,-1),new t5(1,-1,-1),new t5(-1,-1,-1),new t5(-1,1,1),new t5(1,1,1),new t5(1,-1,1),new t5(-1,-1,1)],fD.CLASSNAME="CascadedShadowGenerator",fD.DEFAULT_CASCADES_COUNT=4,fD.MIN_CASCADES_COUNT=2,fD.MAX_CASCADES_COUNT=4,fD._SceneComponentInitialization=e=>{throw iL("ShadowGeneratorSceneComponent")},tW.AddParser(sb.NAME_SHADOWGENERATOR,(e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i{let t=e._getComponent(sb.NAME_SHADOWGENERATOR);t||(t=new fO(e),e._addComponent(t))},i0.AddNodeConstructor("Light_Type_0",(e,t)=>()=>new fN(e,t5.Zero(),t));class fN extends d4{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return nj.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new t5(1,0,0);case 1:return new t5(-1,0,0);case 2:return new t5(0,-1,0);case 3:return new t5(0,1,0);case 4:return new t5(0,0,1);case 5:return new t5(0,0,-1)}return t5.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;let s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;t7.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:s,a?s: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}}iZ([iW()],fN.prototype,"shadowAngle",null);class fF{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{let e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";let e=`@-webkit-keyframes spin1 {\ + 0% { -webkit-transform: rotate(0deg);} + 100% { -webkit-transform: rotate(360deg);} + }\ + @keyframes spin1 {\ + 0% { transform: rotate(0deg);} + 100% { transform: rotate(360deg);} + }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);let t=!!window.SVGSVGElement,i=new Image;fF.DefaultLogoUrl?i.src=fF.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";let r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";let s=new Image;if(fF.DefaultSpinnerUrl?s.src=fF.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!t){let e={w:16,h:18.5},t={w:30,h:30};i.style.width=`${e.w}vh`,i.style.height=`${e.h}vh`,i.style.left=`calc(50% - ${e.w/2}vh)`,i.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${t.w}vh`,s.style.height=`${t.h}vh`,s.style.left=`calc(50% - ${t.w/2}vh)`,s.style.top=`calc(50% - ${t.h/2}vh)`}r.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}fF.DefaultLogoUrl="",fF.DefaultSpinnerUrl="",nC.DefaultLoadingScreenFactory=e=>new fF(e);class fw{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";let n=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),a=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),o=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s);return{front:n,back:a,left:o,right:this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),up:this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),down:this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s),size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,n=!1){let a=new ArrayBuffer(e*e*12),o=new Float32Array(a),l=n?Math.max(1,Math.round(r/4/e)):1,h=1/l,u=h*h,c=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),p=1/e,_=0;for(let n=0;nMath.PI;)s-=2*Math.PI;let a=s/Math.PI,o=Math.round((a=.5*a+.5)*i);o<0?o=0:o>=i&&(o=i-1);let l=Math.round(n/Math.PI*r);l<0?l=0:l>=r&&(l=r-1);let h=r-l-1;return{r:t[h*i*3+3*o+0],g:t[h*i*3+3*o+1],b:t[h*i*3+3*o+2]}}}fw.FACE_LEFT=[new t5(-1,-1,-1),new t5(1,-1,-1),new t5(-1,1,-1),new t5(1,1,-1)],fw.FACE_RIGHT=[new t5(1,-1,1),new t5(-1,-1,1),new t5(1,1,1),new t5(-1,1,1)],fw.FACE_FRONT=[new t5(1,-1,-1),new t5(1,-1,1),new t5(1,1,-1),new t5(1,1,1)],fw.FACE_BACK=[new t5(-1,-1,1),new t5(-1,-1,-1),new t5(-1,1,1),new t5(-1,1,-1)],fw.FACE_DOWN=[new t5(1,1,-1),new t5(1,1,1),new t5(-1,1,-1),new t5(-1,1,1)],fw.FACE_UP=[new t5(-1,-1,-1),new t5(-1,-1,1),new t5(1,-1,-1),new t5(1,-1,1)];class fL{static _Ldexp(e,t){return t>1023?898846567431158e293*e*Math.pow(2,t-1023):t<-1074?5e-324*e*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,r,s,n){s>0?(s=this._Ldexp(1,s-136),e[n+0]=t*s,e[n+1]=i*s,e[n+2]=r*s):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",r="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:a+=r.length+1}}static GetCubeMapTextureData(e,t,i=!1){let r=new Uint8Array(e),s=this.RGBE_ReadHeader(r),n=this.RGBE_ReadPixels(r,s);return fw.ConvertPanoramaToCubemap(n,s.width,s.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i,r,s,n,a,o=t.height,l=t.width,h=t.dataPosition,u=0,c=0,d=0,p=new ArrayBuffer(4*l),_=new Uint8Array(p),f=new ArrayBuffer(t.width*t.height*12),m=new Float32Array(f);for(;o>0;){if(i=e[h++],r=e[h++],s=e[h++],n=e[h++],2!=i||2!=r||128&s||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((s<<8|n)!=l)throw"HDR Bad header format, wrong scan line width";for(d=0,u=0;d<4;d++)for(c=(d+1)*l;u128){if(0==(a=i-128)||a>c-u)throw"HDR Bad Format, bad scanline data (run)";for(;a-- >0;)_[u++]=r}else{if(0==(a=i)||a>c-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=r,--a>0)for(let t=0;t0;){for(a=0;a +#include +#include +#include +uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;rO.ShadersStore.hdrFilteringPixelShader=fU;class fV{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);let i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){let t=e.getSize().width,i=tK.ILog2(t)+1,r=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();let n=e.getInternalTexture();n&&this._engine.updateTextureSamplingMode(3,n,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let a=[[new t5(0,0,-1),new t5(0,-1,0),new t5(1,0,0)],[new t5(0,0,1),new t5(0,-1,0),new t5(-1,0,0)],[new t5(1,0,0),new t5(0,0,1),new t5(0,1,0)],[new t5(1,0,0),new t5(0,0,-1),new t5(0,-1,0)],[new t5(1,0,0),new t5(0,-1,0),new t5(0,0,1)],[new t5(-1,0,0),new t5(0,-1,0),new t5(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",a[e][0]),r.setVector3("right",a[e][1]),r.setVector3("front",a[e][2]);for(let n=0;n{this._effectRenderer=new aJ(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(ig.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class fk extends n3{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(t7.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,n=!1,a=!1,o=null,l=null,h=!1){var u;if(super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=t5.Zero(),this.onLoadObservable=new tj,!e)return;this._coordinatesMode=n6.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=t7.Identity(),this._prefilterOnLoad=a,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),o&&o()},this._onError=l,this.gammaSpace=n,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?ss.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(null===(u=this.getScene())||void 0===u?void 0:u.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture()}getClassName(){return"HDRCubeTexture"}_loadTexture(){let e=this._getEngine(),t=e.getCaps(),i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){let t=this._onLoad,i=new fV(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;let t=fL.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){let e=cn.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}let r=[],s=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));let a=t[fk._FacesMapping[e]];if(this.gammaSpace||n||s){for(let e=0;e255){let e=255/n;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}}n?r.push(n):s?r.push(s):r.push(a)}return r},null,this._onLoad,this._onError)}clone(){let e=new fk(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let r=null;return e.name&&!e.isRenderTarget&&((r=new fk(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=t5.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=t5.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}fk._FacesMapping=["right","left","up","down","front","back"],t0["BABYLON.HDRCubeTexture"]=fk;class fG{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let 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,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new tj,this._onDataLayoutChanged=new tj,this._animationPropertiesOverride=null,this._scene=i||t2.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){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){let e=i$.Clone(()=>new fG(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(){let 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())),i$.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){let i=new fG(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=[],this._targetInfluenceChangedObservers=[],this._targetDataLayoutChangedObservers=[],this._activeTargets=new sa(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=[],this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,e||(e=t2.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}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(){var e;return fW.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(null===(e=this._scene)||void 0===e?void 0:e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}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){let 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)}clone(){let e=new fW(this._scene);for(let t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){let e={};for(let t of(e.id=this.uniqueId,e.targets=[],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 i=-1;for(let e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=fW.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;let r=e.getPositions();if(r){let e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e){ig.Error("Incompatible target. Targets must all have the same vertices count.");return}}}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;ee&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){let 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();let e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4),i=0;for(let r=0;r-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new fW(t);for(let r of(i._uniqueId=e.id,e.targets))i.addTarget(fG.Parse(r,t));return i}}fW.EnableTextureStorage=!0,fW.MaxActiveMorphTargetsInVertexAttributeMode=8;class fH{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=t5.Zero(),this._hitPointWorld=t5.Zero(),this._rayFromWorld=t5.Zero(),this._rayToWorld=t5.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=null!=i?i:-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=t5.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=t5.Zero(),t=t5.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0}}class fX{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw iL("CannonJSPlugin")}constructor(e,t=fX.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new t5(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach(function(e){e.dispose()}),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){let t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){let r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){let r=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach(e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)}),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e);if(!t){ig.Warn("It was not possible to create a physics body for this object.");return}let i=e.physicsBody;i&&this.removePhysicsBody(e);let r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},n=e.getParam("nativeOptions");for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(s[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(t){let r=i[t];e.physicsBody[t].set(r.x,r.y,r.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){let i=t=>{if(!t.rotationQuaternion)return;let r=t.getPhysicsImpostor();if(r&&r.parent!==e&&t.parent){let i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);r.physicsBody&&(this.removePhysicsBody(r),r.physicsBody=null),r.parent=e,r.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(r),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=r.getParam("mass")}t.getChildMeshes(!0).filter(e=>!!e.physicsImpostor).forEach(i)};t.filter(e=>!!e.physicsImpostor).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case ad.HingeJoint:case ad.Hinge2Joint:t=new this.BJSCANNON.HingeConstraint(i,r,n);break;case ad.DistanceJoint:t=new this.BJSCANNON.DistanceConstraint(i,r,s.maxDistance||2);break;case ad.SpringJoint:t=new this.BJSCANNON.Spring(i,r,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break;case ad.LockJoint:t=new this.BJSCANNON.LockConstraint(i,r,n);break;case ad.PointToPointJoint:case ad.BallAndSocketJoint:default:t=new this.BJSCANNON.PointToPointConstraint(i,n.pivotA,r,n.pivotB,n.maxForce)}t.collideConnected=!!s.collision,e.joint.physicsJoint=t,e.joint.type!==ad.SpringJoint?this.world.addConstraint(t):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){t.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==ad.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r1e3*i));e++);this.time+=r;let o=this.time%i/i,l=this.bodies;for(let i=0;i!==l.length;i++){let r=l[i];r.type!==t.Body.STATIC&&r.sleepState!==t.Body.SLEEPING?(r.position.vsub(r.previousPosition,e),e.scale(o,e),r.position.vadd(e,r.interpolatedPosition)):(r.interpolatedPosition.set(r.position.x,r.position.y,r.position.z),r.interpolatedQuaternion.set(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}fX.DefaultPluginFactory=()=>new fY;class fj{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=t5.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new fH}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach(function(e){e.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e});let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}let e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];if(!e||!t){i=i.next;continue}e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){let r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){ig.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){var t;let i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach(function(e){e.physicsImpostor&&r.push(e.physicsImpostor)});let s=e=>Math.max(e,.001),n=new t8;r.forEach(t=>{if(!t.object.rotationQuaternion)return;let r=t.object.rotationQuaternion;n.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);let a=n.toEulerAngles(),o=t.getObjectExtents();if(t===e){let t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{let e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(57.29577951308232*a.x,57.29577951308232*a.y,57.29577951308232*a.z)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case ap.ParticleImpostor:ig.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case ap.SphereImpostor:{let e=o.x,t=o.y,r=o.z,n=Math.max(s(e),s(t),s(r))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case ap.CylinderImpostor:{let e=s(o.x)/2,t=s(o.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case ap.PlaneImpostor:case ap.BoxImpostor:default:{let e=s(o.x),t=s(o.y),r=s(o.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r)}}t.object.rotationQuaternion=r}),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n=s.nativeParams||{},a={body1:i,body2:r,axe1:n.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:n.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:n.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:n.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:n.min,max:n.max,collision:n.collision||s.collision,spring:n.spring,world:this.world};switch(e.joint.type){case ad.BallAndSocketJoint:t="jointBall";break;case ad.SpringJoint:ig.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"),a.min=s.length||a.min,a.max=Math.max(a.min,a.max);case ad.DistanceJoint:t="jointDistance",a.max=s.maxDistance;break;case ad.PrismaticJoint:t="jointPrisme";break;case ad.SliderJoint:t="jointSlide";break;case ad.WheelJoint:t="jointWheel";break;case ad.HingeJoint:default:t="jointHinge"}a.type=t,e.joint.physicsJoint=this.world.add(a)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){ig.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{let t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){let t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.linearVelocity;return t?new t5(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new t5(t.x,t.y,t.z):null}setBodyMass(e,t){let i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?ig.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){let i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){let i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return ig.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){ig.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class fK{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new t8,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new t5,this._tmpContactNormal=new t5,this._tmpVec3=new t5,this._tmpMatrix=new t7,"function"==typeof t){ig.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}if(this.bjsAMMO=t,!this.isSupported()){ig.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{let t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new fH,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(i))for(let e of i._onPhysicsCollideCallbacks)for(let t of e.otherImpostors)(i.physicsBody.isActive()||t.physicsBody.isActive())&&this._isImpostorPairInContact(i,t)&&(i.onCollide({body:t.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),t.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===ap.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){let t,i,r,s;let n=e.physicsBody.get_m_nodes(),a=n.size(),o=[];for(let e=0;e{this.bjsAMMO.destroy(e)}),e._pluginData.toDispose=[]))}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData;switch(s.mainPivot||(s.mainPivot=new t5(0,0,0)),s.connectedPivot||(s.connectedPivot=new t5(0,0,0)),e.joint.type){case ad.DistanceJoint:{let e=s.maxDistance;e&&(s.mainPivot=new t5(0,-e/2,0),s.connectedPivot=new t5(0,e/2,0)),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case ad.HingeJoint:{s.mainAxis||(s.mainAxis=new t5(0,0,0)),s.connectedAxis||(s.connectedAxis=new t5(0,0,0));let e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),n=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);t=new this.bjsAMMO.btHingeConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,n);break}case ad.BallAndSocketJoint:t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:ig.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(t,!e.joint.jointData.collision),e.joint.physicsJoint=t}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s,n=i.getIndices();n||(n=[]);let a=i.getVerticesData(sf.PositionKind);if(a||(a=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?t8.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):t8.Identity(),t7.Compose(t5.One(),e,t.position).invertToRef(this._tmpMatrix),s=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else t7.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),s=this._tmpMatrix;let o=n.length/3;for(let t=0;t{r+=this._addMeshVerts(e,t,i)})}return r}_softVertexData(e){let t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(sf.PositionKind);i||(i=[]);let r=t.getVerticesData(sf.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);let s=[],n=[];for(let e=0;ee*e).reduce((e,t)=>e+t))i=(t=s.length)/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;let r=e.getParam("path");if(null===e.getParam("shape"))return ig.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;i=(t=r.length)-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let a=e.getParam("fixedPoints");a=a>3?3:a;let o=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,a);return o.get_m_cfg().set_collisions(17),o}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n=i.getVerticesData(sf.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);let a=s.length/3;for(let t=0;t{r+=this._addHullVerts(e,t,i)})}return r}_createShape(e,t=!1){let i;let r=e.object,s=e.getObjectExtents();if(!t){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];i=new this.bjsAMMO.btCompoundShape;let r=0;if(t.forEach(e=>{let t=e.getPhysicsImpostor();if(t){if(t.type==ap.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";let s=this._createShape(t),n=e.parent.getWorldMatrix().clone(),a=new t5;n.decompose(a),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*a.x,e.position.y*a.y,e.position.z*a.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,s),t.dispose(),r++}}),r>0){if(e.type!=ap.NoImpostor){let t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,t))}return i}this.bjsAMMO.destroy(i),i=null}switch(e.type){case ap.SphereImpostor:if(tK.WithinEpsilon(s.x,s.y,1e-4)&&tK.WithinEpsilon(s.x,s.z,1e-4))i=new this.bjsAMMO.btSphereShape(s.x/2);else{let e=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(e,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case ap.CapsuleImpostor:{let e=s.x/2;i=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case ap.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case ap.PlaneImpostor:case ap.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case ap.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)i=this.onCreateCustomMeshImpostor(e);else{let t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t),i=0==this._addMeshVerts(t,r,r)?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case ap.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)i=this.onCreateCustomConvexHullImpostor(e);else{let t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,r,r)?(e._pluginData.toDispose.push(t),i=new this.bjsAMMO.btCompoundShape):i=t}break;case ap.NoImpostor:i=new this.bjsAMMO.btSphereShape(s.x/2);break;case ap.CustomImpostor:i=this._createCustom(e);break;case ap.SoftbodyImpostor:i=this._createSoftbody(e);break;case ap.ClothImpostor:i=this._createCloth(e);break;case ap.RopeImpostor:i=this._createRope(e);break;default:ig.Warn("The impostor type is not currently supported by the ammo plugin.")}return i}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>.001||Math.abs(r.getOrigin().y()-t.y)>.001||Math.abs(r.getOrigin().z()-t.z)>.001||Math.abs(r.getRotation().x()-i.x)>.001||Math.abs(r.getRotation().y()-i.y)>.001||Math.abs(r.getRotation().z()-i.z)>.001||Math.abs(r.getRotation().w()-i.w)>.001){if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){let t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(!(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity()))return null;let i=new t5(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(!(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity()))return null;let i=new t5(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(ig.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===ap.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):ig.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(ig.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):ig.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(ig.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):ig.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(ig.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):ig.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,n=!1){let a=e.segments;e.physicsBody.appendAnchor(Math.round((a-1)*i)+a*(a-1-Math.round((a-1)*r)),t.physicsBody,n,s)}appendHook(e,t,i,r=1,s=!1){let n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){ig.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){ig.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){let i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);let r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}fK._DISABLE_COLLISION_FLAG=4,fK._KINEMATIC_FLAG=2,fK._DISABLE_DEACTIVATION_FLAG=4,tW.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return -1;let t=this.reflectionProbes.indexOf(e);return -1!==t&&this.reflectionProbes.splice(t,1),t},tW.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class f${constructor(e,t,i,r=!0,s=!1,n=!1){let a;if(this.name=e,this._viewMatrix=t7.Identity(),this._target=t5.Zero(),this._add=t5.Zero(),this._invertYAxis=!1,this.position=t5.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){let e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new a5(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;let l=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);let t=i.useRightHandedSystem?t7.LookAtRHToRef:t7.LookAtLHToRef,r=i.useRightHandedSystem?t7.PerspectiveFovRH:t7.PerspectiveFovLH;t(this.position,this._target,t5.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position}),this._renderTargetTexture.onBeforeBindObservable.add(()=>{var t,r;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(r=(t=i.getEngine())._debugPushGroup)||void 0===r||r.call(t,`reflection probe generation for ${e}`,1),a=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=a,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),null===(t=(e=i.getEngine())._debugPopGroup)||void 0===t||t.call(e,1)})}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){let e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){let e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){let e=i$.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;ir||new f$(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i)).cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}}iZ([iK()],f$.prototype,"_attachedMesh",void 0),iZ([ij()],f$.prototype,"position",void 0);class fq{}fq.LoaderInjectedPhysicsEngine=void 0;let fQ={},fZ={},fJ=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,n=t.materials.length;s{for(let r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},f1=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),f2=(e,t)=>{if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){let i=t._waitingData.lods.ids,r=t.isEnabled(!1);if(t._waitingData.lods.distances){let s=t._waitingData.lods.distances;if(s.length>=i.length){let n=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let r=0;r0&&t.addLODLevel(n,null),!0===r&&t.setEnabled(!0)}else ss.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},f3=(e,t,i)=>{if("number"!=typeof e){let r=i.getLastEntryById(e);return r&&null!=t?r.instances[parseInt(t)]:r}let r=fQ[e];return r&&null!=t?r.instances[parseInt(t)]:r},f4=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):fZ[e],f5=(e,t,i,r,s=!1)=>{let n=new nq(e),a="importScene has failed JSON parse";try{let r,s;var o=JSON.parse(t);a="";let l=a_.loggingLevel===a_.DETAILED_LOGGING;if(void 0!==o.environmentTexture&&null!==o.environmentTexture){let t=void 0===o.isPBR||o.isPBR;if(o.environmentTextureType&&"BABYLON.HDRCubeTexture"===o.environmentTextureType){let r=o.environmentTextureSize?o.environmentTextureSize:128,s=new fk((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,r,!0,!t,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(s.rotationY=o.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof o.environmentTexture){let t=po.Parse(o.environmentTexture,e,i);e.environmentTexture=t}else if(o.environmentTexture.endsWith(".env")){let t=new po((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}else{let t=po.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}if(!0===o.createDefaultSkybox){let i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=o.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}n.environmentTexture=e.environmentTexture}if(void 0!==o.environmentIntensity&&null!==o.environmentIntensity&&(e.environmentIntensity=o.environmentIntensity),void 0!==o.lights&&null!==o.lights)for(r=0,s=o.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==o.multiMaterials&&null!==o.multiMaterials)for(r=0,s=o.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})}if(void 0!==o.morphTargetManagers&&null!==o.morphTargetManagers)for(let t of o.morphTargetManagers){let i=fW.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==o.skeletons&&null!==o.skeletons)for(r=0,s=o.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)})}if(void 0!==o.transformNodes&&null!==o.transformNodes)for(r=0,s=o.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach(i=>{t.subMaterials.push(f4(i,e))}),t._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(t=>{null!==t._waitingMaterialId&&(t.material=f4(t._waitingMaterialId,e),t._waitingMaterialId=null)}),r=0,s=e.skeletons.length;r{if(t._waitingTransformNodeId){let i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}}),t._hasWaitingData=null)}for(r=0,s=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""}),tW.Parse(o,e,n,i),r=0,s=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,n,a,o)=>{var l;let h="importMesh has failed JSON parse";try{var u=JSON.parse(i);h="";let o=a_.loggingLevel===a_.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;let c=[],d=new Map,p=[];if(void 0!==u.transformNodes&&null!==u.transformNodes)for(let e=0,i=u.transformNodes.length;e{!0!==e&&u.geometries[i]&&Array.isArray(u.geometries[i])&&u.geometries[i].forEach(s=>{s.id===l.geometryId&&("vertexData"===i&&nT.Parse(s,t,r),e=!0)})}),!1===e&&ig.Warn("Geometry not found for mesh "+l.id)}if(l.materialUniqueId||l.materialId){let e=l.materialUniqueId?f:_,i=-1!==e.indexOf(l.materialUniqueId||l.materialId);if(!1===i&&void 0!==u.multiMaterials&&null!==u.multiMaterials){let s=(i,s)=>{e.push(i);let n=fJ(s,u,t,r);n&&n.material&&(fZ[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,h+="\n Material "+n.material.toString(o))};for(let r=0,n=u.multiMaterials.length;rs(e,t=>t.uniqueId===e)):n.materials.forEach(e=>s(e,t=>t.id===e)),e.push(n.uniqueId||n.id);let r=nU.ParseMultiMaterial(n,t);fZ[n.uniqueId||n.id]=r,r&&(i=!0,h+="\n Multi-Material "+r.toString(o));break}}}if(!1===i){e.push(l.materialUniqueId||l.materialId);let i=fJ(e=>l.materialUniqueId&&e.uniqueId===l.materialUniqueId||e.id===l.materialId,u,t,r);i&&i.material?(fZ[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,h+="\n Material "+i.material.toString(o)):ig.Warn("Material not found for mesh "+l.id)}}if(null!==l.skeletonId&&void 0!==l.skeletonId&&-1!==u.skeletonId&&void 0!==u.skeletons&&null!==u.skeletons&&!(n.indexOf(l.skeletonId)>-1))for(let e=0,i=u.skeletons.length;e-1&&void 0!==u.morphTargetManagers&&null!==u.morphTargetManagers&&!(m.indexOf(l.morphTargetManagerId)>-1))for(let e=0,i=u.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach(i=>{e.subMaterials.push(f4(i,t))}),e._waitingSubMaterialsUniqueIds=[]}),t.meshes.forEach(e=>{null!==e._waitingMaterialId&&(e.material=f4(e._waitingMaterialId,t),e._waitingMaterialId=null)});for(let e=0,i=t.transformNodes.length;e-1&&p.splice(e,1)}i._waitingParentId=null}i._waitingData.lods&&f2(t,i)}for(let e of p)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){let i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}}),i._hasWaitingData=null)}for(let e=0,r=t.meshes.length;e{e._loadedUniqueId=""}),!0}catch(t){let e=f1("importMesh",u?u.producer:"Unknown")+h;if(o)o(e,t);else throw ig.Log(e),t}finally{null!==h&&a_.loggingLevel!==a_.NO_LOGGING&&ig.Log(f1("importMesh",u?u.producer:"Unknown")+(a_.loggingLevel!==a_.MINIMAL_LOGGING?h:"")),fZ={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var n=JSON.parse(t);if(s="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!a_.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=il.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=io.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=t5.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),n.fogMode&&0!==n.fogMode)switch(e.fogMode=n.fogMode,e.fogColor=io.FromArray(n.fogColor),e.fogStart=n.fogStart,e.fogEnd=n.fogEnd,e.fogDensity=n.fogDensity,s+=" Fog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===fY.name?t=new fY(void 0,void 0,fq.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===fj.name?t=new fj(void 0,fq.LoaderInjectedPhysicsEngine):("ammo"===n.physicsEngine||n.physicsEngine===fK.name)&&(t=new fK(void 0,fq.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";let i=n.physicsGravity?t5.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}if(void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!f5(e,t,i,r,!0))return!1;return n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0}catch(t){let e=f1("importScene",n?n.producer:"Unknown")+s;if(r)r(e,t);else throw ig.Log(e),t}finally{null!==s&&a_.loggingLevel!==a_.NO_LOGGING&&ig.Log(f1("importScene",n?n.producer:"Unknown")+(a_.loggingLevel!==a_.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>f5(e,t,i,r)});class f6{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,nC.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||io.White(),this.rightColor=e.rightColor||io.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){let e=new f6;return iP.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new f6({isEnabled:e.isEnabled,leftColor:io.FromArray(e.leftColor),rightColor:io.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}i$._FresnelParametersParser=f6.Parse;class f8 extends _u{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new io(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}iZ([iW(),iz("_markAllSubMeshesAsLightsDirty")],f8.prototype,"maxSimultaneousLights",void 0),iZ([iW(),iz("_markAllSubMeshesAsLightsDirty")],f8.prototype,"disableLighting",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],f8.prototype,"environmentTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],f8.prototype,"invertNormalMapX",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],f8.prototype,"invertNormalMapY",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],f8.prototype,"normalTexture",void 0),iZ([iX("emissive"),iz("_markAllSubMeshesAsTexturesDirty")],f8.prototype,"emissiveColor",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty")],f8.prototype,"emissiveTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],f8.prototype,"occlusionStrength",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],f8.prototype,"occlusionTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],f8.prototype,"alphaCutOff",void 0),iZ([iW()],f8.prototype,"doubleSided",null),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty",null)],f8.prototype,"lightmapTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],f8.prototype,"useLightmapAsShadowmap",void 0);class f7 extends f8{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){let t=i$.Clone(()=>new f7(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){let e=i$.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){let r=i$.Parse(()=>new f7(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}iZ([iX(),iz("_markAllSubMeshesAsTexturesDirty","_albedoColor")],f7.prototype,"baseColor",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],f7.prototype,"baseTexture",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],f7.prototype,"metallic",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],f7.prototype,"roughness",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],f7.prototype,"metallicRoughnessTexture",void 0),t0["BABYLON.PBRMetallicRoughnessMaterial"]=f7;class f9 extends f8{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){let t=i$.Clone(()=>new f9(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){let e=i$.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){let r=i$.Parse(()=>new f9(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}iZ([iX("diffuse"),iz("_markAllSubMeshesAsTexturesDirty","_albedoColor")],f9.prototype,"diffuseColor",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],f9.prototype,"diffuseTexture",void 0),iZ([iX("specular"),iz("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],f9.prototype,"specularColor",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty","_microSurface")],f9.prototype,"glossiness",void 0),iZ([iH(),iz("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],f9.prototype,"specularGlossinessTexture",void 0),t0["BABYLON.PBRSpecularGlossinessMaterial"]=f9;class me extends n3{constructor(e,t,i=null){if(super(t),!e)return;if(this._textureMatrix=t7.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{let e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){let e;let t=this._getEngine();e=t._features.support3DTextures?t.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=e,this._texture.isReady=!1,this.isCube=!1,this.is3D=t._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;let i=i=>{let r;if("string"!=typeof i)return;let s=null,n=null,a=i.split("\n"),o=0,l=0,h=0,u=0,c=0;for(let e=0;e0&&(e+1)%4==0)s[e]=255;else{let t=n[e];s[e]=t/c*255}e.is3D?(e.updateSize(o,o,o),t.updateRawTexture3D(e,s,5,!1)):(e.updateSize(o*o,o),t.updateRawTexture(e,s,5,!1)),e.isReady=!0,this._triggerOnLoad()},r=this.getScene();return r?r._loadFile(this.url,i):t._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){let e=new me(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&((i=new me(e.name,t)).name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}me._NoneEmptyLineRegex=/\S+/,t0["BABYLON.ColorGradingTexture"]=me;class mt extends n3{constructor(e,t,i,r=!1,s=!0,n=null,a=null,o=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw Error("Image url is not set");this._coordinatesMode=n6.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=o,this._noMipmap=r,this.gammaSpace=s,this._onLoad=n,this._onError=a,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?ss.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){let i=this.getScene();if(!i)return;let r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r;let s=document.createElement("canvas");r4(this.url,t=>{this._width=t.width,this._height=t.height,s.width=this._width,s.height=this._height;let i=s.getContext("2d");i.drawImage(t,0,0);let r=i.getImageData(0,0,t.width,t.height);this._buffer=r.data.buffer,s.remove(),e()},(e,s)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,s)},i?i.offlineProvider:null)}_loadTexture(){let e=this.getScene();if(!e)return;let t=(()=>{let e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=fw.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){let r=t[mt._FacesMapping[e]];i.push(r)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){let t=new DataView(e),i=new Float32Array(3*e.byteLength/4),r=0;for(let s=0;st.length){ig.Error("Unable to load TGA file - Not enough data");return}u+=c.id_length;let d=!1,p=!1,_=!1;switch(c.image_type){case 9:d=!0;case 1:p=!0;break;case 10:d=!0;case 2:break;case 11:d=!0;case 3:_=!0}let f=c.pixel_size>>3,m=c.width*c.height*f;if(p&&(r=t.subarray(u,u+=c.colormap_length*(c.colormap_size>>3))),d){let e,r,s;i=new Uint8Array(m);let n=0,a=new Uint8Array(f);for(;u>4){default:case 2:s=0,a=1,h=c.width,n=0,o=1,l=c.height;break;case 0:s=0,a=1,h=c.width,n=c.height-1,o=-1,l=-1;break;case 3:s=c.width-1,a=-1,h=-1,n=0,o=1,l=c.height;break;case 1:s=c.width-1,a=-1,h=-1,n=c.height-1,o=-1,l=-1}let g=mn["_getImageData"+(_?"Grey":"")+c.pixel_size+"bits"](c,r,i,n,o,l,s,a,h);e.getEngine()._uploadDataToTextureDirectly(e,g)}mi._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};let mn={GetTGAHeader:mr,UploadContent:ms,_getImageData8bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+3]=255,f[(p+h*_)*4+2]=t[3*c+0],f[(p+h*_)*4+1]=t[3*c+1],f[(p+h*_)*4+0]=t[3*c+2];return f},_getImageData16bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d+=2){let e=((31744&(c=i[d+0]+(i[d+1]<<8)))>>10)*255/31|0,t=((992&c)>>5)*255/31|0,r=(31&c)*255/31|0;f[(p+h*_)*4+0]=e,f[(p+h*_)*4+1]=t,f[(p+h*_)*4+2]=r,f[(p+h*_)*4+3]=32768&c?0:255}return f},_getImageData24bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=3)_[(d+h*p)*4+3]=255,_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2];return _},_getImageData32bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=4)_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2],_[(d+h*p)*4+3]=i[c+3];return _},_getImageDataGrey8bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+0]=c,f[(p+h*_)*4+1]=c,f[(p+h*_)*4+2]=c,f[(p+h*_)*4+3]=255;return f},_getImageDataGrey16bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=2)_[(d+h*p)*4+0]=i[c+0],_[(d+h*p)*4+1]=i[c+0],_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+3]=i[c+1];return _}};class ma{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=mr(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{ms(t,r)})}}nC._TextureLoaders.push(new ma);class mo{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=fL.RGBE_ReadHeader(r),n=fL.RGBE_ReadPixels(r,s),a=s.width*s.height,o=new Float32Array(4*a);for(let e=0;e{let e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,o)})}}nC._TextureLoaders.push(new mo),function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFETC2=1]="cTFETC2",e[e.cTFBC1=2]="cTFBC1",e[e.cTFBC3=3]="cTFBC3",e[e.cTFBC4=4]="cTFBC4",e[e.cTFBC5=5]="cTFBC5",e[e.cTFBC7=6]="cTFBC7",e[e.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",e[e.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",e[e.cTFASTC_4x4=10]="cTFASTC_4x4",e[e.cTFATC_RGB=11]="cTFATC_RGB",e[e.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",e[e.cTFRGBA32=13]="cTFRGBA32",e[e.cTFRGB565=14]="cTFRGB565",e[e.cTFBGR565=15]="cTFBGR565",e[e.cTFRGBA4444=16]="cTFRGBA4444",e[e.cTFFXT1_RGB=17]="cTFFXT1_RGB",e[e.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",e[e.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",e[e.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",e[e.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"}(e0||(e0={}));let ml={JSModuleURL:`${ss._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${ss._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},mh=null,mu=null,mc=0,md=()=>(mh||(mh=new Promise((e,t)=>{mu?e(mu):ss.LoadFileAsync(ss.GetBabylonScriptURL(ml.WasmModuleURL)).then(i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");let r=URL.createObjectURL(new Blob([`(${mg})()`],{type:"application/javascript"}));mu=new Worker(r);let s=i=>{"init"===i.data.action?(mu.removeEventListener("message",s),e(mu)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};mu.addEventListener("message",s),mu.postMessage({action:"init",url:ss.GetBabylonScriptURL(ml.JSModuleURL),wasmBinary:i})}).catch(t)})),mh),mp=(e,t)=>{let i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise((e,r)=>{md().then(()=>{let s=mc++,n=t=>{"transcode"===t.data.action&&t.data.id===s&&(mu.removeEventListener("message",n),t.data.success?e(t.data):r("Transcode is not supported on this device"))};mu.addEventListener("message",n);let a=new Uint8Array(i.byteLength);a.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),mu.postMessage({action:"transcode",id:s,imageData:a,config:t,ignoreSupportedFormats:!1},[a.buffer])},e=>{r(e)})})},m_=(e,t)=>{var i,r;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(r=t._gl)||void 0===r?void 0:r.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},mf=(e,t)=>{let i=e.getEngine();for(let r=0;r{i._releaseTexture(t),m_(e,i)})}else e._invertVScale=!e.invertY,e.width=s.width+3&-4,e.height=s.height+3&-4,e.samplingMode=2,m_(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0)}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[r].levels.length>1;let n=mm.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,m_(e,i),t.fileInfo.images[r].levels.forEach((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,r,s)}),i._features.basisNeedsPOT&&(tK.Log2(e.width)%1!=0||tK.Log2(e.height)%1!=0)&&(ss.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=n6.CLAMP_ADDRESSMODE,e._cachedWrapV=n6.CLAMP_ADDRESSMODE)}}},mm={JSModuleURL:ml.JSModuleURL,WasmModuleURL:ml.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case e0.cTFETC1:i=36196;break;case e0.cTFBC1:i=33776;break;case e0.cTFBC4:i=33779;break;case e0.cTFASTC_4x4:i=37808;break;case e0.cTFETC2:i=37496;break;case e0.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:mp,LoadTextureFromTranscodeResult:mf};function mg(){let e={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFRGB565:14},t=null;onmessage=i=>{if("init"===i.data.action){if(!t){try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}t=BASIS({wasmBinary:i.data.wasmBinary})}null!==t&&t.then(e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})})}else if("transcode"===i.data.action){var r;let t;let s=i.data.config,n=i.data.imageData,a=new BASIS.BasisFile(n),o=function(e){let t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t>2&3],n[h++]=s[l>>4&3],n[h++]=s[l>>6&3]}}return n}(a,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),a):null}(a,e,r,l,h);if(!s){u=!1;break}i.transcodedPixels=s,c.push(i.transcodedPixels.buffer)}}}a.close(),a.delete(),h&&(l=-1),u?postMessage({action:"transcode",success:u,id:i.data.id,fileInfo:o,format:l},c):postMessage({action:"transcode",success:u,id:i.data.id})}}}Object.defineProperty(mm,"JSModuleURL",{get:function(){return ml.JSModuleURL},set:function(e){ml.JSModuleURL=e}}),Object.defineProperty(mm,"WasmModuleURL",{get:function(){return ml.WasmModuleURL},set:function(e){ml.WasmModuleURL=e}});class mv{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=t.getEngine().getCaps();mp(e,{supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}}).then(e=>{let i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;mf(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(e=>{ss.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(e)})}loadData(e,t,i){let r=t.getEngine().getCaps();mp(e,{supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}}).then(e=>{let r=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(r.width,r.height,s,-1!==e.format,()=>{mf(t,e)})}).catch(e=>{ss.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),ss.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,()=>{},!0)})}}nC._TextureLoaders.push(new mv);class mx extends a5{get isSupported(){var e,t;return null!==(t=null===(e=this._engine)||void 0===e?void 0:e.getCaps().drawBuffersExtension)&&void 0!==t&&t}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,r,s,n,a,o,l,h){for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;let i=null===(e=this._renderTarget)||void 0===e?void 0:e.textures;if(i){for(let e=i.length-1;e>=0;e--)this._textures[e]._texture=null;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null}}}class mT{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class mb{constructor(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m;return this.name=e,this.meshes=t,this.scene=r,this.options=i,this.options.map=null!==(s=this.options.map)&&void 0!==s?s:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=null!==(n=this.options.uvsIn)&&void 0!==n?n:sf.UVKind,this.options.uvsOut=null!==(a=this.options.uvsOut)&&void 0!==a?a:sf.UVKind,this.options.layout=null!==(o=this.options.layout)&&void 0!==o?o:mb.LAYOUT_STRIP,this.options.layout===mb.LAYOUT_COLNUM&&(this.options.colnum=null!==(l=this.options.colnum)&&void 0!==l?l:8),this.options.updateInputMeshes=null===(h=this.options.updateInputMeshes)||void 0===h||h,this.options.disposeSources=null===(u=this.options.disposeSources)||void 0===u||u,this._expecting=0,this.options.fillBlanks=null===(c=this.options.fillBlanks)||void 0===c||c,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(d=this.options.customFillColor)&&void 0!==d?d:"black"),this.options.frameSize=null!==(p=this.options.frameSize)&&void 0!==p?p:256,this.options.paddingRatio=null!==(_=this.options.paddingRatio)&&void 0!==_?_:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(f=this.options.paddingMode)&&void 0!==f?f:mb.SUBUV_WRAP,this.options.paddingMode===mb.SUBUV_COLOR&&(this.options.paddingColor=null!==(m=this.options.paddingColor)&&void 0!==m?m:new il(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){let t=this._calculateSize(),i=new t4(1,1).divide(t),r=0,s=this._expecting,n=this.meshes.length,a=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(o,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{r++,d.update(!1);let i=p.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*_.x,t.y*_.y),d.dispose(),n.update(!1),r==s){u(),e();return}},m=a[c]||"_blank";if(n&&null!==n[m]){let e=n[m],t=new Image;e instanceof hO?t.src=e.getContext().canvas.toDataURL("image/png"):t.src=e.url,ss.SetCorsBehavior(t.src,t),t.onload=()=>{p.fillStyle="rgba(0,0,0,0)",p.fillRect(0,0,h,h),d.update(!1),p.setTransform(1,0,0,-1,0,0);let e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)p.drawImage(t,0,0,t.width,t.height,l+o*e[i],l+o*e[i+1]-h,o,o);break;case 1:for(let e=0;e{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length){e();return}let t=0,i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)})}}catch(e){return t(e)}})}dispose(){let e=Object.keys(this.sets);for(let t=0;t{let i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesIndices"===e.name&&t(e));i||(i=new aR("matricesIndices")).setAsAttribute("matricesIndices"),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesWeights"===e.name&&t(e));i||(i=new aR("matricesWeights")).setAsAttribute("matricesWeights"),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.World&&t(e));i||(i=new aR("world")).setAsSystemValue(U.World),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){nw.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&nw.PrepareDefinesForBones(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");let t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});let i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});let r=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 +`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName} * ${i}; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName}; +`,e.compilationString+=`#endif +`,this}}t0["BABYLON.BonesBlock"]=my;class mA extends ax{constructor(e){super(e,N.Vertex),this.registerInput("world0",O.Vector4),this.registerInput("world1",O.Vector4),this.registerInput("world2",O.Vector4),this.registerInput("world3",O.Vector4),this.registerInput("world",O.Matrix,!0),this.registerOutput("output",O.Matrix),this.registerOutput("instanceID",O.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world0"===e.name&&t(e));i||(i=new aR("world0")).setAsAttribute("world0"),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world1"===e.name&&t(e));i||(i=new aR("world1")).setAsAttribute("world1"),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world2"===e.name&&t(e));i||(i=new aR("world2")).setAsAttribute("world2"),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world3"===e.name&&t(e));i||(i=new aR("world3")).setAsAttribute("world3"),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world"===e.name&&t(e));i||(i=new aR("world")).setAsSystemValue(U.World),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let n=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),n=!0),s&&!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)!==i.THIN_INSTANCES&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);let t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);let i=this._outputs[0],r=this._outputs[1],s=this.world0,n=this.world1,a=this.world2,o=this.world3;return e.compilationString+=`#ifdef INSTANCES +`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${n.associatedVariableName}, ${a.associatedVariableName}, ${o.associatedVariableName}); +`,e.compilationString+=`#ifdef THIN_INSTANCES +`,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; +`,e.compilationString+=`#endif +`,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(r,e)+` = float(gl_InstanceID); +`:e.compilationString+=this._declareOutput(r,e)+` = 0.0; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; +`,e.compilationString+=this._declareOutput(r,e)+` = 0.0; +`,e.compilationString+=`#endif +`,this}}t0["BABYLON.InstancesBlock"]=mA;class mR extends ax{constructor(e){super(e,N.Vertex),this.registerInput("position",O.Vector3),this.registerInput("normal",O.Vector3),this.registerInput("tangent",O.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(O.Color4|O.Vector4|O.Vector3),this.registerInput("uv",O.Vector2),this.registerOutput("positionOutput",O.Vector3),this.registerOutput("normalOutput",O.Vector3),this.registerOutput("tangentOutput",O.Vector4),this.registerOutput("uvOutput",O.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new aR("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new aR("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&t(e));i||(i=new aR("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new aR("uv")).setAsAttribute("uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){let t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&nw.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(nw.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){let s=this.position,n=this.normal,a=this.tangent,o=this.uv,l=this.positionOutput,h=this.normalOutput,u=this.tangentOutput,c=this.uvOutput,d=r.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,_=p&&p.supportsNormals&&r.NORMAL,f=p&&p.supportsTangents&&r.TANGENT,m=p&&p.supportsUVs&&r.UV1,g="";(null==p?void 0:p.isUsingTextureForTargets)&&d>0&&(g+=`float vertexID; +`);for(let e=0;e0)for(let t=0;t!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.isSystemValue&&e.systemValue===U.World&&t(e));i||(i=new aR("world")).setAsSystemValue(U.World),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new aR("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&e.type===O.Vector4&&t(e));i||(i=new aR("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var r,s,n,a;let o=this.normal,l=this.tangent,h=o.isConnected;(null===(r=o.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(s=o.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let u=l.isConnected;(null===(n=l.connectInputBlock)||void 0===n?void 0:n.isAttribute)&&!e.isVerticesDataPresent(null===(a=l.connectInputBlock)||void 0===a?void 0:a.name)&&(u=!1);let c=h&&u;i.setValue("TBNBLOCK",c,!0)}_buildBlock(e){super._buildBlock(e);let t=this.normal,i=this.tangent,r=this.world,s=this.TBN,n=this.row0,a=this.row1,o=this.row2;return e.target===N.Fragment&&(e.compilationString+=` + // ${this.name} + vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; + vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); + vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; + mat3 ${s.associatedVariableName} = mat3(${r.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); + `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); +`),e.sharedData.blocksWithDefines.push(this)),this}}t0["BABYLON.TBNBlock"]=mM;class mD extends ax{constructor(e){super(e,N.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",O.Vector4,!1),this.registerInput("worldNormal",O.Vector4,!1),this.registerInput("worldTangent",O.Vector4,!0),this.registerInput("uv",O.Vector2,!1),this.registerInput("normalMapColor",O.Color3,!1),this.registerInput("strength",O.Float,!1),this.registerInput("viewDirection",O.Vector3,!0),this.registerInput("parallaxScale",O.Float,!0),this.registerInput("parallaxHeight",O.Float,!0),this.registerInput("TBN",O.Object,!0,N.VertexAndFragment,new mC("TBN",this,w.Input,mM,"TBNBlock")),this.registerInput("world",O.Matrix,!0),this.registerOutput("output",O.Vector4),this.registerOutput("uvOffset",O.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){let r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new aR("uv")).setAsAttribute(),i.output.connectTo(this.uv)}if(!this.strength.isConnected){let e=new aR("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,n=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let a=null;this.normalMapColor.connectedPoint&&(a=this.normalMapColor.connectedPoint._ownerBlock.samplerName);let o=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&a||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?` +#if !defined(NORMALXYSCALE) +1.0/ +#endif +${e._emitFloat(this.strength.connectInputBlock.value)}`:` +#if !defined(NORMALXYSCALE) +1.0/ +#endif +${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let u={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},c=this.TBN;c.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${c.associatedVariableName}; + #endif + `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[u,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});let d=o&&a?`texture2D(${a}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o&&this.useParallaxOcclusion?a:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${o?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:r.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:o?this.viewDirection.associatedVariableName:"vec3(0.)"},u]}),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; +`+`${this._codeVariableName}.invertY = ${this.invertY}; +${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; +${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; +`}serialize(){let e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}iZ([aE("Invert X axis",L.Boolean,"PROPERTIES",{notifiers:{update:!1}})],mD.prototype,"invertX",void 0),iZ([aE("Invert Y axis",L.Boolean,"PROPERTIES",{notifiers:{update:!1}})],mD.prototype,"invertY",void 0),iZ([aE("Use parallax occlusion",L.Boolean)],mD.prototype,"useParallaxOcclusion",void 0),iZ([aE("Object Space Mode",L.Boolean,"PROPERTIES",{notifiers:{update:!1}})],mD.prototype,"useObjectSpaceNormalMap",void 0),t0["BABYLON.PerturbNormalBlock"]=mD;class mO extends ax{constructor(e){super(e,N.Fragment,!0),this.registerInput("value",O.Float,!0),this.registerInput("cutoff",O.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard; +`,this}}t0["BABYLON.DiscardBlock"]=mO;class mN extends ax{constructor(e){super(e,N.Fragment),this.registerOutput("output",O.Float,N.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===N.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0; +`,this}}t0["BABYLON.FrontFacingBlock"]=mN;class mF extends ax{constructor(e){super(e,N.Fragment),this.registerInput("input",O.AutoDetect,!1),this.registerOutput("dx",O.BasedOnInput),this.registerOutput("dy",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName}); +`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName}); +`),this}}t0["BABYLON.DerivativeBlock"]=mF;class mw extends ax{constructor(e){super(e,N.Fragment),this.registerOutput("xy",O.Vector2,N.Fragment),this.registerOutput("xyz",O.Vector3,N.Fragment),this.registerOutput("xyzw",O.Vector4,N.Fragment),this.registerOutput("x",O.Float,N.Fragment),this.registerOutput("y",O.Float,N.Fragment),this.registerOutput("z",O.Float,N.Fragment),this.registerOutput("w",O.Float,N.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(let i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name}; +`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===N.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}t0["BABYLON.FragCoordBlock"]=mw;class mL extends ax{constructor(e){super(e,N.Fragment),this.registerOutput("xy",O.Vector2,N.Fragment),this.registerOutput("x",O.Float,N.Fragment),this.registerOutput("y",O.Float,N.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){let t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; +`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===N.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}}t0["BABYLON.ScreenSizeBlock"]=mL;class mB extends ax{constructor(e){super(e,N.Fragment),this.registerInput("vector",O.AutoDetect),this.registerInput("worldViewProjection",O.Matrix),this.registerOutput("output",O.Vector2),this.registerOutput("x",O.Float),this.registerOutput("y",O.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.WorldViewProjection&&t(e));i||(i=new aR("worldViewProjection")).setAsSystemValue(U.WorldViewProjection),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;let r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case O.Vector3:e.compilationString+=`vec4 ${s} = ${r} * vec4(${t.associatedVariableName}, 1.0); +`;break;case O.Vector4:e.compilationString+=`vec4 ${s} = ${r} * ${t.associatedVariableName}; +`}return e.compilationString+=`${s}.xy /= ${s}.w;`,e.compilationString+=`${s}.xy = ${s}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${s}.xy; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y; +`),this}}t0["BABYLON.ScreenSpaceBlock"]=mB;class mU extends ax{constructor(e){super(e,N.Fragment),this.registerInput("input",O.Vector2),this.registerInput("strength",O.Float),this.registerInput("center",O.Vector2),this.registerInput("offset",O.Vector2),this.registerOutput("output",O.Vector2),this.registerOutput("x",O.Float),this.registerOutput("y",O.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){let e=new aR("center");e.value=new t4(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){let e=new aR("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){let e=new aR("offset");e.value=new t4(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);let t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` + vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; + float ${i} = ${this.strength.associatedVariableName} * length(${t}); + float ${r} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; + float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; + vec2 ${n} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); + `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n}; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y; +`),this}}t0["BABYLON.TwirlBlock"]=mU;class mV extends ax{constructor(e){super(e,N.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",O.Float),this.registerInput("worldPosition",O.Vector3),this.registerInput("worldNormal",O.Vector3),this.registerInput("worldTangent",O.AutoDetect,!0),this.registerOutput("output",O.Vector4),this.registerOutput("xyz",O.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||ig.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);let i=this.generateInWorldSpace?"":` + vec3 biTangent = cross(normal, tangent); + mat3 TBN = mat3(tangent, biTangent, normal); + `,r=this.generateInWorldSpace?"":` + result = TBN * result; + result = result * vec3(0.5) + vec3(0.5); + `,s=` + vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { + ${i} + ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} + ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} + vec3 worlddX = dFdx(position); + vec3 worlddY = dFdy(position); + vec3 crossX = cross(normal, worlddX); + vec3 crossY = cross(normal, worlddY); + float d = abs(dot(crossY, worlddX)); + vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); + inToNormal.y *= -1.0; + vec3 result = normalize((d * normal) - inToNormal); + ${r} + return vec4(result, 0.); + }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",s,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName}); +`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; +`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; +${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; +${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; +`}serialize(){let e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}iZ([aE("Generate in world space instead of tangent space",L.Boolean,"PROPERTIES",{notifiers:{update:!0}})],mV.prototype,"generateInWorldSpace",void 0),iZ([aE("Force normalization for the worldNormal input",L.Boolean,"PROPERTIES",{notifiers:{update:!0}})],mV.prototype,"automaticNormalizationNormal",void 0),iZ([aE("Force normalization for the worldTangent input",L.Boolean,"PROPERTIES",{notifiers:{update:!0}})],mV.prototype,"automaticNormalizationTangent",void 0),t0["BABYLON.HeightToNormalBlock"]=mV;class mk extends ax{constructor(e){super(e,N.Fragment,!0),this.registerInput("depth",O.Float,!0),this.registerInput("worldPos",O.Vector4,!0),this.registerInput("viewProjection",O.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; +`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` + vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; + float v = p.z / p.w; + #ifndef IS_NDC_HALF_ZRANGE + v = v * 0.5 + 0.5; + #endif + gl_FragDepth = v; + + `:ig.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}t0["BABYLON.FragDepthBlock"]=mk;class mG extends ax{constructor(e){super(e,N.Fragment),this.registerInput("worldPosition",O.Vector4,!1),this.registerInput("viewProjection",O.Matrix,!1),this.registerInput("worldNormal",O.AutoDetect,!0),this.registerOutput("depth",O.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName}; +`,e.compilationString+=`vec3 vPositionWSM; +`,e.compilationString+=`float vDepthMetricSM = 0.0; +`,e.compilationString+=`float zSM; +`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` + #if SM_DEPTHTEXTURE == 1 + #ifdef IS_NDC_HALF_ZRANGE + gl_FragDepth = (clipPos.z / clipPos.w); + #else + gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; + #endif + #endif + `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); +`,this}}t0["BABYLON.ShadowMapBlock"]=mG;class mz extends ax{constructor(e){super(e,N.Fragment,!0),this.registerInput("viewDepth",O.Float,!0),this.registerInput("worldPosition",O.AutoDetect,!0),this.registerInput("viewNormal",O.AutoDetect,!0),this.registerInput("reflectivity",O.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(O.Vector3|O.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(O.Vector3|O.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(O.Vector3|O.Vector4|O.Color3|O.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);let t=this.worldPosition,i=this.viewNormal,r=this.viewDepth,s=this.reflectivity;e.sharedData.blocksWithDefines.push(this);let n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`#ifdef PREPASS_DEPTH\r +`,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${r.associatedVariableName}, 0.0, 0.0, 1.0);\r +`:e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_POSITION\r +`,t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===O.Vector4?t.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_NORMAL\r +`,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===O.Vector4?i.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r +`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===O.Vector4?s.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#endif\r +`,this}}t0["BABYLON.PrePassOutputBlock"]=mz;class mW extends ax{constructor(e){super(e,N.VertexAndFragment,!1),this.registerInput("worldPosition",O.Vector4,!1,N.Vertex),this.registerInput("view",O.Matrix,!1,N.Vertex),this.registerInput("input",O.AutoDetect,!1,N.Fragment),this.registerInput("fogColor",O.AutoDetect,!1,N.Fragment),this.registerOutput("output",O.Color3,N.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.View&&t(e));i||(i=new aR("view")).setAsSystemValue(U.View),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.FogColor&&t(e));i||(i=new aR("fogColor",void 0,O.Color3)).setAsSystemValue(U.FogColor),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){let r=e.getScene();i.setValue("FOG",t.fogEnabled&&nw.GetFogState(e,r))}bind(e,t,i){if(!i)return;let r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===N.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});let t=e._getFreeVariableName("fog"),i=this.input,r=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");let s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG +`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); +`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${r.associatedVariableName}.rgb; +`,e.compilationString+=`#else +${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb; +`,e.compilationString+=`#endif +`}else{let t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz; +`}return this}}t0["BABYLON.FogBlock"]=mW;class mH extends ax{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,ig.Error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?N.Fragment:N.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?N.Fragment:N.Vertex}constructor(e){super(e,N.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",O.Vector4,!1,N.Vertex),this.registerInput("worldNormal",O.Vector4,!1,N.Fragment),this.registerInput("cameraPosition",O.Vector3,!1,N.Fragment),this.registerInput("glossiness",O.Float,!0,N.Fragment),this.registerInput("glossPower",O.Float,!0,N.Fragment),this.registerInput("diffuseColor",O.Color3,!0,N.Fragment),this.registerInput("specularColor",O.Color3,!0,N.Fragment),this.registerInput("view",O.Matrix,!0),this.registerOutput("diffuseOutput",O.Color3,N.Fragment),this.registerOutput("specularOutput",O.Color3,N.Fragment),this.registerOutput("shadow",O.Float,N.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.CameraPosition&&t(e));i||(i=new aR("cameraPosition")).setAsSystemValue(U.CameraPosition),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;let r=e.getScene();if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};nw.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else nw.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;nw.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;let r=i.getScene();this.light?nw.BindLight(this.light,this._lightId,r,e,!0):nw.BindLights(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){let t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));let r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==N.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=`//${this.name}`,i=this.worldPosition,r=i.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${r}; +`,t),e.compilationString+=`${r} = ${i.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):r="v_"+r+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}); +`),e.compilationString+=`lightingInfo info; +`,e.compilationString+=`float shadow = 1.; +`,e.compilationString+=`float aggShadow = 0.; +`,e.compilationString+=`float numLights = 0.; +`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; +`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; +`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),0===this._lightId&&(e.compilationString+=`aggShadow = aggShadow / numLights; +`);let s=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; +`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; +`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = aggShadow; +`),this}serialize(){let e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}iZ([aE("Generate only fragment code",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:mH._OnGenerateOnlyFragmentCodeChanged}})],mH.prototype,"generateOnlyFragmentCode",void 0),t0["BABYLON.LightBlock"]=mH;class mX extends ax{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:t2.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,N.VertexAndFragment),this.registerOutput("source",O.Object,N.VertexAndFragment,new mC("source",this,w.Output,mX,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===N.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!oi.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=n6.Parse(e.texture,t,i))}}t0["BABYLON.ImageSourceBlock"]=mX;class mY extends ax{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:t2.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _IsPrePassTextureBlock(e){return(null==e?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return mY._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!mY._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:t2.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:t2.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?N.Fragment:N.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",O.AutoDetect,!1,N.VertexAndFragment),this.registerInput("source",O.Object,!0,N.VertexAndFragment,new mC("source",this,w.Input,mX,"ImageSourceBlock")),this.registerInput("layer",O.Float,!0),this.registerInput("lod",O.Float,!0),this.registerOutput("rgba",O.Color4,N.Neutral),this.registerOutput("rgb",O.Color3,N.Neutral),this.registerOutput("r",O.Float,N.Neutral),this.registerOutput("g",O.Float,N.Neutral),this.registerOutput("b",O.Float,N.Neutral),this.registerOutput("a",O.Float,N.Neutral),this.registerOutput("level",O.Float,N.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Vector2|O.Vector3|O.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return N.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return N.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===N.Fragment)return N.Fragment;if(e.target===N.Vertex)break;if(e.target===N.Neutral||e.target===N.VertexAndFragment){let t=e.ownerBlock;if(t.target===N.Fragment)return N.Fragment;for(let i of(e=null,t.inputs))if(i.connectedPoint){e=i.connectedPoint;break}}}return N.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){if(e.mode===k.PostProcess){let i=e.getBlockByPredicate(e=>"uv"===e.name&&t(e));i&&i.connectTo(this)}else{let i=e.mode===k.Particle?"particle_uv":"uv",r=e.getInputBlockByPredicate(e=>e.isAttribute&&e.name===i&&t(e));r||(r=new aR("uv")).setAsAttribute(i),r.output.connectTo(this.uv)}}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),void 0==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==N.Fragment}_injectVertexCode(e){let t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName} +`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0)); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,e.compilationString+=`#endif +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}_getUVW(e){var t,i,r;let s=e;if(null!==(r=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==r&&r){let t=this.layer.isConnected?this.layer.associatedVariableName:"0";s=`vec3(${e}, ${t})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){let t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName} +`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix}); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix}); +`,e.compilationString+=`#endif +`}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===N.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===N.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix}); +`;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} + ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); + #endif + `),e.compilationString+=`#ifdef ${this._gammaDefineName} + ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===N.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===N.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; +`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,r,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===N.Vertex||this._fragmentOnly||e.target===N.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===N.Fragment||this._isMixed&&e.target===N.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==N.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((null===(s=null===(r=this._texture)||void 0===r?void 0:r._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));let n=`//${this.name}`;for(let t of(e._emitFunctionFromInclude("helperFunctions",n),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!oi.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=n6.Parse(e.texture,t,i))}}t0["BABYLON.TextureBlock"]=mY;class mj extends ax{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:t2.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?N.Fragment:N.VertexAndFragment)}constructor(e){super(e,N.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new aR("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.World&&t(e));i||(i=new aR("world")).setAsSystemValue(U.World),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.View&&t(e));i||(i=new aR("view")).setAsSystemValue(U.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){let r=this._getTexture();i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize&&(e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)))}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===N.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");let i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; +`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} +${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; +#endif +`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) +${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); +#endif +`),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,e._samplerDeclaration+=`#endif +`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,r=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);let s=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,a=`${this._positionUVWName}`,o=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=` + #ifdef ${this._defineMirroredEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularName} + vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + + #ifdef ${this._defineSphericalName} + vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s}); + #endif + + #ifdef ${this._definePlanarName} + vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + + #ifdef ${this._defineCubicName} + #ifdef ${this._defineLocalCubicName} + vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${o}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); + #else + vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + #endif + + #ifdef ${this._defineProjectionName} + vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s}); + #endif + + #ifdef ${this._defineSkyboxName} + vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${a}, ${s}); + #endif + + #ifdef ${this._defineExplicitName} + vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); + #endif +`;return r||(h+=`#ifdef ${this._defineOppositeZ} + ${this._reflectionVectorName}.z *= -1.0; + #endif +`),i||(h+=` + #ifdef ${this._define3DName} + vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; + #else + vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; + #ifdef ${this._defineProjectionName} + ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; + #endif + ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; + #endif +`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i="vec"+(0===t.length?"4":t.length-1),r=`${i} ${this._reflectionColorName}; + #ifdef ${this._define3DName} +`;return e?r+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; +`:r+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; +`,r+=` + #else +`,e?r+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; +`:r+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; +`,r+=`#endif +`}writeOutputs(e,t){let i="";if(e.target===N.Fragment)for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; +`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){let t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); +`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); +`;return e+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!oi.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=po.Parse(e.texture,t,i):this.texture=n6.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}iZ([aE("Generate only fragment code",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:mj._OnGenerateOnlyFragmentCodeChanged}})],mj.prototype,"generateOnlyFragmentCode",void 0),t0["BABYLON.ReflectionTextureBaseBlock"]=mj;class mK extends mj{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ig.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ig.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?N.Fragment:N.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?N.Fragment:N.Vertex}constructor(e){super(e),this.registerInput("position",O.AutoDetect,!1,N.Vertex),this.registerInput("worldPosition",O.Vector4,!1,N.Vertex),this.registerInput("worldNormal",O.Vector4,!1,N.Fragment),this.registerInput("world",O.Matrix,!1,N.Vertex),this.registerInput("cameraPosition",O.Vector3,!1,N.Fragment),this.registerInput("view",O.Matrix,!1,N.Fragment),this.registerOutput("rgb",O.Color3,N.Fragment),this.registerOutput("rgba",O.Color4,N.Fragment),this.registerOutput("r",O.Float,N.Fragment),this.registerOutput("g",O.Float,N.Fragment),this.registerOutput("b",O.Float,N.Fragment),this.registerOutput("a",O.Float,N.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.CameraPosition&&t(e));i||(i=new aR("cameraPosition")).setAsSystemValue(U.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==N.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);let t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); +`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}t0["BABYLON.ReflectionTextureBlock"]=mK;class m$ extends ax{constructor(e){super(e,N.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",O.AutoDetect,!1,N.VertexAndFragment),this.registerOutput("depth",O.Float,N.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Vector2|O.Vector3|O.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?N.VertexAndFragment:N.Fragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){let i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&!t.connectedPoint.ownerBlock.isAttribute&&e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===O.Vector3?"3":t.type===O.Vector4?"4":"2")),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===N.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}if(this.uv.ownerBlock.target===N.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===N.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===N.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.bindableBlocks.indexOf(this)&&e.sharedData.bindableBlocks.push(this),e.target!==N.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(e=>e.isConnectedInFragmentShader)){for(let t of(e._emit2DSampler(this._samplerName),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){let e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}iZ([aE("Use non linear depth",L.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],m$.prototype,"useNonLinearDepth",void 0),iZ([aE("Store Camera space Z",L.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],m$.prototype,"storeCameraSpaceZ",void 0),iZ([aE("Force 32 bits float",L.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>null==e?void 0:e.disableDepthRenderer()}})],m$.prototype,"force32itsFloat",void 0),t0["BABYLON.SceneDepthBlock"]=m$;class mq extends ax{constructor(e){super(e,N.VertexAndFragment,!0),this.registerInput("worldPosition",O.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return N.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var r,s,n,a,o,l;let h=e.getScene(),u=null!==(r=t.clipPlane)&&void 0!==r?!!r:!!h.clipPlane,c=null!==(s=t.clipPlane2)&&void 0!==s?!!s:!!h.clipPlane2,d=null!==(n=t.clipPlane3)&&void 0!==n?!!n:!!h.clipPlane3,p=null!==(a=t.clipPlane4)&&void 0!==a?!!a:!!h.clipPlane4,_=null!==(o=t.clipPlane5)&&void 0!==o?!!o:!!h.clipPlane5,f=null!==(l=t.clipPlane6)&&void 0!==l?!!l:!!h.clipPlane6;i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",c,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",_,!0),i.setValue("CLIPPLANE6",f,!0)}bind(e,t,i){i&&nN(e,t,i.getScene())}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;if(e.target!==N.Fragment){let i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}t0["BABYLON.ClipPlanesBlock"]=mq;class mQ extends ax{get texture(){return null}set texture(e){}constructor(e,t=N.VertexAndFragment){super(e,t,!1),this.registerOutput("position",O.Object,N.VertexAndFragment,new mC("position",this,w.Output,mX,"ImageSourceBlock")),this.registerOutput("depth",O.Object,N.VertexAndFragment,new mC("depth",this,w.Output,mX,"ImageSourceBlock")),this.registerOutput("normal",O.Object,N.VertexAndFragment,new mC("normal",this,w.Output,mX,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==N.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){let i=t.getScene().enablePrePassRenderer();if(!i)return;let r=i.defaultRT;r.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,r.textures[i.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,r.textures[i.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,r.textures[i.getIndex(6)]))}}t0["BABYLON.PrePassTextureBlock"]=mQ;class mZ extends ax{get endpoints(){return this._endpoints}get target(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==N.VertexAndFragment)return t.target;if(e.connectedPoint.target!==N.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}constructor(e){super(e,N.Neutral),this._endpoints=[],this.registerInput("input",O.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){for(let e of(super.dispose(),this._endpoints))this.detachFromEndpoint(e);this._endpoints=[]}}t0["BABYLON.NodeMaterialTeleportInBlock"]=mZ;class mJ extends ax{constructor(e){super(e,N.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",O.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){(this._target&e)==0&&(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName}; +`)}clone(e,t=""){let i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); +`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}t0["BABYLON.NodeMaterialTeleportOutBlock"]=mJ;class m0 extends ax{constructor(e){super(e,N.Neutral),this.registerInput("left",O.AutoDetect),this.registerInput("right",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(O.Float),this._inputs[1].acceptedConnectionPointTypes.push(O.Float)}getClassName(){return"AddBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; +`,this}}t0["BABYLON.AddBlock"]=m0;class m1 extends ax{constructor(e){super(e,N.Neutral),this.registerInput("input",O.AutoDetect),this.registerInput("factor",O.Float),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; +`,this}}t0["BABYLON.ScaleBlock"]=m1;class m2 extends ax{constructor(e){super(e,N.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; +`+`${this._codeVariableName}.maximum = ${this.maximum}; +`}serialize(){let e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}iZ([aE("Minimum",L.Float)],m2.prototype,"minimum",void 0),iZ([aE("Maximum",L.Float)],m2.prototype,"maximum",void 0),t0["BABYLON.ClampBlock"]=m2;class m3 extends ax{constructor(e){super(e,N.Neutral),this.registerInput("left",O.AutoDetect),this.registerInput("right",O.AutoDetect),this.registerOutput("output",O.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(O.Float),this._inputs[0].excludedConnectionPointTypes.push(O.Matrix),this._inputs[0].excludedConnectionPointTypes.push(O.Vector2),this._inputs[1].excludedConnectionPointTypes.push(O.Float),this._inputs[1].excludedConnectionPointTypes.push(O.Matrix),this._inputs[1].excludedConnectionPointTypes.push(O.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); +`,this}}t0["BABYLON.CrossBlock"]=m3;class m4 extends ax{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),this._outputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),e._emitFunction(i,t,""),this._outputs.forEach(t=>{e.compilationString+=this._declareOutput(t,e)+";\n"}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((t,i)=>{var s,n,a;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(a=null===(n=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===n?void 0:n.samplerName)&&void 0!==a?a:t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0}),this._outputs.forEach((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName}),e.compilationString+=");\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; +`}serialize(){let e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,r;this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=N[e.target],null===(t=e.inParameters)||void 0===t||t.forEach((e,t)=>{let i=O[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,O.Object,!0,N.VertexAndFragment,new mC(e.name,this,w.Input,mX,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})}),null===(i=e.outParameters)||void 0===i||i.forEach((e,t)=>{this.registerOutput(e.name,O[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])}),null===(r=e.inLinkedConnectionTypes)||void 0===r||r.forEach(e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.CameraPosition&&t(e));i||(i=new aR("cameraPosition")).setAsSystemValue(U.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); +`,this}}t0["BABYLON.ViewDirectionBlock"]=gs;class gn extends ax{constructor(e){super(e,N.Neutral),this.registerInput("worldNormal",O.Vector4),this.registerInput("viewDirection",O.Vector3),this.registerInput("bias",O.Float),this.registerInput("power",O.Float),this.registerOutput("fresnel",O.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){let t=new gs("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){let e=new aR("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){let e=new aR("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName}); +`,this}}t0["BABYLON.FresnelBlock"]=gn;class ga extends ax{constructor(e){super(e,N.Neutral),this.registerInput("left",O.AutoDetect),this.registerInput("right",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}}t0["BABYLON.MaxBlock"]=ga;class go extends ax{constructor(e){super(e,N.Neutral),this.registerInput("left",O.AutoDetect),this.registerInput("right",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}}t0["BABYLON.MinBlock"]=go;class gl extends ax{constructor(e){super(e,N.Neutral),this.registerInput("left",O.AutoDetect),this.registerInput("right",O.AutoDetect),this.registerOutput("output",O.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(O.Float),this._inputs[0].excludedConnectionPointTypes.push(O.Matrix),this._inputs[1].excludedConnectionPointTypes.push(O.Float),this._inputs[1].excludedConnectionPointTypes.push(O.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); +`,this}}t0["BABYLON.DistanceBlock"]=gl;class gh extends ax{constructor(e){super(e,N.Neutral),this.registerInput("value",O.AutoDetect),this.registerOutput("output",O.Float),this._inputs[0].excludedConnectionPointTypes.push(O.Float),this._inputs[0].excludedConnectionPointTypes.push(O.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName}); +`,this}}t0["BABYLON.LengthBlock"]=gh;class gu extends ax{constructor(e){super(e,N.Neutral),this.registerInput("value",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName}; +`,this}}t0["BABYLON.NegateBlock"]=gu;class gc extends ax{constructor(e){super(e,N.Neutral),this.registerInput("value",O.AutoDetect),this.registerInput("power",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); +`,this}}t0["BABYLON.PowBlock"]=gc;class gd extends ax{constructor(e){super(e,N.Neutral),this.registerInput("seed",O.AutoDetect),this.registerOutput("output",O.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Vector2|O.Vector3|O.Vector4|O.Color3|O.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy); +`,this}}t0["BABYLON.RandomNumberBlock"]=gd;class gp extends ax{constructor(e){super(e,N.Neutral),this.registerInput("x",O.Float),this.registerInput("y",O.Float),this.registerOutput("output",O.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); +`,this}}t0["BABYLON.ArcTan2Block"]=gp;class g_ extends ax{constructor(e){super(e,N.Neutral),this.registerInput("value",O.AutoDetect),this.registerInput("edge0",O.Float),this.registerInput("edge1",O.Float),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName}); +`,this}}t0["BABYLON.SmoothStepBlock"]=g_;class gf extends ax{constructor(e){super(e,N.Neutral),this.registerInput("input",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return this.input.type===O.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); +`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; +`,this}}t0["BABYLON.ReciprocalBlock"]=gf;class gm extends ax{constructor(e){super(e,N.Neutral),this.registerInput("value",O.AutoDetect),this.registerInput("reference",O.AutoDetect),this.registerInput("distance",O.Float),this.registerInput("replacement",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(O.Float),this._inputs[0].excludedConnectionPointTypes.push(O.Matrix),this._inputs[1].excludedConnectionPointTypes.push(O.Float),this._inputs[1].excludedConnectionPointTypes.push(O.Matrix),this._inputs[3].excludedConnectionPointTypes.push(O.Float),this._inputs[3].excludedConnectionPointTypes.push(O.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`; +`,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { +`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; +`,e.compilationString+=`} else { +`,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; +`,e.compilationString+=`} +`,this}}t0["BABYLON.ReplaceColorBlock"]=gm;class gg extends ax{constructor(e){super(e,N.Neutral),this.registerInput("value",O.AutoDetect),this.registerInput("steps",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(O.Matrix),this._inputs[1].excludedConnectionPointTypes.push(O.Matrix)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName}); +`,this}}t0["BABYLON.PosterizeBlock"]=gg,function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(e1||(e1={}));class gv extends ax{constructor(e){super(e,N.Neutral),this.kind=e1.SawTooth,this.registerInput("input",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(O.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];switch(this.kind){case e1.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); +`;break;case e1.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); +`;break;case e1.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; +`}return this}serialize(){let e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}t0["BABYLON.WaveBlock"]=gv;class gx{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class gT extends ax{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,N.Neutral),this.colorSteps=[new gx(0,io.Black()),new gx(1,io.White())],this.onValueChangedObservable=new tj,this.registerInput("gradient",O.AutoDetect),this.registerOutput("output",O.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Float|O.Vector2|O.Vector3|O.Vector4|O.Color3|O.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){let t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.); +`;return}let i=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; +`,e.compilationString+=`float ${r}; +`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==O.Float&&(s+=".x");for(let t=1;ti.getWorldMatrix().determinant()?-1:1)}_buildBlock(e){return e.target===N.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}}t0["BABYLON.AnisotropyBlock"]=gM;class gD extends mj{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,ig.Error("The position input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?N.Fragment:N.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",O.AutoDetect,!1,N.Vertex),this.registerInput("world",O.Matrix,!1,N.Vertex),this.registerInput("color",O.Color3,!0,N.Fragment),this.registerOutput("reflection",O.Object,N.Fragment,new mC("reflection",this,w.Output,gD,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!r.invertZ:r.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",r.gammaSpace,!0),i.setValue("RGBDREFLECTION",r.isRGBD,!0),r&&r.coordinatesMode!==n6.SKYBOX_MODE&&r.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,r){super.bind(e,t,i);let s=this._getTexture();if(!s||!r)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);let n=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,n,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,n,tK.Log2(n));let a=r.materialDefines,o=s.sphericalPolynomial;if(a.USESPHERICALFROMREFLECTIONMAP&&o){if(a.SPHERICAL_HARMONICS){let t=o.preScaledHarmonics;e.setVector3("vSphericalL00",t.l00),e.setVector3("vSphericalL1_1",t.l1_1),e.setVector3("vSphericalL10",t.l10),e.setVector3("vSphericalL11",t.l11),e.setVector3("vSphericalL2_2",t.l2_2),e.setVector3("vSphericalL2_1",t.l2_1),e.setVector3("vSphericalL20",t.l20),e.setVector3("vSphericalL21",t.l21),e.setVector3("vSphericalL22",t.l22)}else e.setFloat3("vSphericalX",o.x.x,o.x.y,o.x.z),e.setFloat3("vSphericalY",o.y.x,o.y.y,o.y.z),e.setFloat3("vSphericalZ",o.z.x,o.z.y,o.z.z),e.setFloat3("vSphericalXX_ZZ",o.xx.x-o.zz.x,o.xx.y-o.zz.y,o.xx.z-o.zz.z),e.setFloat3("vSphericalYY_ZZ",o.yy.x-o.zz.x,o.yy.y-o.zz.y,o.yy.z-o.zz.z),e.setFloat3("vSphericalZZ",o.zz.x,o.zz.y,o.zz.z),e.setFloat3("vSphericalXY",o.xy.x,o.xy.y,o.xy.z),e.setFloat3("vSphericalYZ",o.yz.x,o.yz.y,o.yz.z),e.setFloat3("vSphericalZX",o.zx.x,o.zx.y,o.zx.z)}}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});let i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) + vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; + #ifdef ${this._defineOppositeZ} + ${i}.z *= -1.0; + #endif + ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i}); + #endif +`}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",` + #ifdef ${this._define3DName} + #define sampleReflection(s, c) textureCube(s, c) + #else + #define sampleReflection(s, c) texture2D(s, c) + #endif +`,`//${this.name}`),e._emitFunction("sampleReflectionLod",` + #ifdef ${this._define3DName} + #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif +`,`//${this.name}`);let r=` + vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { + ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)} + return ${this._reflectionVectorName}; + } +`;return e._emitFunction("computeReflectionCoordsPBR",r,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION + vec2 ${this._vReflectionInfosName} = vec2(1., 0.); + + reflectionOutParams reflectionOut; + + reflectionBlock( + ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz, + ${t}, + alphaG, + ${this._vReflectionMicrosurfaceInfosName}, + ${this._vReflectionInfosName}, + ${this.reflectionColor}, + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) + NdotVUnclamped, + #endif + #ifdef ${this._defineLinearSpecularReflection} + roughness, + #endif + #ifdef ${this._define3DName} + ${this._cubeSamplerName}, + #else + ${this._2DSamplerName}, + #endif + #if defined(NORMAL) && defined(USESPHERICALINVERTEX) + ${this._vEnvironmentIrradianceName}, + #endif + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + ${this._reflectionMatrixName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, // ** not handled ** + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${this._define3DName} + ${this._cubeSamplerName}, + ${this._cubeSamplerName}, + #else + ${this._2DSamplerName}, + ${this._2DSamplerName}, + #endif + #endif + #ifdef REALTIME_FILTERING + ${this._vReflectionFilteringInfoName}, + #endif + reflectionOut + ); + #endif +`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==N.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace}; +`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics}; +${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment}; +`}serialize(){var e,t;let i=super.serialize();return i.useSphericalHarmonics=this.useSphericalHarmonics,i.forceIrradianceInFragment=this.forceIrradianceInFragment,i.gammaSpace=null===(t=null===(e=this.texture)||void 0===e?void 0:e.gammaSpace)||void 0===t||t,i}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}}iZ([aE("Spherical Harmonics",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gD.prototype,"useSphericalHarmonics",void 0),iZ([aE("Force irradiance in fragment",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gD.prototype,"forceIrradianceInFragment",void 0),t0["BABYLON.ReflectionBlock"]=gD;class gO extends ax{constructor(e){super(e,N.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",O.Float,!1,N.Fragment),this.registerInput("roughness",O.Float,!0,N.Fragment),this.registerInput("indexOfRefraction",O.Float,!0,N.Fragment),this.registerInput("normalMapColor",O.Color3,!0,N.Fragment),this.registerInput("uv",O.Vector2,!0,N.Fragment),this.registerInput("tintColor",O.Color3,!0,N.Fragment),this.registerInput("tintAtDistance",O.Float,!0,N.Fragment),this.registerInput("tintThickness",O.Float,!0,N.Fragment),this.registerInput("worldTangent",O.Vector4,!0),this.registerInput("worldNormal",O.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(O.Color4|O.Vector4|O.Vector3),this.registerInput("TBN",O.Object,!0,N.VertexAndFragment,new mC("TBN",this,w.Input,mM,"TBNBlock")),this.registerOutput("clearcoat",O.Object,N.Fragment,new mC("clearcoat",this,w.Output,gO,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new aR("ClearCoat intensity",N.Fragment,O.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===p9._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var r,s;super.bind(e,t,i);let n=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:p9._DefaultIndexOfRefraction,a=1-n,o=1+n;e.setFloat4("vClearCoatRefractionParams",Math.pow(-a/o,2),1/n,a,o);let l=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,h=(null==l?void 0:l.perturbedNormal.isConnected)?l.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",(null==h?void 0:h.invertX)?1:-1,(null==h?void 0:h.invertY)?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",(null==h?void 0:h.invertX)?-1:1,(null==h?void 0:h.invertY)?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_generateTBNSpace(e,t,i){let r="",s=`//${this.name}`,n=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let a={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},o=this.TBN;return o.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${o.associatedVariableName}; + #endif + `:n.isConnected&&(r+=`vec3 tbnNormal = normalize(${i}.xyz); +vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); +vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[a]}),r}static GetCode(e,t,i,r,s,n,a){let o="",l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",h=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",u=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",c=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",p=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",_=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");let i=t.worldNormal;o+=`vec3 vGeometricNormaClearCoatW = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"}; +`}else o+=`vec3 vGeometricNormaClearCoatW = geometricNormalW; +`;return s&&t&&(o+=t._generateTBNSpace(e,r,a),n=t.worldTangent.isConnected),o+=`clearcoatOutParams clearcoatOut; + + #ifdef CLEARCOAT + vec2 vClearCoatParams = vec2(${l}, ${h}); + vec4 vClearCoatTintParams = vec4(${d}, ${p}); + + clearcoatBlock( + ${r}.xyz, + vGeometricNormaClearCoatW, + viewDirectionW, + vClearCoatParams, + specularEnvironmentR0, + #ifdef CLEARCOAT_TEXTURE + vec2(0.), + #endif + #ifdef CLEARCOAT_TINT + vClearCoatTintParams, + ${_}, + vClearCoatRefractionParams, + #ifdef CLEARCOAT_TINT_TEXTURE + vec4(0.), + #endif + #endif + #ifdef CLEARCOAT_BUMP + vec2(0., 1.), + vec4(${u}, 0.), + ${c}, + #if defined(${n?"TANGENT":"IGNORE"}) && defined(NORMAL) + vTBN, + #else + vClearCoatTangentSpaceParams, + #endif + #ifdef OBJECTSPACE_NORMALMAP + normalMatrix, + #endif + #endif + #if defined(FORCENORMALFORWARD) && defined(NORMAL) + faceNormal, + #endif + #ifdef REFLECTION + ${null==i?void 0:i._vReflectionMicrosurfaceInfosName}, + ${null==i?void 0:i._vReflectionInfosName}, + ${null==i?void 0:i.reflectionColor}, + vLightingIntensity, + #ifdef ${null==i?void 0:i._define3DName} + ${null==i?void 0:i._cubeSamplerName}, + #else + ${null==i?void 0:i._2DSamplerName}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${null==i?void 0:i._define3DName} + ${null==i?void 0:i._cubeSamplerName}, + ${null==i?void 0:i._cubeSamplerName}, + #else + ${null==i?void 0:i._2DSamplerName}, + ${null==i?void 0:i._2DSamplerName}, + #endif + #endif + #endif + #if defined(ENVIRONMENTBRDF) && !defined(${null==i?void 0:i._defineSkyboxName}) + #ifdef RADIANCEOCCLUSION + ambientMonochrome, + #endif + #endif + #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) + (gl_FrontFacing ? 1. : -1.), + #endif + clearcoatOut + ); + #else + clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; + #endif +`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===N.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange}; +`}serialize(){let e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.remapF0OnInterfaceChange=null===(r=e.remapF0OnInterfaceChange)||void 0===r||r}}iZ([aE("Remap F0 on interface change",L.Boolean,"ADVANCED")],gO.prototype,"remapF0OnInterfaceChange",void 0),t0["BABYLON.ClearCoatBlock"]=gO;class gN extends ax{constructor(e){super(e,N.Fragment),this._isUnique=!0,this.registerInput("intensity",O.Float,!0,N.Fragment),this.registerInput("indexOfRefraction",O.Float,!0,N.Fragment),this.registerInput("thickness",O.Float,!0,N.Fragment),this.registerOutput("iridescence",O.Object,N.Fragment,new mC("iridescence",this,w.Output,gN,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new aR("Iridescence intensity",N.Fragment,O.Float);e.value=1,e.output.connectTo(this.intensity);let t=new aR("Iridescence ior",N.Fragment,O.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);let i=new aR("Iridescence thickness",N.Fragment,O.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t=(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1.",i=(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:_t._DefaultIndexOfRefraction,r=(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:_t._DefaultMaximumThickness;return`iridescenceOutParams iridescenceOut; + + #ifdef IRIDESCENCE + iridescenceBlock( + vec4(${t}, ${i}, 1., ${r}), + NdotV, + specularEnvironmentR0, + #ifdef CLEARCOAT + NdotVUnclamped, + #endif + iridescenceOut + ); + + float iridescenceIntensity = iridescenceOut.iridescenceIntensity; + specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; + #endif +`}_buildBlock(e){return e.target===N.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){return super.serialize()}_deserialize(e,t,i){super._deserialize(e,t,i)}}t0["BABYLON.IridescenceBlock"]=gN;class gF extends ax{constructor(e){super(e,N.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",O.Float,!1,N.Fragment),this.registerInput("tintAtDistance",O.Float,!0,N.Fragment),this.registerInput("volumeIndexOfRefraction",O.Float,!0,N.Fragment),this.registerOutput("refraction",O.Object,N.Fragment,new mC("refraction",this,w.Output,gF,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=()=>!0){if(!this.intensity.isConnected){let e=new aR("Refraction intensity",N.Fragment,O.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.View&&t(e));i||(i=new aR("view")).setAsSystemValue(U.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){var r,s,n,a;super.bind(e,t,i);let o=this._getTexture();if(!o)return;o.isCube?e.setTexture(this._cubeSamplerName,o):e.setTexture(this._2DSamplerName,o),e.setMatrix(this._refractionMatrixName,o.getRefractionTextureMatrix());let l=1;!o.isCube&&o.depth&&(l=o.depth);let h=null!==(a=null!==(s=null===(r=this.volumeIndexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:null===(n=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==a?a:1.5;e.setFloat4(this._vRefractionInfosName,o.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset,1/h);let u=o.getSize().width;e.setFloat2(this._vRefractionFilteringInfoName,u,tK.Log2(u)),o.boundingBoxSize&&(e.setVector3("vRefractionPosition",o.boundingBoxPosition),e.setVector3("vRefractionSize",o.boundingBoxSize))}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,e._samplerDeclaration+=`#endif +`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",` + #ifdef ${this._define3DName} + #define sampleRefraction(s, c) textureCube(s, c) + #else + #define sampleRefraction(s, c) texture2D(s, c) + #endif +`,`//${this.name}`),e._emitFunction("sampleRefractionLod",` + #ifdef ${this._define3DName} + #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif +`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=(this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}"); +`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); +`)+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; +${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; +${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; +`}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=po.Parse(e.texture,t,i):this.texture=n6.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}iZ([aE("Link refraction to transparency",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gF.prototype,"linkRefractionWithTransparency",void 0),iZ([aE("Invert refraction Y",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gF.prototype,"invertRefractionY",void 0),iZ([aE("Use thickness as depth",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gF.prototype,"useThicknessAsDepth",void 0),t0["BABYLON.RefractionBlock"]=gF;class gw extends ax{constructor(e){super(e,N.Fragment),this._isUnique=!0,this.registerInput("thickness",O.Float,!1,N.Fragment),this.registerInput("tintColor",O.Color3,!0,N.Fragment),this.registerInput("translucencyIntensity",O.Float,!0,N.Fragment),this.registerInput("translucencyDiffusionDist",O.Color3,!0,N.Fragment),this.registerInput("refraction",O.Object,!0,N.Fragment,new mC("refraction",this,w.Input,gF,"RefractionBlock")),this.registerInput("dispersion",O.Float,!0,N.Fragment),this.registerOutput("subsurface",O.Object,N.Fragment,new mC("subsurface",this,w.Output,gw,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){let e=new aR("SubSurface thickness",N.Fragment,O.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x;let T=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",b=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",E=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",S=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",C=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,y=(null==C?void 0:C.tintAtDistance.isConnected)?C.tintAtDistance.associatedVariableName:"1.",A=(null==C?void 0:C.intensity.isConnected)?C.intensity.associatedVariableName:"1.",R=(null==C?void 0:C.view.isConnected)?C.view.associatedVariableName:"",I=(null==t?void 0:t.dispersion.isConnected)?null==t?void 0:t.dispersion.associatedVariableName:"0.0";return""+(null!==(n=null==C?void 0:C.getCode(e))&&void 0!==n?n:"")+`subSurfaceOutParams subSurfaceOut; + + #ifdef SUBSURFACE + vec2 vThicknessParam = vec2(0., ${T}); + vec4 vTintColor = vec4(${b}, ${y}); + vec3 vSubSurfaceIntensity = vec3(${A}, ${E}, 0.); + float dispersion = ${I}; + subSurfaceBlock( + vSubSurfaceIntensity, + vThicknessParam, + vTintColor, + normalW, + specularEnvironmentReflectance, + #ifdef SS_THICKNESSANDMASK_TEXTURE + vec4(0.), + #endif + #ifdef REFLECTION + #ifdef SS_TRANSLUCENCY + ${null==i?void 0:i._reflectionMatrixName}, + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + reflectionOut.irradianceVector, + #endif + #if defined(REALTIME_FILTERING) + ${null==i?void 0:i._cubeSamplerName}, + ${null==i?void 0:i._vReflectionFilteringInfoName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, + #endif + #endif + #endif + #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) + surfaceAlbedo, + #endif + #ifdef SS_REFRACTION + ${r}.xyz, + viewDirectionW, + ${R}, + ${null!==(a=null==C?void 0:C._vRefractionInfosName)&&void 0!==a?a:""}, + ${null!==(o=null==C?void 0:C._refractionMatrixName)&&void 0!==o?o:""}, + ${null!==(l=null==C?void 0:C._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""}, + vLightingIntensity, + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha, + #endif + #ifdef ${null!==(h=null==C?void 0:C._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"} + NdotVUnclamped, + #endif + #ifdef ${null!==(u=null==C?void 0:C._defineLinearSpecularRefraction)&&void 0!==u?u:"IGNORE"} + roughness, + #endif + alphaG, + #ifdef ${null!==(c=null==C?void 0:C._define3DName)&&void 0!==c?c:"IGNORE"} + ${null!==(d=null==C?void 0:C._cubeSamplerName)&&void 0!==d?d:""}, + #else + ${null!==(p=null==C?void 0:C._2DSamplerName)&&void 0!==p?p:""}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${null!==(_=null==C?void 0:C._define3DName)&&void 0!==_?_:"IGNORE"} + ${null!==(f=null==C?void 0:C._cubeSamplerName)&&void 0!==f?f:""}, + ${null!==(m=null==C?void 0:C._cubeSamplerName)&&void 0!==m?m:""}, + #else + ${null!==(g=null==C?void 0:C._2DSamplerName)&&void 0!==g?g:""}, + ${null!==(v=null==C?void 0:C._2DSamplerName)&&void 0!==v?v:""}, + #endif + #endif + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #ifdef REALTIME_FILTERING + ${null!==(x=null==C?void 0:C._vRefractionFilteringInfoName)&&void 0!==x?x:""}, + #endif + #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC + vRefractionPosition, + vRefractionSize, + #endif + #ifdef SS_DISPERSION + dispersion, + #endif + #endif + #ifdef SS_TRANSLUCENCY + ${S}, + #endif + subSurfaceOut + ); + + #ifdef SS_REFRACTION + surfaceAlbedo = subSurfaceOut.surfaceAlbedo; + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha = subSurfaceOut.alpha; + #endif + #endif + #else + subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; + #endif +`}_buildBlock(e){return e.target===N.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}t0["BABYLON.SubSurfaceBlock"]=gw;let gL={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class gB extends ax{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,ig.Error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?N.Fragment:N.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?N.Fragment:N.Vertex}constructor(e){super(e,N.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=io.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",O.Vector4,!1,N.Vertex),this.registerInput("worldNormal",O.Vector4,!1,N.Fragment),this.registerInput("view",O.Matrix,!1),this.registerInput("cameraPosition",O.Vector3,!1,N.Fragment),this.registerInput("perturbedNormal",O.Vector4,!0,N.Fragment),this.registerInput("baseColor",O.Color3,!0,N.Fragment),this.registerInput("metallic",O.Float,!1,N.Fragment),this.registerInput("roughness",O.Float,!1,N.Fragment),this.registerInput("ambientOcc",O.Float,!0,N.Fragment),this.registerInput("opacity",O.Float,!0,N.Fragment),this.registerInput("indexOfRefraction",O.Float,!0,N.Fragment),this.registerInput("ambientColor",O.Color3,!0,N.Fragment),this.registerInput("reflection",O.Object,!0,N.Fragment,new mC("reflection",this,w.Input,gD,"ReflectionBlock")),this.registerInput("clearcoat",O.Object,!0,N.Fragment,new mC("clearcoat",this,w.Input,gO,"ClearCoatBlock")),this.registerInput("sheen",O.Object,!0,N.Fragment,new mC("sheen",this,w.Input,gP,"SheenBlock")),this.registerInput("subsurface",O.Object,!0,N.Fragment,new mC("subsurface",this,w.Input,gw,"SubSurfaceBlock")),this.registerInput("anisotropy",O.Object,!0,N.Fragment,new mC("anisotropy",this,w.Input,gM,"AnisotropyBlock")),this.registerInput("iridescence",O.Object,!0,N.Fragment,new mC("iridescence",this,w.Input,gN,"IridescenceBlock")),this.registerOutput("ambientClr",O.Color3,N.Fragment),this.registerOutput("diffuseDir",O.Color3,N.Fragment),this.registerOutput("specularDir",O.Color3,N.Fragment),this.registerOutput("clearcoatDir",O.Color3,N.Fragment),this.registerOutput("sheenDir",O.Color3,N.Fragment),this.registerOutput("diffuseInd",O.Color3,N.Fragment),this.registerOutput("specularInd",O.Color3,N.Fragment),this.registerOutput("clearcoatInd",O.Color3,N.Fragment),this.registerOutput("sheenInd",O.Color3,N.Fragment),this.registerOutput("refraction",O.Color3,N.Fragment),this.registerOutput("lighting",O.Color3,N.Fragment),this.registerOutput("shadow",O.Float,N.Fragment),this.registerOutput("alpha",O.Float,N.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.CameraPosition&&t(e));i||(i=new aR("cameraPosition")).setAsSystemValue(U.CameraPosition),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===U.View&&t(e));i||(i=new aR("view")).setAsSystemValue(U.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===_u.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===_u.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));let r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",0>r.indexOf(".")?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);let s=e.getScene();if(s.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&lE.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty){if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};nw.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else nw.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,nw.PrepareDefinesForMultiview(s,i)}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;nw.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return(!this._environmentBRDFTexture||!!this._environmentBRDFTexture.isReady())&&(!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var r,s;if(!i)return;let n=i.getScene();this.light?nw.BindLight(this.light,this._lightId,n,e,!0):nw.BindLights(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);let a=this._scene.ambientColor;a&&e.setColor3("ambientFromScene",a);let o=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);e.setFloat(this._invertNormalName,o?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);let l=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((l-1)/(l+1),2)*this._metallicF0Factor,ih.Color3[0]);let h=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,ih.Color3[0],h),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;let r=this.worldPosition,s=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));let n="v_"+r.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${r.associatedVariableName}; +`);let a=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==a?void 0:a.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 +`,e._injectAtEnd+=`vClipSpacePosition = gl_Position; +`,e._injectAtEnd+=`#endif +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:r.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${r.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; +`,t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+`albedoOpacityBlock( + vec4(${t}, 1.), + #ifdef ALBEDO + vec4(1.), + vec2(1., 1.), + #endif + #ifdef OPACITY + vec4(${i}), + vec2(1., 1.), + #endif + albedoOpacityOut + ); + + vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; + float alpha = albedoOpacityOut.alpha; +`}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; +`,t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+`ambientOcclusionBlock( + #ifdef AMBIENT + vec3(${t}), + vec4(0., 1.0, 1.0, 0.), + #endif + aoOut + ); +`}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; +`;return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo; + + reflectivityBlock( + vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), + #ifdef METALLICWORKFLOW + surfaceAlbedo, + ${this._vMetallicReflectanceFactorsName}, + #endif + #ifdef REFLECTIVITY + vec3(0., 0., 1.), + vec4(1.), + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor, + #endif + #ifdef MICROSURFACEMAP + microSurfaceTexel, <== not handled! + #endif + reflectivityOut + ); + + float microSurface = reflectivityOut.microSurface; + float roughness = reflectivityOut.roughness; + + #ifdef METALLICWORKFLOW + surfaceAlbedo = reflectivityOut.surfaceAlbedo; + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; + #endif +`}_buildBlock(e){var t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x,T,b,E,S,C,y,A,R,I,P,M,D,O,F,w,L,B,U,V,k,G,z;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=px(this._scene));let W=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;if(W&&(W.worldPositionConnectionPoint=this.worldPosition,W.cameraPositionConnectionPoint=this.cameraPosition,W.worldNormalConnectionPoint=this.worldNormal,W.viewConnectionPoint=this.view),e.target!==N.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);let H=`//${this.name}`,X=this.perturbedNormal,Y=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(Y=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${Y}; +`,H),e.compilationString+=`${Y} = ${this.worldPosition.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",H,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 +`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); +`,e.compilationString+=`#endif +`):Y="v_"+Y,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",H,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",H,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",H),e._emitFunctionFromInclude("importanceSampling",H),e._emitFunctionFromInclude("pbrHelperFunctions",H),e._emitFunctionFromInclude("imageProcessingDeclaration",H),e._emitFunctionFromInclude("imageProcessingFunctions",H),e._emitFunctionFromInclude("shadowsFragmentFunctions",H),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",H,{replaceStrings:[{search:/vPositionW/g,replace:Y+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",H),e._emitFunctionFromInclude("pbrBRDFFunctions",H,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(i=null==W?void 0:W._defineSkyboxName)&&void 0!==i?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",H),e._emitFunctionFromInclude("pbrDirectLightingFunctions",H,{replaceStrings:[{search:/vPositionW/g,replace:Y+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",H),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",H),e._emitFunctionFromInclude("pbrBlockReflectivity",H),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",H),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",H),e._emitFunctionFromInclude("pbrBlockAnisotropic",H),e._emitUniformFromString("vLightingIntensity","vec4"),(null==W?void 0:W.generateOnlyFragmentCode)&&(e.compilationString+=W.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName}); +`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${Y}.xyz); +`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; +`,e.compilationString+=`vec3 normalW = ${X.isConnected?"normalize("+X.associatedVariableName+".xyz)":"geometricNormalW"}; +`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",H,{replaceStrings:[{search:/vPositionW/g,replace:Y+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",H),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",H),e.compilationString+=`#ifdef UNLIT + vec3 diffuseBase = vec3(1., 1., 1.); + #else +`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",H,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(r=null==W?void 0:W._defineSkyboxName)&&void 0!==r?r:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==W?void 0:W._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});let j=this.anisotropy.isConnected?null===(n=this.anisotropy.connectedPoint)||void 0===n?void 0:n.ownerBlock:null;j&&(j.worldPositionConnectionPoint=this.worldPosition,j.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=j.getCode(e,!this.perturbedNormal.isConnected)),W&&W.hasTexture&&(e.compilationString+=W.getCode(e,j?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",H,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(a=null==W?void 0:W._define3DName)&&void 0!==a?a:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(o=null==W?void 0:W._defineOppositeZ)&&void 0!==o?o:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(l=null==W?void 0:W._defineProjectionName)&&void 0!==l?l:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(h=null==W?void 0:W._defineSkyboxName)&&void 0!==h?h:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(u=null==W?void 0:W._defineLODReflectionAlpha)&&void 0!==u?u:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(c=null==W?void 0:W._defineLinearSpecularReflection)&&void 0!==c?c:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(d=null==W?void 0:W._vReflectionFilteringInfoName)&&void 0!==d?d:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",H,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});let K=this.sheen.isConnected?null===(p=this.sheen.connectedPoint)||void 0===p?void 0:p.ownerBlock:null;K&&(e.compilationString+=K.getCode(W)),e._emitFunctionFromInclude("pbrBlockSheen",H,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(_=null==W?void 0:W._define3DName)&&void 0!==_?_:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(f=null==W?void 0:W._defineSkyboxName)&&void 0!==f?f:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(m=null==W?void 0:W._defineLODReflectionAlpha)&&void 0!==m?m:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(g=null==W?void 0:W._defineLinearSpecularReflection)&&void 0!==g?g:"LINEARSPECULARREFLECTION"}]});let $=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=gN.GetCode($),e._emitFunctionFromInclude("pbrBlockIridescence",H,{replaceStrings:[]});let q=this.clearcoat.isConnected?null===(x=this.clearcoat.connectedPoint)||void 0===x?void 0:x.ownerBlock:null,Q=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Z=this.perturbedNormal.isConnected&&(null===(b=(null===(T=this.perturbedNormal.connectedPoint)||void 0===T?void 0:T.ownerBlock).worldTangent)||void 0===b?void 0:b.isConnected),J=this.anisotropy.isConnected&&(null===(E=this.anisotropy.connectedPoint)||void 0===E?void 0:E.ownerBlock).worldTangent.isConnected,ee=Z||!this.perturbedNormal.isConnected&&J;e.compilationString+=gO.GetCode(e,q,W,Y,Q,ee,this.worldNormal.associatedVariableName),Q&&(ee=null!==(S=null==q?void 0:q.worldTangent.isConnected)&&void 0!==S&&S),e._emitFunctionFromInclude("pbrBlockClearcoat",H,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(C=null==W?void 0:W._define3DName)&&void 0!==C?C:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(y=null==W?void 0:W._defineOppositeZ)&&void 0!==y?y:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(A=null==W?void 0:W._defineProjectionName)&&void 0!==A?A:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(R=null==W?void 0:W._defineSkyboxName)&&void 0!==R?R:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(I=null==W?void 0:W._defineLODReflectionAlpha)&&void 0!==I?I:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(P=null==W?void 0:W._defineLinearSpecularReflection)&&void 0!==P?P:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:ee?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",H,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(M=null==W?void 0:W._defineSkyboxName)&&void 0!==M?M:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(D=null==W?void 0:W._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});let et=this.subsurface.isConnected?null===(O=this.subsurface.connectedPoint)||void 0===O?void 0:O.ownerBlock:null,ei=this.subsurface.isConnected?null===(w=(null===(F=this.subsurface.connectedPoint)||void 0===F?void 0:F.ownerBlock).refraction.connectedPoint)||void 0===w?void 0:w.ownerBlock:null;ei&&(ei.viewConnectionPoint=this.view,ei.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=gw.GetCode(e,et,W,Y),e._emitFunctionFromInclude("pbrBlockSubSurface",H,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(L=null==W?void 0:W._define3DName)&&void 0!==L?L:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(B=null==W?void 0:W._defineOppositeZ)&&void 0!==B?B:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(U=null==W?void 0:W._defineProjectionName)&&void 0!==U?U:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(V=null==ei?void 0:ei._define3DName)&&void 0!==V?V:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(k=null==ei?void 0:ei._defineLODRefractionAlpha)&&void 0!==k?k:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(G=null==ei?void 0:ei._defineLinearSpecularRefraction)&&void 0!==G?G:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(z=null==ei?void 0:ei._defineOppositeZ)&&void 0!==z?z:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",H),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",H,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:Y+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",H,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${Y}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",H),e.compilationString+=`#endif +`;let er=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",es=_u.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();for(let t of(-1===es.indexOf(".")&&(es+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",H,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:er+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:es}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",H,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",H,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",H,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:Y},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]}),this._outputs))if(t.hasEndpoints){let i=gL[t.name];if(i){let[r,s]=i;s&&(e.compilationString+=`#if ${s} +`),e.compilationString+=`${this._declareOutput(t,e)} = ${r}; +`,s&&(e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.); +`,e.compilationString+=`#endif +`)}else ig.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; +${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; +${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; +${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; +${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; +${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; +${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; +${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; +${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; +${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; +${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; +${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; +${this._codeVariableName}.unlit = ${this.unlit}; +${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; +${this._codeVariableName}.debugMode = ${this.debugMode}; +${this._codeVariableName}.debugLimit = ${this.debugLimit}; +${this._codeVariableName}.debugFactor = ${this.debugFactor}; +`}serialize(){let e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){var r,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(r=e.lightFalloff)&&void 0!==r?r:0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=null!==(s=e.realTimeFilteringQuality)&&void 0!==s?s:8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}iZ([aE("Direct lights",L.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],gB.prototype,"directIntensity",void 0),iZ([aE("Environment lights",L.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],gB.prototype,"environmentIntensity",void 0),iZ([aE("Specular highlights",L.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],gB.prototype,"specularIntensity",void 0),iZ([aE("Light falloff",L.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:_u.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:_u.LIGHTFALLOFF_GLTF},{label:"Standard",value:_u.LIGHTFALLOFF_STANDARD}]})],gB.prototype,"lightFalloff",void 0),iZ([aE("Alpha Testing",L.Boolean,"OPACITY")],gB.prototype,"useAlphaTest",void 0),iZ([aE("Alpha CutOff",L.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],gB.prototype,"alphaTestCutoff",void 0),iZ([aE("Alpha blending",L.Boolean,"OPACITY")],gB.prototype,"useAlphaBlending",void 0),iZ([aE("Radiance over alpha",L.Boolean,"RENDERING",{notifiers:{update:!0}})],gB.prototype,"useRadianceOverAlpha",void 0),iZ([aE("Specular over alpha",L.Boolean,"RENDERING",{notifiers:{update:!0}})],gB.prototype,"useSpecularOverAlpha",void 0),iZ([aE("Specular anti-aliasing",L.Boolean,"RENDERING",{notifiers:{update:!0}})],gB.prototype,"enableSpecularAntiAliasing",void 0),iZ([aE("Realtime filtering",L.Boolean,"RENDERING",{notifiers:{update:!0}})],gB.prototype,"realTimeFiltering",void 0),iZ([aE("Realtime filtering quality",L.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],gB.prototype,"realTimeFilteringQuality",void 0),iZ([aE("Energy Conservation",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gB.prototype,"useEnergyConservation",void 0),iZ([aE("Radiance occlusion",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gB.prototype,"useRadianceOcclusion",void 0),iZ([aE("Horizon occlusion",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gB.prototype,"useHorizonOcclusion",void 0),iZ([aE("Unlit",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gB.prototype,"unlit",void 0),iZ([aE("Force normal forward",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gB.prototype,"forceNormalForward",void 0),iZ([aE("Generate only fragment code",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:gB._OnGenerateOnlyFragmentCodeChanged}})],gB.prototype,"generateOnlyFragmentCode",void 0),iZ([aE("Debug mode",L.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],gB.prototype,"debugMode",void 0),iZ([aE("Split position",L.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],gB.prototype,"debugLimit",void 0),iZ([aE("Output factor",L.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],gB.prototype,"debugFactor",void 0),t0["BABYLON.PBRMetallicRoughnessBlock"]=gB;class gU extends ax{constructor(e){super(e,N.Neutral),this.registerInput("left",O.AutoDetect),this.registerInput("right",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(O.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}}t0["BABYLON.ModBlock"]=gU;class gV extends ax{constructor(e){super(e,N.Neutral),this.registerInput("row0",O.Vector4),this.registerInput("row1",O.Vector4),this.registerInput("row2",O.Vector4),this.registerInput("row3",O.Vector4),this.registerOutput("output",O.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){let e=new aR("row0");e.value=new t6(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){let e=new aR("row1");e.value=new t6(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){let e=new aR("row2");e.value=new t6(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){let e=new aR("row3");e.value=new t6(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${n.associatedVariableName}); +`,this}}t0["BABYLON.MatrixBuilder"]=gV,function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(e2||(e2={}));class gk extends ax{constructor(e){super(e,N.Neutral),this.condition=e2.LessThan,this.registerInput("a",O.Float),this.registerInput("b",O.Float),this.registerInput("true",O.AutoDetect,!0),this.registerInput("false",O.AutoDetect,!0),this.registerOutput("output",O.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=O.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case e2.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case e2.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case e2.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case e2.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case e2.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case e2.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case e2.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${r}; +`;break;case e2.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${r}; +`;break;case e2.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${r}; +`}return this}serialize(){let e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${e2[this.condition]}; +`}}t0["BABYLON.ConditionalBlock"]=gk;class gG extends ax{constructor(e){super(e,N.Neutral),this.octaves=6,this.registerInput("seed",O.AutoDetect),this.registerInput("chaos",O.AutoDetect,!0),this.registerInput("offsetX",O.Float,!0),this.registerInput("offsetY",O.Float,!0),this.registerInput("offsetZ",O.Float,!0),this.registerOutput("output",O.Float),this._inputs[0].acceptedConnectionPointTypes.push(O.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(O.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var t,i;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let r=` + + float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } + + // Based on Morgan McGuire @morgan3d + // https://www.shadertoy.com/view/4dS3Wd + float cloudNoise(in vec2 x, in vec2 chaos) { + vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); + + vec2 i = floor(x); + vec2 f = fract(x); + + float n = dot(i, step); + + vec2 u = f * f * (3.0 - 2.0 * f); + return mix( + mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), + mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), + u.y + ); + } + + float cloudNoise(in vec3 x, in vec3 chaos) { + vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); + + vec3 i = floor(x); + vec3 f = fract(x); + + float n = dot(i, step); + + vec3 u = f * f * (3.0 - 2.0 * f); + return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), + mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); + }`,s=` + float fbm(in vec2 st, in vec2 chaos) { + // Initial values + float value = 0.0; + float amplitude = .5; + float frequency = 0.; + + // Loop of octaves + for (int i = 0; i < OCTAVES; i++) { + value += amplitude * cloudNoise(st, chaos); + st *= 2.0; + amplitude *= 0.5; + } + return value; + } + + float fbm(in vec3 x, in vec3 chaos) { + // Initial values + float value = 0.0; + float amplitude = 0.5; + for (int i = 0; i < OCTAVES; ++i) { + value += amplitude * cloudNoise(x, chaos); + x = x * 2.0; + amplitude *= 0.5; + } + return value; + }`,n=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",r,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,s.replace(/fbm/gi,n).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");let a=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===O.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${a} = ${this.seed.associatedVariableName}; +`,this.offsetX.isConnected&&(e.compilationString+=`${a}.x += 0.1 * ${this.offsetX.associatedVariableName}; +`),this.offsetY.isConnected&&(e.compilationString+=`${a}.y += 0.1 * ${this.offsetY.associatedVariableName}; +`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${a}.z += 0.1 * ${this.offsetZ.associatedVariableName}; +`);let l="";return l=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===O.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${n}(${a}, ${l}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; +`}serialize(){let e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}iZ([aE("Octaves",L.Int)],gG.prototype,"octaves",void 0),t0["BABYLON.CloudBlock"]=gG;class gz extends ax{constructor(e){super(e,N.Neutral),this.registerInput("seed",O.Vector2),this.registerInput("offset",O.Float),this.registerInput("density",O.Float),this.registerOutput("output",O.Float),this.registerOutput("cells",O.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){ + mat2 m = mat2(15.27, 47.63, 99.41, 89.98); + vec2 uv = fract(sin(m * seed) * 46839.32); + return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); + } + `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ + vec2 g = floor(seed * density); + vec2 f = fract(seed * density); + float t = 8.0; + vec3 res = vec3(8.0, 0.0, 0.0); + + for(int y=-1; y<=1; y++) + { + for(int x=-1; x<=1; x++) + { + vec2 lattice = vec2(x,y); + vec2 randomOffset = voronoiRandom(lattice + g, offset); + float d = distance(lattice + randomOffset, f); + if(d < res.x) + { + res = vec3(d, randomOffset.x, randomOffset.y); + outValue = res.x; + cells = res.y; + } + } + } + } + `,e._emitFunction("voronoi",t,"// Voronoi");let i=e._getFreeVariableName("tempOutput"),r=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; +`,e.compilationString+=`float ${r} = 0.0; +`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${r}); +`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; +`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${r}; +`),this}}t0["BABYLON.VoronoiNoiseBlock"]=gz;class gW extends ax{constructor(e){super(e,N.Neutral),this.registerInput("input",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==N.VertexAndFragment)return t.target;if(e.connectedPoint.target!==N.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName}; +`,this}}t0["BABYLON.ElbowBlock"]=gW;class gH extends ax{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:t2.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?(null===(e=this.sourceY.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(null===(e=this.sourceZ)||void 0===e?void 0:e.isConnected)?(null===(t=this.sourceY.connectedPoint)||void 0===t?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return(null==e?void 0:e.isConnected)?e.connectedPoint.ownerBlock:null}get samplerName(){let e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceY))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get samplerZName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceZ))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:t2.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:t2.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,N.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",O.AutoDetect,!1),this.registerInput("normal",O.AutoDetect,!1),this.registerInput("sharpness",O.Float,!0),this.registerInput("source",O.Object,!0,N.VertexAndFragment,new mC("source",this,w.Input,mX,"ImageSourceBlock")),this.registerInput("sourceY",O.Object,!0,N.VertexAndFragment,new mC("sourceY",this,w.Input,mX,"ImageSourceBlock")),t||this.registerInput("sourceZ",O.Object,!0,N.VertexAndFragment,new mC("sourceZ",this,w.Input,mX,"ImageSourceBlock")),this.registerOutput("rgba",O.Color4,N.Neutral),this.registerOutput("rgb",O.Color3,N.Neutral),this.registerOutput("r",O.Float,N.Neutral),this.registerOutput("g",O.Float,N.Neutral),this.registerOutput("b",O.Float,N.Neutral),this.registerOutput("a",O.Float,N.Neutral),this.registerOutput("level",O.Float,N.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(O.Color3|O.Vector3|O.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;let r=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:r,n=null!==(i=this.samplerZName)&&void 0!==i?i:r,a=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",o=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),c=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),_=e._getFreeVariableName("uvz");e.compilationString+=` + vec3 ${c} = ${this.normal.associatedVariableName}.xyz; + + vec2 ${d} = ${this.position.associatedVariableName}.yz; + vec2 ${p} = ${this.position.associatedVariableName}.zx; + vec2 ${_} = ${this.position.associatedVariableName}.xy; + `,this.projectAsCube&&(e.compilationString+=` + ${d}.xy = ${d}.yx; + + if (${c}.x >= 0.0) { + ${d}.x = -${d}.x; + } + if (${c}.y < 0.0) { + ${p}.y = -${p}.y; + } + if (${c}.z < 0.0) { + ${_}.x = -${_}.x; + } + `),e.compilationString+=` + vec4 ${o} = texture2D(${r}, ${d}); + vec4 ${l} = texture2D(${s}, ${p}); + vec4 ${h} = texture2D(${n}, ${_}); + + // blend weights + vec3 ${u} = pow(abs(${c}), vec3(${a})); + + // blend and return + vec4 ${this._tempTextureRead} = (${o}*${u}.x + ${l}*${u}.y + ${h}*${u}.z) / (${u}.x + ${u}.y + ${u}.z); + `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} + ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); + #endif + `),e.compilationString+=`#ifdef ${this._gammaDefineName} + ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; +`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e),this._outputs))i.hasEndpoints&&"level"!==i.name&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; +`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!oi.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=n6.Parse(e.texture,t,i))}}iZ([aE("Project as cube",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],gH.prototype,"projectAsCube",void 0),t0["BABYLON.TriPlanarBlock"]=gH;class gX extends gH{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;let i=this.samplerName,r=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=` + // grab coord derivatives for texturing + vec3 ${n} = dFdx(${this.position.associatedVariableName}.xyz); + vec3 ${a} = dFdy(${this.position.associatedVariableName}.xyz); + vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); + + // determine major axis (in x; yz are following axis) + ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : + (${o}.y>${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine minor axis (in x; yz are following axis) + ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : + (${o}.y<${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine median axis (in x; yz are following axis) + ivec3 ${u} = ivec3(3) - ${h} - ${l}; + + // project+fetch + vec4 ${c} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), + vec2(${n}[${l}.y],${n}[${l}.z]), + vec2(${a}[${l}.y],${a}[${l}.z]) ); + vec4 ${d} = textureGrad( ${r}, vec2( ${this.position.associatedVariableName}[${u}.y], ${this.position.associatedVariableName}[${u}.z]), + vec2(${n}[${u}.y],${n}[${u}.z]), + vec2(${a}[${u}.y],${a}[${u}.z]) ); + + // blend factors + vec2 ${p} = vec2(${o}[${l}.x],${o}[${u}.x]); + // make local support + ${p} = clamp( (${p}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); + // shape transition + ${p} = pow( ${p}, vec2(${s}/8.0) ); + // blend and return + vec4 ${this._tempTextureRead} = (${c}*${p}.x + ${d}*${p}.y) / (${p}.x + ${p}.y); + `}}t0["BABYLON.BiPlanarBlock"]=gX;class gY extends ax{constructor(e){super(e,N.Neutral),this.registerInput("input",O.Matrix),this.registerOutput("output",O.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName}); +`,this}}t0["BABYLON.MatrixDeterminantBlock"]=gY;class gj extends ax{constructor(e){super(e,N.Neutral),this.registerInput("input",O.Matrix),this.registerOutput("output",O.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); +`,this}}t0["BABYLON.MatrixTransposeBlock"]=gj,function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(e3||(e3={}));class gK extends ax{constructor(e){super(e,N.Neutral),this.attributeType=e3.None,this.registerInput("input",O.AutoDetect),this.registerInput("fallback",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(e=>{var t;if(this.attributeType)return;let i=e.ownerBlock;if(i instanceof aR&&i.isAttribute)switch(i.name){case"color":this.attributeType=e3.VertexColor;break;case"normal":this.attributeType=e3.Normal;break;case"tangent":this.attributeType=e3.Tangent;break;case"uv":this.attributeType=e3.UV1;break;case"uv2":this.attributeType=e3.UV2;break;case"uv3":this.attributeType=e3.UV3;break;case"uv4":this.attributeType=e3.UV4;break;case"uv5":this.attributeType=e3.UV5;break;case"uv6":this.attributeType=e3.UV6}else if(i instanceof mR)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=e3.Normal;break;case"tangentOutput":this.attributeType=e3.Tangent;break;case"uvOutput":this.attributeType=e3.UV1}})}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case e3.VertexColor:t="VERTEXCOLOR_NME";break;case e3.Normal:t="NORMAL";break;case e3.Tangent:t="TANGENT";break;case e3.UV1:t="UV1";break;case e3.UV2:t="UV2";break;case e3.UV3:t="UV3";break;case e3.UV4:t="UV4";break;case e3.UV5:t="UV5";break;case e3.UV6:t="UV6"}let i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} +`),e.compilationString+=`${i} = ${this.input.associatedVariableName}; +`,t&&(e.compilationString+=`#else +`,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; +`,e.compilationString+=`#endif +`),this}serialize(){let e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.attributeType=null!==(r=e.attributeType)&&void 0!==r?r:e3.None}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.attributeType = ${this.attributeType}; +`}}iZ([aE("Attribute lookup",L.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:e3.None},{label:"Normal",value:e3.Normal},{label:"Tangent",value:e3.Tangent},{label:"Vertex Color",value:e3.VertexColor},{label:"UV1",value:e3.UV1},{label:"UV2",value:e3.UV2},{label:"UV3",value:e3.UV3},{label:"UV4",value:e3.UV4},{label:"UV5",value:e3.UV5},{label:"UV6",value:e3.UV6}]})],gK.prototype,"attributeType",void 0),t0["BABYLON.MeshAttributeExistsBlock"]=gK,function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(e4||(e4={}));class g$ extends ax{constructor(e){super(e,N.Neutral),this.type=e4.EaseInOutSine,this.registerInput("input",O.AutoDetect),this.registerOutput("output",O.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(O.Matrix),this._inputs[0].excludedConnectionPointTypes.push(O.Object),this._inputs[0].excludedConnectionPointTypes.push(O.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if("float"===t)return this._duplicateEntryDirect(e);let i=parseInt(t.replace("vec","")),r=` + vec${i} ret = vec${i}(0.0); + `;for(let t=1;t<=i;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+"return ret;\n"}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="",r="",s="";switch(this.input.type){case O.Float:s="float";break;case O.Vector2:s="vec2";break;case O.Vector3:case O.Color3:s="vec3";break;case O.Vector4:case O.Color4:s="vec4"}switch(r=e4[this.type]+"_"+s,this.type){case e4.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case e4.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case e4.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case e4.EaseInQuad:i="return v * v";break;case e4.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case e4.EaseInOutQuad:i=this._duplicateVector("VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0",s);break;case e4.EaseInCubic:i="return v * v * v";break;case e4.EaseOutCubic:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s);break;case e4.EaseInOutCubic:i=this._duplicateVector("VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0",s);break;case e4.EaseInQuart:i="return v * v * v * v";break;case e4.EaseOutQuart:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s);break;case e4.EaseInOutQuart:i=this._duplicateVector("VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0",s);break;case e4.EaseInQuint:i="return v * v * v * v * v";break;case e4.EaseOutQuint:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s);break;case e4.EaseInOutQuint:i=this._duplicateVector("VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0",s);break;case e4.EaseInExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)",s);break;case e4.EaseOutExpo:i=this._duplicateVector("VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)",s);break;case e4.EaseInOutExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0",s);break;case e4.EaseInCirc:i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s);break;case e4.EaseOutCirc:i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s);break;case e4.EaseInOutCirc:i=this._duplicateVector("VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0",s);break;case e4.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case e4.EaseOutBack:i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s);break;case e4.EaseInOutBack:i=this._duplicateVector("VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0",s);break;case e4.EaseInElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))",s);break;case e4.EaseOutElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0",s);break;case e4.EaseInOutElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0",s)}return e._emitFunction(r,`${s} ${r}(${s} v) {${i};} +`,""),e.compilationString+=this._declareOutput(t,e)+` = ${r}(${this.input.associatedVariableName}); +`,this}serialize(){let e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${e4[this.type]}; +`}}t0["BABYLON.CurveBlock"]=g$;class gq extends sh{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class gQ extends hA{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new gq,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;return!this._isEnabled||null==s||!s.texture||!lE.DecalMapEnabled||!t.texturesEnabled||s.isReady()}prepareDefines(e,t,i){let r=i.decalMap;this._isEnabled&&(null==r?void 0:r.texture)&&lE.DecalMapEnabled&&t.texturesEnabled?(e.DECAL&&e.GAMMADECAL===r.texture.gammaSpace||e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=r.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,nw.PrepareDefinesForMergedUV(r.texture,e,"DECAL")):(e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1)}hardBindForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;if(!this._isEnabled||!(null==s?void 0:s.texture)||!lE.DecalMapEnabled||!t.texturesEnabled)return;let n=this._material.isFrozen,a=s.texture;e.useUbo&&n&&e.isSync||(e.updateFloat4("vDecalInfos",a.coordinatesIndex,0,0,0),nw.BindTextureMatrix(a,e,"decal")),e.setTexture("decalSampler",a)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],gQ.prototype,"isEnabled",void 0),iZ([iW(),iz("_markAllSubMeshesAsTexturesDirty")],gQ.prototype,"smoothAlpha",void 0),t0["BABYLON.DecalMapConfiguration"]=gQ,function(e){e[e.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",e[e.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",e[e.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"}(e5||(e5={})),function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(e6||(e6={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(e8||(e8={}));class gZ{}gZ.DEFAULT_COLOR=io.White(),gZ.DEFAULT_WIDTH_ATTENUATED=1,gZ.DEFAULT_WIDTH=.1;class gJ{static ConvertPoints(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof t5){let t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof t5){let t=[];return e.forEach(e=>{t.push(e.flatMap(e=>[e.x,e.y,e.z]))}),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){let t=[];return e.forEach(e=>{t.push(Array.from(e))}),t}return[]}static OmitZeroLengthPredicate(e,t,i){let r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r}static OmitDuplicatesPredicate(e,t,i,r){let s=[];return gJ._SearchInPoints(e,t,r)||s.push([e,t]),gJ._SearchInPoints(t,i,r)||s.push([t,i]),gJ._SearchInPoints(i,e,r)||s.push([i,e]),0===s.length?null:s}static _SearchInPoints(e,t,i){var r,s,n;for(let a of i)for(let i=0;i{let s=e.getVerticesData(sf.PositionKind),n=e.getIndices();if(s&&n)for(let a=0,o=0;a[e.x,e.y,e.z])}static GetPointsCountInfo(e){let t=Array(e.length),i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){let t;if(0===e.length)return 0;t="number"==typeof e[0]?gJ.ToVector3Array(e):e;let i=ie.Vector3[0],r=0;for(let e=0;e{e.length>t?gJ.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach(e=>{r.push(e)}):(r.push(e.point1),r.push(e.point2))}),r}static SegmentizeLineBySegmentCount(e,t){let i="number"==typeof e[0]?gJ.ToVector3Array(e):e,r=gJ.GetLineLength(i)/t;return gJ.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){let t=[];for(let i=0;ie.length);return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){let s=t*i,n=0,a=0,o=e.length;for(let t=0;t[e.x,e.y,e.z])}static GetArrowCap(e,t,i,r,s,n=0,a=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[r,s,n,a]}}static GetPointsFromText(e,t,i,r,s=0,n=!0){let a=[];for(let o of function(e,t,i,r){let s=Array.from(e),n=t/r.resolution,a=(r.boundingBox.yMax-r.boundingBox.yMin+r.underlineThickness)*n,o=[],l=0,h=0;for(let e=0;e{gJ.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){let e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?` + uniform vec4 grl_aspect_resolution_lineWidth; + uniform mat4 grl_projection; + `:"",fragment:` + uniform vec4 grl_dashOptions; + uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; + uniform vec3 grl_singleColor; + `}}get isEnabled(){return!0}bindForSubMesh(e){var t;if(this._cameraFacing){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}else throw Error("GreasedLinePluginMaterial requires an active camera.");let i=ie.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}let i=ie.Vector4[0];i.x=gJ.BooleanToNumber(this.useDash),i.y=this._dashArray,i.z=this.dashOffset,i.w=this.dashRatio,e.updateVector4("grl_dashOptions",i);let r=ie.Vector4[1];r.x=this.colorMode,r.y=this.visibility,r.z=this.colorsTexture?this.colorsTexture.getSize().width:0,r.w=gJ.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",r),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",null!==(t=this.colorsTexture)&&void 0!==t?t:gZ.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===e8.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return g1.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){let e={CUSTOM_VERTEX_DEFINITIONS:` + attribute float grl_widths; + attribute vec3 grl_offsets; + attribute float grl_colorPointers; + + varying float grlCounters; + varying float grlColorPointer; + + #ifdef GREASED_LINE_CAMERA_FACING + attribute vec4 grl_previousAndSide; + attribute vec4 grl_nextAndCounters; + + vec2 grlFix( vec4 i, float aspect ) { + vec2 res = i.xy / i.w; + res.x *= aspect; + return res; + } + #else + attribute vec3 grl_slopes; + attribute float grl_counters; + #endif + `,CUSTOM_VERTEX_UPDATE_POSITION:` + #ifdef GREASED_LINE_CAMERA_FACING + vec3 grlPositionOffset = grl_offsets; + positionUpdated += grlPositionOffset; + #else + positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); + #endif + `,CUSTOM_VERTEX_MAIN_END:` + grlColorPointer = grl_colorPointers; + + #ifdef GREASED_LINE_CAMERA_FACING + + float grlAspect = grl_aspect_resolution_lineWidth.x; + float grlBaseWidth = grl_aspect_resolution_lineWidth.w; + + + vec3 grlPrevious = grl_previousAndSide.xyz; + float grlSide = grl_previousAndSide.w; + + vec3 grlNext = grl_nextAndCounters.xyz; + grlCounters = grl_nextAndCounters.w; + + mat4 grlMatrix = viewProjection * finalWorld; + vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); + vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); + vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); + + vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); + vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); + vec2 grlNextP = grlFix( grlNextPos, grlAspect ); + + float grlWidth = grlBaseWidth * grl_widths; + + vec2 grlDir; + if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); + else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); + else { + vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); + vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); + grlDir = normalize( grlDir1 + grlDir2 ); + } + vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); + #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM + grlNormal.xy *= -.5 * grlWidth; + #else + grlNormal.xy *= .5 * grlWidth; + #endif + + grlNormal *= grl_projection; + + #ifdef GREASED_LINE_SIZE_ATTENUATION + grlNormal.xy *= grlFinalPosition.w; + grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; + #endif + + grlFinalPosition.xy += grlNormal.xy * grlSide; + gl_Position = grlFinalPosition; + + vPositionW = vec3(grlFinalPosition); + #else + grlCounters = grl_counters; + #endif + `};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:` + varying float grlCounters; + varying float grlColorPointer; + uniform sampler2D grl_colors; + `,CUSTOM_FRAGMENT_MAIN_END:` + float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; + float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; + float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; + float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; + + float grlUseDash = grl_dashOptions.x; + float grlDashArray = grl_dashOptions.y; + float grlDashOffset = grl_dashOptions.z; + float grlDashRatio = grl_dashOptions.w; + + gl_FragColor.a *= step(grlCounters, grlVisibility); + if( gl_FragColor.a == 0. ) discard; + + if(grlUseDash == 1.){ + gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); + if (gl_FragColor.a == 0.) discard; + } + + #ifdef GREASED_LINE_HAS_COLOR + if (grlColorMode == ${e6.COLOR_MODE_SET}.) { + gl_FragColor.rgb = grl_singleColor; + } else if (grlColorMode == ${e6.COLOR_MODE_ADD}.) { + gl_FragColor.rgb += grl_singleColor; + } else if (grlColorMode == ${e6.COLOR_MODE_MULTIPLY}.) { + gl_FragColor.rgb *= grl_singleColor; + } + #else + if (grlUseColors == 1.) { + #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE + vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); + #else + vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); + #endif + if (grlColorMode == ${e6.COLOR_MODE_SET}.) { + gl_FragColor = grlColor; + } else if (grlColorMode == ${e6.COLOR_MODE_ADD}.) { + gl_FragColor += grlColor; + } else if (grlColorMode == ${e6.COLOR_MODE_MULTIPLY}.) { + gl_FragColor *= grlColor; + } + } + #endif + + `}:null}dispose(){var e;null===(e=this.colorsTexture)||void 0===e||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this.colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this.colorsTexture&&o===e.length&&!i){let t=gJ.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else null===(a=this.colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=gJ.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,t||this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;super.parse(e,t,i);let s=e.greasedLineMaterialOptions;null===(r=this.colorsTexture)||void 0===r||r.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=gJ.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):gJ.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var t;null===(t=e.colorsTexture)||void 0===t||t.dispose(),this._colors&&(e.colorsTexture=gJ.CreateColorsTexture(`${e._material.name}-colors-texture`,this._colors,e.colorsSampling,this._scene)),e.setColor(this.color,!0),e.colorsDistributionType=this.colorsDistributionType,e.colorsSampling=this.colorsSampling,e.colorMode=this.colorMode,e.useColors=this.useColors,e.visibility=this.visibility,e.useDash=this.useDash,e.dashCount=this.dashCount,e.dashRatio=this.dashRatio,e.dashOffset=this.dashOffset,e.width=this.width,e.sizeAttenuation=this.sizeAttenuation,e.resolution=this.resolution,e.markAllDefinesAsDirty()}}g1.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",t0[`BABYLON.${g1.GREASED_LINE_MATERIAL_NAME}`]=g1;let g2=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} +if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { +textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} +if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} +`;rO.ShadersStore.greasedLinePixelShader=g2;let g3=`precision highp float; +#include +attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; +#ifdef GREASED_LINE_CAMERA_FACING +attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} +#else +attribute vec3 grl_slopes;attribute float grl_counters; +#endif +void main() { +#include +grlColorPointer=grl_colorPointers; +#ifdef GREASED_LINE_CAMERA_FACING +float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=viewProjection*finalWorld ;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} +vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); +#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM +grlNormal.xy*=-.5*grlWidth; +#else +grlNormal.xy*=.5*grlWidth; +#endif +grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} +grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; +#else +grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; +#endif +} +`;rO.ShadersStore.greasedLineVertexShader=g3;class g4 extends ug{constructor(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f,m;let g=[`COLOR_DISTRIBUTION_TYPE_LINE ${e8.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${e8.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${e6.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${e6.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${e6.COLOR_MODE_MULTIPLY}.`],v=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&g.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(g.push("GREASED_LINE_CAMERA_FACING"),v.push("grl_previousAndSide","grl_nextAndCounters")):(v.push("grl_slopes"),v.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:v,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:g}),this._color=io.White(),this._colorsDistributionType=e8.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:gZ.DEFAULT_COLOR};let x=t.getEngine();this.visibility=null!==(r=i.visibility)&&void 0!==r?r:1,this.useDash=null!==(s=i.useDash)&&void 0!==s&&s,this.dashRatio=null!==(n=i.dashRatio)&&void 0!==n?n:.5,this.dashOffset=null!==(a=i.dashOffset)&&void 0!==a?a:0,this.dashCount=null!==(o=i.dashCount)&&void 0!==o?o:1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?gZ.DEFAULT_WIDTH_ATTENUATED:gZ.DEFAULT_WIDTH,this.sizeAttenuation=null!==(l=i.sizeAttenuation)&&void 0!==l&&l,this.color=null!==(h=i.color)&&void 0!==h?h:io.White(),this.useColors=null!==(u=i.useColors)&&void 0!==u&&u,this.colorsDistributionType=null!==(c=i.colorDistributionType)&&void 0!==c?c:e8.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(d=i.colorsSampling)&&void 0!==d?d:ae.NEAREST_NEAREST,this.colorMode=null!==(p=i.colorMode)&&void 0!==p?p:e6.COLOR_MODE_SET,this._colors=null!==(_=i.colors)&&void 0!==_?_:null,this._cameraFacing=null===(f=i.cameraFacing)||void 0===f||f,this.resolution=null!==(m=i.resolution)&&void 0!==m?m:new t4(x.getRenderWidth(),x.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=gJ.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),x.onDisposeObservable.add(()=>{gJ.DisposeEmptyColorsTexture()})}dispose(){var e;null===(e=this._colorsTexture)||void 0===e||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new t4(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this._colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this._colorsTexture&&o===e.length&&!i){let t=gJ.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else null===(a=this._colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=gJ.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}}get colorsTexture(){var e;return null!==(e=this._colorsTexture)&&void 0!==e?e:null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",gJ.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",gJ.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",gJ.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=null!=e?e:gZ.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r,s;let n=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),n.color&&(this.color=n.color),n.colorDistributionType&&(this.colorsDistributionType=n.colorDistributionType),n.colorsSampling&&(this.colorsSampling=n.colorsSampling),n.colorMode&&(this.colorMode=n.colorMode),n.useColors&&(this.useColors=n.useColors),n.visibility&&(this.visibility=n.visibility),n.useDash&&(this.useDash=n.useDash),n.dashCount&&(this.dashCount=n.dashCount),n.dashRatio&&(this.dashRatio=n.dashRatio),n.dashOffset&&(this.dashOffset=n.dashOffset),n.width&&(this.width=n.width),n.sizeAttenuation&&(this.sizeAttenuation=n.sizeAttenuation),n.resolution&&(this.resolution=n.resolution),n.colors?this.colorsTexture=gJ.CreateColorsTexture(`${this.name}-colors-texture`,n.colors,this.colorsSampling,this.getScene()):this.colorsTexture=gJ.PrepareEmptyColorsTexture(t),this._cameraFacing=null===(s=n.cameraFacing)||void 0===s||s,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}let g5=`#if defined(DBG_ENABLED) +attribute float dbg_initialPass; +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; +#endif`,g6=`#if defined(DBG_ENABLED) +float dbg_vertexIndex = mod(float(gl_VertexID), 3.); +if (dbg_vertexIndex == 0.0) { + dbg_vBarycentric = vec3(1.,0.,0.); +} +else if (dbg_vertexIndex == 1.0) { + dbg_vBarycentric = vec3(0.,1.,0.); +} +else { + dbg_vBarycentric = vec3(0.,0.,1.); +} + +dbg_vVertexWorldPos = vPositionW; +dbg_vPass = dbg_initialPass; +#endif`,g8=`#if defined(DBG_ENABLED) +uniform vec3 dbg_shadedDiffuseColor; +uniform vec4 dbg_shadedSpecularColorPower; +uniform vec3 dbg_thicknessRadiusScale; + +#if DBG_MODE == 2 || DBG_MODE == 3 + uniform vec3 dbg_vertexColor; +#endif + +#if DBG_MODE == 1 + uniform vec3 dbg_wireframeTrianglesColor; +#elif DBG_MODE == 3 + uniform vec3 dbg_wireframeVerticesColor; +#elif DBG_MODE == 4 || DBG_MODE == 5 + uniform vec3 dbg_uvPrimaryColor; + uniform vec3 dbg_uvSecondaryColor; +#elif DBG_MODE == 7 + uniform vec3 dbg_materialColor; +#endif +#endif`,g7=`#if defined(DBG_ENABLED) +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; + +#if !defined(DBG_MULTIPLY) + vec3 dbg_applyShading(vec3 color) { + vec3 N = vNormalW.xyz; + vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); + vec3 H = normalize(L + L); + float LdotN = clamp(dot(L,N), 0., 1.); + float HdotN = clamp(dot(H,N), 0., 1.); + float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); + color *= (LdotN / PI); + color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); + return color; + } +#endif + +#if DBG_MODE == 1 || DBG_MODE == 3 + float dbg_edgeFactor() { + vec3 d = fwidth(dbg_vBarycentric); + vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); + return min(min(a3.x, a3.y), a3.z); + } +#endif + +#if DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor() { + vec3 worldPos = vPositionW; + float dist = length(worldPos - dbg_vVertexWorldPos); + float camDist = length(worldPos - vEyePosition.xyz); + float d = sqrt(camDist) * .001; + return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); + } +#endif + +#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) + float dbg_checkerboardFactor(vec2 uv) { + vec2 f = fract(uv * dbg_thicknessRadiusScale.z); + f -= .5; + return (f.x * f.y) > 0. ? 1. : 0.; + } +#endif +#endif`,g9=`#if defined(DBG_ENABLED) +vec3 dbg_color = vec3(1.); +#if DBG_MODE == 1 + dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); +#elif DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor = dbg_cornerFactor(); + if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; + dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); + #if DBG_MODE == 3 + dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); + #endif +#elif DBG_MODE == 4 && defined(UV1) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); +#elif DBG_MODE == 5 && defined(UV2) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); +#elif DBG_MODE == 6 && defined(VERTEXCOLOR) + dbg_color = vColor.rgb; +#elif DBG_MODE == 7 + dbg_color = dbg_materialColor; +#endif + +#if defined(DBG_MULTIPLY) + gl_FragColor *= vec4(dbg_color, 1.); +#else + #if DBG_MODE != 6 + gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); + #else + gl_FragColor = vec4(dbg_color, 1.); + #endif +#endif +#endif`,ve=[new io(.98,.26,.38),new io(.47,.75,.3),new io(0,.26,.77),new io(.97,.6,.76),new io(.19,.63,.78),new io(.98,.8,.6),new io(.65,.43,.15),new io(.15,.47,.22),new io(.67,.71,.86),new io(.09,.46,.56),new io(.8,.98,.02),new io(.39,.29,.13),new io(.53,.63,.06),new io(.95,.96,.41),new io(1,.72,.94),new io(.63,.08,.31),new io(.66,.96,.95),new io(.22,.14,.19),new io(.14,.65,.59),new io(.93,1,.68),new io(.93,.14,.44),new io(.47,.86,.67),new io(.85,.07,.78),new io(.53,.64,.98),new io(.43,.37,.56),new io(.71,.65,.25),new io(.66,.19,.01),new io(.94,.53,.12),new io(.41,.44,.44),new io(.24,.71,.96),new io(.57,.28,.56),new io(.44,.98,.42)];!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(e7||(e7={}));class vt extends sh{constructor(){super(...arguments),this.DBG_MODE=e7.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class vi extends hA{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,r,s,n,a,o,l,h,u,c,d,p,_;let f=new vt;f.DBG_MODE=null!==(i=t.mode)&&void 0!==i?i:f.DBG_MODE,f.DBG_MULTIPLY=null!==(r=t.multiply)&&void 0!==r?r:f.DBG_MULTIPLY,super(e,"MeshDebug",200,f,!0,!0),this._mode=f.DBG_MODE,this._multiply=f.DBG_MULTIPLY,this.shadedDiffuseColor=null!==(s=t.shadedDiffuseColor)&&void 0!==s?s:new io(1,1,1),this.shadedSpecularColor=null!==(n=t.shadedSpecularColor)&&void 0!==n?n:new io(.8,.8,.8),this.shadedSpecularPower=null!==(a=t.shadedSpecularPower)&&void 0!==a?a:10,this.wireframeThickness=null!==(o=t.wireframeThickness)&&void 0!==o?o:.7,this.wireframeTrianglesColor=null!==(l=t.wireframeTrianglesColor)&&void 0!==l?l:new io(0,0,0),this.wireframeVerticesColor=null!==(h=t.wireframeVerticesColor)&&void 0!==h?h:new io(.8,.8,.8),this.vertexColor=null!==(u=t.vertexColor)&&void 0!==u?u:new io(0,0,0),this.vertexRadius=null!==(c=t.vertexRadius)&&void 0!==c?c:1.2,this.uvScale=null!==(d=t.uvScale)&&void 0!==d?d:20,this.uvPrimaryColor=null!==(p=t.uvPrimaryColor)&&void 0!==p?p:new io(1,1,1),this.uvSecondaryColor=null!==(_=t.uvSecondaryColor)&&void 0!==_?_:new io(.5,.5,.5),this._materialColor=vi.MaterialColors[vi._PluginCount++%vi.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().webGLVersion){ig.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=e7.VERTICES&&this._mode!=e7.TRIANGLES&&this._mode!=e7.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||ig.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:g8}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:g5,CUSTOM_VERTEX_MAIN_END:g6}:{CUSTOM_FRAGMENT_DEFINITIONS:g7,CUSTOM_FRAGMENT_MAIN_END:g9}}static Reset(){this._PluginCount=0,this.MaterialColors=ve}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){let t=e.getVerticesDataKinds(),r=e.getIndices(),s={};for(let i of t)s[i]=e.getVerticesData(i);i=function(){for(let i of(e.setIndices(r),t)){let t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,s[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let r=Array.from(e.getIndices()),s=[];for(let e=0;e{let a=n.data_type(),o=n.num_components(),l=n.normalized(),h=n.byte_stride(),c=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 Error(`Invalid data type ${a}`);let p=u*o,_=p*d.typedArrayConstructor.BYTES_PER_ELEMENT,f=e._malloc(_);try{t.GetAttributeDataArrayForAllPoints(i,n,a,_,f);let e=new d.typedArrayConstructor(d.heap.buffer,f,p);s(r,e.slice(),o,c,h,l)}finally{e._free(f)}};if(i)for(let e in i){let t=i[e],r=n.GetAttributeByUniqueId(o,t);c(n,o,e,r)}else{let t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(let e in t){let i=n.GetAttributeId(o,t[e]);if(-1!==i){let t=n.GetAttribute(o,i);c(n,o,e,t)}}}return u}finally{o&&e.destroy(o),a&&e.destroy(a),n&&e.destroy(n)}}function vs(){let e;onmessage=t=>{let i=t.data;switch(i.id){case"init":{let t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw Error("Draco decoder module is not available");e.then(e=>{let t=vr(e,i.dataView,i.attributes,e=>{postMessage({id:"indices",data:e},[e.buffer])},(e,t,i,r,s,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:s,normalized:n},[t.buffer])});postMessage({id:"decodeMeshDone",totalVertices:t})})}}}vi._PluginCount=0,vi.MaterialColors=ve,iZ([iX()],vi.prototype,"_materialColor",void 0),iZ([iW()],vi.prototype,"_isEnabled",void 0),iZ([iW(),iz("_markAllDefinesAsDirty")],vi.prototype,"mode",void 0),iZ([iW(),iz("_markAllDefinesAsDirty")],vi.prototype,"multiply",void 0),iZ([iX()],vi.prototype,"shadedDiffuseColor",void 0),iZ([iX()],vi.prototype,"shadedSpecularColor",void 0),iZ([iW()],vi.prototype,"shadedSpecularPower",void 0),iZ([iW()],vi.prototype,"wireframeThickness",void 0),iZ([iX()],vi.prototype,"wireframeTrianglesColor",void 0),iZ([iX()],vi.prototype,"wireframeVerticesColor",void 0),iZ([iX()],vi.prototype,"vertexColor",void 0),iZ([iW()],vi.prototype,"vertexRadius",void 0),iZ([iW()],vi.prototype,"uvScale",void 0),iZ([iX()],vi.prototype,"uvPrimaryColor",void 0),iZ([iX()],vi.prototype,"uvSecondaryColor",void 0),t0["BABYLON.MeshDebugPluginMaterial"]=vi,Object.defineProperty(hD.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new gQ(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(_u.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new gQ(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(nM.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});class vn{static get DecoderAvailable(){let e=vn.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 vn._Default||(vn._Default=new vn),vn._Default}constructor(e=vn.DefaultNumWorkers){let t=vn.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:ss.GetBabylonScriptURL(t.wasmUrl,!0),wasmBinaryPromise:ss.LoadFileAsync(ss.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:ss.GetBabylonScriptURL(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then(t=>{let r=`${vr}(${vs})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));return new _E(e,()=>new Promise((e,r)=>{let n=new Worker(s),a=e=>{n.removeEventListener("error",a),n.removeEventListener("message",o),r(e)},o=t=>{"initDone"===t.data.id&&(n.removeEventListener("error",a),n.removeEventListener("message",o),e(n))};n.addEventListener("error",a),n.addEventListener("message",o),n.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))}):this._decoderModulePromise=i.wasmBinaryPromise.then(e=>{if(!i.url)throw Error("Draco decoder module is not available");return ss.LoadBabylonScriptAsync(i.url).then(()=>new Promise(t=>{DracoDecoderModule({wasmBinary:e}).then(e=>{t({module:e})})}))})}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then(e=>{e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then(()=>{}):this._decoderModulePromise?this._decoderModulePromise.then(()=>{}):Promise.resolve()}_decodeMeshAsync(e,t,i){let r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),s=(e,t)=>i&&void 0!==i[e]?(t!==i[e]&&ig.Warn(`Normalized flag from Draco data (${t}) does not match normalized flag from glTF accessor (${i[e]}). Using flag from glTF accessor.`),i[e]):t;if(this._workerPoolPromise)return this._workerPoolPromise.then(e=>new Promise((i,n)=>{e.push((e,a)=>{let o=null,l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",u),n(t),a()},u=t=>{let r=t.data;switch(r.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",u),i({indices:o,attributes:l,totalVertices:r.totalVertices}),a();break;case"indices":o=r.data;break;case"attribute":l.push({kind:r.kind,data:r.data,size:r.size,byteOffset:r.byteOffset,byteStride:r.byteStride,normalized:s(r.kind,r.normalized)})}};e.addEventListener("error",h),e.addEventListener("message",u);let c=r.slice();e.postMessage({id:"decodeMesh",dataView:c,attributes:t},[c.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(e=>{let i=null,s=[],n=vr(e.module,r,t,e=>{i=e},(e,t,i,r,n,a)=>{s.push({kind:e,data:t,size:i,byteOffset:r,byteStride:n,normalized:a})});return{indices:i,attributes:s,totalVertices:n}});throw Error("Draco decoder module is not available")}decodeMeshToGeometryAsync(e,t,i,r){return this._decodeMeshAsync(i,r).then(i=>{let r=new nT(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new sf(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}_decodeMeshToGeometryForGltfAsync(e,t,i,r,s){return this._decodeMeshAsync(i,r,s).then(i=>{let r=new nT(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new sf(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}decodeMeshAsync(e,t){return this._decodeMeshAsync(e,t).then(e=>{let t=new ng;for(let i of(e.indices&&(t.indices=e.indices),e.attributes)){let r=sf.GetFloatData(i.data,i.size,sf.GetDataType(i.data),i.byteOffset,i.byteStride,i.normalized,e.totalVertices);t.set(r,i.kind)}return t})}}vn.Configuration={decoder:{wasmUrl:`${ss._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${ss._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${ss._DefaultCdnUrl}/draco_decoder_gltf.js`}},vn.DefaultNumWorkers=vn.GetDefaultNumWorkers(),vn._Default=null;class va{static get Default(){return va._Default||(va._Default=new va),va._Default}constructor(){let e=va.Configuration.decoder;this._decoderModulePromise=ss.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then(()=>{let n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,r,s),n})}}va.Configuration={decoder:{url:`${ss._DefaultCdnUrl}/meshopt_decoder.js`}},va._Default=null;let vo=0;class vl{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){var e,t;return new vl(this.pos.clone(),this.normal.clone(),null===(e=this.uv)||void 0===e?void 0:e.clone(),null===(t=this.vertColor)||void 0===t?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new vl(t5.Lerp(this.pos,e.pos,t),t5.Lerp(this.normal,e.normal,t),this.uv&&e.uv?t4.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?il.Lerp(this.vertColor,e.vertColor,t):void 0)}}class vh{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){let r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;let n=t5.Normalize(t5.Cross(r,s));return new vh(n,t5.Dot(n,e))}clone(){return new vh(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let n,a;let o=0,l=[];for(n=0;nvh.EPSILON?1:0;o|=t,l.push(t)}switch(o){case 0:(t5.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{let t;let i=[],o=[];for(n=0;n=3&&(t=new vu(i,e.shared)).plane&&r.push(t),o.length>=3&&(t=new vu(o,e.shared)).plane&&s.push(t)}}}}vh.EPSILON=1e-5;class vu{constructor(e,t){this.vertices=e,this.shared=t,this.plane=vh.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){return new vu(this.vertices.map(e=>e.clone()),this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}class vc{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=[],e&&this.build(e)}clone(){let e=new vc;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(e=>e.clone()),e}invert(){for(let e=0;ee.clone()),e.copyTransformAttributes(this),e}union(e){let t=new vc(this.clone()._polygons),i=new vc(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),vd._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){let t=new vc(this._polygons),i=new vc(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){let t=new vc(this.clone()._polygons),i=new vc(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),vd._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){let t=new vc(this._polygons),i=new vc(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){let t=new vc(this.clone()._polygons),i=new vc(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),vd._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){let t=new vc(this._polygons),i=new vc(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){let e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){let i;let r=this.matrix.clone();r.invert();let s=this._polygons,n=[],a=[],o=[],l=null,h=null,u=t5.Zero(),c=t5.Zero(),d=t4.Zero(),p=new il(0,0,0,0),_=[0,0,0],f={};for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId),this.toVertexData(e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:Infinity,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),r=o[e.shared.meshId][e.shared.subMeshId]},()=>{r.indexStart=Math.min(a,r.indexStart),r.indexEnd=Math.max(a,r.indexEnd),a++}).applyToMesh(s),i){let e=0,t;for(let i in s.subMeshes=[],o){for(let n in t=-1,o[i])r=o[i][n],nf.CreateFromIndices(r.materialIndex+e,r.indexStart,r.indexEnd-r.indexStart+1,s),t=Math.max(r.materialIndex,t);e+=++t}}return s}toMesh(e,t=null,i,r){let s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}}let vp=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vNormalW=normalize(normWorldSM*normalUpdated); +#endif +vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}`;rO.ShadersStore.meshUVSpaceRendererVertexShader=vp;let v_=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} +gl_FragColor=texture2D(textureSampler,vDecalTC);} +`;rO.ShadersStore.meshUVSpaceRendererPixelShader=v_,rO.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";let vf=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} +`;rO.ShadersStore.meshUVSpaceRendererMaskerPixelShader=vf;let vm=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;} +if (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;} +if (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;} +if (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;} +if (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}} +`;rO.ShadersStore.meshUVSpaceRendererFinaliserPixelShader=vm;let vg=`precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;} +`;rO.ShadersStore.meshUVSpaceRendererFinaliserVertexShader=vg,nX._TrailMeshParser=(e,t)=>vv.Parse(e,t);class vv extends nX{constructor(e,t,i,r=1,s=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=r,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){let e=this.getVerticesData(sf.PositionKind),t=this.getVerticesData(sf.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*this._sectionPolygonPointsCount;i{this._getSimplifier(e).simplify(t,i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{let t=this._getSimplifier(e),i=(i,r)=>{t.simplify(i,t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()})};sn.Run(e.settings.length,t=>{i(e.settings[t.index],()=>{t.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){return e.simplificationType,e9.QUADRATIC,new vC(e.mesh)}}!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(e9||(e9={}));class vT{constructor(e){this._vertices=e,this.error=[,,,,],this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class vb{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new vE,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class vE{constructor(e){this.data=Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,n,a,o,l){return this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[o]+this.data[t]*this.data[n]*this.data[a]-this.data[i]*this.data[s]*this.data[a]-this.data[e]*this.data[n]*this.data[o]-this.data[t]*this.data[r]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){let t=new vE;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new vE(vE.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}}class vS{constructor(e,t){this.vertexId=e,this.triangleId=t}}class vC{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=.001}simplify(e,t){this._initDecimatedMesh(),sn.Run(this._mesh.subMeshes.length,t=>{this._initWithMesh(t.index,()=>{this._runDecimation(e,t.index,()=>{t.executeNext()})},e.optimizeMesh)},()=>{setTimeout(()=>{t(this._reconstructedMesh)},0)})}_runDecimation(e,t,i){let r=~~(this._triangles.length*e.quality),s=0,n=this._triangles.length,a=(e,t)=>{setTimeout(()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{let t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i)&&!r.deleted&&!r.isDirty){for(let e=0;e<3;++e)if(r.error[e]t.indexOf(!0)||0>i.indexOf(!0))continue;let h=[];if(l.forEach(e=>{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))}),h.length%2!=0)continue;n.q=a.q.add(n.q),n.updatePosition(o);let u=this._references.length;s=this._updateTriangles(n,n,t,s),s=this._updateTriangles(n,a,i,s);let c=this._references.length-u;if(c<=n.triangleCount){if(c)for(let e=0;en-s<=r)},0)};sn.Run(this.decimationIterations,e=>{n-s<=r?e.breakLoop():a(e.index,()=>{e.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];let r=this._mesh.getVerticesData(sf.PositionKind),s=this._mesh.getIndices(),n=this._mesh.subMeshes[e],a=e=>{if(i){for(let t=0;t>0,e=>{if(!r)return;let t=e+n.verticesStart,i=t5.FromArray(r,3*t),s=a(i)||new vb(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),o.push(s.id)},()=>{sn.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,e=>{if(!s)return;let t=3*(n.indexStart/3+e),i=s[t+0],r=s[t+1],a=s[t+2],l=new vT([this._vertices[o[i-n.verticesStart]],this._vertices[o[r-n.verticesStart]],this._vertices[o[a-n.verticesStart]]]);l.originalOffset=t,this._triangles.push(l)},()=>{this._init(t)})})}_init(e){sn.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];t.normal=t5.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(vE.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-t5.Dot(t.normal,t._vertices[0].position)))},()=>{sn.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])},()=>{e()})})}_reconstructMesh(e){let t,i,r;let s=[];for(t=0;t{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(a.push(h[3*t]),a.push(h[3*t+1]),a.push(h[3*t+2])),u&&u.length&&(o.push(u[2*t]),o.push(u[2*t+1])),c&&c.length&&(l.push(c[4*t]),l.push(c[4*t+1]),l.push(c[4*t+2]),l.push(c[4*t+3])),++d})}let p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];let m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(t=0;t{let t=g[i.originalOffset+e],r=i._vertices[e].originalOffsets.indexOf(t);r<0&&(r=0),m.push(i._vertices[e].id+r+_)});this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(sf.PositionKind,n),a.length>0&&this._reconstructedMesh.setVerticesData(sf.NormalKind,a),o.length>0&&this._reconstructedMesh.setVerticesData(sf.UVKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(sf.ColorKind,l);let v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach(e=>{nf.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),nf.AddToMesh(v.materialIndex,_,d,p,3*s.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new nX(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,s){for(let n=0;n.999)return!0;let d=t5.Cross(u,c).normalize();if(r[n]=!1,.2>t5.Dot(d,a.normal))return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;rvR.Parse(e,t);class vR extends vA{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(gJ.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i{var i;let r=[],s=[],n=[],a=gJ.GetLineLength(e);for(let i=0,o=0;o0&&(a=vR._CopyV3(o,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]));return a=vR._CompareV3(n-1,0,e)?vR._CopyV3(1,e):vR._CopyV3(n-1,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]),{previous:t,next:i,uvs:s,side:r}}_createVertexBuffers(){let e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new s_(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));let r=new s_(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_nextAndCounters",0,4));let s=new s_(t,this._widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;let n=new s_(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n,e}}vR._V_START=new t5,vR._V_END=new t5,vR._V_OFFSET_START=new t5,vR._V_OFFSET_END=new t5,nX._GreasedLineRibbonMeshParser=(e,t)=>vI.Parse(e,t);class vI extends vA{constructor(e,t,i,r){var s;if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=null!==(s=i.widths)&&void 0!==s?s:[],this._ribbonWidths=[],this._pathsOptions=null!=r?r:[],i.points&&this.addPoints(gJ.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{let i=vI._ConvertToRibbonPath(e,o.ribbonOptions,this._scene.useRightHandedSystem,s?s[t]:s);n=this._preprocess(i,n,o)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var i,r,s;let n=e.length;if(n<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";let a=[],o=[],l=e[0];for(let t=0;t2)for(let e=0;e0&&(h[0]+=1,h[1]+=1),o.push(h[1]+(e%2!=0?n:0),h[0],h[2]),u&&o.push(h[0],h[1]+(e%2!=0?n:0),h[2])}else for(let e=0;ee.y&&e.x>e.z?i?vI._RightHandedForwardReadOnlyQuaternion:vI._LeftHandedForwardReadOnlyQuaternion:vI._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(a,a,a),s.push(u.add(h)),n.push(u.subtract(h))}r||(s.push(o[o.length-1].add(h)),n.push(o[o.length-1].subtract(h)))}return[s,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&(null==i?void 0:i.x)!==1?e.y===t.y?vI.DIRECTION_XZ:e.z===t.z?vI.DIRECTION_XY:vI.DIRECTION_XZ:vI.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={},s=[];iP.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),iP.DeepCopy(i,r,["instance"],void 0,!0);let n=new vI(e,this._scene,r,s);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){let i=e.lineOptions;return new vI(e.name,t,i,e.pathOptions)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){let t=e.length;this._vSegmentLengths=Array(t),this._vTotalLengths=Array(t);let i=0;for(let r=0;r=this._thinInstanceDataStorage.instancesCount)return!1;let r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},nX.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===sf.ColorKind&&(e=sf.ColorInstanceKind),!!this._userThinInstanceBuffersStorage&&!!this._userThinInstanceBuffersStorage.data[e]&&!(t>=this._thinInstanceDataStorage.instancesCount)&&(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),r&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(nX.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;let r=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData;e<=(r?r.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),nX.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===sf.ColorKind&&(e=sf.ColorInstanceKind);let r=new s_(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},nX.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!1){var s,n,a;i=i||16,"matrix"===e?(null===(s=this._thinInstanceDataStorage.matrixBuffer)||void 0===s||s.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(n=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===n||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===sf.ColorKind&&(e=sf.ColorInstanceKind),null===t?(null===(a=this._userThinInstanceBuffersStorage)||void 0===a?void 0:a.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]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new sf(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},nX.prototype.thinInstanceBufferUpdated=function(e){var t,i,r;"matrix"===e?null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):"previousMatrix"===e?null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(e===sf.ColorKind&&(e=sf.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},nX.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var r;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===sf.ColorKind&&(e=sf.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},nX.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];let e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){var t;return this.isConnected?(null===(t=this._connectedPoint)||void 0===t?void 0:t._storedFunction)?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=[],this._type=tn.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new tj,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===ta.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==tn.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?ta.Compatible:ta.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return ta.TypeIncompatible;let r=i,s=t;return(this.direction===to.Input&&(r=t,s=i),r.isAnAncestorOf(s))?ta.HierarchyIssue:ta.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t0){if(!this._outputs.some(e=>e.hasEndpoints)&&!this.isDebug)return!1;this.outputs.forEach(e=>e._resetCounters())}for(let t of(this._buildId=e.buildId,this._inputs)){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}let i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&ig.Log(`Building ${this.name} [${this.getClassName()}]`);let t=ra.Now;for(let i of(this._buildBlock(e),this._buildExecutionTime=ra.Now-t,this._outputs))for(let t of i.endpoints){let i=t.ownerBlock;i&&i.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach(e=>{let t=this.inputs.find(t=>t.name===e.name);if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value)){if("number"===e.valueType)t.value=e.value;else{let i=t0[e.valueType];i&&(t.value=i.FromArray(e.value))}}}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame}; +`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` +// ${this.getClassName()} +`;this.comments&&(r+=`// ${this.comments} +`);let s=this.getClassName();if("GeometryInputBlock"===s){let e=this.type;r+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e}); +`}else r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}"); +`;for(let i of(r+=this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){let e=this.serialize(),t=t0[e.customType];if(t){let i=new t;return i._deserialize(e),i}return null}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose();this.onBuildObservable.clear()}}iZ([iW("comment")],vM.prototype,"comments",void 0);class vD extends vM{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",tn.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}t0["BABYLON.GeometryOutputBlock"]=vD,function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(tl||(tl={}));class vO{constructor(){this._rotationMatrix=new t7,this._scalingMatrix=new t7,this._positionMatrix=new t7,this._scalingRotationMatrix=new t7,this._transformMatrix=new t7,this._tempVector3=new t5,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;let i=this.executionContext.getExecutionIndex();switch(e){case tl.Positions:if(this.executionContext.getOverridePositionsContextualValue)return this.executionContext.getOverridePositionsContextualValue();if(!this.geometryContext||!this.geometryContext.positions)return t5.Zero();return t5.FromArray(this.geometryContext.positions,3*i);case tl.Normals:if(this.executionContext.getOverrideNormalsContextualValue)return this.executionContext.getOverrideNormalsContextualValue();if(!this.geometryContext||!this.geometryContext.normals)return t5.Zero();return t5.FromArray(this.geometryContext.normals,3*i);case tl.Colors:if(!this.geometryContext||!this.geometryContext.colors)return t6.Zero();return t6.FromArray(this.geometryContext.colors,4*i);case tl.Tangents:if(!this.geometryContext||!this.geometryContext.tangents)return t6.Zero();return t6.FromArray(this.geometryContext.tangents,4*i);case tl.UV:if(this.executionContext.getOverrideUVs1ContextualValue)return this.executionContext.getOverrideUVs1ContextualValue();if(!this.geometryContext||!this.geometryContext.uvs)return t4.Zero();return t4.FromArray(this.geometryContext.uvs,2*i);case tl.UV2:if(!this.geometryContext||!this.geometryContext.uvs2)return t4.Zero();return t4.FromArray(this.geometryContext.uvs2,2*i);case tl.UV3:if(!this.geometryContext||!this.geometryContext.uvs3)return t4.Zero();return t4.FromArray(this.geometryContext.uvs3,2*i);case tl.UV4:if(!this.geometryContext||!this.geometryContext.uvs4)return t4.Zero();return t4.FromArray(this.geometryContext.uvs4,2*i);case tl.UV5:if(!this.geometryContext||!this.geometryContext.uvs5)return t4.Zero();return t4.FromArray(this.geometryContext.uvs5,2*i);case tl.UV6:if(!this.geometryContext||!this.geometryContext.uvs6)return t4.Zero();return t4.FromArray(this.geometryContext.uvs6,2*i);case tl.VertexID:return i;case tl.FaceID:return this.executionContext.getExecutionFaceIndex();case tl.LoopID:return this.executionContext.getExecutionLoopIndex();case tl.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case tl.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case tl.CollectionID:if(!this.geometryContext||!this.geometryContext.metadata)return 0;return this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){let i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case tn.Vector2:return new t4(i,i);case tn.Vector3:return new t5(i,i,i);case tn.Vector4:return new t6(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;let s=e.getConnectedValue(this);if((null===(r=e._connectedPoint)||void 0===r?void 0:r.type)===t)return s;switch(t){case tn.Vector2:return new t4(s,s);case tn.Vector3:return new t5(s,s,s);case tn.Vector4:return new t6(s,s,s,s)}return null}emitErrors(){let e="";for(let t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. +`;for(let t of this.noContextualData)e+=`Contextual input ${tl[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block). +`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){t7.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),t7.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),t7.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${tl[this._contextualSource]}; +`;let t=[],i="";switch(this.type){case tn.Float:case tn.Int:i=`${this.value}`;break;case tn.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case tn.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case tn.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),(this.type===tn.Float||this.type===tn.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){let e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=t0[e.valueType];t&&(this._storedValue=t.FromArray(e.value))}}}}t0["BABYLON.GeometryInputBlock"]=vN;class vF extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",tn.Float,!0,1),this.registerInput("width",tn.Float,!0,0),this.registerInput("height",tn.Float,!0,0),this.registerInput("depth",tn.Float,!0,0),this.registerInput("subdivisions",tn.Int,!0,1),this.registerInput("subdivisionsX",tn.Int,!0,0),this.registerInput("subdivisionsY",tn.Int,!0,0),this.registerInput("subdivisionsZ",tn.Int,!0,0),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){let e=new vN("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new vN("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new vN("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){let e=new vN("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){let t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);let i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),n&&(t.depthSegments=n),function(e){let t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),a=0|(e.depthSegments||e.segments||1),o=new t7,l=new t7,h=new t7,u=hH({width:t,height:r,subdivisionsX:s,subdivisionsY:a});t7.TranslationToRef(0,-i/2,0,l),t7.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),u.transform(h);let c=hH({width:t,height:r,subdivisionsX:s,subdivisionsY:a});t7.TranslationToRef(0,i/2,0,h),c.transform(h);let d=hH({width:i,height:r,subdivisionsX:n,subdivisionsY:a});t7.TranslationToRef(-t/2,0,0,l),t7.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);let p=hH({width:i,height:r,subdivisionsX:n,subdivisionsY:a});t7.TranslationToRef(t/2,0,0,l),t7.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),p.transform(h);let _=hH({width:t,height:i,subdivisionsX:s,subdivisionsY:n});t7.TranslationToRef(0,0,-r/2,l),t7.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h);let f=hH({width:t,height:i,subdivisionsX:s,subdivisionsY:n});return t7.TranslationToRef(0,0,r/2,l),t7.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h),u.merge([c,p,d,_,f],!0),u}(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vF.prototype,"evaluateContext",void 0),t0["BABYLON.BoxBlock"]=vF;class vw{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=vw._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new tj,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){ss.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){let i=e&&e.editorURL?e.editorURL:vw.EditorURL;ss.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){let t=Object.assign({nodeGeometry:this},e);this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";let r=ra.Now;this._initializeBlock(this.outputBlock,i);let s=new vO;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=vw._BuildIdGenerator++),this._buildExecutionTime=ra.Now-r,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;let i=new nX(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){for(let i of(e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();let i={};for(let t of e.blocks){let e=t0[t.customType];if(e){let r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let r=i[t];r&&r.attachToEndpoint(e)}}for(let r=0;re.targetConnectionName)&&!t||this._restoreConnections(n,e,i)}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){let r=e.locations||e.editorData.locations;for(let e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);let s=[];for(let e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}generateCode(){let e=[],t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); +`;for(let s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="// Connections\n"+this.outputBlock._dumpCodeForOutputConnections(e)+"// Output nodes\n"+`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; +`+`nodeGeometry.build(); +`),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}setToDefault(){this.clear(),this.editorData=null;let e=new vF("Box");e.autoConfigure();let t=new vD("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){let t=this.serialize(),i=i$.Clone(()=>new vw(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){let t=e?{}:i$.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];for(let r of(e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[],i))t.blocks.push(r.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){let t=new vw(e);return t.setToDefault(),t.build(),t}static Parse(e){let t=i$.Parse(()=>new vw(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(vw.CreateDefault("blank")):new Promise((r,s)=>{let n=new i2;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let a=JSON.parse(JSON.parse(JSON.parse(n.responseText).jsonPayload).nodeGeometry);t||(t=i$.Parse(()=>new vw(e),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}vw._BuildIdGenerator=0,vw.EditorURL=`${ss._DefaultCdnUrl}/v${nC.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,vw.SnippetUrl="https://snippet.babylonjs.com",iZ([iW()],vw.prototype,"name",void 0),iZ([iW("comment")],vw.prototype,"comment",void 0);class vL extends vM{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=.001,this.registerInput("geometry",tn.Geometry),this.registerOutput("output",tn.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e),i=[],r={};for(let e=0;er[e]),s};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`+`${this._codeVariableName}.epsilon = ${this.epsilon}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vL.prototype,"evaluateContext",void 0),iZ([aE("Epsilon",L.Float,"ADVANCED",{notifiers:{rebuild:!0}})],vL.prototype,"epsilon",void 0),t0["BABYLON.GeometryOptimizeBlock"]=vL;class vB extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",tn.Float,!0,1),this.registerInput("width",tn.Float,!0,0),this.registerInput("height",tn.Float,!0,0),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){let e=new vN("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new vN("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new vN("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){let t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),aa(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vB.prototype,"evaluateContext",void 0),t0["BABYLON.PlaneBlock"]=vB;class vU extends vM{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",tn.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}let e=ng.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){let e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=ng.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=ng.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}iZ([aE("Serialize cached data",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vU.prototype,"serializedCachedData",void 0),t0["BABYLON.MeshBlock"]=vU;class vV extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",tn.Float,!0,1),this.registerInput("radiusX",tn.Float,!0,0),this.registerInput("radiusY",tn.Float,!0,0),this.registerInput("radiusZ",tn.Float,!0,0),this.registerInput("subdivisions",tn.Int,!0,4),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new vN("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),or(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vV.prototype,"evaluateContext",void 0),t0["BABYLON.IcoSphereBlock"]=vV;class vk extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",tn.Int,!0,32),this.registerInput("diameter",tn.Float,!0,1),this.registerInput("diameterX",tn.Float,!0,0),this.registerInput("diameterY",tn.Float,!0,0),this.registerInput("diameterZ",tn.Float,!0,0),this.registerInput("arc",tn.Float,!0,1),this.registerInput("slice",tn.Float,!0,1),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new vN("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),uo(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vk.prototype,"evaluateContext",void 0),t0["BABYLON.SphereBlock"]=vk;class vG extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",tn.Float,!0,1),this.registerInput("height",tn.Float,!0,1),this.registerInput("subdivisions",tn.Int,!0,1),this.registerInput("subdivisionsX",tn.Int,!0,0),this.registerInput("subdivisionsY",tn.Int,!0,0),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){let e=new vN("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new vN("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),hH(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vG.prototype,"evaluateContext",void 0),t0["BABYLON.GridBlock"]=vG;class vz extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",tn.Float,!0,1),this.registerInput("thickness",tn.Float,!0,.5),this.registerInput("tessellation",tn.Int,!0,16),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new vN("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),hK(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vz.prototype,"evaluateContext",void 0),t0["BABYLON.TorusBlock"]=vz;class vW extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",tn.Float,!0,25),this.registerInput("diameter",tn.Float,!0,1),this.registerInput("diameterTop",tn.Float,!0,-1),this.registerInput("diameterBottom",tn.Float,!0,-1),this.registerInput("subdivisions",tn.Int,!0,1),this.registerInput("tessellation",tn.Int,!0,24),this.registerInput("arc",tn.Float,!0,1),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new vN("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){let e=new vN("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),h9(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vW.prototype,"evaluateContext",void 0),t0["BABYLON.CylinderBlock"]=vW;class vH extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",tn.Float,!0,1),this.registerInput("radius",tn.Float,!0,.25),this.registerInput("tessellation",tn.Int,!0,16),this.registerInput("subdivisions",tn.Int,!0,2),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){let e=new vN("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){let e=new vN("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),uh(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vH.prototype,"evaluateContext",void 0),t0["BABYLON.CapsuleBlock"]=vH;class vX extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",tn.Float,!0,.5),this.registerInput("tessellation",tn.Int,!0,64),this.registerInput("arc",tn.Float,!0,1),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new vN("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),ud(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vX.prototype,"evaluateContext",void 0),t0["BABYLON.DiscBlock"]=vX;class vY extends vM{constructor(e){super(e),this.registerOutput("geometry",tn.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}t0["BABYLON.NullBlock"]=vY;class vj extends vM{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tn.Geometry),this.registerInput("positions",tn.Vector3),this.registerOutput("output",tn.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}let t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndext.getConnectedValue(e)+i.getConnectedValue(e):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case th.Subtract:e=r?e=>t.getConnectedValue(e)-i.getConnectedValue(e):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case th.Multiply:e=r?e=>t.getConnectedValue(e)*i.getConnectedValue(e):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case th.Divide:e=r?e=>t.getConnectedValue(e)/i.getConnectedValue(e):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case th.Min:if(r)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case tn.Vector2:e=e=>t4.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tn.Vector3:e=e=>t5.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tn.Vector4:e=e=>t6.Minimize(t.getConnectedValue(e),e.adapt(i,t.type))}break;case th.Max:if(r)e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case tn.Vector2:e=e=>t4.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tn.Vector3:e=e=>t5.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tn.Vector4:e=e=>t6.Maximize(t.getConnectedValue(e),e.adapt(i,t.type))}}this.output._storedFunction=i=>t.type===tn.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${th[this.operation]}; +`}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}iZ([aE("Operation",L.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:th.Add},{label:"Subtract",value:th.Subtract},{label:"Multiply",value:th.Multiply},{label:"Divide",value:th.Divide},{label:"Max",value:th.Max},{label:"Min",value:th.Min}]})],vZ.prototype,"operation",void 0),t0["BABYLON.MathBlock"]=vZ;class vJ extends vM{constructor(e){super(e),this.registerInput("value",tn.AutoDetect),this.registerInput("fromMin",tn.Float,!0,0),this.registerInput("fromMax",tn.Float,!0,1),this.registerInput("toMin",tn.Float,!0,0),this.registerInput("toMax",tn.Float,!0,1),this.registerOutput("output",tn.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tn.Vector2),this._inputs[0].excludedConnectionPointTypes.push(tn.Vector3),this._inputs[0].excludedConnectionPointTypes.push(tn.Vector4),this._inputs[0].excludedConnectionPointTypes.push(tn.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tn.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tn.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{let t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),n=(t-i)/(r-i)*(this.toMax.getConnectedValue(e)-s)+s;return this.output.type===tn.Int?Math.floor(n):n}}}t0["BABYLON.MapRangeBlock"]=vJ,function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(tu||(tu={}));class v0 extends vM{constructor(e){super(e),this.test=tu.Equal,this.registerInput("left",tn.Float),this.registerInput("right",tn.Float,!0,0),this.registerInput("ifTrue",tn.AutoDetect,!0,1),this.registerInput("ifFalse",tn.AutoDetect,!0,0),this.registerOutput("output",tn.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=tn.Float,this._inputs[0].acceptedConnectionPointTypes.push(tn.Int),this._inputs[1].acceptedConnectionPointTypes.push(tn.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let e=e=>{let t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e),r=!1;switch(this.test){case tu.Equal:r=tK.WithinEpsilon(t,i,.001);break;case tu.NotEqual:r=t!==i;break;case tu.LessThan:r=ti;break;case tu.LessOrEqual:r=t<=i;break;case tu.GreaterOrEqual:r=t>=i;break;case tu.Xor:r=!!t&&!i||!t&&!!i;break;case tu.Or:r=!!t||!!i;break;case tu.And:r=!!t&&!!i}return r};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${tu[this.test]}; +`}serialize(){let e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}iZ([aE("Test",L.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:tu.Equal},{label:"NotEqual",value:tu.NotEqual},{label:"LessThan",value:tu.LessThan},{label:"GreaterThan",value:tu.GreaterThan},{label:"LessOrEqual",value:tu.LessOrEqual},{label:"GreaterOrEqual",value:tu.GreaterOrEqual},{label:"Xor",value:tu.Xor},{label:"Or",value:tu.Or},{label:"And",value:tu.And}]})],v0.prototype,"test",void 0),t0["BABYLON.ConditionBlock"]=v0,function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(tc||(tc={}));class v1 extends vM{constructor(e){super(e),this._currentLockId=-1,this.lockMode=tc.None,this.registerInput("min",tn.AutoDetect),this.registerInput("max",tn.AutoDetect),this.registerOutput("output",tn.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tn.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tn.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tn.Texture),this._inputs[1].excludedConnectionPointTypes.push(tn.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tn.Geometry),this._inputs[1].excludedConnectionPointTypes.push(tn.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){let e=new vN("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){let e=new vN("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case tn.Int:case tn.Float:e=e=>{let t=this.min.getConnectedValue(e)||0;return t+Math.random()*((this.max.getConnectedValue(e)||0)-t)};break;case tn.Vector2:e=e=>{let t=this.min.getConnectedValue(e)||t4.Zero(),i=this.max.getConnectedValue(e)||t4.Zero();return new t4(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case tn.Vector3:e=e=>{let t=this.min.getConnectedValue(e)||t5.Zero(),i=this.max.getConnectedValue(e)||t5.Zero();return new t5(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case tn.Vector4:e=e=>{let t=this.min.getConnectedValue(e)||t6.Zero(),i=this.max.getConnectedValue(e)||t6.Zero();return new t6(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==tc.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case tc.InstanceID:i=t.getContextualValue(tl.InstanceID,!0)||0;break;case tc.LoopID:i=t.getContextualValue(tl.LoopID,!0)||0}return(this._currentLockId!==i||this.lockMode===tc.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${tc[this.lockMode]}; +`}serialize(){let e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}iZ([aE("LockMode",L.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:tc.None},{label:"LoopID",value:tc.LoopID},{label:"InstanceID",value:tc.InstanceID}]})],v1.prototype,"lockMode",void 0),t0["BABYLON.RandomBlock"]=v1;class v2 extends vM{constructor(e){super(e),this.registerInput("offset",tn.Vector3,!0,t5.Zero()),this.registerInput("scale",tn.Float,!0,1),this.registerInput("octaves",tn.Float,!0,2,0,16),this.registerInput("roughness",tn.Float,!0,.5,0,1),this.registerOutput("output",tn.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,r){let s=15&e,n=s<8?t:i,a=s<4?i:12===s||14==s?t:r;return this._negateIf(n,s&n)+this._negateIf(a,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let r,s,n;return r=s=n=3735928584,n+=i,s+=t,r+=e,n^=s,n-=this._hashBitRotate(s,14),r^=n,r-=this._hashBitRotate(n,11),s^=r,s-=this._hashBitRotate(r,25),n^=s,n-=this._hashBitRotate(s,16),r^=n,r-=this._hashBitRotate(n,4),s^=r,s-=this._hashBitRotate(r,14),n^=s,n-=this._hashBitRotate(s,24)}_mix(e,t,i,r,s,n,a,o,l,h,u){let c=1-l,d=1-h;return(1-u)*(d*(e*c+t*l)+h*(i*c+r*l))+u*(d*(s*c+n*l)+h*(a*c+o*l))}_perlinNoise(e){let t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,n=e.y-i,a=e.z-r,o=this._fade(s),l=this._fade(n),h=this._fade(a);return this._mix(this._noiseGrad(this._hash(t,i,r),s,n,a),this._noiseGrad(this._hash(t+1,i,r),s-1,n,a),this._noiseGrad(this._hash(t,i+1,r),s,n-1,a),this._noiseGrad(this._hash(t+1,i+1,r),s-1,n-1,a),this._noiseGrad(this._hash(t,i,r+1),s,n,a-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,n,a-1),this._noiseGrad(this._hash(t,i+1,r+1),s,n-1,a-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,n-1,a-1),o,l,h)}_perlinSigned(e){return .982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){let n=new t5(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z),a=1,o=1,l=0,h=0,u=0|(e=tK.Clamp(e,0,15));for(let e=0;e<=u;e++)h+=this._perlin(n.scale(a))*o,l+=o,o*=tK.Clamp(t,0,1),a*=2;let c=e-Math.floor(e);if(0==c)return h/l;let d=h+this._perlin(n.scale(a))*o;return(1-c)*(h/=l)+c*(d/=l+o)}_buildBlock(){this.output._storedFunction=e=>{let t=e.getContextualValue(tl.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,n)}}}t0["BABYLON.NoiseBlock"]=v2;class v3 extends vM{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",tn.Geometry),this.registerInput("geometry1",tn.Geometry,!0),this.registerInput("geometry2",tn.Geometry,!0),this.registerInput("geometry3",tn.Geometry,!0),this.registerInput("geometry4",tn.Geometry,!0),this.registerOutput("output",tn.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{let t=this.geometry0.getConnectedValue(e),i=[];if(!t)return null;if(t=t.clone(),this.geometry1.isConnected){let t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){let t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){let t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){let t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],v3.prototype,"evaluateContext",void 0),t0["BABYLON.MergeGeometryBlock"]=v3;class v4 extends vM{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",tn.Geometry,!0),this.registerInput("geometry1",tn.Geometry,!0),this.registerInput("geometry2",tn.Geometry,!0),this.registerInput("geometry3",tn.Geometry,!0),this.registerInput("geometry4",tn.Geometry,!0),this.registerInput("geometry5",tn.Geometry,!0),this.registerInput("geometry6",tn.Geometry,!0),this.registerInput("geometry7",tn.Geometry,!0),this.registerInput("geometry8",tn.Geometry,!0),this.registerInput("geometry9",tn.Geometry,!0),this.registerOutput("output",tn.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){let s=e.getConnectedValue(t);s&&(s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s))}}_buildBlock(e){let t=e=>{let t=[];return(this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length)?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],v4.prototype,"evaluateContext",void 0),t0["BABYLON.GeometryCollectionBlock"]=v4;class v5 extends vM{constructor(e){super(e),this.registerInput("input",tn.AutoDetect),this.registerOutput("output",tn.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}t0["BABYLON.GeometryElbowBlock"]=v5;class v6 extends vM{constructor(e){super(e),this.registerInput("geometry",tn.Geometry),this.registerOutput("output",tn.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),ng.ComputeNormals(t.positions,t.indices,t.normals),t}}}t0["BABYLON.ComputeNormalsBlock"]=v6;class v8 extends vM{constructor(e){super(e),this.registerInput("xyzw ",tn.Vector4,!0),this.registerInput("xyz ",tn.Vector3,!0),this.registerInput("xy ",tn.Vector2,!0),this.registerInput("zw ",tn.Vector2,!0),this.registerInput("x ",tn.Float,!0),this.registerInput("y ",tn.Float,!0),this.registerInput("z ",tn.Float,!0),this.registerInput("w ",tn.Float,!0),this.registerOutput("xyzw",tn.Vector4),this.registerOutput("xyz",tn.Vector3),this.registerOutput("xy",tn.Vector2),this.registerOutput("zw",tn.Vector2),this.registerOutput("x",tn.Float),this.registerOutput("y",tn.Float),this.registerOutput("z",tn.Float),this.registerOutput("w",tn.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,u=this.xyzOut,c=this.xyOut,d=this.zwOut,p=this.xOut,_=this.yOut,f=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,u=0,c=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(u=i.getConnectedValue(e)),r.isConnected&&(c=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),n.isConnected){let t=n.getConnectedValue(e);t&&(h=t.x,u=t.y)}if(a.isConnected){let t=a.getConnectedValue(e);t&&(c=t.x,d=t.y)}if(o.isConnected){let t=o.getConnectedValue(e);t&&(h=t.x,u=t.y,c=t.z)}return new t6(h,u,c,d)};h._storedFunction=e=>g(e),u._storedFunction=e=>{let t=g(e);return new t5(t.x,t.y,t.z)},c._storedFunction=e=>{let t=g(e);return new t4(t.x,t.y)},d._storedFunction=e=>{let t=g(e);return new t4(t.z,t.w)},p._storedFunction=e=>g(e).x,_._storedFunction=e=>g(e).y,f._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}t0["BABYLON.VectorConverterBlock"]=v8;class v7 extends vM{constructor(e){super(e),this.registerInput("input",tn.AutoDetect),this.registerOutput("output",tn.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tn.Float),this._inputs[0].excludedConnectionPointTypes.push(tn.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tn.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tn.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize()}}t0["BABYLON.NormalizeVectorBlock"]=v7;class v9 extends vM{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tn.Geometry),this.registerInput("id",tn.Int,!0,0),this.registerOutput("output",tn.Geometry),this.id.acceptedConnectionPointTypes.push(tn.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let t=e=>{let t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;let i=new nm;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],v9.prototype,"evaluateContext",void 0),t0["BABYLON.SetMaterialIDBlock"]=v9,function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians"}(td||(td={}));class xe extends vM{constructor(e){super(e),this.operation=td.Cos,this.registerInput("input",tn.AutoDetect),this.registerOutput("output",tn.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tn.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tn.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tn.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case td.Cos:t=e=>Math.cos(e);break;case td.Sin:t=e=>Math.sin(e);break;case td.Abs:t=e=>Math.abs(e);break;case td.Exp:t=e=>Math.exp(e);break;case td.Round:t=e=>Math.round(e);break;case td.Floor:t=e=>Math.floor(e);break;case td.Ceiling:t=e=>Math.ceil(e);break;case td.Sqrt:t=e=>Math.sqrt(e);break;case td.Log:t=e=>Math.log(e);break;case td.Tan:t=e=>Math.tan(e);break;case td.ArcTan:t=e=>Math.atan(e);break;case td.ArcCos:t=e=>Math.acos(e);break;case td.ArcSin:t=e=>Math.asin(e);break;case td.Sign:t=e=>Math.sign(e);break;case td.Negate:t=e=>-e;break;case td.OneMinus:t=e=>1-e;break;case td.Reciprocal:t=e=>1/e;break;case td.ToRadians:t=e=>e*Math.PI/180;break;case td.ToDegrees:t=e=>180*e/Math.PI}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case tn.Int:case tn.Float:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return t(i)};break;case tn.Vector2:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new t4(t(i.x),t(i.y))};break;case tn.Vector3:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new t5(t(i.x),t(i.y),t(i.z))};break;case tn.Vector4:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new t6(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${td[this.operation]}; +`}}iZ([aE("Operation",L.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:td.Cos},{label:"Sin",value:td.Sin},{label:"Abs",value:td.Abs},{label:"Exp",value:td.Exp},{label:"Round",value:td.Round},{label:"Floor",value:td.Floor},{label:"Ceiling",value:td.Ceiling},{label:"Sqrt",value:td.Sqrt},{label:"Log",value:td.Log},{label:"Tan",value:td.Tan},{label:"ArcTan",value:td.ArcTan},{label:"ArcCos",value:td.ArcCos},{label:"ArcSin",value:td.ArcSin},{label:"Sign",value:td.Sign},{label:"Negate",value:td.Negate},{label:"OneMinus",value:td.OneMinus},{label:"Reciprocal",value:td.Reciprocal},{label:"ToDegrees",value:td.ToDegrees},{label:"ToRadians",value:td.ToRadians}]})],xe.prototype,"operation",void 0),t0["BABYLON.GeometryTrigonometryBlock"]=xe;class xt extends vM{constructor(e){super(e),this._rotationMatrix=new t7,this._scalingMatrix=new t7,this._translationMatrix=new t7,this._scalingRotationMatrix=new t7,this._transformMatrix=new t7,this.evaluateContext=!0,this.registerInput("value",tn.AutoDetect),this.registerInput("matrix",tn.Matrix,!0),this.registerInput("translation",tn.Vector3,!0,t5.Zero()),this.registerInput("rotation",tn.Vector3,!0,t5.Zero()),this.registerInput("scaling",tn.Vector3,!0,t5.One()),this.registerOutput("output",tn.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tn.Float),this._inputs[0].excludedConnectionPointTypes.push(tn.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tn.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let t=e=>{let t;let i=this.value.getConnectedValue(e);if(!i)return null;if(this.matrix.isConnected)t=this.matrix.getConnectedValue(e);else{let i=this.scaling.getConnectedValue(e),r=this.rotation.getConnectedValue(e),s=this.translation.getConnectedValue(e);t7.ScalingToRef(i.x,i.y,i.z,this._scalingMatrix),t7.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),t7.TranslationToRef(s.x,s.y,s.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),t=this._transformMatrix}switch(this.value.type){case tn.Geometry:{let e=i.clone();return e.transform(t),e}case tn.Vector2:return t4.Transform(i,t);case tn.Vector3:return t5.TransformCoordinates(i,t);case tn.Vector4:return t6.TransformCoordinates(i,t)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xt.prototype,"evaluateContext",void 0),t0["BABYLON.GeometryTransformBlock"]=xt;class xi extends vM{constructor(e){super(e),this.registerInput("angle",tn.Float,!1,0),this.registerOutput("matrix",tn.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new vN("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>t7.RotationX(this.angle.getConnectedValue(e))}}t0["BABYLON.RotationXBlock"]=xi;class xr extends vM{constructor(e){super(e),this.registerInput("angle",tn.Float,!1,0),this.registerOutput("matrix",tn.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new vN("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>t7.RotationY(this.angle.getConnectedValue(e))}}t0["BABYLON.RotationYBlock"]=xr;class xs extends vM{constructor(e){super(e),this.registerInput("angle",tn.Float,!1,0),this.registerOutput("matrix",tn.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new vN("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>t7.RotationZ(this.angle.getConnectedValue(e))}}t0["BABYLON.RotationZBlock"]=xs;class xn extends vM{constructor(e){super(e),this.registerInput("scale",tn.Vector3,!1,t5.One()),this.registerOutput("matrix",tn.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){let e=new vN("Scale");e.value=new t5(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.scale.getConnectedValue(e);return t7.Scaling(t.x,t.y,t.z)}}}t0["BABYLON.ScalingBlock"]=xn;class xa extends vM{constructor(e){super(e),this.registerInput("source",tn.Vector3,!0,t5.Up()),this.registerInput("target",tn.Vector3,!0,t5.Left()),this.registerOutput("matrix",tn.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new t7;return t.normalize(),i.normalize(),t7.RotationAlignToRef(t,i,r,!0),r}}}t0["BABYLON.AlignBlock"]=xa;class xo extends vM{constructor(e){super(e),this.registerInput("translation",tn.Vector3,!1,t5.Zero()),this.registerOutput("matrix",tn.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){let e=new vN("Translation");e.value=new t5(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.translation.getConnectedValue(e);return t7.Translation(t.x,t.y,t.z)}}}t0["BABYLON.TranslationBlock"]=xo;class xl extends vM{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",tn.Geometry),this.registerInput("instance",tn.Geometry,!0),this.registerInput("density",tn.Float,!0,1,0,1),this.registerInput("matrix",tn.Matrix,!0),this.registerInput("rotation",tn.Vector3,!0,t5.Zero()),this.registerInput("scaling",tn.Vector3,!0,t5.One()),this.scaling.acceptedConnectionPointTypes.push(tn.Float),this.registerOutput("output",tn.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3,i=[],r=new t5,s=[],n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexMath.abs(s[n]-e)&&.001>Math.abs(s[n+1]-t)&&.001>Math.abs(s[n+2]-i)){r=!0;break}r||(this._indexTranslation[s.length/3]=this._currentIndex,s.push(e,t,i))}t=(n=s).length/3}else this._indexTranslation=null;for(this._currentIndex=0;this._currentIndexs)continue;r.fromArray(n,3*this._currentIndex);let a=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(a,r,t,i)}else{let t=e.adaptInput(this.scaling,tn.Vector3,t5.OneReadOnly),s=this.rotation.getConnectedValue(e)||t5.ZeroReadOnly;e._instantiate(a,r,s,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; +`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xl.prototype,"evaluateContext",void 0),iZ([aE("Remove duplicated positions",L.Boolean,"ADVANCED",{notifiers:{update:!0}})],xl.prototype,"removeDuplicatedPositions",void 0),t0["BABYLON.InstantiateOnVerticesBlock"]=xl;class xh extends vM{constructor(e){super(e),this._currentPosition=new t5,this._currentUV=new t4,this._vertex0=new t5,this._vertex1=new t5,this._vertex2=new t5,this._tempVector0=new t5,this._tempVector1=new t5,this._uv0=new t4,this._uv1=new t4,this._uv2=new t4,this.evaluateContext=!0,this.registerInput("geometry",tn.Geometry),this.registerInput("instance",tn.Geometry,!0),this.registerInput("count",tn.Int,!0,256),this.registerInput("matrix",tn.Matrix,!0),this.registerInput("rotation",tn.Vector3,!0,t5.Zero()),this.registerInput("scaling",tn.Vector3,!0,t5.One()),this.scaling.acceptedConnectionPointTypes.push(tn.Float),this.registerOutput("output",tn.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),t5.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r,n=0,a=[],o=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),r=Math.random();if(i>r){let e=i;i=r,r=e}let l=i,h=r-i,u=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+u*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+u*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+u*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+u*this._uv2.x,l*this._uv0.y+h*this._uv1.y+u*this._uv2.y),!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length){n-=s;continue}let c=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,a)}else{let t=e.adaptInput(this.scaling,tn.Vector3,t5.OneReadOnly),i=this.rotation.getConnectedValue(e)||t5.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,a)}o++,this._currentLoopIndex++}}if(a.length){if(1===a.length)this._vertexData=a[0];else{let e=a.splice(0,1)[0];this._vertexData=e.merge(a,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xh.prototype,"evaluateContext",void 0),t0["BABYLON.InstantiateOnFacesBlock"]=xh;class xu extends vM{constructor(e){super(e),this._currentPosition=new t5,this._vertex0=new t5,this._vertex1=new t5,this._vertex2=new t5,this.evaluateContext=!0,this.registerInput("geometry",tn.Geometry),this.registerInput("instance",tn.Geometry,!0),this.registerInput("count",tn.Int,!0,256),this.registerInput("matrix",tn.Matrix,!0),this.registerInput("rotation",tn.Vector3,!0,t5.Zero()),this.registerInput("scaling",tn.Vector3,!0,t5.One()),this.scaling.acceptedConnectionPointTypes.push(tn.Float),this.registerOutput("output",tn.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=[],s=n_(this._vertexData.positions,0,this._vertexData.positions.length/3),n=s.minimum,a=s.maximum,o=new t5(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let s=0;s0&&h++}if(h%2==0){s--;continue}if(!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length)continue;let u=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,r)}else{let t=e.adaptInput(this.scaling,tn.Vector3,t5.OneReadOnly),i=this.rotation.getConnectedValue(e)||t5.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,r)}this._currentLoopIndex++}if(r.length){if(1===r.length)this._vertexData=r[0];else{let e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xu.prototype,"evaluateContext",void 0),t0["BABYLON.InstantiateOnVolumeBlock"]=xu;class xc extends vM{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",tn.Geometry,!0),this.registerInput("count",tn.Int,!0,1),this.registerOutput("output",tn.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xc.prototype,"evaluateContext",void 0);class xd extends xc{constructor(e){super(e),this.registerInput("matrix",tn.Matrix,!0),this.registerInput("position",tn.Vector3,!0,t5.Zero()),this.registerInput("rotation",tn.Vector3,!0,t5.Zero()),this.registerInput("scaling",tn.Vector3,!0,t5.One()),this.scaling.acceptedConnectionPointTypes.push(tn.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){let t=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=t7.Identity(),s=t5.Zero(),n=t5.Zero(),a=t5.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=t7.Identity(),s=t7.Identity(),n=t7.Identity(),a=t5.Zero(),o=t5.Zero(),l=t5.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}t0["BABYLON.IntFloatConverterBlock"]=xf;class xm extends vM{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",tn.AutoDetect),this.registerOutput("output",tn.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tn.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tn.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];let t=e=>{let t=this.input.getConnectedValue(e);return null==t?this.log.push("null"):this.log.push(t.toString()),t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}t0["BABYLON.DebugBlock"]=xm;class xg extends vM{constructor(e){super(e),this.registerInput("geometry",tn.Geometry),this.registerOutput("output",tn.Geometry),this.registerOutput("id",tn.Int),this.registerOutput("collectionId",tn.Int),this.registerOutput("verticesCount",tn.Int),this.registerOutput("facesCount",tn.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}t0["BABYLON.GeometryInfoBlock"]=xg,function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(tp||(tp={}));class xv extends vM{constructor(e){super(e),this.mapping=tp.Spherical,this.registerInput("position",tn.Vector3),this.registerInput("normal",tn.Vector3),this.registerInput("center",tn.Vector3,!0,t5.Zero()),this.registerOutput("uv",tn.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}let e=t5.Zero(),t=t=>{let i=this.position.getConnectedValue(t)||t5.Zero(),r=this.normal.getConnectedValue(t)||t5.Zero(),s=this.center.getConnectedValue(t),n=t4.Zero();switch(this.mapping){case tp.Spherical:{i.subtractToRef(s,e);let t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,(0!==e.x||0!==e.z)&&(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case tp.Cylindrical:{i.subtractToRef(s,e);let t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case tp.Cubic:{let e=Math.abs(r.x),t=Math.abs(r.y),a=Math.abs(r.z),o=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),l=0,h=0;e>=t&&e>=a?(l=i.y/o-s.y,h=i.z/o-s.z):t>=e&&t>=a?(l=i.x/o-s.x,h=i.z/o-s.z):(l=i.x/o-s.x,h=i.y/o-s.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${tp[this.mapping]}; +`}serialize(){let e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}iZ([aE("Mapping",L.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:tp.Spherical},{label:"Cylindrical",value:tp.Cylindrical},{label:"Cubic",value:tp.Cubic}]})],xv.prototype,"mapping",void 0),t0["BABYLON.MappingBlock"]=xv;class xx extends vM{constructor(e){super(e),this.registerInput("matrix0",tn.Matrix),this.registerInput("matrix1",tn.Matrix),this.registerOutput("output",tn.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;let t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}}t0["BABYLON.MatrixComposeBlock"]=xx;class xT extends vM{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",tn.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this.endpoints){let i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(let e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}t0["BABYLON.TeleportInBlock"]=xT;class xb extends vM{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",tn.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){let e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); +`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}t0["BABYLON.TeleportOutBlock"]=xb;class xE extends vM{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",tn.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{let r=new Image,s=document.createElement("canvas"),n=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,n.drawImage(r,0,0);let e=n.getImageData(0,0,r.width,r.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},r.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}let r=e.getSize();ci.GetTextureDataAsync(e,r.width,r.height).then(async e=>{let i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){let e=e=>{let t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;let i=this.coordinates.getConnectedValue(e);if(!i)return null;let r=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),s=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(r*(t.width-1)),a=Math.floor(s*(t.height-1)),o=n+t.width*a;return t6.FromArray(t.data,4*o)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{let i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{let i=e(t);return i?i.x:null},this.g._storedFunction=t=>{let i=e(t);return i?i.y:null},this.b._storedFunction=t=>{let i=e(t);return i?i.z:null},this.a._storedFunction=t=>{let i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates}; +`}serialize(){let e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}iZ([aE("Clamp Coordinates",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xS.prototype,"clampCoordinates",void 0),t0["BABYLON.GeometryTextureFetchBlock"]=xS;class xC extends vM{constructor(e){super(e),this.registerInput("geometry",tn.Geometry),this.registerOutput("min",tn.Vector3),this.registerOutput("max",tn.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);return t?n_(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);return t?n_(t.positions,0,t.positions.length/3).maximum:null}}}t0["BABYLON.BoundingBlock"]=xC,function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(t_||(t_={}));class xy extends vM{constructor(e){super(e),this.evaluateContext=!1,this.operation=t_.Intersect,this.registerInput("geometry0",tn.Geometry),this.registerInput("geometry1",tn.Geometry),this.registerOutput("output",tn.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{let t;let i=this.geometry0.getConnectedValue(e),r=this.geometry1.getConnectedValue(e);if(!i||!r)return null;let s=i.positions.length/3;!i.normals&&r.normals&&(i.normals=Array(i.positions.length)),!r.normals&&i.normals&&(r.normals=Array(r.positions.length)),!i.uvs&&r.uvs&&(i.uvs=Array(2*s)),!r.uvs&&i.uvs&&(r.uvs=Array(2*s)),!i.colors&&r.colors&&(i.colors=Array(4*s)),!r.colors&&i.colors&&(r.colors=Array(4*s));let n=vd.FromVertexData(i),a=vd.FromVertexData(r);switch(this.operation){case t_.Intersect:t=n.intersect(a);break;case t_.Subtract:t=n.subtract(a);break;case t_.Union:t=n.union(a)}return t.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`+`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${t_[this.operation]}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}iZ([aE("Evaluate context",L.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],xy.prototype,"evaluateContext",void 0),iZ([aE("Operation",L.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:t_.Intersect},{label:"Subtract",value:t_.Subtract},{label:"Union",value:t_.Union}]})],xy.prototype,"operation",void 0),t0["BABYLON.BooleanGeometryBlock"]=xy,nC.OfflineProviderFactory=(e,t,i=!1)=>new xA(e,t,i);class xA{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=xA._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,xA.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,ss.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){let t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){let e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`},r=!1,s=i(),n=new i2;navigator.onLine&&(r=!0,s=s+(null==s.match(/\?/)?"?":"&")+Date.now()),n.open("GET",s),n.addEventListener("load",()=>{if(200===n.status||xA._ValidateXHRData(n,1))try{let t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&xA._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()},!1),n.addEventListener("error",()=>{if(r){r=!1;let e=i();n.open("GET",e),n.send()}else t()},!1);try{n.send()}catch(t){ig.Error("Error on XHR send request."),e(!1)}}open(e,t){let i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline)){if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;let t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{ig.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){ig.Error("Error while creating object stores. Exception: "+e.message),i()}}}}else this._isSupported=!1,t&&t()}loadImage(e,t){let i=xA._ReturnFullUrlLocation(e),r=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?r():this._loadImageFromDBAsync(i,t,r)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;let s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{ig.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};let n=s.objectStore("textures").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{ig.Error("Error loading texture "+e+" from DB."),t.src=e}}else ig.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){let r=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(xA._IsUASupportingBlobStorage){let s=new i2;s.open("GET",e),s.responseType="blob",s.addEventListener("load",()=>{if(200===s.status&&this._db){i=s.response;let n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}r()},n.oncomplete=()=>{r()};let a={textureUrl:e,data:i};try{let e=n.objectStore("textures").put(a);e.onsuccess=()=>{},e.onerror=()=>{r()}}catch(i){25===i.code&&(xA._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),s.addEventListener("error",()=>{ig.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),s.send()}else t.src=e}else ig.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,()=>{this._saveVersionIntoDBAsync(e,t)})}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{let s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};let n=s.objectStore("versions").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{ig.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){ig.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else ig.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{let i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};let r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{ig.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){ig.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){let n=xA._ReturnFullUrlLocation(e),a=()=>{this._saveFileAsync(n,t,i,s,r)};this._checkVersionFromDB(n,e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,s,r):this._loadFileAsync(n,t,a):r&&r()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let r,s;r=-1!==e.indexOf(".babylon")?"scenes":"textures";let n=this._db.transaction([r]);n.oncomplete=()=>{s?t(s.data):i()},n.onabort=()=>{i()};let a=n.objectStore(r).get(e);a.onsuccess=e=>{s=e.target.result},a.onerror=()=>{ig.Error("Error loading file "+e+" from DB."),i()}}else ig.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let n,a;n=-1!==e.indexOf(".babylon")?"scenes":"textures";let o=new i2;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(200===o.status||o.status<400&&xA._ValidateXHRData(o,r?6:1)){if(a=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){let i;let r=this._db.transaction([n],"readwrite");r.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},r.oncomplete=()=>{t(a)},i="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{let e=r.objectStore(n).put(i);e.onsuccess=()=>{},e.onerror=()=>{ig.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a)}else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{ig.Error("error on XHR request."),s&&s()},!1),o.send()}else ig.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){let i=mr(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){let t=new Uint8Array(e.response,0,3);if(68===t[0]&&68===t[1]&&83===t[2])return!0}}catch(e){}return!1}}xA._IsUASupportingBlobStorage=!0,xA.IDBStorageEnabled=!1,xA._ParseURL=e=>{document.createElement("a").href=e;let t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},xA._ReturnFullUrlLocation=e=>(-1===e.indexOf("http:/")&&e.indexOf("https:/"),e);class xR{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}let xI=`#version 300 es +void main() {discard;} +`;rO.ShadersStore.gpuUpdateParticlesPixelShader=xI;let xP=`#version 300 es +#define PI 3.14159 +uniform float currentCount;uniform float timeDelta;uniform float stopFactor; +#ifndef LOCAL +uniform mat4 emitterWM; +#endif +uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; +#ifndef COLORGRADIENTS +uniform vec4 color1;uniform vec4 color2; +#endif +uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; +#ifdef BOXEMITTER +uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; +#endif +#ifdef POINTEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#endif +#ifdef HEMISPHERICEMITTER +uniform float radius;uniform float radiusRange;uniform float directionRandomizer; +#endif +#ifdef SPHEREEMITTER +uniform float radius;uniform float radiusRange; +#ifdef DIRECTEDSPHEREEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CYLINDEREMITTER +uniform float radius;uniform float height;uniform float radiusRange; +#ifdef DIRECTEDCYLINDEREMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CONEEMITTER +uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; +#endif +in vec3 position; +#ifdef CUSTOMEMITTER +in vec3 initialPosition; +#endif +in float age;in float life;in vec4 seed;in vec3 size; +#ifndef COLORGRADIENTS +in vec4 color; +#endif +in vec3 direction; +#ifndef BILLBOARD +in vec3 initialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +in float angle; +#else +in vec2 angle; +#endif +#ifdef ANIMATESHEET +in float cellIndex; +#ifdef ANIMATESHEETRANDOMSTART +in float cellStartOffset; +#endif +#endif +#ifdef NOISE +in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; +#endif +out vec3 outPosition; +#ifdef CUSTOMEMITTER +out vec3 outInitialPosition; +#endif +out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; +#ifndef COLORGRADIENTS +out vec4 outColor; +#endif +out vec3 outDirection; +#ifndef BILLBOARD +out vec3 outInitialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +out float outAngle; +#else +out vec2 outAngle; +#endif +#ifdef ANIMATESHEET +out float outCellIndex; +#ifdef ANIMATESHEETRANDOMSTART +out float outCellStartOffset; +#endif +#endif +#ifdef NOISE +out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; +#endif +#ifdef SIZEGRADIENTS +uniform sampler2D sizeGradientSampler; +#endif +#ifdef ANGULARSPEEDGRADIENTS +uniform sampler2D angularSpeedGradientSampler; +#endif +#ifdef VELOCITYGRADIENTS +uniform sampler2D velocityGradientSampler; +#endif +#ifdef LIMITVELOCITYGRADIENTS +uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; +#endif +#ifdef DRAGGRADIENTS +uniform sampler2D dragGradientSampler; +#endif +#ifdef NOISE +uniform vec3 noiseStrength;uniform sampler2D noiseSampler; +#endif +#ifdef ANIMATESHEET +uniform vec4 cellInfos; +#endif +vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} +vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} +void main() {float newAge=age+timeDelta; +if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; +#else +outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; +#endif +outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; +#ifndef COLORGRADIENTS +outColor=color1+(color2-color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#else +outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#endif +#ifdef POINTEMITTER +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(BOXEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; +#elif defined(SPHEREEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(direction1+(direction2-direction1)*randoms3); +#else +newDirection=normalize(newPosition+directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=direction1+(direction2-direction1)*randoms3; +#else +angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +float h=0.0001; +#else +float h=randoms2.y*height.y;h=1.-h*h; +#endif +float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); +if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } +#elif defined(CUSTOMEMITTER) +newPosition=initialPosition;outInitialPosition=initialPosition; +#else +newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); +#endif +float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; +#ifdef LOCAL +outPosition=newPosition; +#else +outPosition=(emitterWM*vec4(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#ifndef BILLBOARD +outInitialDirection=direction; +#endif +#else +#ifdef LOCAL +vec3 initial=newDirection; +#else +vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; +#endif +outDirection=initial*power; +#ifndef BILLBOARD +outInitialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +outCellIndex=cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; +#endif +#ifdef DRAGGRADIENTS +directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; +#endif +#if defined(CUSTOMEMITTER) +outPosition=position+(direction-position)*ageGradient; +outInitialPosition=initialPosition; +#else +outPosition=position+direction*directionScale; +#endif +outLife=life;outSeed=seed; +#ifndef COLORGRADIENTS +outColor=color; +#endif +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; +#else +outSize=size; +#endif +#ifndef BILLBOARD +outInitialDirection=initialDirection; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#else +vec3 updatedDirection=direction+gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} +#endif +outDirection=updatedDirection; +#ifdef NOISE +float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; +#else +outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; +#else +float cellStartOffset=0.; +#endif +float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} +else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} +outCellIndex=float(int(cellInfos.x+ratio*dist)); +#endif +}}`;rO.ShadersStore.gpuUpdateParticlesVertexShader=xP;class xM{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateEffect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof aK&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new rN("gpuUpdateParticles",this._updateEffectOptions,this._engine),new xR(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){let e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);let r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e, +age : f32, +size : vec3, +life : f32, +seed : vec4, +direction : vec3, +dummy0: f32, +#ifdef CUSTOMEMITTER +initialPosition : vec3, +dummy1: f32, +#endif +#ifndef COLORGRADIENTS +color : vec4, +#endif +#ifndef BILLBOARD +initialDirection : vec3, +dummy2: f32, +#endif +#ifdef NOISE +noiseCoordinates1 : vec3, +dummy3: f32, +noiseCoordinates2 : vec3, +dummy4: f32, +#endif +#ifdef ANGULARSPEEDGRADIENTS +angle : f32, +#else +angle : vec2, +#endif +#ifdef ANIMATESHEET +cellIndex : f32, +#ifdef ANIMATESHEETRANDOMSTART +cellStartOffset : f32, +#endif +#endif +};struct Particles {particles : array,};struct SimParams {currentCount : f32, +timeDelta : f32, +stopFactor : f32, +randomTextureSize: i32, +lifeTime : vec2, +emitPower : vec2, +#ifndef COLORGRADIENTS +color1 : vec4, +color2 : vec4, +#endif +sizeRange : vec2, +scaleRange : vec4, +angleRange : vec4, +gravity : vec3, +#ifdef LIMITVELOCITYGRADIENTS +limitVelocityDamping : f32, +#endif +#ifdef ANIMATESHEET +cellInfos : vec4, +#endif +#ifdef NOISE +noiseStrength : vec3, +#endif +#ifndef LOCAL +emitterWM : mat4x4, +#endif +#ifdef BOXEMITTER +direction1 : vec3, +direction2 : vec3, +minEmitBox : vec3, +maxEmitBox : vec3, +#endif +#ifdef CONEEMITTER +radius : vec2, +coneAngle : f32, +height : vec2, +directionRandomizer : f32, +#endif +#ifdef CYLINDEREMITTER +radius : f32, +height : f32, +radiusRange : f32, +#ifdef DIRECTEDCYLINDEREMITTER +direction1 : vec3, +direction2 : vec3, +#else +directionRandomizer : f32, +#endif +#endif +#ifdef HEMISPHERICEMITTER +radius : f32, +radiusRange : f32, +directionRandomizer : f32, +#endif +#ifdef POINTEMITTER +direction1 : vec3, +direction2 : vec3, +#endif +#ifdef SPHEREEMITTER +radius : f32, +radiusRange : f32, +#ifdef DIRECTEDSPHEREEMITTER +direction1 : vec3, +direction2 : vec3, +#else +directionRandomizer : f32, +#endif +#endif +};@binding(0) @group(0) var params : SimParams;@binding(1) @group(0) var particlesIn : Particles;@binding(2) @group(0) var particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d;@binding(4) @group(0) var randomTexture2 : texture_2d; +#ifdef SIZEGRADIENTS +@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d; +#endif +#ifdef ANGULARSPEEDGRADIENTS +@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d; +#endif +#ifdef VELOCITYGRADIENTS +@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d; +#endif +#ifdef LIMITVELOCITYGRADIENTS +@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d; +#endif +#ifdef DRAGGRADIENTS +@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d; +#endif +#ifdef NOISE +@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d; +#endif +fn getRandomVec3(offset : f32,vertexID : f32)->vec3 {return textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} +fn getRandomVec4(offset : f32,vertexID : f32)->vec4 {return textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} +let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4=particlesIn.particles[index].seed;let direction : vec3=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3;var newDirection : vec3;let randoms : vec4=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; +#ifdef SIZEGRADIENTS +sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r; +#else +sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; +#endif +particlesOut.particles[index].size=vec3( +sizex, +params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, +params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +particlesOut.particles[index].angle=vec2( +params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, +params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); +#else +particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; +#endif +#if defined(POINTEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=vec3(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(BOXEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#elif defined(SPHEREEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); +#else +newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#else +angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +let h : f32=0.0001; +#else +var h : f32=randoms2.y*params.height.y;h=1.-h*h; +#endif +var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3(randX,randY,randZ); +if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } +#elif defined(CUSTOMEMITTER) +newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; +#else +newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5)); +#endif +let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; +#ifdef LOCAL +particlesOut.particles[index].position=newPosition; +#else +particlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=direction; +#endif +#else +#ifdef LOCAL +let initial : vec3=newDirection; +#else +let initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz; +#endif +particlesOut.particles[index].direction=initial*power; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +particlesOut.particles[index].cellIndex=params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +particlesOut.particles[index].cellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; +#endif +} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r; +#endif +#ifdef DRAGGRADIENTS +directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r); +#endif +let position : vec3=particlesIn.particles[index].position; +#if defined(CUSTOMEMITTER) +particlesOut.particles[index].position=position+(direction-position)*ageGradient; +particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; +#else +particlesOut.particles[index].position=position+direction*directionScale; +#endif +particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=particlesIn.particles[index].color; +#endif +#ifdef SIZEGRADIENTS +particlesOut.particles[index].size=vec3( +textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r, +particlesIn.particles[index].size.yz); +#else +particlesOut.particles[index].size=particlesIn.particles[index].size; +#endif +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#else +var updatedDirection : vec3=direction+params.gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} +#endif +particlesOut.particles[index].direction=updatedDirection; +#ifdef NOISE +let noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; +#else +let angle : vec2=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; +#else +let cellStartOffset : f32=0.; +#endif +var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} +else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} +particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); +#endif +}} +`;rO.ShadersStoreWGSL.gpuUpdateParticlesComputeShader=xD;class xO{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){var t;let i={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new h5("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new sp(this._engine,void 0,void 0,"ComputeShaderParticleSystemUBO"),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new xR(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){let t=new od(this._engine,4*e.length,11,"ComputeShaderParticleSystemBuffer");return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let e=0;ee){i(t[0],t[0],1);return}for(let r=0;r=s.gradient&&e<=n.gradient){let t=(e-s.gradient)/(n.gradient-s.gradient);i(s,n,t);return}}let r=t.length-1;i(t[r],t[r],1)}}class xB{constructor(e){if(this.particleSystem=e,this.position=t5.Zero(),this.direction=t5.Zero(),this.color=new il(0,0,0,0),this.colorStep=new il(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new t4(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new il(0,0,0,0),this._currentColor2=new il(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=xB._Count++,!this.particleSystem.isAnimationSheetEnabled)return;this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e,t=this.age,i=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===i?(i=1,t=this._randomCellOffset):t+=this._randomCellOffset);let r=this._initialEndSpriteCellID-this._initialStartSpriteCellID;e=this._initialSpriteCellLoop?tK.Clamp(t*i%this.lifeTime/this.lifeTime):tK.Clamp(t*i/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+e*r|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){let t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){let e=ie.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,ie.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(ie.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=xB._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new t6(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}xB._Count=0,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(tf||(tf={}));class xU{constructor(e){if(this.particleSystem=e,this.type=tf.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){let t=t0["BABYLON.AbstractMesh"];e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof t5?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&((e=new t0["BABYLON.Mesh"]("",e.getScene())).isVisible=!1):e=new t5;let t=new xU(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){let t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw iL("ParseParticle")}static Parse(e,t,i){let r=e.particleSystem,s=new xU(xU._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}let xV=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; +#include +#include +#include +#include +#include +#ifdef RAMPGRADIENT +varying vec4 remapRanges;uniform sampler2D rampSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; +#ifdef RAMPGRADIENT +float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); +#endif +#ifdef BLENDMULTIPLYMODE +float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); +#endif +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +baseColor.rgb=toLinearSpace(baseColor.rgb); +#else +#ifdef IMAGEPROCESSING +baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); +#endif +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.particlesPixelShader=xV;let xk=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +#ifndef BILLBOARD +attribute vec3 direction; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +#ifdef RAMPGRADIENT +attribute vec4 remapData; +#endif +attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; +#ifdef ANIMATESHEET +uniform vec3 particlesInfos; +#endif +varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#ifdef RAMPGRADIENT +varying vec4 remapRanges; +#endif +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include +#include +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); +#ifdef BILLBOARDSTRETCHED_LOCAL +vec3 row1=direction; +#else +vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); +#endif +mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; +#ifdef BILLBOARD +vec3 rotatedCorner; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; +#endif +#ifdef RAMPGRADIENT +remapRanges=remapData; +#endif +gl_Position=projection*vec4(viewPos,1.0); +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); +#endif +vColor=color; +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=offset; +#endif +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.particlesVertexShader=xk;class xG extends aq{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new rY(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new tj),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,n=.01){super(e),this._emitterInverseWorldMatrix=t7.Identity(),this._inheritedVelocityOffset=new t5,this.onDisposeObservable=new tj,this.onStoppedObservable=new tj,this._particles=[],this._stockParticles=[],this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new il(0,0,0,0),this._colorDiff=new il(0,0,0,0),this._scaledDirection=t5.Zero(),this._scaledGravity=t5.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=e=>{let t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;if(0!==this._stockParticles.length?(e=this._stockParticles.pop())._reset():e=new xB(this),this._subEmitters&&this._subEmitters.length>0){let t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(t=>{if(t.type===tf.ATTACHED){let i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;let t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(t=>{if(t.type===tf.END){let i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=t7.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||t2.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new rY(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new ak;let a=null;this.updateFunction=e=>{var t;let i=null;this.noiseTexture&&(i=this.noiseTexture.getSize(),null===(t=this.noiseTexture.getContent())||void 0===t||t.then(e=>{a=e}));let r=e===this._particles;for(let t=0;ts.lifeTime){let e=s.age-o;n=(s.lifeTime-o)*n/e,s.age=s.lifeTime}let l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?xL.GetCurrentGradient(l,this._colorGradients,(e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),il.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)}):(s.colorStep.scaleToRef(n,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&xL.GetCurrentGradient(l,this._angularSpeedGradients,(e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=tK.Lerp(s._currentAngularSpeed1,s._currentAngularSpeed2,i)}),s.angle+=s.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&xL.GetCurrentGradient(l,this._velocityGradients,(e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=tK.Lerp(s._currentVelocity1,s._currentVelocity2,i)}),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&xL.GetCurrentGradient(l,this._limitVelocityGradients,(e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);let r=tK.Lerp(s._currentLimitVelocity1,s._currentLimitVelocity2,i);s.direction.length()>r&&s.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&xL.GetCurrentGradient(l,this._dragGradients,(e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);let r=tK.Lerp(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)}),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),t5.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),a&&i&&s._randomNoiseCoordinates1){let e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,i.width,i.height,a),t=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,i.width,i.height,a),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,i.width,i.height,a),o=ie.Vector3[0],l=ie.Vector3[1];o.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),o.scaleToRef(n,l),s.direction.addInPlace(l)}if(this.gravity.scaleToRef(n,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&xL.GetCurrentGradient(l,this._sizeGradients,(e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=tK.Lerp(s._currentSize1,s._currentSize2,i)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&xL.GetCurrentGradient(l,this._colorRemapGradients,(e,t,i)=>{let r=tK.Lerp(e.factor1,t.factor1,i),n=tK.Lerp(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=n-r}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&xL.GetCurrentGradient(l,this._alphaRemapGradients,(e,t,i)=>{let r=tK.Lerp(e.factor1,t.factor1,i),n=tK.Lerp(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=n-r})),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime){this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach(e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),s._attachedSubEmitters=null),this.recycleParticle(s),r&&t--;continue}}}}_addFactorGradient(e,t,i,r){let s=new xw(t,i,r);e.push(s),e.sort((e,t)=>e.gradientt.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(let r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;let e=new Uint8Array(4*this._rawTextureWidth),t=ih.Color3[0];for(let i=0;i{io.LerpToRef(r.color,s.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255})}this._rampGradientsTexture=ae.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);let i=new xF(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);let r=new xN(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((e,t)=>e.gradientt.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(let i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(let e of this._drawWrappers)if(e)for(let t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){return s[(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*r%r|0)*i)*4]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){let e;this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==xG.BILLBOARDMODE_STRETCHED&&this.billboardMode!==xG.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);let t=this._engine,i=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*i),this._vertexBuffer=new s_(t,this._vertexData,!0,i);let r=0,s=this._vertexBuffer.createVertexBuffer(sf.PositionKind,r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[sf.PositionKind]=s,r+=3;let n=this._vertexBuffer.createVertexBuffer(sf.ColorKind,r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[sf.ColorKind]=n,r+=4;let a=this._vertexBuffer.createVertexBuffer("angle",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=a,r+=1;let o=this._vertexBuffer.createVertexBuffer("size",r,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,r+=2,this._isAnimationSheetEnabled){let e=this._vertexBuffer.createVertexBuffer("cellIndex",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,r+=1}if(!this._isBillboardBased||this.billboardMode===xG.BILLBOARDMODE_STRETCHED||this.billboardMode===xG.BILLBOARDMODE_STRETCHED_LOCAL){let e=this._vertexBuffer.createVertexBuffer("direction",r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,r+=3}if(this._useRampGradients){let e=this._vertexBuffer.createVertexBuffer("remapData",r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,r+=4}if(this._useInstancing){let i=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new s_(t,i,!1,2),e=this._spriteBuffer.createVertexBuffer("offset",0,2)}else e=this._vertexBuffer.createVertexBuffer("offset",r,2,this._vertexBufferSize,this._useInstancing),r+=2;this._vertexBuffers.offset=e,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}let e=[],t=[],i=0;for(let r=0;r{e instanceof xG?this._subEmitters.push([new xU(e)]):e instanceof xU?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[]),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);let e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){!this._stopped&&(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===xG.BILLBOARDMODE_STRETCHED||this.billboardMode===xG.BILLBOARDMODE_STRETCHED_LOCAL)&&(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(t5.TransformNormalToRef(e,this._emitterWorldMatrix,ie.Vector3[0]),e=ie.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(t5.TransformNormalToRef(e,this._emitterWorldMatrix,ie.Vector3[0]),e=ie.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;let e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){let t;if(this._alive=this._particles.length>0,this.emitter.position){let e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{let e=this.emitter;this._emitterWorldMatrix=t7.Translation(e.x,e.y,e.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){let e=tK.Clamp(this._actualFrame/this.targetStopDuration);xL.GetCurrentGradient(e,this._lifeTimeGradients,(i,r)=>{let s=i.getFactor(),n=r.getFactor(),a=(e-i.gradient)/(r.gradient-i.gradient);t.lifeTime=tK.Lerp(s,n,a)})}else t.lifeTime=tK.RandomRange(this.minLifeTime,this.maxLifeTime);let e=tK.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),t5.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=tK.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(tK.RandomRange(this.minScaleX,this.maxScaleX),tK.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){let e=this._actualFrame/this.targetStopDuration;xL.GetCurrentGradient(e,this._startSizeGradients,(e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);let s=tK.Lerp(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)})}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=tK.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=tK.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{let e=tK.RandomRange(0,1);il.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new t6(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new t5(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new t5(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){let r=[sf.PositionKind,sf.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1){let i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return nD(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&nO(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===xG.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case xG.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case xG.BILLBOARDMODE_STRETCHED:case xG.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===xG.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case xG.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...xG._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==xG.BILLBOARDMODE_STRETCHED&&this.billboardMode!==xG.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...xG._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(sd.PrepareUniforms(e,this._imageProcessingConfigurationDefines),sd.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0,s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let n=s[e];n||((n=new rY(this._engine)).drawContext&&(n.drawContext.useInstancing=this._useInstancing),s[e]=n);let a=i.join("\n");if(n.defines!==a){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,a),a)}return n}animate(e=!1){var t;let i;if(this._started){if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){let t=this._actualFrame/this.targetStopDuration;xL.GetCurrentGradient(t,this._emitRateGradients,(t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=tK.Lerp(this._currentEmitRate1,this._currentEmitRate2,r)})}i=e*this._scaledUpdateSpeed>>0,this._newPartsExcess+=e*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&!this._alive&&(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this)),!e){let e=0;for(let t=0;t=0&&(d.invertToRef(ie.Matrix[0]),u.setMatrix("invView",ie.Matrix[0])),void 0!==this._vertexArrayObject?(null===(r=this._scene)||void 0===r?void 0:r.forceWireframe)?c.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,u):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,u)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?c.bindBuffers(this._vertexBuffers,(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._linesIndexBuffer:this._indexBuffer,u):c.bindBuffers(this._vertexBuffers,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBufferUseInstancing:null,u),this.useLogarithmicDepth&&this._scene&&nw.BindLogDepth(p,u,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(u),e){case xG.BLENDMODE_ADD:c.setAlphaMode(1);break;case xG.BLENDMODE_ONEONE:c.setAlphaMode(6);break;case xG.BLENDMODE_STANDARD:c.setAlphaMode(2);break;case xG.BLENDMODE_MULTIPLY:c.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(u),this._useInstancing?(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?c.drawElementsType(6,0,10,this._particles.length):c.drawArraysType(7,0,4,this._particles.length):(null===(l=this._scene)||void 0===l?void 0:l.forceWireframe)?c.drawElementsType(1,0,10*this._particles.length):c.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;let e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===xG.BLENDMODE_MULTIPLYADD?this._render(xG.BLENDMODE_MULTIPLY)+this._render(xG.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){let e=(s=this.customShader).shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}let a=this.serialize(i),o=xG.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,this.preventAutoStart||o.start(),o}serialize(e=!1){let t={};if(xG._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters)for(let i of(t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray(),this._subEmitters)){let r=[];for(let t of i)r.push(t.serialize(e));t.subEmitters.push(r)}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){let i=t.emitter;e.emitterId=i.id}else{let i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,i$.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;let r=t.getColorGradients();if(r)for(let t of(e.colorGradients=[],r)){let i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}let s=t.getRampGradients();if(s){for(let t of(e.rampGradients=[],s)){let i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}let n=t.getColorRemapGradients();if(n)for(let t of(e.colorRemapGradients=[],n)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}let a=t.getAlphaRemapGradients();if(a)for(let t of(e.alphaRemapGradients=[],a)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}let o=t.getSizeGradients();if(o)for(let t of(e.sizeGradients=[],o)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}let l=t.getAngularSpeedGradients();if(l)for(let t of(e.angularSpeedGradients=[],l)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}let h=t.getVelocityGradients();if(h)for(let t of(e.velocityGradients=[],h)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}let u=t.getDragGradients();if(u)for(let t of(e.dragGradients=[],u)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}let c=t.getEmitRateGradients();if(c)for(let t of(e.emitRateGradients=[],c)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}let d=t.getStartSizeGradients();if(d)for(let t of(e.startSizeGradients=[],d)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}let p=t.getLifeTimeGradients();if(p)for(let t of(e.lifeTimeGradients=[],p)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}let _=t.getLimitVelocityGradients();if(_){for(let t of(e.limitVelocityGradients=[],_)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,r){var s,n,a;let o,l;o=i instanceof r$?null:i;let h=t0["BABYLON.Texture"];if(h&&o&&(e.texture?t.particleTexture=h.Parse(e.texture,o,r):e.textureName&&(t.particleTexture=new h(r+e.textureName,o,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&o?t.emitter=o.getLastMeshById(e.emitterId):t.emitter=t5.FromArray(e.emitter):t.emitter=t5.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let i=0;i0?l.shaderOptions.defines.join("\n"):"";o=n.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,t)}let h=new xG(a,s||e.capacity,t,o,e.isAnimationSheetEnabled);if(h.customShader=l,h._rootUrl=i,e.id&&(h.id=e.id),e.subEmitters)for(let r of(h.subEmitters=[],e.subEmitters)){let e=[];for(let s of r)e.push(xU.Parse(s,t,i));h.subEmitters.push(e)}return xG._Parse(e,h,t,i),e.textureMask&&(h.textureMask=il.FromArray(e.textureMask)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),r||h.preventAutoStart||h.start(),h}}xG.BILLBOARDMODE_Y=2,xG.BILLBOARDMODE_ALL=7,xG.BILLBOARDMODE_STRETCHED=8,xG.BILLBOARDMODE_STRETCHED_LOCAL=9,xU._ParseParticleSystem=xG.Parse;let xz=`#ifdef CLIPPLANE +in float fClipDistance; +#endif +#ifdef CLIPPLANE2 +in float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +in float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +in float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +in float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +in float fClipDistance6; +#endif +`;rO.IncludesShadersStore.clipPlaneFragmentDeclaration2=xz;let xW=`precision highp float; +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; +#include +#include +#include +#include +#include +void main() { +#include +vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; +#ifdef BLENDMULTIPLYMODE +float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); +#endif +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); +#else +#ifdef IMAGEPROCESSING +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); +#endif +#endif +} +`;rO.ShadersStore.gpuRenderParticlesPixelShader=xW;let xH=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;out float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;out float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;out float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;out float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;out float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;out float fClipDistance6; +#endif +`;rO.IncludesShadersStore.clipPlaneVertexDeclaration2=xH;let xX=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; +#ifdef LOCAL +uniform mat4 emitterWM; +#endif +attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; +#ifndef BILLBOARD +attribute vec3 initialDirection; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +attribute float angle; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include +#include +#ifdef COLORGRADIENTS +uniform sampler2D colorGradientSampler; +#else +uniform vec4 colorDead;attribute vec4 color; +#endif +#ifdef ANIMATESHEET +uniform vec3 sheetInfos; +#endif +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#endif +void main() { +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=uv; +#endif +float ratio=age/life; +#ifdef COLORGRADIENTS +vColor=texture2D(colorGradientSampler,vec2(ratio,0)); +#else +vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); +#endif +vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; +#ifdef BILLBOARD +vec4 rotatedCorner;rotatedCorner.w=0.; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; +#ifdef LOCAL +vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; +#else +vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; +#endif +vPositionW=(invView*viewPosition).xyz; +#endif +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); +#endif +gl_Position=projection*viewPosition; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include +#include +}`;rO.ShadersStore.gpuRenderParticlesVertexShader=xX;class xY extends aq{static get IsSupported(){if(!t2.LastCreatedEngine)return!1;let e=t2.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==xG.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(xG.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(xG.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new rY(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new tj),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);let i=new xN(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(let t in this._drawWrappers)null===(e=this._drawWrappers[t].drawContext)||void 0===e||e.reset()}_addFactorGradient(e,t,i){let r=new xw(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){e&&(i&&e.sort((e,t)=>e.gradientt.gradient?1:0),this[t]&&(this[t].dispose(),this[t]=null))}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new tj,this.onStoppedObservable=new tj,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=t7.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||t2.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!t0["BABYLON.ComputeShaderParticleSystem"])throw Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new t0["BABYLON.ComputeShaderParticleSystem"](this,this._engine)}else{if(!t0["BABYLON.WebGL2ParticleSystem"])throw Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new t0["BABYLON.WebGL2ParticleSystem"](this,this._engine)}this._customWrappers={0:new rY(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new rY(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;let n=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),a=t;isFinite(a)&&(n.capacity=a),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new ak;let o=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize),l=[];for(let e=0;e0;)i.push(0)}let a=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),o=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new s_(t,o,!1,this._attributesStrideSize),this._buffer1=new s_(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new s_(t,a,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),!!this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||((r=new rY(this._engine)).drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);let s=i.join("\n");if(r.defines!==s){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){let s=[sf.PositionKind,"age","life","size","angle"];return e||s.push(sf.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",sf.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){let i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return nD(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&nO(this,this._scene,e),t===xG.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case xG.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case xG.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case xG.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...xY._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===xG.BILLBOARDMODE_STRETCHED)),e.push(...xY._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(sd.PrepareUniforms(e,this._imageProcessingConfigurationDefines),sd.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,!this._stopped&&this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){let i=this[t];if(!e||!e.length||i)return;let r=new Float32Array(this._rawTextureWidth);for(let t=0;t{r[t]=tK.Lerp(e.factor1,i.factor1,s)})}this[t]=ae.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;let e=new Uint8Array(4*this._rawTextureWidth),t=ih.Color4[0];for(let i=0;i{il.LerpToRef(r.color1,s.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a})}this._colorGradientsTexture=ae.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,r,s,n,a;let o=this._getWrapper(e),l=o.effect;this._engine.enableEffect(o);let h=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||t7.IdentityReadOnly;if(l.setMatrix("view",h),l.setMatrix("projection",null!==(r=this.defaultProjectionMatrix)&&void 0!==r?r:this._scene.getProjectionMatrix()),l.setTexture("diffuseSampler",this.particleTexture),l.setVector2("translationPivot",this.translationPivot),l.setVector3("worldOffset",this.worldOffset),this.isLocal&&l.setMatrix("emitterWM",t),this._colorGradientsTexture?l.setTexture("colorGradientSampler",this._colorGradientsTexture):l.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();l.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;l.setVector3("eyePosition",e.globalPosition)}let u=l.defines;if(this._scene&&nN(l,this,this._scene),u.indexOf("#define BILLBOARDMODE_ALL")>=0){let e=h.clone();e.invert(),l.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&nw.BindLogDepth(u,l,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(l),e){case xG.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case xG.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case xG.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case xG.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,l,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(l),(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e){if(this.emitter.position)e=this.emitter.getWorldMatrix();else{let t=this.emitter;e=ie.Matrix[0],t7.TranslationToRef(t.x,t.y,t.z,e)}}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);let t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){let i;if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){let e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{let e=this.emitter;i=ie.Matrix[0],t7.TranslationToRef(e.x,e.y,e.z,i)}let r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===xG.BLENDMODE_MULTIPLYADD?this._render(xG.BLENDMODE_MULTIPLY,i)+this._render(xG.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){let e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?this._initialize(!0):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(let e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?s.shaderOptions.defines.join("\n"):"";r[0]=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}let a=this.serialize(i),o=xY.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,o}serialize(e=!1){let t={};return xG._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){let n;let a=e.name;n=t instanceof r$?t:t.getEngine();let o=new xY(a,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(o._rootUrl=i,e.customShader&&n.createEffectForParticles){let t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=n.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,o);o.setCustomEffect(r,0),o.customShader=t}return e.id&&(o.id=e.id),e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),xG._Parse(e,o,t,i),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o}}class xj{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){for(let t of(this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1),this.systems))t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};let r=ul("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;let s=new hD("emitterSphereMaterial",i);for(let t of(s.emissiveColor=e.color,r.material=s,this.systems))t.emitter=r;this._emitterNode=r}start(e){for(let t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(let e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){let t={};for(let i of(t.systems=[],this.systems))t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){let s=new xj,n=this.BaseAssetsUrl+"/textures/";for(let a of(t=t||t2.LastCreatedScene,e.systems))s.systems.push(i?xY.Parse(a,t,n,!0,r):xG.Parse(a,t,n,!0,r));if(e.emitter){let i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:io.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}}xj.BaseAssetsUrl="https://assets.babylonjs.com/particles";class xK{static CreateDefault(e,t=500,i,r=!1){let s;return(s=r?new xY("default system",{capacity:t},i):new xG("default system",t,i)).emitter=e,s.particleTexture=new n6("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new il(1,1,1,1),s.color2=new il(1,1,1,1),s.colorDead=new il(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,r){t||(t=t2.LastCreatedScene);let s={};return t.addPendingData(s),new Promise((n,a)=>{if(i&&!xY.IsSupported)return t.removePendingData(s),a("Particle system with GPU is not supported.");ss.LoadFile(`${xK.BaseAssetsUrl}/systems/${e}.json`,e=>{t.removePendingData(s);let a=JSON.parse(e.toString());return n(xj.Parse(a,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(s),a(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){let t=new xj;for(let i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",n){return new Promise((a,o)=>{let l=new i2;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let t;let o=JSON.parse(l.responseText);t=r?xY.Parse(o,i,s,!1,n):xG.Parse(o,i,s,!1,n),e&&(t.name=e),a(t)}else o("Unable to load the particle system")}}),l.open("GET",t),l.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){let e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise((n,a)=>{let o=new i2;o.addEventListener("readystatechange",()=>{if(4==o.readyState){if(200==o.status){let a;let l=JSON.parse(JSON.parse(JSON.parse(o.responseText).jsonPayload).particleSystem);(a=i?xY.Parse(l,t,r,!1,s):xG.Parse(l,t,r,!1,s)).snippetId=e,n(a)}else a("Unable to load the snippet "+e)}}),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()})}}xK.BaseAssetsUrl=xj.BaseAssetsUrl,xK.SnippetUrl="https://snippet.babylonjs.com",xK.CreateFromSnippetAsync=xK.ParseFromSnippetAsync,tW.AddParser(sb.NAME_PARTICLESYSTEM,(e,t,i,r)=>{let s=tW.GetIndividualParser(sb.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,a=e.particleSystems.length;ne.activeParticleCount?xY.Parse(e,t,i):xG.Parse(e,t,i)),nC.prototype.createEffectForParticles=function(e,t=[],i=[],r="",s,n,a,o){var l;let h=[],u=[],c=[];return o?o.fillUniformsAttributesAndSamplerNames(u,h,c):(h=xG._GetAttributeNamesOrOptions(),u=xG._GetEffectCreationOptions()),-1===r.indexOf(" BILLBOARD")&&(r+="\n#define BILLBOARD\n"),(null==o?void 0:o.isAnimationSheetEnabled)&&-1===r.indexOf(" ANIMATESHEET")&&(r+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==o?void 0:o.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,u.concat(t),c.concat(i),r,s,n,a)},nX.prototype.getEmittedParticleSystems=function(){let e=[];for(let t=0;t{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),nM.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},nM.prototype.applyImpulse=function(e,t){return this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t),this},nM.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor&&this.physicsImpostor.createJoint(e.physicsImpostor,ad.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this};class x${getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw iL("")}constructor(e,t=x$.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new t5(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){let t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){let r=new fH;return this._physicsPlugin.raycast(e,t,r,i),r}}(function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"})(tg||(tg={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(tv||(tv={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(tx||(tx={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(tT||(tT={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(tb||(tb={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(tE||(tE={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(tS||(tS={})),function(e){e[e.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",e[e.MINIMUM=1]="MINIMUM",e[e.MAXIMUM=2]="MAXIMUM",e[e.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",e[e.MULTIPLY=4]="MULTIPLY"}(tC||(tC={})),sY.prototype.getPhysicsEngine=function(){return this._physicsEngine},sY.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(sb.NAME_PHYSICSENGINE);i||(i=new xq(this),this._addComponent(i));try{if(t&&(null==t?void 0:t.getPluginVersion())!==1){if((null==t?void 0:t.getPluginVersion())===2)this._physicsEngine=new x$(e,t);else throw Error("Unsupported Physics plugin version.")}else this._physicsEngine=new fX(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return ig.Error(e.message),!1}},sY.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},sY.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},sY.prototype.deleteCompoundImpostor=function(e){let t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},sY.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){let t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class xq{constructor(e){this.name=sb.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new tj,this.scene.onAfterPhysicsObservable=new tj,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(nA.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0}),nA.prototype.getPhysicsBody=function(){return this.physicsBody},nA.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};class xQ{static GetContactPointToRef(e,t,i,r,s){let n=e.getScene().getPhysicsEngine(),a=null==n?void 0:n.getPluginVersion();if(1===a){let s=new as(t,i).intersectsMesh(e);if(s.hit&&s.pickedPoint)return r.copyFrom(s.pickedPoint),!0}else if(2===a)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){var i,r,s;return e.getMotionType(t)===tS.STATIC||(null!==(r=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==r?r:0)===0||(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){let s=ie.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}}class xZ{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=t5.Zero(),this._originDirection=t5.Zero(),this._cylinderPosition=t5.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new x0),this._options),this._origin.addToRef(new t5(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new t5(0,this._options.height,0),this._originTop),this._options.updraftMode===tA.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout(()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)},0))}_getHitData(e,t){let i;i=this._options.updraftMode===tA.Perpendicular?this._originDirection:e.subtract(this._originTop);let r=t5.Distance(this._origin,e),s=-1*this._options.strength,n=i.multiplyByFloats(s,s,s);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(xQ.HasAppliedForces(e))return!1;let r=e.getObjectCenterWorld(i);return!!xQ.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){let e=xZ._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=ue("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}xZ._HitData={force:new t5,contactPoint:new t5,distanceFromOrigin:0};class xJ{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=t5.Zero(),this._cylinderPosition=t5.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new x1),this._options),this._origin.addToRef(new t5(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new t5(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout(()=>{this._dataFetched||this._cylinder.dispose()},0))}_getHitData(e,t,i){let r,s,n;let a=xJ.originOnPlane;a.set(this._origin.x,t.y,this._origin.z);let o=ie.Vector3[0];t.subtractToRef(a,o);let l=ie.Vector3[1];if(!xQ.GetContactPointToRef(e,a,o,l,i.instanceIndex))return!1;let h=t5.Distance(l,a)/this._options.radius,u=ie.Vector3[2];if(l.normalizeToRef(u),h>this._options.centripetalForceThreshold&&u.negateInPlace(),h>this._options.centripetalForceThreshold)r=u.x*this._options.centripetalForceMultiplier,s=u.y*this._options.updraftForceMultiplier,n=u.z*this._options.centripetalForceMultiplier;else{let e=t5.Cross(a,t).normalize();r=(e.x+u.x)*this._options.centrifugalForceMultiplier,s=this._originTop.y*this._options.updraftForceMultiplier,n=(e.z+u.z)*this._options.centrifugalForceMultiplier}let c=ie.Vector3[3];return c.set(r,s,n),c.scaleInPlace(this._options.strength),i.force.copyFrom(c),i.contactPoint.copyFrom(t),i.distanceFromOrigin=h,!0}_getBodyHitData(e,t,i){if(xQ.HasAppliedForces(e,i))return!1;let r=e.transformNode,s=e.getObjectCenterWorld(i);return!!xQ.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass||"Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){let e=xJ.hitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=ue("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}xJ.originOnPlane=t5.Zero(),xJ.hitData={force:new t5,contactPoint:new t5,distanceFromOrigin:0};class x0{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=tA.Center}}class x1{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}(function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"})(ty||(ty={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(tA||(tA={}));let x2=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); +vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;rO.ShadersStore.blackAndWhitePixelShader=x2;class x3 extends aL{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,s,n){super(e,"blackAndWhite",["degree"],null,t,i,r,s,n),this.degree=1,this.onApplyObservable.add(e=>{e.setFloat("degree",this.degree)})}static _Parse(e,t,i,r){return i$.Parse(()=>new x3(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}iZ([iW()],x3.prototype,"degree",void 0),t0["BABYLON.BlackAndWhitePostProcess"]=x3;class x4{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(let e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){let t=this._postProcesses[e];for(let e=0;e{let t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)}),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){let t=ss.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){let t=ss.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}let x5=`#include +varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;rO.ShadersStore.extractHighlightsPixelShader=x5;class x6 extends aL{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,s,n,null,a,void 0,null,o),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,t$)),e.setFloat("exposure",this._exposure)})}}iZ([iW()],x6.prototype,"threshold",void 0),t0["BABYLON.ExtractHighlightsPostProcess"]=x6;let x8=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } +`;rO.ShadersStore.bloomMergePixelShader=x8;class x7 extends aL{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,n,a,o,l,null,h,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}}iZ([iW()],x7.prototype,"weight",void 0),t0["BABYLON.BloomMergePostProcess"]=x7;class x9 extends x4{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,r,s=0,n=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new x6("highlights",1,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._blurX=new pn("horizontal blur",new t4(1,0),10,t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new pn("vertical blur",new t4(0,1),10,t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new x7("bloomMerge",this._downscale,this._blurY,i,t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)})}static _Parse(e,t,i,r){return i$.Parse(()=>new Tt(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}iZ([iW()],Tt.prototype,"aberrationAmount",void 0),iZ([iW()],Tt.prototype,"radialIntensity",void 0),iZ([iW()],Tt.prototype,"direction",void 0),iZ([iW()],Tt.prototype,"centerPosition",void 0),iZ([iW()],Tt.prototype,"screenWidth",void 0),iZ([iW()],Tt.prototype,"screenHeight",void 0),t0["BABYLON.ChromaticAberrationPostProcess"]=Tt;let Ti=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float depth=texture2D(depthSampler,vUV).r; +#define CUSTOM_COC_DEPTH +float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; +#define CUSTOM_COC_PIXELDISTANCE +float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} +`;rO.ShadersStore.circleOfConfusionPixelShader=Ti;class Tr extends aL{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,s,n,a,null,o,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(e=>{if(!this._depthTexture){ig.Warn("No depth texture set on CircleOfConfusionPostProcess");return}e.setTexture("depthSampler",this._depthTexture);let t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);let i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)})}set depthTexture(e){this._depthTexture=e}}iZ([iW()],Tr.prototype,"lensSize",void 0),iZ([iW()],Tr.prototype,"fStop",void 0),iZ([iW()],Tr.prototype,"focusDistance",void 0),iZ([iW()],Tr.prototype,"focalLength",void 0),t0["BABYLON.CircleOfConfusionPostProcess"]=Tr;let Ts=`uniform sampler2D textureSampler; +uniform sampler2D colorTable; +varying vec2 vUV;const float SLICE_COUNT=16.0; +vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; +float slicePixelSize=sliceSize/width; +float sliceInnerSize=slicePixelSize*(width-1.0); +float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;rO.ShadersStore.colorCorrectionPixelShader=Ts;class Tn extends aL{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"colorCorrection",null,["colorTable"],i,r,s,n,a);let o=(null==r?void 0:r.getScene())||null;this._colorTableTexture=new n6(t,o,!0,!1,n6.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=n6.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=n6.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,r){return i$.Parse(()=>new Tn(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}iZ([iW()],Tn.prototype,"colorTableUrl",void 0),t0["BABYLON.ColorCorrectionPostProcess"]=Tn;let Ta=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = +texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + +texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + +texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + +texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + +texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + +texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + +texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = +kernel[0] + +kernel[1] + +kernel[2] + +kernel[3] + +kernel[4] + +kernel[5] + +kernel[6] + +kernel[7] + +kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} +gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;rO.ShadersStore.convolutionPixelShader=Ta;class To extends aL{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,n,a,o=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,n,a,null,o),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,r){return i$.Parse(()=>new To(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}}To.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],To.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],To.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],To.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],To.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],To.GaussianKernel=[0,1,0,1,1,1,0,1,0],iZ([iW()],To.prototype,"kernel",void 0),t0["BABYLON.ConvolutionPostProcess"]=To;class Tl extends pn{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=null,l=n6.BILINEAR_SAMPLINGMODE,h,u,c=0,d=!1,p=5){super(e,i,r,s,n,2,h,u,c,`#define DOF 1 +`,d,p),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add(e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)})}}iZ([iW()],Tl.prototype,"direction",void 0),t0["BABYLON.DepthOfFieldBlurPostProcess"]=Tl;let Th=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; +#if BLUR_LEVEL>0 +uniform sampler2D blurStep1; +#endif +#if BLUR_LEVEL>1 +uniform sampler2D blurStep2; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; +#if BLUR_LEVEL==0 +vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); +#endif +#if BLUR_LEVEL==1 +if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} +#endif +#if BLUR_LEVEL==2 +if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} +#endif +} +`;rO.ShadersStore.depthOfFieldMergePixelShader=Th;class Tu extends aL{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,n,a,o,l,null,h,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,n){e||(e="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,n)}}!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(tR||(tR={}));class Tc extends x4{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=tR.Low,r=0,s=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];let n=e.getEngine(),a=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new Tr("circleOfConfusion",t,1,null,n6.BILINEAR_SAMPLINGMODE,n,!1,r,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,l=15;switch(i){case tR.High:o=3,l=51;break;case tR.Medium:o=2,l=31;break;default:l=15,o=1}let h=l/Math.pow(2,o-1),u=1;for(let t=0;tnew Tp(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}t0["BABYLON.DisplayPassPostProcess"]=Tp;let T_=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;rO.ShadersStore.filterPixelShader=T_;class Tf extends aL{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"filter",["kernelMatrix"],null,i,r,s,n,a),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,r){return i$.Parse(()=>new Tf(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}iZ([iG(12,void 0)],Tf.prototype,"kernelMatrix",void 0),t0["BABYLON.FilterPostProcess"]=Tf;let Tm=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); +#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) +void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); +#ifndef MALI +if(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) +{lumaN=lumaW;} +if (!horzSpan) +{lumaS=lumaE;} +if (horzSpan) +{lengthSign=texelSize.y;} +float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) +{lengthSign=-lengthSign;} +float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) +{posB.x+=lengthSign*0.5;} +if (horzSpan) +{posB.y+=lengthSign*0.5;} +vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) +{lumaNN=lumaSS;} +float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) +{posN.x-=offNP.x*3.0;} +if (!doneN) +{posN.y-=offNP.y*3.0;} +bool doneNP=(!doneN) || (!doneP);if (!doneP) +{posP.x+=offNP.x*3.0;} +if (!doneP) +{posP.y+=offNP.y*3.0;} +if (doneNP) +{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} +float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) +{dstN=posM.y-posN.y;} +if (!horzSpan) +{dstP=posP.y-posM.y;} +bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{let t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)})}_getDefines(){let e=this.getEngine();if(!e)return null;let t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return i$.Parse(()=>new Tv(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}t0["BABYLON.FxaaPostProcess"]=Tv;let Tx=`#include +uniform sampler2D textureSampler; +uniform float intensity;uniform float animatedSeed;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;rO.ShadersStore.grainPixelShader=Tx;class TT extends aL{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,n,null,a,void 0,null,o),this.intensity=30,this.animated=!1,this.onApplyObservable.add(e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}static _Parse(e,t,i,r){return i$.Parse(()=>new TT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}iZ([iW()],TT.prototype,"intensity",void 0),iZ([iW()],TT.prototype,"animated",void 0),t0["BABYLON.GrainPostProcess"]=TT;let Tb=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;rO.ShadersStore.highlightsPixelShader=Tb;let TE=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 result=texture2D(textureSampler,vUV); +#ifdef IMAGEPROCESSING +#ifndef FROMLINEARSPACE +result.rgb=toLinearSpace(result.rgb); +#endif +result=applyImageProcessing(result); +#else +#ifdef FROMLINEARSPACE +result=applyImageProcessing(result); +#endif +#endif +gl_FragColor=result;}`;rO.ShadersStore.imageProcessingPixelShader=TE;class TS extends aL{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null,t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){let i=t.scenes;e=i[i.length-1]}else e=t2.LastCreatedScene;e?this._imageProcessingConfiguration=e.imageProcessingConfiguration:this._imageProcessingConfiguration=new sd}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){let e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,n,a=0,o){super(e,"imageProcessing",[],[],t,i,r,s,n,null,a,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(let t in this._defines)this._defines[t]&&(e+=`#define ${t}; +`);let t=["textureSampler"],i=["scale"];sd&&(sd.PrepareSamplers(t,this._defines),sd.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}iZ([iW()],TS.prototype,"_fromLinearSpace",void 0);let TC=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +layout(location=0) out vec4 glFragData[{X}]; +#endif +`;rO.IncludesShadersStore.mrtFragmentDeclaration=TC;let Ty=`#extension GL_EXT_draw_buffers : require +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +precision highp float; +#ifdef BUMP +varying mat4 vWorldView;varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#ifdef VELOCITY +varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#ifdef NEED_UV +varying vec2 vUV; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#if defined(REFLECTIVITY) +#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; +#endif +#ifdef ALBEDOTEXTURE +varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; +#endif +#ifdef REFLECTIVITYCOLOR +uniform vec3 reflectivityColor; +#endif +#ifdef ALBEDOCOLOR +uniform vec3 albedoColor; +#endif +#ifdef METALLIC +uniform float metallic; +#endif +#if defined(ROUGHNESS) || defined(GLOSSINESS) +uniform float glossiness; +#endif +#endif +#if defined(ALPHATEST) && defined(NEED_UV) +uniform sampler2D diffuseSampler; +#endif +#include +#include[RENDER_TARGET_COUNT] +#include +#include +#include +void main() { +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +vec3 normalOutput; +#ifdef BUMP +vec3 normalW=normalize(vNormalW); +#include +#ifdef NORMAL_WORLDSPACE +normalOutput=normalW; +#else +normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); +#endif +#else +normalOutput=normalize(vNormalV); +#endif +#ifdef ENCODE_NORMAL +normalOutput=normalOutput*0.5+0.5; +#endif +#ifdef PREPASS +#ifdef PREPASS_DEPTH +gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); +#endif +#ifdef PREPASS_NORMAL +gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); +#endif +#else +gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); +#endif +#ifdef POSITION +gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); +#endif +#ifdef VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); +#endif +#ifdef REFLECTIVITY +vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); +#ifdef METALLICWORKFLOW +float metal=1.0;float roughness=1.0; +#ifdef ORMTEXTURE +metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; +#endif +#ifdef METALLIC +metal*=metallic; +#endif +#ifdef ROUGHNESS +roughness*=(1.0-glossiness); +#endif +reflectivity.a-=roughness;vec3 color=vec3(1.0); +#ifdef ALBEDOTEXTURE +color=texture2D(albedoSampler,vAlbedoUV).rgb; +#ifdef GAMMAALBEDO +color=toLinearSpace(color); +#endif +#endif +#ifdef ALBEDOCOLOR +color*=albedoColor.xyz; +#endif +reflectivity.rgb=mix(vec3(0.04),color,metal); +#else +#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +reflectivity=texture2D(reflectivitySampler,vReflectivityUV); +#ifdef GAMMAREFLECTIVITYTEXTURE +reflectivity.rgb=toLinearSpace(reflectivity.rgb); +#endif +#else +#ifdef REFLECTIVITYCOLOR +reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; +#endif +#endif +#ifdef GLOSSINESSS +reflectivity.a*=glossiness; +#endif +#endif +gl_FragData[REFLECTIVITY_INDEX]=reflectivity; +#endif +} +`;rO.ShadersStore.geometryPixelShader=Ty,rO.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";let TA=`#include +`;rO.IncludesShadersStore.geometryUboDeclaration=TA;let TR=`precision highp float; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include<__decl__geometryVertex> +#include +attribute vec3 position;attribute vec3 normal; +#ifdef NEED_UV +varying vec2 vUV; +#ifdef ALPHATEST +uniform mat4 diffuseMatrix; +#endif +#ifdef BUMP +uniform mat4 bumpMatrix;varying vec2 vBumpUV; +#endif +#ifdef REFLECTIVITY +uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef BUMP +varying mat4 vWorldView; +#endif +#ifdef BUMP +varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#ifdef VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); +#ifdef BUMP +vWorldView=view*finalWorld;vNormalW=normalUpdated; +#else +#ifdef NORMAL_WORLDSPACE +vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); +#else +vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); +#endif +#endif +vViewPos=view*worldPos; +#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +#if defined(POSITION) || defined(BUMP) +vPositionW=worldPos.xyz/worldPos.w; +#endif +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#include +#ifdef NEED_UV +#ifdef UV1 +#if defined(ALPHATEST) && defined(ALPHATEST_UV1) +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#else +vUV=uv; +#endif +#ifdef BUMP_UV1 +vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV1 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef ALBEDO_UV1 +vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#endif +#ifdef UV2 +#if defined(ALPHATEST) && defined(ALPHATEST_UV2) +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#else +vUV=uv2; +#endif +#ifdef BUMP_UV2 +vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV2 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); +#endif +#ifdef ALBEDO_UV2 +vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#endif +#include +} +`;rO.ShadersStore.geometryVertexShader=TR;let TI=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];nD(TI);class TP{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===TP.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===TP.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===TP.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===TP.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===TP.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case TP.POSITION_TEXTURE_TYPE:return this._positionIndex;case TP.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case TP.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case TP.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case TP.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return -1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new il(0,0,0,0),this._clearDepthColor=new il(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},TP._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[sf.PositionKind,sf.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&lE.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&r.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),n.isVerticesDataPresent(sf.UVKind)&&(s.push(sf.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(sf.UV2Kind)&&(s.push(sf.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),-1!==this._depthIndex&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(s.push(sf.MatricesIndicesKind),s.push(sf.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(sf.MatricesIndicesExtraKind),s.push(sf.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));let a=n.morphTargetManager,o=0;a&&a.numInfluencers>0&&(o=a.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+o),a.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),nw.PrepareAttributesForMorphTargetsInfluencers(s,n,o)),t&&(r.push("#define INSTANCES"),nw.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),nO(i,this._scene,r);let l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),u=h.defines,c=r.join("\n");return u!==c&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:TI,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:c,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:o}},l),c),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],t=[],i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[TP.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[TP.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[TP.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[TP.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[TP.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){let e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices(),s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);let n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},a=[],o=[];for(let e of r)e?(a.push(e.textureType),o.push(e.textureFormat)):(a.push(s),o.push(5));if(this._normalsAreUnsigned=11===a[TP.NORMAL_TEXTURE_TYPE]||13===a[TP.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new mx("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:a,formats:o,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=n6.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=n6.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let l=[!0],h=[!1],u=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:c),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(p),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(c)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){let t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}});let _=e=>{let t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:t7.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){let e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}let a=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;let o=s.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,o)){let h;let u=e._getDrawWrapper();if(!u)return;let c=u.effect;s.enableEffect(u),o||t._bind(e,c,n.fillMode),this._useUbo?(nw.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("view",r.getViewMatrix()));let d=t._instanceDataStorage;if(!d.isFrozen&&(n.backFaceCulling||null!==t.overrideMaterialSideOrientation)){let e=i._getWorldMatrixDeterminant();null===(h=t.overrideMaterialSideOrientation)&&(h=n.sideOrientation),e<0&&(h=h===nB.ClockWiseSideOrientation?nB.CounterClockWiseSideOrientation:nB.ClockWiseSideOrientation)}else h=d.sideOrientation;if(n._preBind(u,h),n.needAlphaTesting()){let e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.bumpTexture&&r.getEngine().getCaps().standardDerivatives&&lE.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),nN(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){let e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){let i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}nw.BindMorphTargetParameters(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),o&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,a,o,(e,t)=>{e||c.setMatrix("world",t)})}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),n=0;n{throw iL("GeometryBufferRendererSceneComponent")};class TM{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(sY.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),sY.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new TP(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},sY.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class TD{constructor(e){this.name=sb.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sb.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}TP._SceneComponentInitialization=e=>{let t=e._getComponent(sb.NAME_GEOMETRYBUFFERRENDERER);t||(t=new TD(e),e._addComponent(t))};let TO=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; +#ifdef OBJECT_BASED +uniform sampler2D velocitySampler; +#else +uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#ifdef GEOMETRY_SUPPORTED +#ifdef OBJECT_BASED +vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount) +break;vec2 offset=vUV+velocity*(hlim+float(i)); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset,0.0); +#else +result+=texture2D(textureSampler,offset); +#endif +} +gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; +#else +vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; +vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset1,0.0); +#else +result+=texture2D(textureSampler,offset1); +#endif +} +gl_FragColor=result/float(nSamples); +#endif +#else +gl_FragColor=texture2D(textureSampler,vUV); +#endif +} +`;rO.ShadersStore.motionBlurPixelShader=TO;class TN extends aL{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,n,a,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",o,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new TM)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}let i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return ig.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=t7.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new t4(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(TP.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){let t=ie.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new t4(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(TP.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){let e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,r){return i$.Parse(()=>new TN(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}iZ([iW()],TN.prototype,"motionStrength",void 0),iZ([iW()],TN.prototype,"motionBlurSamples",null),iZ([iW()],TN.prototype,"isObjectBased",null),t0["BABYLON.MotionBlurPostProcess"]=TN,rO.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class TF extends aL{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,n,a,o,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,a,o,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(e=>{this._refTexture=this._refTexture||new n6(t,e.getScene())}),this.onApplyObservable.add(e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return i$.Parse(()=>new TF(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}iZ([iW()],TF.prototype,"color",void 0),iZ([iW()],TF.prototype,"depth",void 0),iZ([iW()],TF.prototype,"colorLevel",void 0),iZ([iW()],TF.prototype,"refractionTextureUrl",void 0),t0["BABYLON.RefractionPostProcess"]=TF;let Tw=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - +color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;rO.ShadersStore.sharpenPixelShader=Tw;class TL extends aL{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,n,null,a,void 0,null,o),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,r){return i$.Parse(()=>new TL(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}iZ([iW()],TL.prototype,"colorAmount",void 0),iZ([iW()],TL.prototype,"edgeAmount",void 0),t0["BABYLON.SharpenPostProcess"]=TL;class TB{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=[],this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(let e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){let i=this._renderEffects[e];i&&i._enable(ss.MakeArray(t||this._cameras))}_disableEffect(e,t){let i=this._renderEffects[e];i&&i._disable(ss.MakeArray(t||this._cameras))}_attachCameras(e,t){let i;let r=ss.MakeArray(e||this._cameras);if(!r)return;let s=[];for(i=0;i0){let i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){for(let e of Object.keys(this._renderEffects)){let t=this._renderEffects[e].getPostProcesses();if(t)for(let e of t)e.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}iZ([iW()],TB.prototype,"_name",void 0);class TU{constructor(){this._renderPipelines={}}get supportedPipelines(){let e=[];for(let t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){let i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){let r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){let i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(let e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(let e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(sY.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(sb.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new TV(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new TU}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class TV{constructor(e){this.name=sb.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sb.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class Tk extends TB{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){let e=this.bloom;this.bloom=new x9(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen,!0),this.depthOfField=new Tc(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add(()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new x9(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new Tt("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,n6.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new x4(a,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new TT("Grain",1,null,n6.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new x4(a,this.GrainPostProcessId,()=>this.grain,!0);let o=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add(()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,o?ss.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),o=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){let e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;let e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(let e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);let e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new TS("imageProcessing",1,null,n6.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new x4(e,this.ImageProcessingPostProcessId,()=>this.imageProcessing,!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new Tv("fxaa",1,null,n6.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new x4(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&ig.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew Tk(e._name,e._name._hdr,t),e,t,i)}}iZ([iW()],Tk.prototype,"sharpenEnabled",null),iZ([iW()],Tk.prototype,"bloomKernel",null),iZ([iW()],Tk.prototype,"_bloomWeight",void 0),iZ([iW()],Tk.prototype,"_bloomThreshold",void 0),iZ([iW()],Tk.prototype,"_hdr",void 0),iZ([iW()],Tk.prototype,"bloomWeight",null),iZ([iW()],Tk.prototype,"bloomThreshold",null),iZ([iW()],Tk.prototype,"bloomScale",null),iZ([iW()],Tk.prototype,"bloomEnabled",null),iZ([iW()],Tk.prototype,"depthOfFieldEnabled",null),iZ([iW()],Tk.prototype,"depthOfFieldBlurLevel",null),iZ([iW()],Tk.prototype,"fxaaEnabled",null),iZ([iW()],Tk.prototype,"samples",null),iZ([iW()],Tk.prototype,"imageProcessingEnabled",null),iZ([iW()],Tk.prototype,"glowLayerEnabled",null),iZ([iW()],Tk.prototype,"chromaticAberrationEnabled",null),iZ([iW()],Tk.prototype,"grainEnabled",null),t0["BABYLON.DefaultRenderingPipeline"]=Tk;let TG=`uniform sampler2D textureSampler; +uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } +else { lum_threshold=0.5+0.44*threshold; } +luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} +float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); +#ifdef PENTAGON +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); +#else +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); +#endif +blurred/=39.0;gl_FragColor=blurred;}`;rO.ShadersStore.lensHighlightsPixelShader=TG;let Tz=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; +uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; +#define PI 3.14159265 +#define TWOPI 6.28318530 +#define inverse_focal_length 0.1 +vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) +{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} +vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } +vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} +float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} +float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} +vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} +if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} +col/=total_weight; +if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} +return col;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); +vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); +float depth=texture2D(depthSampler,distorted_coords).r; +float distance=near+(far-near)*depth; +vec4 color=texture2D(textureSampler,vUV); +float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } +float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} +float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} +else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} +if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} +if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} +`;rO.ShadersStore.depthOfFieldPixelShader=Tz;class TW{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}let TH=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +float scales[16]=float[16]( +0.1, +0.11406250000000001, +0.131640625, +0.15625, +0.187890625, +0.2265625, +0.272265625, +0.325, +0.384765625, +0.4515625, +0.525390625, +0.60625, +0.694140625, +0.7890625, +0.891015625, +1.0 +);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() +{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;} +float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} +occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} +#endif +#ifdef BLUR +uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; +#ifndef BLUR_BYPASS +uniform sampler2D depthSampler; +#ifdef BLUR_LEGACY +#define inline +float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} +#endif +#endif +void main() +{float result=0.0; +#ifdef BLUR_BYPASS +result=textureLod(textureSampler,vUV,0.0).r; +#else +#ifdef BLUR_H +vec2 step=vec2(1.0/outSize,0.0); +#else +vec2 step=vec2(0.0,1.0/outSize); +#endif +#ifdef BLUR_LEGACY +result=blur13Bilateral(textureSampler,vUV,step); +#else +float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess,!0)),this.addEffect(new x4(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new x4(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new x4(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new x4(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;let t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},a.samples=this.textureSamples,a}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,23283064365386963e-26*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){let i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new t5(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){let e;let t=this.samples,i=[],r=0;for(;r{var t,i,r,s;if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===ns.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",TY.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{let n=this._scene.getEngine().getRenderWidth()/2,a=this._scene.getEngine().getRenderHeight()/2,o=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-n,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:n,h=null!==(r=this._scene.activeCamera.orthoBottom)&&void 0!==r?r:-a,u=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:a;e.setMatrix3x3("depthProjection",TY.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",(l-o)*.5),e.setFloat("yViewport",(u-h)*.5)}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new TW)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new aL("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{let t=this._scene.activeCamera.viewport;e.setVector4("viewport",ie.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){let e=new Uint8Array(65536),t=t4.Zero();for(let i=0;inew TY(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}TY.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],TY.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],iZ([iW()],TY.prototype,"totalStrength",void 0),iZ([iW()],TY.prototype,"maxZ",void 0),iZ([iW()],TY.prototype,"minZAspect",void 0),iZ([iW("epsilon")],TY.prototype,"_epsilon",void 0),iZ([iW("samples")],TY.prototype,"_samples",void 0),iZ([iW("textureSamples")],TY.prototype,"_textureSamples",void 0),iZ([iW()],TY.prototype,"_forceGeometryBuffer",void 0),iZ([iW()],TY.prototype,"_ratio",void 0),iZ([iW()],TY.prototype,"_textureType",void 0),iZ([iW()],TY.prototype,"radius",void 0),iZ([iW()],TY.prototype,"base",void 0),iZ([iW("bypassBlur")],TY.prototype,"_bypassBlur",void 0),iZ([iW("expensiveBlur")],TY.prototype,"_expensiveBlur",void 0),iZ([iW()],TY.prototype,"bilateralSamples",void 0),iZ([iW()],TY.prototype,"bilateralSoften",void 0),iZ([iW()],TY.prototype,"bilateralTolerance",void 0),t0["BABYLON.SSAO2RenderingPipeline"]=TY;let Tj=`uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) +{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} +void main() +{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess,!0)),this.addEffect(new x4(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new x4(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new x4(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new x4(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){for(let i of(super._attachCameras(e,t),this._cameras))this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{let e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e}),this._blurVPostProcess.onActivateObservable.add(()=>{let e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){let t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new aL("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new aL("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,n6.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",ie.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){let e=new Uint8Array(1048576);for(let t=0;t0.0) +hitCoord-=dir;else +hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} +projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} +/** +* Tests the given world position (hitCoord) according to the given reflection vector (dir) +* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). +*/ +ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) +{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){let t=i.getTextureIndex(TP.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(TP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){let t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}let s=t.activeCamera;if(!s)return;let n=s.getViewMatrix(!0),a=s.getProjectionMatrix(!0);e.setMatrix("projection",a),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){let e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,r){return i$.Parse(()=>new TQ(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}iZ([iW()],TQ.prototype,"threshold",void 0),iZ([iW()],TQ.prototype,"strength",void 0),iZ([iW()],TQ.prototype,"reflectionSpecularFalloffExponent",void 0),iZ([iW()],TQ.prototype,"step",void 0),iZ([iW()],TQ.prototype,"roughnessFactor",void 0),iZ([iW()],TQ.prototype,"enableSmoothReflections",null),iZ([iW()],TQ.prototype,"reflectionSamples",null),iZ([iW()],TQ.prototype,"smoothSteps",null),t0["BABYLON.ScreenSpaceReflectionPostProcess"]=TQ;let TZ=`uniform sampler2D textureSampler;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +#if defined(PASS_POST_PROCESS) +void main(void) +{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} +#endif +#if defined(DOWN_SAMPLE_X4) +uniform vec2 dsOffsets[16];void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} +#endif +#if defined(BRIGHT_PASS) +uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth) +accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} +accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} +#endif +#if defined(VLSMERGE) +uniform sampler2D originalSampler;void main(void) +{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} +#endif +#if defined(LUMINANCE) +uniform vec2 lumOffsets[4];void main() +{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) +{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); +#ifdef WEIGHTED_AVERAGE +float GreyValue=dot(color.rgb,weight); +#endif +#ifdef BRIGHTNESS +float GreyValue=max(color.r,max(color.g,color.b)); +#endif +#ifdef HSL_COMPONENT +float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); +#endif +#ifdef MAGNITUDE +float GreyValue=length(color.rgb); +#endif +maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} +average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} +#endif +#if defined(LUMINANCE_DOWN_SAMPLE) +uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; +#ifdef FINAL_DOWN_SAMPLER +#include +#endif +void main() +{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) +{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} +average/=9.0; +#ifdef FINAL_DOWN_SAMPLER +gl_FragColor=pack(average); +#else +gl_FragColor=vec4(average,average,0.0,1.0); +#endif +} +#endif +#if defined(HDR) +uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() +{vec4 color=texture2D(textureAdderSampler,vUV); +#ifndef AUTO_EXPOSURE +vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; +#endif +gl_FragColor=color;} +#endif +#if defined(LENS_FLARE) +#define GHOSTS 3 +uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) +{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} +float noise(in vec2 p) +{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), +hash(i+vec2(1.0,0.0)),u.x), +mix(hash(i+vec2(0.0,1.0)), +hash(i+vec2(1.0,1.0)),u.x),u.y);} +float fbm(vec2 p) +{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} +vec3 pattern(vec2 uv) +{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} +float luminance(vec3 color) +{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} +vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) +{return vec4( +texture2D(tex,texcoord+direction*distortion.r).r, +texture2D(tex,texcoord+direction*distortion.g).g, +texture2D(tex,texcoord+direction*distortion.b).b, +1.0 +);} +void main(void) +{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} +gl_FragColor=result/float(nSamples);} +#endif +`;rO.ShadersStore.standardPixelShader=TZ;class TJ extends TB{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){let t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){let t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer()){ig.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){let e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new TQ("HDRPass",t,e,null,n6.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new x4(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new aL("HDRPass","standard",[],[],e,null,n6.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.originalPostProcess}),this.addEffect(new x4(t.getEngine(),"HDRPassPostProcess",()=>this.originalPostProcess,!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new aL("HDRDepthOfFieldSource","standard",[],[],e,null,n6.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new x4(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new aL("HDRVLSFinal","standard",[],[],e,null,n6.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new x4(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new aL("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,n6.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new x4(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new aL("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,n6.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new x4(t.getEngine(),"HDRPostHDReDepthOfFieldSource",()=>this.hdrFinalPostProcess,!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new Tv("fxaa",1,null,n6.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new x4(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&ig.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){let i=Array(32);this.downSampleX4PostProcess=new aL("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0,r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=1/r*(e+.5),i[t+1]=1/s*(n+.5),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new x4(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){let i=Array(8);this.brightPassPostProcess=new aL("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{let t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new x4(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){let s=e.getEngine(),n=new pn("HDRBlurH_"+i,new t4(1,0),this[r],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new pn("HDRBlurV_"+i,new t4(0,1),this[r],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{let e=n.width/s.getRenderWidth();n.kernel=this[r]*e}),a.onActivateObservable.add(()=>{let e=a.height/s.getRenderHeight();a.kernel=this.horizontalBlur?64*e:this[r]*e}),this.addEffect(new x4(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new x4(e.getEngine(),"HDRBlurV"+i,()=>a,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new aL("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new x4(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){let i=e.enableGeometryBufferRenderer();i.enablePosition=!0;let r=i.getGBuffer();this.volumetricLightPostProcess=new aL("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));let s=t4.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){let t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new x4(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new aL("HDRVLSMerge","standard",[],["originalSampler"],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new x4(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,TJ.LuminanceSteps);this.luminancePostProcess=new aL("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);let r=[];this.luminancePostProcess.onApply=e=>{let t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new x4(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let r=TJ.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");let n=new aL("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(n)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((t,i)=>{let r=Array(18);t.onApply=e=>{if(!s)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[n]=e/s.width,r[n+1]=t/s.height,n+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{let t=e.getEngine().readPixels(0,0,1,1),i=new t6(6030862941101084e-23,1/65025,1/255,1);t.then(e=>{let t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100})}),this.addEffect(new x4(e.getEngine(),"HDRLuminanceDownSample"+i,()=>t,!0))})}_createHdrPostProcess(e,t){let i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new aL("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{let e=(n-s)/1e3;this._hdrCurrentLuminancer-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=tK.Clamp(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),n=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new x4(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new aL("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new x4(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new aL("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new x4(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));let i=new t4(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};let r=t7.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=t7.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);let t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2),n=t5.Dot(t.toVector3(),new t5(1,0,0))+t5.Dot(i.toVector3(),new t5(0,0,1));n*=4;let a=t7.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),o=s.multiply(a).multiply(r);e.setMatrix("lensStarMatrix",o),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new aL("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new x4(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){let i=new TN("HDRMotionBlur",e,t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new aL("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,n6.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=t7.Identity(),s=t7.Identity(),n=t7.Identity(),a=t4.Zero();this.motionBlurPostProcess.onApply=t=>{(n=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=n,a.x=this.motionBlurPostProcess.width,a.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",a),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new x4(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew TJ(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&i$.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}}TJ.LuminanceSteps=6,iZ([iW()],TJ.prototype,"brightThreshold",void 0),iZ([iW()],TJ.prototype,"blurWidth",void 0),iZ([iW()],TJ.prototype,"horizontalBlur",void 0),iZ([iW()],TJ.prototype,"exposure",null),iZ([iH("lensTexture")],TJ.prototype,"lensTexture",void 0),iZ([iW()],TJ.prototype,"volumetricLightCoefficient",void 0),iZ([iW()],TJ.prototype,"volumetricLightPower",void 0),iZ([iW()],TJ.prototype,"volumetricLightBlurScale",void 0),iZ([iW()],TJ.prototype,"hdrMinimumLuminance",void 0),iZ([iW()],TJ.prototype,"hdrDecreaseRate",void 0),iZ([iW()],TJ.prototype,"hdrIncreaseRate",void 0),iZ([iW()],TJ.prototype,"hdrAutoExposure",null),iZ([iH("lensColorTexture")],TJ.prototype,"lensColorTexture",void 0),iZ([iW()],TJ.prototype,"lensFlareStrength",void 0),iZ([iW()],TJ.prototype,"lensFlareGhostDispersal",void 0),iZ([iW()],TJ.prototype,"lensFlareHaloWidth",void 0),iZ([iW()],TJ.prototype,"lensFlareDistortionStrength",void 0),iZ([iW()],TJ.prototype,"lensFlareBlurWidth",void 0),iZ([iH("lensStarTexture")],TJ.prototype,"lensStarTexture",void 0),iZ([iH("lensFlareDirtTexture")],TJ.prototype,"lensFlareDirtTexture",void 0),iZ([iW()],TJ.prototype,"depthOfFieldDistance",void 0),iZ([iW()],TJ.prototype,"depthOfFieldBlurWidth",void 0),iZ([iW()],TJ.prototype,"motionStrength",null),iZ([iW()],TJ.prototype,"objectBasedMotionBlur",null),iZ([iW()],TJ.prototype,"_ratio",void 0),iZ([iW()],TJ.prototype,"BloomEnabled",null),iZ([iW()],TJ.prototype,"DepthOfFieldEnabled",null),iZ([iW()],TJ.prototype,"LensFlareEnabled",null),iZ([iW()],TJ.prototype,"HDREnabled",null),iZ([iW()],TJ.prototype,"VLSEnabled",null),iZ([iW()],TJ.prototype,"MotionBlurEnabled",null),iZ([iW()],TJ.prototype,"fxaaEnabled",null),iZ([iW()],TJ.prototype,"screenSpaceReflectionsEnabled",null),iZ([iW()],TJ.prototype,"volumetricLightStepsCount",null),iZ([iW()],TJ.prototype,"motionBlurSamples",null),iZ([iW()],TJ.prototype,"samples",null),t0["BABYLON.StandardRenderingPipeline"]=TJ;class T0{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}let T1=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } +/** +param csOrigin Camera-space ray origin,which must be +within the view volume and must have z>0.01 and project within the valid screen rectangle +param csDirection Unit length camera-space ray direction +param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates +(**not** [-1,+1] normalized device coordinates). +param csZBuffer The camera-space Z buffer +param csZBufferSize Dimensions of csZBuffer +param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer +param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value +for clipping rays headed towards the camera +param stride Step in horizontal or vertical pixels between samples. This is a float +because integer math is slow on GPUs,but should be set to an integer>=1 +param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units +to conceal banding artifacts,plus the stride ray offset. +param maxSteps Maximum number of iterations. Higher gives better images but may be slow +param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss +param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. +1 is a reasonable value,depending on the scene you may need to set this value to 2 +param hitPixel Pixel coordinates of the first intersection with the scene +param numIterations number of iterations performed +param csHitPoint Camera space location of the ray hit +*/ +#define inline +bool traceScreenSpaceRay1( +vec3 csOrigin, +vec3 csDirection, +mat4 projectToPixelMatrix, +sampler2D csZBuffer, +vec2 csZBufferSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +sampler2D csZBackBuffer, +float csZBackSizeFactor, +#endif +float csZThickness, +float nearPlaneZ, +float stride, +float jitterFraction, +float maxSteps, +float maxRayTraceDistance, +float selfCollisionNumSkip, +out vec2 startPixel, +out vec2 hitPixel, +out vec3 csHitPoint, +out float numIterations +#ifdef SSRAYTRACE_DEBUG +,out vec3 debugColor +#endif +) +{ +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; +#else +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);} +if ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));} +P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); +#endif +P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { +float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} +sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); +#else +hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); +#endif +#else +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); +#else +hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); +#endif +#endif +} +pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} +#ifdef SSRAYTRACE_ENABLE_REFINEMENT +if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || +(refinementStepCount<=stride*1.4) && +(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} +#endif +return hit;} +/** +texCoord: in the [0,1] range +depth: depth in view space (range [znear,zfar]]) +*/ +vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +ndc.z=-projection[2].z-projection[3].z/depth; +#else +ndc.z=projection[2].z+projection[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +`;rO.IncludesShadersStore.screenSpaceRayTrace=T1;let T2=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSR_SUPPORTED +uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +uniform sampler2D backDepthSampler;uniform float backSizeFactor; +#endif +#ifdef SSR_USE_ENVIRONMENT_CUBE +uniform samplerCube envCubeSampler; +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; +#include +#include +#include +vec3 hash(vec3 a) +{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} +float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; +#ifdef SSR_ATTENUATE_SCREEN_BORDERS +vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE +attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS +attenuation*=1.0-(numIterations/maxSteps); +#endif +#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION +vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; +#endif +return attenuation;} +#endif +void main() +{ +#ifdef SSR_SUPPORTED +vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { +#ifdef SSR_USE_BLUR +gl_FragColor=vec4(0.); +#else +gl_FragColor=colorFull; +#endif +return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; +#ifdef SSR_DECODE_NORMAL +csNormal=csNormal*2.0-1.0; +#endif +#ifdef SSR_NORMAL_IS_IN_WORLDSPACE +csNormal=(view*vec4(csNormal,0.0)).xyz; +#endif +float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); +#ifdef SSR_USE_ENVIRONMENT_CUBE +vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); +#endif +#ifdef SSR_INVERTCUBICMAP +wReflectedVector.y*=-1.0; +#endif +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +wReflectedVector.z*=-1.0; +#endif +vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; +#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE +envColor=toLinearSpace(envColor); +#endif +#else +vec3 envColor=color; +#endif +float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; +#ifdef SSRAYTRACE_DEBUG +vec3 debugColor; +#endif +#ifdef SSR_ATTENUATE_FACING_CAMERA +reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); +#endif +if (reflectionAttenuation>0.0) { +#ifdef SSR_USE_BLUR +vec3 jitt=vec3(0.); +#else +float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; +#endif +vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); +rayHasHit=traceScreenSpaceRay1( +csPosition, +normalize(csReflectedVector+jitt), +projectionPixel, +depthSampler, +texSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +backDepthSampler, +backSizeFactor, +#endif +thickness, +nearPlaneZ, +stepSize, +jitter, +maxSteps, +maxDistance, +selfCollisionNumSkip, +startPixel, +hitPixel, +hitPoint, +numIterations +#ifdef SSRAYTRACE_DEBUG +,debugColor +#endif +);} +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=vec4(debugColor,1.);return; +#endif +vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; +#ifdef SSR_INPUT_IS_GAMMA_SPACE +reflectedColor=toLinearSpace(reflectedColor); +#endif +reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} +#ifndef SSR_BLEND_WITH_FRESNEL +SSR*=fresnel; +#endif +#ifdef SSR_USE_BLUR +float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; +float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} +gl_FragColor=vec4(SSR,blur_radius/255.0); +#else +#ifdef SSR_BLEND_WITH_FRESNEL +vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,colorFull.a); +#endif +#else +gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); +#endif +} +`;rO.ShadersStore.screenSpaceReflection2PixelShader=T2;let T3=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) +{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} +void main() +{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} +float blurRadius=colorFull.a*255.0; +vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} +`;rO.ShadersStore.screenSpaceReflection2BlurPixelShader=T3;let T4=`uniform sampler2D textureSampler; +uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; +#include +#ifdef SSR_BLEND_WITH_FRESNEL +#include +#include +uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#endif +void main() +{ +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=texture2D(textureSampler,vUV); +#else +vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +#ifdef SSR_BLEND_WITH_FRESNEL +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,color.a); +#endif +} +`;rO.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader=T4;let T5=t7.Compose(new t5(.5,.5,.5),t8.Identity(),new t5(.5,.5,.5)),T6=t7.Compose(new t5(.5,.5,1),t8.Identity(),new t5(.5,.5,0));class T8 extends TB{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;let t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){let e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!1,s=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{let e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var e,t;let i=this._scene.getEngine(),r=this._prePassRenderer,s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(r&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){let e=r.getRenderTarget();e&&e.textures&&(s=e.textures[r.getIndex(4)].getSize())}else(null===(t=this._ssrPostProcess)||void 0===t?void 0:t.inputTexture)&&(s.width=this._ssrPostProcess.inputTexture.width,s.height=this._ssrPostProcess.inputTexture.height);return s}_updateEffectDefines(){var e,t,i,r,s;let n=[];(this._geometryBufferRenderer||this._prePassRenderer)&&n.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&n.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&n.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(n.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&n.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&n.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&n.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&n.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&n.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&n.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&n.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&n.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&n.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&n.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&n.push("#define SSR_USE_BLUR"),this._debug&&n.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&n.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&n.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&n.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&n.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(null!==(t=null===(e=this._geometryBufferRenderer)||void 0===e?void 0:e.generateNormalsInWorldSpace)&&void 0!==t?t:null===(i=this._prePassRenderer)||void 0===i?void 0:i.generateNormalsInWorldSpace)&&n.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),(null===(r=this._geometryBufferRenderer)||void 0===r?void 0:r.normalsAreUnsigned)&&n.push("#define SSR_DECODE_NORMAL"),null===(s=this._ssrPostProcess)||void 0===s||s.updateEffect(n.join("\n"))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;let t=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){let t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new fE(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),t.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new x4(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new x4(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new x4(t,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;let e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){let t=null!==(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))&&void 0!==e?e:-1;-1!==t&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,r;for(let s=0;s{this._resizeDepthRenderer();let t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){let i=t.getTextureIndex(TP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){let t=i.getIndex(5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));let r=this._scene.activeCamera;if(!r)return;let s=r.getViewMatrix(),n=r.getProjectionMatrix();n.invertToRef(ie.Matrix[0]),s.invertToRef(ie.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",s),e.setMatrix("invView",ie.Matrix[1]),e.setMatrix("invProjectionMatrix",ie.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);let a=this._getTextureSize();t7.ScalingToRef(a.width,a.height,1,ie.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?T6:T5,ie.Matrix[3]),ie.Matrix[3].multiplyToRef(ie.Matrix[2],ie.Matrix[4]),e.setMatrix("projectionPixel",ie.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new T0)}_createBlurAndCombinerPostProcesses(){let e=this._scene.getEngine();this._blurPostProcessX=new aL("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(e=>{var t,i;let r=null!==(i=null===(t=this._blurPostProcessX)||void 0===t?void 0:t.inputTexture.width)&&void 0!==i?i:this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/r,0)}),this._blurPostProcessY=new aL("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(e=>{var t,i;let r=null!==(i=null===(t=this._blurPostProcessY)||void 0===t?void 0:t.inputTexture.height)&&void 0!==i?i:this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/r)});let t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"],r="";this._debug&&(r+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(r+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(r+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(r+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new aL("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(e=>{var t;let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(r||i){if(r&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){let t=r.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[r.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){let t=i.getTextureIndex(TP.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",i.getGBuffer().textures[t]),this.useFresnel&&(e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("depthSampler",i.getGBuffer().textures[0]))}else if(r){let t=r.getIndex(3);if(e.setTexture("reflectivitySampler",r.getRenderTarget().textures[t]),this.useFresnel){let t=r.getIndex(5),i=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[i]),e.setTexture("depthSampler",r.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();i.invertToRef(ie.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",ie.Matrix[0])}}}})}serialize(){let e=i$.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return i$.Parse(()=>new T8(e._name,t,e._ratio),e,t,i)}}iZ([iW()],T8.prototype,"samples",null),iZ([iW()],T8.prototype,"maxDistance",void 0),iZ([iW()],T8.prototype,"step",void 0),iZ([iW()],T8.prototype,"thickness",void 0),iZ([iW()],T8.prototype,"strength",void 0),iZ([iW()],T8.prototype,"reflectionSpecularFalloffExponent",void 0),iZ([iW()],T8.prototype,"maxSteps",void 0),iZ([iW()],T8.prototype,"roughnessFactor",void 0),iZ([iW()],T8.prototype,"selfCollisionNumSkip",void 0),iZ([iW()],T8.prototype,"_reflectivityThreshold",void 0),iZ([iW("_ssrDownsample")],T8.prototype,"_ssrDownsample",void 0),iZ([iW()],T8.prototype,"ssrDownsample",null),iZ([iW("blurDispersionStrength")],T8.prototype,"_blurDispersionStrength",void 0),iZ([iW("blurDownsample")],T8.prototype,"_blurDownsample",void 0),iZ([iW("enableSmoothReflections")],T8.prototype,"_enableSmoothReflections",void 0),iZ([iW("environmentTexture")],T8.prototype,"_environmentTexture",void 0),iZ([iW("environmentTextureIsProbe")],T8.prototype,"_environmentTextureIsProbe",void 0),iZ([iW("attenuateScreenBorders")],T8.prototype,"_attenuateScreenBorders",void 0),iZ([iW("attenuateIntersectionDistance")],T8.prototype,"_attenuateIntersectionDistance",void 0),iZ([iW("attenuateIntersectionIterations")],T8.prototype,"_attenuateIntersectionIterations",void 0),iZ([iW("attenuateFacingCamera")],T8.prototype,"_attenuateFacingCamera",void 0),iZ([iW("attenuateBackfaceReflection")],T8.prototype,"_attenuateBackfaceReflection",void 0),iZ([iW("clipToFrustum")],T8.prototype,"_clipToFrustum",void 0),iZ([iW("useFresnel")],T8.prototype,"_useFresnel",void 0),iZ([iW("enableAutomaticThicknessComputation")],T8.prototype,"_enableAutomaticThicknessComputation",void 0),iZ([iW("backfaceDepthTextureDownsample")],T8.prototype,"_backfaceDepthTextureDownsample",void 0),iZ([iW("backfaceForceDepthWriteTransparentMeshes")],T8.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),iZ([iW("isEnabled")],T8.prototype,"_isEnabled",void 0),iZ([iW("inputTextureColorIsInGammaSpace")],T8.prototype,"_inputTextureColorIsInGammaSpace",void 0),iZ([iW("generateOutputInGammaSpace")],T8.prototype,"_generateOutputInGammaSpace",void 0),iZ([iW("debug")],T8.prototype,"_debug",void 0),t0["BABYLON.SSRRenderingPipeline"]=T8;let T7=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; +#if defined(HABLE_TONEMAPPING) +const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; +#endif +float Luminance(vec3 c) +{return dot(c,vec3(0.22,0.707,0.071));} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 colour=texture2D(textureSampler,vUV).rgb; +#if defined(REINHARD_TONEMAPPING) +float lum=Luminance(colour.rgb); +float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); +colour*=scale/lum; +#elif defined(HABLE_TONEMAPPING) +colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; +#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) +colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; +#elif defined(PHOTOGRAPHIC_TONEMAPPING) +colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); +#endif +gl_FragColor=vec4(colour.rgb,1.0);}`;rO.ShadersStore.tonemapPixelShader=T7,function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(tI||(tI={}));let T9=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +} +`;rO.ShadersStore.volumetricLightScatteringPassVertexShader=be;let bt=`#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV; +#endif +#if defined(ALPHATEST) +uniform sampler2D diffuseSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#if defined(ALPHATEST) +vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) +discard; +#endif +gl_FragColor=vec4(0.0,0.0,0.0,1.0);} +`;rO.ShadersStore.volumetricLightScatteringPassPixelShader=bt;class bi extends aL{get useDiffuseColor(){return ig.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){ig.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,s=100,n=n6.BILINEAR_SAMPLINGMODE,a,o,l){var h,u;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,a,o,"#define NUM_SAMPLES "+s),this._screenCoordinates=t4.Zero(),this.customMeshPosition=t5.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,a=(l=null!==(u=null!==(h=null==i?void 0:i.getScene())&&void 0!==h?h:l)&&void 0!==u?u:this._scene).getEngine(),this._viewPort=new nr(0,0,1,1).toGlobal(a.getRenderWidth(),a.getRenderHeight()),this.mesh=null!=r?r:bi.CreateDefaultMesh("VolumetricLightScatteringMesh",l),this._createPass(l,t.passRatio||t),this.onActivate=e=>{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add(e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;let r=e.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);let s=null===(i=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(r,e,t);let n=[],a=[sf.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(sf.UVKind)&&(a.push(sf.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(sf.UV2Kind)&&(a.push(sf.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(a.push(sf.MatricesIndicesKind),a.push(sf.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),t&&(n.push("#define INSTANCES"),nw.PushAttributesForInstances(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));let l=e._getDrawWrapper(void 0,!0),h=l.defines,u=n.join("\n");return h!==u&&l.setEffect(r.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:r.numBoneInfluencers}),u),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){let t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){let i;let r=e.getEngine();this._volumetricLightScatteringRTT=new a5("volumetricLightScatteringMap",{width:r.getRenderWidth()*t,height:r.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=n6.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=n6.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;let s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);let n=e=>{var t;let i=e.getRenderingMesh(),r=e.getEffectiveMesh();if(this._meshExcluded(i))return;r._internalAbstractMeshDataInfo._isActiveIntermediate=!1;let s=e.getMaterial();if(!s)return;let n=i.getScene(),a=n.getEngine();a.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);let o=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;let l=a.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){let h=null===(t=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[a.currentRenderPassId],u=e._getDrawWrapper();if(i!==this.mesh||u||(u=s._getDrawWrapper()),!u)return;let c=u.effect;if(a.enableEffect(u),l||i._bind(e,c,s.fillMode),i===this.mesh)s.bind(r.getWorldMatrix(),i);else if(h)h.bindForSubMesh(r.getWorldMatrix(),r,e);else{if(c.setMatrix("viewProjection",n.getTransformMatrix()),s&&s.needAlphaTesting()){let e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&c.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&c.setMatrix("world",r.getWorldMatrix()),i._processRendering(r,e,c,nB.TriangleFillMode,o,l,(e,t)=>{e||c.setMatrix("world",t)})}},a=new il(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{i=e.clearColor,e.clearColor=a}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=i}),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{let a;let o=e.getEngine();if(s.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));let t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):ig.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){let e=t2.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return i$.Parse(()=>new bs(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}iZ([iW()],bs.prototype,"ridge",void 0),iZ([iW()],bs.prototype,"valley",void 0),t0["BABYLON.ScreenSpaceCurvaturePostProcess"]=bs;let bn=`uniform vec4 color; +`;rO.IncludesShadersStore.boundingBoxRendererFragmentDeclaration=bn;let ba=`#ifdef WEBGL2 +uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#else +layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; +#endif +`;rO.IncludesShadersStore.boundingBoxRendererUboDeclaration=ba;let bo=`#include<__decl__boundingBoxRendererFragment> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.boundingBoxRendererPixelShader=bo;let bl=`uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +`;rO.IncludesShadersStore.boundingBoxRendererVertexDeclaration=bl;let bh=`attribute vec3 position; +#include<__decl__boundingBoxRendererVertex> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec4 worldPos=world*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;rO.ShadersStore.boundingBoxRendererVertexShader=bh,Object.defineProperty(sY.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),sY.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new bu(this)),this._boundingBoxRenderer},Object.defineProperty(nM.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class bu{constructor(e){this.name=sb.NAME_BOUNDINGBOXRENDERER,this.frontColor=new io(1,1,1),this.backColor=new io(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new tj,this.onAfterBoxRenderingObservable=new tj,this.onResourcesReadyObservable=new tj,this.enabled=!0,this.renderList=new sa(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new sp(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new sp(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(sb.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(sb.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(sb.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(sb.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new ug("colorShader",this.scene,"boundingBoxRenderer",{attributes:[sf.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new ug("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[sf.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=un({size:1});this._vertexBuffers[sf.PositionKind]=new sf(e,t.positions,sf.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){let e=this._vertexBuffers[sf.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;let r=this.scene.getEngine();r.setDepthWrite(!1);let s=this.scene.getTransformMatrix();for(let n=0;n{let t=e._getComponent(sb.NAME_DEPTHRENDERER);t||(t=new bc(e),e._addComponent(t))};let bd=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( +frontColor.rgb+alphaMultiplier*backColor.rgb, +frontColor.a+backColor.a +);}`;rO.ShadersStore.oitFinalPixelShader=bd;let bp=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { +discard;}}`;rO.ShadersStore.oitBackBlendPixelShader=bp;class b_{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class bf{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){let t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new sa(10),this._excludedSubMeshes=new sa(10),this._excludedMeshes=[],this._colorCache=[new il(bf._DEPTH_CLEAR_VALUE,bf._DEPTH_CLEAR_VALUE,0,0),new il(-bf._MIN_DEPTH,bf._MAX_DEPTH,0,0),new il(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){ig.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let e=0;e +uniform vec4 color; +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#include +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.linePixelShader=bg;let bv=`#include +#include +attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=finalWorld*vec4(position,1.0); +#include +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.lineVertexShader=bv,nM.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},nM.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new bT(this,e,t,!0,i),this},Object.defineProperty(nM.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),uT.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new bb(this,e,t),this},ub.prototype.enableEdgesRendering=function(e=.95,t=!1){return uT.prototype.enableEdgesRendering.apply(this,arguments),this};class bx{constructor(){this.edges=[],this.edgesConnectedCount=0}}class bT{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){let t=new ug("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,r=!0,s){var n;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=[],this._linesNormals=[],this._linesIndices=[],this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new sa(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=s?s:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new rY(e.getEngine())),this._prepareRessources(),r&&(null===(n=null==s?void 0:s.useAlternateEdgeFinder)||void 0===n||n?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=bT._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[sf.PositionKind];e&&e._rebuild(),(e=this._buffers[sf.NormalKind])&&e._rebuild();let t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[sf.PositionKind];t&&(t.dispose(),this._buffers[sf.PositionKind]=null),(t=this._buffers[sf.NormalKind])&&(t.dispose(),this._buffers[sf.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),null===(e=this._drawWrapper)||void 0===e||e.dispose()}_processEdgeForAdjacencies(e,t,i,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,r,s){(void 0===t||t5.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort((e,t)=>e[1]t[1]?1:0):e[t].sort((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--a)s(e[a%3],o,a!==n+2?r[i[t+(a+1)%3]]:-1);let h=o.length;i.push(r[i[t+n]],a[0],o[0]),i.push(r[i[t+(n+1)%3]],o[h-1],a[l-1]);let u=l<=h,c=u?l:h,d=u?h:l,p=u?l-1:h-1,_=u?0:1,f=l+h-2,m=0,g=0,v=u?a:o,x=u?o:a,T=0;for(;f-- >0;){let e;_?i.push(v[m],x[g]):i.push(x[g],v[m]),(T+=c)>=d&&ms){let e=r;r=s,s=e}let a=r+"_"+s,o=m[a];o?o.done||(t5.Dot(t,o.normal)0||this._source.hasThinInstances)}render(){let e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}let i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances,s=0;if(r){if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){let e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;enull!=e),this._scene.autoClear=!0;let r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;let s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0],a=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?a=n:this._needsCompositionForThisPass?a=e.imageProcessingPostProcess:s&&(a=s),this._bindFrameBuffer(),this._linkInternalTexture(e,a)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e))){for(let r=0;r=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw iL("PrePassRendererSceneComponent")},bS.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(sY.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),sY.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new bS(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,ig.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},sY.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class bC{constructor(e){this.name=sb.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(sb.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(sb.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(sb.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(sb.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(sb.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(sb.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(sb.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(sb.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;let s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){let t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}bS._SceneComponentInitialization=e=>{let t=e._getComponent(sb.NAME_PREPASSRENDERER);t||(t=new bC(e),e._addComponent(t))};let by=`#define rcp(x) 1./x +#define GOLDEN_RATIO 1.618033988749895 +#define TWO_PI 6.2831855 +vec2 Golden2dSeq(int i,float n) +{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} +vec2 SampleDiskGolden(int i,int sampleCount) +{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;rO.IncludesShadersStore.fibonacci=by,rO.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";let bA=`#include +#include +#include +#include +varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; +#define rcp(x) 1./x +#define Sq(x) x*x +#define SSS_BILATERAL_FILTER true +vec3 EvalBurleyDiffusionProfile(float r,vec3 S) +{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); +vec3 expSum=exp_13*(1.+exp_13*exp_13); +return (S*rcp(8.*PI))*expSum; } +vec2 SampleBurleyDiffusionProfile(float u,float rcpS) +{u=1.-u; +float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); +float p=(g*n)*n; +float c=1.+p+n; +float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); +float x=(3./LOG2_E)*log2(c)-d; +float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; +return vec2(r,rcpPdf);} +vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) +{ +#ifndef SSS_BILATERAL_FILTER +z=0.; +#endif +float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; +#if SSS_CLAMP_ARTIFACT +return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); +#else +return EvalBurleyDiffusionProfile(r,S)*area; +#endif +} +void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, +float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) +{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; +float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; +vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; +float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) +{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} +else +{}} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) +{centerDepth=texture2D(depthSampler,vUV).r;} +if (!passedStencilTest) { +gl_FragColor=inputColor;return;} +float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; +vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; +float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) +{ +#ifdef DEBUG_SSS_SAMPLES +vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; +#endif +gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} +#ifdef DEBUG_SSS_SAMPLES +vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; +#endif +float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); +vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration){ig.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}let i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}}class bI{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=sb.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new io(1,1,1)),this._scene=e,bI._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return ig.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw iL("SubSurfaceSceneComponent")},tW.AddParser(sb.NAME_SUBSURFACE,(e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(sb.NAME_SUBSURFACE);t||(t=new bP(e),e._addComponent(t))};let bM=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform vec4 color; +#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#include +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.outlinePixelShader=bM;let bD=`attribute vec3 position;attribute vec3 normal; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform float offset; +#include +uniform mat4 viewProjection; +#ifdef ALPHATEST +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +vec3 offsetPosition=positionUpdated+(normalUpdated*offset); +#include +#include +#include +vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; +#ifdef ALPHATEST +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include +#include +} +`;rO.ShadersStore.outlineVertexShader=bD,sY.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new bO(this)),this._outlineRenderer},Object.defineProperty(nX.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(nX.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class bO{constructor(e){this.name=sb.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(sb.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(sb.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",t)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];let r=[],s=[sf.PositionKind,sf.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;let o=n.getScene();a.needAlphaTesting()&&(r.push("#define ALPHATEST"),n.isVerticesDataPresent(sf.UVKind)&&(s.push(sf.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(sf.UV2Kind)&&(s.push(sf.UV2Kind),r.push("#define UV2"))),a.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),nO(a,o,r),n.useBones&&n.computeBonesUsingShaders?(s.push(sf.MatricesIndicesKind),s.push(sf.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(sf.MatricesIndicesExtraKind),s.push(sf.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");let l=n.morphTargetManager,h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),nw.PrepareAttributesForMorphTargetsInfluencers(s,n,h)),t&&(r.push("#define INSTANCES"),nw.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));let u=e._getDrawWrapper(i,!0),c=u.defines,d=r.join("\n");if(c!==d){let e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];nD(e),u.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){let r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(bO._StencilReference),this._engine.setStencilFunctionReference(bO._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){let e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}bO._StencilReference=4;class bN{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!(null===(e=this.vertexBuffers)||void 0===e?void 0:e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new tj,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){let e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new a0({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new a0({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;let e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){let e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;let t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){let e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;let t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;null===(e=this._depthEffectWrapper)||void 0===e||e.dispose(),null===(t=this._thicknessEffectWrapper)||void 0===t||t.dispose()}}class bF extends bN{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add(()=>{this._engine.setAlphaMode(2)})))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class bw{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){let e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,r,s,n,a=1,o=6,l=1,h=6,u=!1,c=null,d=!0,p=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new tj,this._name=e,this._scene=t,this._camera=c,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=n,this._textureType=a,this._textureFormat=o,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=u,this._generateDepthBuffer=d,this._samples=p,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){let[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});let e=this._rt.texture;e.incrementReferences(),this._texture=new n6(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=n6.CLAMP_ADDRESSMODE,this._texture.wrapV=n6.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,r,s,n=!1){let a=this._scene.getEngine(),o=new t4(Math.floor(this._blurTextureSizeX/r),Math.floor(this._blurTextureSizeY/r)),l=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:o.x,height:o.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),u=h.texture;u.incrementReferences();let c=new n6(null,this._scene);if(c.name="rttBlurred"+s,c._texture=u,c.wrapU=n6.CLAMP_ADDRESSMODE,c.wrapV=n6.CLAMP_ADDRESSMODE,c.anisotropicFilteringLevel=1,n){let r=new aL("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),r.onSizeChangedObservable.add(()=>{r._textures.forEach(e=>{e.texture.wrapU=n6.CLAMP_ADDRESSMODE,e.texture.wrapV=n6.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(r);let s=new aL("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.onApplyObservable.add(e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),s.onSizeChangedObservable.add(()=>{s._textures.forEach(e=>{e.texture.wrapU=n6.CLAMP_ADDRESSMODE,e.texture.wrapV=n6.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s),r.autoClear=!1,s.autoClear=!1;let n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?s:r;return[h,c,n]}{let r=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new aL("BilateralBlurX","fluidRenderingBilateralBlur",r,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),s.onSizeChangedObservable.add(()=>{s._textures.forEach(e=>{e.texture.wrapU=n6.CLAMP_ADDRESSMODE,e.texture.wrapV=n6.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s);let n=new aL("BilateralBlurY","fluidRenderingBilateralBlur",r,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add(e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),n.onSizeChangedObservable.add(()=>{n._textures.forEach(e=>{e.texture.wrapU=n6.CLAMP_ADDRESSMODE,e.texture.wrapV=n6.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(n),s.autoClear=!1,n.autoClear=!1;let o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?n:s;return[h,c,o]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((null!==(t=null===(e=this._camera)||void 0===e?void 0:e.fov)&&void 0!==t?t:45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,r;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),null===(e=this._rt)||void 0===e||e.dispose(),this._rt=null,null===(t=this._texture)||void 0===t||t.dispose(),this._texture=null,null===(i=this._rtBlur)||void 0===i||i.dispose(),this._rtBlur=null,null===(r=this._textureBlurred)||void 0===r||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(tP||(tP={}));class bL{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new io(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new t5(-2,-1,1).normalize(),this._debugFeature=tP.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new tj,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=null!=t?t:e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new t7,this._depthClearColor=new il(1e6,1e6,1e6,1),this._thicknessClearColor=new il(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;let r=null!==(e=this._depthMapSize)&&void 0!==e?e:this._engine.getRenderWidth(),s=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new bw("Depth",this._scene,r,s,r,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){let e=null!==(t=this._diffuseMapSize)&&void 0!==t?t:this._engine.getRenderWidth(),i=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new bw("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}let n=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),a=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new bw("Thickness",this._scene,n,a,n,a,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){(null===e||e===this._depthRenderTarget)&&this._setBlurDepthParameters(),(null===e||e===this._thicknessRenderTarget)&&this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){var e;let t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;let n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new t4(1/n.getSize().width,1/n.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture)&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),r.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===tP.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===tP.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),(this._debugFeature===tP.DepthTexture||this._debugFeature===tP.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new aL("FluidRendering","fluidRenderingRender",i,r,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(e=>{var i,r,s,n,o,l,h,u,c,d,p,_,f,m,g,v,x,T,b,E,S,C,y;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&e.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(n=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==n?n:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==r?r:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(u=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==u?u:null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(l=null===(o=this._diffuseRenderTarget.texture)||void 0===o?void 0:o.getInternalTexture())&&void 0!==l?l:null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&e.setTextureSampler("bgDepthSamplerSampler",null!==(c=this._bgDepthTexture)&&void 0!==c?c:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(f=null===(_=this._thicknessRenderTarget.textureBlur)||void 0===_?void 0:_.getInternalTexture())&&void 0!==f?f:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(p=null===(d=this._thicknessRenderTarget.texture)||void 0===d?void 0:d.getInternalTexture())&&void 0!==p?p:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){let i=null!==(m=this._environmentMap)&&void 0!==m?m:this._scene.environmentTexture;i&&(e.setTexture("reflectionSampler",i),t.isWebGPU&&e.setTextureSampler("reflectionSamplerSampler",null!==(g=null==i?void 0:i.getInternalTexture())&&void 0!==g?g:null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",a),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case tP.DepthTexture:i=this._depthRenderTarget.texture;break;case tP.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case tP.ThicknessTexture:i=null!==(x=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==x?x:null;break;case tP.ThicknessBlurredTexture:i=(null===(T=this._thicknessRenderTarget)||void 0===T?void 0:T.enableBlur)?null!==(E=null===(b=this._thicknessRenderTarget)||void 0===b?void 0:b.textureBlur)&&void 0!==E?E:null:null!==(C=null===(S=this._thicknessRenderTarget)||void 0===S?void 0:S.texture)&&void 0!==C?C:null;break;case tP.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==tP.Normals&&(e.setTexture("debugSampler",i),t.isWebGPU&&e.setTextureSampler("debugSamplerSampler",null!==(y=null==i?void 0:i.getInternalTexture())&&void 0!==y?y:null))}})}_clearTargets(){var e,t,i;(null===(e=this._depthRenderTarget)||void 0===e?void 0:e.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(t=this._diffuseRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(i=this._thicknessRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var t,i,r,s,n,a;if(this._needInitialization||!e.isReady())return;let o=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(null===(t=this._depthRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(i=this._diffuseRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(r=this._thicknessRenderTarget)||void 0===r?void 0:r.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),null===(s=this._depthRenderTarget)||void 0===s||s.applyBlurPostProcesses(),null===(n=this._diffuseRenderTarget)||void 0===n||n.applyBlurPostProcesses(),null===(a=this._thicknessRenderTarget)||void 0===a||a.applyBlurPostProcesses(),o&&this._engine.bindFramebuffer(o)}dispose(e=!1){var t,i,r,s;e||(null===(t=this._depthRenderTarget)||void 0===t||t.dispose(),this._depthRenderTarget=null,null===(i=this._diffuseRenderTarget)||void 0===i||i.dispose(),this._diffuseRenderTarget=null,null===(r=this._thicknessRenderTarget)||void 0===r||r.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),null===(s=this._renderPostProcess)||void 0===s||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class bB extends bN{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(let t in e){let i;let r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new sf(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new a0({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new sf(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&null!==(t=null===(e=this._diffuseEffectWrapper)||void 0===e?void 0:e.effect.isReady())&&void 0!==t&&t}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){let e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;let t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;for(let t in super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose(),this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}let bU=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; +#include +void main(void) +{vec4 color=texture2D(textureSampler,vUV); +#ifdef DEPTH_TEXTURE +gl_FragDepth=color.r; +#else +if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} +gl_FragColor=color; +#endif +} +`;rO.ShadersStore.copyTextureToTexturePixelShader=bU,function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(tM||(tM={}));class bV{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new aJ(e),this._effectWrapper=new a0({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add(()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)})}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=tM.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;let r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class bk{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new bV(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${r}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}let bG=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +attribute vec3 velocity;varying float velocityNorm; +#endif +void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; +#ifdef FLUIDRENDERING_VELOCITY +velocityNorm=length(velocity); +#endif +} +`;rO.ShadersStore.fluidRenderingParticleDepthVertexShader=bG;let bz=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +varying float velocityNorm; +#endif +void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); +#ifndef FLUIDRENDERING_RHS +normal.z=-normal.z; +#endif +vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; +#ifdef WEBGPU +gl_FragDepth=clipSpacePos.z/clipSpacePos.w; +#else +gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; +#endif +#ifdef FLUIDRENDERING_RHS +realViewPos.z=-realViewPos.z; +#endif +#ifdef FLUIDRENDERING_VELOCITY +glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); +#else +glFragColor=vec4(realViewPos.z,0.,0.,1.); +#endif +} +`;rO.ShadersStore.fluidRenderingParticleDepthPixelShader=bz;let bW=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} +`;rO.ShadersStore.fluidRenderingParticleThicknessVertexShader=bW;let bH=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} +`;rO.ShadersStore.fluidRenderingParticleThicknessPixelShader=bH;let bX=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} +`;rO.ShadersStore.fluidRenderingParticleDiffuseVertexShader=bX;let bY=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} +`;rO.ShadersStore.fluidRenderingParticleDiffusePixelShader=bY;let bj=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} +int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} +glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} +`;rO.ShadersStore.fluidRenderingBilateralBlurPixelShader=bj;let bK=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} +float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} +sum/=wsum;glFragColor=vec4(sum.rgb,1.);} +`;rO.ShadersStore.fluidRenderingStandardBlurPixelShader=bK;let b$=`/* disable_uniformity_analysis */ +#define IOR 1.333 +#define ETA 1.0/IOR +#define F0 0.02 +uniform sampler2D textureSampler;uniform sampler2D depthSampler; +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +uniform sampler2D diffuseSampler; +#else +uniform vec3 diffuseColor; +#endif +#ifdef FLUIDRENDERING_FIXED_THICKNESS +uniform float thickness;uniform sampler2D bgDepthSampler; +#else +uniform float minimumThickness;uniform sampler2D thicknessSampler; +#endif +#ifdef FLUIDRENDERING_ENVIRONMENT +uniform samplerCube reflectionSampler; +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +uniform sampler2D debugSampler; +#endif +uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef FLUIDRENDERING_RHS +ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; +#else +ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} +void main(void) {vec2 texCoord=vUV; +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +vec4 color=texture2D(debugSampler,texCoord); +#ifdef FLUIDRENDERING_DEBUG_DEPTH +glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} +#else +glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} +#endif +return; +#endif +vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; +#ifndef FLUIDRENDERING_FIXED_THICKNESS +float thickness=texture2D(thicknessSampler,texCoord).x; +#else +float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; +#endif +vec4 backColor=texture2D(textureSampler,texCoord); +#ifndef FLUIDRENDERING_FIXED_THICKNESS +if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { +#else +if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { +#endif +glFragColor=backColor;return;} +vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} +vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} +vec3 normal=normalize(cross(ddy,ddx)); +#ifdef FLUIDRENDERING_RHS +normal=-normal; +#endif +#ifndef WEBGPU +if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) +glFragColor=vec4(normal*0.5+0.5,1.0);return; +#endif +vec3 rayDir=normalize(viewPos); +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; +#endif +vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); +#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING +float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; +#endif +vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); +vec3 refractionColor=transmitted.rgb*transmittance; +#ifdef FLUIDRENDERING_ENVIRONMENT +vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; +#else +vec3 finalColor=refractionColor+specular; +#endif +#ifdef FLUIDRENDERING_VELOCITY +float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); +#endif +glFragColor=vec4(finalColor,transmitted.a);} +`;rO.ShadersStore.fluidRenderingRenderPixelShader=b$,Object.defineProperty(sY.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),sY.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new bQ(this)),this._fluidRenderer},sY.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};class bq{constructor(e){this.name=sb.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(sb.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(sb.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._prepareRendering()}_afterCameraDraw(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._render(e)}rebuild(){}dispose(){this.scene.disableFluidRenderer()}}class bQ{static _SceneComponentInitialization(e){let t=e._getComponent(sb.NAME_FLUIDRENDERER);t||(t=new bq(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,bQ._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){let t=this._getParticleSystemIndex(e);return -1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){let s=new bF(this._scene,e);s.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new bL(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==t&&(i.generateDiffuseTexture=t);let n={object:s,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,r,s){let n=new bB(this._scene,e,t);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),r||(r=new bL(this._scene,s),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==i&&(r.generateDiffuseTexture=i);let a={object:n,targetRenderer:r};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}removeRenderObject(e,t=!0){let i=this.renderObjects.indexOf(e);return -1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort((e,t)=>e.object.priorityt.object.priority?1:0)}_removeUnusedTargetRenderers(){let e={};for(let t=0;t{var e;for(let t of(s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`),n)){let i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,r=null==i?void 0:i.texture;if(i&&r){let e=r.width+"_"+r.height,t=a[e];t||(t=a[e]=new bk(this._engine,r.width,r.height)),t.depthRTWrapper._shareDepth(i)}}})}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=this._cameras.get(t)[1],s=e.get(t);if(s)for(let e in r)s[1][e]||r[e].dispose();else for(let e in r)r[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){let e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)})}_setUseVelocityForRenderObject(){for(let e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(let e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var t;for(let t=0;t{let t=e[1];for(let e in t)t[e].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class bZ{get vertexCount(){return this._vertexCount}_createMaterial(e){rN.ShadersStore.gaussianSplattingVertexShader=bZ._VertexShaderSource,rN.ShadersStore.gaussianSplattingFragmentShader=bZ._FragmentShaderSource;let t=new ug("GaussianSplattingShader",e,{vertex:"gaussianSplatting",fragment:"gaussianSplatting"},{attributes:["position"],uniforms:["projection","modelView","viewport"]});t.backFaceCulling=!1,t.alpha=.9999,this._material=t}_getMesh(e){let t=new nX(this.name,e),i=new ng;i.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],i.indices=[0,1,2,0,2,3],i.applyToMesh(t);let r=t.getBoundingInfo();return r.reConstruct(this._minimum,this._maximum),r.isLocked=!0,t.doNotSyncBoundingInfo=!0,t.material=this._material,t}_setData(e){this._vertexCount=e.length/32;let t=this._vertexCount;this._positions=new Float32Array(3*t),this._covA=new Float32Array(3*t),this._covB=new Float32Array(3*t);let i=new Float32Array(e.buffer);this._uBuffer=new Uint8Array(e.buffer);let r=t7.Zero(),s=t7.Zero(),n=t8.Identity();this._minimum.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._maximum.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let e=0;e{var i;for(let i=0;i{i(new Uint32Array(e.data.depthMix.buffer))};let r=new t4;this._sceneBeforeRenderObserver=this.scene.onBeforeRenderObservable.add(()=>{var e;let t=this.scene.getEngine();r.set(t.getRenderWidth(),t.getRenderHeight()),this._material.setVector2("viewport",r);let i=this.mesh.getWorldMatrix();i.multiplyToRef(this.scene.activeCamera.getViewMatrix(),this._modelViewMatrix);let s=this.mesh.getBoundingInfo();s.reConstruct(this._minimum,this._maximum,i),s.isLocked=!0,this._material.setMatrix("modelView",this._modelViewMatrix),null===(e=this._worker)||void 0===e||e.postMessage({view:this._modelViewMatrix.m,positions:this._positions})}),this._sceneDisposeObserver=this.scene.onDisposeObservable.add(()=>{this.dispose()})}loadDataAsync(e){return Promise.resolve(this._loadData(e))}loadFileAsync(e){return ss.LoadFileAsync(e,!0).then(e=>{this._loadData(e)})}dispose(){var e,t;this.scene.onDisposeObservable.remove(this._sceneDisposeObserver),this.scene.onBeforeRenderObservable.remove(this._sceneBeforeRenderObserver),null===(e=this._worker)||void 0===e||e.terminate(),this._worker=null,null===(t=this.mesh)||void 0===t||t.dispose(),this.mesh=null}}bZ._VertexShaderSource=` + precision mediump float; + attribute vec2 position; + + attribute vec4 world0; + attribute vec4 world1; + attribute vec4 world2; + attribute vec4 world3; + + uniform mat4 projection, modelView; + uniform vec2 viewport; + + varying vec4 vColor; + varying vec2 vPosition; + void main () { + vec3 center = world0.xyz; + vec4 color = world1; + vec3 covA = world2.xyz; + vec3 covB = world3.xyz; + + vec4 camspace = modelView * vec4(center, 1); + vec4 pos2d = projection * camspace; + + float bounds = 1.2 * pos2d.w; + if (pos2d.z < -pos2d.w || pos2d.x < -bounds || pos2d.x > bounds + || pos2d.y < -bounds || pos2d.y > bounds) { + gl_Position = vec4(0.0, 0.0, 2.0, 1.0); + return; + } + + mat3 Vrk = mat3( + covA.x, covA.y, covA.z, + covA.y, covB.x, covB.y, + covA.z, covB.y, covB.z + ); + vec2 focal = vec2(1132., 1132.); + mat3 J = mat3( + focal.x / camspace.z, 0., -(focal.x * camspace.x) / (camspace.z * camspace.z), + 0., focal.y / camspace.z, -(focal.y * camspace.y) / (camspace.z * camspace.z), + 0., 0., 0. + ); + + mat3 invy = mat3(1,0,0, 0,-1,0,0,0,1); + + mat3 T = invy * transpose(mat3(modelView)) * J; + mat3 cov2d = transpose(T) * Vrk * T; + + float mid = (cov2d[0][0] + cov2d[1][1]) / 2.0; + float radius = length(vec2((cov2d[0][0] - cov2d[1][1]) / 2.0, cov2d[0][1])); + float lambda1 = mid + radius, lambda2 = mid - radius; + + if(lambda2 < 0.0) return; + vec2 diagonalVector = normalize(vec2(cov2d[0][1], lambda1 - cov2d[0][0])); + vec2 majorAxis = min(sqrt(2.0 * lambda1), 1024.0) * diagonalVector; + vec2 minorAxis = min(sqrt(2.0 * lambda2), 1024.0) * vec2(diagonalVector.y, -diagonalVector.x); + + vColor = color; + vPosition = position; + vec2 vCenter = vec2(pos2d); + gl_Position = vec4( + vCenter + + (position.x * majorAxis * 1. / viewport + + position.y * minorAxis * 1. / viewport) * pos2d.w, pos2d.zw); + }`,bZ._FragmentShaderSource=` + precision highp float; + varying vec4 vColor; + varying vec2 vPosition; + void main () { + float A = -dot(vPosition, vPosition); + if (A < -4.0) discard; + float B = exp(A) * vColor.a; + gl_FragColor = vec4(vColor.rgb, B); + }`,bZ._CreateWorker=function(e){let t,i;let r=[],s=0,n=t=>{s=i.length;let n=new BigInt64Array(s),a=new Uint32Array(n.buffer);for(let e=0;e{if(!a){a=!0;let e=t;n(e),setTimeout(()=>{a=!1,e!==t&&o()},0)}};e.onmessage=e=>{t=e.data.view,.01>Math.abs(r[2]*t[2]+r[6]*t[6]+r[10]*t[10]-1)||(i=e.data.positions,o())}};class bJ{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class b0 extends bJ{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=[],this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new tj,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new il(1,1,1,1),this.position=t5.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=s.distance))&&(s=o,i))break}return s||new sm},sY.prototype._internalMultiPickSprites=function(e,t,i){if(!sm)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(sb.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(sb.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(sb.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();let e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){let n=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,r,s){let n=this.scene;return r?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&s&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){let s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,ic.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,ic.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,ic.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,ic.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){let n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){let i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,ic.CreateNewFromSprite(i.pickedSprite,n,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,ic.CreateNewFromSprite(i.pickedSprite,n,r)),s&&i.pickedSprite.actionManager.processTrigger(6,ic.CreateNewFromSprite(i.pickedSprite,n,r)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,ic.CreateNewFromSprite(n._pickedDownSprite,n,r)))}return i}}let b2=`#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); +#endif +`;rO.IncludesShadersStore.imageProcessingCompatibility=b2;let b3=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +#ifdef PIXEL_PERFECT +vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} +#endif +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#ifdef PIXEL_PERFECT +vec2 uv=uvPixelPerfect(vUV); +#else +vec2 uv=vUV; +#endif +vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) +{if (color.a<0.95) +discard;} +color*=vColor; +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.spritesPixelShader=b3;let b4=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; +vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); +vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; +#ifdef FOG +vFogDistance=viewPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.spritesVertexShader=b4;class b5{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,r=null){let s;this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new s_(e,this._vertexData,!0,this._vertexBufferSize);let n=this._buffer.createVertexBuffer(sf.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),a=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),o=6;if(this._useInstancing){let t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new s_(e,t,!1,2),s=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else s=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;let l=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(sf.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[sf.PositionKind]=n,this._vertexBuffers.options=a,this._vertexBuffers.offsets=s,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[sf.ColorKind]=u,this._createEffects()}_createEffects(){var e,t,i,r;null===(e=this._drawWrapperBase)||void 0===e||e.dispose(),null===(t=this._drawWrapperFog)||void 0===t||t.dispose(),null===(i=this._drawWrapperDepth)||void 0===i||i.dispose(),null===(r=this._drawWrapperFogDepth)||void 0===r||r.dispose(),this._drawWrapperBase=new rY(this._engine),this._drawWrapperFog=new rY(this._engine),this._drawWrapperDepth=new rY(this._engine,!1),this._drawWrapperFogDepth=new rY(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);let s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[sf.PositionKind,"options","offsets","inverts","cellInfo",sf.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],s),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[sf.PositionKind,"options","offsets","inverts","cellInfo",sf.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],s+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,r,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,a=this._drawWrapperDepth,o=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(n=this._drawWrapperFog,a=this._drawWrapperFogDepth,o=!0);let l=n.effect;if(!l.isReady())return;let h=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),c=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length),p=0,_=!0;for(let i=0;i>0;t._xOffset=(t.cellIndex-i*e)*this.cellWidth/s.width,t._yOffset=i*this.cellHeight/s.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._useInstancing?o-=2:(this._vertexData[o+6]=i,this._vertexData[o+7]=r),n?this._vertexData[o+8]=t.invertU?0:1:this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0,this._vertexData[o+10]=t._xOffset,this._vertexData[o+11]=t._yOffset,this._vertexData[o+12]=t._xSize/s.width,this._vertexData[o+13]=t._ySize/s.height,this._vertexData[o+14]=t.color.r,this._vertexData[o+15]=t.color.g,this._vertexData[o+16]=t.color.b,this._vertexData[o+17]=t.color.a}_buildIndexBuffer(){let e=[],t=0;for(let i=0;i{e.cellRef||(e.cellIndex=0);let i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=t2.LastCreatedScene),s._getComponent(sb.NAME_SPRITE)||s._addComponent(new b1(s)),this._fromPacked=o,this._scene=s;let h=this._scene.getEngine();if(this._spriteRenderer=new b5(h,i,n,s),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(void 0!==r)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new n6(t,s,!0,!1,a)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if((e="string"==typeof t?JSON.parse(t):t).frames.length){let t={};for(let i=0;i0);let r=e.substring(0,t-1)+".json";ss.LoadFile(r,e=>{try{let t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON format. Please check documentation for format specifications.")}},void 0,void 0,!1,()=>{ig.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1})}}_checkTextureAlpha(e,t,i,r,s){if(!e.useAlphaForPicking||!this.texture)return!0;let n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));let a=ie.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);let o=(a.x-r.x)/(s.x-r.x),l=1-(a.y-r.y)/(s.y-r.y),h=e._xOffset*n.width+o*e._xSize|0,u=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[(h+u*n.width)*4+3]>.5}intersects(e,t,i,r){let s=Math.min(this.capacity,this.sprites.length),n=t5.Zero(),a=t5.Zero(),o=Number.MAX_VALUE,l=null,h=ie.Vector3[0],u=ie.Vector3[1],c=t.getViewMatrix(),d=e,p=e;for(let t=0;te){if(!this._checkTextureAlpha(s,d,e,n,a))continue;if(p=d,o=e,l=s,r)break}}}}if(l){let e=new sm;c.invertToRef(ie.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=o;let t=ie.Vector3[2];return t.copyFrom(p.direction),t.normalize(),t.scaleInPlace(o),p.origin.addToRef(t,h),e.pickedPoint=t5.TransformCoordinates(h,ie.Matrix[0]),e}return null}multiIntersects(e,t,i){let r;let s=Math.min(this.capacity,this.sprites.length),n=t5.Zero(),a=t5.Zero(),o=[],l=ie.Vector3[0].copyFromFloats(0,0,0),h=ie.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let t=0;t{let a=new i2;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=b6.Parse(t,i||t2.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the sprite manager")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new b6("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,s)=>{let n=new i2;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(JSON.parse(n.responseText).jsonPayload).spriteManager),a=b6.Parse(s,t||t2.LastCreatedScene,i);a.snippetId=e,r(a)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}b6.SnippetUrl="https://snippet.babylonjs.com",b6.CreateFromSnippetAsync=b6.ParseFromSnippetAsync;let b8=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( +texture2D(frameMap,vec2(fX,0.),0.), +texture2D(frameMap,vec2(fX,fdStep*1.),0.), +texture2D(frameMap,vec2(fX,fdStep*2.),0.), +vec4(0.) +);} +void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); +#ifdef FLIPU +tileUV.y=1.0-tileUV.y; +#endif +vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;} +animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} +mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} +vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} +color.xyz*=colorMul;gl_FragColor=color;}`;rO.ShadersStore.spriteMapPixelShader=b8;let b7=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; +gl_Position=worldViewProjection*p;}`;rO.ShadersStore.spriteMapVertexShader=b7,function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(tD||(tD={})),tj.prototype.notifyObserversWithPromise=async function(e,t=-1,i,r,s){let n=Promise.resolve(e);if(!this.observers.length)return n;let a=this._eventState;return a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.userInfo=s,this.observers.forEach(i=>{!a.skipNextObservers&&!i._willBeUnregistered&&i.mask&t&&(n=i.scope?n.then(t=>(a.lastReturnValue=t,i.callback.apply(i.scope,[e,a]))):n.then(t=>(a.lastReturnValue=t,i.callback(e,a))),i.unregisterOnNextCall&&this._deferUnregister(i))}),await n,e};class b9{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class Ee extends b9{constructor(){super(...arguments),this._canBeMerged=e=>e instanceof nX&&!e.isDisposed()&&!!e.isVisible&&!!e.isEnabled()&&!(e.instances.length>0)&&!e.skeleton&&!e.hasLODLevels&&0!==e.getTotalVertices()}static get UpdateSelectionTree(){return Ee._UpdateSelectionTree}static set UpdateSelectionTree(e){Ee._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){let r=e.meshes.slice(0),s=r.length;for(let e=0;e{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),Et[e.id]=!0)},Er=(e,t)=>{let i={},r=e._geometry;return r&&!e.getScene().getGeometryById(r.id)&&Ei(r,t.geometries),e.serialize&&e.serialize(i),i},Es=(e,t)=>{if(e._isMesh){if(1===e.delayLoadState||0===e.delayLoadState){let i=i=>{t.materials=t.materials||[],e.material&&!t.materials.some(t=>t.id===e.material.id)&&t.materials.push(i.serialize())};if(e.material&&!e.material.doNotSerialize){if(e.material instanceof nU){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some(t=>t.id===e.material.id))for(let r of(t.multiMaterials.push(e.material.serialize()),e.material.subMaterials))r&&i(r)}else i(e.material)}else e.material||i(e.getScene().defaultMaterial);let r=e._geometry;r&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),Ei(r,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(Er(e,t))}}else"TransformNode"===e.getClassName()?t.transformNodes.push(e.serialize()):-1!==e.getClassName().indexOf("Camera")?t.cameras.push(e.serialize()):-1!==e.getClassName().indexOf("Light")&&t.lights.push(e.serialize())};class En{static ClearCache(){Et=[]}static Serialize(e){return En._Serialize(e)}static _Serialize(e,t=!0){let i,r,s;let n={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&n6.ForceSerializeBuffers&&ig.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),En.ClearCache(),n.useDelayedTextureLoading=e.useDelayedTextureLoading,n.autoClear=e.autoClear,n.clearColor=e.clearColor.asArray(),n.ambientColor=e.ambientColor.asArray(),n.gravity=e.gravity.asArray(),n.collisionsEnabled=e.collisionsEnabled,n.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(n.fogMode=e.fogMode,n.fogColor=e.fogColor.asArray(),n.fogStart=e.fogStart,n.fogEnd=e.fogEnd,n.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){let t=e.getPhysicsEngine();t&&(n.physicsEnabled=!0,n.physicsGravity=t.gravity.asArray(),n.physicsEngine=t.getPhysicsPluginName())}for(let t of(e.metadata&&(n.metadata=e.metadata),n.morphTargetManagers=[],e.meshes)){let e=t.morphTargetManager;e&&n.morphTargetManagers.push(e.serialize())}for(i=0,n.lights=[];i0){n.animationGroups=[];for(let t=0;t0)for(i=0,n.reflectionProbes=[];it)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){let r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],En.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r{0>e.indexOf(t)&&!t.doNotSerialize&&e.push(t)}),t&&e[r].parent&&0>e.indexOf(e[r].parent)&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach(e=>{Es(e,r)}),r}}class Ea{static IsSupported(e){let t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!Ea.IsSupported(e))throw"Your browser does not support recording so far.";let i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options=Object.assign(Object.assign({},Ea._DefaultOptions),t);let r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(let e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout(()=>{this.stopRecording()},1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise((e,t)=>{this._resolve=e,this._reject=t})}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),this._reject)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();let e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&ss.Download(e,this._fileName)}}Ea._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let Eo=null;function El(e,t,i,r,s="image/png",n=!1,a){let{height:o,width:l}=Eu(e,t,i);if(!(o&&l)){ig.Error("Invalid 'size' parameter !");return}Eo||(Eo=document.createElement("canvas")),Eo.width=l,Eo.height=o;let h=Eo.getContext("2d"),u=e.getRenderWidth()/e.getRenderHeight(),c=l,d=c/u;d>o&&(c=(d=o)*u);let p=Math.max(0,l-c)/2,_=Math.max(0,o-d)/2;t.getScene().activeCamera!==t?Eh(e,t,i,e=>{if(n){let t=new Blob([e]);ss.DownloadBlob(t),r&&r("")}else r&&r(e)},s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):e.onEndFrameObservable.addOnce(()=>{let t=e.getRenderingCanvas();h&&t&&h.drawImage(t,p,_,c,d),Eo&&(n?(ss.EncodeScreenshotCanvasData(Eo,void 0,s,void 0,a),r&&r("")):ss.EncodeScreenshotCanvasData(Eo,r,s,void 0,a))})}function Eh(e,t,i,r,s="image/png",n=1,a=!1,o,l=!1,h=!1,u=!0,c,d){let{height:p,width:_,finalWidth:f,finalHeight:m}=Eu(e,t,i);if(!(p&&_)){ig.Error("Invalid 'size' parameter !");return}let g={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(_,p);let v=t.getScene(),x=new a5("screenShot",{width:_,height:p},v,!1,!1,0,!1,n6.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);x.renderList=v.meshes.slice(),x.samples=n,x.renderSprites=l,x.activeCamera=t,x.forceLayerMaskCheck=u,null==d||d(x);let T=()=>{x.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce(()=>{f===_&&m===p?x.readPixels(void 0,void 0,void 0,!1).then(e=>{a4.DumpData(_,p,e,r,s,o,!0,void 0,c),x.dispose()}):u7("pass",x.getInternalTexture(),v,void 0,void 0,void 0,f,m).then(t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then(e=>{a4.DumpData(f,m,e,r,s,o,!0,void 0,c),t.dispose()})})}),x.render(!0),v.incrementRenderId(),v.resetCachedMaterial(),e.setSize(g.width,g.height),t.getProjectionMatrix(!0),v.render()):setTimeout(T,16)},b=()=>{v.incrementRenderId(),v.resetCachedMaterial(),T()};if(a){let e=new Tv("antialiasing",1,v.activeCamera);x.addPostProcess(e),e.getEffect().isReady()?b():e.getEffect().onCompiled=()=>{b()}}else b()}function Eu(e,t,i){let r=0,s=0,n=0,a=0;if("object"==typeof i){let o=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*o,s=i.width*o):i.width&&!i.height?r=Math.round((s=i.width*o)/e.getAspectRatio(t)):i.height&&!i.width?s=Math.round((r=i.height*o)*e.getAspectRatio(t)):r=Math.round((s=Math.round(e.getRenderWidth()*o))/e.getAspectRatio(t)),i.finalWidth&&i.finalHeight?(a=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?a=Math.round((n=i.finalWidth)/e.getAspectRatio(t)):i.finalHeight&&!i.finalWidth?n=Math.round((a=i.finalHeight)*e.getAspectRatio(t)):(n=s,a=r)}else isNaN(i)||(r=i,s=i,n=i,a=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),a&&(a=Math.floor(a)),{height:0|r,width:0|s,finalWidth:0|n,finalHeight:0|a}}ss.CreateScreenshot=El,ss.CreateScreenshotAsync=function(e,t,i,r="image/png",s){return new Promise((n,a)=>{El(e,t,i,e=>{void 0!==e?n(e):a(Error("Data is undefined"))},r,void 0,s)})},ss.CreateScreenshotUsingRenderTarget=Eh,ss.CreateScreenshotUsingRenderTargetAsync=function(e,t,i,r="image/png",s=1,n=!1,a,o=!1,l=!1,h=!0,u){return new Promise((c,d)=>{Eh(e,t,i,e=>{void 0!==e?c(e):d(Error("Data is undefined"))},r,s,n,a,o,l,h,u)})},function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(tO||(tO={}));class Ec{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(t){let e={};return{getItem:t=>{let i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){let i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){let i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){let i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}Ec._Storage=Ec._GetStorage(),function(e){class t{serialize(){let e={},t=Array(this._characterToIdx.size);return this._characterToIdx.forEach((e,i)=>{t[e]=i}),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){let i=JSON.parse(e),r=new t(i.characters);return r._insertionCosts=i.insertionCosts,r._deletionCosts=i.deletionCosts,r._substitutionCosts=i.substitutionCosts,r}constructor(e,t=null,i=null,r=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,r=null!=r?r:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=Array(e.length),this._deletionCosts=Array(e.length),this._substitutionCosts=Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map(e=>this._alphabet.getCharacterIdx(e))}distance(e){return i._Distance(this,e)}static _Distance(e,t){let r=e._alphabet;if(r!==t._alphabet)throw Error("Cannot Levenshtein compare Sequences built from different alphabets.");let s=e._characters,n=t._characters,a=s.length,o=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;eArray(i._MAX_SEQUENCE_LENGTH+1)),e.Sequence=i}(tN||(tN={}));class Ed{serialize(){return JSON.stringify(this)}static Deserialize(e){let t=JSON.parse(e),i=new Ed(t._segmentLength);return i._points=t._points.map(e=>new t5(e._x,e._y,e._z)),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{let i=()=>this._segmentLength/t5.Distance(this._points[t-1],e);for(let r=i();r<=1;r=i()){let i=this._points[t-1].scale(1-r);e.scaleAndAddToRef(r,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){let t=new Ed(this.getLength()/e);return this._points.forEach(e=>{t.add(e)}),t}tokenize(e){let t=[],i=new t5;for(let r=2;r.98)&&(t5.CrossToRef(Ed._ForwardDir,Ed._InverseFromVec,Ed._UpDir),Ed._UpDir.normalize(),t7.LookAtLHToRef(e,t,Ed._UpDir,Ed._LookMatrix),i.subtractToRef(t,Ed._FromToVec),Ed._FromToVec.normalize(),t5.TransformNormalToRef(Ed._FromToVec,Ed._LookMatrix,r),!0)}static _TokenizeSegment(e,t){Ed._BestMatch=0,Ed._Score=t5.Dot(e,t[0]),Ed._BestScore=Ed._Score;for(let i=1;iEd._BestScore&&(Ed._BestMatch=i,Ed._BestScore=Ed._Score);return Ed._BestMatch}}Ed._ForwardDir=new t5,Ed._InverseFromVec=new t5,Ed._UpDir=new t5,Ed._FromToVec=new t5,Ed._LookMatrix=new t7;class Ep{serialize(){return JSON.stringify(this._sequences.map(e=>e.serialize()))}static Deserialize(e,t){let i=new Ep;return i._sequences=JSON.parse(e).map(e=>tN.Sequence.Deserialize(e,t)),i}static CreateFromTrajectory(e,t,i){return Ep.CreateFromTokenizationPyramid(Ep._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){let i=new Ep;return i._sequences=e.map(e=>new tN.Sequence(e,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=Ep._FINEST_DESCRIPTOR_RESOLUTION){let r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t=0;for(let i=0;ie.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){let i=JSON.parse(e),r=new E_;return r._descriptors=i.descriptors.map(e=>Ep.Deserialize(e,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){let e;this._centroidIdx=-1;let t=this._descriptors.map(t=>(e=0,this._descriptors.forEach(i=>{e+=t.distance(i)}),e));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,E_._MIN_AVERAGE_DISTANCE))}}E_._MIN_AVERAGE_DISTANCE=1;class Ef{constructor(e,t,i){this._scene=e,ig.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{let t=e.data;if(t.startsWith(Ef._SERVER_PREFIX)){let e=t.substr(Ef._SERVER_PREFIX.length);ig.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),this._handleServerMessage(e);return}ig.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{ig.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&En.SerializeAsync(this._scene).then(e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)})}_handleClientMessage(){}}Ef._SERVER_PREFIX="$$";class Em{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){let e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}let Eg="timestamp",Ev="numPoints",Ex=/\r/g;class ET{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{let e=ra.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength,r=0;if(i>0){let e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+ET.NumberOfPointsOffset)+ET.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())}),this.datasetObservable.hasObservers()){let i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new tX(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var r;return this._strategies.has(e)&&!t?void 0:(this._strategies.has(e)&&t&&(null===(r=this._strategies.get(e))||void 0===r||r.dispose(),this._strategies.delete(e)),this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0,s=t.onAfterRenderObservable.add(()=>{r=i,i=0}),n=this._customEventObservable.add(t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)});return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(n)}}},category:i}),{name:e})}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){let e=t(this._scene);if(this._strategies.has(e.id)){e.dispose();continue}this.datasets.ids.push(e.id),i&&(i=i.replace(RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){let e=[ra.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach(t=>{let i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){let r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new Em(1800),this.datasets.ids.length=0,this.datasets.startingIndices=new Em(1800),this._datasetMeta.clear(),this._strategies.forEach(e=>e.dispose()),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){let i=e.replace(Ex,"").split("\n").map(e=>e.split(",").filter(e=>e.length>0)).filter(e=>e.length>0),r=ET.NumberOfPointsOffset;if(i.length<2)return!1;let s={ids:[],data:new Em(1800),startingIndices:new Em(1800)},[n,...a]=i;if(n.length<2||n[0]!==Eg||n[r]!==Ev)return!1;let o=new Map;for(let e=ET.SliceDataOffset;ee.dispose()),this._strategies.clear(),!t)for(let e of this.datasets.ids){let t=o.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${Eg},${Ev}`;for(let t=0;t{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}sY.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new ET(this)),this._perfCollector},tj.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){let e=function(e){let t=[],i=[],r=[],s=e.add(()=>{let e=t.length;for(let s=0;s{t.push(e),i.push(s),r.push(n)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return ni(e,this._coroutineScheduler)},tj.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};let Eb=`#ifdef GL_ES +precision highp float; +#endif +#define M_PI 3.1415926535897932384626433832795 +varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( +- sin( longitude )*sin( latitude ), +cos( latitude ), +- cos( longitude )*sin( latitude ) +);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;rO.ShadersStore.equirectangularPanoramaPixelShader=Eb;class EE extends ac{constructor(e,t={}){super(e),this.options=t,this._direction=new t5(0,0,-1),this._mat=new t7,this._onSelectEnabled=!1,this._origin=new t5(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new tj,this._onHitTestResults=e=>{let t=e.map(e=>{let t=t7.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}});this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&EE.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",ss.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(e=>e.filter(r||(e=>!!e.hitMatrix)))}static XRHitTestWithSelectEvent(e,t){let i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);let r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;t7.FromArrayToRef(t.transform.matrix,0,this._mat),t5.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),t5.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();let i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});EE.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}EE.Name=ah.HIT_TEST,EE.Version=1,au.AddWebXRFeature(EE.Name,(e,t)=>()=>new EE(e,t),EE.Version,!1);let ES=0;class EC extends ac{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new tj,this.onAnchorRemovedObservable=new tj,this.onAnchorUpdatedObservable=new tj,this._tmpVector=new t5,this._tmpQuaternion=new t8,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new t5,i=new t8){this._populateTmpTransformation(t,i);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{let t=await e.xrHitResult.createAnchor(r);return new Promise((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})})}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new t8,i=!1){this._populateTmpTransformation(e,t);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){let e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;let t=e.trackedAnchors;if(t){let i=this._trackedAnchors.filter(e=>!t.has(e.xrAnchor)).map(e=>this._trackedAnchors.indexOf(e)),r=0;i.forEach(e=>{let t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++}),t.forEach(t=>{if(this._lastFrameDetected.has(t)){let i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new t8,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){ss.Warn("Anchor could not be updated")}}else{let i={id:ES++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);let s=this._futureAnchors.filter(e=>e.nativeAnchor===t)[0];s&&(s.resolve(r),s.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then(e=>{t.nativeAnchor=e},e=>{t.resolved=!0,t.reject(e)}),t.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new EC(e,t),EC.Version);let Ey=0;class EA extends ac{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new tj,this.onPlaneRemovedObservable=new tj,this.onPlaneUpdatedObservable=new tj,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){let e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;let i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{let i={id:Ey++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}}),this._lastFrameDetected=i}}_init(){let e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){e();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(e=>{let t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new t5(e.x,e.y,e.z*t)});let r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new t7;t7.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new EA(e,t),EA.Version);class ER extends ac{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new tj}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){let t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper){if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){let i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){let i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{let i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(t=>t.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}}ER.Name=ah.BACKGROUND_REMOVER,ER.Version=1,au.AddWebXRFeature(ER.Name,(e,t)=>()=>new ER(e,t),ER.Version,!0);class EI extends ac{_createPhysicsImpostor(e){let t=this._options.physicsProperties.impostorType||ap.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=ul("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new t8;let s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);let n=new ap(r,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||ig.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce(t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce(()=>{let i=new ap(t.rootMesh,ap.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new t8,this._tmpVector=new t5,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{let t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)})}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._options.enableHeadsetImpostor){let e=this._options.headsetImpostorParams||{impostorType:ap.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=ul("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new t8,this._headsetMesh.isVisible=!1,this._headsetImpostor=new ap(this._headsetMesh,e.impostorType,Object.assign({mass:0},e))}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){let t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties=Object.assign(Object.assign({},this._options.physicsProperties),e)}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),null===(t=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===t?void 0:t.linearVelocity){let e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(null===(i=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===i?void 0:i.angularVelocity){let e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(e=>{var t,i;let r=this._controllers[e],s=r.xrController.grip||r.xrController.pointer,n=r.oldPos||r.impostorMesh.position;if(null===(t=r.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){let e=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(n,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);n.copyFrom(s.position),this._debugMode&&ig.Log([this._tmpVector,"linear"]);let a=r.oldRotation||r.impostorMesh.rotationQuaternion;if(null===(i=r.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){let e=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!a.equalsWithEpsilon(s.rotationQuaternion)){a.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);let e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{let t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(this._delta/1e3*e))}r.impostor.setAngularVelocity(this._tmpVector)}a.copyFrom(s.rotationQuaternion),this._debugMode&&ig.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){let t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}EI.Name=ah.PHYSICS_CONTROLLERS,EI.Version=1,au.AddWebXRFeature(EI.Name,(e,t)=>()=>new EI(e,t),EI.Version,!0);class EP extends ac{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new t7,this._tmpPos=new t5,this._tmpQuat=new t8,this._initHitTestSource=e=>{if(!e)return;let t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};if(this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),!i.space){ss.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(i).then(e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new tj,this.paused=!1,this.xrNativeFeatureName="hit-test",ss.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){let e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then(e=>{this._transientXrHitTestSource=e})}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){let t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach(e=>{this._processWebXRHitTestResult(e.results,e.inputSource)})}}_processWebXRHitTestResult(e,t){let i=[];e.forEach(e=>{let r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;let s=r.transform.position,n=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(n.x,n.y,n.z,n.w),t7.FromFloat32ArrayToRefScaled(r.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());let a={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(a)}),this.onHitTestResultObservable.notifyObservers(i)}}EP.Name=ah.HIT_TEST,EP.Version=2,au.AddWebXRFeature(EP.Name,(e,t)=>()=>new EP(e,t),EP.Version,!1);class EM extends ac{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new tj,this.onFeaturePointsUpdatedObservable=new tj,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;let t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw Error("Received malformed feature point cloud of length: "+t.length);let e=t.length/5,i=[],r=[];for(let s=0;s0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}EM.Name=ah.FEATURE_POINTS,EM.Version=1,au.AddWebXRFeature(EM.Name,e=>()=>new EM(e),EM.Version);let ED=0;class EO extends ac{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new tj,this.onMeshRemovedObservable=new tj,this.onMeshUpdatedObservable=new tj,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach(e=>{this.onMeshRemovedObservable.notifyObservers(e)}),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;let i=e.detectedMeshes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes);if(i){let t=new Set;this._detectedMeshes.forEach((e,r)=>{i.has(r)||t.add(r)}),t.forEach(e=>{let t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))}),i.forEach(t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{let i={id:ED++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}})}}catch(e){ig.Log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){var r;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;let s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let e=0;e()=>new EO(e,t),EO.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(tF||(tF={}));class EN extends ac{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new tj,this.onTrackableImageFoundObservable=new tj,this.onTrackedImageUpdatedObservable=new tj,this._trackableScoreStatus=tF.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach(e=>{e.originalBitmap.close()}),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};let e=this.options.images.map(e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src));try{let t=await Promise.all(e);return this._originalTrackingRequest=t.map((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch(e){return ss.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(e.getImageTrackingResults&&this._trackableScoreStatus!==tF.Waiting){if(this._trackableScoreStatus===tF.NotReceived){this._checkScoresAsync();return}for(let t of e.getImageTrackingResults()){let i=!1,r=t.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=t,s.realWorldWidth!==t.measuredWidthInMeters&&(s.realWorldWidth=t.measuredWidthInMeters,i=!0);let n=e.getPose(t.imageSpace,this._xrSessionManager.referenceSpace);if(n){let e=s.transformationMatrix;t7.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),i=!0}let a="emulated"===t.trackingState;s.emulated!==a&&(s.emulated=a,i=!0),i&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==tF.NotReceived)return;this._trackableScoreStatus=tF.Waiting;let e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||0===e.length){this._trackableScoreStatus=tF.NotReceived;return}for(let t=0;t0?tF.Received:tF.NotReceived}}EN.Name=ah.IMAGE_TRACKING,EN.Version=1,au.AddWebXRFeature(EN.Name,(e,t)=>()=>new EN(e,t),EN.Version,!1);class EF extends ac{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",ss.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!!super.attach()&&!!this._xrSessionManager.session.domOverlayState&&null!==this._xrSessionManager.session.domOverlayState.type&&(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0)}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return ss.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){let e=document.querySelector(this.options.element);if(null===e)return ss.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}EF.Name=ah.DOM_OVERLAY,EF.Version=1,au.AddWebXRFeature(EF.Name,(e,t)=>()=>new EF(e,t),EF.Version,!1);class Ew extends ac{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){var i,r,s,n,a,o;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new t8,this._tmpRotationMatrix=t7.Identity(),this._tmpTranslationDirection=new t5,this._tmpMovementTranslation=new t5,this._tempCacheQuaternion=new t8,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let i=()=>{if(e.motionController)for(let i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(let t of i.allowedComponentTypes){let i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){let t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness||null===r)continue;let s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add(e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add(()=>{r.changes.pressed&&i.buttonChangedhandler(r.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce(()=>{i()})}},!t||void 0===t.xrInput){ss.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=Ew.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(r=t.movementSpeed)&&void 0!==r?r:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(n=t.rotationEnabled)||void 0===n||n,rotationSpeed:null!==(a=t.rotationSpeed)&&void 0!==a?a:1,rotationThreshold:null!==(o=t.rotationThreshold)&&void 0!==o?o:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){let e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,t8.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(t8.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(t7.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),t5.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){let t=this._controllers[e];if(t){for(let e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}Ew.Name=ah.MOVEMENT,Ew.REGISTRATIONS={default:[{allowedComponentTypes:[_M.THUMBSTICK_TYPE,_M.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[_M.THUMBSTICK_TYPE,_M.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},Ew.Version=1,au.AddWebXRFeature(Ew.Name,(e,t)=>()=>new Ew(e,t),Ew.Version,!0);class EL extends ac{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=t5.Up().negateInPlace(),this._lightColor=io.White(),this._intensity=1,this._sphericalHarmonics=new u5,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new tj,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){let e=Date.now();if(e-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)}))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new d5("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new t5(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=sH.FALLOFF_GLTF),this._hdrFilter=new fV(this._xrSessionManager.scene.getEngine()),ss.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){let e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){var e;if(!super.attach())return!1;let t=null!==(e=this.options.reflectionFormat)&&void 0!==e?e:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=t,this._xrSessionManager.session.requestLightProbe({reflectionFormat:t}).then(e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(!this._reflectionCubeMap&&(this._reflectionCubeMap=new n3(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))}),!0}detach(){let e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){let e=Date.now();if(e-this._lightEstimationPollTime()=>new EL(e,t),EL.Version,!1);class EB extends ac{constructor(e){super(e),this.onEyeTrackingStartedObservable=new tj,this.onEyeTrackingEndedObservable=new tj,this.onEyeTrackingFrameUpdateObservable=new tj,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new as(t5.Zero(),t5.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){let t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z);let e=t.transform.orientation;ie.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?t5.RightHandedForwardReadOnly.rotateByQuaternionToRef(ie.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,ie.Quaternion[0].z*=-1,ie.Quaternion[0].w*=-1,t5.LeftHandedForwardReadOnly.rotateByQuaternionToRef(ie.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}EB.Name=ah.EYE_TRACKING,EB.Version=1,au.AddWebXRFeature(EB.Name,e=>()=>new EB(e),EB.Version,!1);class EU{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class EV{constructor(){this._samples=new EU(20),this._entropy=0,this.onFirstStepDetected=new tj}update(e,t,i,r){let s,n;this._samples.push(e,t);let a=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=t4.Distance(a,this._samples.at(1)),this._entropy>this._entropyThreshold)return;for(s=this._samePointCheckStartIdx;so&&(l=t,o=e);if(os*this._squaredProjectionDistanceThreshold)return;let p=ie.Vector3[0];p.set(i,r,0);let _=ie.Vector3[1];_.set(u.x,u.y,0);let f=t5.Cross(p,_).z>0,m=a.clone(),g=a.clone();h.subtractToRef(a,u),f?(u.scaleAndAddToRef(this._axisToApexShrinkFactor,m),u.scaleAndAddToRef(this._axisToApexExtendFactor,g)):(u.scaleAndAddToRef(this._axisToApexExtendFactor,m),u.scaleAndAddToRef(this._axisToApexShrinkFactor,g)),this.onFirstStepDetected.notifyObservers({leftApex:m,rightApex:g,currentPosition:a,currentStepDirection:f?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),!(this._axisLength<.03))}get _vitalityThreshold(){return .1}get forward(){return this._forward}}class EG{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new EV,this._walker=null,this._movement=new t4,this._millisecondsSinceLastUpdate=EG._MillisecondsPerUpdate,this.movementThisFrame=t5.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(e=>{this._walker||(this._walker=new Ek(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add(()=>{ig.Log("Footfall!")}),this._walker.onMovement.add(e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)}))})}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=EG._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=EG._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&!this._walker.update(e.x,e.z)&&(this._walker=null),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class Ez extends ac{static get Name(){return ah.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new t5,this._forward=new t5,this._position=new t5,this._movement=new t5,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&ig.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!!(this.isCompatible&&super.attach())&&(this._walker=new EG(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){let t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;let i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||t5.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}au.AddWebXRFeature(Ez.Name,(e,t)=>()=>new Ez(e,t),Ez.Version,!1);class EW extends hN{constructor(e,t,i,r,s,n){super(e,t,i,r,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=n}}class EH extends hF{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,r,s,n;let a=this._lastSubImages.get(t),o="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(r=e.colorTextureHeight)&&void 0!==r?r:e.textureHeight;if(!this._renderTargetTextures[o]||(null==a?void 0:a.textureWidth)!==l||(null==a?void 0:a.textureHeight)!==h){let t;let i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,r=null!==(n=e.depthStencilTextureHeight)&&void 0!==n?n:h;(l===i||h===r)&&(t=e.depthStencilTexture),this._renderTargetTextures[o]=this._createRenderTargetTexture(l,h,null,e.colorTexture,t,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:l,framebufferHeight:h}}return this._lastSubImages.set(t,e),this._renderTargetTextures[o]}_getSubImageForEye(e){let t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){let t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,r;let s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,n=null!==(r=t.colorTextureWidth)&&void 0!==r?r:t.textureHeight,a=t.viewport;e.x=a.x/s,e.y=a.y/n,e.width=a.width/s,e.height=a.height/n}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class EX extends EW{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,e=>new EY(e,i,this)),this.layer=e}}class EY extends EH{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){let t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}let Ej={},EK={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class E$ extends ac{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;let t=Object.assign({},EK),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return!!super.detach()&&(this._existingLayers.length=0,!0)}createXRWebGLLayer(e=Ej){return new hw(new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e))}createProjectionLayer(e=EK,t=!1){if(t&&"texture-array"!==e.textureType)throw Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");return new EX(this._xrWebGLBinding.createProjectionLayer(e),t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;let t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map(e=>e.layer),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}}E$.Name=ah.LAYERS,E$.Version=1,au.AddWebXRFeature(E$.Name,(e,t)=>()=>new E$(e,t),E$.Version,!1);class Eq extends ac{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){var e,t;if(!this._cachedWebGLTexture)return null;let i=this._xrSessionManager.scene.getEngine(),r=new rU(i,m.Unknown);return r.isCube=!1,r.invertY=!1,r._useSRGBBuffer=!1,r.format="ushort"===this.depthDataFormat?2:5,r.generateMipMaps=!1,r.type="ushort"===this.depthDataFormat?5:1,r.samplingMode=7,r.width=null!==(e=this.width)&&void 0!==e?e:0,r.height=null!==(t=this.height)&&void 0!==t?t:0,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new rX(this._cachedWebGLTexture,i._gl),r}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new tj,this.xrNativeFeatureName="depth-sensing",ss.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;null===(e=this._cachedDepthImageTexture)||void 0===e||e.dispose()}_onXRFrame(e){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(let t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:ss.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{data:s,width:n,height:a,rawValueToMeters:o,getDepthInMeters:l}=r;switch(this._width=n,this._height=a,this._rawValueToMeters=o,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=ae.CreateRTexture(null,n,a,this._xrSessionManager.scene,!1,!0,n6.NEAREST_SAMPLINGMODE,nC.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(e=>e*o));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(e=>e*o))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{texture:s,width:n,height:a}=r;this._width=n,this._height=a,this._cachedWebGLTexture=s;let o=this._xrSessionManager.scene,l=o.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=ae.CreateRTexture(null,n,a,o,!1,!0,n6.NEAREST_SAMPLINGMODE,"ushort"===i?nC.TEXTURETYPE_UNSIGNED_BYTE:nC.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){let e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise(i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map(e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),dataFormatPreference:this.options.dataFormatPreference.map(e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}})}}:{})})}}Eq.Name=ah.DEPTH_SENSING,Eq.Version=1,au.AddWebXRFeature(Eq.Name,(e,t)=>()=>new Eq(e,t),Eq.Version,!1);let EQ=`precision highp float; +#define CUSTOM_FRAGMENT_BEGIN +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; +#define CUSTOM_FRAGMENT_MAIN_END +}`;rO.ShadersStore.velocityPixelShader=EQ;let EZ=`#define CUSTOM_VERTEX_BEGIN +#define VELOCITY +attribute vec3 position; +#include +uniform mat4 viewProjection;uniform mat4 previousViewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; +#endif +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} +#elif +clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;rO.ShadersStore.velocityVertexShader=EZ;class EJ extends a5{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[t7.Identity(),t7.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new ug("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)}),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;let i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach(e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(e=>{e[0].material=e[1]})}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class E0{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){let t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw Error('For Space Warp, the base layer type should "XRProjectionLayer".');let i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw Error("Engine is disposed");let n=new EJ(r,s,this._scene,{width:e,height:t}),a=n.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=r,a._depthStencilTextureArray=s,n.disableRescaling(),n.renderListPredicate=()=>!0,n}_getRenderTargetForSubImage(e,t){let i=this._lastSubImages.get(t),r=this._renderTargetTextures.get(t.eye),s=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return r&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==n||(r=this._createRenderTargetTexture(s,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){let i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){let t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){let t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}}class E1 extends ac{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[ah.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new E0(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;let i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}E1.Name=ah.SPACE_WARP,E1.Version=1,au.AddWebXRFeature(E1.Name,e=>()=>new E1(e),E1.Version,!1);class E2 extends ac{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new tj,this.xrNativeFeatureName="camera-access"}attach(e){return!!super.attach(e)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)}detach(){return!!super.detach()&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach(e=>e.dispose()),this.texturesData.forEach(e=>e.dispose()),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){let i={width:e.camera.width,height:e.camera.height,x:0,y:0},r=e.projectionMatrix,s=(1-r[8])*i.width/2+i.x,n=(1-r[9])*i.height/2+i.y,a=i.width/2*r[0],o=i.height/2*r[5],l=i.width/2*r[4];this.cameraIntrinsics[t]={u0:s,v0:n,ax:a,ay:o,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var i,r;if(!e.camera)return!1;this.viewIndex[t]=e.eye;let s=null===(i=this._glBinding)||void 0===i?void 0:i.getCameraImage(e.camera);if(this._cachedInternalTextures[t])null===(r=this._cachedInternalTextures[t]._hardwareTexture)||void 0===r||r.set(s);else{let i=new rU(this._xrSessionManager.scene.getEngine(),m.Unknown,!0);i.isCube=!0,i.invertY=!1,i.format=5,i.generateMipMaps=!0,i.type=1,i.samplingMode=3,i.width=e.camera.width,i.height=e.camera.height,i._cachedWrapU=1,i._cachedWrapV=1,i._hardwareTexture=new rX(s,this._glContext),this._cachedInternalTextures[t]=i;let r=new n3(this._xrSessionManager.scene);r.name=`WebXR Raw Camera Access (${t})`,r._texture=this._cachedInternalTextures[t],this.texturesData[t]=r,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let r=!0;i.views.forEach((e,t)=>{r=r&&this._updateInternalTextures(e,t)}),r&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}E2.Name=ah.RAW_CAMERA_ACCESS,E2.Version=1,au.AddWebXRFeature(E2.Name,(e,t)=>()=>new E2(e,t),E2.Version,!1);class E3 extends _D{constructor(e,t,i){super(e,E4[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}_L.RegisterController("generic-hand-select-grasp",(e,t)=>new E3(t,e.gamepad,e.handedness));let E4={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class E5 extends _D{constructor(e,t,i){super(e,E6["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";return{filename:"left"===this.handedness?E5.MODEL_LEFT_FILENAME:E5.MODEL_RIGHT_FILENAME,path:E5.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){let e=a_.IsPluginForExtensionAvailable(".glb");return e||ig.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){let i=this._mapping.buttons[e],r=i.rootNodeName;if(!r){ig.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);return}let s=this._getChildByName(this.rootMesh,r);if(!s){ig.Warn("Missing button mesh with name: "+r);return}if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){let t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add(e=>{this._lerpTransform(i,e.value)},void 0,!0)}else ig.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(e=>{let t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach(i=>{if(!this.rootMesh)return;let r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);if(!s){ig.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add(e=>{let t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)},void 0,!0):ig.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){let t;this.rootMesh=new nX(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew E5(t,e.gamepad,e.handedness));let E6={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class E8 extends _D{constructor(e,t,i,r=!1,s=!1){super(e,E7[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return{filename:"left"===this.handedness?E8.MODEL_LEFT_FILENAME:E8.MODEL_RIGHT_FILENAME,path:this._isQuest()?E8.QUEST_MODEL_BASE_URL:E8.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){let t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach(e=>{let r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add(r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-(.2*r.value),this._modelRootNode.getChildren()[3].position.y=-(.005*r.value),this._modelRootNode.getChildren()[3].position.z=-(.005*r.value));return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new nX(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=t8.FromEulerAngles(0,Math.PI,0)),e.forEach(e=>{e.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}E8.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",E8.MODEL_LEFT_FILENAME="left.babylon",E8.MODEL_RIGHT_FILENAME="right.babylon",E8.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",_L.RegisterController("oculus-touch",(e,t)=>new E8(t,e.gamepad,e.handedness)),_L.RegisterController("oculus-touch-legacy",(e,t)=>new E8(t,e.gamepad,e.handedness,!0));let E7={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class E9 extends _D{constructor(e,t,i){super(e,Se[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:E9.MODEL_FILENAME,path:E9.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add(t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-(.15*t.value);return;case"xr-standard-touchpad":case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new nX(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=t8.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}E9.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",E9.MODEL_FILENAME="wand.babylon",_L.RegisterController("htc-vive",(e,t)=>new E9(t,e.gamepad,e.handedness));let Se={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class St{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>{var e;return null!==(e=this._nativeImpl._imageTrackingResults)&&void 0!==e?e:[]}}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;let i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];let r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw Error("This function is not available in Babylon Native")}}cA("NativeXRFrame",St),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(tw||(tw={}));class Si{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=sr(),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 Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName(),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){let i=new(ss.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class Sr{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Sr(e.typeName,e.defaultValue)}}let Ss=new Sr("any",void 0),Sn=new Sr("string",""),Sa=new Sr("number",0),So=new Sr("boolean",!1),Sl=new Sr("Vector2",t4.Zero()),Sh=new Sr("Vector3",t5.Zero()),Su=new Sr("Vector4",t6.Zero());new Sr("Matrix",t7.Identity());let Sc=new Sr("Color3",io.Black()),Sd=new Sr("Color4",new il(0,0,0,0)),Sp=new Sr("Quaternion",t8.Identity());class S_ extends Si{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return this.connectionType===tw.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===tw.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){let i=Si.Parse(e,t);return i.richType=Sr.Parse(e.richType),i}}function Sf(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function Sm(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function Sg(e,t,i){var r,s;let n=null!==(s=null===(r=null==t?void 0:t.getClassName)||void 0===r?void 0:r.call(t))&&void 0!==s?s:"";Sf(n)?i[e]={name:t.name,className:n}:Sm(n)?i[e]={value:t.asArray(),className:n}:i[e]=t}function Sv(e,t,i){let r=t[e],s=null==r?void 0:r.className;return Sf(s)?i.getMeshByName(r.name):Sm(s)?function(e,t){if("Vector2"===e)return t4.FromArray(t);if("Vector3"===e)return t5.FromArray(t);if("Vector4"===e)return t6.FromArray(t);if("Quaternion"===e)return t8.FromArray(t);if("Color3"===e)return new io(t[0],t[1],t[2]);if("Color4"===e)return new il(t[0],t[1],t[2],t[3]);throw Error(`Unknown vector class name ${e}`)}(s,r.value):r&&void 0!==r.value?r.value:r}t0.FGDataConnection=S_;class Sx{constructor(e){this.config=e,this.uniqueId=sr(),this.configure()}configure(){var e,t;this.name=null!==(t=null===(e=this.config)||void 0===e?void 0:e.name)&&void 0!==t?t:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){let i=new S_(e,tw.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){let i=new S_(e,tw.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find(t=>t.name===e)}getDataOutput(e){return this.dataOutputs.find(t=>t.name===e)}serialize(e={},t=Sg){for(let t of(e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName(),this.dataInputs)){let i={};t.serialize(i),e.dataInputs.push(i)}for(let t of this.dataOutputs){let i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){var i,r;let s=ss.Instantiate(e.className),n={},a=null!==(i=t.valueParseFunction)&&void 0!==i?i:Sv;if(e.config)for(let i in e.config)n[i]=a(i,e.config,t.scene);("FGSetPropertyBlock"===(r=e.className)||"FGGetPropertyBlock"===r||"FGPlayAnimationBlock"===r||"FGMeshPickEventBlock"===r)&&(n.pathConverter=t.pathConverter);let o=new s(n);o.uniqueId=e.uniqueId;for(let t=0;tt.name===e)}getSignalOutput(e){return this.signalOutputs.find(t=>t.name===e)}serialize(e={}){for(let t of(super.serialize(e),e.signalInputs=[],e.signalOutputs=[],this.signalInputs)){let i={};t.serialize(i),e.signalInputs.push(i)}for(let t of this.signalOutputs){let i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{var r,s,n;t.type===sS.POINTERPICK&&(null===(r=t.pickInfo)||void 0===r?void 0:r.pickedMesh)&&((null===(s=t.pickInfo)||void 0===s?void 0:s.pickedMesh)===i||Sy(null===(n=t.pickInfo)||void 0===n?void 0:n.pickedMesh,i))&&this._execute(e)});let r=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return SA.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}SA.ClassName="FGMeshPickEventBlock",t0[SA.ClassName]=SA,function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(tL||(tL={}));class SR{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=tL.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){let e=new SC({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==tL.Started)for(let e of(this.state=tL.Started,0===this._executionContexts.length&&this.createContext(),this._executionContexts))for(let t of this._getContextualOrder())t._startPendingTasks(e)}_getContextualOrder(){let e=[];for(let t of this._eventBlocks)if(t.getClassName()===SA.ClassName){let i=t._getReferencedMesh(),r=0;for(;r0;){let r=t.pop();for(let s of(e(r),r.dataInputs))for(let e of s._connectedPoint)i.has(e._ownerBlock.uniqueId)||(t.push(e._ownerBlock),i.add(e._ownerBlock.uniqueId));if(r instanceof Sb)for(let e of r.signalOutputs)for(let r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId))}}serialize(e={},t){for(let i of(e.allBlocks=[],this.visitAllBlocks(t=>{let i={};t.serialize(i),e.allBlocks.push(i)}),e.executionContexts=[],this._executionContexts)){let r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(let i of e)for(let e of i.dataOutputs)if(e.uniqueId===t)return e;throw Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(let i of e)if(i instanceof Sb){for(let e of i.signalInputs)if(e.uniqueId===t)return e}throw Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){var i;let r=t.coordinator.createGraph(),s=[],n=null!==(i=t.valueParseFunction)&&void 0!==i?i:Sv;for(let i of e.allBlocks){let e=Sx.Parse(i,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:n});s.push(e),e instanceof SS&&r.addEventBlock(e)}for(let e of s){for(let t of e.dataInputs)for(let e of t.connectedPointIds){let i=SR.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof Sb)for(let t of e.signalOutputs)for(let e of t.connectedPointIds){let i=SR.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(let t of e.executionContexts)SC.Parse(t,{graph:r,valueParseFunction:n});return r}}class SI{constructor(e){var t;this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add(()=>{this.dispose()}),(null!==(t=SI.SceneCoordinators.get(this.config.scene))&&void 0!==t?t:[]).push(this)}createGraph(){let e=new SR({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){let t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){var e;this._flowGraphs.forEach(e=>e.dispose()),this._flowGraphs.length=0;let t=null!==(e=SI.SceneCoordinators.get(this.config.scene))&&void 0!==e?e:[],i=t.indexOf(this);-1!==i&&t.splice(i,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{let r={};i.serialize(r,t),e._flowGraphs.push(r)})}static Parse(e,t){var i,r;let s=null!==(i=t.valueParseFunction)&&void 0!==i?i:Sv,n=new SI({scene:t.scene});return null===(r=e._flowGraphs)||void 0===r||r.forEach(e=>{SR.Parse(e,{coordinator:n,valueParseFunction:s,pathConverter:t.pathConverter})}),n}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new tj,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){let i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}SI.SceneCoordinators=new Map;class SP extends Sb{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class SM extends SP{constructor(e){super(e),this.message=this.registerDataInput("message",Ss)}_execute(e){let t=this.message.getValue(e);ig.Log(t),this.out._activateSignal(e)}getClassName(){return SM.ClassName}}SM.ClassName="FGConsoleLogBlock",t0[SM.ClassName]=SM;class SD extends SP{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Ss)}_execute(e){let t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return SD.ClassName}}SD.ClassName="FGSetVariableBlock",t0[SD.ClassName]=SD;let SO=new RegExp(/\{(\w+)\}/g);class SN{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=SO.exec(e);for(;i;){let[,r]=i;this.templatedInputs.push(t.registerDataInput(r,Sa)),i=SO.exec(e)}}getAccessor(e,t){let i=this.path;for(let e of this.templatedInputs){let r=e.getValue(t);i=i.replace(`{${e.name}}`,r.toString())}return e.convert(i)}}class SF extends SP{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Ss),this.templateComponent=new SN(e.path,this)}_execute(e){let t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return SF.ClassName}}SF.ClassName="FGSetPropertyBlock",t0.FGSetPropertyBlock=SF;class Sw extends SP{constructor(e){super(e),this.config=e}configure(){super.configure();for(let e=0;et.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return Sw.ClassName}}Sw.ClassName="FGSendCustomEventBlock",t0.FGSendCustomEventBlock=Sw;class SL extends Sb{constructor(e){super(e),this.condition=this.registerDataInput("condition",So),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}t0.FGBranchBlock=SL;class SB extends SP{constructor(e={startIndex:0}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",Sa),this.value=this.registerDataOutput("value",Sa)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{let t=this.value.getValue(e);tr?(this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s)):this.timeRemaining.setValue(r-(s-i),e)}getClassName(){return"FGThrottleBlock"}}t0.FGThrottleBlock=SV;class Sk extends SE{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",Sa)}_preparePendingTasks(e){let t=this.timeout.getValue(e);if(void 0!==t&&t>=0){let i=e._getExecutionVariable(this,"runningTimers")||[],r=new _X({timeout:t,contextObservable:e.configuration.scene.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){let i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):ss.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){for(let t of e._getExecutionVariable(this,"runningTimers")||[])t.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Sk.ClassName}}Sk.ClassName="FGTimerBlock",t0.FGTimerBlock=Sk;class SG extends Sb{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",Sa)}configure(){super.configure(),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)n=0;else if(n>=this.config.numberOutputFlows&&!this.config.loop)return;if(0===(s=s.filter(e=>e!==n)).length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(e=>e)){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}t0.FGDebounceBlock=SY;class Sj extends Sb{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",So)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}t0.FGFlipFlopBlock=Sj;class SK extends Sb{constructor(e){super(e),this.config=e}configure(){super.configure(),this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e));this.runningAnimatable.setValue(t,e),a.push(t)}e._setExecutionVariable(this,"runningAnimatables",a)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){var i;let r=null!==(i=t._getExecutionVariable(this,"runningAnimatables"))&&void 0!==i?i:[],s=r.indexOf(e);-1!==s&&r.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){var t;for(let i of null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[])i.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return S$.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}S$.ClassName="FGPlayAnimationBlock",t0[S$.ClassName]=S$;class Sq extends SP{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",Ss)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}t0.FGStopAnimationBlock=Sq;class SQ extends SP{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",Ss)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}t0.FGPauseAnimationBlock=SQ;class SZ extends Sx{constructor(e){super(e),this.condition=this.registerDataInput("condition",So),this.trueValue=this.registerDataInput("trueValue",Ss),this.falseValue=this.registerDataInput("falseValue",Ss),this.output=this.registerDataOutput("output",Ss)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}t0.FGConditionalDataBlock=SZ;class SJ extends Sx{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Ss)}_updateOutputs(e){let t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return SJ.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}SJ.ClassName="FGGetVariableBlock",t0[SJ.ClassName]=SJ;class S0 extends Sx{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",Ss),this.destinationSystem=this.registerDataInput("destinationSystem",Ss),this.inputCoordinates=this.registerDataInput("inputCoordinates",Sh),this.outputCoordinates=this.registerDataOutput("outputCoordinates",Sh)}_updateOutputs(e){let t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),n=i.getWorldMatrix(),a=ie.Matrix[0].copyFrom(n);a.invert();let o=ie.Matrix[1];a.multiplyToRef(s,o);let l=this.outputCoordinates.getValue(e);t5.TransformCoordinatesToRef(r,o,l)}getClassName(){return"FGCoordinateTransformBlock"}}t0.FGCoordinateTransformBlock=S0;class S1 extends Sx{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",function(e){switch(typeof e){case"string":return Sn;case"number":return Sa;case"boolean":return So;case"object":if(e instanceof t4)return Sl;if(e instanceof t5)return Sh;if(e instanceof t6)return Su;if(e instanceof io)return Sc;else if(e instanceof il)return Sd;else if(e instanceof t8)return Sp;else return Ss;default:return Ss}}(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=Sg){super.serialize(e),t("value",this.config.value,e.config)}}t0.FGConstantBlock=S1;class S2 extends Sx{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Ss),this.templateComponent=new SN(e.path,this)}_updateOutputs(e){let t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return S2.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}S2.ClassName="FGGetPropertyBlock",t0[S2.ClassName]=S2;let S3="cachedOperationValue",S4="cachedExecutionId";class S5 extends Sx{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){let t=e._getExecutionVariable(this,S4),i=e._getExecutionVariable(this,S3);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{let t=this._doOperation(e);e._setExecutionVariable(this,S3,t),e._setExecutionVariable(this,S4,e.executionId),this.value.setValue(t,e)}}}class S6 extends S5{constructor(e,t,i,r,s,n){super(i,n),this._operation=r,this._className=s,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 S8 extends S5{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.input=this.registerDataInput("input",e)}_doOperation(e){return this._operation(this.input.getValue(e))}getClassName(){return this._className}}let S7="FGBitwise",S9="AndBlock",Ce="OrBlock",Ct="XorBlock",Ci="NotBlock",Cr="LeftShiftBlock",Cs="RightShiftBlock",Cn="CountLeadingZerosBlock",Ca="CountTrailingZerosBlock";class Co extends S6{constructor(e){super(Sa,Sa,Sa,(e,t)=>e&t,`${S7}${S9}`,e)}}t0[`${S7}${S9}`]=Co;class Cl extends S6{constructor(e){super(Sa,Sa,Sa,(e,t)=>e|t,`${S7}${Ce}`,e)}}t0[`${S7}${Ce}`]=Cl;class Ch extends S6{constructor(e){super(Sa,Sa,Sa,(e,t)=>e^t,`${S7}${Ct}`,e)}}t0[`${S7}${Ct}`]=Ch;class Cu extends S8{constructor(e){super(Sa,Sa,e=>~e,`${S7}${Ci}`,e)}}t0[`${S7}${Ci}`]=Cu;class Cc extends S6{constructor(e){super(Sa,Sa,Sa,(e,t)=>e<e>>t,`${S7}${Cs}`,e)}}t0[`${S7}${Cs}`]=Cd;class Cp extends S8{constructor(e){super(Sa,Sa,e=>Math.clz32(e),`${S7}${Cn}`,e)}}t0[`${S7}${Cn}`]=Cp;class C_ extends S8{_ctrz(e){return 0==(e>>>=0)?32:31-Math.clz32(e&=-e)}constructor(e){super(Sa,Sa,e=>this._ctrz(e),`${S7}${Ca}`,e)}}t0[`${S7}${Ca}`]=C_;let Cf="FGLogic",Cm="AndBlock",Cg="OrBlock",Cv="NotBlock";class Cx extends S6{constructor(e){super(So,So,So,(e,t)=>e&&t,`${Cf}${Cm}`,e)}}t0[`${Cf}${Cm}`]=Cx;class CT extends S6{constructor(e){super(So,So,So,(e,t)=>e||t,`${Cf}${Cg}`,e)}}t0[`${Cf}${Cg}`]=CT;class Cb extends S8{constructor(e){super(So,So,e=>!e,`${Cf}${Cv}`,e)}}t0[`${Cf}${Cv}`]=Cb;class CE extends S5{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class CS extends S5{constructor(e,t,i,r,s,n,a){super(r,a),this._operation=s,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function CC(e){return e.getClassName?e.getClassName():""}function Cy(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}class CA extends S6{constructor(e){super(Ss,Ss,Ss,(e,t)=>this._polymorphicAdd(e,t),CA.ClassName,e)}_polymorphicAdd(e,t){return Cy(CC(e),CC(t))?e.add(t):e+t}getClassName(){return CA.ClassName}}CA.ClassName="FGAddBlock",t0[CA.ClassName]=CA;class CR extends S6{constructor(e){super(Ss,Ss,Ss,(e,t)=>this._polymorphicAdd(e,t),CR.ClassName,e)}_polymorphicAdd(e,t){return Cy(CC(e),CC(t))?e.subtract(t):e-t}getClassName(){return CR.ClassName}}CR.ClassName="FGSubBlock",t0[CR.ClassName]=CR;class CI extends S6{constructor(e){super(Ss,Ss,Ss,(e,t)=>this._polymorphicMultiply(e,t),CI.ClassName,e)}_polymorphicMultiply(e,t){return Cy(CC(e),CC(t))?e.multiply(t):e*t}}CI.ClassName="FGMultiplyBlock",t0[CI.ClassName]=CI;class CP extends S6{constructor(e){super(Ss,Ss,Ss,(e,t)=>this._polymorphicDivide(e,t),CP.ClassName,e)}_polymorphicDivide(e,t){return Cy(CC(e),CC(t))?e.divide(t):e/t}}CP.ClassName="FGDivideBlock",t0[CP.ClassName]=CP;class CM extends CE{constructor(e){super(Sa,()=>Math.random(),CM.ClassName,e)}}CM.ClassName="FGRandomBlock",t0[CM.ClassName]=CM;class CD extends S6{constructor(e){super(Ss,Ss,Sa,(e,t)=>this._polymorphicDot(e,t),CD.ClassName,e)}_polymorphicDot(e,t){switch(CC(e)){case"Vector2":return t4.Dot(e,t);case"Vector3":return t5.Dot(e,t);case"Vector4":return t6.Dot(e,t);default:throw Error(`Cannot get dot product of ${e} and ${t}`)}}}CD.ClassName="FGDotBlock",t0[CD.ClassName]=CD;class CO extends CE{constructor(e){super(Sa,()=>Math.E,CO.ClassName,e)}}CO.ClassName="FGEBlock",t0[CO.ClassName]=CO;class CN extends CE{constructor(e){super(Sa,()=>Math.PI,CN.ClassName,e)}}CN.ClassName="FGPIBlock",t0[CN.ClassName]=CN;class CF extends CE{constructor(e){super(Sa,()=>Number.POSITIVE_INFINITY,CF.ClassName,e)}}CF.ClassName="FGInfBlock",t0[CF.ClassName]=CF;class Cw extends CE{constructor(e){super(Sa,()=>Number.NaN,Cw.ClassName,e)}}function CL(e,t){switch(CC(e)){case"Vector2":return new t4(t(e.x),t(e.y));case"Vector3":return new t5(t(e.x),t(e.y),t(e.z));case"Vector4":return new t6(t(e.x),t(e.y),t(e.z),t(e.w));default:return t(e)}}Cw.ClassName="FGNaNBlock",t0[Cw.ClassName]=Cw;class CB extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicAbs(e),CB.ClassName,e)}_polymorphicAbs(e){return CL(e,Math.abs)}}CB.ClassName="FGAbsBlock",t0[CB.ClassName]=CB;class CU extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicSign(e),CU.ClassName,e)}_polymorphicSign(e){return CL(e,Math.sign)}}CU.ClassName="FGSignBlock",t0[CU.ClassName]=CU;class CV extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicTrunc(e),CV.ClassName,e)}_polymorphicTrunc(e){return CL(e,Math.trunc)}}CV.ClassName="FGTruncBlock",t0[CV.ClassName]=CV;class Ck extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicFloor(e),Ck.ClassName,e)}_polymorphicFloor(e){return CL(e,Math.floor)}}Ck.ClassName="FGFloorBlock",t0[Ck.ClassName]=Ck;class CG extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicCeiling(e),CG.ClassName,e)}_polymorphicCeiling(e){return CL(e,Math.ceil)}}CG.ClassName="FGCeilBlock",t0[CG.ClassName]=CG;class Cz extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicFract(e),Cz.ClassName,e)}_polymorphicFract(e){return CL(e,e=>e-Math.floor(e))}}Cz.ClassName="FGFractBlock",t0[Cz.ClassName]=Cz;class CW extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicNeg(e),CW.ClassName,e)}_polymorphicNeg(e){return CL(e,e=>-e)}}function CH(e,t,i){switch(CC(e)){case"Vector2":return new t4(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new t5(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new t6(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));default:return i(e,t)}}CW.ClassName="FGNegBlock",t0[CW.ClassName]=CW;class CX extends S6{constructor(e){super(Ss,Ss,Ss,(e,t)=>this._polymorphicRemainder(e,t),CX.ClassName,e)}_polymorphicRemainder(e,t){return CH(e,t,(e,t)=>e%t)}}CX.ClassName="FGRemainderBlock",t0[CX.ClassName]=CX;class CY extends S6{constructor(e){super(Ss,Ss,Ss,(e,t)=>this._polymorphicMin(e,t),CY.ClassName,e)}_polymorphicMin(e,t){return CH(e,t,Math.min)}}CY.ClassName="FGMinBlock",t0[CY.ClassName]=CY;class Cj extends S6{constructor(e){super(Ss,Ss,Ss,(e,t)=>this._polymorphicMax(e,t),Cj.ClassName,e)}_polymorphicMax(e,t){return CH(e,t,Math.max)}}function CK(e,t,i){return Math.min(Math.max(e,t),i)}function C$(e,t,i,r){switch(CC(e)){case"Vector2":return new t4(r(e.x,t.x,i.x),r(e.y,t.y,i.y));case"Vector3":return new t5(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z));case"Vector4":return new t6(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z),r(e.w,t.w,i.w));default:return r(e,t,i)}}Cj.ClassName="FGMaxBlock",t0[Cj.ClassName]=Cj;class Cq extends CS{constructor(e){super(Ss,Ss,Ss,Ss,(e,t,i)=>this._polymorphicClamp(e,t,i),Cq.ClassName,e)}_polymorphicClamp(e,t,i){return C$(e,t,i,CK)}}Cq.ClassName="FGClampBlock",t0[Cq.ClassName]=Cq;class CQ extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicSaturate(e),CQ.ClassName,e)}_polymorphicSaturate(e){return CL(e,e=>CK(e,0,1))}}CQ.ClassName="FGSaturateBlock",t0[CQ.ClassName]=CQ;class CZ extends CS{constructor(e){super(Ss,Ss,Ss,Ss,(e,t,i)=>this._polymorphicInterpolate(e,t,i),CZ.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return C$(e,t,i,this._interpolate)}}CZ.ClassName="FGInterpolateBlock",t0[CZ.ClassName]=CZ;class CJ extends S6{constructor(e){super(Ss,Ss,So,(e,t)=>this._polymorphicEq(e,t),CJ.ClassName,e)}_polymorphicEq(e,t){return Cy(CC(e),CC(t))?e.equals(t):e===t}}CJ.ClassName="FGEqBlock",t0[CJ.ClassName]=CJ;class C0 extends S6{constructor(e){super(Ss,Ss,So,(e,t)=>this._polymorphicLessThan(e,t),C0.ClassName,e)}_polymorphicLessThan(e,t){switch(CC(e)){case"Vector2":return e.xthis._polymorphicLessThanOrEqual(e,t),C1.ClassName,e)}_polymorphicLessThanOrEqual(e,t){switch(CC(e)){case"Vector2":return e.x<=t.x&&e.y<=t.y;case"Vector3":return e.x<=t.x&&e.y<=t.y&&e.z<=t.z;case"Vector4":return e.x<=t.x&&e.y<=t.y&&e.z<=t.z&&e.w<=t.w;default:return e<=t}}}C1.ClassName="FGLessThanOrEqualBlock";class C2 extends S6{constructor(e){super(Ss,Ss,So,(e,t)=>this._polymorphicGreaterThan(e,t),C2.ClassName,e)}_polymorphicGreaterThan(e,t){switch(CC(e)){case"Vector2":return e.x>t.x&&e.y>t.y;case"Vector3":return e.x>t.x&&e.y>t.y&&e.z>t.z;case"Vector4":return e.x>t.x&&e.y>t.y&&e.z>t.z&&e.w>t.w;default:return e>t}}}C2.ClassName="FGGreaterThanBlock",t0[C2.ClassName]=C2;class C3 extends S6{constructor(e){super(Ss,Ss,So,(e,t)=>this._polymorphicGreaterThanOrEqual(e,t),C3.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){switch(CC(e)){case"Vector2":return e.x>=t.x&&e.y>=t.y;case"Vector3":return e.x>=t.x&&e.y>=t.y&&e.z>=t.z;case"Vector4":return e.x>=t.x&&e.y>=t.y&&e.z>=t.z&&e.w>=t.w;default:return e>=t}}}C3.ClassName="FGGreaterThanOrEqualBlock",t0[C3.ClassName]=C3;class C4 extends S8{constructor(e){super(Ss,So,e=>this._polymorphicIsNan(e),C4.ClassName,e)}_polymorphicIsNan(e){switch(CC(e)){case"Vector2":return isNaN(e.x)||isNaN(e.y);case"Vector3":return isNaN(e.x)||isNaN(e.y)||isNaN(e.z);case"Vector4":return isNaN(e.x)||isNaN(e.y)||isNaN(e.z)||isNaN(e.w);default:return isNaN(e)}}}C4.ClassName="FGIsNanBlock",t0[C4.ClassName]=C4;class C5 extends S8{constructor(e){super(Ss,So,e=>this._polymorphicIsInf(e),C5.ClassName,e)}_polymorphicIsInf(e){switch(CC(e)){case"Vector2":return!isFinite(e.x)||!isFinite(e.y);case"Vector3":return!isFinite(e.x)||!isFinite(e.y)||!isFinite(e.z);case"Vector4":return!isFinite(e.x)||!isFinite(e.y)||!isFinite(e.z)||!isFinite(e.w);default:return!isFinite(e)}}}C5.ClassName="FGIsInfBlock";class C6 extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicDegToRad(e),C6.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return CL(e,this._degToRad)}}C6.ClassName="FGDegToRadBlock",t0[C6.ClassName]=C6;class C8 extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicRadToDeg(e),C8.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return CL(e,this._radToDeg)}}C8.ClassName="FGRadToDegBlock",t0[C8.ClassName]=C8;class C7 extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicSin(e),C7.ClassName,e)}_polymorphicSin(e){return CL(e,Math.sin)}}C7.ClassName="FGSinBlock",t0[C7.ClassName]=C7;class C9 extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicCos(e),C9.ClassName,e)}_polymorphicCos(e){return CL(e,Math.cos)}}C9.ClassName="FGCosBlock",t0[C9.ClassName]=C9;class ye extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicTan(e),ye.ClassName,e)}_polymorphicTan(e){return CL(e,Math.tan)}}ye.ClassName="FGTanBlock",t0[ye.ClassName]=ye;class yt extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicAsin(e),yt.ClassName,e)}_polymorphicAsin(e){return CL(e,Math.asin)}}yt.ClassName="FGAsinBlock",t0[yt.ClassName]=yt;class yi extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicAcos(e),yi.ClassName,e)}_polymorphicAcos(e){return CL(e,Math.acos)}}yi.ClassName="FGAcosBlock",t0[yi.ClassName]=yi;class yr extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicAtan(e),yr.ClassName,e)}_polymorphicAtan(e){return CL(e,Math.atan)}}yr.ClassName="FGAtanBlock",t0[yr.ClassName]=yr;class ys extends S6{constructor(e){super(Ss,Ss,Ss,(e,t)=>this._polymorphicAtan2(e,t),ys.ClassName,e)}_polymorphicAtan2(e,t){return CH(e,t,Math.atan2)}}ys.ClassName="FGAtan2Block",t0[ys.ClassName]=ys;class yn extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicSinh(e),yn.ClassName,e)}_polymorphicSinh(e){return CL(e,Math.sinh)}}yn.ClassName="FGSinhBlock",t0[yn.ClassName]=yn;class ya extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicCosh(e),ya.ClassName,e)}_polymorphicCosh(e){return CL(e,Math.cosh)}}ya.ClassName="FGCoshBlock",t0[ya.ClassName]=ya;class yo extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicTanh(e),yo.ClassName,e)}_polymorphicTanh(e){return CL(e,Math.tanh)}}yo.ClassName="FGTanhBlock",t0[yo.ClassName]=yo;class yl extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicAsinh(e),yl.ClassName,e)}_polymorphicAsinh(e){return CL(e,Math.asinh)}}yl.ClassName="FGAsinhBlock",t0[yl.ClassName]=yl;class yh extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicAcosh(e),yh.ClassName,e)}_polymorphicAcosh(e){return CL(e,Math.acosh)}}yh.ClassName="FGAcoshBlock",t0[yh.ClassName]=yh;class yu extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicAtanh(e),yu.ClassName,e)}_polymorphicAtanh(e){return CL(e,Math.atanh)}}yu.ClassName="FGAtanhBlock",t0[yu.ClassName]=yu;class yc extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicExp(e),yc.ClassName,e)}_polymorphicExp(e){return CL(e,Math.exp)}}yc.ClassName="FGExpBlock",t0[yc.ClassName]=yc;class yd extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicLog(e),yd.ClassName,e)}_polymorphicLog(e){return CL(e,Math.log)}}yd.ClassName="FGLogBlock",t0[yd.ClassName]=yd;class yp extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicLog2(e),yp.ClassName,e)}_polymorphicLog2(e){return CL(e,Math.log2)}}yp.ClassName="FGLog2Block",t0[yp.ClassName]=yp;class y_ extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicLog10(e),y_.ClassName,e)}_polymorphicLog10(e){return CL(e,Math.log10)}}y_.ClassName="FGLog10Block",t0[y_.ClassName]=y_;class yf extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicSqrt(e),yf.ClassName,e)}_polymorphicSqrt(e){return CL(e,Math.sqrt)}}yf.ClassName="FGSqrtBlock",t0[yf.ClassName]=yf;class ym extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicCubeRoot(e),ym.ClassName,e)}_polymorphicCubeRoot(e){return CL(e,Math.cbrt)}}ym.ClassName="FGCubeRootBlock",t0[ym.ClassName]=ym;class yg extends S6{constructor(e){super(Ss,Sa,Sa,(e,t)=>this._polymorphicPow(e,t),yg.ClassName,e)}_polymorphicPow(e,t){return CH(e,t,Math.pow)}}yg.ClassName="FGPowBlock",t0[yg.ClassName]=yg;class yv extends S8{constructor(e){super(Ss,Sa,e=>this._polymorphicLength(e),yv.ClassName,e)}_polymorphicLength(e){switch(CC(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw Error(`Cannot compute length of value ${e}`)}}}yv.ClassName="FGLengthBlock",t0[yv.ClassName]=yv;class yx extends S8{constructor(e){super(Ss,Ss,e=>this._polymorphicNormalize(e),yx.ClassName,e)}_polymorphicNormalize(e){switch(CC(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw Error(`Cannot normalize value ${e}`)}}}yx.ClassName="FGNormalizeBlock",t0[yx.ClassName]=yx;class yT extends S6{constructor(e){super(Sh,Sh,Sh,(e,t)=>t5.Cross(e,t),yT.ClassName,e)}}yT.ClassName="FGCrossBlock",t0[yT.ClassName]=yT;class yb extends S6{constructor(e){super(Sl,Sa,Sl,(e,t)=>t4.Transform(e,t7.RotationZ(t)),yb.ClassName,e)}}yb.ClassName="FGRotate2DBlock",t0[yb.ClassName]=yb;class yE extends CS{constructor(e){super(Sh,Sh,Sa,Sh,(e,t,i)=>t5.TransformCoordinates(e,t7.RotationAxis(t,i)),yE.ClassName,e)}}yE.ClassName="FGRotate3DBlock",t0[yE.ClassName]=yE;class yS extends SS{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){let t=e.configuration.scene.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return yS.ClassName}}yS.ClassName="FGSceneReadyEventBlock",t0.FGSceneReadyEventBlock=yS;class yC extends SS{constructor(e){super(e),this.config=e}configure(){super.configure();for(let e=0;e{for(let i=0;i{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return yy.ClassName}}yy.ClassName="FGSceneTickEventBlock",t0[yy.ClassName]=yy;let yA=[];class yR{static generateFrame(){if(!a)return;let e=performance.now(),t=yI();if((a.width!=t.width||a.height!=t.height)&&this.resizeFrame(t.width,t.height),c!=t.seed){var i,r;r=Math.imul((r=i=function(e){var t,i=0;for(t=0;t>>15,1|r),d=(((r^=r+Math.imul(r^r>>>7,61|r))^r>>>14)>>>0)/4294967296,c=t.seed,console.log(1)}u.onApply=e=>{e.setFloat("seed",d+5),e.setFloat("density",t.density/100),e.setFloat("brightness",t.brightness/100)};for(let e=0;e{i.setFloat("seed",1e3*d*(e+1)),i.setFloat4("color",t[`color${e+1}`].r/255,t[`color${e+1}`].g/255,t[`color${e+1}`].b/255,1),i.setUInt("nebulascale",t.scale),i.setUInt("depth",t.depth),i.setFloat("intensity",t.intensity/100-1),i.setFloat("falloff",t.falloff),i.setFloat("persistence",t.persistence)},yA[e].onApplyObservable.add(t=>{t.setTextureSampler("textureSamplerSampler",yA[e].inputTexture.texture)});l.onAfterRenderObservable.addOnce(()=>{console.log(`Rendered in ${Math.round((performance.now()-e)*100)/100}ms`)}),o.beginFrame(),l.render(),o.endFrame()}static resizeFrame(e,t){a.style.width=e.toString()+"px",a.style.height=t.toString()+"px",o.resize()}static async exportFrame(){let e=yI();ss.CreateScreenshotUsingRenderTarget(o,h,{width:a.width,height:a.height},void 0,void 0,void 0,void 0,`nebula-${e.seed}`),this.generateFrame()}static setTransparency(e){e?l.clearColor=new il(0,0,0,0):l.clearColor=new il(0,0,0,1)}static initialize(e,t,i,r){a=e,o=t,l=i,u=new aL("StarShader","stars",null,null,1,h=r,void 0,o,!0,void 0,void 0,void 0,void 0,void 0,void 0,f.WGSL),h.attachPostProcess(u);for(let e=0;e<10;e++)yA.push(new aL("NebulaShader","nebulas",null,null,1,h,void 0,o,!0,void 0,void 0,void 0,void 0,void 0,void 0,f.WGSL))}}function yI(){return p.exportPreset()}let yP=tk()(async()=>{},{loadableGenerated:{modules:["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx -> ./BabylonScene"]},ssr:!1});function yM(){let[e,t]=(0,tU.useState)(!1);return(0,tU.useEffect)(()=>{t(!0),function(){p=new tz.Pane({title:"Parameters",container:document.getElementById("TweakPane")||void 0});let e={width:window.innerWidth,height:window.innerHeight,transparent:!1,autoupdate:!1},t=p.addFolder({title:"Canvas",expanded:!0});t.addInput(e,"width",{min:100,max:7680,step:1}),t.addInput(e,"height",{min:100,max:4320,step:1}),t.addInput(e,"transparent").on("change",()=>{console.log(1),yR.setTransparency(e.transparent)});let i={density:1.5,brightness:100},r=p.addFolder({title:"Stars",expanded:!0});r.addInput(i,"density",{min:0,max:10,step:.01,format:e=>e.toFixed(2)+"%"}),r.addInput(i,"brightness",{min:0,max:200,step:.1,format:e=>e.toFixed(1)+"%"});let s={count:2,scale:5,depth:2,intensity:100,falloff:2,persistence:.5},n=p.addFolder({title:"Nebula",expanded:!0});n.addInput(s,"count",{min:0,max:3,step:1}).on("change",()=>{if(0==s.count)o.hidden=!0;else{o.hidden=!1;for(let e=0;es.count-1&&(l[e].hidden=!0);n.addInput(s,"scale",{min:1,max:50,step:1}),n.addInput(s,"depth",{min:0,max:20,step:1}),n.addInput(s,"intensity",{min:50,max:150,step:1,format:e=>e+"%"}),n.addInput(s,"falloff",{min:1,max:10,step:.1}),n.addInput(s,"persistence",{min:0,max:1,step:.01});let h={seed:""+Math.floor(1e12*Math.random())},u=p.addFolder({title:"Seed",expanded:!1});u.addInput(h,"seed",{format:e=>e.toFixed(0)}),u.addButton({title:"Randomize seed"}).on("click",()=>{h.seed=Math.floor(1e12*Math.random()).toString(),p.refresh(),yR.generateFrame()}),p.addSeparator(),p.addButton({title:"Render"}).on("click",()=>{yR.generateFrame()}),p.addButton({title:"Render Random"}).on("click",()=>{h.seed=Math.floor(1e12*Math.random()).toString();for(let e=0;e<3;e++)a["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())};p.refresh(),yR.generateFrame()}),p.addSeparator(),p.addButton({title:"Save Image"}).on("click",()=>{yR.exportFrame()}),p.addSeparator(),p.addInput(e,"autoupdate"),p.on("change",t=>{let i=t.presetKey;e.autoupdate&&(("width"==i||"height"==i)&&yR.resizeFrame(e.width,e.height),yR.generateFrame())})}()},[]),(0,tB.jsxs)("main",{children:[tB.jsx("div",{id:"TweakPane",className:"fixed top-2.5 right-2.5"}),e&&tB.jsx(yP,{}),!e&&tB.jsx(tG,{})]})}},2295:(e,t,i)=>{"use strict";e.exports=i(6372).vendored["react-ssr"].ReactJsxRuntime},3267:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let r=i(9694);i(3729);let s=r._(i(546));function n(e){return{default:(null==e?void 0:e.default)||e}}function a(e,t){let i=s.default,r={loading:e=>{let{error:t,isLoading:i,pastDelay:r}=e;return null}};"function"==typeof e&&(r.loader=e),Object.assign(r,t);let a=r.loader;return i({...r,loader:()=>null!=a?a().then(n):Promise.resolve(n(()=>null))})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1868:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NoSSR",{enumerable:!0,get:function(){return s}});let r=i(1462);function s(e){let{children:t}=e;return(0,r.throwWithNoSSR)(),t}},546:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}});let r=i(9694)._(i(3729)),s=i(1868),n=function(e){let t=Object.assign({loader:null,loading:null,ssr:!0},e);function i(e){let i=t.loading,n=r.default.createElement(i,{isLoading:!0,pastDelay:!0,error:null}),a=t.ssr?r.default.Fragment:s.NoSSR,o=t.lazy;return r.default.createElement(r.default.Suspense,{fallback:n},r.default.createElement(a,null,r.default.createElement(o,e)))}return t.lazy=r.default.lazy(t.loader),i.displayName="LoadableComponent",i}},9652:function(e,t){/*! Tweakpane 3.1.10 (c) 2016 cocopon, licensed under the MIT license. */(function(e){"use strict";class t{constructor(e){let[t,i]=e.split("-"),r=t.split(".");this.major=parseInt(r[0],10),this.minor=parseInt(r[1],10),this.patch=parseInt(r[2],10),this.prerelease=null!=i?i:null}toString(){let e=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[e,this.prerelease].join("-"):e}}class i{constructor(e){this.controller_=e}get element(){return this.controller_.view.element}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(e){this.controller_.viewProps.set("disabled",e)}get hidden(){return this.controller_.viewProps.get("hidden")}set hidden(e){this.controller_.viewProps.set("hidden",e)}dispose(){this.controller_.viewProps.set("disposed",!0)}}class r{constructor(e){this.target=e}}class s extends r{constructor(e,t,i,r){super(e),this.value=t,this.presetKey=i,this.last=null==r||r}}class n extends r{constructor(e,t,i){super(e),this.value=t,this.presetKey=i}}class a extends r{constructor(e,t){super(e),this.expanded=t}}class o extends r{constructor(e,t){super(e),this.index=t}}function l(e){return null==e}function h(e,t){if(e.length!==t.length)return!1;for(let i=0;i"View has been already disposed",invalidparams:e=>`Invalid parameters for '${e.name}'`,nomatchingcontroller:e=>`No matching controller for '${e.key}'`,nomatchingview:e=>`No matching view for '${JSON.stringify(e.params)}'`,notbindable:()=>"Value is not bindable",propertynotfound:e=>`Property '${e.name}' not found`,shouldneverhappen:()=>"This error should never happen"};class d{static alreadyDisposed(){return new d({type:"alreadydisposed"})}static notBindable(){return new d({type:"notbindable"})}static propertyNotFound(e){return new d({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new d({type:"shouldneverhappen"})}constructor(e){var t;this.message=null!==(t=c[e.type](e.context))&&void 0!==t?t:"Unexpected error",this.name=this.constructor.name,this.stack=Error(this.message).stack,this.type=e.type}}class p{constructor(e,t,i){this.obj_=e,this.key_=t,this.presetKey_=null!=i?i:t}static isBindable(e){return null!==e&&("object"==typeof e||"function"==typeof e)}get key(){return this.key_}get presetKey(){return this.presetKey_}read(){return this.obj_[this.key_]}write(e){this.obj_[this.key_]=e}writeProperty(e,t){let i=this.read();if(!p.isBindable(i))throw d.notBindable();if(!(e in i))throw d.propertyNotFound(e);i[e]=t}}class _ extends i{get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get title(){var e;return null!==(e=this.controller_.valueController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.valueController.props.set("title",e)}on(e,t){let i=t.bind(this);return this.controller_.valueController.emitter.on(e,()=>{i(new r(this))}),this}}class f{constructor(){this.observers_={}}on(e,t){let i=this.observers_[e];return i||(i=this.observers_[e]=[]),i.push({handler:t}),this}off(e,t){let i=this.observers_[e];return i&&(this.observers_[e]=i.filter(e=>e.handler!==t)),this}emit(e,t){let i=this.observers_[e];i&&i.forEach(e=>{e.handler(t)})}}function m(e){return(t,i)=>["tp","-",e,"v",t?`_${t}`:"",i?`-${i}`:""].join("")}function g(e,t){e.emitter.on("change",e=>t(e.rawValue)),t(e.rawValue)}function v(e,t,i){g(e.value(t),i)}function x(e,t){return i=>{i?e.classList.add(t):e.classList.remove(t)}}function T(e,t){g(e,e=>{t.textContent=null!=e?e:""})}let b=m("btn");class E{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(b()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("button");i.classList.add(b("b")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let r=e.createElement("div");r.classList.add(b("t")),T(t.props.value("title"),r),this.buttonElement.appendChild(r)}}class S{constructor(e,t){this.emitter=new f,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new E(e,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}}class C{constructor(e,t){var i;this.constraint_=null==t?void 0:t.constraint,this.equals_=null!==(i=null==t?void 0:t.equals)&&void 0!==i?i:(e,t)=>e===t,this.emitter=new f,this.rawValue_=e}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let i=null!=t?t:{forceEmit:!1,last:!0},r=this.constraint_?this.constraint_.constrain(e):e,s=this.rawValue_;(!this.equals_(s,r)||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=r,this.emitter.emit("change",{options:i,previousRawValue:s,rawValue:r,sender:this}))}}class y{constructor(e){this.emitter=new f,this.value_=e}get rawValue(){return this.value_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let i=null!=t?t:{forceEmit:!1,last:!0},r=this.value_;(r!==e||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=e,this.emitter.emit("change",{options:i,previousRawValue:r,rawValue:this.value_,sender:this}))}}function A(e,t){let i=null==t?void 0:t.constraint,r=null==t?void 0:t.equals;return i||r?new C(e,t):new y(e)}class R{constructor(e){for(let t in this.emitter=new f,this.valMap_=e,this.valMap_)this.valMap_[t].emitter.on("change",()=>{this.emitter.emit("change",{key:t,sender:this})})}static createCore(e){return Object.keys(e).reduce((t,i)=>Object.assign(t,{[i]:A(e[i])}),{})}static fromObject(e){return new R(this.createCore(e))}get(e){return this.valMap_[e].rawValue}set(e,t){this.valMap_[e].rawValue=t}value(e){return this.valMap_[e]}}function I(e){return t=>i=>{if(!t&&void 0===i)return{succeeded:!1,value:void 0};if(t&&void 0===i)return{succeeded:!0,value:void 0};let r=e(i);return void 0!==r?{succeeded:!0,value:r}:{succeeded:!1,value:void 0}}}function P(e){return{custom:t=>I(t)(e),boolean:I(e=>"boolean"==typeof e?e:void 0)(e),number:I(e=>"number"==typeof e?e:void 0)(e),string:I(e=>"string"==typeof e?e:void 0)(e),function:I(e=>"function"==typeof e?e:void 0)(e),constant:t=>I(e=>e===t?t:void 0)(e),raw:I(e=>e)(e),object:t=>I(e=>{if(null!==e&&"object"==typeof e)return Object.keys(t).reduce((i,r)=>{if(void 0===i)return;let s=(0,t[r])(e[r]);return s.succeeded?Object.assign(Object.assign({},i),{[r]:s.value}):void 0},{})})(e),array:t=>I(e=>{if(Array.isArray(e))return e.reduce((e,i)=>{if(void 0===e)return;let r=t(i);if(r.succeeded&&void 0!==r.value)return[...e,r.value]},[])})(e)}}let M={optional:P(!0),required:P(!1)};function D(e,t){let i=M.required.object(t)(e);return i.succeeded?i.value:void 0}function O(e){console.warn(`Missing '${e.key}' of ${e.target} in ${e.place}. Please rebuild plugins with the latest core package.`)}class N{constructor(e){this.value_=e}static create(e){return[new N(e),(t,i)=>{e.setRawValue(t,i)}]}get emitter(){return this.value_.emitter}get rawValue(){return this.value_.rawValue}}let F=m("");function w(e,t){return x(e,F(void 0,t))}class L extends R{constructor(e){var t;super(e),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=N.create(A(this.getGlobalDisabled_())),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var t,i,r;let s=null!=e?e:{};return new L(R.createCore({disabled:null!==(t=s.disabled)&&void 0!==t&&t,disposed:!1,hidden:null!==(i=s.hidden)&&void 0!==i&&i,parent:null!==(r=s.parent)&&void 0!==r?r:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(e){g(this.globalDisabled_,w(e,"disabled")),v(this,"hidden",w(e,"hidden"))}bindDisabled(e){g(this.globalDisabled_,t=>{e.disabled=t})}bindTabIndex(e){g(this.globalDisabled_,t=>{e.tabIndex=t?-1:0})}handleDispose(e){this.value("disposed").emitter.on("change",t=>{t&&e()})}getGlobalDisabled_(){let e=this.get("parent");return!!e&&e.globalDisabled.rawValue||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(e){var t;let i=e.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}}let B=m(""),U={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"};class V{constructor(e){this.parent_=null,this.blade=e.blade,this.view=e.view,this.viewProps=e.viewProps;let t=this.view.element;this.blade.value("positions").emitter.on("change",()=>{["veryfirst","first","last","verylast"].forEach(e=>{t.classList.remove(B(void 0,U[e]))}),this.blade.get("positions").forEach(e=>{t.classList.add(B(void 0,U[e]))})}),this.viewProps.handleDispose(()=>{t&&t.parentElement&&t.parentElement.removeChild(t)})}get parent(){return this.parent_}set parent(e){if(this.parent_=e,!("parent"in this.viewProps.valMap_)){O({key:"parent",target:L.name,place:"BladeController.parent"});return}this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}}let k="http://www.w3.org/2000/svg";function G(e){e.offsetHeight}function z(e){return void 0!==e.ontouchstart}let W={check:'',dropdown:'',p2dpad:''};function H(e,t){let i=e.createElementNS(k,"svg");return i.innerHTML=W[t],i}function X(e,t,i){e.insertBefore(t,e.children[i])}function Y(e){e.parentElement&&e.parentElement.removeChild(e)}function j(e){for(;e.children.length>0;)e.removeChild(e.children[0])}function K(e){return e.relatedTarget?e.relatedTarget:"explicitOriginalTarget"in e?e.explicitOriginalTarget:null}let $=m("lbl");class q{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add($()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add($("l")),v(t.props,"label",t=>{l(t)?this.element.classList.add($(void 0,"nol")):(this.element.classList.remove($(void 0,"nol")),function(e){for(;e.childNodes.length>0;)e.removeChild(e.childNodes[0])}(i),i.appendChild(function(e,t){let i=e.createDocumentFragment();return t.split("\n").map(t=>e.createTextNode(t)).forEach((t,r)=>{r>0&&i.appendChild(e.createElement("br")),i.appendChild(t)}),i}(e,t)))}),this.element.appendChild(i),this.labelElement=i;let r=e.createElement("div");r.classList.add($("v")),this.element.appendChild(r),this.valueElement=r}}class Q extends V{constructor(e,t){let i=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{view:new q(e,{props:t.props,viewProps:i}),viewProps:i})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}}let Z={id:"button",type:"blade",accept(e){let t=D(e,{title:M.required.string,view:M.required.constant("button"),label:M.optional.string});return t?{params:t}:null},controller:e=>new Q(e.document,{blade:e.blade,props:R.fromObject({label:e.params.label}),valueController:new S(e.document,{props:R.fromObject({title:e.params.title}),viewProps:e.viewProps})}),api:e=>e.controller instanceof Q&&e.controller.valueController instanceof S?new _(e.controller):null};class J extends V{constructor(e){super(e),this.value=e.value}}function ee(){return new R({positions:A([],{equals:h})})}class et extends R{constructor(e){super(e)}static create(e){return new et(R.createCore({completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null}))}get styleExpanded(){var e;return null!==(e=this.get("temporaryExpanded"))&&void 0!==e?e:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";let e=this.get("expandedHeight");return this.get("shouldFixHeight")&&!l(e)?`${e}px`:"auto"}bindExpandedClass(e,t){let i=()=>{this.styleExpanded?e.classList.add(t):e.classList.remove(t)};v(this,"expanded",i),v(this,"temporaryExpanded",i)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}}function ei(e,t){t.style.height=e.styleHeight}function er(e,t){e.value("expanded").emitter.on("beforechange",()=>{if(e.set("completed",!1),l(e.get("expandedHeight"))){let i;let r=(i=0,function(e,t){let i=e.style.transition;e.style.transition="none",t(),e.style.transition=i}(t,()=>{e.set("expandedHeight",null),e.set("temporaryExpanded",!0),G(t),i=t.clientHeight,e.set("temporaryExpanded",null),G(t)}),i);r>0&&e.set("expandedHeight",r)}e.set("shouldFixHeight",!0),G(t)}),e.emitter.on("change",()=>{ei(e,t)}),ei(e,t),t.addEventListener("transitionend",t=>{"height"===t.propertyName&&e.cleanUpTransition()})}class es extends i{constructor(e,t){super(e),this.rackApi_=t}}class en{constructor(e){this.emitter=new f,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=e}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(e){for(let t of this.allItems())if(e(t))return t;return null}includes(e){return this.cache_.has(e)}add(e,t){if(this.includes(e))throw d.shouldNeverHappen();let i=void 0!==t?t:this.items_.length;this.items_.splice(i,0,e),this.cache_.add(e);let r=this.extract_(e);r&&(r.emitter.on("add",this.onSubListAdd_),r.emitter.on("remove",this.onSubListRemove_),r.allItems().forEach(e=>{this.cache_.add(e)})),this.emitter.emit("add",{index:i,item:e,root:this,target:this})}remove(e){let t=this.items_.indexOf(e);if(t<0)return;this.items_.splice(t,1),this.cache_.delete(e);let i=this.extract_(e);i&&(i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:t,item:e,root:this,target:this})}onSubListAdd_(e){this.cache_.add(e.item),this.emitter.emit("add",{index:e.index,item:e.item,root:this,target:e.target})}onSubListRemove_(e){this.cache_.delete(e.item),this.emitter.emit("remove",{index:e.index,item:e.item,root:this,target:e.target})}}class ea extends i{constructor(e){super(e),this.onBindingChange_=this.onBindingChange_.bind(this),this.emitter_=new f,this.controller_.binding.emitter.on("change",this.onBindingChange_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingChange_(e){let t=e.sender.target.read();this.emitter_.emit("change",{event:new s(this,t,this.controller_.binding.target.presetKey,e.options.last)})}}class eo extends Q{constructor(e,t){super(e,t),this.binding=t.binding}}class el extends i{constructor(e){super(e),this.onBindingUpdate_=this.onBindingUpdate_.bind(this),this.emitter_=new f,this.controller_.binding.emitter.on("update",this.onBindingUpdate_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingUpdate_(e){let t=e.sender.target.read();this.emitter_.emit("update",{event:new n(this,t,this.controller_.binding.target.presetKey)})}}class eh extends Q{constructor(e,t){super(e,t),this.binding=t.binding,this.viewProps.bindDisabled(this.binding.ticker),this.viewProps.handleDispose(()=>{this.binding.dispose()})}}function eu(e){return e instanceof ep?e.apiSet_:e instanceof es?e.rackApi_.apiSet_:null}function ec(e,t){let i=e.find(e=>e.controller_===t);if(!i)throw d.shouldNeverHappen();return i}function ed(e,t,i){if(!p.isBindable(e))throw d.notBindable();return new p(e,t,i)}class ep extends i{constructor(e,t){super(e),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this),this.onRackInputChange_=this.onRackInputChange_.bind(this),this.onRackMonitorUpdate_=this.onRackMonitorUpdate_.bind(this),this.emitter_=new f,this.apiSet_=new en(eu),this.pool_=t;let i=this.controller_.rack;i.emitter.on("add",this.onRackAdd_),i.emitter.on("remove",this.onRackRemove_),i.emitter.on("inputchange",this.onRackInputChange_),i.emitter.on("monitorupdate",this.onRackMonitorUpdate_),i.children.forEach(e=>{this.setUpApi_(e)})}get children(){return this.controller_.rack.children.map(e=>ec(this.apiSet_,e))}addInput(e,t,i){let r=null!=i?i:{},s=this.controller_.view.element.ownerDocument,n=new ea(this.pool_.createInput(s,ed(e,t,r.presetKey),r));return this.add(n,r.index)}addMonitor(e,t,i){let r=null!=i?i:{},s=this.controller_.view.element.ownerDocument,n=new el(this.pool_.createMonitor(s,ed(e,t),r));return this.add(n,r.index)}addFolder(e){return this.addBlade(Object.assign(Object.assign({},e),{view:"folder"}))}addButton(e){return this.addBlade(Object.assign(Object.assign({},e),{view:"button"}))}addSeparator(e){return this.addBlade(Object.assign(Object.assign({},null!=e?e:{}),{view:"separator"}))}addTab(e){return this.addBlade(Object.assign(Object.assign({},e),{view:"tab"}))}add(e,t){this.controller_.rack.add(e.controller_,t);let i=this.apiSet_.find(t=>t.controller_===e.controller_);return i&&this.apiSet_.remove(i),this.apiSet_.add(e),e}remove(e){this.controller_.rack.remove(e.controller_)}addBlade(e){let t=this.controller_.view.element.ownerDocument,i=this.pool_.createBlade(t,e),r=this.pool_.createBladeApi(i);return this.add(r,e.index)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}setUpApi_(e){this.apiSet_.find(t=>t.controller_===e)||this.apiSet_.add(this.pool_.createBladeApi(e))}onRackAdd_(e){this.setUpApi_(e.bladeController)}onRackRemove_(e){if(e.isRoot){let t=ec(this.apiSet_,e.bladeController);this.apiSet_.remove(t)}}onRackInputChange_(e){let t=e.bladeController;if(t instanceof eo){let i=ec(this.apiSet_,t),r=t.binding;this.emitter_.emit("change",{event:new s(i,r.target.read(),r.target.presetKey,e.options.last)})}else if(t instanceof J){let i=ec(this.apiSet_,t);this.emitter_.emit("change",{event:new s(i,t.value.rawValue,void 0,e.options.last)})}}onRackMonitorUpdate_(e){if(!(e.bladeController instanceof eh))throw d.shouldNeverHappen();let t=ec(this.apiSet_,e.bladeController),i=e.bladeController.binding;this.emitter_.emit("update",{event:new n(t,i.target.read(),i.target.presetKey)})}}class e_ extends es{constructor(e,t){super(e,new ep(e.rackController,t)),this.emitter_=new f,this.controller_.foldable.value("expanded").emitter.on("change",e=>{this.emitter_.emit("fold",{event:new a(this,e.sender.rawValue)})}),this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})})}get expanded(){return this.controller_.foldable.get("expanded")}set expanded(e){this.controller_.foldable.set("expanded",e)}get title(){return this.controller_.props.get("title")}set title(e){this.controller_.props.set("title",e)}get children(){return this.rackApi_.children}addInput(e,t,i){return this.rackApi_.addInput(e,t,i)}addMonitor(e,t,i){return this.rackApi_.addMonitor(e,t,i)}addFolder(e){return this.rackApi_.addFolder(e)}addButton(e){return this.rackApi_.addButton(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){return this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addBlade(e){return this.rackApi_.addBlade(e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}}class ef extends V{constructor(e){super({blade:e.blade,view:e.view,viewProps:e.rackController.viewProps}),this.rackController=e.rackController}}class em{constructor(e,t){let i=m(t.viewName);this.element=e.createElement("div"),this.element.classList.add(i()),t.viewProps.bindClassModifiers(this.element)}}function eg(e){return e instanceof eT?e.rack:e instanceof ef?e.rackController.rack:null}function ev(e){let t=eg(e);return t?t.bcSet_:null}class ex{constructor(e){var t,i;this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildInputChange_=this.onChildInputChange_.bind(this),this.onChildMonitorUpdate_=this.onChildMonitorUpdate_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onDescendantLayout_=this.onDescendantLayout_.bind(this),this.onDescendantInputChange_=this.onDescendantInputChange_.bind(this),this.onDescendantMonitorUpdate_=this.onDescendantMonitorUpdate_.bind(this),this.emitter=new f,this.blade_=null!==(t=e.blade)&&void 0!==t?t:null,null===(i=this.blade_)||void 0===i||i.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=e.viewProps,this.bcSet_=new en(ev),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(e,t){var i;null===(i=e.parent)||void 0===i||i.remove(e),u(e,"parent")?e.parent=this:(e.parent_=this,O({key:"parent",target:"BladeController",place:"BladeRack.add"})),this.bcSet_.add(e,t)}remove(e){u(e,"parent")?e.parent=null:(e.parent_=null,O({key:"parent",target:"BladeController",place:"BladeRack.remove"})),this.bcSet_.remove(e)}find(e){return this.bcSet_.allItems().filter(t=>t instanceof e)}onSetAdd_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("add",{bladeController:e.item,index:e.index,isRoot:t,sender:this}),!t)return;let i=e.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),i instanceof eo)i.binding.emitter.on("change",this.onChildInputChange_);else if(i instanceof eh)i.binding.emitter.on("update",this.onChildMonitorUpdate_);else if(i instanceof J)i.value.emitter.on("change",this.onChildValueChange_);else{let e=eg(i);if(e){let t=e.emitter;t.on("layout",this.onDescendantLayout_),t.on("inputchange",this.onDescendantInputChange_),t.on("monitorupdate",this.onDescendantMonitorUpdate_)}}}onSetRemove_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("remove",{bladeController:e.item,isRoot:t,sender:this}),!t)return;let i=e.item;if(i instanceof eo)i.binding.emitter.off("change",this.onChildInputChange_);else if(i instanceof eh)i.binding.emitter.off("update",this.onChildMonitorUpdate_);else if(i instanceof J)i.value.emitter.off("change",this.onChildValueChange_);else{let e=eg(i);if(e){let t=e.emitter;t.off("layout",this.onDescendantLayout_),t.off("inputchange",this.onDescendantInputChange_),t.off("monitorupdate",this.onDescendantMonitorUpdate_)}}}updatePositions_(){let e=this.bcSet_.items.filter(e=>!e.viewProps.get("hidden")),t=e[0],i=e[e.length-1];this.bcSet_.items.forEach(e=>{let r=[];e===t&&(r.push("first"),(!this.blade_||this.blade_.get("positions").includes("veryfirst"))&&r.push("veryfirst")),e===i&&(r.push("last"),(!this.blade_||this.blade_.get("positions").includes("verylast"))&&r.push("verylast")),e.blade.set("positions",r)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){this.bcSet_.items.filter(e=>e.viewProps.get("disposed")).forEach(e=>{this.bcSet_.remove(e)})}onChildInputChange_(e){let t=function(e,t){for(let i=0;i{for(let e=this.rack.children.length-1;e>=0;e--)this.rack.children[e].viewProps.set("disposed",!0)})}onRackAdd_(e){e.isRoot&&X(this.view.element,e.bladeController.view.element,e.index)}onRackRemove_(e){e.isRoot&&Y(e.bladeController.view.element)}}let eb=m("cnt");class eE{constructor(e,t){var i;this.className_=m(null!==(i=t.viewName)&&void 0!==i?i:"fld"),this.element=e.createElement("div"),this.element.classList.add(this.className_(),eb()),t.viewProps.bindClassModifiers(this.element),this.foldable_=t.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),v(this.foldable_,"completed",x(this.element,this.className_(void 0,"cpl")));let r=e.createElement("button");r.classList.add(this.className_("b")),v(t.props,"title",e=>{l(e)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r;let s=e.createElement("div");s.classList.add(this.className_("i")),this.element.appendChild(s);let n=e.createElement("div");n.classList.add(this.className_("t")),T(t.props.value("title"),n),this.buttonElement.appendChild(n),this.titleElement=n;let a=e.createElement("div");a.classList.add(this.className_("m")),this.buttonElement.appendChild(a);let o=t.containerElement;o.classList.add(this.className_("c")),this.element.appendChild(o),this.containerElement=o}}class eS extends ef{constructor(e,t){var i;let r=et.create(null===(i=t.expanded)||void 0===i||i),s=new eT(e,{blade:t.blade,root:t.root,viewProps:t.viewProps});super(Object.assign(Object.assign({},t),{rackController:s,view:new eE(e,{containerElement:s.view.element,foldable:r,props:t.props,viewName:t.root?"rot":void 0,viewProps:t.viewProps})})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=t.props,this.foldable=r,er(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}}let eC={id:"folder",type:"blade",accept(e){let t=D(e,{title:M.required.string,view:M.required.constant("folder"),expanded:M.optional.boolean});return t?{params:t}:null},controller:e=>new eS(e.document,{blade:e.blade,expanded:e.params.expanded,props:R.fromObject({title:e.params.title}),viewProps:e.viewProps}),api:e=>e.controller instanceof eS?new e_(e.controller,e.pool):null};class ey extends J{constructor(e,t){let i=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{value:t.valueController.value,view:new q(e,{props:t.props,viewProps:i}),viewProps:i})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}}class eA extends i{}let eR=m("spr");class eI{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(eR()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("hr");i.classList.add(eR("r")),this.element.appendChild(i)}}class eP extends V{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new eI(e,{viewProps:t.viewProps})}))}}let eM={id:"separator",type:"blade",accept(e){let t=D(e,{view:M.required.constant("separator")});return t?{params:t}:null},controller:e=>new eP(e.document,{blade:e.blade,viewProps:e.viewProps}),api:e=>e.controller instanceof eP?new eA(e.controller):null},eD=m("tbi");class eO{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(eD()),t.viewProps.bindClassModifiers(this.element),v(t.props,"selected",e=>{e?this.element.classList.add(eD(void 0,"sel")):this.element.classList.remove(eD(void 0,"sel"))});let i=e.createElement("button");i.classList.add(eD("b")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let r=e.createElement("div");r.classList.add(eD("t")),T(t.props.value("title"),r),this.buttonElement.appendChild(r),this.titleElement=r}}class eN{constructor(e,t){this.emitter=new f,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new eO(e,{props:t.props,viewProps:t.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}}class eF{constructor(e,t){this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new eN(e,{props:t.itemProps,viewProps:L.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.cc_=new eT(e,{blade:ee(),viewProps:L.create()}),this.props=t.props,v(this.props,"selected",e=>{this.itemController.props.set("selected",e),this.contentController.viewProps.set("hidden",!e)})}get itemController(){return this.ic_}get contentController(){return this.cc_}onItemClick_(){this.props.set("selected",!0)}}class ew{constructor(e,t){this.controller_=e,this.rackApi_=t}get title(){var e;return null!==(e=this.controller_.itemController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.itemController.props.set("title",e)}get selected(){return this.controller_.props.get("selected")}set selected(e){this.controller_.props.set("selected",e)}get children(){return this.rackApi_.children}addButton(e){return this.rackApi_.addButton(e)}addFolder(e){return this.rackApi_.addFolder(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addInput(e,t,i){return this.rackApi_.addInput(e,t,i)}addMonitor(e,t,i){return this.rackApi_.addMonitor(e,t,i)}addBlade(e){return this.rackApi_.addBlade(e)}}class eL extends es{constructor(e,t){super(e,new ep(e.rackController,t)),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.onSelect_=this.onSelect_.bind(this),this.emitter_=new f,this.pageApiMap_=new Map,this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})}),this.controller_.tab.selectedIndex.emitter.on("change",this.onSelect_),this.controller_.pageSet.emitter.on("add",this.onPageAdd_),this.controller_.pageSet.emitter.on("remove",this.onPageRemove_),this.controller_.pageSet.items.forEach(e=>{this.setUpPageApi_(e)})}get pages(){return this.controller_.pageSet.items.map(e=>{let t=this.pageApiMap_.get(e);if(!t)throw d.shouldNeverHappen();return t})}addPage(e){let t=new eF(this.controller_.view.element.ownerDocument,{itemProps:R.fromObject({selected:!1,title:e.title}),props:R.fromObject({selected:!1})});this.controller_.add(t,e.index);let i=this.pageApiMap_.get(t);if(!i)throw d.shouldNeverHappen();return i}removePage(e){this.controller_.remove(e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}setUpPageApi_(e){let t=this.rackApi_.apiSet_.find(t=>t.controller_===e.contentController);if(!t)throw d.shouldNeverHappen();let i=new ew(e,t);this.pageApiMap_.set(e,i)}onPageAdd_(e){this.setUpPageApi_(e.item)}onPageRemove_(e){if(!this.pageApiMap_.get(e.item))throw d.shouldNeverHappen();this.pageApiMap_.delete(e.item)}onSelect_(e){this.emitter_.emit("select",{event:new o(this,e.rawValue)})}}class eB{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=A(!0),this.selectedIndex=A(-1),this.items_=[]}add(e,t){let i=null!=t?t:this.items_.length;this.items_.splice(i,0,e),e.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(e){let t=this.items_.indexOf(e);t<0||(this.items_.splice(t,1),e.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length){this.selectedIndex.rawValue=-1,this.empty.rawValue=!0;return}let e=this.items_.findIndex(e=>e.rawValue);e<0?(this.items_.forEach((e,t)=>{e.rawValue=0===t}),this.selectedIndex.rawValue=0):(this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e),this.empty.rawValue=!1}onItemSelectedChange_(e){if(e.rawValue){let t=this.items_.findIndex(t=>t===e.sender);this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t}else this.keepSelection_()}}let eU=m("tab");class eV{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(eU(),eb()),t.viewProps.bindClassModifiers(this.element),g(t.empty,x(this.element,eU(void 0,"nop")));let i=e.createElement("div");i.classList.add(eU("t")),this.element.appendChild(i),this.itemsElement=i;let r=e.createElement("div");r.classList.add(eU("i")),this.element.appendChild(r);let s=t.contentsElement;s.classList.add(eU("c")),this.element.appendChild(s),this.contentsElement=s}}class ek extends ef{constructor(e,t){let i=new eT(e,{blade:t.blade,viewProps:t.viewProps}),r=new eB;super({blade:t.blade,rackController:i,view:new eV(e,{contentsElement:i.view.element,empty:r.empty,viewProps:t.viewProps})}),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.pageSet_=new en(()=>null),this.pageSet_.emitter.on("add",this.onPageAdd_),this.pageSet_.emitter.on("remove",this.onPageRemove_),this.tab=r}get pageSet(){return this.pageSet_}add(e,t){this.pageSet_.add(e,t)}remove(e){this.pageSet_.remove(this.pageSet_.items[e])}onPageAdd_(e){let t=e.item;X(this.view.itemsElement,t.itemController.view.element,e.index),t.itemController.viewProps.set("parent",this.viewProps),this.rackController.rack.add(t.contentController,e.index),this.tab.add(t.props.value("selected"))}onPageRemove_(e){let t=e.item;Y(t.itemController.view.element),t.itemController.viewProps.set("parent",null),this.rackController.rack.remove(t.contentController),this.tab.remove(t.props.value("selected"))}}let eG={id:"tab",type:"blade",accept(e){let t=D(e,{pages:M.required.array(M.required.object({title:M.required.string})),view:M.required.constant("tab")});return t&&0!==t.pages.length?{params:t}:null},controller(e){let t=new ek(e.document,{blade:e.blade,viewProps:e.viewProps});return e.params.pages.forEach(i=>{let r=new eF(e.document,{itemProps:R.fromObject({selected:!1,title:i.title}),props:R.fromObject({selected:!1})});t.add(r)}),t},api:e=>e.controller instanceof ek?new eL(e.controller,e.pool):null};class ez{constructor(){this.disabled=!1,this.emitter=new f}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}}class eW{constructor(e,t){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=e,this.emitter=new f,this.interval_=t,this.setTimer_()}get disabled(){return this.disabled_}set disabled(e){this.disabled_=e,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;let e=this.doc_.defaultView;e&&e.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;let e=this.doc_.defaultView;e&&(this.timerId_=e.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}}class eH{constructor(e){this.onValueChange_=this.onValueChange_.bind(this),this.reader=e.reader,this.writer=e.writer,this.emitter=new f,this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.target=e.target,this.read()}read(){let e=this.target.read();void 0!==e&&(this.value.rawValue=this.reader(e))}write_(e){this.writer(this.target,e)}onValueChange_(e){this.write_(e.rawValue),this.emitter.emit("change",{options:e.options,rawValue:e.rawValue,sender:this})}}function eX(e,t){for(;e.lengthe.length?i.splice(0,i.length-e.length):eX(i,e.length),i}(t,i),this.emitter.emit("update",{rawValue:i,sender:this})}onTick_(e){this.read()}}class ej{constructor(e){this.constraints=e}constrain(e){return this.constraints.reduce((e,t)=>t.constrain(e),e)}}function eK(e,t){if(e instanceof t)return e;if(e instanceof ej){let i=e.constraints.reduce((e,i)=>e||(i instanceof t?i:null),null);if(i)return i}return null}class e${constructor(e){this.values=R.fromObject({max:e.max,min:e.min})}constrain(e){let t=this.values.get("max");return Math.min(Math.max(e,this.values.get("min")),t)}}class eq{constructor(e){this.values=R.fromObject({options:e})}get options(){return this.values.get("options")}constrain(e){let t=this.values.get("options");return 0===t.length?e:t.filter(t=>t.value===e).length>0?e:t[0].value}}class eQ{constructor(e){this.values=R.fromObject({max:e.max,min:e.min})}get maxValue(){return this.values.get("max")}get minValue(){return this.values.get("min")}constrain(e){let t=this.values.get("max"),i=this.values.get("min"),r=e;return l(i)||(r=Math.max(r,i)),l(t)||(r=Math.min(r,t)),r}}class eZ{constructor(e,t=0){this.step=e,this.origin=t}constrain(e){let t=this.origin%this.step,i=Math.round((e-t)/this.step);return t+i*this.step}}let eJ=m("lst");class e0{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.props_=t.props,this.element=e.createElement("div"),this.element.classList.add(eJ()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("select");i.classList.add(eJ("s")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;let r=e.createElement("div");r.classList.add(eJ("m")),r.appendChild(H(e,"dropdown")),this.element.appendChild(r),t.value.emitter.on("change",this.onValueChange_),this.value_=t.value,v(this.props_,"options",t=>{j(this.selectElement),t.forEach(t=>{let i=e.createElement("option");i.textContent=t.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){let e=this.props_.get("options").map(e=>e.value);this.selectElement.selectedIndex=e.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}}class e1{constructor(e,t){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new e0(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(e){let t=e.currentTarget;this.value.rawValue=this.props.get("options")[t.selectedIndex].value}}let e2=m("pop");class e3{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(e2()),t.viewProps.bindClassModifiers(this.element),g(t.shows,x(this.element,e2(void 0,"v")))}}class e4{constructor(e,t){this.shows=A(!1),this.viewProps=t.viewProps,this.view=new e3(e,{shows:this.shows,viewProps:this.viewProps})}}let e5=m("txt");class e6{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(e5()),t.viewProps.bindClassModifiers(this.element),this.props_=t.props,this.props_.emitter.on("change",this.onChange_);let i=e.createElement("input");i.classList.add(e5("i")),i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,t.value.emitter.on("change",this.onChange_),this.value_=t.value,this.refresh()}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value_.rawValue)}onChange_(){this.refresh()}}class e8{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=t.parser,this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new e6(e,{props:t.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget.value,i=this.parser_(t);l(i)||(this.value.rawValue=i),this.view.refresh()}}function e7(e){return"false"!==e&&!!e}function e9(e){return String(e)}class te{constructor(e){this.text=e}evaluate(){return Number(this.text)}toString(){return this.text}}let tt={"**":(e,t)=>Math.pow(e,t),"*":(e,t)=>e*t,"/":(e,t)=>e/t,"%":(e,t)=>e%t,"+":(e,t)=>e+t,"-":(e,t)=>e-t,"<<":(e,t)=>e<>":(e,t)=>e>>t,">>>":(e,t)=>e>>>t,"&":(e,t)=>e&t,"^":(e,t)=>e^t,"|":(e,t)=>e|t};class ti{constructor(e,t,i){this.left=t,this.operator=e,this.right=i}evaluate(){let e=tt[this.operator];if(!e)throw Error(`unexpected binary operator: '${this.operator}`);return e(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}}let tr={"+":e=>e,"-":e=>-e,"~":e=>~e};class ts{constructor(e,t){this.operator=e,this.expression=t}evaluate(){let e=tr[this.operator];if(!e)throw Error(`unexpected unary operator: '${this.operator}`);return e(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}}function tn(e){return(t,i)=>{for(let r=0;r>>",">>"],["&"],["^"],["|"]].reduce((e,t)=>(i,r)=>{let s=e(i,r);if(!s)return null;r=s.cursor;let n=s.evaluable;for(;;){let s=function(e,t,i){i+=ta(t,i).length;let r=e.filter(e=>t.startsWith(e,i))[0];return r?(i+=r.length,{cursor:i+=ta(t,i).length,operator:r}):null}(t,i,r);if(!s)break;let a=e(i,r=s.cursor);if(!a)return null;r=a.cursor,n=new ti(s.operator,n,a.evaluable)}return n?{cursor:r,evaluable:n}:null},function e(t,i){var r,s;let n=null!==(s=function(e,t){let i=td(e,t);return(t+=i.length,""===i)?null:{evaluable:new te(i),cursor:t}}(t,r=i))&&void 0!==s?s:function(e,t){let i=e.substr(t,1);if(t+=i.length,"("!==i)return null;let r=t_(e,t);if(!r)return null;t=r.cursor,t+=ta(e,t).length;let s=e.substr(t,1);return(t+=s.length,")"!==s)?null:{evaluable:r.evaluable,cursor:t}}(t,r);if(n)return n;let a=t.substr(i,1);if(i+=a.length,"+"!==a&&"-"!==a&&"~"!==a)return null;let o=e(t,i);return o?{cursor:i=o.cursor,evaluable:new ts(a,o.evaluable)}:null});function t_(e,t){return t+=ta(e,t).length,tp(e,t)}function tf(e){var t;let i=function(e){let t=t_(e,0);return t&&t.cursor+ta(e,t.cursor).length===e.length?t.evaluable:null}(e);return null!==(t=null==i?void 0:i.evaluate())&&void 0!==t?t:null}function tm(e){if("number"==typeof e)return e;if("string"==typeof e){let t=tf(e);if(!l(t))return t}return 0}function tg(e){return String(e)}function tv(e){return t=>t.toFixed(Math.max(Math.min(e,20),0))}let tx=tv(0);function tT(e){return tx(e)+"%"}function tb(e){return String(e)}function tE(e){return e}function tS({primary:e,secondary:t,forward:i,backward:r}){let s=!1;function n(e){s||(s=!0,e(),s=!1)}e.emitter.on("change",r=>{n(()=>{t.setRawValue(i(e,t),r.options)})}),t.emitter.on("change",s=>{n(()=>{e.setRawValue(r(e,t),s.options)}),n(()=>{t.setRawValue(i(e,t),s.options)})}),n(()=>{t.setRawValue(i(e,t),{forceEmit:!1,last:!0})})}function tC(e,t){let i=e*(t.altKey?.1:1)*(t.shiftKey?10:1);return t.upKey?+i:t.downKey?-i:0}function ty(e){return{altKey:e.altKey,downKey:"ArrowDown"===e.key,shiftKey:e.shiftKey,upKey:"ArrowUp"===e.key}}function tA(e){return{altKey:e.altKey,downKey:"ArrowLeft"===e.key,shiftKey:e.shiftKey,upKey:"ArrowRight"===e.key}}function tR(e){return"ArrowUp"===e||"ArrowDown"===e||"ArrowLeft"===e||"ArrowRight"===e}function tI(e,t){var i,r;let s=t.ownerDocument.defaultView,n=t.getBoundingClientRect();return{x:e.pageX-((null!==(i=s&&s.scrollX)&&void 0!==i?i:0)+n.left),y:e.pageY-((null!==(r=s&&s.scrollY)&&void 0!==r?r:0)+n.top)}}class tP{constructor(e){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=e,this.emitter=new f,e.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),e.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),e.addEventListener("touchend",this.onTouchEnd_),e.addEventListener("mousedown",this.onMouseDown_)}computePosition_(e){let t=this.elem_.getBoundingClientRect();return{bounds:{width:t.width,height:t.height},point:e?{x:e.x,y:e.y}:null}}onMouseDown_(e){var t;e.preventDefault(),null===(t=e.currentTarget)||void 0===t||t.focus();let i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(tI(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseMove_(e){this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(tI(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseUp_(e){let t=this.elem_.ownerDocument;t.removeEventListener("mousemove",this.onDocumentMouseMove_),t.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(tI(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onTouchStart_(e){e.preventDefault();let t=e.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-i.left,y:t.clientY-i.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchMove_(e){let t=e.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-i.left,y:t.clientY-i.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchEnd_(e){var t;let i=null!==(t=e.targetTouches.item(0))&&void 0!==t?t:this.lastTouch_,r=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(i?{x:i.clientX-r.left,y:i.clientY-r.top}:void 0),sender:this,shiftKey:e.shiftKey})}}function tM(e,t,i,r,s){return r+(e-t)/(i-t)*(s-r)}function tD(e){return String(e.toFixed(10)).split(".")[1].replace(/0+$/,"").length}function tO(e,t,i){return Math.min(Math.max(e,t),i)}let tN=m("txt");class tF{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(tN(),tN(void 0,"num")),t.arrayPosition&&this.element.classList.add(tN(void 0,t.arrayPosition)),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("input");i.classList.add(tN("i")),i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=t.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(tN()),this.inputElement.classList.add(tN("i"));let r=e.createElement("div");r.classList.add(tN("k")),this.element.appendChild(r),this.knobElement=r;let s=e.createElementNS(k,"svg");s.classList.add(tN("g")),this.knobElement.appendChild(s);let n=e.createElementNS(k,"path");n.classList.add(tN("gb")),s.appendChild(n),this.guideBodyElem_=n;let a=e.createElementNS(k,"path");a.classList.add(tN("gh")),s.appendChild(a),this.guideHeadElem_=a;let o=e.createElement("div");o.classList.add(m("tt")()),this.knobElement.appendChild(o),this.tooltipElem_=o,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.refresh()}onDraggingChange_(e){if(null===e.rawValue){this.element.classList.remove(tN(void 0,"drg"));return}this.element.classList.add(tN(void 0,"drg"));let t=e.rawValue/this.props_.get("draggingScale"),i=t+(t>0?-1:t<0?1:0),r=tO(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",`M ${i+r},0 L${i},4 L${i+r},8 M ${t},-1 L${t},9`),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${t},4`);let s=this.props_.get("formatter");this.tooltipElem_.textContent=s(this.value.rawValue),this.tooltipElem_.style.left=`${t}px`}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value.rawValue)}onChange_(){this.refresh()}}class tw{constructor(e,t){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.parser_=t.parser,this.props=t.props,this.sliderProps_=null!==(i=t.sliderProps)&&void 0!==i?i:null,this.value=t.value,this.viewProps=t.viewProps,this.dragging_=A(null),this.view=new tF(e,{arrayPosition:t.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);let r=new tP(this.view.knobElement);r.emitter.on("down",this.onPointerDown_),r.emitter.on("move",this.onPointerMove_),r.emitter.on("up",this.onPointerUp_)}constrainValue_(e){var t,i;let r=null===(t=this.sliderProps_)||void 0===t?void 0:t.get("minValue"),s=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("maxValue"),n=e;return void 0!==r&&(n=Math.max(n,r)),void 0!==s&&(n=Math.min(n,s)),n}onInputChange_(e){let t=e.currentTarget.value,i=this.parser_(t);l(i)||(this.value.rawValue=this.constrainValue_(i)),this.view.refresh()}onInputKeyDown_(e){let t=tC(this.baseStep_,ty(e));0!==t&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+t),{forceEmit:!1,last:!1})}onInputKeyUp_(e){0!==tC(this.baseStep_,ty(e))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(e){if(!e.point)return null;let t=e.point.x-e.bounds.width/2;return this.constrainValue_(this.originRawValue_+t*this.props.get("draggingScale"))}onPointerMove_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}}let tL=m("sld");class tB{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(tL()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(tL("t")),t.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;let r=e.createElement("div");r.classList.add(tL("k")),this.trackElement.appendChild(r),this.knobElement=r,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.update_()}update_(){let e=tO(tM(this.value.rawValue,this.props_.get("minValue"),this.props_.get("maxValue"),0,100),0,100);this.knobElement.style.width=`${e}%`}onChange_(){this.update_()}}class tU{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.value=t.value,this.viewProps=t.viewProps,this.props=t.props,this.view=new tB(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new tP(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){e.point&&this.value.setRawValue(tM(tO(e.point.x,0,e.bounds.width),0,e.bounds.width,this.props.get("minValue"),this.props.get("maxValue")),t)}onPointerDownOrMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=tC(this.baseStep_,tA(e));0!==t&&this.value.setRawValue(this.value.rawValue+t,{forceEmit:!1,last:!1})}onKeyUp_(e){0!==tC(this.baseStep_,tA(e))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let tV=m("sldtxt");class tk{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(tV());let i=e.createElement("div");i.classList.add(tV("s")),this.sliderView_=t.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(tV("t")),this.textView_=t.textView,r.appendChild(this.textView_.element),this.element.appendChild(r)}}class tG{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.sliderC_=new tU(e,{baseStep:t.baseStep,props:t.sliderProps,value:t.value,viewProps:this.viewProps}),this.textC_=new tw(e,{baseStep:t.baseStep,parser:t.parser,props:t.textProps,sliderProps:t.sliderProps,value:t.value,viewProps:t.viewProps}),this.view=new tk(e,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}}function tz(e,t){e.write(t)}function tW(e){return Array.isArray(e)?M.required.array(M.required.object({text:M.required.string,value:M.required.raw}))(e).value:"object"==typeof e?M.required.raw(e).value:void 0}function tH(e){if("inline"===e||"popup"===e)return e}function tX(e){return M.required.object({max:M.optional.number,min:M.optional.number,step:M.optional.number})(e).value}function tY(e){if(Array.isArray(e))return e;let t=[];return Object.keys(e).forEach(i=>{t.push({text:i,value:e[i]})}),t}function tj(e){return l(e)?null:new eq(tY(e))}function tK(e,t){let i=e&&eK(e,eZ);return i?tD(i.step):Math.max(tD(t),2)}function t$(e){let t=function(e){let t=e?eK(e,eZ):null;return t?t.step:null}(e);return null!=t?t:1}function tq(e,t){var i;let r=e&&eK(e,eZ),s=Math.abs(null!==(i=null==r?void 0:r.step)&&void 0!==i?i:t);return 0===s?.1:Math.pow(10,Math.floor(Math.log10(s))-1)}let tQ=m("ckb");class tZ{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(tQ()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("label");i.classList.add(tQ("l")),this.element.appendChild(i);let r=e.createElement("input");r.classList.add(tQ("i")),r.type="checkbox",i.appendChild(r),this.inputElement=r,t.viewProps.bindDisabled(this.inputElement);let s=e.createElement("div");s.classList.add(tQ("w")),i.appendChild(s);let n=H(e,"check");s.appendChild(n),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}}class tJ{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new tZ(e,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget;this.value.rawValue=t.checked}}let t0={id:"input-bool",type:"input",accept:(e,t)=>{if("boolean"!=typeof e)return null;let i=D(t,{options:M.optional.custom(tW)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>e7,constraint:e=>(function(e){let t=[],i=tj(e.options);return i&&t.push(i),new ej(t)})(e.params),writer:e=>tz},controller:e=>{let t=e.document,i=e.value,r=e.constraint,s=r&&eK(r,eq);return s?new e1(t,{props:new R({options:s.values.value("options")}),value:i,viewProps:e.viewProps}):new tJ(t,{value:i,viewProps:e.viewProps})}},t1=m("col");class t2{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(t1()),t.foldable.bindExpandedClass(this.element,t1(void 0,"expanded")),v(t.foldable,"completed",x(this.element,t1(void 0,"cpl")));let i=e.createElement("div");i.classList.add(t1("h")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(t1("s")),i.appendChild(r),this.swatchElement=r;let s=e.createElement("div");if(s.classList.add(t1("t")),i.appendChild(s),this.textElement=s,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(t1("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}}function t3(e,t,i){let r,s,n;let a=(e%360+360)%360,o=tO(t/100,0,1),l=tO(i/100,0,1),h=l*o,u=h*(1-Math.abs(a/60%2-1)),c=l-h;return a>=0&&a<60?[r,s,n]=[h,u,0]:a>=60&&a<120?[r,s,n]=[u,h,0]:a>=120&&a<180?[r,s,n]=[0,h,u]:a>=180&&a<240?[r,s,n]=[0,u,h]:a>=240&&a<300?[r,s,n]=[u,0,h]:[r,s,n]=[h,0,u],[(r+c)*255,(s+c)*255,(n+c)*255]}function t4(e){return[e[0],e[1],e[2]]}function t5(e,t){return[e[0],e[1],e[2],t]}let t6={hsl:{hsl:(e,t,i)=>[e,t,i],hsv:function(e,t,i){let r=i+t*(100-Math.abs(2*i-100))/200;return[e,0!==r?t*(100-Math.abs(2*i-100))/r:0,i+t*(100-Math.abs(2*i-100))/200]},rgb:function(e,t,i){let r,s,n;let a=(e%360+360)%360,o=tO(t/100,0,1),l=tO(i/100,0,1),h=(1-Math.abs(2*l-1))*o,u=h*(1-Math.abs(a/60%2-1)),c=l-h/2;return a>=0&&a<60?[r,s,n]=[h,u,0]:a>=60&&a<120?[r,s,n]=[u,h,0]:a>=120&&a<180?[r,s,n]=[0,h,u]:a>=180&&a<240?[r,s,n]=[0,u,h]:a>=240&&a<300?[r,s,n]=[u,0,h]:[r,s,n]=[h,0,u],[(r+c)*255,(s+c)*255,(n+c)*255]}},hsv:{hsl:function(e,t,i){let r=100-Math.abs(i*(200-t)/100-100);return[e,0!==r?t*i/r:0,i*(200-t)/200]},hsv:(e,t,i)=>[e,t,i],rgb:t3},rgb:{hsl:function(e,t,i){let r=tO(e/255,0,1),s=tO(t/255,0,1),n=tO(i/255,0,1),a=Math.max(r,s,n),o=Math.min(r,s,n),l=a-o,h=0,u=0;return 0!==l&&(u=l/(1-Math.abs(a+o-1)),h=(h=r===a?(s-n)/l:s===a?2+(n-r)/l:4+(r-s)/l)/6+(h<0?1:0)),[360*h,100*u,(o+a)/2*100]},hsv:function(e,t,i){let r=tO(e/255,0,1),s=tO(t/255,0,1),n=tO(i/255,0,1),a=Math.max(r,s,n),o=a-Math.min(r,s,n);return[0===o?0:a===r?((s-n)/o%6+6)%6*60:a===s?60*((n-r)/o+2):60*((r-s)/o+4),100*(0===a?0:o/a),100*a]},rgb:(e,t,i)=>[e,t,i]}};function t8(e,t){return["float"===t?1:"rgb"===e?255:360,"float"===t?1:"rgb"===e?255:100,"float"===t?1:"rgb"===e?255:100]}function t7(e,t,i,r){let s=t8(t,i),n=t8(t,r);return e.map((e,t)=>e/s[t]*n[t])}function t9(e,t){return!("object"!=typeof e||l(e))&&t in e&&"number"==typeof e[t]}class ie{static black(e="int"){return new ie([0,0,0],"rgb",e)}static fromObject(e,t="int"){return new ie("a"in e?[e.r,e.g,e.b,e.a]:[e.r,e.g,e.b],"rgb",t)}static toRgbaObject(e,t="int"){return e.toRgbaObject(t)}static isRgbColorObject(e){return t9(e,"r")&&t9(e,"g")&&t9(e,"b")}static isRgbaColorObject(e){return this.isRgbColorObject(e)&&t9(e,"a")}static isColorObject(e){return this.isRgbColorObject(e)}static equals(e,t){if(e.mode!==t.mode)return!1;let i=e.comps_,r=t.comps_;for(let e=0;ee.inputElement)];return this.alphaViews_&&e.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),e}}function ir(e){return"int"===e?"int":"float"===e?"float":void 0}function is(e){return D(e,{alpha:M.optional.boolean,color:M.optional.object({alpha:M.optional.boolean,type:M.optional.custom(ir)}),expanded:M.optional.boolean,picker:M.optional.custom(tH)})}function ia(e){return e?.1:1}function io(e){var t;return null===(t=e.color)||void 0===t?void 0:t.type}function il(e,t){let i=e.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*t,t):Math.min(parseFloat(e),t)}let ih={deg:e=>e,grad:e=>360*e/400,rad:e=>360*e/(2*Math.PI),turn:e=>360*e};function iu(e){let t=e.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!t)return parseFloat(e);let i=parseFloat(t[1]);return ih[t[2]](i)}function ic(e){let t=e.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[il(t[1],255),il(t[2],255),il(t[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function id(e){return t=>{let i=ic(t);return i?new ie(i,"rgb",e):null}}function ip(e){let t=e.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[il(t[1],255),il(t[2],255),il(t[3],255),il(t[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function i_(e){return t=>{let i=ip(t);return i?new ie(i,"rgb",e):null}}function im(e){let t=e.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[iu(t[1]),il(t[2],100),il(t[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function ig(e){return t=>{let i=im(t);return i?new ie(i,"hsl",e):null}}function iv(e){let t=e.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[iu(t[1]),il(t[2],100),il(t[3],100),il(t[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function ix(e){return t=>{let i=iv(t);return i?new ie(i,"hsl",e):null}}function iT(e){let t=e.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)];let i=e.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function ib(e){let t=e.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),tM(parseInt(t[4]+t[4],16),0,255,0,1)];let i=e.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),tM(parseInt(i[4],16),0,255,0,1)]:null}function iE(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let i=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function iS(e){return t=>{let i=iE(t);return i?new ie(i,"rgb",e):null}}function iC(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let i=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function iy(e){return t=>{let i=iC(t);return i?new ie(i,"rgb",e):null}}let iA=[{parser:iT,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:ib,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:ic,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:ip,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:im,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:iv,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:iE,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:iC,result:{alpha:!0,mode:"rgb",notation:"object"}}];function iR(e,t="int"){let i=iA.reduce((t,{parser:i,result:r})=>t||(i(e)?r:null),null);return i?"hex"===i.notation&&"float"!==t?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:t}):null:null}let iI={int:[function(e){let t=iT(e);return t?new ie(t,"rgb","int"):null},function(e){let t=ib(e);return t?new ie(t,"rgb","int"):null},id("int"),i_("int"),ig("int"),ix("int"),iS("int"),iy("int")],float:[id("float"),i_("float"),ig("float"),ix("float"),iS("float"),iy("float")]};function iP(e){let t=iI[e];return e=>t.reduce((t,i)=>t||i(e),null)}function iM(e){let t=tO(Math.floor(e),0,255).toString(16);return 1===t.length?`0${t}`:t}function iD(e,t="#"){let i=t4(e.getComponents("rgb")).map(iM).join("");return`${t}${i}`}function iO(e,t="#"){let i=e.getComponents("rgb"),r=[i[0],i[1],i[2],255*i[3]].map(iM).join("");return`${t}${r}`}function iN(e,t){let i=tv("float"===t?2:0),r=t4(e.getComponents("rgb",t)).map(e=>i(e));return`rgb(${r.join(", ")})`}function iF(e,t){let i=tv(2),r=tv("float"===t?2:0),s=e.getComponents("rgb",t).map((e,t)=>(3===t?i:r)(e));return`rgba(${s.join(", ")})`}function iw(e,t){let i=tv("float"===t?2:0),r=["r","g","b"],s=t4(e.getComponents("rgb",t)).map((e,t)=>`${r[t]}: ${i(e)}`);return`{${s.join(", ")}}`}function iL(e,t){let i=tv(2),r=tv("float"===t?2:0),s=["r","g","b","a"],n=e.getComponents("rgb",t).map((e,t)=>`${s[t]}: ${(3===t?i:r)(e)}`);return`{${n.join(", ")}}`}let iB=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:iD},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:iO},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:function(e){let t=[tv(0),tT,tT],i=t4(e.getComponents("hsl")).map((e,i)=>t[i](e));return`hsl(${i.join(", ")})`}},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:function(e){let t=[tv(0),tT,tT,tv(2)],i=e.getComponents("hsl").map((e,i)=>t[i](e));return`hsla(${i.join(", ")})`}},...["int","float"].reduce((e,t)=>[...e,{format:{alpha:!1,mode:"rgb",notation:"func",type:t},stringifier:e=>iN(e,t)},{format:{alpha:!0,mode:"rgb",notation:"func",type:t},stringifier:e=>iF(e,t)},{format:{alpha:!1,mode:"rgb",notation:"object",type:t},stringifier:e=>iw(e,t)},{format:{alpha:!0,mode:"rgb",notation:"object",type:t},stringifier:e=>iL(e,t)}],[])];function iU(e){return iB.reduce((t,i)=>{var r;return t||((r=i.format).alpha===e.alpha&&r.mode===e.mode&&r.notation===e.notation&&r.type===e.type?i.stringifier:null)},null)}let iV=m("apl");class ik{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(iV()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("div");i.classList.add(iV("b")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(iV("c")),i.appendChild(r),this.colorElem_=r;let s=e.createElement("div");s.classList.add(iV("m")),this.element.appendChild(s),this.markerElem_=s;let n=e.createElement("div");n.classList.add(iV("p")),this.markerElem_.appendChild(n),this.previewElem_=n,this.update_()}update_(){let e=this.value.rawValue,t=e.getComponents("rgb"),i=new ie([t[0],t[1],t[2],0],"rgb"),r=new ie([t[0],t[1],t[2],255],"rgb"),s=["to right",iF(i),iF(r)];this.colorElem_.style.background=`linear-gradient(${s.join(",")})`,this.previewElem_.style.backgroundColor=iF(e);let n=tM(t[3],0,1,0,100);this.markerElem_.style.left=`${n}%`}onValueChange_(){this.update_()}}class iG{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new ik(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new tP(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=e.point.x/e.bounds.width,[r,s,n]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new ie([r,s,n,i],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=tC(ia(!0),tA(e));if(0===t)return;let[i,r,s,n]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new ie([i,r,s,n+t],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){0!==tC(ia(!0),tA(e))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let iz=m("coltxt");class iW{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(iz()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(iz("m")),this.modeElem_=function(e){let t=e.createElement("select");return t.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"}].reduce((t,i)=>{let r=e.createElement("option");return r.textContent=i.text,r.value=i.value,t.appendChild(r),t},e.createDocumentFragment())),t}(e),this.modeElem_.classList.add(iz("ms")),i.appendChild(this.modeSelectElement),t.viewProps.bindDisabled(this.modeElem_);let r=e.createElement("div");r.classList.add(iz("mm")),r.appendChild(H(e,"dropdown")),i.appendChild(r),this.element.appendChild(i);let s=e.createElement("div");s.classList.add(iz("w")),this.element.appendChild(s),this.textsElem_=s,this.textViews_=t.textViews,this.applyTextViews_(),g(t.colorMode,e=>{this.modeElem_.value=e})}get modeSelectElement(){return this.modeElem_}get textViews(){return this.textViews_}set textViews(e){this.textViews_=e,this.applyTextViews_()}applyTextViews_(){j(this.textsElem_);let e=this.element.ownerDocument;this.textViews_.forEach(t=>{let i=e.createElement("div");i.classList.add(iz("c")),i.appendChild(t.element),this.textsElem_.appendChild(i)})}}function iH(e,t,i){return new tw(e,{arrayPosition:0===i?"fst":2===i?"lst":"mid",baseStep:ia(!1),parser:t.parser,props:R.fromObject({draggingScale:"float"===t.colorType?.01:1,formatter:tv("float"===t.colorType?2:0)}),value:A(0,{constraint:new e$({min:0,max:t8(t.colorMode,t.colorType)[i]})}),viewProps:t.viewProps})}class iX{constructor(e,t){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=t.colorType,this.parser_=t.parser,this.value=t.value,this.viewProps=t.viewProps,this.colorMode=A(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(e),this.view=new iW(e,{colorMode:this.colorMode,textViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(e){let t={colorMode:this.colorMode.rawValue,colorType:this.colorType_,parser:this.parser_,viewProps:this.viewProps},i=[iH(e,t,0),iH(e,t,1),iH(e,t,2)];return i.forEach((e,t)=>{tS({primary:this.value,secondary:e.value,forward:e=>e.rawValue.getComponents(this.colorMode.rawValue,this.colorType_)[t],backward:(e,i)=>{let r=this.colorMode.rawValue,s=e.rawValue.getComponents(r,this.colorType_);return s[t]=i.rawValue,new ie(t5(t4(s),s[3]),r,this.colorType_)}})}),i}onModeSelectChange_(e){let t=e.currentTarget;this.colorMode.rawValue=t.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.textViews=[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view]}}let iY=m("hpl");class ij{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(iY()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("div");i.classList.add(iY("c")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(iY("m")),this.element.appendChild(r),this.markerElem_=r,this.update_()}update_(){let[e]=this.value.rawValue.getComponents("hsv");this.markerElem_.style.backgroundColor=iN(new ie([e,100,100],"hsv"));let t=tM(e,0,360,0,100);this.markerElem_.style.left=`${t}%`}onValueChange_(){this.update_()}}class iK{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new ij(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new tP(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=tM(tO(e.point.x,0,e.bounds.width),0,e.bounds.width,0,360),[,r,s,n]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new ie([i,r,s,n],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=tC(ia(!1),tA(e));if(0===t)return;let[i,r,s,n]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new ie([i+t,r,s,n],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){0!==tC(ia(!1),tA(e))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let i$=m("svp");class iq{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(i$()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("canvas");i.height=64,i.width=64,i.classList.add(i$("c")),this.element.appendChild(i),this.canvasElement=i;let r=e.createElement("div");r.classList.add(i$("m")),this.element.appendChild(r),this.markerElem_=r,this.update_()}update_(){let e=function(e){let t=e.ownerDocument.defaultView;return t&&"document"in t?e.getContext("2d",{willReadFrequently:!0}):null}(this.canvasElement);if(!e)return;let t=this.value.rawValue.getComponents("hsv"),i=this.canvasElement.width,r=this.canvasElement.height,s=e.getImageData(0,0,i,r),n=s.data;for(let e=0;ee.rawValue.getComponents()[3],backward:(e,t)=>{let i=e.rawValue.getComponents();return i[3]=t.rawValue,new ie(i,e.rawValue.mode)}}),this.textC_=new iX(e,{colorType:t.colorType,parser:tf,value:this.value,viewProps:this.viewProps}),this.view=new ii(e,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:t.supportsAlpha,svPaletteView:this.svPaletteC_.view,textView:this.textC_.view,viewProps:this.viewProps})}get textController(){return this.textC_}}let iJ=m("colsw");class i0{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.element=e.createElement("div"),this.element.classList.add(iJ()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(iJ("sw")),this.element.appendChild(i),this.swatchElem_=i;let r=e.createElement("button");r.classList.add(iJ("b")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r,this.update_()}update_(){let e=this.value.rawValue;this.swatchElem_.style.backgroundColor=iO(e)}onValueChange_(){this.update_()}}class i1{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new i0(e,{value:this.value,viewProps:this.viewProps})}}class i2{constructor(e,t){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=et.create(t.expanded),this.swatchC_=new i1(e,{value:this.value,viewProps:this.viewProps});let i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new e8(e,{parser:t.parser,props:R.fromObject({formatter:t.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new t2(e,{foldable:this.foldable_,pickerLayout:t.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===t.pickerLayout?new e4(e,{viewProps:this.viewProps}):null;let r=new iZ(e,{colorType:t.colorType,supportsAlpha:t.supportsAlpha,value:this.value,viewProps:this.viewProps});r.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=r,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(r.view.element),tS({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),er(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,i=e.relatedTarget;i&&t.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,i=K(e);!(i&&t.contains(i))&&(!i||i!==this.swatchC_.view.buttonElement||z(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.swatchC_.view.buttonElement.focus()}}function i3(e){return t4(e.getComponents("rgb")).reduce((e,t)=>e<<8|255&Math.floor(t),0)}function i4(e){return e.getComponents("rgb").reduce((e,t,i)=>e<<8|255&Math.floor(3===i?255*t:t),0)>>>0}function i5(e){return"number"!=typeof e?ie.black():new ie([e>>16&255,e>>8&255,255&e],"rgb")}function i6(e){return"number"!=typeof e?ie.black():new ie([e>>24&255,e>>16&255,e>>8&255,tM(255&e,0,255,0,1)],"rgb")}function i8(e){var t;return null!=e&&!!e.alpha||null!==(t=null==e?void 0:e.color)&&void 0!==t&&!!t.alpha}let i7={id:"input-color-number",type:"input",accept:(e,t)=>{if("number"!=typeof e||!("color"in t||"view"in t&&"color"===t.view))return null;let i=is(t);return i?{initialValue:e,params:i}:null},binding:{reader:e=>i8(e.params)?i6:i5,equals:ie.equals,writer:e=>(function(e){let t=e?i4:i3;return(e,i)=>{tz(e,t(i))}})(i8(e.params))},controller:e=>{let t=i8(e.params),i="expanded"in e.params?e.params.expanded:void 0,r="picker"in e.params?e.params.picker:void 0;return new i2(e.document,{colorType:"int",expanded:null!=i&&i,formatter:t?e=>iO(e,"0x"):e=>iD(e,"0x"),parser:iP("int"),pickerLayout:null!=r?r:"popup",supportsAlpha:t,value:e.value,viewProps:e.viewProps})}},i9={id:"input-color-object",type:"input",accept:(e,t)=>{if(!ie.isColorObject(e))return null;let i=is(t);return i?{initialValue:e,params:i}:null},binding:{reader:e=>{var t;return t=io(e.params),e=>ie.isColorObject(e)?ie.fromObject(e,t):ie.black(t)},equals:ie.equals,writer:e=>{var t,i,r;return t=e.initialValue,i=ie.isRgbaColorObject(t),r=io(e.params),(e,t)=>{i?function(e,t,i){let r=t.toRgbaObject(i);e.writeProperty("r",r.r),e.writeProperty("g",r.g),e.writeProperty("b",r.b),e.writeProperty("a",r.a)}(e,t,r):function(e,t,i){let r=t.toRgbaObject(i);e.writeProperty("r",r.r),e.writeProperty("g",r.g),e.writeProperty("b",r.b)}(e,t,r)}}},controller:e=>{var t;let i=ie.isRgbaColorObject(e.initialValue),r="expanded"in e.params?e.params.expanded:void 0,s="picker"in e.params?e.params.picker:void 0,n=null!==(t=io(e.params))&&void 0!==t?t:"int";return new i2(e.document,{colorType:n,expanded:null!=r&&r,formatter:e=>i?iL(e,n):iw(e,n),parser:iP(n),pickerLayout:null!=s?s:"popup",supportsAlpha:i,value:e.value,viewProps:e.viewProps})}},re={id:"input-color-string",type:"input",accept:(e,t)=>{if("string"!=typeof e||"view"in t&&"text"===t.view)return null;let i=iR(e,io(t));if(!i||!iU(i))return null;let r=is(t);return r?{initialValue:e,params:r}:null},binding:{reader:e=>{var t;return function(e){let t=iI[e];return i=>{if("string"!=typeof i)return ie.black(e);let r=t.reduce((e,t)=>e||t(i),null);return null!=r?r:ie.black(e)}}(null!==(t=io(e.params))&&void 0!==t?t:"int")},equals:ie.equals,writer:e=>{let t=iR(e.initialValue,io(e.params));if(!t)throw d.shouldNeverHappen();let i=function(e){let t=iU(e);return t?(e,i)=>{tz(e,t(i))}:null}(t);if(!i)throw d.notBindable();return i}},controller:e=>{let t=iR(e.initialValue,io(e.params));if(!t)throw d.shouldNeverHappen();let i=iU(t);if(!i)throw d.shouldNeverHappen();let r="expanded"in e.params?e.params.expanded:void 0,s="picker"in e.params?e.params.picker:void 0;return new i2(e.document,{colorType:t.type,expanded:null!=r&&r,formatter:i,parser:iP(t.type),pickerLayout:null!=s?s:"popup",supportsAlpha:t.alpha,value:e.value,viewProps:e.viewProps})}};class rt{constructor(e){this.components=e.components,this.asm_=e.assembly}constrain(e){let t=this.asm_.toComponents(e).map((e,t)=>{var i,r;return null!==(r=null===(i=this.components[t])||void 0===i?void 0:i.constrain(e))&&void 0!==r?r:e});return this.asm_.fromComponents(t)}}let ri=m("pndtxt");class rr{constructor(e,t){this.textViews=t.textViews,this.element=e.createElement("div"),this.element.classList.add(ri()),this.textViews.forEach(t=>{let i=e.createElement("div");i.classList.add(ri("a")),i.appendChild(t.element),this.element.appendChild(i)})}}class rs{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.acs_=t.axes.map((i,r)=>new tw(e,{arrayPosition:0===r?"fst":r===t.axes.length-1?"lst":"mid",baseStep:t.axes[r].baseStep,parser:t.parser,props:t.axes[r].textProps,value:A(0,{constraint:t.axes[r].constraint}),viewProps:t.viewProps})),this.acs_.forEach((e,i)=>{tS({primary:this.value,secondary:e.value,forward:e=>t.assembly.toComponents(e.rawValue)[i],backward:(e,r)=>{let s=t.assembly.toComponents(e.rawValue);return s[i]=r.rawValue,t.assembly.fromComponents(s)}})}),this.view=new rr(e,{textViews:this.acs_.map(e=>e.view)})}}function rn(e,t){return"step"in e&&!l(e.step)?new eZ(e.step,t):null}function ra(e){return l(e.max)||l(e.min)?l(e.max)&&l(e.min)?null:new eQ({max:e.max,min:e.min}):new e$({max:e.max,min:e.min})}let ro={id:"input-number",type:"input",accept:(e,t)=>{if("number"!=typeof e)return null;let i=D(t,{format:M.optional.function,max:M.optional.number,min:M.optional.number,options:M.optional.custom(tW),step:M.optional.number});return i?{initialValue:e,params:i}:null},binding:{reader:e=>tm,constraint:e=>(function(e,t){let i=[],r=rn(e,t);r&&i.push(r);let s=ra(e);s&&i.push(s);let n=tj(e.options);return n&&i.push(n),new ej(i)})(e.params,e.initialValue),writer:e=>tz},controller:e=>{var t;let i=e.value,r=e.constraint,s=r&&eK(r,eq);if(s)return new e1(e.document,{props:new R({options:s.values.value("options")}),value:i,viewProps:e.viewProps});let n=null!==(t="format"in e.params?e.params.format:void 0)&&void 0!==t?t:tv(tK(r,i.rawValue)),a=r&&eK(r,e$);return a?new tG(e.document,{baseStep:t$(r),parser:tf,sliderProps:new R({maxValue:a.values.value("max"),minValue:a.values.value("min")}),textProps:R.fromObject({draggingScale:tq(r,i.rawValue),formatter:n}),value:i,viewProps:e.viewProps}):new tw(e.document,{baseStep:t$(r),parser:tf,props:R.fromObject({draggingScale:tq(r,i.rawValue),formatter:n}),value:i,viewProps:e.viewProps})}};class rl{constructor(e=0,t=0){this.x=e,this.y=t}getComponents(){return[this.x,this.y]}static isObject(e){if(l(e))return!1;let t=e.x,i=e.y;return"number"==typeof t&&"number"==typeof i}static equals(e,t){return e.x===t.x&&e.y===t.y}toObject(){return{x:this.x,y:this.y}}}let rh={toComponents:e=>e.getComponents(),fromComponents:e=>new rl(...e)},ru=m("p2d");class rc{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(ru()),t.viewProps.bindClassModifiers(this.element),g(t.expanded,x(this.element,ru(void 0,"expanded")));let i=e.createElement("div");i.classList.add(ru("h")),this.element.appendChild(i);let r=e.createElement("button");r.classList.add(ru("b")),r.appendChild(H(e,"p2dpad")),t.viewProps.bindDisabled(r),i.appendChild(r),this.buttonElement=r;let s=e.createElement("div");if(s.classList.add(ru("t")),i.appendChild(s),this.textElement=s,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(ru("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}}let rd=m("p2dp");class rp{constructor(e,t){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.invertsY_=t.invertsY,this.maxValue_=t.maxValue,this.element=e.createElement("div"),this.element.classList.add(rd()),"popup"===t.layout&&this.element.classList.add(rd(void 0,"p")),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(rd("p")),t.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;let r=e.createElementNS(k,"svg");r.classList.add(rd("g")),this.padElement.appendChild(r),this.svgElem_=r;let s=e.createElementNS(k,"line");s.classList.add(rd("ax")),s.setAttributeNS(null,"x1","0"),s.setAttributeNS(null,"y1","50%"),s.setAttributeNS(null,"x2","100%"),s.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(s);let n=e.createElementNS(k,"line");n.classList.add(rd("ax")),n.setAttributeNS(null,"x1","50%"),n.setAttributeNS(null,"y1","0"),n.setAttributeNS(null,"x2","50%"),n.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(n);let a=e.createElementNS(k,"line");a.classList.add(rd("l")),a.setAttributeNS(null,"x1","50%"),a.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(a),this.lineElem_=a;let o=e.createElement("div");o.classList.add(rd("m")),this.padElement.appendChild(o),this.markerElem_=o,t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){let[e,t]=this.value.rawValue.getComponents(),i=this.maxValue_,r=tM(e,-i,+i,0,100),s=tM(t,-i,+i,0,100),n=this.invertsY_?100-s:s;this.lineElem_.setAttributeNS(null,"x2",`${r}%`),this.lineElem_.setAttributeNS(null,"y2",`${n}%`),this.markerElem_.style.left=`${r}%`,this.markerElem_.style.top=`${n}%`}onValueChange_(){this.update_()}onFoldableChange_(){this.update_()}}function r_(e,t,i){return[tC(t[0],tA(e)),tC(t[1],ty(e))*(i?1:-1)]}class rf{constructor(e,t){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.baseSteps_=t.baseSteps,this.maxValue_=t.maxValue,this.invertsY_=t.invertsY,this.view=new rp(e,{invertsY:this.invertsY_,layout:t.layout,maxValue:this.maxValue_,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new tP(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=this.maxValue_,r=tM(e.point.x,0,e.bounds.width,-i,+i),s=tM(this.invertsY_?e.bounds.height-e.point.y:e.point.y,0,e.bounds.height,-i,+i);this.value.setRawValue(new rl(r,s),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onPadKeyDown_(e){tR(e.key)&&e.preventDefault();let[t,i]=r_(e,this.baseSteps_,this.invertsY_);(0!==t||0!==i)&&this.value.setRawValue(new rl(this.value.rawValue.x+t,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(e){let[t,i]=r_(e,this.baseSteps_,this.invertsY_);(0!==t||0!==i)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}class rm{constructor(e,t){var i,r;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=et.create(t.expanded),this.popC_="popup"===t.pickerLayout?new e4(e,{viewProps:this.viewProps}):null;let s=new rf(e,{baseSteps:[t.axes[0].baseStep,t.axes[1].baseStep],invertsY:t.invertsY,layout:t.pickerLayout,maxValue:t.maxValue,value:this.value,viewProps:this.viewProps});s.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=s,this.textC_=new rs(e,{assembly:rh,axes:t.axes,parser:t.parser,value:this.value,viewProps:this.viewProps}),this.view=new rc(e,{expanded:this.foldable_.value("expanded"),pickerLayout:t.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(r=this.view.buttonElement)||void 0===r||r.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),tS({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),er(this.foldable_,this.view.pickerElement))}onPadButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,i=e.relatedTarget;i&&t.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,i=K(e);!(i&&t.contains(i))&&(!i||i!==this.view.buttonElement||z(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.view.buttonElement.focus()}}class rg{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(e){if(l(e))return!1;let t=e.x,i=e.y,r=e.z;return"number"==typeof t&&"number"==typeof i&&"number"==typeof r}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}toObject(){return{x:this.x,y:this.y,z:this.z}}}let rv={toComponents:e=>e.getComponents(),fromComponents:e=>new rg(...e)};function rx(e){return rg.isObject(e)?new rg(e.x,e.y,e.z):new rg}function rT(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z)}function rb(e,t){return{baseStep:t$(t),constraint:t,textProps:R.fromObject({draggingScale:tq(t,e),formatter:tv(tK(t,e))})}}let rE={id:"input-point3d",type:"input",accept:(e,t)=>{if(!rg.isObject(e))return null;let i=D(t,{x:M.optional.custom(tX),y:M.optional.custom(tX),z:M.optional.custom(tX)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>rx,constraint:e=>{var t,i;return t=e.params,i=e.initialValue,new rt({assembly:rv,components:[rj("x"in t?t.x:void 0,i.x),rj("y"in t?t.y:void 0,i.y),rj("z"in t?t.z:void 0,i.z)]})},equals:rg.equals,writer:e=>rT},controller:e=>{let t=e.value,i=e.constraint;if(!(i instanceof rt))throw d.shouldNeverHappen();return new rs(e.document,{assembly:rv,axes:[rb(t.rawValue.x,i.components[0]),rb(t.rawValue.y,i.components[1]),rb(t.rawValue.z,i.components[2])],parser:tf,value:t,viewProps:e.viewProps})}};class rS{constructor(e=0,t=0,i=0,r=0){this.x=e,this.y=t,this.z=i,this.w=r}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(e){if(l(e))return!1;let t=e.x,i=e.y,r=e.z,s=e.w;return"number"==typeof t&&"number"==typeof i&&"number"==typeof r&&"number"==typeof s}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}}let rC={toComponents:e=>e.getComponents(),fromComponents:e=>new rS(...e)};function ry(e){return rS.isObject(e)?new rS(e.x,e.y,e.z,e.w):new rS}function rA(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z),e.writeProperty("w",t.w)}let rR={id:"input-point4d",type:"input",accept:(e,t)=>{if(!rS.isObject(e))return null;let i=D(t,{x:M.optional.custom(tX),y:M.optional.custom(tX),z:M.optional.custom(tX),w:M.optional.custom(tX)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>ry,constraint:e=>{var t,i;return t=e.params,i=e.initialValue,new rt({assembly:rC,components:[rj("x"in t?t.x:void 0,i.x),rj("y"in t?t.y:void 0,i.y),rj("z"in t?t.z:void 0,i.z),rj("w"in t?t.w:void 0,i.w)]})},equals:rS.equals,writer:e=>rA},controller:e=>{let t=e.value,i=e.constraint;if(!(i instanceof rt))throw d.shouldNeverHappen();return new rs(e.document,{assembly:rC,axes:t.rawValue.getComponents().map((e,t)=>{var r;return{baseStep:t$(r=i.components[t]),constraint:r,textProps:R.fromObject({draggingScale:tq(r,e),formatter:tv(tK(r,e))})}}),parser:tf,value:t,viewProps:e.viewProps})}},rI={id:"input-string",type:"input",accept:(e,t)=>{if("string"!=typeof e)return null;let i=D(t,{options:M.optional.custom(tW)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>tb,constraint:e=>(function(e){let t=[],i=tj(e.options);return i&&t.push(i),new ej(t)})(e.params),writer:e=>tz},controller:e=>{let t=e.document,i=e.value,r=e.constraint,s=r&&eK(r,eq);return s?new e1(t,{props:new R({options:s.values.value("options")}),value:i,viewProps:e.viewProps}):new e8(t,{parser:e=>e,props:R.fromObject({formatter:tE}),value:i,viewProps:e.viewProps})}},rP={monitor:{defaultInterval:200,defaultLineCount:3}},rM=m("mll");class rD{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(rM()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("textarea");i.classList.add(rM("i")),i.style.height=`calc(var(--bld-us) * ${t.lineCount})`,i.readOnly=!0,t.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.textareaElem_,t=e.scrollTop===e.scrollHeight-e.clientHeight,i=[];this.value.rawValue.forEach(e=>{void 0!==e&&i.push(this.formatter_(e))}),e.textContent=i.join("\n"),t&&(e.scrollTop=e.scrollHeight)}onValueUpdate_(){this.update_()}}class rO{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new rD(e,{formatter:t.formatter,lineCount:t.lineCount,value:this.value,viewProps:this.viewProps})}}let rN=m("sgl");class rF{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(rN()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("input");i.classList.add(rN("i")),i.readOnly=!0,i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.value.rawValue,t=e[e.length-1];this.inputElement.value=void 0!==t?this.formatter_(t):""}onValueUpdate_(){this.update_()}}class rw{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new rF(e,{formatter:t.formatter,value:this.value,viewProps:this.viewProps})}}let rL={id:"monitor-bool",type:"monitor",accept:(e,t)=>{if("boolean"!=typeof e)return null;let i=D(t,{lineCount:M.optional.number});return i?{initialValue:e,params:i}:null},binding:{reader:e=>e7},controller:e=>{var t;return 1===e.value.rawValue.length?new rw(e.document,{formatter:e9,value:e.value,viewProps:e.viewProps}):new rO(e.document,{formatter:e9,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:rP.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}},rB=m("grl");class rU{constructor(e,t){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=e.createElement("div"),this.element.classList.add(rB()),t.viewProps.bindClassModifiers(this.element),this.formatter_=t.formatter,this.props_=t.props,this.cursor_=t.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);let i=e.createElementNS(k,"svg");i.classList.add(rB("g")),i.style.height=`calc(var(--bld-us) * ${t.lineCount})`,this.element.appendChild(i),this.svgElem_=i;let r=e.createElementNS(k,"polyline");this.svgElem_.appendChild(r),this.lineElem_=r;let s=e.createElement("div");s.classList.add(rB("t"),m("tt")()),this.element.appendChild(s),this.tooltipElem_=s,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}get graphElement(){return this.svgElem_}update_(){let e=this.svgElem_.getBoundingClientRect(),t=this.value.rawValue.length-1,i=this.props_.get("minValue"),r=this.props_.get("maxValue"),s=[];this.value.rawValue.forEach((n,a)=>{if(void 0===n)return;let o=tM(a,0,t,0,e.width),l=tM(n,i,r,e.height,0);s.push([o,l].join(","))}),this.lineElem_.setAttributeNS(null,"points",s.join(" "));let n=this.tooltipElem_,a=this.value.rawValue[this.cursor_.rawValue];if(void 0===a){n.classList.remove(rB("t","a"));return}let o=tM(this.cursor_.rawValue,0,t,0,e.width),l=tM(a,i,r,e.height,0);n.style.left=`${o}px`,n.style.top=`${l}px`,n.textContent=`${this.formatter_(a)}`,n.classList.contains(rB("t","a"))||(n.classList.add(rB("t","a"),rB("t","in")),G(n),n.classList.remove(rB("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}}class rV{constructor(e,t){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props_=t.props,this.value=t.value,this.viewProps=t.viewProps,this.cursor_=A(-1),this.view=new rU(e,{cursor:this.cursor_,formatter:t.formatter,lineCount:t.lineCount,props:this.props_,value:this.value,viewProps:this.viewProps}),z(e)){let e=new tP(this.view.element);e.emitter.on("down",this.onGraphPointerDown_),e.emitter.on("move",this.onGraphPointerMove_),e.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(e){let t=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(tM(e.offsetX,0,t.width,0,this.value.rawValue.length))}onGraphPointerDown_(e){this.onGraphPointerMove_(e)}onGraphPointerMove_(e){if(!e.data.point){this.cursor_.rawValue=-1;return}this.cursor_.rawValue=Math.floor(tM(e.data.point.x,0,e.data.bounds.width,0,this.value.rawValue.length))}onGraphPointerUp_(){this.cursor_.rawValue=-1}}function rk(e){return"format"in e&&!l(e.format)?e.format:tv(2)}function rG(e){return"view"in e&&"graph"===e.view}let rz={id:"monitor-number",type:"monitor",accept:(e,t)=>{if("number"!=typeof e)return null;let i=D(t,{format:M.optional.function,lineCount:M.optional.number,max:M.optional.number,min:M.optional.number,view:M.optional.string});return i?{initialValue:e,params:i}:null},binding:{defaultBufferSize:e=>rG(e)?64:1,reader:e=>tm},controller:e=>{var t,i,r,s;return rG(e.params)?new rV(e.document,{formatter:rk(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:rP.monitor.defaultLineCount,props:R.fromObject({maxValue:null!==(i="max"in e.params?e.params.max:null)&&void 0!==i?i:100,minValue:null!==(r="min"in e.params?e.params.min:null)&&void 0!==r?r:0}),value:e.value,viewProps:e.viewProps}):1===e.value.rawValue.length?new rw(e.document,{formatter:rk(e.params),value:e.value,viewProps:e.viewProps}):new rO(e.document,{formatter:rk(e.params),lineCount:null!==(s=e.params.lineCount)&&void 0!==s?s:rP.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}},rW={id:"monitor-string",type:"monitor",accept:(e,t)=>{if("string"!=typeof e)return null;let i=D(t,{lineCount:M.optional.number,multiline:M.optional.boolean});return i?{initialValue:e,params:i}:null},binding:{reader:e=>tb},controller:e=>{var t;let i=e.value;return i.rawValue.length>1||"multiline"in e.params&&e.params.multiline?new rO(e.document,{formatter:tE,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:rP.monitor.defaultLineCount,value:i,viewProps:e.viewProps}):new rw(e.document,{formatter:tE,value:i,viewProps:e.viewProps})}};class rH{constructor(){this.pluginsMap_={blades:[],inputs:[],monitors:[]}}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(e){"blade"===e.type?this.pluginsMap_.blades.unshift(e):"input"===e.type?this.pluginsMap_.inputs.unshift(e):"monitor"===e.type&&this.pluginsMap_.monitors.unshift(e)}createInput(e,t,i){if(l(t.read()))throw new d({context:{key:t.key},type:"nomatchingcontroller"});let r=this.pluginsMap_.inputs.reduce((r,s)=>null!=r?r:function(e,t){var i;let r=e.accept(t.target.read(),t.params);if(l(r))return null;let s={target:t.target,initialValue:r.initialValue,params:r.params},n=e.binding.reader(s),a=e.binding.constraint?e.binding.constraint(s):void 0,o=A(n(r.initialValue),{constraint:a,equals:e.binding.equals}),h=new eH({reader:n,target:t.target,value:o,writer:e.binding.writer(s)}),u=M.optional.boolean(t.params.disabled).value,c=M.optional.boolean(t.params.hidden).value,d=e.controller({constraint:a,document:t.document,initialValue:r.initialValue,params:r.params,value:h.value,viewProps:L.create({disabled:u,hidden:c})});return new eo(t.document,{binding:h,blade:ee(),props:R.fromObject({label:"label"in t.params?null!==(i=M.optional.string(t.params.label).value)&&void 0!==i?i:null:t.target.key}),valueController:d})}(s,{document:e,target:t,params:i}),null);if(r)return r;throw new d({context:{key:t.key},type:"nomatchingcontroller"})}createMonitor(e,t,i){let r=this.pluginsMap_.monitors.reduce((r,s)=>null!=r?r:function(e,t){var i,r,s,n;let a=e.accept(t.target.read(),t.params);if(l(a))return null;let o={target:t.target,initialValue:a.initialValue,params:a.params},h=e.binding.reader(o),u=null!==(r=null!==(i=M.optional.number(t.params.bufferSize).value)&&void 0!==i?i:e.binding.defaultBufferSize&&e.binding.defaultBufferSize(a.params))&&void 0!==r?r:1,c=M.optional.number(t.params.interval).value,d=new eY({reader:h,target:t.target,ticker:(n=t.document,0===c?new ez:new eW(n,null!=c?c:rP.monitor.defaultInterval)),value:function(e){let t=[];return eX(t,e),A(t)}(u)}),p=M.optional.boolean(t.params.disabled).value,_=M.optional.boolean(t.params.hidden).value,f=e.controller({document:t.document,params:a.params,value:d.value,viewProps:L.create({disabled:p,hidden:_})});return new eh(t.document,{binding:d,blade:ee(),props:R.fromObject({label:"label"in t.params?null!==(s=M.optional.string(t.params.label).value)&&void 0!==s?s:null:t.target.key}),valueController:f})}(s,{document:e,params:i,target:t}),null);if(r)return r;throw new d({context:{key:t.key},type:"nomatchingcontroller"})}createBlade(e,t){let i=this.pluginsMap_.blades.reduce((i,r)=>null!=i?i:function(e,t){let i=e.accept(t.params);if(!i)return null;let r=M.optional.boolean(t.params.disabled).value,s=M.optional.boolean(t.params.hidden).value;return e.controller({blade:ee(),document:t.document,params:Object.assign(Object.assign({},i.params),{disabled:r,hidden:s}),viewProps:L.create({disabled:r,hidden:s})})}(r,{document:e,params:t}),null);if(!i)throw new d({type:"nomatchingview",context:{params:t}});return i}createBladeApi(e){if(e instanceof eo)return new ea(e);if(e instanceof eh)return new el(e);if(e instanceof eT)return new ep(e,this);let t=this.pluginsMap_.blades.reduce((t,i)=>null!=t?t:i.api({controller:e,pool:this}),null);if(!t)throw d.shouldNeverHappen();return t}}function rX(e){return rl.isObject(e)?new rl(e.x,e.y):new rl}function rY(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y)}function rj(e,t){if(!e)return;let i=[],r=rn(e,t);r&&i.push(r);let s=ra(e);return s&&i.push(s),new ej(i)}function rK(e,t){let[i,r]=e?function(e){let t=eK(e,e$);if(t)return[t.values.get("min"),t.values.get("max")];let i=eK(e,eQ);return i?[i.minValue,i.maxValue]:[void 0,void 0]}(e):[];return l(i)&&l(r)?Math.max(10*Math.abs(t$(e)),10*Math.abs(t)):Math.max(Math.abs(null!=i?i:0),Math.abs(null!=r?r:0))}function r$(e,t){return{baseStep:t$(t),constraint:t,textProps:R.fromObject({draggingScale:tq(t,e),formatter:tv(tK(t,e))})}}let rq={id:"input-point2d",type:"input",accept:(e,t)=>{if(!rl.isObject(e))return null;let i=D(t,{expanded:M.optional.boolean,picker:M.optional.custom(tH),x:M.optional.custom(tX),y:M.optional.object({inverted:M.optional.boolean,max:M.optional.number,min:M.optional.number,step:M.optional.number})});return i?{initialValue:e,params:i}:null},binding:{reader:e=>rX,constraint:e=>{var t,i;return t=e.params,i=e.initialValue,new rt({assembly:rh,components:[rj("x"in t?t.x:void 0,i.x),rj("y"in t?t.y:void 0,i.y)]})},equals:rl.equals,writer:e=>rY},controller:e=>{let t=e.document,i=e.value,r=e.constraint;if(!(r instanceof rt))throw d.shouldNeverHappen();let s="expanded"in e.params?e.params.expanded:void 0,n="picker"in e.params?e.params.picker:void 0;return new rm(t,{axes:[r$(i.rawValue.x,r.components[0]),r$(i.rawValue.y,r.components[1])],expanded:null!=s&&s,invertsY:function(e){if(!("y"in e))return!1;let t=e.y;return!!t&&"inverted"in t&&!!t.inverted}(e.params),maxValue:function(e,t){let i=t instanceof rt?t.components[0]:void 0,r=t instanceof rt?t.components[1]:void 0;return Math.max(rK(i,e.x),rK(r,e.y))}(i.rawValue,r),parser:tf,pickerLayout:null!=n?n:"popup",value:i,viewProps:e.viewProps})}};class rQ extends i{constructor(e){super(e),this.emitter_=new f,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new s(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get options(){return this.controller_.valueController.props.get("options")}set options(e){this.controller_.valueController.props.set("options",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}}class rZ extends i{constructor(e){super(e),this.emitter_=new f,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new s(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get maxValue(){return this.controller_.valueController.sliderController.props.get("maxValue")}set maxValue(e){this.controller_.valueController.sliderController.props.set("maxValue",e)}get minValue(){return this.controller_.valueController.sliderController.props.get("minValue")}set minValue(e){this.controller_.valueController.sliderController.props.set("minValue",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}}class rJ extends i{constructor(e){super(e),this.emitter_=new f,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new s(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get formatter(){return this.controller_.valueController.props.get("formatter")}set formatter(e){this.controller_.valueController.props.set("formatter",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}}let r0={id:"list",type:"blade",accept(e){let t=D(e,{options:M.required.custom(tW),value:M.required.raw,view:M.required.constant("list"),label:M.optional.string});return t?{params:t}:null},controller(e){let t=new eq(tY(e.params.options)),i=A(e.params.value,{constraint:t}),r=new e1(e.document,{props:new R({options:t.values.value("options")}),value:i,viewProps:e.viewProps});return new ey(e.document,{blade:e.blade,props:R.fromObject({label:e.params.label}),valueController:r})},api:e=>e.controller instanceof ey&&e.controller.valueController instanceof e1?new rQ(e.controller):null};class r1 extends e_{constructor(e,t){super(e,t)}get element(){return this.controller_.view.element}importPreset(e){(function(e,t){e.forEach(e=>{let i=t[e.target.presetKey];void 0!==i&&e.writer(e.target,e.reader(i))})})(this.controller_.rackController.rack.find(eo).map(e=>e.binding),e),this.refresh()}exportPreset(){return this.controller_.rackController.rack.find(eo).map(e=>e.binding.target).reduce((e,t)=>Object.assign(e,{[t.presetKey]:t.read()}),{})}refresh(){this.controller_.rackController.rack.find(eo).forEach(e=>{e.binding.read()}),this.controller_.rackController.rack.find(eh).forEach(e=>{e.binding.read()})}}class r2 extends eS{constructor(e,t){super(e,{expanded:t.expanded,blade:t.blade,props:t.props,root:!0,viewProps:t.viewProps})}}let r3={id:"slider",type:"blade",accept(e){let t=D(e,{max:M.required.number,min:M.required.number,view:M.required.constant("slider"),format:M.optional.function,label:M.optional.string,value:M.optional.number});return t?{params:t}:null},controller(e){var t,i;let r=null!==(t=e.params.value)&&void 0!==t?t:0,s=new e$({max:e.params.max,min:e.params.min}),n=new tG(e.document,{baseStep:1,parser:tf,sliderProps:new R({maxValue:s.values.value("max"),minValue:s.values.value("min")}),textProps:R.fromObject({draggingScale:tq(void 0,r),formatter:null!==(i=e.params.format)&&void 0!==i?i:tg}),value:A(r,{constraint:s}),viewProps:e.viewProps});return new ey(e.document,{blade:e.blade,props:R.fromObject({label:e.params.label}),valueController:n})},api:e=>e.controller instanceof ey&&e.controller.valueController instanceof tG?new rZ(e.controller):null},r4={id:"text",type:"blade",accept(e){let t=D(e,{parse:M.required.function,value:M.required.raw,view:M.required.constant("text"),format:M.optional.function,label:M.optional.string});return t?{params:t}:null},controller(e){var t;let i=new e8(e.document,{parser:e.params.parse,props:R.fromObject({formatter:null!==(t=e.params.format)&&void 0!==t?t:e=>String(e)}),value:A(e.params.value),viewProps:e.viewProps});return new ey(e.document,{blade:e.blade,props:R.fromObject({label:e.params.label}),valueController:i})},api:e=>e.controller instanceof ey&&e.controller.valueController instanceof e8?new rJ(e.controller):null};function r5(e,t,i){if(e.querySelector(`style[data-tp-style=${t}]`))return;let r=e.createElement("style");r.dataset.tpStyle=t,r.textContent=i,e.head.appendChild(r)}class r6 extends r1{constructor(e){var t,i;let r=null!=e?e:{},s=null!==(t=r.document)&&void 0!==t?t:globalThis.document,n=function(){let e=new rH;return[rq,rE,rR,rI,ro,re,i9,i7,t0,rL,rW,rz,Z,eC,eM,eG].forEach(t=>{e.register(t)}),e}();super(new r2(s,{expanded:r.expanded,blade:ee(),props:R.fromObject({title:r.title}),viewProps:L.create()}),n),this.pool_=n,this.containerElem_=null!==(i=r.container)&&void 0!==i?i:function(e){let t=e.createElement("div");return t.classList.add(m("dfw")()),e.body&&e.body.appendChild(t),t}(s),this.containerElem_.appendChild(this.element),this.doc_=s,this.usesDefaultWrapper_=!r.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw d.alreadyDisposed();return this.doc_}dispose(){let e=this.containerElem_;if(!e)throw d.alreadyDisposed();if(this.usesDefaultWrapper_){let t=e.parentElement;t&&t.removeChild(e)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(e){("plugin"in e?[e.plugin]:"plugins"in e?e.plugins:[]).forEach(e=>{this.pool_.register(e),this.embedPluginStyle_(e)})}embedPluginStyle_(e){e.css&&r5(this.document,`plugin-${e.id}`,e.css)}setUpDefaultPlugins_(){r5(this.document,"default",'.tp-tbiv_b,.tp-coltxtv_ms,.tp-ckbv_i,.tp-rotv_b,.tp-fldv_b,.tp-mllv_i,.tp-sglv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--elm-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--bld-us);line-height:var(--bld-us);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--bld-us);line-height:var(--bld-us);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-mllv_i,.tp-sglv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--mo-fg);height:var(--bld-us);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-mllv_i::-webkit-scrollbar,.tp-sglv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-mllv_i::-webkit-scrollbar-corner,.tp-sglv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-mllv_i::-webkit-scrollbar-thumb,.tp-sglv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-rotv{--font-family: var(--tp-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-br: var(--tp-base-border-radius, 6px);--cnt-h-p: var(--tp-container-horizontal-padding, 4px);--cnt-v-p: var(--tp-container-vertical-padding, 4px);--elm-br: var(--tp-element-border-radius, 2px);--bld-s: var(--tp-blade-spacing, 4px);--bld-us: var(--tp-blade-unit-size, 20px);--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tabv_c .tp-brkv>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-v-p))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tabv_c .tp-brkv>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--bld-s)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tabv_c .tp-brkv>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tabv_c .tp-brkv>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--elm-br);border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tabv_c .tp-brkv .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--elm-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);overflow:hidden;padding-left:var(--cnt-h-p);padding-right:calc(4px + var(--bld-us) + var(--cnt-h-p));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-h-p) + (var(--bld-us) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-v-p);padding-top:var(--cnt-v-p);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--elm-br);cursor:pointer;display:block;height:var(--bld-us);position:relative;width:var(--bld-us)}.tp-ckbv_w svg{bottom:0;display:block;height:16px;left:0;margin:auto;opacity:0;position:absolute;right:0;top:0;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--bld-us)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--bld-s);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--bld-s)}.tp-colpv_rgb{display:flex;margin-top:var(--bld-s);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-v-p);padding-top:calc(var(--cnt-v-p) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-h-p));position:absolute;right:calc(-1*var(--cnt-h-p));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--elm-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--bld-us)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--elm-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;pointer-events:none;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--elm-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;cursor:pointer;display:block;height:var(--bld-us);left:0;margin:0;outline:none;padding:0;position:absolute;top:0;width:var(--bld-us)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--elm-br);bottom:0;content:"";display:block;left:0;position:absolute;right:0;top:0}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--elm-br);color:var(--lbl-fg);cursor:pointer;height:var(--bld-us);line-height:var(--bld-us);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv.tp-fldv-not .tp-fldv_b{display:none}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--bld-us)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-h-p);padding-right:var(--cnt-h-p)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:160px}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding:0 4px}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--bld-us)*3);line-height:var(--bld-us);padding:0 4px;resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--bld-us);margin-right:4px;position:relative;width:var(--bld-us)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--bld-s);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-p2dpv{padding-left:calc(var(--bld-us) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:6px;box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:168px;padding:var(--cnt-v-p) var(--cnt-h-p);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--bld-us);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin:auto;position:absolute;right:0;top:0}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin-bottom:auto;margin-top:auto;position:absolute;right:0;top:0}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--elm-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--bld-us) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_c{padding-bottom:var(--cnt-v-p);padding-left:4px;padding-top:var(--cnt-v-p)}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-h-p) + 4px);padding-right:calc(var(--cnt-h-p) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);bottom:2px;content:"";left:0;pointer-events:none;position:absolute;right:0;top:0}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);opacity:.5;overflow:hidden;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-txtv{position:relative}.tp-txtv_i{padding:0 4px}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:-3px;position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--bld-us) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--elm-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--font-family);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--bld-us) + var(--cnt-h-p));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0}.tp-rotv.tp-rotv-not .tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}'),this.pool_.getAll().forEach(e=>{this.embedPluginStyle_(e)}),this.registerPlugin({plugins:[r3,r0,eG,r4]})}}let r8=new t("3.1.10");e.BladeApi=i,e.ButtonApi=_,e.FolderApi=e_,e.InputBindingApi=ea,e.ListApi=rQ,e.MonitorBindingApi=el,e.Pane=r6,e.SeparatorApi=eA,e.SliderApi=rZ,e.TabApi=eL,e.TabPageApi=ew,e.TextApi=rJ,e.TpChangeEvent=s,e.VERSION=r8,Object.defineProperty(e,"__esModule",{value:!0})})(t)},2917:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>o,metadata:()=>a});var r=i(5036),s=i(265),n=i.n(s);i(3440);let a={title:"sukadia.dev",description:"I code, stream, and create videos."};function o({children:e}){return r.jsx("html",{lang:"en",children:r.jsx("body",{className:n().className,children:e})})}},8187:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>s});var r=i(5036);function s(){return r.jsx("div",{className:"flex h-screen justify-center items-center",children:r.jsx("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:r.jsx("div",{className:"h-10 w-10 rounded-full bg-black"})})})}},926:(e,t,i)=>{"use strict";i.r(t),i.d(t,{$$typeof:()=>n,__esModule:()=>s,default:()=>a});let r=(0,i(6843).createProxy)(String.raw`X:\Some Useful Stuff\Applications\Web\next-sukadia.dev\app\space\page.tsx`),{__esModule:s,$$typeof:n}=r,a=r.default},7481:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>s});var r=i(337);let s=e=>[{type:"image/x-icon",sizes:"16x16",url:(0,r.fillMetadataSegment)(".",e.params,"favicon.ico")+""}]},3440:()=>{}};var t=require("../../webpack-runtime.js");t.C(e);var i=e=>t(t.s=e),r=t.X(0,[638,969,337],()=>i(8899));module.exports=r})(); \ No newline at end of file diff --git a/.next/server/app/space/page.js.nft.json b/.next/server/app/space/page.js.nft.json index 886634f..48bcd56 100644 --- a/.next/server/app/space/page.js.nft.json +++ b/.next/server/app/space/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/106.js","../../chunks/2.js","../../chunks/201.js","../../chunks/310.js","../../chunks/323.js","../../chunks/622.js","../../chunks/676.js","../../chunks/837.js","../../chunks/840.js","../../chunks/862.js","../../chunks/984.js","../../chunks/font-manifest.json","../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file +{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/329.js","../../chunks/337.js","../../chunks/638.js","../../chunks/969.js","../../chunks/font-manifest.json","../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/space/page_client-reference-manifest.js b/.next/server/app/space/page_client-reference-manifest.js index 2c62eb3..5f9b4d9 100644 --- a/.next/server/app/space/page_client-reference-manifest.js +++ b/.next/server/app/space/page_client-reference-manifest.js @@ -1 +1 @@ -globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/space/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"341":{"*":{"id":"9663","name":"*","chunks":[],"async":false}},"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx":{"id":341,"name":"*","chunks":["732","static/chunks/e1206f8c-ab5b5541f866e530.js","105","static/chunks/1f3d3139-f107a678ff6361e9.js","735","static/chunks/604a08ec-59af37265fb99b3d.js","790","static/chunks/d67c510a-e497b3cd5bf43bb4.js","116","static/chunks/537cd76e-7aba1cf7a4752418.js","173","static/chunks/173-2ffa9652644381a8.js","514","static/chunks/app/space/page-b8120f6d5470d1c7.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\loading":[]}} \ No newline at end of file +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/space/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"326":{"*":{"id":"2079","name":"*","chunks":[],"async":false}},"1778":{"*":{"id":"9295","name":"*","chunks":[],"async":false}},"1902":{"*":{"id":"3225","name":"*","chunks":[],"async":false}},"5613":{"*":{"id":"8771","name":"*","chunks":[],"async":false}},"7690":{"*":{"id":"2583","name":"*","chunks":[],"async":false}},"7831":{"*":{"id":"3982","name":"*","chunks":[],"async":false}},"7846":{"*":{"id":"2018","name":"*","chunks":[],"async":false}},"8955":{"*":{"id":"6840","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":3445,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":9989,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":326,"name":"*","chunks":["986","static/chunks/986-72006aa1051e30d3.js","931","static/chunks/app/page-8af0c2c4af65d19c.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page.tsx":{"id":7846,"name":"*","chunks":["732","static/chunks/e1206f8c-1ba69cf5e736c266.js","105","static/chunks/1f3d3139-8a75094e9a213384.js","735","static/chunks/604a08ec-edbc4bb5c67ea975.js","790","static/chunks/d67c510a-4a8f7a6a0c1c3e2a.js","116","static/chunks/537cd76e-7aba1cf7a4752418.js","973","static/chunks/973-5f61489a82d0bbab.js","514","static/chunks/app/space/page-185302d4e0f787e8.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\page":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\space\\loading":[]}} \ No newline at end of file diff --git a/.next/server/app/wiston.html b/.next/server/app/wiston.html index 609d129..1fe4a85 100644 --- a/.next/server/app/wiston.html +++ b/.next/server/app/wiston.html @@ -1 +1 @@ -wiston
‎ -+=-:. -
‎ .*%#%#%%%%#*+-. ++= .:-==:
‎ =%%########%##%%%*-. ++-# .-+*%%%###%#-
‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#.
‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%=
‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%#
‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%:
‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%-
‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%-
‎ %%###################%*--------#**********#%%######################%%#%%%######%@-
‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@-
‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@:
‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%.
‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%%
‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%*
‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%=
‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%.
‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%#
‎ ######%%%%%%%######################################################%@%######%%#%#%##########%-
‎ %%#%%%%%%%%########################################################%@%#########%%%###########%
‎ .%%%%%%%%%###########################################################%###########%@###########%+
‎ =#%%%%%%########################################################################################%
‎ +%%%%%############################################%%#%############################################%-
‎ =%%%%##########%#########################################%%##########################################%%**++======+**#%
‎ -#%%%#########################################################%####################################%###################%.
‎ *%%%#####################################################################################################%###%##########%
‎ .#%###################################################################%##%###############%###############################%#
‎ .+%##############################################################################%#########################################%=
‎ .+%#########################################################################################################################%%
‎ +%##########################################################################################################################%%.
‎ =%#################################################################################%%@%%#####################################%%:
‎ -#################################################################################%@@@%#######################################%%.
‎ :################################################################################%@@#%########################################%%+
‎ +%#############################################################################%@@#- +######################################%+.
‎ -#############################################################################%@@#= :*#################################%*-
‎ =%##########################################################################%@%*- :==- +################################%.
‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################.
‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+:
‎ : .-+####################################################################: #%@+--- =############%#=
‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=:
‎ .:. :-+*############################################################: :+*+- - ....
‎ ::. .:=+*########################################################=. =
‎ ::. .:-=*####################################################*: .-
‎ ::. .:-=+*##########################################*=: .-
‎ .:: ..:--==++***################***++===-::. .-
‎ :-. ..... ..:::. .=
‎ .::. .-+****+====+==: +
‎ :::. .-+#*=:. . +
‎ .::. .=*#+: .::::. =:
‎ .... =*=. ::::: .+
‎ .:::. ::::. +
‎ .:::::.. .:::::. .=
‎ .::::::::::::.......::::::::::+-. =.
‎ ...... .+. +
‎ .::+ .-
‎ .::. +. .:
‎ -: :-. ::
‎ -- .-=: .:::. :.
‎ --.-=:. .---. :.
‎ -=. ==: :=-. :.
‎ :+: :-+. .-=: -
‎ :+- .=-. :=-. -
‎ .+- :-- :=- :. -
‎ .+=. = -=: :: .-
‎ .+=. =:-: -+: .-. .-
‎ .==. .:::::--:.=+ .=: :- .:
‎ ::=:---: .---. .:--+: .-. ::
‎ --. .+-:. .--: :- :.
‎ :- .. .:: .-. -.
‎ :: : .=. :: -.
‎ = .: .+: ::. -.
‎ =. - +. .:. -.
‎ + - .+ :: ::
‎ + . :-. + .:. ::
‎ + .: :- =. .:. .-
‎ -. .: :- .--. .:: .-
‎ = ::. .= == :: .-
‎ :: ::: :: .:-- .:. -
‎ -. .:::: = :---. .:. :.
‎ :. .:::::::=:--:. :: :.
‎ .:. :-= .:
‎ .:: .-. .:
‎ ::. .-: -
‎ .::. :-. =
‎ :::: .-. .=
‎ ::::. :: .-
‎ .::::::::::::. :-
‎ - -:
‎ - =
‎ ::::-----:::::=. =
‎ ::--:. .: .:
‎ :--:. : :
‎ :--. .-: :
‎ ----------. .==. -
‎ = -+. .-
‎ =. .+- =
‎ +. .*: +
‎ .::--: .*. +
‎ .- .+. :-
‎ :: +. --:
‎ -. :- .---::::.
‎ .: + .-
‎ = .- .-
‎ -. -. :=
‎ = = .-=:
‎ -: - .=---:
‎ = -. .--:-
‎ = ....:::-= .=.
‎ ..::::......:::::::::::. + .:.. .::::. :==
‎ :::::::. .::-::::: = .... :---:. .:-==:
‎ .- .. .:-::: = .:.. .:--:. --
‎ .:=. :+ .:. ::::. .*
‎ -: :: ::. :::: *.
‎ .: -. .-. .. .:. --
‎ - .-: .=. .= .=- =. .+
‎ - -=. .=. -. :+. +: .+
‎ - =- .=. = :*. +: +
‎ .: := -: - .*. :+ =.
‎ :. * .-. + +: *. .-
‎ :: + :-. --:. .* .* ::.
‎ ::. + --. ...-:. := .+ :-:
‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:.
‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--:
‎ .:::::::::... ..... + .... .:--::
‎ ..::::::::..:- .:..:::::. .::-:::::
\ No newline at end of file +wiston
‎ -+=-:. -
‎ .*%#%#%%%%#*+-. ++= .:-==:
‎ =%%########%##%%%*-. ++-# .-+*%%%###%#-
‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#.
‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%=
‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%#
‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%:
‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%-
‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%-
‎ %%###################%*--------#**********#%%######################%%#%%%######%@-
‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@-
‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@:
‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%.
‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%%
‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%*
‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%=
‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%.
‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%#
‎ ######%%%%%%%######################################################%@%######%%#%#%##########%-
‎ %%#%%%%%%%%########################################################%@%#########%%%###########%
‎ .%%%%%%%%%###########################################################%###########%@###########%+
‎ =#%%%%%%########################################################################################%
‎ +%%%%%############################################%%#%############################################%-
‎ =%%%%##########%#########################################%%##########################################%%**++======+**#%
‎ -#%%%#########################################################%####################################%###################%.
‎ *%%%#####################################################################################################%###%##########%
‎ .#%###################################################################%##%###############%###############################%#
‎ .+%##############################################################################%#########################################%=
‎ .+%#########################################################################################################################%%
‎ +%##########################################################################################################################%%.
‎ =%#################################################################################%%@%%#####################################%%:
‎ -#################################################################################%@@@%#######################################%%.
‎ :################################################################################%@@#%########################################%%+
‎ +%#############################################################################%@@#- +######################################%+.
‎ -#############################################################################%@@#= :*#################################%*-
‎ =%##########################################################################%@%*- :==- +################################%.
‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################.
‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+:
‎ : .-+####################################################################: #%@+--- =############%#=
‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=:
‎ .:. :-+*############################################################: :+*+- - ....
‎ ::. .:=+*########################################################=. =
‎ ::. .:-=*####################################################*: .-
‎ ::. .:-=+*##########################################*=: .-
‎ .:: ..:--==++***################***++===-::. .-
‎ :-. ..... ..:::. .=
‎ .::. .-+****+====+==: +
‎ :::. .-+#*=:. . +
‎ .::. .=*#+: .::::. =:
‎ .... =*=. ::::: .+
‎ .:::. ::::. +
‎ .:::::.. .:::::. .=
‎ .::::::::::::.......::::::::::+-. =.
‎ ...... .+. +
‎ .::+ .-
‎ .::. +. .:
‎ -: :-. ::
‎ -- .-=: .:::. :.
‎ --.-=:. .---. :.
‎ -=. ==: :=-. :.
‎ :+: :-+. .-=: -
‎ :+- .=-. :=-. -
‎ .+- :-- :=- :. -
‎ .+=. = -=: :: .-
‎ .+=. =:-: -+: .-. .-
‎ .==. .:::::--:.=+ .=: :- .:
‎ ::=:---: .---. .:--+: .-. ::
‎ --. .+-:. .--: :- :.
‎ :- .. .:: .-. -.
‎ :: : .=. :: -.
‎ = .: .+: ::. -.
‎ =. - +. .:. -.
‎ + - .+ :: ::
‎ + . :-. + .:. ::
‎ + .: :- =. .:. .-
‎ -. .: :- .--. .:: .-
‎ = ::. .= == :: .-
‎ :: ::: :: .:-- .:. -
‎ -. .:::: = :---. .:. :.
‎ :. .:::::::=:--:. :: :.
‎ .:. :-= .:
‎ .:: .-. .:
‎ ::. .-: -
‎ .::. :-. =
‎ :::: .-. .=
‎ ::::. :: .-
‎ .::::::::::::. :-
‎ - -:
‎ - =
‎ ::::-----:::::=. =
‎ ::--:. .: .:
‎ :--:. : :
‎ :--. .-: :
‎ ----------. .==. -
‎ = -+. .-
‎ =. .+- =
‎ +. .*: +
‎ .::--: .*. +
‎ .- .+. :-
‎ :: +. --:
‎ -. :- .---::::.
‎ .: + .-
‎ = .- .-
‎ -. -. :=
‎ = = .-=:
‎ -: - .=---:
‎ = -. .--:-
‎ = ....:::-= .=.
‎ ..::::......:::::::::::. + .:.. .::::. :==
‎ :::::::. .::-::::: = .... :---:. .:-==:
‎ .- .. .:-::: = .:.. .:--:. --
‎ .:=. :+ .:. ::::. .*
‎ -: :: ::. :::: *.
‎ .: -. .-. .. .:. --
‎ - .-: .=. .= .=- =. .+
‎ - -=. .=. -. :+. +: .+
‎ - =- .=. = :*. +: +
‎ .: := -: - .*. :+ =.
‎ :. * .-. + +: *. .-
‎ :: + :-. --:. .* .* ::.
‎ ::. + --. ...-:. := .+ :-:
‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:.
‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--:
‎ .:::::::::... ..... + .... .:--::
‎ ..::::::::..:- .:..:::::. .::-:::::
\ No newline at end of file diff --git a/.next/server/app/wiston.rsc b/.next/server/app/wiston.rsc index bbf0228..1042e73 100644 --- a/.next/server/app/wiston.rsc +++ b/.next/server/app/wiston.rsc @@ -1,7 +1,5 @@ -1:HL["/_next/static/css/1d2d59615145af7d.css","style",{"crossOrigin":""}] -0:["P9X42g8nWZ62i2biioMqg",[[["",{"children":["wiston",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],"$L2",[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L3"]]]] -4:I[6954,[],""] -5:I[7264,[],""] -2:[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"childProp":{"current":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","wiston","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","childProp":{"current":["$L6",["$","main",null,{"className":"flex flex-col items-center","children":["$","span",null,{"className":"whitespace-pre-wrap font-mono text-[0.2rem] leading-[0.25rem]","children":["‎ -+=-:. - ",["$","br",null,{}],"‎ .*%#%#%%%%#*+-. ++= .:-==: ",["$","br",null,{}],"‎ =%%########%##%%%*-. ++-# .-+*%%%###%#- ",["$","br",null,{}],"‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#. ",["$","br",null,{}],"‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%= ",["$","br",null,{}],"‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%# ",["$","br",null,{}],"‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%: ",["$","br",null,{}],"‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%- ",["$","br",null,{}],"‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%- ",["$","br",null,{}],"‎ %%###################%*--------#**********#%%######################%%#%%%######%@- ",["$","br",null,{}],"‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@- ",["$","br",null,{}],"‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@: ",["$","br",null,{}],"‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%. ",["$","br",null,{}],"‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%% ",["$","br",null,{}],"‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%* ",["$","br",null,{}],"‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%= ",["$","br",null,{}],"‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%. ",["$","br",null,{}],"‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%# ",["$","br",null,{}],"‎ ######%%%%%%%######################################################%@%######%%#%#%##########%- ",["$","br",null,{}],"‎ %%#%%%%%%%%########################################################%@%#########%%%###########% ",["$","br",null,{}],"‎ .%%%%%%%%%###########################################################%###########%@###########%+ ",["$","br",null,{}],"‎ =#%%%%%%########################################################################################% ",["$","br",null,{}],"‎ +%%%%%############################################%%#%############################################%- ",["$","br",null,{}],"‎ =%%%%##########%#########################################%%##########################################%%**++======+**#% ",["$","br",null,{}],"‎ -#%%%#########################################################%####################################%###################%. ",["$","br",null,{}],"‎ *%%%#####################################################################################################%###%##########% ",["$","br",null,{}],"‎ .#%###################################################################%##%###############%###############################%# ",["$","br",null,{}],"‎ .+%##############################################################################%#########################################%= ",["$","br",null,{}],"‎ .+%#########################################################################################################################%% ",["$","br",null,{}],"‎ +%##########################################################################################################################%%. ",["$","br",null,{}],"‎ =%#################################################################################%%@%%#####################################%%: ",["$","br",null,{}],"‎ -#################################################################################%@@@%#######################################%%. ",["$","br",null,{}],"‎ :################################################################################%@@#%########################################%%+ ",["$","br",null,{}],"‎ +%#############################################################################%@@#- +######################################%+. ",["$","br",null,{}],"‎ -#############################################################################%@@#= :*#################################%*- ",["$","br",null,{}],"‎ =%##########################################################################%@%*- :==- +################################%. ",["$","br",null,{}],"‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################. ",["$","br",null,{}],"‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+: ",["$","br",null,{}],"‎ : .-+####################################################################: #%@+--- =############%#= ",["$","br",null,{}],"‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=: ",["$","br",null,{}],"‎ .:. :-+*############################################################: :+*+- - .... ",["$","br",null,{}],"‎ ::. .:=+*########################################################=. = ",["$","br",null,{}],"‎ ::. .:-=*####################################################*: .- ",["$","br",null,{}],"‎ ::. .:-=+*##########################################*=: .- ",["$","br",null,{}],"‎ .:: ..:--==++***################***++===-::. .- ",["$","br",null,{}],"‎ :-. ..... ..:::. .= ",["$","br",null,{}],"‎ .::. .-+****+====+==: + ",["$","br",null,{}],"‎ :::. .-+#*=:. . + ",["$","br",null,{}],"‎ .::. .=*#+: .::::. =: ",["$","br",null,{}],"‎ .... =*=. ::::: .+ ",["$","br",null,{}],"‎ .:::. ::::. + ",["$","br",null,{}],"‎ .:::::.. .:::::. .= ",["$","br",null,{}],"‎ .::::::::::::.......::::::::::+-. =. ",["$","br",null,{}],"‎ ...... .+. + ",["$","br",null,{}],"‎ .::+ .- ",["$","br",null,{}],"‎ .::. +. .: ",["$","br",null,{}],"‎ -: :-. :: ",["$","br",null,{}],"‎ -- .-=: .:::. :. ",["$","br",null,{}],"‎ --.-=:. .---. :. ",["$","br",null,{}],"‎ -=. ==: :=-. :. ",["$","br",null,{}],"‎ :+: :-+. .-=: - ",["$","br",null,{}],"‎ :+- .=-. :=-. - ",["$","br",null,{}],"‎ .+- :-- :=- :. - ",["$","br",null,{}],"‎ .+=. = -=: :: .- ",["$","br",null,{}],"‎ .+=. =:-: -+: .-. .- ",["$","br",null,{}],"‎ .==. .:::::--:.=+ .=: :- .: ",["$","br",null,{}],"‎ ::=:---: .---. .:--+: .-. :: ",["$","br",null,{}],"‎ --. .+-:. .--: :- :. ",["$","br",null,{}],"‎ :- .. .:: .-. -. ",["$","br",null,{}],"‎ :: : .=. :: -. ",["$","br",null,{}],"‎ = .: .+: ::. -. ",["$","br",null,{}],"‎ =. - +. .:. -. ",["$","br",null,{}],"‎ + - .+ :: :: ",["$","br",null,{}],"‎ + . :-. + .:. :: ",["$","br",null,{}],"‎ + .: :- =. .:. .- ",["$","br",null,{}],"‎ -. .: :- .--. .:: .- ",["$","br",null,{}],"‎ = ::. .= == :: .- ",["$","br",null,{}],"‎ :: ::: :: .:-- .:. - ",["$","br",null,{}],"‎ -. .:::: = :---. .:. :. ",["$","br",null,{}],"‎ :. .:::::::=:--:. :: :. ",["$","br",null,{}],"‎ .:. :-= .: ",["$","br",null,{}],"‎ .:: .-. .: ",["$","br",null,{}],"‎ ::. .-: - ",["$","br",null,{}],"‎ .::. :-. = ",["$","br",null,{}],"‎ :::: .-. .= ",["$","br",null,{}],"‎ ::::. :: .- ",["$","br",null,{}],"‎ .::::::::::::. :- ",["$","br",null,{}],"‎ - -: ",["$","br",null,{}],"‎ - = ",["$","br",null,{}],"‎ ::::-----:::::=. = ",["$","br",null,{}],"‎ ::--:. .: .: ",["$","br",null,{}],"‎ :--:. : : ",["$","br",null,{}],"‎ :--. .-: : ",["$","br",null,{}],"‎ ----------. .==. - ",["$","br",null,{}],"‎ = -+. .- ",["$","br",null,{}],"‎ =. .+- = ",["$","br",null,{}],"‎ +. .*: + ",["$","br",null,{}],"‎ .::--: .*. + ",["$","br",null,{}],"‎ .- .+. :- ",["$","br",null,{}],"‎ :: +. --: ",["$","br",null,{}],"‎ -. :- .---::::. ",["$","br",null,{}],"‎ .: + .-",["$","br",null,{}],"‎ = .- .-",["$","br",null,{}],"‎ -. -. :=",["$","br",null,{}],"‎ = = .-=: ",["$","br",null,{}],"‎ -: - .=---: ",["$","br",null,{}],"‎ = -. .--:- ",["$","br",null,{}],"‎ = ....:::-= .=. ",["$","br",null,{}],"‎ ..::::......:::::::::::. + .:.. .::::. :== ",["$","br",null,{}],"‎ :::::::. .::-::::: = .... :---:. .:-==: ",["$","br",null,{}],"‎ .- .. .:-::: = .:.. .:--:. -- ",["$","br",null,{}],"‎ .:=. :+ .:. ::::. .* ",["$","br",null,{}],"‎ -: :: ::. :::: *. ",["$","br",null,{}],"‎ .: -. .-. .. .:. -- ",["$","br",null,{}],"‎ - .-: .=. .= .=- =. .+ ",["$","br",null,{}],"‎ - -=. .=. -. :+. +: .+ ",["$","br",null,{}],"‎ - =- .=. = :*. +: + ",["$","br",null,{}],"‎ .: := -: - .*. :+ =. ",["$","br",null,{}],"‎ :. * .-. + +: *. .- ",["$","br",null,{}],"‎ :: + :-. --:. .* .* ::. ",["$","br",null,{}],"‎ ::. + --. ...-:. := .+ :-: ",["$","br",null,{}],"‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:. ",["$","br",null,{}],"‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--: ",["$","br",null,{}],"‎ .:::::::::... ..... + .... .:--:: ",["$","br",null,{}],"‎ ..::::::::..:- .:..:::::. .::-::::: ",["$","br",null,{}]]}]}],null],"segment":"__PAGE__"},"styles":null}],"segment":"wiston"},"styles":null}]}]}],null] -3:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"wiston"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] -6:null +2:I[5613,[],""] +3:I[1778,[],""] +0:["xSz9x0FW88Rb7utFdR6Fp",[[["",{"children":["wiston",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["wiston",{"children":["__PAGE__",{},["$L1",["$","main",null,{"className":"flex flex-col items-center","children":["$","span",null,{"className":"whitespace-pre-wrap font-mono text-[0.2rem] leading-[0.25rem]","children":["‎ -+=-:. - ",["$","br",null,{}],"‎ .*%#%#%%%%#*+-. ++= .:-==: ",["$","br",null,{}],"‎ =%%########%##%%%*-. ++-# .-+*%%%###%#- ",["$","br",null,{}],"‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#. ",["$","br",null,{}],"‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%= ",["$","br",null,{}],"‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%# ",["$","br",null,{}],"‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%: ",["$","br",null,{}],"‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%- ",["$","br",null,{}],"‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%- ",["$","br",null,{}],"‎ %%###################%*--------#**********#%%######################%%#%%%######%@- ",["$","br",null,{}],"‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@- ",["$","br",null,{}],"‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@: ",["$","br",null,{}],"‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%. ",["$","br",null,{}],"‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%% ",["$","br",null,{}],"‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%* ",["$","br",null,{}],"‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%= ",["$","br",null,{}],"‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%. ",["$","br",null,{}],"‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%# ",["$","br",null,{}],"‎ ######%%%%%%%######################################################%@%######%%#%#%##########%- ",["$","br",null,{}],"‎ %%#%%%%%%%%########################################################%@%#########%%%###########% ",["$","br",null,{}],"‎ .%%%%%%%%%###########################################################%###########%@###########%+ ",["$","br",null,{}],"‎ =#%%%%%%########################################################################################% ",["$","br",null,{}],"‎ +%%%%%############################################%%#%############################################%- ",["$","br",null,{}],"‎ =%%%%##########%#########################################%%##########################################%%**++======+**#% ",["$","br",null,{}],"‎ -#%%%#########################################################%####################################%###################%. ",["$","br",null,{}],"‎ *%%%#####################################################################################################%###%##########% ",["$","br",null,{}],"‎ .#%###################################################################%##%###############%###############################%# ",["$","br",null,{}],"‎ .+%##############################################################################%#########################################%= ",["$","br",null,{}],"‎ .+%#########################################################################################################################%% ",["$","br",null,{}],"‎ +%##########################################################################################################################%%. ",["$","br",null,{}],"‎ =%#################################################################################%%@%%#####################################%%: ",["$","br",null,{}],"‎ -#################################################################################%@@@%#######################################%%. ",["$","br",null,{}],"‎ :################################################################################%@@#%########################################%%+ ",["$","br",null,{}],"‎ +%#############################################################################%@@#- +######################################%+. ",["$","br",null,{}],"‎ -#############################################################################%@@#= :*#################################%*- ",["$","br",null,{}],"‎ =%##########################################################################%@%*- :==- +################################%. ",["$","br",null,{}],"‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################. ",["$","br",null,{}],"‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+: ",["$","br",null,{}],"‎ : .-+####################################################################: #%@+--- =############%#= ",["$","br",null,{}],"‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=: ",["$","br",null,{}],"‎ .:. :-+*############################################################: :+*+- - .... ",["$","br",null,{}],"‎ ::. .:=+*########################################################=. = ",["$","br",null,{}],"‎ ::. .:-=*####################################################*: .- ",["$","br",null,{}],"‎ ::. .:-=+*##########################################*=: .- ",["$","br",null,{}],"‎ .:: ..:--==++***################***++===-::. .- ",["$","br",null,{}],"‎ :-. ..... ..:::. .= ",["$","br",null,{}],"‎ .::. .-+****+====+==: + ",["$","br",null,{}],"‎ :::. .-+#*=:. . + ",["$","br",null,{}],"‎ .::. .=*#+: .::::. =: ",["$","br",null,{}],"‎ .... =*=. ::::: .+ ",["$","br",null,{}],"‎ .:::. ::::. + ",["$","br",null,{}],"‎ .:::::.. .:::::. .= ",["$","br",null,{}],"‎ .::::::::::::.......::::::::::+-. =. ",["$","br",null,{}],"‎ ...... .+. + ",["$","br",null,{}],"‎ .::+ .- ",["$","br",null,{}],"‎ .::. +. .: ",["$","br",null,{}],"‎ -: :-. :: ",["$","br",null,{}],"‎ -- .-=: .:::. :. ",["$","br",null,{}],"‎ --.-=:. .---. :. ",["$","br",null,{}],"‎ -=. ==: :=-. :. ",["$","br",null,{}],"‎ :+: :-+. .-=: - ",["$","br",null,{}],"‎ :+- .=-. :=-. - ",["$","br",null,{}],"‎ .+- :-- :=- :. - ",["$","br",null,{}],"‎ .+=. = -=: :: .- ",["$","br",null,{}],"‎ .+=. =:-: -+: .-. .- ",["$","br",null,{}],"‎ .==. .:::::--:.=+ .=: :- .: ",["$","br",null,{}],"‎ ::=:---: .---. .:--+: .-. :: ",["$","br",null,{}],"‎ --. .+-:. .--: :- :. ",["$","br",null,{}],"‎ :- .. .:: .-. -. ",["$","br",null,{}],"‎ :: : .=. :: -. ",["$","br",null,{}],"‎ = .: .+: ::. -. ",["$","br",null,{}],"‎ =. - +. .:. -. ",["$","br",null,{}],"‎ + - .+ :: :: ",["$","br",null,{}],"‎ + . :-. + .:. :: ",["$","br",null,{}],"‎ + .: :- =. .:. .- ",["$","br",null,{}],"‎ -. .: :- .--. .:: .- ",["$","br",null,{}],"‎ = ::. .= == :: .- ",["$","br",null,{}],"‎ :: ::: :: .:-- .:. - ",["$","br",null,{}],"‎ -. .:::: = :---. .:. :. ",["$","br",null,{}],"‎ :. .:::::::=:--:. :: :. ",["$","br",null,{}],"‎ .:. :-= .: ",["$","br",null,{}],"‎ .:: .-. .: ",["$","br",null,{}],"‎ ::. .-: - ",["$","br",null,{}],"‎ .::. :-. = ",["$","br",null,{}],"‎ :::: .-. .= ",["$","br",null,{}],"‎ ::::. :: .- ",["$","br",null,{}],"‎ .::::::::::::. :- ",["$","br",null,{}],"‎ - -: ",["$","br",null,{}],"‎ - = ",["$","br",null,{}],"‎ ::::-----:::::=. = ",["$","br",null,{}],"‎ ::--:. .: .: ",["$","br",null,{}],"‎ :--:. : : ",["$","br",null,{}],"‎ :--. .-: : ",["$","br",null,{}],"‎ ----------. .==. - ",["$","br",null,{}],"‎ = -+. .- ",["$","br",null,{}],"‎ =. .+- = ",["$","br",null,{}],"‎ +. .*: + ",["$","br",null,{}],"‎ .::--: .*. + ",["$","br",null,{}],"‎ .- .+. :- ",["$","br",null,{}],"‎ :: +. --: ",["$","br",null,{}],"‎ -. :- .---::::. ",["$","br",null,{}],"‎ .: + .-",["$","br",null,{}],"‎ = .- .-",["$","br",null,{}],"‎ -. -. :=",["$","br",null,{}],"‎ = = .-=: ",["$","br",null,{}],"‎ -: - .=---: ",["$","br",null,{}],"‎ = -. .--:- ",["$","br",null,{}],"‎ = ....:::-= .=. ",["$","br",null,{}],"‎ ..::::......:::::::::::. + .:.. .::::. :== ",["$","br",null,{}],"‎ :::::::. .::-::::: = .... :---:. .:-==: ",["$","br",null,{}],"‎ .- .. .:-::: = .:.. .:--:. -- ",["$","br",null,{}],"‎ .:=. :+ .:. ::::. .* ",["$","br",null,{}],"‎ -: :: ::. :::: *. ",["$","br",null,{}],"‎ .: -. .-. .. .:. -- ",["$","br",null,{}],"‎ - .-: .=. .= .=- =. .+ ",["$","br",null,{}],"‎ - -=. .=. -. :+. +: .+ ",["$","br",null,{}],"‎ - =- .=. = :*. +: + ",["$","br",null,{}],"‎ .: := -: - .*. :+ =. ",["$","br",null,{}],"‎ :. * .-. + +: *. .- ",["$","br",null,{}],"‎ :: + :-. --:. .* .* ::. ",["$","br",null,{}],"‎ ::. + --. ...-:. := .+ :-: ",["$","br",null,{}],"‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:. ",["$","br",null,{}],"‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--: ",["$","br",null,{}],"‎ .:::::::::... ..... + .... .:--:: ",["$","br",null,{}],"‎ ..::::::::..:- .:..:::::. .::-::::: ",["$","br",null,{}]]}]}],null]]},["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children","wiston","children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined","styles":null}]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L2",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"styles":null}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/1d2d59615145af7d.css","precedence":"next","crossOrigin":""}]],"$L4"]]]] +4:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"wiston"}],["$","meta","3",{"name":"description","content":"I code, stream, and create videos."}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}]] +1:null diff --git a/.next/server/app/wiston/page.js b/.next/server/app/wiston/page.js index 8327831..32084ca 100644 --- a/.next/server/app/wiston/page.js +++ b/.next/server/app/wiston/page.js @@ -1 +1 @@ -(()=>{var s={};s.id=619,s.ids=[619],s.modules={5403:s=>{"use strict";s.exports=require("next/dist/client/components/request-async-storage.external")},4749:s=>{"use strict";s.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:s=>{"use strict";s.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:s=>{"use strict";s.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:s=>{"use strict";s.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:s=>{"use strict";s.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:s=>{"use strict";s.exports=require("path")},7310:s=>{"use strict";s.exports=require("url")},1663:(s,r,e)=>{"use strict";e.r(r),e.d(r,{GlobalError:()=>j.a,__next_app__:()=>p,originalPathname:()=>l,pages:()=>o,routeModule:()=>u,tree:()=>i});var x=e(7096),t=e(6132),b=e(7284),j=e.n(b),a=e(2564),n={};for(let s in a)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(s)&&(n[s]=()=>a[s]);e.d(r,n);let i=["",{children:["wiston",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(e.bind(e,5410)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx"]}]},{metadata:{icon:[async s=>(await Promise.resolve().then(e.bind(e,7481))).default(s)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(e.bind(e,5345)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(e.t.bind(e,9291,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async s=>(await Promise.resolve().then(e.bind(e,7481))).default(s)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],o=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx"],l="/wiston/page",p={require:e,loadChunk:()=>Promise.resolve()},u=new x.AppPageRouteModule({definition:{kind:t.x.APP_PAGE,page:"/wiston/page",pathname:"/wiston",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:i}})},5303:()=>{},5410:(s,r,e)=>{"use strict";e.r(r),e.d(r,{default:()=>Wiston,metadata:()=>t});var x=e(4656);let t={title:"wiston"};function Wiston(){return x.jsx("main",{className:"flex flex-col items-center",children:(0,x.jsxs)("span",{className:"whitespace-pre-wrap font-mono text-[0.2rem] leading-[0.25rem]",children:["‎ -+=-:. - ",x.jsx("br",{}),"‎ .*%#%#%%%%#*+-. ++= .:-==: ",x.jsx("br",{}),"‎ =%%########%##%%%*-. ++-# .-+*%%%###%#- ",x.jsx("br",{}),"‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#. ",x.jsx("br",{}),"‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%= ",x.jsx("br",{}),"‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%# ",x.jsx("br",{}),"‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%: ",x.jsx("br",{}),"‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%- ",x.jsx("br",{}),"‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%- ",x.jsx("br",{}),"‎ %%###################%*--------#**********#%%######################%%#%%%######%@- ",x.jsx("br",{}),"‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@- ",x.jsx("br",{}),"‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@: ",x.jsx("br",{}),"‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%. ",x.jsx("br",{}),"‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%% ",x.jsx("br",{}),"‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%* ",x.jsx("br",{}),"‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%= ",x.jsx("br",{}),"‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%. ",x.jsx("br",{}),"‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%# ",x.jsx("br",{}),"‎ ######%%%%%%%######################################################%@%######%%#%#%##########%- ",x.jsx("br",{}),"‎ %%#%%%%%%%%########################################################%@%#########%%%###########% ",x.jsx("br",{}),"‎ .%%%%%%%%%###########################################################%###########%@###########%+ ",x.jsx("br",{}),"‎ =#%%%%%%########################################################################################% ",x.jsx("br",{}),"‎ +%%%%%############################################%%#%############################################%- ",x.jsx("br",{}),"‎ =%%%%##########%#########################################%%##########################################%%**++======+**#% ",x.jsx("br",{}),"‎ -#%%%#########################################################%####################################%###################%. ",x.jsx("br",{}),"‎ *%%%#####################################################################################################%###%##########% ",x.jsx("br",{}),"‎ .#%###################################################################%##%###############%###############################%# ",x.jsx("br",{}),"‎ .+%##############################################################################%#########################################%= ",x.jsx("br",{}),"‎ .+%#########################################################################################################################%% ",x.jsx("br",{}),"‎ +%##########################################################################################################################%%. ",x.jsx("br",{}),"‎ =%#################################################################################%%@%%#####################################%%: ",x.jsx("br",{}),"‎ -#################################################################################%@@@%#######################################%%. ",x.jsx("br",{}),"‎ :################################################################################%@@#%########################################%%+ ",x.jsx("br",{}),"‎ +%#############################################################################%@@#- +######################################%+. ",x.jsx("br",{}),"‎ -#############################################################################%@@#= :*#################################%*- ",x.jsx("br",{}),"‎ =%##########################################################################%@%*- :==- +################################%. ",x.jsx("br",{}),"‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################. ",x.jsx("br",{}),"‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+: ",x.jsx("br",{}),"‎ : .-+####################################################################: #%@+--- =############%#= ",x.jsx("br",{}),"‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=: ",x.jsx("br",{}),"‎ .:. :-+*############################################################: :+*+- - .... ",x.jsx("br",{}),"‎ ::. .:=+*########################################################=. = ",x.jsx("br",{}),"‎ ::. .:-=*####################################################*: .- ",x.jsx("br",{}),"‎ ::. .:-=+*##########################################*=: .- ",x.jsx("br",{}),"‎ .:: ..:--==++***################***++===-::. .- ",x.jsx("br",{}),"‎ :-. ..... ..:::. .= ",x.jsx("br",{}),"‎ .::. .-+****+====+==: + ",x.jsx("br",{}),"‎ :::. .-+#*=:. . + ",x.jsx("br",{}),"‎ .::. .=*#+: .::::. =: ",x.jsx("br",{}),"‎ .... =*=. ::::: .+ ",x.jsx("br",{}),"‎ .:::. ::::. + ",x.jsx("br",{}),"‎ .:::::.. .:::::. .= ",x.jsx("br",{}),"‎ .::::::::::::.......::::::::::+-. =. ",x.jsx("br",{}),"‎ ...... .+. + ",x.jsx("br",{}),"‎ .::+ .- ",x.jsx("br",{}),"‎ .::. +. .: ",x.jsx("br",{}),"‎ -: :-. :: ",x.jsx("br",{}),"‎ -- .-=: .:::. :. ",x.jsx("br",{}),"‎ --.-=:. .---. :. ",x.jsx("br",{}),"‎ -=. ==: :=-. :. ",x.jsx("br",{}),"‎ :+: :-+. .-=: - ",x.jsx("br",{}),"‎ :+- .=-. :=-. - ",x.jsx("br",{}),"‎ .+- :-- :=- :. - ",x.jsx("br",{}),"‎ .+=. = -=: :: .- ",x.jsx("br",{}),"‎ .+=. =:-: -+: .-. .- ",x.jsx("br",{}),"‎ .==. .:::::--:.=+ .=: :- .: ",x.jsx("br",{}),"‎ ::=:---: .---. .:--+: .-. :: ",x.jsx("br",{}),"‎ --. .+-:. .--: :- :. ",x.jsx("br",{}),"‎ :- .. .:: .-. -. ",x.jsx("br",{}),"‎ :: : .=. :: -. ",x.jsx("br",{}),"‎ = .: .+: ::. -. ",x.jsx("br",{}),"‎ =. - +. .:. -. ",x.jsx("br",{}),"‎ + - .+ :: :: ",x.jsx("br",{}),"‎ + . :-. + .:. :: ",x.jsx("br",{}),"‎ + .: :- =. .:. .- ",x.jsx("br",{}),"‎ -. .: :- .--. .:: .- ",x.jsx("br",{}),"‎ = ::. .= == :: .- ",x.jsx("br",{}),"‎ :: ::: :: .:-- .:. - ",x.jsx("br",{}),"‎ -. .:::: = :---. .:. :. ",x.jsx("br",{}),"‎ :. .:::::::=:--:. :: :. ",x.jsx("br",{}),"‎ .:. :-= .: ",x.jsx("br",{}),"‎ .:: .-. .: ",x.jsx("br",{}),"‎ ::. .-: - ",x.jsx("br",{}),"‎ .::. :-. = ",x.jsx("br",{}),"‎ :::: .-. .= ",x.jsx("br",{}),"‎ ::::. :: .- ",x.jsx("br",{}),"‎ .::::::::::::. :- ",x.jsx("br",{}),"‎ - -: ",x.jsx("br",{}),"‎ - = ",x.jsx("br",{}),"‎ ::::-----:::::=. = ",x.jsx("br",{}),"‎ ::--:. .: .: ",x.jsx("br",{}),"‎ :--:. : : ",x.jsx("br",{}),"‎ :--. .-: : ",x.jsx("br",{}),"‎ ----------. .==. - ",x.jsx("br",{}),"‎ = -+. .- ",x.jsx("br",{}),"‎ =. .+- = ",x.jsx("br",{}),"‎ +. .*: + ",x.jsx("br",{}),"‎ .::--: .*. + ",x.jsx("br",{}),"‎ .- .+. :- ",x.jsx("br",{}),"‎ :: +. --: ",x.jsx("br",{}),"‎ -. :- .---::::. ",x.jsx("br",{}),"‎ .: + .-",x.jsx("br",{}),"‎ = .- .-",x.jsx("br",{}),"‎ -. -. :=",x.jsx("br",{}),"‎ = = .-=: ",x.jsx("br",{}),"‎ -: - .=---: ",x.jsx("br",{}),"‎ = -. .--:- ",x.jsx("br",{}),"‎ = ....:::-= .=. ",x.jsx("br",{}),"‎ ..::::......:::::::::::. + .:.. .::::. :== ",x.jsx("br",{}),"‎ :::::::. .::-::::: = .... :---:. .:-==: ",x.jsx("br",{}),"‎ .- .. .:-::: = .:.. .:--:. -- ",x.jsx("br",{}),"‎ .:=. :+ .:. ::::. .* ",x.jsx("br",{}),"‎ -: :: ::. :::: *. ",x.jsx("br",{}),"‎ .: -. .-. .. .:. -- ",x.jsx("br",{}),"‎ - .-: .=. .= .=- =. .+ ",x.jsx("br",{}),"‎ - -=. .=. -. :+. +: .+ ",x.jsx("br",{}),"‎ - =- .=. = :*. +: + ",x.jsx("br",{}),"‎ .: := -: - .*. :+ =. ",x.jsx("br",{}),"‎ :. * .-. + +: *. .- ",x.jsx("br",{}),"‎ :: + :-. --:. .* .* ::. ",x.jsx("br",{}),"‎ ::. + --. ...-:. := .+ :-: ",x.jsx("br",{}),"‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:. ",x.jsx("br",{}),"‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--: ",x.jsx("br",{}),"‎ .:::::::::... ..... + .... .:--:: ",x.jsx("br",{}),"‎ ..::::::::..:- .:..:::::. .::-::::: ",x.jsx("br",{})]})})}},7481:(s,r,e)=>{"use strict";e.r(r),e.d(r,{default:()=>__WEBPACK_DEFAULT_EXPORT__});var x=e(8531);let __WEBPACK_DEFAULT_EXPORT__=s=>{let r=(0,x.fillMetadataSegment)(".",s.params,"favicon.ico");return[{type:"image/x-icon",sizes:"16x16",url:r+""}]}}};var r=require("../../webpack-runtime.js");r.C(s);var __webpack_exec__=s=>r(r.s=s),e=r.X(0,[862,323,622],()=>__webpack_exec__(1663));module.exports=e})(); \ No newline at end of file +(()=>{var s={};s.id=619,s.ids=[619],s.modules={7849:s=>{"use strict";s.exports=require("next/dist/client/components/action-async-storage.external")},5403:s=>{"use strict";s.exports=require("next/dist/client/components/request-async-storage.external")},4749:s=>{"use strict";s.exports=require("next/dist/client/components/static-generation-async-storage.external")},399:s=>{"use strict";s.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5528:s=>{"use strict";s.exports=require("next/dist\\client\\components\\action-async-storage.external.js")},1877:s=>{"use strict";s.exports=require("next/dist\\client\\components\\request-async-storage.external.js")},5319:s=>{"use strict";s.exports=require("next/dist\\client\\components\\static-generation-async-storage.external.js")},1017:s=>{"use strict";s.exports=require("path")},7310:s=>{"use strict";s.exports=require("url")},1663:(s,r,e)=>{"use strict";e.r(r),e.d(r,{GlobalError:()=>n.a,__next_app__:()=>d,originalPathname:()=>l,pages:()=>o,routeModule:()=>p,tree:()=>j});var t=e(482),x=e(9108),b=e(2563),n=e.n(b),a=e(8300),i={};for(let s in a)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(s)&&(i[s]=()=>a[s]);e.d(r,i);let j=["",{children:["wiston",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(e.bind(e,6071)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx"]}]},{metadata:{icon:[async s=>(await Promise.resolve().then(e.bind(e,7481))).default(s)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(e.bind(e,2917)),"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout.tsx"],"not-found":[()=>Promise.resolve().then(e.t.bind(e,9361,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async s=>(await Promise.resolve().then(e.bind(e,7481))).default(s)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],o=["X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page.tsx"],l="/wiston/page",d={require:e,loadChunk:()=>Promise.resolve()},p=new t.AppPageRouteModule({definition:{kind:x.x.APP_PAGE,page:"/wiston/page",pathname:"/wiston",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:j}})},6254:(s,r,e)=>{Promise.resolve().then(e.t.bind(e,2583,23)),Promise.resolve().then(e.t.bind(e,6840,23)),Promise.resolve().then(e.t.bind(e,8771,23)),Promise.resolve().then(e.t.bind(e,3225,23)),Promise.resolve().then(e.t.bind(e,9295,23)),Promise.resolve().then(e.t.bind(e,3982,23))},2731:()=>{},5303:()=>{},2917:(s,r,e)=>{"use strict";e.r(r),e.d(r,{default:()=>a,metadata:()=>n});var t=e(5036),x=e(265),b=e.n(x);e(3440);let n={title:"sukadia.dev",description:"I code, stream, and create videos."};function a({children:s}){return t.jsx("html",{lang:"en",children:t.jsx("body",{className:b().className,children:s})})}},6071:(s,r,e)=>{"use strict";e.r(r),e.d(r,{default:()=>b,metadata:()=>x});var t=e(5036);let x={title:"wiston"};function b(){return t.jsx("main",{className:"flex flex-col items-center",children:(0,t.jsxs)("span",{className:"whitespace-pre-wrap font-mono text-[0.2rem] leading-[0.25rem]",children:["‎ -+=-:. - ",t.jsx("br",{}),"‎ .*%#%#%%%%#*+-. ++= .:-==: ",t.jsx("br",{}),"‎ =%%########%##%%%*-. ++-# .-+*%%%###%#- ",t.jsx("br",{}),"‎ .#%%################%%#=:=+- .+=--+= -+#%%##########%#. ",t.jsx("br",{}),"‎ -%%####################%%+--=*: ==-----# --. -*%%%###############%= ",t.jsx("br",{}),"‎ *%%#####################%+-----+=-------*:+=-+--*%%%#################%#%# ",t.jsx("br",{}),"‎ .#%%###############%#%#####---*+-----------+--=*%%#######################%%%: ",t.jsx("br",{}),"‎ .%%################%@=+*%%%=--+**#=---***=-=++#%############################%%- ",t.jsx("br",{}),"‎ .%%#################%@+---+*---#***#=+#***#*%%%%####################%%%######%%%- ",t.jsx("br",{}),"‎ %%###################%*--------#**********#%%######################%%#%%%######%@- ",t.jsx("br",{}),"‎ #%####################%%--=+===+*********#%%#######################%%###%%#######%@- ",t.jsx("br",{}),"‎ +%%#####################@+-=#**********#%%%########################%%#####%%#######%@: ",t.jsx("br",{}),"‎ .%######################%%%--+******##%%%%%########################%%#######%%%######%%. ",t.jsx("br",{}),"‎ #%###########%%%%%%%%%%%%%%#--==*##%%%%%##########################%@#########%%#######%% ",t.jsx("br",{}),"‎ :%%###########%%###%%%%%%%%#%%#*%%###%%###########################%%%##########%%#######%* ",t.jsx("br",{}),"‎ *%######%%##%%%%%#######%#####%%####%%#############################@##%%%%#####%%#######%%= ",t.jsx("br",{}),"‎ .%%######%%%%%%%%%##################%%#############################%%#%%##%%##%#%%#########%. ",t.jsx("br",{}),"‎ =%#######%@%%%######################%##############################%%%%####%%@%%#@%########%# ",t.jsx("br",{}),"‎ ######%%%%%%%######################################################%@%######%%#%#%##########%- ",t.jsx("br",{}),"‎ %%#%%%%%%%%########################################################%@%#########%%%###########% ",t.jsx("br",{}),"‎ .%%%%%%%%%###########################################################%###########%@###########%+ ",t.jsx("br",{}),"‎ =#%%%%%%########################################################################################% ",t.jsx("br",{}),"‎ +%%%%%############################################%%#%############################################%- ",t.jsx("br",{}),"‎ =%%%%##########%#########################################%%##########################################%%**++======+**#% ",t.jsx("br",{}),"‎ -#%%%#########################################################%####################################%###################%. ",t.jsx("br",{}),"‎ *%%%#####################################################################################################%###%##########% ",t.jsx("br",{}),"‎ .#%###################################################################%##%###############%###############################%# ",t.jsx("br",{}),"‎ .+%##############################################################################%#########################################%= ",t.jsx("br",{}),"‎ .+%#########################################################################################################################%% ",t.jsx("br",{}),"‎ +%##########################################################################################################################%%. ",t.jsx("br",{}),"‎ =%#################################################################################%%@%%#####################################%%: ",t.jsx("br",{}),"‎ -#################################################################################%@@@%#######################################%%. ",t.jsx("br",{}),"‎ :################################################################################%@@#%########################################%%+ ",t.jsx("br",{}),"‎ +%#############################################################################%@@#- +######################################%+. ",t.jsx("br",{}),"‎ -#############################################################################%@@#= :*#################################%*- ",t.jsx("br",{}),"‎ =%##########################################################################%@%*- :==- +################################%. ",t.jsx("br",{}),"‎ -.:+######################################################################%%@%* =#####: ####+=---::--=+*##################. ",t.jsx("br",{}),"‎ - :+###################################################################%%##- *#%%*=- =-. .-*##############%+: ",t.jsx("br",{}),"‎ : .-+####################################################################: #%@+--- =############%#= ",t.jsx("br",{}),"‎ - :=+################################################################+ -%%%%%+ +%%%%%%%%#*=: ",t.jsx("br",{}),"‎ .:. :-+*############################################################: :+*+- - .... ",t.jsx("br",{}),"‎ ::. .:=+*########################################################=. = ",t.jsx("br",{}),"‎ ::. .:-=*####################################################*: .- ",t.jsx("br",{}),"‎ ::. .:-=+*##########################################*=: .- ",t.jsx("br",{}),"‎ .:: ..:--==++***################***++===-::. .- ",t.jsx("br",{}),"‎ :-. ..... ..:::. .= ",t.jsx("br",{}),"‎ .::. .-+****+====+==: + ",t.jsx("br",{}),"‎ :::. .-+#*=:. . + ",t.jsx("br",{}),"‎ .::. .=*#+: .::::. =: ",t.jsx("br",{}),"‎ .... =*=. ::::: .+ ",t.jsx("br",{}),"‎ .:::. ::::. + ",t.jsx("br",{}),"‎ .:::::.. .:::::. .= ",t.jsx("br",{}),"‎ .::::::::::::.......::::::::::+-. =. ",t.jsx("br",{}),"‎ ...... .+. + ",t.jsx("br",{}),"‎ .::+ .- ",t.jsx("br",{}),"‎ .::. +. .: ",t.jsx("br",{}),"‎ -: :-. :: ",t.jsx("br",{}),"‎ -- .-=: .:::. :. ",t.jsx("br",{}),"‎ --.-=:. .---. :. ",t.jsx("br",{}),"‎ -=. ==: :=-. :. ",t.jsx("br",{}),"‎ :+: :-+. .-=: - ",t.jsx("br",{}),"‎ :+- .=-. :=-. - ",t.jsx("br",{}),"‎ .+- :-- :=- :. - ",t.jsx("br",{}),"‎ .+=. = -=: :: .- ",t.jsx("br",{}),"‎ .+=. =:-: -+: .-. .- ",t.jsx("br",{}),"‎ .==. .:::::--:.=+ .=: :- .: ",t.jsx("br",{}),"‎ ::=:---: .---. .:--+: .-. :: ",t.jsx("br",{}),"‎ --. .+-:. .--: :- :. ",t.jsx("br",{}),"‎ :- .. .:: .-. -. ",t.jsx("br",{}),"‎ :: : .=. :: -. ",t.jsx("br",{}),"‎ = .: .+: ::. -. ",t.jsx("br",{}),"‎ =. - +. .:. -. ",t.jsx("br",{}),"‎ + - .+ :: :: ",t.jsx("br",{}),"‎ + . :-. + .:. :: ",t.jsx("br",{}),"‎ + .: :- =. .:. .- ",t.jsx("br",{}),"‎ -. .: :- .--. .:: .- ",t.jsx("br",{}),"‎ = ::. .= == :: .- ",t.jsx("br",{}),"‎ :: ::: :: .:-- .:. - ",t.jsx("br",{}),"‎ -. .:::: = :---. .:. :. ",t.jsx("br",{}),"‎ :. .:::::::=:--:. :: :. ",t.jsx("br",{}),"‎ .:. :-= .: ",t.jsx("br",{}),"‎ .:: .-. .: ",t.jsx("br",{}),"‎ ::. .-: - ",t.jsx("br",{}),"‎ .::. :-. = ",t.jsx("br",{}),"‎ :::: .-. .= ",t.jsx("br",{}),"‎ ::::. :: .- ",t.jsx("br",{}),"‎ .::::::::::::. :- ",t.jsx("br",{}),"‎ - -: ",t.jsx("br",{}),"‎ - = ",t.jsx("br",{}),"‎ ::::-----:::::=. = ",t.jsx("br",{}),"‎ ::--:. .: .: ",t.jsx("br",{}),"‎ :--:. : : ",t.jsx("br",{}),"‎ :--. .-: : ",t.jsx("br",{}),"‎ ----------. .==. - ",t.jsx("br",{}),"‎ = -+. .- ",t.jsx("br",{}),"‎ =. .+- = ",t.jsx("br",{}),"‎ +. .*: + ",t.jsx("br",{}),"‎ .::--: .*. + ",t.jsx("br",{}),"‎ .- .+. :- ",t.jsx("br",{}),"‎ :: +. --: ",t.jsx("br",{}),"‎ -. :- .---::::. ",t.jsx("br",{}),"‎ .: + .-",t.jsx("br",{}),"‎ = .- .-",t.jsx("br",{}),"‎ -. -. :=",t.jsx("br",{}),"‎ = = .-=: ",t.jsx("br",{}),"‎ -: - .=---: ",t.jsx("br",{}),"‎ = -. .--:- ",t.jsx("br",{}),"‎ = ....:::-= .=. ",t.jsx("br",{}),"‎ ..::::......:::::::::::. + .:.. .::::. :== ",t.jsx("br",{}),"‎ :::::::. .::-::::: = .... :---:. .:-==: ",t.jsx("br",{}),"‎ .- .. .:-::: = .:.. .:--:. -- ",t.jsx("br",{}),"‎ .:=. :+ .:. ::::. .* ",t.jsx("br",{}),"‎ -: :: ::. :::: *. ",t.jsx("br",{}),"‎ .: -. .-. .. .:. -- ",t.jsx("br",{}),"‎ - .-: .=. .= .=- =. .+ ",t.jsx("br",{}),"‎ - -=. .=. -. :+. +: .+ ",t.jsx("br",{}),"‎ - =- .=. = :*. +: + ",t.jsx("br",{}),"‎ .: := -: - .*. :+ =. ",t.jsx("br",{}),"‎ :. * .-. + +: *. .- ",t.jsx("br",{}),"‎ :: + :-. --:. .* .* ::. ",t.jsx("br",{}),"‎ ::. + --. ...-:. := .+ :-: ",t.jsx("br",{}),"‎ .::. =: .::.....::::::::::::::::.... .:. .::. .::= .+ :-:. ",t.jsx("br",{}),"‎ ..-.::::::.. ...... .:::::::. .::::--. + .. .:--: ",t.jsx("br",{}),"‎ .:::::::::... ..... + .... .:--:: ",t.jsx("br",{}),"‎ ..::::::::..:- .:..:::::. .::-::::: ",t.jsx("br",{})]})})}},7481:(s,r,e)=>{"use strict";e.r(r),e.d(r,{default:()=>x});var t=e(337);let x=s=>[{type:"image/x-icon",sizes:"16x16",url:(0,t.fillMetadataSegment)(".",s.params,"favicon.ico")+""}]},3440:()=>{}};var r=require("../../webpack-runtime.js");r.C(s);var e=s=>r(r.s=s),t=r.X(0,[638,969,337],()=>e(1663));module.exports=t})(); \ No newline at end of file diff --git a/.next/server/app/wiston/page.js.nft.json b/.next/server/app/wiston/page.js.nft.json index 886634f..48bcd56 100644 --- a/.next/server/app/wiston/page.js.nft.json +++ b/.next/server/app/wiston/page.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/106.js","../../chunks/2.js","../../chunks/201.js","../../chunks/310.js","../../chunks/323.js","../../chunks/622.js","../../chunks/676.js","../../chunks/837.js","../../chunks/840.js","../../chunks/862.js","../../chunks/984.js","../../chunks/font-manifest.json","../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file +{"version":1,"files":["../../../../node_modules/next/dist/client/components/action-async-storage.external.js","../../../../node_modules/next/dist/client/components/async-local-storage.js","../../../../node_modules/next/dist/client/components/request-async-storage.external.js","../../../../node_modules/next/dist/client/components/static-generation-async-storage.external.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../../node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js","../../../../node_modules/next/dist/server/lib/trace/constants.js","../../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../../node_modules/next/package.json","../../../../package.json","../../../package.json","../../chunks/329.js","../../chunks/337.js","../../chunks/638.js","../../chunks/969.js","../../chunks/font-manifest.json","../../webpack-runtime.js","page_client-reference-manifest.js"]} \ No newline at end of file diff --git a/.next/server/app/wiston/page_client-reference-manifest.js b/.next/server/app/wiston/page_client-reference-manifest.js index db0d848..1ab67a7 100644 --- a/.next/server/app/wiston/page_client-reference-manifest.js +++ b/.next/server/app/wiston/page_client-reference-manifest.js @@ -1 +1 @@ -globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/wiston/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"3170":{"*":{"id":"4714","name":"*","chunks":[],"async":false}},"3728":{"*":{"id":"3724","name":"*","chunks":[],"async":false}},"6916":{"*":{"id":"5698","name":"*","chunks":[],"async":false}},"6954":{"*":{"id":"4900","name":"*","chunks":[],"async":false}},"7264":{"*":{"id":"5392","name":"*","chunks":[],"async":false}},"8297":{"*":{"id":"8898","name":"*","chunks":[],"async":false}},"9928":{"*":{"id":"5365","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":3728,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":9928,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":6954,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":3170,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":7264,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":8297,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":1371,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":595,"name":"*","chunks":["185","static/chunks/app/layout-ca25527909104096.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":6916,"name":"*","chunks":["986","static/chunks/986-37229c658d9b7b30.js","931","static/chunks/app/page-39b6caed82efc627.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page":[]}} \ No newline at end of file +globalThis.__RSC_MANIFEST=(globalThis.__RSC_MANIFEST||{});globalThis.__RSC_MANIFEST["/wiston/page"]={"moduleLoading":{"prefix":"/_next/","crossOrigin":null},"ssrModuleMapping":{"326":{"*":{"id":"2079","name":"*","chunks":[],"async":false}},"1778":{"*":{"id":"9295","name":"*","chunks":[],"async":false}},"1902":{"*":{"id":"3225","name":"*","chunks":[],"async":false}},"5613":{"*":{"id":"8771","name":"*","chunks":[],"async":false}},"7690":{"*":{"id":"2583","name":"*","chunks":[],"async":false}},"7831":{"*":{"id":"3982","name":"*","chunks":[],"async":false}},"8955":{"*":{"id":"6840","name":"*","chunks":[],"async":false}}},"edgeSSRModuleMapping":{},"clientModules":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\app-router.js":{"id":7690,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\error-boundary.js":{"id":8955,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\layout-router.js":{"id":5613,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\not-found-boundary.js":{"id":1902,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\render-from-template-context.js":{"id":1778,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\esm\\client\\components\\static-generation-searchparams-bailout-provider.js":{"id":7831,"name":"*","chunks":[],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\font\\google\\target.css?{\"path\":\"app\\\\layout.tsx\",\"import\":\"Inter\",\"arguments\":[{\"subsets\":[\"latin\"]}],\"variableName\":\"inter\"}":{"id":3445,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\globals.scss":{"id":9989,"name":"*","chunks":["185","static/chunks/app/layout-2a5e75b3a17431fd.js"],"async":false},"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page.tsx":{"id":326,"name":"*","chunks":["986","static/chunks/986-72006aa1051e30d3.js","931","static/chunks/app/page-8af0c2c4af65d19c.js"],"async":false}},"entryCSSFiles":{"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\_not-found":[],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\layout":["static/css/1d2d59615145af7d.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\page":["static/css/60c69e914bf8dd4b.css"],"X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\app\\wiston\\page":[]}} \ No newline at end of file diff --git a/.next/server/chunks/106.js b/.next/server/chunks/106.js deleted file mode 100644 index 1cd284b..0000000 --- a/.next/server/chunks/106.js +++ /dev/null @@ -1,113 +0,0 @@ -"use strict";exports.id=106,exports.ids=[106],exports.modules={4106:(e,r,n)=>{n.r(r),n.d(r,{default:()=>BabylonScene});var t=n(784),i=n(9885),s=n(4494),a=n(7690);let BabylonScene=class BabylonScene extends i.PureComponent{componentDidMount(){console.clear(),this.setup(this.canvas)}render(){return t.jsx(t.Fragment,{children:t.jsx("canvas",{id:this.id,ref:this.onMount,style:o})})}constructor(...e){super(...e),this.setup=async e=>{s.vGS.ShadersStoreWGSL.starsPixelShader=` - uniform seed : f32; - uniform density : f32; - uniform brightness : f32; - - fn rand(seed : vec2) -> f32 { - return fract(sin(dot(seed, vec2(12.9898, 78.233))) * 43758.5453); - } - - @fragment - fn main(input : FragmentInputs) -> FragmentOutputs { - - let random = rand(input.vUV*uniforms.seed); - var brightness = 0.0; - if (random < uniforms.density){ - brightness = random/uniforms.density*uniforms.brightness; - } - //fragmentOutputs.color = vec4(1., 1., 1., brightness); - fragmentOutputs.color = vec4(brightness, brightness, brightness, 1.); - } - `,s.vGS.ShadersStoreWGSL.nebulasPixelShader=` - var textureSampler: texture_2d; - var textureSamplerSampler: sampler; - - uniform seed: f32; - uniform color: vec4; - uniform nebulascale: u32; - uniform depth: u32; - uniform intensity: f32; - uniform falloff: f32; - uniform persistence: f32; - - fn mod289(x: vec2) -> vec2 { - return x - floor(x * (1. / 289.)) * 289.; - } - - fn mod289_3(x: vec3) -> vec3 { - return x - floor(x * (1. / 289.)) * 289.; - } - - fn permute3(x: vec3) -> vec3 { - return mod289_3(((x * 34.) + 1.) * x); - } - - // MIT License. \xa9 Ian McEwan, Stefan Gustavson, Munrocket - fn simplexNoise2(v: vec2) -> f32 { - let C = vec4( - 0.211324865405187, // (3.0-sqrt(3.0))/6.0 - 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) - -0.577350269189626, // -1.0 + 2.0 * C.x - 0.024390243902439 // 1.0 / 41.0 - ); - - // First corner - var i = floor(v + dot(v, C.yy)); - let x0 = v - i + dot(i, C.xx); - - // Other corners - var i1 = select(vec2(0., 1.), vec2(1., 0.), x0.x > x0.y); - - // x0 = x0 - 0.0 + 0.0 * C.xx ; - // x1 = x0 - i1 + 1.0 * C.xx ; - // x2 = x0 - 1.0 + 2.0 * C.xx ; - var x12 = x0.xyxy + C.xxzz; - x12.x = x12.x - i1.x; - x12.y = x12.y - i1.y; - - // Permutations - i = mod289(i); // Avoid truncation effects in permutation - - var p = permute3(permute3(i.y + vec3(0., i1.y, 1.)) + i.x + vec3(0., i1.x, 1.)); - var m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), vec3(0.)); - m *= m; - m *= m; - - // Gradients: 41 points uniformly over a line, mapped onto a diamond. - // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) - let x = 2. * fract(p * C.www) - 1.; - let h = abs(x) - 0.5; - let ox = floor(x + 0.5); - let a0 = x - ox; - - // Normalize gradients implicitly by scaling m - // Approximation of: m *= inversesqrt( a0*a0 + h*h ); - m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h); - - // Compute final noise value at P - let g = vec3(a0.x * x0.x + h.x * x0.y, a0.yz * x12.xz + h.yz * x12.yw); - return 130. * dot(m, g); - } - - fn normalNoise(v: vec2) -> f32 { - return simplexNoise2(v)*0.5 + 0.5; - } - - @fragment - fn main(input : FragmentInputs) -> FragmentOutputs { - let sampleColor = textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV); - - var offset = 0.; - let scaledUV = (input.vUV+offset+uniforms.seed)*f32(uniforms.nebulascale)/uniforms.scale; - - var displace = 0.; - var i=u32(0); - for (i=0; i{let r;return await s.fWK.IsSupportedAsync?(r=new s.fWK(e),await r.initAsync()):(console.log("WebGPU is not supported (or turned on) for this browser!"),r=new s.fWK(e)),r},this.id="Babylon",this.onMount=e=>this.canvas=e}};let o={width:window.innerWidth,height:window.innerHeight,background:"transparent"}}}; \ No newline at end of file diff --git a/.next/server/chunks/2.js b/.next/server/chunks/2.js deleted file mode 100644 index ec8dffc..0000000 --- a/.next/server/chunks/2.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";exports.id=2,exports.ids=[2],exports.modules={1323:(e,t)=>{function hoist(e,t){return t in e?e[t]:"then"in e&&"function"==typeof e.then?e.then(e=>hoist(e,t)):"function"==typeof e&&"default"===t?e:void 0}Object.defineProperty(t,"l",{enumerable:!0,get:function(){return hoist}})},2534:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return Error}});let r=n(167),o=r._(n(6689)),l=r._(n(6561)),a={400:"Bad Request",404:"This page could not be found",405:"Method Not Allowed",500:"Internal Server Error"};function _getInitialProps(e){let{res:t,err:n}=e,r=t&&t.statusCode?t.statusCode:n?n.statusCode:404;return{statusCode:r}}let i={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{lineHeight:"48px"},h1:{display:"inline-block",margin:"0 20px 0 0",paddingRight:23,fontSize:24,fontWeight:500,verticalAlign:"top"},h2:{fontSize:14,fontWeight:400,lineHeight:"28px"},wrap:{display:"inline-block"}};let Error=class Error extends o.default.Component{render(){let{statusCode:e,withDarkMode:t=!0}=this.props,n=this.props.title||a[e]||"An unexpected error has occurred";return o.default.createElement("div",{style:i.error},o.default.createElement(l.default,null,o.default.createElement("title",null,e?e+": "+n:"Application error: a client-side exception has occurred")),o.default.createElement("div",{style:i.desc},o.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}"+(t?"@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}":"")}}),e?o.default.createElement("h1",{className:"next-error-h1",style:i.h1},e):null,o.default.createElement("div",{style:i.wrap},o.default.createElement("h2",{style:i.h2},this.props.title||e?n:o.default.createElement(o.default.Fragment,null,"Application error: a client-side exception has occurred (see the browser console for more information)"),"."))))}};Error.displayName="ErrorPage",Error.getInitialProps=_getInitialProps,Error.origGetInitialProps=_getInitialProps,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8801:(e,t)=>{function isInAmpMode(e){let{ampFirst:t=!1,hybrid:n=!1,hasQuery:r=!1}=void 0===e?{}:e;return t||n&&r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return isInAmpMode}})},6561:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{defaultHead:function(){return defaultHead},default:function(){return c}});let r=n(167),o=n(8760),l=o._(n(6689)),a=r._(n(9737)),i=n(8039),d=n(1988),u=n(8801);function defaultHead(e){void 0===e&&(e=!1);let t=[l.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(l.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function onlyReactElement(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===l.default.Fragment?e.concat(l.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}n(8565);let f=["name","httpEquiv","charSet","itemProp"];function unique(){let e=new Set,t=new Set,n=new Set,r={};return o=>{let l=!0,a=!1;if(o.key&&"number"!=typeof o.key&&o.key.indexOf("$")>0){a=!0;let t=o.key.slice(o.key.indexOf("$")+1);e.has(t)?l=!1:e.add(t)}switch(o.type){case"title":case"base":t.has(o.type)?l=!1:t.add(o.type);break;case"meta":for(let e=0,t=f.length;e{let r=e.key||t;if(!n&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,l.default.cloneElement(e,t)}return l.default.cloneElement(e,{key:r})})}function Head(e){let{children:t}=e,n=(0,l.useContext)(i.AmpStateContext),r=(0,l.useContext)(d.HeadManagerContext);return l.default.createElement(a.default,{reduceComponentsToState:reduceComponents,headManager:r,inAmpMode:(0,u.isInAmpMode)(n)},t)}let c=Head;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9737:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return SideEffect}});let r=n(6689),useClientOnlyLayoutEffect=()=>{},useClientOnlyEffect=()=>{};function SideEffect(e){var t;let{headManager:n,reduceComponentsToState:o}=e;function emitChange(){if(n&&n.mountedInstances){let t=r.Children.toArray(Array.from(n.mountedInstances).filter(Boolean));n.updateHead(o(t,e))}}return null==n||null==(t=n.mountedInstances)||t.add(e.children),emitChange(),useClientOnlyLayoutEffect(()=>{var t;return null==n||null==(t=n.mountedInstances)||t.add(e.children),()=>{var t;null==n||null==(t=n.mountedInstances)||t.delete(e.children)}}),useClientOnlyLayoutEffect(()=>(n&&(n._pendingUpdate=emitChange),()=>{n&&(n._pendingUpdate=emitChange)})),useClientOnlyEffect(()=>(n&&n._pendingUpdate&&(n._pendingUpdate(),n._pendingUpdate=null),()=>{n&&n._pendingUpdate&&(n._pendingUpdate(),n._pendingUpdate=null)})),null}},8565:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return warnOnce}});let warnOnce=e=>{}},5244:(e,t)=>{var n;Object.defineProperty(t,"x",{enumerable:!0,get:function(){return n}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE"}(n||(n={}))},8039:(e,t,n)=>{e.exports=n(7093).vendored.contexts.AmpContext},1988:(e,t,n)=>{e.exports=n(7093).vendored.contexts.HeadManagerContext},8760:(e,t)=>{function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(_getRequireWildcardCache=function(e){return e?n:t})(e)}function _interop_require_wildcard(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=_getRequireWildcardCache(t);if(n&&n.has(e))return n.get(e);var r={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var l in e)if("default"!==l&&Object.prototype.hasOwnProperty.call(e,l)){var a=o?Object.getOwnPropertyDescriptor(e,l):null;a&&(a.get||a.set)?Object.defineProperty(r,l,a):r[l]=e[l]}return r.default=e,n&&n.set(e,r),r}t._=t._interop_require_wildcard=_interop_require_wildcard}}; \ No newline at end of file diff --git a/.next/server/chunks/201.js b/.next/server/chunks/201.js deleted file mode 100644 index 5764cae..0000000 --- a/.next/server/chunks/201.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict";exports.id=201,exports.ids=[201],exports.modules={8450:e=>{var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,o=Object.prototype.hasOwnProperty,n={};function stringifyCookie(e){var t;let r=["path"in e&&e.path&&`Path=${e.path}`,"expires"in e&&(e.expires||0===e.expires)&&`Expires=${("number"==typeof e.expires?new Date(e.expires):e.expires).toUTCString()}`,"maxAge"in e&&"number"==typeof e.maxAge&&`Max-Age=${e.maxAge}`,"domain"in e&&e.domain&&`Domain=${e.domain}`,"secure"in e&&e.secure&&"Secure","httpOnly"in e&&e.httpOnly&&"HttpOnly","sameSite"in e&&e.sameSite&&`SameSite=${e.sameSite}`,"priority"in e&&e.priority&&`Priority=${e.priority}`].filter(Boolean);return`${e.name}=${encodeURIComponent(null!=(t=e.value)?t:"")}; ${r.join("; ")}`}function parseCookie(e){let t=new Map;for(let r of e.split(/; */)){if(!r)continue;let e=r.indexOf("=");if(-1===e){t.set(r,"true");continue}let[i,o]=[r.slice(0,e),r.slice(e+1)];try{t.set(i,decodeURIComponent(null!=o?o:"true"))}catch{}}return t}function parseSetCookie(e){if(!e)return;let[[t,r],...i]=parseCookie(e),{domain:o,expires:n,httponly:a,maxage:s,path:l,samesite:u,secure:d,priority:c}=Object.fromEntries(i.map(([e,t])=>[e.toLowerCase(),t])),h={name:t,value:decodeURIComponent(r),domain:o,...n&&{expires:new Date(n)},...a&&{httpOnly:!0},..."string"==typeof s&&{maxAge:Number(s)},path:l,...u&&{sameSite:parseSameSite(u)},...d&&{secure:!0},...c&&{priority:parsePriority(c)}};return compact(h)}function compact(e){let t={};for(let r in e)e[r]&&(t[r]=e[r]);return t}((e,r)=>{for(var i in r)t(e,i,{get:r[i],enumerable:!0})})(n,{RequestCookies:()=>l,ResponseCookies:()=>u,parseCookie:()=>parseCookie,parseSetCookie:()=>parseSetCookie,stringifyCookie:()=>stringifyCookie}),e.exports=((e,n,a,s)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let a of i(n))o.call(e,a)||void 0===a||t(e,a,{get:()=>n[a],enumerable:!(s=r(n,a))||s.enumerable});return e})(t({},"__esModule",{value:!0}),n);var a=["strict","lax","none"];function parseSameSite(e){return e=e.toLowerCase(),a.includes(e)?e:void 0}var s=["low","medium","high"];function parsePriority(e){return e=e.toLowerCase(),s.includes(e)?e:void 0}function splitCookiesString(e){if(!e)return[];var t,r,i,o,n,a=[],s=0;function skipWhitespace(){for(;s=e.length)&&a.push(e.substring(t,e.length))}return a}var l=class{constructor(e){this._parsed=new Map,this._headers=e;let t=e.get("cookie");if(t){let e=parseCookie(t);for(let[t,r]of e)this._parsed.set(t,{name:t,value:r})}}[Symbol.iterator](){return this._parsed[Symbol.iterator]()}get size(){return this._parsed.size}get(...e){let t="string"==typeof e[0]?e[0]:e[0].name;return this._parsed.get(t)}getAll(...e){var t;let r=Array.from(this._parsed);if(!e.length)return r.map(([e,t])=>t);let i="string"==typeof e[0]?e[0]:null==(t=e[0])?void 0:t.name;return r.filter(([e])=>e===i).map(([e,t])=>t)}has(e){return this._parsed.has(e)}set(...e){let[t,r]=1===e.length?[e[0].name,e[0].value]:e,i=this._parsed;return i.set(t,{name:t,value:r}),this._headers.set("cookie",Array.from(i).map(([e,t])=>stringifyCookie(t)).join("; ")),this}delete(e){let t=this._parsed,r=Array.isArray(e)?e.map(e=>t.delete(e)):t.delete(e);return this._headers.set("cookie",Array.from(t).map(([e,t])=>stringifyCookie(t)).join("; ")),r}clear(){return this.delete(Array.from(this._parsed.keys())),this}[Symbol.for("edge-runtime.inspect.custom")](){return`RequestCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(e=>`${e.name}=${encodeURIComponent(e.value)}`).join("; ")}},u=class{constructor(e){var t,r,i;this._parsed=new Map,this._headers=e;let o=null!=(i=null!=(r=null==(t=e.getSetCookie)?void 0:t.call(e))?r:e.get("set-cookie"))?i:[],n=Array.isArray(o)?o:splitCookiesString(o);for(let e of n){let t=parseSetCookie(e);t&&this._parsed.set(t.name,t)}}get(...e){let t="string"==typeof e[0]?e[0]:e[0].name;return this._parsed.get(t)}getAll(...e){var t;let r=Array.from(this._parsed.values());if(!e.length)return r;let i="string"==typeof e[0]?e[0]:null==(t=e[0])?void 0:t.name;return r.filter(e=>e.name===i)}has(e){return this._parsed.has(e)}set(...e){let[t,r,i]=1===e.length?[e[0].name,e[0].value,e[0]]:e,o=this._parsed;return o.set(t,normalizeCookie({name:t,value:r,...i})),replace(o,this._headers),this}delete(...e){let[t,r,i]="string"==typeof e[0]?[e[0]]:[e[0].name,e[0].path,e[0].domain];return this.set({name:t,path:r,domain:i,value:"",expires:new Date(0)})}[Symbol.for("edge-runtime.inspect.custom")](){return`ResponseCookies ${JSON.stringify(Object.fromEntries(this._parsed))}`}toString(){return[...this._parsed.values()].map(stringifyCookie).join("; ")}};function replace(e,t){for(let[,r]of(t.delete("set-cookie"),e)){let e=stringifyCookie(r);t.append("set-cookie",e)}}function normalizeCookie(e={name:"",value:""}){return"number"==typeof e.expires&&(e.expires=new Date(e.expires)),e.maxAge&&(e.expires=new Date(Date.now()+1e3*e.maxAge)),(null===e.path||void 0===e.path)&&(e.path="/"),e}},5842:(e,t,r)=>{var i;(()=>{var o={226:function(o,n){!function(a,s){var l="function",u="undefined",d="object",c="string",h="major",p="model",b="name",f="type",m="vendor",g="version",w="architecture",v="console",x="mobile",y="tablet",P="smarttv",k="wearable",_="embedded",S="Amazon",A="Apple",R="ASUS",O="BlackBerry",C="Browser",j="Chrome",L="Firefox",U="Google",N="Huawei",q="Microsoft",E="Motorola",M="Opera",z="Samsung",I="Sharp",T="Sony",H="Xiaomi",$="Zebra",D="Facebook",B="Chromium OS",W="Mac OS",extend=function(e,t){var r={};for(var i in e)t[i]&&t[i].length%2==0?r[i]=t[i].concat(e[i]):r[i]=e[i];return r},enumerize=function(e){for(var t={},r=0;r0?2===n.length?typeof n[1]==l?this[n[0]]=n[1].call(this,u):this[n[0]]=n[1]:3===n.length?typeof n[1]!==l||n[1].exec&&n[1].test?this[n[0]]=u?u.replace(n[1],n[2]):s:this[n[0]]=u?n[1].call(this,u,n[2]):s:4===n.length&&(this[n[0]]=u?n[3].call(this,u.replace(n[1],n[2])):s):this[n]=u||s;c+=2}},strMapper=function(e,t){for(var r in t)if(typeof t[r]===d&&t[r].length>0){for(var i=0;i2&&(e[p]="iPad",e[f]=y),e},this.getEngine=function(){var e={};return e[b]=s,e[g]=s,rgxMapper.call(e,i,n.engine),e},this.getOS=function(){var e={};return e[b]=s,e[g]=s,rgxMapper.call(e,i,n.os),v&&!e[b]&&o&&"Unknown"!=o.platform&&(e[b]=o.platform.replace(/chrome os/i,B).replace(/macos/i,W)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return i},this.setUA=function(e){return i=typeof e===c&&e.length>350?trim(e,350):e,this},this.setUA(i),this};UAParser.VERSION="1.0.35",UAParser.BROWSER=enumerize([b,g,h]),UAParser.CPU=enumerize([w]),UAParser.DEVICE=enumerize([p,m,f,v,x,P,y,k,_]),UAParser.ENGINE=UAParser.OS=enumerize([b,g]),typeof n!==u?(o.exports&&(n=o.exports=UAParser),n.UAParser=UAParser):r.amdO?void 0!==(i=(function(){return UAParser}).call(t,r,t,e))&&(e.exports=i):typeof a!==u&&(a.UAParser=UAParser);var V=typeof a!==u&&(a.jQuery||a.Zepto);if(V&&!V.ua){var Z=new UAParser;V.ua=Z.getResult(),V.ua.get=function(){return Z.getUA()},V.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var r in t)V.ua[r]=t[r]}}}(this)}},n={};function __nccwpck_require__(e){var t=n[e];if(void 0!==t)return t.exports;var r=n[e]={exports:{}},i=!0;try{o[e].call(r.exports,r,r.exports,__nccwpck_require__),i=!1}finally{i&&delete n[e]}return r.exports}__nccwpck_require__.ab=__dirname+"/";var a=__nccwpck_require__(226);e.exports=a})()},6132:(e,t)=>{var r;Object.defineProperty(t,"x",{enumerable:!0,get:function(){return r}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE"}(r||(r={}))},884:(e,t,r)=>{e.exports=r(517)},8726:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PageSignatureError:function(){return PageSignatureError},RemovedPageError:function(){return RemovedPageError},RemovedUAError:function(){return RemovedUAError}});let PageSignatureError=class PageSignatureError extends Error{constructor({page:e}){super(`The middleware "${e}" accepts an async API directly with the form: - - export function middleware(request, event) { - return NextResponse.redirect('/new-location') - } - - Read more: https://nextjs.org/docs/messages/middleware-new-signature - `)}};let RemovedPageError=class RemovedPageError extends Error{constructor(){super(`The request.page has been deprecated in favour of \`URLPattern\`. - Read more: https://nextjs.org/docs/messages/middleware-request-page - `)}};let RemovedUAError=class RemovedUAError extends Error{constructor(){super(`The request.ua has been removed in favour of \`userAgent\` function. - Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent - `)}}},8098:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NextURL",{enumerable:!0,get:function(){return NextURL}});let i=r(4582),o=r(3987),n=r(5913),a=r(2020),s=/(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)/;function parseURL(e,t){return new URL(String(e).replace(s,"localhost"),t&&String(t).replace(s,"localhost"))}let l=Symbol("NextURLInternal");let NextURL=class NextURL{constructor(e,t,r){let i,o;"object"==typeof t&&"pathname"in t||"string"==typeof t?(i=t,o=r||{}):o=r||t||{},this[l]={url:parseURL(e,i??o.base),options:o,basePath:""},this.analyze()}analyze(){var e,t,r,o,s;let u=(0,a.getNextPathnameInfo)(this[l].url.pathname,{nextConfig:this[l].options.nextConfig,parseData:!0,i18nProvider:this[l].options.i18nProvider}),d=(0,n.getHostname)(this[l].url,this[l].options.headers);this[l].domainLocale=this[l].options.i18nProvider?this[l].options.i18nProvider.detectDomainLocale(d):(0,i.detectDomainLocale)(null==(t=this[l].options.nextConfig)?void 0:null==(e=t.i18n)?void 0:e.domains,d);let c=(null==(r=this[l].domainLocale)?void 0:r.defaultLocale)||(null==(s=this[l].options.nextConfig)?void 0:null==(o=s.i18n)?void 0:o.defaultLocale);this[l].url.pathname=u.pathname,this[l].defaultLocale=c,this[l].basePath=u.basePath??"",this[l].buildId=u.buildId,this[l].locale=u.locale??c,this[l].trailingSlash=u.trailingSlash}formatPathname(){return(0,o.formatNextPathnameInfo)({basePath:this[l].basePath,buildId:this[l].buildId,defaultLocale:this[l].options.forceLocale?void 0:this[l].defaultLocale,locale:this[l].locale,pathname:this[l].url.pathname,trailingSlash:this[l].trailingSlash})}formatSearch(){return this[l].url.search}get buildId(){return this[l].buildId}set buildId(e){this[l].buildId=e}get locale(){return this[l].locale??""}set locale(e){var t,r;if(!this[l].locale||!(null==(r=this[l].options.nextConfig)?void 0:null==(t=r.i18n)?void 0:t.locales.includes(e)))throw TypeError(`The NextURL configuration includes no locale "${e}"`);this[l].locale=e}get defaultLocale(){return this[l].defaultLocale}get domainLocale(){return this[l].domainLocale}get searchParams(){return this[l].url.searchParams}get host(){return this[l].url.host}set host(e){this[l].url.host=e}get hostname(){return this[l].url.hostname}set hostname(e){this[l].url.hostname=e}get port(){return this[l].url.port}set port(e){this[l].url.port=e}get protocol(){return this[l].url.protocol}set protocol(e){this[l].url.protocol=e}get href(){let e=this.formatPathname(),t=this.formatSearch();return`${this.protocol}//${this.host}${e}${t}${this.hash}`}set href(e){this[l].url=parseURL(e),this.analyze()}get origin(){return this[l].url.origin}get pathname(){return this[l].url.pathname}set pathname(e){this[l].url.pathname=e}get hash(){return this[l].url.hash}set hash(e){this[l].url.hash=e}get search(){return this[l].url.search}set search(e){this[l].url.search=e}get password(){return this[l].url.password}set password(e){this[l].url.password=e}get username(){return this[l].url.username}set username(e){this[l].url.username=e}get basePath(){return this[l].basePath}set basePath(e){this[l].basePath=e.startsWith("/")?e:`/${e}`}toString(){return this.href}toJSON(){return this.href}[Symbol.for("edge-runtime.inspect.custom")](){return{href:this.href,origin:this.origin,protocol:this.protocol,username:this.username,password:this.password,host:this.host,hostname:this.hostname,port:this.port,pathname:this.pathname,search:this.search,searchParams:this.searchParams,hash:this.hash}}clone(){return new NextURL(String(this),this[l].options)}}},1109:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RequestCookies:function(){return i.RequestCookies},ResponseCookies:function(){return i.ResponseCookies}});let i=r(8450)},8052:(e,t)=>{function ImageResponse(){throw Error('ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead')}Object.defineProperty(t,"E",{enumerable:!0,get:function(){return ImageResponse}})},3169:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERNALS:function(){return s},NextRequest:function(){return NextRequest}});let i=r(8098),o=r(1542),n=r(8726),a=r(1109),s=Symbol("internal request");let NextRequest=class NextRequest extends Request{constructor(e,t={}){let r="string"!=typeof e&&"url"in e?e.url:String(e);(0,o.validateURL)(r),e instanceof Request?super(e,t):super(r,t);let n=new i.NextURL(r,{headers:(0,o.toNodeOutgoingHttpHeaders)(this.headers),nextConfig:t.nextConfig});this[s]={cookies:new a.RequestCookies(this.headers),geo:t.geo||{},ip:t.ip,nextUrl:n,url:n.toString()}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,geo:this.geo,ip:this.ip,nextUrl:this.nextUrl,url:this.url,bodyUsed:this.bodyUsed,cache:this.cache,credentials:this.credentials,destination:this.destination,headers:Object.fromEntries(this.headers),integrity:this.integrity,keepalive:this.keepalive,method:this.method,mode:this.mode,redirect:this.redirect,referrer:this.referrer,referrerPolicy:this.referrerPolicy,signal:this.signal}}get cookies(){return this[s].cookies}get geo(){return this[s].geo}get ip(){return this[s].ip}get nextUrl(){return this[s].nextUrl}get page(){throw new n.RemovedPageError}get ua(){throw new n.RemovedUAError}get url(){return this[s].url}}},7715:(e,t,r)=>{Object.defineProperty(t,"x",{enumerable:!0,get:function(){return NextResponse}});let i=r(8098),o=r(1542),n=r(1109),a=Symbol("internal response"),s=new Set([301,302,303,307,308]);function handleMiddlewareField(e,t){var r;if(null==e?void 0:null==(r=e.request)?void 0:r.headers){if(!(e.request.headers instanceof Headers))throw Error("request.headers must be an instance of Headers");let r=[];for(let[i,o]of e.request.headers)t.set("x-middleware-request-"+i,o),r.push(i);t.set("x-middleware-override-headers",r.join(","))}}let NextResponse=class NextResponse extends Response{constructor(e,t={}){super(e,t),this[a]={cookies:new n.ResponseCookies(this.headers),url:t.url?new i.NextURL(t.url,{headers:(0,o.toNodeOutgoingHttpHeaders)(this.headers),nextConfig:t.nextConfig}):void 0}}[Symbol.for("edge-runtime.inspect.custom")](){return{cookies:this.cookies,url:this.url,body:this.body,bodyUsed:this.bodyUsed,headers:Object.fromEntries(this.headers),ok:this.ok,redirected:this.redirected,status:this.status,statusText:this.statusText,type:this.type}}get cookies(){return this[a].cookies}static json(e,t){let r=Response.json(e,t);return new NextResponse(r.body,r)}static redirect(e,t){let r="number"==typeof t?t:(null==t?void 0:t.status)??307;if(!s.has(r))throw RangeError('Failed to execute "redirect" on "response": Invalid status code');let i="object"==typeof t?t:{},n=new Headers(null==i?void 0:i.headers);return n.set("Location",(0,o.validateURL)(e)),new NextResponse(null,{...i,headers:n,status:r})}static rewrite(e,t){let r=new Headers(null==t?void 0:t.headers);return r.set("x-middleware-rewrite",(0,o.validateURL)(e)),handleMiddlewareField(t,r),new NextResponse(null,{...t,headers:r})}static next(e){let t=new Headers(null==e?void 0:e.headers);return t.set("x-middleware-next","1"),handleMiddlewareField(e,t),new NextResponse(null,{...e,headers:t})}}},1654:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{isBot:function(){return isBot},userAgentFromString:function(){return userAgentFromString},userAgent:function(){return userAgent}});let i=_interop_require_default(r(5842));function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}function isBot(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}function userAgentFromString(e){return{...(0,i.default)(e),isBot:void 0!==e&&isBot(e)}}function userAgent({headers:e}){return userAgentFromString(e.get("user-agent")||void 0)}},1542:(e,t)=>{function fromNodeOutgoingHttpHeaders(e){let t=new Headers;for(let[r,i]of Object.entries(e)){let e=Array.isArray(i)?i:[i];for(let i of e)void 0!==i&&("number"==typeof i&&(i=i.toString()),t.append(r,i))}return t}function splitCookiesString(e){var t,r,i,o,n,a=[],s=0;function skipWhitespace(){for(;s=e.length)&&a.push(e.substring(t,e.length))}return a}function toNodeOutgoingHttpHeaders(e){let t={},r=[];if(e)for(let[i,o]of e.entries())"set-cookie"===i.toLowerCase()?(r.push(...splitCookiesString(o)),t[i]=1===r.length?r[0]:r):t[i]=o;return t}function validateURL(e){try{return String(new URL(String(e)))}catch(t){throw Error(`URL is malformed "${String(e)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`,{cause:t})}}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{fromNodeOutgoingHttpHeaders:function(){return fromNodeOutgoingHttpHeaders},splitCookiesString:function(){return splitCookiesString},toNodeOutgoingHttpHeaders:function(){return toNodeOutgoingHttpHeaders},validateURL:function(){return validateURL}})},5913:(e,t)=>{function getHostname(e,t){let r;if((null==t?void 0:t.host)&&!Array.isArray(t.host))r=t.host.toString().split(":",1)[0];else{if(!e.hostname)return;r=e.hostname}return r.toLowerCase()}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getHostname",{enumerable:!0,get:function(){return getHostname}})},4582:(e,t)=>{function detectDomainLocale(e,t,r){if(e)for(let n of(r&&(r=r.toLowerCase()),e)){var i,o;let e=null==(i=n.domain)?void 0:i.split(":",1)[0].toLowerCase();if(t===e||r===n.defaultLocale.toLowerCase()||(null==(o=n.locales)?void 0:o.some(e=>e.toLowerCase()===r)))return n}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"detectDomainLocale",{enumerable:!0,get:function(){return detectDomainLocale}})},4340:(e,t)=>{function normalizeLocalePath(e,t){let r;let i=e.split("/");return(t||[]).some(t=>!!i[1]&&i[1].toLowerCase()===t.toLowerCase()&&(r=t,i.splice(1,1),e=i.join("/")||"/",!0)),{pathname:e,detectedLocale:r}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return normalizeLocalePath}})},446:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addLocale",{enumerable:!0,get:function(){return addLocale}});let i=r(8888),o=r(5794);function addLocale(e,t,r,n){if(!t||t===r)return e;let a=e.toLowerCase();return!n&&((0,o.pathHasPrefix)(a,"/api")||(0,o.pathHasPrefix)(a,"/"+t.toLowerCase()))?e:(0,i.addPathPrefix)(e,"/"+t)}},8888:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return addPathPrefix}});let i=r(3974);function addPathPrefix(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:n}=(0,i.parsePath)(e);return""+t+r+o+n}},8277:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathSuffix",{enumerable:!0,get:function(){return addPathSuffix}});let i=r(3974);function addPathSuffix(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:n}=(0,i.parsePath)(e);return""+r+t+o+n}},3987:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"formatNextPathnameInfo",{enumerable:!0,get:function(){return formatNextPathnameInfo}});let i=r(6976),o=r(8888),n=r(8277),a=r(446);function formatNextPathnameInfo(e){let t=(0,a.addLocale)(e.pathname,e.locale,e.buildId?void 0:e.defaultLocale,e.ignorePrefix);return(e.buildId||!e.trailingSlash)&&(t=(0,i.removeTrailingSlash)(t)),e.buildId&&(t=(0,n.addPathSuffix)((0,o.addPathPrefix)(t,"/_next/data/"+e.buildId),"/"===e.pathname?"index.json":".json")),t=(0,o.addPathPrefix)(t,e.basePath),!e.buildId&&e.trailingSlash?t.endsWith("/")?t:(0,n.addPathSuffix)(t,"/"):(0,i.removeTrailingSlash)(t)}},2020:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getNextPathnameInfo",{enumerable:!0,get:function(){return getNextPathnameInfo}});let i=r(4340),o=r(3863),n=r(5794);function getNextPathnameInfo(e,t){var r,a;let{basePath:s,i18n:l,trailingSlash:u}=null!=(r=t.nextConfig)?r:{},d={pathname:e,trailingSlash:"/"!==e?e.endsWith("/"):u};s&&(0,n.pathHasPrefix)(d.pathname,s)&&(d.pathname=(0,o.removePathPrefix)(d.pathname,s),d.basePath=s);let c=d.pathname;if(d.pathname.startsWith("/_next/data/")&&d.pathname.endsWith(".json")){let e=d.pathname.replace(/^\/_next\/data\//,"").replace(/\.json$/,"").split("/"),r=e[0];d.buildId=r,c="index"!==e[1]?"/"+e.slice(1).join("/"):"/",!0===t.parseData&&(d.pathname=c)}if(l){let e=t.i18nProvider?t.i18nProvider.analyze(d.pathname):(0,i.normalizeLocalePath)(d.pathname,l.locales);d.locale=e.detectedLocale,d.pathname=null!=(a=e.pathname)?a:d.pathname,!e.detectedLocale&&d.buildId&&(e=t.i18nProvider?t.i18nProvider.analyze(c):(0,i.normalizeLocalePath)(c,l.locales)).detectedLocale&&(d.locale=e.detectedLocale)}return d}},3974:(e,t)=>{function parsePath(e){let t=e.indexOf("#"),r=e.indexOf("?"),i=r>-1&&(t<0||r-1?{pathname:e.substring(0,i?r:t),query:i?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return parsePath}})},5794:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return pathHasPrefix}});let i=r(3974);function pathHasPrefix(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,i.parsePath)(e);return r===t||r.startsWith(t+"/")}},3863:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removePathPrefix",{enumerable:!0,get:function(){return removePathPrefix}});let i=r(5794);function removePathPrefix(e,t){if(!(0,i.pathHasPrefix)(e,t))return e;let r=e.slice(t.length);return r.startsWith("/")?r:"/"+r}},6976:(e,t)=>{function removeTrailingSlash(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},1057:(e,t,r)=>{let i={NextRequest:r(3169).NextRequest,NextResponse:r(7715).x,ImageResponse:r(8052).E,userAgentFromString:r(1654).userAgentFromString,userAgent:r(1654).userAgent};"undefined"!=typeof URLPattern&&(i.URLPattern=URLPattern),e.exports=i,t.NextRequest=i.NextRequest,t.NextResponse=i.NextResponse,t.ImageResponse=i.ImageResponse,t.userAgentFromString=i.userAgentFromString,t.userAgent=i.userAgent,t.URLPattern=i.URLPattern}}; \ No newline at end of file diff --git a/.next/server/chunks/310.js b/.next/server/chunks/310.js deleted file mode 100644 index e453be6..0000000 --- a/.next/server/chunks/310.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";exports.id=310,exports.ids=[310],exports.modules={7921:(e,r)=>{Object.defineProperty(r,"__esModule",{value:!0}),function(e,r){for(var t in r)Object.defineProperty(e,t,{enumerable:!0,get:r[t]})}(r,{WEB_VITALS:function(){return t},execOnce:function(){return execOnce},isAbsoluteUrl:function(){return isAbsoluteUrl},getLocationOrigin:function(){return getLocationOrigin},getURL:function(){return getURL},getDisplayName:function(){return getDisplayName},isResSent:function(){return isResSent},normalizeRepeatedSlashes:function(){return normalizeRepeatedSlashes},loadGetInitialProps:function(){return loadGetInitialProps},SP:function(){return o},ST:function(){return i},DecodeError:function(){return DecodeError},NormalizeError:function(){return NormalizeError},PageNotFoundError:function(){return PageNotFoundError},MissingStaticPage:function(){return MissingStaticPage},MiddlewareNotFoundError:function(){return MiddlewareNotFoundError},stringifyError:function(){return stringifyError}});let t=["CLS","FCP","FID","INP","LCP","TTFB"];function execOnce(e){let r,t=!1;return function(){for(var n=arguments.length,o=Array(n),i=0;in.test(e);function getLocationOrigin(){let{protocol:e,hostname:r,port:t}=window.location;return e+"//"+r+(t?":"+t:"")}function getURL(){let{href:e}=window.location,r=getLocationOrigin();return e.substring(r.length)}function getDisplayName(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function isResSent(e){return e.finished||e.headersSent}function normalizeRepeatedSlashes(e){let r=e.split("?"),t=r[0];return t.replace(/\\/g,"/").replace(/\/\/+/g,"/")+(r[1]?"?"+r.slice(1).join("?"):"")}async function loadGetInitialProps(e,r){let t=r.res||r.ctx&&r.ctx.res;if(!e.getInitialProps)return r.ctx&&r.Component?{pageProps:await loadGetInitialProps(r.Component,r.ctx)}:{};let n=await e.getInitialProps(r);if(t&&isResSent(t))return n;if(!n){let r='"'+getDisplayName(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.';throw Error(r)}return n}let o="undefined"!=typeof performance,i=o&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);let DecodeError=class DecodeError extends Error{};let NormalizeError=class NormalizeError extends Error{};let PageNotFoundError=class PageNotFoundError extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}};let MissingStaticPage=class MissingStaticPage extends Error{constructor(e,r){super(),this.message="Failed to load static file for page: "+e+" "+r}};let MiddlewareNotFoundError=class MiddlewareNotFoundError extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}};function stringifyError(e){return JSON.stringify({message:e.message,stack:e.stack})}},167:(e,r)=>{r._=r._interop_require_default=_interop_require_default;function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}}}; \ No newline at end of file diff --git a/.next/server/chunks/323.js b/.next/server/chunks/323.js deleted file mode 100644 index 7aae388..0000000 --- a/.next/server/chunks/323.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict";exports.id=323,exports.ids=[323],exports.modules={9001:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RSC:function(){return r},ACTION:function(){return n},NEXT_ROUTER_STATE_TREE:function(){return a},NEXT_ROUTER_PREFETCH:function(){return o},NEXT_URL:function(){return i},RSC_CONTENT_TYPE_HEADER:function(){return u},RSC_VARY_HEADER:function(){return s},FLIGHT_PARAMETERS:function(){return c},NEXT_RSC_UNION_QUERY:function(){return l}});let r="RSC",n="Next-Action",a="Next-Router-State-Tree",o="Next-Router-Prefetch",i="Next-Url",u="text/x-component",s=r+", "+a+", "+o+", "+i,c=[[r],[a],[o]],l="_rsc";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8712:e=>{(()=>{"undefined"!=typeof __nccwpck_require__&&(__nccwpck_require__.ab=__dirname+"/");var t={};(()=>{/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */t.parse=parse,t.serialize=serialize;var e=decodeURIComponent,r=encodeURIComponent,n=/; */,a=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function parse(t,r){if("string"!=typeof t)throw TypeError("argument str must be a string");for(var a={},o=t.split(n),i=(r||{}).decode||e,u=0;u{function lexer(e){for(var t=[],r=0;r=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122||95===i){a+=e[o++];continue}break}if(!a)throw TypeError("Missing parameter name at "+r);t.push({type:"NAME",index:r,value:a}),r=o;continue}if("("===n){var u=1,s="",o=r+1;if("?"===e[o])throw TypeError('Pattern cannot start with "?" at '+o);for(;o-1:void 0===h;a||(p+="(?:"+l+"(?="+c+"))?"),E||(p+="(?="+l+"|"+c+")")}return new RegExp(p,flags(r))}function pathToRegexp(e,t,r){return e instanceof RegExp?regexpToRegexp(e,t):Array.isArray(e)?arrayToRegexp(e,t,r):stringToRegexp(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t.parse=parse,t.compile=compile,t.tokensToFunction=tokensToFunction,t.match=match,t.regexpToFunction=regexpToFunction,t.tokensToRegexp=tokensToRegexp,t.pathToRegexp=pathToRegexp},9368:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_QUERY_PARAM_PREFIX:function(){return r},PRERENDER_REVALIDATE_HEADER:function(){return n},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return a},NEXT_DID_POSTPONE_HEADER:function(){return o},NEXT_CACHE_TAGS_HEADER:function(){return i},NEXT_CACHE_SOFT_TAGS_HEADER:function(){return u},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return s},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return c},NEXT_CACHE_TAG_MAX_LENGTH:function(){return l},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return p},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return f},CACHE_ONE_YEAR:function(){return d},MIDDLEWARE_FILENAME:function(){return g},MIDDLEWARE_LOCATION_REGEXP:function(){return m},INSTRUMENTATION_HOOK_FILENAME:function(){return R},PAGES_DIR_ALIAS:function(){return h},DOT_NEXT_ALIAS:function(){return E},ROOT_DIR_ALIAS:function(){return _},APP_DIR_ALIAS:function(){return y},RSC_MOD_REF_PROXY_ALIAS:function(){return x},RSC_ACTION_VALIDATE_ALIAS:function(){return P},RSC_ACTION_PROXY_ALIAS:function(){return S},RSC_ACTION_ENCRYPTION_ALIAS:function(){return v},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return A},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return T},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return b},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return O},SERVER_PROPS_SSG_CONFLICT:function(){return N},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return C},SERVER_PROPS_EXPORT_ERROR:function(){return I},GSP_NO_RETURNED_VALUE:function(){return M},GSSP_NO_RETURNED_VALUE:function(){return j},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return L},GSSP_COMPONENT_MEMBER_ERROR:function(){return w},NON_STANDARD_NODE_ENV:function(){return U},SSG_FALLBACK_EXPORT_ERROR:function(){return D},ESLINT_DEFAULT_DIRS:function(){return k},ESLINT_PROMPT_VALUES:function(){return $},SERVER_RUNTIME:function(){return F},WEBPACK_LAYERS:function(){return H},WEBPACK_RESOURCE_QUERIES:function(){return G}});let r="nxtP",n="x-prerender-revalidate",a="x-prerender-revalidate-if-generated",o="x-nextjs-postponed",i="x-next-cache-tags",u="x-next-cache-soft-tags",s="x-next-revalidated-tags",c="x-next-revalidate-tag-token",l=256,p=1024,f="_N_T_",d=31536e3,g="middleware",m=`(?:src/)?${g}`,R="instrumentation",h="private-next-pages",E="private-dot-next",_="private-next-root-dir",y="private-next-app-dir",x="next/dist/build/webpack/loaders/next-flight-loader/module-proxy",P="private-next-rsc-action-validate",S="private-next-rsc-action-proxy",v="private-next-rsc-action-encryption",A="private-next-rsc-action-client-wrapper",T="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",b="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",O="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",N="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",C="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",I="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",M="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",j="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",L="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",w="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",U='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',D="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",k=["app","pages","components","lib","src"],$=[{title:"Strict",recommended:!0,config:{extends:"next/core-web-vitals"}},{title:"Base",config:{extends:"next"}},{title:"Cancel",config:null}],F={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},z={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",appMetadataRoute:"app-metadata-route",appRouteHandler:"app-route-handler"},H={...z,GROUP:{server:[z.reactServerComponents,z.actionBrowser,z.appMetadataRoute,z.appRouteHandler],nonClientServerTarget:[z.middleware,z.api],app:[z.reactServerComponents,z.actionBrowser,z.appMetadataRoute,z.appRouteHandler,z.serverSideRendering,z.appPagesBrowser]}},G={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},8531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{fillMetadataSegment:function(){return fillMetadataSegment},normalizeMetadataRoute:function(){return normalizeMetadataRoute}});let n=r(2038),a=_interop_require_default(r(5585)),o=r(1239),i=r(4018),u=r(8043),s=r(1478),c=r(7819);function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}function getMetadataRouteSuffix(e){let t="";return(e.includes("(")&&e.includes(")")||e.includes("@"))&&(t=(0,u.djb2Hash)(e).toString(36).slice(0,6)),t}function fillMetadataSegment(e,t,r){let n=(0,s.normalizeAppPath)(e),u=(0,i.getNamedRouteRegex)(n,!1),l=(0,o.interpolateDynamicPath)(n,t,u),p=getMetadataRouteSuffix(e),f=p?`-${p}`:"",{name:d,ext:g}=a.default.parse(r);return(0,c.normalizePathSep)(a.default.join(l,`${d}${f}${g}`))}function normalizeMetadataRoute(e){if(!(0,n.isMetadataRoute)(e))return e;let t=e,r="";if("/robots"===e)t+=".txt";else if("/manifest"===e)t+=".webmanifest";else if(e.endsWith("/sitemap"))t+=".xml";else{let t=e.slice(0,-(a.default.basename(e).length+1));r=getMetadataRouteSuffix(t)}if(!t.endsWith("/route")){let{dir:o,name:i,ext:u}=a.default.parse(t),s=(0,n.isStaticMetadataRoute)(e);t=a.default.posix.join(o,`${i}${r?`-${r}`:""}${u}`,s?"":"[[...__metadata_id__]]","route")}return t}},2038:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{STATIC_METADATA_IMAGES:function(){return a},isMetadataRouteFile:function(){return isMetadataRouteFile},isStaticMetadataRouteFile:function(){return isStaticMetadataRouteFile},isStaticMetadataRoute:function(){return isStaticMetadataRoute},isMetadataRoute:function(){return isMetadataRoute}});let n=r(7819),a={icon:{filename:"icon",extensions:["ico","jpg","jpeg","png","svg"]},apple:{filename:"apple-icon",extensions:["jpg","jpeg","png"]},favicon:{filename:"favicon",extensions:["ico"]},openGraph:{filename:"opengraph-image",extensions:["jpg","jpeg","png","gif"]},twitter:{filename:"twitter-image",extensions:["jpg","jpeg","png","gif"]}},o=["js","jsx","ts","tsx"],getExtensionRegexString=e=>`(?:${e.join("|")})`;function isMetadataRouteFile(e,t,r){let o=[RegExp(`^[\\\\/]robots${r?`\\.${getExtensionRegexString(t.concat("txt"))}$`:""}`),RegExp(`^[\\\\/]manifest${r?`\\.${getExtensionRegexString(t.concat("webmanifest","json"))}$`:""}`),RegExp("^[\\\\/]favicon\\.ico$"),RegExp(`[\\\\/]sitemap${r?`\\.${getExtensionRegexString(t.concat("xml"))}$`:""}`),RegExp(`[\\\\/]${a.icon.filename}\\d?${r?`\\.${getExtensionRegexString(t.concat(a.icon.extensions))}$`:""}`),RegExp(`[\\\\/]${a.apple.filename}\\d?${r?`\\.${getExtensionRegexString(t.concat(a.apple.extensions))}$`:""}`),RegExp(`[\\\\/]${a.openGraph.filename}\\d?${r?`\\.${getExtensionRegexString(t.concat(a.openGraph.extensions))}$`:""}`),RegExp(`[\\\\/]${a.twitter.filename}\\d?${r?`\\.${getExtensionRegexString(t.concat(a.twitter.extensions))}$`:""}`)],i=(0,n.normalizePathSep)(e);return o.some(e=>e.test(i))}function isStaticMetadataRouteFile(e){return isMetadataRouteFile(e,[],!0)}function isStaticMetadataRoute(e){return"/robots"===e||"/manifest"===e||isStaticMetadataRouteFile(e)}function isMetadataRoute(e){let t=e.replace(/^\/?app\//,"").replace(/\/route$/,"");return"/"!==t[0]&&(t="/"+t),!t.endsWith("/page")&&isMetadataRouteFile(t,o,!1)}},4427:(e,t,r)=>{function getCookieParser(e){return function(){let{cookie:t}=e;if(!t)return{};let{parse:n}=r(8712);return n(Array.isArray(t)?t.join("; "):t)}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getCookieParser",{enumerable:!0,get:function(){return getCookieParser}})},7302:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return a},isInterceptionRouteAppPath:function(){return isInterceptionRouteAppPath},extractInterceptionRouteInformation:function(){return extractInterceptionRouteInformation}});let n=r(1478),a=["(..)(..)","(.)","(..)","(...)"];function isInterceptionRouteAppPath(e){return void 0!==e.split("/").find(e=>a.find(t=>e.startsWith(t)))}function extractInterceptionRouteInformation(e){let t,r,o;for(let n of e.split("/"))if(r=a.find(e=>n.startsWith(e))){[t,o]=e.split(r,2);break}if(!t||!r||!o)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":o="/"===t?`/${o}`:t+"/"+o;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);o=t.split("/").slice(0,-1).concat(o).join("/");break;case"(...)":o="/"+o;break;case"(..)(..)":let i=t.split("/");if(i.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);o=i.slice(0,-2).concat(o).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:o}}},1239:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeVercelUrl:function(){return normalizeVercelUrl},interpolateDynamicPath:function(){return interpolateDynamicPath},getUtils:function(){return getUtils}});let n=r(7310),a=r(5259),o=r(9302),i=r(4018),u=r(4893),s=r(1731),c=r(4419),l=r(1478),p=r(9368);function normalizeVercelUrl(e,t,r,a,o){if(a&&t&&o){let t=(0,n.parse)(e.url,!0);for(let e of(delete t.search,Object.keys(t.query)))(e!==p.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(p.NEXT_QUERY_PARAM_PREFIX)||(r||Object.keys(o.groups)).includes(e))&&delete t.query[e];e.url=(0,n.format)(t)}}function interpolateDynamicPath(e,t,r){if(!r)return e;for(let n of Object.keys(r.groups)){let{optional:a,repeat:o}=r.groups[n],i=`[${o?"...":""}${n}]`;a&&(i=`[${i}]`);let u=e.indexOf(i);if(u>-1){let r;let a=t[n];r=Array.isArray(a)?a.map(e=>e&&encodeURIComponent(e)).join("/"):a?encodeURIComponent(a):"",e=e.slice(0,u)+r+e.slice(u+i.length)}}return e}function getUtils({page:e,i18n:t,basePath:r,rewrites:n,pageIsDynamic:f,trailingSlash:d,caseSensitive:g}){let m,R,h;function getParamsFromRouteMatches(e,r,n){return(0,u.getRouteMatcher)(function(){let{groups:e,routeKeys:a}=m;return{re:{exec:o=>{let i=Object.fromEntries(new URLSearchParams(o)),u=t&&n&&i["1"]===n;for(let e of Object.keys(i)){let t=i[e];if(e!==p.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(p.NEXT_QUERY_PARAM_PREFIX)){let r=e.substring(p.NEXT_QUERY_PARAM_PREFIX.length);i[r]=t,delete i[e]}}let s=Object.keys(a||{}),filterLocaleItem=e=>{if(t){let a=Array.isArray(e),o=a?e[0]:e;if("string"==typeof o&&t.locales.some(e=>e.toLowerCase()===o.toLowerCase()&&(n=e,r.locale=n,!0)))return a&&e.splice(0,1),!a||0===e.length}return!1};return s.every(e=>i[e])?s.reduce((t,r)=>{let n=null==a?void 0:a[r];return n&&!filterLocaleItem(i[r])&&(t[e[n].pos]=i[r]),t},{}):Object.keys(i).reduce((e,t)=>{if(!filterLocaleItem(i[t])){let r=t;return u&&(r=parseInt(t,10)-1+""),Object.assign(e,{[r]:i[t]})}return e},{})}},groups:e}}())(e.headers["x-now-route-matches"])}function normalizeDynamicRouteParams(e,t){let r=!0;return m?{params:e=Object.keys(m.groups).reduce((n,a)=>{let o=e[a];"string"==typeof o&&(o=(0,l.normalizeRscURL)(o)),Array.isArray(o)&&(o=o.map(e=>("string"==typeof e&&(e=(0,l.normalizeRscURL)(e)),e)));let i=h[a],u=m.groups[a].optional,s=Array.isArray(i)?i.some(e=>Array.isArray(o)?o.some(t=>t.includes(e)):null==o?void 0:o.includes(e)):null==o?void 0:o.includes(i);return(s||void 0===o&&!(u&&t))&&(r=!1),u&&(!o||Array.isArray(o)&&1===o.length&&("index"===o[0]||o[0]===`[[...${a}]]`))&&(o=void 0,delete e[a]),o&&"string"==typeof o&&m.groups[a].repeat&&(o=o.split("/")),o&&(n[a]=o),n},{}),hasValidParams:r}:{params:e,hasValidParams:!1}}return f&&(m=(0,i.getNamedRouteRegex)(e,!1),h=(R=(0,u.getRouteMatcher)(m))(e)),{handleRewrites:function(i,u){let l={},p=u.pathname,checkRewrite=n=>{let c=(0,o.getPathMatch)(n.source+(d?"(/)?":""),{removeUnnamedParams:!0,strict:!0,sensitive:!!g}),m=c(u.pathname);if((n.has||n.missing)&&m){let e=(0,s.matchHas)(i,u.query,n.has,n.missing);e?Object.assign(m,e):m=!1}if(m){let{parsedDestination:o,destQuery:i}=(0,s.prepareDestination)({appendParamsToQuery:!0,destination:n.destination,params:m,query:u.query});if(o.protocol)return!0;if(Object.assign(l,i,m),Object.assign(u.query,o.query),delete o.query,Object.assign(u,o),p=u.pathname,r&&(p=p.replace(RegExp(`^${r}`),"")||"/"),t){let e=(0,a.normalizeLocalePath)(p,t.locales);p=e.pathname,u.query.nextInternalLocale=e.detectedLocale||m.nextInternalLocale}if(p===e)return!0;if(f&&R){let e=R(p);if(e)return u.query={...u.query,...e},!0}}return!1};for(let e of n.beforeFiles||[])checkRewrite(e);if(p!==e){let t=!1;for(let e of n.afterFiles||[])if(t=checkRewrite(e))break;if(!t&&!(()=>{let t=(0,c.removeTrailingSlash)(p||"");return t===(0,c.removeTrailingSlash)(e)||(null==R?void 0:R(t))})()){for(let e of n.fallback||[])if(t=checkRewrite(e))break}}return l},defaultRouteRegex:m,dynamicRouteMatcher:R,defaultRouteMatches:h,getParamsFromRouteMatches,normalizeDynamicRouteParams,normalizeVercelUrl:(e,t,r)=>normalizeVercelUrl(e,t,r,f,m),interpolateDynamicPath:(e,t)=>interpolateDynamicPath(e,t,m)}}},9789:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"escapeStringRegexp",{enumerable:!0,get:function(){return escapeStringRegexp}});let r=/[|\\{}()[\]^$+*?.-]/,n=/[|\\{}()[\]^$+*?.-]/g;function escapeStringRegexp(e){return r.test(e)?e.replace(n,"\\$&"):e}},8043:(e,t)=>{function djb2Hash(e){let t=5381;for(let r=0;r{function normalizeLocalePath(e,t){let r;let n=e.split("/");return(t||[]).some(t=>!!n[1]&&n[1].toLowerCase()===t.toLowerCase()&&(r=t,n.splice(1,1),e=n.join("/")||"/",!0)),{pathname:e,detectedLocale:r}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return normalizeLocalePath}})},5585:(e,t,r)=>{let n;n=r(1017),e.exports=n},9701:(e,t)=>{function ensureLeadingSlash(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return ensureLeadingSlash}})},7819:(e,t)=>{function normalizePathSep(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return normalizePathSep}})},1478:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return normalizeAppPath},normalizeRscURL:function(){return normalizeRscURL},normalizePostponedURL:function(){return normalizePostponedURL}});let n=r(9701),a=r(2219);function normalizeAppPath(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,a.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function normalizeRscURL(e){return e.replace(/\.rsc($|\?)/,"$1")}function normalizePostponedURL(e){let t=new URL(e),{pathname:r}=t;return r&&r.startsWith("/_next/postponed")?(t.pathname=r.substring(16)||"/",t.toString()):e}},129:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseRelativeUrl",{enumerable:!0,get:function(){return parseRelativeUrl}}),r(351);let n=r(6024);function parseRelativeUrl(e,t){let r=new URL("http://n"),a=t?new URL(t,r):e.startsWith(".")?new URL("http://n"):r,{pathname:o,searchParams:i,search:u,hash:s,href:c,origin:l}=new URL(e,a);if(l!==r.origin)throw Error("invariant: invalid relative URL, router received "+e);return{pathname:o,query:(0,n.searchParamsToUrlQuery)(i),search:u,hash:s,href:c.slice(r.origin.length)}}},6940:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseUrl",{enumerable:!0,get:function(){return parseUrl}});let n=r(6024),a=r(129);function parseUrl(e){if(e.startsWith("/"))return(0,a.parseRelativeUrl)(e);let t=new URL(e);return{hash:t.hash,hostname:t.hostname,href:t.href,pathname:t.pathname,port:t.port,protocol:t.protocol,query:(0,n.searchParamsToUrlQuery)(t.searchParams),search:t.search}}},9302:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getPathMatch",{enumerable:!0,get:function(){return getPathMatch}});let n=r(9481);function getPathMatch(e,t){let r=[],a=(0,n.pathToRegexp)(e,r,{delimiter:"/",sensitive:"boolean"==typeof(null==t?void 0:t.sensitive)&&t.sensitive,strict:null==t?void 0:t.strict}),o=(0,n.regexpToFunction)((null==t?void 0:t.regexModifier)?new RegExp(t.regexModifier(a.source),a.flags):a,r);return(e,n)=>{if("string"!=typeof e)return!1;let a=o(e);if(!a)return!1;if(null==t?void 0:t.removeUnnamedParams)for(let e of r)"number"==typeof e.name&&delete a.params[e.name];return{...n,...a.params}}}},1731:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{matchHas:function(){return matchHas},compileNonPath:function(){return compileNonPath},prepareDestination:function(){return prepareDestination}});let n=r(9481),a=r(9789),o=r(6940),i=r(7302),u=r(9001),s=r(4427);function getSafeParamName(e){let t="";for(let r=0;r64&&n<91||n>96&&n<123)&&(t+=e[r])}return t}function escapeSegment(e,t){return e.replace(RegExp(":"+(0,a.escapeStringRegexp)(t),"g"),"__ESC_COLON_"+t)}function unescapeSegments(e){return e.replace(/__ESC_COLON_/gi,":")}function matchHas(e,t,r,n){void 0===r&&(r=[]),void 0===n&&(n=[]);let a={},hasMatch=r=>{let n;let o=r.key;switch(r.type){case"header":o=o.toLowerCase(),n=e.headers[o];break;case"cookie":if("cookies"in e)n=e.cookies[r.key];else{let t=(0,s.getCookieParser)(e.headers)();n=t[r.key]}break;case"query":n=t[o];break;case"host":{let{host:t}=(null==e?void 0:e.headers)||{},r=null==t?void 0:t.split(":",1)[0].toLowerCase();n=r}}if(!r.value&&n)return a[getSafeParamName(o)]=n,!0;if(n){let e=RegExp("^"+r.value+"$"),t=Array.isArray(n)?n.slice(-1)[0].match(e):n.match(e);if(t)return Array.isArray(t)&&(t.groups?Object.keys(t.groups).forEach(e=>{a[e]=t.groups[e]}):"host"===r.type&&t[0]&&(a.host=t[0])),!0}return!1},o=r.every(e=>hasMatch(e))&&!n.some(e=>hasMatch(e));return!!o&&a}function compileNonPath(e,t){if(!e.includes(":"))return e;for(let r of Object.keys(t))e.includes(":"+r)&&(e=e.replace(RegExp(":"+r+"\\*","g"),":"+r+"--ESCAPED_PARAM_ASTERISKS").replace(RegExp(":"+r+"\\?","g"),":"+r+"--ESCAPED_PARAM_QUESTION").replace(RegExp(":"+r+"\\+","g"),":"+r+"--ESCAPED_PARAM_PLUS").replace(RegExp(":"+r+"(?!\\w)","g"),"--ESCAPED_PARAM_COLON"+r));return e=e.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g,"\\$1").replace(/--ESCAPED_PARAM_PLUS/g,"+").replace(/--ESCAPED_PARAM_COLON/g,":").replace(/--ESCAPED_PARAM_QUESTION/g,"?").replace(/--ESCAPED_PARAM_ASTERISKS/g,"*"),(0,n.compile)("/"+e,{validate:!1})(t).slice(1)}function prepareDestination(e){let t;let r=Object.assign({},e.query);delete r.__nextLocale,delete r.__nextDefaultLocale,delete r.__nextDataReq,delete r.__nextInferredLocaleFromDefault,delete r[u.NEXT_RSC_UNION_QUERY];let a=e.destination;for(let t of Object.keys({...e.params,...r}))a=escapeSegment(a,t);let s=(0,o.parseUrl)(a),c=s.query,l=unescapeSegments(""+s.pathname+(s.hash||"")),p=unescapeSegments(s.hostname||""),f=[],d=[];(0,n.pathToRegexp)(l,f),(0,n.pathToRegexp)(p,d);let g=[];f.forEach(e=>g.push(e.name)),d.forEach(e=>g.push(e.name));let m=(0,n.compile)(l,{validate:!1}),R=(0,n.compile)(p,{validate:!1});for(let[t,r]of Object.entries(c))Array.isArray(r)?c[t]=r.map(t=>compileNonPath(unescapeSegments(t),e.params)):"string"==typeof r&&(c[t]=compileNonPath(unescapeSegments(r),e.params));let h=Object.keys(e.params).filter(e=>"nextInternalLocale"!==e);if(e.appendParamsToQuery&&!h.some(e=>g.includes(e)))for(let t of h)t in c||(c[t]=e.params[t]);if((0,i.isInterceptionRouteAppPath)(l))for(let t of l.split("/")){let r=i.INTERCEPTION_ROUTE_MARKERS.find(e=>t.startsWith(e));if(r){e.params["0"]=r;break}}try{t=m(e.params);let[r,n]=t.split("#",2);s.hostname=R(e.params),s.pathname=r,s.hash=(n?"#":"")+(n||""),delete s.search}catch(e){if(e.message.match(/Expected .*? to not repeat, but got an array/))throw Error("To use a multi-match in the destination you must add `*` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match");throw e}return s.query={...r,...s.query},{newUrl:t,destQuery:c,parsedDestination:s}}},6024:(e,t)=>{function searchParamsToUrlQuery(e){let t={};return e.forEach((e,r)=>{void 0===t[r]?t[r]=e:Array.isArray(t[r])?t[r].push(e):t[r]=[t[r],e]}),t}function stringifyUrlQueryParam(e){return"string"!=typeof e&&("number"!=typeof e||isNaN(e))&&"boolean"!=typeof e?"":String(e)}function urlQueryToSearchParams(e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[r,n]=e;Array.isArray(n)?n.forEach(e=>t.append(r,stringifyUrlQueryParam(e))):t.set(r,stringifyUrlQueryParam(n))}),t}function assign(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n{Array.from(t.keys()).forEach(t=>e.delete(t)),t.forEach((t,r)=>e.append(r,t))}),e}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{searchParamsToUrlQuery:function(){return searchParamsToUrlQuery},urlQueryToSearchParams:function(){return urlQueryToSearchParams},assign:function(){return assign}})},4419:(e,t)=>{function removeTrailingSlash(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},4893:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getRouteMatcher",{enumerable:!0,get:function(){return getRouteMatcher}});let n=r(351);function getRouteMatcher(e){let{re:t,groups:r}=e;return e=>{let a=t.exec(e);if(!a)return!1;let decode=e=>{try{return decodeURIComponent(e)}catch(e){throw new n.DecodeError("failed to decode param")}},o={};return Object.keys(r).forEach(e=>{let t=r[e],n=a[t.pos];void 0!==n&&(o[e]=~n.indexOf("/")?n.split("/").map(e=>decode(e)):t.repeat?[decode(n)]:decode(n))}),o}}},4018:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getRouteRegex:function(){return getRouteRegex},getNamedRouteRegex:function(){return getNamedRouteRegex},getNamedMiddlewareRegex:function(){return getNamedMiddlewareRegex}});let n=r(7302),a=r(9789),o=r(4419);function parseParameter(e){let t=e.startsWith("[")&&e.endsWith("]");t&&(e=e.slice(1,-1));let r=e.startsWith("...");return r&&(e=e.slice(3)),{key:e,repeat:r,optional:t}}function getParametrizedRoute(e){let t=(0,o.removeTrailingSlash)(e).slice(1).split("/"),r={},i=1;return{parameterizedRoute:t.map(e=>{let t=n.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);if(t&&o){let{key:e,optional:n,repeat:u}=parseParameter(o[1]);return r[e]={pos:i++,repeat:u,optional:n},"/"+(0,a.escapeStringRegexp)(t)+"([^/]+?)"}if(!o)return"/"+(0,a.escapeStringRegexp)(e);{let{key:e,repeat:t,optional:n}=parseParameter(o[1]);return r[e]={pos:i++,repeat:t,optional:n},t?n?"(?:/(.+?))?":"/(.+?)":"/([^/]+?)"}}).join(""),groups:r}}function getRouteRegex(e){let{parameterizedRoute:t,groups:r}=getParametrizedRoute(e);return{re:RegExp("^"+t+"(?:/)?$"),groups:r}}function buildGetSafeRouteKey(){let e=0;return()=>{let t="",r=++e;for(;r>0;)t+=String.fromCharCode(97+(r-1)%26),r=Math.floor((r-1)/26);return t}}function getSafeKeyFromSegment(e){let{getSafeRouteKey:t,segment:r,routeKeys:n,keyPrefix:a}=e,{key:o,optional:i,repeat:u}=parseParameter(r),s=o.replace(/\W/g,"");a&&(s=""+a+s);let c=!1;return(0===s.length||s.length>30)&&(c=!0),isNaN(parseInt(s.slice(0,1)))||(c=!0),c&&(s=t()),a?n[s]=""+a+o:n[s]=""+o,u?i?"(?:/(?<"+s+">.+?))?":"/(?<"+s+">.+?)":"/(?<"+s+">[^/]+?)"}function getNamedParametrizedRoute(e,t){let r=(0,o.removeTrailingSlash)(e).slice(1).split("/"),i=buildGetSafeRouteKey(),u={};return{namedParameterizedRoute:r.map(e=>{let r=n.INTERCEPTION_ROUTE_MARKERS.some(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);return r&&o?getSafeKeyFromSegment({getSafeRouteKey:i,segment:o[1],routeKeys:u,keyPrefix:t?"nxtI":void 0}):o?getSafeKeyFromSegment({getSafeRouteKey:i,segment:o[1],routeKeys:u,keyPrefix:t?"nxtP":void 0}):"/"+(0,a.escapeStringRegexp)(e)}).join(""),routeKeys:u}}function getNamedRouteRegex(e,t){let r=getNamedParametrizedRoute(e,t);return{...getRouteRegex(e),namedRegex:"^"+r.namedParameterizedRoute+"(?:/)?$",routeKeys:r.routeKeys}}function getNamedMiddlewareRegex(e,t){let{parameterizedRoute:r}=getParametrizedRoute(e),{catchAll:n=!0}=t;if("/"===r)return{namedRegex:"^/"+(n?".*":"")+"$"};let{namedParameterizedRoute:a}=getNamedParametrizedRoute(e,!1);return{namedRegex:"^"+a+(n?"(?:(/.*)?)":"")+"$"}}},2219:(e,t)=>{function isGroupSegment(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isGroupSegment",{enumerable:!0,get:function(){return isGroupSegment}})},351:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{WEB_VITALS:function(){return r},execOnce:function(){return execOnce},isAbsoluteUrl:function(){return isAbsoluteUrl},getLocationOrigin:function(){return getLocationOrigin},getURL:function(){return getURL},getDisplayName:function(){return getDisplayName},isResSent:function(){return isResSent},normalizeRepeatedSlashes:function(){return normalizeRepeatedSlashes},loadGetInitialProps:function(){return loadGetInitialProps},SP:function(){return a},ST:function(){return o},DecodeError:function(){return DecodeError},NormalizeError:function(){return NormalizeError},PageNotFoundError:function(){return PageNotFoundError},MissingStaticPage:function(){return MissingStaticPage},MiddlewareNotFoundError:function(){return MiddlewareNotFoundError},stringifyError:function(){return stringifyError}});let r=["CLS","FCP","FID","INP","LCP","TTFB"];function execOnce(e){let t,r=!1;return function(){for(var n=arguments.length,a=Array(n),o=0;on.test(e);function getLocationOrigin(){let{protocol:e,hostname:t,port:r}=window.location;return e+"//"+t+(r?":"+r:"")}function getURL(){let{href:e}=window.location,t=getLocationOrigin();return e.substring(t.length)}function getDisplayName(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function isResSent(e){return e.finished||e.headersSent}function normalizeRepeatedSlashes(e){let t=e.split("?"),r=t[0];return r.replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function loadGetInitialProps(e,t){let r=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await loadGetInitialProps(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(r&&isResSent(r))return n;if(!n){let t='"'+getDisplayName(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.';throw Error(t)}return n}let a="undefined"!=typeof performance,o=a&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);let DecodeError=class DecodeError extends Error{};let NormalizeError=class NormalizeError extends Error{};let PageNotFoundError=class PageNotFoundError extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}};let MissingStaticPage=class MissingStaticPage extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}};let MiddlewareNotFoundError=class MiddlewareNotFoundError extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}};function stringifyError(e){return JSON.stringify({message:e.message,stack:e.stack})}}}; \ No newline at end of file diff --git a/.next/server/chunks/329.js b/.next/server/chunks/329.js new file mode 100644 index 0000000..413ba93 --- /dev/null +++ b/.next/server/chunks/329.js @@ -0,0 +1,6 @@ +"use strict";exports.id=329,exports.ids=[329],exports.modules={2329:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{Head:function(){return E},NextScript:function(){return g},Html:function(){return y},Main:function(){return S},default:function(){return I}});let r=u(n(6689)),i=n(1841),o=n(5778),s=n(9630),a=u(n(676)),l=n(3112);function u(e){return e&&e.__esModule?e:{default:e}}let c=new Set;function f(e,t,n){let r=(0,o.getPageFiles)(e,"/_app"),i=n?[]:(0,o.getPageFiles)(e,t);return{sharedFiles:r,pageFiles:i,allFiles:[...new Set([...r,...i])]}}function d(e,t){let{assetPrefix:n,buildManifest:i,assetQueryString:o,disableOptimizedLoading:s,crossOrigin:a}=e;return i.polyfillFiles.filter(e=>e.endsWith(".js")&&!e.endsWith(".module.js")).map(e=>r.default.createElement("script",{key:e,defer:!s,nonce:t.nonce,crossOrigin:t.crossOrigin||a,noModule:!0,src:`${n}/_next/${e}${o}`}))}function p({styles:e}){if(!e)return null;let t=Array.isArray(e)?e:[];if(e.props&&Array.isArray(e.props.children)){let n=e=>{var t,n;return null==e?void 0:null==(n=e.props)?void 0:null==(t=n.dangerouslySetInnerHTML)?void 0:t.__html};e.props.children.forEach(e=>{Array.isArray(e)?e.forEach(e=>n(e)&&t.push(e)):n(e)&&t.push(e)})}return r.default.createElement("style",{"amp-custom":"",dangerouslySetInnerHTML:{__html:t.map(e=>e.props.dangerouslySetInnerHTML.__html).join("").replace(/\/\*# sourceMappingURL=.*\*\//g,"").replace(/\/\*@ sourceURL=.*?\*\//g,"")}})}function h(e,t,n){let{dynamicImports:i,assetPrefix:o,isDevelopment:s,assetQueryString:a,disableOptimizedLoading:l,crossOrigin:u}=e;return i.map(e=>!e.endsWith(".js")||n.allFiles.includes(e)?null:r.default.createElement("script",{async:!s&&l,defer:!l,key:e,src:`${o}/_next/${encodeURI(e)}${a}`,nonce:t.nonce,crossOrigin:t.crossOrigin||u}))}function m(e,t,n){var i;let{assetPrefix:o,buildManifest:s,isDevelopment:a,assetQueryString:l,disableOptimizedLoading:u,crossOrigin:c}=e;return[...n.allFiles.filter(e=>e.endsWith(".js")),...null==(i=s.lowPriorityFiles)?void 0:i.filter(e=>e.endsWith(".js"))].map(e=>r.default.createElement("script",{key:e,src:`${o}/_next/${encodeURI(e)}${l}`,nonce:t.nonce,async:!a&&u,defer:!u,crossOrigin:t.crossOrigin||c}))}function _(e,t){let{scriptLoader:n,disableOptimizedLoading:i,crossOrigin:o}=e,s=function(e,t){let{assetPrefix:n,scriptLoader:i,crossOrigin:o,nextScriptWorkers:s}=e;if(!s)return null;try{let{partytownSnippet:e}=require("@builder.io/partytown/integration"),s=(Array.isArray(t.children)?t.children:[t.children]).find(e=>{var t,n;return!!e&&!!e.props&&(null==e?void 0:null==(n=e.props)?void 0:null==(t=n.dangerouslySetInnerHTML)?void 0:t.__html.length)&&"data-partytown-config"in e.props});return r.default.createElement(r.default.Fragment,null,!s&&r.default.createElement("script",{"data-partytown-config":"",dangerouslySetInnerHTML:{__html:` + partytown = { + lib: "${n}/_next/static/~partytown/" + }; + `}}),r.default.createElement("script",{"data-partytown":"",dangerouslySetInnerHTML:{__html:e()}}),(i.worker||[]).map((e,n)=>{let{strategy:i,src:s,children:a,dangerouslySetInnerHTML:l,...u}=e,c={};if(s)c.src=s;else if(l&&l.__html)c.dangerouslySetInnerHTML={__html:l.__html};else if(a)c.dangerouslySetInnerHTML={__html:"string"==typeof a?a:Array.isArray(a)?a.join(""):""};else throw Error("Invalid usage of next/script. Did you forget to include a src attribute or an inline script? https://nextjs.org/docs/messages/invalid-script");return r.default.createElement("script",{...c,...u,type:"text/partytown",key:s||n,nonce:t.nonce,"data-nscript":"worker",crossOrigin:t.crossOrigin||o})}))}catch(e){return(0,a.default)(e)&&"MODULE_NOT_FOUND"!==e.code&&console.warn(`Warning: ${e.message}`),null}}(e,t),l=(n.beforeInteractive||[]).filter(e=>e.src).map((e,n)=>{let{strategy:s,...a}=e;return r.default.createElement("script",{...a,key:a.src||n,defer:a.defer??!i,nonce:t.nonce,"data-nscript":"beforeInteractive",crossOrigin:t.crossOrigin||o})});return r.default.createElement(r.default.Fragment,null,s,l)}class E extends r.default.Component{static #e=this.contextType=l.HtmlContext;getCssLinks(e){let{assetPrefix:t,assetQueryString:n,dynamicImports:i,crossOrigin:o,optimizeCss:s,optimizeFonts:a}=this.context,l=e.allFiles.filter(e=>e.endsWith(".css")),u=new Set(e.sharedFiles),c=new Set([]),f=Array.from(new Set(i.filter(e=>e.endsWith(".css"))));if(f.length){let e=new Set(l);f=f.filter(t=>!(e.has(t)||u.has(t))),c=new Set(f),l.push(...f)}let d=[];return l.forEach(e=>{let i=u.has(e);s||d.push(r.default.createElement("link",{key:`${e}-preload`,nonce:this.props.nonce,rel:"preload",href:`${t}/_next/${encodeURI(e)}${n}`,as:"style",crossOrigin:this.props.crossOrigin||o}));let a=c.has(e);d.push(r.default.createElement("link",{key:e,nonce:this.props.nonce,rel:"stylesheet",href:`${t}/_next/${encodeURI(e)}${n}`,crossOrigin:this.props.crossOrigin||o,"data-n-g":a?void 0:i?"":void 0,"data-n-p":a?void 0:i?void 0:""}))}),a&&(d=this.makeStylesheetInert(d)),0===d.length?null:d}getPreloadDynamicChunks(){let{dynamicImports:e,assetPrefix:t,assetQueryString:n,crossOrigin:i}=this.context;return e.map(e=>e.endsWith(".js")?r.default.createElement("link",{rel:"preload",key:e,href:`${t}/_next/${encodeURI(e)}${n}`,as:"script",nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||i}):null).filter(Boolean)}getPreloadMainLinks(e){let{assetPrefix:t,assetQueryString:n,scriptLoader:i,crossOrigin:o}=this.context,s=e.allFiles.filter(e=>e.endsWith(".js"));return[...(i.beforeInteractive||[]).map(e=>r.default.createElement("link",{key:e.src,nonce:this.props.nonce,rel:"preload",href:e.src,as:"script",crossOrigin:this.props.crossOrigin||o})),...s.map(e=>r.default.createElement("link",{key:e,nonce:this.props.nonce,rel:"preload",href:`${t}/_next/${encodeURI(e)}${n}`,as:"script",crossOrigin:this.props.crossOrigin||o}))]}getBeforeInteractiveInlineScripts(){let{scriptLoader:e}=this.context,{nonce:t,crossOrigin:n}=this.props;return(e.beforeInteractive||[]).filter(e=>!e.src&&(e.dangerouslySetInnerHTML||e.children)).map((e,i)=>{let{strategy:o,children:s,dangerouslySetInnerHTML:a,src:l,...u}=e,c="";return a&&a.__html?c=a.__html:s&&(c="string"==typeof s?s:Array.isArray(s)?s.join(""):""),r.default.createElement("script",{...u,dangerouslySetInnerHTML:{__html:c},key:u.id||i,nonce:t,"data-nscript":"beforeInteractive",crossOrigin:n||void 0})})}getDynamicChunks(e){return h(this.context,this.props,e)}getPreNextScripts(){return _(this.context,this.props)}getScripts(e){return m(this.context,this.props,e)}getPolyfillScripts(){return d(this.context,this.props)}makeStylesheetInert(e){return r.default.Children.map(e,e=>{var t,n;if((null==e?void 0:e.type)==="link"&&(null==e?void 0:null==(t=e.props)?void 0:t.href)&&i.OPTIMIZED_FONT_PROVIDERS.some(({url:t})=>{var n,r;return null==e?void 0:null==(r=e.props)?void 0:null==(n=r.href)?void 0:n.startsWith(t)})){let t={...e.props||{},"data-href":e.props.href,href:void 0};return r.default.cloneElement(e,t)}if(null==e?void 0:null==(n=e.props)?void 0:n.children){let t={...e.props||{},children:this.makeStylesheetInert(e.props.children)};return r.default.cloneElement(e,t)}return e}).filter(Boolean)}render(){let{styles:e,ampPath:t,inAmpMode:i,hybridAmp:o,canonicalBase:s,__NEXT_DATA__:a,dangerousAsPath:l,headTags:u,unstable_runtimeJS:c,unstable_JsPreload:d,disableOptimizedLoading:h,optimizeCss:m,optimizeFonts:_,assetPrefix:E,nextFontManifest:g}=this.context,y=!1===c,S=!1===d||!h;this.context.docComponentsRendered.Head=!0;let{head:I}=this.context,T=[],P=[];I&&(I.forEach(e=>{let t;this.context.strictNextHead&&(t=r.default.createElement("meta",{name:"next-head",content:"1"})),e&&"link"===e.type&&"preload"===e.props.rel&&"style"===e.props.as?(t&&T.push(t),T.push(e)):e&&(t&&("meta"!==e.type||!e.props.charSet)&&P.push(t),P.push(e))}),I=T.concat(P));let v=r.default.Children.toArray(this.props.children).filter(Boolean);_&&!i&&(v=this.makeStylesheetInert(v));let O=!1,b=!1;I=r.default.Children.map(I||[],e=>{if(!e)return e;let{type:t,props:n}=e;if(i){let r="";if("meta"===t&&"viewport"===n.name?r='name="viewport"':"link"===t&&"canonical"===n.rel?b=!0:"script"===t&&(n.src&&-1>n.src.indexOf("ampproject")||n.dangerouslySetInnerHTML&&(!n.type||"text/javascript"===n.type))&&(r="{r+=` ${e}="${n[e]}"`}),r+="/>"),r)return console.warn(`Found conflicting amp tag "${e.type}" with conflicting prop ${r} in ${a.page}. https://nextjs.org/docs/messages/conflicting-amp-tag`),null}else"link"===t&&"amphtml"===n.rel&&(O=!0);return e});let N=f(this.context.buildManifest,this.context.__NEXT_DATA__.page,i),A=function(e,t,n=""){if(!e)return{preconnect:null,preload:null};let i=e.pages["/_app"],o=e.pages[t],s=[...i??[],...o??[]];return{preconnect:0===s.length&&(i||o)?r.default.createElement("link",{"data-next-font":e.pagesUsingSizeAdjust?"size-adjust":"",rel:"preconnect",href:"/",crossOrigin:"anonymous"}):null,preload:s?s.map(e=>{let t=/\.(woff|woff2|eot|ttf|otf)$/.exec(e)[1];return r.default.createElement("link",{key:e,rel:"preload",href:`${n}/_next/${encodeURI(e)}`,as:"font",type:`font/${t}`,crossOrigin:"anonymous","data-next-font":e.includes("-s")?"size-adjust":""})}):null}}(g,l,E);return r.default.createElement("head",function(e){let{crossOrigin:t,nonce:n,...r}=e;return r}(this.props),this.context.isDevelopment&&r.default.createElement(r.default.Fragment,null,r.default.createElement("style",{"data-next-hide-fouc":!0,"data-ampdevmode":i?"true":void 0,dangerouslySetInnerHTML:{__html:"body{display:none}"}}),r.default.createElement("noscript",{"data-next-hide-fouc":!0,"data-ampdevmode":i?"true":void 0},r.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{display:block}"}}))),I,this.context.strictNextHead?null:r.default.createElement("meta",{name:"next-head-count",content:r.default.Children.count(I||[]).toString()}),v,_&&r.default.createElement("meta",{name:"next-font-preconnect"}),A.preconnect,A.preload,i&&r.default.createElement(r.default.Fragment,null,r.default.createElement("meta",{name:"viewport",content:"width=device-width,minimum-scale=1,initial-scale=1"}),!b&&r.default.createElement("link",{rel:"canonical",href:s+n(733).cleanAmpPath(l)}),r.default.createElement("link",{rel:"preload",as:"script",href:"https://cdn.ampproject.org/v0.js"}),r.default.createElement(p,{styles:e}),r.default.createElement("style",{"amp-boilerplate":"",dangerouslySetInnerHTML:{__html:"body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}"}}),r.default.createElement("noscript",null,r.default.createElement("style",{"amp-boilerplate":"",dangerouslySetInnerHTML:{__html:"body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}"}})),r.default.createElement("script",{async:!0,src:"https://cdn.ampproject.org/v0.js"})),!i&&r.default.createElement(r.default.Fragment,null,!O&&o&&r.default.createElement("link",{rel:"amphtml",href:s+(t||`${l}${l.includes("?")?"&":"?"}amp=1`)}),this.getBeforeInteractiveInlineScripts(),!m&&this.getCssLinks(N),!m&&r.default.createElement("noscript",{"data-n-css":this.props.nonce??""}),!y&&!S&&this.getPreloadDynamicChunks(),!y&&!S&&this.getPreloadMainLinks(N),!h&&!y&&this.getPolyfillScripts(),!h&&!y&&this.getPreNextScripts(),!h&&!y&&this.getDynamicChunks(N),!h&&!y&&this.getScripts(N),m&&this.getCssLinks(N),m&&r.default.createElement("noscript",{"data-n-css":this.props.nonce??""}),this.context.isDevelopment&&r.default.createElement("noscript",{id:"__next_css__DO_NOT_USE__"}),e||null),r.default.createElement(r.default.Fragment,{},...u||[]))}}class g extends r.default.Component{static #e=this.contextType=l.HtmlContext;getDynamicChunks(e){return h(this.context,this.props,e)}getPreNextScripts(){return _(this.context,this.props)}getScripts(e){return m(this.context,this.props,e)}getPolyfillScripts(){return d(this.context,this.props)}static getInlineScriptSource(e){let{__NEXT_DATA__:t,largePageDataBytes:r}=e;try{let i=JSON.stringify(t);if(c.has(t.page))return(0,s.htmlEscapeJsonString)(i);let o=Buffer.from(i).byteLength,a=n(5955).Z;return r&&o>r&&(c.add(t.page),console.warn(`Warning: data for page "${t.page}"${t.page===e.dangerousAsPath?"":` (path "${e.dangerousAsPath}")`} is ${a(o)} which exceeds the threshold of ${a(r)}, this amount of data can reduce performance. +See more info here: https://nextjs.org/docs/messages/large-page-data`)),(0,s.htmlEscapeJsonString)(i)}catch(e){if((0,a.default)(e)&&-1!==e.message.indexOf("circular structure"))throw Error(`Circular structure in "getInitialProps" result of page "${t.page}". https://nextjs.org/docs/messages/circular-structure`);throw e}}render(){let{assetPrefix:e,inAmpMode:t,buildManifest:n,unstable_runtimeJS:i,docComponentsRendered:o,assetQueryString:s,disableOptimizedLoading:a,crossOrigin:l}=this.context,u=!1===i;if(o.NextScript=!0,t)return null;let c=f(this.context.buildManifest,this.context.__NEXT_DATA__.page,t);return r.default.createElement(r.default.Fragment,null,!u&&n.devFiles?n.devFiles.map(t=>r.default.createElement("script",{key:t,src:`${e}/_next/${encodeURI(t)}${s}`,nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||l})):null,u?null:r.default.createElement("script",{id:"__NEXT_DATA__",type:"application/json",nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||l,dangerouslySetInnerHTML:{__html:g.getInlineScriptSource(this.context)}}),a&&!u&&this.getPolyfillScripts(),a&&!u&&this.getPreNextScripts(),a&&!u&&this.getDynamicChunks(c),a&&!u&&this.getScripts(c))}}function y(e){let{inAmpMode:t,docComponentsRendered:n,locale:i,scriptLoader:o,__NEXT_DATA__:s}=(0,l.useHtmlContext)();return n.Html=!0,function(e,t,n){var i,o,s,a;if(!n.children)return;let l=[],u=Array.isArray(n.children)?n.children:[n.children],c=null==(o=u.find(e=>e.type===E))?void 0:null==(i=o.props)?void 0:i.children,f=null==(a=u.find(e=>"body"===e.type))?void 0:null==(s=a.props)?void 0:s.children,d=[...Array.isArray(c)?c:[c],...Array.isArray(f)?f:[f]];r.default.Children.forEach(d,t=>{var n;if(t&&(null==(n=t.type)?void 0:n.__nextScript)){if("beforeInteractive"===t.props.strategy){e.beforeInteractive=(e.beforeInteractive||[]).concat([{...t.props}]);return}if(["lazyOnload","afterInteractive","worker"].includes(t.props.strategy)){l.push(t.props);return}}}),t.scriptLoader=l}(o,s,e),r.default.createElement("html",{...e,lang:e.lang||i||void 0,amp:t?"":void 0,"data-ampdevmode":void 0})}function S(){let{docComponentsRendered:e}=(0,l.useHtmlContext)();return e.Main=!0,r.default.createElement("next-js-internal-body-render-target",null)}class I extends r.default.Component{static getInitialProps(e){return e.defaultGetInitialProps(e)}render(){return r.default.createElement(y,null,r.default.createElement(E,null),r.default.createElement("body",null,r.default.createElement(S,null),r.default.createElement(g,null)))}}I[i.NEXT_BUILTIN_DOCUMENT]=function(){return r.default.createElement(y,null,r.default.createElement(E,null),r.default.createElement("body",null,r.default.createElement(S,null),r.default.createElement(g,null)))}},1841:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{MODERN_BROWSERSLIST_TARGET:function(){return r.default},COMPILER_NAMES:function(){return i},INTERNAL_HEADERS:function(){return o},COMPILER_INDEXES:function(){return s},PHASE_EXPORT:function(){return a},PHASE_PRODUCTION_BUILD:function(){return l},PHASE_PRODUCTION_SERVER:function(){return u},PHASE_DEVELOPMENT_SERVER:function(){return c},PHASE_TEST:function(){return f},PHASE_INFO:function(){return d},PAGES_MANIFEST:function(){return p},APP_PATHS_MANIFEST:function(){return h},APP_PATH_ROUTES_MANIFEST:function(){return m},BUILD_MANIFEST:function(){return _},APP_BUILD_MANIFEST:function(){return E},FUNCTIONS_CONFIG_MANIFEST:function(){return g},SUBRESOURCE_INTEGRITY_MANIFEST:function(){return y},NEXT_FONT_MANIFEST:function(){return S},EXPORT_MARKER:function(){return I},EXPORT_DETAIL:function(){return T},PRERENDER_MANIFEST:function(){return P},ROUTES_MANIFEST:function(){return v},IMAGES_MANIFEST:function(){return O},SERVER_FILES_MANIFEST:function(){return b},DEV_CLIENT_PAGES_MANIFEST:function(){return N},MIDDLEWARE_MANIFEST:function(){return A},DEV_MIDDLEWARE_MANIFEST:function(){return R},REACT_LOADABLE_MANIFEST:function(){return x},FONT_MANIFEST:function(){return M},SERVER_DIRECTORY:function(){return L},CONFIG_FILES:function(){return j},BUILD_ID_FILE:function(){return C},BLOCKED_PAGES:function(){return w},CLIENT_PUBLIC_FILES_PATH:function(){return F},CLIENT_STATIC_FILES_PATH:function(){return k},STRING_LITERAL_DROP_BUNDLE:function(){return D},NEXT_BUILTIN_DOCUMENT:function(){return U},BARREL_OPTIMIZATION_PREFIX:function(){return $},CLIENT_REFERENCE_MANIFEST:function(){return B},SERVER_REFERENCE_MANIFEST:function(){return W},MIDDLEWARE_BUILD_MANIFEST:function(){return H},MIDDLEWARE_REACT_LOADABLE_MANIFEST:function(){return z},CLIENT_STATIC_FILES_RUNTIME_MAIN:function(){return G},CLIENT_STATIC_FILES_RUNTIME_MAIN_APP:function(){return Y},APP_CLIENT_INTERNALS:function(){return V},CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH:function(){return X},CLIENT_STATIC_FILES_RUNTIME_AMP:function(){return q},CLIENT_STATIC_FILES_RUNTIME_WEBPACK:function(){return Z},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS:function(){return K},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL:function(){return J},EDGE_RUNTIME_WEBPACK:function(){return Q},STATIC_PROPS_ID:function(){return ee},SERVER_PROPS_ID:function(){return et},PAGE_SEGMENT_KEY:function(){return en},GOOGLE_FONT_PROVIDER:function(){return er},OPTIMIZED_FONT_PROVIDERS:function(){return ei},DEFAULT_SERIF_FONT:function(){return eo},DEFAULT_SANS_SERIF_FONT:function(){return es},STATIC_STATUS_PAGES:function(){return ea},TRACE_OUTPUT_VERSION:function(){return el},TURBO_TRACE_DEFAULT_MEMORY_LIMIT:function(){return eu},RSC_MODULE_TYPES:function(){return ec},EDGE_UNSUPPORTED_NODE_APIS:function(){return ef},SYSTEM_ENTRYPOINTS:function(){return ed}});let r=n(167)._(n(350)),i={client:"client",server:"server",edgeServer:"edge-server"},o=["x-invoke-error","x-invoke-output","x-invoke-path","x-invoke-query","x-invoke-status","x-middleware-invoke"],s={[i.client]:0,[i.server]:1,[i.edgeServer]:2},a="phase-export",l="phase-production-build",u="phase-production-server",c="phase-development-server",f="phase-test",d="phase-info",p="pages-manifest.json",h="app-paths-manifest.json",m="app-path-routes-manifest.json",_="build-manifest.json",E="app-build-manifest.json",g="functions-config-manifest.json",y="subresource-integrity-manifest",S="next-font-manifest",I="export-marker.json",T="export-detail.json",P="prerender-manifest.json",v="routes-manifest.json",O="images-manifest.json",b="required-server-files.json",N="_devPagesManifest.json",A="middleware-manifest.json",R="_devMiddlewareManifest.json",x="react-loadable-manifest.json",M="font-manifest.json",L="server",j=["next.config.js","next.config.mjs"],C="BUILD_ID",w=["/_document","/_app","/_error"],F="public",k="static",D="__NEXT_DROP_CLIENT_FILE__",U="__NEXT_BUILTIN_DOCUMENT__",$="__barrel_optimize__",B="client-reference-manifest",W="server-reference-manifest",H="middleware-build-manifest",z="middleware-react-loadable-manifest",G="main",Y=""+G+"-app",V="app-pages-internals",X="react-refresh",q="amp",Z="webpack",K="polyfills",J=Symbol(K),Q="edge-runtime-webpack",ee="__N_SSG",et="__N_SSP",en="__PAGE__",er="https://fonts.googleapis.com/",ei=[{url:er,preconnect:"https://fonts.gstatic.com"},{url:"https://use.typekit.net",preconnect:"https://use.typekit.net"}],eo={name:"Times New Roman",xAvgCharWidth:821,azAvgWidth:854.3953488372093,unitsPerEm:2048},es={name:"Arial",xAvgCharWidth:904,azAvgWidth:934.5116279069767,unitsPerEm:2048},ea=["/500"],el=1,eu=6e3,ec={client:"client",server:"server"},ef=["clearImmediate","setImmediate","BroadcastChannel","ByteLengthQueuingStrategy","CompressionStream","CountQueuingStrategy","DecompressionStream","DomException","MessageChannel","MessageEvent","MessagePort","ReadableByteStreamController","ReadableStreamBYOBRequest","ReadableStreamDefaultController","TransformStreamDefaultController","WritableStreamDefaultController"],ed=new Set([G,X,q,Y]);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3739:(e,t)=>{function n(e){return Object.prototype.toString.call(e)}function r(e){if("[object Object]"!==n(e))return!1;let t=Object.getPrototypeOf(e);return null===t||t.hasOwnProperty("isPrototypeOf")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getObjectClassLabel:function(){return n},isPlainObject:function(){return r}})},350:e=>{e.exports=["chrome 64","edge 79","firefox 67","opera 51","safari 12"]},3404:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"denormalizePagePath",{enumerable:!0,get:function(){return o}});let r=n(5181),i=n(7150);function o(e){let t=(0,i.normalizePathSep)(e);return t.startsWith("/index/")&&!(0,r.isDynamicRoute)(t)?t.slice(6):"/index"!==t?t:"/"}},5766:(e,t)=>{function n(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return n}})},6514:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePagePath",{enumerable:!0,get:function(){return s}});let r=n(5766),i=n(5181),o=n(4316);function s(e){let t=/^\/index(\/|$)/.test(e)&&!(0,i.isDynamicRoute)(e)?"/index"+e:"/"===e?"/index":(0,r.ensureLeadingSlash)(e);{let{posix:e}=n(1017),r=e.normalize(t);if(r!==t)throw new o.NormalizeError("Requested and resolved page mismatch: "+t+" "+r)}return t}},7150:(e,t)=>{function n(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return n}})},2047:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{normalizeAppPath:function(){return o},normalizeRscURL:function(){return s}});let r=n(5766),i=n(2444);function o(e){return(0,r.ensureLeadingSlash)(e.split("/").reduce((e,t,n,r)=>!t||(0,i.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&n===r.length-1?e:e+"/"+t,""))}function s(e){return e.replace(/\.rsc($|\?)/,"$1")}},5181:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getSortedRoutes:function(){return r.getSortedRoutes},isDynamicRoute:function(){return i.isDynamicRoute}});let r=n(6919),i=n(3926)},3926:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isDynamicRoute",{enumerable:!0,get:function(){return o}});let r=n(2407),i=/\/\[[^/]+?\](?=\/|$)/;function o(e){return(0,r.isInterceptionRouteAppPath)(e)&&(e=(0,r.extractInterceptionRouteInformation)(e).interceptedRoute),i.test(e)}},6919:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSortedRoutes",{enumerable:!0,get:function(){return r}});class n{insert(e){this._insert(e.split("/").filter(Boolean),[],!1)}smoosh(){return this._smoosh()}_smoosh(e){void 0===e&&(e="/");let t=[...this.children.keys()].sort();null!==this.slugName&&t.splice(t.indexOf("[]"),1),null!==this.restSlugName&&t.splice(t.indexOf("[...]"),1),null!==this.optionalRestSlugName&&t.splice(t.indexOf("[[...]]"),1);let n=t.map(t=>this.children.get(t)._smoosh(""+e+t+"/")).reduce((e,t)=>[...e,...t],[]);if(null!==this.slugName&&n.push(...this.children.get("[]")._smoosh(e+"["+this.slugName+"]/")),!this.placeholder){let t="/"===e?"/":e.slice(0,-1);if(null!=this.optionalRestSlugName)throw Error('You cannot define a route with the same specificity as a optional catch-all route ("'+t+'" and "'+t+"[[..."+this.optionalRestSlugName+']]").');n.unshift(t)}return null!==this.restSlugName&&n.push(...this.children.get("[...]")._smoosh(e+"[..."+this.restSlugName+"]/")),null!==this.optionalRestSlugName&&n.push(...this.children.get("[[...]]")._smoosh(e+"[[..."+this.optionalRestSlugName+"]]/")),n}_insert(e,t,r){if(0===e.length){this.placeholder=!1;return}if(r)throw Error("Catch-all must be the last part of the URL.");let i=e[0];if(i.startsWith("[")&&i.endsWith("]")){let n=i.slice(1,-1),s=!1;if(n.startsWith("[")&&n.endsWith("]")&&(n=n.slice(1,-1),s=!0),n.startsWith("...")&&(n=n.substring(3),r=!0),n.startsWith("[")||n.endsWith("]"))throw Error("Segment names may not start or end with extra brackets ('"+n+"').");if(n.startsWith("."))throw Error("Segment names may not start with erroneous periods ('"+n+"').");function o(e,n){if(null!==e&&e!==n)throw Error("You cannot use different slug names for the same dynamic path ('"+e+"' !== '"+n+"').");t.forEach(e=>{if(e===n)throw Error('You cannot have the same slug name "'+n+'" repeat within a single dynamic path');if(e.replace(/\W/g,"")===i.replace(/\W/g,""))throw Error('You cannot have the slug names "'+e+'" and "'+n+'" differ only by non-word symbols within a single dynamic path')}),t.push(n)}if(r){if(s){if(null!=this.restSlugName)throw Error('You cannot use both an required and optional catch-all route at the same level ("[...'+this.restSlugName+']" and "'+e[0]+'" ).');o(this.optionalRestSlugName,n),this.optionalRestSlugName=n,i="[[...]]"}else{if(null!=this.optionalRestSlugName)throw Error('You cannot use both an optional and required catch-all route at the same level ("[[...'+this.optionalRestSlugName+']]" and "'+e[0]+'").');o(this.restSlugName,n),this.restSlugName=n,i="[...]"}}else{if(s)throw Error('Optional route parameters are not yet supported ("'+e[0]+'").');o(this.slugName,n),this.slugName=n,i="[]"}}this.children.has(i)||this.children.set(i,new n),this.children.get(i)._insert(e.slice(1),t,r)}constructor(){this.placeholder=!0,this.children=new Map,this.slugName=null,this.restSlugName=null,this.optionalRestSlugName=null}}function r(e){let t=new n;return e.forEach(e=>t.insert(e)),t.smoosh()}},2444:(e,t)=>{function n(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isGroupSegment",{enumerable:!0,get:function(){return n}})},4316:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{WEB_VITALS:function(){return n},execOnce:function(){return r},isAbsoluteUrl:function(){return o},getLocationOrigin:function(){return s},getURL:function(){return a},getDisplayName:function(){return l},isResSent:function(){return u},normalizeRepeatedSlashes:function(){return c},loadGetInitialProps:function(){return f},SP:function(){return d},ST:function(){return p},DecodeError:function(){return h},NormalizeError:function(){return m},PageNotFoundError:function(){return _},MissingStaticPage:function(){return E},MiddlewareNotFoundError:function(){return g},stringifyError:function(){return y}});let n=["CLS","FCP","FID","INP","LCP","TTFB"];function r(e){let t,n=!1;return function(){for(var r=arguments.length,i=Array(r),o=0;oi.test(e);function s(){let{protocol:e,hostname:t,port:n}=window.location;return e+"//"+t+(n?":"+n:"")}function a(){let{href:e}=window.location,t=s();return e.substring(t.length)}function l(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function u(e){return e.finished||e.headersSent}function c(e){let t=e.split("?");return t[0].replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function f(e,t){let n=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await f(t.Component,t.ctx)}:{};let r=await e.getInitialProps(t);if(n&&u(n))return r;if(!r)throw Error('"'+l(e)+'.getInitialProps()" should resolve to an object. But found "'+r+'" instead.');return r}let d="undefined"!=typeof performance,p=d&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);class h extends Error{}class m extends Error{}class _ extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}}class E extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}}class g extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}}function y(e){return JSON.stringify({message:e.message,stack:e.stack})}},676:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{default:function(){return i},getProperError:function(){return o}});let r=n(3739);function i(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function o(e){return i(e)?e:Error((0,r.isPlainObject)(e)?JSON.stringify(e):e+"")}},5955:(e,t)=>{Object.defineProperty(t,"Z",{enumerable:!0,get:function(){return i}});let n=["B","kB","MB","GB","TB","PB","EB","ZB","YB"],r=(e,t)=>{let n=e;return"string"==typeof t?n=e.toLocaleString(t):!0===t&&(n=e.toLocaleString()),n};function i(e,t){if(!Number.isFinite(e))throw TypeError(`Expected a finite number, got ${typeof e}: ${e}`);if((t=Object.assign({},t)).signed&&0===e)return" 0 B";let i=e<0,o=i?"-":t.signed?"+":"";if(i&&(e=-e),e<1)return o+r(e,t.locale)+" B";let s=Math.min(Math.floor(Math.log10(e)/3),n.length-1);return o+r(e=Number((e/Math.pow(1e3,s)).toPrecision(3)),t.locale)+" "+n[s]}},2407:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return i},isInterceptionRouteAppPath:function(){return o},extractInterceptionRouteInformation:function(){return s}});let r=n(2047),i=["(..)(..)","(.)","(..)","(...)"];function o(e){return void 0!==e.split("/").find(e=>i.find(t=>e.startsWith(t)))}function s(e){let t,n,o;for(let r of e.split("/"))if(n=i.find(e=>r.startsWith(e))){[t,o]=e.split(n,2);break}if(!t||!n||!o)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,r.normalizeAppPath)(t),n){case"(.)":o="/"===t?`/${o}`:t+"/"+o;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);o=t.split("/").slice(0,-1).concat(o).join("/");break;case"(...)":o="/"+o;break;case"(..)(..)":let s=t.split("/");if(s.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);o=s.slice(0,-2).concat(o).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:o}}},7093:(e,t,n)=>{e.exports=n(2785)},3112:(e,t,n)=>{e.exports=n(7093).vendored.contexts.HtmlContext},5778:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getPageFiles",{enumerable:!0,get:function(){return o}});let r=n(3404),i=n(6514);function o(e,t){let n=(0,r.denormalizePagePath)((0,i.normalizePagePath)(t));return e.pages[n]||(console.warn(`Could not find files for ${n} in .next/build-manifest.json`),[])}},9630:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ESCAPE_REGEX:function(){return r},htmlEscapeJsonString:function(){return i}});let n={"&":"\\u0026",">":"\\u003e","<":"\\u003c","\u2028":"\\u2028","\u2029":"\\u2029"},r=/[&><\u2028\u2029]/g;function i(e){return e.replace(r,e=>n[e])}},733:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{isBlockedPage:function(){return i},cleanAmpPath:function(){return o},debounce:function(){return s}});let r=n(1841);function i(e){return r.BLOCKED_PAGES.includes(e)}function o(e){return e.match(/\?amp=(y|yes|true|1)/)&&(e=e.replace(/\?amp=(y|yes|true|1)&?/,"?")),e.match(/&=(y|yes|true|1)/)&&(e=e.replace(/&=(y|yes|true|1)/,"")),e=e.replace(/\?$/,"")}function s(e,t,n=1/0){let r,i,o;let s=0,a=0;function l(){let u=Date.now(),c=a+t-u;c<=0||s+n>=u?(r=void 0,e.apply(o,i)):r=setTimeout(l,c)}return function(...e){i=e,o=this,a=Date.now(),void 0===r&&(s=a,r=setTimeout(l,t))}}},167:(e,t)=>{t._=t._interop_require_default=function(e){return e&&e.__esModule?e:{default:e}}}}; \ No newline at end of file diff --git a/.next/server/chunks/337.js b/.next/server/chunks/337.js new file mode 100644 index 0000000..ceae67e --- /dev/null +++ b/.next/server/chunks/337.js @@ -0,0 +1,6 @@ +exports.id=337,exports.ids=[337],exports.modules={4409:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RSC_HEADER:function(){return r},ACTION:function(){return n},NEXT_ROUTER_STATE_TREE:function(){return i},NEXT_ROUTER_PREFETCH_HEADER:function(){return o},NEXT_URL:function(){return a},RSC_CONTENT_TYPE_HEADER:function(){return u},RSC_VARY_HEADER:function(){return s},FLIGHT_PARAMETERS:function(){return c},NEXT_RSC_UNION_QUERY:function(){return l},NEXT_DID_POSTPONE_HEADER:function(){return f}});let r="RSC",n="Next-Action",i="Next-Router-State-Tree",o="Next-Router-Prefetch",a="Next-Url",u="text/x-component",s=r+", "+i+", "+o+", "+a,c=[[r],[i],[o]],l="_rsc",f="x-nextjs-postponed";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7363:e=>{(()=>{"use strict";"undefined"!=typeof __nccwpck_require__&&(__nccwpck_require__.ab=__dirname+"/");var t={};(()=>{/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */t.parse=function(t,r){if("string"!=typeof t)throw TypeError("argument str must be a string");for(var i={},o=t.split(n),a=(r||{}).decode||e,u=0;u{"use strict";function r(e,t){void 0===t&&(t={});for(var r=function(e){for(var t=[],r=0;r=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||95===a){i+=e[o++];continue}break}if(!i)throw TypeError("Missing parameter name at "+r);t.push({type:"NAME",index:r,value:i}),r=o;continue}if("("===n){var u=1,s="",o=r+1;if("?"===e[o])throw TypeError('Pattern cannot start with "?" at '+o);for(;o-1:void 0===v;i||(d+="(?:"+p+"(?="+f+"))?"),R||(d+="(?="+p+"|"+f+")")}return new RegExp(d,a(r))}function s(e,t,n){return e instanceof RegExp?function(e,t){if(!t)return e;var r=e.source.match(/\((?!\?)/g);if(r)for(var n=0;n{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{fillMetadataSegment:function(){return f},normalizeMetadataRoute:function(){return p}});let n=r(8488),i=function(e){return e&&e.__esModule?e:{default:e}}(r(4084)),o=r(9017),a=r(4654),u=r(6325),s=r(9393),c=r(9716);function l(e){let t="";return(e.includes("(")&&e.includes(")")||e.includes("@"))&&(t=(0,u.djb2Hash)(e).toString(36).slice(0,6)),t}function f(e,t,r){let n=(0,s.normalizeAppPath)(e),u=(0,a.getNamedRouteRegex)(n,!1),f=(0,o.interpolateDynamicPath)(n,t,u),p=l(e),d=p?`-${p}`:"",{name:m,ext:g}=i.default.parse(r);return(0,c.normalizePathSep)(i.default.join(f,`${m}${d}${g}`))}function p(e){if(!(0,n.isMetadataRoute)(e))return e;let t=e,r="";if("/robots"===e?t+=".txt":"/manifest"===e?t+=".webmanifest":e.endsWith("/sitemap")?t+=".xml":r=l(e.slice(0,-(i.default.basename(e).length+1))),!t.endsWith("/route")){let{dir:o,name:a,ext:u}=i.default.parse(t),s=(0,n.isStaticMetadataRoute)(e);t=i.default.posix.join(o,`${a}${r?`-${r}`:""}${u}`,s?"":"[[...__metadata_id__]]","route")}return t}},8488:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{STATIC_METADATA_IMAGES:function(){return i},isMetadataRouteFile:function(){return u},isStaticMetadataRouteFile:function(){return s},isStaticMetadataRoute:function(){return c},isMetadataRoute:function(){return l}});let n=r(9716),i={icon:{filename:"icon",extensions:["ico","jpg","jpeg","png","svg"]},apple:{filename:"apple-icon",extensions:["jpg","jpeg","png"]},favicon:{filename:"favicon",extensions:["ico"]},openGraph:{filename:"opengraph-image",extensions:["jpg","jpeg","png","gif"]},twitter:{filename:"twitter-image",extensions:["jpg","jpeg","png","gif"]}},o=["js","jsx","ts","tsx"],a=e=>`(?:${e.join("|")})`;function u(e,t,r){let o=[RegExp(`^[\\\\/]robots${r?`\\.${a(t.concat("txt"))}$`:""}`),RegExp(`^[\\\\/]manifest${r?`\\.${a(t.concat("webmanifest","json"))}$`:""}`),RegExp("^[\\\\/]favicon\\.ico$"),RegExp(`[\\\\/]sitemap${r?`\\.${a(t.concat("xml"))}$`:""}`),RegExp(`[\\\\/]${i.icon.filename}\\d?${r?`\\.${a(t.concat(i.icon.extensions))}$`:""}`),RegExp(`[\\\\/]${i.apple.filename}\\d?${r?`\\.${a(t.concat(i.apple.extensions))}$`:""}`),RegExp(`[\\\\/]${i.openGraph.filename}\\d?${r?`\\.${a(t.concat(i.openGraph.extensions))}$`:""}`),RegExp(`[\\\\/]${i.twitter.filename}\\d?${r?`\\.${a(t.concat(i.twitter.extensions))}$`:""}`)],u=(0,n.normalizePathSep)(e);return o.some(e=>e.test(u))}function s(e){return u(e,[],!0)}function c(e){return"/robots"===e||"/manifest"===e||s(e)}function l(e){let t=e.replace(/^\/?app\//,"").replace(/\/route$/,"");return"/"!==t[0]&&(t="/"+t),!t.endsWith("/page")&&u(t,o,!1)}},892:(e,t,r)=>{"use strict";function n(e){return function(){let{cookie:t}=e;if(!t)return{};let{parse:n}=r(7363);return n(Array.isArray(t)?t.join("; "):t)}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getCookieParser",{enumerable:!0,get:function(){return n}})},8988:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return i},isInterceptionRouteAppPath:function(){return o},extractInterceptionRouteInformation:function(){return a}});let n=r(9393),i=["(..)(..)","(.)","(..)","(...)"];function o(e){return void 0!==e.split("/").find(e=>i.find(t=>e.startsWith(t)))}function a(e){let t,r,o;for(let n of e.split("/"))if(r=i.find(e=>n.startsWith(e))){[t,o]=e.split(r,2);break}if(!t||!r||!o)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":o="/"===t?`/${o}`:t+"/"+o;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);o=t.split("/").slice(0,-1).concat(o).join("/");break;case"(...)":o="/"+o;break;case"(..)(..)":let a=t.split("/");if(a.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);o=a.slice(0,-2).concat(o).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:o}}},9017:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeVercelUrl:function(){return p},interpolateDynamicPath:function(){return d},normalizeDynamicRouteParams:function(){return m},getUtils:function(){return g}});let n=r(7310),i=r(3935),o=r(8237),a=r(4654),u=r(7158),s=r(2762),c=r(5545),l=r(9393),f=r(2740);function p(e,t,r,i,o){if(i&&t&&o){let t=(0,n.parse)(e.url,!0);for(let e of(delete t.search,Object.keys(t.query)))(e!==f.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(f.NEXT_QUERY_PARAM_PREFIX)||(r||Object.keys(o.groups)).includes(e))&&delete t.query[e];e.url=(0,n.format)(t)}}function d(e,t,r){if(!r)return e;for(let n of Object.keys(r.groups)){let{optional:i,repeat:o}=r.groups[n],a=`[${o?"...":""}${n}]`;i&&(a=`[${a}]`);let u=e.indexOf(a);if(u>-1){let r;let i=t[n];r=Array.isArray(i)?i.map(e=>e&&encodeURIComponent(e)).join("/"):i?encodeURIComponent(i):"",e=e.slice(0,u)+r+e.slice(u+a.length)}}return e}function m(e,t,r,n){let i=!0;return r?{params:e=Object.keys(r.groups).reduce((o,a)=>{let u=e[a];"string"==typeof u&&(u=(0,l.normalizeRscURL)(u)),Array.isArray(u)&&(u=u.map(e=>("string"==typeof e&&(e=(0,l.normalizeRscURL)(e)),e)));let s=n[a],c=r.groups[a].optional;return((Array.isArray(s)?s.some(e=>Array.isArray(u)?u.some(t=>t.includes(e)):null==u?void 0:u.includes(e)):null==u?void 0:u.includes(s))||void 0===u&&!(c&&t))&&(i=!1),c&&(!u||Array.isArray(u)&&1===u.length&&("index"===u[0]||u[0]===`[[...${a}]]`))&&(u=void 0,delete e[a]),u&&"string"==typeof u&&r.groups[a].repeat&&(u=u.split("/")),u&&(o[a]=u),o},{}),hasValidParams:i}:{params:e,hasValidParams:!1}}function g({page:e,i18n:t,basePath:r,rewrites:n,pageIsDynamic:l,trailingSlash:g,caseSensitive:h}){let y,E,v;return l&&(y=(0,a.getNamedRouteRegex)(e,!1),v=(E=(0,u.getRouteMatcher)(y))(e)),{handleRewrites:function(a,u){let f={},p=u.pathname,d=n=>{let c=(0,o.getPathMatch)(n.source+(g?"(/)?":""),{removeUnnamedParams:!0,strict:!0,sensitive:!!h})(u.pathname);if((n.has||n.missing)&&c){let e=(0,s.matchHas)(a,u.query,n.has,n.missing);e?Object.assign(c,e):c=!1}if(c){let{parsedDestination:o,destQuery:a}=(0,s.prepareDestination)({appendParamsToQuery:!0,destination:n.destination,params:c,query:u.query});if(o.protocol)return!0;if(Object.assign(f,a,c),Object.assign(u.query,o.query),delete o.query,Object.assign(u,o),p=u.pathname,r&&(p=p.replace(RegExp(`^${r}`),"")||"/"),t){let e=(0,i.normalizeLocalePath)(p,t.locales);p=e.pathname,u.query.nextInternalLocale=e.detectedLocale||c.nextInternalLocale}if(p===e)return!0;if(l&&E){let e=E(p);if(e)return u.query={...u.query,...e},!0}}return!1};for(let e of n.beforeFiles||[])d(e);if(p!==e){let t=!1;for(let e of n.afterFiles||[])if(t=d(e))break;if(!t&&!(()=>{let t=(0,c.removeTrailingSlash)(p||"");return t===(0,c.removeTrailingSlash)(e)||(null==E?void 0:E(t))})()){for(let e of n.fallback||[])if(t=d(e))break}}return f},defaultRouteRegex:y,dynamicRouteMatcher:E,defaultRouteMatches:v,getParamsFromRouteMatches:function(e,r,n){return(0,u.getRouteMatcher)(function(){let{groups:e,routeKeys:i}=y;return{re:{exec:o=>{let a=Object.fromEntries(new URLSearchParams(o)),u=t&&n&&a["1"]===n;for(let e of Object.keys(a)){let t=a[e];e!==f.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(f.NEXT_QUERY_PARAM_PREFIX)&&(a[e.substring(f.NEXT_QUERY_PARAM_PREFIX.length)]=t,delete a[e])}let s=Object.keys(i||{}),c=e=>{if(t){let i=Array.isArray(e),o=i?e[0]:e;if("string"==typeof o&&t.locales.some(e=>e.toLowerCase()===o.toLowerCase()&&(n=e,r.locale=n,!0)))return i&&e.splice(0,1),!i||0===e.length}return!1};return s.every(e=>a[e])?s.reduce((t,r)=>{let n=null==i?void 0:i[r];return n&&!c(a[r])&&(t[e[n].pos]=a[r]),t},{}):Object.keys(a).reduce((e,t)=>{if(!c(a[t])){let r=t;return u&&(r=parseInt(t,10)-1+""),Object.assign(e,{[r]:a[t]})}return e},{})}},groups:e}}())(e.headers["x-now-route-matches"])},normalizeDynamicRouteParams:(e,t)=>m(e,t,y,v),normalizeVercelUrl:(e,t,r)=>p(e,t,r,l,y),interpolateDynamicPath:(e,t)=>d(e,t,y)}}},7436:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"escapeStringRegexp",{enumerable:!0,get:function(){return i}});let r=/[|\\{}()[\]^$+*?.-]/,n=/[|\\{}()[\]^$+*?.-]/g;function i(e){return r.test(e)?e.replace(n,"\\$&"):e}},6325:(e,t)=>{"use strict";function r(e){let t=5381;for(let r=0;r>>0}function n(e){return r(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{djb2Hash:function(){return r},hexHash:function(){return n}})},3935:(e,t)=>{"use strict";function r(e,t){let r;let n=e.split("/");return(t||[]).some(t=>!!n[1]&&n[1].toLowerCase()===t.toLowerCase()&&(r=t,n.splice(1,1),e=n.join("/")||"/",!0)),{pathname:e,detectedLocale:r}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return r}})},4084:(e,t,r)=>{"use strict";let n;n=r(1017),e.exports=n},5940:(e,t)=>{"use strict";function r(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return r}})},9716:(e,t)=>{"use strict";function r(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return r}})},9393:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return o},normalizeRscURL:function(){return a}});let n=r(5940),i=r(5458);function o(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,i.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function a(e){return e.replace(/\.rsc($|\?)/,"$1")}},713:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseRelativeUrl",{enumerable:!0,get:function(){return i}}),r(2881);let n=r(1662);function i(e,t){let r=new URL("http://n"),i=t?new URL(t,r):e.startsWith(".")?new URL("http://n"):r,{pathname:o,searchParams:a,search:u,hash:s,href:c,origin:l}=new URL(e,i);if(l!==r.origin)throw Error("invariant: invalid relative URL, router received "+e);return{pathname:o,query:(0,n.searchParamsToUrlQuery)(a),search:u,hash:s,href:c.slice(r.origin.length)}}},8223:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseUrl",{enumerable:!0,get:function(){return o}});let n=r(1662),i=r(713);function o(e){if(e.startsWith("/"))return(0,i.parseRelativeUrl)(e);let t=new URL(e);return{hash:t.hash,hostname:t.hostname,href:t.href,pathname:t.pathname,port:t.port,protocol:t.protocol,query:(0,n.searchParamsToUrlQuery)(t.searchParams),search:t.search}}},8237:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getPathMatch",{enumerable:!0,get:function(){return i}});let n=r(6358);function i(e,t){let r=[],i=(0,n.pathToRegexp)(e,r,{delimiter:"/",sensitive:"boolean"==typeof(null==t?void 0:t.sensitive)&&t.sensitive,strict:null==t?void 0:t.strict}),o=(0,n.regexpToFunction)((null==t?void 0:t.regexModifier)?new RegExp(t.regexModifier(i.source),i.flags):i,r);return(e,n)=>{if("string"!=typeof e)return!1;let i=o(e);if(!i)return!1;if(null==t?void 0:t.removeUnnamedParams)for(let e of r)"number"==typeof e.name&&delete i.params[e.name];return{...n,...i.params}}}},2762:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{matchHas:function(){return l},compileNonPath:function(){return f},prepareDestination:function(){return p}});let n=r(6358),i=r(7436),o=r(8223),a=r(8988),u=r(4409),s=r(892);function c(e){return e.replace(/__ESC_COLON_/gi,":")}function l(e,t,r,n){void 0===r&&(r=[]),void 0===n&&(n=[]);let i={},o=r=>{let n;let o=r.key;switch(r.type){case"header":o=o.toLowerCase(),n=e.headers[o];break;case"cookie":n="cookies"in e?e.cookies[r.key]:(0,s.getCookieParser)(e.headers)()[r.key];break;case"query":n=t[o];break;case"host":{let{host:t}=(null==e?void 0:e.headers)||{};n=null==t?void 0:t.split(":",1)[0].toLowerCase()}}if(!r.value&&n)return i[function(e){let t="";for(let r=0;r64&&n<91||n>96&&n<123)&&(t+=e[r])}return t}(o)]=n,!0;if(n){let e=RegExp("^"+r.value+"$"),t=Array.isArray(n)?n.slice(-1)[0].match(e):n.match(e);if(t)return Array.isArray(t)&&(t.groups?Object.keys(t.groups).forEach(e=>{i[e]=t.groups[e]}):"host"===r.type&&t[0]&&(i.host=t[0])),!0}return!1};return!!r.every(e=>o(e))&&!n.some(e=>o(e))&&i}function f(e,t){if(!e.includes(":"))return e;for(let r of Object.keys(t))e.includes(":"+r)&&(e=e.replace(RegExp(":"+r+"\\*","g"),":"+r+"--ESCAPED_PARAM_ASTERISKS").replace(RegExp(":"+r+"\\?","g"),":"+r+"--ESCAPED_PARAM_QUESTION").replace(RegExp(":"+r+"\\+","g"),":"+r+"--ESCAPED_PARAM_PLUS").replace(RegExp(":"+r+"(?!\\w)","g"),"--ESCAPED_PARAM_COLON"+r));return e=e.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g,"\\$1").replace(/--ESCAPED_PARAM_PLUS/g,"+").replace(/--ESCAPED_PARAM_COLON/g,":").replace(/--ESCAPED_PARAM_QUESTION/g,"?").replace(/--ESCAPED_PARAM_ASTERISKS/g,"*"),(0,n.compile)("/"+e,{validate:!1})(t).slice(1)}function p(e){let t;let r=Object.assign({},e.query);delete r.__nextLocale,delete r.__nextDefaultLocale,delete r.__nextDataReq,delete r.__nextInferredLocaleFromDefault,delete r[u.NEXT_RSC_UNION_QUERY];let s=e.destination;for(let t of Object.keys({...e.params,...r}))s=s.replace(RegExp(":"+(0,i.escapeStringRegexp)(t),"g"),"__ESC_COLON_"+t);let l=(0,o.parseUrl)(s),p=l.query,d=c(""+l.pathname+(l.hash||"")),m=c(l.hostname||""),g=[],h=[];(0,n.pathToRegexp)(d,g),(0,n.pathToRegexp)(m,h);let y=[];g.forEach(e=>y.push(e.name)),h.forEach(e=>y.push(e.name));let E=(0,n.compile)(d,{validate:!1}),v=(0,n.compile)(m,{validate:!1});for(let[t,r]of Object.entries(p))Array.isArray(r)?p[t]=r.map(t=>f(c(t),e.params)):"string"==typeof r&&(p[t]=f(c(r),e.params));let R=Object.keys(e.params).filter(e=>"nextInternalLocale"!==e);if(e.appendParamsToQuery&&!R.some(e=>y.includes(e)))for(let t of R)t in p||(p[t]=e.params[t]);if((0,a.isInterceptionRouteAppPath)(d))for(let t of d.split("/")){let r=a.INTERCEPTION_ROUTE_MARKERS.find(e=>t.startsWith(e));if(r){e.params["0"]=r;break}}try{let[r,n]=(t=E(e.params)).split("#",2);l.hostname=v(e.params),l.pathname=r,l.hash=(n?"#":"")+(n||""),delete l.search}catch(e){if(e.message.match(/Expected .*? to not repeat, but got an array/))throw Error("To use a multi-match in the destination you must add `*` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match");throw e}return l.query={...r,...l.query},{newUrl:t,destQuery:p,parsedDestination:l}}},1662:(e,t)=>{"use strict";function r(e){let t={};return e.forEach((e,r)=>{void 0===t[r]?t[r]=e:Array.isArray(t[r])?t[r].push(e):t[r]=[t[r],e]}),t}function n(e){return"string"!=typeof e&&("number"!=typeof e||isNaN(e))&&"boolean"!=typeof e?"":String(e)}function i(e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[r,i]=e;Array.isArray(i)?i.forEach(e=>t.append(r,n(e))):t.set(r,n(i))}),t}function o(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n{Array.from(t.keys()).forEach(t=>e.delete(t)),t.forEach((t,r)=>e.append(r,t))}),e}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{searchParamsToUrlQuery:function(){return r},urlQueryToSearchParams:function(){return i},assign:function(){return o}})},5545:(e,t)=>{"use strict";function r(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return r}})},7158:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getRouteMatcher",{enumerable:!0,get:function(){return i}});let n=r(2881);function i(e){let{re:t,groups:r}=e;return e=>{let i=t.exec(e);if(!i)return!1;let o=e=>{try{return decodeURIComponent(e)}catch(e){throw new n.DecodeError("failed to decode param")}},a={};return Object.keys(r).forEach(e=>{let t=r[e],n=i[t.pos];void 0!==n&&(a[e]=~n.indexOf("/")?n.split("/").map(e=>o(e)):t.repeat?[o(n)]:o(n))}),a}}},4654:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getRouteRegex:function(){return s},getNamedRouteRegex:function(){return f},getNamedMiddlewareRegex:function(){return p}});let n=r(8988),i=r(7436),o=r(5545);function a(e){let t=e.startsWith("[")&&e.endsWith("]");t&&(e=e.slice(1,-1));let r=e.startsWith("...");return r&&(e=e.slice(3)),{key:e,repeat:r,optional:t}}function u(e){let t=(0,o.removeTrailingSlash)(e).slice(1).split("/"),r={},u=1;return{parameterizedRoute:t.map(e=>{let t=n.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);if(t&&o){let{key:e,optional:n,repeat:s}=a(o[1]);return r[e]={pos:u++,repeat:s,optional:n},"/"+(0,i.escapeStringRegexp)(t)+"([^/]+?)"}if(!o)return"/"+(0,i.escapeStringRegexp)(e);{let{key:e,repeat:t,optional:n}=a(o[1]);return r[e]={pos:u++,repeat:t,optional:n},t?n?"(?:/(.+?))?":"/(.+?)":"/([^/]+?)"}}).join(""),groups:r}}function s(e){let{parameterizedRoute:t,groups:r}=u(e);return{re:RegExp("^"+t+"(?:/)?$"),groups:r}}function c(e){let{interceptionMarker:t,getSafeRouteKey:r,segment:n,routeKeys:o,keyPrefix:u}=e,{key:s,optional:c,repeat:l}=a(n),f=s.replace(/\W/g,"");u&&(f=""+u+f);let p=!1;(0===f.length||f.length>30)&&(p=!0),isNaN(parseInt(f.slice(0,1)))||(p=!0),p&&(f=r()),u?o[f]=""+u+s:o[f]=s;let d=t?(0,i.escapeStringRegexp)(t):"";return l?c?"(?:/"+d+"(?<"+f+">.+?))?":"/"+d+"(?<"+f+">.+?)":"/"+d+"(?<"+f+">[^/]+?)"}function l(e,t){let r;let a=(0,o.removeTrailingSlash)(e).slice(1).split("/"),u=(r=0,()=>{let e="",t=++r;for(;t>0;)e+=String.fromCharCode(97+(t-1)%26),t=Math.floor((t-1)/26);return e}),s={};return{namedParameterizedRoute:a.map(e=>{let r=n.INTERCEPTION_ROUTE_MARKERS.some(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);if(r&&o){let[r]=e.split(o[0]);return c({getSafeRouteKey:u,interceptionMarker:r,segment:o[1],routeKeys:s,keyPrefix:t?"nxtI":void 0})}return o?c({getSafeRouteKey:u,segment:o[1],routeKeys:s,keyPrefix:t?"nxtP":void 0}):"/"+(0,i.escapeStringRegexp)(e)}).join(""),routeKeys:s}}function f(e,t){let r=l(e,t);return{...s(e),namedRegex:"^"+r.namedParameterizedRoute+"(?:/)?$",routeKeys:r.routeKeys}}function p(e,t){let{parameterizedRoute:r}=u(e),{catchAll:n=!0}=t;if("/"===r)return{namedRegex:"^/"+(n?".*":"")+"$"};let{namedParameterizedRoute:i}=l(e,!1);return{namedRegex:"^"+i+(n?"(?:(/.*)?)":"")+"$"}}},5458:(e,t)=>{"use strict";function r(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isGroupSegment",{enumerable:!0,get:function(){return r}})},2881:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{WEB_VITALS:function(){return r},execOnce:function(){return n},isAbsoluteUrl:function(){return o},getLocationOrigin:function(){return a},getURL:function(){return u},getDisplayName:function(){return s},isResSent:function(){return c},normalizeRepeatedSlashes:function(){return l},loadGetInitialProps:function(){return f},SP:function(){return p},ST:function(){return d},DecodeError:function(){return m},NormalizeError:function(){return g},PageNotFoundError:function(){return h},MissingStaticPage:function(){return y},MiddlewareNotFoundError:function(){return E},stringifyError:function(){return v}});let r=["CLS","FCP","FID","INP","LCP","TTFB"];function n(e){let t,r=!1;return function(){for(var n=arguments.length,i=Array(n),o=0;oi.test(e);function a(){let{protocol:e,hostname:t,port:r}=window.location;return e+"//"+t+(r?":"+r:"")}function u(){let{href:e}=window.location,t=a();return e.substring(t.length)}function s(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function c(e){return e.finished||e.headersSent}function l(e){let t=e.split("?");return t[0].replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function f(e,t){let r=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await f(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(r&&c(r))return n;if(!n)throw Error('"'+s(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.');return n}let p="undefined"!=typeof performance,d=p&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);class m extends Error{}class g extends Error{}class h extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}}class y extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}}class E extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}}function v(e){return JSON.stringify({message:e.message,stack:e.stack})}}}; \ No newline at end of file diff --git a/.next/server/chunks/622.js b/.next/server/chunks/622.js deleted file mode 100644 index a9afa78..0000000 --- a/.next/server/chunks/622.js +++ /dev/null @@ -1 +0,0 @@ -exports.id=622,exports.ids=[622],exports.modules={6254:(e,t,s)=>{Promise.resolve().then(s.t.bind(s,3724,23)),Promise.resolve().then(s.t.bind(s,5365,23)),Promise.resolve().then(s.t.bind(s,4900,23)),Promise.resolve().then(s.t.bind(s,4714,23)),Promise.resolve().then(s.t.bind(s,5392,23)),Promise.resolve().then(s.t.bind(s,8898,23))},2731:()=>{},5345:(e,t,s)=>{"use strict";s.r(t),s.d(t,{default:()=>RootLayout,metadata:()=>n});var o=s(4656),r=s(2999),i=s.n(r);s(3440);let n={title:"sukadia.dev",description:"I code, stream, and create videos."};function RootLayout({children:e}){return o.jsx("html",{lang:"en",children:o.jsx("body",{className:i().className,children:e})})}},3440:()=>{}}; \ No newline at end of file diff --git a/.next/server/chunks/638.js b/.next/server/chunks/638.js new file mode 100644 index 0000000..a0c26c5 --- /dev/null +++ b/.next/server/chunks/638.js @@ -0,0 +1 @@ +exports.id=638,exports.ids=[638],exports.modules={1359:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{prefixes:function(){return a},bootstrap:function(){return l},wait:function(){return s},error:function(){return u},warn:function(){return c},ready:function(){return d},info:function(){return g},event:function(){return p},trace:function(){return f},warnOnce:function(){return v}});let n=r(1191),a={wait:(0,n.white)((0,n.bold)("○")),error:(0,n.red)((0,n.bold)("⨯")),warn:(0,n.yellow)((0,n.bold)("⚠")),ready:"▲",info:(0,n.white)((0,n.bold)(" ")),event:(0,n.green)((0,n.bold)("✓")),trace:(0,n.magenta)((0,n.bold)("\xbb"))},o={log:"log",warn:"warn",error:"error"};function i(e,...t){(""===t[0]||void 0===t[0])&&1===t.length&&t.shift();let r=e in o?o[e]:"log",n=a[e];0===t.length?console[r](""):console[r](" "+n,...t)}function l(...e){console.log(" ",...e)}function s(...e){i("wait",...e)}function u(...e){i("error",...e)}function c(...e){i("warn",...e)}function d(...e){i("ready",...e)}function g(...e){i("info",...e)}function p(...e){i("event",...e)}function f(...e){i("trace",...e)}let _=new Set;function v(...e){_.has(e[0])||(_.add(e.join(" ")),c(...e))}},5407:e=>{(()=>{"use strict";var t={491:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ContextAPI=void 0;let n=r(223),a=r(172),o=r(930),i="context",l=new n.NoopContextManager;class s{constructor(){}static getInstance(){return this._instance||(this._instance=new s),this._instance}setGlobalContextManager(e){return(0,a.registerGlobal)(i,e,o.DiagAPI.instance())}active(){return this._getContextManager().active()}with(e,t,r,...n){return this._getContextManager().with(e,t,r,...n)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return(0,a.getGlobal)(i)||l}disable(){this._getContextManager().disable(),(0,a.unregisterGlobal)(i,o.DiagAPI.instance())}}t.ContextAPI=s},930:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagAPI=void 0;let n=r(56),a=r(912),o=r(957),i=r(172);class l{constructor(){function e(e){return function(...t){let r=(0,i.getGlobal)("diag");if(r)return r[e](...t)}}let t=this;t.setLogger=(e,r={logLevel:o.DiagLogLevel.INFO})=>{var n,l,s;if(e===t){let e=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error(null!==(n=e.stack)&&void 0!==n?n:e.message),!1}"number"==typeof r&&(r={logLevel:r});let u=(0,i.getGlobal)("diag"),c=(0,a.createLogLevelDiagLogger)(null!==(l=r.logLevel)&&void 0!==l?l:o.DiagLogLevel.INFO,e);if(u&&!r.suppressOverrideMessage){let e=null!==(s=Error().stack)&&void 0!==s?s:"";u.warn(`Current logger will be overwritten from ${e}`),c.warn(`Current logger will overwrite one already registered from ${e}`)}return(0,i.registerGlobal)("diag",c,t,!0)},t.disable=()=>{(0,i.unregisterGlobal)("diag",t)},t.createComponentLogger=e=>new n.DiagComponentLogger(e),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}static instance(){return this._instance||(this._instance=new l),this._instance}}t.DiagAPI=l},653:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MetricsAPI=void 0;let n=r(660),a=r(172),o=r(930),i="metrics";class l{constructor(){}static getInstance(){return this._instance||(this._instance=new l),this._instance}setGlobalMeterProvider(e){return(0,a.registerGlobal)(i,e,o.DiagAPI.instance())}getMeterProvider(){return(0,a.getGlobal)(i)||n.NOOP_METER_PROVIDER}getMeter(e,t,r){return this.getMeterProvider().getMeter(e,t,r)}disable(){(0,a.unregisterGlobal)(i,o.DiagAPI.instance())}}t.MetricsAPI=l},181:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PropagationAPI=void 0;let n=r(172),a=r(874),o=r(194),i=r(277),l=r(369),s=r(930),u="propagation",c=new a.NoopTextMapPropagator;class d{constructor(){this.createBaggage=l.createBaggage,this.getBaggage=i.getBaggage,this.getActiveBaggage=i.getActiveBaggage,this.setBaggage=i.setBaggage,this.deleteBaggage=i.deleteBaggage}static getInstance(){return this._instance||(this._instance=new d),this._instance}setGlobalPropagator(e){return(0,n.registerGlobal)(u,e,s.DiagAPI.instance())}inject(e,t,r=o.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,r)}extract(e,t,r=o.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,r)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,n.unregisterGlobal)(u,s.DiagAPI.instance())}_getGlobalPropagator(){return(0,n.getGlobal)(u)||c}}t.PropagationAPI=d},997:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceAPI=void 0;let n=r(172),a=r(846),o=r(139),i=r(607),l=r(930),s="trace";class u{constructor(){this._proxyTracerProvider=new a.ProxyTracerProvider,this.wrapSpanContext=o.wrapSpanContext,this.isSpanContextValid=o.isSpanContextValid,this.deleteSpan=i.deleteSpan,this.getSpan=i.getSpan,this.getActiveSpan=i.getActiveSpan,this.getSpanContext=i.getSpanContext,this.setSpan=i.setSpan,this.setSpanContext=i.setSpanContext}static getInstance(){return this._instance||(this._instance=new u),this._instance}setGlobalTracerProvider(e){let t=(0,n.registerGlobal)(s,this._proxyTracerProvider,l.DiagAPI.instance());return t&&this._proxyTracerProvider.setDelegate(e),t}getTracerProvider(){return(0,n.getGlobal)(s)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,n.unregisterGlobal)(s,l.DiagAPI.instance()),this._proxyTracerProvider=new a.ProxyTracerProvider}}t.TraceAPI=u},277:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.deleteBaggage=t.setBaggage=t.getActiveBaggage=t.getBaggage=void 0;let n=r(491),a=(0,r(780).createContextKey)("OpenTelemetry Baggage Key");function o(e){return e.getValue(a)||void 0}t.getBaggage=o,t.getActiveBaggage=function(){return o(n.ContextAPI.getInstance().active())},t.setBaggage=function(e,t){return e.setValue(a,t)},t.deleteBaggage=function(e){return e.deleteValue(a)}},993:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BaggageImpl=void 0;class r{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let t=this._entries.get(e);if(t)return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries()).map(([e,t])=>[e,t])}setEntry(e,t){let n=new r(this._entries);return n._entries.set(e,t),n}removeEntry(e){let t=new r(this._entries);return t._entries.delete(e),t}removeEntries(...e){let t=new r(this._entries);for(let r of e)t._entries.delete(r);return t}clear(){return new r}}t.BaggageImpl=r},830:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baggageEntryMetadataSymbol=void 0,t.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")},369:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.baggageEntryMetadataFromString=t.createBaggage=void 0;let n=r(930),a=r(993),o=r(830),i=n.DiagAPI.instance();t.createBaggage=function(e={}){return new a.BaggageImpl(new Map(Object.entries(e)))},t.baggageEntryMetadataFromString=function(e){return"string"!=typeof e&&(i.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e=""),{__TYPE__:o.baggageEntryMetadataSymbol,toString:()=>e}}},67:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.context=void 0;let n=r(491);t.context=n.ContextAPI.getInstance()},223:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopContextManager=void 0;let n=r(780);class a{active(){return n.ROOT_CONTEXT}with(e,t,r,...n){return t.call(r,...n)}bind(e,t){return t}enable(){return this}disable(){return this}}t.NoopContextManager=a},780:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ROOT_CONTEXT=t.createContextKey=void 0,t.createContextKey=function(e){return Symbol.for(e)};class r{constructor(e){let t=this;t._currentContext=e?new Map(e):new Map,t.getValue=e=>t._currentContext.get(e),t.setValue=(e,n)=>{let a=new r(t._currentContext);return a._currentContext.set(e,n),a},t.deleteValue=e=>{let n=new r(t._currentContext);return n._currentContext.delete(e),n}}}t.ROOT_CONTEXT=new r},506:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.diag=void 0;let n=r(930);t.diag=n.DiagAPI.instance()},56:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagComponentLogger=void 0;let n=r(172);class a{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return o("debug",this._namespace,e)}error(...e){return o("error",this._namespace,e)}info(...e){return o("info",this._namespace,e)}warn(...e){return o("warn",this._namespace,e)}verbose(...e){return o("verbose",this._namespace,e)}}function o(e,t,r){let a=(0,n.getGlobal)("diag");if(a)return r.unshift(t),a[e](...r)}t.DiagComponentLogger=a},972:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagConsoleLogger=void 0;let r=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];class n{constructor(){for(let e=0;e{Object.defineProperty(t,"__esModule",{value:!0}),t.createLogLevelDiagLogger=void 0;let n=r(957);t.createLogLevelDiagLogger=function(e,t){function r(r,n){let a=t[r];return"function"==typeof a&&e>=n?a.bind(t):function(){}}return en.DiagLogLevel.ALL&&(e=n.DiagLogLevel.ALL),t=t||{},{error:r("error",n.DiagLogLevel.ERROR),warn:r("warn",n.DiagLogLevel.WARN),info:r("info",n.DiagLogLevel.INFO),debug:r("debug",n.DiagLogLevel.DEBUG),verbose:r("verbose",n.DiagLogLevel.VERBOSE)}}},957:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DiagLogLevel=void 0,function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(t.DiagLogLevel||(t.DiagLogLevel={}))},172:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.unregisterGlobal=t.getGlobal=t.registerGlobal=void 0;let n=r(200),a=r(521),o=r(130),i=a.VERSION.split(".")[0],l=Symbol.for(`opentelemetry.js.api.${i}`),s=n._globalThis;t.registerGlobal=function(e,t,r,n=!1){var o;let i=s[l]=null!==(o=s[l])&&void 0!==o?o:{version:a.VERSION};if(!n&&i[e]){let t=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(t.stack||t.message),!1}if(i.version!==a.VERSION){let t=Error(`@opentelemetry/api: Registration of version v${i.version} for ${e} does not match previously registered API v${a.VERSION}`);return r.error(t.stack||t.message),!1}return i[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${a.VERSION}.`),!0},t.getGlobal=function(e){var t,r;let n=null===(t=s[l])||void 0===t?void 0:t.version;if(n&&(0,o.isCompatible)(n))return null===(r=s[l])||void 0===r?void 0:r[e]},t.unregisterGlobal=function(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${a.VERSION}.`);let r=s[l];r&&delete r[e]}},130:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isCompatible=t._makeCompatibilityCheck=void 0;let n=r(521),a=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function o(e){let t=new Set([e]),r=new Set,n=e.match(a);if(!n)return()=>!1;let o={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(null!=o.prerelease)return function(t){return t===e};function i(e){return r.add(e),!1}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;let n=e.match(a);if(!n)return i(e);let l={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};return null!=l.prerelease||o.major!==l.major?i(e):0===o.major?o.minor===l.minor&&o.patch<=l.patch?(t.add(e),!0):i(e):o.minor<=l.minor?(t.add(e),!0):i(e)}}t._makeCompatibilityCheck=o,t.isCompatible=o(n.VERSION)},886:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.metrics=void 0;let n=r(653);t.metrics=n.MetricsAPI.getInstance()},901:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueType=void 0,function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"}(t.ValueType||(t.ValueType={}))},102:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createNoopMeter=t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=t.NOOP_OBSERVABLE_GAUGE_METRIC=t.NOOP_OBSERVABLE_COUNTER_METRIC=t.NOOP_UP_DOWN_COUNTER_METRIC=t.NOOP_HISTOGRAM_METRIC=t.NOOP_COUNTER_METRIC=t.NOOP_METER=t.NoopObservableUpDownCounterMetric=t.NoopObservableGaugeMetric=t.NoopObservableCounterMetric=t.NoopObservableMetric=t.NoopHistogramMetric=t.NoopUpDownCounterMetric=t.NoopCounterMetric=t.NoopMetric=t.NoopMeter=void 0;class r{constructor(){}createHistogram(e,r){return t.NOOP_HISTOGRAM_METRIC}createCounter(e,r){return t.NOOP_COUNTER_METRIC}createUpDownCounter(e,r){return t.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,r){return t.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,r){return t.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,r){return t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}t.NoopMeter=r;class n{}t.NoopMetric=n;class a extends n{add(e,t){}}t.NoopCounterMetric=a;class o extends n{add(e,t){}}t.NoopUpDownCounterMetric=o;class i extends n{record(e,t){}}t.NoopHistogramMetric=i;class l{addCallback(e){}removeCallback(e){}}t.NoopObservableMetric=l;class s extends l{}t.NoopObservableCounterMetric=s;class u extends l{}t.NoopObservableGaugeMetric=u;class c extends l{}t.NoopObservableUpDownCounterMetric=c,t.NOOP_METER=new r,t.NOOP_COUNTER_METRIC=new a,t.NOOP_HISTOGRAM_METRIC=new i,t.NOOP_UP_DOWN_COUNTER_METRIC=new o,t.NOOP_OBSERVABLE_COUNTER_METRIC=new s,t.NOOP_OBSERVABLE_GAUGE_METRIC=new u,t.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new c,t.createNoopMeter=function(){return t.NOOP_METER}},660:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NOOP_METER_PROVIDER=t.NoopMeterProvider=void 0;let n=r(102);class a{getMeter(e,t,r){return n.NOOP_METER}}t.NoopMeterProvider=a,t.NOOP_METER_PROVIDER=new a},200:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),a=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),a(r(46),t)},651:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t._globalThis=void 0,t._globalThis="object"==typeof globalThis?globalThis:global},46:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r),Object.defineProperty(e,n,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),a=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),a(r(651),t)},939:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.propagation=void 0;let n=r(181);t.propagation=n.PropagationAPI.getInstance()},874:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTextMapPropagator=void 0;class r{inject(e,t){}extract(e,t){return e}fields(){return[]}}t.NoopTextMapPropagator=r},194:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultTextMapSetter=t.defaultTextMapGetter=void 0,t.defaultTextMapGetter={get(e,t){if(null!=e)return e[t]},keys:e=>null==e?[]:Object.keys(e)},t.defaultTextMapSetter={set(e,t,r){null!=e&&(e[t]=r)}}},845:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.trace=void 0;let n=r(997);t.trace=n.TraceAPI.getInstance()},403:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NonRecordingSpan=void 0;let n=r(476);class a{constructor(e=n.INVALID_SPAN_CONTEXT){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}t.NonRecordingSpan=a},614:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTracer=void 0;let n=r(491),a=r(607),o=r(403),i=r(139),l=n.ContextAPI.getInstance();class s{startSpan(e,t,r=l.active()){if(null==t?void 0:t.root)return new o.NonRecordingSpan;let n=r&&(0,a.getSpanContext)(r);return"object"==typeof n&&"string"==typeof n.spanId&&"string"==typeof n.traceId&&"number"==typeof n.traceFlags&&(0,i.isSpanContextValid)(n)?new o.NonRecordingSpan(n):new o.NonRecordingSpan}startActiveSpan(e,t,r,n){let o,i,s;if(arguments.length<2)return;2==arguments.length?s=t:3==arguments.length?(o=t,s=r):(o=t,i=r,s=n);let u=null!=i?i:l.active(),c=this.startSpan(e,o,u),d=(0,a.setSpan)(u,c);return l.with(d,s,void 0,c)}}t.NoopTracer=s},124:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NoopTracerProvider=void 0;let n=r(614);class a{getTracer(e,t,r){return new n.NoopTracer}}t.NoopTracerProvider=a},125:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyTracer=void 0;let n=new(r(614)).NoopTracer;class a{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}startSpan(e,t,r){return this._getTracer().startSpan(e,t,r)}startActiveSpan(e,t,r,n){let a=this._getTracer();return Reflect.apply(a.startActiveSpan,a,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):n}}t.ProxyTracer=a},846:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyTracerProvider=void 0;let n=r(125),a=new(r(124)).NoopTracerProvider;class o{getTracer(e,t,r){var a;return null!==(a=this.getDelegateTracer(e,t,r))&&void 0!==a?a:new n.ProxyTracer(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:a}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getTracer(e,t,r)}}t.ProxyTracerProvider=o},996:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SamplingDecision=void 0,function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(t.SamplingDecision||(t.SamplingDecision={}))},607:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getSpanContext=t.setSpanContext=t.deleteSpan=t.setSpan=t.getActiveSpan=t.getSpan=void 0;let n=r(780),a=r(403),o=r(491),i=(0,n.createContextKey)("OpenTelemetry Context Key SPAN");function l(e){return e.getValue(i)||void 0}function s(e,t){return e.setValue(i,t)}t.getSpan=l,t.getActiveSpan=function(){return l(o.ContextAPI.getInstance().active())},t.setSpan=s,t.deleteSpan=function(e){return e.deleteValue(i)},t.setSpanContext=function(e,t){return s(e,new a.NonRecordingSpan(t))},t.getSpanContext=function(e){var t;return null===(t=l(e))||void 0===t?void 0:t.spanContext()}},325:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceStateImpl=void 0;let n=r(564);class a{constructor(e){this._internalState=new Map,e&&this._parse(e)}set(e,t){let r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+"="+this.get(t)),e),[]).join(",")}_parse(e){!(e.length>512)&&(this._internalState=e.split(",").reverse().reduce((e,t)=>{let r=t.trim(),a=r.indexOf("=");if(-1!==a){let o=r.slice(0,a),i=r.slice(a+1,t.length);(0,n.validateKey)(o)&&(0,n.validateValue)(i)&&e.set(o,i)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new a;return e._internalState=new Map(this._internalState),e}}t.TraceStateImpl=a},564:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.validateValue=t.validateKey=void 0;let r="[_0-9a-z-*/]",n=`[a-z]${r}{0,255}`,a=`[a-z0-9]${r}{0,240}@[a-z]${r}{0,13}`,o=RegExp(`^(?:${n}|${a})$`),i=/^[ -~]{0,255}[!-~]$/,l=/,|=/;t.validateKey=function(e){return o.test(e)},t.validateValue=function(e){return i.test(e)&&!l.test(e)}},98:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createTraceState=void 0;let n=r(325);t.createTraceState=function(e){return new n.TraceStateImpl(e)}},476:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.INVALID_SPAN_CONTEXT=t.INVALID_TRACEID=t.INVALID_SPANID=void 0;let n=r(475);t.INVALID_SPANID="0000000000000000",t.INVALID_TRACEID="00000000000000000000000000000000",t.INVALID_SPAN_CONTEXT={traceId:t.INVALID_TRACEID,spanId:t.INVALID_SPANID,traceFlags:n.TraceFlags.NONE}},357:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SpanKind=void 0,function(e){e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER"}(t.SpanKind||(t.SpanKind={}))},139:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.wrapSpanContext=t.isSpanContextValid=t.isValidSpanId=t.isValidTraceId=void 0;let n=r(476),a=r(403),o=/^([0-9a-f]{32})$/i,i=/^[0-9a-f]{16}$/i;function l(e){return o.test(e)&&e!==n.INVALID_TRACEID}function s(e){return i.test(e)&&e!==n.INVALID_SPANID}t.isValidTraceId=l,t.isValidSpanId=s,t.isSpanContextValid=function(e){return l(e.traceId)&&s(e.spanId)},t.wrapSpanContext=function(e){return new a.NonRecordingSpan(e)}},847:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SpanStatusCode=void 0,function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"}(t.SpanStatusCode||(t.SpanStatusCode={}))},475:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TraceFlags=void 0,function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(t.TraceFlags||(t.TraceFlags={}))},521:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.VERSION=void 0,t.VERSION="1.6.0"}},r={};function n(e){var a=r[e];if(void 0!==a)return a.exports;var o=r[e]={exports:{}},i=!0;try{t[e].call(o.exports,o,o.exports,n),i=!1}finally{i&&delete r[e]}return o.exports}n.ab=__dirname+"/";var a={};(()=>{Object.defineProperty(a,"__esModule",{value:!0}),a.trace=a.propagation=a.metrics=a.diag=a.context=a.INVALID_SPAN_CONTEXT=a.INVALID_TRACEID=a.INVALID_SPANID=a.isValidSpanId=a.isValidTraceId=a.isSpanContextValid=a.createTraceState=a.TraceFlags=a.SpanStatusCode=a.SpanKind=a.SamplingDecision=a.ProxyTracerProvider=a.ProxyTracer=a.defaultTextMapSetter=a.defaultTextMapGetter=a.ValueType=a.createNoopMeter=a.DiagLogLevel=a.DiagConsoleLogger=a.ROOT_CONTEXT=a.createContextKey=a.baggageEntryMetadataFromString=void 0;var e=n(369);Object.defineProperty(a,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return e.baggageEntryMetadataFromString}});var t=n(780);Object.defineProperty(a,"createContextKey",{enumerable:!0,get:function(){return t.createContextKey}}),Object.defineProperty(a,"ROOT_CONTEXT",{enumerable:!0,get:function(){return t.ROOT_CONTEXT}});var r=n(972);Object.defineProperty(a,"DiagConsoleLogger",{enumerable:!0,get:function(){return r.DiagConsoleLogger}});var o=n(957);Object.defineProperty(a,"DiagLogLevel",{enumerable:!0,get:function(){return o.DiagLogLevel}});var i=n(102);Object.defineProperty(a,"createNoopMeter",{enumerable:!0,get:function(){return i.createNoopMeter}});var l=n(901);Object.defineProperty(a,"ValueType",{enumerable:!0,get:function(){return l.ValueType}});var s=n(194);Object.defineProperty(a,"defaultTextMapGetter",{enumerable:!0,get:function(){return s.defaultTextMapGetter}}),Object.defineProperty(a,"defaultTextMapSetter",{enumerable:!0,get:function(){return s.defaultTextMapSetter}});var u=n(125);Object.defineProperty(a,"ProxyTracer",{enumerable:!0,get:function(){return u.ProxyTracer}});var c=n(846);Object.defineProperty(a,"ProxyTracerProvider",{enumerable:!0,get:function(){return c.ProxyTracerProvider}});var d=n(996);Object.defineProperty(a,"SamplingDecision",{enumerable:!0,get:function(){return d.SamplingDecision}});var g=n(357);Object.defineProperty(a,"SpanKind",{enumerable:!0,get:function(){return g.SpanKind}});var p=n(847);Object.defineProperty(a,"SpanStatusCode",{enumerable:!0,get:function(){return p.SpanStatusCode}});var f=n(475);Object.defineProperty(a,"TraceFlags",{enumerable:!0,get:function(){return f.TraceFlags}});var _=n(98);Object.defineProperty(a,"createTraceState",{enumerable:!0,get:function(){return _.createTraceState}});var v=n(139);Object.defineProperty(a,"isSpanContextValid",{enumerable:!0,get:function(){return v.isSpanContextValid}}),Object.defineProperty(a,"isValidTraceId",{enumerable:!0,get:function(){return v.isValidTraceId}}),Object.defineProperty(a,"isValidSpanId",{enumerable:!0,get:function(){return v.isValidSpanId}});var S=n(476);Object.defineProperty(a,"INVALID_SPANID",{enumerable:!0,get:function(){return S.INVALID_SPANID}}),Object.defineProperty(a,"INVALID_TRACEID",{enumerable:!0,get:function(){return S.INVALID_TRACEID}}),Object.defineProperty(a,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return S.INVALID_SPAN_CONTEXT}});let b=n(67);Object.defineProperty(a,"context",{enumerable:!0,get:function(){return b.context}});let h=n(506);Object.defineProperty(a,"diag",{enumerable:!0,get:function(){return h.diag}});let O=n(886);Object.defineProperty(a,"metrics",{enumerable:!0,get:function(){return O.metrics}});let E=n(939);Object.defineProperty(a,"propagation",{enumerable:!0,get:function(){return E.propagation}});let R=n(845);Object.defineProperty(a,"trace",{enumerable:!0,get:function(){return R.trace}}),a.default={context:b.context,diag:h.diag,metrics:O.metrics,propagation:E.propagation,trace:R.trace}})(),e.exports=a})()},2740:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_QUERY_PARAM_PREFIX:function(){return r},PRERENDER_REVALIDATE_HEADER:function(){return n},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return a},RSC_PREFETCH_SUFFIX:function(){return o},RSC_SUFFIX:function(){return i},NEXT_DATA_SUFFIX:function(){return l},NEXT_META_SUFFIX:function(){return s},NEXT_BODY_SUFFIX:function(){return u},NEXT_CACHE_TAGS_HEADER:function(){return c},NEXT_CACHE_SOFT_TAGS_HEADER:function(){return d},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return g},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return p},NEXT_CACHE_TAG_MAX_LENGTH:function(){return f},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return _},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return v},CACHE_ONE_YEAR:function(){return S},MIDDLEWARE_FILENAME:function(){return b},MIDDLEWARE_LOCATION_REGEXP:function(){return h},INSTRUMENTATION_HOOK_FILENAME:function(){return O},PAGES_DIR_ALIAS:function(){return E},DOT_NEXT_ALIAS:function(){return R},ROOT_DIR_ALIAS:function(){return P},APP_DIR_ALIAS:function(){return T},RSC_MOD_REF_PROXY_ALIAS:function(){return m},RSC_ACTION_VALIDATE_ALIAS:function(){return N},RSC_ACTION_PROXY_ALIAS:function(){return x},RSC_ACTION_ENCRYPTION_ALIAS:function(){return y},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return C},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return A},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return I},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return M},SERVER_PROPS_SSG_CONFLICT:function(){return D},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return L},SERVER_PROPS_EXPORT_ERROR:function(){return w},GSP_NO_RETURNED_VALUE:function(){return j},GSSP_NO_RETURNED_VALUE:function(){return V},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return B},GSSP_COMPONENT_MEMBER_ERROR:function(){return G},NON_STANDARD_NODE_ENV:function(){return U},SSG_FALLBACK_EXPORT_ERROR:function(){return H},ESLINT_DEFAULT_DIRS:function(){return F},ESLINT_PROMPT_VALUES:function(){return $},SERVER_RUNTIME:function(){return X},WEBPACK_LAYERS:function(){return K},WEBPACK_RESOURCE_QUERIES:function(){return W}});let r="nxtP",n="x-prerender-revalidate",a="x-prerender-revalidate-if-generated",o=".prefetch.rsc",i=".rsc",l=".json",s=".meta",u=".body",c="x-next-cache-tags",d="x-next-cache-soft-tags",g="x-next-revalidated-tags",p="x-next-revalidate-tag-token",f=256,_=1024,v="_N_T_",S=31536e3,b="middleware",h=`(?:src/)?${b}`,O="instrumentation",E="private-next-pages",R="private-dot-next",P="private-next-root-dir",T="private-next-app-dir",m="next/dist/build/webpack/loaders/next-flight-loader/module-proxy",N="private-next-rsc-action-validate",x="private-next-rsc-action-proxy",y="private-next-rsc-action-encryption",C="private-next-rsc-action-client-wrapper",A="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",I="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",M="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",D="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",L="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",w="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",j="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",V="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",B="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",G="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",U='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',H="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",F=["app","pages","components","lib","src"],$=[{title:"Strict",recommended:!0,config:{extends:"next/core-web-vitals"}},{title:"Base",config:{extends:"next"}},{title:"Cancel",config:null}],X={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},k={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",appMetadataRoute:"app-metadata-route",appRouteHandler:"app-route-handler"},K={...k,GROUP:{server:[k.reactServerComponents,k.actionBrowser,k.appMetadataRoute,k.appRouteHandler],nonClientServerTarget:[k.middleware,k.api],app:[k.reactServerComponents,k.actionBrowser,k.appMetadataRoute,k.appRouteHandler,k.serverSideRendering,k.appPagesBrowser]}},W={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},1191:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{reset:function(){return s},bold:function(){return u},dim:function(){return c},italic:function(){return d},underline:function(){return g},inverse:function(){return p},hidden:function(){return f},strikethrough:function(){return _},black:function(){return v},red:function(){return S},green:function(){return b},yellow:function(){return h},blue:function(){return O},magenta:function(){return E},purple:function(){return R},cyan:function(){return P},white:function(){return T},gray:function(){return m},bgBlack:function(){return N},bgRed:function(){return x},bgGreen:function(){return y},bgYellow:function(){return C},bgBlue:function(){return A},bgMagenta:function(){return I},bgCyan:function(){return M},bgWhite:function(){return D}});let{env:n,stdout:a}=(null==(r=globalThis)?void 0:r.process)??{},o=n&&!n.NO_COLOR&&(n.FORCE_COLOR||(null==a?void 0:a.isTTY)&&!n.CI&&"dumb"!==n.TERM),i=(e,t,r,n)=>{let a=e.substring(0,n)+r,o=e.substring(n+t.length),l=o.indexOf(t);return~l?a+i(o,t,r,l):a+o},l=(e,t,r=e)=>n=>{let a=""+n,o=a.indexOf(t,e.length);return~o?e+i(a,t,r,o)+t:e+a+t},s=o?e=>`\x1b[0m${e}\x1b[0m`:String,u=o?l("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"):String,c=o?l("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"):String,d=o?l("\x1b[3m","\x1b[23m"):String,g=o?l("\x1b[4m","\x1b[24m"):String,p=o?l("\x1b[7m","\x1b[27m"):String,f=o?l("\x1b[8m","\x1b[28m"):String,_=o?l("\x1b[9m","\x1b[29m"):String,v=o?l("\x1b[30m","\x1b[39m"):String,S=o?l("\x1b[31m","\x1b[39m"):String,b=o?l("\x1b[32m","\x1b[39m"):String,h=o?l("\x1b[33m","\x1b[39m"):String,O=o?l("\x1b[34m","\x1b[39m"):String,E=o?l("\x1b[35m","\x1b[39m"):String,R=o?l("\x1b[38;2;173;127;168m","\x1b[39m"):String,P=o?l("\x1b[36m","\x1b[39m"):String,T=o?l("\x1b[37m","\x1b[39m"):String,m=o?l("\x1b[90m","\x1b[39m"):String,N=o?l("\x1b[40m","\x1b[49m"):String,x=o?l("\x1b[41m","\x1b[49m"):String,y=o?l("\x1b[42m","\x1b[49m"):String,C=o?l("\x1b[43m","\x1b[49m"):String,A=o?l("\x1b[44m","\x1b[49m"):String,I=o?l("\x1b[45m","\x1b[49m"):String,M=o?l("\x1b[46m","\x1b[49m"):String,D=o?l("\x1b[47m","\x1b[49m"):String},9108:(e,t)=>{"use strict";var r;Object.defineProperty(t,"x",{enumerable:!0,get:function(){return r}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE"}(r||(r={}))},9678:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{validateTags:function(){return s},addImplicitTags:function(){return c},patchFetch:function(){return g}});let n=r(5237),a=r(7636),o=r(2740),i=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=l(t);if(r&&r.has(e))return r.get(e);var n={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var i=a?Object.getOwnPropertyDescriptor(e,o):null;i&&(i.get||i.set)?Object.defineProperty(n,o,i):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}(r(1359));function l(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(l=function(e){return e?r:t})(e)}function s(e,t){let r=[],n=[];for(let t of e)"string"!=typeof t?n.push({tag:t,reason:"invalid type, must be a string"}):t.length>o.NEXT_CACHE_TAG_MAX_LENGTH?n.push({tag:t,reason:`exceeded max length of ${o.NEXT_CACHE_TAG_MAX_LENGTH}`}):r.push(t);if(n.length>0)for(let{tag:e,reason:r}of(console.warn(`Warning: invalid tags passed to ${t}: `),n))console.log(`tag: "${e}" ${r}`);return r}let u=e=>{let t=["/layout"];if(e.startsWith("/")){let r=e.split("/");for(let e=1;er.every(r=>e[r]===t[r]))||e.fetchMetrics.push({url:t.url,cacheStatus:t.cacheStatus,cacheReason:t.cacheReason,status:t.status,method:t.method,start:t.start,end:Date.now(),idx:e.nextFetchId||0})}function g({serverHooks:e,staticGenerationAsyncStorage:t}){if(globalThis._nextOriginalFetch||(globalThis._nextOriginalFetch=globalThis.fetch),globalThis.fetch.__nextPatched)return;let{DynamicServerError:r}=e,l=globalThis._nextOriginalFetch;globalThis.fetch=async(e,u)=>{var g,p;let f;try{(f=new URL(e instanceof Request?e.url:e)).username="",f.password=""}catch{f=void 0}let _=(null==f?void 0:f.href)??"",v=Date.now(),S=(null==u?void 0:null==(g=u.method)?void 0:g.toUpperCase())||"GET",b=(null==(p=null==u?void 0:u.next)?void 0:p.internal)===!0;return await (0,a.getTracer)().trace(b?n.NextNodeServerSpan.internalFetch:n.AppRenderSpan.fetch,{kind:a.SpanKind.CLIENT,spanName:["fetch",S,_].filter(Boolean).join(" "),attributes:{"http.url":_,"http.method":S,"net.peer.name":null==f?void 0:f.hostname,"net.peer.port":(null==f?void 0:f.port)||void 0}},async()=>{var n;let a,g,p;let f=t.getStore()||(null==fetch.__nextGetStaticStore?void 0:fetch.__nextGetStaticStore.call(fetch)),S=e&&"object"==typeof e&&"string"==typeof e.method,h=t=>(S?e[t]:null)||(null==u?void 0:u[t]);if(!f||b||f.isDraftMode)return l(e,u);let O=t=>{var r,n,a;return void 0!==(null==u?void 0:null==(r=u.next)?void 0:r[t])?null==u?void 0:null==(n=u.next)?void 0:n[t]:S?null==(a=e.next)?void 0:a[t]:void 0},E=O("revalidate"),R=s(O("tags")||[],`fetch ${e.toString()}`);if(Array.isArray(R))for(let e of(f.tags||(f.tags=[]),R))f.tags.includes(e)||f.tags.push(e);let P=c(f),T="only-cache"===f.fetchCache,m="force-cache"===f.fetchCache,N="default-cache"===f.fetchCache,x="default-no-store"===f.fetchCache,y="only-no-store"===f.fetchCache,C="force-no-store"===f.fetchCache,A=h("cache"),I="";"string"==typeof A&&void 0!==E&&(S&&"default"===A||i.warn(`fetch for ${_} on ${f.urlPathname} specified "cache: ${A}" and "revalidate: ${E}", only one should be specified.`),A=void 0),"force-cache"===A?E=!1:("no-cache"===A||"no-store"===A||C||y)&&(E=0),("no-cache"===A||"no-store"===A)&&(I=`cache: ${A}`),("number"==typeof E||!1===E)&&(p=E);let M=h("headers"),D="function"==typeof(null==M?void 0:M.get)?M:new Headers(M||{}),L=D.get("authorization")||D.get("cookie"),w=!["get","head"].includes((null==(n=h("method"))?void 0:n.toLowerCase())||"get"),j=(L||w)&&0===f.revalidate;if(C&&(I="fetchCache = force-no-store"),y){if("force-cache"===A||void 0!==p&&(!1===p||p>0))throw Error(`cache: 'force-cache' used on fetch for ${_} with 'export const fetchCache = 'only-no-store'`);I="fetchCache = only-no-store"}if(T&&"no-store"===A)throw Error(`cache: 'no-store' used on fetch for ${_} with 'export const fetchCache = 'only-cache'`);m&&(void 0===E||0===E)&&(I="fetchCache = force-cache",p=!1),void 0===p?N?(p=!1,I="fetchCache = default-cache"):j?(p=0,I="auto no cache"):x?(p=0,I="fetchCache = default-no-store"):(I="auto cache",p="boolean"!=typeof f.revalidate&&void 0!==f.revalidate&&f.revalidate):I||(I=`revalidate: ${p}`),!j&&(void 0===f.revalidate||"number"==typeof p&&(!1===f.revalidate||"number"==typeof f.revalidate&&p0||!1===p;if(f.incrementalCache&&V)try{a=await f.incrementalCache.fetchCacheKey(_,S?e:u)}catch(t){console.error("Failed to generate cache key for",e)}let B=f.nextFetchId??1;f.nextFetchId=B+1;let G="number"!=typeof p?o.CACHE_ONE_YEAR:p,U=async(t,r)=>{let n=["cache","credentials","headers","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","window","duplex",...t?[]:["signal"]];if(S){let t=e,r={body:t._ogBody||t.body};for(let e of n)r[e]=t[e];e=new Request(t.url,r)}else if(u){let e=u;for(let t of(u={body:u._ogBody||u.body},n))u[t]=e[t]}let o={...u,next:{...null==u?void 0:u.next,fetchType:"origin",fetchIdx:B}};return l(e,o).then(async n=>{if(t||d(f,{start:v,url:_,cacheReason:r||I,cacheStatus:0===p||r?"skip":"miss",status:n.status,method:o.method||"GET"}),200===n.status&&f.incrementalCache&&a&&V){let t=Buffer.from(await n.arrayBuffer());try{await f.incrementalCache.set(a,{kind:"FETCH",data:{headers:Object.fromEntries(n.headers.entries()),body:t.toString("base64"),status:n.status,url:n.url},revalidate:G},{fetchCache:!0,revalidate:p,fetchUrl:_,fetchIdx:B,tags:R})}catch(t){console.warn("Failed to set fetch cache",e,t)}let r=new Response(t,{headers:new Headers(n.headers),status:n.status});return Object.defineProperty(r,"url",{value:n.url}),r}return n})},H=()=>Promise.resolve();if(a&&f.incrementalCache){H=await f.incrementalCache.lock(a);let e=f.isOnDemandRevalidate?null:await f.incrementalCache.get(a,{kindHint:"fetch",revalidate:p,fetchUrl:_,fetchIdx:B,tags:R,softTags:P});if(e?await H():g="cache-control: no-cache (hard refresh)",(null==e?void 0:e.value)&&"FETCH"===e.value.kind&&!(f.isRevalidate&&e.isStale)){e.isStale&&(f.pendingRevalidates??={},f.pendingRevalidates[a]||(f.pendingRevalidates[a]=U(!0).catch(console.error)));let t=e.value.data;d(f,{start:v,url:_,cacheReason:I,cacheStatus:"hit",status:t.status||200,method:(null==u?void 0:u.method)||"GET"});let r=new Response(Buffer.from(t.body,"base64"),{headers:t.headers,status:t.status});return Object.defineProperty(r,"url",{value:e.value.data.url}),r}}if(f.isStaticGeneration&&u&&"object"==typeof u){let{cache:t}=u;if("no-store"===t){let t=`no-store fetch ${e}${f.urlPathname?` ${f.urlPathname}`:""}`;null==f.postpone||f.postpone.call(f,t),f.revalidate=0;let n=new r(t);f.dynamicUsageErr=n,f.dynamicUsageDescription=t}let n="next"in u,{next:a={}}=u;if("number"==typeof a.revalidate&&(void 0===f.revalidate||"number"==typeof f.revalidate&&a.revalidatet,globalThis.fetch.__nextPatched=!0}},5237:(e,t)=>{"use strict";var r,n,a,o,i,l,s,u,c,d,g;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NextVanillaSpanAllowlist:function(){return p},BaseServerSpan:function(){return r},LoadComponentsSpan:function(){return n},NextServerSpan:function(){return a},NextNodeServerSpan:function(){return o},StartServerSpan:function(){return i},RenderSpan:function(){return l},RouterSpan:function(){return u},AppRenderSpan:function(){return s},NodeSpan:function(){return c},AppRouteRouteHandlersSpan:function(){return d},ResolveMetadataSpan:function(){return g}}),function(e){e.handleRequest="BaseServer.handleRequest",e.run="BaseServer.run",e.pipe="BaseServer.pipe",e.getStaticHTML="BaseServer.getStaticHTML",e.render="BaseServer.render",e.renderToResponseWithComponents="BaseServer.renderToResponseWithComponents",e.renderToResponse="BaseServer.renderToResponse",e.renderToHTML="BaseServer.renderToHTML",e.renderError="BaseServer.renderError",e.renderErrorToResponse="BaseServer.renderErrorToResponse",e.renderErrorToHTML="BaseServer.renderErrorToHTML",e.render404="BaseServer.render404"}(r||(r={})),function(e){e.loadDefaultErrorComponents="LoadComponents.loadDefaultErrorComponents",e.loadComponents="LoadComponents.loadComponents"}(n||(n={})),function(e){e.getRequestHandler="NextServer.getRequestHandler",e.getServer="NextServer.getServer",e.getServerRequestHandler="NextServer.getServerRequestHandler",e.createServer="createServer.createServer"}(a||(a={})),function(e){e.compression="NextNodeServer.compression",e.getBuildId="NextNodeServer.getBuildId",e.generateStaticRoutes="NextNodeServer.generateStaticRoutes",e.generateFsStaticRoutes="NextNodeServer.generateFsStaticRoutes",e.generatePublicRoutes="NextNodeServer.generatePublicRoutes",e.generateImageRoutes="NextNodeServer.generateImageRoutes.route",e.sendRenderResult="NextNodeServer.sendRenderResult",e.proxyRequest="NextNodeServer.proxyRequest",e.runApi="NextNodeServer.runApi",e.render="NextNodeServer.render",e.renderHTML="NextNodeServer.renderHTML",e.imageOptimizer="NextNodeServer.imageOptimizer",e.getPagePath="NextNodeServer.getPagePath",e.getRoutesManifest="NextNodeServer.getRoutesManifest",e.findPageComponents="NextNodeServer.findPageComponents",e.getFontManifest="NextNodeServer.getFontManifest",e.getServerComponentManifest="NextNodeServer.getServerComponentManifest",e.getRequestHandler="NextNodeServer.getRequestHandler",e.renderToHTML="NextNodeServer.renderToHTML",e.renderError="NextNodeServer.renderError",e.renderErrorToHTML="NextNodeServer.renderErrorToHTML",e.render404="NextNodeServer.render404",e.route="route",e.onProxyReq="onProxyReq",e.apiResolver="apiResolver",e.internalFetch="internalFetch"}(o||(o={})),(i||(i={})).startServer="startServer.startServer",function(e){e.getServerSideProps="Render.getServerSideProps",e.getStaticProps="Render.getStaticProps",e.renderToString="Render.renderToString",e.renderDocument="Render.renderDocument",e.createBodyResult="Render.createBodyResult"}(l||(l={})),function(e){e.renderToString="AppRender.renderToString",e.renderToReadableStream="AppRender.renderToReadableStream",e.getBodyResult="AppRender.getBodyResult",e.fetch="AppRender.fetch"}(s||(s={})),(u||(u={})).executeRoute="Router.executeRoute",(c||(c={})).runHandler="Node.runHandler",(d||(d={})).runHandler="AppRouteRouteHandlers.runHandler",function(e){e.generateMetadata="ResolveMetadata.generateMetadata",e.generateViewport="ResolveMetadata.generateViewport"}(g||(g={}));let p=["BaseServer.handleRequest","Render.getServerSideProps","Render.getStaticProps","AppRender.fetch","AppRender.getBodyResult","Render.renderDocument","Node.runHandler","AppRouteRouteHandlers.runHandler","ResolveMetadata.generateMetadata","ResolveMetadata.generateViewport"]},7636:(e,t,r)=>{"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getTracer:function(){return b},SpanStatusCode:function(){return s},SpanKind:function(){return u}});let a=r(5237);try{n=r(5407)}catch(e){n=r(5407)}let{context:o,propagation:i,trace:l,SpanStatusCode:s,SpanKind:u,ROOT_CONTEXT:c}=n,d=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then,g=(e,t)=>{(null==t?void 0:t.bubble)===!0?e.setAttribute("next.bubble",!0):(t&&e.recordException(t),e.setStatus({code:s.ERROR,message:null==t?void 0:t.message})),e.end()},p=new Map,f=n.createContextKey("next.rootSpanId"),_=0,v=()=>_++;class S{getTracerInstance(){return l.getTracer("next.js","0.0.1")}getContext(){return o}getActiveScopeSpan(){return l.getSpan(null==o?void 0:o.active())}withPropagatedContext(e,t,r){let n=o.active();if(l.getSpanContext(n))return t();let a=i.extract(n,e,r);return o.with(a,t)}trace(...e){var t;let[r,n,i]=e,{fn:s,options:u}="function"==typeof n?{fn:n,options:{}}:{fn:i,options:{...n}};if(!a.NextVanillaSpanAllowlist.includes(r)&&"1"!==process.env.NEXT_OTEL_VERBOSE||u.hideSpan)return s();let _=u.spanName??r,S=this.getSpanContext((null==u?void 0:u.parentSpan)??this.getActiveScopeSpan()),b=!1;S?(null==(t=l.getSpanContext(S))?void 0:t.isRemote)&&(b=!0):(S=c,b=!0);let h=v();return u.attributes={"next.span_name":_,"next.span_type":r,...u.attributes},o.with(S.setValue(f,h),()=>this.getTracerInstance().startActiveSpan(_,u,e=>{let t=()=>{p.delete(h)};b&&p.set(h,new Map(Object.entries(u.attributes??{})));try{if(s.length>1)return s(e,t=>g(e,t));let r=s(e);return d(r)?r.then(()=>e.end(),t=>g(e,t)).finally(t):(e.end(),t()),r}catch(r){throw g(e,r),t(),r}}))}wrap(...e){let t=this,[r,n,i]=3===e.length?e:[e[0],{},e[1]];return a.NextVanillaSpanAllowlist.includes(r)||"1"===process.env.NEXT_OTEL_VERBOSE?function(){let e=n;"function"==typeof e&&"function"==typeof i&&(e=e.apply(this,arguments));let a=arguments.length-1,l=arguments[a];if("function"!=typeof l)return t.trace(r,e,()=>i.apply(this,arguments));{let n=t.getContext().bind(o.active(),l);return t.trace(r,e,(e,t)=>(arguments[a]=function(e){return null==t||t(e),n.apply(this,arguments)},i.apply(this,arguments)))}}:i}startSpan(...e){let[t,r]=e,n=this.getSpanContext((null==r?void 0:r.parentSpan)??this.getActiveScopeSpan());return this.getTracerInstance().startSpan(t,r,n)}getSpanContext(e){return e?l.setSpan(o.active(),e):void 0}getRootSpanAttributes(){let e=o.active().getValue(f);return p.get(e)}}let b=(()=>{let e=new S;return()=>e})()}}; \ No newline at end of file diff --git a/.next/server/chunks/676.js b/.next/server/chunks/676.js deleted file mode 100644 index d1f6098..0000000 --- a/.next/server/chunks/676.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict";exports.id=676,exports.ids=[676],exports.modules={8676:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{Head:function(){return Head},NextScript:function(){return NextScript},Html:function(){return Html},Main:function(){return Main},default:function(){return Document}});let r=_interop_require_default(n(6689)),i=n(4191),o=n(5778),s=n(9630),l=_interop_require_default(n(676)),a=n(3112);function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}let u=new Set;function getDocumentFiles(e,t,n){let r=(0,o.getPageFiles)(e,"/_app"),i=n?[]:(0,o.getPageFiles)(e,t);return{sharedFiles:r,pageFiles:i,allFiles:[...new Set([...r,...i])]}}function getPolyfillScripts(e,t){let{assetPrefix:n,buildManifest:i,assetQueryString:o,disableOptimizedLoading:s,crossOrigin:l}=e;return i.polyfillFiles.filter(e=>e.endsWith(".js")&&!e.endsWith(".module.js")).map(e=>r.default.createElement("script",{key:e,defer:!s,nonce:t.nonce,crossOrigin:t.crossOrigin||l,noModule:!0,src:`${n}/_next/${e}${o}`}))}function hasComponentProps(e){return!!e&&!!e.props}function AmpStyles({styles:e}){if(!e)return null;let t=Array.isArray(e)?e:[];if(e.props&&Array.isArray(e.props.children)){let hasStyles=e=>{var t,n;return null==e?void 0:null==(n=e.props)?void 0:null==(t=n.dangerouslySetInnerHTML)?void 0:t.__html};e.props.children.forEach(e=>{Array.isArray(e)?e.forEach(e=>hasStyles(e)&&t.push(e)):hasStyles(e)&&t.push(e)})}return r.default.createElement("style",{"amp-custom":"",dangerouslySetInnerHTML:{__html:t.map(e=>e.props.dangerouslySetInnerHTML.__html).join("").replace(/\/\*# sourceMappingURL=.*\*\//g,"").replace(/\/\*@ sourceURL=.*?\*\//g,"")}})}function getDynamicChunks(e,t,n){let{dynamicImports:i,assetPrefix:o,isDevelopment:s,assetQueryString:l,disableOptimizedLoading:a,crossOrigin:u}=e;return i.map(e=>!e.endsWith(".js")||n.allFiles.includes(e)?null:r.default.createElement("script",{async:!s&&a,defer:!a,key:e,src:`${o}/_next/${encodeURI(e)}${l}`,nonce:t.nonce,crossOrigin:t.crossOrigin||u}))}function getScripts(e,t,n){var i;let{assetPrefix:o,buildManifest:s,isDevelopment:l,assetQueryString:a,disableOptimizedLoading:u,crossOrigin:c}=e,d=n.allFiles.filter(e=>e.endsWith(".js")),p=null==(i=s.lowPriorityFiles)?void 0:i.filter(e=>e.endsWith(".js"));return[...d,...p].map(e=>r.default.createElement("script",{key:e,src:`${o}/_next/${encodeURI(e)}${a}`,nonce:t.nonce,async:!l&&u,defer:!u,crossOrigin:t.crossOrigin||c}))}function getPreNextWorkerScripts(e,t){let{assetPrefix:n,scriptLoader:i,crossOrigin:o,nextScriptWorkers:s}=e;if(!s)return null;try{let{partytownSnippet:e}=require("@builder.io/partytown/integration"),s=Array.isArray(t.children)?t.children:[t.children],l=s.find(e=>{var t,n;return hasComponentProps(e)&&(null==e?void 0:null==(n=e.props)?void 0:null==(t=n.dangerouslySetInnerHTML)?void 0:t.__html.length)&&"data-partytown-config"in e.props});return r.default.createElement(r.default.Fragment,null,!l&&r.default.createElement("script",{"data-partytown-config":"",dangerouslySetInnerHTML:{__html:` - partytown = { - lib: "${n}/_next/static/~partytown/" - }; - `}}),r.default.createElement("script",{"data-partytown":"",dangerouslySetInnerHTML:{__html:e()}}),(i.worker||[]).map((e,n)=>{let{strategy:i,src:s,children:l,dangerouslySetInnerHTML:a,...u}=e,c={};if(s)c.src=s;else if(a&&a.__html)c.dangerouslySetInnerHTML={__html:a.__html};else if(l)c.dangerouslySetInnerHTML={__html:"string"==typeof l?l:Array.isArray(l)?l.join(""):""};else throw Error("Invalid usage of next/script. Did you forget to include a src attribute or an inline script? https://nextjs.org/docs/messages/invalid-script");return r.default.createElement("script",{...c,...u,type:"text/partytown",key:s||n,nonce:t.nonce,"data-nscript":"worker",crossOrigin:t.crossOrigin||o})}))}catch(e){return(0,l.default)(e)&&"MODULE_NOT_FOUND"!==e.code&&console.warn(`Warning: ${e.message}`),null}}function getPreNextScripts(e,t){let{scriptLoader:n,disableOptimizedLoading:i,crossOrigin:o}=e,s=getPreNextWorkerScripts(e,t),l=(n.beforeInteractive||[]).filter(e=>e.src).map((e,n)=>{let{strategy:s,...l}=e;return r.default.createElement("script",{...l,key:l.src||n,defer:l.defer??!i,nonce:t.nonce,"data-nscript":"beforeInteractive",crossOrigin:t.crossOrigin||o})});return r.default.createElement(r.default.Fragment,null,s,l)}function getHeadHTMLProps(e){let{crossOrigin:t,nonce:n,...r}=e;return r}function getAmpPath(e,t){return e||`${t}${t.includes("?")?"&":"?"}amp=1`}function getNextFontLinkTags(e,t,n=""){if(!e)return{preconnect:null,preload:null};let i=e.pages["/_app"],o=e.pages[t],s=[...i??[],...o??[]],l=!!(0===s.length&&(i||o));return{preconnect:l?r.default.createElement("link",{"data-next-font":e.pagesUsingSizeAdjust?"size-adjust":"",rel:"preconnect",href:"/",crossOrigin:"anonymous"}):null,preload:s?s.map(e=>{let t=/\.(woff|woff2|eot|ttf|otf)$/.exec(e)[1];return r.default.createElement("link",{key:e,rel:"preload",href:`${n}/_next/${encodeURI(e)}`,as:"font",type:`font/${t}`,crossOrigin:"anonymous","data-next-font":e.includes("-s")?"size-adjust":""})}):null}}let Head=class Head extends r.default.Component{static #e=this.contextType=a.HtmlContext;getCssLinks(e){let{assetPrefix:t,assetQueryString:n,dynamicImports:i,crossOrigin:o,optimizeCss:s,optimizeFonts:l}=this.context,a=e.allFiles.filter(e=>e.endsWith(".css")),u=new Set(e.sharedFiles),c=new Set([]),d=Array.from(new Set(i.filter(e=>e.endsWith(".css"))));if(d.length){let e=new Set(a);d=d.filter(t=>!(e.has(t)||u.has(t))),c=new Set(d),a.push(...d)}let p=[];return a.forEach(e=>{let i=u.has(e);s||p.push(r.default.createElement("link",{key:`${e}-preload`,nonce:this.props.nonce,rel:"preload",href:`${t}/_next/${encodeURI(e)}${n}`,as:"style",crossOrigin:this.props.crossOrigin||o}));let l=c.has(e);p.push(r.default.createElement("link",{key:e,nonce:this.props.nonce,rel:"stylesheet",href:`${t}/_next/${encodeURI(e)}${n}`,crossOrigin:this.props.crossOrigin||o,"data-n-g":l?void 0:i?"":void 0,"data-n-p":l?void 0:i?void 0:""}))}),l&&(p=this.makeStylesheetInert(p)),0===p.length?null:p}getPreloadDynamicChunks(){let{dynamicImports:e,assetPrefix:t,assetQueryString:n,crossOrigin:i}=this.context;return e.map(e=>e.endsWith(".js")?r.default.createElement("link",{rel:"preload",key:e,href:`${t}/_next/${encodeURI(e)}${n}`,as:"script",nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||i}):null).filter(Boolean)}getPreloadMainLinks(e){let{assetPrefix:t,assetQueryString:n,scriptLoader:i,crossOrigin:o}=this.context,s=e.allFiles.filter(e=>e.endsWith(".js"));return[...(i.beforeInteractive||[]).map(e=>r.default.createElement("link",{key:e.src,nonce:this.props.nonce,rel:"preload",href:e.src,as:"script",crossOrigin:this.props.crossOrigin||o})),...s.map(e=>r.default.createElement("link",{key:e,nonce:this.props.nonce,rel:"preload",href:`${t}/_next/${encodeURI(e)}${n}`,as:"script",crossOrigin:this.props.crossOrigin||o}))]}getBeforeInteractiveInlineScripts(){let{scriptLoader:e}=this.context,{nonce:t,crossOrigin:n}=this.props;return(e.beforeInteractive||[]).filter(e=>!e.src&&(e.dangerouslySetInnerHTML||e.children)).map((e,i)=>{let{strategy:o,children:s,dangerouslySetInnerHTML:l,src:a,...u}=e,c="";return l&&l.__html?c=l.__html:s&&(c="string"==typeof s?s:Array.isArray(s)?s.join(""):""),r.default.createElement("script",{...u,dangerouslySetInnerHTML:{__html:c},key:u.id||i,nonce:t,"data-nscript":"beforeInteractive",crossOrigin:n||void 0})})}getDynamicChunks(e){return getDynamicChunks(this.context,this.props,e)}getPreNextScripts(){return getPreNextScripts(this.context,this.props)}getScripts(e){return getScripts(this.context,this.props,e)}getPolyfillScripts(){return getPolyfillScripts(this.context,this.props)}makeStylesheetInert(e){return r.default.Children.map(e,e=>{var t,n;if((null==e?void 0:e.type)==="link"&&(null==e?void 0:null==(t=e.props)?void 0:t.href)&&i.OPTIMIZED_FONT_PROVIDERS.some(({url:t})=>{var n,r;return null==e?void 0:null==(r=e.props)?void 0:null==(n=r.href)?void 0:n.startsWith(t)})){let t={...e.props||{},"data-href":e.props.href,href:void 0};return r.default.cloneElement(e,t)}if(null==e?void 0:null==(n=e.props)?void 0:n.children){let t={...e.props||{},children:this.makeStylesheetInert(e.props.children)};return r.default.cloneElement(e,t)}return e}).filter(Boolean)}render(){let{styles:e,ampPath:t,inAmpMode:i,hybridAmp:o,canonicalBase:s,__NEXT_DATA__:l,dangerousAsPath:a,headTags:u,unstable_runtimeJS:c,unstable_JsPreload:d,disableOptimizedLoading:p,optimizeCss:f,optimizeFonts:m,assetPrefix:h,nextFontManifest:g}=this.context,_=!1===c,E=!1===d||!p;this.context.docComponentsRendered.Head=!0;let{head:S}=this.context,y=[],I=[];S&&(S.forEach(e=>{let t;this.context.strictNextHead&&(t=r.default.createElement("meta",{name:"next-head",content:"1"})),e&&"link"===e.type&&"preload"===e.props.rel&&"style"===e.props.as?(t&&y.push(t),y.push(e)):e&&(t&&("meta"!==e.type||!e.props.charSet)&&I.push(t),I.push(e))}),S=y.concat(I));let P=r.default.Children.toArray(this.props.children).filter(Boolean);m&&!i&&(P=this.makeStylesheetInert(P));let T=!1,N=!1;S=r.default.Children.map(S||[],e=>{if(!e)return e;let{type:t,props:n}=e;if(i){let r="";if("meta"===t&&"viewport"===n.name?r='name="viewport"':"link"===t&&"canonical"===n.rel?N=!0:"script"===t&&(n.src&&-1>n.src.indexOf("ampproject")||n.dangerouslySetInnerHTML&&(!n.type||"text/javascript"===n.type))&&(r="{r+=` ${e}="${n[e]}"`}),r+="/>"),r)return console.warn(`Found conflicting amp tag "${e.type}" with conflicting prop ${r} in ${l.page}. https://nextjs.org/docs/messages/conflicting-amp-tag`),null}else"link"===t&&"amphtml"===n.rel&&(T=!0);return e});let O=getDocumentFiles(this.context.buildManifest,this.context.__NEXT_DATA__.page,i),b=getNextFontLinkTags(g,a,h);return r.default.createElement("head",getHeadHTMLProps(this.props),this.context.isDevelopment&&r.default.createElement(r.default.Fragment,null,r.default.createElement("style",{"data-next-hide-fouc":!0,"data-ampdevmode":i?"true":void 0,dangerouslySetInnerHTML:{__html:"body{display:none}"}}),r.default.createElement("noscript",{"data-next-hide-fouc":!0,"data-ampdevmode":i?"true":void 0},r.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{display:block}"}}))),S,this.context.strictNextHead?null:r.default.createElement("meta",{name:"next-head-count",content:r.default.Children.count(S||[]).toString()}),P,m&&r.default.createElement("meta",{name:"next-font-preconnect"}),b.preconnect,b.preload,i&&r.default.createElement(r.default.Fragment,null,r.default.createElement("meta",{name:"viewport",content:"width=device-width,minimum-scale=1,initial-scale=1"}),!N&&r.default.createElement("link",{rel:"canonical",href:s+n(733).cleanAmpPath(a)}),r.default.createElement("link",{rel:"preload",as:"script",href:"https://cdn.ampproject.org/v0.js"}),r.default.createElement(AmpStyles,{styles:e}),r.default.createElement("style",{"amp-boilerplate":"",dangerouslySetInnerHTML:{__html:"body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}"}}),r.default.createElement("noscript",null,r.default.createElement("style",{"amp-boilerplate":"",dangerouslySetInnerHTML:{__html:"body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}"}})),r.default.createElement("script",{async:!0,src:"https://cdn.ampproject.org/v0.js"})),!i&&r.default.createElement(r.default.Fragment,null,!T&&o&&r.default.createElement("link",{rel:"amphtml",href:s+getAmpPath(t,a)}),this.getBeforeInteractiveInlineScripts(),!f&&this.getCssLinks(O),!f&&r.default.createElement("noscript",{"data-n-css":this.props.nonce??""}),!_&&!E&&this.getPreloadDynamicChunks(),!_&&!E&&this.getPreloadMainLinks(O),!p&&!_&&this.getPolyfillScripts(),!p&&!_&&this.getPreNextScripts(),!p&&!_&&this.getDynamicChunks(O),!p&&!_&&this.getScripts(O),f&&this.getCssLinks(O),f&&r.default.createElement("noscript",{"data-n-css":this.props.nonce??""}),this.context.isDevelopment&&r.default.createElement("noscript",{id:"__next_css__DO_NOT_USE__"}),e||null),r.default.createElement(r.default.Fragment,{},...u||[]))}};function handleDocumentScriptLoaderItems(e,t,n){var i,o,s,l;if(!n.children)return;let a=[],u=Array.isArray(n.children)?n.children:[n.children],c=null==(o=u.find(e=>e.type===Head))?void 0:null==(i=o.props)?void 0:i.children,d=null==(l=u.find(e=>"body"===e.type))?void 0:null==(s=l.props)?void 0:s.children,p=[...Array.isArray(c)?c:[c],...Array.isArray(d)?d:[d]];r.default.Children.forEach(p,t=>{var n;if(t&&(null==(n=t.type)?void 0:n.__nextScript)){if("beforeInteractive"===t.props.strategy){e.beforeInteractive=(e.beforeInteractive||[]).concat([{...t.props}]);return}if(["lazyOnload","afterInteractive","worker"].includes(t.props.strategy)){a.push(t.props);return}}}),t.scriptLoader=a}let NextScript=class NextScript extends r.default.Component{static #e=this.contextType=a.HtmlContext;getDynamicChunks(e){return getDynamicChunks(this.context,this.props,e)}getPreNextScripts(){return getPreNextScripts(this.context,this.props)}getScripts(e){return getScripts(this.context,this.props,e)}getPolyfillScripts(){return getPolyfillScripts(this.context,this.props)}static getInlineScriptSource(e){let{__NEXT_DATA__:t,largePageDataBytes:r}=e;try{let i=JSON.stringify(t);if(u.has(t.page))return(0,s.htmlEscapeJsonString)(i);let o=Buffer.from(i).byteLength,l=n(5955).Z;return r&&o>r&&(u.add(t.page),console.warn(`Warning: data for page "${t.page}"${t.page===e.dangerousAsPath?"":` (path "${e.dangerousAsPath}")`} is ${l(o)} which exceeds the threshold of ${l(r)}, this amount of data can reduce performance. -See more info here: https://nextjs.org/docs/messages/large-page-data`)),(0,s.htmlEscapeJsonString)(i)}catch(e){if((0,l.default)(e)&&-1!==e.message.indexOf("circular structure"))throw Error(`Circular structure in "getInitialProps" result of page "${t.page}". https://nextjs.org/docs/messages/circular-structure`);throw e}}render(){let{assetPrefix:e,inAmpMode:t,buildManifest:n,unstable_runtimeJS:i,docComponentsRendered:o,assetQueryString:s,disableOptimizedLoading:l,crossOrigin:a}=this.context,u=!1===i;if(o.NextScript=!0,t)return null;let c=getDocumentFiles(this.context.buildManifest,this.context.__NEXT_DATA__.page,t);return r.default.createElement(r.default.Fragment,null,!u&&n.devFiles?n.devFiles.map(t=>r.default.createElement("script",{key:t,src:`${e}/_next/${encodeURI(t)}${s}`,nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||a})):null,u?null:r.default.createElement("script",{id:"__NEXT_DATA__",type:"application/json",nonce:this.props.nonce,crossOrigin:this.props.crossOrigin||a,dangerouslySetInnerHTML:{__html:NextScript.getInlineScriptSource(this.context)}}),l&&!u&&this.getPolyfillScripts(),l&&!u&&this.getPreNextScripts(),l&&!u&&this.getDynamicChunks(c),l&&!u&&this.getScripts(c))}};function Html(e){let{inAmpMode:t,docComponentsRendered:n,locale:i,scriptLoader:o,__NEXT_DATA__:s}=(0,a.useHtmlContext)();return n.Html=!0,handleDocumentScriptLoaderItems(o,s,e),r.default.createElement("html",{...e,lang:e.lang||i||void 0,amp:t?"":void 0,"data-ampdevmode":void 0})}function Main(){let{docComponentsRendered:e}=(0,a.useHtmlContext)();return e.Main=!0,r.default.createElement("next-js-internal-body-render-target",null)}let Document=class Document extends r.default.Component{static getInitialProps(e){return e.defaultGetInitialProps(e)}render(){return r.default.createElement(Html,null,r.default.createElement(Head,null),r.default.createElement("body",null,r.default.createElement(Main,null),r.default.createElement(NextScript,null)))}};Document[i.NEXT_BUILTIN_DOCUMENT]=function(){return r.default.createElement(Html,null,r.default.createElement(Head,null),r.default.createElement("body",null,r.default.createElement(Main,null),r.default.createElement(NextScript,null)))}},4191:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{MODERN_BROWSERSLIST_TARGET:function(){return i.default},COMPILER_NAMES:function(){return o},INTERNAL_HEADERS:function(){return s},COMPILER_INDEXES:function(){return l},PHASE_EXPORT:function(){return a},PHASE_PRODUCTION_BUILD:function(){return u},PHASE_PRODUCTION_SERVER:function(){return c},PHASE_DEVELOPMENT_SERVER:function(){return d},PHASE_TEST:function(){return p},PHASE_INFO:function(){return f},PAGES_MANIFEST:function(){return m},APP_PATHS_MANIFEST:function(){return h},APP_PATH_ROUTES_MANIFEST:function(){return g},BUILD_MANIFEST:function(){return _},APP_BUILD_MANIFEST:function(){return E},FUNCTIONS_CONFIG_MANIFEST:function(){return S},SUBRESOURCE_INTEGRITY_MANIFEST:function(){return y},NEXT_FONT_MANIFEST:function(){return I},EXPORT_MARKER:function(){return P},EXPORT_DETAIL:function(){return T},PRERENDER_MANIFEST:function(){return N},ROUTES_MANIFEST:function(){return O},IMAGES_MANIFEST:function(){return b},SERVER_FILES_MANIFEST:function(){return v},DEV_CLIENT_PAGES_MANIFEST:function(){return A},MIDDLEWARE_MANIFEST:function(){return R},DEV_MIDDLEWARE_MANIFEST:function(){return x},REACT_LOADABLE_MANIFEST:function(){return M},FONT_MANIFEST:function(){return L},SERVER_DIRECTORY:function(){return C},CONFIG_FILES:function(){return D},BUILD_ID_FILE:function(){return j},BLOCKED_PAGES:function(){return F},CLIENT_PUBLIC_FILES_PATH:function(){return k},CLIENT_STATIC_FILES_PATH:function(){return w},STRING_LITERAL_DROP_BUNDLE:function(){return U},NEXT_BUILTIN_DOCUMENT:function(){return H},BARREL_OPTIMIZATION_PREFIX:function(){return B},CLIENT_REFERENCE_MANIFEST:function(){return $},SERVER_REFERENCE_MANIFEST:function(){return W},MIDDLEWARE_BUILD_MANIFEST:function(){return z},MIDDLEWARE_REACT_LOADABLE_MANIFEST:function(){return G},CLIENT_STATIC_FILES_RUNTIME_MAIN:function(){return Y},CLIENT_STATIC_FILES_RUNTIME_MAIN_APP:function(){return X},APP_CLIENT_INTERNALS:function(){return V},CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH:function(){return q},CLIENT_STATIC_FILES_RUNTIME_AMP:function(){return J},CLIENT_STATIC_FILES_RUNTIME_WEBPACK:function(){return K},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS:function(){return Z},CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL:function(){return Q},EDGE_RUNTIME_WEBPACK:function(){return ee},TEMPORARY_REDIRECT_STATUS:function(){return et},PERMANENT_REDIRECT_STATUS:function(){return en},STATIC_PROPS_ID:function(){return er},SERVER_PROPS_ID:function(){return ei},PAGE_SEGMENT_KEY:function(){return eo},GOOGLE_FONT_PROVIDER:function(){return es},OPTIMIZED_FONT_PROVIDERS:function(){return el},DEFAULT_SERIF_FONT:function(){return ea},DEFAULT_SANS_SERIF_FONT:function(){return eu},STATIC_STATUS_PAGES:function(){return ec},TRACE_OUTPUT_VERSION:function(){return ed},TURBO_TRACE_DEFAULT_MEMORY_LIMIT:function(){return ep},RSC_MODULE_TYPES:function(){return ef},EDGE_UNSUPPORTED_NODE_APIS:function(){return em},SYSTEM_ENTRYPOINTS:function(){return eh}});let r=n(167),i=r._(n(7708)),o={client:"client",server:"server",edgeServer:"edge-server"},s=["x-invoke-path","x-invoke-status","x-invoke-error","x-invoke-query","x-middleware-invoke"],l={[o.client]:0,[o.server]:1,[o.edgeServer]:2},a="phase-export",u="phase-production-build",c="phase-production-server",d="phase-development-server",p="phase-test",f="phase-info",m="pages-manifest.json",h="app-paths-manifest.json",g="app-path-routes-manifest.json",_="build-manifest.json",E="app-build-manifest.json",S="functions-config-manifest.json",y="subresource-integrity-manifest",I="next-font-manifest",P="export-marker.json",T="export-detail.json",N="prerender-manifest.json",O="routes-manifest.json",b="images-manifest.json",v="required-server-files.json",A="_devPagesManifest.json",R="middleware-manifest.json",x="_devMiddlewareManifest.json",M="react-loadable-manifest.json",L="font-manifest.json",C="server",D=["next.config.js","next.config.mjs"],j="BUILD_ID",F=["/_document","/_app","/_error"],k="public",w="static",U="__NEXT_DROP_CLIENT_FILE__",H="__NEXT_BUILTIN_DOCUMENT__",B="__barrel_optimize__",$="client-reference-manifest",W="server-reference-manifest",z="middleware-build-manifest",G="middleware-react-loadable-manifest",Y="main",X=""+Y+"-app",V="app-pages-internals",q="react-refresh",J="amp",K="webpack",Z="polyfills",Q=Symbol(Z),ee="edge-runtime-webpack",et=307,en=308,er="__N_SSG",ei="__N_SSP",eo="__PAGE__",es="https://fonts.googleapis.com/",el=[{url:es,preconnect:"https://fonts.gstatic.com"},{url:"https://use.typekit.net",preconnect:"https://use.typekit.net"}],ea={name:"Times New Roman",xAvgCharWidth:821,azAvgWidth:854.3953488372093,unitsPerEm:2048},eu={name:"Arial",xAvgCharWidth:904,azAvgWidth:934.5116279069767,unitsPerEm:2048},ec=["/500"],ed=1,ep=6e3,ef={client:"client",server:"server"},em=["clearImmediate","setImmediate","BroadcastChannel","ByteLengthQueuingStrategy","CompressionStream","CountQueuingStrategy","DecompressionStream","DomException","MessageChannel","MessageEvent","MessagePort","ReadableByteStreamController","ReadableStreamBYOBRequest","ReadableStreamDefaultController","TransformStreamDefaultController","WritableStreamDefaultController"],eh=new Set([Y,q,J,X]);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},972:(e,t)=>{function getObjectClassLabel(e){return Object.prototype.toString.call(e)}function isPlainObject(e){if("[object Object]"!==getObjectClassLabel(e))return!1;let t=Object.getPrototypeOf(e);return null===t||t.hasOwnProperty("isPrototypeOf")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getObjectClassLabel:function(){return getObjectClassLabel},isPlainObject:function(){return isPlainObject}})},7708:e=>{e.exports=["chrome 64","edge 79","firefox 67","opera 51","safari 12"]},64:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"denormalizePagePath",{enumerable:!0,get:function(){return denormalizePagePath}});let r=n(4676),i=n(9267);function denormalizePagePath(e){let t=(0,i.normalizePathSep)(e);return t.startsWith("/index/")&&!(0,r.isDynamicRoute)(t)?t.slice(6):"/index"!==t?t:"/"}},9341:(e,t)=>{function ensureLeadingSlash(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return ensureLeadingSlash}})},7072:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePagePath",{enumerable:!0,get:function(){return normalizePagePath}});let r=n(9341),i=n(4676),o=n(7921);function normalizePagePath(e){let t=/^\/index(\/|$)/.test(e)&&!(0,i.isDynamicRoute)(e)?"/index"+e:"/"===e?"/index":(0,r.ensureLeadingSlash)(e);{let{posix:e}=n(1017),r=e.normalize(t);if(r!==t)throw new o.NormalizeError("Requested and resolved page mismatch: "+t+" "+r)}return t}},9267:(e,t)=>{function normalizePathSep(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return normalizePathSep}})},4676:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{getSortedRoutes:function(){return r.getSortedRoutes},isDynamicRoute:function(){return i.isDynamicRoute}});let r=n(5651),i=n(3489)},3489:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isDynamicRoute",{enumerable:!0,get:function(){return isDynamicRoute}});let n=/\/\[[^/]+?\](?=\/|$)/;function isDynamicRoute(e){return n.test(e)}},5651:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSortedRoutes",{enumerable:!0,get:function(){return getSortedRoutes}});let UrlNode=class UrlNode{insert(e){this._insert(e.split("/").filter(Boolean),[],!1)}smoosh(){return this._smoosh()}_smoosh(e){void 0===e&&(e="/");let t=[...this.children.keys()].sort();null!==this.slugName&&t.splice(t.indexOf("[]"),1),null!==this.restSlugName&&t.splice(t.indexOf("[...]"),1),null!==this.optionalRestSlugName&&t.splice(t.indexOf("[[...]]"),1);let n=t.map(t=>this.children.get(t)._smoosh(""+e+t+"/")).reduce((e,t)=>[...e,...t],[]);if(null!==this.slugName&&n.push(...this.children.get("[]")._smoosh(e+"["+this.slugName+"]/")),!this.placeholder){let t="/"===e?"/":e.slice(0,-1);if(null!=this.optionalRestSlugName)throw Error('You cannot define a route with the same specificity as a optional catch-all route ("'+t+'" and "'+t+"[[..."+this.optionalRestSlugName+']]").');n.unshift(t)}return null!==this.restSlugName&&n.push(...this.children.get("[...]")._smoosh(e+"[..."+this.restSlugName+"]/")),null!==this.optionalRestSlugName&&n.push(...this.children.get("[[...]]")._smoosh(e+"[[..."+this.optionalRestSlugName+"]]/")),n}_insert(e,t,n){if(0===e.length){this.placeholder=!1;return}if(n)throw Error("Catch-all must be the last part of the URL.");let r=e[0];if(r.startsWith("[")&&r.endsWith("]")){let i=r.slice(1,-1),o=!1;if(i.startsWith("[")&&i.endsWith("]")&&(i=i.slice(1,-1),o=!0),i.startsWith("...")&&(i=i.substring(3),n=!0),i.startsWith("[")||i.endsWith("]"))throw Error("Segment names may not start or end with extra brackets ('"+i+"').");if(i.startsWith("."))throw Error("Segment names may not start with erroneous periods ('"+i+"').");function handleSlug(e,n){if(null!==e&&e!==n)throw Error("You cannot use different slug names for the same dynamic path ('"+e+"' !== '"+n+"').");t.forEach(e=>{if(e===n)throw Error('You cannot have the same slug name "'+n+'" repeat within a single dynamic path');if(e.replace(/\W/g,"")===r.replace(/\W/g,""))throw Error('You cannot have the slug names "'+e+'" and "'+n+'" differ only by non-word symbols within a single dynamic path')}),t.push(n)}if(n){if(o){if(null!=this.restSlugName)throw Error('You cannot use both an required and optional catch-all route at the same level ("[...'+this.restSlugName+']" and "'+e[0]+'" ).');handleSlug(this.optionalRestSlugName,i),this.optionalRestSlugName=i,r="[[...]]"}else{if(null!=this.optionalRestSlugName)throw Error('You cannot use both an optional and required catch-all route at the same level ("[[...'+this.optionalRestSlugName+']]" and "'+e[0]+'").');handleSlug(this.restSlugName,i),this.restSlugName=i,r="[...]"}}else{if(o)throw Error('Optional route parameters are not yet supported ("'+e[0]+'").');handleSlug(this.slugName,i),this.slugName=i,r="[]"}}this.children.has(r)||this.children.set(r,new UrlNode),this.children.get(r)._insert(e.slice(1),t,n)}constructor(){this.placeholder=!0,this.children=new Map,this.slugName=null,this.restSlugName=null,this.optionalRestSlugName=null}};function getSortedRoutes(e){let t=new UrlNode;return e.forEach(e=>t.insert(e)),t.smoosh()}},676:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{default:function(){return isError},getProperError:function(){return getProperError}});let r=n(972);function isError(e){return"object"==typeof e&&null!==e&&"name"in e&&"message"in e}function getProperError(e){return isError(e)?e:Error((0,r.isPlainObject)(e)?JSON.stringify(e):e+"")}},5955:(e,t)=>{Object.defineProperty(t,"Z",{enumerable:!0,get:function(){return prettyBytes}});let n=["B","kB","MB","GB","TB","PB","EB","ZB","YB"],toLocaleString=(e,t)=>{let n=e;return"string"==typeof t?n=e.toLocaleString(t):!0===t&&(n=e.toLocaleString()),n};function prettyBytes(e,t){if(!Number.isFinite(e))throw TypeError(`Expected a finite number, got ${typeof e}: ${e}`);if((t=Object.assign({},t)).signed&&0===e)return" 0 B";let r=e<0,i=r?"-":t.signed?"+":"";if(r&&(e=-e),e<1){let n=toLocaleString(e,t.locale);return i+n+" B"}let o=Math.min(Math.floor(Math.log10(e)/3),n.length-1);e=Number((e/Math.pow(1e3,o)).toPrecision(3));let s=toLocaleString(e,t.locale),l=n[o];return i+s+" "+l}},7093:(e,t,n)=>{e.exports=n(2785)},3112:(e,t,n)=>{e.exports=n(7093).vendored.contexts.HtmlContext},5778:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getPageFiles",{enumerable:!0,get:function(){return getPageFiles}});let r=n(64),i=n(7072);function getPageFiles(e,t){let n=(0,r.denormalizePagePath)((0,i.normalizePagePath)(t));return e.pages[n]||(console.warn(`Could not find files for ${n} in .next/build-manifest.json`),[])}},9630:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{ESCAPE_REGEX:function(){return r},htmlEscapeJsonString:function(){return htmlEscapeJsonString}});let n={"&":"\\u0026",">":"\\u003e","<":"\\u003c","\u2028":"\\u2028","\u2029":"\\u2029"},r=/[&><\u2028\u2029]/g;function htmlEscapeJsonString(e){return e.replace(r,e=>n[e])}},733:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{isBlockedPage:function(){return isBlockedPage},cleanAmpPath:function(){return cleanAmpPath},debounce:function(){return debounce}});let r=n(4191);function isBlockedPage(e){return r.BLOCKED_PAGES.includes(e)}function cleanAmpPath(e){return e.match(/\?amp=(y|yes|true|1)/)&&(e=e.replace(/\?amp=(y|yes|true|1)&?/,"?")),e.match(/&=(y|yes|true|1)/)&&(e=e.replace(/&=(y|yes|true|1)/,"")),e=e.replace(/\?$/,"")}function debounce(e,t,n=1/0){let r,i,o;let s=0,l=0;function run(){let a=Date.now(),u=l+t-a;u<=0||s+n>=a?(r=void 0,e.apply(o,i)):r=setTimeout(run,u)}return function(...e){i=e,o=this,l=Date.now(),void 0===r&&(s=l,r=setTimeout(run,t))}}}}; \ No newline at end of file diff --git a/.next/server/chunks/837.js b/.next/server/chunks/837.js deleted file mode 100644 index ed48f14..0000000 --- a/.next/server/chunks/837.js +++ /dev/null @@ -1 +0,0 @@ -exports.id=837,exports.ids=[837],exports.modules={6686:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Image",{enumerable:!0,get:function(){return m}});let n=r(85),i=r(8425),o=i._(r(9885)),a=n._(r(8908)),l=n._(r(6420)),s=r(5161),u=r(1412),d=r(7927);r(8601);let c=r(713),f=n._(r(8320)),p={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1};function handleLoading(e,t,r,n,i,o){let a=null==e?void 0:e.src;if(!e||e["data-loaded-src"]===a)return;e["data-loaded-src"]=a;let l="decode"in e?e.decode():Promise.resolve();l.catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&i(!0),null==r?void 0:r.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let n=!1,i=!1;r.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>n,isPropagationStopped:()=>i,persist:()=>{},preventDefault:()=>{n=!0,t.preventDefault()},stopPropagation:()=>{i=!0,t.stopPropagation()}})}(null==n?void 0:n.current)&&n.current(e)}})}function getDynamicProps(e){let[t,r]=o.version.split(".",2),n=parseInt(t,10),i=parseInt(r,10);return n>18||18===n&&i>=3?{fetchPriority:e}:{fetchpriority:e}}globalThis.__NEXT_IMAGE_IMPORTED=!0;let g=(0,o.forwardRef)((e,t)=>{let{src:r,srcSet:n,sizes:i,height:a,width:l,decoding:s,className:u,style:d,fetchPriority:c,placeholder:f,loading:p,unoptimized:g,fill:m,onLoadRef:h,onLoadingCompleteRef:y,setBlurComplete:v,setShowAltText:b,onLoad:_,onError:S,...w}=e;return o.default.createElement("img",{...w,...getDynamicProps(c),loading:p,width:l,height:a,decoding:s,"data-nimg":m?"fill":"1",className:u,style:d,sizes:i,srcSet:n,src:r,ref:(0,o.useCallback)(e=>{t&&("function"==typeof t?t(e):"object"==typeof t&&(t.current=e)),e&&(S&&(e.src=e.src),e.complete&&handleLoading(e,f,h,y,v,g))},[r,f,h,y,v,S,g,t]),onLoad:e=>{let t=e.currentTarget;handleLoading(t,f,h,y,v,g)},onError:e=>{b(!0),"empty"!==f&&v(!0),S&&S(e)}})});function ImagePreload(e){let{isAppRouter:t,imgAttributes:r}=e,n={as:"image",imageSrcSet:r.srcSet,imageSizes:r.sizes,crossOrigin:r.crossOrigin,referrerPolicy:r.referrerPolicy,...getDynamicProps(r.fetchPriority)};return t&&a.default.preload?(a.default.preload(r.src,n),null):o.default.createElement(l.default,null,o.default.createElement("link",{key:"__nimg-"+r.src+r.srcSet+r.sizes,rel:"preload",href:r.srcSet?void 0:r.src,...n}))}let m=(0,o.forwardRef)((e,t)=>{let r=(0,o.useContext)(c.RouterContext),n=(0,o.useContext)(d.ImageConfigContext),i=(0,o.useMemo)(()=>{let e=p||n||u.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),r=e.deviceSizes.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:r}},[n]),{onLoad:a,onLoadingComplete:l}=e,m=(0,o.useRef)(a);(0,o.useEffect)(()=>{m.current=a},[a]);let h=(0,o.useRef)(l);(0,o.useEffect)(()=>{h.current=l},[l]);let[y,v]=(0,o.useState)(!1),[b,_]=(0,o.useState)(!1),{props:S,meta:w}=(0,s.getImgProps)(e,{defaultLoader:f.default,imgConf:i,blurComplete:y,showAltText:b});return o.default.createElement(o.default.Fragment,null,o.default.createElement(g,{...S,unoptimized:w.unoptimized,placeholder:w.placeholder,fill:w.fill,onLoadRef:m,onLoadingCompleteRef:h,setBlurComplete:v,setShowAltText:_,ref:t}),w.priority?o.default.createElement(ImagePreload,{isAppRouter:!r,imgAttributes:S}):null)});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1281:(e,t)=>{"use strict";function isInAmpMode(e){let{ampFirst:t=!1,hybrid:r=!1,hasQuery:n=!1}=void 0===e?{}:e;return t||r&&n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return isInAmpMode}})},5161:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImgProps",{enumerable:!0,get:function(){return getImgProps}}),r(8601);let n=r(2490),i=r(1412);function isStaticRequire(e){return void 0!==e.default}function isStaticImageData(e){return void 0!==e.src}function isStaticImport(e){return"object"==typeof e&&(isStaticRequire(e)||isStaticImageData(e))}function getInt(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function getWidths(e,t,r){let{deviceSizes:n,allSizes:i}=e;if(r){let e=/(^|\s)(1?\d?\d)vw/g,t=[];for(let n;n=e.exec(r);n)t.push(parseInt(n[2]));if(t.length){let e=.01*Math.min(...t);return{widths:i.filter(t=>t>=n[0]*e),kind:"w"}}return{widths:i,kind:"w"}}if("number"!=typeof t)return{widths:n,kind:"w"};let o=[...new Set([t,2*t].map(e=>i.find(t=>t>=e)||i[i.length-1]))];return{widths:o,kind:"x"}}function generateImgAttrs(e){let{config:t,src:r,unoptimized:n,width:i,quality:o,sizes:a,loader:l}=e;if(n)return{src:r,srcSet:void 0,sizes:void 0};let{widths:s,kind:u}=getWidths(t,i,a),d=s.length-1;return{sizes:a||"w"!==u?a:"100vw",srcSet:s.map((e,n)=>l({config:t,src:r,quality:o,width:e})+" "+("w"===u?e:n+1)+u).join(", "),src:l({config:t,src:r,quality:o,width:s[d]})}}function getImgProps(e,t){let r,o,a,{src:l,sizes:s,unoptimized:u=!1,priority:d=!1,loading:c,className:f,quality:p,width:g,height:m,fill:h=!1,style:y,onLoad:v,onLoadingComplete:b,placeholder:_="empty",blurDataURL:S,fetchPriority:w,layout:C,objectFit:x,objectPosition:P,lazyBoundary:I,lazyRoot:E,...O}=e,{imgConf:j,showAltText:M,blurComplete:z,defaultLoader:R}=t,A=j||i.imageConfigDefault;if("allSizes"in A)r=A;else{let e=[...A.deviceSizes,...A.imageSizes].sort((e,t)=>e-t),t=A.deviceSizes.sort((e,t)=>e-t);r={...A,allSizes:e,deviceSizes:t}}let k=O.loader||R;delete O.loader,delete O.srcSet;let D="__next_img_default"in k;if(D){if("custom"===r.loader)throw Error('Image with src "'+l+'" is missing "loader" prop.\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader')}else{let e=k;k=t=>{let{config:r,...n}=t;return e(n)}}if(C){"fill"===C&&(h=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[C];e&&(y={...y,...e});let t={responsive:"100vw",fill:"100vw"}[C];t&&!s&&(s=t)}let L="",U=getInt(g),B=getInt(m);if(isStaticImport(l)){let e=isStaticRequire(l)?l.default:l;if(!e.src)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "+JSON.stringify(e));if(!e.height||!e.width)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received "+JSON.stringify(e));if(o=e.blurWidth,a=e.blurHeight,S=S||e.blurDataURL,L=e.src,!h){if(U||B){if(U&&!B){let t=U/e.width;B=Math.round(e.height*t)}else if(!U&&B){let t=B/e.height;U=Math.round(e.width*t)}}else U=e.width,B=e.height}}let H=!d&&("lazy"===c||void 0===c);(!(l="string"==typeof l?l:L)||l.startsWith("data:")||l.startsWith("blob:"))&&(u=!0,H=!1),r.unoptimized&&(u=!0),D&&l.endsWith(".svg")&&!r.dangerouslyAllowSVG&&(u=!0),d&&(w="high");let T=getInt(p),G=Object.assign(h?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:x,objectPosition:P}:{},M?{}:{color:"transparent"},y),N=z||"empty"===_?null:"blur"===_?'url("data:image/svg+xml;charset=utf-8,'+(0,n.getImageBlurSvg)({widthInt:U,heightInt:B,blurWidth:o,blurHeight:a,blurDataURL:S||"",objectFit:G.objectFit})+'")':'url("'+_+'")',W=N?{backgroundSize:G.objectFit||"cover",backgroundPosition:G.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:N}:{},q=generateImgAttrs({config:r,src:l,unoptimized:u,width:U,quality:T,sizes:s,loader:k}),F={...O,loading:H?"lazy":c,fetchPriority:w,width:U,height:B,decoding:"async",className:f,style:{...G,...W},sizes:q.sizes,srcSet:q.srcSet,src:q.src},V={unoptimized:u,priority:d,placeholder:_,fill:h};return{props:F,meta:V}}},6420:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{defaultHead:function(){return defaultHead},default:function(){return c}});let n=r(85),i=r(8425),o=i._(r(9885)),a=n._(r(4005)),l=r(8364),s=r(5851),u=r(1281);function defaultHead(e){void 0===e&&(e=!1);let t=[o.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(o.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function onlyReactElement(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}r(8601);let d=["name","httpEquiv","charSet","itemProp"];function unique(){let e=new Set,t=new Set,r=new Set,n={};return i=>{let o=!0,a=!1;if(i.key&&"number"!=typeof i.key&&i.key.indexOf("$")>0){a=!0;let t=i.key.slice(i.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(i.type){case"title":case"base":t.has(i.type)?o=!1:t.add(i.type);break;case"meta":for(let e=0,t=d.length;e{let n=e.key||t;if(!r&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,o.default.cloneElement(e,t)}return o.default.cloneElement(e,{key:n})})}function Head(e){let{children:t}=e,r=(0,o.useContext)(l.AmpStateContext),n=(0,o.useContext)(s.HeadManagerContext);return o.default.createElement(a.default,{reduceComponentsToState:reduceComponents,headManager:n,inAmpMode:(0,u.isInAmpMode)(r)},t)}let c=Head;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2490:(e,t)=>{"use strict";function getImageBlurSvg(e){let{widthInt:t,heightInt:r,blurWidth:n,blurHeight:i,blurDataURL:o,objectFit:a}=e,l=n?40*n:t,s=i?40*i:r,u=l&&s?"viewBox='0 0 "+l+" "+s+"'":"";return"%3Csvg xmlns='http://www.w3.org/2000/svg' "+u+"%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='"+(u?"none":"contain"===a?"xMidYMid":"cover"===a?"xMidYMid slice":"none")+"' style='filter: url(%23b);' href='"+o+"'/%3E%3C/svg%3E"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImageBlurSvg",{enumerable:!0,get:function(){return getImageBlurSvg}})},1412:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{VALID_LOADERS:function(){return r},imageConfigDefault:function(){return n}});let r=["default","imgix","cloudinary","akamai","custom"],n={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},7990:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{unstable_getImgProps:function(){return unstable_getImgProps},default:function(){return s}});let n=r(85),i=r(5161),o=r(8601),a=r(6686),l=n._(r(8320)),unstable_getImgProps=e=>{(0,o.warnOnce)("Warning: unstable_getImgProps() is experimental and may change or be removed at any time. Use at your own risk.");let{props:t}=(0,i.getImgProps)(e,{defaultLoader:l.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}});for(let[e,r]of Object.entries(t))void 0===r&&delete t[e];return{props:t}},s=a.Image},8320:(e,t)=>{"use strict";function defaultLoader(e){let{config:t,src:r,width:n,quality:i}=e;return t.path+"?url="+encodeURIComponent(r)+"&w="+n+"&q="+(i||75)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r}}),defaultLoader.__next_img_default=!0;let r=defaultLoader},4005:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return SideEffect}});let n=r(9885),useClientOnlyLayoutEffect=()=>{},useClientOnlyEffect=()=>{};function SideEffect(e){var t;let{headManager:r,reduceComponentsToState:i}=e;function emitChange(){if(r&&r.mountedInstances){let t=n.Children.toArray(Array.from(r.mountedInstances).filter(Boolean));r.updateHead(i(t,e))}}return null==r||null==(t=r.mountedInstances)||t.add(e.children),emitChange(),useClientOnlyLayoutEffect(()=>{var t;return null==r||null==(t=r.mountedInstances)||t.add(e.children),()=>{var t;null==r||null==(t=r.mountedInstances)||t.delete(e.children)}}),useClientOnlyLayoutEffect(()=>(r&&(r._pendingUpdate=emitChange),()=>{r&&(r._pendingUpdate=emitChange)})),useClientOnlyEffect(()=>(r&&r._pendingUpdate&&(r._pendingUpdate(),r._pendingUpdate=null),()=>{r&&r._pendingUpdate&&(r._pendingUpdate(),r._pendingUpdate=null)})),null}},8601:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return warnOnce}});let warnOnce=e=>{}},8364:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.AmpContext},5851:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.HeadManagerContext},7927:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.ImageConfigContext},713:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.RouterContext},784:(e,t,r)=>{"use strict";e.exports=r(316).vendored["react-ssr"].ReactJsxRuntime},2451:(e,t,r)=>{e.exports=r(7990)}}; \ No newline at end of file diff --git a/.next/server/chunks/840.js b/.next/server/chunks/840.js deleted file mode 100644 index b33fb27..0000000 --- a/.next/server/chunks/840.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";exports.id=840,exports.ids=[840],exports.modules={2840:(e,t,p)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return App}});let l=p(167),a=l._(p(6689)),o=p(7921);async function appGetInitialProps(e){let{Component:t,ctx:p}=e,l=await (0,o.loadGetInitialProps)(t,p);return{pageProps:l}}let App=class App extends a.default.Component{render(){let{Component:e,pageProps:t}=this.props;return a.default.createElement(e,t)}};App.origGetInitialProps=appGetInitialProps,App.getInitialProps=appGetInitialProps,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}}; \ No newline at end of file diff --git a/.next/server/chunks/862.js b/.next/server/chunks/862.js deleted file mode 100644 index 3dfc942..0000000 --- a/.next/server/chunks/862.js +++ /dev/null @@ -1 +0,0 @@ -exports.id=862,exports.ids=[862],exports.modules={2999:e=>{e.exports={style:{fontFamily:"'__Inter_e66fe9', '__Inter_Fallback_e66fe9'",fontStyle:"normal"},className:"__className_e66fe9"}},6879:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return addBasePath}});let n=r(8549),a=r(6945);function addBasePath(e,t){return(0,a.normalizePathTrailingSlash)((0,n.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5422:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"callServer",{enumerable:!0,get:function(){return callServer}});let n=r(3724);async function callServer(e,t){let r=(0,n.getServerActionDispatcher)();if(!r)throw Error("Invariant: missing action dispatcher.");return new Promise((n,a)=>{r({actionId:e,actionArgs:t,resolve:n,reject:a})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3204:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AppRouterAnnouncer",{enumerable:!0,get:function(){return AppRouterAnnouncer}});let n=r(9885),a=r(8908),o="next-route-announcer";function getAnnouncerNode(){var e;let t=document.getElementsByName(o)[0];if(null==t?void 0:null==(e=t.shadowRoot)?void 0:e.childNodes[0])return t.shadowRoot.childNodes[0];{let e=document.createElement(o);e.style.cssText="position:absolute";let t=document.createElement("div");t.ariaLive="assertive",t.id="__next-route-announcer__",t.role="alert",t.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal";let r=e.attachShadow({mode:"open"});return r.appendChild(t),document.body.appendChild(e),t}}function AppRouterAnnouncer(e){let{tree:t}=e,[r,l]=(0,n.useState)(null);(0,n.useEffect)(()=>{let e=getAnnouncerNode();return l(e),()=>{let e=document.getElementsByTagName(o)[0];(null==e?void 0:e.isConnected)&&document.body.removeChild(e)}},[]);let[u,i]=(0,n.useState)(""),s=(0,n.useRef)();return(0,n.useEffect)(()=>{let e="";if(document.title)e=document.title;else{let t=document.querySelector("h1");t&&(e=t.innerText||t.textContent||"")}void 0!==s.current&&s.current!==e&&i(e),s.current=e},[t]),r?(0,a.createPortal)(u,r):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4361:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RSC:function(){return r},ACTION:function(){return n},NEXT_ROUTER_STATE_TREE:function(){return a},NEXT_ROUTER_PREFETCH:function(){return o},NEXT_URL:function(){return l},RSC_CONTENT_TYPE_HEADER:function(){return u},RSC_VARY_HEADER:function(){return i},FLIGHT_PARAMETERS:function(){return s},NEXT_RSC_UNION_QUERY:function(){return c}});let r="RSC",n="Next-Action",a="Next-Router-State-Tree",o="Next-Router-Prefetch",l="Next-Url",u="text/x-component",i=r+", "+a+", "+o+", "+l,s=[[r],[a],[o]],c="_rsc";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3724:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getServerActionDispatcher:function(){return getServerActionDispatcher},urlToUrlWithoutFlightMarker:function(){return urlToUrlWithoutFlightMarker},default:function(){return AppRouter}});let n=r(8425),a=n._(r(9885)),o=r(2428),l=r(7986),u=r(3678),i=r(1706),s=r(1736),c=r(9236),d=r(5365),f=r(9624),p=r(4692),h=r(6879),_=r(3204),y=r(7502),m=r(2226),g=r(9880),b=r(4361),v=r(4978),P=r(9760),R=null,S=null;function getServerActionDispatcher(){return S}let E={refresh:()=>{}};function urlToUrlWithoutFlightMarker(e){let t=new URL(e,location.origin);return t.searchParams.delete(b.NEXT_RSC_UNION_QUERY),t}function isExternalURL(e){return e.origin!==window.location.origin}function HistoryUpdater(e){let{tree:t,pushRef:r,canonicalUrl:n,sync:o}=e;return(0,a.useInsertionEffect)(()=>{let e={__NA:!0,tree:t};r.pendingPush&&(0,i.createHrefFromUrl)(new URL(window.location.href))!==n?(r.pendingPush=!1,window.history.pushState(e,"",n)):window.history.replaceState(e,"",n),o()},[t,r,n,o]),null}let createEmptyCacheNode=()=>({status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map});function useServerActionDispatcher(e){let t=(0,a.useCallback)(t=>{(0,a.startTransition)(()=>{e({...t,type:u.ACTION_SERVER_ACTION,mutable:{globalMutable:E},cache:createEmptyCacheNode()})})},[e]);S=t}function useChangeByServerResponse(e){return(0,a.useCallback)((t,r,n)=>{(0,a.startTransition)(()=>{e({type:u.ACTION_SERVER_PATCH,flightData:r,previousTree:t,overrideCanonicalUrl:n,cache:createEmptyCacheNode(),mutable:{globalMutable:E}})})},[e])}function useNavigate(e){return(0,a.useCallback)((t,r,n,a)=>{let o=new URL((0,h.addBasePath)(t),location.href);return E.pendingNavigatePath=(0,i.createHrefFromUrl)(o),e({type:u.ACTION_NAVIGATE,url:o,isExternalUrl:isExternalURL(o),locationSearch:location.search,forceOptimisticNavigation:n,shouldScroll:null==a||a,navigateType:r,cache:createEmptyCacheNode(),mutable:{globalMutable:E}})},[e])}function Router(e){let{buildId:t,initialHead:r,initialTree:n,initialCanonicalUrl:i,children:d,assetPrefix:b}=e,S=(0,a.useMemo)(()=>(0,f.createInitialRouterState)({buildId:t,children:d,initialCanonicalUrl:i,initialTree:n,initialParallelRoutes:R,isServer:!0,location:null,initialHead:r}),[t,d,i,n,r]),[{tree:O,cache:T,prefetchCache:j,pushRef:M,focusAndScrollRef:x,canonicalUrl:A,nextUrl:C},N,w]=(0,c.useReducerWithReduxDevtools)(l.reducer,S);(0,a.useEffect)(()=>{R=null},[]);let{searchParams:I,pathname:F}=(0,a.useMemo)(()=>{let e=new URL(A,"http://n");return{searchParams:e.searchParams,pathname:(0,P.hasBasePath)(e.pathname)?(0,v.removeBasePath)(e.pathname):e.pathname}},[A]),D=useChangeByServerResponse(N),L=useNavigate(N);useServerActionDispatcher(N);let U=(0,a.useMemo)(()=>{let e={back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(e,t)=>{if((0,p.isBot)(window.navigator.userAgent))return;let r=new URL((0,h.addBasePath)(e),location.href);isExternalURL(r)||(0,a.startTransition)(()=>{var e;N({type:u.ACTION_PREFETCH,url:r,kind:null!=(e=null==t?void 0:t.kind)?e:u.PrefetchKind.FULL})})},replace:(e,t)=>{void 0===t&&(t={}),(0,a.startTransition)(()=>{var r;L(e,"replace",!!t.forceOptimisticNavigation,null==(r=t.scroll)||r)})},push:(e,t)=>{void 0===t&&(t={}),(0,a.startTransition)(()=>{var r;L(e,"push",!!t.forceOptimisticNavigation,null==(r=t.scroll)||r)})},refresh:()=>{(0,a.startTransition)(()=>{N({type:u.ACTION_REFRESH,cache:createEmptyCacheNode(),mutable:{globalMutable:E},origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}};return e},[N,L]);if((0,a.useEffect)(()=>{window.next&&(window.next.router=U)},[U]),(0,a.useEffect)(()=>{E.refresh=U.refresh},[U.refresh]),(0,a.useEffect)(()=>{function handlePageShow(e){var t;e.persisted&&(null==(t=window.history.state)?void 0:t.tree)&&N({type:u.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.tree})}return window.addEventListener("pageshow",handlePageShow),()=>{window.removeEventListener("pageshow",handlePageShow)}},[N]),M.mpaNavigation){if(E.pendingMpaPath!==A){let e=window.location;M.pendingPush?e.assign(A):e.replace(A),E.pendingMpaPath=A}(0,a.use)((0,g.createInfinitePromise)())}let H=(0,a.useCallback)(e=>{let{state:t}=e;if(t){if(!t.__NA){window.location.reload();return}(0,a.startTransition)(()=>{N({type:u.ACTION_RESTORE,url:new URL(window.location.href),tree:t.tree})})}},[N]);(0,a.useEffect)(()=>(window.addEventListener("popstate",H),()=>{window.removeEventListener("popstate",H)}),[H]);let B=(0,a.useMemo)(()=>(0,m.findHeadInCache)(T,O[1]),[T,O]),k=a.default.createElement(y.RedirectBoundary,null,B,T.subTreeData,a.default.createElement(_.AppRouterAnnouncer,{tree:O}));return a.default.createElement(a.default.Fragment,null,a.default.createElement(HistoryUpdater,{tree:O,pushRef:M,canonicalUrl:A,sync:w}),a.default.createElement(s.PathnameContext.Provider,{value:F},a.default.createElement(s.SearchParamsContext.Provider,{value:I},a.default.createElement(o.GlobalLayoutRouterContext.Provider,{value:{buildId:t,changeByServerResponse:D,tree:O,focusAndScrollRef:x,nextUrl:C}},a.default.createElement(o.AppRouterContext.Provider,{value:U},a.default.createElement(o.LayoutRouterContext.Provider,{value:{childNodes:T.parallelRoutes,tree:O,url:A}},k))))))}function AppRouter(e){let{globalErrorComponent:t,...r}=e;return a.default.createElement(d.ErrorBoundary,{errorComponent:t},a.default.createElement(Router,r))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4954:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"bailoutToClientRendering",{enumerable:!0,get:function(){return bailoutToClientRendering}});let n=r(1118),a=r(4749);function bailoutToClientRendering(){let e=a.staticGenerationAsyncStorage.getStore();return null!=e&&!!e.forceStatic||((null==e?void 0:e.isStaticGeneration)&&(0,n.throwWithNoSSR)(),!1)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3402:(e,t,r)=>{"use strict";function clientHookInServerComponentError(e){}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"clientHookInServerComponentError",{enumerable:!0,get:function(){return clientHookInServerComponentError}}),r(85),r(9885),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5365:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ErrorBoundaryHandler:function(){return ErrorBoundaryHandler},GlobalError:function(){return GlobalError},default:function(){return u},ErrorBoundary:function(){return ErrorBoundary}});let n=r(85),a=n._(r(9885)),o=r(4979),l={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function HandleISRError(e){let{error:t}=e;if("function"==typeof fetch.__nextGetStaticStore){var r;let e=null==(r=fetch.__nextGetStaticStore())?void 0:r.getStore();if((null==e?void 0:e.isRevalidate)||(null==e?void 0:e.isStaticGeneration))throw console.error(t),t}return null}let ErrorBoundaryHandler=class ErrorBoundaryHandler extends a.default.Component{static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.error?{error:null,previousPathname:e.pathname}:{error:t.error,previousPathname:e.pathname}}render(){return this.state.error?a.default.createElement(a.default.Fragment,null,a.default.createElement(HandleISRError,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,a.default.createElement(this.props.errorComponent,{error:this.state.error,reset:this.reset})):this.props.children}constructor(e){super(e),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}};function GlobalError(e){let{error:t}=e,r=null==t?void 0:t.digest;return a.default.createElement("html",{id:"__next_error__"},a.default.createElement("head",null),a.default.createElement("body",null,a.default.createElement(HandleISRError,{error:t}),a.default.createElement("div",{style:l.error},a.default.createElement("div",null,a.default.createElement("h2",{style:l.text},"Application error: a "+(r?"server":"client")+"-side exception has occurred (see the "+(r?"server logs":"browser console")+" for more information)."),r?a.default.createElement("p",{style:l.text},"Digest: "+r):null))))}let u=GlobalError;function ErrorBoundary(e){let{errorComponent:t,errorStyles:r,errorScripts:n,children:l}=e,u=(0,o.usePathname)();return t?a.default.createElement(ErrorBoundaryHandler,{pathname:u,errorComponent:t,errorStyles:r,errorScripts:n},l):a.default.createElement(a.default.Fragment,null,l)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5171:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DYNAMIC_ERROR_CODE:function(){return r},DynamicServerError:function(){return DynamicServerError}});let r="DYNAMIC_SERVER_USAGE";let DynamicServerError=class DynamicServerError extends Error{constructor(e){super("Dynamic server usage: "+e),this.digest=r}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9880:(e,t)=>{"use strict";let r;function createInfinitePromise(){return r||(r=new Promise(()=>{})),r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInfinitePromise",{enumerable:!0,get:function(){return createInfinitePromise}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4900:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return OuterLayoutRouter}}),r(85);let n=r(8425),a=n._(r(9885));r(8908);let o=r(2428),l=r(9102),u=r(9880),i=r(5365),s=r(4538),c=r(4448),d=r(7502),f=r(4714),p=r(1275),h=r(4701),_=r(8026);function walkAddRefetch(e,t){if(e){let[r,n]=e,a=2===e.length;if((0,s.matchSegment)(t[0],r)&&t[1].hasOwnProperty(n)){if(a){let e=walkAddRefetch(void 0,t[1][n]);return[t[0],{...t[1],[n]:[e[0],e[1],e[2],"refetch"]}]}return[t[0],{...t[1],[n]:walkAddRefetch(e.slice(2),t[1][n])}]}}return t}function findDOMNode(e){return null}let y=["bottom","height","left","right","top","width","x","y"];function shouldSkipElement(e){if(["sticky","fixed"].includes(getComputedStyle(e).position))return!0;let t=e.getBoundingClientRect();return y.every(e=>0===t[e])}function topOfElementInViewport(e,t){let r=e.getBoundingClientRect();return r.top>=0&&r.top<=t}function getHashFragmentDomNode(e){var t;return"top"===e?document.body:null!=(t=document.getElementById(e))?t:document.getElementsByName(e)[0]}let InnerScrollAndFocusHandler=class InnerScrollAndFocusHandler extends a.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:t}=this.props;if(e.apply){if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>t.every((t,r)=>(0,s.matchSegment)(t,e[r]))))return;let r=null,n=e.hashFragment;if(n&&(r=getHashFragmentDomNode(n)),r||(r=findDOMNode(this)),!(r instanceof Element))return;for(;!(r instanceof HTMLElement)||shouldSkipElement(r);){if(null===r.nextElementSibling)return;r=r.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,c.handleSmoothScroll)(()=>{if(n){r.scrollIntoView();return}let e=document.documentElement,t=e.clientHeight;!topOfElementInViewport(r,t)&&(e.scrollTop=0,topOfElementInViewport(r,t)||r.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:e.onlyHashChange}),e.onlyHashChange=!1,r.focus()}}}};function ScrollAndFocusHandler(e){let{segmentPath:t,children:r}=e,n=(0,a.useContext)(o.GlobalLayoutRouterContext);if(!n)throw Error("invariant global layout router not mounted");return a.default.createElement(InnerScrollAndFocusHandler,{segmentPath:t,focusAndScrollRef:n.focusAndScrollRef},r)}function InnerLayoutRouter(e){let{parallelRouterKey:t,url:r,childNodes:n,childProp:i,segmentPath:s,tree:c,cacheKey:d}=e,f=(0,a.useContext)(o.GlobalLayoutRouterContext);if(!f)throw Error("invariant global layout router not mounted");let{buildId:p,changeByServerResponse:h,tree:y}=f,m=n.get(d);if(i&&null!==i.current&&(m?m.status===o.CacheStates.LAZY_INITIALIZED&&(m.status=o.CacheStates.READY,m.subTreeData=i.current):(m={status:o.CacheStates.READY,data:null,subTreeData:i.current,parallelRoutes:new Map},n.set(d,m))),!m||m.status===o.CacheStates.LAZY_INITIALIZED){let e=walkAddRefetch(["",...s],y);m={status:o.CacheStates.DATA_FETCH,data:(0,_.createRecordFromThenable)((0,l.fetchServerResponse)(new URL(r,location.origin),e,f.nextUrl,p)),subTreeData:null,head:m&&m.status===o.CacheStates.LAZY_INITIALIZED?m.head:void 0,parallelRoutes:m&&m.status===o.CacheStates.LAZY_INITIALIZED?m.parallelRoutes:new Map},n.set(d,m)}if(!m)throw Error("Child node should always exist");if(m.subTreeData&&m.data)throw Error("Child node should not have both subTreeData and data");if(m.data){let[e,t]=(0,a.use)(m.data);m.data=null,setTimeout(()=>{(0,a.startTransition)(()=>{h(y,e,t)})}),(0,a.use)((0,u.createInfinitePromise)())}m.subTreeData||(0,a.use)((0,u.createInfinitePromise)());let g=a.default.createElement(o.LayoutRouterContext.Provider,{value:{tree:c[1][t],childNodes:m.parallelRoutes,url:r}},m.subTreeData);return g}function LoadingBoundary(e){let{children:t,loading:r,loadingStyles:n,loadingScripts:o,hasLoading:l}=e;return l?a.default.createElement(a.Suspense,{fallback:a.default.createElement(a.default.Fragment,null,n,o,r)},t):a.default.createElement(a.default.Fragment,null,t)}function OuterLayoutRouter(e){let{parallelRouterKey:t,segmentPath:r,childProp:n,error:l,errorStyles:u,errorScripts:c,templateStyles:_,templateScripts:y,loading:m,loadingStyles:g,loadingScripts:b,hasLoading:v,template:P,notFound:R,notFoundStyles:S,styles:E}=e,O=(0,a.useContext)(o.LayoutRouterContext);if(!O)throw Error("invariant expected layout router to be mounted");let{childNodes:T,tree:j,url:M}=O,x=T.get(t);x||(x=new Map,T.set(t,x));let A=j[1][t][0],C=n.segment,N=(0,p.getSegmentValue)(A),w=[A];return a.default.createElement(a.default.Fragment,null,E,w.map(e=>{let E=(0,s.matchSegment)(e,C),O=(0,p.getSegmentValue)(e),T=(0,h.createRouterCacheKey)(e);return a.default.createElement(o.TemplateContext.Provider,{key:(0,h.createRouterCacheKey)(e,!0),value:a.default.createElement(ScrollAndFocusHandler,{segmentPath:r},a.default.createElement(i.ErrorBoundary,{errorComponent:l,errorStyles:u,errorScripts:c},a.default.createElement(LoadingBoundary,{hasLoading:v,loading:m,loadingStyles:g,loadingScripts:b},a.default.createElement(f.NotFoundBoundary,{notFound:R,notFoundStyles:S},a.default.createElement(d.RedirectBoundary,null,a.default.createElement(InnerLayoutRouter,{parallelRouterKey:t,url:M,tree:j,childNodes:x,childProp:E?n:null,segmentPath:r,cacheKey:T,isActive:N===O}))))))},_,y,P)}))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4538:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{matchSegment:function(){return matchSegment},canSegmentBeOverridden:function(){return canSegmentBeOverridden}});let n=r(2290),matchSegment=(e,t)=>"string"==typeof e?"string"==typeof t&&e===t:"string"!=typeof t&&e[0]===t[0]&&e[1]===t[1],canSegmentBeOverridden=(e,t)=>{var r;return!Array.isArray(e)&&!!Array.isArray(t)&&(null==(r=(0,n.getSegmentParam)(e))?void 0:r.param)===t[0]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3094:(e,t,r)=>{"use strict";function maybePostpone(e,t){if(!e.isStaticGeneration||!e.experimental.ppr)return;let n=r(9885);"function"==typeof n.unstable_postpone&&n.unstable_postpone(t)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"maybePostpone",{enumerable:!0,get:function(){return maybePostpone}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4979:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ReadonlyURLSearchParams:function(){return ReadonlyURLSearchParams},useSearchParams:function(){return useSearchParams},usePathname:function(){return usePathname},ServerInsertedHTMLContext:function(){return i.ServerInsertedHTMLContext},useServerInsertedHTML:function(){return i.useServerInsertedHTML},useRouter:function(){return useRouter},useParams:function(){return useParams},useSelectedLayoutSegments:function(){return useSelectedLayoutSegments},useSelectedLayoutSegment:function(){return useSelectedLayoutSegment},redirect:function(){return s.redirect},permanentRedirect:function(){return s.permanentRedirect},RedirectType:function(){return s.RedirectType},notFound:function(){return c.notFound}});let n=r(9885),a=r(2428),o=r(1736),l=r(3402),u=r(1275),i=r(5753),s=r(1612),c=r(1103),d=Symbol("internal for urlsearchparams readonly");function readonlyURLSearchParamsError(){return Error("ReadonlyURLSearchParams cannot be modified")}let ReadonlyURLSearchParams=class ReadonlyURLSearchParams{[Symbol.iterator](){return this[d][Symbol.iterator]()}append(){throw readonlyURLSearchParamsError()}delete(){throw readonlyURLSearchParamsError()}set(){throw readonlyURLSearchParamsError()}sort(){throw readonlyURLSearchParamsError()}constructor(e){this[d]=e,this.entries=e.entries.bind(e),this.forEach=e.forEach.bind(e),this.get=e.get.bind(e),this.getAll=e.getAll.bind(e),this.has=e.has.bind(e),this.keys=e.keys.bind(e),this.values=e.values.bind(e),this.toString=e.toString.bind(e),this.size=e.size}};function useSearchParams(){(0,l.clientHookInServerComponentError)("useSearchParams");let e=(0,n.useContext)(o.SearchParamsContext),t=(0,n.useMemo)(()=>e?new ReadonlyURLSearchParams(e):null,[e]);{let{bailoutToClientRendering:e}=r(4954);e()}return t}function usePathname(){return(0,l.clientHookInServerComponentError)("usePathname"),(0,n.useContext)(o.PathnameContext)}function useRouter(){(0,l.clientHookInServerComponentError)("useRouter");let e=(0,n.useContext)(a.AppRouterContext);if(null===e)throw Error("invariant expected app router to be mounted");return e}function getSelectedParams(e,t){void 0===t&&(t={});let r=e[1];for(let e of Object.values(r)){let r=e[0],n=Array.isArray(r),a=n?r[1]:r;if(!a||a.startsWith("__PAGE__"))continue;let o=n&&("c"===r[2]||"oc"===r[2]);o?t[r[0]]=r[1].split("/"):n&&(t[r[0]]=r[1]),t=getSelectedParams(e,t)}return t}function useParams(){(0,l.clientHookInServerComponentError)("useParams");let e=(0,n.useContext)(a.GlobalLayoutRouterContext),t=(0,n.useContext)(o.PathParamsContext);return(0,n.useMemo)(()=>(null==e?void 0:e.tree)?getSelectedParams(e.tree):t,[null==e?void 0:e.tree,t])}function getSelectedLayoutSegmentPath(e,t,r,n){let a;if(void 0===r&&(r=!0),void 0===n&&(n=[]),r)a=e[1][t];else{var o;let t=e[1];a=null!=(o=t.children)?o:Object.values(t)[0]}if(!a)return n;let l=a[0],i=(0,u.getSegmentValue)(l);return!i||i.startsWith("__PAGE__")?n:(n.push(i),getSelectedLayoutSegmentPath(a,t,!1,n))}function useSelectedLayoutSegments(e){void 0===e&&(e="children"),(0,l.clientHookInServerComponentError)("useSelectedLayoutSegments");let{tree:t}=(0,n.useContext)(a.LayoutRouterContext);return getSelectedLayoutSegmentPath(t,e)}function useSelectedLayoutSegment(e){void 0===e&&(e="children"),(0,l.clientHookInServerComponentError)("useSelectedLayoutSegment");let t=useSelectedLayoutSegments(e);return 0===t.length?null:t[0]}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4714:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NotFoundBoundary",{enumerable:!0,get:function(){return NotFoundBoundary}});let n=r(85),a=n._(r(9885)),o=r(4979);let NotFoundErrorBoundary=class NotFoundErrorBoundary extends a.default.Component{static getDerivedStateFromError(e){if((null==e?void 0:e.digest)==="NEXT_NOT_FOUND")return{notFoundTriggered:!0};throw e}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.notFoundTriggered?{notFoundTriggered:!1,previousPathname:e.pathname}:{notFoundTriggered:t.notFoundTriggered,previousPathname:e.pathname}}render(){return this.state.notFoundTriggered?a.default.createElement(a.default.Fragment,null,a.default.createElement("meta",{name:"robots",content:"noindex"}),!1,this.props.notFoundStyles,this.props.notFound):this.props.children}constructor(e){super(e),this.state={notFoundTriggered:!!e.asNotFound,previousPathname:e.pathname}}};function NotFoundBoundary(e){let{notFound:t,notFoundStyles:r,asNotFound:n,children:l}=e,u=(0,o.usePathname)();return t?a.default.createElement(NotFoundErrorBoundary,{pathname:u,notFound:t,notFoundStyles:r,asNotFound:n},l):a.default.createElement(a.default.Fragment,null,l)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1103:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{notFound:function(){return notFound},isNotFoundError:function(){return isNotFoundError}});let r="NEXT_NOT_FOUND";function notFound(){let e=Error(r);throw e.digest=r,e}function isNotFoundError(e){return(null==e?void 0:e.digest)===r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8862:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PromiseQueue",{enumerable:!0,get:function(){return PromiseQueue}});let n=r(3592),a=r(4941);var o=a._("_maxConcurrency"),l=a._("_runningCount"),u=a._("_queue"),i=a._("_processNext");let PromiseQueue=class PromiseQueue{enqueue(e){let t,r;let a=new Promise((e,n)=>{t=e,r=n}),task=async()=>{try{n._(this,l)[l]++;let r=await e();t(r)}catch(e){r(e)}finally{n._(this,l)[l]--,n._(this,i)[i]()}};return n._(this,u)[u].push({promiseFn:a,task}),n._(this,i)[i](),a}bump(e){let t=n._(this,u)[u].findIndex(t=>t.promiseFn===e);if(t>-1){let e=n._(this,u)[u].splice(t,1)[0];n._(this,u)[u].unshift(e),n._(this,i)[i](!0)}}constructor(e=5){Object.defineProperty(this,i,{value:processNext}),Object.defineProperty(this,o,{writable:!0,value:void 0}),Object.defineProperty(this,l,{writable:!0,value:void 0}),Object.defineProperty(this,u,{writable:!0,value:void 0}),n._(this,o)[o]=e,n._(this,l)[l]=0,n._(this,u)[u]=[]}};function processNext(e){if(void 0===e&&(e=!1),(n._(this,l)[l]0){var t;null==(t=n._(this,u)[u].shift())||t.task()}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7502:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectErrorBoundary:function(){return RedirectErrorBoundary},RedirectBoundary:function(){return RedirectBoundary}});let n=r(8425),a=n._(r(9885)),o=r(4979),l=r(1612);function HandleRedirect(e){let{redirect:t,reset:r,redirectType:n}=e,u=(0,o.useRouter)();return(0,a.useEffect)(()=>{a.default.startTransition(()=>{n===l.RedirectType.push?u.push(t,{}):u.replace(t,{}),r()})},[t,n,r,u]),null}let RedirectErrorBoundary=class RedirectErrorBoundary extends a.default.Component{static getDerivedStateFromError(e){if((0,l.isRedirectError)(e)){let t=(0,l.getURLFromRedirectError)(e),r=(0,l.getRedirectTypeFromError)(e);return{redirect:t,redirectType:r}}throw e}render(){let{redirect:e,redirectType:t}=this.state;return null!==e&&null!==t?a.default.createElement(HandleRedirect,{redirect:e,redirectType:t,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(e){super(e),this.state={redirect:null,redirectType:null}}};function RedirectBoundary(e){let{children:t}=e,r=(0,o.useRouter)();return a.default.createElement(RedirectErrorBoundary,{router:r},t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1612:(e,t,r)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectType:function(){return n},getRedirectError:function(){return getRedirectError},redirect:function(){return redirect},permanentRedirect:function(){return permanentRedirect},isRedirectError:function(){return isRedirectError},getURLFromRedirectError:function(){return getURLFromRedirectError},getRedirectTypeFromError:function(){return getRedirectTypeFromError}});let a=r(5403),o="NEXT_REDIRECT";function getRedirectError(e,t,r){void 0===r&&(r=!1);let n=Error(o);n.digest=o+";"+t+";"+e+";"+r;let l=a.requestAsyncStorage.getStore();return l&&(n.mutableCookies=l.mutableCookies),n}function redirect(e,t){throw void 0===t&&(t="replace"),getRedirectError(e,t,!1)}function permanentRedirect(e,t){throw void 0===t&&(t="replace"),getRedirectError(e,t,!0)}function isRedirectError(e){if("string"!=typeof(null==e?void 0:e.digest))return!1;let[t,r,n,a]=e.digest.split(";",4);return t===o&&("replace"===r||"push"===r)&&"string"==typeof n&&("true"===a||"false"===a)}function getURLFromRedirectError(e){return isRedirectError(e)?e.digest.split(";",3)[2]:null}function getRedirectTypeFromError(e){if(!isRedirectError(e))throw Error("Not a redirect error");return e.digest.split(";",2)[1]}(function(e){e.push="push",e.replace="replace"})(n||(n={})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5392:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return RenderFromTemplateContext}});let n=r(8425),a=n._(r(9885)),o=r(2428);function RenderFromTemplateContext(){let e=(0,a.useContext)(o.TemplateContext);return a.default.createElement(a.default.Fragment,null,e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1847:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyFlightData",{enumerable:!0,get:function(){return applyFlightData}});let n=r(2428),a=r(5929),o=r(4059);function applyFlightData(e,t,r,l){void 0===l&&(l=!1);let[u,i,s]=r.slice(-3);return null!==i&&(3===r.length?(t.status=n.CacheStates.READY,t.subTreeData=i,(0,a.fillLazyItemsTillLeafWithHead)(t,e,u,s,l)):(t.status=n.CacheStates.READY,t.subTreeData=e.subTreeData,t.parallelRoutes=new Map(e.parallelRoutes),(0,o.fillCacheWithNewSubTreeData)(t,e,r,l)),!0)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9605:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return applyRouterStatePatchToTree}});let n=r(4538);function applyPatch(e,t){let[r,a]=e,[o,l]=t;if("__DEFAULT__"===o&&"__DEFAULT__"!==r)return e;if((0,n.matchSegment)(r,o)){let t={};for(let e in a){let r=void 0!==l[e];r?t[e]=applyPatch(a[e],l[e]):t[e]=a[e]}for(let e in l)t[e]||(t[e]=l[e]);let n=[r,t];return e[2]&&(n[2]=e[2]),e[3]&&(n[3]=e[3]),e[4]&&(n[4]=e[4]),n}return t}function applyRouterStatePatchToTree(e,t,r){let a;let[o,l,,,u]=t;if(1===e.length){let e=applyPatch(t,r);return e}let[i,s]=e;if(!(0,n.matchSegment)(i,o))return null;let c=2===e.length;if(c)a=applyPatch(l[s],r);else if(null===(a=applyRouterStatePatchToTree(e.slice(2),l[s],r)))return null;let d=[e[0],{...l,[s]:a}];return u&&(d[4]=!0),d}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6663:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{extractPathFromFlightRouterState:function(){return extractPathFromFlightRouterState},computeChangedPath:function(){return computeChangedPath}});let n=r(4265),a=r(392),o=r(4538),removeLeadingSlash=e=>"/"===e[0]?e.slice(1):e,segmentToPathname=e=>"string"==typeof e?e:e[1];function normalizeSegments(e){return e.reduce((e,t)=>""===(t=removeLeadingSlash(t))||(0,a.isGroupSegment)(t)?e:e+"/"+t,"")||"/"}function extractPathFromFlightRouterState(e){var t;let r=Array.isArray(e[0])?e[0][1]:e[0];if("__DEFAULT__"===r||n.INTERCEPTION_ROUTE_MARKERS.some(e=>r.startsWith(e)))return;if(r.startsWith("__PAGE__"))return"";let a=[r],o=null!=(t=e[1])?t:{},l=o.children?extractPathFromFlightRouterState(o.children):void 0;if(void 0!==l)a.push(l);else for(let[e,t]of Object.entries(o)){if("children"===e)continue;let r=extractPathFromFlightRouterState(t);void 0!==r&&a.push(r)}return normalizeSegments(a)}function computeChangedPathImpl(e,t){let[r,a]=e,[l,u]=t,i=segmentToPathname(r),s=segmentToPathname(l);if(n.INTERCEPTION_ROUTE_MARKERS.some(e=>i.startsWith(e)||s.startsWith(e)))return"";if(!(0,o.matchSegment)(r,l)){var c;return null!=(c=extractPathFromFlightRouterState(t))?c:""}for(let e in a)if(u[e]){let t=computeChangedPathImpl(a[e],u[e]);if(null!==t)return segmentToPathname(l)+"/"+t}return null}function computeChangedPath(e,t){let r=computeChangedPathImpl(e,t);return null==r||"/"===r?r:normalizeSegments(r.split("/"))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1706:(e,t)=>{"use strict";function createHrefFromUrl(e,t){return void 0===t&&(t=!0),e.pathname+e.search+(t?e.hash:"")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createHrefFromUrl",{enumerable:!0,get:function(){return createHrefFromUrl}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9624:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInitialRouterState",{enumerable:!0,get:function(){return createInitialRouterState}});let n=r(2428),a=r(1706),o=r(5929),l=r(6663);function createInitialRouterState(e){var t;let{buildId:r,initialTree:u,children:i,initialCanonicalUrl:s,initialParallelRoutes:c,isServer:d,location:f,initialHead:p}=e,h={status:n.CacheStates.READY,data:null,subTreeData:i,parallelRoutes:d?new Map:c};return(null===c||0===c.size)&&(0,o.fillLazyItemsTillLeafWithHead)(h,void 0,u,p),{buildId:r,tree:u,cache:h,prefetchCache:new Map,pushRef:{pendingPush:!1,mpaNavigation:!1},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:f?(0,a.createHrefFromUrl)(f):s,nextUrl:null!=(t=(0,l.extractPathFromFlightRouterState)(u)||(null==f?void 0:f.pathname))?t:null}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8775:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createOptimisticTree",{enumerable:!0,get:function(){return createOptimisticTree}});let n=r(4538);function createOptimisticTree(e,t,r){let a;let[o,l,u,i,s]=t||[null,{}],c=e[0],d=1===e.length,f=null!==o&&(0,n.matchSegment)(o,c),p=Object.keys(l).length>1,h=!t||!f||p,_={};if(null!==o&&f&&(_=l),!d&&!p){let t=createOptimisticTree(e.slice(1),_?_.children:null,r||h);a=t}let y=[c,{..._,...a?{children:a}:{}}];return u&&(y[2]=u),!r&&h?y[3]="refetch":f&&i&&(y[3]=i),f&&s&&(y[4]=s),y}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8026:(e,t)=>{"use strict";function createRecordFromThenable(e){return e.status="pending",e.then(t=>{"pending"===e.status&&(e.status="fulfilled",e.value=t)},t=>{"pending"===e.status&&(e.status="rejected",e.reason=t)}),e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRecordFromThenable",{enumerable:!0,get:function(){return createRecordFromThenable}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4701:(e,t)=>{"use strict";function createRouterCacheKey(e,t){return void 0===t&&(t=!1),Array.isArray(e)?(e[0]+"|"+e[1]+"|"+e[2]).toLowerCase():t&&e.startsWith("__PAGE__")?"__PAGE__":e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRouterCacheKey",{enumerable:!0,get:function(){return createRouterCacheKey}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9102:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fetchServerResponse",{enumerable:!0,get:function(){return fetchServerResponse}});let n=r(4361),a=r(3724),o=r(5422),l=r(3678),u=r(755),i=r(5082),{createFromFetch:s}=r(2623);function doMpaNavigation(e){return[(0,a.urlToUrlWithoutFlightMarker)(e).toString(),void 0]}async function fetchServerResponse(e,t,r,c,d){let f={[n.RSC]:"1",[n.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(t))};d===l.PrefetchKind.AUTO&&(f[n.NEXT_ROUTER_PREFETCH]="1"),r&&(f[n.NEXT_URL]=r);let p=(0,u.hexHash)([f[n.NEXT_ROUTER_PREFETCH]||"0",f[n.NEXT_ROUTER_STATE_TREE],f[n.NEXT_URL]].join(","));try{let t=new URL(e);t.searchParams.set(n.NEXT_RSC_UNION_QUERY,p);let r=await fetch(t,{credentials:"same-origin",headers:f}),l=(0,a.urlToUrlWithoutFlightMarker)(r.url),u=r.redirected?l:void 0,d=r.headers.get("content-type")||"",h=!!r.headers.get(i.NEXT_DID_POSTPONE_HEADER);if(d!==n.RSC_CONTENT_TYPE_HEADER||!r.ok)return e.hash&&(l.hash=e.hash),doMpaNavigation(l.toString());let[_,y]=await s(Promise.resolve(r),{callServer:o.callServer});if(c!==_)return doMpaNavigation(r.url);return[y,u,h]}catch(t){return console.error("Failed to fetch RSC payload for "+e+". Falling back to browser navigation.",t),[e.toString(),void 0]}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1924:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithDataProperty",{enumerable:!0,get:function(){return fillCacheWithDataProperty}});let n=r(2428),a=r(4701);function fillCacheWithDataProperty(e,t,r,o,l){void 0===l&&(l=!1);let u=r.length<=2,[i,s]=r,c=(0,a.createRouterCacheKey)(s),d=t.parallelRoutes.get(i);if(!d||l&&t.parallelRoutes.size>1)return{bailOptimistic:!0};let f=e.parallelRoutes.get(i);f&&f!==d||(f=new Map(d),e.parallelRoutes.set(i,f));let p=d.get(c),h=f.get(c);if(u){h&&h.data&&h!==p||f.set(c,{status:n.CacheStates.DATA_FETCH,data:o(),subTreeData:null,parallelRoutes:new Map});return}if(!h||!p){h||f.set(c,{status:n.CacheStates.DATA_FETCH,data:o(),subTreeData:null,parallelRoutes:new Map});return}return h===p&&(h={status:h.status,data:h.data,subTreeData:h.subTreeData,parallelRoutes:new Map(h.parallelRoutes)},f.set(c,h)),fillCacheWithDataProperty(h,p,r.slice(2),o)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4059:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return fillCacheWithNewSubTreeData}});let n=r(2428),a=r(2582),o=r(5929),l=r(4701);function fillCacheWithNewSubTreeData(e,t,r,u){let i=r.length<=5,[s,c]=r,d=(0,l.createRouterCacheKey)(c),f=t.parallelRoutes.get(s);if(!f)return;let p=e.parallelRoutes.get(s);p&&p!==f||(p=new Map(f),e.parallelRoutes.set(s,p));let h=f.get(d),_=p.get(d);if(i){_&&_.data&&_!==h||(_={status:n.CacheStates.READY,data:null,subTreeData:r[3],parallelRoutes:h?new Map(h.parallelRoutes):new Map},h&&(0,a.invalidateCacheByRouterState)(_,h,r[2]),(0,o.fillLazyItemsTillLeafWithHead)(_,h,r[2],r[4],u),p.set(d,_));return}_&&h&&(_===h&&(_={status:_.status,data:_.data,subTreeData:_.subTreeData,parallelRoutes:new Map(_.parallelRoutes)},p.set(d,_)),fillCacheWithNewSubTreeData(_,h,r.slice(2),u))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5929:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return fillLazyItemsTillLeafWithHead}});let n=r(2428),a=r(4701);function fillLazyItemsTillLeafWithHead(e,t,r,o,l){let u=0===Object.keys(r[1]).length;if(u){e.head=o;return}for(let u in r[1]){let i=r[1][u],s=i[0],c=(0,a.createRouterCacheKey)(s);if(t){let r=t.parallelRoutes.get(u);if(r){let t=new Map(r),a=t.get(c),s=l&&a?{status:a.status,data:a.data,subTreeData:a.subTreeData,parallelRoutes:new Map(a.parallelRoutes)}:{status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map(null==a?void 0:a.parallelRoutes)};t.set(c,s),fillLazyItemsTillLeafWithHead(s,a,i,o,l),e.parallelRoutes.set(u,t);continue}}let d={status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map},f=e.parallelRoutes.get(u);f?f.set(c,d):e.parallelRoutes.set(u,new Map([[c,d]])),fillLazyItemsTillLeafWithHead(d,void 0,i,o,l)}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6699:(e,t)=>{"use strict";var r;function getPrefetchEntryCacheStatus(e){let{kind:t,prefetchTime:r,lastUsedTime:n}=e;return Date.now()<(null!=n?n:r)+3e4?n?"reusable":"fresh":"auto"===t&&Date.now(){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleMutable",{enumerable:!0,get:function(){return handleMutable}});let n=r(6663);function handleMutable(e,t){var r,a,o,l;let u=null==(a=t.shouldScroll)||a;return{buildId:e.buildId,canonicalUrl:null!=t.canonicalUrl?t.canonicalUrl===e.canonicalUrl?e.canonicalUrl:t.canonicalUrl:e.canonicalUrl,pushRef:{pendingPush:null!=t.pendingPush?t.pendingPush:e.pushRef.pendingPush,mpaNavigation:null!=t.mpaNavigation?t.mpaNavigation:e.pushRef.mpaNavigation},focusAndScrollRef:{apply:!!u&&((null==t?void 0:t.scrollableSegments)!==void 0||e.focusAndScrollRef.apply),onlyHashChange:!!t.hashFragment&&e.canonicalUrl.split("#",1)[0]===(null==(r=t.canonicalUrl)?void 0:r.split("#",1)[0]),hashFragment:u?t.hashFragment&&""!==t.hashFragment?decodeURIComponent(t.hashFragment.slice(1)):e.focusAndScrollRef.hashFragment:null,segmentPaths:u?null!=(o=null==t?void 0:t.scrollableSegments)?o:e.focusAndScrollRef.segmentPaths:[]},cache:t.cache?t.cache:e.cache,prefetchCache:t.prefetchCache?t.prefetchCache:e.prefetchCache,tree:void 0!==t.patchedTree?t.patchedTree:e.tree,nextUrl:void 0!==t.patchedTree?null!=(l=(0,n.computeChangedPath)(e.tree,t.patchedTree))?l:e.canonicalUrl:e.nextUrl}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1986:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheBelowFlightSegmentPath",{enumerable:!0,get:function(){return invalidateCacheBelowFlightSegmentPath}});let n=r(4701);function invalidateCacheBelowFlightSegmentPath(e,t,r){let a=r.length<=2,[o,l]=r,u=(0,n.createRouterCacheKey)(l),i=t.parallelRoutes.get(o);if(!i)return;let s=e.parallelRoutes.get(o);if(s&&s!==i||(s=new Map(i),e.parallelRoutes.set(o,s)),a){s.delete(u);return}let c=i.get(u),d=s.get(u);d&&c&&(d===c&&(d={status:d.status,data:d.data,subTreeData:d.subTreeData,parallelRoutes:new Map(d.parallelRoutes)},s.set(u,d)),invalidateCacheBelowFlightSegmentPath(d,c,r.slice(2)))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2582:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheByRouterState",{enumerable:!0,get:function(){return invalidateCacheByRouterState}});let n=r(4701);function invalidateCacheByRouterState(e,t,r){for(let a in r[1]){let o=r[1][a][0],l=(0,n.createRouterCacheKey)(o),u=t.parallelRoutes.get(a);if(u){let t=new Map(u);t.delete(l),e.parallelRoutes.set(a,t)}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},145:(e,t)=>{"use strict";function isNavigatingToNewRootLayout(e,t){let r=e[0],n=t[0];if(Array.isArray(r)&&Array.isArray(n)){if(r[0]!==n[0]||r[2]!==n[2])return!0}else if(r!==n)return!0;if(e[4])return!t[4];if(t[4])return!0;let a=Object.values(e[1])[0],o=Object.values(t[1])[0];return!a||!o||isNavigatingToNewRootLayout(a,o)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNavigatingToNewRootLayout",{enumerable:!0,get:function(){return isNavigatingToNewRootLayout}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4879:(e,t)=>{"use strict";function readRecordValue(e){if("fulfilled"===e.status)return e.value;throw e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"readRecordValue",{enumerable:!0,get:function(){return readRecordValue}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2755:(e,t,r)=>{"use strict";function fastRefreshReducerNoop(e,t){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fastRefreshReducer",{enumerable:!0,get:function(){return n}}),r(9102),r(8026),r(4879),r(1706),r(9605),r(145),r(8237),r(3466),r(1847);let n=fastRefreshReducerNoop;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2226:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"findHeadInCache",{enumerable:!0,get:function(){return findHeadInCache}});let n=r(4701);function findHeadInCache(e,t){let r=0===Object.keys(t).length;if(r)return e.head;for(let r in t){let[a,o]=t[r],l=e.parallelRoutes.get(r);if(!l)continue;let u=(0,n.createRouterCacheKey)(a),i=l.get(u);if(!i)continue;let s=findHeadInCache(i,o);if(s)return s}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1275:(e,t)=>{"use strict";function getSegmentValue(e){return Array.isArray(e)?e[1]:e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentValue",{enumerable:!0,get:function(){return getSegmentValue}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8237:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleExternalUrl:function(){return handleExternalUrl},navigateReducer:function(){return navigateReducer}});let n=r(2428),a=r(9102),o=r(8026),l=r(4879),u=r(1706),i=r(1986),s=r(1924),c=r(8775),d=r(9605),f=r(4320),p=r(145),h=r(3678),_=r(3466),y=r(1847),m=r(6699),g=r(8155),b=r(1196);function handleExternalUrl(e,t,r,n){return t.previousTree=e.tree,t.mpaNavigation=!0,t.canonicalUrl=r,t.pendingPush=n,t.scrollableSegments=void 0,(0,_.handleMutable)(e,t)}function generateSegmentsFromPatch(e){let t=[],[r,n]=e;if(0===Object.keys(n).length)return[[r]];for(let[e,a]of Object.entries(n))for(let n of generateSegmentsFromPatch(a))""===r?t.push([e,...n]):t.push([r,e,...n]);return t}function addRefetchToLeafSegments(e,t,r,a,o){let l=!1;e.status=n.CacheStates.READY,e.subTreeData=t.subTreeData,e.parallelRoutes=new Map(t.parallelRoutes);let u=generateSegmentsFromPatch(a).map(e=>[...r,...e]);for(let r of u){let n=(0,s.fillCacheWithDataProperty)(e,t,r,o);(null==n?void 0:n.bailOptimistic)||(l=!0)}return l}function navigateReducer(e,t){let{url:r,isExternalUrl:v,navigateType:P,cache:R,mutable:S,forceOptimisticNavigation:E,shouldScroll:O}=t,{pathname:T,hash:j}=r,M=(0,u.createHrefFromUrl)(r),x="push"===P;(0,g.prunePrefetchCache)(e.prefetchCache);let A=JSON.stringify(S.previousTree)===JSON.stringify(e.tree);if(A)return(0,_.handleMutable)(e,S);if(v)return handleExternalUrl(e,S,r.toString(),x);let C=e.prefetchCache.get((0,u.createHrefFromUrl)(r,!1));if(E&&(null==C?void 0:C.kind)!==h.PrefetchKind.TEMPORARY){let t=T.split("/");t.push("__PAGE__");let l=(0,c.createOptimisticTree)(t,e.tree,!1),i={...R};i.status=n.CacheStates.READY,i.subTreeData=e.cache.subTreeData,i.parallelRoutes=new Map(e.cache.parallelRoutes);let d=null,f=t.slice(1).map(e=>["children",e]).flat(),p=(0,s.fillCacheWithDataProperty)(i,e.cache,f,()=>(d||(d=(0,o.createRecordFromThenable)((0,a.fetchServerResponse)(r,l,e.nextUrl,e.buildId))),d),!0);if(!(null==p?void 0:p.bailOptimistic))return S.previousTree=e.tree,S.patchedTree=l,S.pendingPush=x,S.hashFragment=j,S.shouldScroll=O,S.scrollableSegments=[],S.cache=i,S.canonicalUrl=M,e.prefetchCache.set((0,u.createHrefFromUrl)(r,!1),{data:d?(0,o.createRecordFromThenable)(Promise.resolve(d)):null,kind:h.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:e.tree,lastUsedTime:Date.now()}),(0,_.handleMutable)(e,S)}if(!C){let t=(0,o.createRecordFromThenable)((0,a.fetchServerResponse)(r,e.tree,e.nextUrl,e.buildId,void 0)),n={data:(0,o.createRecordFromThenable)(Promise.resolve(t)),kind:h.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:e.tree,lastUsedTime:null};e.prefetchCache.set((0,u.createHrefFromUrl)(r,!1),n),C=n}let N=(0,m.getPrefetchEntryCacheStatus)(C),{treeAtTimeOfPrefetch:w,data:I}=C;b.prefetchQueue.bump(I);let[F,D,L]=(0,l.readRecordValue)(I);if(C.lastUsedTime||(C.lastUsedTime=Date.now()),"string"==typeof F)return handleExternalUrl(e,S,F,x);let U=e.tree,H=e.cache,B=[];for(let t of F){let l=t.slice(0,-4),u=t.slice(-3)[0],s=["",...l],c=(0,d.applyRouterStatePatchToTree)(s,U,u);if(null===c&&(c=(0,d.applyRouterStatePatchToTree)(s,w,u)),null!==c){if((0,p.isNavigatingToNewRootLayout)(U,c))return handleExternalUrl(e,S,M,x);let d=!L&&(0,y.applyFlightData)(H,R,t,"auto"===C.kind&&N===m.PrefetchCacheEntryStatus.reusable);d||N!==m.PrefetchCacheEntryStatus.stale||(d=addRefetchToLeafSegments(R,H,l,u,()=>(0,o.createRecordFromThenable)((0,a.fetchServerResponse)(r,U,e.nextUrl,e.buildId))));let h=(0,f.shouldHardNavigate)(s,U);for(let e of(h?(R.status=n.CacheStates.READY,R.subTreeData=H.subTreeData,(0,i.invalidateCacheBelowFlightSegmentPath)(R,H,l),S.cache=R):d&&(S.cache=R),H=R,U=c,generateSegmentsFromPatch(u))){let t=[...l,...e];"__DEFAULT__"!==t[t.length-1]&&B.push(t)}}}return S.previousTree=e.tree,S.patchedTree=U,S.canonicalUrl=D?(0,u.createHrefFromUrl)(D):M,S.pendingPush=x,S.scrollableSegments=B,S.hashFragment=j,S.shouldScroll=O,(0,_.handleMutable)(e,S)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1196:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{prefetchQueue:function(){return c},prefetchReducer:function(){return prefetchReducer}});let n=r(1706),a=r(9102),o=r(3678),l=r(8026),u=r(8155),i=r(4361),s=r(8862),c=new s.PromiseQueue(5);function prefetchReducer(e,t){(0,u.prunePrefetchCache)(e.prefetchCache);let{url:r}=t;r.searchParams.delete(i.NEXT_RSC_UNION_QUERY);let s=(0,n.createHrefFromUrl)(r,!1),d=e.prefetchCache.get(s);if(d&&(d.kind===o.PrefetchKind.TEMPORARY&&e.prefetchCache.set(s,{...d,kind:t.kind}),!(d.kind===o.PrefetchKind.AUTO&&t.kind===o.PrefetchKind.FULL)))return e;let f=(0,l.createRecordFromThenable)(c.enqueue(()=>(0,a.fetchServerResponse)(r,e.tree,e.nextUrl,e.buildId,t.kind)));return e.prefetchCache.set(s,{treeAtTimeOfPrefetch:e.tree,data:f,kind:t.kind,prefetchTime:Date.now(),lastUsedTime:null}),e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8155:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prunePrefetchCache",{enumerable:!0,get:function(){return prunePrefetchCache}});let n=r(6699);function prunePrefetchCache(e){for(let[t,r]of e)(0,n.getPrefetchEntryCacheStatus)(r)===n.PrefetchCacheEntryStatus.expired&&e.delete(t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8038:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"refreshReducer",{enumerable:!0,get:function(){return refreshReducer}});let n=r(9102),a=r(8026),o=r(4879),l=r(1706),u=r(9605),i=r(145),s=r(8237),c=r(3466),d=r(2428),f=r(5929);function refreshReducer(e,t){let{cache:r,mutable:p,origin:h}=t,_=e.canonicalUrl,y=e.tree,m=JSON.stringify(p.previousTree)===JSON.stringify(y);if(m)return(0,c.handleMutable)(e,p);r.data||(r.data=(0,a.createRecordFromThenable)((0,n.fetchServerResponse)(new URL(_,h),[y[0],y[1],y[2],"refetch"],e.nextUrl,e.buildId)));let[g,b]=(0,o.readRecordValue)(r.data);if("string"==typeof g)return(0,s.handleExternalUrl)(e,p,g,e.pushRef.pendingPush);for(let t of(r.data=null,g)){if(3!==t.length)return console.log("REFRESH FAILED"),e;let[n]=t,a=(0,u.applyRouterStatePatchToTree)([""],y,n);if(null===a)throw Error("SEGMENT MISMATCH");if((0,i.isNavigatingToNewRootLayout)(y,a))return(0,s.handleExternalUrl)(e,p,_,e.pushRef.pendingPush);let o=b?(0,l.createHrefFromUrl)(b):void 0;b&&(p.canonicalUrl=o);let[c,h]=t.slice(-2);null!==c&&(r.status=d.CacheStates.READY,r.subTreeData=c,(0,f.fillLazyItemsTillLeafWithHead)(r,void 0,n,h),p.cache=r,p.prefetchCache=new Map),p.previousTree=y,p.patchedTree=a,p.canonicalUrl=_,y=a}return(0,c.handleMutable)(e,p)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2910:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"restoreReducer",{enumerable:!0,get:function(){return restoreReducer}});let n=r(1706);function restoreReducer(e,t){let{url:r,tree:a}=t,o=(0,n.createHrefFromUrl)(r);return{buildId:e.buildId,canonicalUrl:o,pushRef:e.pushRef,focusAndScrollRef:e.focusAndScrollRef,cache:e.cache,prefetchCache:e.prefetchCache,tree:a,nextUrl:r.pathname}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9747:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverActionReducer",{enumerable:!0,get:function(){return serverActionReducer}});let n=r(5422),a=r(4361),o=r(8026),l=r(4879),u=r(6879),i=r(1706),s=r(8237),c=r(9605),d=r(145),f=r(2428),p=r(3466),h=r(5929),{createFromFetch:_,encodeReply:y}=r(2623);async function fetchServerAction(e,t){let r,{actionId:o,actionArgs:l}=t,i=await y(l),s=await fetch("",{method:"POST",headers:{Accept:a.RSC_CONTENT_TYPE_HEADER,[a.ACTION]:o,[a.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(e.tree)),...e.nextUrl?{[a.NEXT_URL]:e.nextUrl}:{}},body:i}),c=s.headers.get("x-action-redirect");try{let e=JSON.parse(s.headers.get("x-action-revalidated")||"[[],0,0]");r={paths:e[0]||[],tag:!!e[1],cookie:e[2]}}catch(e){r={paths:[],tag:!1,cookie:!1}}let d=c?new URL((0,u.addBasePath)(c),new URL(e.canonicalUrl,window.location.href)):void 0;if(s.headers.get("content-type")===a.RSC_CONTENT_TYPE_HEADER){let e=await _(Promise.resolve(s),{callServer:n.callServer});if(c){let[,t]=null!=e?e:[];return{actionFlightData:t,redirectLocation:d,revalidatedParts:r}}let[t,[,a]]=null!=e?e:[];return{actionResult:t,actionFlightData:a,redirectLocation:d,revalidatedParts:r}}return{redirectLocation:d,revalidatedParts:r}}function serverActionReducer(e,t){let{mutable:r,cache:n,resolve:a,reject:u}=t,_=e.canonicalUrl,y=e.tree,m=JSON.stringify(r.previousTree)===JSON.stringify(y);if(m)return(0,p.handleMutable)(e,r);if(r.inFlightServerAction){if("fulfilled"!==r.inFlightServerAction.status&&r.globalMutable.pendingNavigatePath&&r.globalMutable.pendingNavigatePath!==_)return r.inFlightServerAction.then(()=>{r.actionResultResolved||(r.inFlightServerAction=null,r.globalMutable.pendingNavigatePath=void 0,r.globalMutable.refresh(),r.actionResultResolved=!0)},()=>{}),e}else r.inFlightServerAction=(0,o.createRecordFromThenable)(fetchServerAction(e,t));try{let{actionResult:t,actionFlightData:o,redirectLocation:u}=(0,l.readRecordValue)(r.inFlightServerAction);if(u&&(e.pushRef.pendingPush=!0,r.pendingPush=!0),r.previousTree=e.tree,!o){if(r.actionResultResolved||(a(t),r.actionResultResolved=!0),u)return(0,s.handleExternalUrl)(e,r,u.href,e.pushRef.pendingPush);return e}if("string"==typeof o)return(0,s.handleExternalUrl)(e,r,o,e.pushRef.pendingPush);for(let t of(r.inFlightServerAction=null,o)){if(3!==t.length)return console.log("SERVER ACTION APPLY FAILED"),e;let[a]=t,o=(0,c.applyRouterStatePatchToTree)([""],y,a);if(null===o)throw Error("SEGMENT MISMATCH");if((0,d.isNavigatingToNewRootLayout)(y,o))return(0,s.handleExternalUrl)(e,r,_,e.pushRef.pendingPush);let[l,u]=t.slice(-2);null!==l&&(n.status=f.CacheStates.READY,n.subTreeData=l,(0,h.fillLazyItemsTillLeafWithHead)(n,void 0,a,u),r.cache=n,r.prefetchCache=new Map),r.previousTree=y,r.patchedTree=o,r.canonicalUrl=_,y=o}if(u){let e=(0,i.createHrefFromUrl)(u,!1);r.canonicalUrl=e}return r.actionResultResolved||(a(t),r.actionResultResolved=!0),(0,p.handleMutable)(e,r)}catch(t){if("rejected"===t.status)return r.actionResultResolved||(u(t.reason),r.actionResultResolved=!0),e;throw t}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9794:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverPatchReducer",{enumerable:!0,get:function(){return serverPatchReducer}});let n=r(1706),a=r(9605),o=r(145),l=r(8237),u=r(1847),i=r(3466);function serverPatchReducer(e,t){let{flightData:r,previousTree:s,overrideCanonicalUrl:c,cache:d,mutable:f}=t,p=JSON.stringify(s)===JSON.stringify(e.tree);if(!p)return console.log("TREE MISMATCH"),e;if(f.previousTree)return(0,i.handleMutable)(e,f);if("string"==typeof r)return(0,l.handleExternalUrl)(e,f,r,e.pushRef.pendingPush);let h=e.tree,_=e.cache;for(let t of r){let r=t.slice(0,-4),[i]=t.slice(-3,-2),s=(0,a.applyRouterStatePatchToTree)(["",...r],h,i);if(null===s)throw Error("SEGMENT MISMATCH");if((0,o.isNavigatingToNewRootLayout)(h,s))return(0,l.handleExternalUrl)(e,f,e.canonicalUrl,e.pushRef.pendingPush);let p=c?(0,n.createHrefFromUrl)(c):void 0;p&&(f.canonicalUrl=p),(0,u.applyFlightData)(_,d,t),f.previousTree=h,f.patchedTree=s,f.cache=d,_=d,h=s}return(0,i.handleMutable)(e,f)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3678:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PrefetchKind:function(){return r},ACTION_REFRESH:function(){return n},ACTION_NAVIGATE:function(){return a},ACTION_RESTORE:function(){return o},ACTION_SERVER_PATCH:function(){return l},ACTION_PREFETCH:function(){return u},ACTION_FAST_REFRESH:function(){return i},ACTION_SERVER_ACTION:function(){return s}});let n="refresh",a="navigate",o="restore",l="server-patch",u="prefetch",i="fast-refresh",s="server-action";(function(e){e.AUTO="auto",e.FULL="full",e.TEMPORARY="temporary"})(r||(r={})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7986:(e,t,r)=>{"use strict";function serverReducer(e,t){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return n}}),r(3678),r(8237),r(9794),r(2910),r(8038),r(1196),r(2755),r(9747);let n=serverReducer;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4320:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldHardNavigate",{enumerable:!0,get:function(){return shouldHardNavigate}});let n=r(4538);function shouldHardNavigate(e,t){let[r,a]=t,[o,l]=e;if(!(0,n.matchSegment)(o,r))return!!Array.isArray(o);let u=e.length<=2;return!u&&shouldHardNavigate(e.slice(2),a[l])}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3032:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return createSearchParamsBailoutProxy}});let n=r(1492);function createSearchParamsBailoutProxy(){return new Proxy({},{get(e,t){"string"==typeof t&&(0,n.staticGenerationBailout)("searchParams."+t)}})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1492:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationBailout",{enumerable:!0,get:function(){return staticGenerationBailout}});let n=r(5171),a=r(3094),o=r(4749);let StaticGenBailoutError=class StaticGenBailoutError extends Error{constructor(...e){super(...e),this.code="NEXT_STATIC_GEN_BAILOUT"}};function formatErrorMessage(e,t){let{dynamic:r,link:n}=t||{};return"Page"+(r?' with `dynamic = "'+r+'"`':"")+" couldn't be rendered statically because it used `"+e+"`."+(n?" See more info here: "+n:"")}let staticGenerationBailout=(e,t)=>{let r=o.staticGenerationAsyncStorage.getStore();if(!r)return!1;if(r.forceStatic)return!0;if(r.dynamicShouldError){var l;throw new StaticGenBailoutError(formatErrorMessage(e,{...t,dynamic:null!=(l=null==t?void 0:t.dynamic)?l:"error"}))}let u=formatErrorMessage(e,{...t,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if((0,a.maybePostpone)(r,u),r.revalidate=0,(null==t?void 0:t.dynamic)||(r.staticPrefetchBailout=!0),r.isStaticGeneration){let t=new n.DynamicServerError(u);throw r.dynamicUsageDescription=e,r.dynamicUsageStack=t.stack,t}return!1};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8898:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return StaticGenerationSearchParamsBailoutProvider}});let n=r(85),a=n._(r(9885)),o=r(3032);function StaticGenerationSearchParamsBailoutProvider(e){let{Component:t,propsForComponent:r,isStaticGeneration:n}=e;if(n){let e=(0,o.createSearchParamsBailoutProxy)();return a.default.createElement(t,{searchParams:e,...r})}return a.default.createElement(t,r)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9236:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"useReducerWithReduxDevtools",{enumerable:!0,get:function(){return a}});let n=r(9885);function useReducerWithReduxDevtoolsNoop(e,t){let[r,a]=(0,n.useReducer)(e,t);return[r,a,()=>{}]}let a=useReducerWithReduxDevtoolsNoop;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9760:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return hasBasePath}});let n=r(6364);function hasBasePath(e){return(0,n.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6945:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return normalizePathTrailingSlash}});let n=r(6923),a=r(5525),normalizePathTrailingSlash=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:r,hash:o}=(0,a.parsePath)(e);return""+(0,n.removeTrailingSlash)(t)+r+o};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4978:(e,t,r)=>{"use strict";function removeBasePath(e){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return removeBasePath}}),r(9760),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},755:(e,t)=>{"use strict";function djb2Hash(e){let t=5381;for(let r=0;r{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_DYNAMIC_NO_SSR_CODE:function(){return r},throwWithNoSSR:function(){return throwWithNoSSR}});let r="NEXT_DYNAMIC_NO_SSR_CODE";function throwWithNoSSR(){let e=Error(r);throw e.digest=r,e}},1518:(e,t)=>{"use strict";function ensureLeadingSlash(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return ensureLeadingSlash}})},8549:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return addPathPrefix}});let n=r(5525);function addPathPrefix(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:a,hash:o}=(0,n.parsePath)(e);return""+t+r+a+o}},8321:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return normalizeAppPath},normalizeRscURL:function(){return normalizeRscURL},normalizePostponedURL:function(){return normalizePostponedURL}});let n=r(1518),a=r(392);function normalizeAppPath(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,a.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function normalizeRscURL(e){return e.replace(/\.rsc($|\?)/,"$1")}function normalizePostponedURL(e){let t=new URL(e),{pathname:r}=t;return r&&r.startsWith("/_next/postponed")?(t.pathname=r.substring(16)||"/",t.toString()):e}},4448:(e,t)=>{"use strict";function handleSmoothScroll(e,t){if(void 0===t&&(t={}),t.onlyHashChange){e();return}let r=document.documentElement,n=r.style.scrollBehavior;r.style.scrollBehavior="auto",t.dontForceLayout||r.getClientRects(),e(),r.style.scrollBehavior=n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return handleSmoothScroll}})},4692:(e,t)=>{"use strict";function isBot(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isBot",{enumerable:!0,get:function(){return isBot}})},5525:(e,t)=>{"use strict";function parsePath(e){let t=e.indexOf("#"),r=e.indexOf("?"),n=r>-1&&(t<0||r-1?{pathname:e.substring(0,n?r:t),query:n?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return parsePath}})},6364:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return pathHasPrefix}});let n=r(5525);function pathHasPrefix(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,n.parsePath)(e);return r===t||r.startsWith(t+"/")}},6923:(e,t)=>{"use strict";function removeTrailingSlash(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},392:(e,t)=>{"use strict";function isGroupSegment(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isGroupSegment",{enumerable:!0,get:function(){return isGroupSegment}})},5153:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createProxy",{enumerable:!0,get:function(){return a}});let n=r(5951),a=n.createClientModuleProxy},8730:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js")},7284:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js")},9195:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DYNAMIC_ERROR_CODE:function(){return r},DynamicServerError:function(){return DynamicServerError}});let r="DYNAMIC_SERVER_USAGE";let DynamicServerError=class DynamicServerError extends Error{constructor(e){super("Dynamic server usage: "+e),this.digest=r}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8165:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js")},2236:(e,t,r)=>{"use strict";function maybePostpone(e,t){if(!e.isStaticGeneration||!e.experimental.ppr)return;let n=r(3542);"function"==typeof n.unstable_postpone&&n.unstable_postpone(t)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"maybePostpone",{enumerable:!0,get:function(){return maybePostpone}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4009:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js")},9291:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return NotFound}});let n=r(5196),a=n._(r(3542)),o={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{display:"inline-block"},h1:{display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},h2:{fontSize:14,fontWeight:400,lineHeight:"49px",margin:0}};function NotFound(){return a.default.createElement(a.default.Fragment,null,a.default.createElement("title",null,"404: This page could not be found."),a.default.createElement("div",{style:o.error},a.default.createElement("div",null,a.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}),a.default.createElement("h1",{className:"next-error-h1",style:o.h1},"404"),a.default.createElement("div",{style:o.desc},a.default.createElement("h2",{style:o.h2},"This page could not be found.")))))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5676:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js")},1263:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return createSearchParamsBailoutProxy}});let n=r(3657);function createSearchParamsBailoutProxy(){return new Proxy({},{get(e,t){"string"==typeof t&&(0,n.staticGenerationBailout)("searchParams."+t)}})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3657:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationBailout",{enumerable:!0,get:function(){return staticGenerationBailout}});let n=r(9195),a=r(2236),o=r(5319);let StaticGenBailoutError=class StaticGenBailoutError extends Error{constructor(...e){super(...e),this.code="NEXT_STATIC_GEN_BAILOUT"}};function formatErrorMessage(e,t){let{dynamic:r,link:n}=t||{};return"Page"+(r?' with `dynamic = "'+r+'"`':"")+" couldn't be rendered statically because it used `"+e+"`."+(n?" See more info here: "+n:"")}let staticGenerationBailout=(e,t)=>{let r=o.staticGenerationAsyncStorage.getStore();if(!r)return!1;if(r.forceStatic)return!0;if(r.dynamicShouldError){var l;throw new StaticGenBailoutError(formatErrorMessage(e,{...t,dynamic:null!=(l=null==t?void 0:t.dynamic)?l:"error"}))}let u=formatErrorMessage(e,{...t,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if((0,a.maybePostpone)(r,u),r.revalidate=0,(null==t?void 0:t.dynamic)||(r.staticPrefetchBailout=!0),r.isStaticGeneration){let t=new n.DynamicServerError(u);throw r.dynamicUsageDescription=e,r.dynamicUsageStack=t.stack,t}return!1};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7701:(e,t,r)=>{"use strict";let{createProxy:n}=r(5153);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js")},2564:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{renderToReadableStream:function(){return n.renderToReadableStream},decodeReply:function(){return n.decodeReply},decodeAction:function(){return n.decodeAction},decodeFormState:function(){return n.decodeFormState},AppRouter:function(){return a.default},LayoutRouter:function(){return o.default},RenderFromTemplateContext:function(){return l.default},staticGenerationAsyncStorage:function(){return u.staticGenerationAsyncStorage},requestAsyncStorage:function(){return i.requestAsyncStorage},actionAsyncStorage:function(){return s.actionAsyncStorage},staticGenerationBailout:function(){return c.staticGenerationBailout},createSearchParamsBailoutProxy:function(){return f.createSearchParamsBailoutProxy},serverHooks:function(){return p},preloadStyle:function(){return h.preloadStyle},preloadFont:function(){return h.preloadFont},preconnect:function(){return h.preconnect},taintObjectReference:function(){return _.taintObjectReference},StaticGenerationSearchParamsBailoutProvider:function(){return d.default},NotFoundBoundary:function(){return y}});let n=r(5951),a=_interop_require_default(r(8730)),o=_interop_require_default(r(8165)),l=_interop_require_default(r(5676)),u=r(5319),i=r(1877),s=r(5528),c=r(3657),d=_interop_require_default(r(7701)),f=r(1263),p=_interop_require_wildcard(r(9195)),h=r(8483),_=r(3369);function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(_getRequireWildcardCache=function(e){return e?r:t})(e)}function _interop_require_wildcard(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=_getRequireWildcardCache(t);if(r&&r.has(e))return r.get(e);var n={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var l=a?Object.getOwnPropertyDescriptor(e,o):null;l&&(l.get||l.set)?Object.defineProperty(n,o,l):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}let{NotFoundBoundary:y}=r(4009)},8483:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{preloadStyle:function(){return preloadStyle},preloadFont:function(){return preloadFont},preconnect:function(){return preconnect}});let n=_interop_require_default(r(8337));function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}function preloadStyle(e,t){let r={as:"style"};"string"==typeof t&&(r.crossOrigin=t),n.default.preload(e,r)}function preloadFont(e,t,r){let a={as:"font",type:t};"string"==typeof r&&(a.crossOrigin=r),n.default.preload(e,a)}function preconnect(e,t){n.default.preconnect(e,"string"==typeof t?{crossOrigin:t}:void 0)}},3369:(e,t,r)=>{"use strict";function notImplemented(){throw Error("Taint can only be used with the taint flag.")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{taintObjectReference:function(){return n},taintUniqueValue:function(){return a}}),r(3542);let n=notImplemented,a=notImplemented},6132:(e,t)=>{"use strict";var r;Object.defineProperty(t,"x",{enumerable:!0,get:function(){return r}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE"}(r||(r={}))},7096:(e,t,r)=>{"use strict";e.exports=r(399)},8337:(e,t,r)=>{"use strict";e.exports=r(7096).vendored["react-rsc"].ReactDOM},4656:(e,t,r)=>{"use strict";e.exports=r(7096).vendored["react-rsc"].ReactJsxRuntime},5951:(e,t,r)=>{"use strict";e.exports=r(7096).vendored["react-rsc"].ReactServerDOMWebpackServerEdge},3542:(e,t,r)=>{"use strict";e.exports=r(7096).vendored["react-rsc"].React},5082:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_QUERY_PARAM_PREFIX:function(){return r},PRERENDER_REVALIDATE_HEADER:function(){return n},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return a},NEXT_DID_POSTPONE_HEADER:function(){return o},NEXT_CACHE_TAGS_HEADER:function(){return l},NEXT_CACHE_SOFT_TAGS_HEADER:function(){return u},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return i},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return s},NEXT_CACHE_TAG_MAX_LENGTH:function(){return c},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return d},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return f},CACHE_ONE_YEAR:function(){return p},MIDDLEWARE_FILENAME:function(){return h},MIDDLEWARE_LOCATION_REGEXP:function(){return _},INSTRUMENTATION_HOOK_FILENAME:function(){return y},PAGES_DIR_ALIAS:function(){return m},DOT_NEXT_ALIAS:function(){return g},ROOT_DIR_ALIAS:function(){return b},APP_DIR_ALIAS:function(){return v},RSC_MOD_REF_PROXY_ALIAS:function(){return P},RSC_ACTION_VALIDATE_ALIAS:function(){return R},RSC_ACTION_PROXY_ALIAS:function(){return S},RSC_ACTION_ENCRYPTION_ALIAS:function(){return E},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return O},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return T},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return j},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return M},SERVER_PROPS_SSG_CONFLICT:function(){return x},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return A},SERVER_PROPS_EXPORT_ERROR:function(){return C},GSP_NO_RETURNED_VALUE:function(){return N},GSSP_NO_RETURNED_VALUE:function(){return w},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return I},GSSP_COMPONENT_MEMBER_ERROR:function(){return F},NON_STANDARD_NODE_ENV:function(){return D},SSG_FALLBACK_EXPORT_ERROR:function(){return L},ESLINT_DEFAULT_DIRS:function(){return U},ESLINT_PROMPT_VALUES:function(){return H},SERVER_RUNTIME:function(){return B},WEBPACK_LAYERS:function(){return G},WEBPACK_RESOURCE_QUERIES:function(){return W}});let r="nxtP",n="x-prerender-revalidate",a="x-prerender-revalidate-if-generated",o="x-nextjs-postponed",l="x-next-cache-tags",u="x-next-cache-soft-tags",i="x-next-revalidated-tags",s="x-next-revalidate-tag-token",c=256,d=1024,f="_N_T_",p=31536e3,h="middleware",_=`(?:src/)?${h}`,y="instrumentation",m="private-next-pages",g="private-dot-next",b="private-next-root-dir",v="private-next-app-dir",P="private-next-rsc-mod-ref-proxy",R="private-next-rsc-action-validate",S="private-next-rsc-action-proxy",E="private-next-rsc-action-encryption",O="private-next-rsc-action-client-wrapper",T="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",j="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",M="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",x="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",A="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",C="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",N="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",w="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",I="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",F="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",D='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',L="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",U=["app","pages","components","lib","src"],H=[{title:"Strict",recommended:!0,config:{extends:"next/core-web-vitals"}},{title:"Base",config:{extends:"next"}},{title:"Cancel",config:null}],B={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},k={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",appMetadataRoute:"app-metadata-route",appRouteHandler:"app-route-handler"},G={...k,GROUP:{server:[k.reactServerComponents,k.actionBrowser,k.appMetadataRoute,k.appRouteHandler],nonClientServerTarget:[k.middleware,k.api],app:[k.reactServerComponents,k.actionBrowser,k.appMetadataRoute,k.appRouteHandler,k.serverSideRendering,k.appPagesBrowser]}},W={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},2290:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentParam",{enumerable:!0,get:function(){return getSegmentParam}});let n=r(4265);function getSegmentParam(e){let t=n.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t));return(t&&(e=e.slice(t.length)),e.startsWith("[[...")&&e.endsWith("]]"))?{type:"optional-catchall",param:e.slice(5,-2)}:e.startsWith("[...")&&e.endsWith("]")?{type:"catchall",param:e.slice(4,-1)}:e.startsWith("[")&&e.endsWith("]")?{type:"dynamic",param:e.slice(1,-1)}:null}},4265:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return a},isInterceptionRouteAppPath:function(){return isInterceptionRouteAppPath},extractInterceptionRouteInformation:function(){return extractInterceptionRouteInformation}});let n=r(8321),a=["(..)(..)","(.)","(..)","(...)"];function isInterceptionRouteAppPath(e){return void 0!==e.split("/").find(e=>a.find(t=>e.startsWith(t)))}function extractInterceptionRouteInformation(e){let t,r,o;for(let n of e.split("/"))if(r=a.find(e=>n.startsWith(e))){[t,o]=e.split(r,2);break}if(!t||!r||!o)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":o="/"===t?`/${o}`:t+"/"+o;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);o=t.split("/").slice(0,-1).concat(o).join("/");break;case"(...)":o="/"+o;break;case"(..)(..)":let l=t.split("/");if(l.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);o=l.slice(0,-2).concat(o).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:o}}},316:(e,t,r)=>{"use strict";e.exports=r(399)},2428:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.AppRouterContext},1736:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.HooksClientContext},5753:(e,t,r)=>{"use strict";e.exports=r(316).vendored.contexts.ServerInsertedHtml},8908:(e,t,r)=>{"use strict";e.exports=r(316).vendored["react-ssr"].ReactDOM},2623:(e,t,r)=>{"use strict";e.exports=r(316).vendored["react-ssr"].ReactServerDOMWebpackClientEdge},9885:(e,t,r)=>{"use strict";e.exports=r(316).vendored["react-ssr"].React},3592:(e,t,r)=>{"use strict";function _class_private_field_loose_base(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}r.r(t),r.d(t,{_:()=>_class_private_field_loose_base,_class_private_field_loose_base:()=>_class_private_field_loose_base})},4941:(e,t,r)=>{"use strict";r.r(t),r.d(t,{_:()=>_class_private_field_loose_key,_class_private_field_loose_key:()=>_class_private_field_loose_key});var n=0;function _class_private_field_loose_key(e){return"__private_"+n+++"_"+e}},85:(e,t,r)=>{"use strict";function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:()=>_interop_require_default,_interop_require_default:()=>_interop_require_default})},8425:(e,t,r)=>{"use strict";function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(_getRequireWildcardCache=function(e){return e?r:t})(e)}function _interop_require_wildcard(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=_getRequireWildcardCache(t);if(r&&r.has(e))return r.get(e);var n={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var l=a?Object.getOwnPropertyDescriptor(e,o):null;l&&(l.get||l.set)?Object.defineProperty(n,o,l):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}r.r(t),r.d(t,{_:()=>_interop_require_wildcard,_interop_require_wildcard:()=>_interop_require_wildcard})},5196:(e,t,r)=>{"use strict";function _interop_require_default(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:()=>_interop_require_default,_interop_require_default:()=>_interop_require_default})}}; \ No newline at end of file diff --git a/.next/server/chunks/969.js b/.next/server/chunks/969.js new file mode 100644 index 0000000..bee558c --- /dev/null +++ b/.next/server/chunks/969.js @@ -0,0 +1 @@ +exports.id=969,exports.ids=[969],exports.modules={265:e=>{e.exports={style:{fontFamily:"'__Inter_e66fe9', '__Inter_Fallback_e66fe9'",fontStyle:"normal"},className:"__className_e66fe9"}},8928:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return u}});let n=r(1870),o=r(9847);function u(e,t){return(0,o.normalizePathTrailingSlash)((0,n.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3664:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"callServer",{enumerable:!0,get:function(){return o}});let n=r(2583);async function o(e,t){let r=(0,n.getServerActionDispatcher)();if(!r)throw Error("Invariant: missing action dispatcher.");return new Promise((n,o)=>{r({actionId:e,actionArgs:t,resolve:n,reject:o})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3371:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AppRouterAnnouncer",{enumerable:!0,get:function(){return l}});let n=r(3729),o=r(1202),u="next-route-announcer";function l(e){let{tree:t}=e,[r,l]=(0,n.useState)(null);(0,n.useEffect)(()=>(l(function(){var e;let t=document.getElementsByName(u)[0];if(null==t?void 0:null==(e=t.shadowRoot)?void 0:e.childNodes[0])return t.shadowRoot.childNodes[0];{let e=document.createElement(u);e.style.cssText="position:absolute";let t=document.createElement("div");return t.ariaLive="assertive",t.id="__next-route-announcer__",t.role="alert",t.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal",e.attachShadow({mode:"open"}).appendChild(t),document.body.appendChild(e),t}}()),()=>{let e=document.getElementsByTagName(u)[0];(null==e?void 0:e.isConnected)&&document.body.removeChild(e)}),[]);let[a,i]=(0,n.useState)(""),s=(0,n.useRef)();return(0,n.useEffect)(()=>{let e="";if(document.title)e=document.title;else{let t=document.querySelector("h1");t&&(e=t.innerText||t.textContent||"")}void 0!==s.current&&s.current!==e&&i(e),s.current=e},[t]),r?(0,o.createPortal)(a,r):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5048:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RSC_HEADER:function(){return r},ACTION:function(){return n},NEXT_ROUTER_STATE_TREE:function(){return o},NEXT_ROUTER_PREFETCH_HEADER:function(){return u},NEXT_URL:function(){return l},RSC_CONTENT_TYPE_HEADER:function(){return a},RSC_VARY_HEADER:function(){return i},FLIGHT_PARAMETERS:function(){return s},NEXT_RSC_UNION_QUERY:function(){return c},NEXT_DID_POSTPONE_HEADER:function(){return d}});let r="RSC",n="Next-Action",o="Next-Router-State-Tree",u="Next-Router-Prefetch",l="Next-Url",a="text/x-component",i=r+", "+o+", "+u+", "+l,s=[[r],[o],[u]],c="_rsc",d="x-nextjs-postponed";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2583:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getServerActionDispatcher:function(){return O},urlToUrlWithoutFlightMarker:function(){return j},createEmptyCacheNode:function(){return T},default:function(){return x}});let n=r(7824)._(r(3729)),o=r(6860),u=r(8085),l=r(7475),a=r(8486),i=r(4954),s=r(6840),c=r(7995),d=r(6338),f=r(8928),p=r(3371),h=r(7046),y=r(7550),_=r(5897),b=r(5048),g=r(2874),m=r(6411),v=null,P=null;function O(){return P}let R={};function j(e){let t=new URL(e,location.origin);return t.searchParams.delete(b.NEXT_RSC_UNION_QUERY),t}function E(e){return e.origin!==window.location.origin}function S(e){let{appRouterState:t,sync:r}=e;return(0,n.useInsertionEffect)(()=>{let{tree:e,pushRef:n,canonicalUrl:o}=t,u={__NA:!0,__PRIVATE_NEXTJS_INTERNALS_TREE:e};n.pendingPush&&(0,l.createHrefFromUrl)(new URL(window.location.href))!==o?(n.pendingPush=!1,window.history.pushState(u,"",o)):window.history.replaceState(u,"",o),r(t)},[t,r]),null}let T=()=>({status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map});function M(e){let{buildId:t,initialHead:r,initialTree:l,initialCanonicalUrl:s,initialSeedData:b,assetPrefix:O}=e,j=(0,n.useMemo)(()=>(0,c.createInitialRouterState)({buildId:t,initialSeedData:b,initialCanonicalUrl:s,initialTree:l,initialParallelRoutes:v,isServer:!0,location:null,initialHead:r}),[t,b,s,l,r]),[T,M,x]=(0,i.useReducerWithReduxDevtools)(j);(0,n.useEffect)(()=>{v=null},[]);let{canonicalUrl:C}=(0,i.useUnwrapState)(T),{searchParams:A,pathname:w}=(0,n.useMemo)(()=>{let e=new URL(C,"http://n");return{searchParams:e.searchParams,pathname:(0,m.hasBasePath)(e.pathname)?(0,g.removeBasePath)(e.pathname):e.pathname}},[C]),N=(0,n.useCallback)((e,t,r)=>{(0,n.startTransition)(()=>{M({type:u.ACTION_SERVER_PATCH,flightData:t,previousTree:e,overrideCanonicalUrl:r})})},[M]),I=(0,n.useCallback)((e,t,r)=>{let n=new URL((0,f.addBasePath)(e),location.href);return M({type:u.ACTION_NAVIGATE,url:n,isExternalUrl:E(n),locationSearch:location.search,shouldScroll:null==r||r,navigateType:t})},[M]);P=(0,n.useCallback)(e=>{(0,n.startTransition)(()=>{M({...e,type:u.ACTION_SERVER_ACTION})})},[M]);let U=(0,n.useMemo)(()=>({back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(e,t)=>{if((0,d.isBot)(window.navigator.userAgent))return;let r=new URL((0,f.addBasePath)(e),window.location.href);E(r)||(0,n.startTransition)(()=>{var e;M({type:u.ACTION_PREFETCH,url:r,kind:null!=(e=null==t?void 0:t.kind)?e:u.PrefetchKind.FULL})})},replace:(e,t)=>{void 0===t&&(t={}),(0,n.startTransition)(()=>{var r;I(e,"replace",null==(r=t.scroll)||r)})},push:(e,t)=>{void 0===t&&(t={}),(0,n.startTransition)(()=>{var r;I(e,"push",null==(r=t.scroll)||r)})},refresh:()=>{(0,n.startTransition)(()=>{M({type:u.ACTION_REFRESH,origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}}),[M,I]);(0,n.useEffect)(()=>{window.next&&(window.next.router=U)},[U]),(0,n.useEffect)(()=>{function e(e){var t;e.persisted&&(null==(t=window.history.state)?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE)&&M({type:u.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE})}return window.addEventListener("pageshow",e),()=>{window.removeEventListener("pageshow",e)}},[M]);let{pushRef:D}=(0,i.useUnwrapState)(T);if(D.mpaNavigation){if(R.pendingMpaPath!==C){let e=window.location;D.pendingPush?e.assign(C):e.replace(C),R.pendingMpaPath=C}(0,n.use)((0,_.createInfinitePromise)())}(0,n.useEffect)(()=>{window.history.pushState.bind(window.history),window.history.replaceState.bind(window.history);let e=e=>{let{state:t}=e;if(t){if(!t.__NA){window.location.reload();return}(0,n.startTransition)(()=>{M({type:u.ACTION_RESTORE,url:new URL(window.location.href),tree:t.__PRIVATE_NEXTJS_INTERNALS_TREE})})}};return window.addEventListener("popstate",e),()=>{window.removeEventListener("popstate",e)}},[M]);let{cache:F,tree:L,nextUrl:H,focusAndScrollRef:k}=(0,i.useUnwrapState)(T),W=(0,n.useMemo)(()=>(0,y.findHeadInCache)(F,L[1]),[F,L]),B=n.default.createElement(h.RedirectBoundary,null,W,F.subTreeData,n.default.createElement(p.AppRouterAnnouncer,{tree:L}));return n.default.createElement(n.default.Fragment,null,n.default.createElement(S,{appRouterState:(0,i.useUnwrapState)(T),sync:x}),n.default.createElement(a.PathnameContext.Provider,{value:w},n.default.createElement(a.SearchParamsContext.Provider,{value:A},n.default.createElement(o.GlobalLayoutRouterContext.Provider,{value:{buildId:t,changeByServerResponse:N,tree:L,focusAndScrollRef:k,nextUrl:H}},n.default.createElement(o.AppRouterContext.Provider,{value:U},n.default.createElement(o.LayoutRouterContext.Provider,{value:{childNodes:F.parallelRoutes,tree:L,url:C}},B))))))}function x(e){let{globalErrorComponent:t,...r}=e;return n.default.createElement(s.ErrorBoundary,{errorComponent:t},n.default.createElement(M,r))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"bailoutToClientRendering",{enumerable:!0,get:function(){return u}});let n=r(1462),o=r(4749);function u(){let e=o.staticGenerationAsyncStorage.getStore();(null==e||!e.forceStatic)&&(null==e?void 0:e.isStaticGeneration)&&(0,n.throwWithNoSSR)()}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8446:(e,t,r)=>{"use strict";function n(e){}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"clientHookInServerComponentError",{enumerable:!0,get:function(){return n}}),r(9694),r(3729),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6840:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ErrorBoundaryHandler:function(){return a},GlobalError:function(){return i},default:function(){return s},ErrorBoundary:function(){return c}});let n=r(9694)._(r(3729)),o=r(4767),u={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function l(e){let{error:t}=e;if("function"==typeof fetch.__nextGetStaticStore){var r;let e=null==(r=fetch.__nextGetStaticStore())?void 0:r.getStore();if((null==e?void 0:e.isRevalidate)||(null==e?void 0:e.isStaticGeneration))throw console.error(t),t}return null}class a extends n.default.Component{static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.error?{error:null,previousPathname:e.pathname}:{error:t.error,previousPathname:e.pathname}}render(){return this.state.error?n.default.createElement(n.default.Fragment,null,n.default.createElement(l,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,n.default.createElement(this.props.errorComponent,{error:this.state.error,reset:this.reset})):this.props.children}constructor(e){super(e),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}}function i(e){let{error:t}=e,r=null==t?void 0:t.digest;return n.default.createElement("html",{id:"__next_error__"},n.default.createElement("head",null),n.default.createElement("body",null,n.default.createElement(l,{error:t}),n.default.createElement("div",{style:u.error},n.default.createElement("div",null,n.default.createElement("h2",{style:u.text},"Application error: a "+(r?"server":"client")+"-side exception has occurred (see the "+(r?"server logs":"browser console")+" for more information)."),r?n.default.createElement("p",{style:u.text},"Digest: "+r):null))))}let s=i;function c(e){let{errorComponent:t,errorStyles:r,errorScripts:u,children:l}=e,i=(0,o.usePathname)();return t?n.default.createElement(a,{pathname:i,errorComponent:t,errorStyles:r,errorScripts:u},l):n.default.createElement(n.default.Fragment,null,l)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3082:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DYNAMIC_ERROR_CODE:function(){return r},DynamicServerError:function(){return n}});let r="DYNAMIC_SERVER_USAGE";class n extends Error{constructor(e){super("Dynamic server usage: "+e),this.digest=r}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5897:(e,t)=>{"use strict";let r;function n(){return r||(r=new Promise(()=>{})),r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInfinitePromise",{enumerable:!0,get:function(){return n}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8771:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return v}}),r(9694);let n=r(7824)._(r(3729));r(1202);let o=r(6860),u=r(7013),l=r(5897),a=r(6840),i=r(4287),s=r(1586),c=r(7046),d=r(3225),f=r(3717),p=r(5325),h=["bottom","height","left","right","top","width","x","y"];function y(e,t){let r=e.getBoundingClientRect();return r.top>=0&&r.top<=t}class _ extends n.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:t}=this.props;if(e.apply){if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>t.every((t,r)=>(0,i.matchSegment)(t,e[r]))))return;let r=null,n=e.hashFragment;if(n&&(r=function(e){var t;return"top"===e?document.body:null!=(t=document.getElementById(e))?t:document.getElementsByName(e)[0]}(n)),!r&&(r=null),!(r instanceof Element))return;for(;!(r instanceof HTMLElement)||function(e){if(["sticky","fixed"].includes(getComputedStyle(e).position))return!0;let t=e.getBoundingClientRect();return h.every(e=>0===t[e])}(r);){if(null===r.nextElementSibling)return;r=r.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,s.handleSmoothScroll)(()=>{if(n){r.scrollIntoView();return}let e=document.documentElement,t=e.clientHeight;!y(r,t)&&(e.scrollTop=0,y(r,t)||r.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:e.onlyHashChange}),e.onlyHashChange=!1,r.focus()}}}}function b(e){let{segmentPath:t,children:r}=e,u=(0,n.useContext)(o.GlobalLayoutRouterContext);if(!u)throw Error("invariant global layout router not mounted");return n.default.createElement(_,{segmentPath:t,focusAndScrollRef:u.focusAndScrollRef},r)}function g(e){let{parallelRouterKey:t,url:r,childNodes:a,segmentPath:s,tree:c,cacheKey:d}=e,f=(0,n.useContext)(o.GlobalLayoutRouterContext);if(!f)throw Error("invariant global layout router not mounted");let{buildId:p,changeByServerResponse:h,tree:y}=f,_=a.get(d);if(!_||_.status===o.CacheStates.LAZY_INITIALIZED){let e=function e(t,r){if(t){let[n,o]=t,u=2===t.length;if((0,i.matchSegment)(r[0],n)&&r[1].hasOwnProperty(o)){if(u){let t=e(void 0,r[1][o]);return[r[0],{...r[1],[o]:[t[0],t[1],t[2],"refetch"]}]}return[r[0],{...r[1],[o]:e(t.slice(2),r[1][o])}]}}return r}(["",...s],y);_={status:o.CacheStates.DATA_FETCH,data:(0,u.fetchServerResponse)(new URL(r,location.origin),e,f.nextUrl,p),subTreeData:null,head:_&&_.status===o.CacheStates.LAZY_INITIALIZED?_.head:void 0,parallelRoutes:_&&_.status===o.CacheStates.LAZY_INITIALIZED?_.parallelRoutes:new Map},a.set(d,_)}if(!_)throw Error("Child node should always exist");if(_.subTreeData&&_.data)throw Error("Child node should not have both subTreeData and data");if(_.data){let[e,t]=(0,n.use)(_.data);_.data=null,setTimeout(()=>{(0,n.startTransition)(()=>{h(y,e,t)})}),(0,n.use)((0,l.createInfinitePromise)())}return _.subTreeData||(0,n.use)((0,l.createInfinitePromise)()),n.default.createElement(o.LayoutRouterContext.Provider,{value:{tree:c[1][t],childNodes:_.parallelRoutes,url:r}},_.subTreeData)}function m(e){let{children:t,loading:r,loadingStyles:o,loadingScripts:u,hasLoading:l}=e;return l?n.default.createElement(n.Suspense,{fallback:n.default.createElement(n.default.Fragment,null,o,u,r)},t):n.default.createElement(n.default.Fragment,null,t)}function v(e){let{parallelRouterKey:t,segmentPath:r,error:u,errorStyles:l,errorScripts:i,templateStyles:s,templateScripts:h,loading:y,loadingStyles:_,loadingScripts:v,hasLoading:P,template:O,notFound:R,notFoundStyles:j,styles:E}=e,S=(0,n.useContext)(o.LayoutRouterContext);if(!S)throw Error("invariant expected layout router to be mounted");let{childNodes:T,tree:M,url:x}=S,C=T.get(t);C||(C=new Map,T.set(t,C));let A=M[1][t][0],w=(0,f.getSegmentValue)(A),N=[A];return n.default.createElement(n.default.Fragment,null,E,N.map(e=>{let E=(0,f.getSegmentValue)(e),S=(0,p.createRouterCacheKey)(e);return n.default.createElement(o.TemplateContext.Provider,{key:(0,p.createRouterCacheKey)(e,!0),value:n.default.createElement(b,{segmentPath:r},n.default.createElement(a.ErrorBoundary,{errorComponent:u,errorStyles:l,errorScripts:i},n.default.createElement(m,{hasLoading:P,loading:y,loadingStyles:_,loadingScripts:v},n.default.createElement(d.NotFoundBoundary,{notFound:R,notFoundStyles:j},n.default.createElement(c.RedirectBoundary,null,n.default.createElement(g,{parallelRouterKey:t,url:x,tree:M,childNodes:C,segmentPath:r,cacheKey:S,isActive:w===E}))))))},s,h,O)}))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4287:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{matchSegment:function(){return o},canSegmentBeOverridden:function(){return u}});let n=r(4269),o=(e,t)=>"string"==typeof e?"string"==typeof t&&e===t:"string"!=typeof t&&e[0]===t[0]&&e[1]===t[1],u=(e,t)=>{var r;return!Array.isArray(e)&&!!Array.isArray(t)&&(null==(r=(0,n.getSegmentParam)(e))?void 0:r.param)===t[0]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4767:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ReadonlyURLSearchParams:function(){return p},useSearchParams:function(){return h},usePathname:function(){return y},ServerInsertedHTMLContext:function(){return i.ServerInsertedHTMLContext},useServerInsertedHTML:function(){return i.useServerInsertedHTML},useRouter:function(){return _},useParams:function(){return b},useSelectedLayoutSegments:function(){return g},useSelectedLayoutSegment:function(){return m},redirect:function(){return s.redirect},permanentRedirect:function(){return s.permanentRedirect},RedirectType:function(){return s.RedirectType},notFound:function(){return c.notFound}});let n=r(3729),o=r(6860),u=r(8486),l=r(8446),a=r(3717),i=r(9505),s=r(2792),c=r(226),d=Symbol("internal for urlsearchparams readonly");function f(){return Error("ReadonlyURLSearchParams cannot be modified")}class p{[Symbol.iterator](){return this[d][Symbol.iterator]()}append(){throw f()}delete(){throw f()}set(){throw f()}sort(){throw f()}constructor(e){this[d]=e,this.entries=e.entries.bind(e),this.forEach=e.forEach.bind(e),this.get=e.get.bind(e),this.getAll=e.getAll.bind(e),this.has=e.has.bind(e),this.keys=e.keys.bind(e),this.values=e.values.bind(e),this.toString=e.toString.bind(e),this.size=e.size}}function h(){(0,l.clientHookInServerComponentError)("useSearchParams");let e=(0,n.useContext)(u.SearchParamsContext),t=(0,n.useMemo)(()=>e?new p(e):null,[e]);{let{bailoutToClientRendering:e}=r(4586);e()}return t}function y(){return(0,l.clientHookInServerComponentError)("usePathname"),(0,n.useContext)(u.PathnameContext)}function _(){(0,l.clientHookInServerComponentError)("useRouter");let e=(0,n.useContext)(o.AppRouterContext);if(null===e)throw Error("invariant expected app router to be mounted");return e}function b(){(0,l.clientHookInServerComponentError)("useParams");let e=(0,n.useContext)(o.GlobalLayoutRouterContext),t=(0,n.useContext)(u.PathParamsContext);return(0,n.useMemo)(()=>(null==e?void 0:e.tree)?function e(t,r){for(let n of(void 0===r&&(r={}),Object.values(t[1]))){let t=n[0],o=Array.isArray(t),u=o?t[1]:t;!u||u.startsWith("__PAGE__")||(o&&("c"===t[2]||"oc"===t[2])?r[t[0]]=t[1].split("/"):o&&(r[t[0]]=t[1]),r=e(n,r))}return r}(e.tree):t,[null==e?void 0:e.tree,t])}function g(e){void 0===e&&(e="children"),(0,l.clientHookInServerComponentError)("useSelectedLayoutSegments");let{tree:t}=(0,n.useContext)(o.LayoutRouterContext);return function e(t,r,n,o){let u;if(void 0===n&&(n=!0),void 0===o&&(o=[]),n)u=t[1][r];else{var l;let e=t[1];u=null!=(l=e.children)?l:Object.values(e)[0]}if(!u)return o;let i=u[0],s=(0,a.getSegmentValue)(i);return!s||s.startsWith("__PAGE__")?o:(o.push(s),e(u,r,!1,o))}(t,e)}function m(e){void 0===e&&(e="children"),(0,l.clientHookInServerComponentError)("useSelectedLayoutSegment");let t=g(e);return 0===t.length?null:t[0]}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3225:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NotFoundBoundary",{enumerable:!0,get:function(){return l}});let n=r(9694)._(r(3729)),o=r(4767);class u extends n.default.Component{static getDerivedStateFromError(e){if((null==e?void 0:e.digest)==="NEXT_NOT_FOUND")return{notFoundTriggered:!0};throw e}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.notFoundTriggered?{notFoundTriggered:!1,previousPathname:e.pathname}:{notFoundTriggered:t.notFoundTriggered,previousPathname:e.pathname}}render(){return this.state.notFoundTriggered?n.default.createElement(n.default.Fragment,null,n.default.createElement("meta",{name:"robots",content:"noindex"}),!1,this.props.notFoundStyles,this.props.notFound):this.props.children}constructor(e){super(e),this.state={notFoundTriggered:!!e.asNotFound,previousPathname:e.pathname}}}function l(e){let{notFound:t,notFoundStyles:r,asNotFound:l,children:a}=e,i=(0,o.usePathname)();return t?n.default.createElement(u,{pathname:i,notFound:t,notFoundStyles:r,asNotFound:l},a):n.default.createElement(n.default.Fragment,null,a)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},226:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{notFound:function(){return n},isNotFoundError:function(){return o}});let r="NEXT_NOT_FOUND";function n(){let e=Error(r);throw e.digest=r,e}function o(e){return(null==e?void 0:e.digest)===r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2051:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PromiseQueue",{enumerable:!0,get:function(){return s}});let n=r(9996),o=r(7074);var u=o._("_maxConcurrency"),l=o._("_runningCount"),a=o._("_queue"),i=o._("_processNext");class s{enqueue(e){let t,r;let o=new Promise((e,n)=>{t=e,r=n}),u=async()=>{try{n._(this,l)[l]++;let r=await e();t(r)}catch(e){r(e)}finally{n._(this,l)[l]--,n._(this,i)[i]()}};return n._(this,a)[a].push({promiseFn:o,task:u}),n._(this,i)[i](),o}bump(e){let t=n._(this,a)[a].findIndex(t=>t.promiseFn===e);if(t>-1){let e=n._(this,a)[a].splice(t,1)[0];n._(this,a)[a].unshift(e),n._(this,i)[i](!0)}}constructor(e=5){Object.defineProperty(this,i,{value:c}),Object.defineProperty(this,u,{writable:!0,value:void 0}),Object.defineProperty(this,l,{writable:!0,value:void 0}),Object.defineProperty(this,a,{writable:!0,value:void 0}),n._(this,u)[u]=e,n._(this,l)[l]=0,n._(this,a)[a]=[]}}function c(e){if(void 0===e&&(e=!1),(n._(this,l)[l]0){var t;null==(t=n._(this,a)[a].shift())||t.task()}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7046:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectErrorBoundary:function(){return a},RedirectBoundary:function(){return i}});let n=r(7824)._(r(3729)),o=r(4767),u=r(2792);function l(e){let{redirect:t,reset:r,redirectType:l}=e,a=(0,o.useRouter)();return(0,n.useEffect)(()=>{n.default.startTransition(()=>{l===u.RedirectType.push?a.push(t,{}):a.replace(t,{}),r()})},[t,l,r,a]),null}class a extends n.default.Component{static getDerivedStateFromError(e){if((0,u.isRedirectError)(e))return{redirect:(0,u.getURLFromRedirectError)(e),redirectType:(0,u.getRedirectTypeFromError)(e)};throw e}render(){let{redirect:e,redirectType:t}=this.state;return null!==e&&null!==t?n.default.createElement(l,{redirect:e,redirectType:t,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(e){super(e),this.state={redirect:null,redirectType:null}}}function i(e){let{children:t}=e,r=(0,o.useRouter)();return n.default.createElement(a,{router:r},t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7761:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RedirectStatusCode",{enumerable:!0,get:function(){return r}}),function(e){e[e.SeeOther=303]="SeeOther",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect"}(r||(r={})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2792:(e,t,r)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectType:function(){return n},getRedirectError:function(){return i},redirect:function(){return s},permanentRedirect:function(){return c},isRedirectError:function(){return d},getURLFromRedirectError:function(){return f},getRedirectTypeFromError:function(){return p},getRedirectStatusCodeFromError:function(){return h}});let o=r(5403),u=r(7849),l=r(7761),a="NEXT_REDIRECT";function i(e,t,r){void 0===r&&(r=l.RedirectStatusCode.TemporaryRedirect);let n=Error(a);n.digest=a+";"+t+";"+e+";"+r+";";let u=o.requestAsyncStorage.getStore();return u&&(n.mutableCookies=u.mutableCookies),n}function s(e,t){void 0===t&&(t="replace");let r=u.actionAsyncStorage.getStore();throw i(e,t,(null==r?void 0:r.isAction)?l.RedirectStatusCode.SeeOther:l.RedirectStatusCode.TemporaryRedirect)}function c(e,t){void 0===t&&(t="replace");let r=u.actionAsyncStorage.getStore();throw i(e,t,(null==r?void 0:r.isAction)?l.RedirectStatusCode.SeeOther:l.RedirectStatusCode.PermanentRedirect)}function d(e){if("string"!=typeof(null==e?void 0:e.digest))return!1;let[t,r,n,o]=e.digest.split(";",4),u=Number(o);return t===a&&("replace"===r||"push"===r)&&"string"==typeof n&&!isNaN(u)&&u in l.RedirectStatusCode}function f(e){return d(e)?e.digest.split(";",3)[2]:null}function p(e){if(!d(e))throw Error("Not a redirect error");return e.digest.split(";",2)[1]}function h(e){if(!d(e))throw Error("Not a redirect error");return Number(e.digest.split(";",4)[3])}(function(e){e.push="push",e.replace="replace"})(n||(n={})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9295:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return u}});let n=r(7824)._(r(3729)),o=r(6860);function u(){let e=(0,n.useContext)(o.TemplateContext);return n.default.createElement(n.default.Fragment,null,e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9543:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyFlightData",{enumerable:!0,get:function(){return l}});let n=r(6860),o=r(7234),u=r(6408);function l(e,t,r,l){void 0===l&&(l=!1);let[a,i,s]=r.slice(-3);if(null===i)return!1;if(3===r.length){let r=i[2];t.status=n.CacheStates.READY,t.subTreeData=r,(0,o.fillLazyItemsTillLeafWithHead)(t,e,a,i,s,l)}else t.status=n.CacheStates.READY,t.subTreeData=e.subTreeData,t.parallelRoutes=new Map(e.parallelRoutes),(0,u.fillCacheWithNewSubTreeData)(t,e,r,l);return!0}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1697:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return function e(t,r,u){let l;let[a,i,,,s]=r;if(1===t.length)return o(r,u);let[c,d]=t;if(!(0,n.matchSegment)(c,a))return null;if(2===t.length)l=o(i[d],u);else if(null===(l=e(t.slice(2),i[d],u)))return null;let f=[t[0],{...i,[d]:l}];return s&&(f[4]=!0),f}}});let n=r(4287);function o(e,t){let[r,u]=e,[l,a]=t;if("__DEFAULT__"===l&&"__DEFAULT__"!==r)return e;if((0,n.matchSegment)(r,l)){let t={};for(let e in u)void 0!==a[e]?t[e]=o(u[e],a[e]):t[e]=u[e];for(let e in a)t[e]||(t[e]=a[e]);let n=[r,t];return e[2]&&(n[2]=e[2]),e[3]&&(n[3]=e[3]),e[4]&&(n[4]=e[4]),n}return t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5684:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{extractPathFromFlightRouterState:function(){return s},computeChangedPath:function(){return c}});let n=r(5767),o=r(9457),u=r(4287),l=e=>"/"===e[0]?e.slice(1):e,a=e=>"string"==typeof e?e:e[1];function i(e){return e.reduce((e,t)=>""===(t=l(t))||(0,o.isGroupSegment)(t)?e:e+"/"+t,"")||"/"}function s(e){var t;let r=Array.isArray(e[0])?e[0][1]:e[0];if("__DEFAULT__"===r||n.INTERCEPTION_ROUTE_MARKERS.some(e=>r.startsWith(e)))return;if(r.startsWith("__PAGE__"))return"";let o=[r],u=null!=(t=e[1])?t:{},l=u.children?s(u.children):void 0;if(void 0!==l)o.push(l);else for(let[e,t]of Object.entries(u)){if("children"===e)continue;let r=s(t);void 0!==r&&o.push(r)}return i(o)}function c(e,t){let r=function e(t,r){let[o,l]=t,[i,c]=r,d=a(o),f=a(i);if(n.INTERCEPTION_ROUTE_MARKERS.some(e=>d.startsWith(e)||f.startsWith(e)))return"";if(!(0,u.matchSegment)(o,i)){var p;return null!=(p=s(r))?p:""}for(let t in l)if(c[t]){let r=e(l[t],c[t]);if(null!==r)return a(i)+"/"+r}return null}(e,t);return null==r||"/"===r?r:i(r.split("/"))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7475:(e,t)=>{"use strict";function r(e,t){return void 0===t&&(t=!0),e.pathname+e.search+(t?e.hash:"")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createHrefFromUrl",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7995:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInitialRouterState",{enumerable:!0,get:function(){return a}});let n=r(6860),o=r(7475),u=r(7234),l=r(5684);function a(e){var t;let{buildId:r,initialTree:a,initialSeedData:i,initialCanonicalUrl:s,initialParallelRoutes:c,isServer:d,location:f,initialHead:p}=e,h=i[2],y={status:n.CacheStates.READY,data:null,subTreeData:h,parallelRoutes:d?new Map:c};return(null===c||0===c.size)&&(0,u.fillLazyItemsTillLeafWithHead)(y,void 0,a,i,p),{buildId:r,tree:a,cache:y,prefetchCache:new Map,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:f?(0,o.createHrefFromUrl)(f):s,nextUrl:null!=(t=(0,l.extractPathFromFlightRouterState)(a)||(null==f?void 0:f.pathname))?t:null}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5325:(e,t)=>{"use strict";function r(e,t){return void 0===t&&(t=!1),Array.isArray(e)?(e[0]+"|"+e[1]+"|"+e[2]).toLowerCase():t&&e.startsWith("__PAGE__")?"__PAGE__":e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRouterCacheKey",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7013:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fetchServerResponse",{enumerable:!0,get:function(){return c}});let n=r(5048),o=r(2583),u=r(3664),l=r(8085),a=r(5344),{createFromFetch:i}=r(2228);function s(e){return[(0,o.urlToUrlWithoutFlightMarker)(e).toString(),void 0]}async function c(e,t,r,c,d){let f={[n.RSC_HEADER]:"1",[n.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(t))};d===l.PrefetchKind.AUTO&&(f[n.NEXT_ROUTER_PREFETCH_HEADER]="1"),r&&(f[n.NEXT_URL]=r);let p=(0,a.hexHash)([f[n.NEXT_ROUTER_PREFETCH_HEADER]||"0",f[n.NEXT_ROUTER_STATE_TREE],f[n.NEXT_URL]].join(","));try{let t=new URL(e);t.searchParams.set(n.NEXT_RSC_UNION_QUERY,p);let r=await fetch(t,{credentials:"same-origin",headers:f}),l=(0,o.urlToUrlWithoutFlightMarker)(r.url),a=r.redirected?l:void 0,d=r.headers.get("content-type")||"",h=!!r.headers.get(n.NEXT_DID_POSTPONE_HEADER);if(d!==n.RSC_CONTENT_TYPE_HEADER||!r.ok)return e.hash&&(l.hash=e.hash),s(l.toString());let[y,_]=await i(Promise.resolve(r),{callServer:u.callServer});if(c!==y)return s(r.url);return[_,a,h]}catch(t){return console.error("Failed to fetch RSC payload for "+e+". Falling back to browser navigation.",t),[e.toString(),void 0]}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7676:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithDataProperty",{enumerable:!0,get:function(){return function e(t,r,u,l){let a=u.length<=2,[i,s]=u,c=(0,o.createRouterCacheKey)(s),d=r.parallelRoutes.get(i),f=t.parallelRoutes.get(i);f&&f!==d||(f=new Map(d),t.parallelRoutes.set(i,f));let p=null==d?void 0:d.get(c),h=f.get(c);if(a){h&&h.data&&h!==p||f.set(c,{status:n.CacheStates.DATA_FETCH,data:l(),subTreeData:null,parallelRoutes:new Map});return}if(!h||!p){h||f.set(c,{status:n.CacheStates.DATA_FETCH,data:l(),subTreeData:null,parallelRoutes:new Map});return}return h===p&&(h={status:h.status,data:h.data,subTreeData:h.subTreeData,parallelRoutes:new Map(h.parallelRoutes)},f.set(c,h)),e(h,p,u.slice(2),l)}}});let n=r(6860),o=r(5325);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6408:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return function e(t,r,a,i){let s=a.length<=5,[c,d]=a,f=(0,l.createRouterCacheKey)(d),p=r.parallelRoutes.get(c);if(!p)return;let h=t.parallelRoutes.get(c);h&&h!==p||(h=new Map(p),t.parallelRoutes.set(c,h));let y=p.get(f),_=h.get(f);if(s){if(!_||!_.data||_===y){let e=a[3],t=e[2];_={status:n.CacheStates.READY,data:null,subTreeData:t,parallelRoutes:y?new Map(y.parallelRoutes):new Map},y&&(0,o.invalidateCacheByRouterState)(_,y,a[2]),(0,u.fillLazyItemsTillLeafWithHead)(_,y,a[2],e,a[4],i),h.set(f,_)}return}_&&y&&(_===y&&(_={status:_.status,data:_.data,subTreeData:_.subTreeData,parallelRoutes:new Map(_.parallelRoutes)},h.set(f,_)),e(_,y,a.slice(2),i))}}});let n=r(6860),o=r(250),u=r(7234),l=r(5325);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7234:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return function e(t,r,u,l,a,i){if(0===Object.keys(u[1]).length){t.head=a;return}for(let s in u[1]){let c;let d=u[1][s],f=d[0],p=(0,o.createRouterCacheKey)(f),h=null!==l&&null!==l[1]&&void 0!==l[1][s]?l[1][s]:null;if(r){let o=r.parallelRoutes.get(s);if(o){let r,u=new Map(o),l=u.get(p);if(null!==h){let e=h[2];r={status:n.CacheStates.READY,data:null,subTreeData:e,parallelRoutes:new Map(null==l?void 0:l.parallelRoutes)}}else r=i&&l?{status:l.status,data:l.data,subTreeData:l.subTreeData,parallelRoutes:new Map(l.parallelRoutes)}:{status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map(null==l?void 0:l.parallelRoutes)};u.set(p,r),e(r,l,d,h||null,a,i),t.parallelRoutes.set(s,u);continue}}if(null!==h){let e=h[2];c={status:n.CacheStates.READY,data:null,subTreeData:e,parallelRoutes:new Map}}else c={status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map};let y=t.parallelRoutes.get(s);y?y.set(p,c):t.parallelRoutes.set(s,new Map([[p,c]])),e(c,void 0,d,h,a,i)}}}});let n=r(6860),o=r(5325);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},696:(e,t)=>{"use strict";var r;function n(e){let{kind:t,prefetchTime:r,lastUsedTime:n}=e;return Date.now()<(null!=n?n:r)+3e4?n?"reusable":"fresh":"auto"===t&&Date.now(){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleMutable",{enumerable:!0,get:function(){return u}});let n=r(5684);function o(e){return void 0!==e}function u(e,t){var r,u,l;let a=null==(u=t.shouldScroll)||u,i=e.nextUrl;if(o(t.patchedTree)){let r=(0,n.computeChangedPath)(e.tree,t.patchedTree);r?i=r:i||(i=e.canonicalUrl)}return{buildId:e.buildId,canonicalUrl:o(t.canonicalUrl)?t.canonicalUrl===e.canonicalUrl?e.canonicalUrl:t.canonicalUrl:e.canonicalUrl,pushRef:{pendingPush:o(t.pendingPush)?t.pendingPush:e.pushRef.pendingPush,mpaNavigation:o(t.mpaNavigation)?t.mpaNavigation:e.pushRef.mpaNavigation,preserveCustomHistoryState:o(t.preserveCustomHistoryState)?t.preserveCustomHistoryState:e.pushRef.preserveCustomHistoryState},focusAndScrollRef:{apply:!!a&&(!!o(null==t?void 0:t.scrollableSegments)||e.focusAndScrollRef.apply),onlyHashChange:!!t.hashFragment&&e.canonicalUrl.split("#",1)[0]===(null==(r=t.canonicalUrl)?void 0:r.split("#",1)[0]),hashFragment:a?t.hashFragment&&""!==t.hashFragment?decodeURIComponent(t.hashFragment.slice(1)):e.focusAndScrollRef.hashFragment:null,segmentPaths:a?null!=(l=null==t?void 0:t.scrollableSegments)?l:e.focusAndScrollRef.segmentPaths:[]},cache:t.cache?t.cache:e.cache,prefetchCache:t.prefetchCache?t.prefetchCache:e.prefetchCache,tree:o(t.patchedTree)?t.patchedTree:e.tree,nextUrl:i}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2293:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheBelowFlightSegmentPath",{enumerable:!0,get:function(){return function e(t,r,o){let u=o.length<=2,[l,a]=o,i=(0,n.createRouterCacheKey)(a),s=r.parallelRoutes.get(l);if(!s)return;let c=t.parallelRoutes.get(l);if(c&&c!==s||(c=new Map(s),t.parallelRoutes.set(l,c)),u){c.delete(i);return}let d=s.get(i),f=c.get(i);f&&d&&(f===d&&(f={status:f.status,data:f.data,subTreeData:f.subTreeData,parallelRoutes:new Map(f.parallelRoutes)},c.set(i,f)),e(f,d,o.slice(2)))}}});let n=r(5325);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},250:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"invalidateCacheByRouterState",{enumerable:!0,get:function(){return o}});let n=r(5325);function o(e,t,r){for(let o in r[1]){let u=r[1][o][0],l=(0,n.createRouterCacheKey)(u),a=t.parallelRoutes.get(o);if(a){let t=new Map(a);t.delete(l),e.parallelRoutes.set(o,t)}}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3694:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNavigatingToNewRootLayout",{enumerable:!0,get:function(){return function e(t,r){let n=t[0],o=r[0];if(Array.isArray(n)&&Array.isArray(o)){if(n[0]!==o[0]||n[2]!==o[2])return!0}else if(n!==o)return!0;if(t[4])return!r[4];if(r[4])return!0;let u=Object.values(t[1])[0],l=Object.values(r[1])[0];return!u||!l||e(u,l)}}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2298:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fastRefreshReducer",{enumerable:!0,get:function(){return n}}),r(7013),r(7475),r(1697),r(3694),r(9643),r(4080),r(9543),r(2583);let n=function(e,t){return e};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7550:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"findHeadInCache",{enumerable:!0,get:function(){return function e(t,r){if(0===Object.keys(r).length)return t.head;for(let o in r){let[u,l]=r[o],a=t.parallelRoutes.get(o);if(!a)continue;let i=(0,n.createRouterCacheKey)(u),s=a.get(i);if(!s)continue;let c=e(s,l);if(c)return c}}}});let n=r(5325);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3717:(e,t)=>{"use strict";function r(e){return Array.isArray(e)?e[1]:e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentValue",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9643:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{handleExternalUrl:function(){return g},navigateReducer:function(){return v}});let n=r(6860),o=r(7013),u=r(7475),l=r(2293),a=r(7676),i=r(1697),s=r(7528),c=r(3694),d=r(8085),f=r(4080),p=r(9543),h=r(696),y=r(2574),_=r(7772),b=r(2583);function g(e,t,r,n){return t.mpaNavigation=!0,t.canonicalUrl=r,t.pendingPush=n,t.scrollableSegments=void 0,(0,f.handleMutable)(e,t)}function m(e){let t=[],[r,n]=e;if(0===Object.keys(n).length)return[[r]];for(let[e,o]of Object.entries(n))for(let n of m(o))""===r?t.push([e,...n]):t.push([r,e,...n]);return t}function v(e,t){let{url:r,isExternalUrl:v,navigateType:P,shouldScroll:O}=t,R={},{hash:j}=r,E=(0,u.createHrefFromUrl)(r),S="push"===P;if((0,y.prunePrefetchCache)(e.prefetchCache),R.preserveCustomHistoryState=!1,v)return g(e,R,r.toString(),S);let T=e.prefetchCache.get((0,u.createHrefFromUrl)(r,!1));if(!T){let t={data:(0,o.fetchServerResponse)(r,e.tree,e.nextUrl,e.buildId,void 0),kind:d.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:e.tree,lastUsedTime:null};e.prefetchCache.set((0,u.createHrefFromUrl)(r,!1),t),T=t}let M=(0,h.getPrefetchEntryCacheStatus)(T),{treeAtTimeOfPrefetch:x,data:C}=T;return _.prefetchQueue.bump(C),C.then(t=>{let[d,y,_]=t;if(T&&!T.lastUsedTime&&(T.lastUsedTime=Date.now()),"string"==typeof d)return g(e,R,d,S);let v=e.tree,P=e.cache,C=[];for(let t of d){let u=t.slice(0,-4),d=t.slice(-3)[0],f=["",...u],y=(0,i.applyRouterStatePatchToTree)(f,v,d);if(null===y&&(y=(0,i.applyRouterStatePatchToTree)(f,x,d)),null!==y){if((0,c.isNavigatingToNewRootLayout)(v,y))return g(e,R,E,S);let i=(0,b.createEmptyCacheNode)(),O=(0,p.applyFlightData)(P,i,t,(null==T?void 0:T.kind)==="auto"&&M===h.PrefetchCacheEntryStatus.reusable);for(let t of((!O&&M===h.PrefetchCacheEntryStatus.stale||_)&&(O=function(e,t,r,o,u){let l=!1;for(let i of(e.status=n.CacheStates.READY,e.subTreeData=t.subTreeData,e.parallelRoutes=new Map(t.parallelRoutes),m(o).map(e=>[...r,...e])))(0,a.fillCacheWithDataProperty)(e,t,i,u),l=!0;return l}(i,P,u,d,()=>(0,o.fetchServerResponse)(r,v,e.nextUrl,e.buildId))),(0,s.shouldHardNavigate)(f,v)?(i.status=n.CacheStates.READY,i.subTreeData=P.subTreeData,(0,l.invalidateCacheBelowFlightSegmentPath)(i,P,u),R.cache=i):O&&(R.cache=i),P=i,v=y,m(d))){let e=[...u,...t];"__DEFAULT__"!==e[e.length-1]&&C.push(e)}}}return R.patchedTree=v,R.canonicalUrl=y?(0,u.createHrefFromUrl)(y):E,R.pendingPush=S,R.scrollableSegments=C,R.hashFragment=j,R.shouldScroll=O,(0,f.handleMutable)(e,R)},()=>e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7772:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{prefetchQueue:function(){return i},prefetchReducer:function(){return s}});let n=r(7475),o=r(7013),u=r(8085),l=r(2574),a=r(5048),i=new(r(2051)).PromiseQueue(5);function s(e,t){(0,l.prunePrefetchCache)(e.prefetchCache);let{url:r}=t;r.searchParams.delete(a.NEXT_RSC_UNION_QUERY);let s=(0,n.createHrefFromUrl)(r,!1),c=e.prefetchCache.get(s);if(c&&(c.kind===u.PrefetchKind.TEMPORARY&&e.prefetchCache.set(s,{...c,kind:t.kind}),!(c.kind===u.PrefetchKind.AUTO&&t.kind===u.PrefetchKind.FULL)))return e;let d=i.enqueue(()=>(0,o.fetchServerResponse)(r,e.tree,e.nextUrl,e.buildId,t.kind));return e.prefetchCache.set(s,{treeAtTimeOfPrefetch:e.tree,data:d,kind:t.kind,prefetchTime:Date.now(),lastUsedTime:null}),e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2574:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prunePrefetchCache",{enumerable:!0,get:function(){return o}});let n=r(696);function o(e){for(let[t,r]of e)(0,n.getPrefetchEntryCacheStatus)(r)===n.PrefetchCacheEntryStatus.expired&&e.delete(t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7787:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"refreshReducer",{enumerable:!0,get:function(){return f}});let n=r(7013),o=r(7475),u=r(1697),l=r(3694),a=r(9643),i=r(4080),s=r(6860),c=r(7234),d=r(2583);function f(e,t){let{origin:r}=t,f={},p=e.canonicalUrl,h=e.tree;f.preserveCustomHistoryState=!1;let y=(0,d.createEmptyCacheNode)();return y.data=(0,n.fetchServerResponse)(new URL(p,r),[h[0],h[1],h[2],"refetch"],e.nextUrl,e.buildId),y.data.then(t=>{let[r,n]=t;if("string"==typeof r)return(0,a.handleExternalUrl)(e,f,r,e.pushRef.pendingPush);for(let t of(y.data=null,r)){if(3!==t.length)return console.log("REFRESH FAILED"),e;let[r]=t,i=(0,u.applyRouterStatePatchToTree)([""],h,r);if(null===i)throw Error("SEGMENT MISMATCH");if((0,l.isNavigatingToNewRootLayout)(h,i))return(0,a.handleExternalUrl)(e,f,p,e.pushRef.pendingPush);let d=n?(0,o.createHrefFromUrl)(n):void 0;n&&(f.canonicalUrl=d);let[_,b]=t.slice(-2);if(null!==_){let e=_[2];y.status=s.CacheStates.READY,y.subTreeData=e,(0,c.fillLazyItemsTillLeafWithHead)(y,void 0,r,_,b),f.cache=y,f.prefetchCache=new Map}f.patchedTree=i,f.canonicalUrl=p,h=i}return(0,i.handleMutable)(e,f)},()=>e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5206:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"restoreReducer",{enumerable:!0,get:function(){return u}});let n=r(7475),o=r(5684);function u(e,t){var r;let{url:u,tree:l}=t,a=(0,n.createHrefFromUrl)(u);return{buildId:e.buildId,canonicalUrl:a,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:e.focusAndScrollRef,cache:e.cache,prefetchCache:e.prefetchCache,tree:l,nextUrl:null!=(r=(0,o.extractPathFromFlightRouterState)(l))?r:u.pathname}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9501:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverActionReducer",{enumerable:!0,get:function(){return g}});let n=r(3664),o=r(5048),u=r(8928),l=r(7475),a=r(9643),i=r(1697),s=r(3694),c=r(6860),d=r(4080),f=r(7234),p=r(2583),h=r(5684),{createFromFetch:y,encodeReply:_}=r(2228);async function b(e,t){let r,{actionId:l,actionArgs:a}=t,i=await _(a),s=(0,h.extractPathFromFlightRouterState)(e.tree),c=e.nextUrl&&e.nextUrl!==s,d=await fetch("",{method:"POST",headers:{Accept:o.RSC_CONTENT_TYPE_HEADER,[o.ACTION]:l,[o.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(e.tree)),...c?{[o.NEXT_URL]:e.nextUrl}:{}},body:i}),f=d.headers.get("x-action-redirect");try{let e=JSON.parse(d.headers.get("x-action-revalidated")||"[[],0,0]");r={paths:e[0]||[],tag:!!e[1],cookie:e[2]}}catch(e){r={paths:[],tag:!1,cookie:!1}}let p=f?new URL((0,u.addBasePath)(f),new URL(e.canonicalUrl,window.location.href)):void 0;if(d.headers.get("content-type")===o.RSC_CONTENT_TYPE_HEADER){let e=await y(Promise.resolve(d),{callServer:n.callServer});if(f){let[,t]=null!=e?e:[];return{actionFlightData:t,redirectLocation:p,revalidatedParts:r}}let[t,[,o]]=null!=e?e:[];return{actionResult:t,actionFlightData:o,redirectLocation:p,revalidatedParts:r}}return{redirectLocation:p,revalidatedParts:r}}function g(e,t){let{resolve:r,reject:n}=t,o={},u=e.canonicalUrl,h=e.tree;return o.preserveCustomHistoryState=!1,o.inFlightServerAction=b(e,t),o.inFlightServerAction.then(t=>{let{actionResult:n,actionFlightData:y,redirectLocation:_}=t;if(_&&(e.pushRef.pendingPush=!0,o.pendingPush=!0),!y)return(o.actionResultResolved||(r(n),o.actionResultResolved=!0),_)?(0,a.handleExternalUrl)(e,o,_.href,e.pushRef.pendingPush):e;if("string"==typeof y)return(0,a.handleExternalUrl)(e,o,y,e.pushRef.pendingPush);for(let t of(o.inFlightServerAction=null,y)){if(3!==t.length)return console.log("SERVER ACTION APPLY FAILED"),e;let[r]=t,n=(0,i.applyRouterStatePatchToTree)([""],h,r);if(null===n)throw Error("SEGMENT MISMATCH");if((0,s.isNavigatingToNewRootLayout)(h,n))return(0,a.handleExternalUrl)(e,o,u,e.pushRef.pendingPush);let[l,d]=t.slice(-2),y=null!==l?l[2]:null;if(null!==y){let e=(0,p.createEmptyCacheNode)();e.status=c.CacheStates.READY,e.subTreeData=y,(0,f.fillLazyItemsTillLeafWithHead)(e,void 0,r,l,d),o.cache=e,o.prefetchCache=new Map}o.patchedTree=n,o.canonicalUrl=u,h=n}if(_){let e=(0,l.createHrefFromUrl)(_,!1);o.canonicalUrl=e}return o.actionResultResolved||(r(n),o.actionResultResolved=!0),(0,d.handleMutable)(e,o)},t=>{if("rejected"===t.status)return o.actionResultResolved||(n(t.reason),o.actionResultResolved=!0),e;throw t})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7910:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverPatchReducer",{enumerable:!0,get:function(){return c}});let n=r(7475),o=r(1697),u=r(3694),l=r(9643),a=r(9543),i=r(4080),s=r(2583);function c(e,t){let{flightData:r,overrideCanonicalUrl:c}=t,d={};if(d.preserveCustomHistoryState=!1,"string"==typeof r)return(0,l.handleExternalUrl)(e,d,r,e.pushRef.pendingPush);let f=e.tree,p=e.cache;for(let t of r){let r=t.slice(0,-4),[i]=t.slice(-3,-2),h=(0,o.applyRouterStatePatchToTree)(["",...r],f,i);if(null===h)throw Error("SEGMENT MISMATCH");if((0,u.isNavigatingToNewRootLayout)(f,h))return(0,l.handleExternalUrl)(e,d,e.canonicalUrl,e.pushRef.pendingPush);let y=c?(0,n.createHrefFromUrl)(c):void 0;y&&(d.canonicalUrl=y);let _=(0,s.createEmptyCacheNode)();(0,a.applyFlightData)(p,_,t),d.patchedTree=h,d.cache=_,p=_,f=h}return(0,i.handleMutable)(e,d)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8085:(e,t)=>{"use strict";var r;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PrefetchKind:function(){return r},ACTION_REFRESH:function(){return n},ACTION_NAVIGATE:function(){return o},ACTION_RESTORE:function(){return u},ACTION_SERVER_PATCH:function(){return l},ACTION_PREFETCH:function(){return a},ACTION_FAST_REFRESH:function(){return i},ACTION_SERVER_ACTION:function(){return s},isThenable:function(){return c}});let n="refresh",o="navigate",u="restore",l="server-patch",a="prefetch",i="fast-refresh",s="server-action";function c(e){return e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(function(e){e.AUTO="auto",e.FULL="full",e.TEMPORARY="temporary"})(r||(r={})),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3479:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return n}}),r(8085),r(9643),r(7910),r(5206),r(7787),r(7772),r(2298),r(9501);let n=function(e,t){return e};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7528:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldHardNavigate",{enumerable:!0,get:function(){return function e(t,r){let[o,u]=r,[l,a]=t;return(0,n.matchSegment)(l,o)?!(t.length<=2)&&e(t.slice(2),u[a]):!!Array.isArray(l)}}});let n=r(4287);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5517:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return o}});let n=r(1396);function o(){return new Proxy({},{get(e,t){"string"==typeof t&&(0,n.staticGenerationBailout)("searchParams."+t)}})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1396:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationBailout",{enumerable:!0,get:function(){return a}});let n=r(3082),o=r(4749);class u extends Error{constructor(...e){super(...e),this.code="NEXT_STATIC_GEN_BAILOUT"}}function l(e,t){let{dynamic:r,link:n}=t||{};return"Page"+(r?' with `dynamic = "'+r+'"`':"")+" couldn't be rendered statically because it used `"+e+"`."+(n?" See more info here: "+n:"")}let a=(e,t)=>{let{dynamic:r,link:a}=void 0===t?{}:t,i=o.staticGenerationAsyncStorage.getStore();if(!i)return!1;if(i.forceStatic)return!0;if(i.dynamicShouldError)throw new u(l(e,{link:a,dynamic:null!=r?r:"error"}));let s=l(e,{dynamic:r,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if(null==i.postpone||i.postpone.call(i,e),i.revalidate=0,i.isStaticGeneration){let t=new n.DynamicServerError(s);throw i.dynamicUsageDescription=e,i.dynamicUsageStack=t.stack,t}return!1};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3982:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return u}});let n=r(9694)._(r(3729)),o=r(5517);function u(e){let{Component:t,propsForComponent:r,isStaticGeneration:u}=e;if(u){let e=(0,o.createSearchParamsBailoutProxy)();return n.default.createElement(t,{searchParams:e,...r})}return n.default.createElement(t,r)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4954:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{useUnwrapState:function(){return l},useReducerWithReduxDevtools:function(){return a}});let n=r(7824)._(r(3729)),o=r(8085);function u(e){if(e instanceof Map){let t={};for(let[r,n]of e.entries()){if("function"==typeof n){t[r]="fn()";continue}if("object"==typeof n&&null!==n){if(n.$$typeof){t[r]=n.$$typeof.toString();continue}if(n._bundlerConfig){t[r]="FlightData";continue}}t[r]=u(n)}return t}if("object"==typeof e&&null!==e){let t={};for(let r in e){let n=e[r];if("function"==typeof n){t[r]="fn()";continue}if("object"==typeof n&&null!==n){if(n.$$typeof){t[r]=n.$$typeof.toString();continue}if(n.hasOwnProperty("_bundlerConfig")){t[r]="FlightData";continue}}t[r]=u(n)}return t}return Array.isArray(e)?e.map(u):e}function l(e){return(0,o.isThenable)(e)?(0,n.use)(e):e}r(4087);let a=function(e){return[e,()=>{},()=>{}]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6411:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return o}});let n=r(6050);function o(e){return(0,n.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9847:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return u}});let n=r(4310),o=r(2244),u=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:r,hash:u}=(0,o.parsePath)(e);return""+(0,n.removeTrailingSlash)(t)+r+u};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2874:(e,t,r)=>{"use strict";function n(e){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return n}}),r(6411),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4269:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentParam",{enumerable:!0,get:function(){return o}});let n=r(5767);function o(e){let t=n.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t));return(t&&(e=e.slice(t.length)),e.startsWith("[[...")&&e.endsWith("]]"))?{type:"optional-catchall",param:e.slice(5,-2)}:e.startsWith("[...")&&e.endsWith("]")?{type:"catchall",param:e.slice(4,-1)}:e.startsWith("[")&&e.endsWith("]")?{type:"dynamic",param:e.slice(1,-1)}:null}},5767:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return o},isInterceptionRouteAppPath:function(){return u},extractInterceptionRouteInformation:function(){return l}});let n=r(7655),o=["(..)(..)","(.)","(..)","(...)"];function u(e){return void 0!==e.split("/").find(e=>o.find(t=>e.startsWith(t)))}function l(e){let t,r,u;for(let n of e.split("/"))if(r=o.find(e=>n.startsWith(e))){[t,u]=e.split(r,2);break}if(!t||!r||!u)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":u="/"===t?`/${u}`:t+"/"+u;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);u=t.split("/").slice(0,-1).concat(u).join("/");break;case"(...)":u="/"+u;break;case"(..)(..)":let l=t.split("/");if(l.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);u=l.slice(0,-2).concat(u).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:u}}},6372:(e,t,r)=>{"use strict";e.exports=r(399)},6860:(e,t,r)=>{"use strict";e.exports=r(6372).vendored.contexts.AppRouterContext},8486:(e,t,r)=>{"use strict";e.exports=r(6372).vendored.contexts.HooksClientContext},9505:(e,t,r)=>{"use strict";e.exports=r(6372).vendored.contexts.ServerInsertedHtml},1202:(e,t,r)=>{"use strict";e.exports=r(6372).vendored["react-ssr"].ReactDOM},2228:(e,t,r)=>{"use strict";e.exports=r(6372).vendored["react-ssr"].ReactServerDOMWebpackClientEdge},3729:(e,t,r)=>{"use strict";e.exports=r(6372).vendored["react-ssr"].React},5344:(e,t)=>{"use strict";function r(e){let t=5381;for(let r=0;r>>0}function n(e){return r(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{djb2Hash:function(){return r},hexHash:function(){return n}})},1462:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_DYNAMIC_NO_SSR_CODE:function(){return r},throwWithNoSSR:function(){return n}});let r="NEXT_DYNAMIC_NO_SSR_CODE";function n(){let e=Error(r);throw e.digest=r,e}},8092:(e,t)=>{"use strict";function r(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return r}})},4087:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ActionQueueContext:function(){return a},createMutableActionQueue:function(){return c}});let n=r(7824),o=r(8085),u=r(3479),l=n._(r(3729)),a=l.default.createContext(null);function i(e,t){null!==e.pending&&(e.pending=e.pending.next,null!==e.pending&&s({actionQueue:e,action:e.pending,setState:t}))}async function s(e){let{actionQueue:t,action:r,setState:n}=e,u=t.state;if(!u)throw Error("Invariant: Router state not initialized");t.pending=r;let l=r.payload,a=t.action(u,l);function s(e){if(r.discarded){t.needsRefresh&&null===t.pending&&(t.needsRefresh=!1,t.dispatch({type:o.ACTION_REFRESH,origin:window.location.origin},n));return}t.state=e,t.devToolsInstance&&t.devToolsInstance.send(l,e),i(t,n),r.resolve(e)}(0,o.isThenable)(a)?a.then(s,e=>{i(t,n),r.reject(e)}):s(a)}function c(){let e={state:null,dispatch:(t,r)=>(function(e,t,r){let n={resolve:r,reject:()=>{}};if(t.type!==o.ACTION_RESTORE){let e=new Promise((e,t)=>{n={resolve:e,reject:t}});(0,l.startTransition)(()=>{r(e)})}let u={payload:t,next:null,resolve:n.resolve,reject:n.reject};null===e.pending?(e.last=u,s({actionQueue:e,action:u,setState:r})):t.type===o.ACTION_NAVIGATE?(e.pending.discarded=!0,e.last=u,e.pending.payload.type===o.ACTION_SERVER_ACTION&&(e.needsRefresh=!0),s({actionQueue:e,action:u,setState:r})):(null!==e.last&&(e.last.next=u),e.last=u)})(e,t,r),action:async(e,t)=>{if(null===e)throw Error("Invariant: Router state not initialized");return(0,u.reducer)(e,t)},pending:null,last:null};return e}},1870:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return o}});let n=r(2244);function o(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:u}=(0,n.parsePath)(e);return""+t+r+o+u}},7655:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return u},normalizeRscURL:function(){return l}});let n=r(8092),o=r(9457);function u(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,o.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function l(e){return e.replace(/\.rsc($|\?)/,"$1")}},1586:(e,t)=>{"use strict";function r(e,t){if(void 0===t&&(t={}),t.onlyHashChange){e();return}let r=document.documentElement,n=r.style.scrollBehavior;r.style.scrollBehavior="auto",t.dontForceLayout||r.getClientRects(),e(),r.style.scrollBehavior=n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return r}})},6338:(e,t)=>{"use strict";function r(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isBot",{enumerable:!0,get:function(){return r}})},2244:(e,t)=>{"use strict";function r(e){let t=e.indexOf("#"),r=e.indexOf("?"),n=r>-1&&(t<0||r-1?{pathname:e.substring(0,n?r:t),query:n?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return r}})},6050:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return o}});let n=r(2244);function o(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,n.parsePath)(e);return r===t||r.startsWith(t+"/")}},4310:(e,t)=>{"use strict";function r(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return r}})},9457:(e,t)=>{"use strict";function r(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isGroupSegment",{enumerable:!0,get:function(){return r}})},6843:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createProxy",{enumerable:!0,get:function(){return n}});let n=r(8195).createClientModuleProxy},7519:(e,t,r)=>{let{createProxy:n}=r(6843);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\app-router.js")},2563:(e,t,r)=>{let{createProxy:n}=r(6843);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\error-boundary.js")},8096:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DYNAMIC_ERROR_CODE:function(){return r},DynamicServerError:function(){return n}});let r="DYNAMIC_SERVER_USAGE";class n extends Error{constructor(e){super("Dynamic server usage: "+e),this.digest=r}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2517:(e,t,r)=>{let{createProxy:n}=r(6843);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\layout-router.js")},1150:(e,t,r)=>{let{createProxy:n}=r(6843);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\not-found-boundary.js")},9361:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return u}});let n=r(6783)._(r(2)),o={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{display:"inline-block"},h1:{display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},h2:{fontSize:14,fontWeight:400,lineHeight:"49px",margin:0}};function u(){return n.default.createElement(n.default.Fragment,null,n.default.createElement("title",null,"404: This page could not be found."),n.default.createElement("div",{style:o.error},n.default.createElement("div",null,n.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}),n.default.createElement("h1",{className:"next-error-h1",style:o.h1},"404"),n.default.createElement("div",{style:o.desc},n.default.createElement("h2",{style:o.h2},"This page could not be found.")))))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},571:(e,t,r)=>{let{createProxy:n}=r(6843);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\render-from-template-context.js")},8650:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return o}});let n=r(2973);function o(){return new Proxy({},{get(e,t){"string"==typeof t&&(0,n.staticGenerationBailout)("searchParams."+t)}})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2973:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationBailout",{enumerable:!0,get:function(){return a}});let n=r(8096),o=r(5319);class u extends Error{constructor(...e){super(...e),this.code="NEXT_STATIC_GEN_BAILOUT"}}function l(e,t){let{dynamic:r,link:n}=t||{};return"Page"+(r?' with `dynamic = "'+r+'"`':"")+" couldn't be rendered statically because it used `"+e+"`."+(n?" See more info here: "+n:"")}let a=(e,t)=>{let{dynamic:r,link:a}=void 0===t?{}:t,i=o.staticGenerationAsyncStorage.getStore();if(!i)return!1;if(i.forceStatic)return!0;if(i.dynamicShouldError)throw new u(l(e,{link:a,dynamic:null!=r?r:"error"}));let s=l(e,{dynamic:r,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if(null==i.postpone||i.postpone.call(i,e),i.revalidate=0,i.isStaticGeneration){let t=new n.DynamicServerError(s);throw i.dynamicUsageDescription=e,i.dynamicUsageStack=t.stack,t}return!1};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2336:(e,t,r)=>{let{createProxy:n}=r(6843);e.exports=n("X:\\Some Useful Stuff\\Applications\\Web\\next-sukadia.dev\\node_modules\\next\\dist\\client\\components\\static-generation-searchparams-bailout-provider.js")},8300:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{renderToReadableStream:function(){return n.renderToReadableStream},decodeReply:function(){return n.decodeReply},decodeAction:function(){return n.decodeAction},decodeFormState:function(){return n.decodeFormState},AppRouter:function(){return o.default},LayoutRouter:function(){return u.default},RenderFromTemplateContext:function(){return l.default},staticGenerationAsyncStorage:function(){return a.staticGenerationAsyncStorage},requestAsyncStorage:function(){return i.requestAsyncStorage},actionAsyncStorage:function(){return s.actionAsyncStorage},staticGenerationBailout:function(){return c.staticGenerationBailout},createSearchParamsBailoutProxy:function(){return f.createSearchParamsBailoutProxy},serverHooks:function(){return p},preloadStyle:function(){return _.preloadStyle},preloadFont:function(){return _.preloadFont},preconnect:function(){return _.preconnect},taintObjectReference:function(){return b.taintObjectReference},StaticGenerationSearchParamsBailoutProvider:function(){return d.default},NotFoundBoundary:function(){return h.NotFoundBoundary},patchFetch:function(){return v}});let n=r(8195),o=g(r(7519)),u=g(r(2517)),l=g(r(571)),a=r(5319),i=r(1877),s=r(5528),c=r(2973),d=g(r(2336)),f=r(8650),p=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=m(t);if(r&&r.has(e))return r.get(e);var n={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&Object.prototype.hasOwnProperty.call(e,u)){var l=o?Object.getOwnPropertyDescriptor(e,u):null;l&&(l.get||l.set)?Object.defineProperty(n,u,l):n[u]=e[u]}return n.default=e,r&&r.set(e,n),n}(r(8096)),h=r(1150),y=r(9678);r(2563);let _=r(1806),b=r(2730);function g(e){return e&&e.__esModule?e:{default:e}}function m(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(m=function(e){return e?r:t})(e)}function v(){return(0,y.patchFetch)({serverHooks:p,staticGenerationAsyncStorage:a.staticGenerationAsyncStorage})}},1806:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{preloadStyle:function(){return o},preloadFont:function(){return u},preconnect:function(){return l}});let n=function(e){return e&&e.__esModule?e:{default:e}}(r(5091));function o(e,t){let r={as:"style"};"string"==typeof t&&(r.crossOrigin=t),n.default.preload(e,r)}function u(e,t,r){let o={as:"font",type:t};"string"==typeof r&&(o.crossOrigin=r),n.default.preload(e,o)}function l(e,t){n.default.preconnect(e,"string"==typeof t?{crossOrigin:t}:void 0)}},2730:(e,t,r)=>{"use strict";function n(){throw Error("Taint can only be used with the taint flag.")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{taintObjectReference:function(){return o},taintUniqueValue:function(){return u}}),r(2);let o=n,u=n},482:(e,t,r)=>{"use strict";e.exports=r(399)},5091:(e,t,r)=>{"use strict";e.exports=r(482).vendored["react-rsc"].ReactDOM},5036:(e,t,r)=>{"use strict";e.exports=r(482).vendored["react-rsc"].ReactJsxRuntime},8195:(e,t,r)=>{"use strict";e.exports=r(482).vendored["react-rsc"].ReactServerDOMWebpackServerEdge},2:(e,t,r)=>{"use strict";e.exports=r(482).vendored["react-rsc"].React},9996:(e,t,r)=>{"use strict";function n(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}r.r(t),r.d(t,{_:()=>n,_class_private_field_loose_base:()=>n})},7074:(e,t,r)=>{"use strict";r.r(t),r.d(t,{_:()=>o,_class_private_field_loose_key:()=>o});var n=0;function o(e){return"__private_"+n+++"_"+e}},9694:(e,t,r)=>{"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:()=>n,_interop_require_default:()=>n})},7824:(e,t,r)=>{"use strict";function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function o(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var o={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var l in e)if("default"!==l&&Object.prototype.hasOwnProperty.call(e,l)){var a=u?Object.getOwnPropertyDescriptor(e,l):null;a&&(a.get||a.set)?Object.defineProperty(o,l,a):o[l]=e[l]}return o.default=e,r&&r.set(e,o),o}r.r(t),r.d(t,{_:()=>o,_interop_require_wildcard:()=>o})},6783:(e,t,r)=>{"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:()=>n,_interop_require_default:()=>n})}}; \ No newline at end of file diff --git a/.next/server/chunks/984.js b/.next/server/chunks/984.js deleted file mode 100644 index b8142a4..0000000 --- a/.next/server/chunks/984.js +++ /dev/null @@ -1,11502 +0,0 @@ -exports.id=984,exports.ids=[984],exports.modules={3642:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return dynamic}});let r=i(85);i(9885);let s=r._(i(112));function convertModule(e){return{default:(null==e?void 0:e.default)||e}}function dynamic(e,t){let i=s.default,r={loading:e=>{let{error:t,isLoading:i,pastDelay:r}=e;return null}};"function"==typeof e&&(r.loader=e),Object.assign(r,t);let a=r.loader;return i({...r,loader:()=>null!=a?a().then(convertModule):Promise.resolve(convertModule(()=>null))})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6800:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NoSSR",{enumerable:!0,get:function(){return NoSSR}});let r=i(1118);function NoSSR(e){let{children:t}=e;return(0,r.throwWithNoSSR)(),t}},112:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}});let r=i(85),s=r._(i(9885)),a=i(6800);function Loadable(e){let t=Object.assign({loader:null,loading:null,ssr:!0},e);function LoadableComponent(e){let i=t.loading,r=s.default.createElement(i,{isLoading:!0,pastDelay:!0,error:null}),n=t.ssr?s.default.Fragment:a.NoSSR,o=t.lazy;return s.default.createElement(s.default.Suspense,{fallback:r},s.default.createElement(n,null,s.default.createElement(o,e)))}return t.lazy=s.default.lazy(t.loader),LoadableComponent.displayName="LoadableComponent",LoadableComponent}let n=Loadable},784:(e,t,i)=>{"use strict";e.exports=i(316).vendored["react-ssr"].ReactJsxRuntime},6224:function(e,t){/*! Tweakpane 3.1.10 (c) 2016 cocopon, licensed under the MIT license. */(function(e){"use strict";let Semver=class Semver{constructor(e){let[t,i]=e.split("-"),r=t.split(".");this.major=parseInt(r[0],10),this.minor=parseInt(r[1],10),this.patch=parseInt(r[2],10),this.prerelease=null!=i?i:null}toString(){let e=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[e,this.prerelease].join("-"):e}};let BladeApi=class BladeApi{constructor(e){this.controller_=e}get element(){return this.controller_.view.element}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(e){this.controller_.viewProps.set("disabled",e)}get hidden(){return this.controller_.viewProps.get("hidden")}set hidden(e){this.controller_.viewProps.set("hidden",e)}dispose(){this.controller_.viewProps.set("disposed",!0)}};let TpEvent=class TpEvent{constructor(e){this.target=e}};let TpChangeEvent=class TpChangeEvent extends TpEvent{constructor(e,t,i,r){super(e),this.value=t,this.presetKey=i,this.last=null==r||r}};let TpUpdateEvent=class TpUpdateEvent extends TpEvent{constructor(e,t,i){super(e),this.value=t,this.presetKey=i}};let TpFoldEvent=class TpFoldEvent extends TpEvent{constructor(e,t){super(e),this.expanded=t}};let TpTabSelectEvent=class TpTabSelectEvent extends TpEvent{constructor(e,t){super(e),this.index=t}};function isEmpty(e){return null==e}function deepEqualsArray(e,t){if(e.length!==t.length)return!1;for(let i=0;i"View has been already disposed",invalidparams:e=>`Invalid parameters for '${e.name}'`,nomatchingcontroller:e=>`No matching controller for '${e.key}'`,nomatchingview:e=>`No matching view for '${JSON.stringify(e.params)}'`,notbindable:()=>"Value is not bindable",propertynotfound:e=>`Property '${e.name}' not found`,shouldneverhappen:()=>"This error should never happen"};let TpError=class TpError{static alreadyDisposed(){return new TpError({type:"alreadydisposed"})}static notBindable(){return new TpError({type:"notbindable"})}static propertyNotFound(e){return new TpError({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new TpError({type:"shouldneverhappen"})}constructor(e){var i;this.message=null!==(i=t[e.type](e.context))&&void 0!==i?i:"Unexpected error",this.name=this.constructor.name,this.stack=Error(this.message).stack,this.type=e.type}};let BindingTarget=class BindingTarget{constructor(e,t,i){this.obj_=e,this.key_=t,this.presetKey_=null!=i?i:t}static isBindable(e){return null!==e&&("object"==typeof e||"function"==typeof e)}get key(){return this.key_}get presetKey(){return this.presetKey_}read(){return this.obj_[this.key_]}write(e){this.obj_[this.key_]=e}writeProperty(e,t){let i=this.read();if(!BindingTarget.isBindable(i))throw TpError.notBindable();if(!(e in i))throw TpError.propertyNotFound(e);i[e]=t}};let ButtonApi=class ButtonApi extends BladeApi{get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get title(){var e;return null!==(e=this.controller_.valueController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.valueController.props.set("title",e)}on(e,t){let i=t.bind(this),r=this.controller_.valueController.emitter;return r.on(e,()=>{i(new TpEvent(this))}),this}};let Emitter=class Emitter{constructor(){this.observers_={}}on(e,t){let i=this.observers_[e];return i||(i=this.observers_[e]=[]),i.push({handler:t}),this}off(e,t){let i=this.observers_[e];return i&&(this.observers_[e]=i.filter(e=>e.handler!==t)),this}emit(e,t){let i=this.observers_[e];i&&i.forEach(e=>{e.handler(t)})}};function ClassName(e){return(t,i)=>["tp","-",e,"v",t?`_${t}`:"",i?`-${i}`:""].join("")}function compose(e,t){return i=>t(e(i))}function extractValue(e){return e.rawValue}function bindValue(e,t){e.emitter.on("change",compose(extractValue,t)),t(e.rawValue)}function bindValueMap(e,t,i){bindValue(e.value(t),i)}function applyClass(e,t,i){i?e.classList.add(t):e.classList.remove(t)}function valueToClassName(e,t){return i=>{applyClass(e,t,i)}}function bindValueToTextContent(e,t){bindValue(e,e=>{t.textContent=null!=e?e:""})}let i=ClassName("btn");let ButtonView=class ButtonView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(i()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("button");r.classList.add(i("b")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r;let s=e.createElement("div");s.classList.add(i("t")),bindValueToTextContent(t.props.value("title"),s),this.buttonElement.appendChild(s)}};let ButtonController=class ButtonController{constructor(e,t){this.emitter=new Emitter,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new ButtonView(e,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}};let BoundValue=class BoundValue{constructor(e,t){var i;this.constraint_=null==t?void 0:t.constraint,this.equals_=null!==(i=null==t?void 0:t.equals)&&void 0!==i?i:(e,t)=>e===t,this.emitter=new Emitter,this.rawValue_=e}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let i=null!=t?t:{forceEmit:!1,last:!0},r=this.constraint_?this.constraint_.constrain(e):e,s=this.rawValue_,a=!this.equals_(s,r);(a||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=r,this.emitter.emit("change",{options:i,previousRawValue:s,rawValue:r,sender:this}))}};let PrimitiveValue=class PrimitiveValue{constructor(e){this.emitter=new Emitter,this.value_=e}get rawValue(){return this.value_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let i=null!=t?t:{forceEmit:!1,last:!0},r=this.value_;(r!==e||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=e,this.emitter.emit("change",{options:i,previousRawValue:r,rawValue:this.value_,sender:this}))}};function createValue(e,t){let i=null==t?void 0:t.constraint,r=null==t?void 0:t.equals;return i||r?new BoundValue(e,t):new PrimitiveValue(e)}let ValueMap=class ValueMap{constructor(e){for(let t in this.emitter=new Emitter,this.valMap_=e,this.valMap_){let e=this.valMap_[t];e.emitter.on("change",()=>{this.emitter.emit("change",{key:t,sender:this})})}}static createCore(e){let t=Object.keys(e);return t.reduce((t,i)=>Object.assign(t,{[i]:createValue(e[i])}),{})}static fromObject(e){let t=this.createCore(e);return new ValueMap(t)}get(e){return this.valMap_[e].rawValue}set(e,t){this.valMap_[e].rawValue=t}value(e){return this.valMap_[e]}};function parseObject(e,t){let i=Object.keys(t),r=i.reduce((i,r)=>{if(void 0===i)return;let s=t[r],a=s(e[r]);return a.succeeded?Object.assign(Object.assign({},i),{[r]:a.value}):void 0},{});return r}function parseArray(e,t){return e.reduce((e,i)=>{if(void 0===e)return;let r=t(i);if(r.succeeded&&void 0!==r.value)return[...e,r.value]},[])}function isObject(e){return null!==e&&"object"==typeof e}function createParamsParserBuilder(e){return t=>i=>{if(!t&&void 0===i)return{succeeded:!1,value:void 0};if(t&&void 0===i)return{succeeded:!0,value:void 0};let r=e(i);return void 0!==r?{succeeded:!0,value:r}:{succeeded:!1,value:void 0}}}function createParamsParserBuilders(e){return{custom:t=>createParamsParserBuilder(t)(e),boolean:createParamsParserBuilder(e=>"boolean"==typeof e?e:void 0)(e),number:createParamsParserBuilder(e=>"number"==typeof e?e:void 0)(e),string:createParamsParserBuilder(e=>"string"==typeof e?e:void 0)(e),function:createParamsParserBuilder(e=>"function"==typeof e?e:void 0)(e),constant:t=>createParamsParserBuilder(e=>e===t?t:void 0)(e),raw:createParamsParserBuilder(e=>e)(e),object:t=>createParamsParserBuilder(e=>{if(isObject(e))return parseObject(e,t)})(e),array:t=>createParamsParserBuilder(e=>{if(Array.isArray(e))return parseArray(e,t)})(e)}}let r={optional:createParamsParserBuilders(!0),required:createParamsParserBuilders(!1)};function parseParams(e,t){let i=r.required.object(t)(e);return i.succeeded?i.value:void 0}function warnMissing(e){console.warn(`Missing '${e.key}' of ${e.target} in ${e.place}. Please rebuild plugins with the latest core package.`)}function disposeElement(e){return e&&e.parentElement&&e.parentElement.removeChild(e),null}let ReadonlyValue=class ReadonlyValue{constructor(e){this.value_=e}static create(e){return[new ReadonlyValue(e),(t,i)=>{e.setRawValue(t,i)}]}get emitter(){return this.value_.emitter}get rawValue(){return this.value_.rawValue}};let s=ClassName("");function valueToModifier(e,t){return valueToClassName(e,s(void 0,t))}let ViewProps=class ViewProps extends ValueMap{constructor(e){var t;super(e),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=ReadonlyValue.create(createValue(this.getGlobalDisabled_())),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var t,i,r;let s=null!=e?e:{};return new ViewProps(ValueMap.createCore({disabled:null!==(t=s.disabled)&&void 0!==t&&t,disposed:!1,hidden:null!==(i=s.hidden)&&void 0!==i&&i,parent:null!==(r=s.parent)&&void 0!==r?r:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(e){bindValue(this.globalDisabled_,valueToModifier(e,"disabled")),bindValueMap(this,"hidden",valueToModifier(e,"hidden"))}bindDisabled(e){bindValue(this.globalDisabled_,t=>{e.disabled=t})}bindTabIndex(e){bindValue(this.globalDisabled_,t=>{e.tabIndex=t?-1:0})}handleDispose(e){this.value("disposed").emitter.on("change",t=>{t&&e()})}getGlobalDisabled_(){let e=this.get("parent"),t=!!e&&e.globalDisabled.rawValue;return t||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(e){var t;let i=e.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}};function getAllBladePositions(){return["veryfirst","first","last","verylast"]}let a=ClassName(""),n={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"};let BladeController=class BladeController{constructor(e){this.parent_=null,this.blade=e.blade,this.view=e.view,this.viewProps=e.viewProps;let t=this.view.element;this.blade.value("positions").emitter.on("change",()=>{getAllBladePositions().forEach(e=>{t.classList.remove(a(void 0,n[e]))}),this.blade.get("positions").forEach(e=>{t.classList.add(a(void 0,n[e]))})}),this.viewProps.handleDispose(()=>{disposeElement(t)})}get parent(){return this.parent_}set parent(e){if(this.parent_=e,!("parent"in this.viewProps.valMap_)){warnMissing({key:"parent",target:ViewProps.name,place:"BladeController.parent"});return}this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}};let o="http://www.w3.org/2000/svg";function forceReflow(e){e.offsetHeight}function disableTransitionTemporarily(e,t){let i=e.style.transition;e.style.transition="none",t(),e.style.transition=i}function supportsTouch(e){return void 0!==e.ontouchstart}function getGlobalObject(){return globalThis}function getWindowDocument(){let e=getGlobalObject();return e.document}function getCanvasContext(e){let t=e.ownerDocument.defaultView;return t&&"document"in t?e.getContext("2d",{willReadFrequently:!0}):null}let l={check:'',dropdown:'',p2dpad:''};function createSvgIconElement(e,t){let i=e.createElementNS(o,"svg");return i.innerHTML=l[t],i}function insertElementAt(e,t,i){e.insertBefore(t,e.children[i])}function removeElement(e){e.parentElement&&e.parentElement.removeChild(e)}function removeChildElements(e){for(;e.children.length>0;)e.removeChild(e.children[0])}function removeChildNodes(e){for(;e.childNodes.length>0;)e.removeChild(e.childNodes[0])}function findNextTarget(e){return e.relatedTarget?e.relatedTarget:"explicitOriginalTarget"in e?e.explicitOriginalTarget:null}let h=ClassName("lbl");function createLabelNode(e,t){let i=e.createDocumentFragment(),r=t.split("\n").map(t=>e.createTextNode(t));return r.forEach((t,r)=>{r>0&&i.appendChild(e.createElement("br")),i.appendChild(t)}),i}let LabelView=class LabelView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(h()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(h("l")),bindValueMap(t.props,"label",t=>{isEmpty(t)?this.element.classList.add(h(void 0,"nol")):(this.element.classList.remove(h(void 0,"nol")),removeChildNodes(i),i.appendChild(createLabelNode(e,t)))}),this.element.appendChild(i),this.labelElement=i;let r=e.createElement("div");r.classList.add(h("v")),this.element.appendChild(r),this.valueElement=r}};let LabelController=class LabelController extends BladeController{constructor(e,t){let i=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{view:new LabelView(e,{props:t.props,viewProps:i}),viewProps:i})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}};let c={id:"button",type:"blade",accept(e){let t=parseParams(e,{title:r.required.string,view:r.required.constant("button"),label:r.optional.string});return t?{params:t}:null},controller:e=>new LabelController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:new ButtonController(e.document,{props:ValueMap.fromObject({title:e.params.title}),viewProps:e.viewProps})}),api:e=>e.controller instanceof LabelController&&e.controller.valueController instanceof ButtonController?new ButtonApi(e.controller):null};let ValueBladeController=class ValueBladeController extends BladeController{constructor(e){super(e),this.value=e.value}};function createBlade(){return new ValueMap({positions:createValue([],{equals:deepEqualsArray})})}let Foldable=class Foldable extends ValueMap{constructor(e){super(e)}static create(e){let t=ValueMap.createCore({completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null});return new Foldable(t)}get styleExpanded(){var e;return null!==(e=this.get("temporaryExpanded"))&&void 0!==e?e:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";let e=this.get("expandedHeight");return this.get("shouldFixHeight")&&!isEmpty(e)?`${e}px`:"auto"}bindExpandedClass(e,t){let onExpand=()=>{let i=this.styleExpanded;i?e.classList.add(t):e.classList.remove(t)};bindValueMap(this,"expanded",onExpand),bindValueMap(this,"temporaryExpanded",onExpand)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}};function computeExpandedFolderHeight(e,t){let i=0;return disableTransitionTemporarily(t,()=>{e.set("expandedHeight",null),e.set("temporaryExpanded",!0),forceReflow(t),i=t.clientHeight,e.set("temporaryExpanded",null),forceReflow(t)}),i}function applyHeight(e,t){t.style.height=e.styleHeight}function bindFoldable(e,t){e.value("expanded").emitter.on("beforechange",()=>{if(e.set("completed",!1),isEmpty(e.get("expandedHeight"))){let i=computeExpandedFolderHeight(e,t);i>0&&e.set("expandedHeight",i)}e.set("shouldFixHeight",!0),forceReflow(t)}),e.emitter.on("change",()=>{applyHeight(e,t)}),applyHeight(e,t),t.addEventListener("transitionend",t=>{"height"===t.propertyName&&e.cleanUpTransition()})}let RackLikeApi=class RackLikeApi extends BladeApi{constructor(e,t){super(e),this.rackApi_=t}};function addButtonAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"button"}))}function addFolderAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"folder"}))}function addSeparatorAsBlade(e,t){let i=null!=t?t:{};return e.addBlade(Object.assign(Object.assign({},i),{view:"separator"}))}function addTabAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"tab"}))}let NestedOrderedSet=class NestedOrderedSet{constructor(e){this.emitter=new Emitter,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=e}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(e){for(let t of this.allItems())if(e(t))return t;return null}includes(e){return this.cache_.has(e)}add(e,t){if(this.includes(e))throw TpError.shouldNeverHappen();let i=void 0!==t?t:this.items_.length;this.items_.splice(i,0,e),this.cache_.add(e);let r=this.extract_(e);r&&(r.emitter.on("add",this.onSubListAdd_),r.emitter.on("remove",this.onSubListRemove_),r.allItems().forEach(e=>{this.cache_.add(e)})),this.emitter.emit("add",{index:i,item:e,root:this,target:this})}remove(e){let t=this.items_.indexOf(e);if(t<0)return;this.items_.splice(t,1),this.cache_.delete(e);let i=this.extract_(e);i&&(i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:t,item:e,root:this,target:this})}onSubListAdd_(e){this.cache_.add(e.item),this.emitter.emit("add",{index:e.index,item:e.item,root:this,target:e.target})}onSubListRemove_(e){this.cache_.delete(e.item),this.emitter.emit("remove",{index:e.index,item:e.item,root:this,target:e.target})}};let InputBindingApi=class InputBindingApi extends BladeApi{constructor(e){super(e),this.onBindingChange_=this.onBindingChange_.bind(this),this.emitter_=new Emitter,this.controller_.binding.emitter.on("change",this.onBindingChange_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingChange_(e){let t=e.sender.target.read();this.emitter_.emit("change",{event:new TpChangeEvent(this,t,this.controller_.binding.target.presetKey,e.options.last)})}};let InputBindingController=class InputBindingController extends LabelController{constructor(e,t){super(e,t),this.binding=t.binding}};let MonitorBindingApi=class MonitorBindingApi extends BladeApi{constructor(e){super(e),this.onBindingUpdate_=this.onBindingUpdate_.bind(this),this.emitter_=new Emitter,this.controller_.binding.emitter.on("update",this.onBindingUpdate_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingUpdate_(e){let t=e.sender.target.read();this.emitter_.emit("update",{event:new TpUpdateEvent(this,t,this.controller_.binding.target.presetKey)})}};let MonitorBindingController=class MonitorBindingController extends LabelController{constructor(e,t){super(e,t),this.binding=t.binding,this.viewProps.bindDisabled(this.binding.ticker),this.viewProps.handleDispose(()=>{this.binding.dispose()})}};function findSubBladeApiSet(e){return e instanceof RackApi?e.apiSet_:e instanceof RackLikeApi?e.rackApi_.apiSet_:null}function getApiByController(e,t){let i=e.find(e=>e.controller_===t);if(!i)throw TpError.shouldNeverHappen();return i}function createBindingTarget(e,t,i){if(!BindingTarget.isBindable(e))throw TpError.notBindable();return new BindingTarget(e,t,i)}let RackApi=class RackApi extends BladeApi{constructor(e,t){super(e),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this),this.onRackInputChange_=this.onRackInputChange_.bind(this),this.onRackMonitorUpdate_=this.onRackMonitorUpdate_.bind(this),this.emitter_=new Emitter,this.apiSet_=new NestedOrderedSet(findSubBladeApiSet),this.pool_=t;let i=this.controller_.rack;i.emitter.on("add",this.onRackAdd_),i.emitter.on("remove",this.onRackRemove_),i.emitter.on("inputchange",this.onRackInputChange_),i.emitter.on("monitorupdate",this.onRackMonitorUpdate_),i.children.forEach(e=>{this.setUpApi_(e)})}get children(){return this.controller_.rack.children.map(e=>getApiByController(this.apiSet_,e))}addInput(e,t,i){let r=null!=i?i:{},s=this.controller_.view.element.ownerDocument,a=this.pool_.createInput(s,createBindingTarget(e,t,r.presetKey),r),n=new InputBindingApi(a);return this.add(n,r.index)}addMonitor(e,t,i){let r=null!=i?i:{},s=this.controller_.view.element.ownerDocument,a=this.pool_.createMonitor(s,createBindingTarget(e,t),r),n=new MonitorBindingApi(a);return this.add(n,r.index)}addFolder(e){return addFolderAsBlade(this,e)}addButton(e){return addButtonAsBlade(this,e)}addSeparator(e){return addSeparatorAsBlade(this,e)}addTab(e){return addTabAsBlade(this,e)}add(e,t){this.controller_.rack.add(e.controller_,t);let i=this.apiSet_.find(t=>t.controller_===e.controller_);return i&&this.apiSet_.remove(i),this.apiSet_.add(e),e}remove(e){this.controller_.rack.remove(e.controller_)}addBlade(e){let t=this.controller_.view.element.ownerDocument,i=this.pool_.createBlade(t,e),r=this.pool_.createBladeApi(i);return this.add(r,e.index)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}setUpApi_(e){let t=this.apiSet_.find(t=>t.controller_===e);t||this.apiSet_.add(this.pool_.createBladeApi(e))}onRackAdd_(e){this.setUpApi_(e.bladeController)}onRackRemove_(e){if(e.isRoot){let t=getApiByController(this.apiSet_,e.bladeController);this.apiSet_.remove(t)}}onRackInputChange_(e){let t=e.bladeController;if(t instanceof InputBindingController){let i=getApiByController(this.apiSet_,t),r=t.binding;this.emitter_.emit("change",{event:new TpChangeEvent(i,r.target.read(),r.target.presetKey,e.options.last)})}else if(t instanceof ValueBladeController){let i=getApiByController(this.apiSet_,t);this.emitter_.emit("change",{event:new TpChangeEvent(i,t.value.rawValue,void 0,e.options.last)})}}onRackMonitorUpdate_(e){if(!(e.bladeController instanceof MonitorBindingController))throw TpError.shouldNeverHappen();let t=getApiByController(this.apiSet_,e.bladeController),i=e.bladeController.binding;this.emitter_.emit("update",{event:new TpUpdateEvent(t,i.target.read(),i.target.presetKey)})}};let FolderApi=class FolderApi extends RackLikeApi{constructor(e,t){super(e,new RackApi(e.rackController,t)),this.emitter_=new Emitter,this.controller_.foldable.value("expanded").emitter.on("change",e=>{this.emitter_.emit("fold",{event:new TpFoldEvent(this,e.sender.rawValue)})}),this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})})}get expanded(){return this.controller_.foldable.get("expanded")}set expanded(e){this.controller_.foldable.set("expanded",e)}get title(){return this.controller_.props.get("title")}set title(e){this.controller_.props.set("title",e)}get children(){return this.rackApi_.children}addInput(e,t,i){return this.rackApi_.addInput(e,t,i)}addMonitor(e,t,i){return this.rackApi_.addMonitor(e,t,i)}addFolder(e){return this.rackApi_.addFolder(e)}addButton(e){return this.rackApi_.addButton(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){return this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addBlade(e){return this.rackApi_.addBlade(e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}};let RackLikeController=class RackLikeController extends BladeController{constructor(e){super({blade:e.blade,view:e.view,viewProps:e.rackController.viewProps}),this.rackController=e.rackController}};let PlainView=class PlainView{constructor(e,t){let i=ClassName(t.viewName);this.element=e.createElement("div"),this.element.classList.add(i()),t.viewProps.bindClassModifiers(this.element)}};function findInputBindingController(e,t){for(let i=0;it instanceof e)}onSetAdd_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("add",{bladeController:e.item,index:e.index,isRoot:t,sender:this}),!t)return;let i=e.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),i instanceof InputBindingController)i.binding.emitter.on("change",this.onChildInputChange_);else if(i instanceof MonitorBindingController)i.binding.emitter.on("update",this.onChildMonitorUpdate_);else if(i instanceof ValueBladeController)i.value.emitter.on("change",this.onChildValueChange_);else{let e=findSubRack(i);if(e){let t=e.emitter;t.on("layout",this.onDescendantLayout_),t.on("inputchange",this.onDescendantInputChange_),t.on("monitorupdate",this.onDescendantMonitorUpdate_)}}}onSetRemove_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("remove",{bladeController:e.item,isRoot:t,sender:this}),!t)return;let i=e.item;if(i instanceof InputBindingController)i.binding.emitter.off("change",this.onChildInputChange_);else if(i instanceof MonitorBindingController)i.binding.emitter.off("update",this.onChildMonitorUpdate_);else if(i instanceof ValueBladeController)i.value.emitter.off("change",this.onChildValueChange_);else{let e=findSubRack(i);if(e){let t=e.emitter;t.off("layout",this.onDescendantLayout_),t.off("inputchange",this.onDescendantInputChange_),t.off("monitorupdate",this.onDescendantMonitorUpdate_)}}}updatePositions_(){let e=this.bcSet_.items.filter(e=>!e.viewProps.get("hidden")),t=e[0],i=e[e.length-1];this.bcSet_.items.forEach(e=>{let r=[];e===t&&(r.push("first"),(!this.blade_||this.blade_.get("positions").includes("veryfirst"))&&r.push("veryfirst")),e===i&&(r.push("last"),(!this.blade_||this.blade_.get("positions").includes("verylast"))&&r.push("verylast")),e.blade.set("positions",r)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){let e=this.bcSet_.items.filter(e=>e.viewProps.get("disposed"));e.forEach(e=>{this.bcSet_.remove(e)})}onChildInputChange_(e){let t=findInputBindingController(this.find(InputBindingController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:t,options:e.options,sender:this})}onChildMonitorUpdate_(e){let t=findMonitorBindingController(this.find(MonitorBindingController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("monitorupdate",{bladeController:t,sender:this})}onChildValueChange_(e){let t=findValueBladeController(this.find(ValueBladeController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:t,options:e.options,sender:this})}onDescendantLayout_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onDescendantInputChange_(e){this.emitter.emit("inputchange",{bladeController:e.bladeController,options:e.options,sender:this})}onDescendantMonitorUpdate_(e){this.emitter.emit("monitorupdate",{bladeController:e.bladeController,sender:this})}onBladePositionsChange_(){this.updatePositions_()}};let RackController=class RackController extends BladeController{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new PlainView(e,{viewName:"brk",viewProps:t.viewProps})})),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);let i=new BladeRack({blade:t.root?void 0:t.blade,viewProps:t.viewProps});i.emitter.on("add",this.onRackAdd_),i.emitter.on("remove",this.onRackRemove_),this.rack=i,this.viewProps.handleDispose(()=>{for(let e=this.rack.children.length-1;e>=0;e--){let t=this.rack.children[e];t.viewProps.set("disposed",!0)}})}onRackAdd_(e){e.isRoot&&insertElementAt(this.view.element,e.bladeController.view.element,e.index)}onRackRemove_(e){e.isRoot&&removeElement(e.bladeController.view.element)}};let u=ClassName("cnt");let FolderView=class FolderView{constructor(e,t){var i;this.className_=ClassName(null!==(i=t.viewName)&&void 0!==i?i:"fld"),this.element=e.createElement("div"),this.element.classList.add(this.className_(),u()),t.viewProps.bindClassModifiers(this.element),this.foldable_=t.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),bindValueMap(this.foldable_,"completed",valueToClassName(this.element,this.className_(void 0,"cpl")));let r=e.createElement("button");r.classList.add(this.className_("b")),bindValueMap(t.props,"title",e=>{isEmpty(e)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r;let s=e.createElement("div");s.classList.add(this.className_("i")),this.element.appendChild(s);let a=e.createElement("div");a.classList.add(this.className_("t")),bindValueToTextContent(t.props.value("title"),a),this.buttonElement.appendChild(a),this.titleElement=a;let n=e.createElement("div");n.classList.add(this.className_("m")),this.buttonElement.appendChild(n);let o=t.containerElement;o.classList.add(this.className_("c")),this.element.appendChild(o),this.containerElement=o}};let FolderController=class FolderController extends RackLikeController{constructor(e,t){var i;let r=Foldable.create(null===(i=t.expanded)||void 0===i||i),s=new RackController(e,{blade:t.blade,root:t.root,viewProps:t.viewProps});super(Object.assign(Object.assign({},t),{rackController:s,view:new FolderView(e,{containerElement:s.view.element,foldable:r,props:t.props,viewName:t.root?"rot":void 0,viewProps:t.viewProps})})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=t.props,this.foldable=r,bindFoldable(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}};let d={id:"folder",type:"blade",accept(e){let t=parseParams(e,{title:r.required.string,view:r.required.constant("folder"),expanded:r.optional.boolean});return t?{params:t}:null},controller:e=>new FolderController(e.document,{blade:e.blade,expanded:e.params.expanded,props:ValueMap.fromObject({title:e.params.title}),viewProps:e.viewProps}),api:e=>e.controller instanceof FolderController?new FolderApi(e.controller,e.pool):null};let LabeledValueController=class LabeledValueController extends ValueBladeController{constructor(e,t){let i=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{value:t.valueController.value,view:new LabelView(e,{props:t.props,viewProps:i}),viewProps:i})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}};let SeparatorApi=class SeparatorApi extends BladeApi{};let _=ClassName("spr");let SeparatorView=class SeparatorView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(_()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("hr");i.classList.add(_("r")),this.element.appendChild(i)}};let SeparatorController=class SeparatorController extends BladeController{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new SeparatorView(e,{viewProps:t.viewProps})}))}};let p={id:"separator",type:"blade",accept(e){let t=parseParams(e,{view:r.required.constant("separator")});return t?{params:t}:null},controller:e=>new SeparatorController(e.document,{blade:e.blade,viewProps:e.viewProps}),api:e=>e.controller instanceof SeparatorController?new SeparatorApi(e.controller):null},f=ClassName("tbi");let TabItemView=class TabItemView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(f()),t.viewProps.bindClassModifiers(this.element),bindValueMap(t.props,"selected",e=>{e?this.element.classList.add(f(void 0,"sel")):this.element.classList.remove(f(void 0,"sel"))});let i=e.createElement("button");i.classList.add(f("b")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let r=e.createElement("div");r.classList.add(f("t")),bindValueToTextContent(t.props.value("title"),r),this.buttonElement.appendChild(r),this.titleElement=r}};let TabItemController=class TabItemController{constructor(e,t){this.emitter=new Emitter,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new TabItemView(e,{props:t.props,viewProps:t.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}};let TabPageController=class TabPageController{constructor(e,t){this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new TabItemController(e,{props:t.itemProps,viewProps:ViewProps.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.cc_=new RackController(e,{blade:createBlade(),viewProps:ViewProps.create()}),this.props=t.props,bindValueMap(this.props,"selected",e=>{this.itemController.props.set("selected",e),this.contentController.viewProps.set("hidden",!e)})}get itemController(){return this.ic_}get contentController(){return this.cc_}onItemClick_(){this.props.set("selected",!0)}};let TabPageApi=class TabPageApi{constructor(e,t){this.controller_=e,this.rackApi_=t}get title(){var e;return null!==(e=this.controller_.itemController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.itemController.props.set("title",e)}get selected(){return this.controller_.props.get("selected")}set selected(e){this.controller_.props.set("selected",e)}get children(){return this.rackApi_.children}addButton(e){return this.rackApi_.addButton(e)}addFolder(e){return this.rackApi_.addFolder(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addInput(e,t,i){return this.rackApi_.addInput(e,t,i)}addMonitor(e,t,i){return this.rackApi_.addMonitor(e,t,i)}addBlade(e){return this.rackApi_.addBlade(e)}};let TabApi=class TabApi extends RackLikeApi{constructor(e,t){super(e,new RackApi(e.rackController,t)),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.onSelect_=this.onSelect_.bind(this),this.emitter_=new Emitter,this.pageApiMap_=new Map,this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})}),this.controller_.tab.selectedIndex.emitter.on("change",this.onSelect_),this.controller_.pageSet.emitter.on("add",this.onPageAdd_),this.controller_.pageSet.emitter.on("remove",this.onPageRemove_),this.controller_.pageSet.items.forEach(e=>{this.setUpPageApi_(e)})}get pages(){return this.controller_.pageSet.items.map(e=>{let t=this.pageApiMap_.get(e);if(!t)throw TpError.shouldNeverHappen();return t})}addPage(e){let t=this.controller_.view.element.ownerDocument,i=new TabPageController(t,{itemProps:ValueMap.fromObject({selected:!1,title:e.title}),props:ValueMap.fromObject({selected:!1})});this.controller_.add(i,e.index);let r=this.pageApiMap_.get(i);if(!r)throw TpError.shouldNeverHappen();return r}removePage(e){this.controller_.remove(e)}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}setUpPageApi_(e){let t=this.rackApi_.apiSet_.find(t=>t.controller_===e.contentController);if(!t)throw TpError.shouldNeverHappen();let i=new TabPageApi(e,t);this.pageApiMap_.set(e,i)}onPageAdd_(e){this.setUpPageApi_(e.item)}onPageRemove_(e){let t=this.pageApiMap_.get(e.item);if(!t)throw TpError.shouldNeverHappen();this.pageApiMap_.delete(e.item)}onSelect_(e){this.emitter_.emit("select",{event:new TpTabSelectEvent(this,e.rawValue)})}};let Tab=class Tab{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=createValue(!0),this.selectedIndex=createValue(-1),this.items_=[]}add(e,t){let i=null!=t?t:this.items_.length;this.items_.splice(i,0,e),e.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(e){let t=this.items_.indexOf(e);t<0||(this.items_.splice(t,1),e.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length){this.selectedIndex.rawValue=-1,this.empty.rawValue=!0;return}let e=this.items_.findIndex(e=>e.rawValue);e<0?(this.items_.forEach((e,t)=>{e.rawValue=0===t}),this.selectedIndex.rawValue=0):(this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e),this.empty.rawValue=!1}onItemSelectedChange_(e){if(e.rawValue){let t=this.items_.findIndex(t=>t===e.sender);this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t}else this.keepSelection_()}};let m=ClassName("tab");let TabView=class TabView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(m(),u()),t.viewProps.bindClassModifiers(this.element),bindValue(t.empty,valueToClassName(this.element,m(void 0,"nop")));let i=e.createElement("div");i.classList.add(m("t")),this.element.appendChild(i),this.itemsElement=i;let r=e.createElement("div");r.classList.add(m("i")),this.element.appendChild(r);let s=t.contentsElement;s.classList.add(m("c")),this.element.appendChild(s),this.contentsElement=s}};let TabController=class TabController extends RackLikeController{constructor(e,t){let i=new RackController(e,{blade:t.blade,viewProps:t.viewProps}),r=new Tab;super({blade:t.blade,rackController:i,view:new TabView(e,{contentsElement:i.view.element,empty:r.empty,viewProps:t.viewProps})}),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.pageSet_=new NestedOrderedSet(()=>null),this.pageSet_.emitter.on("add",this.onPageAdd_),this.pageSet_.emitter.on("remove",this.onPageRemove_),this.tab=r}get pageSet(){return this.pageSet_}add(e,t){this.pageSet_.add(e,t)}remove(e){this.pageSet_.remove(this.pageSet_.items[e])}onPageAdd_(e){let t=e.item;insertElementAt(this.view.itemsElement,t.itemController.view.element,e.index),t.itemController.viewProps.set("parent",this.viewProps),this.rackController.rack.add(t.contentController,e.index),this.tab.add(t.props.value("selected"))}onPageRemove_(e){let t=e.item;removeElement(t.itemController.view.element),t.itemController.viewProps.set("parent",null),this.rackController.rack.remove(t.contentController),this.tab.remove(t.props.value("selected"))}};let g={id:"tab",type:"blade",accept(e){let t=parseParams(e,{pages:r.required.array(r.required.object({title:r.required.string})),view:r.required.constant("tab")});return t&&0!==t.pages.length?{params:t}:null},controller(e){let t=new TabController(e.document,{blade:e.blade,viewProps:e.viewProps});return e.params.pages.forEach(i=>{let r=new TabPageController(e.document,{itemProps:ValueMap.fromObject({selected:!1,title:i.title}),props:ValueMap.fromObject({selected:!1})});t.add(r)}),t},api:e=>e.controller instanceof TabController?new TabApi(e.controller,e.pool):null};function createBladeController(e,t){let i=e.accept(t.params);if(!i)return null;let s=r.optional.boolean(t.params.disabled).value,a=r.optional.boolean(t.params.hidden).value;return e.controller({blade:createBlade(),document:t.document,params:Object.assign(Object.assign({},i.params),{disabled:s,hidden:a}),viewProps:ViewProps.create({disabled:s,hidden:a})})}let ManualTicker=class ManualTicker{constructor(){this.disabled=!1,this.emitter=new Emitter}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}};let IntervalTicker=class IntervalTicker{constructor(e,t){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=e,this.emitter=new Emitter,this.interval_=t,this.setTimer_()}get disabled(){return this.disabled_}set disabled(e){this.disabled_=e,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;let e=this.doc_.defaultView;e&&e.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;let e=this.doc_.defaultView;e&&(this.timerId_=e.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}};let InputBinding=class InputBinding{constructor(e){this.onValueChange_=this.onValueChange_.bind(this),this.reader=e.reader,this.writer=e.writer,this.emitter=new Emitter,this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.target=e.target,this.read()}read(){let e=this.target.read();void 0!==e&&(this.value.rawValue=this.reader(e))}write_(e){this.writer(this.target,e)}onValueChange_(e){this.write_(e.rawValue),this.emitter.emit("change",{options:e.options,rawValue:e.rawValue,sender:this})}};function fillBuffer(e,t){for(;e.lengthe.length?i.splice(0,i.length-e.length):fillBuffer(i,e.length),i}let MonitorBinding=class MonitorBinding{constructor(e){this.onTick_=this.onTick_.bind(this),this.reader_=e.reader,this.target=e.target,this.emitter=new Emitter,this.value=e.value,this.ticker=e.ticker,this.ticker.emitter.on("tick",this.onTick_),this.read()}dispose(){this.ticker.dispose()}read(){let e=this.target.read();if(void 0===e)return;let t=this.value.rawValue,i=this.reader_(e);this.value.rawValue=createPushedBuffer(t,i),this.emitter.emit("update",{rawValue:i,sender:this})}onTick_(e){this.read()}};let CompositeConstraint=class CompositeConstraint{constructor(e){this.constraints=e}constrain(e){return this.constraints.reduce((e,t)=>t.constrain(e),e)}};function findConstraint(e,t){if(e instanceof t)return e;if(e instanceof CompositeConstraint){let i=e.constraints.reduce((e,i)=>e||(i instanceof t?i:null),null);if(i)return i}return null}let DefiniteRangeConstraint=class DefiniteRangeConstraint{constructor(e){this.values=ValueMap.fromObject({max:e.max,min:e.min})}constrain(e){let t=this.values.get("max"),i=this.values.get("min");return Math.min(Math.max(e,i),t)}};let ListConstraint=class ListConstraint{constructor(e){this.values=ValueMap.fromObject({options:e})}get options(){return this.values.get("options")}constrain(e){let t=this.values.get("options");if(0===t.length)return e;let i=t.filter(t=>t.value===e).length>0;return i?e:t[0].value}};let RangeConstraint=class RangeConstraint{constructor(e){this.values=ValueMap.fromObject({max:e.max,min:e.min})}get maxValue(){return this.values.get("max")}get minValue(){return this.values.get("min")}constrain(e){let t=this.values.get("max"),i=this.values.get("min"),r=e;return isEmpty(i)||(r=Math.max(r,i)),isEmpty(t)||(r=Math.min(r,t)),r}};let StepConstraint=class StepConstraint{constructor(e,t=0){this.step=e,this.origin=t}constrain(e){let t=this.origin%this.step,i=Math.round((e-t)/this.step);return t+i*this.step}};let v=ClassName("lst");let ListView=class ListView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.props_=t.props,this.element=e.createElement("div"),this.element.classList.add(v()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("select");i.classList.add(v("s")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;let r=e.createElement("div");r.classList.add(v("m")),r.appendChild(createSvgIconElement(e,"dropdown")),this.element.appendChild(r),t.value.emitter.on("change",this.onValueChange_),this.value_=t.value,bindValueMap(this.props_,"options",t=>{removeChildElements(this.selectElement),t.forEach(t=>{let i=e.createElement("option");i.textContent=t.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){let e=this.props_.get("options").map(e=>e.value);this.selectElement.selectedIndex=e.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}};let ListController=class ListController{constructor(e,t){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new ListView(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(e){let t=e.currentTarget;this.value.rawValue=this.props.get("options")[t.selectedIndex].value}};let x=ClassName("pop");let PopupView=class PopupView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(x()),t.viewProps.bindClassModifiers(this.element),bindValue(t.shows,valueToClassName(this.element,x(void 0,"v")))}};let PopupController=class PopupController{constructor(e,t){this.shows=createValue(!1),this.viewProps=t.viewProps,this.view=new PopupView(e,{shows:this.shows,viewProps:this.viewProps})}};let b=ClassName("txt");let TextView=class TextView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(b()),t.viewProps.bindClassModifiers(this.element),this.props_=t.props,this.props_.emitter.on("change",this.onChange_);let i=e.createElement("input");i.classList.add(b("i")),i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,t.value.emitter.on("change",this.onChange_),this.value_=t.value,this.refresh()}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value_.rawValue)}onChange_(){this.refresh()}};let TextController=class TextController{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=t.parser,this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new TextView(e,{props:t.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget,i=t.value,r=this.parser_(i);isEmpty(r)||(this.value.rawValue=r),this.view.refresh()}};function boolToString(e){return String(e)}function boolFromUnknown(e){return"false"!==e&&!!e}function BooleanFormatter(e){return boolToString(e)}let NumberLiteralNode=class NumberLiteralNode{constructor(e){this.text=e}evaluate(){return Number(this.text)}toString(){return this.text}};let T={"**":(e,t)=>Math.pow(e,t),"*":(e,t)=>e*t,"/":(e,t)=>e/t,"%":(e,t)=>e%t,"+":(e,t)=>e+t,"-":(e,t)=>e-t,"<<":(e,t)=>e<>":(e,t)=>e>>t,">>>":(e,t)=>e>>>t,"&":(e,t)=>e&t,"^":(e,t)=>e^t,"|":(e,t)=>e|t};let BinaryOperationNode=class BinaryOperationNode{constructor(e,t,i){this.left=t,this.operator=e,this.right=i}evaluate(){let e=T[this.operator];if(!e)throw Error(`unexpected binary operator: '${this.operator}`);return e(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}};let S={"+":e=>e,"-":e=>-e,"~":e=>~e};let UnaryOperationNode=class UnaryOperationNode{constructor(e,t){this.operator=e,this.expression=t}evaluate(){let e=S[this.operator];if(!e)throw Error(`unexpected unary operator: '${this.operator}`);return e(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}};function combineReader(e){return(t,i)=>{for(let r=0;rt.startsWith(e,i))[0];return r?(i+=r.length,{cursor:i+=readWhitespace(t,i).length,operator:r}):null}function createBinaryOperationExpressionParser(e,t){return(i,r)=>{let s=e(i,r);if(!s)return null;r=s.cursor;let a=s.evaluable;for(;;){let s=readBinaryOperator(t,i,r);if(!s)break;r=s.cursor;let n=e(i,r);if(!n)return null;r=n.cursor,a=new BinaryOperationNode(s.operator,a,n.evaluable)}return a?{cursor:r,evaluable:a}:null}}let R=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((e,t)=>createBinaryOperationExpressionParser(e,t),parseUnaryExpression);function parseExpression(e,t){return t+=readWhitespace(e,t).length,R(e,t)}function parseEcmaNumberExpression(e){let t=parseExpression(e,0);if(!t)return null;let i=t.cursor+readWhitespace(e,t.cursor).length;return i!==e.length?null:t.evaluable}function parseNumber(e){var t;let i=parseEcmaNumberExpression(e);return null!==(t=null==i?void 0:i.evaluate())&&void 0!==t?t:null}function numberFromUnknown(e){if("number"==typeof e)return e;if("string"==typeof e){let t=parseNumber(e);if(!isEmpty(t))return t}return 0}function numberToString(e){return String(e)}function createNumberFormatter(e){return t=>t.toFixed(Math.max(Math.min(e,20),0))}let P=createNumberFormatter(0);function formatPercentage(e){return P(e)+"%"}function stringFromUnknown(e){return String(e)}function formatString(e){return e}function connectValues({primary:e,secondary:t,forward:i,backward:r}){let s=!1;function preventFeedback(e){s||(s=!0,e(),s=!1)}e.emitter.on("change",r=>{preventFeedback(()=>{t.setRawValue(i(e,t),r.options)})}),t.emitter.on("change",s=>{preventFeedback(()=>{e.setRawValue(r(e,t),s.options)}),preventFeedback(()=>{t.setRawValue(i(e,t),s.options)})}),preventFeedback(()=>{t.setRawValue(i(e,t),{forceEmit:!1,last:!0})})}function getStepForKey(e,t){let i=e*(t.altKey?.1:1)*(t.shiftKey?10:1);return t.upKey?+i:t.downKey?-i:0}function getVerticalStepKeys(e){return{altKey:e.altKey,downKey:"ArrowDown"===e.key,shiftKey:e.shiftKey,upKey:"ArrowUp"===e.key}}function getHorizontalStepKeys(e){return{altKey:e.altKey,downKey:"ArrowLeft"===e.key,shiftKey:e.shiftKey,upKey:"ArrowRight"===e.key}}function isVerticalArrowKey(e){return"ArrowUp"===e||"ArrowDown"===e}function isArrowKey(e){return isVerticalArrowKey(e)||"ArrowLeft"===e||"ArrowRight"===e}function computeOffset$1(e,t){var i,r;let s=t.ownerDocument.defaultView,a=t.getBoundingClientRect();return{x:e.pageX-((null!==(i=s&&s.scrollX)&&void 0!==i?i:0)+a.left),y:e.pageY-((null!==(r=s&&s.scrollY)&&void 0!==r?r:0)+a.top)}}let PointerHandler=class PointerHandler{constructor(e){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=e,this.emitter=new Emitter,e.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),e.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),e.addEventListener("touchend",this.onTouchEnd_),e.addEventListener("mousedown",this.onMouseDown_)}computePosition_(e){let t=this.elem_.getBoundingClientRect();return{bounds:{width:t.width,height:t.height},point:e?{x:e.x,y:e.y}:null}}onMouseDown_(e){var t;e.preventDefault(),null===(t=e.currentTarget)||void 0===t||t.focus();let i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseMove_(e){this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseUp_(e){let t=this.elem_.ownerDocument;t.removeEventListener("mousemove",this.onDocumentMouseMove_),t.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onTouchStart_(e){e.preventDefault();let t=e.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-i.left,y:t.clientY-i.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchMove_(e){let t=e.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-i.left,y:t.clientY-i.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchEnd_(e){var t;let i=null!==(t=e.targetTouches.item(0))&&void 0!==t?t:this.lastTouch_,r=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(i?{x:i.clientX-r.left,y:i.clientY-r.top}:void 0),sender:this,shiftKey:e.shiftKey})}};function mapRange(e,t,i,r,s){return r+(e-t)/(i-t)*(s-r)}function getDecimalDigits(e){let t=String(e.toFixed(10)),i=t.split(".")[1];return i.replace(/0+$/,"").length}function constrainRange(e,t,i){return Math.min(Math.max(e,t),i)}let A=ClassName("txt");let NumberTextView=class NumberTextView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(A(),A(void 0,"num")),t.arrayPosition&&this.element.classList.add(A(void 0,t.arrayPosition)),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("input");i.classList.add(A("i")),i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=t.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(A()),this.inputElement.classList.add(A("i"));let r=e.createElement("div");r.classList.add(A("k")),this.element.appendChild(r),this.knobElement=r;let s=e.createElementNS(o,"svg");s.classList.add(A("g")),this.knobElement.appendChild(s);let a=e.createElementNS(o,"path");a.classList.add(A("gb")),s.appendChild(a),this.guideBodyElem_=a;let n=e.createElementNS(o,"path");n.classList.add(A("gh")),s.appendChild(n),this.guideHeadElem_=n;let l=e.createElement("div");l.classList.add(ClassName("tt")()),this.knobElement.appendChild(l),this.tooltipElem_=l,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.refresh()}onDraggingChange_(e){if(null===e.rawValue){this.element.classList.remove(A(void 0,"drg"));return}this.element.classList.add(A(void 0,"drg"));let t=e.rawValue/this.props_.get("draggingScale"),i=t+(t>0?-1:t<0?1:0),r=constrainRange(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",`M ${i+r},0 L${i},4 L${i+r},8 M ${t},-1 L${t},9`),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${t},4`);let s=this.props_.get("formatter");this.tooltipElem_.textContent=s(this.value.rawValue),this.tooltipElem_.style.left=`${t}px`}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value.rawValue)}onChange_(){this.refresh()}};let NumberTextController=class NumberTextController{constructor(e,t){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.parser_=t.parser,this.props=t.props,this.sliderProps_=null!==(i=t.sliderProps)&&void 0!==i?i:null,this.value=t.value,this.viewProps=t.viewProps,this.dragging_=createValue(null),this.view=new NumberTextView(e,{arrayPosition:t.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);let r=new PointerHandler(this.view.knobElement);r.emitter.on("down",this.onPointerDown_),r.emitter.on("move",this.onPointerMove_),r.emitter.on("up",this.onPointerUp_)}constrainValue_(e){var t,i;let r=null===(t=this.sliderProps_)||void 0===t?void 0:t.get("minValue"),s=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("maxValue"),a=e;return void 0!==r&&(a=Math.max(a,r)),void 0!==s&&(a=Math.min(a,s)),a}onInputChange_(e){let t=e.currentTarget,i=t.value,r=this.parser_(i);isEmpty(r)||(this.value.rawValue=this.constrainValue_(r)),this.view.refresh()}onInputKeyDown_(e){let t=getStepForKey(this.baseStep_,getVerticalStepKeys(e));0!==t&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+t),{forceEmit:!1,last:!1})}onInputKeyUp_(e){let t=getStepForKey(this.baseStep_,getVerticalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(e){if(!e.point)return null;let t=e.point.x-e.bounds.width/2;return this.constrainValue_(this.originRawValue_+t*this.props.get("draggingScale"))}onPointerMove_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}};let M=ClassName("sld");let SliderView=class SliderView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(M()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(M("t")),t.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;let r=e.createElement("div");r.classList.add(M("k")),this.trackElement.appendChild(r),this.knobElement=r,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.update_()}update_(){let e=constrainRange(mapRange(this.value.rawValue,this.props_.get("minValue"),this.props_.get("maxValue"),0,100),0,100);this.knobElement.style.width=`${e}%`}onChange_(){this.update_()}};let SliderController=class SliderController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.value=t.value,this.viewProps=t.viewProps,this.props=t.props,this.view=new SliderView(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){e.point&&this.value.setRawValue(mapRange(constrainRange(e.point.x,0,e.bounds.width),0,e.bounds.width,this.props.get("minValue"),this.props.get("maxValue")),t)}onPointerDownOrMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(this.baseStep_,getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue+t,{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(this.baseStep_,getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let I=ClassName("sldtxt");let SliderTextView=class SliderTextView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(I());let i=e.createElement("div");i.classList.add(I("s")),this.sliderView_=t.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(I("t")),this.textView_=t.textView,r.appendChild(this.textView_.element),this.element.appendChild(r)}};let SliderTextController=class SliderTextController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.sliderC_=new SliderController(e,{baseStep:t.baseStep,props:t.sliderProps,value:t.value,viewProps:this.viewProps}),this.textC_=new NumberTextController(e,{baseStep:t.baseStep,parser:t.parser,props:t.textProps,sliderProps:t.sliderProps,value:t.value,viewProps:t.viewProps}),this.view=new SliderTextView(e,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}};function writePrimitive(e,t){e.write(t)}function parseListOptions(e){return Array.isArray(e)?r.required.array(r.required.object({text:r.required.string,value:r.required.raw}))(e).value:"object"==typeof e?r.required.raw(e).value:void 0}function parsePickerLayout(e){if("inline"===e||"popup"===e)return e}function parsePointDimensionParams(e){return r.required.object({max:r.optional.number,min:r.optional.number,step:r.optional.number})(e).value}function normalizeListOptions(e){if(Array.isArray(e))return e;let t=[];return Object.keys(e).forEach(i=>{t.push({text:i,value:e[i]})}),t}function createListConstraint(e){return isEmpty(e)?null:new ListConstraint(normalizeListOptions(e))}function findStep(e){let t=e?findConstraint(e,StepConstraint):null;return t?t.step:null}function getSuitableDecimalDigits(e,t){let i=e&&findConstraint(e,StepConstraint);return i?getDecimalDigits(i.step):Math.max(getDecimalDigits(t),2)}function getBaseStep(e){let t=findStep(e);return null!=t?t:1}function getSuitableDraggingScale(e,t){var i;let r=e&&findConstraint(e,StepConstraint),s=Math.abs(null!==(i=null==r?void 0:r.step)&&void 0!==i?i:t);return 0===s?.1:Math.pow(10,Math.floor(Math.log10(s))-1)}let D=ClassName("ckb");let CheckboxView=class CheckboxView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(D()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("label");i.classList.add(D("l")),this.element.appendChild(i);let r=e.createElement("input");r.classList.add(D("i")),r.type="checkbox",i.appendChild(r),this.inputElement=r,t.viewProps.bindDisabled(this.inputElement);let s=e.createElement("div");s.classList.add(D("w")),i.appendChild(s);let a=createSvgIconElement(e,"check");s.appendChild(a),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}};let CheckboxController=class CheckboxController{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new CheckboxView(e,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget;this.value.rawValue=t.checked}};function createConstraint$6(e){let t=[],i=createListConstraint(e.options);return i&&t.push(i),new CompositeConstraint(t)}let O={id:"input-bool",type:"input",accept:(e,t)=>{if("boolean"!=typeof e)return null;let i=parseParams(t,{options:r.optional.custom(parseListOptions)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>boolFromUnknown,constraint:e=>createConstraint$6(e.params),writer:e=>writePrimitive},controller:e=>{let t=e.document,i=e.value,r=e.constraint,s=r&&findConstraint(r,ListConstraint);return s?new ListController(t,{props:new ValueMap({options:s.values.value("options")}),value:i,viewProps:e.viewProps}):new CheckboxController(t,{value:i,viewProps:e.viewProps})}},B=ClassName("col");let ColorView=class ColorView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(B()),t.foldable.bindExpandedClass(this.element,B(void 0,"expanded")),bindValueMap(t.foldable,"completed",valueToClassName(this.element,B(void 0,"cpl")));let i=e.createElement("div");i.classList.add(B("h")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(B("s")),i.appendChild(r),this.swatchElement=r;let s=e.createElement("div");if(s.classList.add(B("t")),i.appendChild(s),this.textElement=s,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(B("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};function rgbToHslInt(e,t,i){let r=constrainRange(e/255,0,1),s=constrainRange(t/255,0,1),a=constrainRange(i/255,0,1),n=Math.max(r,s,a),o=Math.min(r,s,a),l=n-o,h=0,c=0;return 0!==l&&(c=l/(1-Math.abs(n+o-1)),h=(h=r===n?(s-a)/l:s===n?2+(a-r)/l:4+(r-s)/l)/6+(h<0?1:0)),[360*h,100*c,100*((o+n)/2)]}function hslToRgbInt(e,t,i){let r,s,a;let n=(e%360+360)%360,o=constrainRange(t/100,0,1),l=constrainRange(i/100,0,1),h=(1-Math.abs(2*l-1))*o,c=h*(1-Math.abs(n/60%2-1)),u=l-h/2;return n>=0&&n<60?[r,s,a]=[h,c,0]:n>=60&&n<120?[r,s,a]=[c,h,0]:n>=120&&n<180?[r,s,a]=[0,h,c]:n>=180&&n<240?[r,s,a]=[0,c,h]:n>=240&&n<300?[r,s,a]=[c,0,h]:[r,s,a]=[h,0,c],[(r+u)*255,(s+u)*255,(a+u)*255]}function rgbToHsvInt(e,t,i){let r=constrainRange(e/255,0,1),s=constrainRange(t/255,0,1),a=constrainRange(i/255,0,1),n=Math.max(r,s,a),o=n-Math.min(r,s,a);return[0===o?0:n===r?60*(((s-a)/o%6+6)%6):n===s?60*((a-r)/o+2):60*((r-s)/o+4),100*(0===n?0:o/n),100*n]}function hsvToRgbInt(e,t,i){let r,s,a;let n=(e%360+360)%360,o=constrainRange(t/100,0,1),l=constrainRange(i/100,0,1),h=l*o,c=h*(1-Math.abs(n/60%2-1)),u=l-h;return n>=0&&n<60?[r,s,a]=[h,c,0]:n>=60&&n<120?[r,s,a]=[c,h,0]:n>=120&&n<180?[r,s,a]=[0,h,c]:n>=180&&n<240?[r,s,a]=[0,c,h]:n>=240&&n<300?[r,s,a]=[c,0,h]:[r,s,a]=[h,0,c],[(r+u)*255,(s+u)*255,(a+u)*255]}function hslToHsvInt(e,t,i){let r=i+t*(100-Math.abs(2*i-100))/200;return[e,0!==r?t*(100-Math.abs(2*i-100))/r:0,i+t*(100-Math.abs(2*i-100))/200]}function hsvToHslInt(e,t,i){let r=100-Math.abs(i*(200-t)/100-100);return[e,0!==r?t*i/r:0,i*(200-t)/200]}function removeAlphaComponent(e){return[e[0],e[1],e[2]]}function appendAlphaComponent(e,t){return[e[0],e[1],e[2],t]}let N={hsl:{hsl:(e,t,i)=>[e,t,i],hsv:hslToHsvInt,rgb:hslToRgbInt},hsv:{hsl:hsvToHslInt,hsv:(e,t,i)=>[e,t,i],rgb:hsvToRgbInt},rgb:{hsl:rgbToHslInt,hsv:rgbToHsvInt,rgb:(e,t,i)=>[e,t,i]}};function getColorMaxComponents(e,t){return["float"===t?1:"rgb"===e?255:360,"float"===t?1:"rgb"===e?255:100,"float"===t?1:"rgb"===e?255:100]}function loopHueRange(e,t){return e===t?t:(e%t+t)%t}function constrainColorComponents(e,t,i){var r;let s=getColorMaxComponents(t,i);return["rgb"===t?constrainRange(e[0],0,s[0]):loopHueRange(e[0],s[0]),constrainRange(e[1],0,s[1]),constrainRange(e[2],0,s[2]),constrainRange(null!==(r=e[3])&&void 0!==r?r:1,0,1)]}function convertColorType(e,t,i,r){let s=getColorMaxComponents(t,i),a=getColorMaxComponents(t,r);return e.map((e,t)=>e/s[t]*a[t])}function convertColor(e,t,i){let r=convertColorType(e,t.mode,t.type,"int"),s=N[t.mode][i.mode](...r);return convertColorType(s,i.mode,"int",i.type)}function isRgbColorComponent(e,t){return!("object"!=typeof e||isEmpty(e))&&t in e&&"number"==typeof e[t]}let Color=class Color{static black(e="int"){return new Color([0,0,0],"rgb",e)}static fromObject(e,t="int"){let i="a"in e?[e.r,e.g,e.b,e.a]:[e.r,e.g,e.b];return new Color(i,"rgb",t)}static toRgbaObject(e,t="int"){return e.toRgbaObject(t)}static isRgbColorObject(e){return isRgbColorComponent(e,"r")&&isRgbColorComponent(e,"g")&&isRgbColorComponent(e,"b")}static isRgbaColorObject(e){return this.isRgbColorObject(e)&&isRgbColorComponent(e,"a")}static isColorObject(e){return this.isRgbColorObject(e)}static equals(e,t){if(e.mode!==t.mode)return!1;let i=e.comps_,r=t.comps_;for(let e=0;ee.inputElement)];return this.alphaViews_&&e.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),e}};function parseColorType(e){return"int"===e?"int":"float"===e?"float":void 0}function parseColorInputParams(e){return parseParams(e,{alpha:r.optional.boolean,color:r.optional.object({alpha:r.optional.boolean,type:r.optional.custom(parseColorType)}),expanded:r.optional.boolean,picker:r.optional.custom(parsePickerLayout)})}function getBaseStepForColor(e){return e?.1:1}function extractColorType(e){var t;return null===(t=e.color)||void 0===t?void 0:t.type}function equalsStringColorFormat(e,t){return e.alpha===t.alpha&&e.mode===t.mode&&e.notation===t.notation&&e.type===t.type}function parseCssNumberOrPercentage(e,t){let i=e.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*t,t):Math.min(parseFloat(e),t)}let w={deg:e=>e,grad:e=>360*e/400,rad:e=>360*e/(2*Math.PI),turn:e=>360*e};function parseCssNumberOrAngle(e){let t=e.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!t)return parseFloat(e);let i=parseFloat(t[1]),r=t[2];return w[r](i)}function parseFunctionalRgbColorComponents(e){let t=e.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[parseCssNumberOrPercentage(t[1],255),parseCssNumberOrPercentage(t[2],255),parseCssNumberOrPercentage(t[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function createFunctionalRgbColorParser(e){return t=>{let i=parseFunctionalRgbColorComponents(t);return i?new Color(i,"rgb",e):null}}function parseFunctionalRgbaColorComponents(e){let t=e.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[parseCssNumberOrPercentage(t[1],255),parseCssNumberOrPercentage(t[2],255),parseCssNumberOrPercentage(t[3],255),parseCssNumberOrPercentage(t[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function createFunctionalRgbaColorParser(e){return t=>{let i=parseFunctionalRgbaColorComponents(t);return i?new Color(i,"rgb",e):null}}function parseHslColorComponents(e){let t=e.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[parseCssNumberOrAngle(t[1]),parseCssNumberOrPercentage(t[2],100),parseCssNumberOrPercentage(t[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function createHslColorParser(e){return t=>{let i=parseHslColorComponents(t);return i?new Color(i,"hsl",e):null}}function parseHslaColorComponents(e){let t=e.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let i=[parseCssNumberOrAngle(t[1]),parseCssNumberOrPercentage(t[2],100),parseCssNumberOrPercentage(t[3],100),parseCssNumberOrPercentage(t[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function createHslaColorParser(e){return t=>{let i=parseHslaColorComponents(t);return i?new Color(i,"hsl",e):null}}function parseHexRgbColorComponents(e){let t=e.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)];let i=e.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function parseHexRgbColor(e){let t=parseHexRgbColorComponents(e);return t?new Color(t,"rgb","int"):null}function parseHexRgbaColorComponents(e){let t=e.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),mapRange(parseInt(t[4]+t[4],16),0,255,0,1)];let i=e.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),mapRange(parseInt(i[4],16),0,255,0,1)]:null}function parseHexRgbaColor(e){let t=parseHexRgbaColorComponents(e);return t?new Color(t,"rgb","int"):null}function parseObjectRgbColorComponents(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let i=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function createObjectRgbColorParser(e){return t=>{let i=parseObjectRgbColorComponents(t);return i?new Color(i,"rgb",e):null}}function parseObjectRgbaColorComponents(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let i=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function createObjectRgbaColorParser(e){return t=>{let i=parseObjectRgbaColorComponents(t);return i?new Color(i,"rgb",e):null}}let L=[{parser:parseHexRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:parseHexRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:parseFunctionalRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:parseFunctionalRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:parseHslColorComponents,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:parseHslaColorComponents,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:parseObjectRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:parseObjectRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"object"}}];function detectStringColor(e){return L.reduce((t,{parser:i,result:r})=>t||(i(e)?r:null),null)}function detectStringColorFormat(e,t="int"){let i=detectStringColor(e);return i?"hex"===i.notation&&"float"!==t?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:t}):null:null}let V={int:[parseHexRgbColor,parseHexRgbaColor,createFunctionalRgbColorParser("int"),createFunctionalRgbaColorParser("int"),createHslColorParser("int"),createHslaColorParser("int"),createObjectRgbColorParser("int"),createObjectRgbaColorParser("int")],float:[createFunctionalRgbColorParser("float"),createFunctionalRgbaColorParser("float"),createHslColorParser("float"),createHslaColorParser("float"),createObjectRgbColorParser("float"),createObjectRgbaColorParser("float")]};function createColorStringBindingReader(e){let t=V[e];return i=>{if("string"!=typeof i)return Color.black(e);let r=t.reduce((e,t)=>e||t(i),null);return null!=r?r:Color.black(e)}}function createColorStringParser(e){let t=V[e];return e=>t.reduce((t,i)=>t||i(e),null)}function zerofill(e){let t=constrainRange(Math.floor(e),0,255).toString(16);return 1===t.length?`0${t}`:t}function colorToHexRgbString(e,t="#"){let i=removeAlphaComponent(e.getComponents("rgb")).map(zerofill).join("");return`${t}${i}`}function colorToHexRgbaString(e,t="#"){let i=e.getComponents("rgb"),r=[i[0],i[1],i[2],255*i[3]].map(zerofill).join("");return`${t}${r}`}function colorToFunctionalRgbString(e,t){let i=createNumberFormatter("float"===t?2:0),r=removeAlphaComponent(e.getComponents("rgb",t)).map(e=>i(e));return`rgb(${r.join(", ")})`}function createFunctionalRgbColorFormatter(e){return t=>colorToFunctionalRgbString(t,e)}function colorToFunctionalRgbaString(e,t){let i=createNumberFormatter(2),r=createNumberFormatter("float"===t?2:0),s=e.getComponents("rgb",t).map((e,t)=>(3===t?i:r)(e));return`rgba(${s.join(", ")})`}function createFunctionalRgbaColorFormatter(e){return t=>colorToFunctionalRgbaString(t,e)}function colorToFunctionalHslString(e){let t=[createNumberFormatter(0),formatPercentage,formatPercentage],i=removeAlphaComponent(e.getComponents("hsl")).map((e,i)=>t[i](e));return`hsl(${i.join(", ")})`}function colorToFunctionalHslaString(e){let t=[createNumberFormatter(0),formatPercentage,formatPercentage,createNumberFormatter(2)],i=e.getComponents("hsl").map((e,i)=>t[i](e));return`hsla(${i.join(", ")})`}function colorToObjectRgbString(e,t){let i=createNumberFormatter("float"===t?2:0),r=["r","g","b"],s=removeAlphaComponent(e.getComponents("rgb",t)).map((e,t)=>`${r[t]}: ${i(e)}`);return`{${s.join(", ")}}`}function createObjectRgbColorFormatter(e){return t=>colorToObjectRgbString(t,e)}function colorToObjectRgbaString(e,t){let i=createNumberFormatter(2),r=createNumberFormatter("float"===t?2:0),s=["r","g","b","a"],a=e.getComponents("rgb",t).map((e,t)=>`${s[t]}: ${(3===t?i:r)(e)}`);return`{${a.join(", ")}}`}function createObjectRgbaColorFormatter(e){return t=>colorToObjectRgbaString(t,e)}let U=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:colorToHexRgbString},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:colorToHexRgbaString},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:colorToFunctionalHslString},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:colorToFunctionalHslaString},...["int","float"].reduce((e,t)=>[...e,{format:{alpha:!1,mode:"rgb",notation:"func",type:t},stringifier:createFunctionalRgbColorFormatter(t)},{format:{alpha:!0,mode:"rgb",notation:"func",type:t},stringifier:createFunctionalRgbaColorFormatter(t)},{format:{alpha:!1,mode:"rgb",notation:"object",type:t},stringifier:createObjectRgbColorFormatter(t)},{format:{alpha:!0,mode:"rgb",notation:"object",type:t},stringifier:createObjectRgbaColorFormatter(t)}],[])];function findColorStringifier(e){return U.reduce((t,i)=>t||(equalsStringColorFormat(i.format,e)?i.stringifier:null),null)}let k=ClassName("apl");let APaletteView=class APaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(k()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("div");i.classList.add(k("b")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(k("c")),i.appendChild(r),this.colorElem_=r;let s=e.createElement("div");s.classList.add(k("m")),this.element.appendChild(s),this.markerElem_=s;let a=e.createElement("div");a.classList.add(k("p")),this.markerElem_.appendChild(a),this.previewElem_=a,this.update_()}update_(){let e=this.value.rawValue,t=e.getComponents("rgb"),i=new Color([t[0],t[1],t[2],0],"rgb"),r=new Color([t[0],t[1],t[2],255],"rgb"),s=["to right",colorToFunctionalRgbaString(i),colorToFunctionalRgbaString(r)];this.colorElem_.style.background=`linear-gradient(${s.join(",")})`,this.previewElem_.style.backgroundColor=colorToFunctionalRgbaString(e);let a=mapRange(t[3],0,1,0,100);this.markerElem_.style.left=`${a}%`}onValueChange_(){this.update_()}};let APaletteController=class APaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new APaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=e.point.x/e.bounds.width,r=this.value.rawValue,[s,a,n]=r.getComponents("hsv");this.value.setRawValue(new Color([s,a,n,i],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(getBaseStepForColor(!0),getHorizontalStepKeys(e));if(0===t)return;let i=this.value.rawValue,[r,s,a,n]=i.getComponents("hsv");this.value.setRawValue(new Color([r,s,a,n+t],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(getBaseStepForColor(!0),getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let G=ClassName("coltxt");function createModeSelectElement(e){let t=e.createElement("select");return t.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"}].reduce((t,i)=>{let r=e.createElement("option");return r.textContent=i.text,r.value=i.value,t.appendChild(r),t},e.createDocumentFragment())),t}let ColorTextView=class ColorTextView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(G()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(G("m")),this.modeElem_=createModeSelectElement(e),this.modeElem_.classList.add(G("ms")),i.appendChild(this.modeSelectElement),t.viewProps.bindDisabled(this.modeElem_);let r=e.createElement("div");r.classList.add(G("mm")),r.appendChild(createSvgIconElement(e,"dropdown")),i.appendChild(r),this.element.appendChild(i);let s=e.createElement("div");s.classList.add(G("w")),this.element.appendChild(s),this.textsElem_=s,this.textViews_=t.textViews,this.applyTextViews_(),bindValue(t.colorMode,e=>{this.modeElem_.value=e})}get modeSelectElement(){return this.modeElem_}get textViews(){return this.textViews_}set textViews(e){this.textViews_=e,this.applyTextViews_()}applyTextViews_(){removeChildElements(this.textsElem_);let e=this.element.ownerDocument;this.textViews_.forEach(t=>{let i=e.createElement("div");i.classList.add(G("c")),i.appendChild(t.element),this.textsElem_.appendChild(i)})}};function createFormatter$2(e){return createNumberFormatter("float"===e?2:0)}function createConstraint$5(e,t,i){let r=getColorMaxComponents(e,t)[i];return new DefiniteRangeConstraint({min:0,max:r})}function createComponentController(e,t,i){return new NumberTextController(e,{arrayPosition:0===i?"fst":2===i?"lst":"mid",baseStep:getBaseStepForColor(!1),parser:t.parser,props:ValueMap.fromObject({draggingScale:"float"===t.colorType?.01:1,formatter:createFormatter$2(t.colorType)}),value:createValue(0,{constraint:createConstraint$5(t.colorMode,t.colorType,i)}),viewProps:t.viewProps})}let ColorTextController=class ColorTextController{constructor(e,t){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=t.colorType,this.parser_=t.parser,this.value=t.value,this.viewProps=t.viewProps,this.colorMode=createValue(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(e),this.view=new ColorTextView(e,{colorMode:this.colorMode,textViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(e){let t={colorMode:this.colorMode.rawValue,colorType:this.colorType_,parser:this.parser_,viewProps:this.viewProps},i=[createComponentController(e,t,0),createComponentController(e,t,1),createComponentController(e,t,2)];return i.forEach((e,t)=>{connectValues({primary:this.value,secondary:e.value,forward:e=>e.rawValue.getComponents(this.colorMode.rawValue,this.colorType_)[t],backward:(e,i)=>{let r=this.colorMode.rawValue,s=e.rawValue.getComponents(r,this.colorType_);return s[t]=i.rawValue,new Color(appendAlphaComponent(removeAlphaComponent(s),s[3]),r,this.colorType_)}})}),i}onModeSelectChange_(e){let t=e.currentTarget;this.colorMode.rawValue=t.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.textViews=[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view]}};let z=ClassName("hpl");let HPaletteView=class HPaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(z()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("div");i.classList.add(z("c")),this.element.appendChild(i);let r=e.createElement("div");r.classList.add(z("m")),this.element.appendChild(r),this.markerElem_=r,this.update_()}update_(){let e=this.value.rawValue,[t]=e.getComponents("hsv");this.markerElem_.style.backgroundColor=colorToFunctionalRgbString(new Color([t,100,100],"hsv"));let i=mapRange(t,0,360,0,100);this.markerElem_.style.left=`${i}%`}onValueChange_(){this.update_()}};let HPaletteController=class HPaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new HPaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=mapRange(constrainRange(e.point.x,0,e.bounds.width),0,e.bounds.width,0,360),r=this.value.rawValue,[,s,a,n]=r.getComponents("hsv");this.value.setRawValue(new Color([i,s,a,n],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(getBaseStepForColor(!1),getHorizontalStepKeys(e));if(0===t)return;let i=this.value.rawValue,[r,s,a,n]=i.getComponents("hsv");this.value.setRawValue(new Color([r+t,s,a,n],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(getBaseStepForColor(!1),getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let W=ClassName("svp");let SvPaletteView=class SvPaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(W()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let i=e.createElement("canvas");i.height=64,i.width=64,i.classList.add(W("c")),this.element.appendChild(i),this.canvasElement=i;let r=e.createElement("div");r.classList.add(W("m")),this.element.appendChild(r),this.markerElem_=r,this.update_()}update_(){let e=getCanvasContext(this.canvasElement);if(!e)return;let t=this.value.rawValue,i=t.getComponents("hsv"),r=this.canvasElement.width,s=this.canvasElement.height,a=e.getImageData(0,0,r,s),n=a.data;for(let e=0;ee.rawValue.getComponents()[3],backward:(e,t)=>{let i=e.rawValue.getComponents();return i[3]=t.rawValue,new Color(i,e.rawValue.mode)}}),this.textC_=new ColorTextController(e,{colorType:t.colorType,parser:parseNumber,value:this.value,viewProps:this.viewProps}),this.view=new ColorPickerView(e,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:t.supportsAlpha,svPaletteView:this.svPaletteC_.view,textView:this.textC_.view,viewProps:this.viewProps})}get textController(){return this.textC_}};let H=ClassName("colsw");let ColorSwatchView=class ColorSwatchView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.element=e.createElement("div"),this.element.classList.add(H()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(H("sw")),this.element.appendChild(i),this.swatchElem_=i;let r=e.createElement("button");r.classList.add(H("b")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r,this.update_()}update_(){let e=this.value.rawValue;this.swatchElem_.style.backgroundColor=colorToHexRgbaString(e)}onValueChange_(){this.update_()}};let ColorSwatchController=class ColorSwatchController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new ColorSwatchView(e,{value:this.value,viewProps:this.viewProps})}};let ColorController=class ColorController{constructor(e,t){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=Foldable.create(t.expanded),this.swatchC_=new ColorSwatchController(e,{value:this.value,viewProps:this.viewProps});let i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new TextController(e,{parser:t.parser,props:ValueMap.fromObject({formatter:t.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new ColorView(e,{foldable:this.foldable_,pickerLayout:t.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===t.pickerLayout?new PopupController(e,{viewProps:this.viewProps}):null;let r=new ColorPickerController(e,{colorType:t.colorType,supportsAlpha:t.supportsAlpha,value:this.value,viewProps:this.viewProps});r.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=r,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(r.view.element),connectValues({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),bindFoldable(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,i=e.relatedTarget;i&&t.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,i=findNextTarget(e);!(i&&t.contains(i))&&(!i||i!==this.swatchC_.view.buttonElement||supportsTouch(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.swatchC_.view.buttonElement.focus()}};function colorFromObject(e,t){return Color.isColorObject(e)?Color.fromObject(e,t):Color.black(t)}function colorToRgbNumber(e){return removeAlphaComponent(e.getComponents("rgb")).reduce((e,t)=>e<<8|255&Math.floor(t),0)}function colorToRgbaNumber(e){return e.getComponents("rgb").reduce((e,t,i)=>e<<8|255&Math.floor(3===i?255*t:t),0)>>>0}function numberToRgbColor(e){return new Color([e>>16&255,e>>8&255,255&e],"rgb")}function numberToRgbaColor(e){return new Color([e>>24&255,e>>16&255,e>>8&255,mapRange(255&e,0,255,0,1)],"rgb")}function colorFromRgbNumber(e){return"number"!=typeof e?Color.black():numberToRgbColor(e)}function colorFromRgbaNumber(e){return"number"!=typeof e?Color.black():numberToRgbaColor(e)}function createColorStringWriter(e){let t=findColorStringifier(e);return t?(e,i)=>{writePrimitive(e,t(i))}:null}function createColorNumberWriter(e){let t=e?colorToRgbaNumber:colorToRgbNumber;return(e,i)=>{writePrimitive(e,t(i))}}function writeRgbaColorObject(e,t,i){let r=t.toRgbaObject(i);e.writeProperty("r",r.r),e.writeProperty("g",r.g),e.writeProperty("b",r.b),e.writeProperty("a",r.a)}function writeRgbColorObject(e,t,i){let r=t.toRgbaObject(i);e.writeProperty("r",r.r),e.writeProperty("g",r.g),e.writeProperty("b",r.b)}function createColorObjectWriter(e,t){return(i,r)=>{e?writeRgbaColorObject(i,r,t):writeRgbColorObject(i,r,t)}}function shouldSupportAlpha$1(e){var t;return null!=e&&!!e.alpha||null!==(t=null==e?void 0:e.color)&&void 0!==t&&!!t.alpha}function createFormatter$1(e){return e?e=>colorToHexRgbaString(e,"0x"):e=>colorToHexRgbString(e,"0x")}function isForColor(e){return"color"in e||"view"in e&&"color"===e.view}let X={id:"input-color-number",type:"input",accept:(e,t)=>{if("number"!=typeof e||!isForColor(t))return null;let i=parseColorInputParams(t);return i?{initialValue:e,params:i}:null},binding:{reader:e=>shouldSupportAlpha$1(e.params)?colorFromRgbaNumber:colorFromRgbNumber,equals:Color.equals,writer:e=>createColorNumberWriter(shouldSupportAlpha$1(e.params))},controller:e=>{let t=shouldSupportAlpha$1(e.params),i="expanded"in e.params?e.params.expanded:void 0,r="picker"in e.params?e.params.picker:void 0;return new ColorController(e.document,{colorType:"int",expanded:null!=i&&i,formatter:createFormatter$1(t),parser:createColorStringParser("int"),pickerLayout:null!=r?r:"popup",supportsAlpha:t,value:e.value,viewProps:e.viewProps})}};function shouldSupportAlpha(e){return Color.isRgbaColorObject(e)}function createColorObjectReader(e){return t=>colorFromObject(t,e)}function createColorObjectFormatter(e,t){return i=>e?colorToObjectRgbaString(i,t):colorToObjectRgbString(i,t)}let Y={id:"input-color-object",type:"input",accept:(e,t)=>{if(!Color.isColorObject(e))return null;let i=parseColorInputParams(t);return i?{initialValue:e,params:i}:null},binding:{reader:e=>createColorObjectReader(extractColorType(e.params)),equals:Color.equals,writer:e=>createColorObjectWriter(shouldSupportAlpha(e.initialValue),extractColorType(e.params))},controller:e=>{var t;let i=Color.isRgbaColorObject(e.initialValue),r="expanded"in e.params?e.params.expanded:void 0,s="picker"in e.params?e.params.picker:void 0,a=null!==(t=extractColorType(e.params))&&void 0!==t?t:"int";return new ColorController(e.document,{colorType:a,expanded:null!=r&&r,formatter:createColorObjectFormatter(i,a),parser:createColorStringParser(a),pickerLayout:null!=s?s:"popup",supportsAlpha:i,value:e.value,viewProps:e.viewProps})}},j={id:"input-color-string",type:"input",accept:(e,t)=>{if("string"!=typeof e||"view"in t&&"text"===t.view)return null;let i=detectStringColorFormat(e,extractColorType(t));if(!i)return null;let r=findColorStringifier(i);if(!r)return null;let s=parseColorInputParams(t);return s?{initialValue:e,params:s}:null},binding:{reader:e=>{var t;return createColorStringBindingReader(null!==(t=extractColorType(e.params))&&void 0!==t?t:"int")},equals:Color.equals,writer:e=>{let t=detectStringColorFormat(e.initialValue,extractColorType(e.params));if(!t)throw TpError.shouldNeverHappen();let i=createColorStringWriter(t);if(!i)throw TpError.notBindable();return i}},controller:e=>{let t=detectStringColorFormat(e.initialValue,extractColorType(e.params));if(!t)throw TpError.shouldNeverHappen();let i=findColorStringifier(t);if(!i)throw TpError.shouldNeverHappen();let r="expanded"in e.params?e.params.expanded:void 0,s="picker"in e.params?e.params.picker:void 0;return new ColorController(e.document,{colorType:t.type,expanded:null!=r&&r,formatter:i,parser:createColorStringParser(t.type),pickerLayout:null!=s?s:"popup",supportsAlpha:t.alpha,value:e.value,viewProps:e.viewProps})}};let PointNdConstraint=class PointNdConstraint{constructor(e){this.components=e.components,this.asm_=e.assembly}constrain(e){let t=this.asm_.toComponents(e).map((e,t)=>{var i,r;return null!==(r=null===(i=this.components[t])||void 0===i?void 0:i.constrain(e))&&void 0!==r?r:e});return this.asm_.fromComponents(t)}};let K=ClassName("pndtxt");let PointNdTextView=class PointNdTextView{constructor(e,t){this.textViews=t.textViews,this.element=e.createElement("div"),this.element.classList.add(K()),this.textViews.forEach(t=>{let i=e.createElement("div");i.classList.add(K("a")),i.appendChild(t.element),this.element.appendChild(i)})}};function createAxisController(e,t,i){return new NumberTextController(e,{arrayPosition:0===i?"fst":i===t.axes.length-1?"lst":"mid",baseStep:t.axes[i].baseStep,parser:t.parser,props:t.axes[i].textProps,value:createValue(0,{constraint:t.axes[i].constraint}),viewProps:t.viewProps})}let PointNdTextController=class PointNdTextController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.acs_=t.axes.map((i,r)=>createAxisController(e,t,r)),this.acs_.forEach((e,i)=>{connectValues({primary:this.value,secondary:e.value,forward:e=>t.assembly.toComponents(e.rawValue)[i],backward:(e,r)=>{let s=t.assembly.toComponents(e.rawValue);return s[i]=r.rawValue,t.assembly.fromComponents(s)}})}),this.view=new PointNdTextView(e,{textViews:this.acs_.map(e=>e.view)})}};function createStepConstraint(e,t){return"step"in e&&!isEmpty(e.step)?new StepConstraint(e.step,t):null}function createRangeConstraint(e){return isEmpty(e.max)||isEmpty(e.min)?isEmpty(e.max)&&isEmpty(e.min)?null:new RangeConstraint({max:e.max,min:e.min}):new DefiniteRangeConstraint({max:e.max,min:e.min})}function findNumberRange(e){let t=findConstraint(e,DefiniteRangeConstraint);if(t)return[t.values.get("min"),t.values.get("max")];let i=findConstraint(e,RangeConstraint);return i?[i.minValue,i.maxValue]:[void 0,void 0]}function createConstraint$4(e,t){let i=[],r=createStepConstraint(e,t);r&&i.push(r);let s=createRangeConstraint(e);s&&i.push(s);let a=createListConstraint(e.options);return a&&i.push(a),new CompositeConstraint(i)}let q={id:"input-number",type:"input",accept:(e,t)=>{if("number"!=typeof e)return null;let i=parseParams(t,{format:r.optional.function,max:r.optional.number,min:r.optional.number,options:r.optional.custom(parseListOptions),step:r.optional.number});return i?{initialValue:e,params:i}:null},binding:{reader:e=>numberFromUnknown,constraint:e=>createConstraint$4(e.params,e.initialValue),writer:e=>writePrimitive},controller:e=>{var t;let i=e.value,r=e.constraint,s=r&&findConstraint(r,ListConstraint);if(s)return new ListController(e.document,{props:new ValueMap({options:s.values.value("options")}),value:i,viewProps:e.viewProps});let a=null!==(t="format"in e.params?e.params.format:void 0)&&void 0!==t?t:createNumberFormatter(getSuitableDecimalDigits(r,i.rawValue)),n=r&&findConstraint(r,DefiniteRangeConstraint);return n?new SliderTextController(e.document,{baseStep:getBaseStep(r),parser:parseNumber,sliderProps:new ValueMap({maxValue:n.values.value("max"),minValue:n.values.value("min")}),textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(r,i.rawValue),formatter:a}),value:i,viewProps:e.viewProps}):new NumberTextController(e.document,{baseStep:getBaseStep(r),parser:parseNumber,props:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(r,i.rawValue),formatter:a}),value:i,viewProps:e.viewProps})}};let Point2d=class Point2d{constructor(e=0,t=0){this.x=e,this.y=t}getComponents(){return[this.x,this.y]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,i=e.y;return"number"==typeof t&&"number"==typeof i}static equals(e,t){return e.x===t.x&&e.y===t.y}toObject(){return{x:this.x,y:this.y}}};let $={toComponents:e=>e.getComponents(),fromComponents:e=>new Point2d(...e)},Q=ClassName("p2d");let Point2dView=class Point2dView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(Q()),t.viewProps.bindClassModifiers(this.element),bindValue(t.expanded,valueToClassName(this.element,Q(void 0,"expanded")));let i=e.createElement("div");i.classList.add(Q("h")),this.element.appendChild(i);let r=e.createElement("button");r.classList.add(Q("b")),r.appendChild(createSvgIconElement(e,"p2dpad")),t.viewProps.bindDisabled(r),i.appendChild(r),this.buttonElement=r;let s=e.createElement("div");if(s.classList.add(Q("t")),i.appendChild(s),this.textElement=s,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(Q("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};let Z=ClassName("p2dp");let Point2dPickerView=class Point2dPickerView{constructor(e,t){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.invertsY_=t.invertsY,this.maxValue_=t.maxValue,this.element=e.createElement("div"),this.element.classList.add(Z()),"popup"===t.layout&&this.element.classList.add(Z(void 0,"p")),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("div");i.classList.add(Z("p")),t.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;let r=e.createElementNS(o,"svg");r.classList.add(Z("g")),this.padElement.appendChild(r),this.svgElem_=r;let s=e.createElementNS(o,"line");s.classList.add(Z("ax")),s.setAttributeNS(null,"x1","0"),s.setAttributeNS(null,"y1","50%"),s.setAttributeNS(null,"x2","100%"),s.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(s);let a=e.createElementNS(o,"line");a.classList.add(Z("ax")),a.setAttributeNS(null,"x1","50%"),a.setAttributeNS(null,"y1","0"),a.setAttributeNS(null,"x2","50%"),a.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(a);let n=e.createElementNS(o,"line");n.classList.add(Z("l")),n.setAttributeNS(null,"x1","50%"),n.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(n),this.lineElem_=n;let l=e.createElement("div");l.classList.add(Z("m")),this.padElement.appendChild(l),this.markerElem_=l,t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){let[e,t]=this.value.rawValue.getComponents(),i=this.maxValue_,r=mapRange(e,-i,+i,0,100),s=mapRange(t,-i,+i,0,100),a=this.invertsY_?100-s:s;this.lineElem_.setAttributeNS(null,"x2",`${r}%`),this.lineElem_.setAttributeNS(null,"y2",`${a}%`),this.markerElem_.style.left=`${r}%`,this.markerElem_.style.top=`${a}%`}onValueChange_(){this.update_()}onFoldableChange_(){this.update_()}};function computeOffset(e,t,i){return[getStepForKey(t[0],getHorizontalStepKeys(e)),getStepForKey(t[1],getVerticalStepKeys(e))*(i?1:-1)]}let Point2dPickerController=class Point2dPickerController{constructor(e,t){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.baseSteps_=t.baseSteps,this.maxValue_=t.maxValue,this.invertsY_=t.invertsY,this.view=new Point2dPickerView(e,{invertsY:this.invertsY_,layout:t.layout,maxValue:this.maxValue_,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let i=this.maxValue_,r=mapRange(e.point.x,0,e.bounds.width,-i,+i),s=mapRange(this.invertsY_?e.bounds.height-e.point.y:e.point.y,0,e.bounds.height,-i,+i);this.value.setRawValue(new Point2d(r,s),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onPadKeyDown_(e){isArrowKey(e.key)&&e.preventDefault();let[t,i]=computeOffset(e,this.baseSteps_,this.invertsY_);(0!==t||0!==i)&&this.value.setRawValue(new Point2d(this.value.rawValue.x+t,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(e){let[t,i]=computeOffset(e,this.baseSteps_,this.invertsY_);(0!==t||0!==i)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let Point2dController=class Point2dController{constructor(e,t){var i,r;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=Foldable.create(t.expanded),this.popC_="popup"===t.pickerLayout?new PopupController(e,{viewProps:this.viewProps}):null;let s=new Point2dPickerController(e,{baseSteps:[t.axes[0].baseStep,t.axes[1].baseStep],invertsY:t.invertsY,layout:t.pickerLayout,maxValue:t.maxValue,value:this.value,viewProps:this.viewProps});s.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=s,this.textC_=new PointNdTextController(e,{assembly:$,axes:t.axes,parser:t.parser,value:this.value,viewProps:this.viewProps}),this.view=new Point2dView(e,{expanded:this.foldable_.value("expanded"),pickerLayout:t.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(r=this.view.buttonElement)||void 0===r||r.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),connectValues({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),bindFoldable(this.foldable_,this.view.pickerElement))}onPadButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,i=e.relatedTarget;i&&t.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,i=findNextTarget(e);!(i&&t.contains(i))&&(!i||i!==this.view.buttonElement||supportsTouch(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.view.buttonElement.focus()}};let Point3d=class Point3d{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,i=e.y,r=e.z;return"number"==typeof t&&"number"==typeof i&&"number"==typeof r}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}toObject(){return{x:this.x,y:this.y,z:this.z}}};let J={toComponents:e=>e.getComponents(),fromComponents:e=>new Point3d(...e)};function point3dFromUnknown(e){return Point3d.isObject(e)?new Point3d(e.x,e.y,e.z):new Point3d}function writePoint3d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z)}function createConstraint$3(e,t){return new PointNdConstraint({assembly:J,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y),createDimensionConstraint("z"in e?e.z:void 0,t.z)]})}function createAxis$2(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}let ee={id:"input-point3d",type:"input",accept:(e,t)=>{if(!Point3d.isObject(e))return null;let i=parseParams(t,{x:r.optional.custom(parsePointDimensionParams),y:r.optional.custom(parsePointDimensionParams),z:r.optional.custom(parsePointDimensionParams)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>point3dFromUnknown,constraint:e=>createConstraint$3(e.params,e.initialValue),equals:Point3d.equals,writer:e=>writePoint3d},controller:e=>{let t=e.value,i=e.constraint;if(!(i instanceof PointNdConstraint))throw TpError.shouldNeverHappen();return new PointNdTextController(e.document,{assembly:J,axes:[createAxis$2(t.rawValue.x,i.components[0]),createAxis$2(t.rawValue.y,i.components[1]),createAxis$2(t.rawValue.z,i.components[2])],parser:parseNumber,value:t,viewProps:e.viewProps})}};let Point4d=class Point4d{constructor(e=0,t=0,i=0,r=0){this.x=e,this.y=t,this.z=i,this.w=r}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,i=e.y,r=e.z,s=e.w;return"number"==typeof t&&"number"==typeof i&&"number"==typeof r&&"number"==typeof s}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}};let et={toComponents:e=>e.getComponents(),fromComponents:e=>new Point4d(...e)};function point4dFromUnknown(e){return Point4d.isObject(e)?new Point4d(e.x,e.y,e.z,e.w):new Point4d}function writePoint4d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z),e.writeProperty("w",t.w)}function createConstraint$2(e,t){return new PointNdConstraint({assembly:et,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y),createDimensionConstraint("z"in e?e.z:void 0,t.z),createDimensionConstraint("w"in e?e.w:void 0,t.w)]})}function createAxis$1(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}let ei={id:"input-point4d",type:"input",accept:(e,t)=>{if(!Point4d.isObject(e))return null;let i=parseParams(t,{x:r.optional.custom(parsePointDimensionParams),y:r.optional.custom(parsePointDimensionParams),z:r.optional.custom(parsePointDimensionParams),w:r.optional.custom(parsePointDimensionParams)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>point4dFromUnknown,constraint:e=>createConstraint$2(e.params,e.initialValue),equals:Point4d.equals,writer:e=>writePoint4d},controller:e=>{let t=e.value,i=e.constraint;if(!(i instanceof PointNdConstraint))throw TpError.shouldNeverHappen();return new PointNdTextController(e.document,{assembly:et,axes:t.rawValue.getComponents().map((e,t)=>createAxis$1(e,i.components[t])),parser:parseNumber,value:t,viewProps:e.viewProps})}};function createConstraint$1(e){let t=[],i=createListConstraint(e.options);return i&&t.push(i),new CompositeConstraint(t)}let er={id:"input-string",type:"input",accept:(e,t)=>{if("string"!=typeof e)return null;let i=parseParams(t,{options:r.optional.custom(parseListOptions)});return i?{initialValue:e,params:i}:null},binding:{reader:e=>stringFromUnknown,constraint:e=>createConstraint$1(e.params),writer:e=>writePrimitive},controller:e=>{let t=e.document,i=e.value,r=e.constraint,s=r&&findConstraint(r,ListConstraint);return s?new ListController(t,{props:new ValueMap({options:s.values.value("options")}),value:i,viewProps:e.viewProps}):new TextController(t,{parser:e=>e,props:ValueMap.fromObject({formatter:formatString}),value:i,viewProps:e.viewProps})}},es={monitor:{defaultInterval:200,defaultLineCount:3}},ea=ClassName("mll");let MultiLogView=class MultiLogView{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(ea()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("textarea");i.classList.add(ea("i")),i.style.height=`calc(var(--bld-us) * ${t.lineCount})`,i.readOnly=!0,t.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.textareaElem_,t=e.scrollTop===e.scrollHeight-e.clientHeight,i=[];this.value.rawValue.forEach(e=>{void 0!==e&&i.push(this.formatter_(e))}),e.textContent=i.join("\n"),t&&(e.scrollTop=e.scrollHeight)}onValueUpdate_(){this.update_()}};let MultiLogController=class MultiLogController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new MultiLogView(e,{formatter:t.formatter,lineCount:t.lineCount,value:this.value,viewProps:this.viewProps})}};let en=ClassName("sgl");let SingleLogView=class SingleLogView{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(en()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("input");i.classList.add(en("i")),i.readOnly=!0,i.type="text",t.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.value.rawValue,t=e[e.length-1];this.inputElement.value=void 0!==t?this.formatter_(t):""}onValueUpdate_(){this.update_()}};let SingleLogController=class SingleLogController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new SingleLogView(e,{formatter:t.formatter,value:this.value,viewProps:this.viewProps})}};let eo={id:"monitor-bool",type:"monitor",accept:(e,t)=>{if("boolean"!=typeof e)return null;let i=parseParams(t,{lineCount:r.optional.number});return i?{initialValue:e,params:i}:null},binding:{reader:e=>boolFromUnknown},controller:e=>{var t;return 1===e.value.rawValue.length?new SingleLogController(e.document,{formatter:BooleanFormatter,value:e.value,viewProps:e.viewProps}):new MultiLogController(e.document,{formatter:BooleanFormatter,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:es.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}},el=ClassName("grl");let GraphLogView=class GraphLogView{constructor(e,t){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=e.createElement("div"),this.element.classList.add(el()),t.viewProps.bindClassModifiers(this.element),this.formatter_=t.formatter,this.props_=t.props,this.cursor_=t.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);let i=e.createElementNS(o,"svg");i.classList.add(el("g")),i.style.height=`calc(var(--bld-us) * ${t.lineCount})`,this.element.appendChild(i),this.svgElem_=i;let r=e.createElementNS(o,"polyline");this.svgElem_.appendChild(r),this.lineElem_=r;let s=e.createElement("div");s.classList.add(el("t"),ClassName("tt")()),this.element.appendChild(s),this.tooltipElem_=s,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}get graphElement(){return this.svgElem_}update_(){let e=this.svgElem_.getBoundingClientRect(),t=this.value.rawValue.length-1,i=this.props_.get("minValue"),r=this.props_.get("maxValue"),s=[];this.value.rawValue.forEach((a,n)=>{if(void 0===a)return;let o=mapRange(n,0,t,0,e.width),l=mapRange(a,i,r,e.height,0);s.push([o,l].join(","))}),this.lineElem_.setAttributeNS(null,"points",s.join(" "));let a=this.tooltipElem_,n=this.value.rawValue[this.cursor_.rawValue];if(void 0===n){a.classList.remove(el("t","a"));return}let o=mapRange(this.cursor_.rawValue,0,t,0,e.width),l=mapRange(n,i,r,e.height,0);a.style.left=`${o}px`,a.style.top=`${l}px`,a.textContent=`${this.formatter_(n)}`,a.classList.contains(el("t","a"))||(a.classList.add(el("t","a"),el("t","in")),forceReflow(a),a.classList.remove(el("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}};let GraphLogController=class GraphLogController{constructor(e,t){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props_=t.props,this.value=t.value,this.viewProps=t.viewProps,this.cursor_=createValue(-1),this.view=new GraphLogView(e,{cursor:this.cursor_,formatter:t.formatter,lineCount:t.lineCount,props:this.props_,value:this.value,viewProps:this.viewProps}),supportsTouch(e)){let e=new PointerHandler(this.view.element);e.emitter.on("down",this.onGraphPointerDown_),e.emitter.on("move",this.onGraphPointerMove_),e.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(e){let t=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(mapRange(e.offsetX,0,t.width,0,this.value.rawValue.length))}onGraphPointerDown_(e){this.onGraphPointerMove_(e)}onGraphPointerMove_(e){if(!e.data.point){this.cursor_.rawValue=-1;return}this.cursor_.rawValue=Math.floor(mapRange(e.data.point.x,0,e.data.bounds.width,0,this.value.rawValue.length))}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function createFormatter(e){return"format"in e&&!isEmpty(e.format)?e.format:createNumberFormatter(2)}function createTextMonitor(e){var t;return 1===e.value.rawValue.length?new SingleLogController(e.document,{formatter:createFormatter(e.params),value:e.value,viewProps:e.viewProps}):new MultiLogController(e.document,{formatter:createFormatter(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:es.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}function createGraphMonitor(e){var t,i,r;return new GraphLogController(e.document,{formatter:createFormatter(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:es.monitor.defaultLineCount,props:ValueMap.fromObject({maxValue:null!==(i="max"in e.params?e.params.max:null)&&void 0!==i?i:100,minValue:null!==(r="min"in e.params?e.params.min:null)&&void 0!==r?r:0}),value:e.value,viewProps:e.viewProps})}function shouldShowGraph(e){return"view"in e&&"graph"===e.view}let eh={id:"monitor-number",type:"monitor",accept:(e,t)=>{if("number"!=typeof e)return null;let i=parseParams(t,{format:r.optional.function,lineCount:r.optional.number,max:r.optional.number,min:r.optional.number,view:r.optional.string});return i?{initialValue:e,params:i}:null},binding:{defaultBufferSize:e=>shouldShowGraph(e)?64:1,reader:e=>numberFromUnknown},controller:e=>shouldShowGraph(e.params)?createGraphMonitor(e):createTextMonitor(e)},ec={id:"monitor-string",type:"monitor",accept:(e,t)=>{if("string"!=typeof e)return null;let i=parseParams(t,{lineCount:r.optional.number,multiline:r.optional.boolean});return i?{initialValue:e,params:i}:null},binding:{reader:e=>stringFromUnknown},controller:e=>{var t;let i=e.value,r=i.rawValue.length>1||"multiline"in e.params&&e.params.multiline;return r?new MultiLogController(e.document,{formatter:formatString,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:es.monitor.defaultLineCount,value:i,viewProps:e.viewProps}):new SingleLogController(e.document,{formatter:formatString,value:i,viewProps:e.viewProps})}};function createInputBindingController(e,t){var i;let s=e.accept(t.target.read(),t.params);if(isEmpty(s))return null;let a={target:t.target,initialValue:s.initialValue,params:s.params},n=e.binding.reader(a),o=e.binding.constraint?e.binding.constraint(a):void 0,l=createValue(n(s.initialValue),{constraint:o,equals:e.binding.equals}),h=new InputBinding({reader:n,target:t.target,value:l,writer:e.binding.writer(a)}),c=r.optional.boolean(t.params.disabled).value,u=r.optional.boolean(t.params.hidden).value,d=e.controller({constraint:o,document:t.document,initialValue:s.initialValue,params:s.params,value:h.value,viewProps:ViewProps.create({disabled:c,hidden:u})});return new InputBindingController(t.document,{binding:h,blade:createBlade(),props:ValueMap.fromObject({label:"label"in t.params?null!==(i=r.optional.string(t.params.label).value)&&void 0!==i?i:null:t.target.key}),valueController:d})}function createTicker(e,t){return 0===t?new ManualTicker:new IntervalTicker(e,null!=t?t:es.monitor.defaultInterval)}function createMonitorBindingController(e,t){var i,s,a;let n=e.accept(t.target.read(),t.params);if(isEmpty(n))return null;let o={target:t.target,initialValue:n.initialValue,params:n.params},l=e.binding.reader(o),h=null!==(s=null!==(i=r.optional.number(t.params.bufferSize).value)&&void 0!==i?i:e.binding.defaultBufferSize&&e.binding.defaultBufferSize(n.params))&&void 0!==s?s:1,c=r.optional.number(t.params.interval).value,u=new MonitorBinding({reader:l,target:t.target,ticker:createTicker(t.document,c),value:initializeBuffer(h)}),d=r.optional.boolean(t.params.disabled).value,_=r.optional.boolean(t.params.hidden).value,p=e.controller({document:t.document,params:n.params,value:u.value,viewProps:ViewProps.create({disabled:d,hidden:_})});return new MonitorBindingController(t.document,{binding:u,blade:createBlade(),props:ValueMap.fromObject({label:"label"in t.params?null!==(a=r.optional.string(t.params.label).value)&&void 0!==a?a:null:t.target.key}),valueController:p})}let PluginPool=class PluginPool{constructor(){this.pluginsMap_={blades:[],inputs:[],monitors:[]}}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(e){"blade"===e.type?this.pluginsMap_.blades.unshift(e):"input"===e.type?this.pluginsMap_.inputs.unshift(e):"monitor"===e.type&&this.pluginsMap_.monitors.unshift(e)}createInput(e,t,i){let r=t.read();if(isEmpty(r))throw new TpError({context:{key:t.key},type:"nomatchingcontroller"});let s=this.pluginsMap_.inputs.reduce((r,s)=>null!=r?r:createInputBindingController(s,{document:e,target:t,params:i}),null);if(s)return s;throw new TpError({context:{key:t.key},type:"nomatchingcontroller"})}createMonitor(e,t,i){let r=this.pluginsMap_.monitors.reduce((r,s)=>null!=r?r:createMonitorBindingController(s,{document:e,params:i,target:t}),null);if(r)return r;throw new TpError({context:{key:t.key},type:"nomatchingcontroller"})}createBlade(e,t){let i=this.pluginsMap_.blades.reduce((i,r)=>null!=i?i:createBladeController(r,{document:e,params:t}),null);if(!i)throw new TpError({type:"nomatchingview",context:{params:t}});return i}createBladeApi(e){if(e instanceof InputBindingController)return new InputBindingApi(e);if(e instanceof MonitorBindingController)return new MonitorBindingApi(e);if(e instanceof RackController)return new RackApi(e,this);let t=this.pluginsMap_.blades.reduce((t,i)=>null!=t?t:i.api({controller:e,pool:this}),null);if(!t)throw TpError.shouldNeverHappen();return t}};function createDefaultPluginPool(){let e=new PluginPool;return[eu,ee,ei,er,q,j,Y,X,O,eo,ec,eh,c,d,p,g].forEach(t=>{e.register(t)}),e}function point2dFromUnknown(e){return Point2d.isObject(e)?new Point2d(e.x,e.y):new Point2d}function writePoint2d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y)}function createDimensionConstraint(e,t){if(!e)return;let i=[],r=createStepConstraint(e,t);r&&i.push(r);let s=createRangeConstraint(e);return s&&i.push(s),new CompositeConstraint(i)}function createConstraint(e,t){return new PointNdConstraint({assembly:$,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y)]})}function getSuitableMaxDimensionValue(e,t){let[i,r]=e?findNumberRange(e):[];if(!isEmpty(i)||!isEmpty(r))return Math.max(Math.abs(null!=i?i:0),Math.abs(null!=r?r:0));let s=getBaseStep(e);return Math.max(10*Math.abs(s),10*Math.abs(t))}function getSuitableMaxValue(e,t){let i=t instanceof PointNdConstraint?t.components[0]:void 0,r=t instanceof PointNdConstraint?t.components[1]:void 0,s=getSuitableMaxDimensionValue(i,e.x),a=getSuitableMaxDimensionValue(r,e.y);return Math.max(s,a)}function createAxis(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}function shouldInvertY(e){if(!("y"in e))return!1;let t=e.y;return!!t&&"inverted"in t&&!!t.inverted}let eu={id:"input-point2d",type:"input",accept:(e,t)=>{if(!Point2d.isObject(e))return null;let i=parseParams(t,{expanded:r.optional.boolean,picker:r.optional.custom(parsePickerLayout),x:r.optional.custom(parsePointDimensionParams),y:r.optional.object({inverted:r.optional.boolean,max:r.optional.number,min:r.optional.number,step:r.optional.number})});return i?{initialValue:e,params:i}:null},binding:{reader:e=>point2dFromUnknown,constraint:e=>createConstraint(e.params,e.initialValue),equals:Point2d.equals,writer:e=>writePoint2d},controller:e=>{let t=e.document,i=e.value,r=e.constraint;if(!(r instanceof PointNdConstraint))throw TpError.shouldNeverHappen();let s="expanded"in e.params?e.params.expanded:void 0,a="picker"in e.params?e.params.picker:void 0;return new Point2dController(t,{axes:[createAxis(i.rawValue.x,r.components[0]),createAxis(i.rawValue.y,r.components[1])],expanded:null!=s&&s,invertsY:shouldInvertY(e.params),maxValue:getSuitableMaxValue(i.rawValue,r),parser:parseNumber,pickerLayout:null!=a?a:"popup",value:i,viewProps:e.viewProps})}};let ListApi=class ListApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get options(){return this.controller_.valueController.props.get("options")}set options(e){this.controller_.valueController.props.set("options",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}};let SliderApi=class SliderApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get maxValue(){return this.controller_.valueController.sliderController.props.get("maxValue")}set maxValue(e){this.controller_.valueController.sliderController.props.set("maxValue",e)}get minValue(){return this.controller_.valueController.sliderController.props.get("minValue")}set minValue(e){this.controller_.valueController.sliderController.props.set("minValue",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}};let TextApi=class TextApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get formatter(){return this.controller_.valueController.props.get("formatter")}set formatter(e){this.controller_.valueController.props.set("formatter",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let i=t.bind(this);return this.emitter_.on(e,e=>{i(e.event)}),this}};let ed={id:"list",type:"blade",accept(e){let t=parseParams(e,{options:r.required.custom(parseListOptions),value:r.required.raw,view:r.required.constant("list"),label:r.optional.string});return t?{params:t}:null},controller(e){let t=new ListConstraint(normalizeListOptions(e.params.options)),i=createValue(e.params.value,{constraint:t}),r=new ListController(e.document,{props:new ValueMap({options:t.values.value("options")}),value:i,viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:r})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof ListController?new ListApi(e.controller):null};function exportPresetJson(e){return e.reduce((e,t)=>Object.assign(e,{[t.presetKey]:t.read()}),{})}function importPresetJson(e,t){e.forEach(e=>{let i=t[e.target.presetKey];void 0!==i&&e.writer(e.target,e.reader(i))})}let RootApi=class RootApi extends FolderApi{constructor(e,t){super(e,t)}get element(){return this.controller_.view.element}importPreset(e){let t=this.controller_.rackController.rack.find(InputBindingController).map(e=>e.binding);importPresetJson(t,e),this.refresh()}exportPreset(){let e=this.controller_.rackController.rack.find(InputBindingController).map(e=>e.binding.target);return exportPresetJson(e)}refresh(){this.controller_.rackController.rack.find(InputBindingController).forEach(e=>{e.binding.read()}),this.controller_.rackController.rack.find(MonitorBindingController).forEach(e=>{e.binding.read()})}};let RootController=class RootController extends FolderController{constructor(e,t){super(e,{expanded:t.expanded,blade:t.blade,props:t.props,root:!0,viewProps:t.viewProps})}};let e_={id:"slider",type:"blade",accept(e){let t=parseParams(e,{max:r.required.number,min:r.required.number,view:r.required.constant("slider"),format:r.optional.function,label:r.optional.string,value:r.optional.number});return t?{params:t}:null},controller(e){var t,i;let r=null!==(t=e.params.value)&&void 0!==t?t:0,s=new DefiniteRangeConstraint({max:e.params.max,min:e.params.min}),a=new SliderTextController(e.document,{baseStep:1,parser:parseNumber,sliderProps:new ValueMap({maxValue:s.values.value("max"),minValue:s.values.value("min")}),textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(void 0,r),formatter:null!==(i=e.params.format)&&void 0!==i?i:numberToString}),value:createValue(r,{constraint:s}),viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:a})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof SliderTextController?new SliderApi(e.controller):null},ep={id:"text",type:"blade",accept(e){let t=parseParams(e,{parse:r.required.function,value:r.required.raw,view:r.required.constant("text"),format:r.optional.function,label:r.optional.string});return t?{params:t}:null},controller(e){var t;let i=new TextController(e.document,{parser:e.params.parse,props:ValueMap.fromObject({formatter:null!==(t=e.params.format)&&void 0!==t?t:e=>String(e)}),value:createValue(e.params.value),viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:i})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof TextController?new TextApi(e.controller):null};function createDefaultWrapperElement(e){let t=e.createElement("div");return t.classList.add(ClassName("dfw")()),e.body&&e.body.appendChild(t),t}function embedStyle(e,t,i){if(e.querySelector(`style[data-tp-style=${t}]`))return;let r=e.createElement("style");r.dataset.tpStyle=t,r.textContent=i,e.head.appendChild(r)}let Pane=class Pane extends RootApi{constructor(e){var t,i;let r=null!=e?e:{},s=null!==(t=r.document)&&void 0!==t?t:getWindowDocument(),a=createDefaultPluginPool(),n=new RootController(s,{expanded:r.expanded,blade:createBlade(),props:ValueMap.fromObject({title:r.title}),viewProps:ViewProps.create()});super(n,a),this.pool_=a,this.containerElem_=null!==(i=r.container)&&void 0!==i?i:createDefaultWrapperElement(s),this.containerElem_.appendChild(this.element),this.doc_=s,this.usesDefaultWrapper_=!r.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw TpError.alreadyDisposed();return this.doc_}dispose(){let e=this.containerElem_;if(!e)throw TpError.alreadyDisposed();if(this.usesDefaultWrapper_){let t=e.parentElement;t&&t.removeChild(e)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(e){let t="plugin"in e?[e.plugin]:"plugins"in e?e.plugins:[];t.forEach(e=>{this.pool_.register(e),this.embedPluginStyle_(e)})}embedPluginStyle_(e){e.css&&embedStyle(this.document,`plugin-${e.id}`,e.css)}setUpDefaultPlugins_(){embedStyle(this.document,"default",'.tp-tbiv_b,.tp-coltxtv_ms,.tp-ckbv_i,.tp-rotv_b,.tp-fldv_b,.tp-mllv_i,.tp-sglv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--elm-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--bld-us);line-height:var(--bld-us);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--bld-us);line-height:var(--bld-us);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-mllv_i,.tp-sglv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--mo-fg);height:var(--bld-us);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-mllv_i::-webkit-scrollbar,.tp-sglv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-mllv_i::-webkit-scrollbar-corner,.tp-sglv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-mllv_i::-webkit-scrollbar-thumb,.tp-sglv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-rotv{--font-family: var(--tp-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-br: var(--tp-base-border-radius, 6px);--cnt-h-p: var(--tp-container-horizontal-padding, 4px);--cnt-v-p: var(--tp-container-vertical-padding, 4px);--elm-br: var(--tp-element-border-radius, 2px);--bld-s: var(--tp-blade-spacing, 4px);--bld-us: var(--tp-blade-unit-size, 20px);--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tabv_c .tp-brkv>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-v-p))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tabv_c .tp-brkv>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--bld-s)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tabv_c .tp-brkv>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tabv_c .tp-brkv>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--elm-br);border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tabv_c .tp-brkv .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--elm-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);overflow:hidden;padding-left:var(--cnt-h-p);padding-right:calc(4px + var(--bld-us) + var(--cnt-h-p));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-h-p) + (var(--bld-us) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-v-p);padding-top:var(--cnt-v-p);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--elm-br);cursor:pointer;display:block;height:var(--bld-us);position:relative;width:var(--bld-us)}.tp-ckbv_w svg{bottom:0;display:block;height:16px;left:0;margin:auto;opacity:0;position:absolute;right:0;top:0;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--bld-us)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--bld-s);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--bld-s)}.tp-colpv_rgb{display:flex;margin-top:var(--bld-s);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-v-p);padding-top:calc(var(--cnt-v-p) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-h-p));position:absolute;right:calc(-1*var(--cnt-h-p));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--elm-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--bld-us)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--elm-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;pointer-events:none;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--elm-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;cursor:pointer;display:block;height:var(--bld-us);left:0;margin:0;outline:none;padding:0;position:absolute;top:0;width:var(--bld-us)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--elm-br);bottom:0;content:"";display:block;left:0;position:absolute;right:0;top:0}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--elm-br);color:var(--lbl-fg);cursor:pointer;height:var(--bld-us);line-height:var(--bld-us);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv.tp-fldv-not .tp-fldv_b{display:none}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--bld-us)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-h-p);padding-right:var(--cnt-h-p)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:160px}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding:0 4px}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--bld-us)*3);line-height:var(--bld-us);padding:0 4px;resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--bld-us);margin-right:4px;position:relative;width:var(--bld-us)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--bld-s);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-p2dpv{padding-left:calc(var(--bld-us) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:6px;box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:168px;padding:var(--cnt-v-p) var(--cnt-h-p);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--bld-us);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin:auto;position:absolute;right:0;top:0}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin-bottom:auto;margin-top:auto;position:absolute;right:0;top:0}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--elm-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--bld-us) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_c{padding-bottom:var(--cnt-v-p);padding-left:4px;padding-top:var(--cnt-v-p)}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-h-p) + 4px);padding-right:calc(var(--cnt-h-p) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);bottom:2px;content:"";left:0;pointer-events:none;position:absolute;right:0;top:0}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);opacity:.5;overflow:hidden;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-txtv{position:relative}.tp-txtv_i{padding:0 4px}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:-3px;position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--bld-us) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--elm-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--font-family);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--bld-us) + var(--cnt-h-p));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0}.tp-rotv.tp-rotv-not .tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}'),this.pool_.getAll().forEach(e=>{this.embedPluginStyle_(e)}),this.registerPlugin({plugins:[e_,ed,g,ep]})}};let ef=new Semver("3.1.10");e.BladeApi=BladeApi,e.ButtonApi=ButtonApi,e.FolderApi=FolderApi,e.InputBindingApi=InputBindingApi,e.ListApi=ListApi,e.MonitorBindingApi=MonitorBindingApi,e.Pane=Pane,e.SeparatorApi=SeparatorApi,e.SliderApi=SliderApi,e.TabApi=TabApi,e.TabPageApi=TabPageApi,e.TextApi=TextApi,e.TpChangeEvent=TpChangeEvent,e.VERSION=ef,Object.defineProperty(e,"__esModule",{value:!0})})(t)},4494:(e,t,i)=>{"use strict";let r,s,a;i.d(t,{YfP:()=>ArcRotateCamera,HEv:()=>math_color_Color4,Dso:()=>postProcess_PostProcess,xsS:()=>scene_Scene,xeF:()=>q,vGS:()=>ShaderStore,w1W:()=>tools_Tools,Pa4:()=>math_vector_Vector3,fWK:()=>webgpuEngine_WebGPUEngine});let AbstractScene=class AbstractScene{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,i,r){for(let s in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,s)&&this._BabylonFileParsers[s](e,t,i,r)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=(e=(e=(e=e.concat(this.meshes)).concat(this.lights)).concat(this.cameras)).concat(this.transformNodes),this.skeletons.forEach(t=>e=e.concat(t.bones)),e}};AbstractScene._BabylonFileParsers={},AbstractScene._IndividualBabylonFileParsers={};let AbstractActionManager=class AbstractActionManager{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(let e in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,t)){let i=parseInt(t);if(i===e)return!0}return!1}};AbstractActionManager.Triggers={};let EventState=class EventState{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}};let Observer=class Observer{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}};let observable_Observable=class observable_Observable{static FromPromise(e,t){let i=new observable_Observable;return e.then(e=>{i.notifyObservers(e)}).catch(e=>{if(t)t.notifyObservers(e);else throw e}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=[],this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new EventState(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;let a=new Observer(e,t,r);return a.unregisterOnNextCall=s,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=()=>{this.remove(a)},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){if(!e)return!1;e._remove=null;let t=this._observers.indexOf(e);return -1!==t&&(this._deferUnregister(e),!0)}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return -1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,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,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let a=this._eventState;for(let n of(a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.lastReturnValue=e,a.userInfo=s,this._observers))if(!n._willBeUnregistered&&(n.mask&t&&(n.unregisterOnNextCall&&this._deferUnregister(n),n.scope?a.lastReturnValue=n.callback.apply(n.scope,[e,a]):a.lastReturnValue=n.callback(e,a)),a.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let 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(){let e=new observable_Observable;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}};let math_scalar_Scalar=class math_scalar_Scalar{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){let t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}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,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=math_scalar_Scalar.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){let i=math_scalar_Scalar.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let r=math_scalar_Scalar.Clamp(i);return t*(r=-2*r*r*r+3*r*r)+e*(1-r)}static MoveTowards(e,t,i){return Math.abs(t-e)<=i?t:e+math_scalar_Scalar.Sign(t-e)*i}static MoveTowardsAngle(e,t,i){let r=math_scalar_Scalar.DeltaAngle(e,t),s=0;return-i180&&(r-=360),e+r*math_scalar_Scalar.Clamp(i)}static InverseLerp(e,t,i){return e!=t?math_scalar_Scalar.Clamp((i-e)/(t-e)):0}static Hermite(e,t,i,r,s){let a=s*s,n=s*a;return e*(2*n-3*a+1)+i*(-2*n+3*a)+t*(n-2*a+s)+r*(n-a)}static Hermite1stDerivative(e,t,i,r,s){let a=s*s;return(a-s)*6*e+(3*a-4*s+1)*t+(-a+s)*6*i+(3*a-2*s)*r}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=math_scalar_Scalar.TwoPi*Math.floor((e+Math.PI)/math_scalar_Scalar.TwoPi)}static HCF(e,t){let i=e%t;return 0===i?t:math_scalar_Scalar.HCF(t,i)}};math_scalar_Scalar.TwoPi=2*Math.PI;let n=1/2.2,o=(1+Math.sqrt(5))/2;let arrayTools_ArrayTools=class arrayTools_ArrayTools{static BuildArray(e,t){let i=[];for(let r=0;r{let i=newFunction.previous;if(!i)return;let r=newFunction.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),newFunction.next=void 0,newFunction.previous=void 0}}let l=["push","splice","pop","shift","unshift"];function _ObserveArray(e,t){let i=l.map(i=>_observeArrayfunction(e,i,t));return()=>{i.forEach(e=>{null==e||e()})}}let h={};let performanceConfigurator_PerformanceConfigurator=class performanceConfigurator_PerformanceConfigurator{static SetMatrixPrecision(e){if(performanceConfigurator_PerformanceConfigurator.MatrixTrackPrecisionChange=!1,e&&!performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits&&performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices)for(let e=0;eparseInt(e.toString().replace(/\W/g,""));let math_vector_Vector2=class math_vector_Vector2{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=_ExtractAsInt(this.x),t=_ExtractAsInt(this.y);return 397*e^t}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return math_vector_Vector2.FromArrayToRef(e,t,this),this}asArray(){let e=[];return this.toArray(e,0),e}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)}add(e){return new this.constructor(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}addVector3(e){return new this.constructor(this.x+e.x,this.y+e.y)}subtract(e){return new this.constructor(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 this.constructor(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 this.constructor(this.x*e,this.y*t)}divide(e){return new this.constructor(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.divideToRef(e,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){let t=new this.constructor(0,0);return this.scaleToRef(e,t),t}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=.001){return e&&math_scalar_Scalar.WithinEpsilon(this.x,e.x,t)&&math_scalar_Scalar.WithinEpsilon(this.y,e.y,t)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(e,t){let i=Math.cos(e),r=Math.sin(e),s=i*this.x-r*this.y,a=r*this.x+i*this.y;return t.x=s,t.y=a,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 math_vector_Vector2.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new math_vector_Vector2(0,0)}static One(){return new math_vector_Vector2(1,1)}static Random(e=0,t=1){return new math_vector_Vector2(math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t))}static get ZeroReadOnly(){return math_vector_Vector2._ZeroReadOnly}static FromArray(e,t=0){return new math_vector_Vector2(e[t],e[t+1])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i}static CatmullRom(e,t,i,r,s){let a=s*s,n=s*a,o=.5*(2*t.x+(-e.x+i.x)*s+(2*e.x-5*t.x+4*i.x-r.x)*a+(-e.x+3*t.x-3*i.x+r.x)*n),l=.5*(2*t.y+(-e.y+i.y)*s+(2*e.y-5*t.y+4*i.y-r.y)*a+(-e.y+3*t.y-3*i.y+r.y)*n);return new e.constructor(o,l)}static Clamp(e,t,i){let r=e.x;r=(r=r>i.x?i.x:r)i.y?i.y:s)t.x?e.x:t.x,r=e.y>t.y?e.y:t.y;return new e.constructor(i,r)}static Transform(e,t){let i=new e.constructor;return math_vector_Vector2.TransformToRef(e,t,i),i}static TransformToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+r[12],a=e.x*r[1]+e.y*r[5]+r[13];return i.x=s,i.y=a,i}static PointInTriangle(e,t,i,r){let s=.5*(-i.y*r.x+t.y*(-i.x+r.x)+t.x*(i.y-r.y)+i.x*r.y),a=s<0?-1:1,n=(t.y*r.x-t.x*r.y+(r.y-t.y)*e.x+(t.x-r.x)*e.y)*a,o=(t.x*i.y-t.y*i.x+(t.y-i.y)*e.x+(i.x-t.x)*e.y)*a;return n>0&&o>0&&n+o<2*s*a}static Distance(e,t){return Math.sqrt(math_vector_Vector2.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y;return i*i+r*r}static Center(e,t){let i=new e.constructor;return math_vector_Vector2.CenterToRef(e,t,i)}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,i){let r=math_vector_Vector2.DistanceSquared(t,i);if(0===r)return math_vector_Vector2.Distance(e,t);let s=i.subtract(t),a=Math.max(0,Math.min(1,math_vector_Vector2.Dot(e.subtract(t),s)/r)),n=t.add(s.multiplyByFloats(a,a));return math_vector_Vector2.Distance(e,n)}};math_vector_Vector2._ZeroReadOnly=math_vector_Vector2.Zero();let math_vector_Vector3=class math_vector_Vector3{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,i=0){this._isDirty=!0,this._x=e,this._y=t,this._z=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=_ExtractAsInt(this._x),t=_ExtractAsInt(this._y),i=_ExtractAsInt(this._z),r=e;return 397*(r=397*r^t)^i}asArray(){let e=[];return this.toArray(e,0),e}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 math_vector_Vector3.FromArrayToRef(e,t,this),this}toQuaternion(){return math_vector_Quaternion.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this.addInPlaceFromFloats(e._x,e._y,e._z)}addInPlaceFromFloats(e,t,i){return this._x+=e,this._y+=t,this._z+=i,this._isDirty=!0,this}add(e){return new this.constructor(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t.copyFromFloats(this._x+e._x,this._y+e._y,this._z+e._z)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new this.constructor(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,i){return new this.constructor(this._x-e,this._y-t,this._z-i)}subtractFromFloatsToRef(e,t,i,r){return r.copyFromFloats(this._x-e,this._y-t,this._z-i)}negate(){return new this.constructor(-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.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new this.constructor(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t.copyFromFloats(this._x*e,this._y*e,this._z*e)}getNormalToRef(e){let t=this.length(),i=Math.acos(this.y/t),r=Math.atan2(this.z,this.x);i>Math.PI/2?i-=Math.PI/2:i+=Math.PI/2;let s=t*Math.sin(i)*Math.cos(r),a=t*Math.cos(i),n=t*Math.sin(i)*Math.sin(r);return e.set(s,a,n),e}applyRotationQuaternionToRef(e,t){let i=this._x,r=this._y,s=this._z,a=e._x,n=e._y,o=e._z,l=e._w,h=2*(n*s-o*r),c=2*(o*i-a*s),u=2*(a*r-n*i);return t._x=i+l*h+n*u-o*c,t._y=r+l*c+o*h-a*u,t._z=s+l*u+a*c-n*h,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new this.constructor)}scaleAndAddToRef(e,t){return t.addInPlaceFromFloats(this._x*e,this._y*e,this._z*e)}projectOnPlane(e,t){let i=new this.constructor;return this.projectOnPlaneToRef(e,t,i),i}projectOnPlaneToRef(e,t,i){let r=e.normal,s=e.d,a=MathTmp.Vector3[0];this.subtractToRef(t,a),a.normalize();let n=math_vector_Vector3.Dot(a,r);if(1e-10>Math.abs(n))i.setAll(1/0);else{let e=-(math_vector_Vector3.Dot(t,r)+s)/n,o=a.scaleInPlace(e);t.addToRef(o,i)}return i}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=.001){return e&&math_scalar_Scalar.WithinEpsilon(this._x,e._x,t)&&math_scalar_Scalar.WithinEpsilon(this._y,e._y,t)&&math_scalar_Scalar.WithinEpsilon(this._z,e._z,t)}equalsToFloats(e,t,i){return this._x===e&&this._y===t&&this._z===i}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.copyFromFloats(this._x*e._x,this._y*e._y,this._z*e._z)}multiplyByFloats(e,t,i){return new this.constructor(this._x*e,this._y*t,this._z*i)}divide(e){return new this.constructor(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t.copyFromFloats(this._x/e._x,this._y/e._y,this._z/e._z)}divideInPlace(e){return this.divideToRef(e,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,i){return ethis._x&&(this.x=e),t>this._y&&(this.y=t),i>this._z&&(this.z=i),this}isNonUniformWithinEpsilon(e){let t=Math.abs(this._x),i=Math.abs(this._y);if(!math_scalar_Scalar.WithinEpsilon(t,i,e))return!0;let r=Math.abs(this._z);return!(math_scalar_Scalar.WithinEpsilon(t,r,e)&&math_scalar_Scalar.WithinEpsilon(i,r,e))}get isNonUniform(){let e=Math.abs(this._x),t=Math.abs(this._y);if(e!==t)return!0;let i=Math.abs(this._z);return e!==i}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}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){return"xyz"===(e=e.toLowerCase())||(MathTmp.Vector3[0].copyFrom(this),["x","y","z"].forEach((t,i)=>{this[t]=MathTmp.Vector3[0][e[i]]})),this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(MathTmp.Matrix[0]),math_vector_Vector3.TransformCoordinatesToRef(this,MathTmp.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,i){return this.subtractToRef(t,MathTmp.Vector3[0]),MathTmp.Vector3[0].rotateByQuaternionToRef(e,MathTmp.Vector3[0]),t.addToRef(MathTmp.Vector3[0],i),i}cross(e){let t=new this.constructor;return math_vector_Vector3.CrossToRef(this,e,t)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){let e=new this.constructor(0,0,0);return this.normalizeToRef(e),e}normalizeToRef(e){let t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/t,e)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,i){return this._x=e,this._y=t,this._z=i,this._isDirty=!0,this}set(e,t,i){return this.copyFromFloats(e,t,i)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,i,r){let s=math_vector_Vector3.Dot(e,i)-r,a=math_vector_Vector3.Dot(t,i)-r;return s/(s-a)}static GetAngleBetweenVectors(e,t,i){let r=e.normalizeToRef(MathTmp.Vector3[1]),s=t.normalizeToRef(MathTmp.Vector3[2]),a=math_vector_Vector3.Dot(r,s);a=math_scalar_Scalar.Clamp(a,-1,1);let n=Math.acos(a),o=MathTmp.Vector3[3];return(math_vector_Vector3.CrossToRef(r,s,o),math_vector_Vector3.Dot(o,i)>0)?isNaN(n)?0:n:isNaN(n)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(e,t,i){MathTmp.Vector3[0].copyFrom(e);let r=MathTmp.Vector3[0];MathTmp.Vector3[1].copyFrom(t);let s=MathTmp.Vector3[1];MathTmp.Vector3[2].copyFrom(i);let a=MathTmp.Vector3[2],n=MathTmp.Vector3[3],o=MathTmp.Vector3[4];r.normalize(),s.normalize(),a.normalize(),math_vector_Vector3.CrossToRef(a,r,n),math_vector_Vector3.CrossToRef(n,a,o);let l=Math.atan2(math_vector_Vector3.Dot(s,n),math_vector_Vector3.Dot(s,o));return math_scalar_Scalar.NormalizeRadians(l)}static PitchYawRollToMoveBetweenPointsToRef(e,t,i){let r=math_vector_TmpVectors.Vector3[0];return t.subtractToRef(e,r),i._y=Math.atan2(r.x,r.z)||0,i._x=Math.atan2(Math.sqrt(r.x**2+r.z**2),r.y)||0,i._z=0,i._isDirty=!0,i}static PitchYawRollToMoveBetweenPoints(e,t){let i=math_vector_Vector3.Zero();return math_vector_Vector3.PitchYawRollToMoveBetweenPointsToRef(e,t,i)}static SlerpToRef(e,t,i,r){let s,a;i=math_scalar_Scalar.Clamp(i,0,1);let n=MathTmp.Vector3[0],o=MathTmp.Vector3[1];n.copyFrom(e);let l=n.length();n.normalizeFromLength(l),o.copyFrom(t);let h=o.length();o.normalizeFromLength(h);let c=math_vector_Vector3.Dot(n,o);if(c<.999){let e=Math.acos(c),t=1/Math.sin(e);s=Math.sin((1-i)*e)*t,a=Math.sin(i*e)*t}else s=1-i,a=i;return n.scaleInPlace(s),o.scaleInPlace(a),r.copyFrom(n).addInPlace(o),r.scaleInPlace(math_scalar_Scalar.Lerp(l,h,i)),r}static SmoothToRef(e,t,i,r,s){return math_vector_Vector3.SlerpToRef(e,t,0===r?1:i/r,s),s}static FromArray(e,t=0){return new math_vector_Vector3(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return math_vector_Vector3.FromArray(e,t)}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._isDirty=!0,i}static FromFloatArrayToRef(e,t,i){return math_vector_Vector3.FromArrayToRef(e,t,i)}static FromFloatsToRef(e,t,i,r){return r.copyFromFloats(e,t,i),r}static Zero(){return new math_vector_Vector3(0,0,0)}static One(){return new math_vector_Vector3(1,1,1)}static Up(){return new math_vector_Vector3(0,1,0)}static get UpReadOnly(){return math_vector_Vector3._UpReadOnly}static get DownReadOnly(){return math_vector_Vector3._DownReadOnly}static get RightReadOnly(){return math_vector_Vector3._RightReadOnly}static get LeftReadOnly(){return math_vector_Vector3._LeftReadOnly}static get LeftHandedForwardReadOnly(){return math_vector_Vector3._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return math_vector_Vector3._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return math_vector_Vector3._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return math_vector_Vector3._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return math_vector_Vector3._ZeroReadOnly}static get OneReadOnly(){return math_vector_Vector3._OneReadOnly}static Down(){return new math_vector_Vector3(0,-1,0)}static Forward(e=!1){return new math_vector_Vector3(0,0,e?-1:1)}static Backward(e=!1){return new math_vector_Vector3(0,0,e?1:-1)}static Right(){return new math_vector_Vector3(1,0,0)}static Left(){return new math_vector_Vector3(-1,0,0)}static Random(e=0,t=1){return new math_vector_Vector3(math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t))}static TransformCoordinates(e,t){let i=math_vector_Vector3.Zero();return math_vector_Vector3.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,n=e*a[0]+t*a[4]+i*a[8]+a[12],o=e*a[1]+t*a[5]+i*a[9]+a[13],l=e*a[2]+t*a[6]+i*a[10]+a[14],h=1/(e*a[3]+t*a[7]+i*a[11]+a[15]);return s._x=n*h,s._y=o*h,s._z=l*h,s._isDirty=!0,s}static TransformNormal(e,t){let i=math_vector_Vector3.Zero();return math_vector_Vector3.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformNormalFromFloatsToRef(e,t,i,r,s){let a=r.m;return s._x=e*a[0]+t*a[4]+i*a[8],s._y=e*a[1]+t*a[5]+i*a[9],s._z=e*a[2]+t*a[6]+i*a[10],s._isDirty=!0,s}static CatmullRom(e,t,i,r,s){let a=s*s,n=s*a,o=.5*(2*t._x+(-e._x+i._x)*s+(2*e._x-5*t._x+4*i._x-r._x)*a+(-e._x+3*t._x-3*i._x+r._x)*n),l=.5*(2*t._y+(-e._y+i._y)*s+(2*e._y-5*t._y+4*i._y-r._y)*a+(-e._y+3*t._y-3*i._y+r._y)*n),h=.5*(2*t._z+(-e._z+i._z)*s+(2*e._z-5*t._z+4*i._z-r._z)*a+(-e._z+3*t._z-3*i._z+r._z)*n);return new e.constructor(o,l,h)}static Clamp(e,t,i){let r=new e.constructor;return math_vector_Vector3.ClampToRef(e,t,i,r),r}static ClampToRef(e,t,i,r){let s=e._x;s=(s=s>i._x?i._x:s)i._y?i._y:a)i._z?i._z:n)0&&P<0?(M.copyFrom(l),n=t,o=i):P>0&&A<0?(M.copyFrom(c),n=i,o=r):(M.copyFrom(h).scaleInPlace(-1),n=r,o=t);let I=MathTmp.Vector3[9],D=MathTmp.Vector3[4];n.subtractToRef(b,E),o.subtractToRef(b,I),math_vector_Vector3.CrossToRef(E,I,D);let O=0>math_vector_Vector3.Dot(D,u);if(!O)return s.copyFrom(b),Math.abs(g*v);let B=MathTmp.Vector3[5];math_vector_Vector3.CrossToRef(M,D,B),B.normalize();let N=MathTmp.Vector3[9];N.copyFrom(n).subtractInPlace(b);let F=N.length();if(F<.001)return s.copyFrom(n),math_vector_Vector3.Distance(e,n);N.normalizeFromLength(F);let w=math_vector_Vector3.Dot(B,N),L=MathTmp.Vector3[7];L.copyFrom(b).addInPlace(B.scaleInPlace(F*w)),E.copyFrom(L).subtractInPlace(n),g=M.length(),M.normalizeFromLength(g);let V=math_vector_Vector3.Dot(E,M)/Math.max(g,.001);return V=math_scalar_Scalar.Clamp(V,0,1),L.copyFrom(n).addInPlace(M.scaleInPlace(V*g)),s.copyFrom(L),math_vector_Vector3.Distance(e,L)}static Center(e,t){return math_vector_Vector3.CenterToRef(e,t,math_vector_Vector3.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,i){let r=new e.constructor;return math_vector_Vector3.RotationFromAxisToRef(e,t,i,r),r}static RotationFromAxisToRef(e,t,i,r){let s=MathTmp.Quaternion[0];return math_vector_Quaternion.RotationQuaternionFromAxisToRef(e,t,i,s),s.toEulerAnglesToRef(r),r}};math_vector_Vector3._UpReadOnly=math_vector_Vector3.Up(),math_vector_Vector3._DownReadOnly=math_vector_Vector3.Down(),math_vector_Vector3._LeftHandedForwardReadOnly=math_vector_Vector3.Forward(!1),math_vector_Vector3._RightHandedForwardReadOnly=math_vector_Vector3.Forward(!0),math_vector_Vector3._LeftHandedBackwardReadOnly=math_vector_Vector3.Backward(!1),math_vector_Vector3._RightHandedBackwardReadOnly=math_vector_Vector3.Backward(!0),math_vector_Vector3._RightReadOnly=math_vector_Vector3.Right(),math_vector_Vector3._LeftReadOnly=math_vector_Vector3.Left(),math_vector_Vector3._ZeroReadOnly=math_vector_Vector3.Zero(),math_vector_Vector3._OneReadOnly=math_vector_Vector3.One();let math_vector_Vector4=class math_vector_Vector4{constructor(e=0,t=0,i=0,r=0){this.x=e,this.y=t,this.z=i,this.w=r}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let e=_ExtractAsInt(this.x),t=_ExtractAsInt(this.y),i=_ExtractAsInt(this.z),r=_ExtractAsInt(this.w),s=e;return 397*(s=397*(s=397*s^t)^i)^r}asArray(){let e=[];return this.toArray(e,0),e}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 math_vector_Vector4.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}add(e){return new this.constructor(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 this.constructor(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,i,r){return new this.constructor(this.x-e,this.y-t,this.z-i,this.w-r)}subtractFromFloatsToRef(e,t,i,r,s){return s.x=this.x-e,s.y=this.y-t,s.z=this.z-i,s.w=this.w-r,s}negate(){return new this.constructor(-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.copyFromFloats(-1*this.x,-1*this.y,-1*this.z,-1*this.w)}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new this.constructor(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=.001){return e&&math_scalar_Scalar.WithinEpsilon(this.x,e.x,t)&&math_scalar_Scalar.WithinEpsilon(this.y,e.y,t)&&math_scalar_Scalar.WithinEpsilon(this.z,e.z,t)&&math_scalar_Scalar.WithinEpsilon(this.w,e.w,t)}equalsToFloats(e,t,i,r){return this.x===e&&this.y===t&&this.z===i&&this.w===r}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new this.constructor(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,i,r){return new this.constructor(this.x*e,this.y*t,this.z*i,this.w*r)}divide(e){return new this.constructor(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.xthis.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}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(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(){let e=this.length();return 0===e?this:this.scaleInPlace(1/e)}toVector3(){return new math_vector_Vector3(this.x,this.y,this.z)}clone(){return new this.constructor(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,i,r){return this.x=e,this.y=t,this.z=i,this.w=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}setAll(e){return this.x=this.y=this.z=this.w=e,this}static FromArray(e,t){return t||(t=0),new math_vector_Vector4(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i.x=e[t],i.y=e[t+1],i.z=e[t+2],i.w=e[t+3],i}static FromFloatArrayToRef(e,t,i){return math_vector_Vector4.FromArrayToRef(e,t,i),i}static FromFloatsToRef(e,t,i,r,s){return s.x=e,s.y=t,s.z=i,s.w=r,s}static Zero(){return new math_vector_Vector4(0,0,0,0)}static One(){return new math_vector_Vector4(1,1,1,1)}static Random(e=0,t=1){return new math_vector_Vector4(math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t),math_scalar_Scalar.RandomRange(e,t))}static get ZeroReadOnly(){return math_vector_Vector4._ZeroReadOnly}static Normalize(e){let t=math_vector_Vector4.Zero();return math_vector_Vector4.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return t.copyFrom(e),t.normalize(),t}static Minimize(e,t){let i=new e.constructor;return i.copyFrom(e),i.minimizeInPlace(t),i}static Maximize(e,t){let i=new e.constructor;return i.copyFrom(e),i.maximizeInPlace(t),i}static Distance(e,t){return Math.sqrt(math_vector_Vector4.DistanceSquared(e,t))}static DistanceSquared(e,t){let i=e.x-t.x,r=e.y-t.y,s=e.z-t.z,a=e.w-t.w;return i*i+r*r+s*s+a*a}static Center(e,t){return math_vector_Vector4.CenterToRef(e,t,math_vector_Vector4.Zero())}static CenterToRef(e,t,i){return i.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}static TransformCoordinates(e,t){let i=math_vector_Vector4.Zero();return math_vector_Vector4.TransformCoordinatesToRef(e,t,i),i}static TransformCoordinatesToRef(e,t,i){return math_vector_Vector4.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,i),i}static TransformCoordinatesFromFloatsToRef(e,t,i,r,s){let a=r.m,n=e*a[0]+t*a[4]+i*a[8]+a[12],o=e*a[1]+t*a[5]+i*a[9]+a[13],l=e*a[2]+t*a[6]+i*a[10]+a[14],h=e*a[3]+t*a[7]+i*a[11]+a[15];return s.x=n,s.y=o,s.z=l,s.w=h,s}static TransformNormal(e,t){let i=new e.constructor;return math_vector_Vector4.TransformNormalToRef(e,t,i),i}static TransformNormalToRef(e,t,i){let r=t.m,s=e.x*r[0]+e.y*r[4]+e.z*r[8],a=e.x*r[1]+e.y*r[5]+e.z*r[9],n=e.x*r[2]+e.y*r[6]+e.z*r[10];return i.x=s,i.y=a,i.z=n,i.w=e.w,i}static TransformNormalFromFloatsToRef(e,t,i,r,s,a){let n=s.m;return a.x=e*n[0]+t*n[4]+i*n[8],a.y=e*n[1]+t*n[5]+i*n[9],a.z=e*n[2]+t*n[6]+i*n[10],a.w=r,a}static FromVector3(e,t=0){return new math_vector_Vector4(e._x,e._y,e._z,t)}};math_vector_Vector4._ZeroReadOnly=math_vector_Vector4.Zero();let math_vector_Quaternion=class math_vector_Quaternion{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,i=0,r=1){this._isDirty=!0,this._x=e,this._y=t,this._z=i,this._w=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=_ExtractAsInt(this._x),t=_ExtractAsInt(this._y),i=_ExtractAsInt(this._z),r=_ExtractAsInt(this._w),s=e;return 397*(s=397*(s=397*s^t)^i)^r}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}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=.001){return e&&math_scalar_Scalar.WithinEpsilon(this._x,e._x,t)&&math_scalar_Scalar.WithinEpsilon(this._y,e._y,t)&&math_scalar_Scalar.WithinEpsilon(this._z,e._z,t)&&math_scalar_Scalar.WithinEpsilon(this._w,e._w,t)}clone(){return new this.constructor(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,i,r){return this._x=e,this._y=t,this._z=i,this._w=r,this._isDirty=!0,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}add(e){return new this.constructor(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}subtract(e){return new this.constructor(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 this.constructor(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){let t=new this.constructor(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){let i=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,r=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,s=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,a=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(i,r,s,a),t}multiplyInPlace(e){return this.multiplyToRef(e,this),this}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 this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){let e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();let 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(){let e=this.length();return 0===e||this.scaleInPlace(1/e),this}normalizeToNew(){let e=this.length();return 0===e?this.clone():this.scale(1/e)}toEulerAngles(){let e=math_vector_Vector3.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){let t=this._z,i=this._x,r=this._y,s=this._w,a=r*t-i*s;if(a<-.4999999)e._y=2*Math.atan2(r,s),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(a>.4999999)e._y=2*Math.atan2(r,s),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{let n=s*s,o=t*t,l=i*i,h=r*r;e._z=Math.atan2(2*(i*r+t*s),-o-l+h+n),e._x=Math.asin(-2*a),e._y=Math.atan2(2*(t*i+r*s),o-l-h+n),e._isDirty=!0}return e}toRotationMatrix(e){return math_vector_Matrix.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return math_vector_Quaternion.FromRotationMatrixToRef(e,this),this}static FromRotationMatrix(e){let t=new math_vector_Quaternion;return math_vector_Quaternion.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){let i;let r=e.m,s=r[0],a=r[4],n=r[8],o=r[1],l=r[5],h=r[9],c=r[2],u=r[6],d=r[10],_=s+l+d;return _>0?(i=.5/Math.sqrt(_+1),t._w=.25/i,t._x=(u-h)*i,t._y=(n-c)*i,t._z=(o-a)*i):s>l&&s>d?(i=2*Math.sqrt(1+s-l-d),t._w=(u-h)/i,t._x=.25*i,t._y=(a+o)/i,t._z=(n+c)/i):l>d?(i=2*Math.sqrt(1+l-s-d),t._w=(n-c)/i,t._x=(a+o)/i,t._y=.25*i,t._z=(h+u)/i):(i=2*Math.sqrt(1+d-s-l),t._w=(o-a)/i,t._x=(n+c)/i,t._y=(h+u)/i,t._z=.25*i),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,i=.1){let r=math_vector_Quaternion.Dot(e,t);return 1-r*r<=i}static SmoothToRef(e,t,i,r,s){let a=0===r?1:i/r;return a=math_scalar_Scalar.Clamp(a,0,1),math_vector_Quaternion.SlerpToRef(e,t,a,s),s}static Zero(){return new math_vector_Quaternion(0,0,0,0)}static Inverse(e){return new e.constructor(-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 math_vector_Quaternion(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 math_vector_Quaternion.RotationAxisToRef(e,t,new math_vector_Quaternion)}static RotationAxisToRef(e,t,i){let r=Math.sin(t/2);return e.normalize(),i._w=Math.cos(t/2),i._x=e._x*r,i._y=e._y*r,i._z=e._z*r,i._isDirty=!0,i}static FromArray(e,t){return t||(t=0),new math_vector_Quaternion(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,i){return i._x=e[t],i._y=e[t+1],i._z=e[t+2],i._w=e[t+3],i._isDirty=!0,i}static FromEulerAngles(e,t,i){let r=new math_vector_Quaternion;return math_vector_Quaternion.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerAnglesToRef(e,t,i,r){return math_vector_Quaternion.RotationYawPitchRollToRef(t,e,i,r),r}static FromEulerVector(e){let t=new math_vector_Quaternion;return math_vector_Quaternion.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return math_vector_Quaternion.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,i,r=.001){let s=math_vector_Vector3.Dot(e,t)+1;return sMath.abs(e.z)?i.set(-e.y,e.x,0,0):i.set(0,-e.z,e.y,0):(math_vector_Vector3.CrossToRef(e,t,math_vector_TmpVectors.Vector3[0]),i.set(math_vector_TmpVectors.Vector3[0].x,math_vector_TmpVectors.Vector3[0].y,math_vector_TmpVectors.Vector3[0].z,s)),i.normalize()}static RotationYawPitchRoll(e,t,i){let r=new math_vector_Quaternion;return math_vector_Quaternion.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){let s=.5*i,a=.5*t,n=.5*e,o=Math.sin(s),l=Math.cos(s),h=Math.sin(a),c=Math.cos(a),u=Math.sin(n),d=Math.cos(n);return r._x=d*h*l+u*c*o,r._y=u*c*l-d*h*o,r._z=d*c*o-u*h*l,r._w=d*c*l+u*h*o,r._isDirty=!0,r}static RotationAlphaBetaGamma(e,t,i){let r=new math_vector_Quaternion;return math_vector_Quaternion.RotationAlphaBetaGammaToRef(e,t,i,r),r}static RotationAlphaBetaGammaToRef(e,t,i,r){let s=(i+e)*.5,a=(i-e)*.5,n=.5*t;return r._x=Math.cos(a)*Math.sin(n),r._y=Math.sin(a)*Math.sin(n),r._z=Math.sin(s)*Math.cos(n),r._w=Math.cos(s)*Math.cos(n),r._isDirty=!0,r}static RotationQuaternionFromAxis(e,t,i){let r=new math_vector_Quaternion(0,0,0,0);return math_vector_Quaternion.RotationQuaternionFromAxisToRef(e,t,i,r),r}static RotationQuaternionFromAxisToRef(e,t,i,r){let s=MathTmp.Matrix[0];return math_vector_Matrix.FromXYZAxesToRef(e.normalize(),t.normalize(),i.normalize(),s),math_vector_Quaternion.FromRotationMatrixToRef(s,r),r}static FromLookDirectionLH(e,t){let i=new math_vector_Quaternion;return math_vector_Quaternion.FromLookDirectionLHToRef(e,t,i),i}static FromLookDirectionLHToRef(e,t,i){let r=MathTmp.Matrix[0];return math_vector_Matrix.LookDirectionLHToRef(e,t,r),math_vector_Quaternion.FromRotationMatrixToRef(r,i),i}static FromLookDirectionRH(e,t){let i=new math_vector_Quaternion;return math_vector_Quaternion.FromLookDirectionRHToRef(e,t,i),i}static FromLookDirectionRHToRef(e,t,i){let r=MathTmp.Matrix[0];return math_vector_Matrix.LookDirectionRHToRef(e,t,r),math_vector_Quaternion.FromRotationMatrixToRef(r,i)}static Slerp(e,t,i){let r=math_vector_Quaternion.Identity();return math_vector_Quaternion.SlerpToRef(e,t,i,r),r}static SlerpToRef(e,t,i,r){let s,a;let n=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,o=!1;if(n<0&&(o=!0,n=-n),n>.999999)a=1-i,s=o?-i:i;else{let e=Math.acos(n),t=1/Math.sin(e);a=Math.sin((1-i)*e)*t,s=o?-Math.sin(i*e)*t:Math.sin(i*e)*t}return r._x=a*e._x+s*t._x,r._y=a*e._y+s*t._y,r._z=a*e._z+s*t._z,r._w=a*e._w+s*t._w,r._isDirty=!0,r}static Hermite(e,t,i,r,s){let a=s*s,n=s*a,o=2*n-3*a+1,l=-2*n+3*a,h=n-2*a+s,c=n-a,u=e._x*o+i._x*l+t._x*h+r._x*c,d=e._y*o+i._y*l+t._y*h+r._y*c,_=e._z*o+i._z*l+t._z*h+r._z*c,p=e._w*o+i._w*l+t._w*h+r._w*c;return new e.constructor(u,d,_,p)}static Hermite1stDerivative(e,t,i,r,s){let a=new e.constructor;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let n=s*s;return a._x=(n-s)*6*e._x+(3*n-4*s+1)*t._x+(-n+s)*6*i._x+(3*n-2*s)*r._x,a._y=(n-s)*6*e._y+(3*n-4*s+1)*t._y+(-n+s)*6*i._y+(3*n-2*s)*r._y,a._z=(n-s)*6*e._z+(3*n-4*s+1)*t._z+(-n+s)*6*i._z+(3*n-2*s)*r._z,a._w=(n-s)*6*e._w+(3*n-4*s+1)*t._w+(-n+s)*6*i._w+(3*n-2*s)*r._w,a._isDirty=!0,a}};let math_vector_Matrix=class math_vector_Matrix{static get Use64Bits(){return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=math_vector_Matrix._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,i=!1,r=!0){this._isIdentity=e,this._isIdentity3x2=e||i,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&r}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,performanceConfigurator_PerformanceConfigurator.MatrixTrackPrecisionChange&&performanceConfigurator_PerformanceConfigurator.MatrixTrackedMatrices.push(this),this._m=new performanceConfigurator_PerformanceConfigurator.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let 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]?this._isIdentity3x2=!1: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;let e=this._m,t=e[0],i=e[1],r=e[2],s=e[3],a=e[4],n=e[5],o=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],_=e[12],p=e[13],f=e[14],m=e[15],g=u*m-f*d,v=c*m-p*d,x=c*f-p*u,b=h*m-_*d,T=h*f-u*_,S=h*p-_*c;return t*+(n*g-o*v+l*x)+-(i*(a*g-o*b+l*T))+r*+(a*v-n*b+l*S)+-(s*(a*x-n*T+o*S))}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} -${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} -${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} -${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return math_vector_Matrix.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){let t=new this.constructor;return this.addToRef(e,t),t}addToRef(e,t){let i=this._m,r=t._m,s=e.m;for(let e=0;e<16;e++)r[e]=i[e]+s[e];return t.markAsUpdated(),t}addToSelf(e){let t=this._m,i=e.m;for(let e=0;e<16;e++)t[e]+=i[e];return this.markAsUpdated(),this}invertToRef(e){if(!0===this._isIdentity)return math_vector_Matrix.IdentityToRef(e),e;let t=this._m,i=t[0],r=t[1],s=t[2],a=t[3],n=t[4],o=t[5],l=t[6],h=t[7],c=t[8],u=t[9],d=t[10],_=t[11],p=t[12],f=t[13],m=t[14],g=t[15],v=d*g-m*_,x=u*g-f*_,b=u*m-f*d,T=c*g-p*_,S=c*m-d*p,C=c*f-p*u,E=+(o*v-l*x+h*b),y=-(n*v-l*T+h*S),R=+(n*x-o*T+h*C),P=-(n*b-o*S+l*C),A=i*E+r*y+s*R+a*P;if(0===A)return e.copyFrom(this),e;let M=1/A,I=l*g-m*h,D=o*g-f*h,O=o*m-f*l,B=n*g-p*h,N=n*m-p*l,F=n*f-p*o,w=l*_-d*h,L=o*_-u*h,V=o*d-u*l,U=n*_-c*h,k=n*d-c*l,G=n*u-c*o;return math_vector_Matrix.FromValuesToRef(E*M,-(r*v-s*x+a*b)*M,+(r*I-s*D+a*O)*M,-(r*w-s*L+a*V)*M,y*M,+(i*v-s*T+a*S)*M,-(i*I-s*B+a*N)*M,+(i*w-s*U+a*k)*M,R*M,-(i*x-r*T+a*C)*M,+(i*D-r*B+a*F)*M,-(i*L-r*U+a*G)*M,P*M,+(i*b-r*S+s*C)*M,-(i*O-r*N+s*F)*M,+(i*V-r*k+s*G)*M,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,i){return this._m[12]=e,this._m[13]=t,this._m[14]=i,this.markAsUpdated(),this}addTranslationFromFloats(e,t,i){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=i,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new math_vector_Vector3(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(){let e=this.m;return math_vector_Matrix.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}multiply(e){let t=new this.constructor;return this.multiplyToRef(e,t),t}copyFrom(e){return e.copyToArray(this._m),this.updateFlag=e.updateFlag,this._updateIdentityStatus(e._isIdentity,e._isIdentityDirty,e._isIdentity3x2,e._isIdentity3x2Dirty),this}copyToArray(e,t=0){let i=this._m;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],this}multiplyToRef(e,t){return this._isIdentity?t.copyFrom(e):e._isIdentity?t.copyFrom(this):(this.multiplyToArray(e,t._m,0),t.markAsUpdated()),t}multiplyToArray(e,t,i){let r=this._m,s=e.m,a=r[0],n=r[1],o=r[2],l=r[3],h=r[4],c=r[5],u=r[6],d=r[7],_=r[8],p=r[9],f=r[10],m=r[11],g=r[12],v=r[13],x=r[14],b=r[15],T=s[0],S=s[1],C=s[2],E=s[3],y=s[4],R=s[5],P=s[6],A=s[7],M=s[8],I=s[9],D=s[10],O=s[11],B=s[12],N=s[13],F=s[14],w=s[15];return t[i]=a*T+n*y+o*M+l*B,t[i+1]=a*S+n*R+o*I+l*N,t[i+2]=a*C+n*P+o*D+l*F,t[i+3]=a*E+n*A+o*O+l*w,t[i+4]=h*T+c*y+u*M+d*B,t[i+5]=h*S+c*R+u*I+d*N,t[i+6]=h*C+c*P+u*D+d*F,t[i+7]=h*E+c*A+u*O+d*w,t[i+8]=_*T+p*y+f*M+m*B,t[i+9]=_*S+p*R+f*I+m*N,t[i+10]=_*C+p*P+f*D+m*F,t[i+11]=_*E+p*A+f*O+m*w,t[i+12]=g*T+v*y+x*M+b*B,t[i+13]=g*S+v*R+x*I+b*N,t[i+14]=g*C+v*P+x*D+b*F,t[i+15]=g*E+v*A+x*O+b*w,this}equals(e){if(!e)return!1;if((this._isIdentity||e._isIdentity)&&!this._isIdentityDirty&&!e._isIdentityDirty)return this._isIdentity&&e._isIdentity;let t=this.m,i=e.m;return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]}clone(){let e=new this.constructor;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=_ExtractAsInt(this._m[0]);for(let t=1;t<16;t++)e=397*e^_ExtractAsInt(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new math_vector_Quaternion,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,i,r){if(this._isIdentity)return i&&i.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;let s=this._m;if(i&&i.copyFromFloats(s[12],s[13],s[14]),(e=e||MathTmp.Vector3[0]).x=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),e.y=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),e.z=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]),r){let t=r.absoluteScaling.x<0?-1:1,i=r.absoluteScaling.y<0?-1:1,s=r.absoluteScaling.z<0?-1:1;e.x*=t,e.y*=i,e.z*=s}else 0>=this.determinant()&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){let i=1/e._x,r=1/e._y,a=1/e._z;math_vector_Matrix.FromValuesToRef(s[0]*i,s[1]*i,s[2]*i,0,s[4]*r,s[5]*r,s[6]*r,0,s[8]*a,s[9]*a,s[10]*a,0,0,0,0,1,MathTmp.Matrix[0]),math_vector_Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;let t=4*e;return new math_vector_Vector4(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<3){let i=4*e;t.x=this._m[i+0],t.y=this._m[i+1],t.z=this._m[i+2],t.w=this._m[i+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){let e=new this.constructor;return math_vector_Matrix.TransposeToRef(this,e),e}transposeToRef(e){return math_vector_Matrix.TransposeToRef(this,e),e}setRowFromFloats(e,t,i,r,s){if(e<0||e>3)return this;let a=4*e;return this._m[a+0]=t,this._m[a+1]=i,this._m[a+2]=r,this._m[a+3]=s,this.markAsUpdated(),this}scale(e){let t=new this.constructor;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let i=0;i<16;i++)t._m[i]=this._m[i]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let i=0;i<16;i++)t._m[i]+=this._m[i]*e;return t.markAsUpdated(),t}toNormalMatrix(e){let t=MathTmp.Matrix[0];this.invertToRef(t),t.transposeToRef(e);let i=e._m;return math_vector_Matrix.FromValuesToRef(i[0],i[1],i[2],0,i[4],i[5],i[6],0,i[8],i[9],i[10],0,0,0,0,1,e),e}getRotationMatrix(){let e=new this.constructor;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){let t=MathTmp.Vector3[0];if(!this.decompose(t))return math_vector_Matrix.IdentityToRef(e),e;let i=this._m,r=1/t._x,s=1/t._y,a=1/t._z;return math_vector_Matrix.FromValuesToRef(i[0]*r,i[1]*r,i[2]*r,0,i[4]*s,i[5]*s,i[6]*s,0,i[8]*a,i[9]*a,i[10]*a,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){let e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){let i=new math_vector_Matrix;return math_vector_Matrix.FromArrayToRef(e,t,i),i}static FromArrayToRef(e,t,i){for(let r=0;r<16;r++)i._m[r]=e[r+t];return i.markAsUpdated(),i}static FromFloat32ArrayToRefScaled(e,t,i,r){for(let s=0;s<16;s++)r._m[s]=e[s+t]*i;return r.markAsUpdated(),r}static get IdentityReadOnly(){return math_vector_Matrix._IdentityReadOnly}static FromValuesToRef(e,t,i,r,s,a,n,o,l,h,c,u,d,_,p,f,m){let g=m._m;g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=s,g[5]=a,g[6]=n,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated()}static FromValues(e,t,i,r,s,a,n,o,l,h,c,u,d,_,p,f){let m=new math_vector_Matrix,g=m._m;return g[0]=e,g[1]=t,g[2]=i,g[3]=r,g[4]=s,g[5]=a,g[6]=n,g[7]=o,g[8]=l,g[9]=h,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=p,g[15]=f,m.markAsUpdated(),m}static Compose(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.ComposeToRef(e,t,i,r),r}static ComposeToRef(e,t,i,r){let s=r._m,a=t._x,n=t._y,o=t._z,l=t._w,h=a+a,c=n+n,u=o+o,d=a*h,_=a*c,p=a*u,f=n*c,m=n*u,g=o*u,v=l*h,x=l*c,b=l*u,T=e._x,S=e._y,C=e._z;return s[0]=(1-(f+g))*T,s[1]=(_+b)*T,s[2]=(p-x)*T,s[3]=0,s[4]=(_-b)*S,s[5]=(1-(d+g))*S,s[6]=(m+v)*S,s[7]=0,s[8]=(p+x)*C,s[9]=(m-v)*C,s[10]=(1-(d+f))*C,s[11]=0,s[12]=i._x,s[13]=i._y,s[14]=i._z,s[15]=1,r.markAsUpdated(),r}static Identity(){let e=math_vector_Matrix.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 math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){let e=math_vector_Matrix.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){let t=new math_vector_Matrix;return math_vector_Matrix.RotationXToRef(e,t),t}static Invert(e){let t=new e.constructor;return e.invertToRef(t),t}static RotationXToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return math_vector_Matrix.FromValuesToRef(1,0,0,0,0,r,i,0,0,-i,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationY(e){let t=new math_vector_Matrix;return math_vector_Matrix.RotationYToRef(e,t),t}static RotationYToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return math_vector_Matrix.FromValuesToRef(r,0,-i,0,0,1,0,0,i,0,r,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationZ(e){let t=new math_vector_Matrix;return math_vector_Matrix.RotationZToRef(e,t),t}static RotationZToRef(e,t){let i=Math.sin(e),r=Math.cos(e);return math_vector_Matrix.FromValuesToRef(r,i,0,0,-i,r,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===r&&0===i),t}static RotationAxis(e,t){let i=new math_vector_Matrix;return math_vector_Matrix.RotationAxisToRef(e,t,i),i}static RotationAxisToRef(e,t,i){let r=Math.sin(-t),s=Math.cos(-t),a=1-s;e.normalize();let n=i._m;return n[0]=e._x*e._x*a+s,n[1]=e._x*e._y*a-e._z*r,n[2]=e._x*e._z*a+e._y*r,n[3]=0,n[4]=e._y*e._x*a+e._z*r,n[5]=e._y*e._y*a+s,n[6]=e._y*e._z*a-e._x*r,n[7]=0,n[8]=e._z*e._x*a-e._y*r,n[9]=e._z*e._y*a+e._x*r,n[10]=e._z*e._z*a+s,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,i.markAsUpdated(),i}static RotationAlignToRef(e,t,i,r=!1){let s=math_vector_Vector3.Dot(t,e),a=i._m;if(s<-.999)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=r?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=r?-1:1,a[11]=0;else{let i=math_vector_Vector3.Cross(t,e),r=1/(1+s);a[0]=i._x*i._x*r+s,a[1]=i._y*i._x*r-i._z,a[2]=i._z*i._x*r+i._y,a[3]=0,a[4]=i._x*i._y*r+i._z,a[5]=i._y*i._y*r+s,a[6]=i._z*i._y*r-i._x,a[7]=0,a[8]=i._x*i._z*r-i._y,a[9]=i._y*i._z*r+i._x,a[10]=i._z*i._z*r+s,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,i.markAsUpdated(),i}static RotationYawPitchRoll(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.RotationYawPitchRollToRef(e,t,i,r),r}static RotationYawPitchRollToRef(e,t,i,r){return math_vector_Quaternion.RotationYawPitchRollToRef(e,t,i,MathTmp.Quaternion[0]),MathTmp.Quaternion[0].toRotationMatrix(r),r}static Scaling(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.ScalingToRef(e,t,i,r),r}static ScalingToRef(e,t,i,r){return math_vector_Matrix.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1,r),r._updateIdentityStatus(1===e&&1===t&&1===i),r}static Translation(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.TranslationToRef(e,t,i,r),r}static TranslationToRef(e,t,i,r){return math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1,r),r._updateIdentityStatus(0===e&&0===t&&0===i),r}static Lerp(e,t,i){let r=new e.constructor;return math_vector_Matrix.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){let s=r._m,a=e.m,n=t.m;for(let e=0;e<16;e++)s[e]=a[e]*(1-i)+n[e]*i;return r.markAsUpdated(),r}static DecomposeLerp(e,t,i){let r=new e.constructor;return math_vector_Matrix.DecomposeLerpToRef(e,t,i,r),r}static DecomposeLerpToRef(e,t,i,r){let s=MathTmp.Vector3[0],a=MathTmp.Quaternion[0],n=MathTmp.Vector3[1];e.decompose(s,a,n);let o=MathTmp.Vector3[2],l=MathTmp.Quaternion[1],h=MathTmp.Vector3[3];t.decompose(o,l,h);let c=MathTmp.Vector3[4];math_vector_Vector3.LerpToRef(s,o,i,c);let u=MathTmp.Quaternion[2];math_vector_Quaternion.SlerpToRef(a,l,i,u);let d=MathTmp.Vector3[5];return math_vector_Vector3.LerpToRef(n,h,i,d),math_vector_Matrix.ComposeToRef(c,u,d,r),r}static LookAtLH(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.LookAtLHToRef(e,t,i,r),r}static LookAtLHToRef(e,t,i,r){let s=MathTmp.Vector3[0],a=MathTmp.Vector3[1],n=MathTmp.Vector3[2];t.subtractToRef(e,n),n.normalize(),math_vector_Vector3.CrossToRef(i,n,s);let o=s.lengthSquared();0===o?s.x=1:s.normalizeFromLength(Math.sqrt(o)),math_vector_Vector3.CrossToRef(n,s,a),a.normalize();let l=-math_vector_Vector3.Dot(s,e),h=-math_vector_Vector3.Dot(a,e),c=-math_vector_Vector3.Dot(n,e);math_vector_Matrix.FromValuesToRef(s._x,a._x,n._x,0,s._y,a._y,n._y,0,s._z,a._z,n._z,0,l,h,c,1,r)}static LookAtRH(e,t,i){let r=new math_vector_Matrix;return math_vector_Matrix.LookAtRHToRef(e,t,i,r),r}static LookAtRHToRef(e,t,i,r){let s=MathTmp.Vector3[0],a=MathTmp.Vector3[1],n=MathTmp.Vector3[2];e.subtractToRef(t,n),n.normalize(),math_vector_Vector3.CrossToRef(i,n,s);let o=s.lengthSquared();0===o?s.x=1:s.normalizeFromLength(Math.sqrt(o)),math_vector_Vector3.CrossToRef(n,s,a),a.normalize();let l=-math_vector_Vector3.Dot(s,e),h=-math_vector_Vector3.Dot(a,e),c=-math_vector_Vector3.Dot(n,e);return math_vector_Matrix.FromValuesToRef(s._x,a._x,n._x,0,s._y,a._y,n._y,0,s._z,a._z,n._z,0,l,h,c,1,r),r}static LookDirectionLH(e,t){let i=new math_vector_Matrix;return math_vector_Matrix.LookDirectionLHToRef(e,t,i),i}static LookDirectionLHToRef(e,t,i){let r=MathTmp.Vector3[0];r.copyFrom(e),r.scaleInPlace(-1);let s=MathTmp.Vector3[1];return math_vector_Vector3.CrossToRef(t,r,s),math_vector_Matrix.FromValuesToRef(s._x,s._y,s._z,0,t._x,t._y,t._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static LookDirectionRH(e,t){let i=new math_vector_Matrix;return math_vector_Matrix.LookDirectionRHToRef(e,t,i),i}static LookDirectionRHToRef(e,t,i){let r=MathTmp.Vector3[2];return math_vector_Vector3.CrossToRef(t,e,r),math_vector_Matrix.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,i),i}static OrthoLH(e,t,i,r,s){let a=new math_vector_Matrix;return math_vector_Matrix.OrthoLHToRef(e,t,i,r,a,s),a}static OrthoLHToRef(e,t,i,r,s,a){let n=2/e,o=2/t,l=2/(r-i),h=-(r+i)/(r-i);return math_vector_Matrix.FromValuesToRef(n,0,0,0,0,o,0,0,0,0,l,0,0,0,h,1,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(1===n&&1===o&&1===l&&0===h),s}static OrthoOffCenterLH(e,t,i,r,s,a,n){let o=new math_vector_Matrix;return math_vector_Matrix.OrthoOffCenterLHToRef(e,t,i,r,s,a,o,n),o}static OrthoOffCenterLHToRef(e,t,i,r,s,a,n,o){return math_vector_Matrix.FromValuesToRef(2/(t-e),0,0,0,0,2/(r-i),0,0,0,0,2/(a-s),0,(e+t)/(e-t),(r+i)/(i-r),-(a+s)/(a-s),1,n),o&&n.multiplyToRef(c,n),n.markAsUpdated(),n}static ObliqueOffCenterLHToRef(e,t,i,r,s,a,n,o,l,h,c){let u=-n*Math.cos(o),d=-n*Math.sin(o);return math_vector_Matrix.TranslationToRef(0,0,-l,MathTmp.Matrix[1]),math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,MathTmp.Matrix[0]),MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0],MathTmp.Matrix[0]),math_vector_Matrix.TranslationToRef(0,0,l,MathTmp.Matrix[1]),MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1],MathTmp.Matrix[0]),math_vector_Matrix.OrthoOffCenterLHToRef(e,t,i,r,s,a,h,c),MathTmp.Matrix[0].multiplyToRef(h,h),h}static OrthoOffCenterRH(e,t,i,r,s,a,n){let o=new math_vector_Matrix;return math_vector_Matrix.OrthoOffCenterRHToRef(e,t,i,r,s,a,o,n),o}static OrthoOffCenterRHToRef(e,t,i,r,s,a,n,o){return math_vector_Matrix.OrthoOffCenterLHToRef(e,t,i,r,s,a,n,o),n._m[10]*=-1,n}static ObliqueOffCenterRHToRef(e,t,i,r,s,a,n,o,l,h,c){let u=n*Math.cos(o),d=n*Math.sin(o);return math_vector_Matrix.TranslationToRef(0,0,l,MathTmp.Matrix[1]),math_vector_Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,MathTmp.Matrix[0]),MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0],MathTmp.Matrix[0]),math_vector_Matrix.TranslationToRef(0,0,-l,MathTmp.Matrix[1]),MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1],MathTmp.Matrix[0]),math_vector_Matrix.OrthoOffCenterRHToRef(e,t,i,r,s,a,h,c),MathTmp.Matrix[0].multiplyToRef(h,h),h}static PerspectiveLH(e,t,i,r,s,a=0){let n=new math_vector_Matrix,o=Math.tan(a);return math_vector_Matrix.FromValuesToRef(2*i/e,0,0,0,0,2*i/t,0,o,0,0,(r+i)/(r-i),1,0,0,-2*r*i/(r-i),0,n),s&&n.multiplyToRef(c,n),n._updateIdentityStatus(!1),n}static PerspectiveFovLH(e,t,i,r,s,a=0,n=!1){let o=new math_vector_Matrix;return math_vector_Matrix.PerspectiveFovLHToRef(e,t,i,r,o,!0,s,a,n),o}static PerspectiveFovLHToRef(e,t,i,r,s,a=!0,n,o=0,l=!1){let h=1/Math.tan(.5*e),u=a?h/t:h,d=a?h:h*t,_=l&&0===i?-1:0!==r?(r+i)/(r-i):1,p=l&&0===i?2*r:0!==r?-2*r*i/(r-i):-2*i,f=Math.tan(o);return math_vector_Matrix.FromValuesToRef(u,0,0,0,0,d,0,f,0,0,_,1,0,0,p,0,s),n&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(e,t,i,r,s,a=!0,n,o=0){let l=1/Math.tan(.5*e),h=a?l/t:l,u=a?l:l*t,d=Math.tan(o);return math_vector_Matrix.FromValuesToRef(h,0,0,0,0,u,0,d,0,0,-i,1,0,0,1,0,s),n&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(e,t,i,r,s,a=0,n=!1){let o=new math_vector_Matrix;return math_vector_Matrix.PerspectiveFovRHToRef(e,t,i,r,o,!0,s,a,n),o}static PerspectiveFovRHToRef(e,t,i,r,s,a=!0,n,o=0,l=!1){let h=1/Math.tan(.5*e),u=a?h/t:h,d=a?h:h*t,_=l&&0===i?1:0!==r?-(r+i)/(r-i):-1,p=l&&0===i?2*r:0!==r?-2*r*i/(r-i):-2*i,f=Math.tan(o);return math_vector_Matrix.FromValuesToRef(u,0,0,0,0,d,0,f,0,0,_,-1,0,0,p,0,s),n&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(e,t,i,r,s,a=!0,n,o=0){let l=1/Math.tan(.5*e),h=a?l/t:l,u=a?l:l*t,d=Math.tan(o);return math_vector_Matrix.FromValuesToRef(h,0,0,0,0,u,0,d,0,0,-i,-1,0,0,-1,0,s),n&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(e,t,i,r,s,a){let n=e.width,o=e.height,l=e.x,h=e.y,c=math_vector_Matrix.FromValues(n/2,0,0,0,0,-o/2,0,0,0,0,a-s,0,l+n/2,o/2+h,s,1),u=new t.constructor;return t.multiplyToRef(i,u),u.multiplyToRef(r,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){let t=e.m,i=[t[0],t[1],t[4],t[5]];return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits?i:new Float32Array(i)}static GetAsMatrix3x3(e){let t=e.m,i=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return performanceConfigurator_PerformanceConfigurator.MatrixUse64Bits?i:new Float32Array(i)}static Transpose(e){let t=new e.constructor;return math_vector_Matrix.TransposeToRef(e,t),t}static TransposeToRef(e,t){let i=e.m,r=i[0],s=i[4],a=i[8],n=i[12],o=i[1],l=i[5],h=i[9],c=i[13],u=i[2],d=i[6],_=i[10],p=i[14],f=i[3],m=i[7],g=i[11],v=i[15],x=t._m;return x[0]=r,x[1]=s,x[2]=a,x[3]=n,x[4]=o,x[5]=l,x[6]=h,x[7]=c,x[8]=u,x[9]=d,x[10]=_,x[11]=p,x[12]=f,x[13]=m,x[14]=g,x[15]=v,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){let t=new math_vector_Matrix;return math_vector_Matrix.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();let i=e.normal.x,r=e.normal.y,s=e.normal.z,a=-2*i,n=-2*r,o=-2*s;return math_vector_Matrix.FromValuesToRef(a*i+1,n*i,o*i,0,a*r,n*r+1,o*r,0,a*s,n*s,o*s+1,0,a*e.d,n*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,i,r){return math_vector_Matrix.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static FromQuaternionToRef(e,t){let i=e._x*e._x,r=e._y*e._y,s=e._z*e._z,a=e._x*e._y,n=e._z*e._w,o=e._z*e._x,l=e._y*e._w,h=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(r+s),t._m[1]=2*(a+n),t._m[2]=2*(o-l),t._m[3]=0,t._m[4]=2*(a-n),t._m[5]=1-2*(s+i),t._m[6]=2*(h+c),t._m[7]=0,t._m[8]=2*(o+l),t._m[9]=2*(h-c),t._m[10]=1-2*(r+i),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}};math_vector_Matrix._UpdateFlagSeed=0,math_vector_Matrix._IdentityReadOnly=math_vector_Matrix.Identity();let MathTmp=class MathTmp{};MathTmp.Vector3=arrayTools_ArrayTools.BuildTuple(11,math_vector_Vector3.Zero),MathTmp.Matrix=arrayTools_ArrayTools.BuildTuple(2,math_vector_Matrix.Identity),MathTmp.Quaternion=arrayTools_ArrayTools.BuildTuple(3,math_vector_Quaternion.Zero);let math_vector_TmpVectors=class math_vector_TmpVectors{};math_vector_TmpVectors.Vector2=arrayTools_ArrayTools.BuildTuple(3,math_vector_Vector2.Zero),math_vector_TmpVectors.Vector3=arrayTools_ArrayTools.BuildTuple(13,math_vector_Vector3.Zero),math_vector_TmpVectors.Vector4=arrayTools_ArrayTools.BuildTuple(3,math_vector_Vector4.Zero),math_vector_TmpVectors.Quaternion=arrayTools_ArrayTools.BuildTuple(2,math_vector_Quaternion.Zero),math_vector_TmpVectors.Matrix=arrayTools_ArrayTools.BuildTuple(8,math_vector_Matrix.Identity),h["BABYLON.Vector2"]=math_vector_Vector2,h["BABYLON.Vector3"]=math_vector_Vector3,h["BABYLON.Vector4"]=math_vector_Vector4,h["BABYLON.Matrix"]=math_vector_Matrix;let c=math_vector_Matrix.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1);function colorChannelToLinearSpace(e){return Math.pow(e,2.2)}function colorChannelToLinearSpaceExact(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function colorChannelToGammaSpace(e){return Math.pow(e,n)}function colorChannelToGammaSpaceExact(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let math_color_Color3=class math_color_Color3{constructor(e=0,t=0,i=0){this.r=e,this.g=t,this.b=i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return 397*(e=397*e^(255*this.g|0))^(255*this.b|0)}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 math_color_Color3.FromArrayToRef(e,t,this),this}toColor4(e=1){return new math_color_Color4(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 math_color_Color3(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,this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,i){return this.r===e&&this.g===t&&this.b===i}scale(e){return new math_color_Color3(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,this}clampToRef(e=0,t=1,i){return i.r=math_scalar_Scalar.Clamp(this.r,e,t),i.g=math_scalar_Scalar.Clamp(this.g,e,t),i.b=math_scalar_Scalar.Clamp(this.b,e,t),this}add(e){return new math_color_Color3(this.r+e.r,this.g+e.g,this.b+e.b)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,this}subtract(e){return new math_color_Color3(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,this}clone(){return new math_color_Color3(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,i){return this.r=e,this.g=t,this.b=i,this}set(e,t,i){return this.copyFromFloats(e,t,i)}toHexString(){let e=Math.round(255*this.r),t=Math.round(255*this.g),i=Math.round(255*this.b);return"#"+math_scalar_Scalar.ToHex(e)+math_scalar_Scalar.ToHex(t)+math_scalar_Scalar.ToHex(i)}toHSV(){let e=new math_color_Color3;return this.toHSVToRef(e),e}toHSVToRef(e){let t=this.r,i=this.g,r=this.b,s=Math.max(t,i,r),a=Math.min(t,i,r),n=0,o=0,l=s-a;0!==s&&(o=l/s),s!=a&&(s==t?(n=(i-r)/l,i=0&&a<=1?(o=s,l=n):a>=1&&a<=2?(o=n,l=s):a>=2&&a<=3?(l=s,h=n):a>=3&&a<=4?(l=n,h=s):a>=4&&a<=5?(o=n,h=s):a>=5&&a<=6&&(o=s,h=n);let c=i-s;r.set(o+c,l+c,h+c)}static FromHSV(e,t,i){let r=new math_color_Color3(0,0,0);return math_color_Color3.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new math_color_Color3(0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return math_color_Color3.FromInts(t,i,r)}static FromArray(e,t=0){return new math_color_Color3(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new math_color_Color3(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new math_color_Color3(0,0,0);return math_color_Color3.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let a=s*s,n=s*a,o=2*n-3*a+1,l=-2*n+3*a,h=n-2*a+s,c=n-a,u=e.r*o+i.r*l+t.r*h+r.r*c,d=e.g*o+i.g*l+t.g*h+r.g*c,_=e.b*o+i.b*l+t.b*h+r.b*c;return new math_color_Color3(u,d,_)}static Hermite1stDerivative(e,t,i,r,s){let a=math_color_Color3.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let n=s*s;a.r=(n-s)*6*e.r+(3*n-4*s+1)*t.r+(-n+s)*6*i.r+(3*n-2*s)*r.r,a.g=(n-s)*6*e.g+(3*n-4*s+1)*t.g+(-n+s)*6*i.g+(3*n-2*s)*r.g,a.b=(n-s)*6*e.b+(3*n-4*s+1)*t.b+(-n+s)*6*i.b+(3*n-2*s)*r.b}static Red(){return new math_color_Color3(1,0,0)}static Green(){return new math_color_Color3(0,1,0)}static Blue(){return new math_color_Color3(0,0,1)}static Black(){return new math_color_Color3(0,0,0)}static get BlackReadOnly(){return math_color_Color3._BlackReadOnly}static White(){return new math_color_Color3(1,1,1)}static Purple(){return new math_color_Color3(.5,0,.5)}static Magenta(){return new math_color_Color3(1,0,1)}static Yellow(){return new math_color_Color3(1,1,0)}static Gray(){return new math_color_Color3(.5,.5,.5)}static Teal(){return new math_color_Color3(0,1,1)}static Random(){return new math_color_Color3(Math.random(),Math.random(),Math.random())}};math_color_Color3._BlackReadOnly=math_color_Color3.Black();let math_color_Color4=class math_color_Color4{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}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 math_color_Color4.FromArrayToRef(e,t,this),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 math_color_Color4(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new math_color_Color4(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,this}scale(e){return new math_color_Color4(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=math_scalar_Scalar.Clamp(this.r,e,t),i.g=math_scalar_Scalar.Clamp(this.g,e,t),i.b=math_scalar_Scalar.Clamp(this.b,e,t),i.a=math_scalar_Scalar.Clamp(this.a,e,t),this}multiply(e){return new math_color_Color4(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}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 397*(e=397*(e=397*e^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)}clone(){return new math_color_Color4(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}toHexString(e=!1){let t=Math.round(255*this.r),i=Math.round(255*this.g),r=Math.round(255*this.b);if(e)return"#"+math_scalar_Scalar.ToHex(t)+math_scalar_Scalar.ToHex(i)+math_scalar_Scalar.ToHex(r);let s=Math.round(255*this.a);return"#"+math_scalar_Scalar.ToHex(t)+math_scalar_Scalar.ToHex(i)+math_scalar_Scalar.ToHex(r)+math_scalar_Scalar.ToHex(s)}toLinearSpace(e=!1){let t=new math_color_Color4;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=colorChannelToLinearSpaceExact(this.r),e.g=colorChannelToLinearSpaceExact(this.g),e.b=colorChannelToLinearSpaceExact(this.b)):(e.r=colorChannelToLinearSpace(this.r),e.g=colorChannelToLinearSpace(this.g),e.b=colorChannelToLinearSpace(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new math_color_Color4;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=colorChannelToGammaSpaceExact(this.r),e.g=colorChannelToGammaSpaceExact(this.g),e.b=colorChannelToGammaSpaceExact(this.b)):(e.r=colorChannelToGammaSpace(this.r),e.g=colorChannelToGammaSpace(this.g),e.b=colorChannelToGammaSpace(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new math_color_Color4(0,0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return math_color_Color4.FromInts(t,i,r,s)}static Lerp(e,t,i){let r=new math_color_Color4(0,0,0,0);return math_color_Color4.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,r,s){let a=s*s,n=s*a,o=2*n-3*a+1,l=-2*n+3*a,h=n-2*a+s,c=n-a,u=e.r*o+i.r*l+t.r*h+r.r*c,d=e.g*o+i.g*l+t.g*h+r.g*c,_=e.b*o+i.b*l+t.b*h+r.b*c,p=e.a*o+i.a*l+t.a*h+r.a*c;return new math_color_Color4(u,d,_,p)}static Hermite1stDerivative(e,t,i,r,s){let a=new math_color_Color4;return this.Hermite1stDerivativeToRef(e,t,i,r,s,a),a}static Hermite1stDerivativeToRef(e,t,i,r,s,a){let n=s*s;a.r=(n-s)*6*e.r+(3*n-4*s+1)*t.r+(-n+s)*6*i.r+(3*n-2*s)*r.r,a.g=(n-s)*6*e.g+(3*n-4*s+1)*t.g+(-n+s)*6*i.g+(3*n-2*s)*r.g,a.b=(n-s)*6*e.b+(3*n-4*s+1)*t.b+(-n+s)*6*i.b+(3*n-2*s)*r.b,a.a=(n-s)*6*e.a+(3*n-4*s+1)*t.a+(-n+s)*6*i.a+(3*n-2*s)*r.a}static FromColor3(e,t=1){return new math_color_Color4(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new math_color_Color4(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new math_color_Color4(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){let t=[];for(let i=0;inew math_color_Color4(0,0,0,0)),h["BABYLON.Color3"]=math_color_Color3,h["BABYLON.Color4"]=math_color_Color4;let Action=class Action{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new observable_Observable,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){let e=this._condition;if(!e)return!0;let t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){let t=this._evaluateConditionForCurrentFrame();t&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){}_serialize(e,t){let i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){let e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}};Action._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof math_vector_Vector2?e.x+", "+e.y:e instanceof math_vector_Vector3?e.x+", "+e.y+", "+e.z:e instanceof math_color_Color3?e.r+", "+e.g+", "+e.b:e instanceof math_color_Color4?e.r+", "+e.g+", "+e.b+", "+e.a:e,Action._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),h["BABYLON.Action"]=Action;let ActionEvent=class ActionEvent{constructor(e,t,i,r,s,a){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=a}static CreateNew(e,t,i){let r=e.getScene();return new ActionEvent(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new ActionEvent(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new ActionEvent(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new ActionEvent(e,t.x,t.y,null,i,r)}};let Condition=class Condition{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}};let ValueCondition=class ValueCondition extends Condition{static get IsEqual(){return ValueCondition._IsEqual}static get IsDifferent(){return ValueCondition._IsDifferent}static get IsGreater(){return ValueCondition._IsGreater}static get IsLesser(){return ValueCondition._IsLesser}constructor(e,t,i,r,s=ValueCondition.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case ValueCondition.IsGreater:return this._effectiveTarget[this._property]>this.value;case ValueCondition.IsLesser:return this._effectiveTarget[this._property]e<10?"0"+e:""+e,t=new Date;return"["+padStr(t.getHours())+":"+padStr(t.getMinutes())+":"+padStr(t.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){if(void 0!==i&&!logger_Logger._CheckLimit(t,i))return;let r=logger_Logger._FormatMessage(t),s=this._Levels[e];s.logFunc&&s.logFunc("BJS - "+r);let a=`
${r}

`;logger_Logger._AddLogEntry(a),logger_Logger._GenerateLimitMessage(t,e)}static get LogCache(){return logger_Logger._LogCache}static ClearLogCache(){logger_Logger._LogCache="",logger_Logger._LogLimitOutputs={},logger_Logger.errorsCount=0}static set LogLevels(e){logger_Logger.Log=logger_Logger._LogDisabled,logger_Logger.Warn=logger_Logger._LogDisabled,logger_Logger.Error=logger_Logger._LogDisabled,[logger_Logger.MessageLogLevel,logger_Logger.WarningLogLevel,logger_Logger.ErrorLogLevel].forEach(t=>{if((e&t)===t){let e=this._Levels[t];logger_Logger[e.name]=logger_Logger._LogEnabled.bind(logger_Logger,t)}})}};logger_Logger.NoneLogLevel=0,logger_Logger.MessageLogLevel=1,logger_Logger.WarningLogLevel=2,logger_Logger.ErrorLogLevel=4,logger_Logger.AllLogLevel=7,logger_Logger.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",logger_Logger._LogCache="",logger_Logger._LogLimitOutputs={},logger_Logger._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],logger_Logger.errorsCount=0,logger_Logger.Log=logger_Logger._LogEnabled.bind(logger_Logger,logger_Logger.MessageLogLevel),logger_Logger.Warn=logger_Logger._LogEnabled.bind(logger_Logger,logger_Logger.WarningLogLevel),logger_Logger.Error=logger_Logger._LogEnabled.bind(logger_Logger,logger_Logger.ErrorLogLevel);let SwitchBooleanAction=class SwitchBooleanAction extends Action{constructor(e,t,i,r){super(e,r),this.propertyPath=i,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=!this._effectiveTarget[this._property]}serialize(e){return super._serialize({name:"SwitchBooleanAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath}]},e)}};let SetStateAction=class SetStateAction extends Action{constructor(e,t,i,r){super(e,r),this.value=i,this._target=t}execute(){this._target.state=this.value}serialize(e){return super._serialize({name:"SetStateAction",properties:[Action._GetTargetProperty(this._target),{name:"value",value:this.value}]},e)}};let SetValueAction=class SetValueAction extends Action{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){this._effectiveTarget[this._property]=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"SetValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)}]},e)}};let IncrementValueAction=class IncrementValueAction extends Action{constructor(e,t,i,r,s){super(e,s),this.propertyPath=i,this.value=r,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath),"number"!=typeof this._effectiveTarget[this._property]&&logger_Logger.Warn("Warning: IncrementValueAction can only be used with number values")}execute(){this._effectiveTarget[this._property]+=this.value,this._target.markAsDirty&&this._target.markAsDirty(this._property)}serialize(e){return super._serialize({name:"IncrementValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)}]},e)}};let PlayAnimationAction=class PlayAnimationAction extends Action{constructor(e,t,i,r,s,a){super(e,a),this.from=i,this.to=r,this.loop=s,this._target=t}_prepare(){}execute(){let e=this._actionManager.getScene();e.beginAnimation(this._target,this.from,this.to,this.loop)}serialize(e){return super._serialize({name:"PlayAnimationAction",properties:[Action._GetTargetProperty(this._target),{name:"from",value:String(this.from)},{name:"to",value:String(this.to)},{name:"loop",value:Action._SerializeValueAsString(this.loop)||!1}]},e)}};let StopAnimationAction=class StopAnimationAction extends Action{constructor(e,t,i){super(e,i),this._target=t}_prepare(){}execute(){let e=this._actionManager.getScene();e.stopAnimation(this._target)}serialize(e){return super._serialize({name:"StopAnimationAction",properties:[Action._GetTargetProperty(this._target)]},e)}};let DoNothingAction=class DoNothingAction extends Action{constructor(e=0,t){super(e,t)}execute(){}serialize(e){return super._serialize({name:"DoNothingAction",properties:[]},e)}};let CombineAction=class CombineAction extends Action{constructor(e,t,i,r=!0){super(e,i),this.children=t,this.enableChildrenConditions=r}_prepare(){for(let e=0;e!e||e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&("SubMesh"===e.getClassName()||"PhysicsBody"===e.getClassName())?e.clone(t):e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?Object.assign({},e):null;function GetAllPropertyNames(e){let t=[];do Object.getOwnPropertyNames(e).forEach(function(e){-1===t.indexOf(e)&&t.push(e)});while(e=Object.getPrototypeOf(e));return t}let DeepCopier=class DeepCopier{static DeepCopy(e,t,i,r,s=!1){let a=GetAllPropertyNames(e);for(let n of a){if("_"===n[0]&&(!r||-1===r.indexOf(n))||n.endsWith("Observable")||i&&-1!==i.indexOf(n))continue;let a=e[n],o=typeof a;if("function"!==o)try{if("object"===o){if(a instanceof Uint8Array)t[n]=Uint8Array.from(a);else if(a instanceof Array){if(t[n]=[],a.length>0){if("object"==typeof a[0])for(let e=0;e-1&&this._scene.actionManagers.splice(e,1);let t=this._scene.meshes.filter(e=>e.actionManager===this);for(let e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=ActionManager.OnPickTrigger&&t.trigger<=ActionManager.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=ActionManager.OnPickTrigger&&t.trigger<=ActionManager.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===ActionManager.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(logger_Logger.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,ActionManager.Triggers[e.trigger]?ActionManager.Triggers[e.trigger]++:ActionManager.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){let t=this.actions.indexOf(e);return -1!==t&&(this.actions.splice(t,1),ActionManager.Triggers[e.trigger]-=1,0===ActionManager.Triggers[e.trigger]&&delete ActionManager.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{let i=h["BABYLON."+e];return i&&new i(...t)},parseParameter=(e,t,i,r)=>{if(null===r){let e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}let s=r.split("."),a=t.split(",");for(let e=0;e{if(e.detached)return;let o=[],l=null,h=null,c=e.combine&&e.combine.length>0;if(2===e.type?o.push(r):o.push(t),c){let t=[];for(let i=0;i0){let e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:ActionManager[s.name],parameter:t}}else r=ActionManager[s.name];for(let e=0;e(e=e.slice(1,e.length-1),AndOrNotEvaluator._HandleParenthesisContent(e,t))):AndOrNotEvaluator._HandleParenthesisContent(e,t))||"false"!==e&&AndOrNotEvaluator.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);let r=e.split("||");for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e)){let s=AndOrNotEvaluator._SimplifyNegation(r[e].trim()),a=s.split("&&");if(a.length>1)for(let e=0;e(e=e.replace(/[\s]/g,()=>"")).length%2?"!":"")).trim())?e="false":"!false"===e&&(e="true"),e}};let Tags=class Tags{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>Tags.HasTags(e),e.addTags=t=>Tags.AddTagsTo(e,t),e.removeTags=t=>Tags.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Tags.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;let t=e._tags;for(let 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)return e._tags;{let t=[];for(let i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}}static AddTagsTo(e,t){if(!t||"string"!=typeof t)return;let i=t.split(" ");i.forEach(function(t){Tags._AddTagTo(e,t)})}static _AddTagTo(e,t){""===(t=t.trim())||"true"===t||"false"===t||t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Tags.EnableFor(e),e._tags[t]=!0)}static RemoveTagsFrom(e,t){if(!Tags.HasTags(e))return;let i=t.split(" ");for(let t in i)Tags._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Tags.HasTags(e):AndOrNotEvaluator.Eval(t,t=>Tags.HasTags(e)&&e._tags[t]))}};let u={};function _WarnImport(e,t=!1){if(!t||!u[e])return u[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}let d={},_={},_copySource=function(e,t,i,r={}){let s=e();Tags&&Tags.HasTags(t)&&Tags.AddTagsTo(s,Tags.GetTags(t,!0));let a=getMergedStore(s),n={};for(let e in a){let o=a[e],l=t[e],h=o.type;if(null!=l&&("uniqueId"!==e||decorators_SerializationHelper.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:s[e]=l;break;case 1:r.cloneTexturesOnlyOnce&&n[l.uniqueId]?s[e]=n[l.uniqueId]:(s[e]=i||l.isRenderTarget?l:l.clone(),n[l.uniqueId]=s[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:s[e]=i?l:l.clone()}}return s};function getDirectStore(e){let t=e.getClassName();return d[t]||(d[t]={}),d[t]}function getMergedStore(e){let t=e.getClassName();if(_[t])return _[t];_[t]={};let i=_[t],r=e,s=t;for(;s;){let e;let t=d[s];for(let e in t)i[e]=t[e];let a=!1;do{if(!(e=Object.getPrototypeOf(r)).getClassName){a=!0;break}if(e.getClassName()!==s)break;r=e}while(e);if(a)break;s=e.getClassName(),r=e}return i}function generateSerializableMember(e,t){return(i,r)=>{let s=getDirectStore(i);s[r]||(s[r]={type:e,sourceName:t})}}function generateExpandMember(e,t=null){return(i,r)=>{let s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]===t||(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}function expandToProperty(e,t=null){return generateExpandMember(e,t)}function serialize(e){return generateSerializableMember(0,e)}function serializeAsTexture(e){return generateSerializableMember(1,e)}function serializeAsColor3(e){return generateSerializableMember(2,e)}function serializeAsFresnelParameters(e){return generateSerializableMember(3,e)}function serializeAsVector3(e){return generateSerializableMember(5,e)}function serializeAsMeshReference(e){return generateSerializableMember(6,e)}function serializeAsColorCurves(e){return generateSerializableMember(7,e)}function serializeAsQuaternion(e){return generateSerializableMember(10,e)}function serializeAsCameraReference(e){return generateSerializableMember(11,e)}let decorators_SerializationHelper=class decorators_SerializationHelper{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{let a=s;if("undefined"!=typeof _native&&_native[t]){let e=_native[t];a=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=a,a(...i)}}decorators_SerializationHelper.AllowLoadingUniqueId=!1,decorators_SerializationHelper._ImageProcessingConfigurationParser=e=>{throw _WarnImport("ImageProcessingConfiguration")},decorators_SerializationHelper._FresnelParametersParser=e=>{throw _WarnImport("FresnelParameters")},decorators_SerializationHelper._ColorCurvesParser=e=>{throw _WarnImport("ColorCurves")},decorators_SerializationHelper._TextureParser=(e,t,i)=>{throw _WarnImport("Texture")},nativeOverride.filter=function(e){return(t,i,r)=>nativeOverride(t,i,r,e)},function(e){e[e.NONE=0]="NONE",e[e.STEP=1]="STEP"}(K||(K={}));let AnimationRange=class AnimationRange{constructor(e,t,i){this.name=e,this.from=t,this.to=i}clone(){return new AnimationRange(this.name,this.from,this.to)}};function __decorate(e,t,i,r){var s,a=arguments.length,n=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,i,r);else for(var o=e.length-1;o>=0;o--)(s=e[o])&&(n=(a<3?s(n):a>3?s(t,i,n):s(t,i))||n);return a>3&&n&&Object.defineProperty(t,i,n),n}Object.create,Object.create;let _InternalNodeDataInfo=class _InternalNodeDataInfo{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new observable_Observable,this._onClonedObservable=new observable_Observable}};let node_Node=class node_Node{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):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;let t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){let t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&((void 0===this._parentNode._children||null===this._parentNode._children)&&(this._parentNode._children=[]),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){let 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){this._isDirty=!1,this._nodeDataStorage=new _InternalNodeDataInfo,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new observable_Observable,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=math_vector_Matrix.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new observable_Observable,this._onDisposeObserver=null,this._behaviors=[],this.name=e,this.id=e,this._scene=t||engineStore_EngineStore.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){let i=this._behaviors.indexOf(e);return -1!==i||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){let 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(let 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={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,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._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):(!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,i){if(this._children)for(let r=0;r(!t||t(e))&&void 0!==e.cullingStrategy),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew node_Node(e,this.getScene()),this);if(t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i{throw _WarnImport("AnimationRange")},node_Node._NodeConstructors={},__decorate([serialize()],node_Node.prototype,"name",void 0),__decorate([serialize()],node_Node.prototype,"id",void 0),__decorate([serialize()],node_Node.prototype,"uniqueId",void 0),__decorate([serialize()],node_Node.prototype,"state",void 0),__decorate([serialize()],node_Node.prototype,"metadata",void 0);let Size=class Size{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){return 397*(0|this.width)^(0|this.height)}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 Size(this.width*e,this.height*t)}clone(){return new Size(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 Size(0,0)}add(e){let t=new Size(this.width+e.width,this.height+e.height);return t}subtract(e){let t=new Size(this.width-e.width,this.height-e.height);return t}static Lerp(e,t,i){let r=e.width+(t.width-e.width)*i,s=e.height+(t.height-e.height)*i;return new Size(r,s)}};function createXMLHttpRequest(){return"undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}let webRequest_WebRequest=class webRequest_WebRequest{constructor(){this._xhr=createXMLHttpRequest(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(webRequest_WebRequest.CustomRequestHeaders).length>0||webRequest_WebRequest.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(let e in webRequest_WebRequest.CustomRequestHeaders){let t=webRequest_WebRequest.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return webRequest_WebRequest.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,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){webRequest_WebRequest.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(let e of webRequest_WebRequest.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}return 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)}};webRequest_WebRequest.CustomRequestHeaders={},webRequest_WebRequest.CustomRequestModifiers=[],webRequest_WebRequest.SkipRequestModificationForBabylonCDN=!0;let p={key:0,repeatCount:0,loopMode:2};let animation_Animation=class animation_Animation{static _PrepareAnimation(e,t,i,r,s,a,n,o){let l;if(!isNaN(parseFloat(s))&&isFinite(s)?l=animation_Animation.ANIMATIONTYPE_FLOAT:s instanceof math_vector_Quaternion?l=animation_Animation.ANIMATIONTYPE_QUATERNION:s instanceof math_vector_Vector3?l=animation_Animation.ANIMATIONTYPE_VECTOR3:s instanceof math_vector_Vector2?l=animation_Animation.ANIMATIONTYPE_VECTOR2:s instanceof math_color_Color3?l=animation_Animation.ANIMATIONTYPE_COLOR3:s instanceof math_color_Color4?l=animation_Animation.ANIMATIONTYPE_COLOR4:s instanceof Size&&(l=animation_Animation.ANIMATIONTYPE_SIZE),void 0==l)return null;let h=new animation_Animation(e,t,i,l,n),c=[{frame:0,value:s},{frame:r,value:a}];return h.setKeys(c),void 0!==o&&h.setEasingFunction(o),h}static CreateAnimation(e,t,i,r){let s=new animation_Animation(e+"Animation",e,i,t,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);return s.setEasingFunction(r),s}static CreateAndStartAnimation(e,t,i,r,s,a,n,o,l,h,c){let u=animation_Animation._PrepareAnimation(e,i,r,s,a,n,o,l);return u&&(t.getScene&&(c=t.getScene()),c)?c.beginDirectAnimation(t,[u],0,s,1===u.loopMode,1,h):null}static CreateAndStartHierarchyAnimation(e,t,i,r,s,a,n,o,l,h,c){let u=animation_Animation._PrepareAnimation(e,r,s,a,n,o,l,h);if(!u)return null;let d=t.getScene();return d.beginDirectHierarchyAnimation(t,i,[u],0,a,1===u.loopMode,1,c)}static CreateMergeAndStartAnimation(e,t,i,r,s,a,n,o,l,h){let c=animation_Animation._PrepareAnimation(e,i,r,s,a,n,o,l);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,s,1===c.loopMode,1,h)):null}static MakeAnimationAdditive(e,t,i,r=!1,s){var a,n;let o;let l=e;if((o="object"==typeof t?t:{referenceFrame:null!=t?t:0,range:i,cloneOriginalAnimation:r,clonedAnimationName:s}).cloneOriginalAnimation&&((l=e.clone()).name=o.clonedAnimationName||l.name),!l._keys.length)return l;let h=o.referenceFrame&&o.referenceFrame>=0?o.referenceFrame:0,c=0,u=l._keys[0],d=l._keys.length-1,_=l._keys[d],f={referenceValue:u.value,referencePosition:math_vector_TmpVectors.Vector3[0],referenceQuaternion:math_vector_TmpVectors.Quaternion[0],referenceScaling:math_vector_TmpVectors.Vector3[1],keyPosition:math_vector_TmpVectors.Vector3[2],keyQuaternion:math_vector_TmpVectors.Quaternion[1],keyScaling:math_vector_TmpVectors.Vector3[3]},m=u.frame,g=_.frame;if(o.range){let e=l.getRange(o.range);e&&(m=e.from,g=e.to)}else m=null!==(a=o.fromFrame)&&void 0!==a?a:m,g=null!==(n=o.toFrame)&&void 0!==n?n:g;if(m!==u.frame&&(c=l.createKeyForFrame(m)),g!==_.frame&&(d=l.createKeyForFrame(g)),1===l._keys.length){let e=l._getKeyValue(l._keys[0]);f.referenceValue=e.clone?e.clone():e}else if(h<=u.frame){let e=l._getKeyValue(u.value);f.referenceValue=e.clone?e.clone():e}else if(h>=_.frame){let e=l._getKeyValue(_.value);f.referenceValue=e.clone?e.clone():e}else{p.key=0;let e=l._interpolate(h,p);f.referenceValue=e.clone?e.clone():e}l.dataType===animation_Animation.ANIMATIONTYPE_QUATERNION?f.referenceValue.normalize().conjugateInPlace():l.dataType===animation_Animation.ANIMATIONTYPE_MATRIX&&(f.referenceValue.decompose(f.referenceScaling,f.referenceQuaternion,f.referencePosition),f.referenceQuaternion.normalize().conjugateInPlace());let v=Number.MAX_VALUE,x=o.clipKeys?[]:null;for(let e=c;e<=d;e++){let t=l._keys[e];if(x&&(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},v===Number.MAX_VALUE&&(v=t.frame),t.frame-=v,x.push(t)),!e||l.dataType===animation_Animation.ANIMATIONTYPE_FLOAT||t.value!==u.value)switch(l.dataType){case animation_Animation.ANIMATIONTYPE_MATRIX:t.value.decompose(f.keyScaling,f.keyQuaternion,f.keyPosition),f.keyPosition.subtractInPlace(f.referencePosition),f.keyScaling.divideInPlace(f.referenceScaling),f.referenceQuaternion.multiplyToRef(f.keyQuaternion,f.keyQuaternion),math_vector_Matrix.ComposeToRef(f.keyScaling,f.keyQuaternion,f.keyPosition,t.value);break;case animation_Animation.ANIMATIONTYPE_QUATERNION:f.referenceValue.multiplyToRef(t.value,t.value);break;case animation_Animation.ANIMATIONTYPE_VECTOR2:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_COLOR3:case animation_Animation.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(f.referenceValue,t.value);break;case animation_Animation.ANIMATIONTYPE_SIZE:t.value.width-=f.referenceValue.width,t.value.height-=f.referenceValue.height;break;default:t.value-=f.referenceValue}}return x&&l.setKeys(x,!0),l}static TransitionTo(e,t,i,r,s,a,n,o=null){if(n<=0)return i[e]=t,o&&o(),null;let l=s*(n/1e3);a.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(a);let h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=o,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,a){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=a,this._easingFunction=null,this._runtimeAnimations=[],this._events=[],this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=void 0===s?animation_Animation.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=animation_Animation._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType]+", nKeys: "+(this._keys?this._keys.length:"none")+", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;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=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let r=this._keys,s=r.length,a=t.key;for(;a>=0&&e=r[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(r[0].value);if(a+1>s-1)return i?void 0:this._getKeyValue(r[s-1].value);let n=r[a],o=r[a+1];if(i&&(e===n.frame||e===o.frame))return;let l=this._getKeyValue(n.value),h=this._getKeyValue(o.value);if(n.interpolation===K.STEP)return o.frame>e?l:h;let c=void 0!==n.outTangent&&void 0!==o.inTangent,u=o.frame-n.frame,d=(e-n.frame)/u,_=this.getEasingFunction();switch(null!==_&&(d=_.ease(d)),this.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:{let e=c?this.floatInterpolateFunctionWithTangents(l,n.outTangent*u,h,o.inTangent*u,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case animation_Animation.ANIMATIONTYPE_QUATERNION:{let e=c?this.quaternionInterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:break;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case animation_Animation.ANIMATIONTYPE_VECTOR3:{let e=c?this.vector3InterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_VECTOR2:{let e=c?this.vector2InterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_SIZE:switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(l,h,d).add(t.offsetValue.scale(t.repeatCount))}break;case animation_Animation.ANIMATIONTYPE_COLOR3:{let e=c?this.color3InterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_COLOR4:{let e=c?this.color4InterpolateFunctionWithTangents(l,n.outTangent.scale(u),h,o.inTangent.scale(u),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:if(animation_Animation.AllowMatricesInterpolation)return this.matrixInterpolateFunction(l,h,d,t.workValue);return l;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return l}}return 0}matrixInterpolateFunction(e,t,i,r){return animation_Animation.AllowMatrixDecomposeForInterpolation?r?(math_vector_Matrix.DecomposeLerpToRef(e,t,i,r),r):math_vector_Matrix.DecomposeLerp(e,t,i):r?(math_vector_Matrix.LerpToRef(e,t,i,r),r):math_vector_Matrix.Lerp(e,t,i)}clone(){let e=new animation_Animation(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)for(let t in e._ranges={},this._ranges){let i=this._ranges[t];i&&(e._ranges[t]=i.clone())}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){p.key=0;let t=this._interpolate(e,p,!0);if(!t)return p.key===e?p.key:p.key+1;let i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(p.key+1,0,i),p.key+1}serialize(){let 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;let t=this.dataType;e.keys=[];let i=this.getKeys();for(let r=0;r=2&&(r=l.values[1]),l.values.length>=3&&(n=l.values[2]),l.values.length>=4&&(o=l.values[3]);break;case animation_Animation.ANIMATIONTYPE_QUATERNION:if(t=math_vector_Quaternion.FromArray(l.values),l.values.length>=8){let e=math_vector_Quaternion.FromArray(l.values.slice(4,8));e.equals(math_vector_Quaternion.Zero())||(r=e)}if(l.values.length>=12){let e=math_vector_Quaternion.FromArray(l.values.slice(8,12));e.equals(math_vector_Quaternion.Zero())||(n=e)}l.values.length>=13&&(o=l.values[12]);break;case animation_Animation.ANIMATIONTYPE_MATRIX:t=math_vector_Matrix.FromArray(l.values),l.values.length>=17&&(o=l.values[16]);break;case animation_Animation.ANIMATIONTYPE_COLOR3:t=math_color_Color3.FromArray(l.values),l.values[3]&&(r=math_color_Color3.FromArray(l.values[3])),l.values[4]&&(n=math_color_Color3.FromArray(l.values[4])),l.values[5]&&(o=l.values[5]);break;case animation_Animation.ANIMATIONTYPE_COLOR4:t=math_color_Color4.FromArray(l.values),l.values[4]&&(r=math_color_Color4.FromArray(l.values[4])),l.values[5]&&(n=math_color_Color4.FromArray(l.values[5])),l.values[6]&&(o=math_color_Color4.FromArray(l.values[6]));break;case animation_Animation.ANIMATIONTYPE_VECTOR3:default:t=math_vector_Vector3.FromArray(l.values),l.values[3]&&(r=math_vector_Vector3.FromArray(l.values[3])),l.values[4]&&(n=math_vector_Vector3.FromArray(l.values[4])),l.values[5]&&(o=l.values[5])}let h={};h.frame=l.frame,h.value=t,void 0!=r&&(h.inTangent=r),void 0!=n&&(h.outTangent=n),void 0!=o&&(h.interpolation=o),a.push(h)}if(r.setKeys(a),e.ranges)for(i=0;i{let s=new webRequest_WebRequest;s.addEventListener("readystatechange",()=>{if(4==s.readyState){if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){let e=[];for(let i of t)e.push(this.Parse(i));i(e)}else{let r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")}}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{let r=new webRequest_WebRequest;r.addEventListener("readystatechange",()=>{if(4==r.readyState){if(200==r.status){let i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){let r=JSON.parse(i.animations),s=[];for(let t of r.animations){let i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{let r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)}}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}};animation_Animation._UniqueIdGenerator=0,animation_Animation.AllowMatricesInterpolation=!1,animation_Animation.AllowMatrixDecomposeForInterpolation=!0,animation_Animation.SnippetUrl="https://snippet.babylonjs.com",animation_Animation.ANIMATIONTYPE_FLOAT=0,animation_Animation.ANIMATIONTYPE_VECTOR3=1,animation_Animation.ANIMATIONTYPE_QUATERNION=2,animation_Animation.ANIMATIONTYPE_MATRIX=3,animation_Animation.ANIMATIONTYPE_COLOR3=4,animation_Animation.ANIMATIONTYPE_COLOR4=7,animation_Animation.ANIMATIONTYPE_VECTOR2=5,animation_Animation.ANIMATIONTYPE_SIZE=6,animation_Animation.ANIMATIONLOOPMODE_RELATIVE=0,animation_Animation.ANIMATIONLOOPMODE_CYCLE=1,animation_Animation.ANIMATIONLOOPMODE_CONSTANT=2,animation_Animation.ANIMATIONLOOPMODE_YOYO=4,animation_Animation.CreateFromSnippetAsync=animation_Animation.ParseFromSnippetAsync,h["BABYLON.Animation"]=animation_Animation,node_Node._AnimationRangeFactory=(e,t,i)=>new AnimationRange(e,t,i);let InterpolateValueAction=class InterpolateValueAction extends Action{constructor(e,t,i,r,s=1e3,a,n,o){super(e,a),this.duration=1e3,this.onInterpolationDoneObservable=new observable_Observable,this.propertyPath=i,this.value=r,this.duration=s,this.stopOtherAnimations=n,this.onInterpolationDone=o,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){let e;let t=this._actionManager.getScene(),i=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=animation_Animation.ANIMATIONTYPE_FLOAT;else if(this.value instanceof math_color_Color3)e=animation_Animation.ANIMATIONTYPE_COLOR3;else if(this.value instanceof math_vector_Vector3)e=animation_Animation.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof math_vector_Matrix)e=animation_Animation.ANIMATIONTYPE_MATRIX;else if(this.value instanceof math_vector_Quaternion)e=animation_Animation.ANIMATIONTYPE_QUATERNION;else{logger_Logger.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}let r=new animation_Animation("InterpolateValueAction",this._property,100*(1e3/this.duration),e,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(i),this.stopOtherAnimations&&t.stopAnimation(this._effectiveTarget),t.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()})}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)},{name:"duration",value:Action._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Action._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}};h["BABYLON.InterpolateValueAction"]=InterpolateValueAction;let f=Object.freeze(new math_vector_Quaternion(0,0,0,0)),m=Object.freeze(math_vector_Vector3.Zero()),g=Object.freeze(math_vector_Vector2.Zero()),v=Object.freeze(Size.Zero()),x=Object.freeze(math_color_Color3.Black());let RuntimeAnimation=class RuntimeAnimation{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,i,r){if(this._events=[],this._currentFrame=0,this._originalValue=[],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._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===animation_Animation.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=math_vector_Matrix.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){let e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(let 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];let s=t.getEvents();s&&s.length>0&&s.forEach(e=>{this._events.push(e._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e[i[0]];for(let e=1;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);let i=this._events;if(i.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);let u=i-t,d=e*(l.framePerSecond*s)/1e3+this._absoluteFrameOffset,_=0;if(r&&this._animationState.loopMode===animation_Animation.ANIMATIONLOOPMODE_YOYO){let e=(d-t)/u;d=Math.abs(Math.sin(e*Math.PI))*u+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&d>=u)c=!1,_=l._getKeyValue(this._maxValue);else if(!r&&t>=i&&d<=u)c=!1,_=l._getKeyValue(this._minValue);else if(this._animationState.loopMode!==animation_Animation.ANIMATIONLOOPMODE_CYCLE){let e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=animation_Animation.ANIMATIONLOOPMODE_CYCLE;let r=l._interpolate(t,this._animationState),s=l._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),l.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-r;break;case animation_Animation.ANIMATIONTYPE_QUATERNION:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_VECTOR2:case animation_Animation.ANIMATIONTYPE_SIZE:case animation_Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(r)}this._highLimitsCache[e]=s}_=this._highLimitsCache[e],n=this._offsetsCache[e]}if(void 0===n)switch(l.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:n=0;break;case animation_Animation.ANIMATIONTYPE_QUATERNION:n=f;break;case animation_Animation.ANIMATIONTYPE_VECTOR3:n=m;break;case animation_Animation.ANIMATIONTYPE_VECTOR2:n=g;break;case animation_Animation.ANIMATIONTYPE_SIZE:n=v;break;case animation_Animation.ANIMATIONTYPE_COLOR3:n=x}if(this._host&&this._host.syncRoot){let e=this._host.syncRoot,i=(e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame);o=t+u*i}else o=d>0&&t>i||d<0&&t0&&this.currentFrame>o||s<0&&this.currentFrame0?0:l.getKeys().length-1}this._currentFrame=o,this._animationState.repeatCount=0===u?0:d/u>>0,this._animationState.highLimitValue=_,this._animationState.offsetValue=n;let b=l._interpolate(o,this._animationState);if(this.setValue(b,a),p.length){for(let e=0;e0&&o>=p[e].frame&&p[e].frame>=t||u<0&&o<=p[e].frame&&p[e].frame<=t){let t=p[e];t.isDone||(t.onlyOnce&&(p.splice(e,1),e--),t.isDone=!0,t.action(o))}}return c||(this._stopped=!0),c}};function IsWindowObjectExist(){return"undefined"!=typeof window}function IsNavigatorAvailable(){return"undefined"!=typeof navigator}function IsDocumentAvailable(){return"undefined"!=typeof document}function GetDOMTextContent(e){let t="",i=e.firstChild;for(;i;)3===i.nodeType&&(t+=i.textContent),i=i.nextSibling;return t}let precisionDate_PrecisionDate=class precisionDate_PrecisionDate{static get Now(){return IsWindowObjectExist()&&window.performance&&window.performance.now?window.performance.now():Date.now()}};let filesInputStore_FilesInputStore=class filesInputStore_FilesInputStore{};filesInputStore_FilesInputStore.FilesToLoad={};let RetryStrategy=class RetryStrategy{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}};let BaseError=class BaseError extends Error{};BaseError._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));let b={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};let RuntimeError=class RuntimeError extends BaseError{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",BaseError._setPrototypeOf(this,RuntimeError.prototype)}};let stringTools_EncodeArrayBufferToBase64=e=>{let t,i,r,s,a,n,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",c=0,u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c>2,a=(3&t)<<4|i>>4,n=(15&i)<<2|r>>6,o=63&r,isNaN(i)?n=o=64:isNaN(r)&&(o=64),h+=l.charAt(s)+l.charAt(a)+l.charAt(n)+l.charAt(o);return h},DecodeBase64ToString=e=>atob(e),stringTools_DecodeBase64ToBinary=e=>{let t=DecodeBase64ToString(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;e{h+=i.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}};let ShaderCodeCursor=class ShaderCodeCursor{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{let e=t.split(";");for(let t=0;t{""!==(a=a.trim())&&(i.push(a),a="")},push=e=>{rShaderDefineExpression._Stack[r],pop=()=>-1===r?"!!INVALID EXPRESSION!!":ShaderDefineExpression._Stack[r--],s=0,a="";for(;s1){for(pushOperand();-1!==r&&ShaderDefineExpression._OperatorPriority[peek()]>=ShaderDefineExpression._OperatorPriority[n];)i.push(pop());push(n),s++}else a+=t;s++}for(pushOperand();-1!==r;)"("===peek()?pop():i.push(pop());return ShaderDefineExpression._InfixToPostfixCache.size>=ShaderDefineExpression.InfixToPostfixCacheLimitSize&&ShaderDefineExpression.ClearCache(),ShaderDefineExpression._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((e,t)=>e[1].accessTime-t[1].accessTime);for(let t=0;t":i=r>s;break;case"<":i=r=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}};!function(e){e[e.GLSL=0]="GLSL",e[e.WGSL=1]="WGSL"}(q||(q={}));let T=/defined\s*?\((.+?)\)/g,S=/defined\s*?\[(.+?)\]/g,C=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,E=/__decl__/,y=/light\{X\}.(\w*)/g,R=/\{X\}/g,P=[];let ShaderProcessor=class ShaderProcessor{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,r){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));let s=this._ProcessShaderConversion(e,t,r);i(s,e)})}static PreProcess(e,t,i,r){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));let s=this._ApplyPreProcessing(e,t,r);i(s,e)})}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;let r=t.shouldUseHighPrecisionShader;return -1===e.indexOf("precision highp float")?e=r?"precision highp float;\n"+e:"precision mediump float;\n"+e:r||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){let t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new ShaderDefineIsDefinedOperator(t[1].trim(),"!"===e[0]);let i="",r=0;for(i of["==","!=",">=","<=","<",">"])if((r=e.indexOf(i))>-1)break;if(-1===r)return new ShaderDefineIsDefinedOperator(e);let s=e.substring(0,r).trim(),a=e.substring(r+i.length).trim();return new ShaderDefineArithmeticOperator(s,i,a)}static _BuildSubExpression(e){e=e.replace(T,"defined[$1]");let t=ShaderDefineExpression.infixToPostfix(e),i=[];for(let e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;let s="&&"==e?new ShaderDefineAndOperator:new ShaderDefineOrOperator;"string"==typeof t&&(t=t.replace(S,"defined($1)")),"string"==typeof r&&(r=r.replace(S,"defined($1)")),s.leftOperand="string"==typeof r?this._ExtractOperation(r):r,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(S,"defined($1)")),"string"==typeof r?this._ExtractOperation(r):r}static _BuildExpression(e,t){let i=new ShaderCodeTestNode,r=e.substring(0,t),s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),"#ifdef"===r?i.testExpression=new ShaderDefineIsDefinedOperator(s):"#ifndef"===r?i.testExpression=new ShaderDefineIsDefinedOperator(s,!0):i.testExpression=this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let r=e.currentLine;for(;this._MoveCursor(e,i);){r=e.currentLine;let s=r.substring(0,5).toLowerCase();if("#else"===s){let i=new ShaderCodeNode;t.children.push(i),this._MoveCursor(e,i);return}if("#elif"===s){let e=this._BuildExpression(r,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;let i=e.currentLine;if(i.indexOf("#")>=0){let r=ShaderProcessor._MoveCursorRegex.exec(i);if(r&&r.length){let s=r[0];switch(s){case"#ifdef":{let r=new ShaderCodeConditionNode;t.children.push(r);let s=this._BuildExpression(i,6);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let r=new ShaderCodeConditionNode;t.children.push(r);let s=this._BuildExpression(i,7);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#if":{let r=new ShaderCodeConditionNode,s=this._BuildExpression(i,3);t.children.push(r),r.children.push(s),this._MoveCursorWithinIf(e,r,s)}}continue}}let r=new ShaderCodeNode;if(r.line=i,t.children.push(r),"#"===i[0]&&"d"===i[1]){let e=i.replace(";","").split(" ");r.additionalDefineKey=e[1],3===e.length&&(r.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){let r=new ShaderCodeNode,s=new ShaderCodeCursor;return s.lineIndex=-1,s.lines=e.split("\n"),this._MoveCursor(s,r),r.process(t,i)}static _PreparePreProcessors(e,t){var i;let r=e.defines,s={};for(let e of r){let t=e.replace("#define","").replace(";","").trim(),i=t.split(" ");s[i[0]]=i.length>1?i[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===q.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let r=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===q.GLSL&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;let s=t.defines,a=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,s,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ApplyPreProcessing(e,t,i){var r,s;let a=e,n=t.defines,o=this._PreparePreProcessors(t,i);return(null===(r=t.processor)||void 0===r?void 0:r.preProcessor)&&(a=t.processor.preProcessor(a,n,t.isFragment,t.processingContext)),a=this._EvaluatePreProcessors(a,o,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(a=t.processor.postProcessor(a,n,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(a=i.inlineShaderCode(a)),a}static _ProcessIncludes(e,t,i){let r;for(P.length=0;null!==(r=C.exec(e));)P.push(r);let s=String(e),a=[e],n=!1;for(let e of P){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(E,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),t.includesShadersStore[r]){let i=t.includesShadersStore[r];if(e[2]){let t=e[3].split(",");for(let e=0;et+"{X}")),i+=n.replace(R,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(y,(e,t)=>t+"{X}")),i=i.replace(R,r)}let s=[];for(let t of a){let r=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}else{let e=t.shadersRepository+"ShadersInclude/"+r+".fx";ShaderProcessor._FileToolsLoadFile(e,e=>{t.includesShadersStore[r]=e,this._ProcessIncludes(a.join(""),t,i)});return}}P.length=0,s=a.join(""),n?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,r,s,a){throw _WarnImport("FileTools")}};ShaderProcessor._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;let ShaderStore=class ShaderStore{static GetShadersRepository(e=q.GLSL){return e===q.GLSL?ShaderStore.ShadersRepository:ShaderStore.ShadersRepositoryWGSL}static GetShadersStore(e=q.GLSL){return e===q.GLSL?ShaderStore.ShadersStore:ShaderStore.ShadersStoreWGSL}static GetIncludesShadersStore(e=q.GLSL){return e===q.GLSL?ShaderStore.IncludesShadersStore:ShaderStore.IncludesShadersStoreWGSL}};ShaderStore.ShadersRepository="src/Shaders/",ShaderStore.ShadersStore={},ShaderStore.IncludesShadersStore={},ShaderStore.ShadersRepositoryWGSL="src/ShadersWGSL/",ShaderStore.ShadersStoreWGSL={},ShaderStore.IncludesShadersStoreWGSL={};let effect_Effect=class effect_Effect{static get ShadersRepository(){return ShaderStore.ShadersRepository}static set ShadersRepository(e){ShaderStore.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new observable_Observable),this._onBindObservable}constructor(e,t,i,r=null,s,a=null,n=null,o=null,l=null,h,c="",u=q.GLSL){var d,_,p;if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new observable_Observable,this.onErrorObservable=new observable_Observable,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!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,t.attributes){if(this._engine=i,this._attributesNames=t.attributes,this._uniformsNames=t.uniformsNames.concat(t.samplers),this._samplerList=t.samplers.slice(),this.defines=t.defines,this.onError=t.onError,this.onCompiled=t.onCompiled,this._fallbacks=t.fallbacks,this._indexParameters=t.indexParameters,this._transformFeedbackVaryings=t.transformFeedbackVaryings||null,this._multiTarget=!!t.multiTarget,this._shaderLanguage=null!==(d=t.shaderLanguage)&&void 0!==d?d:q.GLSL,t.uniformBuffersNames){this._uniformBuffersNamesList=t.uniformBuffersNames.slice();for(let e=0;e{if(o[0]&&o[1]){n.isFragment=!0;let[e,i]=o;ShaderProcessor.Process(i,n,(i,r)=>{this._fragmentSourceCodeBeforeMigration=r,this._processFinalCode&&(i=this._processFinalCode("fragment",i));let a=ShaderProcessor.Finalize(e,i,n);n=null,this._useFinalCode(a.vertexCode,a.fragmentCode,s,t)},this._engine)}};this._loadShader(i,"Vertex","",e=>{ShaderProcessor.Initialize(n),ShaderProcessor.Process(e,n,(t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,this._processFinalCode&&(t=this._processFinalCode("vertex",t)),o[0]=t,shadersLoaded()},this._engine)}),this._loadShader(r,"Fragment","Pixel",e=>{this._rawFragmentSourceCode=e,o[1]=e,shadersLoaded()})}_useFinalCode(e,t,i,r=!1){if(i){let r=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===q.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===q.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(r)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){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){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=GetDOMTextContent(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}let a=ShaderStore.GetShadersStore(this._shaderLanguage);if(a[e+t+"Shader"]){r(a[e+t+"Shader"]);return}if(i&&a[e+i+"Shader"]){r(a[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:ShaderStore.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{let e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,r);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?a._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,rebuildRebind,null,this._transformFeedbackVaryings,this._key):a._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,rebuildRebind,r,this._transformFeedbackVaryings,this._key),a._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,i,this._attributes),i)for(let e=0;e=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${a[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,r,s;this._compilationError=e.message;let a=this._attributesNames,n=this._fallbacks;if(logger_Logger.Error("Unable to compile effect:"),logger_Logger.Error("Uniforms: "+this._uniformsNames.map(function(e){return" "+e})),logger_Logger.Error("Attributes: "+a.map(function(e){return" "+e})),logger_Logger.Error("Defines:\n"+this.defines),effect_Effect.LogShaderCodeOnCompilationError){let e=null,t=null,a=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([a,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),a&&(logger_Logger.Error("Vertex code:"),logger_Logger.Error(a))),(null===(r=this._pipelineContext)||void 0===r?void 0:r._getFragmentShaderCode())&&([a,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),a&&(logger_Logger.Error("Fragment code:"),logger_Logger.Error(a))),e&&logger_Logger.Error(e),t&&logger_Logger.Error(t)}logger_Logger.Error("Error: "+this._compilationError);let notifyErrors=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,notifyErrors()),n?(this._pipelineContext=null,n.hasMoreFallbacks?(this._allFallbacksProcessed=!1,logger_Logger.Error("Trying next fallback."),this.defines=n.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,notifyErrors(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||notifyErrors())}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)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){let i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){let r=this._samplerList.indexOf(e);for(let e=1;e{t._swapAndDie(this,!1),this.isReady=e.isReady};e.isAsync?e.proxy.then(swapAndSetIsReady):swapAndSetIsReady(e.proxy);return}switch(this.source){case $.Temp:break;case $.Url:t=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e: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);return;case $.Raw:(t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,void 0,this._useSRGBBuffer))._swapAndDie(this,!1),this.isReady=!0;break;case $.Raw3D:(t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case $.Raw2DArray:(t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case $.Dynamic:(t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case $.Cube:t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case $.CubeRaw:(t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this,!1),this.isReady=!0;break;case $.CubeRawRGBD:return;case $.CubePrefiltered:(t=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,e=>{e&&e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension))._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var i;null===(i=this._hardwareTexture)||void 0===i||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),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);let r=this._engine.getLoadedTexturesCache(),s=r.indexOf(this);-1!==s&&r.splice(s,1),-1===(s=r.indexOf(e))&&r.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}};internalTexture_InternalTexture._Counter=0;let WebGLShaderProcessor=class WebGLShaderProcessor{constructor(){this.shaderLanguage=q.GLSL}postProcessor(e,t,i,r,s){return s.getCaps().drawBuffersExtension||(e=e.replace(/#extension.+GL_EXT_draw_buffers.+(enable|require)/g,"")),e}};let A=/(flat\s)?\s*varying\s*.*/;let WebGL2ShaderProcessor=class WebGL2ShaderProcessor{constructor(){this.shaderLanguage=q.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return A.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){let r=-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("),i){let 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,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else{let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}return e}};let dataBuffer_DataBuffer=class dataBuffer_DataBuffer{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=dataBuffer_DataBuffer._Counter++}};dataBuffer_DataBuffer._Counter=0;let WebGLDataBuffer=class WebGLDataBuffer extends dataBuffer_DataBuffer{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}};let WebGLPipelineContext=class WebGLPipelineContext{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)}_fillEffectInformation(e,t,i,r,s,a,n,o){let l;let h=this.engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let c=this.engine.getUniforms(this,i);for(c.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l{a[e]=t}),h.getAttributes(this,n)))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a||4!==a.length)return a=[t,i,r,s],this._valueCache[e]=a,!0;let n=!1;return a[0]!==t&&(a[0]=t,n=!0),a[1]!==i&&(a[1]=i,n=!0),a[2]!==r&&(a[2]=r,n=!0),a[3]!==s&&(a[3]=s,n=!0),n}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setInt4(this._uniforms[e],t,i,r,s)&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setUInt4(this._uniforms[e],t,i,r,s)&&(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.toArray())&&(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){let i=this._valueCache[e];(void 0===i||i!==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,i){this._cacheFloat2(e,t,i)&&!this.engine.setFloat2(this._uniforms[e],t,i)&&(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,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setFloat3(this._uniforms[e],t,i,r)&&(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,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setFloat4(this._uniforms[e],t,i,r,s)&&(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(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}};let WebGLHardwareTexture=class WebGLHardwareTexture{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw 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(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return null!==(i=null===(t=this._MSAARenderBuffers)||void 0===t?void 0:t[e])&&void 0!==i?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}};let drawWrapper_DrawWrapper=class drawWrapper_DrawWrapper{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(r=this.drawContext)||void 0===r||r.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}};let StencilStateComposer=class StencilStateComposer{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(){var e;this.stencilMaterial=void 0,null===(e=this.stencilGlobal)||void 0===e||e.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){var t;if(!e)return;let i=!this.useStencilGlobalOnly&&!!(null===(t=this.stencilMaterial)||void 0===t?void 0:t.enabled);this.enabled=i?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=i?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=i?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=i?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=i?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=i?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=i?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=i?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))}};let BufferPointer=class BufferPointer{};let ThinEngine=class ThinEngine{static get NpmPackage(){return"babylonjs@6.28.1"}static get Version(){return"6.28.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return effect_Effect.ShadersRepository}static set ShadersRepository(e){effect_Effect.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);let i=document.createElement("canvas");return i.width=e,i.height=t,i}createCanvas(e,t){return ThinEngine._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,i,r){var s,a,n,o,l,h,c,u,d,_,p;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new observable_Observable,this._frameId=0,this._uniformBuffers=[],this._storageBuffers=[],this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.onContextLostObservable=new observable_Observable,this.onContextRestoredObservable=new observable_Observable,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new DepthCullingState,this._stencilStateComposer=new StencilStateComposer,this._stencilState=new StencilState,this._alphaState=new AlphaState,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=[],this._renderTargetWrapperCache=[],this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=[],this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=[],this._currentInstanceLocations=[],this._currentInstanceBuffers=[],this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=[],this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=[],this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new observable_Observable,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=precisionDate_PrecisionDate.Now;let f=null;i=i||{},this._creationOptions=i,this.adaptToDeviceRatio=null!=r&&r,this._stencilStateComposer.stencilGlobal=this._stencilState,performanceConfigurator_PerformanceConfigurator.SetMatrixPrecision(!!i.useHighPrecisionMatrix),i.antialias=null!=t?t:i.antialias,i.deterministicLockstep=null!==(s=i.deterministicLockstep)&&void 0!==s&&s,i.lockstepMaxSteps=null!==(a=i.lockstepMaxSteps)&&void 0!==a?a:4,i.timeStep=null!==(n=i.timeStep)&&void 0!==n?n:1/60,i.audioEngine=null===(o=i.audioEngine)||void 0===o||o,i.stencil=null===(l=i.stencil)||void 0===l||l,this._audioContext=null!==(c=null===(h=i.audioEngineOptions)||void 0===h?void 0:h.audioContext)&&void 0!==c?c:null,this._audioDestination=null!==(d=null===(u=i.audioEngineOptions)||void 0===u?void 0:u.audioDestination)&&void 0!==d?d:null,this.premultipliedAlpha=null===(_=i.premultipliedAlpha)||void 0===_||_,this.useExactSrgbConversions=null!==(p=i.useExactSrgbConversions)&&void 0!==p&&p,this._doNotHandleContextLost=!!i.doNotHandleContextLost,this._isStencilEnable=!!i.stencil,r=r||i.adaptToDeviceRatio||!1;let m=IsWindowObjectExist()&&window.devicePixelRatio||1,g=i.limitDeviceRatio||m;if(this._hardwareScalingLevel=r?1/Math.min(g,m):1,this._lastDevicePixelRatio=m,!e)return;if(e.getContext){if(f=e,this._renderingCanvas=f,void 0===i.preserveDrawingBuffer&&(i.preserveDrawingBuffer=!1),void 0===i.xrCompatible&&(i.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();let e=navigator.userAgent;for(let t of ThinEngine.ExceptionList){let r=t.key,s=t.targets,a=new RegExp(r);if(a.test(e)){if(t.capture&&t.captureConstraint){let i=t.capture,r=t.captureConstraint,s=new RegExp(i),a=s.exec(e);if(a&&a.length>0){let e=parseInt(a[a.length-1]);if(e>=r)continue}}for(let e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":i.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,logger_Logger.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},f.addEventListener("webglcontextlost",this._onContextLost,!1),f.addEventListener("webglcontextrestored",this._onContextRestored,!1),i.powerPreference=i.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(i.xrCompatible=!1),!i.disableWebGL2Support)try{this._gl=f.getContext("webgl2",i)||f.getContext("experimental-webgl2",i),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!f)throw Error("The provided canvas is null or undefined.");try{this._gl=f.getContext("webgl",i)||f.getContext("experimental-webgl",i)}catch(e){throw Error("WebGL not supported")}}if(!this._gl)throw 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";let t=this._gl.getContextAttributes();t&&(i.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==i.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=i.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new WebGL2ShaderProcessor:new WebGLShaderProcessor,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);let v=`Babylon.js v${ThinEngine.Version}`;console.log(v+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",v)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{let e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&IsDocumentAvailable()&&"ontouchend"in document},this._checkForMobile(),IsWindowObjectExist()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;let i=this._depthCullingState.depthTest,r=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,a=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=i,this._depthCullingState.depthFunc=r,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=a,logger_Logger.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){let e=this._internalTexturesCache.slice();for(let t of e)t._rebuild()}_rebuildRenderTargetWrappers(){let e=this._renderTargetWrapperCache.slice();for(let t of e)t._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}effect_Effect.ResetCache()}areAllEffectsReady(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];if(!t.isReady())return!1}return!0}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuild();for(let e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;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")),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._glVersion=this._gl.getParameter(this._gl.VERSION);let t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.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=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e: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{let 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{let 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{let 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{let 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){let 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{let 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{let 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=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,IsWindowObjectExist()){let{cancelAnimationFrame:e}=this.getHostWindow()||window;if("function"==typeof e)return e(this._frameHandler)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return IsWindowObjectExist()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}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}_queueNewFrame(e,t){return ThinEngine.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=()=>this._renderLoop(),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,i,r=!1){var s,a;let n=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=n;let o=0;if(t&&e){let t=!0;if(this._currentRenderTarget){let i=null===(s=this._currentRenderTarget.texture)||void 0===s?void 0:s.format;if(8===i||9===i||10===i||11===i){let i=null===(a=this._currentRenderTarget.texture)||void 0===a?void 0:a.type;7===i||5===i?(ThinEngine._TempClearColorUint32[0]=255*e.r,ThinEngine._TempClearColorUint32[1]=255*e.g,ThinEngine._TempClearColorUint32[2]=255*e.b,ThinEngine._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,ThinEngine._TempClearColorUint32)):(ThinEngine._TempClearColorInt32[0]=255*e.r,ThinEngine._TempClearColorInt32[1]=255*e.g,ThinEngine._TempClearColorInt32[2]=255*e.b,ThinEngine._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,ThinEngine._TempClearColorInt32)),t=!1}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),o|=this._gl.COLOR_BUFFER_BIT)}i&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),o|=this._gl.DEPTH_BUFFER_BIT),r&&(this._gl.clearStencil(0),o|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(o)}_viewport(e,t,i,r){(e!==this._viewportCached.x||t!==this._viewportCached.y||i!==this._viewportCached.z||r!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=i,this._viewportCached.w=r,this._gl.viewport(e,t,i,r))}setViewport(e,t,i){let r=t||this.getRenderWidth(),s=i||this.getRenderHeight(),a=e.x||0,n=e.y||0;this._cachedViewport=e,this._viewport(a*r,n*s,r*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,i;if(this.adaptToDeviceRatio){let e=IsWindowObjectExist()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(IsWindowObjectExist()&&IsDocumentAvailable()){if(this._renderingCanvas){let 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,i=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,i=window.innerHeight}else t=this._renderingCanvas?this._renderingCanvas.width:100,i=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,i/this._hardwareScalingLevel,e)}setSize(e,t,i=!1){return!!this._renderingCanvas&&(e|=0,t|=0,(!!i||this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)&&(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0))}bindFramebuffer(e,t=0,i,r,s,a=0,n=0){var o,l,h,c,u,d;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer);let _=this._gl;e.isMulti||(e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,null===(o=e.texture._hardwareTexture)||void 0===o?void 0:o.underlyingResource,a,n):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,a):e._currentLOD===a||(_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,null===(h=e.texture._hardwareTexture)||void 0===h?void 0:h.underlyingResource,a),e._currentLOD=a));let p=e._depthStencilTexture;if(p){let i=e._depthStencilTextureWithStencil?_.DEPTH_STENCIL_ATTACHMENT:_.DEPTH_ATTACHMENT;e.is2DArray?_.framebufferTextureLayer(_.FRAMEBUFFER,i,null===(c=p._hardwareTexture)||void 0===c?void 0:c.underlyingResource,a,n):e.isCube?_.framebufferTexture2D(_.FRAMEBUFFER,i,_.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(u=p._hardwareTexture)||void 0===u?void 0:u.underlyingResource,a):_.framebufferTexture2D(_.FRAMEBUFFER,i,_.TEXTURE_2D,null===(d=p._hardwareTexture)||void 0===d?void 0:d.underlyingResource,a)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,i,r):(!i&&(i=e.width,a&&(i/=Math.pow(2,a))),!r&&(r=e.height,a&&(r/=Math.pow(2,a))),this._viewport(0,0,i,r)),this.wipeCaches()}setState(e,t=0,i,r=!1,s,a,n=0){var o,l;(this._depthCullingState.cull!==e||i)&&(this._depthCullingState.cull=e);let h=null===(l=null!==(o=this.cullBackFaces)&&void 0!==o?o:s)||void 0===l||l?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||i)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(n);let c=r?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==c||i)&&(this._depthCullingState.frontFace=c),this._stencilStateComposer.stencilMaterial=a}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){let e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){let e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,i){var r;this._currentRenderTarget=null;let s=this._gl;if(e._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,i);return}s.bindFramebuffer(s.READ_FRAMEBUFFER,e._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,e._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}(null===(r=e.texture)||void 0===r?void 0:r.generateMipMaps)&&!t&&!e.isCube&&this.generateMipmaps(e.texture),i&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),i()),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,i){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create vertex buffer");let r=new WebGLDataBuffer(i);return this.bindArrayBuffer(r),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),this._resetVertexBufferBinding(),r.references=1,r}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,i){let r=this._gl.createBuffer(),s=new WebGLDataBuffer(r);if(!r)throw Error("Unable to create index buffer");this.bindIndexBuffer(s);let a=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,a,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),s.references=1,s.is32Bits=4===a.BYTES_PER_ELEMENT,s}_normalizeIndexData(e){let t=e.BYTES_PER_ELEMENT;if(2===t)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t=65535)return new Uint32Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);this._gl.uniformBlockBinding(r,s,i)}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,i,r,s,a,n){let o=this._currentBufferPointers[t];if(!o)return;let l=!1;o.active?(o.buffer!==e&&(o.buffer=e,l=!0),o.size!==i&&(o.size=i,l=!0),o.type!==r&&(o.type=r,l=!0),o.normalized!==s&&(o.normalized=s,l=!0),o.stride!==a&&(o.stride=a,l=!0),o.offset!==n&&(o.offset=n,l=!0)):(l=!0,o.active=!0,o.index=t,o.size=i,o.type=r,o.normalized=s,o.stride=a,o.offset=n,o.buffer=e),(l||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),r===this._gl.UNSIGNED_INT||r===this._gl.INT?this._gl.vertexAttribIPointer(t,i,r,a,n):this._gl.vertexAttribPointer(t,i,r,s,a,n))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,i){let r=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){let t=r[s],n=null;if(i&&(n=i[t]),n||(n=e[t]),!n)continue;this._gl.enableVertexAttribArray(a),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[a]=!0);let o=n.getBuffer();o&&(this._vertexAttribPointer(o,a,n.getSize(),n.type,n.normalized,n.byteStride,n.byteOffset),n.getIsInstanced()&&(this._gl.vertexAttribDivisor(a,n.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(a),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,i,r){let s=this._gl.createVertexArray();if(!s)throw Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,i,r),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}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,i,r,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let a=0;for(let n=0;n=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,i[n],this._gl.FLOAT,!1,r,a)),a+=4*i[n]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,i,r){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==i)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=i,this._bindVertexBuffersAttributes(e,i,r)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,i=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",o=this._compileShader(t,"vertex",r,n),l=this._compileShader(i,"fragment",r,n);return this._createShaderProgram(e,o,l,s,a)}inlineShaderCode(e){return e}createPipelineContext(e){let t=new WebGLPipelineContext;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,i,r,s=null){let a=r.createProgram();if(e.program=a,!a)throw Error("Unable to create program");return r.attachShader(a,t),r.attachShader(a,i),r.linkProgram(a),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_finalizePipelineContext(e){let t=e.context,i=e.vertexShader,r=e.fragmentShader,s=e.program,a=t.getProgramParameter(s,t.LINK_STATUS);if(!a){if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(i);if(t)throw e.vertexCompilationError=t,Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(r,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(r);if(t)throw e.fragmentCompilationError=t,Error("FRAGMENT SHADER "+t)}let a=t.getProgramInfoLog(s);if(a)throw e.programLinkError=a,Error(a)}if(this.validateShaderPrograms){t.validateProgram(s);let i=t.getProgramParameter(s,t.VALIDATE_STATUS);if(!i){let i=t.getProgramInfoLog(s);if(i)throw e.programValidationError=i,Error(i)}}t.deleteShader(i),t.deleteShader(r),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,i,r,s,a,n,o,l,h){r?e.program=this.createRawShaderProgram(e,t,i,void 0,l):e.program=this.createShaderProgram(e,t,i,o,void 0,l),e.program.__SPECTOR_rebuildProgram=n}_isRenderingStateCompiled(e){return!this._isDisposed&&!e._isDisposed&&!!this._gl.getProgramParameter(e.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(e),!0)}_executeWhenRenderingStateIsCompiled(e,t){if(!e.isParallelCompiled){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}getUniforms(e,t){let i=[];for(let r=0;r1||this.isWebGPU)),(1!==o||this._caps.textureFloatLinearFiltering)&&(2!==o||this._caps.textureHalfFloatLinearFiltering)||(l=1),1!==o||this._caps.textureFloat||(o=0,logger_Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let d=this._gl,_=new internalTexture_InternalTexture(this,r),p=e.width||e,f=e.height||e,m=e.layers||0,g=this._getSamplingParameters(l,n),v=0!==m?d.TEXTURE_2D_ARRAY:d.TEXTURE_2D,x=this._getRGBABufferInternalSizedFormat(o,h,c),b=this._getInternalFormat(h),T=this._getWebGLTextureType(o);return this._bindTextureDirectly(v,_),0!==m?(_.is2DArray=!0,d.texImage3D(v,0,x,p,f,m,0,b,T,null)):d.texImage2D(v,0,x,p,f,0,b,T,null),d.texParameteri(v,d.TEXTURE_MAG_FILTER,g.mag),d.texParameteri(v,d.TEXTURE_MIN_FILTER,g.min),d.texParameteri(v,d.TEXTURE_WRAP_S,d.CLAMP_TO_EDGE),d.texParameteri(v,d.TEXTURE_WRAP_T,d.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(v),this._bindTextureDirectly(v,null),_._useSRGBBuffer=c,_.baseWidth=p,_.baseHeight=f,_.width=p,_.height=f,_.depth=m,_.isReady=!0,_.samples=u,_.generateMipMaps=n,_.samplingMode=l,_.type=o,_.format=h,_.label=a,this._internalTexturesCache.push(_),_}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,i,r,s=3,a=null,n=null,o,l,h=null,c=null,u=null,d=null,_,p,f){e=e||"";let m="data:"===e.substr(0,5),g="blob:"===e.substr(0,5),v=m&&-1!==e.indexOf(";base64,"),x=c||new internalTexture_InternalTexture(this,$.Url);x!==c&&(x.label=e.substring(0,60));let b=e;!this._transformTextureUrl||v||c||h||(e=this._transformTextureUrl(e)),b!==e&&(x._originalUrl=b);let T=e.lastIndexOf("."),S=d||(T>-1?e.substring(T).toLowerCase():""),C=null,E=S.indexOf("?");for(let e of(E>-1&&(S=S.split("?")[0]),ThinEngine._TextureLoaders))if(e.canLoad(S,_)){C=e;break}r&&r.addPendingData(x),x.url=e,x.generateMipMaps=!t,x.samplingMode=s,x.invertY=i,x._useSRGBBuffer=this._getUseSRGBBuffer(!!f,t),this._doNotHandleContextLost||(x._buffer=h);let y=null;a&&!c&&(y=x.onLoadedObservable.add(a)),c||this._internalTexturesCache.push(x);let onInternalError=(i,c)=>{r&&r.removePendingData(x),e===b?(y&&x.onLoadedObservable.remove(y),engineStore_EngineStore.UseFallbackTexture&&this._createTextureBase(engineStore_EngineStore.FallbackTexture,t,x.invertY,r,s,null,n,o,l,h,x),i=(i||"Unknown error")+(engineStore_EngineStore.UseFallbackTexture?" - Fallback texture was used":""),x.onErrorObservable.notifyObservers({message:i,exception:c}),n&&n(i,c)):(logger_Logger.Warn(`Failed to load ${e}, falling back to ${b}`),this._createTextureBase(b,t,x.invertY,r,s,a,n,o,l,h,x,u,d,_,p,f))};if(C){let callback=e=>{C.loadData(e,x,(e,t,i,a,n,l)=>{l?onInternalError("TextureLoader failed to load data"):o(x,S,r,{width:e,height:t},x.invertY,!i,a,()=>(n(),!1),s)},p)};h?h instanceof ArrayBuffer?callback(new Uint8Array(h)):ArrayBuffer.isView(h)?callback(h):n&&n("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,e=>callback(new Uint8Array(e)),void 0,r?r.offlineProvider:void 0,!0,(e,t)=>{onInternalError("Unable to load "+(e&&e.responseURL,t))})}else{let onload=e=>{g&&!this._doNotHandleContextLost&&(x._buffer=e),o(x,S,r,e,x.invertY,t,!1,l,s)};!m||v?h&&("string"==typeof h.decoding||h.close)?onload(h):ThinEngine._FileToolsLoadImage(e,onload,onInternalError,r?r.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof h||h instanceof ArrayBuffer||ArrayBuffer.isView(h)||h instanceof Blob?ThinEngine._FileToolsLoadImage(h,onload,onInternalError,r?r.offlineProvider:null,_,x.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):h&&onload(h)}return x}createTexture(e,t,i,r,s=3,a=null,n=null,o=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,r,s,a,n,this._prepareWebGLTexture.bind(this),(e,t,i,s,a,n)=>{let o=this._gl,l=i.width===e&&i.height===t,c=this._getTexImageParametersForCreateTexture(h,s,a._useSRGBBuffer);if(l)return o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),!1;let u=this._caps.maxTextureSize;if(i.width>u||i.height>u||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!!this._workingCanvas&&!!this._workingContext&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(i,0,0,i.width,i.height,0,0,e,t),o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,this._workingCanvas),a.width=e,a.height=t,!1);{let e=new internalTexture_InternalTexture(this,$.Temp);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,c.internalFormat,c.format,c.type,i),this._rescaleTexture(e,a,r,c.format,()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,a,!0),n()})}return!0},o,l,h,c,u,d,p)}_getTexImageParametersForCreateTexture(e,t,i){let r,s;return null==e&&(e=".jpg"!==t||i?5:4),1===this.webGLVersion?s=r=this._getInternalFormat(e,i):(r=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,i)),{internalFormat:s,format:r,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,i,r,s,a){throw _WarnImport("FileTools")}_rescaleTexture(e,t,i,r,s){}createRawTexture(e,t,i,r,s,a,n,o=null,l=0,h=0,c=!1){throw _WarnImport("Engine.RawTexture")}createRawCubeTexture(e,t,i,r,s,a,n,o=null){throw _WarnImport("Engine.RawTexture")}createRawTexture3D(e,t,i,r,s,a,n,o,l=null,h=0){throw _WarnImport("Engine.RawTexture")}createRawTexture2DArray(e,t,i,r,s,a,n,o,l=null,h=0){throw _WarnImport("Engine.RawTexture")}_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,i=!1){let r=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||i);this._setTextureParameterInteger(r,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(r,this._gl.TEXTURE_MIN_FILTER,s.min),i&&(t.generateMipMaps=!0,this._gl.generateMipmap(r)),this._bindTextureDirectly(r,null),t.samplingMode=e}updateTextureDimensions(e,t,i,r=1){}updateTextureWrappingMode(e,t,i=null,r=null){let s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(i),e),e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(r),e),e._cachedWrapR=r),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,i,r,s,a=1){let n=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=n,e.baseHeight=o,e.width=n,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=a,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=0,e._comparisonFunction=s;let h=this._gl,c=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(c,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(c,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(c,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(c,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(c,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(c,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,n=0){let o=this._gl,l=o.TEXTURE_2D;if(e.isCube&&(l=o.TEXTURE_CUBE_MAP_POSITIVE_X+a),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(l,n,t,i,r,0,s)}_uploadDataToTextureDirectly(e,t,i=0,r=0,s,a=!1){let n=this._gl,o=this._getWebGLTextureType(e.type),l=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=n.TEXTURE_2D;e.isCube&&(c=n.TEXTURE_CUBE_MAP_POSITIVE_X+i);let u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=a?e.width:Math.pow(2,Math.max(u-r,0)),p=a?e.height:Math.pow(2,Math.max(d-r,0));n.texImage2D(c,r,h,_,p,0,l,o,t)}updateTextureData(e,t,i,r,s,a,n=0,o=0,l=!1){let h=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,_=h.TEXTURE_2D;e.isCube&&(_=h.TEXTURE_CUBE_MAP_POSITIVE_X+n,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(_,o,i,r,s,a,u,c,t),l&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){let s=this._gl,a=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(a,e,!0),this._uploadDataToTextureDirectly(e,t,i,r),this._bindTextureDirectly(a,null,!0)}_prepareWebGLTextureContinuation(e,t,i,r,s){let a=this._gl;if(!a)return;let n=this._getSamplingParameters(s,!i);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,n.mag),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,n.min),i||r||a.generateMipmap(a.TEXTURE_2D),this._bindTextureDirectly(a.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,i,r,s,a,n,o,l=3){let h=this.getCaps().maxTextureSize,c=Math.min(h,this.needPOTTextures?ThinEngine.GetExponentOfTwo(r.width,h):r.width),u=Math.min(h,this.needPOTTextures?ThinEngine.GetExponentOfTwo(r.height,h):r.height),d=this._gl;if(d){if(!e._hardwareTexture){i&&i.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=r.width,e.baseHeight=r.height,e.width=c,e.height=u,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:".jpg"!==t||e._useSRGBBuffer?5:4,o(c,u,r,t,e,()=>{this._prepareWebGLTextureContinuation(e,i,a,n,l)})||this._prepareWebGLTextureContinuation(e,i,a,n,l)}}_setupFramebufferDepthAttachments(e,t,i,r,s=1){let a=this._gl;if(e&&t)return this._createRenderBuffer(i,r,s,a.DEPTH_STENCIL,a.DEPTH24_STENCIL8,a.DEPTH_STENCIL_ATTACHMENT);if(t){let e=a.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=a.DEPTH_COMPONENT32F),this._createRenderBuffer(i,r,s,e,e,a.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(i,r,s,a.STENCIL_INDEX8,a.STENCIL_INDEX8,a.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,i,r,s,a,n=!0){let o=this._gl,l=o.createRenderbuffer();return this._updateRenderBuffer(l,e,t,i,r,s,a,n)}_updateRenderBuffer(e,t,i,r,s,a,n,o=!0){let l=this._gl;return l.bindRenderbuffer(l.RENDERBUFFER,e),r>1&&l.renderbufferStorageMultisample?l.renderbufferStorageMultisample(l.RENDERBUFFER,r,a,t,i):l.renderbufferStorage(l.RENDERBUFFER,s,t,i),l.framebufferRenderbuffer(l.FRAMEBUFFER,n,l.RENDERBUFFER,e),o&&l.bindRenderbuffer(l.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();let i=this._internalTexturesCache.indexOf(e);-1!==i&&this._internalTexturesCache.splice(i,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){let t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let i=e.getSamplers();for(let t=0;t-1;i&&o&&(this._activeChannel=t._associatedChannel);let l=this._boundTexturesCache[this._activeChannel];if(l!==t||r){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(a=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==a?a:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else i&&(n=!0,this._activateCurrentTexture());return o&&!i&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),n}_bindTexture(e,t,i){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;let r=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(r,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,i))}_bindSamplerUniformToChannel(e,t){let i=this._boundUniforms[e];i&&i._currentState!==t&&(this._gl.uniform1i(i,t),i._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:break;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,i=!1,r=!1,s=""){let a;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;let i=t.getInternalTexture();i&&(i._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;a=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!i&&a&&(a._associatedChannel=e);let n=!0;this._boundTexturesCache[e]===a&&(i||this._bindSamplerUniformToChannel(a._associatedChannel,e),n=!1),this._activeChannel=e;let o=this._getTextureTarget(a);if(n&&this._bindTextureDirectly(o,a,i),a&&!a.isMultiview){if(a.isCube&&a._cachedCoordinatesMode!==t.coordinatesMode){a._cachedCoordinatesMode=t.coordinatesMode;let e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}a._cachedWrapU!==t.wrapU&&(a._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),a)),a._cachedWrapV!==t.wrapV&&(a._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),a)),a.is3D&&a._cachedWrapR!==t.wrapR&&(a._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),a)),this._setAnisotropicLevel(o,a,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,i,r){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===i.length||(this._textureUnits=new Int32Array(i.length));for(let t=0;t=this._caps.maxVertexAttribs)&&this._vertexAttribArraysEnabled[e]&&this.disableAttributeByIndex(e)}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e,t;for(let t of(this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},IsWindowObjectExist()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,effect_Effect.ResetCache(),this._activeRequests))t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&(null===(t=this._gl.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext())}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(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let i=!0,r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),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);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);let a=t.checkFramebufferStatus(t.FRAMEBUFFER);if((i=(i=i&&a===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),i=i&&t.getError()===t.NO_ERROR),i){t.bindFramebuffer(t.FRAMEBUFFER,null);let e=t.RGBA,r=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,r,s),i=i&&t.getError()===t.NO_ERROR}for(t.deleteTexture(r),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!i&&t.getError()!==t.NO_ERROR;);return i}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:break;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:break;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:i=this._gl.ALPHA;break;case 1:i=this._gl.LUMINANCE;break;case 2:i=this._gl.LUMINANCE_ALPHA;break;case 6:i=this._gl.RED;break;case 7:i=this._gl.RG;break;case 4:i=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:i=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:i=this._gl.RED_INTEGER;break;case 9:i=this._gl.RG_INTEGER;break;case 10:i=this._gl.RGB_INTEGER;break;case 11:i=this._gl.RGBA_INTEGER}return i}_getRGBABufferInternalSizedFormat(e,t,i=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return i?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return i?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return i?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:if(6===t)return this._gl.R32F;return this._gl.RGBA32F;case 2:if(6===t)return this._gl.R16F;return this._gl.RGBA16F}return this._gl.RGBA8}_loadFile(e,t,i,r,s,a){let n=ThinEngine._FileToolsLoadFile(e,t,i,r,s,a);return this._activeRequests.push(n),n.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),n}static _FileToolsLoadFile(e,t,i,r,s,a){throw _WarnImport("FileTools")}readPixels(e,t,i,r,s=!0,a=!0){let n=s?this._gl.RGBA:this._gl.RGB,o=new Uint8Array(r*i*(s?4:3));return a&&this.flushFramebuffer(),this._gl.readPixels(e,t,i,r,n,this._gl.UNSIGNED_BYTE,o),Promise.resolve(o)}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{let e=this._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{let e=this._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}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){let t=ThinEngine.CeilingPOT(e),i=ThinEngine.FloorPOT(e);return t-e>e-i?i:t}static GetExponentOfTwo(e,t,i=2){let r;switch(i){case 1:r=ThinEngine.FloorPOT(e);break;case 2:r=ThinEngine.NearestPOT(e);break;default:r=ThinEngine.CeilingPOT(e)}return Math.min(r,t)}static QueueNewFrame(e,t){if(IsWindowObjectExist()){let{requestAnimationFrame:i}=t||window;if("function"==typeof i)return i(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:IsDocumentAvailable()?document:null}};ThinEngine._TempClearColorUint32=new Uint32Array(4),ThinEngine._TempClearColorInt32=new Int32Array(4),ThinEngine.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:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],ThinEngine._TextureLoaders=[],ThinEngine.CollisionsEpsilon=.001,ThinEngine._IsSupported=null,ThinEngine._HasMajorPerformanceCaveat=null;let TimingTools=class TimingTools{static SetImmediate(e){IsWindowObjectExist()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}};let M=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);let LoadFileError=class LoadFileError extends RuntimeError{constructor(e,t){super(e,b.LoadFileError),this.name="LoadFileError",BaseError._setPrototypeOf(this,LoadFileError.prototype),t instanceof webRequest_WebRequest?this.request=t:this.file=t}};let RequestFileError=class RequestFileError extends RuntimeError{constructor(e,t){super(e,b.RequestFileError),this.request=t,this.name="RequestFileError",BaseError._setPrototypeOf(this,RequestFileError.prototype)}};let ReadFileError=class ReadFileError extends RuntimeError{constructor(e,t){super(e,b.ReadFileError),this.file=t,this.name="ReadFileError",BaseError._setPrototypeOf(this,ReadFileError.prototype)}};let I={DefaultRetryStrategy:RetryStrategy.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e},_CleanUrl=e=>e=e.replace(/#/gm,"%23"),SetCorsBehavior=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&I.CorsBehavior){if("string"==typeof I.CorsBehavior||I.CorsBehavior instanceof String)t.crossOrigin=I.CorsBehavior;else{let i=I.CorsBehavior(e);i&&(t.crossOrigin=i)}}},LoadImage=(e,t,i,r,s="",a)=>{var n;let o;let l=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(o=URL.createObjectURL(new Blob([e],{type:s})),l=!0):o=`data:${s};base64,`+stringTools_EncodeArrayBufferToBase64(e):e instanceof Blob?(o=URL.createObjectURL(e),l=!0):(o=_CleanUrl(e),o=I.PreprocessUrl(e));let h=engineStore_EngineStore.LastCreatedEngine,onErrorHandler=t=>{if(i){let r=o||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(n=null==h?void 0:h._features.forceBitmapOverHTMLImageElement)&&void 0!==n&&n)return LoadFile(o,r=>{h.createImageBitmap(new Blob([r],{type:s}),Object.assign({premultiplyAlpha:"none"},a)).then(e=>{t(e),l&&URL.revokeObjectURL(o)}).catch(t=>{i&&i("Error while trying to load image: "+e,t)})},void 0,r||void 0,!0,(e,t)=>{onErrorHandler(t)}),null;let c=new Image;SetCorsBehavior(o,c);let u=[],unloadHandlersList=()=>{u.forEach(e=>{e.target.removeEventListener(e.name,e.handler)}),u.length=0};u.push({target:c,name:"load",handler:()=>{unloadHandlersList(),t(c),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{unloadHandlersList(),onErrorHandler(e),l&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src)return;unloadHandlersList();let t=Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);engineStore_EngineStore.UseFallbackTexture=!1,onErrorHandler(t),l&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach(e=>{e.target.addEventListener(e.name,e.handler)});let d="blob:"===o.substring(0,5),_="data:"===o.substring(0,5),noOfflineSupport=()=>{d||_||!webRequest_WebRequest.IsCustomRequestAvailable?c.src=o:LoadFile(o,(e,t,i)=>{let r=!s&&i?i:s,a=new Blob([e],{type:r}),n=URL.createObjectURL(a);l=!0,c.src=n},void 0,r||void 0,!0,(e,t)=>{onErrorHandler(t)})};if(!d&&!_&&r&&r.enableTexturesOffline)r.open(()=>{r&&r.loadImage(o,c)},noOfflineSupport);else{if(-1!==o.indexOf("file:")){let e=decodeURIComponent(o.substring(5).toLowerCase());if(filesInputStore_FilesInputStore.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(filesInputStore_FilesInputStore.FilesToLoad[e])}catch(i){t=URL.createObjectURL(filesInputStore_FilesInputStore.FilesToLoad[e])}c.src=t,l=!0}catch(e){c.src=""}return c}}noOfflineSupport()}return c},ReadFile=(e,t,i,r,s)=>{let a=new FileReader,n={onCompleteObservable:new observable_Observable,abort:()=>a.abort()};return a.onloadend=()=>n.onCompleteObservable.notifyObservers(n),s&&(a.onerror=()=>{s(new ReadFileError(`Unable to read ${e.name}`,e))}),a.onload=e=>{t(e.target.result)},i&&(a.onprogress=i),r?a.readAsArrayBuffer(e):a.readAsText(e),n},LoadFile=(e,t,i,r,s,a,n)=>{if(e.name)return ReadFile(e,t,i,s,a?e=>{a(void 0,e)}:void 0);if(-1!==e.indexOf("file:")){let r=decodeURIComponent(e.substring(5).toLowerCase());0===r.indexOf("./")&&(r=r.substring(2));let n=filesInputStore_FilesInputStore.FilesToLoad[r];if(n)return ReadFile(n,t,i,s,a?e=>a(void 0,new LoadFileError(e.message,e.file)):void 0)}let{match:o,type:l}=TestBase64DataUrl(e);if(o){let i={onCompleteObservable:new observable_Observable,abort:()=>()=>{}};try{let i=s?DecodeBase64UrlToBinary(e):DecodeBase64UrlToString(e);t(i,void 0,l)}catch(e){a?a(void 0,e):logger_Logger.Error(e.message||"Failed to parse the Data URL")}return TimingTools.SetImmediate(()=>{i.onCompleteObservable.notifyObservers(i)}),i}return RequestFile(e,(e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))},i,r,s,a?e=>{a(e.request,new LoadFileError(e.message,e.request))}:void 0,n)},RequestFile=(e,t,i,r,s,a,n)=>{e=_CleanUrl(e),e=I.PreprocessUrl(e);let o=I.BaseUrl+e,l=!1,h={onCompleteObservable:new observable_Observable,abort:()=>l=!0},requestFile=()=>{let e,r=new webRequest_WebRequest,c=null,unbindEvents=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",onLoadEnd))},onLoadEnd=()=>{unbindEvents(),h.onCompleteObservable.notifyObservers(h),h.onCompleteObservable.clear(),i=void 0,e=null,onLoadEnd=null,a=void 0,n=void 0,t=void 0};h.abort=()=>{l=!0,onLoadEnd&&onLoadEnd(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==c&&(clearTimeout(c),c=null),r=null};let handleError=e=>{let t=e.message||"Unknown error";a&&r?a(new RequestFileError(t,r)):logger_Logger.Error(t)},retryLoop=h=>{if(r){if(r.open("GET",o),n)try{n(r)}catch(e){handleError(e);return}s&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),onLoadEnd&&r.addEventListener("loadend",onLoadEnd),e=()=>{if(!l&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!IsWindowObjectExist()||IsFileURL())){try{t&&t(s?r.response:r.responseText,r)}catch(e){handleError(e)}return}let i=I.DefaultRetryStrategy;if(i){let e=i(o,r,h);if(-1!==e){unbindEvents(),r=new webRequest_WebRequest,c=setTimeout(()=>retryLoop(h+1),e);return}}let n=new RequestFileError("Error status: "+r.status+" "+r.statusText+" - Unable to load "+o,r);a&&a(n)}},r.addEventListener("readystatechange",e),r.send()}};retryLoop(0)};if(r&&r.enableSceneOffline){let noOfflineSupport=e=>{e&&e.status>400?a&&a(e):requestFile()};r.open(()=>{r&&r.loadFile(I.BaseUrl+e,e=>{!l&&t&&t(e),h.onCompleteObservable.notifyObservers(h)},i?e=>{!l&&i&&i(e)}:void 0,noOfflineSupport,s)},noOfflineSupport)}else requestFile();return h},IsFileURL=()=>"undefined"!=typeof location&&"file:"===location.protocol,IsBase64DataUrl=e=>M.test(e),TestBase64DataUrl=e=>{let t=M.exec(e);if(null===t||0===t.length)return{match:!1,type:""};{let e=t[0].replace("data:","").replace("base64,","");return{match:!0,type:e}}};function DecodeBase64UrlToBinary(e){return stringTools_DecodeBase64ToBinary(e.split(",")[1])}let DecodeBase64UrlToString=e=>DecodeBase64ToString(e.split(",")[1]);ThinEngine._FileToolsLoadImage=LoadImage,ThinEngine._FileToolsLoadFile=LoadFile,ShaderProcessor._FileToolsLoadFile=LoadFile,((e,t,i,s,a,n,o,l,h,c)=>{Object.defineProperty(r={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:i.DefaultRetryStrategy,BaseUrl:i.BaseUrl,CorsBehavior:i.CorsBehavior,PreprocessUrl:i.PreprocessUrl,IsBase64DataUrl:s,IsFileURL:a,LoadFile:n,LoadImage:o,ReadFile:l,RequestFile:h,SetCorsBehavior:c},"DefaultRetryStrategy",{get:function(){return i.DefaultRetryStrategy},set:function(e){i.DefaultRetryStrategy=e}}),Object.defineProperty(r,"BaseUrl",{get:function(){return i.BaseUrl},set:function(e){i.BaseUrl=e}}),Object.defineProperty(r,"PreprocessUrl",{get:function(){return i.PreprocessUrl},set:function(e){i.PreprocessUrl=e}}),Object.defineProperty(r,"CorsBehavior",{get:function(){return i.CorsBehavior},set:function(e){i.CorsBehavior=e}})})(DecodeBase64UrlToBinary,DecodeBase64UrlToString,I,IsBase64DataUrl,IsFileURL,LoadFile,LoadImage,ReadFile,RequestFile,SetCorsBehavior);let InstantiationTools=class InstantiationTools{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=h[e];if(t)return t;logger_Logger.Warn(e+" not found, you may have missed an import.");let i=e.split("."),r=window||this;for(let e=0,t=i.length;e{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}InstantiationTools.RegisteredExternalClasses={};let tools_Tools=class tools_Tools{static get BaseUrl(){return I.BaseUrl}static set BaseUrl(e){I.BaseUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||!(-1===e.indexOf("://")||-1===e.indexOf(".")||-1===e.indexOf("/")||e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){LoadFile(e,e=>{i(e)},void 0,void 0,t,(e,t)=>{r(t)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(tools_Tools.ScriptBaseUrl&&e.startsWith(tools_Tools._DefaultCdnUrl)){let t="/"===tools_Tools.ScriptBaseUrl[tools_Tools.ScriptBaseUrl.length-1]?tools_Tools.ScriptBaseUrl.substring(0,tools_Tools.ScriptBaseUrl.length-1):tools_Tools.ScriptBaseUrl;e=e.replace(tools_Tools._DefaultCdnUrl,t)}return e=tools_Tools.ScriptPreprocessUrl(e),t&&(e=tools_Tools.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=tools_Tools.GetBabylonScriptURL(e),tools_Tools.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=tools_Tools.GetBabylonScriptURL(e),tools_Tools.LoadScriptAsync(e)}static LoadScript(e,t,i,r){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}if(!IsWindowObjectExist()){null==i||i(`Cannot load script '${e}' outside of a window or a worker`);return}let s=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},s.appendChild(a)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(e,t)=>{i(t||Error(e))})})}static ReadFileAsDataURL(e,t,i){let r=new FileReader,s={onCompleteObservable:new observable_Observable,abort:()=>r.abort()};return r.onloadend=()=>{s.onCompleteObservable.notifyObservers(s)},r.onload=e=>{t(e.target.result)},r.onprogress=i,r.readAsDataURL(e),s}static ReadFile(e,t,i,r,s){return ReadFile(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]),i=window.URL,r=i.createObjectURL(t);return r}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){DeepCopier.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{let r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,a=new Uint8Array(s);for(let e=0;et(e)):e.toBlob(function(e){t(e)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let e=new Date,i=(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2);t="screenshot_"+i+".png"}tools_Tools.Download(e,t)}else if(e&&"undefined"!=typeof URL){let t=URL.createObjectURL(e),i=window.open("");if(!i)return;let r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(tools_Tools._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(e=>{let i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{let e=i.result;t(e)}});return}let r=e.toDataURL(i,s);t(r)}}else this.ToBlob(e,function(e){e&&tools_Tools.DownloadBlob(e,r),t&&t("")},i,s)}static Download(e,t){if("undefined"==typeof URL)return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",a=!1,n){throw _WarnImport("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw _WarnImport("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",a=1,n=!1,o,l=!1,h=!1,c=!0,u){throw _WarnImport("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,a=!1,n,o=!1,l=!1,h=!0,c){throw _WarnImport("ScreenshotTools")}static RandomId(){return guid_RandomGUID()}static IsBase64(e){return IsBase64DataUrl(e)}static DecodeBase64(e){return DecodeBase64UrlToBinary(e)}static get errorsCount(){return logger_Logger.errorsCount}static Log(e){logger_Logger.Log(e)}static Warn(e){logger_Logger.Warn(e)}static Error(e){logger_Logger.Error(e)}static get LogCache(){return logger_Logger.LogCache}static ClearLogCache(){logger_Logger.ClearLogCache()}static set LogLevels(e){logger_Logger.LogLevels=e}static set PerformanceLogLevel(e){if((e&tools_Tools.PerformanceUserMarkLogLevel)===tools_Tools.PerformanceUserMarkLogLevel){tools_Tools.StartPerformanceCounter=tools_Tools._StartUserMark,tools_Tools.EndPerformanceCounter=tools_Tools._EndUserMark;return}if((e&tools_Tools.PerformanceConsoleLogLevel)===tools_Tools.PerformanceConsoleLogLevel){tools_Tools.StartPerformanceCounter=tools_Tools._StartPerformanceConsole,tools_Tools.EndPerformanceCounter=tools_Tools._EndPerformanceConsole;return}tools_Tools.StartPerformanceCounter=tools_Tools._StartPerformanceCounterDisabled,tools_Tools.EndPerformanceCounter=tools_Tools._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!tools_Tools._Performance){if(!IsWindowObjectExist())return;tools_Tools._Performance=window.performance}t&&tools_Tools._Performance.mark&&tools_Tools._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&tools_Tools._Performance.mark&&(tools_Tools._Performance.mark(e+"-End"),tools_Tools._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(tools_Tools._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(tools_Tools._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return precisionDate_PrecisionDate.Now}static GetClassName(e,t=!1){let i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__}i||(i=typeof e)}return i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return!!IsNavigatorAvailable()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}};tools_Tools.UseCustomRequestHeaders=!1,tools_Tools.CustomRequestHeaders=webRequest_WebRequest.CustomRequestHeaders,tools_Tools.GetDOMTextContent=GetDOMTextContent,tools_Tools._DefaultCdnUrl="https://cdn.babylonjs.com",tools_Tools.GetAbsoluteUrl="object"==typeof document?e=>{let t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},tools_Tools.NoneLogLevel=logger_Logger.NoneLogLevel,tools_Tools.MessageLogLevel=logger_Logger.MessageLogLevel,tools_Tools.WarningLogLevel=logger_Logger.WarningLogLevel,tools_Tools.ErrorLogLevel=logger_Logger.ErrorLogLevel,tools_Tools.AllLogLevel=logger_Logger.AllLogLevel,tools_Tools.IsWindowObjectExist=IsWindowObjectExist,tools_Tools.PerformanceNoneLogLevel=0,tools_Tools.PerformanceUserMarkLogLevel=1,tools_Tools.PerformanceConsoleLogLevel=2,tools_Tools.StartPerformanceCounter=tools_Tools._StartPerformanceCounterDisabled,tools_Tools.EndPerformanceCounter=tools_Tools._EndPerformanceCounterDisabled;let AsyncLoop=class AsyncLoop{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?r.breakLoop():setTimeout(()=>{for(let a=0;a=e)break;if(i(n),s&&s()){r.breakLoop();break}}r.executeNext()},a)},r)}};engineStore_EngineStore.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";let SmartArray=class SmartArray{constructor(e){this.length=0,this.data=Array(e),this._id=SmartArray._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return -1!==this.indexOf(e)}};SmartArray._GlobalId=0;let SmartArrayNoDuplicate=class SmartArrayNoDuplicate extends SmartArray{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=(this.length+e.length)*2);for(let t=0;tthis.add(e,t))}get(e){let t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e))&&this.add(e,i),i}getOrAdd(e,t){let i=this.get(e);return void 0!==i?i:(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){let 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(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}};let MaterialDefines=class MaterialDefines{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(let 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(){for(let e of(this._keys.length=0,Object.keys(this)))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(let 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;tthis._setDefaultValue(e))}_setDefaultValue(e){var t,i,r,s,a;let n=null!==(r=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==r?r:typeof this[e],o=null===(a=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===a?void 0:a.default;switch(n){case"number":this[e]=null!=o?o:0;break;case"string":this[e]=null!=o?o:"";break;default:this[e]=null!=o&&o}}toString(){let e="";for(let t=0;tnew ColorCurves,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}static Parse(e){return decorators_SerializationHelper.Parse(()=>new ColorCurves,e,null,null)}};__decorate([serialize()],ColorCurves.prototype,"_globalHue",void 0),__decorate([serialize()],ColorCurves.prototype,"_globalDensity",void 0),__decorate([serialize()],ColorCurves.prototype,"_globalSaturation",void 0),__decorate([serialize()],ColorCurves.prototype,"_globalExposure",void 0),__decorate([serialize()],ColorCurves.prototype,"_highlightsHue",void 0),__decorate([serialize()],ColorCurves.prototype,"_highlightsDensity",void 0),__decorate([serialize()],ColorCurves.prototype,"_highlightsSaturation",void 0),__decorate([serialize()],ColorCurves.prototype,"_highlightsExposure",void 0),__decorate([serialize()],ColorCurves.prototype,"_midtonesHue",void 0),__decorate([serialize()],ColorCurves.prototype,"_midtonesDensity",void 0),__decorate([serialize()],ColorCurves.prototype,"_midtonesSaturation",void 0),__decorate([serialize()],ColorCurves.prototype,"_midtonesExposure",void 0),decorators_SerializationHelper._ColorCurvesParser=ColorCurves.Parse;let ImageProcessingConfigurationDefines=class ImageProcessingConfigurationDefines extends MaterialDefines{constructor(){super(),this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.EXPOSURE=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}};let ImageProcessingConfiguration=class ImageProcessingConfiguration{constructor(){this.colorCurves=new ColorCurves,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=ImageProcessingConfiguration.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new math_color_Color4(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new observable_Observable}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"}static PrepareUniforms(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&&ColorCurves.PrepareUniforms(e),t.DITHER&&e.push("ditherIntensity")}static PrepareSamplers(e,t){t.COLORGRADING&&e.push("txColorTransform")}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled){e.VIGNETTE=!1,e.TONEMAPPING=!1,e.TONEMAPPING_ACES=!1,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,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled;return}(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,e.TONEMAPPING=this.toneMappingEnabled,this._toneMappingType===ImageProcessingConfiguration.TONEMAPPING_ACES)?e.TONEMAPPING_ACES=!0:e.TONEMAPPING_ACES=!1,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&&ColorCurves.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){let i=1/e.getEngine().getRenderWidth(),r=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",i,r),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){let s=null!=t?t:r/i,a=Math.tan(.5*this.vignetteCameraFov),n=a*s,o=Math.sqrt(n*a);n=tools_Tools.Mix(n,o,this.vignetteStretch),a=tools_Tools.Mix(a,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",n,a,-n*this.vignetteCenterX,-a*this.vignetteCenterY);let l=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,l)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);let t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return decorators_SerializationHelper.Clone(()=>new ImageProcessingConfiguration,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}static Parse(e){let t=decorators_SerializationHelper.Parse(()=>new ImageProcessingConfiguration,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}};ImageProcessingConfiguration.TONEMAPPING_STANDARD=0,ImageProcessingConfiguration.TONEMAPPING_ACES=1,ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY=0,ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE=1,__decorate([serializeAsColorCurves()],ImageProcessingConfiguration.prototype,"colorCurves",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_colorCurvesEnabled",void 0),__decorate([serializeAsTexture("colorGradingTexture")],ImageProcessingConfiguration.prototype,"_colorGradingTexture",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_colorGradingEnabled",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_colorGradingWithGreenDepth",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_colorGradingBGR",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_exposure",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_toneMappingEnabled",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_toneMappingType",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_contrast",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteStretch",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteCenterX",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteCenterY",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteWeight",void 0),__decorate([generateSerializableMember(8,void 0)],ImageProcessingConfiguration.prototype,"vignetteColor",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"vignetteCameraFov",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_vignetteBlendMode",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_vignetteEnabled",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_ditheringEnabled",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_ditheringIntensity",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_skipFinalColorClamp",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_applyByPostProcess",void 0),__decorate([serialize()],ImageProcessingConfiguration.prototype,"_isEnabled",void 0),decorators_SerializationHelper._ImageProcessingConfigurationParser=ImageProcessingConfiguration.Parse,ThinEngine.prototype.createUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create uniform buffer");let r=new WebGLDataBuffer(i);return this.bindUniformBuffer(r),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),r.references=1,r},ThinEngine.prototype.createDynamicUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create dynamic uniform buffer");let r=new WebGLDataBuffer(i);return this.bindUniformBuffer(r),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),r.references=1,r},ThinEngine.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},ThinEngine.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},ThinEngine.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},ThinEngine.prototype.bindUniformBlock=function(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)};let UniformBuffer=class UniformBuffer{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=r?r:"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){let e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let i=this._uniformLocationPointer-e;for(let e=0;e0){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:i},16==t)t*=i;else{let e=4-t;t=t*i+e*i}r=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(UniformBuffer._UpdatedUbosInFrame[this._name]||(UniformBuffer._UpdatedUbosInFrame[this._name]=0),UniformBuffer._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let r=this._uniformLocations[e];if(void 0===r){if(this._buffer){logger_Logger.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),r=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;en[t]=e),n}if(!(e instanceof Array||e instanceof Float32Array)||0!==r||e.length!==h){if(e instanceof Array){let t=r/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,r,h);{let t=e.byteOffset+r;if(o){let i=new Float32Array(h),r=new Float32Array(e.buffer,t,h);return i.set(r),i}let i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return o?e.slice():e}};buffer_VertexBuffer._Counter=0,buffer_VertexBuffer.BYTE=5120,buffer_VertexBuffer.UNSIGNED_BYTE=5121,buffer_VertexBuffer.SHORT=5122,buffer_VertexBuffer.UNSIGNED_SHORT=5123,buffer_VertexBuffer.INT=5124,buffer_VertexBuffer.UNSIGNED_INT=5125,buffer_VertexBuffer.FLOAT=5126,buffer_VertexBuffer.PositionKind="position",buffer_VertexBuffer.NormalKind="normal",buffer_VertexBuffer.TangentKind="tangent",buffer_VertexBuffer.UVKind="uv",buffer_VertexBuffer.UV2Kind="uv2",buffer_VertexBuffer.UV3Kind="uv3",buffer_VertexBuffer.UV4Kind="uv4",buffer_VertexBuffer.UV5Kind="uv5",buffer_VertexBuffer.UV6Kind="uv6",buffer_VertexBuffer.ColorKind="color",buffer_VertexBuffer.ColorInstanceKind="instanceColor",buffer_VertexBuffer.MatricesIndicesKind="matricesIndices",buffer_VertexBuffer.MatricesWeightsKind="matricesWeights",buffer_VertexBuffer.MatricesIndicesExtraKind="matricesIndicesExtra",buffer_VertexBuffer.MatricesWeightsExtraKind="matricesWeightsExtra";let PickingInfo=class PickingInfo{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){let i;if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(buffer_VertexBuffer.NormalKind))return null;let r=this.pickedMesh.getIndices();(null==r?void 0:r.length)===0&&(r=null);let s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1],n=math_vector_TmpVectors.Vector3[2];if(t){let e=this.pickedMesh.getVerticesData(buffer_VertexBuffer.NormalKind),t=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId],s):s.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),o=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),l=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId+2],n):n.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]);t=t.scale(this.bu),o=o.scale(this.bv),l=l.scale(1-this.bu-this.bv),i=new math_vector_Vector3(t.x+o.x+l.x,t.y+o.y+l.y,t.z+o.z+l.z)}else{let e=this.pickedMesh.getVerticesData(buffer_VertexBuffer.PositionKind),t=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId],s):s.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),o=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId+1],a):a.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),l=r?math_vector_Vector3.FromArrayToRef(e,3*r[3*this.faceId+2],n):n.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]),h=t.subtract(o),c=l.subtract(o);i=math_vector_Vector3.Cross(h,c)}let transformNormalToWorld=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(math_vector_TmpVectors.Matrix[0].copyFrom(i),(i=math_vector_TmpVectors.Matrix[0]).setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(math_vector_TmpVectors.Matrix[1]),i=math_vector_TmpVectors.Matrix[1]),math_vector_Vector3.TransformNormalToRef(t,i,t)};if(e&&transformNormalToWorld(this.pickedMesh,i),this.ray){let t=math_vector_TmpVectors.Vector3[0].copyFrom(i);e||transformNormalToWorld(this.pickedMesh,t),math_vector_Vector3.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=buffer_VertexBuffer.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let r=math_vector_Vector2.FromArray(i,2*t[3*this.faceId]),s=math_vector_Vector2.FromArray(i,2*t[3*this.faceId+1]),a=math_vector_Vector2.FromArray(i,2*t[3*this.faceId+2]);return r=r.scale(this.bu),s=s.scale(this.bv),a=a.scale(1-this.bu-this.bv),new math_vector_Vector2(r.x+s.x+a.x,r.y+s.y+a.y)}};let PostProcessManager=class PostProcessManager{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[buffer_VertexBuffer.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(this._scene.getEngine(),e,buffer_VertexBuffer.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let 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(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){let i=this._scene.activeCamera;return!!(i&&(t=t||i._postProcesses.filter(e=>null!=e))&&0!==t.length&&this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0)}directRender(e,t=null,i=!1,r=0,s=0,a=!1){var n;let o=this._scene.getEngine();for(let l=0;lnull!=e)).length||!this._scene.postProcessesEnabled)return;let o=this._scene.getEngine();for(let l=0,h=r.length;lt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.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,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&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;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;i=Z.LeftClick&&i<=Z.RightClick&&(l.type=1===r?"pointerdown":"pointerup",l.button=i-2),l}static _CreateWheelEvent(e,t,i,r,s,a){let n=this._CreateMouseEvent(e,t,i,r,s,a);switch(n.pointerId=1,n.type="wheel",n.deltaMode=EventConstants.DOM_DELTA_PIXEL,n.deltaX=0,n.deltaY=0,n.deltaZ=0,i){case Z.MouseWheelX:n.deltaX=r;break;case Z.MouseWheelY:n.deltaY=r;break;case Z.MouseWheelZ:n.deltaZ=r}return n}static _CreateMouseEvent(e,t,i,r,s,a){let n=this._CreateEvent(a),o=s.pollInput(e,t,Z.Horizontal),l=s.pollInput(e,t,Z.Vertical);return a?(n.movementX=0,n.movementY=0,n.offsetX=n.movementX-a.getBoundingClientRect().x,n.offsetY=n.movementY-a.getBoundingClientRect().y):(n.movementX=s.pollInput(e,t,J.DeltaHorizontal),n.movementY=s.pollInput(e,t,J.DeltaVertical),n.offsetX=0,n.offsetY=0),this._CheckNonCharacterKeys(n,s),n.clientX=o,n.clientY=l,n.x=o,n.y=l,n.deviceType=e,n.deviceSlot=t,n.inputIndex=i,n}static _CreateKeyboardEvent(e,t,i,r){let s=this._CreateEvent(r);return this._CheckNonCharacterKeys(s,i),s.deviceType=Q.Keyboard,s.deviceSlot=0,s.inputIndex=e,s.type=1===t?"keydown":"keyup",s.key=String.fromCharCode(e),s.keyCode=e,s}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(Q.Keyboard),r=i&&1===t.pollInput(Q.Keyboard,0,18),s=i&&1===t.pollInput(Q.Keyboard,0,17),a=i&&(1===t.pollInput(Q.Keyboard,0,91)||1===t.pollInput(Q.Keyboard,0,92)||1===t.pollInput(Q.Keyboard,0,93)),n=i&&1===t.pollInput(Q.Keyboard,0,16);e.altKey=r,e.ctrlKey=s,e.metaKey=a,e.shiftKey=n}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}};let NativeDeviceInputSystem=class NativeDeviceInputSystem{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(e,t,r,s)=>{let a=DeviceEventFactory.CreateDeviceEvent(e,t,r,s,this);i(e,t,a)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===Q.Mouse||e===Q.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}};let D=Object.keys(Z).length/2;let WebDeviceInputSystem=class WebDeviceInputSystem{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=tools_Tools.IsSafari(),this._usingMacOS=IsNavigatorAvailable()&&/(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=IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=IsNavigatorAvailable()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=tools_Tools.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let r=this._inputs[e][t];if(!r)throw`Unable to find device ${Q[e]}`;e>=Q.DualShock&&e<=Q.DualSense&&this._updateDevice(e,t,i);let s=r[i];if(void 0===s)throw`Unable to find input ${i} for device ${Q[e]} in slot ${t}`;return i===Z.Move&&tools_Tools.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),s}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this===null||void 0===this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let e of this._inputs)if(e)for(let t in e){let i=+t,r=e[i];if(r)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Q.Keyboard,0,255));let t=this._inputs[Q.Keyboard][0];t&&(t[e.keyCode]=1,e.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&!this._metaKeys.includes(e.keyCode)&&this._metaKeys.push(e.keyCode),this._onInputChanged(Q.Keyboard,0,e))},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(Q.Keyboard,0,255));let t=this._inputs[Q.Keyboard][0];if(t){if(t[e.keyCode]=0,e.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(let e of this._metaKeys){let i=DeviceEventFactory.CreateDeviceEvent(Q.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(Q.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(Q.Keyboard,0,e)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[Q.Keyboard][0];for(let t=0;t{let t=this._getPointerType(e),i=t===Q.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===Q.Touch&&-1===i){let r=this._activeTouchIds.indexOf(-1);if(r>=0)i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i);else{tools_Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);let r=this._inputs[t][i];r&&(e.inputIndex=Z.Move,r[Z.Horizontal]=e.clientX,r[Z.Vertical]=e.clientY,t===Q.Touch&&0===r[Z.LeftClick]&&(r[Z.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,e),this._usingSafari||-1===e.button||(e.inputIndex=e.button+2,r[e.button+2]=r[e.button+2]?0:1,this._onInputChanged(t,i,e)))},this._pointerDownEvent=e=>{let t=this._getPointerType(e),i=t===Q.Mouse?0:e.pointerId;if(t===Q.Touch){let t=this._activeTouchIds.indexOf(-1);if(t>=0)i=t,this._activeTouchIds[t]=e.pointerId;else{tools_Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===Q.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);let r=this._inputs[t][i];if(r){let s=r[Z.Horizontal],a=r[Z.Vertical];if(t===Q.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){}r[Z.Horizontal]=e.clientX,r[Z.Vertical]=e.clientY,r[e.button+2]=1,e.inputIndex=e.button+2,this._onInputChanged(t,i,e),(s!==e.clientX||a!==e.clientY)&&(e.inputIndex=Z.Move,this._onInputChanged(t,i,e))}},this._pointerUpEvent=e=>{var t,i,r,s,a;let n=this._getPointerType(e),o=n===Q.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(n===Q.Touch){if(-1===o)return;this._activeTouchIds[o]=-1}let l=null===(t=this._inputs[n])||void 0===t?void 0:t[o];if(l&&0!==l[e.button+2]){let t=l[Z.Horizontal],h=l[Z.Vertical];l[Z.Horizontal]=e.clientX,l[Z.Vertical]=e.clientY,l[e.button+2]=0,void 0===e.pointerId&&(e.pointerId=this._mouseId),(t!==e.clientX||h!==e.clientY)&&(e.inputIndex=Z.Move,this._onInputChanged(n,o,e)),e.inputIndex=e.button+2,n===Q.Mouse&&this._mouseId>=0&&(null===(r=(i=this._elementToAttachTo).hasPointerCapture)||void 0===r?void 0:r.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(a=(s=this._elementToAttachTo).hasPointerCapture)||void 0===a?void 0:a.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(n,o,e),n===Q.Touch&&this._onDeviceDisconnected(n,o)}},this._pointerCancelEvent=e=>{var t,i,r,s;if("mouse"===e.pointerType){let e=this._inputs[Q.Mouse][0];this._mouseId>=0&&(null===(i=(t=this._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=Z.LeftClick;t<=Z.BrowserForward;t++)if(1===e[t]){e[t]=0;let i=DeviceEventFactory.CreateDeviceEvent(Q.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(Q.Mouse,0,i)}}else{let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;(null===(s=(r=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(r,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[Q.Touch][t][Z.LeftClick]=0;let i=DeviceEventFactory.CreateDeviceEvent(Q.Touch,t,Z.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(Q.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(Q.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1,noop=function(){};try{let t=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",noop,t),this._elementToAttachTo.removeEventListener("test",noop,t)}catch(e){}this._pointerBlurEvent=()=>{var e,t,i,r,s;if(this.isDeviceAvailable(Q.Mouse)){let i=this._inputs[Q.Mouse][0];this._mouseId>=0&&(null===(t=(e=this._elementToAttachTo).hasPointerCapture)||void 0===t?void 0:t.call(e,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let e=Z.LeftClick;e<=Z.BrowserForward;e++)if(1===i[e]){i[e]=0;let t=DeviceEventFactory.CreateDeviceEvent(Q.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(Q.Mouse,0,t)}}if(this.isDeviceAvailable(Q.Touch)){let e=this._inputs[Q.Touch];for(let t=0;t{let t=Q.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,D));let i=this._inputs[t][0];i&&(i[Z.MouseWheelX]=e.deltaX||0,i[Z.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[Z.MouseWheelZ]=e.deltaZ||0,void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[Z.MouseWheelX]&&(e.inputIndex=Z.MouseWheelX,this._onInputChanged(t,0,e)),0!==i[Z.MouseWheelY]&&(e.inputIndex=Z.MouseWheelY,this._onInputChanged(t,0,e)),0!==i[Z.MouseWheelZ]&&(e.inputIndex=Z.MouseWheelZ,this._onInputChanged(t,0,e)))},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(Q.Mouse)){let e=this._inputs[Q.Mouse][0];e[Z.MouseWheelX]=0,e[Z.MouseWheelY]=0,e[Z.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return -1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?Q.DualSense:Q.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?Q.Xbox:-1!==e.indexOf("057e")?Q.Switch:Q.Generic}_getPointerType(e){let t=Q.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=Q.Touch),t}};let DeviceSource=class DeviceSource{constructor(e,t,i=0){this.deviceType=t,this.deviceSlot=i,this.onInputChangedObservable=new observable_Observable,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}};let InternalDeviceSourceManager=class InternalDeviceSourceManager{constructor(e){this._registeredManagers=[],this._refCount=0,this.registerManager=e=>{for(let t=0;t{let t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};let t=Object.keys(Q).length/2;this._devices=Array(t);let onDeviceConnected=(e,t)=>{for(let i of(this._devices[e]||(this._devices[e]=[]),this._devices[e][t]||(this._devices[e][t]=t),this._registeredManagers)){let r=new DeviceSource(this._deviceInputSystem,e,t);i._addDevice(r)}},onDeviceDisconnected=(e,t)=>{var i;for(let r of((null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t],this._registeredManagers))r._removeDevice(e,t)},onInputChanged=(e,t,i)=>{if(i)for(let r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new NativeDeviceInputSystem(onDeviceConnected,onDeviceDisconnected,onInputChanged):this._deviceInputSystem=new WebDeviceInputSystem(e,onDeviceConnected,onDeviceDisconnected,onInputChanged)}dispose(){this._deviceInputSystem.dispose()}};let DeviceSourceManager=class DeviceSourceManager{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){let t=Object.keys(Q).length/2;this._devices=Array(t),this._firstDevice=Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new InternalDeviceSourceManager(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new observable_Observable(e=>{for(let t of this._devices)if(t)for(let i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)}),this.onDeviceDisconnectedObservable=new observable_Observable,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]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,r;let s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(r=this._devices[e])||void 0===r?void 0:r[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;null===(s=null===(r=this._devices[e])||void 0===r?void 0:r[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case Q.Keyboard:case Q.Mouse:this._firstDevice[e]=0;break;case Q.Touch:case Q.DualSense:case Q.DualShock:case Q.Xbox:case Q.Switch:case Q.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i=Z.MouseWheelX&&t.inputIndex<=Z.MouseWheelZ?pointerEvents_PointerEventTypes.POINTERWHEEL:pointerEvents_PointerEventTypes.POINTERMOVE;r.onPointerMove&&(e=e||this._pickMove(t),r.onPointerMove(t,e,n)),e?(i=new PointerInfo(n,t,e),this._setRayOnPointerInfo(e,t)):(i=new PointerInfo(n,t,null,this),this._movePointerInfo=i),r.onPointerObservable.hasObservers()&&r.onPointerObservable.notifyObservers(i,n)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&i._pickingAvailable&&!e.ray&&(e.ray=i.createPickingRay(t.offsetX,t.offsetY,math_vector_Matrix.Identity(),i.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,i){let r=this._scene,s=new PointerInfoPre(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(s.originalPickingInfo=e,s.ray=e.ray,e.originMesh&&(s.nearInteractionPickingInfo=e)),r.onPrePointerObservable.notifyObservers(s,i),!!s.skipOnPointerObservable}_pickMove(e){let t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){let r=i.getEngine(),s=r.getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){let e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=Z.Move,this._checkPrePointerObservable(e,i,pointerEvents_PointerEventTypes.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,pointerEvents_PointerEventTypes.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){let i;let r=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(5,ActionEvent.CreateNew(e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(2,ActionEvent.CreateNew(e.pickedMesh,t,e));break;case 1:i.processTrigger(4,ActionEvent.CreateNew(e.pickedMesh,t,e));break;case 2:i.processTrigger(3,ActionEvent.CreateNew(e.pickedMesh,t,e))}i.hasSpecificTrigger(8)&&window.setTimeout(()=>{let e=r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh,!1,r.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&i&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>InputManager.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(8,ActionEvent.CreateNew(e.pickedMesh,t)))},InputManager.LongPressDelay)}}else for(let i of r._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let s=pointerEvents_PointerEventTypes.POINTERDOWN;e?(r.onPointerDown&&r.onPointerDown(t,e,s),i=new PointerInfo(s,t,e),this._setRayOnPointerInfo(e,t)):i=new PointerInfo(s,t,null,this),r.onPointerObservable.hasObservers()&&r.onPointerObservable.notifyObservers(i,s)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let r=new PointerEvent("pointerup",t);r.inputIndex=Z.Move;let s=new _ClickInfo;i?s.doubleClick=!0:s.singleClick=!0,this._checkPrePointerObservable(e,r,pointerEvents_PointerEventTypes.POINTERUP)||this._processPointerUp(e,r,s)}_processPointerUp(e,t,i){let r=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(r.onPointerPick&&r.onPointerPick(t,e),i.singleClick&&!i.ignore&&r.onPointerObservable.observers.length>this._cameraObserverCount)){let i=pointerEvents_PointerEventTypes.POINTERPICK,s=new PointerInfo(i,t,e);this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,i)}let s=e.pickedMesh._getActionManagerForTrigger();if(s&&!i.ignore){s.processTrigger(7,ActionEvent.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&s.processTrigger(1,ActionEvent.CreateNew(e.pickedMesh,t,e));let r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,ActionEvent.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let s of r._pointerUpStage)e=s.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,ActionEvent.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let s=new PointerInfo(pointerEvents_PointerEventTypes.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),r.onPointerObservable.notifyObservers(s,pointerEvents_PointerEventTypes.POINTERUP),r.onPointerUp&&r.onPointerUp(t,e,pointerEvents_PointerEventTypes.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let s=0;if(i.singleClick?s=pointerEvents_PointerEventTypes.POINTERTAP:i.doubleClick&&(s=pointerEvents_PointerEventTypes.POINTERDOUBLETAP),s){let i=new PointerInfo(s,t,e);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(s)&&r.onPointerObservable.notifyObservers(i,s)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,r=null){let s=this._scene,a=s.getEngine();r||(r=a.getInputElement()),this._alreadyAttached&&this.detachControl(),r&&(this._alreadyAttachedTo=r),this._deviceSourceManager=new DeviceSourceManager(a),this._initActionManager=e=>{if(!this._meshPickProceed){let t=!s.skipPointerUpPicking&&(0!==s._registeredActions||this._checkForPicking()||s.onPointerUp)?s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerUpPredicate,s.pointerUpFastCheck,s.cameraToUseForPointers):null;this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>InputManager.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){let t=this._delayedClicks[e].evt,i=pointerEvents_PointerEventTypes.POINTERTAP,r=new PointerInfo(i,t,this._currentPickResult);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(i)&&s.onPointerObservable.notifyObservers(r,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,r)=>{var s,a;let n=new _ClickInfo;this._currentPickResult=null;let o=null,l=e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERPICK)||t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERPICK)||e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP)||t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP)||e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)||t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP);!l&&AbstractActionManager&&(o=this._initActionManager(o,n))&&(l=o.hasPickTriggers);let h=!1;if(l){let l=i.button;if(n.hasSwiped=this._isPointerSwiping(),!n.hasSwiped){let c=!InputManager.ExclusiveDoubleClickMode;if(!c&&(c=!e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)&&!t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP))&&!AbstractActionManager.HasSpecificTrigger(6)&&(o=this._initActionManager(o,n))&&(c=!o.hasSpecificTrigger(6)),c)(Date.now()-this._previousStartingPointerTime>InputManager.DoubleClickDelay||l!==this._previousButtonPressed)&&(n.singleClick=!0,r(n,this._currentPickResult),h=!0);else{let e={evt:i,clickInfo:n,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,l,n,r),InputManager.DoubleClickDelay)};this._delayedClicks[l]=e}let u=e.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)||t.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP);!u&&AbstractActionManager.HasSpecificTrigger(6)&&(o=this._initActionManager(o,n))&&(u=o.hasSpecificTrigger(6)),u&&(l===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>InputManager.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>InputManager.DragMovementThreshold),a.isPointerLock&&a._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=Z.MouseWheelX&&e.inputIndex<=Z.MouseWheelZ?pointerEvents_PointerEventTypes.POINTERWHEEL:pointerEvents_PointerEventTypes.POINTERMOVE)||!s.cameraToUseForPointers&&!s.activeCamera)return;if(s.skipPointerMovePicking){this._processPointerMove(new PickingInfo,e);return}s.pointerMovePredicate||(s.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||s.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0));let t=s._registeredActions>0||s.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;let i;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,InputManager.ExclusiveDoubleClickMode){for(let i=0;ie.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0)),this._pickedDownMesh=null,i=!s.skipPointerDownPicking&&(0!==s._registeredActions||this._checkForPicking()||s.onPointerDown)?s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,s.pointerDownPredicate,s.pointerDownFastCheck,s.cameraToUseForPointers):new PickingInfo,this._processPointerDown(i,e))},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),s.preventDefaultOnPointerUp&&r&&(e.preventDefault(),r.focus()),this._initClickEvent(s.onPrePointerObservable,s.onPointerObservable,e,(t,i)=>{if(s.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,pointerEvents_PointerEventTypes.POINTERUP)){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1);return}!t.hasSwiped&&(t.singleClick&&s.onPrePointerObservable.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERTAP)&&this._checkPrePointerObservable(null,e,pointerEvents_PointerEventTypes.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&s.onPrePointerObservable.hasSpecificMask(pointerEvents_PointerEventTypes.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,pointerEvents_PointerEventTypes.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[e.pointerId]){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(s.cameraToUseForPointers||s.activeCamera)&&(s.pointerUpPredicate||(s.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!s.cameraToUseForPointers||(s.cameraToUseForPointers.layerMask&e.layerMask)!=0)),!this._meshPickProceed&&(AbstractActionManager&&AbstractActionManager.HasTriggers||this._checkForPicking()||s.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=e=>{let t=KeyboardEventTypes.KEYDOWN;if(s.onPreKeyboardObservable.hasObservers()){let i=new KeyboardInfoPre(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let i=new KeyboardInfo(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(14,ActionEvent.CreateNewFromScene(s,e))},this._onKeyUp=e=>{let t=KeyboardEventTypes.KEYUP;if(s.onPreKeyboardObservable.hasObservers()){let i=new KeyboardInfoPre(t,e);if(s.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(s.onKeyboardObservable.hasObservers()){let i=new KeyboardInfo(t,e);s.onKeyboardObservable.notifyObservers(i,t)}s.actionManager&&s.actionManager.processTrigger(15,ActionEvent.CreateNewFromScene(s,e))},this._deviceSourceManager.onDeviceConnectedObservable.add(r=>{r.deviceType===Q.Mouse?r.onInputChangedObservable.add(s=>{s.inputIndex===Z.LeftClick||s.inputIndex===Z.MiddleClick||s.inputIndex===Z.RightClick||s.inputIndex===Z.BrowserBack||s.inputIndex===Z.BrowserForward?t&&1===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===Z.Move?this._onPointerMove(s):(s.inputIndex===Z.MouseWheelX||s.inputIndex===Z.MouseWheelY||s.inputIndex===Z.MouseWheelZ)&&this._onPointerMove(s))}):r.deviceType===Q.Touch?r.onInputChangedObservable.add(s=>{s.inputIndex===Z.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===Z.Move&&this._onPointerMove(s)}):r.deviceType===Q.Keyboard&&r.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,i,r){let s;if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let a=this._meshUnderPointerId[t];a&&(s=a._getActionManagerForTrigger(10))&&s.processTrigger(10,ActionEvent.CreateNew(a,r,{pointerId:t})),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,(s=e._getActionManagerForTrigger(9))&&s.processTrigger(9,ActionEvent.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){for(let t in this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null),this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}};InputManager.DragMovementThreshold=10,InputManager.LongPressDelay=500,InputManager.DoubleClickDelay=300,InputManager.ExclusiveDoubleClickMode=!1;let perfCounter_PerfCounter=class perfCounter_PerfCounter{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){perfCounter_PerfCounter.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){perfCounter_PerfCounter.Enabled&&(this._startMonitoringTime=precisionDate_PrecisionDate.Now)}endMonitoring(e=!0){if(!perfCounter_PerfCounter.Enabled)return;e&&this.fetchNewFrame();let t=precisionDate_PrecisionDate.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;let e=precisionDate_PrecisionDate.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}};perfCounter_PerfCounter.Enabled=!0;let math_plane_Plane=class math_plane_Plane{constructor(e,t,i,r){this.normal=new math_vector_Vector3(e,t,i),this.d=r}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new math_plane_Plane(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){return 397*this.normal.getHashCode()^(0|this.d)}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),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){let t=math_plane_Plane._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,s=this.normal.y,a=this.normal.z,n=this.d,o=r*i[0]+s*i[1]+a*i[2]+n*i[3],l=r*i[4]+s*i[5]+a*i[6]+n*i[7],h=r*i[8]+s*i[9]+a*i[10]+n*i[11],c=r*i[12]+s*i[13]+a*i[14]+n*i[15];return new math_plane_Plane(o,l,h,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r;let s=t.x-e.x,a=t.y-e.y,n=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,c=a*h-n*l,u=n*o-s*h,d=s*l-a*o,_=Math.sqrt(c*c+u*u+d*d);return r=0!==_?1/_:0,this.normal.x=c*r,this.normal.y=u*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){let i=math_vector_Vector3.Dot(this.normal,e);return i<=t}signedDistanceTo(e){return math_vector_Vector3.Dot(e,this.normal)+this.d}static FromArray(e){return new math_plane_Plane(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new math_plane_Plane(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new math_plane_Plane(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){let r=-(t.x*e.x+t.y*e.y+t.z*e.z);return math_vector_Vector3.Dot(i,t)+r}};math_plane_Plane._TmpMatrix=math_vector_Matrix.Identity();let Frustum=class Frustum{static GetPlanes(e){let t=[];for(let e=0;e<6;e++)t.push(new math_plane_Plane(0,0,0,0));return Frustum.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Frustum.GetNearPlaneToRef(e,t[0]),Frustum.GetFarPlaneToRef(e,t[1]),Frustum.GetLeftPlaneToRef(e,t[2]),Frustum.GetRightPlaneToRef(e,t[3]),Frustum.GetTopPlaneToRef(e,t[4]),Frustum.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(0>t[i].dotCoordinate(e))return!1;return!0}};let UniqueIdGenerator=class UniqueIdGenerator{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}};UniqueIdGenerator._UniqueIdCounter=1;let LightConstants=class LightConstants{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}};LightConstants.FALLOFF_DEFAULT=0,LightConstants.FALLOFF_PHYSICAL=1,LightConstants.FALLOFF_GLTF=2,LightConstants.FALLOFF_STANDARD=3,LightConstants.LIGHTMAP_DEFAULT=0,LightConstants.LIGHTMAP_SPECULAR=1,LightConstants.LIGHTMAP_SHADOWSONLY=2,LightConstants.INTENSITYMODE_AUTOMATIC=0,LightConstants.INTENSITYMODE_LUMINOUSPOWER=1,LightConstants.INTENSITYMODE_LUMINOUSINTENSITY=2,LightConstants.INTENSITYMODE_ILLUMINANCE=3,LightConstants.INTENSITYMODE_LUMINANCE=4,LightConstants.LIGHTTYPEID_POINTLIGHT=0,LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT=1,LightConstants.LIGHTTYPEID_SPOTLIGHT=2,LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT=3;let PointerPickingConfiguration=class PointerPickingConfiguration{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}};!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(ea||(ea={}));let scene_Scene=class scene_Scene extends AbstractScene{static DefaultMaterialFactory(e){throw _WarnImport("StandardMaterial")}static CollisionCoordinatorFactory(){throw _WarnImport("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case ea.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case ea.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case ea.Aggressive: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(16))}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(16))}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 InputManager.DragMovementThreshold}static set DragMovementThreshold(e){InputManager.DragMovementThreshold=e}static get LongPressDelay(){return InputManager.LongPressDelay}static set LongPressDelay(e){InputManager.LongPressDelay=e}static get DoubleClickDelay(){return InputManager.DoubleClickDelay}static set DoubleClickDelay(e){InputManager.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return InputManager.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){InputManager.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",i=!1){let r=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,s=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return math_vector_TmpVectors.Vector4[0].set(r.x,r.y,r.z,s?-1:1),e&&(i?e.setFloat3(t,math_vector_TmpVectors.Vector4[0].x,math_vector_TmpVectors.Vector4[0].y,math_vector_TmpVectors.Vector4[0].z):e.setVector4(t,math_vector_TmpVectors.Vector4[0])),math_vector_TmpVectors.Vector4[0]}finalizeSceneUbo(){let 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(16))}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(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}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(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=_ObserveArray(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=scene_Scene.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=scene_Scene.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e),e.addFromContainer&&e.serialize&&this._serializableComponents.push(e)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new InputManager(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new math_color_Color4(.2,.2,.3,1),this.ambientColor=new math_color_Color3(0,0,0),this.environmentIntensity=1,this._performancePriority=ea.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new observable_Observable,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 observable_Observable,this._onDisposeObserver=null,this.onBeforeRenderObservable=new observable_Observable,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new observable_Observable,this.onAfterRenderCameraObservable=new observable_Observable,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new observable_Observable,this.onAfterAnimationsObservable=new observable_Observable,this.onBeforeDrawPhaseObservable=new observable_Observable,this.onAfterDrawPhaseObservable=new observable_Observable,this.onReadyObservable=new observable_Observable,this.onBeforeCameraRenderObservable=new observable_Observable,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new observable_Observable,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new observable_Observable,this.onAfterActiveMeshesEvaluationObservable=new observable_Observable,this.onBeforeParticlesRenderingObservable=new observable_Observable,this.onAfterParticlesRenderingObservable=new observable_Observable,this.onDataLoadedObservable=new observable_Observable,this.onNewCameraAddedObservable=new observable_Observable,this.onCameraRemovedObservable=new observable_Observable,this.onNewLightAddedObservable=new observable_Observable,this.onLightRemovedObservable=new observable_Observable,this.onNewGeometryAddedObservable=new observable_Observable,this.onGeometryRemovedObservable=new observable_Observable,this.onNewTransformNodeAddedObservable=new observable_Observable,this.onTransformNodeRemovedObservable=new observable_Observable,this.onNewMeshAddedObservable=new observable_Observable,this.onMeshRemovedObservable=new observable_Observable,this.onNewSkeletonAddedObservable=new observable_Observable,this.onSkeletonRemovedObservable=new observable_Observable,this.onNewMaterialAddedObservable=new observable_Observable,this.onNewMultiMaterialAddedObservable=new observable_Observable,this.onMaterialRemovedObservable=new observable_Observable,this.onMultiMaterialRemovedObservable=new observable_Observable,this.onNewTextureAddedObservable=new observable_Observable,this.onTextureRemovedObservable=new observable_Observable,this.onBeforeRenderTargetsRenderObservable=new observable_Observable,this.onAfterRenderTargetsRenderObservable=new observable_Observable,this.onBeforeStepObservable=new observable_Observable,this.onAfterStepObservable=new observable_Observable,this.onActiveCameraChanged=new observable_Observable,this.onActiveCamerasChanged=new observable_Observable,this.onBeforeRenderingGroupObservable=new observable_Observable,this.onAfterRenderingGroupObservable=new observable_Observable,this.onMeshImportedObservable=new observable_Observable,this.onAnimationFileImportedObservable=new observable_Observable,this._registeredForLateAnimationBindings=new SmartArrayNoDuplicate(256),this._pointerPickingConfiguration=new PointerPickingConfiguration,this.onPrePointerObservable=new observable_Observable,this.onPointerObservable=new observable_Observable,this.onPreKeyboardObservable=new observable_Observable,this.onKeyboardObservable=new observable_Observable,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=scene_Scene.FOGMODE_NONE,this.fogColor=new math_color_Color3(.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 math_vector_Vector3(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new SmartArrayNoDuplicate(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new perfCounter_PerfCounter,this._activeIndices=new perfCounter_PerfCounter,this._activeParticles=new perfCounter_PerfCounter,this._activeBones=new perfCounter_PerfCounter,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=Array(256),this._activeRequests=[],this._pendingData=[],this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new SmartArray(256),this._processedMaterials=new SmartArray(256),this._renderTargets=new SmartArrayNoDuplicate(256),this._materialsRenderTargets=new SmartArrayNoDuplicate(256),this._activeParticleSystems=new SmartArray(256),this._activeSkeletons=new SmartArrayNoDuplicate(32),this._softwareSkinnedMeshes=new SmartArrayNoDuplicate(32),this._activeAnimatables=[],this._transformMatrix=math_vector_Matrix.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=Stage.Create(),this._beforeClearStage=Stage.Create(),this._beforeRenderTargetClearStage=Stage.Create(),this._gatherRenderTargetsStage=Stage.Create(),this._gatherActiveCameraRenderTargetsStage=Stage.Create(),this._isReadyForMeshStage=Stage.Create(),this._beforeEvaluateActiveMeshStage=Stage.Create(),this._evaluateSubMeshStage=Stage.Create(),this._preActiveMeshStage=Stage.Create(),this._cameraDrawRenderTargetStage=Stage.Create(),this._beforeCameraDrawStage=Stage.Create(),this._beforeRenderTargetDrawStage=Stage.Create(),this._beforeRenderingGroupDrawStage=Stage.Create(),this._beforeRenderingMeshStage=Stage.Create(),this._afterRenderingMeshStage=Stage.Create(),this._afterRenderingGroupDrawStage=Stage.Create(),this._afterCameraDrawStage=Stage.Create(),this._afterCameraPostProcessStage=Stage.Create(),this._afterRenderTargetDrawStage=Stage.Create(),this._afterRenderTargetPostProcessStage=Stage.Create(),this._afterRenderStage=Stage.Create(),this._pointerMoveStage=Stage.Create(),this._pointerDownStage=Stage.Create(),this._pointerUpStage=Stage.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=[];let i=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);e=this._engine=e||engineStore_EngineStore.LastCreatedEngine,i.virtual?e._virtualScenes.push(this):(engineStore_EngineStore._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new RenderingManager(this),PostProcessManager&&(this.postProcessManager=new PostProcessManager(this)),IsWindowObjectExist()&&this.attachControl(),this._createUbo(),ImageProcessingConfiguration&&(this._imageProcessingConfiguration=new ImageProcessingConfiguration),this.setDefaultCandidateProviders(),i.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=i.useMaterialMeshMap,this.useClonedMeshMap=i.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,i=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==i}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,i){return this._inputManager.simulatePointerUp(e,t,i),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,i=!0){this._inputManager.attachControl(e,t,i)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){var t,i,r;let s;if(this._isDisposed)return!1;let a=this.getEngine(),n=a.currentRenderPassId;a.currentRenderPassId=null!==(i=null===(t=this.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==i?i:n;let o=!0;for(this._pendingData.length>0&&(o=!1),null===(r=this.prePassRenderer)||void 0===r||r.update(),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),s=0;s0;for(let e of this._isReadyForMeshStage)e.action(t,i)||(o=!1);if(!e)continue;let r=t.material||this.defaultMaterial;if(r){if(r._storeEffectOnSubMeshes)for(let e of t.subMeshes){let t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else r.hasRenderTargetTextures&&null!=r.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(r)&&(this._processedMaterials.push(r),this._materialsRenderTargets.concatWithNoDuplicate(r.getRenderTargetTextures()))}}if(e)for(s=0;s0)for(let e of this.activeCameras)e.isReady(!0)||(o=!1);else this.activeCamera&&!this.activeCamera.isReady(!0)&&(o=!1);for(let e of this.particleSystems)e.isReady()||(o=!1);if(this.layers)for(let e of this.layers)e.isReady()||(o=!1);return a.areAllEffectsReady()||(o=!1),a.currentRenderPassId=n,o}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){let execFunc=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(execFunc)})};this.registerBeforeRender(execFunc)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){let t=this.isLoading,i=this._pendingData.indexOf(e);-1!==i&&this._pendingData.splice(i,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){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=precisionDate_PrecisionDate.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,i,r){i||r||!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?Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Frustum.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(i,r):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){let t=new UniformBuffer(this._engine,void 0,!1,null!=e?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 UniqueIdGenerator.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){let i=this.meshes.indexOf(e);return -1===i||(this.meshes[i]=this.meshes[this.meshes.length-1],this.meshes.pop(),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach(e=>{this.removeMesh(e)}),i}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){let t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){let 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){let t=this.skeletons.indexOf(e);return -1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return -1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(-1!==t){for(let 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){let t=this.cameras.indexOf(e);if(-1===t||(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let 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){let t=this.particleSystems.indexOf(e);return -1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){let t=this.animations.indexOf(e);return -1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,i){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return -1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return -1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(-1!==t&&tt.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=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){let t=this.getMeshById(e);if(t)return t;let i=this.getTransformNodeById(e);if(i)return i;let r=this.getLightById(e);if(r)return r;let s=this.getCameraById(e);if(s)return s;let a=this.getBoneById(e);return a||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let i=this.getTransformNodeByName(e);if(i)return i;let r=this.getLightByName(e);if(r)return r;let s=this.getCameraByName(e);if(s)return s;let a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){i&&i("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=s,this._skipEvaluateActiveMeshesCompletely=e,r)for(let e=0;ee.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode){this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let e=this._activeMeshes.length;for(let t=0;t0&&(i.layerMask&this.activeCamera.layerMask)!=0&&(this._skipFrustumClipping||i.alwaysSelectAsActiveMesh||i.isInFrustum(this._frustumPlanes)))){for(let e of(this._activeMeshes.push(i),this.activeCamera._activeMeshes.push(i),r!==i&&r._activate(this._renderId,!1),this._preActiveMeshStage))e.action(i);i._activate(this._renderId,!1)&&(i.isAnInstance?i._internalAbstractMeshDataInfo._actAsRegularMesh&&(r=i):r._internalAbstractMeshDataInfo._onlyForInstances=!1,r._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(i,r)),i._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){let r=this.getActiveSubMeshCandidates(t),s=r.length;i=i||1===s;for(let a=0;a0&&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),this._gatherActiveCameraRenderTargetsStage))i.action(this._renderTargets);let o=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){tools_Tools.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(let e of this._cameraDrawRenderTargetStage)o=e.action(this.activeCamera)||o;this._intermediateRendering=!1}for(let t of(this._engine.currentRenderPassId=null!==(a=null!==(s=null===(r=e.outputRenderTarget)||void 0===r?void 0:r.renderPassId)&&void 0!==s?s:e.renderPassId)&&void 0!==a?a:0,o&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame(),this._beforeCameraDrawStage))t.action(this.activeCamera);for(let e of(this.onBeforeDrawPhaseObservable.notifyObservers(this),n.snapshotRendering&&1===n.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this),this._afterCameraDrawStage))e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(let e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1)||(13===i.trigger&&i._executeCurrent(ActionEvent.CreateNew(t,void 0,r)),t.actionManager.hasSpecificTrigger(13,e=>{let t=e.mesh?e.mesh:e;return r===t})&&13!==i.trigger||t._intersectionsInProgress.splice(a,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(scene_Scene.MinDeltaTime,Math.min(this._engine.getDeltaTime(),scene_Scene.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),i=1e3/t/1e3,r=0,s=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,s);e>0&&r0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}for(let e of(this._engine.currentRenderPassId=null!==(s=null==n?void 0:n.renderPassId)&&void 0!==s?s:0,this.activeCamera=n,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this._beforeClearStage))e.action();for(let e of(this._clearFrameBuffer(this.activeCamera),this._gatherRenderTargetsStage))e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}for(let e of(this._checkIntersections(),this._afterRenderStage))e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;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;let e=this._activeRequests.slice();for(let t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){console.error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();let t=this._engine.getInputElement();if(t)for(let e=0;ee.dispose(!0)),this._disposeList(this.transformNodes,e=>e.dispose(!0));let i=this.cameras;this._disposeList(i),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 r=this._engine.scenes.indexOf(this);r>-1&&this._engine.scenes.splice(r,1),engineStore_EngineStore._LastCreatedScene===this&&(this._engine.scenes.length>0?engineStore_EngineStore._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:engineStore_EngineStore._LastCreatedScene=null),(r=this._engine._virtualScenes.indexOf(this))>-1&&this._engine._virtualScenes.splice(r,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){let i=e.slice(0);for(let e of(t=null!=t?t:e=>e.dispose(),i))t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;let r=e.getBoundingInfo(),s=r.boundingBox.minimumWorld,a=r.boundingBox.maximumWorld;math_vector_Vector3.CheckExtends(s,t,i),math_vector_Vector3.CheckExtends(a,t,i)}),{min:t,max:i}}createPickingRay(e,t,i,r,s=!1){throw _WarnImport("Ray")}createPickingRayToRef(e,t,i,r,s,a=!1,n=!1){throw _WarnImport("Ray")}createPickingRayInCameraSpace(e,t,i){throw _WarnImport("Ray")}createPickingRayInCameraSpaceToRef(e,t,i,r){throw _WarnImport("Ray")}get _pickingAvailable(){return!1}pick(e,t,i,r,s,a){let n=_WarnImport("Ray",!0);return n&&logger_Logger.Warn(n),new PickingInfo}pickWithBoundingInfo(e,t,i,r,s){let a=_WarnImport("Ray",!0);return a&&logger_Logger.Warn(a),new PickingInfo}pickWithRay(e,t,i,r){throw _WarnImport("Ray")}multiPick(e,t,i,r,s){throw _WarnImport("Ray")}multiPickWithRay(e,t,i){throw _WarnImport("Ray")}setPointerOverMesh(e,t,i){this._inputManager.setPointerOverMesh(e,t,i)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of(this.postProcessManager&&this.postProcessManager._rebuild(),this._components))e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,i){if(void 0===t)return e;let r=[];for(let s in e){let a=e[s];Tags&&Tags.MatchesQuery(a,t)&&(!i||i(a))&&r.push(a)}return r}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,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t,i=!0,r=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,i,r)}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(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let i of this.materials)(!t||t(i))&&i.markAsDirty(e)}_loadFile(e,t,i,r,s,a,n){let o=LoadFile(e,t,i,r?this.offlineProvider:void 0,s,a,n);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_loadFileAsync(e,t,i,r,s){return new Promise((a,n)=>{this._loadFile(e,e=>{a(e)},t,i,r,(e,t)=>{n(t)},s)})}_requestFile(e,t,i,r,s,a,n){let o=RequestFile(e,t,i,r?this.offlineProvider:void 0,s,a,n);return this._activeRequests.push(o),o.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),o}_requestFileAsync(e,t,i,r,s){return new Promise((a,n)=>{this._requestFile(e,e=>{a(e)},t,i,r,e=>{n(e)},s)})}_readFile(e,t,i,r,s){let a=ReadFile(e,t,i,r,s);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}_readFileAsync(e,t,i){return new Promise((r,s)=>{this._readFile(e,e=>{r(e)},t,i,e=>{s(e)})})}getPerfCollector(){throw _WarnImport("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)}};scene_Scene.FOGMODE_NONE=0,scene_Scene.FOGMODE_EXP=1,scene_Scene.FOGMODE_EXP2=2,scene_Scene.FOGMODE_LINEAR=3,scene_Scene.MinDeltaTime=1,scene_Scene.MaxDeltaTime=1e3,function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(en||(en={}));let math_axis_Axis=class math_axis_Axis{};math_axis_Axis.X=new math_vector_Vector3(1,0,0),math_axis_Axis.Y=new math_vector_Vector3(0,1,0),math_axis_Axis.Z=new math_vector_Vector3(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(eo||(eo={}));let Bone=class Bone extends node_Node{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,i=null,r=null,s=null,a=null,n=null){var o;super(e,t.getScene()),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=null!==(o=null==r?void 0:r.clone())&&void 0!==o?o:math_vector_Matrix.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=a?a:this._localMatrix.clone(),this._index=n,this._absoluteMatrix=new math_vector_Matrix,this._absoluteBindMatrix=new math_vector_Matrix,this._absoluteInverseBindMatrix=new math_vector_Matrix,this._finalMatrix=new math_vector_Matrix,t.bones.push(this),this.setParent(i,!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){let 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(){var e;if(this._linkedTransformNode){let t=math_vector_TmpVectors.Vector3[0],i=math_vector_TmpVectors.Quaternion[0],r=math_vector_TmpVectors.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:math_vector_Quaternion.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}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=math_vector_Vector3.Zero(),this._localRotation=math_vector_Quaternion.Zero(),this._localPosition=math_vector_Vector3.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,math_vector_Matrix.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?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;ethis._absoluteBindMatrix.determinant()?-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=en.LOCAL,i,r=!0){let s=this.getLocalMatrix();if(t==en.LOCAL)r?(s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z)):s.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let a=Bone._TmpMats[0],n=Bone._TmpVecs[0];this.parent?i&&t?(a.copyFrom(this.parent.getAbsoluteMatrix()),a.multiplyToRef(t,a)):a.copyFrom(this.parent.getAbsoluteMatrix()):math_vector_Matrix.IdentityToRef(a),r&&a.setTranslationFromFloats(0,0,0),a.invert(),math_vector_Vector3.TransformCoordinatesToRef(e,a,n),r?(s.addAtIndex(12,n.x),s.addAtIndex(13,n.y),s.addAtIndex(14,n.z)):s.setTranslationFromFloats(n.x,n.y,n.z)}this._markAsDirtyAndDecompose()}translate(e,t=en.LOCAL,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=en.LOCAL,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,en.WORLD,t)}scale(e,t,i,r=!1){let s=this.getLocalMatrix(),a=Bone._TmpMats[0];for(let r of(math_vector_Matrix.ScalingToRef(e,t,i,a),a.multiplyToRef(s,s),a.invert(),this.children)){let s=r.getLocalMatrix();s.multiplyToRef(a,s),s.multiplyAtIndex(12,e),s.multiplyAtIndex(13,t),s.multiplyAtIndex(14,i),r._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(let s of this.children)s.scale(e,t,i,r)}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,i,r=en.LOCAL,s){if(r===en.LOCAL){let a=Bone._TmpQuat;math_vector_Quaternion.RotationYawPitchRollToRef(e,t,i,a),this.setRotationQuaternion(a,r,s);return}let a=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(a,s))return;let n=Bone._TmpMats[1];math_vector_Matrix.RotationYawPitchRollToRef(e,t,i,n),a.multiplyToRef(n,n),this._rotateWithMatrix(n,r,s)}rotate(e,t,i=en.LOCAL,r){let s=Bone._TmpMats[0];s.setTranslationFromFloats(0,0,0),math_vector_Matrix.RotationAxisToRef(e,t,s),this._rotateWithMatrix(s,i,r)}setAxisAngle(e,t,i=en.LOCAL,r){if(i===en.LOCAL){let s=Bone._TmpQuat;math_vector_Quaternion.RotationAxisToRef(e,t,s),this.setRotationQuaternion(s,i,r);return}let s=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;let a=Bone._TmpMats[1];math_vector_Matrix.RotationAxisToRef(e,t,a),s.multiplyToRef(a,a),this._rotateWithMatrix(a,i,r)}setRotation(e,t=en.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=en.LOCAL,i){if(t===en.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}let r=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=Bone._TmpMats[1];math_vector_Matrix.FromQuaternionToRef(e,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,t,i)}setRotationMatrix(e,t=en.LOCAL,i){if(t===en.LOCAL){let r=Bone._TmpQuat;math_vector_Quaternion.FromRotationMatrixToRef(e,r),this.setRotationQuaternion(r,t,i);return}let r=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=Bone._TmpMats[1];s.copyFrom(e),r.multiplyToRef(e,s),this._rotateWithMatrix(s,t,i)}_rotateWithMatrix(e,t=en.LOCAL,i){let r=this.getLocalMatrix(),s=r.m[12],a=r.m[13],n=r.m[14],o=this.getParent(),l=Bone._TmpMats[3],h=Bone._TmpMats[4];o&&t==en.WORLD?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):t==en.WORLD&&i?(l.copyFrom(i.getWorldMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(s,a,n),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){let i=Bone._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),math_vector_Matrix.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):math_vector_Matrix.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=en.LOCAL,t=null){let i=math_vector_Vector3.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=en.LOCAL,t,i){if(e==en.LOCAL){let e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let r=Bone._TmpMats[0];t&&e?(r.copyFrom(this.getAbsoluteMatrix()),r.multiplyToRef(e,r)):r=this.getAbsoluteMatrix(),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){let t=math_vector_Vector3.Zero();return this.getPositionToRef(en.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(en.WORLD,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);let e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}let e=this.children,t=e.length;for(let i=0;i-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i-1){let s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){let r=s[i];(!e||r.animation.name==e)&&(!t||t(r.target))&&(r.dispose(),s.splice(i,1))}0==s.length&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else{let e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);let t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){let t;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 i=!1,r=this._runtimeAnimations;for(t=0;t0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;let t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;let i=this._animationTime;for(let e=0;ee.playOrder-t.playOrder)},scene_Scene.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,a=1,n,o,l,h,c=!1){let u=this.beginAnimation(e,t,i,s,a,n,o,!1,l,h,c);return u.weight=r,u},scene_Scene.prototype.beginAnimation=function(e,t,i,r,s=1,a,n,o=!0,l,h,c=!1){t>i&&s>0&&(s*=-1),o&&this.stopAnimation(e,void 0,l),n||(n=new Animatable(this,e,t,i,r,s,a,void 0,h,c));let u=!l||l(e);if(e.animations&&u&&n.appendAnimations(e,e.animations),e.getAnimatables){let c=e.getAnimatables();for(let e=0;er&&a>0)a*=-1;else if(r>i&&a<0){let e=r;r=i,i=e}let h=new Animatable(this,e,i,r,s,a,n,t,o,l);return h},scene_Scene.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,a,n,o,l,h=!1){let c=e.getDescendants(t),u=[];for(let t of(u.push(this.beginDirectAnimation(e,i,r,s,a,n,o,l,h)),c))u.push(this.beginDirectAnimation(t,i,r,s,a,n,o,l,h));return u},scene_Scene.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,s),o.scaleAndAddToRef(l,i)}s.normalize()}for(let t=0;t0)s.copyFrom(r);else if(1===e.animations.length){if(math_vector_Quaternion.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,a,n=1;if(e.totalWeight<1){let t=1-e.totalWeight;a=[],(i=[]).push(r),a.push(t)}else{if(2===e.animations.length&&(math_vector_Quaternion.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],a=[],n=e.totalWeight}for(let t=0;t=h&&a.frame<=c&&(r?(o=a.value.clone(),f?(n=o.getTranslation(),o.setTranslation(n.scaleInPlace(m))):g&&s?(n=o.getTranslation(),o.setTranslation(n.multiplyInPlace(s))):o=a.value):o=a.value,v.push({frame:a.frame+i,value:o}));return this.animations[0].createRange(t,h+i,c+i),!0},function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(el||(el={}));let Angle=class Angle{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){let i=t.subtract(e),r=Math.atan2(i.y,i.x);return new Angle(r)}static FromRadians(e){return new Angle(e)}static FromDegrees(e){return new Angle(e*Math.PI/180)}};let Arc2=class Arc2{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,a=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,n=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new math_vector_Vector2((s*(t.y-i.y)-a*(e.y-t.y))/n,((e.x-t.x)*a-(t.x-i.x)*s)/n),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Angle.BetweenTwoPoints(this.centerPoint,this.startPoint);let o=this.startAngle.degrees(),l=Angle.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=Angle.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-o>180&&(l-=360),l-o<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-o<0?el.CW:el.CCW,this.angle=Angle.FromDegrees(this.orientation===el.CW?o-h:h-o)}};let math_path_Path2=class math_path_Path2{constructor(e,t){this._points=[],this._length=0,this.closed=!1,this._points.push(new math_vector_Vector2(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new math_vector_Vector2(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let a=this._points[this._points.length-1],n=new math_vector_Vector2(e,t),o=new math_vector_Vector2(i,r),l=new Arc2(a,n,o),h=l.angle.radians()/s;l.orientation===el.CW&&(h*=-1);let c=l.startAngle.radians()+h;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r,a=this._points[this._points.length-1];for(let n=0;n<=s;n++){let o=n/s,l=equation(o,a.x,e,i),h=equation(o,a.y,t,r);this.addLineTo(l,h)}return this}addBezierCurveTo(e,t,i,r,s,a,n=36){if(this.closed)return this;let equation=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s,o=this._points[this._points.length-1];for(let l=0;l<=n;l++){let h=l/n,c=equation(h,o.x,e,i,s),u=equation(h,o.y,t,r,a);this.addLineTo(c,u)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(o<0&&(i=this._points[s],n=-n,a=this._points[r],o=-o),e.ya.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{let r=o*(e.x-i.x)-n*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(a.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=a.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r1)return math_vector_Vector2.Zero();let t=e*this.length(),i=0;for(let e=0;e=i&&t<=o){let e=n.normalize(),r=t-i;return new math_vector_Vector2(s.x+e.x*r,s.y+e.y*r)}i=o}return math_vector_Vector2.Zero()}static StartingAt(e,t){return new math_path_Path2(e,t)}};let Path3D=class Path3D{constructor(e,t=null,i,r=!1){this.path=e,this._curve=[],this._distances=[],this._tangents=[],this._normals=[],this._binormals=[],this._pointAtData={id:0,point:math_vector_Vector3.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:math_vector_Matrix.Identity()};for(let t=0;tt){let i=e;e=t,t=i}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),a=this.getPointAt(t),n=this.getPreviousPointIndexAt(t)+1,o=[];return 0!==e&&(s++,o.push(r)),o.push(...i.slice(s,n)),(1!==t||1===e)&&o.push(a),new Path3D(o,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i;let r=e.length();if(0===r&&(r=1),null==t){let t;t=math_scalar_Scalar.WithinEpsilon(Math.abs(e.y)/r,1,.001)?math_scalar_Scalar.WithinEpsilon(Math.abs(e.x)/r,1,.001)?math_scalar_Scalar.WithinEpsilon(Math.abs(e.z)/r,1,.001)?math_vector_Vector3.Zero():new math_vector_Vector3(0,0,1):new math_vector_Vector3(1,0,0):new math_vector_Vector3(0,-1,0),i=math_vector_Vector3.Cross(e,t)}else i=math_vector_Vector3.Cross(e,t),math_vector_Vector3.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){let i;if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let r=this.getPoints();if(e<=0)return this._setPointAtData(0,0,r[0],0,t);if(e>=1)return this._setPointAtData(1,1,r[r.length-1],r.length-1,t);let s=r[0],a=0,n=e*this.length();for(let o=1;on){let r=a-n,h=r/l,c=s.subtract(i),u=i.add(c.scaleInPlace(h));return this._setPointAtData(e,1-h,u,o-1,t)}s=i}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=math_vector_Matrix.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),a=this._tangents[t].clone(),n=this._normals[t].clone(),o=this._binormals[t].clone(),l=math_vector_Quaternion.RotationQuaternionFromAxis(r,s,i),h=math_vector_Quaternion.RotationQuaternionFromAxis(n,o,a),c=math_vector_Quaternion.Slerp(l,h,this._pointAtData.subPosition);c.toRotationMatrix(this._pointAtData.interpolationMatrix)}}};let Curve3=class Curve3{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;let s=[],equation=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let a=0;a<=r;a++)s.push(new math_vector_Vector3(equation(a/r,e.x,t.x,i.x),equation(a/r,e.y,t.y,i.y),equation(a/r,e.z,t.z,i.z)));return new Curve3(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;let a=[],equation=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let n=0;n<=s;n++)a.push(new math_vector_Vector3(equation(n/s,e.x,t.x,i.x,r.x),equation(n/s,e.y,t.y,i.y,r.y),equation(n/s,e.z,t.z,i.z,r.z)));return new Curve3(a)}static CreateHermiteSpline(e,t,i,r,s){let a=[],n=1/s;for(let o=0;o<=s;o++)a.push(math_vector_Vector3.Hermite(e,t,i,r,o*n));return new Curve3(a)}static CreateCatmullRomSpline(e,t,i){let r=[],s=1/t,a=0;if(i){let i=e.length;for(let n=0;n=.5?(1-this.easeInCore((1-e)*2))*.5+.5:.5*this.easeInCore(2*e)}};EasingFunction.EASINGMODE_EASEIN=0,EasingFunction.EASINGMODE_EASEOUT=1,EasingFunction.EASINGMODE_EASEINOUT=2;let CircleEase=class CircleEase extends EasingFunction{easeInCore(e){return 1-Math.sqrt(1-(e=Math.max(0,Math.min(1,e)))*e)}};let BackEase=class BackEase extends EasingFunction{constructor(e=1){super(),this.amplitude=e}easeInCore(e){let t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}};let ExponentialEase=class ExponentialEase extends EasingFunction{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)}};let QuadraticEase=class QuadraticEase extends EasingFunction{easeInCore(e){return e*e}};let SineEase=class SineEase extends EasingFunction{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}};let TargetedAnimation=class TargetedAnimation{getClassName(){return"TargetedAnimation"}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}};let AnimationGroup=class AnimationGroup{syncWithMask(){if(!this.mask){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;ea&&(a=t.to);let n=new AnimationGroup(e[0].name+"_merged",e[0]._scene,r);for(let r of e){for(let e of(i&&r.normalize(s,a),r.targetedAnimations))n.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return n}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=[],this._animatables=[],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._parentContainer=null,this.onAnimationEndObservable=new observable_Observable,this.onAnimationLoopObservable=new observable_Observable,this.onAnimationGroupLoopObservable=new observable_Observable,this.onAnimationGroupEndObservable=new observable_Observable,this.onAnimationGroupPauseObservable=new observable_Observable,this.onAnimationGroupPlayObservable=new observable_Observable,this.metadata=null,this._animationLoopFlags=[],this._scene=t||engineStore_EngineStore.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new TargetedAnimation;i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-1;t--){let i=this._targetedAnimations[t];i.animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){let t={frame:e,value:a.value,inTangent:a.inTangent,outTangent:a.outTangent,interpolation:a.interpolation};s.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount!==this._numActiveAnimatables||(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let a=0;a{this.onAnimationEndObservable.notifyObservers(n),this._checkAnimationGroupEnded(o)},this._processLoop(o,n,a),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;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){let 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){let t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){let r=new AnimationGroup(e||this.name,this._scene,this._weight,this._playOrder);for(let e of(r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask,this._targetedAnimations))r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){let 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;tn[0].frame&&(e=n[0].frame),t=t&&e<=i||s&&r.frame>=t&&r.frame<=i){let e={frame:r.frame,value:r.value.clone?r.value.clone():r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation,lockedTangent:r.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}if(0===u.length){o.splice(e,1),e--;continue}a>u[0].frame&&(a=u[0].frame),n{r.value=void 0,t(r)},i):t(r)}catch(e){i(e)}}function createYieldingScheduler(e=25){let t;return(i,r,s)=>{let a=performance.now();void 0===t||a-t>e?(t=a,setTimeout(()=>{inlineScheduler(i,r,s)},0)):inlineScheduler(i,r,s)}}function runCoroutine(e,t,i,r,s){let resume=()=>{let a;let onStep=e=>{e.done?i(e.value):void 0===a?a=!0:resume()};do a=void 0,s&&s.aborted?r(Error("Aborted")):t(e,onStep,r),void 0===a&&(a=!1);while(a)};resume()}function runCoroutineSync(e,t){let i;return runCoroutine(e,inlineScheduler,e=>i=e,e=>{throw e},t),i}function runCoroutineAsync(e,t,i){return new Promise((r,s)=>{runCoroutine(e,t,r,s,i)})}function makeSyncFunction(e,t){return(...i)=>runCoroutineSync(e(...i),t)}!function(e){e[e.Include=0]="Include",e[e.Exclude=1]="Exclude"}(eh||(eh={}));let math_viewport_Viewport=class math_viewport_Viewport{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new math_viewport_Viewport(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new math_viewport_Viewport(this.x,this.y,this.width,this.height)}};let camera_Camera=class camera_Camera extends node_Node{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,r;let s=0,a=0;if(this.mode===camera_Camera.PERSPECTIVE_CAMERA)this.fovMode===camera_Camera.FOVMODE_VERTICAL_FIXED?(a=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*a):a=(s=2*this.minZ*Math.tan(this.fov/2))/this.getEngine().getAspectRatio(this);else{let n=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:n)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-n),a=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(r=this.orthoBottom)&&void 0!==r?r:-o)}return s*a}set orthoLeft(e){for(let t of(this._orthoLeft=e,this._rigCameras))t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){for(let t of(this._orthoRight=e,this._rigCameras))t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){for(let t of(this._orthoBottom=e,this._rigCameras))t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){for(let t of(this._orthoTop=e,this._rigCameras))t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){for(let t of(this._mode=e,this._rigCameras))t.mode=e}get mode(){return this._mode}constructor(e,t,i,r=!0){super(e,i),this._position=math_vector_Vector3.Zero(),this._upVector=math_vector_Vector3.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=camera_Camera.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new math_viewport_Viewport(0,0,1,1),this.layerMask=268435455,this.fovMode=camera_Camera.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=camera_Camera.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new observable_Observable,this.onProjectionMatrixChangedObservable=new observable_Observable,this.onAfterCheckInputsObservable=new observable_Observable,this.onRestoreStateObservable=new observable_Observable,this.isRigCamera=!1,this._rigCameras=[],this._skipRendering=!1,this._projectionMatrix=new math_vector_Matrix,this._postProcesses=[],this._activeMeshes=new SmartArray(256),this._globalPosition=math_vector_Vector3.Zero(),this._computedViewMatrix=math_vector_Matrix.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=math_vector_Matrix.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=math_vector_Quaternion.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!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}_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 i=0;i-1?(logger_Logger.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){let 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 math_vector_Matrix.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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){var t,i,r,s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x;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;let b=this.getEngine(),T=this.getScene(),S=b.useReverseDepthBuffer;if(this.mode===camera_Camera.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=b.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),(T.useRightHandedSystem?math_vector_Matrix.PerspectiveFovRHToRef:math_vector_Matrix.PerspectiveFovLHToRef)(this.fov,b.getAspectRatio(this),S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===camera_Camera.FOVMODE_VERTICAL_FIXED,b.isNDCHalfZRange,this.projectionPlaneTilt,S);else{let e=b.getRenderWidth()/2,C=b.getRenderHeight()/2;T.useRightHandedSystem?this.oblique?math_vector_Matrix.ObliqueOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(r=this.orthoBottom)&&void 0!==r?r:-C,null!==(s=this.orthoTop)&&void 0!==s?s:C,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,b.isNDCHalfZRange):math_vector_Matrix.OrthoOffCenterRHToRef(null!==(a=this.orthoLeft)&&void 0!==a?a:-e,null!==(n=this.orthoRight)&&void 0!==n?n:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-C,null!==(l=this.orthoTop)&&void 0!==l?l:C,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,b.isNDCHalfZRange):this.oblique?math_vector_Matrix.ObliqueOffCenterLHToRef(null!==(h=this.orthoLeft)&&void 0!==h?h:-e,null!==(c=this.orthoRight)&&void 0!==c?c:e,null!==(u=this.orthoBottom)&&void 0!==u?u:-C,null!==(d=this.orthoTop)&&void 0!==d?d:C,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,b.isNDCHalfZRange):math_vector_Matrix.OrthoOffCenterLHToRef(null!==(_=this.orthoLeft)&&void 0!==_?_:-e,null!==(p=this.orthoRight)&&void 0!==p?p:e,null!==(f=this.orthoBottom)&&void 0!==f?f:-C,null!==(m=this.orthoTop)&&void 0!==m?m:C,S?this.maxZ:this.minZ,S?this.minZ:this.maxZ,this._projectionMatrix,b.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=null===(g=this.oblique)||void 0===g?void 0:g.angle,this._cache.obliqueLength=null===(v=this.oblique)||void 0===v?void 0:v.length,this._cache.obliqueOffset=null===(x=this.oblique)||void 0===x?void 0:x.offset,this._cache.renderWidth=b.getRenderWidth(),this._cache.renderHeight=b.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?math_vector_Vector3.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?Frustum.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=Frustum.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),!t||!(this.rigCameras.length>0))return e.isInFrustum(this._frustumPlanes);{let t=!1;return this.rigCameras.forEach(i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)}),t}}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw _WarnImport("Ray")}getForwardRayToRef(e,t=100,i,r){throw _WarnImport("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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){let 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!==camera_Camera.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){let t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=tools_Tools.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==camera_Camera.RIG_MODE_NONE){let e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);let 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 math_vector_Matrix.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=tools_Tools.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;ecamera_Camera._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=camera_Camera.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),s=decorators_SerializationHelper.Parse(r,e,t);if(void 0!==e.parentId&&(s._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(s._waitingParentInstanceIndex=e.parentInstanceIndex),s.inputs&&(s.inputs.parse(e),s._setupInputs()),e.upVector&&(s.upVector=math_vector_Vector3.FromArray(e.upVector)),s.setPosition&&(s.position.copyFromFloats(0,0,0),s.setPosition(math_vector_Vector3.FromArray(e.position))),e.target&&s.setTarget&&s.setTarget(math_vector_Vector3.FromArray(e.target)),e.cameraRigMode){let t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};s.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;tthis.parent._getWorldMatrixDeterminant()&&(e*=-1),e}};camera_Camera._CreateDefaultParsedCamera=(e,t)=>{throw _WarnImport("UniversalCamera")},camera_Camera.PERSPECTIVE_CAMERA=0,camera_Camera.ORTHOGRAPHIC_CAMERA=1,camera_Camera.FOVMODE_VERTICAL_FIXED=0,camera_Camera.FOVMODE_HORIZONTAL_FIXED=1,camera_Camera.RIG_MODE_NONE=0,camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED=14,camera_Camera.RIG_MODE_VR=20,camera_Camera.RIG_MODE_CUSTOM=22,camera_Camera.ForceAttachControlToAlwaysPreventDefault=!1,__decorate([serializeAsVector3("position")],camera_Camera.prototype,"_position",void 0),__decorate([serializeAsVector3("upVector")],camera_Camera.prototype,"_upVector",void 0),__decorate([serialize()],camera_Camera.prototype,"orthoLeft",null),__decorate([serialize()],camera_Camera.prototype,"orthoRight",null),__decorate([serialize()],camera_Camera.prototype,"orthoBottom",null),__decorate([serialize()],camera_Camera.prototype,"orthoTop",null),__decorate([serialize()],camera_Camera.prototype,"fov",void 0),__decorate([serialize()],camera_Camera.prototype,"projectionPlaneTilt",void 0),__decorate([serialize()],camera_Camera.prototype,"minZ",void 0),__decorate([serialize()],camera_Camera.prototype,"maxZ",void 0),__decorate([serialize()],camera_Camera.prototype,"inertia",void 0),__decorate([serialize()],camera_Camera.prototype,"mode",null),__decorate([serialize()],camera_Camera.prototype,"layerMask",void 0),__decorate([serialize()],camera_Camera.prototype,"fovMode",void 0),__decorate([serialize()],camera_Camera.prototype,"cameraRigMode",void 0),__decorate([serialize()],camera_Camera.prototype,"interaxialDistance",void 0),__decorate([serialize()],camera_Camera.prototype,"isStereoscopicSideBySide",void 0);let IntersectionInfo=class IntersectionInfo{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}};let boundingBox_BoundingBox=class boundingBox_BoundingBox{constructor(e,t,i){this.vectors=arrayTools_ArrayTools.BuildArray(8,math_vector_Vector3.Zero),this.center=math_vector_Vector3.Zero(),this.centerWorld=math_vector_Vector3.Zero(),this.extendSize=math_vector_Vector3.Zero(),this.extendSizeWorld=math_vector_Vector3.Zero(),this.directions=arrayTools_ArrayTools.BuildArray(3,math_vector_Vector3.Zero),this.vectorsWorld=arrayTools_ArrayTools.BuildArray(8,math_vector_Vector3.Zero),this.minimumWorld=math_vector_Vector3.Zero(),this.maximumWorld=math_vector_Vector3.Zero(),this.minimum=math_vector_Vector3.Zero(),this.maximum=math_vector_Vector3.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){let r=e.x,s=e.y,a=e.z,n=t.x,o=t.y,l=t.z,h=this.vectors;this.minimum.copyFromFloats(r,s,a),this.maximum.copyFromFloats(n,o,l),h[0].copyFromFloats(r,s,a),h[1].copyFromFloats(n,o,l),h[2].copyFromFloats(n,s,a),h[3].copyFromFloats(r,o,a),h[4].copyFromFloats(r,s,l),h[5].copyFromFloats(n,o,a),h[6].copyFromFloats(r,o,l),h[7].copyFromFloats(n,s,l),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||math_vector_Matrix.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){let t=boundingBox_BoundingBox._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,a=i.scaleInPlace(.5*s),n=this.center.subtractToRef(a,t[1]),o=this.center.addToRef(a,t[2]);return this.reConstruct(n,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,s=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)s[e].copyFrom(a[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){let n=s[r];math_vector_Vector3.TransformCoordinatesToRef(a[r],e,n),t.minimizeInPlace(n),i.maximizeInPlace(n)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}math_vector_Vector3.FromArrayToRef(e.m,0,r[0]),math_vector_Vector3.FromArrayToRef(e.m,4,r[1]),math_vector_Vector3.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return boundingBox_BoundingBox.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return boundingBox_BoundingBox.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,n=i.x,o=i.y,l=i.z,h=e.x,c=e.y,u=e.z;return!(n-h<-.001)&&!(-.001>h-r)&&!(o-c<-.001)&&!(-.001>c-s)&&!(l-u<-.001)&&!(-.001>u-a)}intersectsSphere(e){return boundingBox_BoundingBox.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,a=i.y,n=i.z,o=r.x,l=r.y,h=r.z,c=e.x,u=e.y,d=e.z,_=t.x,p=t.y,f=t.z;return!(o_)&&!(lp)&&!(hf)}dispose(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){let s=boundingBox_BoundingBox._TmpVector3[0];math_vector_Vector3.ClampToRef(i,e,t,s);let a=math_vector_Vector3.DistanceSquared(i,s);return a<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let t=0;t<8;++t)if(0>r.dotCoordinate(e[t]))return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}};boundingBox_BoundingBox._TmpVector3=arrayTools_ArrayTools.BuildArray(3,math_vector_Vector3.Zero);let boundingSphere_BoundingSphere=class boundingSphere_BoundingSphere{constructor(e,t,i){this.center=math_vector_Vector3.Zero(),this.centerWorld=math_vector_Vector3.Zero(),this.minimum=math_vector_Vector3.Zero(),this.maximum=math_vector_Vector3.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);let r=math_vector_Vector3.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||math_vector_Matrix.IdentityReadOnly)}scale(e){let t=this.radius*e,i=boundingSphere_BoundingSphere._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{math_vector_Vector3.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=boundingSphere_BoundingSphere._TmpVector3[0];math_vector_Vector3.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){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(0>e[i].dotCoordinate(t))return!1;return!0}intersectsPoint(e){let t=math_vector_Vector3.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld{let r=math_vector_Vector3.Dot(t.centerWorld,e),s=Math.abs(math_vector_Vector3.Dot(t.directions[0],e))*t.extendSize.x,a=Math.abs(math_vector_Vector3.Dot(t.directions[1],e))*t.extendSize.y,n=Math.abs(math_vector_Vector3.Dot(t.directions[2],e))*t.extendSize.z,o=s+a+n;i.min=r-o,i.max=r+o},axisOverlap=(e,t,i)=>(computeBoxExtents(e,t,O),computeBoxExtents(e,i,B),!(O.min>B.max||B.min>O.max));let boundingInfo_BoundingInfo=class boundingInfo_BoundingInfo{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new boundingBox_BoundingBox(e,t,i),this.boundingSphere=new boundingSphere_BoundingSphere(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}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){let i=boundingInfo_BoundingInfo._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=boundingInfo_BoundingInfo._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let t=math_vector_Vector3.Minimize(this.minimum,e),i=math_vector_Vector3.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){let t=math_vector_TmpVectors.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let i=math_vector_TmpVectors.Vector3[0];return math_vector_Vector3.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),math_vector_Vector3.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!!((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(1===t||3===t||this.boundingBox.isInFrustum(e))}get diagonalLength(){let e=this.boundingBox,t=e.maximumWorld.subtractToRef(e.minimumWorld,boundingInfo_BoundingInfo._TmpVector3[0]);return t.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(!boundingSphere_BoundingSphere.Intersects(this.boundingSphere,e.boundingSphere)||!boundingBox_BoundingBox.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!!(axisOverlap(i.directions[0],i,r)&&axisOverlap(i.directions[1],i,r)&&axisOverlap(i.directions[2],i,r)&&axisOverlap(r.directions[0],i,r)&&axisOverlap(r.directions[1],i,r)&&axisOverlap(r.directions[2],i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[0],r.directions[0]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[0],r.directions[1]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[0],r.directions[2]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[1],r.directions[0]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[1],r.directions[1]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[1],r.directions[2]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[2],r.directions[0]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[2],r.directions[1]),i,r)&&axisOverlap(math_vector_Vector3.Cross(i.directions[2],r.directions[2]),i,r))}};boundingInfo_BoundingInfo._TmpVector3=arrayTools_ArrayTools.BuildArray(2,math_vector_Vector3.Zero);let MathHelpers=class MathHelpers{static extractMinAndMaxIndexed(e,t,i,r,s,a){for(let n=i;n!Array.isArray(e)&&!Array.isArray(t))],MathHelpers,"extractMinAndMaxIndexed",null),__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],MathHelpers,"extractMinAndMax",null);let subMesh_SubMesh=class subMesh_SubMesh{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines}set materialDefines(e){var t;let i=null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0);i.defines=e}_getDrawWrapper(e,t=!1){e=null!=e?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new drawWrapper_DrawWrapper(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null}get _drawWrapper(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e){this._removeDrawWrapper(e);return}for(let e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,a,n,o=!0){return new subMesh_SubMesh(e,t,i,r,s,a,n,o)}constructor(e,t,i,r,s,a,n,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,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=a,this._renderingMesh=n||a,l&&a.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=a.subMeshes.length-1,o&&(this.refreshBoundingInfo(),a.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(){let e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var t;let i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){let e=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return i}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){let t;if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(buffer_VertexBuffer.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){let e=this._renderingMesh.getBoundingInfo();t={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else t=extractMinAndMaxIndexed(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new boundingInfo_BoundingInfo(t.minimum,t.maximum),this}_checkCollision(e){let t=this.getBoundingInfo();return t._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){let t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){let 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){let i=[];for(let t=this.indexStart;to&&(o=t)}return new subMesh_SubMesh(e,n,o-n+1,t,i,r,s,a)}};let VertexDataMaterialInfo=class VertexDataMaterialInfo{};let mesh_vertexData_VertexData=class mesh_vertexData_VertexData{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=makeSyncFunction(this._applyToCoroutine.bind(this)),this.uniqueId=mesh_vertexData_VertexData._UniqueIDGenerator,mesh_vertexData_VertexData._UniqueIDGenerator++}set(e,t){switch(e.length||logger_Logger.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case buffer_VertexBuffer.PositionKind:this.positions=e;break;case buffer_VertexBuffer.NormalKind:this.normals=e;break;case buffer_VertexBuffer.TangentKind:this.tangents=e;break;case buffer_VertexBuffer.UVKind:this.uvs=e;break;case buffer_VertexBuffer.UV2Kind:this.uvs2=e;break;case buffer_VertexBuffer.UV3Kind:this.uvs3=e;break;case buffer_VertexBuffer.UV4Kind:this.uvs4=e;break;case buffer_VertexBuffer.UV5Kind:this.uvs5=e;break;case buffer_VertexBuffer.UV6Kind:this.uvs6=e;break;case buffer_VertexBuffer.ColorKind:this.colors=e;break;case buffer_VertexBuffer.MatricesIndicesKind:this.matricesIndices=e;break;case buffer_VertexBuffer.MatricesWeightsKind:this.matricesWeights=e;break;case buffer_VertexBuffer.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case buffer_VertexBuffer.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,i){if(this.positions&&(e.setVerticesData(buffer_VertexBuffer.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(buffer_VertexBuffer.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(buffer_VertexBuffer.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(buffer_VertexBuffer.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(buffer_VertexBuffer.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(buffer_VertexBuffer.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(buffer_VertexBuffer.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(buffer_VertexBuffer.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(buffer_VertexBuffer.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(buffer_VertexBuffer.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1)for(let t of(e.subMeshes=[],this.materialInfos))new subMesh_SubMesh(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,e);return this}_update(e,t,i){return this.positions&&e.updateVerticesData(buffer_VertexBuffer.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(buffer_VertexBuffer.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(buffer_VertexBuffer.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(buffer_VertexBuffer.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(buffer_VertexBuffer.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(buffer_VertexBuffer.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(buffer_VertexBuffer.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(buffer_VertexBuffer.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(buffer_VertexBuffer.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(buffer_VertexBuffer.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(buffer_VertexBuffer.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(buffer_VertexBuffer.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1];for(let n=i;ne.determinant();return this.positions&&mesh_vertexData_VertexData._TransformVector3Coordinates(this.positions,e),this.normals&&mesh_vertexData_VertexData._TransformVector3Normals(this.normals,e),this.tangents&&mesh_vertexData_VertexData._TransformVector4Normals(this.tangents,e),t&&this.indices&&mesh_vertexData_VertexData._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];let e=[];for(let t of this.materialInfos){let i=new mesh_vertexData_VertexData;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let e=t.indexStart;e({vertexData:e})):[{vertexData:e}];return runCoroutineSync(this._mergeCoroutine(void 0,a,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,n=!1){var o,l,h,c;this._validate();let u=t.map(e=>e.vertexData),d=this;for(let e of u)if(e){if(e._validate(),n)!this.normals!=!e.normals&&(this.normals?e.normals=new Float32Array(e.positions.length):this.normals=new Float32Array(this.positions.length)),!this.tangents!=!e.tangents&&(this.tangents?e.tangents=new Float32Array(e.positions.length/3*4):this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs!=!e.uvs&&(this.uvs?e.uvs=new Float32Array(e.positions.length/3*2):this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2!=!e.uvs2&&(this.uvs2?e.uvs2=new Float32Array(e.positions.length/3*2):this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3!=!e.uvs3&&(this.uvs3?e.uvs3=new Float32Array(e.positions.length/3*2):this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4!=!e.uvs4&&(this.uvs4?e.uvs4=new Float32Array(e.positions.length/3*2):this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5!=!e.uvs5&&(this.uvs5?e.uvs5=new Float32Array(e.positions.length/3*2):this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6!=!e.uvs6&&(this.uvs6?e.uvs6=new Float32Array(e.positions.length/3*2):this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors!=!e.colors&&(this.colors?(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)):(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1))),!this.matricesIndices!=!e.matricesIndices&&(this.matricesIndices?e.matricesIndices=new Float32Array(e.positions.length/3*4):this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights!=!e.matricesWeights&&(this.matricesWeights?e.matricesWeights=new Float32Array(e.positions.length/3*4):this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra!=!e.matricesIndicesExtra&&(this.matricesIndicesExtra?e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4):this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra!=!e.matricesWeightsExtra&&(this.matricesWeightsExtra?e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4):this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4));else if(!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 Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let i=0,r=0,s=0,a=[],n=null,o=[];for(let t of this.splitBasedOnMaterialID())o.push({vertexData:t,transform:e});for(let e of t)if(e.vertexData)for(let t of e.vertexData.splitBasedOnMaterialID())o.push({vertexData:t,transform:e.transform});for(let e of(o.sort((e,t)=>{let i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}),o)){let t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,n&&n.materialIndex===i)n.indexCount+=t.indices.length,n.verticesCount+=t.positions.length/3;else{let e=new VertexDataMaterialInfo;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,a.push(e),n=e}r+=t.indices.length,s+=t.positions.length/3}let l=o.splice(0,1)[0];d=l.vertexData,e=l.transform,u=o.map(e=>e.vertexData),t=o,this.materialInfos=a}let _=u.reduce((e,t)=>{var i,r;return e+(null!==(r=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==r?r:0)},null!==(l=null===(o=d.indices)||void 0===o?void 0:o.length)&&void 0!==l?l:0),p=s||u.some(e=>e.indices===d.indices),f=p?null===(h=d.indices)||void 0===h?void 0:h.slice():d.indices;if(_>0){let s=null!==(c=null==f?void 0:f.length)&&void 0!==c?c:0;if(f||(f=Array(_)),f.length!==_){if(Array.isArray(f))f.length=_;else{let e=i||f instanceof Uint32Array?new Uint32Array(_):new Uint16Array(_);e.set(f),f=e}e&&0>e.determinant()&&mesh_vertexData_VertexData._FlipFaces(f,0,s)}let a=d.positions?d.positions.length/3:0;for(let{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;ti.determinant()&&mesh_vertexData_VertexData._FlipFaces(f,s,e.indices.length),a+=e.positions.length/3,s+=e.indices.length,r&&(yield)}}return this.indices=f,this.positions=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.PositionKind,d.positions,e,t.map(e=>[e.vertexData.positions,e.transform])),r&&(yield),d.normals&&(this.normals=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.NormalKind,d.normals,e,t.map(e=>[e.vertexData.normals,e.transform])),r&&(yield)),d.tangents&&(this.tangents=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.TangentKind,d.tangents,e,t.map(e=>[e.vertexData.tangents,e.transform])),r&&(yield)),d.uvs&&(this.uvs=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UVKind,d.uvs,e,t.map(e=>[e.vertexData.uvs,e.transform])),r&&(yield)),d.uvs2&&(this.uvs2=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV2Kind,d.uvs2,e,t.map(e=>[e.vertexData.uvs2,e.transform])),r&&(yield)),d.uvs3&&(this.uvs3=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV3Kind,d.uvs3,e,t.map(e=>[e.vertexData.uvs3,e.transform])),r&&(yield)),d.uvs4&&(this.uvs4=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV4Kind,d.uvs4,e,t.map(e=>[e.vertexData.uvs4,e.transform])),r&&(yield)),d.uvs5&&(this.uvs5=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV5Kind,d.uvs5,e,t.map(e=>[e.vertexData.uvs5,e.transform])),r&&(yield)),d.uvs6&&(this.uvs6=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.UV6Kind,d.uvs6,e,t.map(e=>[e.vertexData.uvs6,e.transform])),r&&(yield)),d.colors&&(this.colors=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.ColorKind,d.colors,e,t.map(e=>[e.vertexData.colors,e.transform])),r&&(yield)),d.matricesIndices&&(this.matricesIndices=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesIndicesKind,d.matricesIndices,e,t.map(e=>[e.vertexData.matricesIndices,e.transform])),r&&(yield)),d.matricesWeights&&(this.matricesWeights=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesWeightsKind,d.matricesWeights,e,t.map(e=>[e.vertexData.matricesWeights,e.transform])),r&&(yield)),d.matricesIndicesExtra&&(this.matricesIndicesExtra=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesIndicesExtraKind,d.matricesIndicesExtra,e,t.map(e=>[e.vertexData.matricesIndicesExtra,e.transform])),r&&(yield)),d.matricesWeightsExtra&&(this.matricesWeightsExtra=mesh_vertexData_VertexData._MergeElement(buffer_VertexBuffer.MatricesWeightsExtraKind,d.matricesWeightsExtra,e,t.map(e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(e=>null!==e[0]&&void 0!==e[0]);if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((e,t)=>e+t[0].length,t.length),n=e===buffer_VertexBuffer.PositionKind?mesh_vertexData_VertexData._TransformVector3Coordinates:e===buffer_VertexBuffer.NormalKind?mesh_vertexData_VertexData._TransformVector3Normals:e===buffer_VertexBuffer.TangentKind?mesh_vertexData_VertexData._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let e=new Float32Array(a);e.set(t),i&&n(e,i,0,t.length);let r=t.length;for(let[t,i]of s)e.set(t,r),i&&n(e,i,r,t.length),r+=t.length;return e}{let e=Array(a);for(let i=0;i{let i=buffer_VertexBuffer.DeduceStride(e);if(t.length%i!=0)throw Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},e=getElementCount(buffer_VertexBuffer.PositionKind,this.positions),validateElementCount=(t,i)=>{let r=getElementCount(t,i);if(r!==e)throw Error("The "+t+"s element count ("+r+") does not match the positions count ("+e+")")};this.normals&&validateElementCount(buffer_VertexBuffer.NormalKind,this.normals),this.tangents&&validateElementCount(buffer_VertexBuffer.TangentKind,this.tangents),this.uvs&&validateElementCount(buffer_VertexBuffer.UVKind,this.uvs),this.uvs2&&validateElementCount(buffer_VertexBuffer.UV2Kind,this.uvs2),this.uvs3&&validateElementCount(buffer_VertexBuffer.UV3Kind,this.uvs3),this.uvs4&&validateElementCount(buffer_VertexBuffer.UV4Kind,this.uvs4),this.uvs5&&validateElementCount(buffer_VertexBuffer.UV5Kind,this.uvs5),this.uvs6&&validateElementCount(buffer_VertexBuffer.UV6Kind,this.uvs6),this.colors&&validateElementCount(buffer_VertexBuffer.ColorKind,this.colors),this.matricesIndices&&validateElementCount(buffer_VertexBuffer.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&validateElementCount(buffer_VertexBuffer.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&validateElementCount(buffer_VertexBuffer.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&validateElementCount(buffer_VertexBuffer.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return mesh_vertexData_VertexData.Parse(e)}serialize(){let 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)),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)for(let t of(e.materialInfos=[],this.materialInfos)){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}return e}static ExtractFromMesh(e,t,i){return mesh_vertexData_VertexData._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return mesh_vertexData_VertexData._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new mesh_vertexData_VertexData;return e.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)&&(r.positions=e.getVerticesData(buffer_VertexBuffer.PositionKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&(r.normals=e.getVerticesData(buffer_VertexBuffer.NormalKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)&&(r.tangents=e.getVerticesData(buffer_VertexBuffer.TangentKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(r.uvs=e.getVerticesData(buffer_VertexBuffer.UVKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(r.uvs2=e.getVerticesData(buffer_VertexBuffer.UV2Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV3Kind)&&(r.uvs3=e.getVerticesData(buffer_VertexBuffer.UV3Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV4Kind)&&(r.uvs4=e.getVerticesData(buffer_VertexBuffer.UV4Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV5Kind)&&(r.uvs5=e.getVerticesData(buffer_VertexBuffer.UV5Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.UV6Kind)&&(r.uvs6=e.getVerticesData(buffer_VertexBuffer.UV6Kind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)&&(r.colors=e.getVerticesData(buffer_VertexBuffer.ColorKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw _WarnImport("ribbonBuilder")}static CreateBox(e){throw _WarnImport("boxBuilder")}static CreateTiledBox(e){throw _WarnImport("tiledBoxBuilder")}static CreateTiledPlane(e){throw _WarnImport("tiledPlaneBuilder")}static CreateSphere(e){throw _WarnImport("sphereBuilder")}static CreateCylinder(e){throw _WarnImport("cylinderBuilder")}static CreateTorus(e){throw _WarnImport("torusBuilder")}static CreateLineSystem(e){throw _WarnImport("linesBuilder")}static CreateDashedLines(e){throw _WarnImport("linesBuilder")}static CreateGround(e){throw _WarnImport("groundBuilder")}static CreateTiledGround(e){throw _WarnImport("groundBuilder")}static CreateGroundFromHeightMap(e){throw _WarnImport("groundBuilder")}static CreatePlane(e){throw _WarnImport("planeBuilder")}static CreateDisc(e){throw _WarnImport("discBuilder")}static CreatePolygon(e,t,i,r,s,a,n){throw _WarnImport("polygonBuilder")}static CreateIcoSphere(e){throw _WarnImport("icoSphereBuilder")}static CreatePolyhedron(e){throw _WarnImport("polyhedronBuilder")}static CreateCapsule(e={orientation:math_vector_Vector3.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw _WarnImport("capsuleBuilder")}static CreateTorusKnot(e){throw _WarnImport("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let s=0,a=0,n=0,o=0,l=0,h=0,c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=0,v=0,x=0,b=0,T=0,S=0,C=0,E=!1,y=!1,R=!1,P=!1,A=1,M=0,I=null;r&&(E=!!r.facetNormals,y=!!r.facetPositions,R=!!r.facetPartitioning,A=!0===r.useRightHandedSystem?-1:1,M=r.ratio||0,P=!!r.depthSort,I=r.distanceTo,P&&void 0===I&&(I=math_vector_Vector3.Zero()));let D=0,O=0,B=0,N=0;for(R&&r&&r.bbSize&&(D=r.subDiv.X*M/r.bbSize.x,O=r.subDiv.Y*M/r.bbSize.y,B=r.subDiv.Z*M/r.bbSize.z,N=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),s=0;s!Array.isArray(e))],mesh_vertexData_VertexData,"_TransformVector3Coordinates",null),__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],mesh_vertexData_VertexData,"_TransformVector3Normals",null),__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],mesh_vertexData_VertexData,"_TransformVector4Normals",null),__decorate([nativeOverride.filter((...[e])=>!Array.isArray(e))],mesh_vertexData_VertexData,"_FlipFaces",null);let SceneLoaderFlags=class SceneLoaderFlags{static get ForceFullSceneLoadingForIncremental(){return SceneLoaderFlags._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){SceneLoaderFlags._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return SceneLoaderFlags._ShowLoadingScreen}static set ShowLoadingScreen(e){SceneLoaderFlags._ShowLoadingScreen=e}static get loggingLevel(){return SceneLoaderFlags._LoggingLevel}static set loggingLevel(e){SceneLoaderFlags._LoggingLevel=e}static get CleanBoneMatrixWeights(){return SceneLoaderFlags._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){SceneLoaderFlags._CleanBoneMatrixWeights=e}};SceneLoaderFlags._ForceFullSceneLoadingForIncremental=!1,SceneLoaderFlags._ShowLoadingScreen=!0,SceneLoaderFlags._CleanBoneMatrixWeights=!1,SceneLoaderFlags._LoggingLevel=0;let CompatibilityOptions=class CompatibilityOptions{};CompatibilityOptions.UseOpenGLOrientationForUV=!1;let Geometry=class Geometry{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){let t=new Geometry(Geometry.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){if(this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||engineStore_EngineStore.LastCreatedScene,!this._scene)return;this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){for(let t of(this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects(),this._meshes))t._markSubMeshesAsAttributesDirty()}load(e,t){if(2!==this.delayLoadState){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t;let i=new mesh_vertexData_VertexData;i.indices=[];let r=this.getIndices();if(r)for(let e=0;e0){let r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){let r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){let r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){let r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(CompatibilityOptions.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){let r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){let r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){let r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,i,e.matricesIndices._updatable)}}if(e.matricesIndicesExtra){if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{let i=[];for(let t=0;t>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}}e.matricesWeights&&(Geometry._CleanMatricesWeights(e,t),t.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{let r=t.getScene().getLastSkeletonById(e.skeletonId);if(!r)return;i=r.bones.length}let r=t.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),s=t.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind),a=e.matricesWeights,n=e.matricesWeightsExtra,o=e.numBoneInfluencer,l=a.length;for(let e=0;eo-1)&&(l=o-1),t>.001){let i=1/t;for(let t=0;t<4;t++)a[e+t]*=i;if(n)for(let t=0;t<4;t++)n[e+t]*=i}else l>=4?(n[e+l-4]=1-t,s[e+l-4]=i):(a[e+l]=1-t,r[e+l]=i)}t.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind,s)}static Parse(e,t,i){let r=new Geometry(e.id,t,void 0,e.updatable);return r._loadedUniqueId=e.uniqueId,Tags&&Tags.AddTagsTo(r,e.tags),e.delayLoadingFile?(r.delayLoadState=4,r.delayLoadingFile=i+e.delayLoadingFile,r._boundingInfo=new boundingInfo_BoundingInfo(math_vector_Vector3.FromArray(e.boundingBoxMinimum),math_vector_Vector3.FromArray(e.boundingBoxMaximum)),r._delayInfo=[],e.hasUVs&&r._delayInfo.push(buffer_VertexBuffer.UVKind),e.hasUVs2&&r._delayInfo.push(buffer_VertexBuffer.UV2Kind),e.hasUVs3&&r._delayInfo.push(buffer_VertexBuffer.UV3Kind),e.hasUVs4&&r._delayInfo.push(buffer_VertexBuffer.UV4Kind),e.hasUVs5&&r._delayInfo.push(buffer_VertexBuffer.UV5Kind),e.hasUVs6&&r._delayInfo.push(buffer_VertexBuffer.UV6Kind),e.hasColors&&r._delayInfo.push(buffer_VertexBuffer.ColorKind),e.hasMatricesIndices&&r._delayInfo.push(buffer_VertexBuffer.MatricesIndicesKind),e.hasMatricesWeights&&r._delayInfo.push(buffer_VertexBuffer.MatricesWeightsKind),r._delayLoadingFunction=mesh_vertexData_VertexData.ImportVertexData):mesh_vertexData_VertexData.ImportVertexData(e,r),t.pushGeometry(r,!0),r}};let PerformanceMonitor=class PerformanceMonitor{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new RollingAverage(e)}sampleFrame(e=precisionDate_PrecisionDate.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){let 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(){let 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()}};let RollingAverage=class RollingAverage{constructor(e){this._samples=Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let 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;let 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){let t=this._samples.length;return(e%t+t)%t}};function allocateAndCopyTypedBuffer(e,t,i=!1,r){switch(e){case 3:{let e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{let e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{let e=new Int16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{let e=new Uint16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{let e=new Int32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{let e=new Uint32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{let e=new Float32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Float32Array(r)),e}}let s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}ThinEngine.prototype.setAlphaConstants=function(e,t,i,r){this._alphaState.setAlphaBlendConstants(e,t,i,r)},ThinEngine.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode===e){if(!t){let t=0===e;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}return}switch(e){case 0:this._alphaState.alphaBlend=!1;break;case 7:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 8:case 14: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 2: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 6:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 1:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 3:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 4:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 5: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 9: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 10: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 11:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case 12:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 13: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 15:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case 16: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 17: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=0===e),this._alphaMode=e},ThinEngine.prototype.getAlphaMode=function(){return this._alphaMode},ThinEngine.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case 0:this._alphaState.setAlphaEquationParameters(32774,32774);break;case 1:this._alphaState.setAlphaEquationParameters(32778,32778);break;case 2:this._alphaState.setAlphaEquationParameters(32779,32779);break;case 3:this._alphaState.setAlphaEquationParameters(32776,32776);break;case 4:this._alphaState.setAlphaEquationParameters(32775,32775);break;case 5:this._alphaState.setAlphaEquationParameters(32775,32774)}this._alphaEquation=e}},ThinEngine.prototype.getAlphaEquation=function(){return this._alphaEquation},ThinEngine.prototype._readTexturePixelsSync=function(e,t,i,r=-1,s=0,a=null,n=!0,o=!1,l=0,h=0){var c,u;let d=this._gl;if(!d)throw Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let e=d.createFramebuffer();if(!e)throw Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),r>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+r,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,s):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,s);let _=void 0!==e.type?this._getWebGLTextureType(e.type):d.UNSIGNED_BYTE;return o?a||(a=allocateAndCopyTypedBuffer(e.type,4*t*i)):_===d.UNSIGNED_BYTE?(a||(a=new Uint8Array(4*t*i)),_=d.UNSIGNED_BYTE):(a||(a=new Float32Array(4*t*i)),_=d.FLOAT),n&&this.flushFramebuffer(),d.readPixels(l,h,t,i,d.RGBA,_,a),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),a},ThinEngine.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,a=null,n=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,a,n,o,l,h))},ThinEngine.prototype.updateDynamicIndexBuffer=function(e,t,i=0){let r;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),r=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,r,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},ThinEngine.prototype.updateDynamicVertexBuffer=function(e,t,i,r){this.bindArrayBuffer(e),void 0===i&&(i=0);let s=t.byteLength||t.length;void 0===r||r>=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()};let engine_Engine=class engine_Engine extends ThinEngine{static get NpmPackage(){return ThinEngine.NpmPackage}static get Version(){return ThinEngine.Version}static get Instances(){return engineStore_EngineStore.Instances}static get LastCreatedEngine(){return engineStore_EngineStore.LastCreatedEngine}static get LastCreatedScene(){return engineStore_EngineStore.LastCreatedScene}_createImageBitmapFromSource(e,t){let i=new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{this.createImageBitmap(s,t).then(e=>{i(e)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e});return i}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){let r=this.createCanvas(t,i),s=r.getContext("2d");if(!s)throw Error("Unable to get 2d context for resizeImageBitmap");s.drawImage(e,0,0);let a=s.getImageData(0,0,t,i).data;return a}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};let t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!engine_Engine.audioEngine&&this._creationOptions.audioEngine&&engine_Engine.AudioEngineFactory&&(engine_Engine.audioEngine=engine_Engine.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),IsDocumentAvailable()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&engine_Engine._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==engine_Engine.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;null===(e=this._onPointerLockChange)||void 0===e||e.call(this)}getAspectRatio(e,t=!1){let i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){let i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}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)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){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()}restoreStencilState(){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)}setDirectViewport(e,t,i,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((r,s)=>{this._loadFile(e,e=>{r(e)},void 0,t,i,(e,t)=>{s(t)})})}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))}setTextureFromPostProcess(e,t,i){var r;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==s?void 0:s.texture)&&void 0!==r?r:null,i)}setTextureFromPostProcessOutput(e,t,i){var r,s;this._bindTexture(e,null!==(s=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e0?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()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){!this.isFullscreen&&(this._pointerLockRequested=e,this._renderingCanvas&&engine_Engine._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&engine_Engine._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&engine_Engine._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){engine_Engine._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this.onEndFrameObservable.notifyObservers(this)}setSize(e,t,i=!1){if(!this._renderingCanvas||!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e1&&s){let t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(a,s),e.transformFeedback=t}return r.linkProgram(a),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,e.isParallelCompiled||this._finalizePipelineContext(e),a}_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)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){let t=++engine_Engine._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let n=i;n||(n=this.scenes[this.scenes.length-1]),n.postProcessManager.directRender([this._rescalePostProcess],a,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,r,0,0,t.width,t.height,0),this.unBindFramebuffer(a),a.dispose(),s&&s()}))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,r=0,s=0){let a=new WebGLHardwareTexture(e,this._gl),n=new internalTexture_InternalTexture(this,$.Unknown,!0);return n._hardwareTexture=a,n.baseWidth=r,n.baseHeight=s,n.width=r,n.height=s,n.isReady=!0,n.useMipMaps=t,this.updateTextureSamplingMode(i,n),n}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,a=this._getWebGLTextureType(e.type),n=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,n),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,o,n,a,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion){logger_Logger.Error("WebGL 1 does not support texture comparison.");return}let i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create instance buffer");let i=new WebGLDataBuffer(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){let r=this._gl;return new Promise((s,a)=>{let check=()=>{let n=r.clientWaitSync(e,t,0);if(n==r.WAIT_FAILED){a();return}if(n==r.TIMEOUT_EXPIRED){setTimeout(check,i);return}s()};check()})}_readPixelsAsync(e,t,i,r,s,a,n){if(this._webGLVersion<2)throw Error("_readPixelsAsync only work on WebGL2+");let o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,n.byteLength,o.STREAM_READ),o.readPixels(e,t,i,r,s,a,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);let h=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(o.flush(),this._clientWaitAsync(h,0,10).then(()=>(o.deleteSync(h),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,n),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),n))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===engineStore_EngineStore.Instances.length&&engine_Engine.audioEngine&&(engine_Engine.audioEngine.dispose(),engine_Engine.audioEngine=null);let e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),IsDocumentAvailable()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();let t=engineStore_EngineStore.Instances.indexOf(this);t>=0&&engineStore_EngineStore.Instances.splice(t,1),engine_Engine.Instances.length||engineStore_EngineStore.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!IsWindowObjectExist())return;let e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!IsWindowObjectExist())return;let e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=engine_Engine.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){let t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){let e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){let t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);let i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";let r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,a=0;try{a=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:a,descent:a-s}}};engine_Engine.ALPHA_DISABLE=0,engine_Engine.ALPHA_ADD=1,engine_Engine.ALPHA_COMBINE=2,engine_Engine.ALPHA_SUBTRACT=3,engine_Engine.ALPHA_MULTIPLY=4,engine_Engine.ALPHA_MAXIMIZED=5,engine_Engine.ALPHA_ONEONE=6,engine_Engine.ALPHA_PREMULTIPLIED=7,engine_Engine.ALPHA_PREMULTIPLIED_PORTERDUFF=8,engine_Engine.ALPHA_INTERPOLATE=9,engine_Engine.ALPHA_SCREENMODE=10,engine_Engine.DELAYLOADSTATE_NONE=0,engine_Engine.DELAYLOADSTATE_LOADED=1,engine_Engine.DELAYLOADSTATE_LOADING=2,engine_Engine.DELAYLOADSTATE_NOTLOADED=4,engine_Engine.NEVER=512,engine_Engine.ALWAYS=519,engine_Engine.LESS=513,engine_Engine.EQUAL=514,engine_Engine.LEQUAL=515,engine_Engine.GREATER=516,engine_Engine.GEQUAL=518,engine_Engine.NOTEQUAL=517,engine_Engine.KEEP=7680,engine_Engine.REPLACE=7681,engine_Engine.INCR=7682,engine_Engine.DECR=7683,engine_Engine.INVERT=5386,engine_Engine.INCR_WRAP=34055,engine_Engine.DECR_WRAP=34056,engine_Engine.TEXTURE_CLAMP_ADDRESSMODE=0,engine_Engine.TEXTURE_WRAP_ADDRESSMODE=1,engine_Engine.TEXTURE_MIRROR_ADDRESSMODE=2,engine_Engine.TEXTUREFORMAT_ALPHA=0,engine_Engine.TEXTUREFORMAT_LUMINANCE=1,engine_Engine.TEXTUREFORMAT_LUMINANCE_ALPHA=2,engine_Engine.TEXTUREFORMAT_RGB=4,engine_Engine.TEXTUREFORMAT_RGBA=5,engine_Engine.TEXTUREFORMAT_RED=6,engine_Engine.TEXTUREFORMAT_R=6,engine_Engine.TEXTUREFORMAT_RG=7,engine_Engine.TEXTUREFORMAT_RED_INTEGER=8,engine_Engine.TEXTUREFORMAT_R_INTEGER=8,engine_Engine.TEXTUREFORMAT_RG_INTEGER=9,engine_Engine.TEXTUREFORMAT_RGB_INTEGER=10,engine_Engine.TEXTUREFORMAT_RGBA_INTEGER=11,engine_Engine.TEXTURETYPE_UNSIGNED_BYTE=0,engine_Engine.TEXTURETYPE_UNSIGNED_INT=0,engine_Engine.TEXTURETYPE_FLOAT=1,engine_Engine.TEXTURETYPE_HALF_FLOAT=2,engine_Engine.TEXTURETYPE_BYTE=3,engine_Engine.TEXTURETYPE_SHORT=4,engine_Engine.TEXTURETYPE_UNSIGNED_SHORT=5,engine_Engine.TEXTURETYPE_INT=6,engine_Engine.TEXTURETYPE_UNSIGNED_INTEGER=7,engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,engine_Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,engine_Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,engine_Engine.TEXTURETYPE_UNSIGNED_INT_24_8=12,engine_Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,engine_Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,engine_Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,engine_Engine.TEXTURE_NEAREST_SAMPLINGMODE=1,engine_Engine.TEXTURE_BILINEAR_SAMPLINGMODE=2,engine_Engine.TEXTURE_TRILINEAR_SAMPLINGMODE=3,engine_Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,engine_Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,engine_Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,engine_Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,engine_Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,engine_Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,engine_Engine.TEXTURE_NEAREST_LINEAR=7,engine_Engine.TEXTURE_NEAREST_NEAREST=1,engine_Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,engine_Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,engine_Engine.TEXTURE_LINEAR_LINEAR=2,engine_Engine.TEXTURE_LINEAR_NEAREST=12,engine_Engine.TEXTURE_EXPLICIT_MODE=0,engine_Engine.TEXTURE_SPHERICAL_MODE=1,engine_Engine.TEXTURE_PLANAR_MODE=2,engine_Engine.TEXTURE_CUBIC_MODE=3,engine_Engine.TEXTURE_PROJECTION_MODE=4,engine_Engine.TEXTURE_SKYBOX_MODE=5,engine_Engine.TEXTURE_INVCUBIC_MODE=6,engine_Engine.TEXTURE_EQUIRECTANGULAR_MODE=7,engine_Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,engine_Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,engine_Engine.SCALEMODE_FLOOR=1,engine_Engine.SCALEMODE_NEAREST=2,engine_Engine.SCALEMODE_CEILING=3,engine_Engine._RescalePostProcessFactory=null,engine_Engine._RenderPassIdCounter=0;let N=math_vector_Matrix.Compose(math_vector_Vector3.One(),math_vector_Quaternion.FromEulerAngles(0,Math.PI,0),math_vector_Vector3.Zero());let transformNode_TransformNode=class transformNode_TransformNode extends node_Node{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&transformNode_TransformNode.BILLBOARDMODE_USE_POSITION)!=0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==transformNode_TransformNode.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new math_vector_Vector3(0,0,1),this._up=new math_vector_Vector3(0,1,0),this._right=new math_vector_Vector3(1,0,0),this._position=math_vector_Vector3.Zero(),this._rotation=math_vector_Vector3.Zero(),this._rotationQuaternion=null,this._scaling=math_vector_Vector3.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=transformNode_TransformNode.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=math_vector_Matrix.Zero(),this._usePivotMatrix=!1,this._absolutePosition=math_vector_Vector3.Zero(),this._absoluteScaling=math_vector_Vector3.Zero(),this._absoluteRotationQuaternion=math_vector_Quaternion.Identity(),this._pivotMatrix=math_vector_Matrix.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new observable_Observable,this._nonUniformScaling=!1,i&&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}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 math_vector_Vector3.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return math_vector_Vector3.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return math_vector_Vector3.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._poseMatrix=e.clone(),this}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=math_vector_Matrix.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===transformNode_TransformNode.BILLBOARDMODE_NONE&&!e.pivotMatrixUpdated&&!this._infiniteDistance&&!this._position._isDirty&&!this._scaling._isDirty&&(!this._rotationQuaternion||!this._rotationQuaternion._isDirty)&&!this._rotation._isDirty}_initCache(){super._initCache();let 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=math_vector_Matrix.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||math_vector_Quaternion.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){let t,i,r;if(!e)return this;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let e=math_vector_TmpVectors.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),math_vector_Vector3.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=math_vector_Vector3.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=math_vector_TmpVectors.Matrix[0];return this._localMatrix.invertToRef(e),math_vector_Vector3.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=math_vector_Vector3.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=en.LOCAL){let a=transformNode_TransformNode._LookAtVectorCache,n=s===en.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(n,a),this.setDirection(a,t,i,r),s===en.WORLD&&this.parent){if(this.rotationQuaternion){let e=math_vector_TmpVectors.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);let t=math_vector_TmpVectors.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{let e=math_vector_TmpVectors.Quaternion[0];math_vector_Quaternion.FromEulerVectorToRef(this.rotation,e);let t=math_vector_TmpVectors.Matrix[0];e.toRotationMatrix(t);let i=math_vector_TmpVectors.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}}return this}getDirection(e){let t=math_vector_Vector3.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return math_vector_Vector3.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,a=Math.sqrt(e.x*e.x+e.z*e.z),n=-Math.atan2(e.y,a);return this.rotationQuaternion?math_vector_Quaternion.RotationYawPitchRollToRef(s+t,n+i,r,this.rotationQuaternion):(this.rotation.x=n+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=en.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==en.WORLD){let t=math_vector_TmpVectors.Matrix[0];i.invertToRef(t),e=math_vector_Vector3.TransformCoordinates(e,t)}return this.setPivotMatrix(math_vector_Matrix.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=math_vector_Vector3.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(){let e=math_vector_Vector3.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),math_vector_Vector3.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=math_vector_TmpVectors.Quaternion[0],s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1],n=math_vector_TmpVectors.Matrix[1];math_vector_Matrix.IdentityToRef(n);let o=math_vector_TmpVectors.Matrix[0];this.computeWorldMatrix(!0);let l=this.rotationQuaternion;return l||(l=transformNode_TransformNode._TmpRotation,math_vector_Quaternion.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,l)),math_vector_Matrix.ComposeToRef(this.scaling,l,this.position,o),this.parent&&o.multiplyToRef(this.parent.computeWorldMatrix(!0),o),e&&(e.computeWorldMatrix(!0).invertToRef(n),o.multiplyToRef(n,o)),o.decompose(a,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(a),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(math_vector_Matrix.Identity()),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),0>e.getFinalMatrix().determinant()&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(0>this.parent.getWorldMatrix().determinant()&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null):e&&(this.parent=this._currentParentWhenAttachingToBone),this}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==en.LOCAL){if(this.parent){let i=this.parent.getWorldMatrix(),r=math_vector_TmpVectors.Matrix[0];i.invertToRef(r),e=math_vector_Vector3.TransformNormal(e,r),0>i.determinant()&&(t*=-1)}(r=math_vector_Quaternion.RotationAxisToRef(e,t,transformNode_TransformNode._RotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=math_vector_Quaternion.RotationAxisToRef(e,t,transformNode_TransformNode._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=math_vector_Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=math_vector_TmpVectors.Vector3[0],s=math_vector_TmpVectors.Vector3[1],a=math_vector_TmpVectors.Vector3[2],n=math_vector_TmpVectors.Quaternion[0],o=math_vector_TmpVectors.Matrix[0],l=math_vector_TmpVectors.Matrix[1],h=math_vector_TmpVectors.Matrix[2],c=math_vector_TmpVectors.Matrix[3];return e.subtractToRef(this.position,r),math_vector_Matrix.TranslationToRef(r.x,r.y,r.z,o),math_vector_Matrix.TranslationToRef(-r.x,-r.y,-r.z,l),math_vector_Matrix.RotationAxisToRef(t,i,h),l.multiplyToRef(h,c),c.multiplyToRef(o,c),c.decompose(s,n,a),this.position.addInPlace(a),n.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(i&&i!==en.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{let e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=math_vector_TmpVectors.Quaternion[1],math_vector_Quaternion.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=math_vector_TmpVectors.Quaternion[0];return math_vector_Quaternion.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==transformNode_TransformNode.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){let i;if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let r=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===r||this.isSynchronized()))return this._currentRenderId=r,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=r,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let a=this._getEffectiveParent(),n=transformNode_TransformNode._TmpScaling,o=this._position;if(this._infiniteDistance&&!this.parent&&t){let e=t.getWorldMatrix(),i=new math_vector_Vector3(e.m[12],e.m[13],e.m[14]);(o=transformNode_TransformNode._TmpTranslation).copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.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,i=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){let e=this.rotation.lengthSquared();e&&(this._rotationQuaternion.multiplyInPlace(math_vector_Quaternion.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else i=transformNode_TransformNode._TmpRotation,math_vector_Quaternion.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,i);if(this._usePivotMatrix){let e=math_vector_TmpVectors.Matrix[1];math_vector_Matrix.ScalingToRef(n.x,n.y,n.z,e);let t=math_vector_TmpVectors.Matrix[0];i.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,math_vector_TmpVectors.Matrix[4]),math_vector_TmpVectors.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 math_vector_Matrix.ComposeToRef(n,i,o,this._localMatrix);if(a&&a.getWorldMatrix){if(e&&a.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),math_vector_TmpVectors.Matrix[7])}else math_vector_TmpVectors.Matrix[7].copyFrom(a.getWorldMatrix());let e=math_vector_TmpVectors.Vector3[5],t=math_vector_TmpVectors.Vector3[6],i=math_vector_TmpVectors.Quaternion[0];math_vector_TmpVectors.Matrix[7].decompose(t,i,e),math_vector_Matrix.ScalingToRef(t.x,t.y,t.z,math_vector_TmpVectors.Matrix[7]),math_vector_TmpVectors.Matrix[7].setTranslation(e),transformNode_TransformNode.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),math_vector_TmpVectors.Matrix[6]),math_vector_TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(a.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){let e=math_vector_TmpVectors.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),math_vector_TmpVectors.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&math_vector_TmpVectors.Matrix[1].multiplyToRef(N,math_vector_TmpVectors.Matrix[1]),math_vector_TmpVectors.Matrix[1].setTranslationFromFloats(0,0,0),math_vector_TmpVectors.Matrix[1].invertToRef(math_vector_TmpVectors.Matrix[0]),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_ALL)!==transformNode_TransformNode.BILLBOARDMODE_ALL){math_vector_TmpVectors.Matrix[0].decompose(void 0,math_vector_TmpVectors.Quaternion[0],void 0);let e=math_vector_TmpVectors.Vector3[1];math_vector_TmpVectors.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_X)!==transformNode_TransformNode.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_Y)!==transformNode_TransformNode.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_Z)!==transformNode_TransformNode.BILLBOARDMODE_Z&&(e.z=0),math_vector_Matrix.RotationYawPitchRollToRef(e.y,e.x,e.z,math_vector_TmpVectors.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(math_vector_TmpVectors.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){let e=math_vector_TmpVectors.Vector3[0];this._worldMatrix.getTranslationToRef(e);let i=t.globalPosition;this._worldMatrix.invertToRef(math_vector_TmpVectors.Matrix[1]);let r=math_vector_TmpVectors.Vector3[1];math_vector_Vector3.TransformCoordinatesToRef(i,math_vector_TmpVectors.Matrix[1],r),r.normalize();let s=-Math.atan2(r.z,r.x)+Math.PI/2,a=Math.sqrt(r.x*r.x+r.z*r.z),n=-Math.atan2(r.y,a);if(math_vector_Quaternion.RotationYawPitchRollToRef(s,n,0,math_vector_TmpVectors.Quaternion[0]),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_ALL)!==transformNode_TransformNode.BILLBOARDMODE_ALL){let e=math_vector_TmpVectors.Vector3[1];math_vector_TmpVectors.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_X)!==transformNode_TransformNode.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_Y)!==transformNode_TransformNode.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&transformNode_TransformNode.BILLBOARDMODE_Z)!==transformNode_TransformNode.BILLBOARDMODE_Z&&(e.z=0),math_vector_Matrix.RotationYawPitchRollToRef(e.y,e.x,e.z,math_vector_TmpVectors.Matrix[0])}else math_vector_Matrix.FromQuaternionToRef(math_vector_TmpVectors.Quaternion[0],math_vector_TmpVectors.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(math_vector_TmpVectors.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):a&&a._nonUniformScaling?this._updateNonUniformScalingState(a._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=math_vector_Matrix.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let e=this.getChildren();for(let t=0;tnew transformNode_TransformNode(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;inew transformNode_TransformNode(e.name,t),e,t,i);return e.localMatrix?r.setPreTransformMatrix(math_vector_Matrix.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(math_vector_Matrix.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r}getChildTransformNodes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&e instanceof transformNode_TransformNode),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){let e=this.getChildTransformNodes(!0);for(let t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let a=this.getHierarchyBoundingVectors(e,i),n=a.max.subtract(a.min),o=Math.max(n.x,n.y,n.z);return 0===o||(this.scaling.scaleInPlace(1/o),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r))),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}};transformNode_TransformNode.BILLBOARDMODE_NONE=0,transformNode_TransformNode.BILLBOARDMODE_X=1,transformNode_TransformNode.BILLBOARDMODE_Y=2,transformNode_TransformNode.BILLBOARDMODE_Z=4,transformNode_TransformNode.BILLBOARDMODE_ALL=7,transformNode_TransformNode.BILLBOARDMODE_USE_POSITION=128,transformNode_TransformNode.BillboardUseParentOrientation=!1,transformNode_TransformNode._TmpRotation=math_vector_Quaternion.Zero(),transformNode_TransformNode._TmpScaling=math_vector_Vector3.Zero(),transformNode_TransformNode._TmpTranslation=math_vector_Vector3.Zero(),transformNode_TransformNode._LookAtVectorCache=new math_vector_Vector3(0,0,0),transformNode_TransformNode._RotationAxisCache=new math_vector_Quaternion,__decorate([serializeAsVector3("position")],transformNode_TransformNode.prototype,"_position",void 0),__decorate([serializeAsVector3("rotation")],transformNode_TransformNode.prototype,"_rotation",void 0),__decorate([serializeAsQuaternion("rotationQuaternion")],transformNode_TransformNode.prototype,"_rotationQuaternion",void 0),__decorate([serializeAsVector3("scaling")],transformNode_TransformNode.prototype,"_scaling",void 0),__decorate([serialize("billboardMode")],transformNode_TransformNode.prototype,"_billboardMode",void 0),__decorate([serialize()],transformNode_TransformNode.prototype,"scalingDeterminant",void 0),__decorate([serialize("infiniteDistance")],transformNode_TransformNode.prototype,"_infiniteDistance",void 0),__decorate([serialize()],transformNode_TransformNode.prototype,"ignoreNonUniformScaling",void 0),__decorate([serialize()],transformNode_TransformNode.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);let _MeshCollisionData=class _MeshCollisionData{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new math_vector_Vector3(0,0,0),this._diffPositionForCollisions=new math_vector_Vector3(0,0,0),this._collisionResponse=!0}};let _FacetDataStorage=class _FacetDataStorage{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=math_vector_Vector3.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}};let _InternalAbstractMeshDataInfo=class _InternalAbstractMeshDataInfo{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new _FacetDataStorage,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 _MeshCollisionData,this._enableDistantPicking=!1,this._rawBoundingInfo=null}};let abstractMesh_AbstractMesh=class abstractMesh_AbstractMesh extends transformNode_TransformNode{static get BILLBOARDMODE_NONE(){return transformNode_TransformNode.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return transformNode_TransformNode.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return transformNode_TransformNode.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return transformNode_TransformNode.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return transformNode_TransformNode.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return transformNode_TransformNode.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;let t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty(e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()})}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._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){var t;return null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[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}get _positions(){return null}set skeleton(e){let 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 _InternalAbstractMeshDataInfo,this._waitingMaterialId=null,this.cullingStrategy=abstractMesh_AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new observable_Observable,this.onCollisionPositionChangeObservable=new observable_Observable,this.onMaterialChangedObservable=new observable_Observable,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=math_color_Color3.Red(),this.outlineWidth=.02,this.overlayColor=math_color_Color3.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 math_vector_Vector3(.5,1,.5),this.ellipsoidOffset=new math_vector_Vector3(0,0,0),this.edgesWidth=1,this.edgesColor=new math_color_Color4(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=[],this._unIndexed=!1,this._lightSources=[],this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new observable_Observable,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>engine_Engine.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new UniformBuffer(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case ea.Aggressive:this.doNotSyncBoundingInfo=!0;case ea.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){let 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);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode]+", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==transformNode_TransformNode.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){return this.actionManager&&(t||this.actionManager.isRecursive)&&(!e||this.actionManager.hasSpecificTrigger(e))?this.actionManager: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(let e of this.subMeshes)e._rebuild()}_resyncLightSources(){for(let e of(this._lightSources.length=0,this.getScene().lights))e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;it.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(let 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,i,r){return this}updateVerticesData(e,t,i,r){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(){var e;return null!==(e=this.rawBoundingInfo)&&void 0!==e?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new boundingInfo_BoundingInfo(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(buffer_VertexBuffer.MatricesIndicesKind)&&this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===transformNode_TransformNode.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,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){let r=new math_vector_Matrix,s=this.rotationQuaternion?this.rotationQuaternion:math_vector_Quaternion.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);s.toRotationMatrix(r);let a=math_vector_Vector3.Zero(),n=this.definedFacingForward?-1:1;return math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e*n,t,i*n,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new math_vector_Vector3(e*r,t,i*r)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){let i=extractMinAndMax(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new boundingInfo_BoundingInfo(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t0){let e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*r)}}if(e++,r===buffer_VertexBuffer.PositionKind&&this._positions&&3===e){e=0;let r=3*t;this._positions[t++].copyFromFloats(i[r],i[r+1],i[r+2])}}}if(i&&e&&this.skeleton){let e=this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),t=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind);if(t&&e){let s=this.numBoneInfluencers>4,a=s?this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind):null,n=s?this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind):null,o=this.skeleton.getTransformMatrices(this),l=math_vector_TmpVectors.Vector3[0],h=math_vector_TmpVectors.Matrix[0],c=math_vector_TmpVectors.Matrix[1],u=0;for(let d=0;d0&&(math_vector_Matrix.FromFloat32ArrayToRefScaled(o,Math.floor(16*e[u+_]),p,c),h.addToSelf(c));if(s)for(_=0;_<4;_++)(p=n[u+_])>0&&(math_vector_Matrix.FromFloat32ArrayToRefScaled(o,Math.floor(16*a[u+_]),p,c),h.addToSelf(c));r===buffer_VertexBuffer.NormalKind?math_vector_Vector3.TransformNormalFromFloatsToRef(i[d],i[d+1],i[d+2],h,l):math_vector_Vector3.TransformCoordinatesFromFloatsToRef(i[d],i[d+1],i[d+2],h,l),l.toArray(i,d),r===buffer_VertexBuffer.PositionKind&&this._positions&&this._positions[d/3].copyFrom(l)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,buffer_VertexBuffer.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,buffer_VertexBuffer.PositionKind)}_getPositionData(e,t){var i;let r=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),r&&(e&&this.skeleton||t&&this.morphTargetManager)){if(r=r.slice(),this._generatePointsArray(),this._positions){let e=this._positions;this._internalAbstractMeshDataInfo._positions=Array(e.length);for(let t=0;t1||!r.IsGlobal)&&r.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,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let i of this.getChildMeshes())if(i.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){let t=this.getAbsolutePosition();t.addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);let i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s1)||a._checkCollision(e))&&this._collideForSubMesh(a,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=math_vector_TmpVectors.Matrix[0],i=math_vector_TmpVectors.Matrix[1];return math_vector_Matrix.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,a=!1){let n=new PickingInfo,o=this.getClassName(),l="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,h=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(h.boundingSphere,l)||!e.intersectsBox(h.boundingBox,l)))return n;if(r)return n.hit=!a,n.pickedMesh=a?null:this,n.distance=a?0:math_vector_Vector3.Distance(e.origin,h.boundingSphere.center),n.subMeshId=0,n;if(!this._generatePointsArray())return n;let c=null,u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length,_=!1;for(let e=0;e1&&!s.canIntersects(e))continue;let a=s.intersects(e,this._positions,this.getIndices(),t,i);if(a&&(t||!c||a.distancee!==this&&e.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(this))&&e.excludedMeshes.splice(t,1);let i=e.getShadowGenerators();if(i){let e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){let e=i.value,r=e.getShadowMap();r&&r.renderList&&-1!==(t=r.renderList.indexOf(this))&&r.renderList.splice(t,1)}}}),("InstancedMesh"!==this.getClassName()||"InstancedLinesMesh"!==this.getClassName())&&this.releaseSubMeshes();let a=r.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,a.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),a.wipeCaches(),r.removeMesh(this),this._parentContainer){let 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(i=0;i65535){t=!0;break}t?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){let t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:math_vector_Vector3.Zero()}e.depthSortedFacets=[];for(let t=0;t.001?s.maximum.x-s.minimum.x:.001,e.bbSize.y=s.maximum.y-s.minimum.y>.001?s.maximum.y-s.minimum.y:.001,e.bbSize.z=s.maximum.z-s.minimum.z>.001?s.maximum.z-s.minimum.z:.001;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),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=s,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),math_vector_Vector3.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&mesh_vertexData_VertexData.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let t=e.depthSortedIndices.length/3|0;for(let r=0;rs.subDiv.max||n<0||n>s.subDiv.max||o<0||o>s.subDiv.max?null:s.facetPartitioning[a+s.subDiv.max*n+s.subDiv.max*s.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let n=this.getWorldMatrix(),o=math_vector_TmpVectors.Matrix[5];n.invertToRef(o);let l=math_vector_TmpVectors.Vector3[8];math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e,t,i,o,l);let h=this.getClosestFacetAtLocalCoordinates(l.x,l.y,l.z,r,s,a);return r&&math_vector_Vector3.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,n,r),h}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,a=!0){let n,o,l,h=null,c=0,u=0,d=0,_=0,p=0,f=0,m=0,g=0,v=this.getFacetLocalPositions(),x=this.getFacetLocalNormals(),b=this.getFacetsAtLocalCoordinates(e,t,i);if(!b)return null;let T=Number.MAX_VALUE,S=T;for(let C=0;C=0||s&&!a&&_<=0)&&(_=o.x*l.x+o.y*l.y+o.z*l.z,p=-(o.x*e+o.y*t+o.z*i-_)/(o.x*o.x+o.y*o.y+o.z*o.z),f=e+o.x*p,m=t+o.y*p,g=i+o.z*p,(S=(c=f-e)*c+(u=m-t)*u+(d=g-i)*d)e.emitter===this)}};function addClipPlaneUniforms(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")}function prepareStringDefinesForClipPlanes(e,t,i){var r,s,a,n,o,l;let h=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),u=!!(null!==(a=e.clipPlane3)&&void 0!==a?a:t.clipPlane3),d=!!(null!==(n=e.clipPlane4)&&void 0!==n?n:t.clipPlane4),_=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),p=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),c&&i.push("#define CLIPPLANE2"),u&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),_&&i.push("#define CLIPPLANE5"),p&&i.push("#define CLIPPLANE6")}function prepareDefinesForClipPlanes(e,t,i){var r,s,a,n,o,l;let h=!1,c=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),u=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(a=e.clipPlane3)&&void 0!==a?a:t.clipPlane3),_=!!(null!==(n=e.clipPlane4)&&void 0!==n?n:t.clipPlane4),p=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==c&&(i.CLIPPLANE=c,h=!0),i.CLIPPLANE2!==u&&(i.CLIPPLANE2=u,h=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,h=!0),i.CLIPPLANE4!==_&&(i.CLIPPLANE4=_,h=!0),i.CLIPPLANE5!==p&&(i.CLIPPLANE5=p,h=!0),i.CLIPPLANE6!==f&&(i.CLIPPLANE6=f,h=!0),h}function bindClipPlane(e,t,i){var r,s,a,n,o,l;let h=null!==(r=t.clipPlane)&&void 0!==r?r:i.clipPlane;setClipPlane(e,"vClipPlane",h),setClipPlane(e,"vClipPlane2",h=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2),setClipPlane(e,"vClipPlane3",h=null!==(a=t.clipPlane3)&&void 0!==a?a:i.clipPlane3),setClipPlane(e,"vClipPlane4",h=null!==(n=t.clipPlane4)&&void 0!==n?n:i.clipPlane4),setClipPlane(e,"vClipPlane5",h=null!==(o=t.clipPlane5)&&void 0!==o?o:i.clipPlane5),setClipPlane(e,"vClipPlane6",h=null!==(l=t.clipPlane6)&&void 0!==l?l:i.clipPlane6)}function setClipPlane(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}abstractMesh_AbstractMesh.OCCLUSION_TYPE_NONE=0,abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC=1,abstractMesh_AbstractMesh.OCCLUSION_TYPE_STRICT=2,abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,abstractMesh_AbstractMesh.CULLINGSTRATEGY_STANDARD=0,abstractMesh_AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,abstractMesh_AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,abstractMesh_AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,h["BABYLON.AbstractMesh"]=abstractMesh_AbstractMesh;let MaterialHelper=class MaterialHelper{static BindSceneUniformBuffer(e,t){t.bindToEffect(e,"Scene")}static PrepareDefinesForMergedUV(e,t,i){t._needUVs=!0,t[i]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[i+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[i+"DIRECTUV"]=0}static BindTextureMatrix(e,t,i){let r=e.getTextureMatrix();t.updateMatrix(i+"Matrix",r)}static GetFogState(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==scene_Scene.FOGMODE_NONE}static PrepareDefinesForMisc(e,t,i,r,s,a,n,o=!1){n._areMiscDirty&&(n.LOGARITHMICDEPTH=i,n.POINTSIZE=r,n.FOG=s&&this.GetFogState(e,t),n.NONUNIFORMSCALING=e.nonUniformScaling,n.ALPHATEST=a,n.DECAL_AFTER_DETAIL=o)}static PrepareDefinesForCamera(e,t){let i=!1;if(e.activeCamera){let r=t.CAMERA_ORTHOGRAPHIC?1:0,s=t.CAMERA_PERSPECTIVE?1:0,a=e.activeCamera.mode===camera_Camera.ORTHOGRAPHIC_CAMERA?1:0,n=e.activeCamera.mode===camera_Camera.PERSPECTIVE_CAMERA?1:0;(r^a||s^n)&&(t.CAMERA_ORTHOGRAPHIC=1===a,t.CAMERA_PERSPECTIVE=1===n,i=!0)}return i}static PrepareDefinesForFrameBoundValues(e,t,i,r,s,a=null,n=!1){let o=MaterialHelper.PrepareDefinesForCamera(e,r);!1!==a&&(o=prepareDefinesForClipPlanes(i,e,r)),!t.getColorWrite()!==r.DEPTHPREPASS&&(r.DEPTHPREPASS=!r.DEPTHPREPASS,o=!0),r.INSTANCES!==s&&(r.INSTANCES=s,o=!0),r.THIN_INSTANCES!==n&&(r.THIN_INSTANCES=n,o=!0),o&&r.markAsUnprocessed()}static PrepareDefinesForBones(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;let i=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&i)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!i&&void 0;let r=e.getScene().prePassRenderer;if(r&&r.enabled){let i=-1===r.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=i}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}static PrepareDefinesForMorphTargets(e,t){let i=e.morphTargetManager;i?(t.MORPHTARGETS_UV=i.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=i.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=i.supportsNormals&&t.NORMAL,t.MORPHTARGETS=i.numInfluencers>0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){let i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!i&&!!i.isEnabled}static PrepareDefinesForAttributes(e,t,i,r,s=!1,a=!0,n=!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(buffer_VertexBuffer.NormalKind),t._needNormals&&e.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){let i=e.useVertexColors&&e.isVerticesDataPresent(buffer_VertexBuffer.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&a}return e.isVerticesDataPresent(buffer_VertexBuffer.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),n&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){let i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){let r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(r!==t.ORDER_INDEPENDENT_TRANSPARENCY||s!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){let r=t.PREPASS;if(!t._arePrePassDirty)return;let s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i0&&(n.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=LightConstants.LIGHTMAP_DEFAULT?(n.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==LightConstants.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}static PrepareDefinesForLights(e,t,i,r,s=4,a=!1){if(!i._areLightsDirty)return i._needNormals;let n=0,o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!a){for(let a of t.lightSources)if(this.PrepareDefinesForLight(e,t,a,n,i,r,o),++n===s)break}i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=n;e0&&(s=r+a,t.addFallback(s,"LIGHT"+a)),!e.SHADOWS&&(e["SHADOW"+a]&&t.addFallback(r,"SHADOW"+a),e["SHADOWPCF"+a]&&t.addFallback(r,"SHADOWPCF"+a),e["SHADOWPCSS"+a]&&t.addFallback(r,"SHADOWPCSS"+a),e["SHADOWPOISSON"+a]&&t.addFallback(r,"SHADOWPOISSON"+a),e["SHADOWESM"+a]&&t.addFallback(r,"SHADOWESM"+a),e["SHADOWCLOSEESM"+a]&&t.addFallback(r,"SHADOWCLOSEESM"+a));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){let r=i.NUM_MORPH_INFLUENCERS;if(r>0&&engineStore_EngineStore.LastCreatedEngine){let s=engineStore_EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs,a=t.morphTargetManager;if(null==a?void 0:a.isUsingTextureForTargets)return;let n=a&&a.supportsNormals&&i.NORMAL,o=a&&a.supportsTangents&&i.TANGENT,l=a&&a.supportsUVs&&i.UV1;for(let i=0;is&&logger_Logger.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){let r=i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES;r&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,r){i.NUM_BONE_INFLUENCERS>0&&(r.addCPUSkinningFallback(0,t),e.push(buffer_VertexBuffer.MatricesIndicesKind),e.push(buffer_VertexBuffer.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(buffer_VertexBuffer.MatricesIndicesExtraKind),e.push(buffer_VertexBuffer.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(buffer_VertexBuffer.ColorInstanceKind)}static PushAttributesForInstances(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"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,r,s,a=!0){e._bindLight(t,i,r,s,a)}static BindLights(e,t,i,r,s=4){let a=Math.min(t.lightSources.length,s);for(let s=0;s-1){let i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{let s=r.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),MaterialHelper._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){let i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){let e=i.activeCamera;e.mode===camera_Camera.ORTHOGRAPHIC_CAMERA&&logger_Logger.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}};MaterialHelper._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},MaterialHelper._TempFogColor=math_color_Color3.Black();let MaterialStencilState=class MaterialStencilState{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}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){decorators_SerializationHelper.Clone(()=>e,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}parse(e,t,i){decorators_SerializationHelper.Parse(()=>this,e,t,i)}};__decorate([serialize()],MaterialStencilState.prototype,"func",null),__decorate([serialize()],MaterialStencilState.prototype,"funcRef",null),__decorate([serialize()],MaterialStencilState.prototype,"funcMask",null),__decorate([serialize()],MaterialStencilState.prototype,"opStencilFail",null),__decorate([serialize()],MaterialStencilState.prototype,"opDepthFail",null),__decorate([serialize()],MaterialStencilState.prototype,"opStencilDepthPass",null),__decorate([serialize()],MaterialStencilState.prototype,"mask",null),__decorate([serialize()],MaterialStencilState.prototype,"enabled",null),function(e){e[e.Created=1]="Created",e[e.Disposed=2]="Disposed",e[e.GetDefineNames=4]="GetDefineNames",e[e.PrepareUniformBuffer=8]="PrepareUniformBuffer",e[e.IsReadyForSubMesh=16]="IsReadyForSubMesh",e[e.PrepareDefines=32]="PrepareDefines",e[e.BindForSubMesh=64]="BindForSubMesh",e[e.PrepareEffect=128]="PrepareEffect",e[e.GetAnimatables=256]="GetAnimatables",e[e.GetActiveTextures=512]="GetActiveTextures",e[e.HasTexture=1024]="HasTexture",e[e.FillRenderTargetTextures=2048]="FillRenderTargetTextures",e[e.HasRenderTargetTextures=4096]="HasRenderTargetTextures",e[e.HardBindForSubMesh=8192]="HardBindForSubMesh"}(ec||(ec={}));let material_Material=class material_Material{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(1===t||1===e)&&this.markAsDirty(material_Material.MiscDirtyFlag+material_Material.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(material_Material.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(material_Material.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 observable_Observable),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 observable_Observable),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new observable_Observable),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(material_Material.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(material_Material.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case material_Material.WireFrameFillMode:case material_Material.LineListDrawMode:case material_Material.LineLoopDrawMode:case material_Material.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?material_Material.WireFrameFillMode:material_Material.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case material_Material.PointFillMode:case material_Material.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?material_Material.PointFillMode:material_Material.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(material_Material.MiscDirtyFlag))}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!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.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new observable_Observable,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,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 MaterialStencilState,this._useUBO=!1,this._fillMode=material_Material.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=()=>void 0,this._callbackPluginEventIsReadyForSubMesh=()=>void 0,this._callbackPluginEventPrepareDefines=()=>void 0,this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>void 0,this._callbackPluginEventHardBindForSubMesh=()=>void 0,this._callbackPluginEventBindForSubMesh=()=>void 0,this._callbackPluginEventHasRenderTargetTextures=()=>void 0,this._callbackPluginEventFillRenderTargetTextures=()=>void 0,this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;let r=t||engineStore_EngineStore.LastCreatedScene;if(!r)return;this._scene=r,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||tools_Tools.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new drawWrapper_DrawWrapper(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=material_Material.ClockWiseSideOrientation:this.sideOrientation=material_Material.CounterClockWiseSideOrientation,this._uniformBuffer=new UniformBuffer(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),material_Material.OnEventObservable.notifyObservers(this,ec.Created)}toString(e){let t="Name: "+this.name;return t}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,i){let r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===material_Material.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===material_Material.MATERIAL_OPAQUE||this._transparencyMode===material_Material.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){let t=this.getScene().meshes;for(let i of t)if(i.subMeshes)for(let t of i.subMeshes)t.getMaterial()===this&&t.effect&&(t.effect._wasPreviouslyReady=!1,t.effect._wasPreviouslyUsingInstances=null,t.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(material_Material.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),r=null==t?this.sideOrientation:t,s=r===material_Material.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(ec.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i.effect;r&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,MaterialHelper.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){let e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){let e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){if(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction){let e=this._scene.getEngine();e.setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){let e=this._scene.getEngine();e.setDepthWrite(this._cachedDepthWriteState)}if(this.disableColorWrite){let e=this._scene.getEngine();e.setColorWrite(this._cachedColorWriteState)}}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(ec.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(ec.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(ec.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),material_Material._parsePlugins(i,e,this._scene,t),this.pluginManager)for(let t of this.pluginManager._plugins){let i=e.pluginManager.getPlugin(t.name);t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}{let e=this._scene.meshes;return e.filter(e=>e.material===this)}}forceCompilation(e,t,i,r){let s=Object.assign({clipPlane:!1,useInstances:!1},i),a=this.getScene(),n=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let checkReady=()=>{if(!this._scene||!this._scene.getEngine())return;let i=a.clipPlane;if(s.clipPlane&&(a.clipPlane=new math_plane_Plane(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,a=null;if(e.subMeshes){let t=new subMesh_SubMesh(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?a=t.effect.getCompilationError():(i=!1,setTimeout(checkReady,16)))}i&&(this.allowShaderHotSwapping=n,a&&r&&r(a),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=n,t&&t(this)):setTimeout(checkReady,16);s.clipPlane&&(a.clipPlane=i)};checkReady()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,e=>{r(e)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(material_Material._DirtyCallbackArray.length=0,e&material_Material.TextureDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._TextureDirtyCallBack),e&material_Material.LightDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._LightsDirtyCallBack),e&material_Material.FresnelDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._FresnelDirtyCallBack),e&material_Material.AttributesDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._AttributeDirtyCallBack),e&material_Material.MiscDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._MiscDirtyCallBack),e&material_Material.PrePassDirtyFlag&&material_Material._DirtyCallbackArray.push(material_Material._PrePassDirtyCallBack),material_Material._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(material_Material._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){let e=this.getScene().meshes;for(let t of e)if(t.subMeshes)for(let e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let t=this.getScene().meshes;for(let i of t)if(i.subMeshes){for(let t of i.subMeshes)if(t.getMaterial(!1)===this)for(let i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(material_Material._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(material_Material._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(material_Material._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(material_Material._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(material_Material._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(material_Material._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(material_Material._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(material_Material._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(material_Material._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(material_Material._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==ea.BackwardCompatible){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(ec.Disposed,this._eventInfo),this._parentContainer){let e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i){if(this.meshMap)for(let t in this.meshMap){let i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{let t=r.meshes;for(let i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,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){let i=e.geometry;if(i){if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(let r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(let t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return logger_Logger.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";let r=tools_Tools.Instantiate(e.customType),s=r.Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _parsePlugins(e,t,i,r){var s;if(e.plugins)for(let a in e.plugins){let n=e.plugins[a],o=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(n.name);if(!o){let e=tools_Tools.Instantiate("BABYLON."+a);e&&(o=new e(t))}null==o||o.parse(n,i,r)}}};material_Material.TriangleFillMode=0,material_Material.WireFrameFillMode=1,material_Material.PointFillMode=2,material_Material.PointListDrawMode=3,material_Material.LineListDrawMode=4,material_Material.LineLoopDrawMode=5,material_Material.LineStripDrawMode=6,material_Material.TriangleStripDrawMode=7,material_Material.TriangleFanDrawMode=8,material_Material.ClockWiseSideOrientation=0,material_Material.CounterClockWiseSideOrientation=1,material_Material.TextureDirtyFlag=1,material_Material.LightDirtyFlag=2,material_Material.FresnelDirtyFlag=4,material_Material.AttributesDirtyFlag=8,material_Material.MiscDirtyFlag=16,material_Material.PrePassDirtyFlag=32,material_Material.AllDirtyFlag=63,material_Material.MATERIAL_OPAQUE=0,material_Material.MATERIAL_ALPHATEST=1,material_Material.MATERIAL_ALPHABLEND=2,material_Material.MATERIAL_ALPHATESTANDBLEND=3,material_Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,material_Material.MATERIAL_NORMALBLENDMETHOD_RNM=1,material_Material.OnEventObservable=new observable_Observable,material_Material._AllDirtyCallBack=e=>e.markAllAsDirty(),material_Material._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),material_Material._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),material_Material._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),material_Material._MiscDirtyCallBack=e=>e.markAsMiscDirty(),material_Material._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),material_Material._LightsDirtyCallBack=e=>e.markAsLightDirty(),material_Material._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),material_Material._FresnelAndMiscDirtyCallBack=e=>{material_Material._FresnelDirtyCallBack(e),material_Material._MiscDirtyCallBack(e)},material_Material._TextureAndMiscDirtyCallBack=e=>{material_Material._TextureDirtyCallBack(e),material_Material._MiscDirtyCallBack(e)},material_Material._DirtyCallbackArray=[],material_Material._RunDirtyCallBacks=e=>{for(let t of material_Material._DirtyCallbackArray)t(e)},__decorate([serialize()],material_Material.prototype,"id",void 0),__decorate([serialize()],material_Material.prototype,"uniqueId",void 0),__decorate([serialize()],material_Material.prototype,"name",void 0),__decorate([serialize()],material_Material.prototype,"metadata",void 0),__decorate([serialize()],material_Material.prototype,"checkReadyOnEveryCall",void 0),__decorate([serialize()],material_Material.prototype,"checkReadyOnlyOnce",void 0),__decorate([serialize()],material_Material.prototype,"state",void 0),__decorate([serialize("alpha")],material_Material.prototype,"_alpha",void 0),__decorate([serialize("backFaceCulling")],material_Material.prototype,"_backFaceCulling",void 0),__decorate([serialize("cullBackFaces")],material_Material.prototype,"_cullBackFaces",void 0),__decorate([serialize()],material_Material.prototype,"sideOrientation",void 0),__decorate([serialize("alphaMode")],material_Material.prototype,"_alphaMode",void 0),__decorate([serialize()],material_Material.prototype,"_needDepthPrePass",void 0),__decorate([serialize()],material_Material.prototype,"disableDepthWrite",void 0),__decorate([serialize()],material_Material.prototype,"disableColorWrite",void 0),__decorate([serialize()],material_Material.prototype,"forceDepthWrite",void 0),__decorate([serialize()],material_Material.prototype,"depthFunction",void 0),__decorate([serialize()],material_Material.prototype,"separateCullingPass",void 0),__decorate([serialize("fogEnabled")],material_Material.prototype,"_fogEnabled",void 0),__decorate([serialize()],material_Material.prototype,"pointSize",void 0),__decorate([serialize()],material_Material.prototype,"zOffset",void 0),__decorate([serialize()],material_Material.prototype,"zOffsetUnits",void 0),__decorate([serialize()],material_Material.prototype,"pointsCloud",null),__decorate([serialize()],material_Material.prototype,"fillMode",null),__decorate([serialize()],material_Material.prototype,"transparencyMode",null);let multiMaterial_MultiMaterial=class multiMaterial_MultiMaterial extends material_Material{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){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}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){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new multiMaterial_MultiMaterial(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,Tags&&Tags.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(e=>i.subMaterials.push(t.getLastMaterialById(e))),i}};h["BABYLON.MultiMaterial"]=multiMaterial_MultiMaterial;let MeshLODLevel=class MeshLODLevel{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}};let _CreationDataStorage=class _CreationDataStorage{};let _InstanceDataStorage=class _InstanceDataStorage{constructor(){this.visibleInstances={},this.batchCache=new _InstancesBatch,this.batchCacheReplacementModeInFrozenMode=new _InstancesBatch,this.instancesBufferSize=2048}};let _InstancesBatch=class _InstancesBatch{constructor(){this.mustReturn=!1,this.visibleInstances=[],this.renderSelf=[],this.hardwareInstancedRendering=[]}};let _ThinInstanceDataStorage=class _ThinInstanceDataStorage{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}};let _InternalMeshDataInfo=class _InternalMeshDataInfo{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=[],this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}};let mesh_Mesh=class mesh_Mesh extends abstractMesh_AbstractMesh{static _GetDefaultSideOrientation(e){return e||mesh_Mesh.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(buffer_VertexBuffer.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(buffer_VertexBuffer.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 observable_Observable),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new observable_Observable),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new observable_Observable),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new observable_Observable),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new observable_Observable),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(){var e;return(null!==(e=this._thinInstanceDataStorage.instancesCount)&&void 0!==e?e:0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=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}constructor(e,t=null,i=null,r=null,s,a=!0){if(super(e,t),this._internalMeshDataInfo=new _InternalMeshDataInfo,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new _InstanceDataStorage,this._thinInstanceDataStorage=new _ThinInstanceDataStorage,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=mesh_Mesh.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,i)=>{e&&i&&(this._uniformBuffer?this.transferToEffect(t):i.bindOnlyWorldMatrix(t))},r){if(r._geometry&&r._geometry.applyToMesh(this),DeepCopier.DeepCopy(r,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=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){let e=r._ranges;for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,this._internalMetadata=r._internalMetadata,Tags&&Tags.HasTags(r)&&Tags.AddTagsTo(this,Tags.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix()),this.id=e+"."+r.id,this.material=r.material,!s){let t=r.getDescendants(!0);for(let i=0;i{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 observable_Observable(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,i){let r=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));for(let s of(r.parent=e||this.parent,r.position=this.position.clone(),r.scaling=this.scaling.clone(),this.rotationQuaternion?r.rotationQuaternion=this.rotationQuaternion.clone():r.rotation=this.rotation.clone(),i&&i(this,r),this.getChildTransformNodes(!0)))"InstancedMesh"===s.getClassName()&&"Mesh"===r.getClassName()&&s.sourceMesh===this?s.instantiateHierarchy(r,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:r},i):s.instantiateHierarchy(r,t,i);return r}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices()+", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let i=0;i0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,i)=>t.distanceOrScreenCoveragei.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return logger_Logger.Warn("You cannot use a mesh as LOD level twice"),this;let i=new MeshLODLevel(e,t);return this._internalMeshDataInfo._LODLevels.push(i),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let i=0;in*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();let d=this.material||c.defaultMaterial;if(d){if(d._storeEffectOnSubMeshes)for(let e of this.subMeshes){let t=e.getMaterial();if(t){if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,u))return!1}else if(!t.isReady(this,u))return!1}}else if(!d.isReady(this,u))return!1}let _=h.currentRenderPassId;for(let e of this.lightSources){let t=e.getShadowGenerators();if(!t)continue;let c=t.values();for(let e=c.next();!0!==e.done;e=c.next()){let t=e.value;if(t&&(!(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)||(null===(r=t.getShadowMap())||void 0===r?void 0:r.renderList)&&(null===(a=null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||void 0===a?void 0:a.indexOf(this))!==-1)){let e=t.getShadowMap(),i=null!==(n=e.renderPassIds)&&void 0!==n?n:[h.currentRenderPassId];for(let e=0;e0){let i=this.getIndices();if(!i)return null;let r=i.length,s=!1;if(e)s=!0;else for(let e of this.subMeshes)if(e.indexStart+e.indexCount>r||e.verticesStart+e.verticesCount>t){s=!0;break}if(!s)return this.subMeshes[0]}return this.releaseSubMeshes(),new subMesh_SubMesh(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),i=t/e|0,r=0;for(;i%3!=0;)i++;this.releaseSubMeshes();for(let s=0;s=t);s++)subMesh_SubMesh.CreateFromIndices(0,r,s===e-1?t-r:i,this,void 0,!1),r+=i;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,i=!1,r){if(this._geometry)this._geometry.setVerticesData(e,t,i,r);else{let r=new mesh_vertexData_VertexData;r.set(t,e);let s=this.getScene();new Geometry(Geometry.RandomId(),s,r,i,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let i=this.getVertexBuffer(e);i&&i.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=Geometry.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,i,r){return this._geometry&&(r?(this.makeGeometryUnique(),this.updateVerticesData(e,t,i,!1)):this._geometry.updateVerticesData(e,t,i)),this}updateMeshPositions(e,t=!0){let i=this.getVerticesData(buffer_VertexBuffer.PositionKind);if(!i)return this;if(e(i),this.updateVerticesData(buffer_VertexBuffer.PositionKind,i,!1,!1),t){let e=this.getIndices(),t=this.getVerticesData(buffer_VertexBuffer.NormalKind);if(!t)return this;mesh_vertexData_VertexData.ComputeNormals(i,e,t),this.updateVerticesData(buffer_VertexBuffer.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry||1===this._geometry.meshes.length)return this;let e=this._geometry,t=this._geometry.copy(Geometry.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,i=!1){if(this._geometry)this._geometry.setIndices(e,t,i);else{let t=new mesh_vertexData_VertexData;t.indices=e;let r=this.getScene();new Geometry(Geometry.RandomId(),r,t,i,this)}return this}updateIndices(e,t,i=!1){return this._geometry&&this._geometry.updateIndices(e,t,i),this}toLeftHanded(){return this._geometry&&this._geometry.toLeftHanded(),this}_bind(e,t,i,r=!0){let s;if(!this._geometry)return this;let a=this.getScene().getEngine();if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)s=null;else switch(this._getRenderingFillMode(i)){case material_Material.PointFillMode:s=null;break;case material_Material.WireFrameFillMode:s=e._getLinesIndexBuffer(this.getIndices(),a);break;default:case material_Material.TriangleFillMode:s=this._geometry.getIndexBuffer()}return r&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,s,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,s),this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);let r=this.getScene(),s=r.getEngine();return this._unIndexed||t==material_Material.PointFillMode?s.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||i):t==material_Material.WireFrameFillMode?s.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||i):s.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||i),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}let i=this.getScene(),r=i._isInIntermediateRendering(),s=r?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!s&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){let t=this._instanceDataStorage.visibleInstances,s=i.getRenderId(),n=r?t.intermediateDefaultRenderId:t.defaultRenderId;a.visibleInstances[e]=t[s],!a.visibleInstances[e]&&n&&(a.visibleInstances[e]=t[n])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==a.visibleInstances[e]&&void 0!==a.visibleInstances[e],this._instanceDataStorage.previousBatch=a,a}_renderWithInstances(e,t,i,r,s){var a;let n=i.visibleInstances[e._id],o=n?n.length:0,l=this._instanceDataStorage,h=l.instancesBufferSize,c=l.instancesBuffer,u=l.instancesPreviousBuffer,d=64*(o+1);for(;l.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&c.activeCamera===c.activeCameras[0]||u<=1;if(d&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let _=this._getInstancesRenderList(e._id,!!i);if(_.mustReturn||!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let p=c.getEngine(),f=0,m=null;this.ignoreCameraMaxZ&&c.activeCamera&&!c._isInIntermediateRendering()&&(f=c.activeCamera.maxZ,m=c.activeCamera,c.activeCamera.maxZ=0,c.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let g=e.getRenderingMesh(),v=_.hardwareInstancedRendering[e._id]||g.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,x=this._instanceDataStorage,b=e.getMaterial();if(!b)return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this;if(x.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===b){if(b._storeEffectOnSubMeshes&&!(null===(a=e.effect)||void 0===a?void 0:a._wasPreviouslyReady)||!b._storeEffectOnSubMeshes&&!(null===(n=b.getEffect())||void 0===n?void 0:n._wasPreviouslyReady))return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this}else{if(b._storeEffectOnSubMeshes){if(!b.isReadyForSubMesh(this,e,v))return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this}else if(!b.isReady(this,v))return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=b}t&&p.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),l=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();let T=null!==(o=null==l?void 0:l.effect)&&void 0!==o?o:null;for(let t of c._beforeRenderingMeshStage)t.action(this,e,_,T);if(!l||!T)return m&&(m.maxZ=f,c.updateTransformMatrix(!0)),this;let S=i||this;if(!x.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||null!==this.overrideMaterialSideOrientation)){let e=S._getWorldMatrixDeterminant();null==(h=this.overrideMaterialSideOrientation)&&(h=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(h=h===material_Material.ClockWiseSideOrientation?material_Material.CounterClockWiseSideOrientation:material_Material.ClockWiseSideOrientation),x.sideOrientation=h}else h=x.sideOrientation;let C=this._internalMeshDataInfo._effectiveMaterial._preBind(l,h);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&p.setDepthWrite(!0);let E=this._internalMeshDataInfo._effectiveMaterial,y=E.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),v||this._bind(e,T,y,!1);let R=S.getWorldMatrix();for(let t of(E._storeEffectOnSubMeshes?E.bindForSubMesh(R,this,e):E.bind(R,this),!E.backFaceCulling&&E.separateCullingPass&&(p.setState(!0,E.zOffset,!1,!C,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._processRendering(this,e,T,y,_,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),p.setState(!0,E.zOffset,!1,C,E.cullBackFaces,E.stencil,E.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,T,y,_,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind(),c._afterRenderingMeshStage))t.action(this,e,_,T);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),m&&(m.maxZ=f,c.updateTransformMatrix(!0)),c.performancePriority!==ea.Aggressive||x.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsKind)&&(this.isVerticesDataPresent(buffer_VertexBuffer.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){let e=this.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind),t=e.length;for(let i=0;ii&&r++,0!==a&&u++,c+=a,i=a}if(l[u]++,u>a&&(a=u),0===c)s++;else{let i=1/c,r=0;for(let s=0;s.001&&n++}}let h=this.skeleton.bones.length,c=this.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),u=this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind),d=0;for(let e=0;e=h||i<0)&&d++}let _="Number of Weights = "+i/4+"\nMaximum influences = "+a+"\nMissing Weights = "+s+"\nNot Sorted = "+r+"\nNot Normalized = "+n+"\nWeightCounts = ["+l+"]\nNumber of bones = "+h+"\nBad Bone Indices = "+d;return{skinned:!0,valid:0===s&&0===n&&0===d,report:_}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return tools_Tools.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=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return!!(2!==this.delayLoadState&&super.isInFrustum(e))&&(this._checkDelayState(),!0)}setMaterialById(e){let t;let i=this.getScene().materials;for(t=i.length-1;t>-1;t--)if(i[t].id===e)return this.material=i[t],this;let r=this.getScene().multiMaterials;for(t=r.length-1;t>-1;t--)if(r[t].id===e){this.material=r[t];break}return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){let t;if(!this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind))return this;let i=this.subMeshes.splice(0);this._resetPointsArrayCache();let r=this.getVerticesData(buffer_VertexBuffer.PositionKind),s=math_vector_Vector3.Zero();for(t=0;te.determinant()&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=i,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?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,i,r=!0){return new mesh_Mesh(e,this.getScene(),t,this,i,r)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);let i=this._internalMeshDataInfo;if(i._onBeforeDrawObservable&&i._onBeforeDrawObservable.clear(),i._onBeforeBindObservable&&i._onBeforeBindObservable.clear(),i._onBeforeRenderObservable&&i._onBeforeRenderObservable.clear(),i._onAfterRenderObservable&&i._onAfterRenderObservable.clear(),i._onBetweenPassObservable&&i._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(i.meshMap)for(let e in i.meshMap){let t=i.meshMap[e];t&&(t._internalMeshDataInfo._source=null,i.meshMap[e]=void 0)}i._source&&i._source._internalMeshDataInfo.meshMap&&(i._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{let e=this.getScene().meshes;for(let t of e)t._internalMeshDataInfo&&t._internalMeshDataInfo._source&&t._internalMeshDataInfo._source===this&&(t._internalMeshDataInfo._source=null)}i._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,i,r,s,a,n=!1){let o=this.getScene();return tools_Tools.LoadImage(e,e=>{let o=e.width,l=e.height,h=this.getEngine().createCanvas(o,l),c=h.getContext("2d");c.drawImage(e,0,0);let u=c.getImageData(0,0,o,l).data;this.applyDisplacementMapFromBuffer(u,o,l,t,i,s,a,n),r&&r(this)},()=>{},o.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,i,r,s,a,n,o=!1){if(!this.isVerticesDataPresent(buffer_VertexBuffer.PositionKind)||!this.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)||!this.isVerticesDataPresent(buffer_VertexBuffer.UVKind))return logger_Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let l=this.getVerticesData(buffer_VertexBuffer.PositionKind,!0,!0),h=this.getVerticesData(buffer_VertexBuffer.NormalKind),c=this.getVerticesData(buffer_VertexBuffer.UVKind),u=math_vector_Vector3.Zero(),d=math_vector_Vector3.Zero(),_=math_vector_Vector2.Zero();a=a||math_vector_Vector2.Zero(),n=n||new math_vector_Vector2(1,1);for(let o=0;o{let r=new Float32Array(i.length*t),s=0;for(let a=0;aMath.abs(r[3*c[e]+t])&&(r[3*c[e]+t]=0),x[e]+=r[3*c[e]+t]+"|"}if(!(x[0]==x[1]||x[0]==x[2]||x[1]==x[2]))for(let e=0;e<3;e++){if(void 0===(h=T[x[e]])){T[x[e]]=b,h=b++;for(let t=0;t<3;t++)u.push(r[3*c[e]+t]);if(null!=s)for(let t=0;t<4;t++)p.push(s[4*c[e]+t]);if(null!=t)for(let i=0;i<2;i++)_.push(t[2*c[e]+i]);if(null!=a)for(let t=0;t<4;t++)f.push(a[4*c[e]+t]);if(null!=n)for(let t=0;t<4;t++)m.push(n[4*c[e]+t]);if(null!=o)for(let t=0;t<4;t++)g.push(o[4*c[e]+t]);if(null!=l)for(let t=0;t<4;t++)v.push(l[4*c[e]+t])}d.push(h)}}let S=[];mesh_vertexData_VertexData.ComputeNormals(u,d,S),e.positions=u,e.indices=d,e.normals=S,null!=t&&(e.uvs=_),null!=s&&(e.colors=p),null!=a&&(e.matricesIndices=f),null!=n&&(e.matricesWeights=m),null!=o&&(e.matricesIndicesExtra=g),null!=n&&(e.matricesWeightsExtra=v),e.applyToMesh(this,this.isVertexBufferUpdatable(buffer_VertexBuffer.PositionKind))}}static _instancedMeshFactory(e,t){throw _WarnImport("InstancedMesh")}static _PhysicsImpostorParser(e,t,i){throw _WarnImport("PhysicsImpostor")}createInstance(e){return mesh_Mesh._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e{let t=r.length-1-e,i=r[t];for(let e=0;e{for(let e=0;e-1&&(r.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(r.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(r.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t4,h=l?this.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind):null,c=l?this.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),d=math_vector_Vector3.Zero(),_=new math_vector_Matrix,p=new math_vector_Matrix,f=0;for(let e=0;e0&&(math_vector_Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*n[f+t]),m,p),_.addToSelf(p));if(l)for(t=0;t<4;t++)(m=c[f+t])>0&&(math_vector_Matrix.FromFloat32ArrayToRefScaled(u,Math.floor(16*h[f+t]),m,p),_.addToSelf(p));math_vector_Vector3.TransformCoordinatesFromFloatsToRef(r._sourcePositions[e],r._sourcePositions[e+1],r._sourcePositions[e+2],_,d),d.toArray(s,e),i&&(math_vector_Vector3.TransformNormalFromFloatsToRef(r._sourceNormals[e],r._sourceNormals[e+1],r._sourceNormals[e+2],_,d),d.toArray(a,e)),_.reset()}return this.updateVerticesData(buffer_VertexBuffer.PositionKind,s),i&&this.updateVerticesData(buffer_VertexBuffer.NormalKind,a),this}static MinMax(e){let t=null,i=null;return(e.forEach(function(e){let r=e.getBoundingInfo(),s=r.boundingBox;t&&i?(t.minimizeInPlace(s.minimumWorld),i.maximizeInPlace(s.maximumWorld)):(t=s.minimumWorld,i=s.maximumWorld)}),t&&i)?{min:t,max:i}:{min:math_vector_Vector3.Zero(),max:math_vector_Vector3.Zero()}}static Center(e){let t=e instanceof Array?mesh_Mesh.MinMax(e):e;return math_vector_Vector3.Center(t.min,t.max)}static MergeMeshes(e,t=!0,i,r,s,a){return runCoroutineSync(mesh_Mesh._MergeMeshesCoroutine(e,t,i,r,s,a,!1))}static MergeMeshesAsync(e,t=!0,i,r,s,a){return runCoroutineAsync(mesh_Mesh._MergeMeshesCoroutine(e,t,i,r,s,a,!0),createYieldingScheduler())}static*_MergeMeshesCoroutine(e,t=!0,i,r,s,a,n){let o;if(0===(e=e.filter(Boolean)).length)return null;if(!i){let t=0;for(o=0;o=65536)return logger_Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(s=!1);let l=[],h=[],c=[],u=e[0].overrideMaterialSideOrientation;for(o=0;ol.indexOf(e.subMaterials[t])&&l.push(e.subMaterials[t]);for(let i=0;il.indexOf(e)&&l.push(e);for(let i=0;i{let t=e.computeWorldMatrix(!0),i=mesh_vertexData_VertexData.ExtractFromMesh(e,!1,!1);return{vertexData:i,transform:t}},{vertexData:_,transform:p}=getVertexDataFromMesh(d);n&&(yield);let f=Array(e.length-1);for(let t=1;t{throw _WarnImport("GroundMesh")},mesh_Mesh._GoldbergMeshParser=(e,t)=>{throw _WarnImport("GoldbergMesh")},mesh_Mesh._LinesMeshParser=(e,t)=>{throw _WarnImport("LinesMesh")},mesh_Mesh._GreasedLineMeshParser=(e,t)=>{throw _WarnImport("GreasedLineMesh")},mesh_Mesh._GreasedLineRibbonMeshParser=(e,t)=>{throw _WarnImport("GreasedLineRibbonMesh")},mesh_Mesh._TrailMeshParser=(e,t)=>{throw _WarnImport("TrailMesh")},h["BABYLON.Mesh"]=mesh_Mesh,mesh_Mesh._instancedMeshFactory=(e,t)=>{let i=new instancedMesh_InstancedMesh(e,t);if(t.instancedBuffers)for(let e in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e];return i};let instancedMesh_InstancedMesh=class instancedMesh_InstancedMesh extends abstractMesh_AbstractMesh{constructor(e,t){for(let i of(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(),t.getAnimationRanges()))null!=i&&this.createAnimationRange(i.name,i.from,i.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){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.receiveShadows)!==e&&tools_Tools.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.material)!==e&&tools_Tools.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.visibility)!==e&&tools_Tools.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.skeleton)!==e&&tools_Tools.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&&logger_Logger.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,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),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 i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||logger_Logger.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){let i=this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0;if(i)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!==transformNode_TransformNode.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new math_vector_Matrix);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,math_vector_TmpVectors.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(math_vector_TmpVectors.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){let 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;e0)||-1!==this.includedOnlyMeshes.indexOf(e))&&(!this.excludedMeshes||!(this.excludedMeshes.length>0)||-1===this.excludedMeshes.indexOf(e))&&(0===this.includeOnlyWithLayerMask||(this.includeOnlyWithLayerMask&e.layerMask)!=0)&&(0===this.excludeWithLayerMask||!(this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.dispose()}this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){let e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(let 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){let i=light_Light.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=decorators_SerializationHelper.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=decorators_SerializationHelper.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)})),decorators_SerializationHelper.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){let r=node_Node.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){let i=light_Light.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=decorators_SerializationHelper.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{let r=t.apply(e,i);for(let e of i)e._resyncLightSource(this);return r};let i=e.splice;for(let t of(e.splice=(t,r)=>{let s=i.apply(e,[t,r]);for(let e of s)e._resyncLightSource(this);return s},e))t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._resyncMeshes(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===light_Light.INTENSITYMODE_AUTOMATIC&&(i=t===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?light_Light.INTENSITYMODE_ILLUMINANCE:light_Light.INTENSITYMODE_LUMINOUSINTENSITY),t){case light_Light.LIGHTTYPEID_POINTLIGHT:case light_Light.LIGHTTYPEID_SPOTLIGHT:switch(i){case light_Light.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case light_Light.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case light_Light.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case light_Light.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case light_Light.INTENSITYMODE_ILLUMINANCE:e=1;break;case light_Light.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);let i=2*Math.PI*(1-Math.cos(t));e=i}}break;case light_Light.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){let e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}};light_Light.FALLOFF_DEFAULT=LightConstants.FALLOFF_DEFAULT,light_Light.FALLOFF_PHYSICAL=LightConstants.FALLOFF_PHYSICAL,light_Light.FALLOFF_GLTF=LightConstants.FALLOFF_GLTF,light_Light.FALLOFF_STANDARD=LightConstants.FALLOFF_STANDARD,light_Light.LIGHTMAP_DEFAULT=LightConstants.LIGHTMAP_DEFAULT,light_Light.LIGHTMAP_SPECULAR=LightConstants.LIGHTMAP_SPECULAR,light_Light.LIGHTMAP_SHADOWSONLY=LightConstants.LIGHTMAP_SHADOWSONLY,light_Light.INTENSITYMODE_AUTOMATIC=LightConstants.INTENSITYMODE_AUTOMATIC,light_Light.INTENSITYMODE_LUMINOUSPOWER=LightConstants.INTENSITYMODE_LUMINOUSPOWER,light_Light.INTENSITYMODE_LUMINOUSINTENSITY=LightConstants.INTENSITYMODE_LUMINOUSINTENSITY,light_Light.INTENSITYMODE_ILLUMINANCE=LightConstants.INTENSITYMODE_ILLUMINANCE,light_Light.INTENSITYMODE_LUMINANCE=LightConstants.INTENSITYMODE_LUMINANCE,light_Light.LIGHTTYPEID_POINTLIGHT=LightConstants.LIGHTTYPEID_POINTLIGHT,light_Light.LIGHTTYPEID_DIRECTIONALLIGHT=LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT,light_Light.LIGHTTYPEID_SPOTLIGHT=LightConstants.LIGHTTYPEID_SPOTLIGHT,light_Light.LIGHTTYPEID_HEMISPHERICLIGHT=LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT,__decorate([serializeAsColor3()],light_Light.prototype,"diffuse",void 0),__decorate([serializeAsColor3()],light_Light.prototype,"specular",void 0),__decorate([serialize()],light_Light.prototype,"falloffType",void 0),__decorate([serialize()],light_Light.prototype,"intensity",void 0),__decorate([serialize()],light_Light.prototype,"range",null),__decorate([serialize()],light_Light.prototype,"intensityMode",null),__decorate([serialize()],light_Light.prototype,"radius",null),__decorate([serialize()],light_Light.prototype,"_renderPriority",void 0),__decorate([expandToProperty("_reorderLightsInScene")],light_Light.prototype,"renderPriority",void 0),__decorate([serialize("shadowEnabled")],light_Light.prototype,"_shadowEnabled",void 0),__decorate([serialize("excludeWithLayerMask")],light_Light.prototype,"_excludeWithLayerMask",void 0),__decorate([serialize("includeOnlyWithLayerMask")],light_Light.prototype,"_includeOnlyWithLayerMask",void 0),__decorate([serialize("lightmapMode")],light_Light.prototype,"_lightmapMode",void 0);let KeepAssets=class KeepAssets extends AbstractScene{};let InstantiatedEntries=class InstantiatedEntries{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}};let AssetContainer=class AssetContainer extends AbstractScene{constructor(e){if(super(),this._wasAddedToScene=!1,!(e=e||engineStore_EngineStore.LastCreatedScene))return;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(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of this.particleSystems)e.rebuild();for(let e of this.textures)e._rebuild()})}_topologicalSort(e){let t=new Map;for(let i of e)t.set(i.uniqueId,i);let i={dependsOn:new Map,dependedBy:new Map};for(let t of e){let e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(let r of e){let e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof instancedMesh_InstancedMesh){let a=r.sourceMesh;t.has(a.uniqueId)&&(s.add(a.uniqueId),i.dependedBy.get(a.uniqueId).add(e))}let a=i.dependedBy.get(e);for(let s of r.getDescendants()){let r=s.uniqueId;if(t.has(r)){a.add(r);let t=i.dependsOn.get(r);t.add(e)}}}let r=[],s=[];for(let r of e){let e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}for(;s.length>0;){let e=s.shift();r.push(e);let a=i.dependedBy.get(e.uniqueId);for(let r of Array.from(a.values())){let a=i.dependsOn.get(r);a.delete(e.uniqueId),0===a.size&&t.get(r)&&(s.push(t.get(r)),t.delete(r))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(e=>console.error(e.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId)))for(let s of(e.push(i),t.add(i.uniqueId),i.getDescendants(!0)))this._addNodeAndDescendantsToList(e,t,s,r)}_isNodeInContainer(e){return e instanceof mesh_Mesh&&-1!==this.meshes.indexOf(e)||e instanceof transformNode_TransformNode&&-1!==this.transformNodes.indexOf(e)||e instanceof light_Light&&-1!==this.lights.indexOf(e)||e instanceof camera_Camera&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return logger_Logger.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return logger_Logger.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return logger_Logger.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return logger_Logger.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||tools_Tools.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},a=new InstantiatedEntries,n=[],o=[],l=Object.assign({doNotInstantiate:!0},i),onClone=(t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof mesh_Mesh&&i.morphTargetManager){let e=t.morphTargetManager;i.morphTargetManager=e.clone();for(let t=0;t{if(onClone(i,n),i.parent){let e=r[i.parent.uniqueId],t=s[e];t?n.parent=t:n.parent=i.parent}if(n.position&&i.position&&n.position.copyFrom(i.position),n.rotationQuaternion&&i.rotationQuaternion&&n.rotationQuaternion.copyFrom(i.rotationQuaternion),n.rotation&&i.rotation&&n.rotation.copyFrom(i.rotation),n.scaling&&i.scaling&&n.scaling.copyFrom(i.scaling),n.material&&n.material){if(t){let t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){for(let a of t.subMaterials)a&&(i=a.clone(e?e(a.name):"Clone of "+a.name),o.push(a),r[a.uniqueId]=i.uniqueId,s[i.uniqueId]=i);t.subMaterials=t.subMaterials.map(e=>e&&s[r[e.uniqueId]])}}"InstancedMesh"!==n.getClassName()&&(n.material=s[r[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===n.parent&&a.rootNodes.push(n)};return u.forEach(e=>{if("InstancedMesh"===e.getClassName()){let t=e.sourceMesh,i=r[t.uniqueId],a="number"==typeof i?s[i]:t,n=a.createInstance(e.name);onNewCreated(e,n)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);let i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw Error(`Could not clone or instantiate node on Asset Container ${e.name}`);onNewCreated(e,i)}}),this.skeletons.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name);for(let e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){let t=s[r[e.uniqueId]];if(!t||t.isAnInstance||(t.skeleton=i,-1!==n.indexOf(i)))continue;for(let e of(n.push(i),i.bones))e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}a.skeletons.push(i)}),this.animationGroups.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name,e=>{let t=s[r[e.uniqueId]];return t||e});a.animationGroups.push(i)}),a}addAllToScene(){if(!this._wasAddedToScene){for(let e of(this._isValidHierarchy()||tools_Tools.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture),this.scene._serializableComponents))e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of(this.cameras.forEach(i=>{(!e||e(i))&&(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{(!e||e(i))&&(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{(!e||e(i))&&(this.scene.addMesh(i),t.push(i))}),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(i=>{(!e||e(i))&&(this.scene.addTransformNode(i),t.push(i))}),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)}),t))i.parent&&-1===this.scene.getNodes().indexOf(i.parent)&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){for(let e of(this._isValidHierarchy()||tools_Tools.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),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(){for(let e of(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),this.scene._serializableComponents))e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(let r of e){let e=!0;if(i){for(let t of i)if(r===t){e=!1;break}}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){for(let t in this._wasAddedToScene=!1,void 0===e&&(e=new KeepAssets),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(){let e=new mesh_Mesh("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=engineStore_EngineStore.LastCreatedScene,t,i=null){if(!e)return logger_Logger.Error("No scene available to merge animations to"),[];let r=i||(t=>{let i=null,r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i}),s=this.getNodes();s.forEach(e=>{let t=r(e);if(null!==t){for(let i of e.animations){let e=t.animations.filter(e=>e.targetProperty===i.targetProperty);for(let i of e){let e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}});let a=[];return this.animationGroups.slice().forEach(e=>{a.push(e.clone(e.name,r)),e.animatables.forEach(e=>{e.stop()})}),t.forEach(t=>{let i=r(t.target);i&&(e.beginAnimation(i,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))}),a}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;let t=[],i=new Set;for(t.push(e);t.length>0;){let e=t.pop();if(e instanceof mesh_Mesh?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof transformNode_TransformNode?this.transformNodes.push(e):e instanceof light_Light?this.lights.push(e):e instanceof camera_Camera&&this.cameras.push(e),e instanceof abstractMesh_AbstractMesh){if(e.material&&-1===this.materials.indexOf(e.material))for(let t of(this.materials.push(e.material),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(let r of e.getChildren())i.has(r)||t.push(r);i.add(e)}this.populateRootNodes()}};engine_Engine.AudioEngineFactory=(e,t,i)=>new AudioEngine(e,t,i);let AudioEngine=class AudioEngine{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=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 observable_Observable,this.onAudioLockedObservable=new observable_Observable,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!IsWindowObjectExist())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);let r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if((null===(e=this._audioContext)||void 0===e?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?null===(t=this._audioContext)||void 0===t||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(null===(e=this._audioContext)||void 0===e?void 0:e.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,logger_Logger.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";let e=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",t=document.createElement("style");t.appendChild(document.createTextNode(".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }")),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))}};let Sound=class Sound{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){let e=this.isPaused?0:engine_Engine.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;let t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){var a,n,o,l,h;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 observable_Observable,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=math_vector_Vector3.Zero(),this._localDirection=new math_vector_Vector3(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,!(i=i||engineStore_EngineStore.LastCreatedScene))return;if(this._scene=i,Sound._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{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&&logger_Logger.Error("XHR "+e.status+" error on: "+t+"."),logger_Logger.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:e=!1}e?!r&&(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):logger_Logger.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){logger_Logger.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),engine_Engine.audioEngine&&!engine_Engine.audioEngine.WarnedWebAudioUnsupported&&(logger_Logger.Error("Web Audio is not supported by your browser."),engine_Engine.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.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){var t;(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.audioContext)&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.audioContext)&&engine_Engine.audioEngine.audioContext.decodeAudioData(e,e=>{this._audioBufferLoaded(e)},e=>{logger_Logger.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)})}setAudioBuffer(e){var t;(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,r,s,a,n,o,l,h,c,u;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(r=e.useCustomAttenuation)&&void 0!==r?r:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(a=e.refDistance)&&void 0!==a?a:this.refDistance,this.distanceModel=null!==(n=e.distanceModel)&&void 0!==n?n:this.distanceModel,this._playbackRate=null!==(o=e.playbackRate)&&void 0!==o?o:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this.spatialSound=null!==(h=e.spatialSound)&&void 0!==h?h:this._spatialSound,this._setOffset(null!==(c=e.offset)&&void 0!==c?c:void 0),this.setVolume(null!==(u=e.volume)&&void 0!==u?u: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(){var e,t;(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&engine_Engine.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:engine_Engine.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,null===(e=this._soundPanner)||void 0===e||e.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.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(){var e;(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){let tryToPlay=()=>{var e,t;if(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.unlocked){let e=this._htmlAudioElement.play();void 0!==e&&e.catch(()=>{var e,t;null===(e=engine_Engine.audioEngine)||void 0===e||e.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))};tryToPlay()}}else{let tryToPlay=()=>{var s,a,n,o;if(null===(s=engine_Engine.audioEngine)||void 0===s?void 0:s.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){let e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=null===(a=engine_Engine.audioEngine)||void 0===a?void 0:a.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!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?(null===(n=engine_Engine.audioEngine)||void 0===n?void 0:n.audioContext.currentTime)+e:engine_Engine.audioEngine.audioContext.currentTime;let s=((this.isPaused?this.currentTime:0)+(null!==(o=this._offset)&&void 0!==o?o:0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};(null===(n=engine_Engine.audioEngine)||void 0===n?void 0:n.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var e;(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.audioContext.state)==="suspended"?(engine_Engine.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=engine_Engine.audioEngine.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))):tryToPlay()},500):tryToPlay()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){logger_Logger.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){var t;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((null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){let t=e?engine_Engine.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=()=>void 0),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1}else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>void 0,this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=engine_Engine.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=engine_Engine.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&engine_Engine.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(engine_Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,engine_Engine.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,engine_Engine.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){var t;if(e.getBoundingInfo){let t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{let setBufferAndRun=()=>{this._isReadyToPlay?(t._audioBuffer=this.getAudioBuffer(),t._isReadyToPlay=!0,t.autoplay&&t.play(0,this._offset,this._length)):setTimeout(setBufferAndRun,300)},e={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},t=new Sound(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,e);return this.useCustomAttenuation&&t.setAttenuationFunction(this._customAttenuationFunction),t.setPosition(this._position),t.setPlaybackRate(this._playbackRate),setBufferAndRun(),t}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){let 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,i,r){let s,a;let n=e.name;s=e.url?i+e.url:i+n;let o={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};if(r){let setBufferAndRun=()=>{r._isReadyToPlay?(a._audioBuffer=r.getAudioBuffer(),a._isReadyToPlay=!0,a.autoplay&&a.play(0,a._offset,a._length)):setTimeout(setBufferAndRun,300)};a=new Sound(n,new ArrayBuffer(0),t,null,o),setBufferAndRun()}else a=new Sound(n,s,t,()=>{t.removePendingData(a)},o),t.addPendingData(a);if(e.position){let t=math_vector_Vector3.FromArray(e.position);a.setPosition(t)}if(e.isDirectional&&(a.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){let t=math_vector_Vector3.FromArray(e.localDirectionToMesh);a.setLocalDirectionToMesh(t)}if(e.connectedMeshId){let i=t.getMeshById(e.connectedMeshId);i&&a.attachToMesh(i)}return e.metadata&&(a.metadata=e.metadata),a}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(null===(e=engine_Engine.audioEngine)||void 0===e||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}};Sound._SceneComponentInitialization=e=>{throw _WarnImport("AudioSceneComponent")};let SoundTrack=class SoundTrack{constructor(e,t={}){if(this.id=-1,this._isInitialized=!1,!(e=e||engineStore_EngineStore.LastCreatedScene))return;this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}_initializeSoundTrackAudioGraph(){var e;(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&engine_Engine.audioEngine.audioContext&&(this._outputAudioNode=engine_Engine.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(engine_Engine.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(engine_Engine.audioEngine&&engine_Engine.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){let t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=engine_Engine.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=engine_Engine.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e{var s;let a;let n=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,l=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)})}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach(e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()})}dispose(){let e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){let e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){let e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),math_vector_Vector3.TransformNormalToRef(AudioSceneComponent._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_AUDIO);t||(t=new AudioSceneComponent(e),e._addComponent(t))};let BakedVertexAnimationManager=class BakedVertexAnimationManager{constructor(e){if(this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,!(e=e||engineStore_EngineStore.LastCreatedScene))return;this._scene=e,this.animationParameters=new math_vector_Vector4(0,0,0,30)}_markSubMeshesAsAttributesDirty(){for(let e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;let i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){let e=new BakedVertexAnimationManager(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,r=30){this.animationParameters=new math_vector_Vector4(e,t,i,r)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){decorators_SerializationHelper.Clone(()=>e,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}parse(e,t,i){decorators_SerializationHelper.Parse(()=>this,e,t,i)}};__decorate([serializeAsTexture(),expandToProperty("_markSubMeshesAsAttributesDirty")],BakedVertexAnimationManager.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markSubMeshesAsAttributesDirty")],BakedVertexAnimationManager.prototype,"isEnabled",void 0),__decorate([serialize()],BakedVertexAnimationManager.prototype,"animationParameters",void 0),__decorate([serialize()],BakedVertexAnimationManager.prototype,"time",void 0);let thinTexture_ThinTexture=class thinTexture_ThinTexture{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(null==e?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Size.Zero(),this._cachedBaseSize=Size.Zero(),this._initialSamplingMode=2,this._texture=thinTexture_ThinTexture._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(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;this._texture._size&&(this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size)}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.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight):(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)}};let baseTexture_BaseTexture=class baseTexture_BaseTexture extends thinTexture_ThinTexture{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,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){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,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=guid_RandomGUID()),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=0,this.wrapR=1,this.anisotropicFilteringLevel=baseTexture_BaseTexture.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 observable_Observable,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?baseTexture_BaseTexture._IsScene(e)?this._scene=e:this._engine=e:this._scene=engineStore_EngineStore.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}checkTransformsAreIdentical(e){return null!==e}getTextureMatrix(){return math_vector_Matrix.IdentityReadOnly}getReflectionTextureMatrix(){return math_vector_Matrix.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,a){let n=this._getEngine();if(!n)return null;let o=n._getUseSRGBBuffer(!!s,t),l=n.getLoadedTexturesCache();for(let n=0;n=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let 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;let t=decorators_SerializationHelper.Serialize(this);return decorators_SerializationHelper.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0===i){t();return}for(let r=0;r{0==--i&&t()}):0==--i&&t()}}}static _IsScene(e){return"Scene"===e.getClassName()}};function GenerateBase64StringFromPixelData(e,t,i=!1){let r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT,i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}let a=document.createElement("canvas");a.width=r,a.height=s;let n=a.getContext("2d");if(!n)return null;let o=n.createImageData(r,s),l=o.data;if(l.set(e),n.putImageData(o,0,0),i){let e=document.createElement("canvas");e.width=r,e.height=s;let t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(a,0,0),e.toDataURL("image/png")):null}return a.toDataURL("image/png")}function GenerateBase64StringFromTexture(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=e._readPixelsSync(t,i);return s?GenerateBase64StringFromPixelData(s,e.getSize(),r.invertY):null}async function GenerateBase64StringFromTextureAsync(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=await e.readPixels(t,i);return s?GenerateBase64StringFromPixelData(s,e.getSize(),r.invertY):null}baseTexture_BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,__decorate([serialize()],baseTexture_BaseTexture.prototype,"uniqueId",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"name",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"metadata",void 0),__decorate([serialize("hasAlpha")],baseTexture_BaseTexture.prototype,"_hasAlpha",void 0),__decorate([serialize("getAlphaFromRGB")],baseTexture_BaseTexture.prototype,"_getAlphaFromRGB",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"level",void 0),__decorate([serialize("coordinatesIndex")],baseTexture_BaseTexture.prototype,"_coordinatesIndex",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"optimizeUVAllocation",void 0),__decorate([serialize("coordinatesMode")],baseTexture_BaseTexture.prototype,"_coordinatesMode",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"wrapU",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"wrapV",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"wrapR",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"anisotropicFilteringLevel",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"isCube",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"is3D",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"is2DArray",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"gammaSpace",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"invertZ",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"lodLevelInAlpha",void 0),__decorate([serialize()],baseTexture_BaseTexture.prototype,"lodGenerationOffset",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"lodGenerationScale",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"linearSpecularLOD",null),__decorate([serializeAsTexture()],baseTexture_BaseTexture.prototype,"irradianceTexture",null),__decorate([serialize()],baseTexture_BaseTexture.prototype,"isRenderTarget",void 0);let texture_Texture=class texture_Texture extends baseTexture_BaseTexture{static _CreateVideoTexture(e,t,i,r=!1,s=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,n={},o,l=5){throw _WarnImport("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,i,r,s=texture_Texture.TRILINEAR_SAMPLINGMODE,a=null,n=null,o=null,l=!1,h,c,u,d,_){var p,f,m,g,v,x,b,T,S,C;let E;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._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 observable_Observable,this._isBlocking=!0,this.name=e||"",this.url=e;let y=!1,R=null,P=!0;"object"==typeof i&&null!==i?(E=null!==(p=i.noMipmap)&&void 0!==p&&p,r=null!==(f=i.invertY)&&void 0!==f?f:!CompatibilityOptions.UseOpenGLOrientationForUV,s=null!==(m=i.samplingMode)&&void 0!==m?m:texture_Texture.TRILINEAR_SAMPLINGMODE,a=null!==(g=i.onLoad)&&void 0!==g?g:null,n=null!==(v=i.onError)&&void 0!==v?v:null,o=null!==(x=i.buffer)&&void 0!==x?x:null,l=null!==(b=i.deleteBuffer)&&void 0!==b&&b,h=i.format,c=i.mimeType,u=i.loaderOptions,d=i.creationFlags,y=null!==(T=i.useSRGBBuffer)&&void 0!==T&&T,R=null!==(S=i.internalTexture)&&void 0!==S?S:null,P=null!==(C=i.gammaSpace)&&void 0!==C?C:P):E=!!i,this._gammaSpace=P,this._noMipmap=E,this._invertY=void 0===r?!CompatibilityOptions.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=o,this._deleteBuffer=l,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=y,this._forcedExtension=_,h&&(this._format=h);let A=this.getScene(),M=this._getEngine();if(!M)return;M.onBeforeTextureInitObservable.notifyObservers(this);let load=()=>{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),a&&a(),!this.isBlocking&&A&&A.resetCachedMaterial()},errorHandler=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},n&&n(e,t),texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!R){this._delayedOnLoad=load,this._delayedOnError=errorHandler;return}if(this._texture=null!=R?R:this._getFromCache(this.url,E,s,this._invertY,y,this.isCube),this._texture){if(this._texture.isReady)TimingTools.SetImmediate(()=>load());else{let e=this._texture.onLoadedObservable.add(load);this._texture.onErrorObservable.add(t=>{var i;errorHandler(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)})}}else if(A&&A.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=load,this._delayedOnError=errorHandler;else{try{this._texture=M.createTexture(this.url,E,this._invertY,A,s,load,errorHandler,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,y)}catch(e){throw errorHandler("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,e=>e.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;let e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?TimingTools.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,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}checkTransformsAreIdentical(e){return null!==e&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}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=math_vector_Matrix.Zero(),this._rowGenerationMatrix=new math_vector_Matrix,this._t0=math_vector_Vector3.Zero(),this._t1=math_vector_Vector3.Zero(),this._t2=math_vector_Vector3.Zero()),math_vector_Matrix.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(math_vector_Matrix.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,math_vector_TmpVectors.Matrix[0]),math_vector_Matrix.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,math_vector_TmpVectors.Matrix[1]),math_vector_Matrix.ScalingToRef(this._cachedUScale,this._cachedVScale,0,math_vector_TmpVectors.Matrix[2]),math_vector_Matrix.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,math_vector_TmpVectors.Matrix[3]),math_vector_TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(math_vector_TmpVectors.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),math_vector_Matrix.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));let t=this.getScene();return t&&this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e||this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode&&(this.coordinatesMode!==texture_Texture.PROJECTION_MODE||this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag))return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=math_vector_Matrix.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=math_vector_Matrix.Zero());let 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 texture_Texture.PLANAR_MODE:math_vector_Matrix.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 texture_Texture.PROJECTION_MODE:{math_vector_Matrix.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:math_vector_Matrix.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let 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 decorators_SerializationHelper.Clone(()=>new texture_Texture(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;let i=this.name;!texture_Texture.SerializeBuffers&&this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let r=super.serialize(texture_Texture._SerializeInternalTextureUniqueId);return r?((texture_Texture.SerializeBuffers||texture_Texture.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(r.base64String=this._buffer,r.name=r.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?r.base64String="data:image/png;base64,"+stringTools_EncodeArrayBufferToBase64(this._buffer):(texture_Texture.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(r.base64String=!this._engine||this._engine._features.supportSyncTextureRead?GenerateBase64StringFromTexture(this):GenerateBase64StringFromTextureAsync(this))),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r._creationFlags=this._creationFlags,r._useSRGBBuffer=this._useSRGBBuffer,texture_Texture._SerializeInternalTextureUniqueId&&(r.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),r.noMipmap=this._noMipmap,this.name=i,r):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){let r;if(e.customType){let r=InstantiationTools.Instantiate(e.customType),s=r.Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return texture_Texture._CubeTextureParser(e,t,i);let s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;if(s){let i=t.getEngine().getLoadedTexturesCache();for(let t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}let onLoaded=t=>{var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){let i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{var s,a,n;let o=!0;if(e.noMipmap&&(o=!1),e.mirrorPlane){let i=texture_Texture._CreateMirror(e.name,e.renderTargetSize,t,o);return i._waitingRenderList=e.renderList,i.mirrorPlane=math_plane_Plane.FromArray(e.mirrorPlane),onLoaded(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{onLoaded(s)},null!==(a=e._creationFlags)&&void 0!==a?a:0,null!==(n=e._useSRGBBuffer)&&void 0!==n&&n)).name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||texture_Texture.UseSerializedUrlIfAny)&&(a=e.url);let n={noMipmap:!o,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{onLoaded(s)},internalTexture:r};s=new texture_Texture(a,t,n)}return s}},e,t);return a}static CreateFromBase64String(e,t,i,r,s,a=texture_Texture.TRILINEAR_SAMPLINGMODE,n=null,o=null,l=5,h){return new texture_Texture("data:"+t,i,r,s,a,n,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,r=!1,s,a=!0,n=texture_Texture.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,c){return"data:"!==e.substr(0,5)&&(e="data:"+e),new texture_Texture(e,i,s,a,n,o,l,t,r,h,void 0,void 0,c)}};function _convertRGBtoRGBATextureData(e,t,i,r){let s;let a=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),a=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r{throw _WarnImport("CubeTexture")},texture_Texture._CreateMirror=(e,t,i,r)=>{throw _WarnImport("MirrorTexture")},texture_Texture._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw _WarnImport("RenderTargetTexture")},texture_Texture.NEAREST_SAMPLINGMODE=1,texture_Texture.NEAREST_NEAREST_MIPLINEAR=8,texture_Texture.BILINEAR_SAMPLINGMODE=2,texture_Texture.LINEAR_LINEAR_MIPNEAREST=11,texture_Texture.TRILINEAR_SAMPLINGMODE=3,texture_Texture.LINEAR_LINEAR_MIPLINEAR=3,texture_Texture.NEAREST_NEAREST_MIPNEAREST=4,texture_Texture.NEAREST_LINEAR_MIPNEAREST=5,texture_Texture.NEAREST_LINEAR_MIPLINEAR=6,texture_Texture.NEAREST_LINEAR=7,texture_Texture.NEAREST_NEAREST=1,texture_Texture.LINEAR_NEAREST_MIPNEAREST=9,texture_Texture.LINEAR_NEAREST_MIPLINEAR=10,texture_Texture.LINEAR_LINEAR=2,texture_Texture.LINEAR_NEAREST=12,texture_Texture.EXPLICIT_MODE=0,texture_Texture.SPHERICAL_MODE=1,texture_Texture.PLANAR_MODE=2,texture_Texture.CUBIC_MODE=3,texture_Texture.PROJECTION_MODE=4,texture_Texture.SKYBOX_MODE=5,texture_Texture.INVCUBIC_MODE=6,texture_Texture.EQUIRECTANGULAR_MODE=7,texture_Texture.FIXED_EQUIRECTANGULAR_MODE=8,texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,texture_Texture.CLAMP_ADDRESSMODE=0,texture_Texture.WRAP_ADDRESSMODE=1,texture_Texture.MIRROR_ADDRESSMODE=2,texture_Texture.UseSerializedUrlIfAny=!1,__decorate([serialize()],texture_Texture.prototype,"url",void 0),__decorate([serialize()],texture_Texture.prototype,"uOffset",void 0),__decorate([serialize()],texture_Texture.prototype,"vOffset",void 0),__decorate([serialize()],texture_Texture.prototype,"uScale",void 0),__decorate([serialize()],texture_Texture.prototype,"vScale",void 0),__decorate([serialize()],texture_Texture.prototype,"uAng",void 0),__decorate([serialize()],texture_Texture.prototype,"vAng",void 0),__decorate([serialize()],texture_Texture.prototype,"wAng",void 0),__decorate([serialize()],texture_Texture.prototype,"uRotationCenter",void 0),__decorate([serialize()],texture_Texture.prototype,"vRotationCenter",void 0),__decorate([serialize()],texture_Texture.prototype,"wRotationCenter",void 0),__decorate([serialize()],texture_Texture.prototype,"homogeneousRotationInUVTransform",void 0),__decorate([serialize()],texture_Texture.prototype,"isBlocking",null),h["BABYLON.Texture"]=texture_Texture,decorators_SerializationHelper._TextureParser=texture_Texture.Parse,ThinEngine.prototype.updateRawTexture=function(e,t,i,r,s=null,a=0,n=!1){if(!e)return;let o=this._getRGBABufferInternalSizedFormat(a,i,n),l=this._getInternalFormat(i),h=this._getWebGLTextureType(a);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.type=a,e.invertY=r,e._compression=s),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),s&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[s],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e.width,e.height,0,l,h,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},ThinEngine.prototype.createRawTexture=function(e,t,i,r,s,a,n,o=null,l=0,h=0,c=!1){let u=new internalTexture_InternalTexture(this,$.Raw);u.baseWidth=t,u.baseHeight=i,u.width=t,u.height=i,u.format=r,u.generateMipMaps=s,u.samplingMode=n,u.invertY=a,u._compression=o,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,r,a,o,l,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);let d=this._getSamplingParameters(n,s);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),s&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},ThinEngine.prototype.createRawCubeTexture=function(e,t,i,r,s,a,n,o=null){let l=this._gl,h=new internalTexture_InternalTexture(this,$.CubeRaw);h.isCube=!0,h.format=i,h.type=r,this._doNotHandleContextLost||(h._bufferViewArray=e);let c=this._getWebGLTextureType(r),u=this._getInternalFormat(i);u===l.RGB&&(u=l.RGBA),c!==l.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==l.FLOAT||this._caps.textureFloatRender?c!==l.HALF_FLOAT||this._caps.colorBufferFloat||(s=!1,logger_Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(s=!1,logger_Logger.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(s=!1,n=1,logger_Logger.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(s=!1,n=1,logger_Logger.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")),h.width=t,h.height=t,h.invertY=a,h._compression=o;let d=!this.needPOTTextures||tools_Tools.IsExponentOfTwo(h.width)&&tools_Tools.IsExponentOfTwo(h.height);if(d||(s=!1),e)this.updateRawCubeTexture(h,e,i,r,a,o);else{let e=this._getRGBABufferInternalSizedFormat(r);this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,h,!0);for(let t=0;t<6;t++)o?l.compressedTexImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this.getCaps().s3tc[o],h.width,h.height,0,void 0):l.texImage2D(l.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,e,h.width,h.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,h,!0),e&&s&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);let _=this._getSamplingParameters(n,s);return l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MAG_FILTER,_.mag),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_MIN_FILTER,_.min),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_CUBE_MAP,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),this._bindTextureDirectly(l.TEXTURE_CUBE_MAP,null),h.generateMipMaps=s,h.samplingMode=n,h.isReady=!0,h},ThinEngine.prototype.updateRawCubeTexture=function(e,t,i,r,s,a=null,n=0){e._bufferViewArray=t,e.format=i,e.type=r,e.invertY=s,e._compression=a;let o=this._gl,l=this._getWebGLTextureType(r),h=this._getInternalFormat(i),c=this._getRGBABufferInternalSizedFormat(r),u=!1;h===o.RGB&&(h=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===s||!!s),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let i=0;i<6;i++){let s=t[i];a?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,n,this.getCaps().s3tc[a],e.width,e.height,0,s):(u&&(s=_convertRGBtoRGBATextureData(s,e.width,e.height,r)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+i,n,c,e.width,e.height,0,h,l,s))}let d=!this.needPOTTextures||tools_Tools.IsExponentOfTwo(e.width)&&tools_Tools.IsExponentOfTwo(e.height);d&&e.generateMipMaps&&0===n&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},ThinEngine.prototype.createRawCubeTextureFromUrl=function(e,t,i,r,s,a,n,o,l=null,h=null,c=3,u=!1){let d=this._gl,_=this.createRawCubeTexture(null,i,r,s,!a,u,c,null);null==t||t.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_);let internalCallback=e=>{let i=_.width,a=n(e);if(a){if(o){let e=this._getWebGLTextureType(s),t=this._getInternalFormat(r),n=this._getRGBABufferInternalSizedFormat(s),l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);let h=o(a);for(let r=0;r>r;for(let i=0;i<6;i++){let o=h[r][i];l&&(o=_convertRGBtoRGBATextureData(o,a,a,s)),d.texImage2D(i,r,n,a,a,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(_,a,r,s,u);_.isReady=!0,null==t||t.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,e=>{internalCallback(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(_),h&&e&&h(e.status+" "+e.statusText,i)}),_},ThinEngine.prototype.createRawTexture2DArray=_makeCreateRawTextureFunction(!1),ThinEngine.prototype.createRawTexture3D=_makeCreateRawTextureFunction(!0),ThinEngine.prototype.updateRawTexture2DArray=_makeUpdateRawTextureFunction(!1),ThinEngine.prototype.updateRawTexture3D=_makeUpdateRawTextureFunction(!0);let rawTexture_RawTexture=class rawTexture_RawTexture extends texture_Texture{constructor(e,t,i,r,s,a=!0,n=!1,o=3,l=0,h,c){if(super(null,s,!a,n,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,!this._engine)return;this._engine._caps.textureFloatLinearFiltering||1!==l||(o=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(o=1),this._texture=this._engine.createRawTexture(e,t,i,r,a,n,o,null,l,null!=h?h:0,null!=c&&c),this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,r,s=!0,a=!1,n=3){return new rawTexture_RawTexture(e,t,i,1,r,s,a,n)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,a=!1,n=3){return new rawTexture_RawTexture(e,t,i,2,r,s,a,n)}static CreateAlphaTexture(e,t,i,r,s=!0,a=!1,n=3){return new rawTexture_RawTexture(e,t,i,0,r,s,a,n)}static CreateRGBTexture(e,t,i,r,s=!0,a=!1,n=3,o=0,l=0,h=!1){return new rawTexture_RawTexture(e,t,i,4,r,s,a,n,o,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,a=!1,n=3,o=0,l=0,h=!1){return new rawTexture_RawTexture(e,t,i,5,r,s,a,n,o,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,a=!1,n=3,o=0,l=!1){return new rawTexture_RawTexture(e,t,i,5,r,s,a,n,o,1,l)}static CreateRTexture(e,t,i,r,s=!0,a=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,o=1){return new rawTexture_RawTexture(e,t,i,6,r,s,a,n,o)}static CreateRStorageTexture(e,t,i,r,s=!0,a=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,o=1){return new rawTexture_RawTexture(e,t,i,6,r,s,a,n,o,1)}};let AutoRotationBehavior=class AutoRotationBehavior{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;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===pointerEvents_PointerEventTypes.POINTERDOWN){this._isPointerDown=!0;return}e.type===pointerEvents_PointerEventTypes.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let e=precisionDate_PrecisionDate.Now,t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();let i=e-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=null!=e?e:precisionDate_PrecisionDate.Now}_reachTargetAlpha(){return!!this._attachedCamera&&!!this.targetAlpha&&.001>Math.abs(this._attachedCamera.alpha-this.targetAlpha)}_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=precisionDate_PrecisionDate.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)}};let BouncingBehavior=class BouncingBehavior{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=[]}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;let t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add(e=>{if(!e)return;e.computeWorldMatrix(!0);let 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||(BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode),this._radiusBounceTransition=animation_Animation.CreateAnimation("radius",animation_Animation.ANIMATIONTYPE_FLOAT,60,BouncingBehavior.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=animation_Animation.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()}};BouncingBehavior.EasingFunction=new BackEase(.3),BouncingBehavior.EasingMode=EasingFunction.EASINGMODE_EASEOUT;let FramingBehavior=class FramingBehavior{constructor(){this.onTargetFramingAnimationEndObservable=new observable_Observable,this._mode=FramingBehavior.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=[],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;let t=this._attachedCamera.getScene();FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===pointerEvents_PointerEventTypes.POINTERDOWN){this._isPointerDown=!0;return}e.type===pointerEvents_PointerEventTypes.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(e=>{e&&this.zoomOnMesh(e,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;let 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,i=null){e.computeWorldMatrix(!0);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new math_vector_Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}))&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===FramingBehavior.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=precisionDate_PrecisionDate.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>.5*Math.PI&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=animation_Animation.CreateAnimation("beta",animation_Animation.ANIMATIONTYPE_FLOAT,60,FramingBehavior.EasingFunction));let e=animation_Animation.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=precisionDate_PrecisionDate.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)}};FramingBehavior.EasingFunction=new ExponentialEase,FramingBehavior.EasingMode=EasingFunction.EASINGMODE_EASEINOUT,FramingBehavior.IgnoreBoundsSizeMode=0,FramingBehavior.FitFrustumSidesMode=1;let ray_Ray=class ray_Ray{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new ray_Ray(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r,s,a,n;let o=ray_Ray._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),l=ray_Ray._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),h=0,c=Number.MAX_VALUE;if(1e-7>Math.abs(this.direction.x)){if(this.origin.xl.x)return!1}else if(r=1/this.direction.x,s=(o.x-this.origin.x)*r,(a=(l.x-this.origin.x)*r)==-1/0&&(a=1/0),s>a&&(n=s,s=a,a=n),(h=Math.max(s,h))>(c=Math.min(a,c)))return!1;if(1e-7>Math.abs(this.direction.y)){if(this.origin.yl.y)return!1}else if(r=1/this.direction.y,s=(o.y-this.origin.y)*r,(a=(l.y-this.origin.y)*r)==-1/0&&(a=1/0),s>a&&(n=s,s=a,a=n),(h=Math.max(s,h))>(c=Math.min(a,c)))return!1;if(1e-7>Math.abs(this.direction.z)){if(this.origin.zl.z)return!1}else if(r=1/this.direction.z,s=(o.z-this.origin.z)*r,(a=(l.z-this.origin.z)*r)==-1/0&&(a=1/0),s>a&&(n=s,s=a,a=n),(h=Math.max(s,h))>(c=Math.min(a,c)))return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,a=i*i+r*r+s*s,n=e.radius+t,o=n*n;if(a<=o)return!0;let l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&a-l*l<=o}intersectsTriangle(e,t,i){let r=ray_Ray._TmpVector3[0],s=ray_Ray._TmpVector3[1],a=ray_Ray._TmpVector3[2],n=ray_Ray._TmpVector3[3],o=ray_Ray._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),math_vector_Vector3.CrossToRef(this.direction,s,a);let l=math_vector_Vector3.Dot(r,a);if(0===l)return null;let h=1/l;this.origin.subtractToRef(e,n);let c=math_vector_Vector3.Dot(n,a)*h;if(c<0||c>1)return null;math_vector_Vector3.CrossToRef(n,r,o);let u=math_vector_Vector3.Dot(this.direction,o)*h;if(u<0||c+u>1)return null;let d=math_vector_Vector3.Dot(s,o)*h;return d>this.length?null:new IntersectionInfo(1-c-u,c,d)}intersectsPlane(e){let t;let i=math_vector_Vector3.Dot(e.normal,this.direction);if(999999997475243e-21>Math.abs(i))return null;{let r=math_vector_Vector3.Dot(e.normal,this.origin);return(t=(-e.d-r)/i)<0?t<-.000000999999997475243?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let e=(this.origin.y-t)/this.direction.y;if(e>0)return null;return new math_vector_Vector3(this.origin.x+-(this.direction.x*e),t,this.origin.z+-(this.direction.z*e))}case"x":{let e=(this.origin.x-t)/this.direction.x;if(e>0)return null;return new math_vector_Vector3(t,this.origin.y+-(this.direction.y*e),this.origin.z+-(this.direction.z*e))}case"z":{let e=(this.origin.z-t)/this.direction.z;if(e>0)return null;return new math_vector_Vector3(this.origin.x+-(this.direction.x*e),this.origin.y+-(this.direction.y*e),t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,a=!1){let n=math_vector_TmpVectors.Matrix[0];return e.getWorldMatrix().invertToRef(n),this._tmpRay?ray_Ray.TransformToRef(this,n,this._tmpRay):this._tmpRay=ray_Ray.Transform(this,n),e.intersects(this._tmpRay,t,i,r,s,a)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=math_vector_TmpVectors.Vector3[0],a=math_vector_TmpVectors.Vector3[1],n=math_vector_TmpVectors.Vector3[2],o=math_vector_TmpVectors.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(ray_Ray._Rayl,n),r.addToRef(n,a),e.subtractToRef(r,o);let l=math_vector_Vector3.Dot(s,s),h=math_vector_Vector3.Dot(s,n),c=math_vector_Vector3.Dot(n,n),u=math_vector_Vector3.Dot(s,o),d=math_vector_Vector3.Dot(n,o),_=l*c-h*h,p,f=_,m,g=_;_f&&(p=f,m=d+h,g=c)),m<0?(m=0,0>-u?p=0:-u>l?p=f:(p=-u,f=l)):m>g&&(m=g,-u+h<0?p=0:-u+h>l?p=f:(p=-u+h,f=l));let v=Math.abs(p)0&&x<=this.length&&S.lengthSquared()=e.distance))?h:null},scene_Scene.prototype._internalPick=function(e,t,i,r,s){let a=null,n=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),a=this.cameraToUseForPointers||this.activeCamera;for(let n=0;n(this._tempPickingRay||(this._tempPickingRay=ray_Ray.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay),i,r,!0);return a&&(a.ray=this.createPickingRay(e,t,math_vector_Matrix.Identity(),s||null)),a},Object.defineProperty(scene_Scene.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),scene_Scene.prototype.pick=function(e,t,i,r,s,a,n=!1){let o=this._internalPick((i,r)=>(this._tempPickingRay||(this._tempPickingRay=ray_Ray.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,r),this._tempPickingRay),i,r,!1,a);return o&&(o.ray=this.createPickingRay(e,t,math_vector_Matrix.Identity(),s||null)),o},scene_Scene.prototype.pickWithRay=function(e,t,i,r){let s=this._internalPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=math_vector_Matrix.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ray_Ray.Zero()),ray_Ray.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s},scene_Scene.prototype.multiPick=function(e,t,i,r,s){return this._internalMultiPick(i=>this.createPickingRay(e,t,i,r||null),i,s)},scene_Scene.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=math_vector_Matrix.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ray_Ray.Zero()),ray_Ray.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i)},camera_Camera.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new ray_Ray(math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),e),e,t,i)},camera_Camera.prototype.getForwardRayToRef=function(e,t=100,i,r){return i||(i=this.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(this.position),math_vector_TmpVectors.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),math_vector_Vector3.TransformNormalToRef(math_vector_TmpVectors.Vector3[2],i,math_vector_TmpVectors.Vector3[3]),math_vector_Vector3.NormalizeToRef(math_vector_TmpVectors.Vector3[3],e.direction),e};let pivotTools_PivotTools=class pivotTools_PivotTools{static _RemoveAndStorePivotPoint(e){e&&0===pivotTools_PivotTools._PivotCached&&(e.getPivotPointToRef(pivotTools_PivotTools._OldPivotPoint),pivotTools_PivotTools._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(math_vector_Matrix.IdentityReadOnly),pivotTools_PivotTools._OldPivotPoint.subtractToRef(e.getPivotPoint(),pivotTools_PivotTools._PivotTranslation),pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1,1,1),pivotTools_PivotTools._PivotTmpVector.subtractInPlace(e.scaling),pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation),e.position.addInPlace(pivotTools_PivotTools._PivotTmpVector))),pivotTools_PivotTools._PivotCached++}static _RestorePivotPoint(e){e&&!pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0,0,0)&&1===pivotTools_PivotTools._PivotCached&&(e.setPivotPoint(pivotTools_PivotTools._OldPivotPoint),e._postMultiplyPivotMatrix=pivotTools_PivotTools._PivotPostMultiplyPivotMatrix,pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1,1,1),pivotTools_PivotTools._PivotTmpVector.subtractInPlace(e.scaling),pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation),e.position.subtractInPlace(pivotTools_PivotTools._PivotTmpVector)),this._PivotCached--}};function CreatePlaneVertexData(e){let t=[],i=[],r=[],s=[],a=e.width||e.size||1,n=e.height||e.size||1,o=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,l=a/2,h=n/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,CompatibilityOptions.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,CompatibilityOptions.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,CompatibilityOptions.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,CompatibilityOptions.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),mesh_vertexData_VertexData._ComputeSides(o,i,t,r,s,e.frontUVs,e.backUVs);let c=new mesh_vertexData_VertexData;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function planeBuilder_CreatePlane(e,t={},i=null){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreatePlaneVertexData(t);return s.applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}pivotTools_PivotTools._PivotCached=0,pivotTools_PivotTools._OldPivotPoint=new math_vector_Vector3,pivotTools_PivotTools._PivotTranslation=new math_vector_Vector3,pivotTools_PivotTools._PivotTmpVector=new math_vector_Vector3,pivotTools_PivotTools._PivotPostMultiplyPivotMatrix=!1,mesh_vertexData_VertexData.CreatePlane=CreatePlaneVertexData,mesh_Mesh.CreatePlane=(e,t,i,r,s)=>planeBuilder_CreatePlane(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);let pointerDragBehavior_PointerDragBehavior=class pointerDragBehavior_PointerDragBehavior{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new observable_Observable,this.onDragStartObservable=new observable_Observable,this.onDragEndObservable=new observable_Observable,this.onEnabledObservable=new observable_Observable,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new math_vector_Vector3(0,0,0),this._alternatePickedPoint=new math_vector_Vector3(0,0,0),this._worldDragAxis=new math_vector_Vector3(0,0,0),this._targetPosition=new math_vector_Vector3(0,0,0),this._attachedToElement=!1,this._startDragRay=new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),this._lastPointerRay={},this._dragDelta=new math_vector_Vector3,this._pointA=new math_vector_Vector3(0,0,0),this._pointC=new math_vector_Vector3(0,0,0),this._localAxis=new math_vector_Vector3(0,0,0),this._lookAt=new math_vector_Vector3(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,pointerDragBehavior_PointerDragBehavior._PlaneScene||(this._debugMode?pointerDragBehavior_PointerDragBehavior._PlaneScene=this._scene:(pointerDragBehavior_PointerDragBehavior._PlaneScene=new scene_Scene(this._scene.getEngine(),{virtual:!0}),pointerDragBehavior_PointerDragBehavior._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{pointerDragBehavior_PointerDragBehavior._PlaneScene.dispose(),pointerDragBehavior_PointerDragBehavior._PlaneScene=null}))),this._dragPlane=planeBuilder_CreatePlane("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:mesh_Mesh.DOUBLESIDE},pointerDragBehavior_PointerDragBehavior._PlaneScene),this.lastDragPosition=new math_vector_Vector3(0,0,0);let i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(e=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(e.type==pointerEvents_PointerEventTypes.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==pointerEvents_PointerEventTypes.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==e.event.pointerId&&(this._activeDragButton===e.event.button||-1===this._activeDragButton)&&this.releaseDrag();else if(e.type==pointerEvents_PointerEventTypes.POINTERMOVE){let t=e.event.pointerId;if(this.currentDraggingPointerId===pointerDragBehavior_PointerDragBehavior._AnyMouseId&&t!==pointerDragBehavior_PointerDragBehavior._AnyMouseId){let i=e.event,r="mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent;r&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new ray_Ray(new math_vector_Vector3,new math_vector_Vector3)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let e=!1;pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}})}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){let e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=pointerDragBehavior_PointerDragBehavior._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===pointerDragBehavior_PointerDragBehavior._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);let r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;let t=this._pickWithRayOnDragPlane(e);if(t){pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?math_vector_Vector3.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=math_vector_Vector3.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(math_vector_Vector3.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(!this._useAlternatePickedPointAboveMaxDragAngle)return null;{this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*math_vector_Vector3.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);let t=math_vector_Vector3.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}}let i=pointerDragBehavior_PointerDragBehavior._PlaneScene.pickWithRay(e,e=>e==this._dragPlane);return i&&i.hit&&i.pickedMesh&&i.pickedPoint?i.pickedPoint:null}_updateDragPlanePosition(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?math_vector_Vector3.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),e.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(math_vector_Vector3.Dot(this._localAxis,this._pointC))>.999?Math.abs(math_vector_Vector3.Dot(math_vector_Vector3.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(math_vector_Vector3.Right()):this._lookAt.copyFrom(math_vector_Vector3.UpReadOnly):(math_vector_Vector3.CrossToRef(this._localAxis,this._pointC,this._lookAt),math_vector_Vector3.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?math_vector_Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}};pointerDragBehavior_PointerDragBehavior._AnyMouseId=-2;let webXRFeaturesManager_WebXRFeatureName=class webXRFeaturesManager_WebXRFeatureName{};webXRFeaturesManager_WebXRFeatureName.ANCHOR_SYSTEM="xr-anchor-system",webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER="xr-background-remover",webXRFeaturesManager_WebXRFeatureName.HIT_TEST="xr-hit-test",webXRFeaturesManager_WebXRFeatureName.MESH_DETECTION="xr-mesh-detection",webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS="xr-physics-controller",webXRFeaturesManager_WebXRFeatureName.PLANE_DETECTION="xr-plane-detection",webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION="xr-controller-pointer-selection",webXRFeaturesManager_WebXRFeatureName.TELEPORTATION="xr-controller-teleportation",webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS="xr-feature-points",webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING="xr-hand-tracking",webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING="xr-image-tracking",webXRFeaturesManager_WebXRFeatureName.NEAR_INTERACTION="xr-near-interaction",webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY="xr-dom-overlay",webXRFeaturesManager_WebXRFeatureName.MOVEMENT="xr-controller-movement",webXRFeaturesManager_WebXRFeatureName.LIGHT_ESTIMATION="xr-light-estimation",webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING="xr-eye-tracking",webXRFeaturesManager_WebXRFeatureName.WALKING_LOCOMOTION="xr-walking-locomotion",webXRFeaturesManager_WebXRFeatureName.LAYERS="xr-layers",webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING="xr-depth-sensing",webXRFeaturesManager_WebXRFeatureName.SPACE_WARP="xr-space-warp";let WebXRFeaturesManager=class WebXRFeaturesManager{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){let s=this._AvailableFeatures[e][t];if(!s)throw Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){let t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){let t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){let t="string"==typeof e?e:e.Name,i=this._features[t];return!!i&&!!i.enabled&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,s=!0){let a="string"==typeof e?e:e.Name,n=0;if("string"==typeof t){if(!t)throw Error(`Error in provided version - ${a} (${t})`);if(-1===(n="stable"===t?WebXRFeaturesManager.GetStableVersionOfFeature(a):"latest"===t?WebXRFeaturesManager.GetLatestVersionOfFeature(a):+t)||isNaN(n))throw Error(`feature not found - ${a} (${t})`)}else n=t;let o=WebXRFeaturesManager._ConflictingFeatures[a];if(void 0!==o&&-1!==this.getEnabledFeatures().indexOf(o))throw Error(`Feature ${a} cannot be enabled while ${o} is enabled.`);let l=this._features[a],h=WebXRFeaturesManager.ConstructFeature(a,n,this._xrSessionManager,i);if(!h)throw Error(`feature not found - ${a}`);l&&this.disableFeature(a);let c=h();if(c.dependsOn){let e=c.dependsOn.every(e=>!!this._features[e]);if(!e)throw Error(`Dependant features missing. Make sure the following features are enabled - ${c.dependsOn.join(", ")}`)}if(c.isCompatible())return this._features[a]={featureImplementation:c,enabled:!0,version:n,required:s},r?this._xrSessionManager.session&&!this._features[a].featureImplementation.attached&&this.attachFeature(a):this._features[a].featureImplementation.disableAutoAttach=!0,this._features[a].featureImplementation;if(!s)return tools_Tools.Warn(`Feature ${a} not compatible with the current environment/browser and was not enabled.`),c;throw Error("required feature not compatible")}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){let t=this.getEnabledFeatures();for(let i of t){let t=this._features[i],r=t.featureImplementation.xrNativeFeatureName;if(r&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),t.featureImplementation.getXRSessionInitExtension){let i=await t.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),i)}}return e}};WebXRFeaturesManager._AvailableFeatures={},WebXRFeaturesManager._ConflictingFeatures={[webXRFeaturesManager_WebXRFeatureName.TELEPORTATION]:webXRFeaturesManager_WebXRFeatureName.MOVEMENT,[webXRFeaturesManager_WebXRFeatureName.MOVEMENT]:webXRFeaturesManager_WebXRFeatureName.TELEPORTATION};let WebXRAbstractFeature=class WebXRAbstractFeature{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName=""}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,e=>this._onXRFrame(e)),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(e=>{e.observable.remove(e.observer)}),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}};let PhysicsJoint=class PhysicsJoint{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}};PhysicsJoint.DistanceJoint=0,PhysicsJoint.HingeJoint=1,PhysicsJoint.BallAndSocketJoint=2,PhysicsJoint.WheelJoint=3,PhysicsJoint.SliderJoint=4,PhysicsJoint.PrismaticJoint=5,PhysicsJoint.UniversalJoint=6,PhysicsJoint.Hinge2Joint=PhysicsJoint.WheelJoint,PhysicsJoint.PointToPointJoint=8,PhysicsJoint.SpringJoint=9,PhysicsJoint.LockJoint=10,mesh_Mesh._PhysicsImpostorParser=function(e,t,i){return new physicsImpostor_PhysicsImpostor(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};let physicsImpostor_PhysicsImpostor=class physicsImpostor_PhysicsImpostor{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=[],this._onAfterPhysicsStepCallbacks=[],this._onPhysicsCollideCallbacks=[],this._deltaPosition=math_vector_Vector3.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new math_vector_Quaternion,this._tmpQuat2=new math_vector_Quaternion,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new math_vector_Quaternion),!this._options.disableBidirectionalTransformation&&this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(e=>{e(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(e=>{e(this)}),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,physicsImpostor_PhysicsImpostor._TmpVecs[0]),this.object.translate(physicsImpostor_PhysicsImpostor._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;let t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter(e=>-1!==e.otherImpostors.indexOf(t)).forEach(i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)}))},!this.object){logger_Logger.Error("No object was provided. A physics object is obligatory");return}if(this.object.parent&&0!==i.mass&&logger_Logger.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),!this._scene)return;this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=math_vector_Quaternion.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new math_vector_Quaternion),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&logger_Logger.Warn("You must affect impostors to children before affecting impostor to parent.")):logger_Logger.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){if(this.object.parent instanceof abstractMesh_AbstractMesh){let e=this.object.parent;return e.physicsImpostor}return null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(!this.object.getBoundingInfo)return physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE;{let e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION;let i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);let r=this.object.getBoundingInfo(),s=r.boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}}getObjectCenter(){if(!this.object.getBoundingInfo)return this.object.position;{let e=this.object.getBoundingInfo();return e.boundingBox.centerWorld}}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):math_vector_Vector3.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):math_vector_Vector3.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){let t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):logger_Logger.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){let t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):logger_Logger.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e],r=-1,s=this._onPhysicsCollideCallbacks.some((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){let t=e.otherImpostors.every(e=>i.indexOf(e)>-1);return t&&(r=s),t}return!1});s?this._onPhysicsCollideCallbacks.splice(r,1):logger_Logger.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):math_vector_Quaternion.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){let r=new PhysicsJoint(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;let a=this._physicsEngine.getPhysicsPlugin();return a.appendAnchor&&this._physicsEngine&&a.appendAnchor(this,e,t,i,r,s),this}addHook(e,t,i,r){if(!this._physicsEngine)return this;let s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor&&this._physicsEngine&&s.appendHook(this,e,t,i,r),this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new physicsImpostor_PhysicsImpostor(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach(e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new math_vector_Quaternion),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,s){let a=physicsImpostor_PhysicsImpostor._TmpVecs[0],n=this.object;if(n.rotationQuaternion){if(s){let i=physicsImpostor_PhysicsImpostor._TmpQuat;n.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,en.WORLD,t)}else e.setRotationQuaternion(n.rotationQuaternion,en.WORLD,t)}a.x=0,a.y=0,a.z=0,i&&(a.x=i.x,a.y=i.y,a.z=i.z,e.getDirectionToRef(a,t,a),null==r&&(r=i.length()),a.x*=r,a.y*=r,a.z*=r),e.getParent()?(a.addInPlace(n.getAbsolutePosition()),e.setAbsolutePosition(a,t)):(t.setAbsolutePosition(n.getAbsolutePosition()),t.position.x-=a.x,t.position.y-=a.y,t.position.z-=a.z)}syncImpostorWithBone(e,t,i,r,s,a){let n=this.object;if(n.rotationQuaternion){if(s){let i=physicsImpostor_PhysicsImpostor._TmpQuat;e.getRotationQuaternionToRef(en.WORLD,t,i),i.multiplyToRef(s,n.rotationQuaternion)}else e.getRotationQuaternionToRef(en.WORLD,t,n.rotationQuaternion)}let o=physicsImpostor_PhysicsImpostor._TmpVecs[0],l=physicsImpostor_PhysicsImpostor._TmpVecs[1];a||((a=physicsImpostor_PhysicsImpostor._TmpVecs[2]).x=0,a.y=1,a.z=0),e.getDirectionToRef(a,t,l),e.getAbsolutePositionToRef(t,o),null==r&&i&&(r=i.length()),null!=r&&(o.x+=l.x*r,o.y+=l.y*r,o.z+=l.z*r),n.setAbsolutePosition(o)}};physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE=new math_vector_Vector3(1,1,1),physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION=math_vector_Quaternion.Identity(),physicsImpostor_PhysicsImpostor._TmpVecs=arrayTools_ArrayTools.BuildArray(3,math_vector_Vector3.Zero),physicsImpostor_PhysicsImpostor._TmpQuat=math_vector_Quaternion.Identity(),physicsImpostor_PhysicsImpostor.NoImpostor=0,physicsImpostor_PhysicsImpostor.SphereImpostor=1,physicsImpostor_PhysicsImpostor.BoxImpostor=2,physicsImpostor_PhysicsImpostor.PlaneImpostor=3,physicsImpostor_PhysicsImpostor.MeshImpostor=4,physicsImpostor_PhysicsImpostor.CapsuleImpostor=6,physicsImpostor_PhysicsImpostor.CylinderImpostor=7,physicsImpostor_PhysicsImpostor.ParticleImpostor=8,physicsImpostor_PhysicsImpostor.HeightmapImpostor=9,physicsImpostor_PhysicsImpostor.ConvexHullImpostor=10,physicsImpostor_PhysicsImpostor.CustomImpostor=100,physicsImpostor_PhysicsImpostor.RopeImpostor=101,physicsImpostor_PhysicsImpostor.ClothImpostor=102,physicsImpostor_PhysicsImpostor.SoftbodyImpostor=103,function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(eu||(eu={}));let sceneLoader_SceneLoader=class sceneLoader_SceneLoader{static get ForceFullSceneLoadingForIncremental(){return SceneLoaderFlags.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){SceneLoaderFlags.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return SceneLoaderFlags.ShowLoadingScreen}static set ShowLoadingScreen(e){SceneLoaderFlags.ShowLoadingScreen=e}static get loggingLevel(){return SceneLoaderFlags.loggingLevel}static set loggingLevel(e){SceneLoaderFlags.loggingLevel=e}static get CleanBoneMatrixWeights(){return SceneLoaderFlags.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){SceneLoaderFlags.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return sceneLoader_SceneLoader._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){let t=sceneLoader_SceneLoader._RegisteredPlugins[e];return t||(logger_Logger.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"),sceneLoader_SceneLoader.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(let t in sceneLoader_SceneLoader._RegisteredPlugins){let i=sceneLoader_SceneLoader._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return sceneLoader_SceneLoader._RegisteredPlugins[t]}return sceneLoader_SceneLoader.GetDefaultPlugin()}static _GetPluginForFilename(e){let t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));let i=e.lastIndexOf("."),r=e.substring(i,e.length).toLowerCase();return sceneLoader_SceneLoader._GetPluginForExtension(r)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r=e.rawData?"binary data":e.url,s="Unable to load from "+r;return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,r,s,a,n,o){let l;let h=sceneLoader_SceneLoader._GetDirectLoad(e.url);if(e.rawData&&!n)throw"When using ArrayBufferView to load data the file extension must be provided.";let c=n?sceneLoader_SceneLoader._GetPluginForExtension(n):h?sceneLoader_SceneLoader._GetPluginForDirectLoad(e.url):sceneLoader_SceneLoader._GetPluginForFilename(e.url);if(e.rawData&&!c.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";if(!(l=void 0!==c.plugin.createPlugin?c.plugin.createPlugin():c.plugin))throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(sceneLoader_SceneLoader.OnPluginActivatedObservable.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!IsBase64DataUrl(e.url))){if(l.directLoad){let e=l.directLoad(t,h);e.then?e.then(e=>{i(l,e)}).catch(e=>{s("Error in directLoad of _loadData: "+e,e)}):i(l,e)}else i(l,h);return l}let u=c.isBinary,dataCallback=(e,r)=>{if(t.isDisposed){s("Scene has been disposed");return}i(l,e,r)},d=null,_=!1,p=l.onDisposeObservable;p&&p.add(()=>{_=!0,d&&(d.abort(),d=null),a()});let manifestChecked=()=>{if(_)return;let errorCallback=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";d=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,dataCallback,r,u,errorCallback,o):t._loadFile(e.file||e.url,dataCallback,r,!0,u,errorCallback)},f=t.getEngine(),m=f.enableOfflineSupport;if(m){let i=!1;for(let r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}m=!i}return m&&engine_Engine.OfflineProviderFactory?t.offlineProvider=engine_Engine.OfflineProviderFactory(e.url,manifestChecked,f.disableManifestCheck):manifestChecked(),l}static _GetFileInfo(e,t){let i,r;let s=null,a=null;if(t){if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r="arrayBuffer",a=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,r="";else{if("/"===t.substr(0,1))return tools_Tools.Error("Wrong sceneFilename parameter"),null;i=e+t,r=t}}else i=e,r=tools_Tools.GetFilename(e),e=tools_Tools.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:a}}static GetPluginForExtension(e){return sceneLoader_SceneLoader._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!sceneLoader_SceneLoader._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){let t=e.extensions;sceneLoader_SceneLoader._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{let t=e.extensions;Object.keys(t).forEach(i=>{sceneLoader_SceneLoader._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",r=engineStore_EngineStore.LastCreatedScene,s=null,a=null,n=null,o=null,l=""){if(!r)return logger_Logger.Error("No scene available to import mesh to"),null;let h=sceneLoader_SceneLoader._GetFileInfo(t,i);if(!h)return null;let c={};r.addPendingData(c);let disposeHandler=()=>{r.removePendingData(c)},errorHandler=(e,t)=>{let i=sceneLoader_SceneLoader._FormatErrorMessage(h,e,t);n?n(r,i,new RuntimeError(i,b.SceneLoaderError,t)):logger_Logger.Error(i),disposeHandler()},u=a?e=>{try{a(e)}catch(e){errorHandler("Error in onProgress callback: "+e,e)}}:void 0,successHandler=(e,t,i,a,n,o,l)=>{if(r.importedMeshesFiles.push(h.url),s)try{s(e,t,i,a,n,o,l)}catch(e){errorHandler("Error in onSuccess callback: "+e,e)}r.removePendingData(c)};return sceneLoader_SceneLoader._LoadData(h,r,(t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){let s=[],a=[],n=[];t.importMesh(e,r,i,h.rootUrl,s,a,n,errorHandler)&&(r.loadingPluginName=t.name,successHandler(s,a,n,[],[],[],[]))}else t.importMeshAsync(e,r,i,h.rootUrl,u,h.name).then(e=>{r.loadingPluginName=t.name,successHandler(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)}).catch(e=>{errorHandler(e.message,e)})},u,errorHandler,disposeHandler,o,l)}static ImportMeshAsync(e,t,i="",r=engineStore_EngineStore.LastCreatedScene,s=null,a=null,n=""){return new Promise((o,l)=>{sceneLoader_SceneLoader.ImportMesh(e,t,i,r,(e,t,i,r,s,a,n)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:a,lights:n})},s,(e,t,i)=>{l(i||Error(t))},a,n)})}static Load(e,t="",i=engineStore_EngineStore.LastCreatedEngine,r=null,s=null,a=null,n=null,o=""){return i?sceneLoader_SceneLoader.Append(e,t,new scene_Scene(i),r,s,a,n,o):(tools_Tools.Error("No engine available"),null)}static LoadAsync(e,t="",i=engineStore_EngineStore.LastCreatedEngine,r=null,s=null,a=""){return new Promise((n,o)=>{sceneLoader_SceneLoader.Load(e,t,i,e=>{n(e)},r,(e,t,i)=>{o(i||Error(t))},s,a)})}static Append(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=null,s=null,a=null,n=null,o=""){if(!i)return logger_Logger.Error("No scene available to append to"),null;let l=sceneLoader_SceneLoader._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let disposeHandler=()=>{i.removePendingData(h)};sceneLoader_SceneLoader.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));let errorHandler=(e,t)=>{let r=sceneLoader_SceneLoader._FormatErrorMessage(l,e,t);a?a(i,r,new RuntimeError(r,b.SceneLoaderError,t)):logger_Logger.Error(r),disposeHandler()},c=s?e=>{try{s(e)}catch(e){errorHandler("Error in onProgress callback",e)}}:void 0,successHandler=()=>{if(r)try{r(i)}catch(e){errorHandler("Error in onSuccess callback",e)}i.removePendingData(h)};return sceneLoader_SceneLoader._LoadData(l,i,(e,t)=>{e.load?!e.load(i,t,l.rootUrl,errorHandler)||(i.loadingPluginName=e.name,successHandler()):e.loadAsync(i,t,l.rootUrl,c,l.name).then(()=>{i.loadingPluginName=e.name,successHandler()}).catch(e=>{errorHandler(e.message,e)})},c,errorHandler,disposeHandler,n,o)}static AppendAsync(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=null,s=null,a=""){return new Promise((n,o)=>{sceneLoader_SceneLoader.Append(e,t,i,e=>{n(e)},r,(e,t,i)=>{o(i||Error(t))},s,a)})}static LoadAssetContainer(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=null,s=null,a=null,n=null,o=""){if(!i)return logger_Logger.Error("No scene available to load asset container to"),null;let l=sceneLoader_SceneLoader._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let disposeHandler=()=>{i.removePendingData(h)},errorHandler=(e,t)=>{let r=sceneLoader_SceneLoader._FormatErrorMessage(l,e,t);a?a(i,r,new RuntimeError(r,b.SceneLoaderError,t)):logger_Logger.Error(r),disposeHandler()},c=s?e=>{try{s(e)}catch(e){errorHandler("Error in onProgress callback",e)}}:void 0,successHandler=e=>{if(r)try{r(e)}catch(e){errorHandler("Error in onSuccess callback",e)}i.removePendingData(h)};return sceneLoader_SceneLoader._LoadData(l,i,(e,t)=>{if(e.loadAssetContainer){let r=e.loadAssetContainer(i,t,l.rootUrl,errorHandler);r&&(r.populateRootNodes(),i.loadingPluginName=e.name,successHandler(r))}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,c,l.name).then(t=>{t.populateRootNodes(),i.loadingPluginName=e.name,successHandler(t)}).catch(e=>{errorHandler(e.message,e)}):errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},c,errorHandler,disposeHandler,n,o)}static LoadAssetContainerAsync(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=null,s=null){return new Promise((a,n)=>{sceneLoader_SceneLoader.LoadAssetContainer(e,t,i,e=>{a(e)},r,(e,t,i)=>{n(i||Error(t))},s)})}static ImportAnimations(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=!0,s=eu.Clean,a=null,n=null,o=null,l=null,h=null){if(!i){logger_Logger.Error("No scene available to load animations to");return}if(r){for(let e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(e=>{e.dispose()});let e=i.getNodes();e.forEach(e=>{e.animations&&(e.animations=[])})}else switch(s){case eu.Clean:i.animationGroups.slice().forEach(e=>{e.dispose()});break;case eu.Stop:i.animationGroups.forEach(e=>{e.stop()});break;case eu.Sync:i.animationGroups.forEach(e=>{e.reset(),e.restart()});break;case eu.NoSync:break;default:logger_Logger.Error("Unknown animation group loading mode value '"+s+"'");return}let c=i.animatables.length;this.LoadAssetContainer(e,t,i,e=>{e.mergeAnimationsTo(i,i.animatables.slice(c),a),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),n&&n(i)},o,l,h)}static ImportAnimationsAsync(e,t="",i=engineStore_EngineStore.LastCreatedScene,r=!0,s=eu.Clean,a=null,n=null,o=null,l=null,h=null){return new Promise((n,l)=>{sceneLoader_SceneLoader.ImportAnimations(e,t,i,r,s,a,e=>{n(e)},o,(e,t,i)=>{l(i||Error(t))},h)})}};sceneLoader_SceneLoader.NO_LOGGING=0,sceneLoader_SceneLoader.MINIMAL_LOGGING=1,sceneLoader_SceneLoader.SUMMARY_LOGGING=2,sceneLoader_SceneLoader.DETAILED_LOGGING=3,sceneLoader_SceneLoader.OnPluginActivatedObservable=new observable_Observable,sceneLoader_SceneLoader._RegisteredPlugins={},sceneLoader_SceneLoader._ShowingLoadingScreen=!1;let PushMaterial=class PushMaterial extends material_Material{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new math_vector_Matrix,this._storeEffectOnSubMeshes=i}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){let 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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}};(function(e){e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=4]="Vector2",e[e.Vector3=8]="Vector3",e[e.Vector4=16]="Vector4",e[e.Color3=32]="Color3",e[e.Color4=64]="Color4",e[e.Matrix=128]="Matrix",e[e.Object=256]="Object",e[e.AutoDetect=1024]="AutoDetect",e[e.BasedOnInput=2048]="BasedOnInput",e[e.All=4095]="All"})(ed||(ed={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Neutral=4]="Neutral",e[e.VertexAndFragment=3]="VertexAndFragment"}(e_||(e_={}));let NodeMaterialBuildState=class NodeMaterialBuildState{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){let t=e.sharedData.emitComments,i=this.target===e_.Fragment;this.compilationString=` -${t?"//Entry point\n":""}void main(void) { -${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` -${t?"//Constants\n":""}${this._constantDeclaration} -${this.compilationString}`);let r="";for(let e in this.functions)r+=this.functions[e]+` -`;for(let e in this.compilationString=` -${r} -${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} -${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} -${this._injectAtEnd}`),this.compilationString=`${this.compilationString} -}`,this.sharedData.varyingDeclaration&&(this.compilationString=` -${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration} -${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` -${t?"//Samplers\n":""}${this._samplerDeclaration} -${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` -${t?"//Uniforms\n":""}${this._uniformDeclaration} -${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` -${t?"//Attributes\n":""}${this._attributeDeclaration} -${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString),this.extensions){let t=this.extensions[e];this.compilationString=` -${t} -${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return(e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e])?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e)?e+this.sharedData.variableNames[e]:e:(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2D ${e}; -`,this.samplers.push(e))}_emit2DArraySampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; -`,this.samplers.push(e))}_getGLType(e){switch(e){case ed.Float:return"float";case ed.Int:return"int";case ed.Vector2:return"vec2";case ed.Color3:case ed.Vector3:return"vec3";case ed.Color4:case ed.Vector4:return"vec4";case ed.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} -${t} -#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` -`+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] -`;let r=effect_Effect.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(r=t+` -`+r),!i)return r;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] -`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""} -`,this.sharedData.emitComments&&(this.functions[s]=t+` -`+this.functions[s]);return}if(this.functions[s]=effect_Effect.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+` -`+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;ee.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===e_.Vertex||(e.ownerBlock.target===e_.Neutral||e.ownerBlock.target===e_.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===e_.Vertex)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===e_.Vertex||e.target===e_.Vertex||(e.ownerBlock.target===e_.Neutral||e.ownerBlock.target===e_.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===e_.Fragment)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===e_.Fragment||(e.ownerBlock.target===e_.Neutral||e.ownerBlock.target===e_.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=[],this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=ed.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new observable_Observable,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=e_.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===ep.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(t.target===e_.Fragment){if(i.target===e_.Vertex)return ep.TargetIncompatible;for(let e of i.outputs)if(e.ownerBlock.target!=e_.Neutral&&e.isConnectedInVertexShader)return ep.TargetIncompatible}if(this.type!==e.type&&e.innerType!==ed.AutoDetect)return NodeMaterialConnectionPoint.AreEquivalentTypes(this.type,e.type)?ep.Compatible:e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&NodeMaterialConnectionPoint.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?ep.Compatible:ep.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return ep.TypeIncompatible;let r=i,s=t;return(this.direction===ef.Input&&(r=t,s=i),r.isAnAncestorOf(s))?ep.HierarchyIssue:ep.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}};let NodeMaterialBlock=class NodeMaterialBlock{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){(this._target&e)==0&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}constructor(e,t=e_.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=[],this._outputs=[],this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===e_.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=UniqueIdGenerator.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===e_.Neutral}initialize(e){}bind(e,t,i,r){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){let t=e.connectedPoint;return t?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return -1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,s){return(s=null!=s?s:new NodeMaterialConnectionPoint(e,this,ef.Input)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=null!=r?r:new NodeMaterialConnectionPoint(e,this,ef.Output)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(let t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===ed.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(let t of this._outputs)if(!e||!e.target||e.target===e_.Neutral||(e.target&t.target)!=0)return t;return null}getSiblingOutput(e){let t=this._outputs.indexOf(e);return -1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){let s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput))&&this.target!==e_.Vertex&&!!((this.target===e_.VertexAndFragment||this.target===e_.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);let s=null!=t._vertexState,a=e._buildTarget===e_.Vertex&&e.target!==e_.VertexAndFragment;if(s&&((e.target&e._buildTarget)==0||(e.target&i.target)==0||this.target!==e_.VertexAndFragment&&a)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){let e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName}; -`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){for(let t of["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"])if(e===t)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(let t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(let i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==e_.Neutral&&((i.target&this.target)==0||(i.target&e.target)==0))continue;let r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===e_.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case e_.Vertex:e.sharedData.checks.emitVertex=!0;break;case e_.Fragment:e.sharedData.checks.emitFragment=!0}for(let i of(!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` -//${this.name} -`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target,this._outputs))if((i.target&e.target)!=0)for(let r of i.endpoints){let i=r.ownerBlock;i&&(i.target&e.target)!=0&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; -${e}.visibleOnFrame = ${this.visibleOnFrame}; -${e}.target = ${this.target}; -`}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` -// ${this.getClassName()} -`;for(let i of(this.comments&&(r+=`// ${this.comments} -`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); -`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,a=s.ownerBlock;-1===t.indexOf(a)&&(r+=a._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); -`}return t}clone(e,t=""){let i=this.serialize(),r=h[i.customType];if(r){let s=new r;return s._deserialize(i,e,t),s}return null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var r;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(r=e.target)&&void 0!==r?r:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose()}};let TransformBlock=class TransformBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.complementW=1,this.complementZ=0,this.target=e_.Vertex,this.registerInput("vector",ed.AutoDetect),this.registerInput("transform",ed.Matrix),this.registerOutput("output",ed.Vector4),this.registerOutput("xyz",ed.Vector3),this._inputs[0].onConnectionObservable.add(e=>{if(e.ownerBlock.isInput){let t=e.ownerBlock;("normal"===t.name||"tangent"===t.name)&&(this.complementW=0)}})}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){let r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),e.sharedData.blocksWithDefines.push(this);let s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName}); -`,e.compilationString+=`#ifdef NONUNIFORMSCALING -`,e.compilationString+=`${s} = transposeMat3(inverseMat3(${s})); -`,e.compilationString+=`#endif -`,t.connectedPoint.type){case ed.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); -`;break;case ed.Vector3:case ed.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); -`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); -`}}else{let r=i.associatedVariableName;switch(t.connectedPoint.type){case ed.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); -`;break;case ed.Vector3:case ed.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); -`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * ${t.associatedVariableName}; -`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; -`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){let e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; -`+`${this._codeVariableName}.complementW = ${this.complementW}; -`}};h["BABYLON.TransformBlock"]=TransformBlock;let VertexOutputBlock=class VertexOutputBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Vertex,!0),this.registerInput("vector",ed.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(let t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);let t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName}; -`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; -`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; -`),this}};function editableInPropertyPage(e,t=em.Boolean,i="PROPERTIES",r){return(s,a)=>{let n=s._propStore;n||(n=[],s._propStore=n),n.push({propertyName:a,displayName:e,type:t,groupName:i,options:null!=r?r:{}})}}h["BABYLON.VertexOutputBlock"]=VertexOutputBlock,function(e){e[e.Boolean=0]="Boolean",e[e.Float=1]="Float",e[e.Int=2]="Int",e[e.Vector2=3]="Vector2",e[e.List=4]="List"}(em||(em={}));let FragmentOutputBlock=class FragmentOutputBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",ed.Color4,!0),this.registerInput("rgb",ed.AutoDetect,!0),this.registerInput("a",ed.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){this.useLogarithmicDepth&&i&&MaterialHelper.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);let t=this.rgba,i=this.rgb,r=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||r.isConnected,e.sharedData.blocksWithDefines.push(this),this.useLogarithmicDepth&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");let s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)r.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); -`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; -`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===ed.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t}); -`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t}); -`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor); -`,e.compilationString+=`#endif -`,this.useLogarithmicDepth&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; -`),e.compilationString+=`#if defined(PREPASS)\r -`,e.compilationString+=`gl_FragData[0] = gl_FragColor;\r -`,e.compilationString+=`#endif\r -`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; -`}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(r=e.useLogarithmicDepth)&&void 0!==r&&r}};__decorate([editableInPropertyPage("Convert to gamma space",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],FragmentOutputBlock.prototype,"convertToGammaSpace",void 0),__decorate([editableInPropertyPage("Convert to linear space",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],FragmentOutputBlock.prototype,"convertToLinearSpace",void 0),__decorate([editableInPropertyPage("Use logarithmic depth",em.Boolean,"PROPERTIES")],FragmentOutputBlock.prototype,"useLogarithmicDepth",void 0),h["BABYLON.FragmentOutputBlock"]=FragmentOutputBlock,function(e){e[e.Uniform=0]="Uniform",e[e.Attribute=1]="Attribute",e[e.Varying=2]="Varying",e[e.Undefined=3]="Undefined"}(eg||(eg={})),function(e){e[e.World=1]="World",e[e.View=2]="View",e[e.Projection=3]="Projection",e[e.ViewProjection=4]="ViewProjection",e[e.WorldView=5]="WorldView",e[e.WorldViewProjection=6]="WorldViewProjection",e[e.CameraPosition=7]="CameraPosition",e[e.FogColor=8]="FogColor",e[e.DeltaTime=9]="DeltaTime",e[e.CameraParameters=10]="CameraParameters",e[e.MaterialAlpha=11]="MaterialAlpha"}(ev||(ev={})),function(e){e[e.None=0]="None",e[e.Time=1]="Time",e[e.RealTime=2]="RealTime"}(ex||(ex={}));let F={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},w={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},L={particle_texturemask:!0};let InputBlock=class InputBlock extends NodeMaterialBlock{get type(){if(this._type===ed.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=ed.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=ed.Vector2,this._type;case"Vector3":return this._type=ed.Vector3,this._type;case"Vector4":return this._type=ed.Vector4,this._type;case"Color3":return this._type=ed.Color3,this._type;case"Color4":return this._type=ed.Color4,this._type;case"Matrix":return this._type=ed.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=ed.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=ed.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=ed.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=ed.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case ev.World:case ev.WorldView:case ev.WorldViewProjection:case ev.View:case ev.ViewProjection:case ev.Projection:this._type=ed.Matrix;break;case ev.CameraPosition:this._type=ed.Vector3;break;case ev.FogColor:this._type=ed.Color3;break;case ev.DeltaTime:case ev.MaterialAlpha:this._type=ed.Float;break;case ev.CameraParameters:this._type=ed.Vector4}}return this._type}constructor(e,t=e_.Vertex,i=ed.AutoDetect){super(e,t,!1),this._mode=eg.Undefined,this._animationType=ex.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new observable_Observable,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=eg.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===ed.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=eg.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=eg.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===eg.Undefined}get isUniform(){return this._mode===eg.Uniform}set isUniform(e){this._mode=e?eg.Uniform:eg.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===eg.Attribute}set isAttribute(e){this._mode=e?eg.Attribute:eg.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===eg.Varying}set isVarying(e){this._mode=e?eg.Varying:eg.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=eg.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case ex.Time:this.type===ed.Float&&(this.value+=.01*e.getAnimationRatio());break;case ex.RealTime:this.type===ed.Float&&(this.value=(precisionDate_PrecisionDate.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)} -`:`#ifdef ${e} -`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case ed.Float:this.value=0;break;case ed.Vector2:this.value=math_vector_Vector2.Zero();break;case ed.Vector3:this.value=math_vector_Vector3.Zero();break;case ed.Vector4:this.value=math_vector_Vector4.Zero();break;case ed.Color3:this.value=math_color_Color3.White();break;case ed.Color4:this.value=new math_color_Color4(1,1,1,1);break;case ed.Matrix:this.value=math_vector_Matrix.Identity()}}_emitConstant(e){switch(this.type){case ed.Float:return`${e._emitFloat(this.value)}`;case ed.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case ed.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case ed.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case ed.Color3:return TmpColors.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${TmpColors.Color3[0].r}, ${TmpColors.Color3[0].g}, ${TmpColors.Color3[0].b})`;case ed.Color4:return TmpColors.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${TmpColors.Color4[0].r}, ${TmpColors.Color4[0].g}, ${TmpColors.Color4[0].b}, ${TmpColors.Color4[0].a})`}return""}get _noContextSwitch(){return w[this.name]}_emit(e,t){var i;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)}; -`;return}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName}; -`,t&&(e._uniformDeclaration+=`#endif -`);let i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case ev.WorldView:i.needWorldViewMatrix=!0;break;case ev.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==ex.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=null!==(i=F[this.name])&&void 0!==i?i:this.name,this.target===e_.Vertex&&e._vertexState){w[this.name]?L[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t);return}if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),w[this.name]?L[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName}; -`,t&&(e._attributeDeclaration+=`#endif -`))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;let s=this.associatedVariableName;switch(this._systemValue){case ev.World:e.setMatrix(s,t);break;case ev.WorldView:e.setMatrix(s,i);break;case ev.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;let r=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case ev.World:case ev.WorldView:case ev.WorldViewProjection:break;case ev.View:e.setMatrix(r,t.getViewMatrix());break;case ev.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case ev.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case ev.CameraPosition:t.bindEyePosition(e,r,!0);break;case ev.FogColor:e.setColor3(r,t.fogColor);break;case ev.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case ev.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case ev.MaterialAlpha:e.setFloat(r,i.alpha)}return}let s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case ed.Float:e.setFloat(r,s);break;case ed.Int:e.setInt(r,s);break;case ed.Color3:TmpColors.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&TmpColors.Color3[0].toGammaSpaceToRef(TmpColors.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&TmpColors.Color3[0].toLinearSpaceToRef(TmpColors.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,TmpColors.Color3[0]);break;case ed.Color4:TmpColors.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&TmpColors.Color4[0].toGammaSpaceToRef(TmpColors.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&TmpColors.Color4[0].toLinearSpaceToRef(TmpColors.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,TmpColors.Color4[0]);break;case ed.Vector2:e.setVector2(r,s);break;case ed.Vector3:e.setVector3(r,s);break;case ed.Vector4:e.setVector4(r,s);break;case ed.Matrix:e.setMatrix(r,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); -`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${ev[this._systemValue]}); -`;if(this.isUniform){let t=[],i="";switch(this.type){case ed.Float:i=`${this.value}`;break;case ed.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case ed.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case ed.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case ed.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ed.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case ed.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===ed.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${ex[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){let e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===eg.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===eg.Attribute&&e.type===ed.Vector3&&(this._type=ed.Vector4),e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=h[e.valueType];t&&(this._storedValue=t.FromArray(e.value))}}}};h["BABYLON.InputBlock"]=InputBlock;let CurrentScreenBlock=class CurrentScreenBlock extends NodeMaterialBlock{constructor(e){super(e,e_.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ed.AutoDetect,!1,e_.VertexAndFragment),this.registerOutput("rgba",ed.Color4,e_.Neutral),this.registerOutput("rgb",ed.Color3,e_.Neutral),this.registerOutput("r",ed.Float,e_.Neutral),this.registerOutput("g",ed.Float,e_.Neutral),this.registerOutput("b",ed.Float,e_.Neutral),this.registerOutput("a",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?e_.VertexAndFragment:e_.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===e_.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); -`;return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); -`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); -`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===e_.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.blockingBlocks.indexOf(this)&&e.sharedData.blockingBlocks.push(this),0>e.sharedData.textureBlocks.indexOf(this)&&e.sharedData.textureBlocks.push(this),0>e.sharedData.blocksWithDefines.indexOf(this)&&e.sharedData.blocksWithDefines.push(this),e.target!==e_.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e),this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};h["BABYLON.CurrentScreenBlock"]=CurrentScreenBlock;let ParticleTextureBlock=class ParticleTextureBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",ed.AutoDetect,!1,e_.VertexAndFragment),this.registerOutput("rgba",ed.Color4,e_.Neutral),this.registerOutput("rgb",ed.Color3,e_.Neutral),this.registerOutput("r",ed.Float,e_.Neutral),this.registerOutput("g",ed.Float,e_.Neutral),this.registerOutput("b",ed.Float,e_.Neutral),this.registerOutput("a",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"particle_uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute("particle_uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`}_buildBlock(e){if(super._buildBlock(e),e.target===e_.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); -`,this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};h["BABYLON.ParticleTextureBlock"]=ParticleTextureBlock;let ParticleRampGradientBlock=class ParticleRampGradientBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._isUnique=!0,this.registerInput("color",ed.Color4,!1,e_.Fragment),this.registerOutput("rampColor",ed.Color4,e_.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==e_.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` - #ifdef RAMPGRADIENT - vec4 baseColor = ${this.color.associatedVariableName}; - float alpha = ${this.color.associatedVariableName}.a; - - float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); - - vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); - baseColor.rgb *= rampColor.rgb; - - // Remapped alpha - float finalAlpha = baseColor.a; - baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); - - ${this._declareOutput(this.rampColor,e)} = baseColor; - #else - ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; - #endif - `,this}};h["BABYLON.ParticleRampGradientBlock"]=ParticleRampGradientBlock;let ParticleBlendMultiplyBlock=class ParticleBlendMultiplyBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._isUnique=!0,this.registerInput("color",ed.Color4,!1,e_.Fragment),this.registerInput("alphaTexture",ed.Float,!1,e_.Fragment),this.registerInput("alphaColor",ed.Float,!1,e_.Fragment),this.registerOutput("blendColor",ed.Color4,e_.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==e_.Vertex)return e.compilationString+=` - #ifdef BLENDMULTIPLYMODE - ${this._declareOutput(this.blendColor,e)}; - float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; - ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); - ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; - #else - ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; - #endif - `,this}};h["BABYLON.ParticleBlendMultiplyBlock"]=ParticleBlendMultiplyBlock;let EffectFallbacks=class EffectFallbacks{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=[]),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._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;let i=this._mesh.getScene();for(let e=0;e0&&(r.computeBonesUsingShaders=!1);continue}if(r.computeBonesUsingShaders&&0!==r.numBoneInfluencers){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes)for(let e of r.subMeshes){let i=e.effect;if(i===t){r.computeBonesUsingShaders=!1;break}}}}}else{let t=this._defines[this._currentRank];if(t)for(let i=0;i0}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 texture(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t: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,i=!1){if(this.samples===e&&!i)return e;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){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=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,a){var n;return null===(n=this._depthStencilTexture)||void 0===n||n.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:a},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var e,t,i,r,s,a,n,o;let l=null;if(this._isMulti){let i=this.textures;if(i&&i.length>0){let r=!1,s=i.length,a=i[i.length-1]._source;(a===$.Depth||a===$.DepthStencil)&&(r=!0,s--);let n=[],o=[],h=[],c=[],u=[],d=[],_=[],p={};for(let r=0;r1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let t=0;t<(null===(e=this._textures)||void 0===e?void 0:e.length);++t)this._textures[t].dispose();this._textures=null}dispose(e=!1){var t;e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}};let WebGLRenderTargetWrapper=class WebGLRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height)).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}_shareDepth(e){super._shareDepth(e);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let s=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,s,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var s,a,n,o;if(!e._hardwareTexture)return;let l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){let l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(a=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==a?a:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=null!==(o=null!=i?i:null===(n=this.faceIndices)||void 0===n?void 0:n[t])&&void 0!==o?o:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{let s=this._context,a=s["COLOR_ATTACHMENT"+t+"_WEBGL"],n=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,a,n,e._hardwareTexture.underlyingResource,r)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let s=null!==(r=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==r?r:this.textures.length;for(let e=0;e1&&(15===n.format?u=r.DEPTH_COMPONENT16:16===n.format?u=r.DEPTH_COMPONENT24:17===n.format||13===n.format?u=r.DEPTH24_STENCIL8:14===n.format?u=r.DEPTH_COMPONENT32F:18===n.format&&(u=r.DEPTH32F_STENCIL8)),n.is2DArray?r.texImage3D(a,0,u,n.width,n.height,s,0,c,h,null):r.texImage2D(a,0,u,n.width,n.height,0,c,h,null),this._bindTextureDirectly(a,null),this._internalTexturesCache.push(n),i._depthStencilBuffer){let e=this._currentFramebuffer;this._bindUnboundFramebuffer(i._framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null}return n},ThinEngine.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);let r=e.texture._hardwareTexture;if(r.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){let s=i.createFramebuffer();if(!s)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);let a=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!a)throw Error("Unable to create multi sampled framebuffer");r.addMSAARenderBuffer(a)}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};let postProcess_PostProcess=class postProcess_PostProcess{static RegisterShaderCodeProcessing(e,t){if(!t){delete postProcess_PostProcess._CustomShaderCodeProcessing[null!=e?e:""];return}postProcess_PostProcess._CustomShaderCodeProcessing[null!=e?e:""]=t}static _GetShaderCodeProcessing(e){var t;return null!==(t=postProcess_PostProcess._CustomShaderCodeProcessing[e])&&void 0!==t?t:postProcess_PostProcess._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)})}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,i,r,s,a,n=1,o,l,h=null,c=0,u="postprocess",d,_=!1,p=5,f=q.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new SmartArray(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new math_vector_Vector2(1,1),this._texelSize=math_vector_Vector2.Zero(),this.onActivateObservable=new observable_Observable,this.onSizeChangedObservable=new observable_Observable,this.onApplyObservable=new observable_Observable,this.onBeforeRenderObservable=new observable_Observable,this.onAfterRenderObservable=new observable_Observable,this.name=e,null!=a?(this._camera=a,this._scene=a.getScene(),a.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=s,this.renderTargetSamplingMode=n||1,this._reusable=l||!1,this._textureType=c,this._textureFormat=p,this._shaderLanguage=f,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=d,this._drawWrapper=new drawWrapper_DrawWrapper(this._engine),_||this.updateEffect(h)}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 SmartArray(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,a,n,o){var l,h;let c=postProcess_PostProcess._GetShaderCodeProcessing(this.name);if(null==c?void 0:c.defineCustomBindings){let r=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];r.push(...this._parameters);let s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=c.defineCustomBindings(this.name,e,r,s),t=r,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=n?n:this._vertexUrl,fragment:null!=o?o:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:[],samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:null!=s?s:null,onError:null!=a?a:null,indexParameters:r||this._indexParameters,processCodeAfterIncludes:(null==c?void 0:c.processCodeAfterIncludes)?(e,t)=>c.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==c?void 0:c.processFinalCode)?(e,t)=>c.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let a=null;for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)}),this._flushTextureCache(),this._renderId++}if(this._shareOutputWithPostProcess)a=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)a=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;a=this.inputTexture;for(let t=0;t=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&&-1!==(t=this._scene.postProcesses.indexOf(this))&&this._scene.postProcesses.splice(t,1),this._parentContainer){let e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(-1!==(t=this._engine.postProcesses.indexOf(this))&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),0===(t=e._postProcesses.indexOf(this))&&e._postProcesses.length>0){let e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){let e=decorators_SerializationHelper.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(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=postProcess_PostProcess.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,i){let r=h[e.customType];if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new postProcess_PostProcess(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,i,r)}};postProcess_PostProcess._CustomShaderCodeProcessing={},__decorate([serialize()],postProcess_PostProcess.prototype,"uniqueId",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"name",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"width",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"height",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"renderTargetSamplingMode",void 0),__decorate([generateSerializableMember(8,void 0)],postProcess_PostProcess.prototype,"clearColor",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"autoClear",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"forceAutoClearInAlphaMode",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"alphaMode",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"alphaConstants",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"enablePixelPerfectMode",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"forceFullscreenViewport",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"scaleMode",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"alwaysForcePOT",void 0),__decorate([serialize("samples")],postProcess_PostProcess.prototype,"_samples",void 0),__decorate([serialize()],postProcess_PostProcess.prototype,"adaptScaleToCurrentViewport",void 0),h["BABYLON.PostProcess"]=postProcess_PostProcess;let VectorMergerBlock=class VectorMergerBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",ed.Vector4,!0),this.registerInput("xyz ",ed.Vector3,!0),this.registerInput("xy ",ed.Vector2,!0),this.registerInput("zw ",ed.Vector2,!0),this.registerInput("x",ed.Float,!0),this.registerInput("y",ed.Float,!0),this.registerInput("z",ed.Float,!0),this.registerInput("w",ed.Float,!0),this.registerOutput("xyzw",ed.Vector4),this.registerOutput("xyz",ed.Vector3),this.registerOutput("xy",ed.Vector2),this.registerOutput("zw",ed.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){let t=this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle;return"."+t.substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.x,i=this.y,r=this.z,s=this.w,a=this.xyIn,n=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],c=this._outputs[1],u=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; -`)):o.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${o.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${o.associatedVariableName}${this._buildSwizzle(3)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; -`)):(a.isConnected?(h.hasEndpoints&&(n.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${n.associatedVariableName})${this._buildSwizzle(4)}; -`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${a.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; -`)):(h.hasEndpoints&&(n.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${n.associatedVariableName})${this._buildSwizzle(4)}; -`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; -`)),d.hasEndpoints&&(n.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; -`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; -`)),this}serialize(){let e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){var r,s,a,n;super._deserialize(e,t,i),this.xSwizzle=null!==(r=e.xSwizzle)&&void 0!==r?r:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(a=e.zSwizzle)&&void 0!==a?a:"z",this.wSwizzle=null!==(n=e.wSwizzle)&&void 0!==n?n:"w"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; -${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; -${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; -${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; -`}};h["BABYLON.VectorMergerBlock"]=VectorMergerBlock;let RemapBlock=class RemapBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.sourceRange=new math_vector_Vector2(-1,1),this.targetRange=new math_vector_Vector2(0,1),this.registerInput("input",ed.AutoDetect),this.registerInput("sourceMin",ed.Float,!0),this.registerInput("sourceMax",ed.Float,!0),this.registerInput("targetMin",ed.Float,!0),this.registerInput("targetMax",ed.Float,!0),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),a=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${a} - ${s}) / (${r} - ${i}); -`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); -`+`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); -`}serialize(){let e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=math_vector_Vector2.FromArray(e.sourceRange),this.targetRange=math_vector_Vector2.FromArray(e.targetRange)}};__decorate([editableInPropertyPage("From",em.Vector2)],RemapBlock.prototype,"sourceRange",void 0),__decorate([editableInPropertyPage("To",em.Vector2)],RemapBlock.prototype,"targetRange",void 0),h["BABYLON.RemapBlock"]=RemapBlock;let MultiplyBlock=class MultiplyBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ed.Float),this._inputs[1].acceptedConnectionPointTypes.push(ed.Float)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; -`,this}};h["BABYLON.MultiplyBlock"]=MultiplyBlock,function(e){e[e.Material=0]="Material",e[e.PostProcess=1]="PostProcess",e[e.Particle=2]="Particle",e[e.ProceduralTexture=3]="ProceduralTexture"}(eb||(eb={}));let BoxParticleEmitter=class BoxParticleEmitter{constructor(){this.direction1=new math_vector_Vector3(0,1,0),this.direction2=new math_vector_Vector3(0,1,0),this.minEmitBox=new math_vector_Vector3(-.5,-.5,-.5),this.maxEmitBox=new math_vector_Vector3(.5,.5,.5)}startDirectionFunction(e,t,i,r){let s=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),a=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),n=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);if(r){t.x=s,t.y=a,t.z=n;return}math_vector_Vector3.TransformNormalFromFloatsToRef(s,a,n,e,t)}startPositionFunction(e,t,i,r){let s=math_scalar_Scalar.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),a=math_scalar_Scalar.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),n=math_scalar_Scalar.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=s,t.y=a,t.z=n;return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(s,a,n,e,t)}clone(){let e=new BoxParticleEmitter;return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){math_vector_Vector3.FromArrayToRef(e.direction1,0,this.direction1),math_vector_Vector3.FromArrayToRef(e.direction2,0,this.direction2),math_vector_Vector3.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),math_vector_Vector3.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}};let ConeParticleEmitter=class ConeParticleEmitter{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?math_vector_TmpVectors.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),math_vector_TmpVectors.Vector3[0]).normalize();let s=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),a=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),n=math_scalar_Scalar.RandomRange(0,this.directionRandomizer);t.x=math_vector_TmpVectors.Vector3[0].x+s,t.y=math_vector_TmpVectors.Vector3[0].y+a,t.z=math_vector_TmpVectors.Vector3[0].z+n,t.normalize()}startPositionFunction(e,t,i,r){let s;let a=math_scalar_Scalar.RandomRange(0,2*Math.PI);s=this.emitFromSpawnPointOnly?1e-4:1-(s=math_scalar_Scalar.RandomRange(0,this.heightRange))*s;let n=this._radius-math_scalar_Scalar.RandomRange(0,this._radius*this.radiusRange);n*=s;let o=n*Math.sin(a),l=n*Math.cos(a),h=s*this._height;if(r){t.x=o,t.y=h,t.z=l;return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){let e=new ConeParticleEmitter(this._radius,this._angle,this.directionRandomizer);return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}};let CylinderParticleEmitter=class CylinderParticleEmitter{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=math_vector_Vector3.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),math_vector_Vector3.TransformNormalToRef(this._tempVector,s,this._tempVector);let a=math_scalar_Scalar.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),n=Math.atan2(this._tempVector.x,this._tempVector.z);if(n+=math_scalar_Scalar.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=a,this._tempVector.x=Math.sin(n),this._tempVector.z=Math.cos(n),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}math_vector_Vector3.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){let s=math_scalar_Scalar.RandomRange(-this.height/2,this.height/2),a=math_scalar_Scalar.RandomRange(0,2*Math.PI),n=math_scalar_Scalar.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),o=Math.sqrt(n)*this.radius,l=o*Math.cos(a),h=o*Math.sin(a);if(r){t.copyFromFloats(l,s,h);return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){let e=new CylinderParticleEmitter(this.radius,this.directionRandomizer);return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}};let CylinderDirectedParticleEmitter=class CylinderDirectedParticleEmitter extends CylinderParticleEmitter{constructor(e=1,t=1,i=1,r=new math_vector_Vector3(0,1,0),s=new math_vector_Vector3(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t){let i=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),r=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),s=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);math_vector_Vector3.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new CylinderDirectedParticleEmitter(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){let e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}};let HemisphericParticleEmitter=class HemisphericParticleEmitter{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),a=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),n=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),o=math_scalar_Scalar.RandomRange(0,this.directionRandomizer);if(s.x+=a,s.y+=n,s.z+=o,s.normalize(),r){t.copyFrom(s);return}math_vector_Vector3.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-math_scalar_Scalar.RandomRange(0,this.radius*this.radiusRange),a=math_scalar_Scalar.RandomRange(0,1),n=math_scalar_Scalar.RandomRange(0,2*Math.PI),o=Math.acos(2*a-1),l=s*Math.cos(n)*Math.sin(o),h=s*Math.cos(o),c=s*Math.sin(n)*Math.sin(o);if(r){t.copyFromFloats(l,Math.abs(h),c);return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),c,e,t)}clone(){let e=new HemisphericParticleEmitter(this.radius,this.directionRandomizer);return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}};let PointParticleEmitter=class PointParticleEmitter{constructor(){this.direction1=new math_vector_Vector3(0,1,0),this.direction2=new math_vector_Vector3(0,1,0)}startDirectionFunction(e,t,i,r){let s=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),a=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),n=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,a,n);return}math_vector_Vector3.TransformNormalFromFloatsToRef(s,a,n,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){let e=new PointParticleEmitter;return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){math_vector_Vector3.FromArrayToRef(e.direction1,0,this.direction1),math_vector_Vector3.FromArrayToRef(e.direction2,0,this.direction2)}};let SphereParticleEmitter=class SphereParticleEmitter{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),a=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),n=math_scalar_Scalar.RandomRange(0,this.directionRandomizer),o=math_scalar_Scalar.RandomRange(0,this.directionRandomizer);if(s.x+=a,s.y+=n,s.z+=o,s.normalize(),r){t.copyFrom(s);return}math_vector_Vector3.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-math_scalar_Scalar.RandomRange(0,this.radius*this.radiusRange),a=math_scalar_Scalar.RandomRange(0,1),n=math_scalar_Scalar.RandomRange(0,2*Math.PI),o=Math.acos(2*a-1),l=s*Math.cos(n)*Math.sin(o),h=s*Math.cos(o),c=s*Math.sin(n)*Math.sin(o);if(r){t.copyFromFloats(l,h,c);return}math_vector_Vector3.TransformCoordinatesFromFloatsToRef(l,h,c,e,t)}clone(){let e=new SphereParticleEmitter(this.radius,this.directionRandomizer);return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}};let SphereDirectedParticleEmitter=class SphereDirectedParticleEmitter extends SphereParticleEmitter{constructor(e=1,t=new math_vector_Vector3(0,1,0),i=new math_vector_Vector3(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){let i=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),r=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),s=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);math_vector_Vector3.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new SphereDirectedParticleEmitter(this.radius,this.direction1,this.direction2);return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){let e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}};let CustomParticleEmitter=class CustomParticleEmitter{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){let s=math_vector_TmpVectors.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);let e=math_vector_TmpVectors.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(r){t.copyFrom(s);return}math_vector_Vector3.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){let s=math_vector_TmpVectors.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r){t.copyFrom(s);return}math_vector_Vector3.TransformCoordinatesToRef(s,e,t)}clone(){let e=new CustomParticleEmitter;return DeepCopier.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e}parse(e){}};let MeshParticleEmitter=class MeshParticleEmitter{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(buffer_VertexBuffer.PositionKind),this._normals=e.getVerticesData(buffer_VertexBuffer.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=math_vector_Vector3.Zero(),this._mesh=null,this.direction1=new math_vector_Vector3(0,1,0),this.direction2=new math_vector_Vector3(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){math_vector_Vector3.TransformNormalToRef(this._storedNormal,e,t);return}let s=math_scalar_Scalar.RandomRange(this.direction1.x,this.direction2.x),a=math_scalar_Scalar.RandomRange(this.direction1.y,this.direction2.y),n=math_scalar_Scalar.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,a,n);return}math_vector_Vector3.TransformNormalFromFloatsToRef(s,a,n,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;let s=3*Math.random()*(this._indices.length/3)|0,a=Math.random(),n=Math.random()*(1-a),o=1-a-n,l=this._indices[s],h=this._indices[s+1],c=this._indices[s+2],u=math_vector_TmpVectors.Vector3[0],d=math_vector_TmpVectors.Vector3[1],_=math_vector_TmpVectors.Vector3[2],p=math_vector_TmpVectors.Vector3[3];math_vector_Vector3.FromArrayToRef(this._positions,3*l,u),math_vector_Vector3.FromArrayToRef(this._positions,3*h,d),math_vector_Vector3.FromArrayToRef(this._positions,3*c,_),p.x=a*u.x+n*d.x+o*_.x,p.y=a*u.y+n*d.y+o*_.y,p.z=a*u.z+n*d.z+o*_.z,r?t.copyFromFloats(p.x,p.y,p.z):math_vector_Vector3.TransformCoordinatesFromFloatsToRef(p.x,p.y,p.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(math_vector_Vector3.FromArrayToRef(this._normals,3*l,u),math_vector_Vector3.FromArrayToRef(this._normals,3*h,d),math_vector_Vector3.FromArrayToRef(this._normals,3*c,_),this._storedNormal.x=a*u.x+n*d.x+o*_.x,this._storedNormal.y=a*u.y+n*d.y+o*_.y,this._storedNormal.z=a*u.z+n*d.z+o*_.z)}clone(){let e=new MeshParticleEmitter(this.mesh);return DeepCopier.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;let t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){math_vector_Vector3.FromArrayToRef(e.direction1,0,this.direction1),math_vector_Vector3.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}};let BaseParticleSystem=class BaseParticleSystem{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:math_vector_Vector3.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:math_vector_Vector3.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:math_vector_Vector3.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:math_vector_Vector3.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(let i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=math_vector_Vector3.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new math_vector_Vector3(10,10,10),this.onAnimationEnd=null,this.blendMode=BaseParticleSystem.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new math_vector_Vector2(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new math_vector_Vector3(0,0,0),this._useLogarithmicDepth=!1,this.gravity=math_vector_Vector3.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new math_color_Color4(1,1,1,1),this.color2=new math_color_Color4(1,1,1,1),this.colorDead=new math_color_Color4(0,0,0,1),this.textureMask=new math_color_Color4(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new ImageProcessingConfigurationDefines,this.id=e,this.name=e}createPointEmitter(e,t){let i=new PointParticleEmitter;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){let i=new HemisphericParticleEmitter(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){let i=new SphereParticleEmitter(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new math_vector_Vector3(0,1,0),i=new math_vector_Vector3(0,1,0)){let r=new SphereDirectedParticleEmitter(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){let s=new CylinderParticleEmitter(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new math_vector_Vector3(0,1,0),s=new math_vector_Vector3(0,1,0)){let a=new CylinderDirectedParticleEmitter(e,t,i,r,s);return this.particleEmitterType=a,a}createConeEmitter(e=1,t=Math.PI/4){let i=new ConeParticleEmitter(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){let s=new BoxParticleEmitter;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}};BaseParticleSystem.BLENDMODE_ONEONE=0,BaseParticleSystem.BLENDMODE_STANDARD=1,BaseParticleSystem.BLENDMODE_ADD=2,BaseParticleSystem.BLENDMODE_MULTIPLY=3,BaseParticleSystem.BLENDMODE_MULTIPLYADD=4;let ColorSplitterBlock=class ColorSplitterBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("rgba",ed.Color4,!0),this.registerInput("rgb ",ed.Color3,!0),this.registerOutput("rgb",ed.Color3),this.registerOutput("r",ed.Float),this.registerOutput("g",ed.Float),this.registerOutput("b",ed.Float),this.registerOutput("a",ed.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);let t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;let i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],a=this._outputs[3],n=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; -`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.r; -`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g; -`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.b; -`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.a; -`),this}};h["BABYLON.ColorSplitterBlock"]=ColorSplitterBlock,ThinEngine.prototype.createRenderTargetCubeTexture=function(e,t){let i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);let s=this._gl,a=new internalTexture_InternalTexture(this,$.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,a,!0);let n=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,logger_Logger.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,n.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,n.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);let o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,a.width=e,a.height=e,a.isReady=!0,a.isCube=!0,a.samples=1,a.generateMipMaps=r.generateMipMaps,a.samplingMode=r.samplingMode,a.type=r.type,a.format=r.format,this._internalTexturesCache.push(a),i.setTextures(a),i};let U={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};let EffectRenderer=class EffectRenderer{constructor(e,t=U){var i,r;this._fullscreenViewport=new math_viewport_Viewport(0,0,1,1);let s=null!==(i=t.positions)&&void 0!==i?i:U.positions,a=null!==(r=t.indices)&&void 0!==r?r:U.indices;this.engine=e,this._vertexBuffers={[buffer_VertexBuffer.PositionKind]:new buffer_VertexBuffer(e,s,buffer_VertexBuffer.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(a),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{for(let t in this._indexBuffer=e.createIndexBuffer(a),this._vertexBuffers){let e=this._vertexBuffers[t];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(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[buffer_VertexBuffer.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}};let EffectWrapper=class EffectWrapper{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new observable_Observable;let i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)}));let r=e.defines?e.defines.join("\n"):"";this._drawWrapper=new drawWrapper_DrawWrapper(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"],i,e.samplerNames,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new effect_Effect(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._wasPreviouslyReady=!1,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}};let k="passPixelShader",G=`varying vec2 vUV;uniform sampler2D textureSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);}`;ShaderStore.ShadersStore[k]=G;let z={name:k,shader:G};let dumpTools_DumpTools=class dumpTools_DumpTools{static _CreateDumpRenderer(){if(!dumpTools_DumpTools._DumpToolsEngine){let e;let t=null,i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new ThinEngine(e,!1,i)}catch(r){t=new ThinEngine(e=document.createElement("canvas"),!1,i)}t.getCaps().parallelShaderCompile=void 0;let r=new EffectRenderer(t),s=new EffectWrapper({engine:t,name:z.name,fragmentShader:z.shader,samplerNames:["textureSampler"]});dumpTools_DumpTools._DumpToolsEngine={canvas:e,engine:t,renderer:r,wrapper:s}}return dumpTools_DumpTools._DumpToolsEngine}static async DumpFramebuffer(e,t,i,r,s="image/png",a,n){let o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);dumpTools_DumpTools.DumpData(e,t,l,r,s,a,!0,void 0,n)}static DumpDataAsync(e,t,i,r="image/png",s,a=!1,n=!1,o){return new Promise(l=>{dumpTools_DumpTools.DumpData(e,t,i,e=>l(e),r,s,a,n,o)})}static DumpData(e,t,i,r,s="image/png",a,n=!1,o=!1,l){let h=dumpTools_DumpTools._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){let e=new Uint8Array(i.length),t=i.length;for(;t--;){let r=i[t];e[t]=Math.round(255*math_scalar_Scalar.Clamp(r))}i=e}let c=h.engine.createRawTexture(i,e,t,5,!1,!n,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",c),h.renderer.draw(),o?tools_Tools.ToBlob(h.canvas,e=>{let t=new FileReader;t.onload=e=>{let t=e.target.result;r&&r(t)},t.readAsArrayBuffer(e)},s,l):tools_Tools.EncodeScreenshotCanvasData(h.canvas,r,s,a,l),c.dispose()}static Dispose(){dumpTools_DumpTools._DumpToolsEngine&&(dumpTools_DumpTools._DumpToolsEngine.wrapper.dispose(),dumpTools_DumpTools._DumpToolsEngine.renderer.dispose(),dumpTools_DumpTools._DumpToolsEngine.engine.dispose()),dumpTools_DumpTools._DumpToolsEngine=null}};tools_Tools.DumpData=dumpTools_DumpTools.DumpData,tools_Tools.DumpDataAsync=dumpTools_DumpTools.DumpDataAsync,tools_Tools.DumpFramebuffer=dumpTools_DumpTools.DumpFramebuffer;let renderTargetTexture_RenderTargetTexture=class renderTargetTexture_RenderTargetTexture extends texture_Texture{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=_ObserveArray(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 i;i=Array.isArray(e)?e:[e];for(let e=0;e{var i;let r=this._renderList?this._renderList.length:0;(0===t&&r>0||0===r)&&(null===(i=this.getScene())||void 0===i||i.meshes.forEach(e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new observable_Observable,this.onAfterUnbindObservable=new observable_Observable,this.onBeforeRenderObservable=new observable_Observable,this.onAfterRenderObservable=new observable_Observable,this.onClearObservable=new observable_Observable,this.onResizeObservable=new observable_Observable,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=math_vector_Vector3.Zero(),!(i=this.getScene()))return;let R=this.getScene().getEngine();if(this._gammaSpace=y,this._coordinatesMode=texture_Texture.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=n,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=R.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new RenderingManager(i),this._renderingManager._useSceneAutoClearSetup=!0,c)return;this._renderTargetOptions={generateMipMaps:r,type:a,format:null!==(C=this._format)&&void 0!==C?C:void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:_,creationFlags:p,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:E,label:this.name},this.samplingMode===texture_Texture.NEAREST_SAMPLINGMODE&&(this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE),d||(n?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=texture_Texture.INVCUBIC_MODE,this._textureMatrix=math_vector_Matrix.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0===_||(this.samples=_))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14){var a;null===(a=this._renderTarget)||void 0===a||a.createDepthStencilTexture(e,t,i,r,s)}_releaseRenderPassId(){if(this._scene){let e=this._scene.getEngine();for(let t=0;t0&&(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(){let e=this._size.layers;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;let i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;let r=this.getScene();r&&(this._processSizeParameter(e,!1),i?this._renderTarget=r.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=r.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,i=!1){var r;let s=this.getScene();if(!s)return i;let a=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),a.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){let i=e*t,r=engine_Engine.NearestPOT(i+16384/(128+i));return Math.min(engine_Engine.FloorPOT(e),r)}_prepareRenderingManager(e,t,i,r){let s=this.getScene();if(!s)return;this._renderingManager.reset();let a=s.getRenderId();for(let n=0;n{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,s=null){var a,n,o,l,h,c;let u=this.getScene();if(!u)return;let d=u.getEngine();null===(a=d._debugPushGroup)||void 0===a||a.call(d,`render to face #${e} layer #${r}`,1),this._prepareFrame(u,e,r,t),this.is2DArray?(d.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(d.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));let _=d.snapshotRendering&&1===d.snapshotRenderingMode;if(_)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||u.clearColor,!0,!0,!0);else{let a=null,c=this.renderList?this.renderList:u.getActiveMeshes().data,_=this.renderList?this.renderList.length:u.getActiveMeshes().length;for(let t of(this.getCustomRenderList&&(a=this.getCustomRenderList(this.is2DArray?r:e,c,_)),a?this._prepareRenderingManager(a,a.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(c,_,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),a=c),u._beforeRenderTargetClearStage))t.action(this,e,r);for(let t of(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||u.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||u.updateTransformMatrix(!0),u._beforeRenderTargetDrawStage))t.action(this,e,r);for(let t of(this._renderingManager.render(this.customRenderFunction,a,this.renderParticles,this.renderSprites),u._afterRenderTargetDrawStage))t.action(this,e,r);let p=null!==(o=null===(n=this._texture)||void 0===n?void 0:n.generateMipMaps)&&void 0!==o&&o;for(let i of(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&u.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e),u._afterRenderTargetPostProcessStage))i.action(this,e,r);this._texture&&(this._texture.generateMipMaps=p),this._doNotChangeAspectRatio||u.updateTransformMatrix(!0),i&&dumpTools_DumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),d)}this._unbindFrameBuffer(d,e),this._texture&&this.isCube&&5===e&&d.generateMipMapsForCubemap(this._texture),null===(c=d._debugPopGroup)||void 0===c||c.call(d,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){let e=this.getSize(),t=new renderTargetTexture_RenderTargetTexture(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;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&t.customRenderTargets.splice(i,1),t.cameras))(i=e.customRenderTargets.indexOf(this))>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}};renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE=0,renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME=1,renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,texture_Texture._CreateRenderTargetTexture=(e,t,i,r,s)=>new renderTargetTexture_RenderTargetTexture(e,t,i,r);let ProceduralTextureSceneComponent=class ProceduralTextureSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){tools_Tools.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}};let W=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.proceduralVertexShader=W;let proceduralTexture_ProceduralTexture=class proceduralTexture_ProceduralTexture extends texture_Texture{constructor(e,t,i,r,s=null,a=!0,n=!1,o=0){super(null,r,!a),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new observable_Observable,this.onBeforeGenerationObservable=new observable_Observable,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=[],this._samplers=[],this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null;let l=(r=this.getScene()||engineStore_EngineStore.LastCreatedScene)._getComponent(sceneComponent_SceneComponentConstants.NAME_PROCEDURALTEXTURE);l||(l=new ProceduralTextureSceneComponent(r),r._addComponent(l)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=o,this._generateMipMaps=a,this._drawWrapper=new drawWrapper_DrawWrapper(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;let h=this._createRtWrapper(n,t,a,o);this._texture=h.texture;let c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(this._fullEngine,c,buffer_VertexBuffer.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then(e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){let e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}isReady(){let e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;let t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;let i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[buffer_VertexBuffer.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var e;null===(e=this._rtWrapper)||void 0===e||e.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0})),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;let i=this._texture.isCube;this._rtWrapper.dispose();let r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return -1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;let r=this.getScene();if(!r)return;let s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(let e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(let e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(let e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(let e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(let e in this._colors4){let t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(let e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(let e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;null===(t=s._debugPushGroup)||void 0===t||t.call(s,`procedural texture generation for ${this.name}`,1);let a=s.currentViewport;if(this.isCube)for(let e=0;e<6;e++)s.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(material_Material.TriangleFillMode,0,6);else s.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(material_Material.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),a&&s.setViewport(a),this.isCube&&s.generateMipMapsForCubemap(this._texture),null===(i=s._debugPopGroup)||void 0===i||i.call(s,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){let e=this.getSize(),t=new proceduralTexture_ProceduralTexture(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){let e=this.getScene();if(!e)return;let t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);let i=this._vertexBuffers[buffer_VertexBuffer.PositionKind];i&&(i.dispose(),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}};__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"isEnabled",void 0),__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"autoClear",void 0),__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"_generateMipMaps",void 0),__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"_size",void 0),__decorate([serialize()],proceduralTexture_ProceduralTexture.prototype,"refreshRate",null),h["BABYLON.ProceduralTexture"]=proceduralTexture_ProceduralTexture,function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Exp2=4]="Exp2",e[e.Round=5]="Round",e[e.Floor=6]="Floor",e[e.Ceiling=7]="Ceiling",e[e.Sqrt=8]="Sqrt",e[e.Log=9]="Log",e[e.Tan=10]="Tan",e[e.ArcTan=11]="ArcTan",e[e.ArcCos=12]="ArcCos",e[e.ArcSin=13]="ArcSin",e[e.Fract=14]="Fract",e[e.Sign=15]="Sign",e[e.Radians=16]="Radians",e[e.Degrees=17]="Degrees"}(eT||(eT={}));let TrigonometryBlock=class TrigonometryBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.operation=eT.Cos,this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="";switch(this.operation){case eT.Cos:i="cos";break;case eT.Sin:i="sin";break;case eT.Abs:i="abs";break;case eT.Exp:i="exp";break;case eT.Exp2:i="exp2";break;case eT.Round:i="round";break;case eT.Floor:i="floor";break;case eT.Ceiling:i="ceil";break;case eT.Sqrt:i="sqrt";break;case eT.Log:i="log";break;case eT.Tan:i="tan";break;case eT.ArcTan:i="atan";break;case eT.ArcCos:i="acos";break;case eT.ArcSin:i="asin";break;case eT.Fract:i="fract";break;case eT.Sign:i="sign";break;case eT.Radians:i="radians";break;case eT.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); -`,this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${eT[this.operation]}; -`;return e}};h["BABYLON.TrigonometryBlock"]=TrigonometryBlock;let H={effect:null,subMesh:null};let NodeMaterialDefines=class NodeMaterialDefines extends MaterialDefines{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!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=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}};let NodeMaterial=class NodeMaterial extends PushMaterial{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||engineStore_EngineStore.LastCreatedScene),this._buildId=NodeMaterial._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new math_vector_Matrix,this._cachedWorldViewProjectionMatrix=new math_vector_Matrix,this._optimizers=[],this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new observable_Observable,this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[],this._mode=eb.Material,this.forceAlphaBlending=!1,this._options=Object.assign({emitComments:!1},i),this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){tools_Tools.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(let t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){let t=this._optimizers.indexOf(e);if(!(t>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){let t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return(e.target&e_.Vertex)!=0&&this._addVertexOutputNode(e),(e.target&e_.Fragment)!=0&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||((e.target&e_.Vertex)!=0&&this._removeVertexOutputNode(e),(e.target&e_.Fragment)!=0&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=e_.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){let t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=e_.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){let t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){e.target===e_.VertexAndFragment?i.push(e):t.target===e_.Fragment&&e.target===e_.Vertex&&e._preparationId!==this._buildId&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){let t=e.getClassName();for(let e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(let s of e.inputs){s.associatedVariableName="";let a=s.connectedPoint;if(a){let s=a.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}for(let s of(e.isTeleportOut&&e.entryPoint&&this._processInitializeOnLink(e.entryPoint,t,i,r),e.outputs))s.associatedVariableName=""}_resetDualBlocks(e,t){for(let i of(e.target===e_.VertexAndFragment&&(e.buildId=t),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._resetDualBlocks(e.entryPoint,t)}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;let r=this.getScene().getEngine(),s=this._mode===eb.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new NodeMaterialBuildState,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=e_.Vertex,this._fragmentCompilationState=new NodeMaterialBuildState,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=e_.Fragment,this._sharedData=new NodeMaterialBuildStateSharedData,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;let a=[],n=[];for(let e of this._vertexOutputNodes)a.push(e),this._initializeBlock(e,this._vertexCompilationState,n,i);for(let e of this._fragmentOutputNodes)n.push(e),this._initializeBlock(e,this._fragmentCompilationState,a,i);for(let e of(this.optimize(),a))e.build(this._vertexCompilationState,a);for(let e of(this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState,n))this._resetDualBlocks(e,this._buildId-1);for(let e of n)e.build(this._fragmentCompilationState,n);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=NodeMaterial._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);let o=this.getScene().meshes;for(let e of o)if(e.subMeshes)for(let t of e.subMeshes){if(t.getMaterial()!==this||!t.materialDefines)continue;let e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();let l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(let e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){let i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind),t.TANGENT=e.isVerticesDataPresent(buffer_VertexBuffer.TangentKind);let a=e.useVertexColors&&e.isVerticesDataPresent(buffer_VertexBuffer.ColorKind);t.VERTEXCOLOR_NME=a;let n=!1;for(let i=1;i<=6;++i){let r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),n=n||t["UV"+i]!==r}let o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;MaterialHelper.PrepareDefinesForPrePass(this.getScene(),t,!o),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||n)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){let e=this.getBlockByPredicate(e=>"PrePassOutputBlock"===e.getClassName()),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){let e=this.getAllTextureBlocks().filter(e=>"PrePassTextureBlock"===e.getClassName()),t=[];for(let i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){let t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");for(let r of(i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]})),t))i.texturesRequired.includes(r)||i.texturesRequired.push(r);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,a=0,n=5){return this.mode!==eb.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,a,n)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,a,n=0,o=5){let l=this.name+this._buildId,h=new NodeMaterialDefines,c=new abstractMesh_AbstractMesh(l+"PostProcess",this.getScene()),u=this._buildId;return this._processDefines(c,h),effect_Effect.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new postProcess_PostProcess(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,a,h.toString(),n,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,o),e.nodeMaterialSource=this,e.onApplyObservable.add(t=>{u!==this._buildId&&(delete effect_Effect.ShadersStore[l+"VertexShader"],delete effect_Effect.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),u=this._buildId);let i=this._processDefines(c,h);i&&(effect_Effect.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),TimingTools.SetImmediate(()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l))),this._checkInternals(t)}),e}createProceduralTexture(e,t){if(this.mode!==eb.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId,r=new proceduralTexture_ProceduralTexture(i,e,null,t),s=new abstractMesh_AbstractMesh(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};let a=new NodeMaterialDefines,n=this._processDefines(s,a);effect_Effect.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[buffer_VertexBuffer.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),null==n?void 0:n.fallbacks,void 0);r.nodeMaterialSource=this,r._setEffect(o);let l=this._buildId;return r.onBeforeGenerationObservable.add(()=>{l!==this._buildId&&(delete effect_Effect.ShadersStore[i+"VertexShader"],delete effect_Effect.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,a.markAllAsDirty(),l=this._buildId);let e=this._processDefines(s,a);e&&(effect_Effect.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),TimingTools.SetImmediate(()=>{o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[buffer_VertexBuffer.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString(),null==e?void 0:e.fallbacks,void 0),r._setEffect(o)})),this._checkInternals(o)}),r}_createEffectForParticles(e,t,i,r,s,a,n,o=""){let l=this.name+this._buildId+"_"+t;a||(a=new NodeMaterialDefines),n||(n=this.getScene().getMeshByName(this.name+"Particle"))||((n=new abstractMesh_AbstractMesh(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId,c=[],u=o;if(!s){let o=this._processDefines(n,a);effect_Effect.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(c,t),u=c.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+"\n"+u,null==o?void 0:o.fallbacks,i,r,e),e.setCustomEffect(s,t)}s.onBindObservable.add(s=>{h!==this._buildId&&(delete effect_Effect.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,a.markAllAsDirty(),h=this._buildId),c.length=0,e.fillDefines(c,t);let d=c.join("\n");d!==u&&(a.markAllAsDirty(),u=d);let _=this._processDefines(n,a);if(_){effect_Effect.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,a.toString()+"\n"+u,null==_?void 0:_.fallbacks,i,r,e),e.setCustomEffect(s,t),this._createEffectForParticles(e,t,i,r,s,a,n,o);return}this._checkInternals(s)})}_checkInternals(e){if(this._sharedData.animatedInputs){let e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(let t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(let t of this._sharedData.bindableBlocks)t.bind(e,this);for(let t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==eb.Particle){console.log("Incompatible material mode");return}this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==eb.Material){console.log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let s=null,a=this.getScene();if(MaterialHelper.PrepareDefinesForCamera(a,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(r=>{r.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(s=>{s.prepareDefines(e,this,t,i,r)}),t.isDirty){let i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)});let r=[];this._sharedData.dynamicUniformBlocks.forEach(e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)});let a=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(e=>{let t=a.indexOf(e);-1===t&&a.push(e)});let n=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(e=>{let t=n.indexOf(e);-1===t&&n.push(e)});let o=new EffectFallbacks;this._sharedData.blocksWithFallbacks.forEach(t=>{t.provideFallbacks(e,o)}),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:a,mergedSamplers:n,fallbacks:o}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;let r=this.getScene();if(this._sharedData.animatedInputs){let e=r.getFrameId();if(this._animationFrame!==e){for(let e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new NodeMaterialDefines);let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=r.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some(t=>!t.isReady(e,this,s,i)))return!1;let n=this._processDefines(e,s,i,t);if(n){let e=t.effect,i=s.toString(),o=a.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:n.mergedUniforms,uniformBuffersNames:n.uniformBuffers,samplers:n.mergedSamplers,defines:i,fallbacks:n.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:s.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},a);if(o){if(this._onEffectCreatedObservable&&(H.effect=o,H.subMesh=t,this._onEffectCreatedObservable.notifyObservers(H)),this.allowShaderHotSwapping&&e&&!o.isReady()){if(o=e,s.markAsUnprocessed(),n.lightDisposed)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(o,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader -${this._vertexCompilationState.compilationString} - -// Fragment shader -${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){let t=this.getScene();if(!this._activeEffect)return;let i=this._sharedData.hints;for(let r of(i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._sharedData.inputBlocks))r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);let a=this._mustRebind(r,s,t.visibility),n=this._sharedData;if(a){for(let e of n.bindableBlocks)e.bind(s,this,t,i);for(let e of n.forcedBindableBlocks)e.bind(s,this,t,i);for(let e of n.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(let e of n.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){let e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter(e=>e.texture).map(e=>e.texture)),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){let e=[];for(let t of this.attachedBlocks)NodeMaterial._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(let t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(let e of this.getTextureBlocks().filter(e=>e.texture).map(e=>e.texture))e.dispose();for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){let t=Object.assign({nodeMaterial:this},e);this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise(t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){let i=e&&e.editorURL?e.editorURL:NodeMaterial.EditorURL;tools_Tools.LoadBabylonScript(i,()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()})}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position");let t=new InputBlock("World");t.setAsSystemValue(ev.World);let i=new TransformBlock("WorldPos");e.connectTo(i),t.connectTo(i);let r=new InputBlock("ViewProjection");r.setAsSystemValue(ev.ViewProjection);let s=new TransformBlock("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);let a=new VertexOutputBlock("VertexOutput");s.connectTo(a);let n=new InputBlock("color");n.value=new math_color_Color4(.8,.8,.8,1);let o=new FragmentOutputBlock("FragmentOutput");n.connectTo(o),this.addOutputNode(a),this.addOutputNode(o),this._mode=eb.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position2d");let t=new InputBlock("Constant1");t.isConstant=!0,t.value=1;let i=new VectorMergerBlock("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new VertexOutputBlock("VertexOutput");i.connectTo(r);let s=new InputBlock("Scale");s.visibleInInspector=!0,s.value=new math_vector_Vector2(1,1);let a=new RemapBlock("uv0");e.connectTo(a);let n=new MultiplyBlock("UV scale");a.connectTo(n),s.connectTo(n);let o=new CurrentScreenBlock("CurrentScreen");n.connectTo(o),o.texture=new texture_Texture("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());let l=new FragmentOutputBlock("FragmentOutput");o.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=eb.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position2d");let t=new InputBlock("Constant1");t.isConstant=!0,t.value=1;let i=new VectorMergerBlock("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new VertexOutputBlock("VertexOutput");i.connectTo(r);let s=new InputBlock("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=ex.Time,s.isConstant=!1;let a=new InputBlock("Color3");a.value=new math_color_Color3(1,1,1),a.isConstant=!1;let n=new FragmentOutputBlock("FragmentOutput"),o=new VectorMergerBlock("VectorMerger");o.visibleInInspector=!1;let l=new TrigonometryBlock("Cos");l.operation=eT.Cos,e.connectTo(o),s.output.connectTo(l.input),l.output.connectTo(o.z),o.xyzOut.connectTo(n.rgb),this.addOutputNode(r),this.addOutputNode(n),this._mode=eb.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;let e=new InputBlock("uv");e.setAsAttribute("particle_uv");let t=new ParticleTextureBlock("ParticleTexture");e.connectTo(t);let i=new InputBlock("Color");i.setAsAttribute("particle_color");let r=new MultiplyBlock("Texture * Color");t.connectTo(r),i.connectTo(r);let s=new ParticleRampGradientBlock("ParticleRampGradient");r.connectTo(s);let a=new ColorSplitterBlock("ColorSplitter");i.connectTo(a);let n=new ParticleBlendMultiplyBlock("ParticleBlendMultiply");s.connectTo(n),t.connectTo(n,{output:"a"}),a.connectTo(n,{output:"a"});let o=new FragmentOutputBlock("FragmentOutput");n.connectTo(o),this.addOutputNode(o),this._mode=eb.Particle}async loadAsync(e,t=""){return NodeMaterial.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}generateCode(){let e=[],t=[],i=["const","var","let"];for(let e of this._vertexOutputNodes)this._gatherBlocks(e,t);let r=[];for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); -`;for(let r of(s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${eb[this.mode]}; -`,t))r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(let t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));for(let t of(e=[],s+="\n// Connections\n",this._vertexOutputNodes))s+=t._dumpCodeForOutputConnections(e);for(let t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(let e of(s+="\n// Output nodes\n",this._vertexOutputNodes))s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); -`;for(let e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); -`;return s+`nodeMaterial.build(); -`}serialize(e){let t=e?{}:decorators_SerializationHelper.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{for(let e of(t.customType="BABYLON.NodeMaterial",t.outputNodes=[],this._vertexOutputNodes))this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}for(let e of(t.blocks=[],i))t.blocks.push(e.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let a=i[s.id];if(a){for(let n of s.inputs)if(i[n.targetBlockId]===e&&n.targetConnectionName===r.name){let e=a.getInputByName(n.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(a,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var r;i||this.clear();let s={};for(let i of e.blocks){let e=h[i.customType];if(e){let r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let i=s[t];i.attachToEndpoint(e)}}for(let t=0;tnew NodeMaterial(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){let e=[];return this.getActiveTextures().forEach(t=>{let i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((e,t)=>{i.onLoadedObservable.addOnce(()=>{e()}),i.onErrorObservable.addOnce(e=>{t(e)})}))}),Promise.all(e)}static Parse(e,t,i=""){let r=decorators_SerializationHelper.Parse(()=>new NodeMaterial(e.name,t),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,r="",s=!1,a){let n=null!=a?a:new NodeMaterial(e,i),o=await i._loadFileAsync(t),l=JSON.parse(o);return n.parseSerializedObject(l,r),s||n.build(),n}static ParseFromSnippetAsync(e,t=engineStore_EngineStore.LastCreatedScene,i="",r,s=!1,a=!1){return"_BLANK"===e?Promise.resolve(NodeMaterial.CreateDefault("blank",t)):new Promise((n,o)=>{let l=new webRequest_WebRequest;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let h=JSON.parse(JSON.parse(l.responseText).jsonPayload),c=JSON.parse(h.nodeMaterial);r||((r=decorators_SerializationHelper.Parse(()=>new NodeMaterial(e,t),c,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(c),r.snippetId=e;try{s||r.build()}catch(e){o(e)}a?r.whenTexturesReadyAsync().then(()=>{n(r)}).catch(e=>{o(e)}):n(r)}else o("Unable to load the snippet "+e)}}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}static CreateDefault(e,t){let i=new NodeMaterial(e,t);return i.setToDefault(),i.build(),i}};function CreateIcoSphereVertexData(e){let t;let i=e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,r=e.radius||1,s=void 0===e.flat||e.flat,a=0|(e.subdivisions||4),n=e.radiusX||r,o=e.radiusY||r,l=e.radiusZ||r,h=(1+Math.sqrt(5))/2,c=[-1,h,-0,1,h,0,-1,-h,0,1,-h,0,0,-1,-h,0,1,-h,0,-1,h,0,1,h,h,0,1,h,0,-1,-h,0,1,-h,0,-1],u=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],_=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],p=138/1024,f=239/1024,m=60/1024,g=26/1024,v=-40/1024,x=20/1024,b=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],T=[],S=[],C=[],E=[],y=0,R=[,,,],P=[,,,];for(t=0;t<3;t++)R[t]=math_vector_Vector3.Zero(),P[t]=math_vector_Vector2.Zero();for(let e=0;e<20;e++){for(t=0;t<3;t++){let i=u[3*e+t];R[t].copyFromFloats(c[3*d[i]],c[3*d[i]+1],c[3*d[i]+2]),R[t].normalize(),P[t].copyFromFloats(_[2*i]*p+m+b[e]*v,_[2*i+1]*f+g+b[e]*x)}let interp_vertex=(e,t,i,r)=>{let h;let c=math_vector_Vector3.Lerp(R[0],R[2],t/a),u=math_vector_Vector3.Lerp(R[1],R[2],t/a),d=a===t?R[2]:math_vector_Vector3.Lerp(c,u,e/(a-t));if(d.normalize(),s){let e=math_vector_Vector3.Lerp(R[0],R[2],r/a),t=math_vector_Vector3.Lerp(R[1],R[2],r/a);h=math_vector_Vector3.Lerp(e,t,i/(a-r))}else h=new math_vector_Vector3(d.x,d.y,d.z);h.x/=n,h.y/=o,h.z/=l,h.normalize();let _=math_vector_Vector2.Lerp(P[0],P[2],t/a),p=math_vector_Vector2.Lerp(P[1],P[2],t/a),f=a===t?P[2]:math_vector_Vector2.Lerp(_,p,e/(a-t));S.push(d.x*n,d.y*o,d.z*l),C.push(h.x,h.y,h.z),E.push(f.x,CompatibilityOptions.UseOpenGLOrientationForUV?1-f.y:f.y),T.push(y),y++};for(let e=0;eCreateIcoSphere(e,t,i),function(e){e.WRIST="wrist",e.THUMB="thumb",e.INDEX="index",e.MIDDLE="middle",e.RING="ring",e.LITTLE="little"}(eS||(eS={})),function(e){e.WRIST="wrist",e.THUMB_METACARPAL="thumb-metacarpal",e.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",e.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",e.THUMB_TIP="thumb-tip",e.INDEX_FINGER_METACARPAL="index-finger-metacarpal",e.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",e.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",e.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",e.INDEX_FINGER_TIP="index-finger-tip",e.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",e.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",e.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",e.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",e.MIDDLE_FINGER_TIP="middle-finger-tip",e.RING_FINGER_METACARPAL="ring-finger-metacarpal",e.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",e.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",e.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",e.RING_FINGER_TIP="ring-finger-tip",e.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",e.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",e.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",e.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",e.PINKY_FINGER_TIP="pinky-finger-tip"}(eC||(eC={}));let X=[eC.WRIST,eC.THUMB_METACARPAL,eC.THUMB_PHALANX_PROXIMAL,eC.THUMB_PHALANX_DISTAL,eC.THUMB_TIP,eC.INDEX_FINGER_METACARPAL,eC.INDEX_FINGER_PHALANX_PROXIMAL,eC.INDEX_FINGER_PHALANX_INTERMEDIATE,eC.INDEX_FINGER_PHALANX_DISTAL,eC.INDEX_FINGER_TIP,eC.MIDDLE_FINGER_METACARPAL,eC.MIDDLE_FINGER_PHALANX_PROXIMAL,eC.MIDDLE_FINGER_PHALANX_INTERMEDIATE,eC.MIDDLE_FINGER_PHALANX_DISTAL,eC.MIDDLE_FINGER_TIP,eC.RING_FINGER_METACARPAL,eC.RING_FINGER_PHALANX_PROXIMAL,eC.RING_FINGER_PHALANX_INTERMEDIATE,eC.RING_FINGER_PHALANX_DISTAL,eC.RING_FINGER_TIP,eC.PINKY_FINGER_METACARPAL,eC.PINKY_FINGER_PHALANX_PROXIMAL,eC.PINKY_FINGER_PHALANX_INTERMEDIATE,eC.PINKY_FINGER_PHALANX_DISTAL,eC.PINKY_FINGER_TIP],Y={[eS.WRIST]:[eC.WRIST],[eS.THUMB]:[eC.THUMB_METACARPAL,eC.THUMB_PHALANX_PROXIMAL,eC.THUMB_PHALANX_DISTAL,eC.THUMB_TIP],[eS.INDEX]:[eC.INDEX_FINGER_METACARPAL,eC.INDEX_FINGER_PHALANX_PROXIMAL,eC.INDEX_FINGER_PHALANX_INTERMEDIATE,eC.INDEX_FINGER_PHALANX_DISTAL,eC.INDEX_FINGER_TIP],[eS.MIDDLE]:[eC.MIDDLE_FINGER_METACARPAL,eC.MIDDLE_FINGER_PHALANX_PROXIMAL,eC.MIDDLE_FINGER_PHALANX_INTERMEDIATE,eC.MIDDLE_FINGER_PHALANX_DISTAL,eC.MIDDLE_FINGER_TIP],[eS.RING]:[eC.RING_FINGER_METACARPAL,eC.RING_FINGER_PHALANX_PROXIMAL,eC.RING_FINGER_PHALANX_INTERMEDIATE,eC.RING_FINGER_PHALANX_DISTAL,eC.RING_FINGER_TIP],[eS.LITTLE]:[eC.PINKY_FINGER_METACARPAL,eC.PINKY_FINGER_PHALANX_PROXIMAL,eC.PINKY_FINGER_PHALANX_INTERMEDIATE,eC.PINKY_FINGER_PHALANX_DISTAL,eC.PINKY_FINGER_TIP]};let WebXRHand=class WebXRHand{get handMesh(){return this._handMesh}getHandPartMeshes(e){return Y[e].map(e=>this._jointMeshes[X.indexOf(e)])}getJointMesh(e){return this._jointMeshes[X.indexOf(e)]}constructor(e,t,i,r,s=!1,a=!1,n=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=a,this._jointScaleFactor=n,this._jointTransforms=Array(X.length),this._jointTransformMatrices=new Float32Array(16*X.length),this._tempJointMatrix=new math_vector_Matrix,this._jointRadii=new Float32Array(X.length),this._scene=t[0].getScene();for(let e=0;e{e.rootMesh&&e.rootMesh.setEnabled(!1)})),this.xrController.onMotionControllerInitObservable.add(e=>{e.onModelLoadedObservable.add(e=>{e.rootMesh&&e.rootMesh.setEnabled(!1)}),e.rootMesh&&e.rootMesh.setEnabled(!1)})}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(e=>e.alwaysSelectAsActiveMesh=!0),this._handMesh.skeleton){let e=this._handMesh.skeleton;X.forEach((i,r)=>{let s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){let i=this.xrController.inputSource.hand;if(!i)return;let r=X.map(e=>i[e]||i.get(e)),s=!1;if(e.fillPoses&&e.fillJointRadii)s=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){s=!0;for(let i=0;i{let i=this._jointTransforms[t];math_vector_Matrix.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);let r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),!this._scene.useRightHandedSystem&&(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}};let WebXRHandTracking=class WebXRHandTracking extends WebXRAbstractFeature{static _GenerateTrackedJointMeshes(e){let t={};return["left","right"].map(i=>{var r,s,a,n,o;let l=[],h=(null===(r=e.jointMeshes)||void 0===r?void 0:r.sourceMesh)||CreateIcoSphere("jointParent",WebXRHandTracking._ICOSPHERE_PARAMS);h.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t{var r,s,a,n,o;let l={};(null===(s=null===(r=WebXRHandTracking._RightHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===s?void 0:s.isDisposed())&&(WebXRHandTracking._RightHandGLB=null),(null===(n=null===(a=WebXRHandTracking._LeftHandGLB)||void 0===a?void 0:a.meshes[1])||void 0===n?void 0:n.isDisposed())&&(WebXRHandTracking._LeftHandGLB=null);let h=!!(WebXRHandTracking._RightHandGLB&&WebXRHandTracking._LeftHandGLB),c=await Promise.all([WebXRHandTracking._RightHandGLB||sceneLoader_SceneLoader.ImportMeshAsync("",WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL,WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),WebXRHandTracking._LeftHandGLB||sceneLoader_SceneLoader.ImportMeshAsync("",WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL,WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);WebXRHandTracking._RightHandGLB=c[0],WebXRHandTracking._LeftHandGLB=c[1];let u=new NodeMaterial("handShader",e,{emitComments:!1});await u.loadAsync(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL),u.needDepthPrePass=!0,u.transparencyMode=material_Material.MATERIAL_ALPHABLEND,u.alphaMode=2,u.build(!1);let d=Object.assign({base:math_color_Color3.FromInts(116,63,203),fresnel:math_color_Color3.FromInts(149,102,229),fingerColor:math_color_Color3.FromInts(177,130,255),tipFresnel:math_color_Color3.FromInts(220,200,255)},null===(o=null==t?void 0:t.handMeshes)||void 0===o?void 0:o.customColors),_={base:u.getBlockByName("baseColor"),fresnel:u.getBlockByName("fresnelColor"),fingerColor:u.getBlockByName("fingerColor"),tipFresnel:u.getBlockByName("tipFresnelColor")};_.base.value=d.base,_.fresnel.value=d.fresnel,_.fingerColor.value=d.fingerColor,_.tipFresnel.value=d.tipFresnel,["left","right"].forEach(t=>{let i="left"==t?WebXRHandTracking._LeftHandGLB:WebXRHandTracking._RightHandGLB;if(!i)throw Error("Could not load hand model");let r=i.meshes[1];r._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,r.material=u.clone(`${t}HandShaderClone`,!0),r.isVisible=!1,l[t]=r,h||e.useRightHandedSystem||i.meshes[1].rotate(math_axis_Axis.Y,Math.PI)}),u.dispose(),i({left:l.left,right:l.right})})}static _GenerateDefaultHandMeshRigMapping(e){let t="right"==e?"R":"L";return{[eC.WRIST]:`wrist_${t}`,[eC.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[eC.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[eC.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[eC.THUMB_TIP]:`thumb_tip_${t}`,[eC.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[eC.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[eC.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[eC.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[eC.INDEX_FINGER_TIP]:`index_tip_${t}`,[eC.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[eC.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[eC.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[eC.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[eC.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[eC.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[eC.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[eC.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[eC.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[eC.RING_FINGER_TIP]:`ring_tip_${t}`,[eC.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[eC.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[eC.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[eC.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[eC.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this.onHandAddedObservable=new observable_Observable,this.onHandRemovedObservable=new observable_Observable,this._attachHand=e=>{var t,i,r;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;let s=e.inputSource.handedness,a=new WebXRHand(e,this._handResources.jointMeshes[s],this._handResources.handMeshes&&this._handResources.handMeshes[s],this._handResources.rigMappings&&this._handResources.rigMappings[s],null===(t=this.options.handMeshes)||void 0===t?void 0:t.meshesUseLeftHandedCoordinates,null===(i=this.options.jointMeshes)||void 0===i?void 0:i.invisible,null===(r=this.options.jointMeshes)||void 0===r?void 0:r.scaleFactor);this._attachedHands[e.uniqueId]=a,this._trackingHands[s]=a,this.onHandAddedObservable.notifyObservers(a)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";let i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};let e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach(e=>{let t=e[0],i=e[1];t.forEach((e,t)=>{i[X[t]]=e})}),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){var e,t,i,r;return!!super.attach()&&(this._handResources={jointMeshes:WebXRHandTracking._GenerateTrackedJointMeshes(this.options),handMeshes:(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||null,rigMappings:(null===(t=this.options.handMeshes)||void 0===t?void 0:t.customRigMappings)||null},(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)||(null===(r=this.options.handMeshes)||void 0===r?void 0:r.disableDefaultMeshes)||WebXRHandTracking._GenerateDefaultHandMeshesAsync(engineStore_EngineStore.LastCreatedScene,this.options).then(e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:WebXRHandTracking._GenerateDefaultHandMeshRigMapping("left"),right:WebXRHandTracking._GenerateDefaultHandMeshRigMapping("right")},null===(t=this._trackingHands.left)||void 0===t||t.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),null===(i=this._trackingHands.right)||void 0===i||i.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)}),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){var t,i;null===(t=this._trackingHands.left)||void 0===t||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),null===(i=this._trackingHands.right)||void 0===i||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;let i=this.getHandByControllerId(e);if(i){let r="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[r])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[r]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach(e=>this._detachHandById(e)),!0)}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),!this._handResources.handMeshes||(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),WebXRHandTracking._RightHandGLB=null,WebXRHandTracking._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(e=>e.dispose()),this._handResources.jointMeshes.right.forEach(e=>e.dispose()))}};WebXRHandTracking.Name=webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING,WebXRHandTracking.Version=1,WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",WebXRHandTracking._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},WebXRHandTracking._RightHandGLB=null,WebXRHandTracking._LeftHandGLB=null,WebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name,(e,t)=>()=>new WebXRHandTracking(e,t),WebXRHandTracking.Version,!1),function(e){e[e.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",e[e.RADIAL_SIDE=1]="RADIAL_SIDE",e[e.ULNAR_SIDE=2]="ULNAR_SIDE",e[e.BELOW_WRIST=3]="BELOW_WRIST"}(eE||(eE={})),function(e){e[e.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",e[e.HAND_ROTATION=1]="HAND_ROTATION"}(ey||(ey={})),function(e){e[e.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",e[e.PALM_UP=1]="PALM_UP",e[e.GAZE_FOCUS=2]="GAZE_FOCUS",e[e.PALM_AND_GAZE=3]="PALM_AND_GAZE"}(eR||(eR={}));let BoneIKController=class BoneIKController{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=math_vector_Vector3.Zero(),this.poleTargetPosition=math_vector_Vector3.Zero(),this.poleTargetLocalOffset=math_vector_Vector3.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=math_vector_Quaternion.Identity(),this._bone1Mat=math_vector_Matrix.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=math_vector_Vector3.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;let r=t.getParent();if(!r){this._notEnoughInformation=!0,logger_Logger.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length){this._notEnoughInformation=!0,logger_Logger.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();let s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){let e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);let t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=math_vector_Vector3.Distance(t,i),this._bone1Length=math_vector_Vector3.Distance(i,r)}else{e.computeWorldMatrix(!0);let t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;let i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=math_vector_Vector3.Distance(i,r)}this._bone1.getRotationMatrixToRef(en.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;let t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;let e=this.targetPosition,t=this.poleTargetPosition,i=BoneIKController._TmpMats[0],r=BoneIKController._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&math_vector_Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);let s=BoneIKController._TmpVecs[0],a=BoneIKController._TmpVecs[1],n=BoneIKController._TmpVecs[2],o=BoneIKController._TmpVecs[3],l=BoneIKController._TmpVecs[4],h=BoneIKController._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,o),o.normalize(),math_vector_Vector3.CrossToRef(o,l,a),a.normalize(),math_vector_Vector3.CrossToRef(o,a,n),n.normalize(),math_vector_Matrix.FromXYZAxesToRef(n,o,a,i);let c=this._bone1Length,u=this._bone2Length,d=math_vector_Vector3.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let _=(u*u+d*d-c*c)/(2*u*d),p=(d*d+c*c-u*u)/(2*d*c);_>1&&(_=1),p>1&&(p=1),_<-1&&(_=-1),p<-1&&(p=-1);let f=Math.acos(_),m=Math.acos(p),g=-f-m;if(this._rightHandedSystem)math_vector_Matrix.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),math_vector_Matrix.RotationAxisToRef(this._bendAxis,m,r),r.multiplyToRef(i,i);else{let e=BoneIKController._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,math_vector_Matrix.RotationAxisToRef(e,-m,r),r.multiplyToRef(i,i)}this.poleAngle&&(math_vector_Matrix.RotationAxisToRef(o,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||math_vector_Quaternion.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),math_vector_Quaternion.FromRotationMatrixToRef(i,h),math_vector_Quaternion.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,en.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,en.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,en.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new math_vector_Quaternion),e.getRotationQuaternionToRef(en.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}};BoneIKController._TmpVecs=[math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),math_vector_Vector3.Zero()],BoneIKController._TmpQuat=math_vector_Quaternion.Identity(),BoneIKController._TmpMats=[math_vector_Matrix.Identity(),math_vector_Matrix.Identity()];let BoneLookController=class BoneLookController{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=math_vector_Vector3.Up(),this.upAxisSpace=en.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=math_vector_Quaternion.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=math_vector_Vector3.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=math_axis_Axis.Y,t=math_axis_Axis.X;null!=r.yawAxis&&(e=r.yawAxis.clone()).normalize(),null!=r.pitchAxis&&(t=r.pitchAxis.clone()).normalize();let i=math_vector_Vector3.Cross(t,e);this._transformYawPitch=math_vector_Matrix.Identity(),math_vector_Matrix.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=en.BONE||(this.upAxisSpace=en.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}let e=this.bone,t=BoneLookController._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target,r=BoneLookController._TmpMats[0],s=BoneLookController._TmpMats[1],a=this.mesh,n=e.getParent(),o=BoneLookController._TmpVecs[1];o.copyFrom(this.upAxis),this.upAxisSpace==en.BONE&&n?(this._transformYawPitch&&math_vector_Vector3.TransformCoordinatesToRef(o,this._transformYawPitchInv,o),n.getDirectionToRef(o,this.mesh,o)):this.upAxisSpace==en.LOCAL&&(a.getDirectionToRef(o,o),(1!=a.scaling.x||1!=a.scaling.y||1!=a.scaling.z)&&o.normalize());let l=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(l=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),l||h){let e=BoneLookController._TmpMats[2],r=BoneLookController._TmpMats[3];if(this.upAxisSpace==en.BONE&&1==o.y&&n)n.getRotationMatrixToRef(en.WORLD,this.mesh,e);else if(this.upAxisSpace!=en.LOCAL||1!=o.y||n){let t=BoneLookController._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&math_vector_Vector3.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),n?n.getDirectionToRef(t,this.mesh,t):a.getDirectionToRef(t,t);let i=math_vector_Vector3.Cross(o,t);i.normalize(),t=math_vector_Vector3.Cross(i,o),math_vector_Matrix.FromXYZAxesToRef(i,o,t,e)}else e.copyFrom(a.getWorldMatrix());e.invertToRef(r);let s=null;if(h){let a=BoneLookController._TmpVecs[3];i.subtractToRef(t,a),math_vector_Vector3.TransformCoordinatesToRef(a,r,a),s=Math.sqrt(a.x*a.x+a.z*a.z);let n=Math.atan2(a.y,s),o=n;n>this._maxPitch?(a.y=this._maxPitchTan*s,o=this._maxPitch):nthis._maxYaw||oMath.PI?this._isAngleBetween(n,this._maxYaw,this._midYawConstraint)?(a.z=this._maxYawCos*s,a.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(n,this._midYawConstraint,this._minYaw)&&(a.z=this._minYawCos*s,a.x=this._minYawSin*s,l=this._minYaw):o>this._maxYaw?(a.z=this._maxYawCos*s,a.x=this._maxYawSin*s,n<0&&this.useAbsoluteValueForYaw&&(a.x*=-1),l=this._maxYaw):oMath.PI){let e=BoneLookController._TmpVecs[8];e.copyFrom(math_axis_Axis.Z),this._transformYawPitch&&math_vector_Vector3.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);let t=BoneLookController._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),math_vector_Vector3.TransformCoordinatesToRef(e,t,e),math_vector_Vector3.TransformCoordinatesToRef(e,r,e);let i=Math.atan2(e.x,e.z),o=this._getAngleBetween(i,n),h=this._getAngleBetween(i,this._midYawConstraint);if(o>h){null==s&&(s=Math.sqrt(a.x*a.x+a.z*a.z));let e=this._getAngleBetween(i,this._maxYaw),t=this._getAngleBetween(i,this._minYaw);l=tMath.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI;let i=0;return(i=e<(t=t<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,t<(i=i<0?i+2*Math.PI:i)){if(e>t&&ei&&e0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):((!this._transformMatrices||this._isDirty)&&this.prepare(),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(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){for(let e of this.bones)if(e._linkedTransformNode){let 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(let e of this._meshesWithPoseMatrix){let t=e.getPoseMatrix(),i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){for(let i of(this._synchronizedWithMesh=e,this.bones))if(!i.getParent()){let e=i.getBindMatrix();e.multiplyToRef(t,math_vector_TmpVectors.Matrix[1]),i._updateAbsoluteBindMatrices(math_vector_TmpVectors.Matrix[1])}if(this.isUsingTextureForMatrices){let t=(this.bones.length+1)*4;e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=rawTexture_RawTexture.CreateRGBATexture(e._bonesTransformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))}}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=rawTexture_RawTexture.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),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{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){let 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(){var e;let t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(a.animation=r.animations[0].serialize()),t.ranges=[],this._ranges){let i=this._ranges[e];if(!i)continue;let r={};r.name=e,r.from=i.from,r.to=i.to,t.ranges.push(r)}}return t}static Parse(e,t){let i;let r=new skeleton_Skeleton(e.name,e.id,t);for(e.dimensionsAtRest&&(r.dimensionsAtRest=math_vector_Vector3.FromArray(e.dimensionsAtRest)),r.needInitialSkinMatrix=e.needInitialSkinMatrix,i=0;i-1&&(a=r.bones[t.parentBoneIndex]);let n=t.rest?math_vector_Matrix.FromArray(t.rest):null,o=new Bone(t.name,r,a,math_vector_Matrix.FromArray(t.matrix),n,null,s);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(animation_Animation.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(r._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(i=0;i0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}};let StorageBuffer=class StorageBuffer{constructor(e,t,i=3,r){this._engine=e,this._label=r,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i){return this._engine.readFromStorageBuffer(this._buffer,e,t,i)}dispose(){let e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}};let j=(()=>{let e=new Uint8Array(4),t=new Uint32Array(e.buffer);return!!((t[0]=1)&e[0])})();Object.defineProperty(buffer_VertexBuffer.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(buffer_VertexBuffer.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(buffer_VertexBuffer.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),buffer_VertexBuffer.prototype._rebuild=function(){var e,t;null===(e=this._buffer)||void 0===e||e._rebuild(),null===(t=this._alignedBuffer)||void 0===t||t._rebuild()},buffer_VertexBuffer.prototype.dispose=function(){var e;this._ownsBuffer&&this._buffer.dispose(),null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},buffer_VertexBuffer.prototype._alignBuffer=function(){var e,t;let i,r;let s=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideMultiple4Bytes||this.byteStride%4==0||!s)return;let a=buffer_VertexBuffer.GetTypeByteLength(this.type),n=this.byteStride+3&-4,o=n/a,l=this.totalVertices,h=l*n,c=h/a;if(Array.isArray(s)){let e=new Float32Array(s);i=new DataView(e.buffer,e.byteOffset,e.byteLength)}else i=s instanceof ArrayBuffer?new DataView(s,0,s.byteLength):new DataView(s.buffer,s.byteOffset,s.byteLength);r=this.type===buffer_VertexBuffer.BYTE?new Int8Array(c):this.type===buffer_VertexBuffer.UNSIGNED_BYTE?new Uint8Array(c):this.type===buffer_VertexBuffer.SHORT?new Int16Array(c):this.type===buffer_VertexBuffer.UNSIGNED_SHORT?new Uint16Array(c):this.type===buffer_VertexBuffer.INT?new Int32Array(c):this.type===buffer_VertexBuffer.UNSIGNED_INT?new Uint32Array(c):new Float32Array(c);let u=this.getSize(),d=this.byteOffset;for(let e=0;e{if(t.type!==pointerEvents_PointerEventTypes.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===EventConstants.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,pointerEvents_PointerEventTypes.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"}};__decorate([serialize()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionX",void 0),__decorate([serialize()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionY",void 0),__decorate([serialize()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionZ",void 0);let BaseCameraPointersInput=class BaseCameraPointersInput{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=a=>{var n,o;let l=a.event,h="touch"===l.pointerType;if(a.type!==pointerEvents_PointerEventTypes.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;let c=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else if(a.type!==pointerEvents_PointerEventTypes.POINTERDOWN&&h&&(null===(n=this._pointA)||void 0===n?void 0:n.pointerId)!==l.pointerId&&(null===(o=this._pointB)||void 0===o?void 0:o.pointerId)!==l.pointerId)return;else if(a.type===pointerEvents_PointerEventTypes.POINTERDOWN&&(-1===this._currentActiveButton||h)){try{null==c||c.setPointerCapture(l.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else{if(null!==this._pointB)return;this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType}}-1!==this._currentActiveButton||h||(this._currentActiveButton=l.button),this.onButtonDown(l),!e&&(l.preventDefault(),i&&i.focus())}else if(a.type===pointerEvents_PointerEventTypes.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(a.type===pointerEvents_PointerEventTypes.POINTERUP&&(this._currentActiveButton===l.button||h)){try{null==c||c.releasePointerCapture(l.pointerId)}catch(e){}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(a.type===pointerEvents_PointerEventTypes.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&null===this._pointB){let e=l.clientX-this._pointA.x,t=l.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){let e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;let t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,n=t*t+i*i,o={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:a.type};this.onMultiTouch(this._pointA,this._pointB,r,n,s,o),s=o,r=n}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,pointerEvents_PointerEventTypes.POINTERDOWN|pointerEvents_PointerEventTypes.POINTERUP|pointerEvents_PointerEventTypes.POINTERMOVE|pointerEvents_PointerEventTypes.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let a=this.camera.getScene().getEngine().getHostWindow();a&&tools_Tools.RegisterTopRootEvents(a,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&tools_Tools.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let 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,i){}onMultiTouch(e,t,i,r,s,a){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}};__decorate([serialize()],BaseCameraPointersInput.prototype,"buttons",void 0);var K,q,$,Q,Z,J,ee,et,ei,er,es,ea,en,eo,el,eh,ec,eu,ed,e_,ep,ef,em,eg,ev,ex,eb,eT,eS,eC,eE,ey,eR,eP,eA,eM,eI,eD,eO,eB,eN,eF,ew,eL,eV,eU,ek,eG,ez,eW,eH,eX,eY,ej,eK,eq,e$,eQ,eZ,eJ,e0,e1,e2,e3,e4,e5,e6,e8,e7,e9,te,tt,ti,tr,ts,ta,tn,to,tl,th,tc,tu,td,t_,tp,tf,tm,tg,tv,tx,tb,tT,tS,tC,tE,ty,tR,tP,tA,tM,tI,tD,tO,tB,tN,tF,tw,tL,tV,tU,tk,tG,tz,tW,tH,tX,tY,tj,tK,tq,t$,tQ,tZ,tJ,t0,t1,t2,t3,t4,t5,t6,t8,t7,t9,ie,it,ii,ir,is,ia,io,il={};let CameraInputsManager=class CameraInputsManager{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){logger_Logger.Warn("camera input of type "+t+" already exists on camera");return}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(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement)for(let t in e=!camera_Camera.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e,this.attached)this.attached[t].attachControl(e)}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){for(let e in this.checkInputs=()=>{},this.attached){let 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){let t={};for(let e in this.attached){let i=this.attached[e],r=decorators_SerializationHelper.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t)for(let e in this.clear(),t){let i=il[e];if(i){let r=t[e],s=decorators_SerializationHelper.Parse(()=>new i,r,null);this.add(s)}}else for(let t in this.attached){let i=il[this.attached[t].getClassName()];if(i){let r=decorators_SerializationHelper.Parse(()=>new i,e,null);this.remove(this.attached[t]),this.add(r)}}}};let Gamepad=class Gamepad{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=1,a=2,n=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=Gamepad.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,this._rightStickAxisX=a,this._rightStickAxisY=n,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){this._onleftstickchanged&&(this._leftStick.x!==e.x||this._leftStick.y!==e.y)&&this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){this._onrightstickchanged&&(this._rightStick.x!==e.x||this._rightStick.y!==e.y)&&this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}};Gamepad.GAMEPAD=0,Gamepad.GENERIC=1,Gamepad.XBOX=2,Gamepad.POSE_ENABLED=3,Gamepad.DUALSHOCK=4;let GenericPad=class GenericPad extends Gamepad{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new observable_Observable,this.onButtonUpObservable=new observable_Observable,this.type=Gamepad.GENERIC,this._buttons=Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type===Gamepad.POSE_ENABLED||this.gamepad&&e.type!==Gamepad.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.XBOX)}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){let e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){let i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){let i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}let i=this.gamepad.leftStick;if(i&&0!=i.y){let e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}};__decorate([serialize()],ArcRotateCameraGamepadInput.prototype,"gamepadRotationSensibility",void 0),__decorate([serialize()],ArcRotateCameraGamepadInput.prototype,"gamepadMoveSensibility",void 0),il.ArcRotateCameraGamepadInput=ArcRotateCameraGamepadInput;let ArcRotateCameraKeyboardMoveInput=class ArcRotateCameraKeyboardMoveInput{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=[]}attachControl(e){e=tools_Tools.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=>{let i=t.event;if(!i.metaKey){if(t.type===KeyboardEventTypes.KEYDOWN){if(this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);-1===t&&this._keys.push(i.keyCode),i.preventDefault&&!e&&i.preventDefault()}}else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&!e&&i.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){let e=this.camera;for(let t=0;t0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==pointerEvents_PointerEventTypes.POINTERWHEEL)return;let i=t.event,r=0,s=i.deltaMode===EventConstants.DOM_DELTA_LINE?40:1,a=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(a,this,i);else if(this.wheelDeltaPercentage){if((r=this._computeDeltaFromMouseWheelLegacyEvent(a,this.camera.radius))>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=math_scalar_Scalar.Clamp(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(a,e)}}else r=a/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,pointerEvents_PointerEventTypes.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;let e=this.camera,t=0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset;t&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=math_plane_Plane.FromPositionAndNormal(e.target,t)}_getPosition(){var e;let t=this.camera,i=t.getScene(),r=i.createPickingRay(i.pointerX,i.pointerY,math_vector_Matrix.Identity(),t,!1);(0!==t.targetScreenOffset.x||0!==t.targetScreenOffset.y)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=math_vector_Vector3.TransformNormal(this._viewOffset,t._cameraTransformMatrix),r.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=null!==(e=r.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),r.origin.addInPlace(r.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;let r=this.camera,s=1-r.inertia;if(r.lowerRadiusLimit){let i=null!==(t=r.lowerRadiusLimit)&&void 0!==t?t:0;r.radius-(r.inertialRadiusOffset+e)/st&&(e=(r.radius-t)*s-r.inertialRadiusOffset)}let a=e/s,n=a/r.radius,o=this._getPosition(),l=math_vector_TmpVectors.Vector3[6];o.subtractToRef(r.target,l),l.scaleInPlace(n),l.scaleInPlace(s),this._inertialPanning.addInPlace(l),r.inertialRadiusOffset+=e}_zeroIfClose(e){.001>Math.abs(e.x)&&(e.x=0),.001>Math.abs(e.y)&&(e.y=0),.001>Math.abs(e.z)&&(e.z=0)}};__decorate([serialize()],ArcRotateCameraMouseWheelInput.prototype,"wheelPrecision",void 0),__decorate([serialize()],ArcRotateCameraMouseWheelInput.prototype,"zoomToMouseLocation",void 0),__decorate([serialize()],ArcRotateCameraMouseWheelInput.prototype,"wheelDeltaPercentage",void 0),il.ArcRotateCameraMouseWheelInput=ArcRotateCameraMouseWheelInput;let ArcRotateCameraPointersInput=class ArcRotateCameraPointersInput extends BaseCameraPointersInput{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){let i=t.x-e.x,r=t.y-e.y;this.camera.inertialPanningX+=-i/this.panningSensibility,this.camera.inertialPanningY+=r/this.panningSensibility}}_computePinchZoom(e,t){let i=this.camera.radius||ArcRotateCameraPointersInput.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=i*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=(t-e)*.001*i*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,i){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=i/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,i,r,s,a){(0!==i||null!==s)&&(0!==r||null!==a)&&(this.multiTouchPanAndZoom?(this._computePinchZoom(i,r),this._computeMultiTouchPanning(s,a)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(r)-Math.sqrt(i))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,a)):this.multiTouchPanning?this._computeMultiTouchPanning(s,a):this.pinchZoom&&this._computePinchZoom(i,r))}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}};ArcRotateCameraPointersInput.MinimumRadiusForPinch=.001,__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"buttons",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"angularSensibilityX",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"angularSensibilityY",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"pinchPrecision",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"pinchDeltaPercentage",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"useNaturalPinchZoom",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"pinchZoom",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"panningSensibility",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"multiTouchPanning",void 0),__decorate([serialize()],ArcRotateCameraPointersInput.prototype,"multiTouchPanAndZoom",void 0),il.ArcRotateCameraPointersInput=ArcRotateCameraPointersInput;let ArcRotateCameraInputsManager=class ArcRotateCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addMouseWheel(){return this.add(new ArcRotateCameraMouseWheelInput),this}addPointers(){return this.add(new ArcRotateCameraPointersInput),this}addKeyboard(){return this.add(new ArcRotateCameraKeyboardMoveInput),this}};ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation=function(){return this.add(new ArcRotateCameraVRDeviceOrientationInput),this};let ArcRotateCameraVRDeviceOrientationInput=class ArcRotateCameraVRDeviceOrientationInput{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);let t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):tools_Tools.Warn("Permission not granted.")}).catch(e=>{tools_Tools.Error(e)}):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}};il.ArcRotateCameraVRDeviceOrientationInput=ArcRotateCameraVRDeviceOrientationInput;let FlyCameraKeyboardInput=class FlyCameraKeyboardInput{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=[]}attachControl(e){e=tools_Tools.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=>{let i=t.event;if(t.type===KeyboardEventTypes.KEYDOWN){if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);-1===t&&this._keys.push(i.keyCode),e||i.preventDefault()}}else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t{this._pointerInput(e)},pointerEvents_PointerEventTypes.POINTERDOWN|pointerEvents_PointerEventTypes.POINTERUP|pointerEvents_PointerEventTypes.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add(()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)})}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){let t=e.event,i=this.camera,r=i.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType||e.type!==pointerEvents_PointerEventTypes.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;let s=t.target;if(e.type===pointerEvents_PointerEventTypes.POINTERDOWN){try{null==s||s.setPointerCapture(t.pointerId)}catch(e){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),r.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===pointerEvents_PointerEventTypes.POINTERUP){try{null==s||s.releasePointerCapture(t.pointerId)}catch(e){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===pointerEvents_PointerEventTypes.POINTERMOVE){if(!this._previousPosition){r.isPointerLock&&this._onMouseMove(e.event);return}let i=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(i,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){let t=this.camera,i=t.getEngine();if(!i.isPointerLock)return;let r=e.movementX,s=e.movementY;this._rotateCamera(r,s),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){let i;let r=this.camera,s=r._calculateHandednessMultiplier();e*=s;let a=e/this.angularSensibility,n=t/this.angularSensibility,o=math_vector_Quaternion.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z);if(this.buttonsPitch.some(e=>e===this.activeButton)&&(i=math_vector_Quaternion.RotationAxis(math_axis_Axis.X,n),o.multiplyInPlace(i)),this.buttonsYaw.some(e=>e===this.activeButton)){i=math_vector_Quaternion.RotationAxis(math_axis_Axis.Y,a),o.multiplyInPlace(i);let e=r.bankedTurnLimit+r._trackRoll;if(r.bankedTurn&&-ee===this.activeButton)&&(i=math_vector_Quaternion.RotationAxis(math_axis_Axis.Z,-a),r._trackRoll-=a,o.multiplyInPlace(i)),o.toEulerAnglesToRef(r.rotation)}};__decorate([serialize()],FlyCameraMouseInput.prototype,"buttons",void 0),__decorate([serialize()],FlyCameraMouseInput.prototype,"angularSensibility",void 0),il.FlyCameraMouseInput=FlyCameraMouseInput;let FollowCameraKeyboardMoveInput=class FollowCameraKeyboardMoveInput{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=[]}attachControl(e){e=tools_Tools.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=>{let i=t.event;if(!i.metaKey){if(t.type===KeyboardEventTypes.KEYDOWN){if(this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);-1===t&&this._keys.push(i.keyCode),i.preventDefault&&!e&&i.preventDefault()}}else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&!e&&i.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(){this._onKeyboardObserver&&this._keys.forEach(e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)})}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}};__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetIncr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetDecr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierAlt",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierCtrl",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierShift",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetIncr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetDecr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierAlt",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierCtrl",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierShift",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusIncr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusDecr",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierAlt",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierCtrl",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierShift",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"heightSensibility",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"rotationSensibility",void 0),__decorate([serialize()],FollowCameraKeyboardMoveInput.prototype,"radiusSensibility",void 0),il.FollowCameraKeyboardMoveInput=FollowCameraKeyboardMoveInput;let FollowCameraMouseWheelInput=class FollowCameraMouseWheelInput{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==pointerEvents_PointerEventTypes.POINTERWHEEL)return;let i=t.event,r=0,s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(console.assert(this.axisControlRadius+this.axisControlHeight+this.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,pointerEvents_PointerEventTypes.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}};__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"axisControlRadius",void 0),__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"axisControlHeight",void 0),__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"axisControlRotation",void 0),__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"wheelPrecision",void 0),__decorate([serialize()],FollowCameraMouseWheelInput.prototype,"wheelDeltaPercentage",void 0),il.FollowCameraMouseWheelInput=FollowCameraMouseWheelInput;let FollowCameraPointersInput=class FollowCameraPointersInput extends BaseCameraPointersInput{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,a){if(0===i&&null===s||0===r&&null===a)return;let n=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(n*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=n*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=n*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=n*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=n),this.axisPinchControlHeight&&(this.camera.heightOffset+=n),this.axisPinchControlRadius&&(this.camera.radius-=n))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;let e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";console.assert(this.axisXControlRotation+this.axisXControlHeight+this.axisXControlRadius<=1,e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),console.assert(this.axisYControlRotation+this.axisYControlHeight+this.axisYControlRadius<=1,e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),console.assert(this.axisPinchControlRotation+this.axisPinchControlHeight+this.axisPinchControlRadius<=1,e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}};__decorate([serialize()],FollowCameraPointersInput.prototype,"angularSensibilityX",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"angularSensibilityY",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"pinchPrecision",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"pinchDeltaPercentage",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisXControlRadius",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisXControlHeight",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisXControlRotation",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisYControlRadius",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisYControlHeight",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisYControlRotation",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisPinchControlRadius",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisPinchControlHeight",void 0),__decorate([serialize()],FollowCameraPointersInput.prototype,"axisPinchControlRotation",void 0),il.FollowCameraPointersInput=FollowCameraPointersInput;let FreeCameraKeyboardMoveInput=class FreeCameraKeyboardMoveInput{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=[]}attachControl(e){e=tools_Tools.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=>{let i=t.event;if(!i.metaKey){if(t.type===KeyboardEventTypes.KEYDOWN){if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);-1===t&&this._keys.push(i.keyCode),e||i.preventDefault()}}else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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){let e=this.camera;for(let t=0;t{let s=r.event,a="touch"===s.pointerType;if(!this.touchEnabled&&a||r.type!==pointerEvents_PointerEventTypes.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;let n=s.target;if(r.type===pointerEvents_PointerEventTypes.POINTERDOWN){if(a&&-1!==this._activePointerId||!a&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==n||n.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},!e&&(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===pointerEvents_PointerEventTypes.POINTERUP){if(a&&this._activePointerId!==s.pointerId||!a&&this._currentActiveButton!==s.button)return;try{null==n||n.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===pointerEvents_PointerEventTypes.POINTERMOVE&&(this._activePointerId===s.pointerId||!a)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let t=this.camera._calculateHandednessMultiplier(),i=(s.clientX-this._previousPosition.x)*t,r=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=r/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:r}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;let r=this.camera._calculateHandednessMultiplier(),s=i.movementX*r;this.camera.cameraRotation.y+=s/this.angularSensibility;let a=i.movementY;this.camera.cameraRotation.x+=a/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,pointerEvents_PointerEventTypes.POINTERDOWN|pointerEvents_PointerEventTypes.POINTERUP|pointerEvents_PointerEventTypes.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.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"}};__decorate([serialize()],FreeCameraMouseInput.prototype,"buttons",void 0),__decorate([serialize()],FreeCameraMouseInput.prototype,"angularSensibility",void 0),il.FreeCameraMouseInput=FreeCameraMouseInput,function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(eP||(eP={}));let FreeCameraMouseWheelInput=class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput{constructor(){super(...arguments),this._moveRelative=math_vector_Vector3.Zero(),this._rotateRelative=math_vector_Vector3.Zero(),this._moveScene=math_vector_Vector3.Zero(),this._wheelXAction=eP.MoveRelative,this._wheelXActionCoordinate=eo.X,this._wheelYAction=eP.MoveRelative,this._wheelYActionCoordinate=eo.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){(null!==e||this._wheelXAction===eP.MoveRelative)&&(this._wheelXAction=eP.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==eP.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){(null!==e||this._wheelYAction===eP.MoveRelative)&&(this._wheelYAction=eP.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==eP.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){(null!==e||this._wheelZAction===eP.MoveRelative)&&(this._wheelZAction=eP.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==eP.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){(null!==e||this._wheelXAction===eP.RotateRelative)&&(this._wheelXAction=eP.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==eP.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){(null!==e||this._wheelYAction===eP.RotateRelative)&&(this._wheelYAction=eP.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==eP.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){(null!==e||this._wheelZAction===eP.RotateRelative)&&(this._wheelZAction=eP.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==eP.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){(null!==e||this._wheelXAction===eP.MoveScene)&&(this._wheelXAction=eP.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==eP.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){(null!==e||this._wheelYAction===eP.MoveScene)&&(this._wheelYAction=eP.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==eP.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){(null!==e||this._wheelZAction===eP.MoveScene)&&(this._wheelZAction=eP.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==eP.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);let e=math_vector_Matrix.Zero();this.camera.getViewMatrix().invertToRef(e);let t=math_vector_Vector3.Zero();math_vector_Vector3.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,i){if(0===e||null===t||null===i)return;let r=null;switch(t){case eP.MoveRelative:r=this._moveRelative;break;case eP.RotateRelative:r=this._rotateRelative;break;case eP.MoveScene:r=this._moveScene}switch(i){case eo.X:r.set(e,0,0);break;case eo.Y:r.set(0,e,0);break;case eo.Z:r.set(0,0,e)}}};__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelXMoveRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelYMoveRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelZMoveRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelXRotateRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelYRotateRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelZRotateRelative",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelXMoveScene",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelYMoveScene",null),__decorate([serialize()],FreeCameraMouseWheelInput.prototype,"wheelZMoveScene",null),il.FreeCameraMouseWheelInput=FreeCameraMouseWheelInput;let FreeCameraTouchInput=class FreeCameraTouchInput{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=[],this._isSafari=tools_Tools.IsSafari()}attachControl(e){e=tools_Tools.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s){if(i.type===pointerEvents_PointerEventTypes.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===pointerEvents_PointerEventTypes.POINTERUP){e||r.preventDefault();let i=this._pointerPressed.indexOf(r.pointerId);if(-1===i||(this._pointerPressed.splice(i,1),0!=i))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===pointerEvents_PointerEventTypes.POINTERMOVE){if(e||r.preventDefault(),!t)return;let i=this._pointerPressed.indexOf(r.pointerId);if(0!=i)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,pointerEvents_PointerEventTypes.POINTERDOWN|pointerEvents_PointerEventTypes.POINTERUP|pointerEvents_PointerEventTypes.POINTERMOVE),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.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||0===this._offsetX&&0===this._offsetY)return;let e=this.camera,t=e._calculateHandednessMultiplier();e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility;let i=this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1;if(i)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{let t=e._computeLocalCameraSpeed(),i=new math_vector_Vector3(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);math_vector_Matrix.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(math_vector_Vector3.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}};__decorate([serialize()],FreeCameraTouchInput.prototype,"touchAngularSensibility",void 0),__decorate([serialize()],FreeCameraTouchInput.prototype,"touchMoveSensibility",void 0),il.FreeCameraTouchInput=FreeCameraTouchInput;let FreeCameraInputsManager=class FreeCameraInputsManager extends CameraInputsManager{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new FreeCameraKeyboardMoveInput),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new FreeCameraMouseInput(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new FreeCameraMouseWheelInput,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new FreeCameraTouchInput),this}clear(){super.clear(),this._mouseInput=null}};FreeCameraInputsManager.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new FreeCameraDeviceOrientationInput,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};let FreeCameraDeviceOrientationInput=class FreeCameraDeviceOrientationInput{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1,eventHandler=()=>{window.removeEventListener("deviceorientation",eventHandler),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",eventHandler),i("WaitForOrientationChangeAsync timed out"))},e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"==e?window.addEventListener("deviceorientation",eventHandler):tools_Tools.Warn("Permission not granted.")}).catch(e=>{tools_Tools.Error(e)}):window.addEventListener("deviceorientation",eventHandler)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new math_vector_Quaternion,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new observable_Observable,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-tools_Tools.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?tools_Tools.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?tools_Tools.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?tools_Tools.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new math_vector_Quaternion(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new math_vector_Quaternion),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){let e=this.camera.getScene().getEngine().getHostWindow();if(e){let eventHandler=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e?eventHandler():tools_Tools.Warn("Permission not granted.")}).catch(e=>{tools_Tools.Error(e)}):eventHandler()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(math_vector_Quaternion.RotationYawPitchRollToRef(tools_Tools.ToRadians(this._alpha),tools_Tools.ToRadians(this._beta),-tools_Tools.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}};il.FreeCameraDeviceOrientationInput=FreeCameraDeviceOrientationInput;let FreeCameraGamepadInput=class FreeCameraGamepadInput{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=math_vector_Matrix.Identity(),this._deltaTransform=math_vector_Vector3.Zero(),this._vector3=math_vector_Vector3.Zero(),this._vector2=math_vector_Vector2.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===Gamepad.POSE_ENABLED||this.gamepad&&e.type!==Gamepad.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){let e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):math_vector_Matrix.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);let r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),math_vector_Vector3.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}};__decorate([serialize()],FreeCameraGamepadInput.prototype,"gamepadAngularSensibility",void 0),__decorate([serialize()],FreeCameraGamepadInput.prototype,"gamepadMoveSensibility",void 0),il.FreeCameraGamepadInput=FreeCameraGamepadInput,function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(eA||(eA={}));let VirtualJoystick=class VirtualJoystick{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;let i=Object.assign(Object.assign({},VirtualJoystick._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,VirtualJoystick._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=eA.X,this._axisTargetedByUpAndDown=eA.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new StringDictionary,this.deltaPosition=math_vector_Vector3.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{VirtualJoystick._VJCanvasWidth=window.innerWidth,VirtualJoystick._VJCanvasHeight=window.innerHeight,VirtualJoystick.Canvas&&(VirtualJoystick.Canvas.width=VirtualJoystick._VJCanvasWidth,VirtualJoystick.Canvas.height=VirtualJoystick._VJCanvasHeight),VirtualJoystick._HalfWidth=VirtualJoystick._VJCanvasWidth/2},!VirtualJoystick.Canvas){window.addEventListener("resize",this._onResize,!1),VirtualJoystick.Canvas=document.createElement("canvas"),VirtualJoystick._VJCanvasWidth=window.innerWidth,VirtualJoystick._VJCanvasHeight=window.innerHeight,VirtualJoystick.Canvas.width=window.innerWidth,VirtualJoystick.Canvas.height=window.innerHeight,VirtualJoystick.Canvas.style.width="100%",VirtualJoystick.Canvas.style.height="100%",VirtualJoystick.Canvas.style.position="absolute",VirtualJoystick.Canvas.style.backgroundColor="transparent",VirtualJoystick.Canvas.style.top="0px",VirtualJoystick.Canvas.style.left="0px",VirtualJoystick.Canvas.style.zIndex="5",VirtualJoystick.Canvas.style.touchAction="none",VirtualJoystick.Canvas.setAttribute("touch-action","none");let e=VirtualJoystick.Canvas.getContext("2d");if(!e)throw Error("Unable to create canvas for virtual joystick");VirtualJoystick._VJCanvasContext=e,VirtualJoystick._VJCanvasContext.strokeStyle="#ffffff",VirtualJoystick._VJCanvasContext.lineWidth=2,document.body.appendChild(VirtualJoystick.Canvas)}VirtualJoystick._HalfWidth=VirtualJoystick.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&VirtualJoystick._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new math_vector_Vector2(0,0),this._joystickPreviousPointerPos=new math_vector_Vector2(0,0),this._joystickPointerStartPos=new math_vector_Vector2(0,0),this._deltaJoystickVector=new math_vector_Vector2(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},VirtualJoystick.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("contextmenu",e=>{e.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){e.preventDefault(),(!0===this._leftJoystick?e.clientXVirtualJoystick._HalfWidth)&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):VirtualJoystick._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){let t=new math_vector_Vector2(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){let t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){let e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?VirtualJoystick._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.lineWidth=2,VirtualJoystick._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath(),VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.lineWidth=6,VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?VirtualJoystick._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.lineWidth=2,VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(VirtualJoystick._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.fillStyle="white",VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle="red",VirtualJoystick._VJCanvasContext.lineWidth=6,VirtualJoystick._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){VirtualJoystick.Canvas&&(VirtualJoystick.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(VirtualJoystick.Canvas),VirtualJoystick.Canvas=null),this._released=!0}};VirtualJoystick._GlobalJoystickIndex=0,VirtualJoystick._AlwaysVisibleSticks=0,FreeCameraInputsManager.prototype.addVirtualJoystick=function(){return this.add(new FreeCameraVirtualJoystickInput),this};let FreeCameraVirtualJoystickInput=class FreeCameraVirtualJoystickInput{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){let e=this.camera,t=50*e._computeLocalCameraSpeed(),i=math_vector_Matrix.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=math_vector_Vector3.TransformCoordinates(new math_vector_Vector3(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new VirtualJoystick(!0),this._leftjoystick.setAxisForUpDown(eA.Z),this._leftjoystick.setAxisForLeftRight(eA.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new VirtualJoystick(!1),this._rightjoystick.setAxisForUpDown(eA.X),this._rightjoystick.setAxisForLeftRight(eA.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}};il.FreeCameraVirtualJoystickInput=FreeCameraVirtualJoystickInput;let targetCamera_TargetCamera=class targetCamera_TargetCamera extends camera_Camera{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=math_vector_Vector3.Zero(),this._tmpTargetVector=math_vector_Vector3.Zero(),this.cameraDirection=new math_vector_Vector3(0,0,0),this.cameraRotation=new math_vector_Vector2(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new math_vector_Quaternion,this.rotation=new math_vector_Vector3(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=math_vector_Vector3.Zero(),this._initialFocalDistance=1,this._viewMatrix=math_vector_Matrix.Zero(),this._camMatrix=math_vector_Matrix.Zero(),this._cameraTransformMatrix=math_vector_Matrix.Zero(),this._cameraRotationMatrix=math_vector_Matrix.Zero(),this._referencePoint=new math_vector_Vector3(0,0,1),this._transformedReferencePoint=math_vector_Vector3.Zero(),this._deferredPositionUpdate=new math_vector_Vector3,this._deferredRotationQuaternionUpdate=new math_vector_Quaternion,this._deferredRotationUpdate=new math_vector_Vector3,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=math_vector_Vector3.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();let 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){let e=this.lockedTarget,t=e.computeWorldMatrix();t.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 math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new math_vector_Quaternion(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let 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;let 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(){let 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+=.001),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),math_vector_Matrix.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);let 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&&math_vector_Quaternion.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){this.parent.getWorldMatrix().invertToRef(math_vector_TmpVectors.Matrix[0]),math_vector_Vector3.TransformNormalToRef(this.cameraDirection,math_vector_TmpVectors.Matrix[0],math_vector_TmpVectors.Vector3[0]),this._deferredPositionUpdate.addInPlace(math_vector_TmpVectors.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=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(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint&&(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion)){let e=this._deferredRotationUpdate.lengthSquared();e&&(math_vector_Quaternion.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)<.001*this.speed&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<.001*this.speed&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<.001*this.speed&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),i&&(Math.abs(this.cameraRotation.x)<.001*this.speed&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<.001*this.speed&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):math_vector_Matrix.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return math_vector_Vector3.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),math_vector_Vector3.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?math_axis_Axis.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(math_vector_Quaternion.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),math_axis_Axis.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,i){if(this.ignoreParentScaling){if(this.parent){let r=this.parent.getWorldMatrix();math_vector_Vector3.TransformCoordinatesToRef(e,r,this._globalPosition),math_vector_Vector3.TransformCoordinatesToRef(t,r,this._tmpTargetVector),math_vector_Vector3.TransformNormalToRef(i,r,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(i);this.getScene().useRightHandedSystem?math_vector_Matrix.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):math_vector_Matrix.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix);return}if(this.getScene().useRightHandedSystem?math_vector_Matrix.LookAtRHToRef(e,t,i,this._viewMatrix):math_vector_Matrix.LookAtLHToRef(e,t,i,this._viewMatrix),this.parent){let 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!==camera_Camera.RIG_MODE_NONE){let t=new targetCamera_TargetCamera(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,this.cameraRigMode===camera_Camera.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new math_vector_Quaternion),t._cameraRigParams={},t.rotationQuaternion=new math_vector_Quaternion),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:{let i=this.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,r=this.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*r,t);break}case camera_Camera.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){let i=this.getTarget();i.subtractToRef(this.position,targetCamera_TargetCamera._TargetFocalPoint),targetCamera_TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);let r=targetCamera_TargetCamera._TargetFocalPoint.addInPlace(this.position);math_vector_Matrix.TranslationToRef(-r.x,-r.y,-r.z,targetCamera_TargetCamera._TargetTransformMatrix),targetCamera_TargetCamera._TargetTransformMatrix.multiplyToRef(math_vector_Matrix.RotationAxis(t.upVector,e),targetCamera_TargetCamera._RigCamTransformMatrix),math_vector_Matrix.TranslationToRef(r.x,r.y,r.z,targetCamera_TargetCamera._TargetTransformMatrix),targetCamera_TargetCamera._RigCamTransformMatrix.multiplyToRef(targetCamera_TargetCamera._TargetTransformMatrix,targetCamera_TargetCamera._RigCamTransformMatrix),math_vector_Vector3.TransformCoordinatesToRef(this.position,targetCamera_TargetCamera._RigCamTransformMatrix,t.position),t.setTarget(r)}getClassName(){return"TargetCamera"}};targetCamera_TargetCamera._RigCamTransformMatrix=new math_vector_Matrix,targetCamera_TargetCamera._TargetTransformMatrix=new math_vector_Matrix,targetCamera_TargetCamera._TargetFocalPoint=new math_vector_Vector3,__decorate([serializeAsVector3()],targetCamera_TargetCamera.prototype,"rotation",void 0),__decorate([serialize()],targetCamera_TargetCamera.prototype,"speed",void 0),__decorate([serializeAsMeshReference("lockedTargetId")],targetCamera_TargetCamera.prototype,"lockedTarget",void 0);let FreeCamera=class FreeCamera extends targetCamera_TargetCamera{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){let e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){let t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){let e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){let t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){let e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){let e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){let e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){let e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new math_vector_Vector3(.5,1,.5),this.ellipsoidOffset=new math_vector_Vector3(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=math_vector_Vector3.Zero(),this._diffPosition=math_vector_Vector3.Zero(),this._newPosition=math_vector_Vector3.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>engine_Engine.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new FreeCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new math_vector_Vector3(0,0,0),this.cameraRotation=new math_vector_Vector2(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?math_vector_Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=math_vector_Vector3.Zero(),this._transformedDirection=math_vector_Vector3.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"}};__decorate([serializeAsVector3()],FreeCamera.prototype,"ellipsoid",void 0),__decorate([serializeAsVector3()],FreeCamera.prototype,"ellipsoidOffset",void 0),__decorate([serialize()],FreeCamera.prototype,"checkCollisions",void 0),__decorate([serialize()],FreeCamera.prototype,"applyGravity",void 0),node_Node.AddNodeConstructor("TouchCamera",(e,t)=>()=>new TouchCamera(e,math_vector_Vector3.Zero(),t));let TouchCamera=class TouchCamera extends FreeCamera{get touchAngularSensibility(){let e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){let e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){let e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}};node_Node.AddNodeConstructor("ArcRotateCamera",(e,t)=>()=>new ArcRotateCamera(e,0,0,1,math_vector_Vector3.Zero(),t));let ArcRotateCamera=class ArcRotateCamera extends targetCamera_TargetCamera{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 math_vector_Matrix,this._upToYMatrix=new math_vector_Matrix,this._upVector=math_vector_Vector3.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){math_vector_Matrix.RotationAlignToRef(math_vector_Vector3.UpReadOnly,this._upVector,this._yToUpMatrix),math_vector_Matrix.RotationAlignToRef(this._upVector,math_vector_Vector3.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let 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 BouncingBehavior,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 FramingBehavior,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 AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,a,n=!0){super(e,math_vector_Vector3.Zero(),a,n),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=math_vector_Vector3.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=math_vector_Vector2.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new math_vector_Matrix,this.panningAxis=new math_vector_Vector3(1,1,0),this._transformedDirection=new math_vector_Vector3,this.mapPanning=!1,this.onMeshTargetChangedObservable=new observable_Observable,this.checkCollisions=!1,this.collisionRadius=new math_vector_Vector3(.5,.5,.5),this._previousPosition=math_vector_Vector3.Zero(),this._collisionVelocity=math_vector_Vector3.Zero(),this._newPosition=math_vector_Vector3.Zero(),this._computationVector=math_vector_Vector3.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);let r=Math.cos(this.alpha),s=Math.sin(this.alpha),a=Math.cos(this.beta),n=Math.sin(this.beta);0===n&&(n=1e-4);let o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*n,this.radius*a,this.radius*s*n),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=(l=l.clone()).negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=math_vector_Vector3.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new ArcRotateCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new math_vector_Vector3(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=math_vector_Vector2.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){let e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}let 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!!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,i=!0,r=2){let s=arguments;t=tools_Tools.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[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(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){let e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier(),i=this.inertialAlphaOffset*t;this.beta<=0&&(i*=-1),this.alpha+=i*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,.001>Math.abs(this.inertialAlphaOffset)&&(this.inertialAlphaOffset=0),.001>Math.abs(this.inertialBetaOffset)&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<.001*this.speed&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){let e=new math_vector_Vector3(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),math_vector_Vector3.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){let e=this.upVector,t=math_vector_Vector3.CrossToRef(this._transformedDirection,e,this._transformedDirection);math_vector_Vector3.CrossToRef(e,t,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost){if(this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);let e=math_vector_Vector3.DistanceSquared(this._transformedDirection,this.panningOriginTarget);e<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<.001*this.speed&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<.001*this.speed&&(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.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.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)&&math_vector_Vector3.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);let 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);let 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,i=!1,r=!1){var s;if(r=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:r,e.getBoundingInfo)t?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{let t=this._getTargetPosition();if(t&&!i&&t.equals(e))return;this._targetHost=null,this._target=e,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&math_vector_Vector3.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let 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&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=mesh_Mesh.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){let t=e||this.getScene().meshes;i=mesh_Mesh.MinMax(t),r=math_vector_Vector3.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=mesh_Mesh.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:case camera_Camera.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}let r=new ArcRotateCamera(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:case camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:case camera_Camera.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=math_vector_Vector3.Distance(e,t),s=this.getScene().getEngine(),a=s.getAspectRatio(this),n=Math.tan(this.fov/2),o=n*a,l=.5*r*i;return Math.max(l*Math.sqrt(1+1/(o*o)),l*Math.sqrt(1+1/(n*n)))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}};__decorate([serialize()],ArcRotateCamera.prototype,"alpha",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"beta",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"radius",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"overrideCloneAlphaBetaRadius",void 0),__decorate([serializeAsVector3("target")],ArcRotateCamera.prototype,"_target",void 0),__decorate([serializeAsMeshReference("targetHost")],ArcRotateCamera.prototype,"_targetHost",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialAlphaOffset",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialBetaOffset",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialRadiusOffset",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"lowerAlphaLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"upperAlphaLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"lowerBetaLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"upperBetaLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"lowerRadiusLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"upperRadiusLimit",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialPanningX",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"inertialPanningY",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"pinchToPanMaxDistance",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"panningDistanceLimit",void 0),__decorate([serializeAsVector3()],ArcRotateCamera.prototype,"panningOriginTarget",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"panningInertia",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"zoomToMouseLocation",null),__decorate([serialize()],ArcRotateCamera.prototype,"zoomOnFactor",void 0),__decorate([generateSerializableMember(4,void 0)],ArcRotateCamera.prototype,"targetScreenOffset",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"allowUpsideDown",void 0),__decorate([serialize()],ArcRotateCamera.prototype,"useInputToRestoreState",void 0),node_Node.AddNodeConstructor("DeviceOrientationCamera",(e,t)=>()=>new DeviceOrientationCamera(e,math_vector_Vector3.Zero(),t));let DeviceOrientationCamera=class DeviceOrientationCamera extends FreeCamera{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new math_vector_Quaternion,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new math_vector_Quaternion,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add(e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new math_vector_Quaternion),math_vector_Quaternion.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))}))})}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=math_axis_Axis.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new math_vector_Quaternion),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}};let FlyCameraInputsManager=class FlyCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addKeyboard(){return this.add(new FlyCameraKeyboardInput),this}addMouse(){return this.add(new FlyCameraMouseInput),this}};let FlyCamera=class FlyCamera extends targetCamera_TargetCamera{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){let e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){let t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){let e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){let t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new math_vector_Vector3(1,1,1),this.ellipsoidOffset=new math_vector_Vector3(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=math_vector_Vector3.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=math_vector_Vector3.Zero(),this._diffPosition=math_vector_Vector3.Zero(),this._newPosition=math_vector_Vector3.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>engine_Engine.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new FlyCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new math_vector_Vector3(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?math_vector_Vector3.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=math_vector_Vector3.Zero(),this._transformedDirection=math_vector_Vector3.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()}restoreRoll(e){let t=this._trackRoll,i=this.rotation.z,r=t-i;Math.abs(r)>=.001&&(this.rotation.z+=r/e,.001>=Math.abs(t-this.rotation.z)&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}};__decorate([serializeAsVector3()],FlyCamera.prototype,"ellipsoid",void 0),__decorate([serializeAsVector3()],FlyCamera.prototype,"ellipsoidOffset",void 0),__decorate([serialize()],FlyCamera.prototype,"checkCollisions",void 0),__decorate([serialize()],FlyCamera.prototype,"applyGravity",void 0);let FollowCameraInputsManager=class FollowCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addKeyboard(){return this.add(new FollowCameraKeyboardMoveInput),this}addMouseWheel(){return this.add(new FollowCameraMouseWheelInput),this}addPointers(){return this.add(new FollowCameraPointersInput),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}};node_Node.AddNodeConstructor("FollowCamera",(e,t)=>()=>new FollowCamera(e,math_vector_Vector3.Zero(),t)),node_Node.AddNodeConstructor("ArcFollowCamera",(e,t)=>()=>new ArcFollowCamera(e,0,0,1,null,t));let FollowCamera=class FollowCamera extends targetCamera_TargetCamera{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new FollowCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;let t=math_vector_TmpVectors.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);let i=Math.atan2(t.m[8],t.m[10]),r=tools_Tools.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),a=s.x+Math.sin(r)*this.radius,n=s.z+Math.cos(r)*this.radius,o=a-this.position.x,l=s.y+this.heightOffset-this.position.y,h=n-this.position.z,c=o*this.cameraAcceleration*2,u=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new math_vector_Vector3(this.position.x+c,this.position.y+u,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=tools_Tools.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}};__decorate([serialize()],FollowCamera.prototype,"radius",void 0),__decorate([serialize()],FollowCamera.prototype,"lowerRadiusLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"upperRadiusLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"rotationOffset",void 0),__decorate([serialize()],FollowCamera.prototype,"lowerRotationOffsetLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"upperRotationOffsetLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"heightOffset",void 0),__decorate([serialize()],FollowCamera.prototype,"lowerHeightOffsetLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"upperHeightOffsetLimit",void 0),__decorate([serialize()],FollowCamera.prototype,"cameraAcceleration",void 0),__decorate([serialize()],FollowCamera.prototype,"maxCameraSpeed",void 0),__decorate([serializeAsMeshReference("lockedTargetId")],FollowCamera.prototype,"lockedTarget",void 0);let ArcFollowCamera=class ArcFollowCamera extends targetCamera_TargetCamera{constructor(e,t,i,r,s,a){super(e,math_vector_Vector3.Zero(),a),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=math_vector_Vector3.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);let e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}};(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.Back=8]="Back",e[e.Start=9]="Start",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"})(eM||(eM={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(eI||(eI={}));let Xbox360Pad=class Xbox360Pad extends Gamepad{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new observable_Observable,this.onButtonUpObservable=new observable_Observable,this.onPadDownObservable=new observable_Observable,this.onPadUpObservable=new observable_Observable,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=Gamepad.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,eM.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,eM.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,eM.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,eM.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,eM.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,eM.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,eM.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,eM.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,eM.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,eM.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,eI.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,eI.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,eI.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,eI.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}};(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.Share=8]="Share",e[e.Options=9]="Options",e[e.LeftStick=10]="LeftStick",e[e.RightStick=11]="RightStick"})(eD||(eD={})),function(e){e[e.Up=12]="Up",e[e.Down=13]="Down",e[e.Left=14]="Left",e[e.Right=15]="Right"}(eO||(eO={}));let DualShockPad=class DualShockPad extends Gamepad{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new observable_Observable,this.onButtonUpObservable=new observable_Observable,this.onPadDownObservable=new observable_Observable,this.onPadUpObservable=new observable_Observable,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=Gamepad.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,eD.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,eD.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,eD.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,eD.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,eD.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,eD.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,eD.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,eD.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,eD.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,eD.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,eO.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,eO.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,eO.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,eO.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}};let GamepadManager=class GamepadManager{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new observable_Observable,IsWindowObjectExist()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new observable_Observable(e=>{for(let t in this._babylonGamepads){let i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}}),this._onGamepadConnectedEvent=e=>{let t;let i=e.gamepad;i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected||(this._babylonGamepads[i.index]?((t=this._babylonGamepads[i.index]).browserGamepad=i,t._isConnected=!0):t=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(t),this._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=e=>{let t=e.gamepad;for(let e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){let t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport){if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){let e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}}get gamepads(){return this._babylonGamepads}getGamepadByType(e=Gamepad.XBOX){for(let t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(e=>{e.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);let i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Xbox360Pad(e.id,e.index,e,r):i?new DualShockPad(e.id,e.index,e):new GenericPad(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){for(let e in this._updateGamepadObjects(),this._babylonGamepads){let t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch(e){-1===this._loggedErrors.indexOf(t.index)&&(tools_Tools.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&engine_Engine.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new universalCamera_UniversalCamera(e,math_vector_Vector3.Zero(),t));let universalCamera_UniversalCamera=class universalCamera_UniversalCamera extends TouchCamera{get gamepadAngularSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}};camera_Camera._CreateDefaultParsedCamera=(e,t)=>new universalCamera_UniversalCamera(e,math_vector_Vector3.Zero(),t),node_Node.AddNodeConstructor("GamepadCamera",(e,t)=>()=>new GamepadCamera(e,math_vector_Vector3.Zero(),t));let GamepadCamera=class GamepadCamera extends universalCamera_UniversalCamera{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}};let ih=`varying vec2 vUV;uniform samplerCube textureSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 uv=vUV*2.0-1.0; -#ifdef POSITIVEX -gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); -#endif -#ifdef NEGATIVEX -gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); -#endif -#ifdef POSITIVEY -gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); -#endif -#ifdef NEGATIVEY -gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); -#endif -#ifdef POSITIVEZ -gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); -#endif -#ifdef NEGATIVEZ -gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); -#endif -}`;ShaderStore.ShadersStore.passCubePixelShader=ih;let PassPostProcess=class PassPostProcess extends postProcess_PostProcess{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,a,n=0,o=!1){super(e,"pass",null,null,t,i,r,s,a,void 0,n,void 0,null,o)}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new PassPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};h["BABYLON.PassPostProcess"]=PassPostProcess,engine_Engine._RescalePostProcessFactory=e=>new PassPostProcess("rescale",1,null,2,e,!1,0);let ic=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;ShaderStore.ShadersStore.anaglyphPixelShader=ic;let AnaglyphPostProcess=class AnaglyphPostProcess extends postProcess_PostProcess{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,a){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,a),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)})}};function setStereoscopicAnaglyphRigMode(e){e._rigCameras[0]._rigPostProcess=new PassPostProcess(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new AnaglyphPostProcess(e.name+"_anaglyph",1,e._rigCameras)}h["BABYLON.AnaglyphPostProcess"]=AnaglyphPostProcess,node_Node.AddNodeConstructor("AnaglyphArcRotateCamera",(e,t,i)=>()=>new AnaglyphArcRotateCamera(e,0,0,1,math_vector_Vector3.Zero(),i.interaxial_distance,t));let AnaglyphArcRotateCamera=class AnaglyphArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,a,n){super(e,t,i,r,s,n),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=a,this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:a})}getClassName(){return"AnaglyphArcRotateCamera"}};node_Node.AddNodeConstructor("AnaglyphFreeCamera",(e,t,i)=>()=>new AnaglyphFreeCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,t));let AnaglyphFreeCamera=class AnaglyphFreeCamera extends FreeCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}};node_Node.AddNodeConstructor("AnaglyphGamepadCamera",(e,t,i)=>()=>new AnaglyphGamepadCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,t));let AnaglyphGamepadCamera=class AnaglyphGamepadCamera extends GamepadCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}};node_Node.AddNodeConstructor("AnaglyphUniversalCamera",(e,t,i)=>()=>new AnaglyphUniversalCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,t));let AnaglyphUniversalCamera=class AnaglyphUniversalCamera extends universalCamera_UniversalCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(camera_Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}};let iu=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; -#ifdef IS_STEREOSCOPIC_HORIZ -useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); -#else -#ifdef IS_STEREOSCOPIC_INTERLACED -float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); -#else -useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); -#endif -#endif -if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} -gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} -`;ShaderStore.ShadersStore.stereoscopicInterlacePixelShader=iu;let StereoscopicInterlacePostProcessI=class StereoscopicInterlacePostProcessI extends postProcess_PostProcess{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,a,n){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,a,n,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new math_vector_Vector2(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new math_vector_Vector2(1/this.width,1/this.height)}),this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}};function setStereoscopicRigMode(e){let t=e.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,r=e.cameraRigMode===camera_Camera.RIG_MODE_STEREOSCOPIC_INTERLACED;r?(e._rigCameras[0]._rigPostProcess=new PassPostProcess(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new StereoscopicInterlacePostProcessI(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new math_viewport_Viewport(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new math_viewport_Viewport(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}node_Node.AddNodeConstructor("StereoscopicArcRotateCamera",(e,t,i)=>()=>new StereoscopicArcRotateCamera(e,0,0,1,math_vector_Vector3.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicArcRotateCamera=class StereoscopicArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,a,n,o){super(e,t,i,r,s,o),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=a,this.isStereoscopicSideBySide=n,this.setCameraRigMode(n?camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:a})}getClassName(){return"StereoscopicArcRotateCamera"}};node_Node.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new StereoscopicFreeCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicFreeCamera=class StereoscopicFreeCamera extends FreeCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}};node_Node.AddNodeConstructor("StereoscopicGamepadCamera",(e,t,i)=>()=>new StereoscopicGamepadCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicGamepadCamera=class StereoscopicGamepadCamera extends GamepadCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}};node_Node.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new StereoscopicUniversalCamera(e,math_vector_Vector3.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicUniversalCamera=class StereoscopicUniversalCamera extends universalCamera_UniversalCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?camera_Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:camera_Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}};node_Node.AddNodeConstructor("VirtualJoysticksCamera",(e,t)=>()=>new VirtualJoysticksCamera(e,math_vector_Vector3.Zero(),t));let VirtualJoysticksCamera=class VirtualJoysticksCamera extends FreeCamera{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}};let VRCameraMetrics=class VRCameraMetrics{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return math_vector_Matrix.Translation(t,0,0)}get rightHMatrix(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return math_vector_Matrix.Translation(-t,0,0)}get leftPreViewMatrix(){return math_vector_Matrix.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return math_vector_Matrix.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){let e=new VRCameraMetrics;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}};let id=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; -float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) -gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;ShaderStore.ShadersStore.vrDistortionCorrectionPixelShader=id;let VRDistortionCorrectionPostProcess=class VRDistortionCorrectionPostProcess extends postProcess_PostProcess{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,texture_Texture.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new math_vector_Vector2(2,2/this.aspectRatio),this._scaleFactor=new math_vector_Vector2(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new math_vector_Vector2(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)}),this.onApplyObservable.add(e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}};let i_=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;ShaderStore.ShadersStore.vrMultiviewToSingleviewPixelShader=i_;let MultiviewRenderTarget=class MultiviewRenderTarget extends renderTargetTexture_RenderTargetTexture{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}};function createMultiviewUbo(e,t){let i=new UniformBuffer(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}engine_Engine.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){let s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";let a=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});a._framebuffer=s.createFramebuffer();let n=new internalTexture_InternalTexture(this,$.Unknown,!0);return n.width=e,n.height=t,n.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),a._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),a._depthStencilTextureArray=r,n.isReady=!0,a.setTextures(n),a._depthStencilTexture=n,a},engine_Engine.prototype.bindMultiviewFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"},engine_Engine.prototype.bindSpaceWarpFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw Error("Invalid Space Warp framebuffer")},camera_Camera.prototype._useMultiviewToSingleView=!1,camera_Camera.prototype._multiviewTexture=null,camera_Camera.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=e||this._multiviewTexture.getRenderHeight()!=t)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:e,height:t})):this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:e,height:t})};let ip=scene_Scene.prototype.createSceneUniformBuffer;scene_Scene.prototype._transformMatrixR=math_vector_Matrix.Zero(),scene_Scene.prototype._multiviewSceneUbo=null,scene_Scene.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=createMultiviewUbo(this.getEngine(),"scene_multiview")},scene_Scene.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?createMultiviewUbo(this.getEngine(),e):ip.bind(this)(e)},scene_Scene.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,math_vector_TmpVectors.Matrix[0]),Frustum.GetRightPlaneToRef(math_vector_TmpVectors.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},scene_Scene.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{}),this.onApplyObservable.add(e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)})}};function setVRRigMode(e,t){let i=t.vrCameraMetrics||VRCameraMetrics.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new math_viewport_Viewport(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new math_vector_Matrix,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new math_viewport_Viewport(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new math_vector_Matrix,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(logger_Logger.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}node_Node.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(e,t)=>()=>new VRDeviceOrientationArcRotateCamera(e,0,0,1,math_vector_Vector3.Zero(),t));let VRDeviceOrientationArcRotateCamera=class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,a,n=!0,o=VRCameraMetrics.GetDefault()){super(e,t,i,r,s,a),this._setRigMode=e=>setVRRigMode(this,e),o.compensateDistortion=n,this.setCameraRigMode(camera_Camera.RIG_MODE_VR,{vrCameraMetrics:o}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}};node_Node.AddNodeConstructor("VRDeviceOrientationFreeCamera",(e,t)=>()=>new VRDeviceOrientationFreeCamera(e,math_vector_Vector3.Zero(),t));let VRDeviceOrientationFreeCamera=class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera{constructor(e,t,i,r=!0,s=VRCameraMetrics.GetDefault()){super(e,t,i),this._setRigMode=e=>setVRRigMode(this,e),s.compensateDistortion=r,this.setCameraRigMode(camera_Camera.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}};node_Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(e,t)=>()=>new VRDeviceOrientationGamepadCamera(e,math_vector_Vector3.Zero(),t));let VRDeviceOrientationGamepadCamera=class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera{constructor(e,t,i,r=!0,s=VRCameraMetrics.GetDefault()){super(e,t,i,r,s),this._setRigMode=e=>setVRRigMode(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}};let PrePassConfiguration=class PrePassConfiguration{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}};let MaterialFlags=class MaterialFlags{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(1))}};MaterialFlags._DiffuseTextureEnabled=!0,MaterialFlags._DetailTextureEnabled=!0,MaterialFlags._DecalMapEnabled=!0,MaterialFlags._AmbientTextureEnabled=!0,MaterialFlags._OpacityTextureEnabled=!0,MaterialFlags._ReflectionTextureEnabled=!0,MaterialFlags._EmissiveTextureEnabled=!0,MaterialFlags._SpecularTextureEnabled=!0,MaterialFlags._BumpTextureEnabled=!0,MaterialFlags._LightmapTextureEnabled=!0,MaterialFlags._RefractionTextureEnabled=!0,MaterialFlags._ColorGradingTextureEnabled=!0,MaterialFlags._FresnelEnabled=!0,MaterialFlags._ClearCoatTextureEnabled=!0,MaterialFlags._ClearCoatBumpTextureEnabled=!0,MaterialFlags._ClearCoatTintTextureEnabled=!0,MaterialFlags._SheenTextureEnabled=!0,MaterialFlags._AnisotropicTextureEnabled=!0,MaterialFlags._ThicknessTextureEnabled=!0,MaterialFlags._RefractionIntensityTextureEnabled=!0,MaterialFlags._TranslucencyIntensityTextureEnabled=!0,MaterialFlags._IridescenceTextureEnabled=!0;let im=`#ifdef DECAL -uniform vec4 vDecalInfos; -#endif -`;ShaderStore.IncludesShadersStore.decalFragmentDeclaration=im;let ig=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; -#ifdef SPECULARTERM -uniform vec4 vSpecularColor; -#endif -uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; -#ifdef DIFFUSE -uniform vec2 vDiffuseInfos; -#endif -#ifdef AMBIENT -uniform vec2 vAmbientInfos; -#endif -#ifdef OPACITY -uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#ifdef ALPHATEST -uniform float alphaCutOff; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) -uniform mat4 view; -#endif -#ifdef REFRACTION -uniform vec4 vRefractionInfos; -#ifndef REFRACTIONMAP_3D -uniform mat4 refractionMatrix; -#endif -#ifdef REFRACTIONFRESNEL -uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; -#endif -#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) -uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; -#endif -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -uniform vec2 vSpecularInfos; -#endif -#ifdef DIFFUSEFRESNEL -uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; -#endif -#ifdef OPACITYFRESNEL -uniform vec4 opacityParts; -#endif -#ifdef EMISSIVEFRESNEL -uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos; -#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) -uniform mat4 reflectionMatrix; -#endif -#ifndef REFLECTIONMAP_SKYBOX -#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; -#endif -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos; -#endif -#include -#define ADDITIONAL_FRAGMENT_DECLARATION -`;ShaderStore.IncludesShadersStore.defaultFragmentDeclaration=ig;let iv=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; -#ifdef MULTIVIEW -mat4 viewProjectionR; -#endif -mat4 view;mat4 projection;vec4 vEyePosition;}; -`;ShaderStore.IncludesShadersStore.sceneUboDeclaration=iv;let ix=`#ifdef WEBGL2 -uniform mat4 world;uniform float visibility; -#else -layout(std140,column_major) uniform;uniform Mesh -{mat4 world;float visibility;}; -#endif -#define WORLD_UBO -`;ShaderStore.IncludesShadersStore.meshUboDeclaration=ix;let ib=`layout(std140,column_major) uniform;uniform Material -{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; -#define ADDITIONAL_UBO_DECLARATION -}; -#include -#include -`;ShaderStore.IncludesShadersStore.defaultUboDeclaration=ib;let iT=`#ifdef PREPASS -#extension GL_EXT_draw_buffers : require -layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; -#ifdef PREPASS_DEPTH -varying highp vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; -#endif -#endif -`;ShaderStore.IncludesShadersStore.prePassDeclaration=iT;let iS=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY -#extension GL_EXT_draw_buffers : require -layout(location=0) out vec2 depth; -layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; -#define MAX_DEPTH 99999.0 -highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; -#endif -`;ShaderStore.IncludesShadersStore.oitDeclaration=iS;let iC=`#ifdef MAINUV{X} -varying vec2 vMainUV{X}; -#endif -`;ShaderStore.IncludesShadersStore.mainUVVaryingDeclaration=iC;let iE=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; -const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; -#define saturate(x) clamp(x,0.0,1.0) -#define absEps(x) abs(x)+Epsilon -#define maxEps(x) max(x,Epsilon) -#define saturateEps(x) clamp(x,Epsilon,1.0) -mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( -vec3(i0.x,i1.x,i2.x), -vec3(i0.y,i1.y,i2.y), -vec3(i0.z,i1.z,i2.z) -);return outMatrix;} -mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), -b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), -b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} -#if USE_EXACT_SRGB_CONVERSIONS -vec3 toLinearSpaceExact(vec3 color) -{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); -#else -return -vec3( -color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, -color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, -color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); -#endif -} -vec3 toGammaSpaceExact(vec3 color) -{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); -#else -return -vec3( -color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, -color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, -color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); -#endif -} -#endif -float toLinearSpace(float color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; -#else -return pow(color,LinearEncodePowerApprox); -#endif -} -vec3 toLinearSpace(vec3 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return toLinearSpaceExact(color); -#else -return pow(color,vec3(LinearEncodePowerApprox)); -#endif -} -vec4 toLinearSpace(vec4 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return vec4(toLinearSpaceExact(color.rgb),color.a); -#else -return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); -#endif -} -float toGammaSpace(float color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; -#else -return pow(color,GammaEncodePowerApprox); -#endif -} -vec3 toGammaSpace(vec3 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return toGammaSpaceExact(color); -#else -return pow(color,vec3(GammaEncodePowerApprox)); -#endif -} -vec4 toGammaSpace(vec4 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return vec4(toGammaSpaceExact(color.rgb),color.a); -#else -return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); -#endif -} -float square(float value) -{return value*value;} -vec3 square(vec3 value) -{return value*value;} -float pow5(float value) {float sq=value*value;return sq*sq*value;} -float getLuminance(vec3 color) -{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} -float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} -float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} -const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } -vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} -vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} -`;ShaderStore.IncludesShadersStore.helperFunctions=iE;let iy=`#ifdef LIGHT{X} -uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; -#ifdef SPECULARTERM -uniform vec4 vLightSpecular{X}; -#else -vec4 vLightSpecular{X}=vec4(0.); -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DArrayShadow shadowSampler{X}; -#else -uniform highp sampler2DArray shadowSampler{X}; -#endif -#ifdef SHADOWCSMDEBUG{X} -const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] -( -vec3 ( 1.5,0.0,0.0 ), -vec3 ( 0.0,1.5,0.0 ), -vec3 ( 0.0,0.0,5.5 ), -vec3 ( 1.5,0.0,5.5 ), -vec3 ( 1.5,1.5,0.0 ), -vec3 ( 1.0,1.0,1.0 ), -vec3 ( 0.0,1.0,5.5 ), -vec3 ( 0.5,3.5,0.75 ) -);vec3 shadowDebug{X}; -#endif -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -int index{X}=-1; -#else -int index{X}=SHADOWCSMNUM_CASCADES{X}-1; -#endif -float diff{X}=0.; -#elif defined(SHADOWCUBE{X}) -uniform samplerCube shadowSampler{X}; -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DShadow shadowSampler{X}; -#else -uniform sampler2D shadowSampler{X}; -#endif -uniform mat4 lightMatrix{X}; -#endif -uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; -#endif -#ifdef SPOTLIGHT{X} -uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; -#elif defined(POINTLIGHT{X}) -uniform vec4 vLightFalloff{X}; -#elif defined(HEMILIGHT{X}) -uniform vec3 vLightGround{X}; -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; -#endif -#endif -`;ShaderStore.IncludesShadersStore.lightFragmentDeclaration=iy;let iR=`#ifdef LIGHT{X} -uniform Light{X} -{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; -#ifdef SPOTLIGHT{X} -vec4 vLightDirection;vec4 vLightFalloff; -#elif defined(POINTLIGHT{X}) -vec4 vLightFalloff; -#elif defined(HEMILIGHT{X}) -vec3 vLightGround; -#endif -vec4 shadowsInfo;vec2 depthValues;} light{X}; -#ifdef PROJECTEDLIGHTTEXTURE{X} -uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DArrayShadow shadowSampler{X}; -#else -uniform highp sampler2DArray shadowSampler{X}; -#endif -#ifdef SHADOWCSMDEBUG{X} -const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] -( -vec3 ( 1.5,0.0,0.0 ), -vec3 ( 0.0,1.5,0.0 ), -vec3 ( 0.0,0.0,5.5 ), -vec3 ( 1.5,0.0,5.5 ), -vec3 ( 1.5,1.5,0.0 ), -vec3 ( 1.0,1.0,1.0 ), -vec3 ( 0.0,1.0,5.5 ), -vec3 ( 0.5,3.5,0.75 ) -);vec3 shadowDebug{X}; -#endif -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -int index{X}=-1; -#else -int index{X}=SHADOWCSMNUM_CASCADES{X}-1; -#endif -float diff{X}=0.; -#elif defined(SHADOWCUBE{X}) -uniform samplerCube shadowSampler{X}; -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DShadow shadowSampler{X}; -#else -uniform sampler2D shadowSampler{X}; -#endif -uniform mat4 lightMatrix{X}; -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStore.lightUboDeclaration=iR;let iP=`struct lightingInfo -{vec3 diffuse; -#ifdef SPECULARTERM -vec3 specular; -#endif -#ifdef NDOTL -float ndl; -#endif -};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) -{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} -else -{lightVectorW=normalize(-lightData.xyz);} -float ndl=max(0.,dot(vNormal,lightVectorW)); -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=ndl*diffuseColor*attenuation; -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; -#endif -return result;} -lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) -{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=ndl*diffuseColor*attenuation; -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; -#endif -return result;} -result.diffuse=vec3(0.); -#ifdef SPECULARTERM -result.specular=vec3(0.); -#endif -#ifdef NDOTL -result.ndl=0.; -#endif -return result;} -lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=mix(groundColor,diffuseColor,ndl); -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; -#endif -return result;} -#define inline -vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;ShaderStore.IncludesShadersStore.lightsFragmentFunctions=iP;let iA=`#ifdef SHADOWS -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -#ifndef SHADOWFLOAT -float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} -#endif -float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) -{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} -#define inline -float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) -{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; -#ifndef SHADOWFLOAT -float shadow=unpack(textureCube(shadowSampler,directionToLight)); -#else -float shadow=textureCube(shadowSampler,directionToLight).x; -#endif -return depth>shadow ? darkness : 1.0;} -#define inline -float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) -{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); -#ifndef SHADOWFLOAT -if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} -#endif -#define inline -float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} -#define inline -float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); -#ifndef SHADOWFLOAT -if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} -#ifdef IS_NDC_HALF_ZRANGE -#define ZINCLIP clipSpace.z -#else -#define ZINCLIP uvDepth.z -#endif -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define GREATEST_LESS_THAN_ONE 0.99999994 -/* disable_uniformity_analysis */ -#define inline -float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -const vec3 PoissonSamplers32[64]=vec3[64]( -vec3(0.06407013,0.05409927,0.), -vec3(0.7366577,0.5789394,0.), -vec3(-0.6270542,-0.5320278,0.), -vec3(-0.4096107,0.8411095,0.), -vec3(0.6849564,-0.4990818,0.), -vec3(-0.874181,-0.04579735,0.), -vec3(0.9989998,0.0009880066,0.), -vec3(-0.004920578,-0.9151649,0.), -vec3(0.1805763,0.9747483,0.), -vec3(-0.2138451,0.2635818,0.), -vec3(0.109845,0.3884785,0.), -vec3(0.06876755,-0.3581074,0.), -vec3(0.374073,-0.7661266,0.), -vec3(0.3079132,-0.1216763,0.), -vec3(-0.3794335,-0.8271583,0.), -vec3(-0.203878,-0.07715034,0.), -vec3(0.5912697,0.1469799,0.), -vec3(-0.88069,0.3031784,0.), -vec3(0.5040108,0.8283722,0.), -vec3(-0.5844124,0.5494877,0.), -vec3(0.6017799,-0.1726654,0.), -vec3(-0.5554981,0.1559997,0.), -vec3(-0.3016369,-0.3900928,0.), -vec3(-0.5550632,-0.1723762,0.), -vec3(0.925029,0.2995041,0.), -vec3(-0.2473137,0.5538505,0.), -vec3(0.9183037,-0.2862392,0.), -vec3(0.2469421,0.6718712,0.), -vec3(0.3916397,-0.4328209,0.), -vec3(-0.03576927,-0.6220032,0.), -vec3(-0.04661255,0.7995201,0.), -vec3(0.4402924,0.3640312,0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.) -);const vec3 PoissonSamplers64[64]=vec3[64]( -vec3(-0.613392,0.617481,0.), -vec3(0.170019,-0.040254,0.), -vec3(-0.299417,0.791925,0.), -vec3(0.645680,0.493210,0.), -vec3(-0.651784,0.717887,0.), -vec3(0.421003,0.027070,0.), -vec3(-0.817194,-0.271096,0.), -vec3(-0.705374,-0.668203,0.), -vec3(0.977050,-0.108615,0.), -vec3(0.063326,0.142369,0.), -vec3(0.203528,0.214331,0.), -vec3(-0.667531,0.326090,0.), -vec3(-0.098422,-0.295755,0.), -vec3(-0.885922,0.215369,0.), -vec3(0.566637,0.605213,0.), -vec3(0.039766,-0.396100,0.), -vec3(0.751946,0.453352,0.), -vec3(0.078707,-0.715323,0.), -vec3(-0.075838,-0.529344,0.), -vec3(0.724479,-0.580798,0.), -vec3(0.222999,-0.215125,0.), -vec3(-0.467574,-0.405438,0.), -vec3(-0.248268,-0.814753,0.), -vec3(0.354411,-0.887570,0.), -vec3(0.175817,0.382366,0.), -vec3(0.487472,-0.063082,0.), -vec3(-0.084078,0.898312,0.), -vec3(0.488876,-0.783441,0.), -vec3(0.470016,0.217933,0.), -vec3(-0.696890,-0.549791,0.), -vec3(-0.149693,0.605762,0.), -vec3(0.034211,0.979980,0.), -vec3(0.503098,-0.308878,0.), -vec3(-0.016205,-0.872921,0.), -vec3(0.385784,-0.393902,0.), -vec3(-0.146886,-0.859249,0.), -vec3(0.643361,0.164098,0.), -vec3(0.634388,-0.049471,0.), -vec3(-0.688894,0.007843,0.), -vec3(0.464034,-0.188818,0.), -vec3(-0.440840,0.137486,0.), -vec3(0.364483,0.511704,0.), -vec3(0.034028,0.325968,0.), -vec3(0.099094,-0.308023,0.), -vec3(0.693960,-0.366253,0.), -vec3(0.678884,-0.204688,0.), -vec3(0.001801,0.780328,0.), -vec3(0.145177,-0.898984,0.), -vec3(0.062655,-0.611866,0.), -vec3(0.315226,-0.604297,0.), -vec3(-0.780145,0.486251,0.), -vec3(-0.371868,0.882138,0.), -vec3(0.200476,0.494430,0.), -vec3(-0.494552,-0.711051,0.), -vec3(0.612476,0.705252,0.), -vec3(-0.578845,-0.768792,0.), -vec3(-0.772454,-0.090976,0.), -vec3(0.504440,0.372295,0.), -vec3(0.155736,0.065157,0.), -vec3(0.391522,0.849605,0.), -vec3(-0.620106,-0.328104,0.), -vec3(0.789239,-0.419965,0.), -vec3(-0.545396,0.538133,0.), -vec3(-0.178564,-0.596057,0.) -); -#define inline -float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) -#endif -#if defined(DETAIL) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) -#endif -#if defined(BUMP) && defined(PARALLAX) -const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; icurrRayHeight) -{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} -else -{currRayHeight-=stepSize;vLastOffset=vCurrOffset; -#ifdef PARALLAX_RHS -vCurrOffset-=stepSize*vMaxOffset; -#else -vCurrOffset+=stepSize*vMaxOffset; -#endif -lastSampledHeight=currSampledHeight;}} -return vCurrOffset;} -vec2 parallaxOffset(vec3 viewDir,float heightScale) -{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; -#ifdef PARALLAX_RHS -return texCoordOffset; -#else -return -texCoordOffset; -#endif -} -#endif -`;ShaderStore.IncludesShadersStore.bumpFragmentFunctions=iF;let iw=`#ifdef CLIPPLANE -varying float fClipDistance; -#endif -#ifdef CLIPPLANE2 -varying float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -varying float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -varying float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -varying float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -varying float fClipDistance6; -#endif -`;ShaderStore.IncludesShadersStore.clipPlaneFragmentDeclaration=iw;let iL=`#ifdef LOGARITHMICDEPTH -uniform float logarithmicDepthConstant;varying float vFragmentDepth; -#endif -`;ShaderStore.IncludesShadersStore.logDepthDeclaration=iL;let iV=`#ifdef FOG -#define FOGMODE_NONE 0. -#define FOGMODE_EXP 1. -#define FOGMODE_EXP2 2. -#define FOGMODE_LINEAR 3. -#define E 2.71828 -uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() -{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) -{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} -else if (FOGMODE_EXP==vFogInfos.x) -{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} -else if (FOGMODE_EXP2==vFogInfos.x) -{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} -return clamp(fogCoeff,0.0,1.0);} -#endif -`;ShaderStore.IncludesShadersStore.fogFragmentDeclaration=iV;let iU=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -if (false) {} -#endif -#ifdef CLIPPLANE -else if (fClipDistance>0.0) -{discard;} -#endif -#ifdef CLIPPLANE2 -else if (fClipDistance2>0.0) -{discard;} -#endif -#ifdef CLIPPLANE3 -else if (fClipDistance3>0.0) -{discard;} -#endif -#ifdef CLIPPLANE4 -else if (fClipDistance4>0.0) -{discard;} -#endif -#ifdef CLIPPLANE5 -else if (fClipDistance5>0.0) -{discard;} -#endif -#ifdef CLIPPLANE6 -else if (fClipDistance6>0.0) -{discard;} -#endif -`;ShaderStore.IncludesShadersStore.clipPlaneFragment=iU;let ik=`vec2 uvOffset=vec2(0.0,0.0); -#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) -#ifdef NORMALXYSCALE -float normalScale=1.0; -#elif defined(BUMP) -float normalScale=vBumpInfos.y; -#else -float normalScale=1.0; -#endif -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#elif defined(BUMP) -vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); -#else -vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); -#endif -#elif defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#else -vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); -#endif -#endif -#ifdef PARALLAX -mat3 invTBN=transposeMat3(TBN); -#ifdef PARALLAXOCCLUSION -uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); -#else -uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); -#endif -#endif -#ifdef DETAIL -vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); -#endif -#ifdef BUMP -#ifdef OBJECTSPACE_NORMALMAP -#define CUSTOM_FRAGMENT_BUMP_FRAGMENT -normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); -#elif !defined(DETAIL) -normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); -#else -vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; -#if DETAIL_NORMALBLENDMETHOD==0 -detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); -#elif DETAIL_NORMALBLENDMETHOD==1 -detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; -#endif -normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); -#endif -#elif defined(DETAIL) -detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); -#endif -`;ShaderStore.IncludesShadersStore.bumpFragment=ik;let iG=`#ifdef DECAL -#ifdef GAMMADECAL -decalColor.rgb=toLinearSpace(decalColor.rgb); -#endif -#ifdef DECAL_SMOOTHALPHA -decalColor.a*=decalColor.a; -#endif -surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); -#endif -`;ShaderStore.IncludesShadersStore.decalFragment=iG;let iz=`#ifdef DEPTHPREPASS -gl_FragColor=vec4(0.,0.,0.,1.0);return; -#endif -`;ShaderStore.IncludesShadersStore.depthPrePass=iz;let iW=`#ifdef LIGHT{X} -#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) -#else -#ifdef PBR -#ifdef SPOTLIGHT{X} -preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(POINTLIGHT{X}) -preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(HEMILIGHT{X}) -preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(DIRLIGHT{X}) -preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#endif -preInfo.NdotV=NdotV; -#ifdef SPOTLIGHT{X} -#ifdef LIGHT_FALLOFF_GLTF{X} -preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); -#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) -preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); -#elif defined(LIGHT_FALLOFF_STANDARD{X}) -preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); -#else -preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); -#endif -#elif defined(POINTLIGHT{X}) -#ifdef LIGHT_FALLOFF_GLTF{X} -preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); -#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) -preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); -#elif defined(LIGHT_FALLOFF_STANDARD{X}) -preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); -#else -preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); -#endif -#else -preInfo.attenuation=1.0; -#endif -#ifdef HEMILIGHT{X} -preInfo.roughness=roughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#ifdef IRIDESCENCE -preInfo.iridescenceIntensity=iridescenceIntensity; -#endif -#ifdef HEMILIGHT{X} -info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); -#elif defined(SS_TRANSLUCENCY) -info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); -#else -info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); -#endif -#ifdef SPECULARTERM -#ifdef ANISOTROPIC -info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#else -info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#endif -#ifdef SHEEN -#ifdef SHEEN_LINKWITHALBEDO -preInfo.roughness=sheenOut.sheenIntensity; -#else -#ifdef HEMILIGHT{X} -preInfo.roughness=sheenOut.sheenRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#endif -info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#ifdef CLEARCOAT -#ifdef HEMILIGHT{X} -preInfo.roughness=clearcoatOut.clearCoatRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); -#ifdef CLEARCOAT_TINT -absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; -#ifdef SPECULARTERM -info.specular*=absorption; -#endif -#endif -info.diffuse*=info.clearCoat.w; -#ifdef SPECULARTERM -info.specular*=info.clearCoat.w; -#endif -#ifdef SHEEN -info.sheen*=info.clearCoat.w; -#endif -#endif -#else -#ifdef SPOTLIGHT{X} -info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#elif defined(HEMILIGHT{X}) -info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); -#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) -info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#endif -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); -#endif -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -for (int i=0; i=0.) {index{X}=i;break;}} -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -if (index{X}>=0) -#endif -{ -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; -#endif -#ifndef SHADOWCSMNOBLEND{X} -float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) -{index{X}+=1;float nextShadow=0.; -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -shadow=mix(nextShadow,shadow,diffRatio); -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); -#endif -} -#endif -} -#elif defined(SHADOWCLOSEESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); -#else -shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); -#else -shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPOISSON{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); -#else -shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#else -#if defined(SHADOWCUBE{X}) -shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); -#else -shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#endif -#ifdef SHADOWONLY -#ifndef SHADOWINUSE -#define SHADOWINUSE -#endif -globalShadow+=shadow;shadowLightCount+=1.0; -#endif -#else -shadow=1.; -#endif -aggShadow+=shadow;numLights+=1.0; -#ifndef SHADOWONLY -#ifdef CUSTOMUSERLIGHTING -diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); -#ifdef SPECULARTERM -specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); -#endif -#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) -diffuseBase+=lightmapColor.rgb*shadow; -#ifdef SPECULARTERM -#ifndef LIGHTMAPNOSPECULAR{X} -specularBase+=info.specular*shadow*lightmapColor.rgb; -#endif -#endif -#ifdef CLEARCOAT -#ifndef LIGHTMAPNOSPECULAR{X} -clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; -#endif -#endif -#ifdef SHEEN -#ifndef LIGHTMAPNOSPECULAR{X} -sheenBase+=info.sheen.rgb*shadow; -#endif -#endif -#else -#ifdef SHADOWCSMDEBUG{X} -diffuseBase+=info.diffuse*shadowDebug{X}; -#else -diffuseBase+=info.diffuse*shadow; -#endif -#ifdef SPECULARTERM -specularBase+=info.specular*shadow; -#endif -#ifdef CLEARCOAT -clearCoatBase+=info.clearCoat.rgb*shadow; -#endif -#ifdef SHEEN -sheenBase+=info.sheen.rgb*shadow; -#endif -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStore.lightFragment=iW;let iH=`#ifdef LOGARITHMICDEPTH -gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; -#endif -`;ShaderStore.IncludesShadersStore.logDepthFragment=iH;let iX=`#ifdef FOG -float fog=CalcFogFactor(); -#ifdef PBR -fog=toLinearSpace(fog); -#endif -color.rgb=mix(vFogColor,color.rgb,fog); -#endif -`;ShaderStore.IncludesShadersStore.fogFragment=iX;let iY=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY -float fragDepth=gl_FragCoord.z; -#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS -uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; -#endif -ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); -#ifdef USE_REVERSE_DEPTHBUFFER -float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; -#else -float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; -#endif -float alphaMultiplier=1.0-lastFrontColor.a; -#ifdef USE_REVERSE_DEPTHBUFFER -if (fragDepth>nearestDepth || fragDepthfurthestDepth) { -#endif -return;} -#ifdef USE_REVERSE_DEPTHBUFFER -if (fragDepthfurthestDepth) { -#else -if (fragDepth>nearestDepth && fragDepth -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -#include[SCENE_MRT_COUNT] -#include -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include[1..7] -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include -#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) -#ifdef REFRACTION -#ifdef REFRACTIONMAP_3D -uniform samplerCube refractionCubeSampler; -#else -uniform sampler2D refraction2DSampler; -#endif -#endif -#if defined(SPECULARTERM) -#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) -#endif -#include -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -uniform samplerCube reflectionCubeSampler; -#else -uniform sampler2D reflection2DSampler; -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); -#endif -#include -#ifdef TWOSIDEDLIGHTING -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -#ifdef DIFFUSE -baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); -#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) -if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) -#endif -#include -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -baseColor.rgb*=vColor.rgb; -#endif -#ifdef DETAIL -baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); -#endif -#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) -#endif -#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE -vec3 baseAmbientColor=vec3(1.,1.,1.); -#ifdef AMBIENT -baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; -#endif -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS -#ifdef SPECULARTERM -float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; -#ifdef SPECULAR -vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; -#ifdef GLOSSINESS -glossiness=glossiness*specularMapColor.a; -#endif -#endif -#else -float glossiness=0.; -#endif -vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; -#ifdef SPECULARTERM -vec3 specularBase=vec3(0.,0.,0.); -#endif -float shadow=1.;float aggShadow=0.;float numLights=0.; -#ifdef LIGHTMAP -vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); -#ifdef RGBDLIGHTMAP -lightmapColor.rgb=fromRGBD(lightmapColor); -#endif -lightmapColor.rgb*=vLightmapInfos.y; -#endif -#include[0..maxSimultaneousLights] -aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); -#ifdef REFRACTION -vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); -#ifdef REFRACTIONMAP_3D -#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC -refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); -#endif -refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} -#else -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); -#endif -#ifdef RGBDREFRACTION -refractionColor.rgb=fromRGBD(refractionColor); -#endif -#ifdef IS_REFRACTION_LINEAR -refractionColor.rgb=toGammaSpace(refractionColor.rgb); -#endif -refractionColor.rgb*=vRefractionInfos.x; -#endif -vec4 reflectionColor=vec4(0.,0.,0.,1.); -#ifdef REFLECTION -vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -vReflectionUVW.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -#ifdef ROUGHNESS -float bias=vReflectionInfos.y; -#ifdef SPECULARTERM -#ifdef SPECULAR -#ifdef GLOSSINESS -bias*=(1.0-specularMapColor.a); -#endif -#endif -#endif -reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); -#else -reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); -#endif -#else -vec2 coords=vReflectionUVW.xy; -#ifdef REFLECTIONMAP_PROJECTION -coords/=vReflectionUVW.z; -#endif -coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); -#endif -#ifdef RGBDREFLECTION -reflectionColor.rgb=fromRGBD(reflectionColor); -#endif -#ifdef IS_REFLECTION_LINEAR -reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); -#endif -reflectionColor.rgb*=vReflectionInfos.x; -#ifdef REFLECTIONFRESNEL -float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); -#ifdef REFLECTIONFRESNELFROMSPECULAR -#ifdef SPECULARTERM -reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#else -reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#endif -#else -reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#endif -#endif -#endif -#ifdef REFRACTIONFRESNEL -float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#ifdef OPACITYRGB -opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; -#else -alpha*=opacityMap.a*vOpacityInfos.y; -#endif -#endif -#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) -alpha*=vColor.a; -#endif -#ifdef OPACITYFRESNEL -float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; -#endif -#ifdef ALPHATEST -#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS -if (alpha -#include -#ifdef IMAGEPROCESSINGPOSTPROCESS -color.rgb=toLinearSpace(color.rgb); -#else -#ifdef IMAGEPROCESSING -color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); -#endif -#endif -color.a*=visibility; -#ifdef PREMULTIPLYALPHA -color.rgb*=color.a; -#endif -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); -#endif -#ifdef PREPASS_VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_IRRADIANCE -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_DEPTH -gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_NORMAL -#ifdef PREPASS_NORMAL_WORLDSPACE -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); -#else -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); -#endif -#endif -#ifdef PREPASS_ALBEDO_SQRT -gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_REFLECTIVITY -#if defined(SPECULARTERM) -#if defined(SPECULAR) -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; -#endif -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=color; -#endif -#include -#if ORDER_INDEPENDENT_TRANSPARENCY -if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} -#endif -#define CUSTOM_FRAGMENT_MAIN_END -} -`;ShaderStore.ShadersStore.defaultPixelShader=ij;let iK=`#ifdef DECAL -uniform vec4 vDecalInfos;uniform mat4 decalMatrix; -#endif -`;ShaderStore.IncludesShadersStore.decalVertexDeclaration=iK;let iq=`uniform mat4 viewProjection;uniform mat4 view; -#ifdef DIFFUSE -uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; -#endif -#ifdef AMBIENT -uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; -#endif -#ifdef OPACITY -uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; -#endif -#ifdef REFLECTION -uniform mat4 reflectionMatrix; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos;uniform mat4 detailMatrix; -#endif -#include -#define ADDITIONAL_VERTEX_DECLARATION -`;ShaderStore.IncludesShadersStore.defaultVertexDeclaration=iq;let i$=`#ifdef UV{X} -attribute vec2 uv{X}; -#endif -`;ShaderStore.IncludesShadersStore.uvAttributeDeclaration=i$;let iQ=`#if NUM_BONE_INFLUENCERS>0 -attribute vec4 matricesIndices;attribute vec4 matricesWeights; -#if NUM_BONE_INFLUENCERS>4 -attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; -#endif -#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#ifdef BONETEXTURE -uniform highp sampler2D boneSampler;uniform float boneTextureWidth; -#else -uniform mat4 mBones[BonesPerMesh]; -#ifdef BONES_VELOCITY_ENABLED -uniform mat4 mPreviousBones[BonesPerMesh]; -#endif -#endif -#ifdef BONETEXTURE -#define inline -mat4 readMatrixFromRawSampler(sampler2D smp,float index) -{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStore.bonesDeclaration=iQ;let iZ=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; -#ifdef INSTANCES -attribute vec4 bakedVertexAnimationSettingsInstanced; -#endif -#define inline -mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) -{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} -#endif -`;ShaderStore.IncludesShadersStore.bakedVertexAnimationDeclaration=iZ;let iJ=`#ifdef INSTANCES -attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; -#ifdef INSTANCESCOLOR -attribute vec4 instanceColor; -#endif -#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) -uniform mat4 world; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; -#ifdef THIN_INSTANCES -uniform mat4 previousWorld; -#endif -#endif -#else -#if !defined(WORLD_UBO) -uniform mat4 world; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -uniform mat4 previousWorld; -#endif -#endif -`;ShaderStore.IncludesShadersStore.instancesDeclaration=iJ;let i0=`#ifdef PREPASS -#ifdef PREPASS_DEPTH -varying vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#endif -`;ShaderStore.IncludesShadersStore.prePassVertexDeclaration=i0;let i1=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 -varying vec2 v_VARYINGNAME_UV; -#endif -`;ShaderStore.IncludesShadersStore.samplerVertexDeclaration=i1;let i2=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -varying mat3 vTBN; -#endif -#endif -`;ShaderStore.IncludesShadersStore.bumpVertexDeclaration=i2;let i3=`#ifdef CLIPPLANE -uniform vec4 vClipPlane;varying float fClipDistance; -#endif -#ifdef CLIPPLANE2 -uniform vec4 vClipPlane2;varying float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -uniform vec4 vClipPlane3;varying float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -uniform vec4 vClipPlane4;varying float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -uniform vec4 vClipPlane5;varying float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -uniform vec4 vClipPlane6;varying float fClipDistance6; -#endif -`;ShaderStore.IncludesShadersStore.clipPlaneVertexDeclaration=i3;let i4=`#ifdef FOG -varying vec3 vFogDistance; -#endif -`;ShaderStore.IncludesShadersStore.fogVertexDeclaration=i4;let i5=`#ifdef LIGHT{X} -uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; -#ifdef SPECULARTERM -uniform vec4 vLightSpecular{X}; -#else -vec4 vLightSpecular{X}=vec4(0.); -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#elif defined(SHADOWCUBE{X}) -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; -#endif -uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; -#endif -#ifdef SPOTLIGHT{X} -uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; -#elif defined(POINTLIGHT{X}) -uniform vec4 vLightFalloff{X}; -#elif defined(HEMILIGHT{X}) -uniform vec3 vLightGround{X}; -#endif -#endif -`;ShaderStore.IncludesShadersStore.lightVxFragmentDeclaration=i5;let i6=`#ifdef LIGHT{X} -uniform Light{X} -{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; -#ifdef SPOTLIGHT{X} -vec4 vLightDirection;vec4 vLightFalloff; -#elif defined(POINTLIGHT{X}) -vec4 vLightFalloff; -#elif defined(HEMILIGHT{X}) -vec3 vLightGround; -#endif -vec4 shadowsInfo;vec2 depthValues;} light{X}; -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#elif defined(SHADOWCUBE{X}) -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStore.lightVxUboDeclaration=i6;let i8=`#ifdef MORPHTARGETS -uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; -#ifdef MORPHTARGETS_TEXTURE -uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) -{ -float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} -#endif -#endif -`;ShaderStore.IncludesShadersStore.morphTargetsVertexGlobalDeclaration=i8;let i7=`#ifdef MORPHTARGETS -#ifndef MORPHTARGETS_TEXTURE -attribute vec3 position{X}; -#ifdef MORPHTARGETS_NORMAL -attribute vec3 normal{X}; -#endif -#ifdef MORPHTARGETS_TANGENT -attribute vec3 tangent{X}; -#endif -#ifdef MORPHTARGETS_UV -attribute vec2 uv_{X}; -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStore.morphTargetsVertexDeclaration=i7;let i9=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -float vertexID; -#endif -#endif -`;ShaderStore.IncludesShadersStore.morphTargetsVertexGlobal=i9;let re=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; -#endif -#else -positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStore.morphTargetsVertex=re;let rt=`#ifdef INSTANCES -mat4 finalWorld=mat4(world0,world1,world2,world3); -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); -#endif -#ifdef THIN_INSTANCES -finalWorld=world*finalWorld; -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -finalPreviousWorld=previousWorld*finalPreviousWorld; -#endif -#endif -#else -mat4 finalWorld=world; -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -mat4 finalPreviousWorld=previousWorld; -#endif -#endif -`;ShaderStore.IncludesShadersStore.instancesVertex=rt;let ri=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#if NUM_BONE_INFLUENCERS>0 -mat4 influence; -#ifdef BONETEXTURE -influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; -#endif -#else -influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -#endif -finalWorld=finalWorld*influence; -#endif -#endif -`;ShaderStore.IncludesShadersStore.bonesVertex=ri;let rr=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -{ -#ifdef INSTANCES -#define BVASNAME bakedVertexAnimationSettingsInstanced -#else -#define BVASNAME bakedVertexAnimationSettings -#endif -float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; -#endif -finalWorld=finalWorld*VATInfluence;} -#endif -`;ShaderStore.IncludesShadersStore.bakedVertexAnimation=rr;let rs=`#ifdef PREPASS_DEPTH -vViewPos=(view*worldPos).rgb; -#endif -#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*worldPos; -#if NUM_BONE_INFLUENCERS>0 -mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#endif -`;ShaderStore.IncludesShadersStore.prePassVertex=rs;let ra=`#if !defined(UV{X}) && defined(MAINUV{X}) -vec2 uv{X}=vec2(0.,0.); -#endif -#ifdef MAINUV{X} -vMainUV{X}=uv{X}; -#endif -`;ShaderStore.IncludesShadersStore.uvVariableDeclaration=ra;let rn=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 -if (v_INFONAME_==0.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} -#ifdef UV2 -else if (v_INFONAME_==1.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} -#endif -#ifdef UV3 -else if (v_INFONAME_==2.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} -#endif -#ifdef UV4 -else if (v_INFONAME_==3.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} -#endif -#ifdef UV5 -else if (v_INFONAME_==4.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} -#endif -#ifdef UV6 -else if (v_INFONAME_==5.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} -#endif -#endif -`;ShaderStore.IncludesShadersStore.samplerVertexImplementation=rn;let ro=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); -#endif -#endif -`;ShaderStore.IncludesShadersStore.bumpVertex=ro;let rl=`#ifdef CLIPPLANE -fClipDistance=dot(worldPos,vClipPlane); -#endif -#ifdef CLIPPLANE2 -fClipDistance2=dot(worldPos,vClipPlane2); -#endif -#ifdef CLIPPLANE3 -fClipDistance3=dot(worldPos,vClipPlane3); -#endif -#ifdef CLIPPLANE4 -fClipDistance4=dot(worldPos,vClipPlane4); -#endif -#ifdef CLIPPLANE5 -fClipDistance5=dot(worldPos,vClipPlane5); -#endif -#ifdef CLIPPLANE6 -fClipDistance6=dot(worldPos,vClipPlane6); -#endif -`;ShaderStore.IncludesShadersStore.clipPlaneVertex=rl;let rh=`#ifdef FOG -vFogDistance=(view*worldPos).xyz; -#endif -`;ShaderStore.IncludesShadersStore.fogVertex=rh;let rc=`#ifdef SHADOWS -#if defined(SHADOWCSM{X}) -vPositionFromCamera{X}=view*worldPos;for (int i=0; i -#define CUSTOM_VERTEX_BEGIN -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#ifdef TANGENT -attribute vec4 tangent; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#include[2..7] -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include -#include -#include -#include -#include[1..7] -#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) -#if defined(SPECULARTERM) -#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) -#endif -#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include -#include -#include -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -vPositionW=vec3(worldPos); -#include -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#include[2..7] -#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) -#if defined(SPECULARTERM) -#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) -#endif -#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) -#include -#include -#include -#include[0..maxSimultaneousLights] -#include -#include -#include -#define CUSTOM_VERTEX_MAIN_END -} -`;ShaderStore.ShadersStore.defaultVertexShader=rp;let rf=RegExp("^([gimus]+)!");let MaterialPluginManager=class MaterialPluginManager{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;tthis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort((e,t)=>e.priority-t.priority),this._codeInjectionPoints={};let i={};for(let e of(i[MaterialPluginManager._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0},this._plugins))e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!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;t0&&t.uniforms.push(...this._uniformList),this._samplerList.length>0&&t.samplers.push(...this._samplerList),this._uboList.length>0&&t.uniformBuffersNames.push(...this._uboList),t.customCode=this._injectCustomCode(t,t.customCode);break;case ec.PrepareUniformBuffer:for(let e of(this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[],this._plugins)){let r=e.getUniforms();if(r){if(r.ubo)for(let e of r.ubo){if(e.size&&e.type){let r=null!==(i=e.arraySize)&&void 0!==i?i:0;t.ubo.addUniform(e.name,e.size,r),this._uboDeclaration+=`${e.type} ${e.name}${r>0?`[${r}]`:""}; -`}this._uniformList.push(e.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}e.getSamplers(this._samplerList),e.getUniformBuffersNames(this._uboList)}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var s,a;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let n=null===(s=this._codeInjectionPoints)||void 0===s?void 0:s[i];if(!n)return r;let o=null;for(let t in n){let s="";for(let r of this._activePlugins){let n=null===(a=r.getCustomCode(i))||void 0===a?void 0:a[t];if(n){if(r.resolveIncludes){if(null===o){let t=q.GLSL;o={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:ShaderStore.GetShadersRepository(t),includesShadersStore:ShaderStore.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}o.isFragment="fragment"===i,ShaderProcessor._ProcessIncludes(n,o,e=>n=e)}s+=n+"\n"}}if(s.length>0){if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{let i=rf.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}0>e.indexOf("g")&&(e+="g");let i=r,a=new RegExp(t,e),n=a.exec(i);for(;null!==n;){let e=s;for(let t=0;t{UnregisterAllMaterialPlugins()});let rm=[],rg=null;function UnregisterAllMaterialPlugins(){rm.length=0,material_Material.OnEventObservable.remove(rg),rg=null}let MaterialPluginBase=class MaterialPluginBase{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,a=!1,n=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=n,e.pluginManager||(e.pluginManager=new MaterialPluginManager(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),a&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;let i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){decorators_SerializationHelper.Clone(()=>e,this)}serialize(){return decorators_SerializationHelper.Serialize(this)}parse(e,t,i){decorators_SerializationHelper.Parse(()=>this,e,t,i)}};__decorate([serialize()],MaterialPluginBase.prototype,"name",void 0),__decorate([serialize()],MaterialPluginBase.prototype,"priority",void 0),__decorate([serialize()],MaterialPluginBase.prototype,"resolveIncludes",void 0),__decorate([serialize()],MaterialPluginBase.prototype,"registerForExtraEvents",void 0);let MaterialDetailMapDefines=class MaterialDetailMapDefines extends MaterialDefines{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}};let material_detailMapConfiguration_DetailMapConfiguration=class material_detailMapConfiguration_DetailMapConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new MaterialDetailMapDefines,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=material_Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||!i.getCaps().standardDerivatives||!this._texture||!MaterialFlags.DetailTextureEnabled||!!this._texture.isReady()}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&MaterialFlags.DetailTextureEnabled&&this._isEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||!this._texture||!MaterialFlags.DetailTextureEnabled||(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),MaterialHelper.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&MaterialFlags.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){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}};__decorate([serializeAsTexture("detailTexture"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"texture",void 0),__decorate([serialize()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"diffuseBlendLevel",void 0),__decorate([serialize()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"roughnessBlendLevel",void 0),__decorate([serialize()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"bumpLevel",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"normalBlendMethod",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"isEnabled",void 0);let rv={effect:null,subMesh:null};let StandardMaterialDefines=class StandardMaterialDefines extends MaterialDefines{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_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.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!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.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,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_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){for(let t of["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"])this[t]=t===e}};let standardMaterial_StandardMaterial=class standardMaterial_StandardMaterial extends PushMaterial{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}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}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new math_color_Color3(0,0,0),this.diffuseColor=new math_color_Color3(1,1,1),this.specularColor=new math_color_Color3(1,1,1),this.emissiveColor=new math_color_Color3(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new SmartArray(16),this._worldViewProjectionMatrix=math_vector_Matrix.Zero(),this._globalAmbientColor=new math_color_Color3(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new material_detailMapConfiguration_DetailMapConfiguration(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new PrePassConfiguration,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),standardMaterial_StandardMaterial.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),standardMaterial_StandardMaterial.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!standardMaterial_StandardMaterial.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||!!standardMaterial_StandardMaterial.RefractionTextureEnabled&&!!this._refractionTexture&&!!this._refractionTexture.isRenderTarget||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===material_Material.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==material_Material.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(ec.GetDefineNames,this._eventInfo),t.materialDefines=new StandardMaterialDefines(this._eventInfo.defineNames));let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=r.getEngine();s._needNormals=MaterialHelper.PrepareDefinesForLights(r,e,s,!0,this._maxSimultaneousLights,this._disableLighting),MaterialHelper.PrepareDefinesForMultiview(r,s);let n=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(MaterialHelper.PrepareDefinesForPrePass(r,s,this.canRenderToMRT&&!n),MaterialHelper.PrepareDefinesForOIT(r,s,n),s._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s._needUVs=!1;for(let e=1;e<=6;++e)s["MAINUV"+e]=!1;if(r.texturesEnabled){if(s.DIFFUSEDIRECTUV=0,s.BUMPDIRECTUV=0,s.AMBIENTDIRECTUV=0,s.OPACITYDIRECTUV=0,s.EMISSIVEDIRECTUV=0,s.SPECULARDIRECTUV=0,s.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===texture_Texture.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,s.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case texture_Texture.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case texture_Texture.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case texture_Texture.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case texture_Texture.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case texture_Texture.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case texture_Texture.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case texture_Texture.CUBIC_MODE:case texture_Texture.INVCUBIC_MODE:default:s.setReflectionMode("REFLECTIONMAP_CUBIC")}s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else s.REFLECTION=!1,s.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&standardMaterial_StandardMaterial.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAX_RHS=r.useRightHandedSystem,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAX_RHS=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube,s.RGBDREFRACTION=this._refractionTexture.isRGBD,s.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha,s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,s.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}s._areFresnelDirty&&(standardMaterial_StandardMaterial.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),MaterialHelper.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s,this._applyDecalMapAfterDetailMap),MaterialHelper.PrepareDefinesForFrameBoundValues(r,a,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),MaterialHelper.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(s.isDirty){let i=s._areLightsDisposed;s.markAsProcessed();let n=new EffectFallbacks;s.REFLECTION&&n.addFallback(0,"REFLECTION"),s.SPECULAR&&n.addFallback(0,"SPECULAR"),s.BUMP&&n.addFallback(0,"BUMP"),s.PARALLAX&&n.addFallback(1,"PARALLAX"),s.PARALLAX_RHS&&n.addFallback(1,"PARALLAX_RHS"),s.PARALLAXOCCLUSION&&n.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&n.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&n.addFallback(1,"FOG"),s.POINTSIZE&&n.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&n.addFallback(0,"LOGARITHMICDEPTH"),MaterialHelper.HandleFallbacksForShadows(s,n,this._maxSimultaneousLights),s.SPECULARTERM&&n.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&n.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&n.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&n.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&n.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&n.addFallback(4,"FRESNEL"),s.MULTIVIEW&&n.addFallback(0,"MULTIVIEW");let l=[buffer_VertexBuffer.PositionKind];s.NORMAL&&l.push(buffer_VertexBuffer.NormalKind),s.TANGENT&&l.push(buffer_VertexBuffer.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(buffer_VertexBuffer.ColorKind),MaterialHelper.PrepareAttributesForBones(l,e,s,n),MaterialHelper.PrepareAttributesForInstances(l,s),MaterialHelper.PrepareAttributesForMorphTargets(l,e,s),MaterialHelper.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default",c=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],u=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],_={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=n,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=c,this._eventInfo.attributes=l,this._eventInfo.samplers=u,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=_,this._callbackPluginEventGeneric(ec.PrepareEffect,this._eventInfo),PrePassConfiguration.AddUniforms(c),PrePassConfiguration.AddSamplers(u),ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(c,s),ImageProcessingConfiguration.PrepareSamplers(u,s)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),addClipPlaneUniforms(c);let p={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,c,d,u,s,l,p));let f=s.toString(),m=t.effect,g=r.getEngine().createEffect(h,{attributes:l,uniformsNames:c,uniformBuffersNames:d,samplers:u,defines:f,fallbacks:n,onCompiled:this.onCompiled,onError:this.onError,indexParameters:_,processFinalCode:p.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},a);if(this._eventInfo.customCode=void 0,g){if(this._onEffectCreatedObservable&&(rv.effect=g,rv.subMesh=t,this._onEffectCreatedObservable.notifyObservers(rv)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,s.markAsUnprocessed(),o=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var r;let s=this.getScene(),a=i.materialDefines;if(!a)return;let n=i.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),a.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let o=n._forceRebindOnNextCall||this._mustRebind(s,n,t.visibility);MaterialHelper.BindBonesParameters(t,n);let l=this._uniformBuffer;if(o){if(this.bindViewProjection(n),!l.useUbo||!this.isFrozen||!l.isSync||n._forceRebindOnNextCall){if(standardMaterial_StandardMaterial.FresnelEnabled&&a.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new math_color_Color3(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),MaterialHelper.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),MaterialHelper.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),MaterialHelper.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){let e=this._reflectionTexture;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),MaterialHelper.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),MaterialHelper.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),MaterialHelper.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&standardMaterial_StandardMaterial.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),MaterialHelper.BindTextureMatrix(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled){let e=1;if(!this._refractionTexture.isCube&&(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let e=this._refractionTexture;l.updateVector3("vRefractionPosition",e.boundingBoxPosition),l.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),a.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",standardMaterial_StandardMaterial.EmissiveTextureEnabled?this.emissiveColor:math_color_Color3.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled&&n.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled&&n.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled&&n.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?n.setTexture("reflectionCubeSampler",this._reflectionTexture):n.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled&&n.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled&&n.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled&&n.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&standardMaterial_StandardMaterial.BumpTextureEnabled&&n.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled&&(this._refractionTexture.isCube?n.setTexture("refractionCubeSampler",this._refractionTexture):n.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),bindClipPlane(n,this,s),this.bindEyePosition(n)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&MaterialHelper.BindLights(s,t,n,a,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==scene_Scene.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||a.PREPASS)&&this.bindView(n),MaterialHelper.BindFogParameters(s,t,n),a.NUM_MORPH_INFLUENCERS&&MaterialHelper.BindMorphTargetParameters(t,n),a.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(r=t.bakedVertexAnimationManager)||void 0===r||r.bind(n,a.INSTANCES)),this.useLogarithmicDepth&&MaterialHelper.BindLogDepth(a,n,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),l.update()}getAnimatables(){let e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),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._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),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._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){let e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),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._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){var i,r,s,a,n,o,l,h,c;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(a=this._reflectionTexture)||void 0===a||a.dispose(),null===(n=this._emissiveTexture)||void 0===n||n.dispose(),null===(o=this._specularTexture)||void 0===o||o.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(c=this._refractionTexture)||void 0===c||c.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=decorators_SerializationHelper.Clone(()=>new standardMaterial_StandardMaterial(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new standardMaterial_StandardMaterial(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),material_Material._parsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return MaterialFlags.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){MaterialFlags.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return MaterialFlags.DetailTextureEnabled}static set DetailTextureEnabled(e){MaterialFlags.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return MaterialFlags.AmbientTextureEnabled}static set AmbientTextureEnabled(e){MaterialFlags.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return MaterialFlags.OpacityTextureEnabled}static set OpacityTextureEnabled(e){MaterialFlags.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return MaterialFlags.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){MaterialFlags.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return MaterialFlags.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){MaterialFlags.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return MaterialFlags.SpecularTextureEnabled}static set SpecularTextureEnabled(e){MaterialFlags.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return MaterialFlags.BumpTextureEnabled}static set BumpTextureEnabled(e){MaterialFlags.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return MaterialFlags.LightmapTextureEnabled}static set LightmapTextureEnabled(e){MaterialFlags.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return MaterialFlags.RefractionTextureEnabled}static set RefractionTextureEnabled(e){MaterialFlags.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return MaterialFlags.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){MaterialFlags.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return MaterialFlags.FresnelEnabled}static set FresnelEnabled(e){MaterialFlags.FresnelEnabled=e}};__decorate([serializeAsTexture("diffuseTexture")],standardMaterial_StandardMaterial.prototype,"_diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"diffuseTexture",void 0),__decorate([serializeAsTexture("ambientTexture")],standardMaterial_StandardMaterial.prototype,"_ambientTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"ambientTexture",void 0),__decorate([serializeAsTexture("opacityTexture")],standardMaterial_StandardMaterial.prototype,"_opacityTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"opacityTexture",void 0),__decorate([serializeAsTexture("reflectionTexture")],standardMaterial_StandardMaterial.prototype,"_reflectionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"reflectionTexture",void 0),__decorate([serializeAsTexture("emissiveTexture")],standardMaterial_StandardMaterial.prototype,"_emissiveTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"emissiveTexture",void 0),__decorate([serializeAsTexture("specularTexture")],standardMaterial_StandardMaterial.prototype,"_specularTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"specularTexture",void 0),__decorate([serializeAsTexture("bumpTexture")],standardMaterial_StandardMaterial.prototype,"_bumpTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"bumpTexture",void 0),__decorate([serializeAsTexture("lightmapTexture")],standardMaterial_StandardMaterial.prototype,"_lightmapTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"lightmapTexture",void 0),__decorate([serializeAsTexture("refractionTexture")],standardMaterial_StandardMaterial.prototype,"_refractionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"refractionTexture",void 0),__decorate([serializeAsColor3("ambient")],standardMaterial_StandardMaterial.prototype,"ambientColor",void 0),__decorate([serializeAsColor3("diffuse")],standardMaterial_StandardMaterial.prototype,"diffuseColor",void 0),__decorate([serializeAsColor3("specular")],standardMaterial_StandardMaterial.prototype,"specularColor",void 0),__decorate([serializeAsColor3("emissive")],standardMaterial_StandardMaterial.prototype,"emissiveColor",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"specularPower",void 0),__decorate([serialize("useAlphaFromDiffuseTexture")],standardMaterial_StandardMaterial.prototype,"_useAlphaFromDiffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"useAlphaFromDiffuseTexture",void 0),__decorate([serialize("useEmissiveAsIllumination")],standardMaterial_StandardMaterial.prototype,"_useEmissiveAsIllumination",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useEmissiveAsIllumination",void 0),__decorate([serialize("linkEmissiveWithDiffuse")],standardMaterial_StandardMaterial.prototype,"_linkEmissiveWithDiffuse",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"linkEmissiveWithDiffuse",void 0),__decorate([serialize("useSpecularOverAlpha")],standardMaterial_StandardMaterial.prototype,"_useSpecularOverAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useSpecularOverAlpha",void 0),__decorate([serialize("useReflectionOverAlpha")],standardMaterial_StandardMaterial.prototype,"_useReflectionOverAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useReflectionOverAlpha",void 0),__decorate([serialize("disableLighting")],standardMaterial_StandardMaterial.prototype,"_disableLighting",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],standardMaterial_StandardMaterial.prototype,"disableLighting",void 0),__decorate([serialize("useObjectSpaceNormalMap")],standardMaterial_StandardMaterial.prototype,"_useObjectSpaceNormalMap",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useObjectSpaceNormalMap",void 0),__decorate([serialize("useParallax")],standardMaterial_StandardMaterial.prototype,"_useParallax",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useParallax",void 0),__decorate([serialize("useParallaxOcclusion")],standardMaterial_StandardMaterial.prototype,"_useParallaxOcclusion",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useParallaxOcclusion",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"parallaxScaleBias",void 0),__decorate([serialize("roughness")],standardMaterial_StandardMaterial.prototype,"_roughness",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"roughness",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"indexOfRefraction",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"invertRefractionY",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"alphaCutOff",void 0),__decorate([serialize("useLightmapAsShadowmap")],standardMaterial_StandardMaterial.prototype,"_useLightmapAsShadowmap",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useLightmapAsShadowmap",void 0),__decorate([serializeAsFresnelParameters("diffuseFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_diffuseFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"diffuseFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("opacityFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_opacityFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"opacityFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("reflectionFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_reflectionFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"reflectionFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("refractionFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_refractionFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"refractionFresnelParameters",void 0),__decorate([serializeAsFresnelParameters("emissiveFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_emissiveFresnelParameters",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"emissiveFresnelParameters",void 0),__decorate([serialize("useReflectionFresnelFromSpecular")],standardMaterial_StandardMaterial.prototype,"_useReflectionFresnelFromSpecular",void 0),__decorate([expandToProperty("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"useReflectionFresnelFromSpecular",void 0),__decorate([serialize("useGlossinessFromSpecularMapAlpha")],standardMaterial_StandardMaterial.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useGlossinessFromSpecularMapAlpha",void 0),__decorate([serialize("maxSimultaneousLights")],standardMaterial_StandardMaterial.prototype,"_maxSimultaneousLights",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],standardMaterial_StandardMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize("invertNormalMapX")],standardMaterial_StandardMaterial.prototype,"_invertNormalMapX",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"invertNormalMapX",void 0),__decorate([serialize("invertNormalMapY")],standardMaterial_StandardMaterial.prototype,"_invertNormalMapY",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"invertNormalMapY",void 0),__decorate([serialize("twoSidedLighting")],standardMaterial_StandardMaterial.prototype,"_twoSidedLighting",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"twoSidedLighting",void 0),__decorate([serialize("applyDecalMapAfterDetailMap")],standardMaterial_StandardMaterial.prototype,"_applyDecalMapAfterDetailMap",void 0),__decorate([expandToProperty("_markAllSubMeshesAsMiscDirty")],standardMaterial_StandardMaterial.prototype,"applyDecalMapAfterDetailMap",void 0),__decorate([serialize()],standardMaterial_StandardMaterial.prototype,"useLogarithmicDepth",null),h["BABYLON.StandardMaterial"]=standardMaterial_StandardMaterial,scene_Scene.DefaultMaterialFactory=e=>new standardMaterial_StandardMaterial("default material",e),ThinEngine.prototype.createDynamicTexture=function(e,t,i,r){let s=new internalTexture_InternalTexture(this,$.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?ThinEngine.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?ThinEngine.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},ThinEngine.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,a=!1,n=!1){if(!e)return;let o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,a);this._unpackFlipY(void 0===i?e.invertY:i),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,u);o.texImage2D(l,0,d,u,c,t),e.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0};let DynamicTexture=class DynamicTexture extends texture_Texture{constructor(e,t,i=null,r=!1,s=3,a=5,n){super(null,i,!r,n,s,void 0,void 0,void 0,void 0,a),this.name=e,this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let o=this._getEngine();if(!o)return;t.getContext?(this._canvas=t,this._texture=o.createDynamicTexture(t.width,t.height,r,s)):(this._canvas=o.createCanvas(1,1),t.width||0===t.width?this._texture=o.createDynamicTexture(t.width,t.height,r,s):this._texture=o.createDynamicTexture(t,t,r,s));let l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(){let e=this.getSize();this._context.fillRect(0,0,e.width,e.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,a,n,o=!0){let l=this.getSize();if(a&&(this._context.fillStyle=a,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){let i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){let e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),o&&this.update(n)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new DynamicTexture(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){let e=this.getScene();e&&!e.isReady()&&logger_Logger.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return DynamicTexture._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}};let WebXRLayerWrapper=class WebXRLayerWrapper{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){this.isFixedFoveationSupported&&(this.layer.fixedFoveation=Math.max(0,Math.min(1,e||0)))}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.createRenderTargetTextureProvider=s}};let WebXRLayerRenderTargetTextureProvider=class WebXRLayerRenderTargetTextureProvider{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=[],this._engine=e.getEngine()}_createInternalTexture(e,t){let i=new internalTexture_InternalTexture(this._engine,$.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new WebGLHardwareTexture(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,a){if(!this._engine)throw Error("Engine is disposed");let n={width:e,height:t},o=a?new MultiviewRenderTarget(this._scene,n):new renderTargetTexture_RenderTargetTexture("XR renderTargetTexture",n,this._scene),l=o.renderTarget;if(l._samples=o.samples,(i||!r)&&(l._framebuffer=i),r){if(a)l._colorTextureArray=r;else{let e=this._createInternalTexture(n,r);l.setTexture(e,0),o._texture=e}}return s&&(a?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(n,s)),o.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(o.skipInitialClear=!0),this._renderTargetTextures.push(o),o}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.length=0}};let WebXRWebGLLayerWrapper=class WebXRWebGLLayerWrapper extends WebXRLayerWrapper{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new WebXRWebGLLayerRenderTargetTextureProvider(e.scene,this)),this.layer=e}};let WebXRWebGLLayerRenderTargetTextureProvider=class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){let i=this._layer.getViewport(t);if(!i)return!1;let r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){let t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}};let WebXRManagedOutputCanvasOptions=class WebXRManagedOutputCanvasOptions{static GetDefaults(e){let t=new WebXRManagedOutputCanvasOptions;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}};let WebXRManagedOutputCanvas=class WebXRManagedOutputCanvas{constructor(e,t=WebXRManagedOutputCanvasOptions.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new observable_Observable,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{let e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add(()=>{this._addCanvas()}),e.onXRSessionEnded.add(()=>{this._removeCanvas()})}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){let createLayer=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new WebXRWebGLLayerWrapper(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{tools_Tools.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>createLayer()):Promise.resolve(createLayer())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(()=>{this._setCanvasSize(!0)})}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}};let NativeXRLayerWrapper=class NativeXRLayerWrapper extends WebXRLayerWrapper{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new NativeXRLayerRenderTargetTextureProvider(e,this)),this.layer=e}};let NativeXRLayerRenderTargetTextureProvider=class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}};let NativeXRRenderTarget=class NativeXRRenderTarget{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}};let WebXRSessionManager=class WebXRSessionManager{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new observable_Observable,this.onXRReferenceSpaceChanged=new observable_Observable,this.onXRSessionEnded=new observable_Observable,this.onXRSessionInit=new observable_Observable,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch(()=>{logger_Logger.Warn("Could not end XR session.")})):Promise.resolve()}trySetViewportForView(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){let t=this.scene.getEngine();return this._xrNavigator.xr.native?new NativeXRRenderTarget(this):((e=e||WebXRManagedOutputCanvasOptions.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new WebXRManagedOutputCanvas(this,e))}initializeAsync(){return(this._xrNavigator=navigator,this._xrNavigator.xr)?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then(t=>(this.session=t,this._sessionMode=e,this.onXRSessionInit.notifyObservers(t),this.inXRSession=!0,this.session.addEventListener("end",()=>{var e;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&(null===(e=this._baseLayerRTTProvider)||void 0===e||e.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return WebXRSessionManager.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{var i;this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then(e=>e,e=>(logger_Logger.Error("XR.requestReferenceSpace failed for the following reason: "),logger_Logger.Error(e),logger_Logger.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(e=>{let t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)},e=>{throw logger_Logger.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))).then(e=>this.session.requestReferenceSpace("viewer").then(t=>(this.viewerReferenceSpace=t,e))).then(e=>(this.referenceSpace=this.baseReferenceSpace=e,this.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new NativeXRLayerWrapper(e.baseLayer):new WebXRWebGLLayerWrapper(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);let t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(e=>Promise.resolve(void 0===e||e)).catch(e=>(logger_Logger.Warn(e),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e}get currentFrameRate(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate}get supportedFrameRates(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():(this.inXRSession||!t)&&this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null}set fixedFoveation(e){this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=Math.max(0,Math.min(1,e||0)))}get enabledFeatures(){var e,t;return null!==(t=null===(e=this.session)||void 0===e?void 0:e.enabledFeatures)&&void 0!==t?t:null}};(function(e){e[e.ENTERING_XR=0]="ENTERING_XR",e[e.EXITING_XR=1]="EXITING_XR",e[e.IN_XR=2]="IN_XR",e[e.NOT_IN_XR=3]="NOT_IN_XR"})(eB||(eB={})),function(e){e[e.NOT_TRACKING=0]="NOT_TRACKING",e[e.TRACKING_LOST=1]="TRACKING_LOST",e[e.TRACKING=2]="TRACKING"}(eN||(eN={})),mesh_Mesh._GroundMeshParser=(e,t)=>GroundMesh.Parse(e,t);let GroundMesh=class GroundMesh extends mesh_Mesh{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),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=math_vector_TmpVectors.Matrix[5];i.invertToRef(r);let s=math_vector_TmpVectors.Vector3[8];if(math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t),n=-(a.x*e+a.z*t+a.w)/a.y;return math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0,n,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new math_vector_Vector3(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=math_vector_TmpVectors.Matrix[5];r.invertToRef(s);let a=math_vector_TmpVectors.Vector3[8];if(math_vector_Vector3.TransformCoordinatesFromFloatsToRef(e,0,t,s,a),e=a.x,t=a.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let n=this._getFacetAt(e,t);return math_vector_Vector3.TransformNormalFromFloatsToRef(n.x,n.y,n.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];return te.maxHeight){h=!0;let t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){let r=new math_vector_Vector3(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),c=(r.x+e.width/2)/e.width*(e.bufferWidth-1)|0,u=(1-(r.z+e.height/2)/e.height)*(e.bufferHeight-1)|0,d=(c+u*e.bufferWidth)*4,_=e.buffer[d]/255,p=e.buffer[d+1]/255,f=e.buffer[d+2]/255,m=e.buffer[d+3]/255;h&&(_=1-_,p=1-p,f=1-f);let g=_*o.r+p*o.g+f*o.b;m>=l?r.y=e.minHeight+(e.maxHeight-e.minHeight)*g:r.y=e.minHeight-.001,s.push(r.x,r.y,r.z),a.push(0,0,0),n.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t=e.minHeight,c=s[3*n+1]>=e.minHeight,u=s[3*o+1]>=e.minHeight;h&&c&&u&&(r.push(a),r.push(n),r.push(o));let d=s[3*l+1]>=e.minHeight;d&&h&&u&&(r.push(l),r.push(a),r.push(o))}mesh_vertexData_VertexData.ComputeNormals(s,r,a);let c=new mesh_vertexData_VertexData;return c.indices=r,c.positions=s,c.normals=a,c.uvs=n,c}function CreateGround(e,t={},i){let r=new GroundMesh(e,i);r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ;let s=CreateGroundVertexData(t);return s.applyToMesh(r,t.updatable),r._setReady(!0),r}function CreateTiledGround(e,t,i=null){let r=new mesh_Mesh(e,i),s=CreateTiledGroundVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateGroundFromHeightMap(e,t,i={},r=null){let s=i.width||10,a=i.height||10,n=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new math_color_Color3(.3,.59,.11),c=i.alphaFilter||0,u=i.updatable,d=i.onReady;r=r||engineStore_EngineStore.LastCreatedScene;let _=new GroundMesh(e,r);return _._subdivisionsX=n,_._subdivisionsY=n,_._width=s,_._height=a,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),tools_Tools.LoadImage(t,e=>{let t=e.width,i=e.height;if(r.isDisposed)return;let p=null==r?void 0:r.getEngine().resizeImageBitmap(e,t,i),f=CreateGroundFromHeightMapVertexData({width:s,height:a,subdivisions:n,minHeight:o,maxHeight:l,colorFilter:h,buffer:p,bufferWidth:t,bufferHeight:i,alphaFilter:c});f.applyToMesh(_,u),d&&d(_),_._setReady(!0)},()=>{},r.offlineProvider),_}function CreateTorusVertexData(e){let t=[],i=[],r=[],s=[],a=e.diameter||1,n=e.thickness||.5,o=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,h=o+1;for(let e=0;e<=o;e++){let l=e/o,c=e*Math.PI*2/o-Math.PI/2,u=math_vector_Matrix.Translation(a/2,0,0).multiply(math_vector_Matrix.RotationY(c));for(let a=0;a<=o;a++){let c=1-a/o,d=a*Math.PI*2/o+Math.PI,_=Math.cos(d),p=Math.sin(d),f=new math_vector_Vector3(_,p,0),m=f.scale(n/2),g=new math_vector_Vector2(l,c);m=math_vector_Vector3.TransformCoordinates(m,u),f=math_vector_Vector3.TransformNormal(f,u),i.push(m.x,m.y,m.z),r.push(f.x,f.y,f.z),s.push(g.x,CompatibilityOptions.UseOpenGLOrientationForUV?1-g.y:g.y);let v=(e+1)%h,x=(a+1)%h;t.push(e*h+a),t.push(e*h+x),t.push(v*h+a),t.push(e*h+x),t.push(v*h+x),t.push(v*h+a)}}mesh_vertexData_VertexData._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);let c=new mesh_vertexData_VertexData;return c.indices=t,c.positions=i,c.normals=r,c.uvs=s,c}function CreateTorus(e,t={},i){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateTorusVertexData(t);return s.applyToMesh(r,t.updatable),r}mesh_vertexData_VertexData.CreateGround=CreateGroundVertexData,mesh_vertexData_VertexData.CreateTiledGround=CreateTiledGroundVertexData,mesh_vertexData_VertexData.CreateGroundFromHeightMap=CreateGroundFromHeightMapVertexData,mesh_Mesh.CreateGround=(e,t,i,r,s,a)=>CreateGround(e,{width:t,height:i,subdivisions:r,updatable:a},s),mesh_Mesh.CreateTiledGround=(e,t,i,r,s,a,n,o,l)=>CreateTiledGround(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:a,precision:n,updatable:l},o),mesh_Mesh.CreateGroundFromHeightMap=(e,t,i,r,s,a,n,o,l,h,c)=>CreateGroundFromHeightMap(e,t,{width:i,height:r,subdivisions:s,minHeight:a,maxHeight:n,updatable:l,onReady:h,alphaFilter:c},o),mesh_vertexData_VertexData.CreateTorus=CreateTorusVertexData,mesh_Mesh.CreateTorus=(e,t,i,r,s,a,n)=>CreateTorus(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:n,updatable:a},s);let VRExperienceHelperGazer=class VRExperienceHelperGazer{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=VRExperienceHelperGazer._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=CreateTorus("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;let t=new standardMaterial_StandardMaterial("targetMat",e);t.specularColor=math_color_Color3.Black(),t.emissiveColor=new math_color_Color3(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new ray_Ray(math_vector_Vector3.Zero(),new math_vector_Vector3(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}};VRExperienceHelperGazer._IdCounter=0;let VRExperienceHelperCameraGazer=class VRExperienceHelperCameraGazer extends VRExperienceHelperGazer{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){let t=this._getCamera();return t?t.getForwardRay(e):new ray_Ray(math_vector_Vector3.Zero(),math_vector_Vector3.Forward())}};let VRExperienceHelper=class VRExperienceHelper{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new observable_Observable,this.onAfterEnteringVRObservable=new observable_Observable,this.onExitingVRObservable=new observable_Observable,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new math_vector_Vector3(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new math_vector_Vector3(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new math_color_Color3(.2,.2,1),this._pickedGazeColor=new math_color_Color3(0,0,1),this.onNewMeshSelected=new observable_Observable,this.onNewMeshPicked=new observable_Observable,this.onBeforeCameraTeleport=new observable_Observable,this.onAfterCameraTeleport=new observable_Observable,this.onSelectedMeshUnselected=new observable_Observable,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==Gamepad.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged(e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))}),e.rightStick&&e.onrightstickchanged(e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)}),e.type===Gamepad.XBOX&&(e.onbuttondown(e=>{this._interactionsEnabled&&e===eM.A&&this._cameraGazer._selectionPointerDown()}),e.onbuttonup(e=>{this._interactionsEnabled&&e===eM.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=math_vector_Vector3.Zero(),this._workingQuaternion=math_vector_Quaternion.Identity(),this._workingMatrix=math_vector_Matrix.Identity(),logger_Logger.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement();let i="getVRDisplays"in navigator;if(i||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new math_vector_Vector3(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new DeviceOrientationCamera("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof targetCamera_TargetCamera&&this._scene.activeCamera.rotation)){let e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(math_vector_Quaternion.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then(i=>{i?(logger_Logger.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new VRExperienceHelperCameraGazer(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(e=>{switch(e){case eB.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case eB.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case eB.IN_XR:this._hasEnteredVR=!0;break;case eB.NOT_IN_XR:this._hasEnteredVR=!1}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new VRExperienceHelperCameraGazer(()=>this.currentVRCamera,e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png",t=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";t+=".babylonVRicon.vrdisplaypresenting { display: none; }";let i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});let i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},pointerEvents_PointerEventTypes.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new CircleEase,this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===pointerEvents_PointerEventTypes.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===pointerEvents_PointerEventTypes.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===eB.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){let e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){logger_Logger.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=math_vector_Quaternion.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){logger_Logger.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===eB.IN_XR&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>(!!this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e)}removeFloorMesh(e){if(!this._floorMeshesCollection)return;let t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){let t=e.floorMeshes||[];if(!t.length){let i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr){t.forEach(e=>{this.xr.teleportation.addFloorMesh(e)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}if(!this.xrTestDone){let waitForXr=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(waitForXr),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(waitForXr);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);let t=new ImageProcessingConfiguration;t.vignetteColor=new math_color_Color4(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){(!this._teleportationRequestInitiated||t._teleportationRequestInitiated)&&(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated){if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;let e=math_vector_Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,math_vector_Quaternion.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),math_vector_Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);let r=new ray_Ray(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}}_createTeleportationCircles(){this._teleportationTarget=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;let e=new DynamicTexture("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;let t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();let i=new standardMaterial_StandardMaterial("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;let r=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;let s=new animation_Animation("animationInnerCircle","position.y",30,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CYCLE),a=[];a.push({frame:0,value:0}),a.push({frame:30,value:.4}),a.push({frame:60,value:0}),s.setKeys(a);let n=new SineEase;n.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),s.setEasingFunction(n),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof FreeCamera))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];let t=math_vector_Quaternion.FromRotationMatrix(math_vector_Matrix.RotationY(Math.PI/4*this._rotationAngle)),i=new animation_Animation("animationRotation","rotationQuaternion",90,animation_Animation.ANIMATIONTYPE_QUATERNION,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];let s=new animation_Animation("animationPP","vignetteWeight",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),a=[];a.push({frame:0,value:0}),a.push({frame:3,value:4}),a.push({frame:6,value:0}),s.setKeys(a),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);let n=new animation_Animation("animationPP2","vignetteStretch",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:10}),o.push({frame:6,value:0}),n.setKeys(o),n.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(n),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){let t,i;if(!(this.currentVRCamera instanceof FreeCamera))return;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED){i=90;let e=math_vector_Vector3.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];let r=new animation_Animation("animationCameraTeleportation","position",90,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];let a=Math.round(i/2),n=new animation_Animation("animationPP","vignetteWeight",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:a,value:8}),o.push({frame:i,value:0}),n.setKeys(o),this._postProcessMove.animations.push(n);let l=new animation_Animation("animationPP2","vignetteStretch",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:a,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){if(!this.updateControllerLaserColor)return}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}};VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME=0,VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED=1;let intersectBoxAASphere=(e,t,i,r)=>!(e.x>i.x+r)&&!(i.x-r>t.x)&&!(e.y>i.y+r)&&!(i.y-r>t.y)&&!(e.z>i.z+r)&&!(i.z-r>t.z),rx=function(){let e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;let a=i*i-4*t*r;if(a<0)return e;let n=Math.sqrt(a),o=(-i-n)/(2*t),l=(-i+n)/(2*t);if(o>l){let e=l;l=o,o=e}return o>0&&o0&&l=0))}_canDoCollision(e,t,i,r){let s=math_vector_Vector3.Distance(this._basePointWorld,e),a=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+a+t)&&!!intersectBoxAASphere(i,r,this._basePointWorld,this._velocityWorldLength+a)}_testTriangle(e,t,i,r,s,a,n){let o;let l=!1;t||(t=[]),t[e]||(t[e]=new math_plane_Plane(0,0,0,0),t[e].copyFromPoints(i,r,s));let h=t[e];if(!a&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;let c=h.signedDistanceTo(this._basePoint),u=math_vector_Vector3.Dot(h.normal,this._velocity);if(Collider.DoubleSidedCheck&&u>1e-4)return;if(0==u){if(Math.abs(c)>=1)return;l=!0,o=0}else{o=(-1-c)/u;let e=(1-c)/u;if(o>e){let t=e;e=o,o=t}if(o>1||e<0)return;o<0&&(o=0),o>1&&(o=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,_=1;if(!l&&(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(o,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,_=o,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*math_vector_Vector3.Dot(this._velocity,this._tempVector),a=this._tempVector.lengthSquared()-1,n=rx(e,t,a,_);n.found&&(_=n.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),(n=rx(e,t=2*math_vector_Vector3.Dot(this._velocity,this._tempVector),a=this._tempVector.lengthSquared()-1,_)).found&&(_=n.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),(n=rx(e,t=2*math_vector_Vector3.Dot(this._velocity,this._tempVector),a=this._tempVector.lengthSquared()-1,_)).found&&(_=n.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let o=this._edge.lengthSquared(),l=math_vector_Vector3.Dot(this._edge,this._velocity),h=math_vector_Vector3.Dot(this._edge,this._baseToVertex);if((n=rx(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*math_vector_Vector3.Dot(this._velocity,this._baseToVertex)-l*h),a=o*(1-this._baseToVertex.lengthSquared())+h*h,_)).found){let e=(l*n.root-h)/o;e>=0&&e<=1&&(_=n.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=math_vector_Vector3.Dot(this._edge,this._velocity),h=math_vector_Vector3.Dot(this._edge,this._baseToVertex),(n=rx(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*math_vector_Vector3.Dot(this._velocity,this._baseToVertex)-l*h),a=o*(1-this._baseToVertex.lengthSquared())+h*h,_)).found){let e=(l*n.root-h)/o;e>=0&&e<=1&&(_=n.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=math_vector_Vector3.Dot(this._edge,this._velocity),h=math_vector_Vector3.Dot(this._edge,this._baseToVertex),(n=rx(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*math_vector_Vector3.Dot(this._velocity,this._baseToVertex)-l*h),a=o*(1-this._baseToVertex.lengthSquared())+h*h,_)).found){let e=(l*n.root-h)/o;e>=0&&e<=1&&(_=n.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){let e=_*_*this._velocitySquaredLength;(!this.collisionFound||e=r){s.copyFrom(e);return}let o=a?a.collisionMask:i.collisionMask;i._initialize(e,t,n);let l=a&&a.surroundingMeshes||this._scene.meshes;for(let e=0;enew DefaultCollisionCoordinator;let ComputeEffect=class ComputeEffect{constructor(e,t,i,r=""){var s,a;let n;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new observable_Observable,this.onErrorObservable=new observable_Observable,this.onBindObservable=new observable_Observable,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=q.WGSL,this.name=e,this._key=r,this._engine=i,this.uniqueId=ComputeEffect._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(a=t.entryPoint)&&void 0!==a?a:"main",this._shaderStore=ShaderStore.GetShadersStore(this._shaderLanguage),this._shaderRepository=ShaderStore.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=ShaderStore.GetIncludesShadersStore(this._shaderLanguage);let o=IsWindowObjectExist()?this._engine.getHostDocument():null;e.computeSource?n="source:"+e.computeSource:e.computeElement?(n=o?o.getElementById(e.computeElement):null)||(n=e.computeElement):n=e.compute||e;let l={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(n,"Compute","",i=>{ShaderProcessor.Initialize(l),ShaderProcessor.PreProcess(i,l,r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));let s=ShaderProcessor.Finalize(r,"",l);this._useFinalCode(s.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){let i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=GetDOMTextContent(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getComputeShaderCode())&&void 0!==t?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){let e=this.defines,t=this._pipelineContext;this._isReady=!1;try{let i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,()=>{this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)}),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t){let i=null;if(t&&e){let r=t.match(/COMPUTE SHADER ERROR: 0:(\d+?):/);if(r&&2===r.length){let t=parseInt(r[1]),s=e.split("\n",-1);s.length>=t&&(i=`Offending line [${t}] in compute code: ${s[t-1]}`)}}return[e,i]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,logger_Logger.Error("Unable to compile compute effect:"),logger_Logger.Error("Defines:\n"+this.defines),ComputeEffect.LogShaderCodeOnCompilationError){let e=null,t=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getComputeShaderCode())&&([t,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),t&&(logger_Logger.Error("Compute code:"),logger_Logger.Error(t))),e&&logger_Logger.Error(e)}logger_Logger.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){ShaderStore.GetShadersStore(q.WGSL)[`${e}ComputeShader`]=t}};ComputeEffect._UniqueIdSeed=0,ComputeEffect.LogShaderCodeOnCompilationError=!0,function(e){e[e.Texture=0]="Texture",e[e.StorageTexture=1]="StorageTexture",e[e.UniformBuffer=2]="UniformBuffer",e[e.StorageBuffer=3]="StorageBuffer",e[e.TextureWithoutSampler=4]="TextureWithoutSampler",e[e.Sampler=5]="Sampler",e[e.ExternalTexture=6]="ExternalTexture"}(eF||(eF={})),ThinEngine.prototype.createComputeEffect=function(e,t){throw Error("createComputeEffect: This engine does not support compute shaders!")},ThinEngine.prototype.createComputePipelineContext=function(){throw Error("createComputePipelineContext: This engine does not support compute shaders!")},ThinEngine.prototype.createComputeContext=function(){},ThinEngine.prototype.computeDispatch=function(e,t,i,r,s,a,n){throw Error("computeDispatch: This engine does not support compute shaders!")},ThinEngine.prototype.areAllComputeEffectsReady=function(){return!0},ThinEngine.prototype.releaseComputeEffects=function(){},ThinEngine.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},ThinEngine.prototype._rebuildComputeEffects=function(){},ThinEngine.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},ThinEngine.prototype._releaseComputeEffect=function(e){},ThinEngine.prototype._deleteComputePipelineContext=function(e){};let ComputeShader=class ComputeShader{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,r={}){if(this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=UniqueIdGenerator.UniqueId,!this._engine.getCaps().supportComputeShaders){logger_Logger.Error("This engine does not support compute shaders!");return}if(!r.bindingsMapping){logger_Logger.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!");return}this._context=t.createComputeContext(),this._shaderPath=i,this._options=Object.assign({bindingsMapping:{},defines:[]},r)}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){let r=this._bindings[e];this._bindings[e]={type:i?eF.Texture:eF.TextureWithoutSampler,object:t,indexInGroupEntries:null==r?void 0:r.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!r||r.object!==t||r.type!==this._bindings[e].type)}setStorageTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:eF.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setExternalTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:eF.ExternalTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setVideoTexture(e,t){return!!t.externalTexture&&(this.setExternalTexture(e,t.externalTexture),!0)}setUniformBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:eF.UniformBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:eF.StorageBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:eF.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(let e in this._bindings){let t=this._bindings[e],i=t.type,r=t.object;switch(i){case eF.Texture:case eF.TextureWithoutSampler:case eF.StorageTexture:case eF.ExternalTexture:if(!r.isReady())return!1}}let t=[],i=this._shaderPath;if(this._options.defines)for(let e=0;e{let check=()=>{this.dispatch(e,t,i)?s():setTimeout(check,r)};check()})}serialize(){let e=decorators_SerializationHelper.Serialize(this);for(let t in e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={},this._bindings){let i=this._bindings[t],r=i.object;switch(i.type){case eF.Texture:case eF.TextureWithoutSampler:case eF.StorageTexture:{let s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type})}case eF.UniformBuffer:}}return e}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new ComputeShader(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(let s in e.textures){let a=e.bindings[s],n=texture_Texture.Parse(e.textures[s],t,i);a.type===eF.Texture?r.setTexture(s,n):a.type===eF.TextureWithoutSampler?r.setTexture(s,n,!1):r.setStorageTexture(s,n)}return r}};__decorate([serialize()],ComputeShader.prototype,"name",void 0),h["BABYLON.ComputeShader"]=ComputeShader;let OctreeBlock=class OctreeBlock{constructor(e,t,i,r,s,a){this.entries=[],this._boundingVectors=[],this._capacity=i,this._depth=r,this._maxDepth=s,this._creationFunc=a,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{let i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Octree.CreationFuncForSubMeshes=(e,t)=>{let i=e.getBoundingInfo();i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},scene_Scene.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(sceneComponent_SceneComponentConstants.NAME_OCTREE);i||(i=new OctreeSceneComponent(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Octree(Octree.CreationFuncForMeshes,e,t));let r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(scene_Scene.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),abstractMesh_AbstractMesh.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){let i=this.getScene(),r=i._getComponent(sceneComponent_SceneComponentConstants.NAME_OCTREE);r||(r=new OctreeSceneComponent(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new Octree(Octree.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);let s=this.getBoundingInfo(),a=s.boundingBox;return this._submeshesOctree.update(a.minimumWorld,a.maximumWorld,this.subMeshes),this._submeshesOctree};let OctreeSceneComponent=class OctreeSceneComponent{constructor(e){if(this.name=sceneComponent_SceneComponentConstants.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new ray_Ray(math_vector_Vector3.Zero(),new math_vector_Vector3(1,1,1)),!(e=e||engineStore_EngineStore.LastCreatedScene))return;this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t)}register(){this.scene.onMeshRemovedObservable.add(e=>{let t=this.scene.selectionOctree;if(null!=t){let i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{let t=this.scene.selectionOctree;null!=t&&t.addMesh(e)})}getActiveMeshCandidates(){var e;return(null===(e=this.scene._selectionOctree)||void 0===e?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){if(e._submeshesOctree&&e.useOctreeForRenderingSelection){let t=e._submeshesOctree.select(this.scene.frustumPlanes);return t}return this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForPicking){ray_Ray.TransformToRef(t,e.getWorldMatrix(),this._tempRay);let i=e._submeshesOctree.intersectsRay(this._tempRay);return i}return this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){let i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z),r=e._submeshesOctree.intersects(t._basePointWorld,i);return r}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}};function CreateCylinderVertexData(e){let t,i,r,s,a,n,o;let l=e.height||2,h=0===e.diameterTop?0:e.diameterTop||e.diameter||1,c=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;h=h||1e-5,c=c||1e-5;let u=0|(e.tessellation||24),d=0|(e.subdivisions||1),_=!!e.hasRings,p=!!e.enclose,f=0===e.cap?0:e.cap||mesh_Mesh.CAP_ALL,m=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,g=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,v=e.faceUV||[,,,],x=e.faceColors,b=2+(1+(1!==m&&p?2:0))*(_?d:1);for(t=0;t{let t,i,r;let s=e?h/2:c/2;if(0===s)return;let a=e?v[b-1]:v[0],n=null;x&&(n=e?x[b-1]:x[0]);let o=S.length/3,d=e?l/2:-l/2,_=new math_vector_Vector3(0,d,0);S.push(_.x,_.y,_.z),C.push(0,e?1:-1,0);let p=a.y+(a.w-a.y)*.5;E.push(a.x+(a.z-a.x)*.5,CompatibilityOptions.UseOpenGLOrientationForUV?1-p:p),n&&y.push(n.r,n.g,n.b,n.a);let f=new math_vector_Vector2(.5,.5);for(r=0;r<=u;r++){t=2*Math.PI*r*m/u;let o=Math.cos(-t),l=Math.sin(-t);i=new math_vector_Vector3(o*s,d,l*s);let h=new math_vector_Vector2(o*f.x+.5,l*f.y+.5);S.push(i.x,i.y,i.z),C.push(0,e?1:-1,0);let c=a.y+(a.w-a.y)*h.y;E.push(a.x+(a.z-a.x)*h.x,CompatibilityOptions.UseOpenGLOrientationForUV?1-c:c),n&&y.push(n.r,n.g,n.b,n.a)}for(r=0;r{void 0!==n&&n instanceof scene_Scene||(void 0!==n&&(l=o||mesh_Mesh.DEFAULTSIDE,o=n),n=a,a=1);let h={height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:a,sideOrientation:l,updatable:o};return cylinderBuilder_CreateCylinder(e,h,n)},node_Node.AddNodeConstructor("Light_Type_3",(e,t)=>()=>new HemisphericLight(e,math_vector_Vector3.Zero(),t));let HemisphericLight=class HemisphericLight extends light_Light{constructor(e,t,i){super(e,i),this.groundColor=new math_color_Color3(0,0,0),this.direction=t||math_vector_Vector3.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=math_vector_Vector3.Normalize(e.subtract(math_vector_Vector3.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=math_vector_Vector3.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){let i=math_vector_Vector3.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=math_vector_Matrix.Identity()),this._worldMatrix}getTypeID(){return light_Light.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}};__decorate([serializeAsColor3()],HemisphericLight.prototype,"groundColor",void 0),__decorate([serializeAsVector3()],HemisphericLight.prototype,"direction",void 0);let utilityLayerRenderer_UtilityLayerRenderer=class utilityLayerRenderer_UtilityLayerRenderer{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return(t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera)?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new HemisphericLight("shared gizmo light",new math_vector_Vector3(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=math_color_Color3.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer?utilityLayerRenderer_UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(engineStore_EngineStore.LastCreatedScene):utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(e),utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=null}),utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer&&(utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(engineStore_EngineStore.LastCreatedScene),utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=null})),utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new observable_Observable,this.utilityLayerScene=new scene_Scene(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(t=>{if(!this.utilityLayerScene.activeCamera||!this.pickingEnabled||!this.processAllEvents&&t.type!==pointerEvents_PointerEventTypes.POINTERMOVE&&t.type!==pointerEvents_PointerEventTypes.POINTERUP&&t.type!==pointerEvents_PointerEventTypes.POINTERDOWN&&t.type!==pointerEvents_PointerEventTypes.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;let i=t.event;if(e.isPointerCaptured(i.pointerId)){this._pointerCaptures[i.pointerId]=!1;return}let getNearPickDataForScene=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new PickingInfo;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},r=getNearPickDataForScene(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=pointerEvents_PointerEventTypes.POINTERDOWN){t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(t.type,t.event,r),t.type),t.type===pointerEvents_PointerEventTypes.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{let i=getNearPickDataForScene(e),s=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):t.type===pointerEvents_PointerEventTypes.POINTERDOWN?this._pointerCaptures[s.pointerId]=!0:(t.type===pointerEvents_PointerEventTypes.POINTERMOVE||t.type===pointerEvents_PointerEventTypes.POINTERUP)&&(this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,i,s)):!this._pointerCaptures[s.pointerId]&&(r.distance0)):!this._pointerCaptures[s.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):((t.type===pointerEvents_PointerEventTypes.POINTERMOVE||t.type===pointerEvents_PointerEventTypes.POINTERUP)&&this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,r,s))),t.type===pointerEvents_PointerEventTypes.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new PointerInfo(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){let e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}};utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=null,utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=null,function(e){e[e.Origin=0]="Origin",e[e.Pivot=1]="Pivot"}(ew||(ew={})),function(e){e[e.World=0]="World",e[e.Local=1]="Local"}(eL||(eL={}));let gizmo_Gizmo=class gizmo_Gizmo{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach(e=>{e.dispose()}),e.parent=this._rootMesh,this._customMeshSet=!0}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;let t=e==eL.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=ew.Origin,this._updateScale=!0,this._coordinatesMode=eL.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=math_vector_Matrix.RotationY(Math.PI),this._rootMesh=new mesh_Mesh("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=math_vector_Quaternion.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(()=>{this._update()})}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh){if(this.anchorPoint==ew.Pivot&&e.getAbsolutePivotPoint){let t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{let t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new math_vector_Vector3(0,0,0);this._rootMesh.position.copyFrom(i)}}if(this.updateGizmoRotationToMatchAttachedMesh){let t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName(),i=t?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,gizmo_Gizmo.PreserveScaling?i:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){let t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,math_vector_TmpVectors.Vector3[0]);let r=this.scaleRatio;if(t.mode==camera_Camera.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){let e=t.orthoTop-t.orthoBottom;r*=e}}else{let e=t.getScene().useRightHandedSystem?math_vector_Vector3.RightHandedForwardReadOnly:math_vector_Vector3.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=math_vector_Vector3.Dot(math_vector_TmpVectors.Vector3[0],i)}this._rootMesh.scaling.setAll(r),0>e._getWorldMatrixDeterminant()&&!gizmo_Gizmo.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_matrixChanged(){if(this._attachedNode){if(this._attachedNode._isCamera){let e,t;let i=this._attachedNode;if(i.parent){let t=math_vector_TmpVectors.Matrix[1];i.parent._worldMatrix.invertToRef(t),this._attachedNode._worldMatrix.multiplyToRef(t,math_vector_TmpVectors.Matrix[0]),e=math_vector_TmpVectors.Matrix[0]}else e=this._attachedNode._worldMatrix;i.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(e,math_vector_TmpVectors.Matrix[1]),t=math_vector_TmpVectors.Matrix[1]):t=e,t.decompose(math_vector_TmpVectors.Vector3[1],math_vector_TmpVectors.Quaternion[0],math_vector_TmpVectors.Vector3[0]);let r="FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName();if(r){let e=this._attachedNode;e.rotation=math_vector_TmpVectors.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(math_vector_TmpVectors.Quaternion[0]),e.rotationQuaternion.normalize())}i.position.copyFrom(math_vector_TmpVectors.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){let e=this._attachedNode;if(e.parent){let t=math_vector_TmpVectors.Matrix[0],i=math_vector_TmpVectors.Matrix[1];if(e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Quaternion[0],e.position),math_vector_TmpVectors.Quaternion[0].normalize(),e.isUsingPivotMatrix()){let t=math_vector_TmpVectors.Quaternion[1];math_vector_Quaternion.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);let i=math_vector_TmpVectors.Matrix[2];math_vector_Matrix.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);let r=math_vector_TmpVectors.Matrix[2];t.toRotationMatrix(r);let s=e.getPivotMatrix(),a=math_vector_TmpVectors.Matrix[3];s.invertToRef(a),s.multiplyToRef(i,math_vector_TmpVectors.Matrix[4]),math_vector_TmpVectors.Matrix[4].multiplyToRef(r,math_vector_TmpVectors.Matrix[5]),math_vector_TmpVectors.Matrix[5].multiplyToRef(a,math_vector_TmpVectors.Matrix[6]),math_vector_TmpVectors.Matrix[6].getTranslationToRef(math_vector_TmpVectors.Vector3[1]),e.position.subtractInPlace(math_vector_TmpVectors.Vector3[1])}}else this._attachedNode._worldMatrix.decompose(math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Quaternion[0],e.position,gizmo_Gizmo.PreserveScaling?e:void 0);math_vector_TmpVectors.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(math_vector_TmpVectors.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(math_vector_TmpVectors.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=math_vector_TmpVectors.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){let e=this._attachedNode,t=e.getParent();if(t){let i=math_vector_TmpVectors.Matrix[0],r=math_vector_TmpVectors.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r);let s=e.getLocalMatrix();s.copyFrom(r)}else{let t=e.getLocalMatrix();t.copyFrom(e.getFinalMatrix())}e.markAsDirty()}else{let e=this._attachedNode;if(e.getTypeID){let t=e.getTypeID();if(t===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT||t===light_Light.LIGHTTYPEID_SPOTLIGHT||t===light_Light.LIGHTTYPEID_POINTLIGHT){let t=e.parent;if(t){let i=math_vector_TmpVectors.Matrix[0],r=math_vector_TmpVectors.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,math_vector_TmpVectors.Quaternion[0],math_vector_TmpVectors.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,math_vector_TmpVectors.Quaternion[0],math_vector_TmpVectors.Vector3[0]);e.position=new math_vector_Vector3(math_vector_TmpVectors.Vector3[0].x,math_vector_TmpVectors.Vector3[0].y,math_vector_TmpVectors.Vector3[0].z),e.direction&&(e.direction=new math_vector_Vector3(e.direction.x,e.direction.y,e.direction.z))}}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach(e=>{e.material=t,e.color&&(e.color=t.diffuseColor)})}static GizmoAxisPointerObserver(e,t){let i=!1,r=e.utilityLayerScene.onPointerObservable.add(e=>{var r,s;if(e.pickInfo){if(e.type===pointerEvents_PointerEventTypes.POINTERMOVE){if(i)return;t.forEach(t=>{var i,r;if(t.colliderMeshes&&t.gizmoMeshes){let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,a=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=a,e.color&&(e.color=a.diffuseColor)})}})}if(e.type===pointerEvents_PointerEventTypes.POINTERDOWN&&t.has(null===(r=e.pickInfo.pickedMesh)||void 0===r?void 0:r.parent)){i=!0;let r=t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent);r.active=!0,t.forEach(t=>{var i,r;let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,a=(s||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=a,e.color&&(e.color=a.diffuseColor)})})}e.type===pointerEvents_PointerEventTypes.POINTERUP&&t.forEach(e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach(t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)})})}});return r}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}};gizmo_Gizmo.PreserveScaling=!1,Object.defineProperty(scene_Scene.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new DebugLayer(this)),this._debugLayer},enumerable:!0,configurable:!0}),function(e){e[e.Properties=0]="Properties",e[e.Debug=1]="Debug",e[e.Statistics=2]="Statistics",e[e.Tools=3]="Tools",e[e.Settings=4]="Settings"}(eV||(eV={}));let DebugLayer=class DebugLayer{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new observable_Observable),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new observable_Observable),this._onSelectionChangedObservable)}constructor(e){if(this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||engineStore_EngineStore.LastCreatedScene,!this._scene)return;this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(let e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(let e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}let t=Object.assign(Object.assign({},DebugLayer.Config),e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise(t=>{if(void 0===this.BJSINSPECTOR){let i=e&&e.inspectorURL?e.inspectorURL:DebugLayer.InspectorURL;tools_Tools.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}};function CreateBoxVertexData(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],i=[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],r=[],s=[],a=e.width||e.size||1,n=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1,h=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,c=(c+4)%4;let u=[2,0,3,1][h],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(l){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]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],r=[17,18,19,16],s=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),r.unshift(r.pop()),u--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),_=_.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}let p=[a/2,n/2,o/2];s=_.reduce((e,t,i)=>e.concat(t*p[i%3]),[]);let f=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,m=e.faceUV||Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new math_vector_Vector4(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new math_color_Color4(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,CompatibilityOptions.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,CompatibilityOptions.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,CompatibilityOptions.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),r.push(m[e].z,CompatibilityOptions.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);mesh_vertexData_VertexData._ComputeSides(f,s,t,i,r,e.frontUVs,e.backUVs);let x=new mesh_vertexData_VertexData;if(x.indices=t,x.positions=s,x.normals=i,x.uvs=r,g){let e=f===mesh_vertexData_VertexData.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function CreateSegmentedBoxVertexData(e){let t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),a=0|(e.heightSegments||e.segments||1),n=0|(e.depthSegments||e.segments||1),o=new math_vector_Matrix,l=new math_vector_Matrix,h=new math_vector_Matrix,c=CreateGroundVertexData({width:t,height:r,subdivisionsX:s,subdivisionsY:n});math_vector_Matrix.TranslationToRef(0,-i/2,0,l),math_vector_Matrix.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),c.transform(h);let u=CreateGroundVertexData({width:t,height:r,subdivisionsX:s,subdivisionsY:n});math_vector_Matrix.TranslationToRef(0,i/2,0,h),u.transform(h);let d=CreateGroundVertexData({width:i,height:r,subdivisionsX:a,subdivisionsY:n});math_vector_Matrix.TranslationToRef(-t/2,0,0,l),math_vector_Matrix.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);let _=CreateGroundVertexData({width:i,height:r,subdivisionsX:a,subdivisionsY:n});math_vector_Matrix.TranslationToRef(t/2,0,0,l),math_vector_Matrix.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h);let p=CreateGroundVertexData({width:t,height:i,subdivisionsX:s,subdivisionsY:a});math_vector_Matrix.TranslationToRef(0,0,-r/2,l),math_vector_Matrix.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),p.transform(h);let f=CreateGroundVertexData({width:t,height:i,subdivisionsX:s,subdivisionsY:a});return math_vector_Matrix.TranslationToRef(0,0,r/2,l),math_vector_Matrix.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h),c.merge([u,_,d,p,f],!0),c}function boxBuilder_CreateBox(e,t={},i=null){let r=new mesh_Mesh(e,i);t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateBoxVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateSphereVertexData(e){let t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,a=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,n=e.slice&&e.slice<=0?1:e.slice||1,o=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new math_vector_Vector3(i/2,r/2,s/2),c=2+t,u=2*c,d=[],_=[],p=[],f=[];for(let e=0;e<=c;e++){let t=e/c,i=t*Math.PI*n;for(let e=0;e<=u;e++){let r=e/u,s=r*Math.PI*2*a,n=math_vector_Matrix.RotationZ(-i),o=math_vector_Matrix.RotationY(s),l=math_vector_Vector3.TransformCoordinates(math_vector_Vector3.Up(),n),c=math_vector_Vector3.TransformCoordinates(l,o),d=c.multiply(h),m=c.divide(h).normalize();_.push(d.x,d.y,d.z),p.push(m.x,m.y,m.z),f.push(r,CompatibilityOptions.UseOpenGLOrientationForUV?1-t:t)}if(e>0){let t=_.length/3;for(let i=t-2*(u+1);i+u+21&&(d.push(i),d.push(i+1),d.push(i+u+1)),(em?m:Math.floor(g);let v=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,x=e.uvs,b=e.colors,T=[],S=[],C=[],E=[],y=[],R=[],P=[],A=[],M=[],I=[];if(d.length<2){let e=[],t=[];for(r=0;r0&&(o=a[s].subtract(a[s-1]).length()+P[i],y[i].push(o),P[i]=o),s++;p&&(s--,T.push(a[0].x,a[0].y,a[0].z),o=a[s].subtract(a[0]).length()+P[i],y[i].push(o),P[i]=o),M[i]=n+O,I[i]=D,D+=n+O}let B=null,N=null;for(r=0;r{let s=r[0].length,a=0,n=o._originalBuilderSideOrientation===mesh_Mesh.DOUBLESIDE?2:1;for(let l=1;l<=n;++l)for(let n=0;n1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);let h=2*Math.PI*o,c=1===o?h/n:h/(n-1),u=0;for(let e=0;e0||u>0){switch(m=-d,g=-_,v=d,x=_,s){case mesh_Mesh.CENTER:l/=2,m-=l,v+=l;break;case mesh_Mesh.LEFT:v+=l,p=-l/2;break;case mesh_Mesh.RIGHT:m-=l,p=l/2}switch(a){case mesh_Mesh.CENTER:u/=2,g-=u,x+=u;break;case mesh_Mesh.BOTTOM:x+=u,f=-u/2;break;case mesh_Mesh.TOP:g-=u,f=u/2}}let b=[],T=[],S=[];S[0]=[0,0,1,0,1,1,0,1],S[1]=[0,0,1,0,1,1,0,1],(t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.ROTATE_ROW)&&(S[1]=[1,1,0,1,0,0,1,0]),(t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.FLIP_ROW)&&(S[1]=[1,0,0,0,0,1,1,1]),(t===mesh_Mesh.FLIP_N_ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_ROW)&&(S[1]=[0,1,1,1,1,0,0,0]);let C=[],E=[],y=[],R=0;for(let e=0;e0||u>0){let e,n,h,S;let P=u>0&&(a===mesh_Mesh.CENTER||a===mesh_Mesh.TOP),A=u>0&&(a===mesh_Mesh.CENTER||a===mesh_Mesh.BOTTOM),M=l>0&&(s===mesh_Mesh.CENTER||s===mesh_Mesh.RIGHT),I=l>0&&(s===mesh_Mesh.CENTER||s===mesh_Mesh.LEFT),D=[];if(P&&M&&(b.push(m+p,g+f,0),b.push(-d+p,g+f,0),b.push(-d+p,g+u+f,0),b.push(m+p,g+u+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,h=1,S=1,D=[e=1-l/i,n=1-u/r,h,n,h,S,e,S],t===mesh_Mesh.ROTATE_ROW&&(D=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),t===mesh_Mesh.FLIP_ROW&&(D=[1-e,n,1-h,n,1-h,S,1-e,S]),t===mesh_Mesh.FLIP_N_ROTATE_ROW&&(D=[e,1-n,h,1-n,h,1-S,e,1-S]),C=C.concat(D),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),P&&I&&(b.push(d+p,g+f,0),b.push(v+p,g+f,0),b.push(v+p,g+u+f,0),b.push(d+p,g+u+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,S=1,D=[e=0,n=1-u/r,h=l/i,n,h,S,e,S],(t===mesh_Mesh.ROTATE_ROW||t===mesh_Mesh.ROTATE_TILE&&o%2==0)&&(D=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_ROW||t===mesh_Mesh.FLIP_TILE&&o%2==0)&&(D=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_ROW||t===mesh_Mesh.FLIP_N_ROTATE_TILE&&o%2==0)&&(D=[e,1-n,h,1-n,h,1-S,e,1-S]),C=C.concat(D),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),A&&M&&(b.push(m+p,_+f,0),b.push(-d+p,_+f,0),b.push(-d+p,x+f,0),b.push(m+p,x+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,n=0,h=1,D=[e=1-l/i,n,h,n,h,S=u/r,e,S],(t===mesh_Mesh.ROTATE_ROW&&c%2==1||t===mesh_Mesh.ROTATE_TILE&&c%1==0)&&(D=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_ROW&&c%2==1||t===mesh_Mesh.FLIP_TILE&&c%2==0)&&(D=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_ROW&&c%2==1||t===mesh_Mesh.FLIP_N_ROTATE_TILE&&c%2==0)&&(D=[e,1-n,h,1-n,h,1-S,e,1-S]),C=C.concat(D),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),A&&I&&(b.push(d+p,_+f,0),b.push(v+p,_+f,0),b.push(v+p,x+f,0),b.push(d+p,x+f,0),y.push(R,R+1,R+3,R+1,R+2,R+3),R+=4,D=[e=0,n=0,h=l/i,n,h,S=u/r,e,S],(t===mesh_Mesh.ROTATE_ROW&&c%2==1||t===mesh_Mesh.ROTATE_TILE&&(c+o)%2==1)&&(D=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_ROW&&c%2==1||t===mesh_Mesh.FLIP_TILE&&(c+o)%2==1)&&(D=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_ROW&&c%2==1||t===mesh_Mesh.FLIP_N_ROTATE_TILE&&(c+o)%2==1)&&(D=[e,1-n,h,1-n,h,1-S,e,1-S]),C=C.concat(D),E.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),T.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),P){let s=[];e=0,n=1-u/r,h=1,S=1,s[0]=[e,n,h,n,h,S,e,S],s[1]=[e,n,h,n,h,S,e,S],(t===mesh_Mesh.ROTATE_TILE||t===mesh_Mesh.ROTATE_ROW)&&(s[1]=[1-e,1-n,1-h,1-n,1-h,1-S,1-e,1-S]),(t===mesh_Mesh.FLIP_TILE||t===mesh_Mesh.FLIP_ROW)&&(s[1]=[1-e,n,1-h,n,1-h,S,1-e,S]),(t===mesh_Mesh.FLIP_N_ROTATE_TILE||t===mesh_Mesh.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-n,h,1-n,h,1-S,e,1-S]);for(let e=0;ee+C)),C+=x[e].length,i)for(let t=0;t<4;t++)v.push(i[e].r,i[e].g,i[e].b,i[e].a)}let E=new math_vector_Vector3(0,0,n/2),y=math_vector_Matrix.RotationY(Math.PI);p=x[0].map(e=>math_vector_Vector3.TransformNormal(e,y).add(E)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),f=b[0].map(e=>math_vector_Vector3.TransformNormal(e,y)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),p=p.concat(x[1].map(e=>e.subtract(E)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[1].map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let R=new math_vector_Vector3(s/2,0,0),P=math_vector_Matrix.RotationY(-Math.PI/2);p=p.concat(x[2].map(e=>math_vector_Vector3.TransformNormal(e,P).add(R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[2].map(e=>math_vector_Vector3.TransformNormal(e,P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let A=math_vector_Matrix.RotationY(Math.PI/2);p=p.concat(x[3].map(e=>math_vector_Vector3.TransformNormal(e,A).subtract(R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[3].map(e=>math_vector_Vector3.TransformNormal(e,A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let M=new math_vector_Vector3(0,a/2,0),I=math_vector_Matrix.RotationX(Math.PI/2);p=p.concat(x[4].map(e=>math_vector_Vector3.TransformNormal(e,I).add(M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[4].map(e=>math_vector_Vector3.TransformNormal(e,I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let D=math_vector_Matrix.RotationX(-Math.PI/2);p=p.concat(x[5].map(e=>math_vector_Vector3.TransformNormal(e,D).subtract(M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(b[5].map(e=>math_vector_Vector3.TransformNormal(e,D)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),mesh_vertexData_VertexData._ComputeSides(u,p,g,f,m);let O=new mesh_vertexData_VertexData;if(O.indices=g,O.positions=p,O.normals=f,O.uvs=m,i){let e=u===mesh_vertexData_VertexData.DOUBLESIDE?v.concat(v):v;O.colors=e}return O}function CreateTorusKnotVertexData(e){let t,i;let r=[],s=[],a=[],n=[],o=e.radius||2,l=e.tube||.5,h=e.radialSegments||32,c=e.tubularSegments||32,u=e.p||2,d=e.q||3,_=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,getPos=e=>{let t=d/u*e,i=Math.cos(t),r=o*Math.sin(t)*.5;return new math_vector_Vector3(o*(2+i)*.5*Math.cos(e),o*(2+i)*Math.sin(e)*.5,r)};for(t=0;t<=h;t++){let e=t%h,r=e/h*2*u*Math.PI,a=getPos(r),o=getPos(r+.01),d=o.subtract(a),_=o.add(a),p=math_vector_Vector3.Cross(d,_);for(_=math_vector_Vector3.Cross(p,d),p.normalize(),_.normalize(),i=0;iboxBuilder_CreateBox(e,{size:t,sideOrientation:s,updatable:r},i),mesh_vertexData_VertexData.CreateSphere=CreateSphereVertexData,mesh_Mesh.CreateSphere=(e,t,i,r,s,a)=>sphereBuilder_CreateSphere(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:a,updatable:s},r),mesh_Mesh.CreateCapsule=(e,t,i)=>capsuleBuilder_CreateCapsule(e,t,i),mesh_vertexData_VertexData.CreateCapsule=CreateCapsuleVertexData,mesh_vertexData_VertexData.CreateRibbon=CreateRibbonVertexData,mesh_Mesh.CreateRibbon=(e,t,i=!1,r,s,a,n=!1,o,l)=>CreateRibbon(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:n,sideOrientation:o,instance:l},a),mesh_vertexData_VertexData.CreateDisc=CreateDiscVertexData,mesh_Mesh.CreateDisc=(e,t,i,r=null,s,a)=>discBuilder_CreateDisc(e,{radius:t,tessellation:i,sideOrientation:a,updatable:s},r),mesh_vertexData_VertexData.CreateTiledPlane=CreateTiledPlaneVertexData,mesh_vertexData_VertexData.CreateTiledBox=CreateTiledBoxVertexData,mesh_vertexData_VertexData.CreateTorusKnot=CreateTorusKnotVertexData,mesh_Mesh.CreateTorusKnot=(e,t,i,r,s,a,n,o,l,h)=>CreateTorusKnot(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:a,q:n,sideOrientation:h,updatable:l},o);let rb={effect:null,subMesh:null};let shaderMaterial_ShaderMaterial=class shaderMaterial_ShaderMaterial extends PushMaterial{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new math_vector_Matrix,this._cachedWorldViewProjectionMatrix=new math_vector_Matrix,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},r)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return -1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);let i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var r,s,a;let n=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){if(n){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{let e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}}let o=this.getScene(),l=o.getEngine(),h=[],c=[],u=new EffectFallbacks,d=this._shaderPath,_=this._options.uniforms,p=this._options.uniformBuffers,f=this._options.samplers;l.getCaps().multiview&&o.activeCamera&&o.activeCamera.outputRenderTarget&&o.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,h.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e4&&(c.push(buffer_VertexBuffer.MatricesIndicesExtraKind),c.push(buffer_VertexBuffer.MatricesWeightsExtraKind));let t=e.skeleton;h.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),u.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(h.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(h.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else h.push("#define NUM_BONE_INFLUENCERS 0");let m=0,g=e?e.morphTargetManager:null;if(g){let e=g.supportsUVs&&-1!==h.indexOf("#define UV1"),t=g.supportsTangents&&-1!==h.indexOf("#define TANGENT"),i=g.supportsNormals&&-1!==h.indexOf("#define NORMAL");m=g.numInfluencers,e&&h.push("#define MORPHTARGETS_UV"),t&&h.push("#define MORPHTARGETS_TANGENT"),i&&h.push("#define MORPHTARGETS_NORMAL"),m>0&&h.push("#define MORPHTARGETS"),g.isUsingTextureForTargets&&(h.push("#define MORPHTARGETS_TEXTURE"),-1===this._options.uniforms.indexOf("morphTargetTextureIndices")&&this._options.uniforms.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),h.push("#define NUM_MORPH_INFLUENCERS "+m);for(let r=0;r0&&((_=_.slice()).push("morphTargetInfluences"),_.push("morphTargetTextureInfo"),_.push("morphTargetTextureIndices"))}else h.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(h.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===this._options.uniforms.indexOf("bakedVertexAnimationSettings")&&this._options.uniforms.push("bakedVertexAnimationSettings"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTime")&&this._options.uniforms.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),MaterialHelper.PrepareAttributesForBakedVertexAnimation(c,e,h)}for(let e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&h.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&(addClipPlaneUniforms(_),prepareStringDefinesForClipPlanes(this,o,h)),this.customShaderNameResolve&&(_=_.slice(),p=p.slice(),f=f.slice(),d=this.customShaderNameResolve(d,_,p,f,h,c));let v=n?i._getDrawWrapper():this._drawWrapper,x=null!==(r=null==v?void 0:v.effect)&&void 0!==r?r:null,b=null!==(s=null==v?void 0:v.defines)&&void 0!==s?s:null,T=h.join("\n"),S=x;return b!==T&&(S=l.createEffect(d,{attributes:c,uniformsNames:_,uniformBuffersNames:p,samplers:f,defines:T,fallbacks:u,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},l),n?i.setEffect(S,T,this._materialContext):v&&v.setEffect(S,T),this._onEffectCreatedObservable&&(rb.effect=S,rb.subMesh=null!==(a=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==a?a:null,this._onEffectCreatedObservable.notifyObservers(rb))),S._wasPreviouslyUsingInstances=!!t,!!(null==S?void 0:S.isReady())&&(x!==S&&o.resetCachedMaterial(),S._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){let i=this.getScene(),r=null!=t?t:this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var r;this.bind(e,t,null===(r=i._drawWrapperOverride)||void 0===r?void 0:r.effect,i)}bind(e,t,i,r){var s;let a=r&&this._storeEffectOnSubMeshes,n=null!=i?i:a?r.effect:this.getEffect();if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e,i);let o=this._options.uniformBuffers,l=!1;if(n&&o&&o.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let i=0;i0&&MaterialHelper.BindMorphTargetParameters(t,n);let i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(n,!!n._wasPreviouslyUsingInstances))}this._afterBind(t,n)}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._textures)e.push(this._textures[t]);for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;tnew shaderMaterial_ShaderMaterial(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);for(let i in t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach(e=>{let t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))}),this.stencil.copyTo(t.stencil),this._textures)t.setTexture(i,this._textures[i]);for(let e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(let e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(let e in this._ints)t.setInt(e,this._ints[e]);for(let e in this._uints)t.setUInt(e,this._uints[e]);for(let e in this._floats)t.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(let e in this._colors3)t.setColor3(e,this._colors3[e]);for(let e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(let e in this._colors4)t.setColor4(e,this._colors4[e]);for(let e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(let e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(let e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(let e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(let e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(let e in this._matrices)t.setMatrix(e,this._matrices[e]);for(let e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(let e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(let e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(let e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(let e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(let e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(let e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(let e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(let e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){let t=this._textureArrays[e];for(let e=0;enew shaderMaterial_ShaderMaterial(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,texture_Texture.Parse(e.textures[r],t,i));for(r in e.textureArrays){let a=e.textureArrays[r],n=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>math_color_Color3.FromArray(e));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,math_color_Color4.FromArray(e.colors4[r]));for(r in e.colors4Arrays){let t=e.colors4Arrays[r].reduce((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>math_color_Color4.FromArray(e));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,math_vector_Vector2.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,math_vector_Vector3.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,math_vector_Vector4.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,math_vector_Quaternion.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,math_vector_Matrix.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,a)=>{let n=new webRequest_WebRequest;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let t=JSON.parse(n.responseText),a=this.Parse(t,i||engineStore_EngineStore.LastCreatedScene,r);e&&(a.name=e),s(a)}else a("Unable to load the ShaderMaterial")}}),n.open("GET",t),n.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,s)=>{let a=new webRequest_WebRequest;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let s=JSON.parse(JSON.parse(a.responseText).jsonPayload),n=JSON.parse(s.shaderMaterial),o=this.Parse(n,t||engineStore_EngineStore.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};shaderMaterial_ShaderMaterial.SnippetUrl="https://snippet.babylonjs.com",shaderMaterial_ShaderMaterial.CreateFromSnippetAsync=shaderMaterial_ShaderMaterial.ParseFromSnippetAsync,h["BABYLON.ShaderMaterial"]=shaderMaterial_ShaderMaterial;let rT=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -#define VERTEXCOLOR -varying vec4 vColor; -#else -uniform vec4 color; -#endif -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -gl_FragColor=vColor; -#else -gl_FragColor=color; -#endif -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.colorPixelShader=rT;let rS=`attribute vec3 position; -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include -#include -#include -uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#include -#include -#include -vec4 worldPos=finalWorld*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#include -#include -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.colorVertexShader=rS,mesh_Mesh._LinesMeshParser=(e,t)=>LinesMesh.Parse(e,t);let LinesMesh=class LinesMesh extends mesh_Mesh{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,r=null,s,a,n,o){super(e,t,i,r,s),this.useVertexColor=a,this.useVertexAlpha=n,this.color=new math_color_Color3(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let l={attributes:[buffer_VertexBuffer.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===n?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),a?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(buffer_VertexBuffer.ColorKind)):(l.uniforms.push("color"),this._color4=new math_color_Color4),o?this.material=o:(this.material=new shaderMaterial_ShaderMaterial("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=material_Material.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){let{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(material_Material.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(material_Material.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new LinesMesh(e,this.getScene(),t,this,i)}createInstance(e){let t=new InstancedLinesMesh(e,this);if(this.instancedBuffers)for(let e in t.instancedBuffers={},this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e];return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){let i=new LinesMesh(e.name,t);return i.color=math_color_Color3.FromArray(e.color),i.alpha=e.alpha,i}};let InstancedLinesMesh=class InstancedLinesMesh extends instancedMesh_InstancedMesh{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}};function CreateLineSystemVertexData(e){let t=[],i=[],r=e.lines,s=e.colors,a=[],n=0;for(let e=0;e0&&(t.push(n-1),t.push(n)),n++}}let o=new mesh_vertexData_VertexData;return o.indices=t,o.positions=i,s&&(o.colors=a),o}function CreateDashedLinesVertexData(e){let t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,a=[],n=[],o=math_vector_Vector3.Zero(),l=0,h=0,c=0,u=0,d=0,_=0,p=0;for(p=0;p{let t=math_vector_Vector3.Zero(),i=e.length/6,a=0,n=0,o=0,l=0,h=0,c=0,u=0,d=0;for(u=0;ulinesBuilder_CreateLines(e,{points:t,updatable:r,instance:s},i),mesh_Mesh.CreateDashedLines=(e,t,i,r,s,a=null,n,o)=>CreateDashedLines(e,{points:t,dashSize:i,gapSize:r,dashNb:s,updatable:n,instance:o},a);let IndexedVector2=class IndexedVector2 extends math_vector_Vector2{constructor(e,t){super(e.x,e.y),this.index=t}};let PolygonPoints=class PolygonPoints{constructor(){this.elements=[]}add(e){let t=[];return e.forEach(e=>{let i=new IndexedVector2(e,this.elements.length);t.push(i),this.elements.push(i)}),t}computeBounds(){let e=new math_vector_Vector2(this.elements[0].x,this.elements[0].y),t=new math_vector_Vector2(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}};let PolygonMeshBuilder=class PolygonMeshBuilder{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new PolygonPoints,this._outlinepoints=new PolygonPoints,this._holes=[],this._epoints=[],this._eholes=[],this.bjsEarcut=r,this._name=e,this._scene=i||engineStore_EngineStore.LastCreatedScene,s=t instanceof math_path_Path2?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&logger_Logger.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new PolygonPoints;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){let r=new mesh_Mesh(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(buffer_VertexBuffer.PositionKind,s.positions,e),r.setVerticesData(buffer_VertexBuffer.NormalKind,s.normals,e),r.setVerticesData(buffer_VertexBuffer.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new mesh_vertexData_VertexData,r=[],s=[],a=[],n=this._points.computeBounds();this._points.elements.forEach(e=>{r.push(0,1,0),s.push(e.x,0,e.y),a.push((e.x-n.min.x)/n.width,(e.y-n.min.y)/n.height)});let o=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){let i=s.length/3;this._points.elements.forEach(t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),a.push(1-(t.x-n.min.x)/n.width,1-(t.y-n.min.y)/n.height)});let l=o.length;for(let e=0;e{this._addSide(s,r,a,o,n,i,e,!0,t)})}return i.indices=o,i.positions=s,i.normals=r,i.uvs=a,i}_addSide(e,t,i,r,s,a,n,o,l){let h=e.length/3,c=0;for(let u=0;ul?S<-.999?new math_vector_Vector3(d.x,0,d.y).subtract(new math_vector_Vector3(_.x,0,_.y)).normalize():g.add(m).normalize():x;let C=math_vector_Vector3.Dot(v,m);T=C>l?C<-.999?new math_vector_Vector3(_.x,0,_.y).subtract(new math_vector_Vector3(d.x,0,d.y)).normalize():v.add(m).normalize():x,i.push(c/s.width,0),i.push(c/s.width,1),c+=m.length(),i.push(c/s.width,0),i.push(c/s.width,1),t.push(b.x,b.y,b.z),t.push(b.x,b.y,b.z),t.push(T.x,T.y,T.z),t.push(T.x,T.y,T.z),o?(r.push(h),r.push(h+2),r.push(h+1),r.push(h+1),r.push(h+2),r.push(h+3)):(r.push(h),r.push(h+1),r.push(h+2),r.push(h+1),r.push(h+3),r.push(h+2)),h+=4}}};function CreatePolygonVertexData(e,t,i,r,s,a,n){let o=i||[,,,],l=[],h=n||!1;for(let e=0;e<3;e++)void 0===o[e]&&(o[e]=new math_vector_Vector4(0,0,1,1)),r&&void 0===r[e]&&(r[e]=new math_color_Color4(1,1,1,1));let c=e.getVerticesData(buffer_VertexBuffer.PositionKind),u=e.getVerticesData(buffer_VertexBuffer.NormalKind),d=e.getVerticesData(buffer_VertexBuffer.UVKind),_=e.getIndices(),p=c.length/9,f=0,m=0,g=0,v=0,x=[0];if(h)for(let e=p;eMath.abs(u[e+1])&&(T=1),.001>Math.abs(u[e+1]-1)&&(T=0),.001>Math.abs(u[e+1]+1)&&(T=2),b=e/3,1===T?((f=b-p)%4<1.5?h?d[2*b]=o[T].x+(o[T].z-o[T].x)*x[Math.floor(f/4)]/v:d[2*b]=o[T].x:h?d[2*b]=o[T].x+(o[T].z-o[T].x)*x[Math.floor(f/4)+1]/v:d[2*b]=o[T].z,f%2==0?d[2*b+1]=CompatibilityOptions.UseOpenGLOrientationForUV?1-o[T].w:o[T].w:d[2*b+1]=CompatibilityOptions.UseOpenGLOrientationForUV?1-o[T].y:o[T].y):(d[2*b]=(1-d[2*b])*o[T].x+d[2*b]*o[T].z,d[2*b+1]=(1-d[2*b+1])*o[T].y+d[2*b+1]*o[T].w,CompatibilityOptions.UseOpenGLOrientationForUV&&(d[2*b+1]=1-d[2*b+1])),r&&l.push(r[T].r,r[T].g,r[T].b,r[T].a);mesh_vertexData_VertexData._ComputeSides(t,c,_,u,d,s,a);let S=new mesh_vertexData_VertexData;if(S.indices=_,S.positions=c,S.normals=u,S.uvs=d,r){let e=t===mesh_vertexData_VertexData.DOUBLESIDE?l.concat(l):l;S.colors=e}return S}function CreatePolygon(e,t,i=null,r=earcut){t.sideOrientation=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation);let s=t.shape,a=t.holes||[],n=t.depth||0,o=t.smoothingThreshold||2,l=[],h=[];for(let e=0;e1),n=t.rotationFunction||(()=>0),o=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||mesh_Mesh.NO_CAP,c=t.updatable,u=t.firstNormal||null,d=t.adjustFrame||!1,_=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),p=t.instance,f=t.invertUV||!1;return _ExtrudeShapeGeneric(e,s,r,null,null,a,n,o,l,h,!0,i,!!c,_,p||null,f,t.frontUVs||null,t.backUVs||null,u,d)}function _ExtrudeShapeGeneric(e,t,i,r,s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x){let b,T;let extrusionPathArray=(e,t,i,r,s,a,n,o,l,h,c)=>{let u=i.getTangents(),d=i.getNormals(),_=i.getBinormals(),p=i.getDistances();if(c){for(let e=0;e0){let t=u[e-1];0>math_vector_Vector3.Dot(t,u[e])&&u[e].scaleInPlace(-1),t=d[e-1],0>math_vector_Vector3.Dot(t,d[e])&&d[e].scaleInPlace(-1),t=_[e-1],0>math_vector_Vector3.Dot(t,_[e])&&_[e].scaleInPlace(-1)}}let f=0,m=h&&o?o:()=>null!==a?a:0,g=h&&n?n:()=>null!==s?s:1,v=l===mesh_Mesh.NO_CAP||l===mesh_Mesh.CAP_END?0:2,x=math_vector_TmpVectors.Matrix[0];for(let i=0;i{let t;let i=[],r=math_vector_Vector3.Zero();for(t=0;t3?0:h,c,x);let S=CreateRibbon(e,{pathArray:T,closeArray:o,closePath:l,updatable:d,sideOrientation:_,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},u);return S._creationDataStorage.pathArray=T,S._creationDataStorage.path3D=b,S._creationDataStorage.cap=h,S}function CreateLathe(e,t,i=null){let r,s;let a=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,n=void 0===t.closed||t.closed,o=t.shape,l=t.radius||1,h=t.tessellation||64,c=t.clip||0,u=t.updatable,d=mesh_Mesh._GetDefaultSideOrientation(t.sideOrientation),_=t.cap||mesh_Mesh.NO_CAP,p=[],f=t.invertUV||!1,m=0,g=0,v=2*Math.PI/h*a;for(m=0;m<=h-c;m++){for(s=[],(_==mesh_Mesh.CAP_START||_==mesh_Mesh.CAP_ALL)&&(s.push(new math_vector_Vector3(0,o[0].y,0)),s.push(new math_vector_Vector3(Math.cos(m*v)*o[0].x*l,o[0].y,Math.sin(m*v)*o[0].x*l))),g=0;g1)?1:t.arc||1;let tubePathArray=(e,t,i,r,s,a,n,o)=>{let l,h,c,u;let d=t.getTangents(),_=t.getNormals(),p=t.getDistances(),f=2*Math.PI/s*o,m=a||(()=>r),g=math_vector_TmpVectors.Matrix[0],v=n===mesh_Mesh.NO_CAP||n===mesh_Mesh.CAP_END?0:2;for(let t=0;t{let r=[];for(let s=0;s3?0:c,t.arc);let p=CreateRibbon(e,{pathArray:s,closePath:!0,closeArray:!1,updatable:d,sideOrientation:_,invertUV:u,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return p._creationDataStorage.pathArray=s,p._creationDataStorage.path3D=r,p._creationDataStorage.tessellation=l,p._creationDataStorage.cap=c,p._creationDataStorage.arc=t.arc,p._creationDataStorage.radius=o,p}function CreatePolyhedronVertexData(e){let t,i,r,s,a,n;let o=[];o[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},o[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},o[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},o[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},o[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},o[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},o[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},o[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},o[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},o[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},o[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},o[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},o[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},o[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},o[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};let l=e.type&&(e.type<0||e.type>=o.length)?0:e.type||0,h=e.size,c=e.sizeX||h||1,u=e.sizeY||h||1,d=e.sizeZ||h||1,_=e.custom||o[l],p=_.face.length,f=e.faceUV||Array(p),m=e.faceColors,g=void 0===e.flat||e.flat,v=0===e.sideOrientation?0:e.sideOrientation||mesh_vertexData_VertexData.DEFAULTSIDE,x=[],b=[],T=[],S=[],C=[],E=0,y=0,R=[],P=0,A=0;if(g)for(A=0;ACreatePolygon(e,{shape:t,holes:r,updatable:s,sideOrientation:a},i,n),mesh_Mesh.ExtrudePolygon=(e,t,i,r,s,a,n,o=earcut)=>ExtrudePolygon(e,{shape:t,holes:s,depth:i,updatable:a,sideOrientation:n},r,o),mesh_Mesh.ExtrudeShape=(e,t,i,r,s,a,n=null,o,l,h)=>{let c={shape:t,path:i,scale:r,rotation:s,cap:0===a?0:a||mesh_Mesh.NO_CAP,sideOrientation:l,instance:h,updatable:o};return ExtrudeShape(e,c,n)},mesh_Mesh.ExtrudeShapeCustom=(e,t,i,r,s,a,n,o,l,h,c,u)=>{let d={shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:a,ribbonClosePath:n,cap:0===o?0:o||mesh_Mesh.NO_CAP,sideOrientation:c,instance:u,updatable:h};return ExtrudeShapeCustom(e,d,l)},mesh_Mesh.CreateLathe=(e,t,i,r,s,a,n)=>CreateLathe(e,{shape:t,radius:i,tessellation:r,sideOrientation:n,updatable:a},s),mesh_Mesh.CreateTube=(e,t,i,r,s,a,n,o,l,h)=>CreateTube(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:a,updatable:o,sideOrientation:l,instance:h},n),mesh_vertexData_VertexData.CreatePolyhedron=CreatePolyhedronVertexData,mesh_Mesh.CreatePolyhedron=(e,t,i)=>polyhedronBuilder_CreatePolyhedron(e,t,i);let rC=new math_vector_Vector3(1,0,0),rE=new math_vector_Vector3(-1,0,0),ry=new math_vector_Vector3(0,1,0),rR=new math_vector_Vector3(0,-1,0),rP=new math_vector_Vector3(0,0,1),rA=new math_vector_Vector3(0,0,-1);let DecalVertex=class DecalVertex{constructor(e=math_vector_Vector3.Zero(),t=math_vector_Vector3.Up(),i=math_vector_Vector2.Zero(),r=0,s=0,a=null,n=null,o=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=a,this.localNormalOverride=n,this.matrixIndicesOverride=o,this.matrixWeightsOverride=l}clone(){var e,t,i,r;return new DecalVertex(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,null===(e=this.localPositionOverride)||void 0===e?void 0:e.slice(),null===(t=this.localNormalOverride)||void 0===t?void 0:t.slice(),null===(i=this.matrixIndicesOverride)||void 0===i?void 0:i.slice(),null===(r=this.matrixWeightsOverride)||void 0===r?void 0:r.slice())}};function CreateDecal(e,t,i){var r,s,a,n;let o=!!t.skeleton,l=i.localMode||o,h=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,c=t.getIndices(),u=o?t.getPositionData(!0,!0):t.getVerticesData(buffer_VertexBuffer.PositionKind),d=o?t.getNormalsData(!0,!0):t.getVerticesData(buffer_VertexBuffer.NormalKind),_=l?o?t.getVerticesData(buffer_VertexBuffer.PositionKind):u:null,p=l?o?t.getVerticesData(buffer_VertexBuffer.NormalKind):d:null,f=t.getVerticesData(buffer_VertexBuffer.UVKind),m=o?t.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind):null,g=o?t.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind):null,v=o?t.getVerticesData(buffer_VertexBuffer.MatricesIndicesExtraKind):null,x=o?t.getVerticesData(buffer_VertexBuffer.MatricesWeightsExtraKind):null,b=i.position||math_vector_Vector3.Zero(),T=i.normal||math_vector_Vector3.Up(),S=i.size||math_vector_Vector3.One(),C=i.angle||0;if(!T){let e=new math_vector_Vector3(0,0,1),i=t.getScene().activeCamera,r=math_vector_Vector3.TransformCoordinates(e,i.getWorldMatrix());T=i.globalPosition.subtract(r)}let E=-Math.atan2(T.z,T.x)-Math.PI/2,y=Math.sqrt(T.x*T.x+T.z*T.z),R=Math.atan2(T.y,y),P=new mesh_vertexData_VertexData;P.indices=[],P.positions=[],P.normals=[],P.uvs=[],P.matricesIndices=o?[]:null,P.matricesWeights=o?[]:null,P.matricesIndicesExtra=v?[]:null,P.matricesWeightsExtra=x?[]:null;let A=0,extractDecalVector3=(e,t)=>{let r=new DecalVertex;if(!c||!u||!d)return r;let s=c[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new math_vector_Vector3(u[3*s],u[3*s+1],u[3*s+2]),math_vector_Vector3.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new math_vector_Vector3(d[3*s],d[3*s+1],d[3*s+2]),math_vector_Vector3.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&f){let e=f[2*s+1];r.uv=new math_vector_Vector2(f[2*s],CompatibilityOptions.UseOpenGLOrientationForUV?1-e:e)}return r},M=[0,0,0,0],clip=(e,t)=>{if(0===e.length)return e;let i=.5*Math.abs(math_vector_Vector3.Dot(S,t)),indexOf=(e,t,i,r)=>{for(let s=0;s{var s,a,n,o,l,h,c,u,d,f,v,x,b,T,S,C;let E=math_vector_Vector3.GetClipFactor(e.position,r.position,t,i),y=M,R=M;if(m&&g){let t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(s=e.matrixIndicesOverride)&&void 0!==s?s:m,l=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:g,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,c=null!==(n=r.matrixIndicesOverride)&&void 0!==n?n:m,u=null!==(o=r.matrixWeightsOverride)&&void 0!==o?o:g;y=[0,0,0,0],R=[0,0,0,0];let d=0;for(let e=0;e<4;++e)if(l[t+e]>0){let r=indexOf(c,i[t+e],h,4);y[d]=i[t+e],R[d]=math_scalar_Scalar.Lerp(l[t+e],r>=0?u[r]:0,E),d++}for(let e=0;e<4&&d<4;++e){let r=c[h+e];-1===indexOf(i,r,t,4)&&(y[d]=r,R[d]=math_scalar_Scalar.Lerp(0,u[h+e],E),d++)}let _=R[0]+R[1]+R[2]+R[3];R[0]/=_,R[1]/=_,R[2]/=_,R[3]/=_}let P=e.localPositionOverride?e.localPositionOverride[0]:null!==(l=null==_?void 0:_[e.vertexIdx])&&void 0!==l?l:0,A=e.localPositionOverride?e.localPositionOverride[1]:null!==(h=null==_?void 0:_[e.vertexIdx+1])&&void 0!==h?h:0,I=e.localPositionOverride?e.localPositionOverride[2]:null!==(c=null==_?void 0:_[e.vertexIdx+2])&&void 0!==c?c:0,D=r.localPositionOverride?r.localPositionOverride[0]:null!==(u=null==_?void 0:_[r.vertexIdx])&&void 0!==u?u:0,O=r.localPositionOverride?r.localPositionOverride[1]:null!==(d=null==_?void 0:_[r.vertexIdx+1])&&void 0!==d?d:0,B=r.localPositionOverride?r.localPositionOverride[2]:null!==(f=null==_?void 0:_[r.vertexIdx+2])&&void 0!==f?f:0,N=e.localNormalOverride?e.localNormalOverride[0]:null!==(v=null==p?void 0:p[e.vertexIdx])&&void 0!==v?v:0,F=e.localNormalOverride?e.localNormalOverride[1]:null!==(x=null==p?void 0:p[e.vertexIdx+1])&&void 0!==x?x:0,w=e.localNormalOverride?e.localNormalOverride[2]:null!==(b=null==p?void 0:p[e.vertexIdx+2])&&void 0!==b?b:0,L=r.localNormalOverride?r.localNormalOverride[0]:null!==(T=null==p?void 0:p[r.vertexIdx])&&void 0!==T?T:0,V=r.localNormalOverride?r.localNormalOverride[1]:null!==(S=null==p?void 0:p[r.vertexIdx+1])&&void 0!==S?S:0,U=r.localNormalOverride?r.localNormalOverride[2]:null!==(C=null==p?void 0:p[r.vertexIdx+2])&&void 0!==C?C:0,k=N+(L-N)*E,G=F+(V-F)*E,z=w+(U-w)*E,W=Math.sqrt(k*k+G*G+z*z);return new DecalVertex(math_vector_Vector3.Lerp(e.position,r.position,E),math_vector_Vector3.Lerp(e.normal,r.normal,E).normalize(),math_vector_Vector2.Lerp(e.uv,r.uv,E),-1,-1,_?[P+(D-P)*E,A+(O-A)*E,I+(B-I)*E]:null,p?[k/W,G/W,z/W]:null,y,R)},r=null;e.length>3&&(r=[]);for(let s=0;s0,_=c>0,p=u>0;switch((d?1:0)+(_?1:0)+(p?1:0)){case 0:e.length>3?(r.push(e[s]),r.push(e[s+1]),r.push(e[s+2])):r=e;break;case 1:if(r=null!=r?r:[],d&&(a=e[s+1],n=e[s+2],o=clipVertices(e[s],a),l=clipVertices(e[s],n)),_){a=e[s],n=e[s+2],o=clipVertices(e[s+1],a),l=clipVertices(e[s+1],n),r.push(o),r.push(n.clone()),r.push(a.clone()),r.push(n.clone()),r.push(o.clone()),r.push(l);break}p&&(a=e[s],n=e[s+1],o=clipVertices(e[s+2],a),l=clipVertices(e[s+2],n)),a&&n&&o&&l&&(r.push(a.clone()),r.push(n.clone()),r.push(o),r.push(l),r.push(o.clone()),r.push(n.clone()));break;case 2:r=null!=r?r:[],d||(n=clipVertices(a=e[s].clone(),e[s+1]),o=clipVertices(a,e[s+2]),r.push(a),r.push(n),r.push(o)),_||(n=clipVertices(a=e[s+1].clone(),e[s+2]),o=clipVertices(a,e[s]),r.push(a),r.push(n),r.push(o)),p||(n=clipVertices(a=e[s+2].clone(),e[s]),o=clipVertices(a,e[s+1]),r.push(a),r.push(n),r.push(o))}}return r},I=t instanceof mesh_Mesh?t:null,D=null==I?void 0:I._thinInstanceDataStorage.matrixData,O=(null==I?void 0:I.thinInstanceCount)||1,B=math_vector_TmpVectors.Matrix[0];B.copyFrom(math_vector_Matrix.IdentityReadOnly);for(let e=0;e=-t[0].normal.z&&0>=-t[1].normal.z&&0>=-t[2].normal.z)&&(t=clip(t,rC))&&(t=clip(t,rE))&&(t=clip(t,ry))&&(t=clip(t,rR))&&(t=clip(t,rP))&&(t=clip(t,rA)))for(let e=0;eCreateDecal(e,t,{position:i,normal:r,size:s,angle:a});let _IsoVector=class _IsoVector{constructor(e=0,t=0){this.x=e,this.y=t,e!==Math.floor(e)&&logger_Logger.Warn("x is not an integer, floor(x) used"),t!==Math.floor(t)&&logger_Logger.Warn("y is not an integer, floor(y) used")}clone(){return new _IsoVector(this.x,this.y)}rotate60About(e){let t=this.x;return this.x=e.x+e.y-this.y,this.y=t+this.y-e.x,this}rotateNeg60About(e){let t=this.x;return this.x=t+this.y-e.y,this.y=e.x+e.y-t,this}rotate120(e,t){e!==Math.floor(e)&&logger_Logger.Warn("m not an integer only floor(m) used"),t!==Math.floor(t)&&logger_Logger.Warn("n not an integer only floor(n) used");let i=this.x;return this.x=e-i-this.y,this.y=t+i,this}rotateNeg120(e,t){e!==Math.floor(e)&&logger_Logger.Warn("m is not an integer, floor(m) used"),t!==Math.floor(t)&&logger_Logger.Warn("n is not an integer, floor(n) used");let i=this.x;return this.x=this.y-t,this.y=e+t-i-this.y,this}toCartesianOrigin(e,t){let i=math_vector_Vector3.Zero();return i.x=e.x+2*this.x*t+this.y*t,i.y=e.y+Math.sqrt(3)*this.y*t,i}static Zero(){return new _IsoVector(0,0)}};let PolyhedronData=class PolyhedronData{constructor(e,t,i,r){this.name=e,this.category=t,this.vertex=i,this.face=r}};let GeodesicData=class GeodesicData extends PolyhedronData{innerToData(e,t){for(let i=0;it.vecToidx[e+i]))}mapABOBtoDATA(e,t){let i=t.IDATA.edgematch[e][0];for(let r=0;r-1?i[e][1]>0&&t[i[e][0]].push([e,i[e][1]]):t[12].push([e,i[e][0]]);let r=[];for(let e=0;e<12;e++)r[e]=e;let s=12;for(let e=0;e<12;e++){t[e].sort((e,t)=>e[1]-t[1]);for(let i=0;ie[3]-t[3]);for(let e=0;e0;)s=t[o],this.face[s].indexOf(n)>-1?(a=(this.face[s].indexOf(n)+1)%3,n=this.face[s][a],i.push(n),r.push(s),t.splice(o,1),o=0):o++;return this.adjacentFaces.push(i),r}toGoldbergPolyhedronData(){let e=new PolyhedronData("GeoDual","Goldberg",[],[]);e.name="GD dual";let t=this.vertex.length,i=Array(t);for(let e=0;e{r=0,s=0,a=0,n=this.face[t];for(let e=0;e<3;e++)o=this.vertex[n[e]],r+=o[0],s+=o[1],a+=o[2];e.vertex[t]=[r/3,s/3,a/3]});return e}static BuildGeodesicData(e){let t=new GeodesicData("Geodesic-m-n","Geodesic",[[0,o,-1],[-o,1,0],[-1,0,-o],[1,0,-o],[o,1,0],[0,o,1],[-1,0,o],[-o,-1,0],[0,-o,-1],[o,-1,0],[1,0,o],[0,-o,1]],[]);e.setIndices(),e.calcCoeffs(),e.createInnerFacets(),e.edgeVecsABOB(),e.mapABOBtoOBOA(),e.mapABOBtoBAOA();for(let i=0;iGoldbergMesh.Parse(e,t);let GoldbergMesh=class GoldbergMesh extends mesh_Mesh{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(logger_Logger.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(logger_Logger.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(logger_Logger.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(r=1),c.push(r,s);for(let e=0;e<6;e++)r=o.x+l*Math.cos(h+e*Math.PI/3),s=o.y+l*Math.sin(h+e*Math.PI/3),r<0&&(r=0),r>1&&(r=1),u.push(r,s);for(let e=a;emath_color_Color4.FromArray(e)),i.faceCenters=i.faceCenters.map(e=>math_vector_Vector3.FromArray(e)),i.faceZaxis=i.faceZaxis.map(e=>math_vector_Vector3.FromArray(e)),i.faceXaxis=i.faceXaxis.map(e=>math_vector_Vector3.FromArray(e)),i.faceYaxis=i.faceYaxis.map(e=>math_vector_Vector3.FromArray(e));let r=new GoldbergMesh(e.name,t);return r.goldbergData=i,r}};let ShapePath=class ShapePath{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new math_path_Path2(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,a){this._currentPath.addBezierCurveTo(e,t,i,r,s,a,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}};function CreateShapePath(e,t,i,r,s,a){let n=a.glyphs[e]||a.glyphs["?"];if(!n)return null;let o=new ShapePath(s);if(n.o){let e=n.o.split(" ");for(let s=0,a=e.length;s - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include - - #include - - varying vec3 vColor; - - uniform vec3 colorBase; - uniform vec3 colorZero; - uniform vec3 colorQuarter; - uniform vec3 colorHalf; - uniform vec3 colorFull; - - uniform float targetBoneIndex; - - void main() { - vec3 positionUpdated = position; - - #include - #include - #include - - vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); - - vec3 color = colorBase; - float totalWeight = 0.; - if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ - totalWeight += matricesWeights[0]; - } - if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ - totalWeight += matricesWeights[1]; - } - if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ - totalWeight += matricesWeights[2]; - } - if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ - totalWeight += matricesWeights[3]; - } - - color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); - color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); - color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); - color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); - vColor = color; - - gl_Position = projection * view * worldPos; - }`,effect_Effect.ShadersStore["boneWeights:"+l.name+"FragmentShader"]=` - precision highp float; - varying vec3 vPosition; - - varying vec3 vColor; - - void main() { - vec4 color = vec4(vColor, 1.0); - gl_FragColor = color; - } - `;let f=new shaderMaterial_ShaderMaterial("boneWeight:"+l.name,t,{vertex:"boneWeights:"+l.name,fragment:"boneWeights:"+l.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return f.setColor3("colorBase",h),f.setColor3("colorZero",c),f.setColor3("colorQuarter",u),f.setColor3("colorHalf",d),f.setColor3("colorFull",_),f.setFloat("targetBoneIndex",p),f.getClassName=()=>"BoneWeightShader",f.transparencyMode=material_Material.MATERIAL_OPAQUE,f}static CreateSkeletonMapShader(e,t){var i;let r=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new math_color_Color3(1,.38,.18),location:0},{color:new math_color_Color3(.59,.18,1),location:.2},{color:new math_color_Color3(.59,1,.18),location:.4},{color:new math_color_Color3(1,.87,.17),location:.6},{color:new math_color_Color3(1,.17,.42),location:.8},{color:new math_color_Color3(.17,.68,1),location:1}],a=r.bones.length+1,n=SkeletonViewer._CreateBoneMapColorBuffer(a,s,t),o=new shaderMaterial_ShaderMaterial("boneWeights:"+r.name,t,{vertexSource:`precision highp float; - - attribute vec3 position; - attribute vec2 uv; - - uniform mat4 view; - uniform mat4 projection; - uniform mat4 worldViewProjection; - uniform float colorMap[`+4*r.bones.length+`]; - - #include - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include - #include - - varying vec3 vColor; - - void main() { - vec3 positionUpdated = position; - - #include - #include - #include - - vec3 color = vec3(0.); - bool first = true; - - for (int i = 0; i < 4; i++) { - int boneIdx = int(matricesIndices[i]); - float boneWgt = matricesWeights[i]; - - vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); - - if (boneWgt > 0.) { - if (first) { - first = false; - color = c; - } else { - color = mix(color, c, boneWgt); - } - } - } - - vColor = color; - - vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); - - gl_Position = projection * view * worldPos; - }`,fragmentSource:` - precision highp float; - varying vec3 vColor; - - void main() { - vec4 color = vec4( vColor, 1.0 ); - gl_FragColor = color; - } - `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",n),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=material_Material.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){let r=new DynamicTexture("temp",{width:e,height:1},i,!1),s=r.getContext(),a=s.createLinearGradient(0,0,e,0);t.forEach(e=>{a.addColorStop(e.location,e.color.toHexString())}),s.fillStyle=a,s.fillRect(0,0,e,1),r.update();let n=[],o=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eSkeletonViewer.DISPLAY_SPHERE_AND_SPURS&&(e=SkeletonViewer.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,a={}){var n,o,l,h,c,u,d,_,p,f,m,g,v,x;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=a,this.color=math_color_Color3.White(),this._debugLines=[],this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,a.pauseAnimations=null===(n=a.pauseAnimations)||void 0===n||n,a.returnToRest=null!==(o=a.returnToRest)&&void 0!==o&&o,a.displayMode=null!==(l=a.displayMode)&&void 0!==l?l:SkeletonViewer.DISPLAY_LINES,a.displayOptions=null!==(h=a.displayOptions)&&void 0!==h?h:{},a.displayOptions.midStep=null!==(c=a.displayOptions.midStep)&&void 0!==c?c:.235,a.displayOptions.midStepFactor=null!==(u=a.displayOptions.midStepFactor)&&void 0!==u?u:.155,a.displayOptions.sphereBaseSize=null!==(d=a.displayOptions.sphereBaseSize)&&void 0!==d?d:.15,a.displayOptions.sphereScaleUnit=null!==(_=a.displayOptions.sphereScaleUnit)&&void 0!==_?_:2,a.displayOptions.sphereFactor=null!==(p=a.displayOptions.sphereFactor)&&void 0!==p?p:.865,a.displayOptions.spurFollowsChild=null!==(f=a.displayOptions.spurFollowsChild)&&void 0!==f&&f,a.displayOptions.showLocalAxes=null!==(m=a.displayOptions.showLocalAxes)&&void 0!==m&&m,a.displayOptions.localAxesSize=null!==(g=a.displayOptions.localAxesSize)&&void 0!==g?g:.075,a.computeBonesUsingShaders=null===(v=a.computeBonesUsingShaders)||void 0===v||v,a.useAllBones=null===(x=a.useAllBones)||void 0===x||x;let b=t.getVerticesData(buffer_VertexBuffer.MatricesIndicesKind),T=t.getVerticesData(buffer_VertexBuffer.MatricesWeightsKind);if(this._boneIndices=new Set,!a.useAllBones&&b&&T)for(let e=0;eSkeletonViewer.DISPLAY_SPHERE_AND_SPURS&&(S=SkeletonViewer.DISPLAY_LINES),this.displayMode=S,this.update(),this._bindObs()}_bindObs(){this.displayMode===SkeletonViewer.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case SkeletonViewer.DISPLAY_LINES:this._displayLinesUpdate();break;case SkeletonViewer.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,a=0){let n=math_vector_TmpVectors.Matrix[0],o=t.getParent();if(n.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==a){let e=math_vector_TmpVectors.Matrix[1];math_vector_Matrix.IdentityToRef(e),e.setTranslationFromFloats(r,s,a),e.multiplyToRef(n,n)}o&&n.multiplyToRef(o.getAbsoluteMatrix(),n),n.multiplyToRef(i,n),e.x=n.m[12],e.y=n.m[13],e.z=n.m[14]}_getLinesForBonesWithLength(e,t){let i=e.length,r=this.mesh,s=r.position,a=0;for(let r=0;r=0;a--){let t=e[a],n=t.getParent();if(!n||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let o=this._debugLines[i];o||(o=[math_vector_Vector3.Zero(),math_vector_Vector3.Zero()],this._debugLines[i]=o),t.getAbsolutePositionToRef(r,o[0]),n.getAbsolutePositionToRef(r,o[1]),o[0].subtractInPlace(s),o[1].subtractInPlace(s),i++}}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(null===e||-1===e._index){t.copyFrom(math_vector_Matrix.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;let r=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,a=[],n=[],o=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,r.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY,l=this.options.displayOptions||{};for(let i=0;i{let s=new math_vector_Matrix;i.getLocalMatrix().multiplyToRef(h,s);let a=new math_vector_Vector3;s.decompose(void 0,void 0,a);let u=math_vector_Vector3.Distance(c,a);if(u>t&&(t=u),e)return;let d=a.clone().subtract(c.clone()),_=d.length(),p=d.normalize().scale(_),f=l.midStep||.165,m=l.midStepFactor||.215,g=p.scale(f),v=ExtrudeShapeCustom("skeletonViewer",{shape:[new math_vector_Vector3(1,-1,0),new math_vector_Vector3(1,1,0),new math_vector_Vector3(-1,1,0),new math_vector_Vector3(-1,-1,0),new math_vector_Vector3(1,-1,0)],path:[math_vector_Vector3.Zero(),g,p],scaleFunction:e=>{switch(e){case 0:case 2:break;case 1:return _*m}return 0},sideOrientation:mesh_Mesh.DEFAULTSIDE,updatable:!1},r),x=v.getTotalVertices(),b=[],T=[];for(let e=0;e9?T.push(i.getIndex(),0,0,0):T.push(o.getIndex(),0,0,0);v.position=c.clone(),v.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,b,!1),v.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,T,!1),v.convertToFlatShadedMesh(),n.push(v)});let u=l.sphereBaseSize||.2,d=sphereBuilder_CreateSphere("skeletonViewer",{segments:6,diameter:u,updatable:!0},r),_=d.getTotalVertices(),p=[],f=[];for(let e=0;e<_;e++)p.push(1,0,0,0),f.push(o.getIndex(),0,0,0);d.setVerticesData(buffer_VertexBuffer.MatricesWeightsKind,p,!1),d.setVerticesData(buffer_VertexBuffer.MatricesIndicesKind,f,!1),d.position=c.clone(),a.push([d,o])}let h=l.sphereScaleUnit||2,c=l.sphereFactor||.85,u=[];for(let e=0;e{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;let e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))})):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},engine_Engine.prototype._getGlAlgorithmType=function(e){return e===abstractMesh_AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(abstractMesh_AbstractMesh.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new _OcclusionDataStorage),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),abstractMesh_AbstractMesh.prototype._checkOcclusionQuery=function(){let e=this._occlusionDataStorage;if(e.occlusionType===abstractMesh_AbstractMesh.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;let t=this.getEngine();if(!t.getCaps().supportOcclusionQuery||!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery){let i=t.isQueryResultAvailable(this._occlusionQuery);if(i){let i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,-1===e.occlusionRetryCount||!(e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==abstractMesh_AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}let i=this.getScene();if(i.getBoundingBoxRenderer){let r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded},engine_Engine.prototype.createTransformFeedback=function(){let e=this._gl.createTransformFeedback();if(!e)throw Error("Unable to create Transform Feedback");return e},engine_Engine.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},engine_Engine.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},engine_Engine.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},engine_Engine.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},engine_Engine.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},engine_Engine.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},ThinEngine.prototype.createExternalTexture=function(e){return null},ThinEngine.prototype.setExternalTexture=function(e,t){throw Error("setExternalTexture: This engine does not support external textures!")},ThinEngine.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;let r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),a=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);let t=e._workingCanvas.getContext("2d");if(!t)throw Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),a||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},ThinEngine.prototype.restoreSingleAttachment=function(){let e=this._gl;this.bindAttachments([e.BACK])},ThinEngine.prototype.restoreSingleAttachmentForRenderTarget=function(){let e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},ThinEngine.prototype.buildTextureLayout=function(e){let t=this._gl,i=[];for(let r=0;r1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(l=t.depthTextureFormat));let x=this._gl,b=x.createFramebuffer();this._bindUnboundFramebuffer(b);let T=e.width||e,S=e.height||e,C=[],E=[],y=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),R=this._setupFramebufferDepthAttachments(!y&&n,!o&&a,T,S);v._framebuffer=b,v._depthStencilBuffer=R,v._generateDepthBuffer=!o&&a,v._generateStencilBuffer=!y&&n,v._attachments=E;for(let e=0;e1||this.isWebGPU);let f=this.webGLVersion>1,m=x[f?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(E.push(m),-1===o)continue;let v=new internalTexture_InternalTexture(this,$.MultiRenderTarget);C[e]=v,x.activeTexture(x["TEXTURE"+e]),x.bindTexture(o,v._hardwareTexture.underlyingResource),x.texParameteri(o,x.TEXTURE_MAG_FILTER,h.mag),x.texParameteri(o,x.TEXTURE_MIN_FILTER,h.min),x.texParameteri(o,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(o,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE);let b=this._getRGBABufferInternalSizedFormat(i,n,a),y=this._getInternalFormat(n),R=this._getWebGLTextureType(i);if(f&&(35866===o||32879===o))35866===o?v.is2DArray=!0:v.is3D=!0,v.baseDepth=v.depth=l,x.texImage3D(o,0,b,T,S,l,0,y,R,null);else if(34067===o){for(let e=0;e<6;e++)x.texImage2D(x.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,b,T,S,0,y,R,null);v.isCube=!0}else x.texImage2D(x.TEXTURE_2D,0,b,T,S,0,y,R,null);s&&x.generateMipmap(o),this._bindTextureDirectly(o,null),v.baseWidth=T,v.baseHeight=S,v.width=T,v.height=S,v.isReady=!0,v.samples=1,v.generateMipMaps=s,v.samplingMode=t,v.type=i,v._useSRGBBuffer=a,v.format=n,this._internalTexturesCache.push(v)}if(o&&this._caps.depthTextureExtension){let e=new internalTexture_InternalTexture(this,$.Depth),t=5,i=x.DEPTH_COMPONENT16,r=x.DEPTH_COMPONENT,a=x.UNSIGNED_SHORT,n=x.DEPTH_ATTACHMENT;this.webGLVersion<2?i=x.DEPTH_COMPONENT:14===l?(t=1,a=x.FLOAT,i=x.DEPTH_COMPONENT32F):18===l?(t=0,a=x.FLOAT_32_UNSIGNED_INT_24_8_REV,i=x.DEPTH32F_STENCIL8,r=x.DEPTH_STENCIL,n=x.DEPTH_STENCIL_ATTACHMENT):16===l?(t=0,a=x.UNSIGNED_INT,i=x.DEPTH_COMPONENT24,n=x.DEPTH_ATTACHMENT):(13===l||17===l)&&(t=12,a=x.UNSIGNED_INT_24_8,i=x.DEPTH24_STENCIL8,r=x.DEPTH_STENCIL,n=x.DEPTH_STENCIL_ATTACHMENT),x.activeTexture(x.TEXTURE0),x.bindTexture(x.TEXTURE_2D,e._hardwareTexture.underlyingResource),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE),x.texImage2D(x.TEXTURE_2D,0,i,T,S,0,r,a,null),x.framebufferTexture2D(x.FRAMEBUFFER,n,x.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=T,e.baseHeight=S,e.width=T,e.height=S,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=l,e.type=t,C[h]=e,this._internalTexturesCache.push(e)}return v.setTextures(C),i&&x.drawBuffers(E),this._bindUnboundFramebuffer(null),v.setLayerAndFaceIndices(m,f),this.resetTextureCache(),v},ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let r=e._attachments.length;if(0===r)return 1;let s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);let a=!!e._depthStencilBuffer;if(a&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){let a=s.createFramebuffer();if(!a)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=a,this._bindUnboundFramebuffer(a);let n=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(r.width,r.height,t,-1,this._getRGBAMultiSampleBufferFormat(r.type,r.format),o);if(!l)throw Error("Unable to create multi sampled framebuffer");a.addMSAARenderBuffer(l),r.samples=t,n.push(o)}i&&s.drawBuffers(n)}else this._bindUnboundFramebuffer(e._framebuffer);return a&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},ThinEngine.prototype._createDepthStencilCubeTexture=function(e,t,i){let r=new internalTexture_InternalTexture(this,$.DepthStencil);if(r.isCube=!0,1===this.webGLVersion)return logger_Logger.Error("Depth cube texture is not supported by WebGL 1."),r;let s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),a=this._gl;this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=r,i._depthStencilTextureWithStencil=s.generateStencil;for(let t=0;t<6;t++)s.generateStencil?a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,a.DEPTH24_STENCIL8,e,e,0,a.DEPTH_STENCIL,a.UNSIGNED_INT_24_8,null):a.texImage2D(a.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,a.DEPTH_COMPONENT24,e,e,0,a.DEPTH_COMPONENT,a.UNSIGNED_INT,null);return this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(r),r},ThinEngine.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)},void 0,void 0,!0,(e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)})},ThinEngine.prototype._cascadeLoadFiles=function(e,t,i,r=null){let s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},ThinEngine.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,a){let n=[];n._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(r[o],o,n,e,t,i,s,a)},ThinEngine.prototype._partialLoadImg=function(e,t,i,r,s,a,n=null,o){let l=guid_RandomGUID();LoadImage(e,e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(l),6===i._internalCount&&a&&a(s,i)},(e,t)=>{r&&r.removePendingData(l),n&&n(e,t)},r?r.offlineProvider:null,o),r&&r.addPendingData(l)},ThinEngine.prototype._setCubeMapTextureParams=function(e,t,i){let r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),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),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},ThinEngine.prototype.createCubeTextureBase=function(e,t,i,r,s=null,a=null,n,o=null,l=!1,h=0,c=0,u=null,d=null,_=null,p=!1){let f=u||new internalTexture_InternalTexture(this,$.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!r,f._lodGenerationScale=h,f._lodGenerationOffset=c,f._useSRGBBuffer=!!p&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!r),f!==u&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=o,f._files=i);let m=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));let g=e.split("?")[0],v=g.lastIndexOf("."),x=o||(v>-1?g.substring(v).toLowerCase():""),b=null;for(let e of ThinEngine._TextureLoaders)if(e.canLoad(x)){b=e;break}if(b){let onloaddata=e=>{d&&d(f,e),b.loadCubeData(e,f,l,s,a)};i&&6===i.length?b.supportCascades?this._cascadeLoadFiles(t,e=>onloaddata(e.map(e=>new Uint8Array(e))),i,a):a?a("Textures type does not support cascades."):logger_Logger.Warn("Texture loader does not support cascades."):this._loadFile(e,e=>onloaddata(new Uint8Array(e)),void 0,void 0,!0,(u,g)=>{e===m?a&&u&&a(u.status+" "+u.statusText,g):(logger_Logger.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!r,s,a,n,o,l,h,c,f,d,_,p))})}else{if(!i)throw Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,f,(e,t)=>{_&&_(e,t)},i,a)}return this._internalTexturesCache.push(f),f},ThinEngine.prototype.createCubeTexture=function(e,t,i,r,s=null,a=null,n,o=null,l=!1,h=0,c=0,u=null,d,_=!1){let p=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,a,n,o,l,h,c,u,e=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),(e,t)=>{let i=this.needPOTTextures?ThinEngine.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,a=[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);let o=n?this._getInternalFormat(n,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA,l=n?this._getInternalFormat(n):p.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(l=o);for(let e=0;ee&&(e===t||e.match(RegExp("\\b"+t+"\\b","g")))))return e;let t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}Object.defineProperty(engine_Engine.prototype,"onBeforeViewRenderObservable",{get:function(){return rM}}),Object.defineProperty(engine_Engine.prototype,"onAfterViewRenderObservable",{get:function(){return rI}}),Object.defineProperty(engine_Engine.prototype,"inputElement",{get:function(){return this._inputElement},set:function(e){var t;this._inputElement!==e&&(this._inputElement=e,null===(t=this._onEngineViewChanged)||void 0===t||t.call(this))}}),engine_Engine.prototype.getInputElement=function(){return this.inputElement||this.getRenderingCanvas()},engine_Engine.prototype.registerView=function(e,t,i){for(let t of(this.views||(this.views=[]),this.views))if(t.target===e)return t;let r=this.getRenderingCanvas();r&&(e.width=r.width,e.height=r.height);let s={target:e,camera:t,clearBeforeCopy:i,enabled:!0,id:(1e5*Math.random()).toFixed()};return this.views.push(s),t&&t.onDisposeObservable.add(()=>{this.unRegisterView(e)}),s},engine_Engine.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(let t of this.views)if(t.target===e){let e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},engine_Engine.prototype._renderViewStep=function(e){let t=e.target,i=t.getContext("2d");if(!i)return!0;let r=this.getRenderingCanvas();rM.notifyObservers(e);let s=e.camera,a=null,n=null;if(s){if(!(n=s.getScene())||n.activeCameras&&n.activeCameras.length)return!0;this.activeView=e,a=n.activeCamera,n.activeCamera=s}if(e.customResize)e.customResize(t);else{let e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!!r.width&&!!r.height&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),a&&n&&(n.activeCamera=a),rI.notifyObservers(e),!0)},engine_Engine.prototype._renderViews=function(){let e;if(!this.views||0===this.views.length)return!1;let t=this.getRenderingCanvas();if(!t)return!1;for(let t of this.views){if(!t.enabled)continue;let i=t.target;if(i===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return(!e||!!this._renderViewStep(e))&&(this.activeView=null,!0)},ThinEngine.prototype.createStorageBuffer=function(e,t){throw Error("createStorageBuffer: Unsupported method in this engine!")},ThinEngine.prototype.updateStorageBuffer=function(e,t,i,r){},ThinEngine.prototype.readFromStorageBuffer=function(e,t,i,r){throw Error("readFromStorageBuffer: Unsupported method in this engine!")},ThinEngine.prototype.setStorageBuffer=function(e,t){throw Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(engine_Engine.prototype,"texturesSupported",{get:function(){let e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(engine_Engine.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),engine_Engine.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},engine_Engine.prototype.setTextureFormatToUse=function(e){let t=this.texturesSupported;for(let i=0,r=t.length;i{this._flush()})}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}};NativeDataStream.DEFAULT_BUFFER_SIZE=65536;let rD=[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))],rO=[()=>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],applySH3=(e,t)=>rD[e]*rO[e](t),rB=[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];let SphericalHarmonics=class SphericalHarmonics{constructor(){this.preScaled=!1,this.l00=math_vector_Vector3.Zero(),this.l1_1=math_vector_Vector3.Zero(),this.l10=math_vector_Vector3.Zero(),this.l11=math_vector_Vector3.Zero(),this.l2_2=math_vector_Vector3.Zero(),this.l2_1=math_vector_Vector3.Zero(),this.l20=math_vector_Vector3.Zero(),this.l21=math_vector_Vector3.Zero(),this.l22=math_vector_Vector3.Zero()}addLight(e,t,i){math_vector_TmpVectors.Vector3[0].set(t.r,t.g,t.b);let r=math_vector_TmpVectors.Vector3[0],s=math_vector_TmpVectors.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(applySH3(0,e),math_vector_TmpVectors.Vector3[2]),this.l00.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(1,e),math_vector_TmpVectors.Vector3[2]),this.l1_1.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(2,e),math_vector_TmpVectors.Vector3[2]),this.l10.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(3,e),math_vector_TmpVectors.Vector3[2]),this.l11.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(4,e),math_vector_TmpVectors.Vector3[2]),this.l2_2.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(5,e),math_vector_TmpVectors.Vector3[2]),this.l2_1.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(6,e),math_vector_TmpVectors.Vector3[2]),this.l20.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(7,e),math_vector_TmpVectors.Vector3[2]),this.l21.addInPlace(math_vector_TmpVectors.Vector3[2]),s.scaleToRef(applySH3(8,e),math_vector_TmpVectors.Vector3[2]),this.l22.addInPlace(math_vector_TmpVectors.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(rB[0]),this.l1_1.scaleInPlace(rB[1]),this.l10.scaleInPlace(rB[2]),this.l11.scaleInPlace(rB[3]),this.l2_2.scaleInPlace(rB[4]),this.l2_1.scaleInPlace(rB[5]),this.l20.scaleInPlace(rB[6]),this.l21.scaleInPlace(rB[7]),this.l22.scaleInPlace(rB[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(rD[0]),this.l1_1.scaleInPlace(rD[1]),this.l10.scaleInPlace(rD[2]),this.l11.scaleInPlace(rD[3]),this.l2_2.scaleInPlace(rD[4]),this.l2_1.scaleInPlace(rD[5]),this.l20.scaleInPlace(rD[6]),this.l21.scaleInPlace(rD[7]),this.l22.scaleInPlace(rD[8])}updateFromArray(e){return math_vector_Vector3.FromArrayToRef(e[0],0,this.l00),math_vector_Vector3.FromArrayToRef(e[1],0,this.l1_1),math_vector_Vector3.FromArrayToRef(e[2],0,this.l10),math_vector_Vector3.FromArrayToRef(e[3],0,this.l11),math_vector_Vector3.FromArrayToRef(e[4],0,this.l2_2),math_vector_Vector3.FromArrayToRef(e[5],0,this.l2_1),math_vector_Vector3.FromArrayToRef(e[6],0,this.l20),math_vector_Vector3.FromArrayToRef(e[7],0,this.l21),math_vector_Vector3.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return math_vector_Vector3.FromFloatsToRef(e[0],e[1],e[2],this.l00),math_vector_Vector3.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),math_vector_Vector3.FromFloatsToRef(e[6],e[7],e[8],this.l10),math_vector_Vector3.FromFloatsToRef(e[9],e[10],e[11],this.l11),math_vector_Vector3.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),math_vector_Vector3.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),math_vector_Vector3.FromFloatsToRef(e[18],e[19],e[20],this.l20),math_vector_Vector3.FromFloatsToRef(e[21],e[22],e[23],this.l21),math_vector_Vector3.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){let t=new SphericalHarmonics;return t.updateFromArray(e)}static FromPolynomial(e){let t=new SphericalHarmonics;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}};let SphericalPolynomial=class SphericalPolynomial{constructor(){this.x=math_vector_Vector3.Zero(),this.y=math_vector_Vector3.Zero(),this.z=math_vector_Vector3.Zero(),this.xx=math_vector_Vector3.Zero(),this.yy=math_vector_Vector3.Zero(),this.zz=math_vector_Vector3.Zero(),this.xy=math_vector_Vector3.Zero(),this.yz=math_vector_Vector3.Zero(),this.zx=math_vector_Vector3.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=SphericalHarmonics.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){math_vector_TmpVectors.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=math_vector_TmpVectors.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),math_vector_TmpVectors.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),math_vector_TmpVectors.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(math_vector_TmpVectors.Vector3[0]).addInPlace(math_vector_TmpVectors.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(math_vector_TmpVectors.Vector3[0]).subtractInPlace(math_vector_TmpVectors.Vector3[1]),this.zz.copyFrom(e.l00),math_vector_TmpVectors.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(math_vector_TmpVectors.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){let t=new SphericalPolynomial;return t.updateFromHarmonics(e)}static FromArray(e){let t=new SphericalPolynomial;return math_vector_Vector3.FromArrayToRef(e[0],0,t.x),math_vector_Vector3.FromArrayToRef(e[1],0,t.y),math_vector_Vector3.FromArrayToRef(e[2],0,t.z),math_vector_Vector3.FromArrayToRef(e[3],0,t.xx),math_vector_Vector3.FromArrayToRef(e[4],0,t.yy),math_vector_Vector3.FromArrayToRef(e[5],0,t.zz),math_vector_Vector3.FromArrayToRef(e[6],0,t.yz),math_vector_Vector3.FromArrayToRef(e[7],0,t.zx),math_vector_Vector3.FromArrayToRef(e[8],0,t.xy),t}};let rN=`varying vec2 vUV;uniform sampler2D textureSampler; -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;function CreateResizedCopy(e,t,i,r=!0){let s=e.getScene(),a=s.getEngine(),n=new renderTargetTexture_RenderTargetTexture("resized"+e.name,{width:t,height:i},s,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);n.wrapU=e.wrapU,n.wrapV=e.wrapV,n.uOffset=e.uOffset,n.vOffset=e.vOffset,n.uScale=e.uScale,n.vScale=e.vScale,n.uAng=e.uAng,n.vAng=e.vAng,n.wAng=e.wAng,n.coordinatesIndex=e.coordinatesIndex,n.level=e.level,n.anisotropicFilteringLevel=e.anisotropicFilteringLevel,n._texture.isReady=!1,e.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.wrapV=texture_Texture.CLAMP_ADDRESSMODE;let o=new PassPostProcess("pass",1,null,r?texture_Texture.BILINEAR_SAMPLINGMODE:texture_Texture.NEAREST_SAMPLINGMODE,a,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(t){t.setTexture("textureSampler",e)};let t=n.renderTarget;t&&(s.postProcessManager.directRender([o],t),a.unBindFramebuffer(t),n.disposeFramebufferObjects(),o.dispose(),n.getInternalTexture().isReady=!0)}),n}function ApplyPostProcess(e,t,i,r,s,a,n,o){let l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,r=null!=r?r:t.type,a=null!=a?a:t.format,n=null!=n?n:t.width,o=null!=o?o:t.height,-1===r&&(r=0),new Promise(h=>{let c=new postProcess_PostProcess("postprocess",e,null,null,1,null,s,l,!1,void 0,r,void 0,null,!1,a);c.externalTextureSamplerBinding=!0;let u=l.createRenderTargetTexture({width:n,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:a});c.getEffect().executeWhenCompiled(()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([c],u,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,h(t)})})}function ToHalfFloat(e){s||(s=new Float32Array(1),a=new Int32Array(s.buffer)),s[0]=e;let t=a[0],i=t>>16&32768,r=t>>12&2047,n=t>>23&255;return n<103?i:n>142?(i|=31744,i|=(255==n?0:1)&&8388607&t):n<113?(r|=2048,i|=(r>>114-n)+(r>>113-n&1)):(i|=n-112<<10|r>>1,i+=1&r)}function FromHalfFloat(e){let t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*6103515625e-14*(r/1024):31==i?r?NaN:(t?-1:1)*(1/0):(t?-1:1)*Math.pow(2,i-15)*(1+r/1024)}ShaderStore.ShadersStore.rgbdDecodePixelShader=rN;let ProcessAsync=async(e,t,i,r,s)=>{let a;let n=e.getScene(),o=n.getEngine();a=e.isCube?new postProcess_PostProcess("lodCube","lodCube",["lod","gamma"],null,1,null,texture_Texture.NEAREST_NEAREST_MIPNEAREST,o,!1,["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"][r]):new postProcess_PostProcess("lod","lod",["lod","gamma"],null,1,null,texture_Texture.NEAREST_NEAREST_MIPNEAREST,o),await new Promise(e=>{a.getEffect().executeWhenCompiled(()=>{e(0)})});let l=new renderTargetTexture_RenderTargetTexture("temp",{width:t,height:i},n,!1);a.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",s),t.setBool("gamma",e.gammaSpace)};let h=e.getInternalTexture();try{if(l.renderTarget&&h){let r=h.samplingMode;0!==s?e.updateSamplingMode(texture_Texture.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(texture_Texture.NEAREST_NEAREST),n.postProcessManager.directRender([a],l.renderTarget,!0),e.updateSamplingMode(r);let c=await o.readPixels(0,0,t,i),u=new Uint8Array(c.buffer,0,c.byteLength);return o.unBindFramebuffer(l.renderTarget),u}throw Error("Render to texture failed.")}finally{l.dispose(),a.dispose()}};async function GetTextureDataAsync(e,t,i,r=0,s=0){return!e.isReady()&&e._texture&&await new Promise((t,i)=>{if(null===e._texture){i(0);return}e._texture.onLoadedObservable.addOnce(()=>{t(0)})}),await ProcessAsync(e,t,i,r,s)}let rF={CreateResizedCopy,ApplyPostProcess,ToHalfFloat,FromHalfFloat,GetTextureDataAsync};let RGBDTextureTools=class RGBDTextureTools{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,a=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(a=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(a=!0,t.type=1),a&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let expandRGBDTexture=()=>{if(a){let r=new postProcess_PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);r.externalTextureSamplerBinding=!0;let s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});r.getEffect().executeWhenCompiled(()=>{r.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([r],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),r&&r.dispose(),s._swapAndDie(t),t.isReady=!0})}};s?expandRGBDTexture():e.onLoadObservable.addOnce(expandRGBDTexture)}static EncodeTextureToRGBD(e,t,i=0){return ApplyPostProcess("rgbdEncode",e,t,i,1,5)}};let FileFaceOrientation=class FileFaceOrientation{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}};let CubeMapToSphericalPolynomialTools=class CubeMapToSphericalPolynomialTools{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;let i,r;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();let s=e.getSize().width,a=e.readPixels(0,void 0,void 0,!1),n=e.readPixels(1,void 0,void 0,!1);e.isRenderTarget?(i=e.readPixels(3,void 0,void 0,!1),r=e.readPixels(2,void 0,void 0,!1)):(i=e.readPixels(2,void 0,void 0,!1),r=e.readPixels(3,void 0,void 0,!1));let o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,c=0;return(1==e.textureType||2==e.textureType)&&(c=1),new Promise(e=>{Promise.all([n,a,i,r,o,l]).then(([t,i,r,a,n,o])=>{let l={size:s,right:i,left:t,up:r,down:a,front:n,back:o,format:5,type:c,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(l))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){let t=new SphericalHarmonics,i=0,r=2/e.size,s=.5*r,a=s-1;for(let n=0;n<6;n++){let o=this._FileFaces[n],l=e[o.name],h=a,c=5===e.format?4:3;for(let n=0;ng){let t=g/e;p*=t,f*=t,m*=t}}else p=math_scalar_Scalar.Clamp(p,0,g),f=math_scalar_Scalar.Clamp(f,0,g),m=math_scalar_Scalar.Clamp(m,0,g);let v=new math_color_Color3(p,f,m);t.addLight(d,v,_),i+=_,u+=r}h+=r}}let n=4*Math.PI*6/6/i;return t.scaleInPlace(n),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),SphericalPolynomial.FromHarmonics(t)}};CubeMapToSphericalPolynomialTools._FileFaces=[new FileFaceOrientation("right",new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,-1),new math_vector_Vector3(0,-1,0)),new FileFaceOrientation("left",new math_vector_Vector3(-1,0,0),new math_vector_Vector3(0,0,1),new math_vector_Vector3(0,-1,0)),new FileFaceOrientation("up",new math_vector_Vector3(0,1,0),new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,1)),new FileFaceOrientation("down",new math_vector_Vector3(0,-1,0),new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,-1)),new FileFaceOrientation("front",new math_vector_Vector3(0,0,1),new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,-1,0)),new FileFaceOrientation("back",new math_vector_Vector3(0,0,-1),new math_vector_Vector3(-1,0,0),new math_vector_Vector3(0,-1,0))],CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE=4096,CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS=!1,baseTexture_BaseTexture.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(baseTexture_BaseTexture.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;this._texture.isReady&&!this._texture._sphericalPolynomialPromise&&(this._texture._sphericalPolynomialPromise=CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});let rw=`varying vec2 vUV;uniform sampler2D textureSampler; -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;ShaderStore.ShadersStore.rgbdEncodePixelShader=rw;let rL="image/png",rV=[134,22,135,150,246,214,150,54];function GetEnvInfo(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(let e=0;e2)throw Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "2".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:rL})}function CreateImageDataArrayBufferViews(e,t){t=normalizeEnvInfo(t);let i=t.specular,r=math_scalar_Scalar.Log2(t.width);if(r=Math.round(r)+1,i.mipmaps.length!==6*r)throw Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);let s=Array(r);for(let t=0;t{if(i){let i=t.createTexture(null,!0,!0,null,1,null,e=>{d(e)},e);r.getEffect().executeWhenCompiled(()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,a,n),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),u())})}else{if(t._uploadImageToTexture(c,e,a,n),o){let i=l[n];i&&t._uploadImageToTexture(i._texture,e,a,0)}u()}})}function UploadLevelsAsync(e,t,i=rL){if(!tools_Tools.IsExponentOfTwo(e.width))throw Error("Texture size must be a power of two");let r=math_scalar_Scalar.ILog2(e.width)+1,s=e.getEngine(),a=!1,n=!1,o=null,l=null,h=null,c=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),c.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(a=!0,e.type=2):c.textureFloatRender&&c.textureFloatLinearFiltering&&(a=!0,e.type=1):a=!1:(a=!1,n=!0,h={}),a)o=new postProcess_PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=s.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,n){let t=e._lodGenerationScale,i=e._lodGenerationOffset;for(let a=0;a<3;a++){let n=a/2,o=1-n,l=(r-1)*t+i,c=i+(l-i)*o,u=Math.round(Math.min(Math.max(c,0),l)),d=new internalTexture_InternalTexture(s,$.Temp);d.isCube=!0,d.invertY=!0,d.generateMipMaps=!1,s.updateTextureSamplingMode(2,d);let _=new baseTexture_BaseTexture(null);switch(_._isCube=!0,_._texture=d,h[u]=_,a){case 0:e._lodTextureLow=_;break;case 1:e._lodTextureMid=_;break;case 2:e._lodTextureHigh=_}}}let u=[];for(let r=0;r_OnImageReadyAsync(t,s,a,o,f,c,r,n,h,l,e));else{let t=new Image;t.src=f,d=new Promise((i,u)=>{t.onload=()=>{_OnImageReadyAsync(t,s,a,o,f,c,r,n,h,l,e).then(()=>i()).catch(e=>{u(e)})},t.onerror=e=>{u(e)}})}u.push(d)}if(t.length{l&&(s._releaseTexture(e),l._swapAndDie(e)),o&&o.dispose(),n&&(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 UploadEnvSpherical(e,t){t=normalizeEnvInfo(t);let i=t.irradiance;if(!i)return;let r=new SphericalPolynomial;math_vector_Vector3.FromArrayToRef(i.x,0,r.x),math_vector_Vector3.FromArrayToRef(i.y,0,r.y),math_vector_Vector3.FromArrayToRef(i.z,0,r.z),math_vector_Vector3.FromArrayToRef(i.xx,0,r.xx),math_vector_Vector3.FromArrayToRef(i.yy,0,r.yy),math_vector_Vector3.FromArrayToRef(i.zz,0,r.zz),math_vector_Vector3.FromArrayToRef(i.yz,0,r.yz),math_vector_Vector3.FromArrayToRef(i.zx,0,r.zx),math_vector_Vector3.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function ExtractBetweenMarkers(e,t,i,r){let s=r,a=0,n="";for(;s=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function RemoveComments(e){let t=0,i="",r=!1,s=[];for(;t=0&&e.charAt(t)!==i;)t--;return t}function EscapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}let ShaderCodeInliner=class ShaderCodeInliner{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&console.log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&console.log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:a,type:s,parameters:d,body:c,callIndex:0}),e=h+1;let _=t>0?this._sourceCode.substring(0,t):"",p=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(let t of this._functionDescr){let{name:i,type:r,parameters:s,body:a}=t,n=0;for(;n{let t=[],i=0,r=0;for(;i0?this._sourceCode.substring(0,o):"",m=h+1{let o=s[0];return IsIdentifierChar(e.charAt(o-1))||IsIdentifierChar(e.charAt(o+a))?t[r]:n})}return e}};ShaderCodeInliner._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;let NativePipelineContext=class NativePipelineContext{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){let e=this.compilationError.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,r,s,a,n,o){let l;let h=this._engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let c=this._engine.getUniforms(this,i);for(c.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l{a[e]=t}),o.push(...h.getAttributes(this,n))}dispose(){this._uniforms={}}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let a=!1;return s[0]!==t&&(s[0]=t,a=!0),s[1]!==i&&(s[1]=i,a=!0),s[2]!==r&&(s[2]=r,a=!0),a}_cacheFloat4(e,t,i,r,s){let a=this._valueCache[e];if(!a)return a=[t,i,r,s],this._valueCache[e]=a,!0;let n=!1;return a[0]!==t&&(a[0]=t,n=!0),a[1]!==i&&(a[1]=i,n=!0),a[2]!==r&&(a[2]=r,n=!0),a[3]!==s&&(a[3]=s,n=!0),n}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setInt4(this._uniforms[e],t,i,r,s)&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setUInt4(this._uniforms[e],t,i,r,s)&&(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)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(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.toArray())&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}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,i){this._cacheFloat2(e,t,i)&&!this._engine.setFloat2(this._uniforms[e],t,i)&&(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,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setFloat3(this._uniforms[e],t,i,r)&&(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,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setFloat4(this._uniforms[e],t,i,r,s)&&(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(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)}};let NativeRenderTargetWrapper=class NativeRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}};let NativeHardwareTexture=class NativeHardwareTexture{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}};function getNativeTextureFormat(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new RuntimeError(`Unsupported texture format or type: format ${e}, type ${t}.`,b.UnsupportedTextureError)}function getNativeSamplingMode(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw Error(`Unsupported sampling mode: ${e}.`)}}function getNativeAddressMode(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw Error("Unexpected wrap mode: "+e+".")}}function getNativeStencilFunc(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw Error(`Unsupported stencil func mode: ${e}.`)}}function getNativeStencilOpFail(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw Error(`Unsupported stencil OpFail mode: ${e}.`)}}function getNativeStencilDepthFail(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw Error(`Unsupported stencil depthFail mode: ${e}.`)}}function getNativeStencilDepthPass(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw Error(`Unsupported stencil opPass mode: ${e}.`)}}function getNativeAlphaMode(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw Error(`Unsupported alpha mode: ${e}.`)}}function getNativeAttribType(e){switch(e){case buffer_VertexBuffer.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case buffer_VertexBuffer.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case buffer_VertexBuffer.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case buffer_VertexBuffer.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case buffer_VertexBuffer.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw Error(`Unsupported attribute type: ${e}.`)}}let rU=new observable_Observable;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{(e=t)&&rU.notifyObservers(e)}})}function AcquireNativeObjectAsync(){return new Promise(e=>{"undefined"==typeof _native?rU.addOnce(t=>e(t)):e(_native)})}async function RegisterNativeTypeAsync(e,t){(await AcquireNativeObjectAsync())[e]=t}let NativeDataBuffer=class NativeDataBuffer extends dataBuffer_DataBuffer{};let CommandBufferEncoder=class CommandBufferEncoder{constructor(e){this._engine=e,this._pending=[],this._isCommandBufferScopeActive=!1,this._commandStream=NativeEngine._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}};let NativeEngine=class NativeEngine extends engine_Engine{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new CommandBufferEncoder(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==NativeEngine.PROTOCOL_VERSION)throw Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.PROTOCOL_VERSION} (JS)`);this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},tools_Tools.Log("Babylon Native (v"+engine_Engine.Version+") launched"),tools_Tools.LoadScript=function(e,t,i,r){tools_Tools.LoadFile(e,e=>{Function(e).apply(null),t&&t()},void 0,void 0,!1,(e,t)=>{i&&i("LoadScript Error",t)})},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function flat(){let e=isNaN(arguments[0])?1:Number(arguments[0]);return e?Array.prototype.reduce.call(this,function(t,i){return Array.isArray(i)?t.push.apply(t,flat.call(i,e-1)):t.push(i),t},[]):Array.prototype.slice.call(this)},writable:!0});let t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();let i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new WebGL2ShaderProcessor,this.onNewSceneAddedObservable.add(e=>{let t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new NativeDataStream}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,r=!1){if(this.useReverseDepthBuffer)throw Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){let r=this._normalizeIndexData(e),s=new NativeDataBuffer;return s.references=1,s.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,null!=t&&t)),s}createVertexBuffer(e,t,i){let r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new NativeDataBuffer;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,null!=t&&t)),s}_recordVertexArrayObject(e,t,i,r,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);let a=r.getAttributesNames();for(let i=0;i=0){let r=a[i],o=null;if(s&&(o=s[r]),o||(o=t[r]),o){let t=o.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,n,o.byteOffset,o.byteStride,o.getSize(),getNativeAttribType(o.type),o.normalized,o.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){let s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){return this._engine.getAttributes(e.nativeProgram,t)}drawElementsType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){return new NativePipelineContext(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,r,s,a,n,o){r?e.nativeProgram=this.createRawShaderProgram():e.nativeProgram=this.createShaderProgram(e,t,i,o)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){if(!this.isAsync(e)){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}createRawShaderProgram(){throw Error("Not Supported")}createShaderProgram(e,t,i,r){if(e.nativeProgram)throw Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=new ShaderCodeInliner(t);s.processCode(),t=s.code;let a=new ShaderCodeInliner(i);a.processCode(),i=a.code,t=ThinEngine._ConcatenateShader(t,r),i=ThinEngine._ConcatenateShader(i,r);let onSuccess=()=>{var t;e.isCompiled=!0,null===(t=e.onCompiled)||void 0===t||t.call(e),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,onSuccess,t=>{e.compilationError=t});try{let r=e.nativeProgram=this._engine.createProgram(t,i);return onSuccess(),r}catch(t){let e=null==t?void 0:t.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){let t=new ShaderCodeInliner(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){e&&e.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){return this._engine.getUniforms(e.nativeProgram,t)}bindUniformBlock(e,t,i){throw Error("Not Implemented")}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.nativeProgram);let i=e.getSamplers();for(let t=0;t{}};return e}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,getNativeStencilOpFail(this._stencilOpStencilFail),getNativeStencilDepthFail(this._stencilOpDepthFail),getNativeStencilDepthPass(this._stencilOpStencilDepthPass),getNativeStencilFunc(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,a){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(a),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;let i=getNativeAlphaMode(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){let i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){let r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,a,n,o=null,l=0,h=0,c=!1){let u=new internalTexture_InternalTexture(this,$.Raw);if(u.format=r,u.generateMipMaps=s,u.samplingMode=n,u.invertY=a,u.baseWidth=t,u.baseHeight=i,u.width=u.baseWidth,u.height=u.baseHeight,u._compression=o,u.type=l,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!s),this.updateRawTexture(u,e,r,a,o,l,u._useSRGBBuffer),u._hardwareTexture){let e=u._hardwareTexture.underlyingResource,t=getNativeSamplingMode(n);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(u),u}createRawTexture2DArray(e,t,i,r,s,a,n,o,l=null,h=0){let c=new internalTexture_InternalTexture(this,$.Raw2DArray);if(c.baseWidth=t,c.baseHeight=i,c.baseDepth=r,c.width=t,c.height=i,c.depth=r,c.format=s,c.type=h,c.generateMipMaps=a,c.samplingMode=o,c.is2DArray=!0,c._hardwareTexture){let l=c._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,getNativeTextureFormat(s,h),a,n);let u=getNativeSamplingMode(o);this._setTextureSampling(l,u)}return c.isReady=!0,this._internalTexturesCache.push(c),c}updateRawTexture(e,t,i,r,s=null,a=0,n=!1){if(e){if(t&&e._hardwareTexture){let r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,getNativeTextureFormat(i,a),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,a=null,n=null,o=null,l=null,h=null,c=null,u,d,_,p=!1){e=e||"";let f="data:"===e.substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new internalTexture_InternalTexture(this,$.Url),v=e;!this._transformTextureUrl||m||l||o||(e=this._transformTextureUrl(e));let x=e.lastIndexOf("."),b=c||(x>-1?e.substring(x).toLowerCase():""),T=null;for(let e of engine_Engine._TextureLoaders)if(e.canLoad(b)){T=e;break}r&&r.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=s,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(p,t),this.doNotHandleContextLost||(g._buffer=o);let S=null;a&&!l&&(S=g.onLoadedObservable.add(a)),l||this._internalTexturesCache.push(g);let onInternalError=(i,l)=>{r&&r.removePendingData(g),e===v?(S&&g.onLoadedObservable.remove(S),engineStore_EngineStore.UseFallbackTexture&&this.createTexture(engineStore_EngineStore.FallbackTexture,t,g.invertY,r,s,null,n,o,g),n&&n((i||"Unknown error")+(engineStore_EngineStore.UseFallbackTexture?" - Fallback texture was used":""),l)):(logger_Logger.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,r,s,a,n,o,g,h,c,u,d))};if(T)throw Error("Loading textures from IInternalTextureLoader not yet implemented.");{let onload=e=>{if(!g._hardwareTexture){r&&r.removePendingData(g);return}let a=g._hardwareTexture.underlyingResource;this._engine.loadTexture(a,e,!t,i,g._useSRGBBuffer,()=>{g.baseWidth=this._engine.getTextureWidth(a),g.baseHeight=this._engine.getTextureHeight(a),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;let e=getNativeSamplingMode(s);this._setTextureSampling(a,e),r&&r.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>{throw Error("Could not load a native texture.")})};if(f&&o){if(o instanceof ArrayBuffer)onload(new Uint8Array(o));else if(ArrayBuffer.isView(o))onload(o);else if("string"==typeof o)onload(new Uint8Array(tools_Tools.DecodeBase64(o)));else throw Error("Unsupported buffer type")}else m?onload(new Uint8Array(tools_Tools.DecodeBase64(e))):this._loadFile(e,e=>onload(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{onInternalError("Unable to load "+(e&&e.responseURL,t))})}return g}wrapNativeTexture(e,t=!1,i=3){let r=new NativeHardwareTexture(e,this._engine),s=new internalTexture_InternalTexture(this,$.Unknown,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){var r,s;let a=t.generateStencil||!1,n=t.samples||1,o=new internalTexture_InternalTexture(this,$.DepthStencil),l=null!==(r=e.width)&&void 0!==r?r:e,h=null!==(s=e.height)&&void 0!==s?s:e,c=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,a,!0,n);return i._framebufferDepthStencil=c,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){let i=new Promise((t,i)=>{let r=this.createCanvasImage();r.onload=()=>{try{let e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e});return i}createImageBitmap(e,t){return new Promise((t,i)=>{if(Array.isArray(e)&&e.length){let i=this._engine.createImageBitmap(e[0]);if(i){t(i);return}}i("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,a=null,n,o=null,l=!1,h=0,c=0,u=null,d,_=!1){let p=u||new internalTexture_InternalTexture(this,$.Cube);p.isCube=!0,p.url=e,p.generateMipMaps=!r,p._lodGenerationScale=h,p._lodGenerationOffset=c,p._useSRGBBuffer=this._getUseSRGBBuffer(_,!!r),this._doNotHandleContextLost||(p._extension=o,p._files=i);let f=e.lastIndexOf("."),m=o||(f>-1?e.substring(f).toLowerCase():"");if(".env"===m){let onloaddata=e=>{let t=GetEnvInfo(e);p.width=t.width,p.height=t.width,UploadEnvSpherical(p,t);let i=t.specular;if(!i)throw Error("Nothing else parsed so far");p._lodGenerationScale=i.lodGenerationScale;let r=CreateImageDataArrayBufferViews(e,t);p.format=5,p.type=0,p.generateMipMaps=!0,p.getEngine().updateTextureSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE,p),p._isRGBD=!0,p.invertY=!0,this._engine.loadCubeTextureWithMips(p._hardwareTexture.underlyingResource,r,!1,p._useSRGBBuffer,()=>{p.isReady=!0,s&&s()},()=>{throw Error("Could not load a native cube texture.")})};if(i&&6===i.length)throw Error("Multi-file loading not allowed on env files.");this._loadFile(e,e=>onloaddata(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{a&&e&&a(e.status+" "+e.statusText,t)})}else{if(!i||6!==i.length)throw Error("Cannot load cubemap because 6 files were not defined");let e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map(e=>tools_Tools.LoadFileAsync(e).then(e=>new Uint8Array(e)))).then(e=>new Promise((t,i)=>{this._engine.loadCubeTexture(p._hardwareTexture.underlyingResource,e,!r,!0,p._useSRGBBuffer,t,i)})).then(()=>{p.isReady=!0,s&&s()},e=>{a&&a(`Failed to load cubemap: ${e.message}`,e)})}return this._internalTexturesCache.push(p),p}_createHardwareTexture(){return new NativeHardwareTexture(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){let r=new NativeRenderTargetWrapper(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=$.Unknown){var s,a,n;let o;let l=!1,h=0,c=3,u=5,d=!1,_=1;void 0!==t&&"object"==typeof t?(l=!!t.generateMipMaps,h=void 0===t.type?0:t.type,c=void 0===t.samplingMode?3:t.samplingMode,u=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,_=null!==(s=t.samples)&&void 0!==s?s:1,o=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(1!==h||this._caps.textureFloatLinearFiltering)&&(2!==h||this._caps.textureHalfFloatLinearFiltering)||(c=1),1!==h||this._caps.textureFloat||(h=0,logger_Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let p=new internalTexture_InternalTexture(this,r),f=null!==(a=e.width)&&void 0!==a?a:e,m=null!==(n=e.height)&&void 0!==n?n:e,g=e.layers||0;if(0!==g)throw Error("Texture layers are not supported in Babylon Native");let v=p._hardwareTexture.underlyingResource,x=getNativeTextureFormat(u,h);return this._engine.initializeTexture(v,f,m,l,x,!0,d,_),this._setTextureSampling(v,getNativeSamplingMode(c)),p._useSRGBBuffer=d,p.baseWidth=f,p.baseHeight=m,p.width=f,p.height=m,p.depth=g,p.isReady=!0,p.samples=_,p.generateMipMaps=l,p.samplingMode=c,p.type=h,p.format=u,p.label=o,this._internalTexturesCache.push(p),p}createRenderTargetTexture(e,t){var i,r,s,a;let n;let o=this._createHardwareRenderTargetWrapper(!1,!1,e),l=!0,h=!1,c=!1,u=1;void 0!==t&&"object"==typeof t&&(l=null===(i=t.generateDepthBuffer)||void 0===i||i,h=!!t.generateStencilBuffer,c=!!t.noColorAttachment,n=t.colorAttachment,u=null!==(r=t.samples)&&void 0!==r?r:1);let d=n||(c?null:this._createInternalTexture(e,t,!0,$.RenderTarget)),_=null!==(s=e.width)&&void 0!==s?s:e,p=null!==(a=e.height)&&void 0!==a?a:e,f=this._engine.createFrameBuffer(d?d._hardwareTexture.underlyingResource:null,_,p,h,l,u);return o._framebuffer=f,o._generateDepthBuffer=l,o._generateStencilBuffer=h,o._samples=u,o.setTextures(d),o}updateRenderTargetTextureSampleCount(e,t){return logger_Logger.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){let i=getNativeSamplingMode(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw Error("Required width/height for frame buffers not yet supported in NativeEngine.");e._framebufferDepthStencil?this._bindUnboundFramebuffer(e._framebufferDepthStencil):this._bindUnboundFramebuffer(e._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){let r=this._normalizeIndexData(t);e.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(e.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i,r){let s=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(e.nativeVertexBuffer,s.buffer,s.byteOffset+(null!=i?i:0),null!=r?r:s.byteLength)}_setTexture(e,t,i=!1,r=!1){let s;let a=this._boundUniforms[e];if(!a)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;return s=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!!s&&!!s._hardwareTexture&&(this._setTextureWrapMode(s._hardwareTexture.underlyingResource,getNativeAddressMode(t.wrapU),getNativeAddressMode(t.wrapV),getNativeAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(a,s._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){let t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){let i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){let e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let e=new _native.Image;return e}updateTextureData(e,t,i,r,s,a,n=0,o=0,l=!1){throw Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,a=0,n=0){throw Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,r,s,a,n,o,l,h){var c,u,d,_;if(void 0!==r&&-1!==r)throw Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture(null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(u=null==a?void 0:a.buffer)&&void 0!==u?u:null,null!==(d=null==a?void 0:a.byteOffset)&&void 0!==d?d:0,null!==(_=null==a?void 0:a.byteLength)&&void 0!==_?_:0).then(e=>(a||(a=new Uint8Array(e)),a))}};NativeEngine.PROTOCOL_VERSION=8,NativeEngine._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new ValidatedNativeDataStream:new NativeDataStream};let ValidatedNativeDataStream=class ValidatedNativeDataStream extends NativeDataStream{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}};(function(e){e.LowPower="low-power",e.HighPerformance="high-performance"})(eU||(eU={})),function(e){e.DepthClipControl="depth-clip-control",e.Depth32FloatStencil8="depth32float-stencil8",e.TextureCompressionBC="texture-compression-bc",e.TextureCompressionETC2="texture-compression-etc2",e.TextureCompressionASTC="texture-compression-astc",e.TimestampQuery="timestamp-query",e.IndirectFirstInstance="indirect-first-instance",e.ShaderF16="shader-f16",e.RG11B10UFloatRenderable="rg11b10ufloat-renderable",e.BGRA8UnormStorage="bgra8unorm-storage",e.Float32Filterable="float32-filterable"}(ek||(ek={})),function(e){e.Unmapped="unmapped",e.Pending="pending",e.Mapped="mapped"}(eG||(eG={})),function(e){e[e.MapRead=1]="MapRead",e[e.MapWrite=2]="MapWrite",e[e.CopySrc=4]="CopySrc",e[e.CopyDst=8]="CopyDst",e[e.Index=16]="Index",e[e.Vertex=32]="Vertex",e[e.Uniform=64]="Uniform",e[e.Storage=128]="Storage",e[e.Indirect=256]="Indirect",e[e.QueryResolve=512]="QueryResolve"}(ez||(ez={})),function(e){e[e.Read=1]="Read",e[e.Write=2]="Write"}(eW||(eW={})),function(e){e.E1d="1d",e.E2d="2d",e.E3d="3d"}(eH||(eH={})),function(e){e[e.CopySrc=1]="CopySrc",e[e.CopyDst=2]="CopyDst",e[e.TextureBinding=4]="TextureBinding",e[e.StorageBinding=8]="StorageBinding",e[e.RenderAttachment=16]="RenderAttachment"}(eX||(eX={})),function(e){e.E1d="1d",e.E2d="2d",e.E2dArray="2d-array",e.Cube="cube",e.CubeArray="cube-array",e.E3d="3d"}(eY||(eY={})),function(e){e.All="all",e.StencilOnly="stencil-only",e.DepthOnly="depth-only"}(ej||(ej={})),function(e){e.R8Unorm="r8unorm",e.R8Snorm="r8snorm",e.R8Uint="r8uint",e.R8Sint="r8sint",e.R16Uint="r16uint",e.R16Sint="r16sint",e.R16Float="r16float",e.RG8Unorm="rg8unorm",e.RG8Snorm="rg8snorm",e.RG8Uint="rg8uint",e.RG8Sint="rg8sint",e.R32Uint="r32uint",e.R32Sint="r32sint",e.R32Float="r32float",e.RG16Uint="rg16uint",e.RG16Sint="rg16sint",e.RG16Float="rg16float",e.RGBA8Unorm="rgba8unorm",e.RGBA8UnormSRGB="rgba8unorm-srgb",e.RGBA8Snorm="rgba8snorm",e.RGBA8Uint="rgba8uint",e.RGBA8Sint="rgba8sint",e.BGRA8Unorm="bgra8unorm",e.BGRA8UnormSRGB="bgra8unorm-srgb",e.RGB9E5UFloat="rgb9e5ufloat",e.RGB10A2UINT="rgb10a2uint",e.RGB10A2Unorm="rgb10a2unorm",e.RG11B10UFloat="rg11b10ufloat",e.RG32Uint="rg32uint",e.RG32Sint="rg32sint",e.RG32Float="rg32float",e.RGBA16Uint="rgba16uint",e.RGBA16Sint="rgba16sint",e.RGBA16Float="rgba16float",e.RGBA32Uint="rgba32uint",e.RGBA32Sint="rgba32sint",e.RGBA32Float="rgba32float",e.Stencil8="stencil8",e.Depth16Unorm="depth16unorm",e.Depth24Plus="depth24plus",e.Depth24PlusStencil8="depth24plus-stencil8",e.Depth32Float="depth32float",e.BC1RGBAUnorm="bc1-rgba-unorm",e.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",e.BC2RGBAUnorm="bc2-rgba-unorm",e.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",e.BC3RGBAUnorm="bc3-rgba-unorm",e.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",e.BC4RUnorm="bc4-r-unorm",e.BC4RSnorm="bc4-r-snorm",e.BC5RGUnorm="bc5-rg-unorm",e.BC5RGSnorm="bc5-rg-snorm",e.BC6HRGBUFloat="bc6h-rgb-ufloat",e.BC6HRGBFloat="bc6h-rgb-float",e.BC7RGBAUnorm="bc7-rgba-unorm",e.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",e.ETC2RGB8Unorm="etc2-rgb8unorm",e.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",e.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",e.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",e.ETC2RGBA8Unorm="etc2-rgba8unorm",e.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",e.EACR11Unorm="eac-r11unorm",e.EACR11Snorm="eac-r11snorm",e.EACRG11Unorm="eac-rg11unorm",e.EACRG11Snorm="eac-rg11snorm",e.ASTC4x4Unorm="astc-4x4-unorm",e.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",e.ASTC5x4Unorm="astc-5x4-unorm",e.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",e.ASTC5x5Unorm="astc-5x5-unorm",e.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",e.ASTC6x5Unorm="astc-6x5-unorm",e.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",e.ASTC6x6Unorm="astc-6x6-unorm",e.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",e.ASTC8x5Unorm="astc-8x5-unorm",e.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",e.ASTC8x6Unorm="astc-8x6-unorm",e.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",e.ASTC8x8Unorm="astc-8x8-unorm",e.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",e.ASTC10x5Unorm="astc-10x5-unorm",e.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",e.ASTC10x6Unorm="astc-10x6-unorm",e.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",e.ASTC10x8Unorm="astc-10x8-unorm",e.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",e.ASTC10x10Unorm="astc-10x10-unorm",e.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",e.ASTC12x10Unorm="astc-12x10-unorm",e.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",e.ASTC12x12Unorm="astc-12x12-unorm",e.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",e.Depth32FloatStencil8="depth32float-stencil8"}(eK||(eK={})),function(e){e.ClampToEdge="clamp-to-edge",e.Repeat="repeat",e.MirrorRepeat="mirror-repeat"}(eq||(eq={})),function(e){e.Nearest="nearest",e.Linear="linear"}(e$||(e$={})),function(e){e.Nearest="nearest",e.Linear="linear"}(eQ||(eQ={})),function(e){e.Never="never",e.Less="less",e.Equal="equal",e.LessEqual="less-equal",e.Greater="greater",e.NotEqual="not-equal",e.GreaterEqual="greater-equal",e.Always="always"}(eZ||(eZ={})),function(e){e[e.Vertex=1]="Vertex",e[e.Fragment=2]="Fragment",e[e.Compute=4]="Compute"}(eJ||(eJ={})),function(e){e.Uniform="uniform",e.Storage="storage",e.ReadOnlyStorage="read-only-storage"}(e0||(e0={})),function(e){e.Filtering="filtering",e.NonFiltering="non-filtering",e.Comparison="comparison"}(e1||(e1={})),function(e){e.Float="float",e.UnfilterableFloat="unfilterable-float",e.Depth="depth",e.Sint="sint",e.Uint="uint"}(e2||(e2={})),(e3||(e3={})).WriteOnly="write-only",function(e){e.Error="error",e.Warning="warning",e.Info="info"}(e4||(e4={})),function(e){e.Validation="validation",e.Internal="internal"}(e5||(e5={})),(e6||(e6={})).Auto="auto",function(e){e.PointList="point-list",e.LineList="line-list",e.LineStrip="line-strip",e.TriangleList="triangle-list",e.TriangleStrip="triangle-strip"}(e8||(e8={})),function(e){e.CCW="ccw",e.CW="cw"}(e7||(e7={})),function(e){e.None="none",e.Front="front",e.Back="back"}(e9||(e9={})),function(e){e[e.Red=1]="Red",e[e.Green=2]="Green",e[e.Blue=4]="Blue",e[e.Alpha=8]="Alpha",e[e.All=15]="All"}(te||(te={})),function(e){e.Zero="zero",e.One="one",e.Src="src",e.OneMinusSrc="one-minus-src",e.SrcAlpha="src-alpha",e.OneMinusSrcAlpha="one-minus-src-alpha",e.Dst="dst",e.OneMinusDst="one-minus-dst",e.DstAlpha="dst-alpha",e.OneMinusDstAlpha="one-minus-dst-alpha",e.SrcAlphaSaturated="src-alpha-saturated",e.Constant="constant",e.OneMinusConstant="one-minus-constant"}(tt||(tt={})),function(e){e.Add="add",e.Subtract="subtract",e.ReverseSubtract="reverse-subtract",e.Min="min",e.Max="max"}(ti||(ti={})),function(e){e.Keep="keep",e.Zero="zero",e.Replace="replace",e.Invert="invert",e.IncrementClamp="increment-clamp",e.DecrementClamp="decrement-clamp",e.IncrementWrap="increment-wrap",e.DecrementWrap="decrement-wrap"}(tr||(tr={})),function(e){e.Uint16="uint16",e.Uint32="uint32"}(ts||(ts={})),function(e){e.Uint8x2="uint8x2",e.Uint8x4="uint8x4",e.Sint8x2="sint8x2",e.Sint8x4="sint8x4",e.Unorm8x2="unorm8x2",e.Unorm8x4="unorm8x4",e.Snorm8x2="snorm8x2",e.Snorm8x4="snorm8x4",e.Uint16x2="uint16x2",e.Uint16x4="uint16x4",e.Sint16x2="sint16x2",e.Sint16x4="sint16x4",e.Unorm16x2="unorm16x2",e.Unorm16x4="unorm16x4",e.Snorm16x2="snorm16x2",e.Snorm16x4="snorm16x4",e.Float16x2="float16x2",e.Float16x4="float16x4",e.Float32="float32",e.Float32x2="float32x2",e.Float32x3="float32x3",e.Float32x4="float32x4",e.Uint32="uint32",e.Uint32x2="uint32x2",e.Uint32x3="uint32x3",e.Uint32x4="uint32x4",e.Sint32="sint32",e.Sint32x2="sint32x2",e.Sint32x3="sint32x3",e.Sint32x4="sint32x4",e.UNORM10x10x10x2="unorm10-10-10-2"}(ta||(ta={})),function(e){e.Vertex="vertex",e.Instance="instance"}(tn||(tn={})),function(e){e.Beginning="beginning",e.End="end"}(to||(to={})),function(e){e.Beginning="beginning",e.End="end"}(tl||(tl={})),function(e){e.Load="load",e.Clear="clear"}(th||(th={})),function(e){e.Store="store",e.Discard="discard"}(tc||(tc={})),function(e){e.Occlusion="occlusion",e.Timestamp="timestamp"}(tu||(tu={})),function(e){e.Opaque="opaque",e.Premultiplied="premultiplied"}(td||(td={})),function(e){e.Unknown="unknown",e.Destroyed="destroyed"}(t_||(t_={})),function(e){e.Validation="validation",e.OutOfMemory="out-of-memory",e.Internal="internal"}(tp||(tp={}));let WebGPUShaderProcessor=class WebGPUShaderProcessor{constructor(){this.shaderLanguage=q.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let t=0;t=0&&(u.push(n[l]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=u,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){for(let e of(this.uniformBuffer=new UniformBuffer(this.engine,void 0,void 0,"leftOver-"+this._name),this.shaderProcessingContext.leftOverUniforms)){let t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=WebGPUShaderProcessor.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.vertex}_getFragmentShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.fragment}};let rk={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};let WebGPUShaderProcessingContext=class WebGPUShaderProcessingContext{static get KnownUBOs(){return WebGPUShaderProcessingContext._SimplifiedKnownBindings?WebGPUShaderProcessingContext._SimplifiedKnownUBOs:WebGPUShaderProcessingContext._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){let e=WebGPUShaderProcessingContext.KnownUBOs,t=[];for(let i in e){let r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;let r=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=rk[e])&&void 0!==i?i:1)*(t||1),r}getVaryingNextLocation(e,t=0){var i;let r=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=rk[e])&&void 0!==i?i:1)*(t||1),r}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";let t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}};WebGPUShaderProcessingContext._SimplifiedKnownBindings=!0,WebGPUShaderProcessingContext._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},WebGPUShaderProcessingContext._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};let WebGPUShaderProcessorGLSL=class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=q.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0,s=e.indexOf("["),a=e.indexOf("]");if(s>0&&a>0){let t=e.substring(s+1,a);isNaN(r=+t)&&(r=+i[t.trim()]),e=e.substr(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){let i=`// Internals UBO -uniform ${WebGPUShaderProcessor.InternalsUBOName} { -float yFactor_; -float textureOutputHeight_; -}; -`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){let i=t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/;return i.test(e)}varyingProcessor(e,t,i){var r;this._preProcessors=i;let s=t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,a=s.exec(e);if(null!==a){let s;let n=null!==(r=a[1])&&void 0!==r?r:"",o=a[2],l=a[3];t?(s=this._webgpuProcessingContext.availableVaryings[l],this._missingVaryings[s]="",void 0===s&&logger_Logger.Warn(`Invalid fragment shader: The varying named "${l}" is not declared in the vertex shader! This declaration will be ignored.`)):(s=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(l,o,i)[2]),this._webgpuProcessingContext.availableVaryings[l]=s,this._missingVaryings[s]=`layout(location = ${s}) ${n} in ${o} ${l};`),e=e.replace(a[0],void 0===s?"":`layout(location = ${s}) ${n} ${t?"in":"out"} ${o} ${l};`)}return e}attributeProcessor(e,t){this._preProcessors=t;let i=this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,r=i.exec(e);if(null!==r){let i=r[1],s=r[2],a=this._webgpuProcessingContext.getAttributeNextLocation(i,this._getArraySize(s,i,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=a,this._webgpuProcessingContext.orderedAttributes[a]=s;let n=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==n){let t=`_int_${s}_`;e=e.replace(r[0],`layout(location = ${a}) in ${n<0?-1===n?"int":"ivec"+-n:1===n?"uint":"uvec"+n} ${t}; ${i} ${s} = ${i}(${t});`)}else e=e.replace(r[0],`layout(location = ${a}) in ${i} ${s};`)}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;let s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let a=s[1],n=s[2];if(0===a.indexOf("sampler")||1===a.indexOf("sampler")){let s=0;[n,a,s]=this._getArraySize(n,a,i);let o=this._webgpuProcessingContext.availableTextures[n];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:e2.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}let l=null!==(r=WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[a])&&void 0!==r?r:"sampler",h=!!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[l],c=h?e1.Comparison:e1.Filtering,u=n+WebGPUShaderProcessor.AutoSamplerSuffix,d=this._webgpuProcessingContext.availableSamplers[u];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:c});let _="u"===a.charAt(0)?"u":"i"===a.charAt(0)?"i":"";_&&(a=a.substr(1));let p=h?e2.Depth:"u"===_?e2.Uint:"i"===_?e2.Sint:e2.Float;o.sampleType=p;let f=s>0,m=d.binding.groupIndex,g=d.binding.bindingIndex,v=WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[a],x=WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[a],b=WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[x];if(f){let t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${_}${l} ${u};`),e=` -`;for(let i=0;i0?"\n":""}#define ${n}${i} ${_}${v}(${n}Texture${i}, ${u})`}e=t.join("\n")+e,this._textureArrayProcessing.push(n)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${l} ${u}; - layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${_}${x} ${n}Texture; - #define ${n} ${_}${v}(${n}Texture, ${u})`;this._webgpuProcessingContext.availableTextures[n]=o,this._webgpuProcessingContext.availableSamplers[u]=d,this._addSamplerBindingDescription(u,d,!t);for(let e=0;e=0,i=` - glFragCoord_ = gl_FragCoord; - if (yFactor_ == 1.) { - glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; - } - `,r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(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(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){let t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(a||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",t?"vec4 glFragCoord_;\n":""),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else{e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex");let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}if(!i){let t=e.lastIndexOf("}");e=e.substring(0,t)+"gl_Position.y *= yFactor_;\n",s.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){let i=RegExp(t+"\\s*\\[(.+)?\\]","gm"),r=i.exec(e);for(;null!==r;){let s=r[1],a=+s;this._preProcessors&&isNaN(a)&&(a=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+a),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { - `;for(let e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}]; -`:i+=` ${e.type} ${e.name}; -`;return i+"};\n\n"}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}let i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}};let rG=`#if NUM_BONE_INFLUENCERS>0 -attribute matricesIndices : vec4;attribute matricesWeights : vec4; -#if NUM_BONE_INFLUENCERS>4 -attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; -#endif -#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#ifdef BONETEXTURE -var boneSampler : texture_2d;uniform boneTextureWidth : f32; -#else -uniform mBones : array; -#ifdef BONES_VELOCITY_ENABLED -uniform mPreviousBones : array; -#endif -#endif -#ifdef BONETEXTURE -fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 -{let offset=i32(index) *4; -let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStoreWGSL.bonesDeclaration=rG;let rz=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#if NUM_BONE_INFLUENCERS>0 -var influence : mat4x4; -#ifdef BONETEXTURE -influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; -#endif -#else -influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; -#endif -#endif -finalWorld=finalWorld*influence; -#endif -#endif -`;ShaderStore.IncludesShadersStoreWGSL.bonesVertex=rz;let rW=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; -#ifdef INSTANCES -attribute bakedVertexAnimationSettingsInstanced : vec4; -#endif -fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 -{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} -#endif -`;ShaderStore.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration=rW;let rH=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -{ -#ifdef INSTANCES -let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; -#else -let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; -#endif -let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; -#endif -finalWorld=finalWorld*VATInfluence;} -#endif -`;ShaderStore.IncludesShadersStoreWGSL.bakedVertexAnimation=rH;let rX=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -if (false) {} -#endif -#ifdef CLIPPLANE -else if (fragmentInputs.fClipDistance>0.0) -{discard;} -#endif -#ifdef CLIPPLANE2 -else if (fragmentInputs.fClipDistance2>0.0) -{discard;} -#endif -#ifdef CLIPPLANE3 -else if (fragmentInputs.fClipDistance3>0.0) -{discard;} -#endif -#ifdef CLIPPLANE4 -else if (fragmentInputs.fClipDistance4>0.0) -{discard;} -#endif -#ifdef CLIPPLANE5 -else if (fragmentInputs.fClipDistance5>0.0) -{discard;} -#endif -#ifdef CLIPPLANE6 -else if (fragmentInputs.fClipDistance6>0.0) -{discard;} -#endif -`;ShaderStore.IncludesShadersStoreWGSL.clipPlaneFragment=rX;let rY=`#ifdef CLIPPLANE -varying fClipDistance: f32; -#endif -#ifdef CLIPPLANE2 -varying fClipDistance2: f32; -#endif -#ifdef CLIPPLANE3 -varying fClipDistance3: f32; -#endif -#ifdef CLIPPLANE4 -varying fClipDistance4: f32; -#endif -#ifdef CLIPPLANE5 -varying fClipDistance5: f32; -#endif -#ifdef CLIPPLANE6 -varying fClipDistance6: f32; -#endif -`;ShaderStore.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration=rY;let rj=`#ifdef CLIPPLANE -vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); -#endif -#ifdef CLIPPLANE2 -vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); -#endif -#ifdef CLIPPLANE3 -vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); -#endif -#ifdef CLIPPLANE4 -vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); -#endif -#ifdef CLIPPLANE5 -vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); -#endif -#ifdef CLIPPLANE6 -vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); -#endif -`;ShaderStore.IncludesShadersStoreWGSL.clipPlaneVertex=rj;let rK=`#ifdef CLIPPLANE -uniform vClipPlane: vec4;varying fClipDistance: f32; -#endif -#ifdef CLIPPLANE2 -uniform vClipPlane2: vec4;varying fClipDistance2: f32; -#endif -#ifdef CLIPPLANE3 -uniform vClipPlane3: vec4;varying fClipDistance3: f32; -#endif -#ifdef CLIPPLANE4 -uniform vClipPlane4: vec4;varying fClipDistance4: f32; -#endif -#ifdef CLIPPLANE5 -uniform vClipPlane5: vec4;varying fClipDistance5: f32; -#endif -#ifdef CLIPPLANE6 -uniform vClipPlane6: vec4;varying fClipDistance6: f32; -#endif -`;ShaderStore.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration=rK;let rq=`#ifdef INSTANCES -attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; -#ifdef INSTANCESCOLOR -attribute instanceColor : vec4; -#endif -#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) -uniform world : mat4x4; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; -#ifdef THIN_INSTANCES -uniform previousWorld : mat4x4; -#endif -#endif -#else -#if !defined(WORLD_UBO) -uniform world : mat4x4; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -uniform previousWorld : mat4x4; -#endif -#endif -`;ShaderStore.IncludesShadersStoreWGSL.instancesDeclaration=rq;let r$=`#ifdef INSTANCES -var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -var finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); -#endif -#ifdef THIN_INSTANCES -#if !defined(WORLD_UBO) -finalWorld=uniforms.world*finalWorld; -#else -finalWorld=mesh.world*finalWorld; -#endif -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -finalPreviousWorld=previousWorld*finalPreviousWorld; -#endif -#endif -#else -#if !defined(WORLD_UBO) -var finalWorld=uniforms.world; -#else -var finalWorld=mesh.world; -#endif -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -var finalPreviousWorld=previousWorld; -#endif -#endif -`;ShaderStore.IncludesShadersStoreWGSL.instancesVertex=r$;let rQ=`struct Mesh {world : mat4x4, -visibility : f32,};var mesh : Mesh; -#define WORLD_UBO -`;ShaderStore.IncludesShadersStoreWGSL.meshUboDeclaration=rQ;let rZ=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#ifdef MORPHTARGETS_NORMAL -normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; -#endif -#else -positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStoreWGSL.morphTargetsVertex=rZ;let rJ=`#ifdef MORPHTARGETS -#ifndef MORPHTARGETS_TEXTURE -attribute position{X} : vec3; -#ifdef MORPHTARGETS_NORMAL -attribute normal{X} : vec3; -#endif -#ifdef MORPHTARGETS_TANGENT -attribute tangent{X} : vec3; -#endif -#ifdef MORPHTARGETS_UV -attribute uv_{X} : vec2; -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration=rJ;let r0=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -var vertexID : f32; -#endif -#endif -`;ShaderStore.IncludesShadersStoreWGSL.morphTargetsVertexGlobal=r0;let r1=`#ifdef MORPHTARGETS -uniform morphTargetInfluences : array; -#ifdef MORPHTARGETS_TEXTURE -uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 -{ -let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} -#endif -#endif -`;ShaderStore.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration=r1;let r2=`struct Scene {viewProjection : mat4x4, -#ifdef MULTIVIEW -viewProjectionR : mat4x4, -#endif -view : mat4x4, -projection : mat4x4, -vEyePosition : vec4,};var scene : Scene; -`;ShaderStore.IncludesShadersStoreWGSL.sceneUboDeclaration=r2;let r3="fragmentOutputs.fragDepth",r4={texture_1d:eY.E1d,texture_2d:eY.E2d,texture_2d_array:eY.E2dArray,texture_3d:eY.E3d,texture_cube:eY.Cube,texture_cube_array:eY.CubeArray,texture_multisampled_2d:eY.E2d,texture_depth_2d:eY.E2d,texture_depth_2d_array:eY.E2dArray,texture_depth_cube:eY.Cube,texture_depth_cube_array:eY.CubeArray,texture_depth_multisampled_2d:eY.E2d,texture_storage_1d:eY.E1d,texture_storage_2d:eY.E2d,texture_storage_2d_array:eY.E2dArray,texture_storage_3d:eY.E3d,texture_external:null};let WebGPUShaderProcessorWGSL=class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor{constructor(){super(...arguments),this.shaderLanguage=q.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let r=0,s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;let a=t.substring(e+1,s);for(isNaN(r=+a)&&(r=+i[a.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${WebGPUShaderProcessor.InternalsUBOName} { - yFactor_: f32, - textureOutputHeight_: f32, -}; -var internals : ${WebGPUShaderProcessor.InternalsUBOName}; -`+RemoveComments(e)}varyingProcessor(e,t,i){let r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==r){let s;let a=r[2],n=r[1];t?void 0===(s=this._webgpuProcessingContext.availableVaryings[n])&&logger_Logger.Warn(`Invalid fragment shader: The varying named "${n}" is not declared in the vertex shader! This declaration will be ignored.`):(s=this._webgpuProcessingContext.getVaryingNextLocation(a,this._getArraySize(n,a,i)[2]),this._webgpuProcessingContext.availableVaryings[n]=s,this._varyingsWGSL.push(` @location(${s}) ${n} : ${a},`),this._varyingNamesWGSL.push(n)),e=""}return e}attributeProcessor(e,t){let i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){let r=i[2],s=i[1],a=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=a,this._webgpuProcessingContext.orderedAttributes[a]=s;let n=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==n){let e=`_int_${s}_`;this._attributesInputWGSL.push(`@location(${a}) ${e} : ${n<0?-1===n?"i32":"vec"+-n+"":1===n?"u32":"vec"+n+""},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = ${r}(vertexInputs_.${e});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${a}) ${s} : ${r},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = vertexInputs_.${s};`);e=""}return e}uniformProcessor(e,t,i){let r=this.uniformRegexp.exec(e);if(null!==r){let t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){let r=this.textureRegexp.exec(e);if(null!==r){let s=r[1],a=r[2],n=!!r[3],o=r[4],l=o.indexOf("storage")>0,h=r[6],c=l?h.substring(0,h.indexOf(",")).trim():null,u=n?this._getArraySize(s,a,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)u=d.textures.length;else{d={isTextureArray:u>0,isStorageTexture:l,textures:[],sampleType:e2.Float},u=u||1;for(let e=0;e0,p=r4[o],f=_?e2.Depth:"u32"===h?e2.Uint:"i32"===h?e2.Sint:e2.Float;if(d.sampleType=f,void 0===p)throw`Can't get the texture dimension corresponding to the texture function "${o}"!`;for(let i=0;i=0?` - if (internals.yFactor_ == 1.) { - fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; - } - `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);let r=this._buildLeftOverUBO();e=r+e,t=r+t,e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join("\n")),s+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(s+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n"+this._attributesWGSL.join("\n")+"\n};\nvar vertexInputs : VertexInputs_;\n");let a="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(a+=this._varyingsWGSL.join("\n")),a+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=s+a+e;let n=` - vertexInputs${this._hasNonFloatAttribute?"_":""} = input; -`;this._hasNonFloatAttribute&&(n+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n"+this._attributesConversionCodeWGSL.join("\n")+"\n");let o=` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; - return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",n,o),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4,\n",c=!1,u=0;for(;!c&&!((u=t.indexOf(r3,u))<0);){let e=u;for(c=!0;u>1&&"\n"!==t.charAt(u);){if("/"===t.charAt(u)&&"/"===t.charAt(u-1)){c=!1;break}u--}u=e+r3.length}return c&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=l+h+t,t=this._injectStartingAndEndingCode(t,"fn main"," fragmentInputs = input;\n "+i," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { -`;for(let t of this._webgpuProcessingContext.leftOverUniforms){let s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),a=WebGPUShaderProcessor.UniformSizes[s];if(t.length>0){if(a<=2){let a=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${a} { - @size(16) - el: ${s}, - }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${a}, ${t.length}>, -`}else r+=` ${t.name} : array<${t.type}, ${t.length}>, -`}else r+=` ${t.name} : ${t.type}, -`}return r+="};\n",r=`${i} -${r}@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e}; -`}_processSamplers(e,t){let i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],a=r[2],n=s.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)===s.length-WebGPUShaderProcessor.AutoSamplerSuffix.length?s.substring(0,s.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)):null,o="sampler_comparison"===a?e1.Comparison:e1.Filtering;if(n){let e=this._webgpuProcessingContext.availableTextures[n];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:o},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);let h=e.substring(0,r.index),c=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,u=e.substring(r.index);e=h+c+u,i.lastIndex+=c.length}return e}_processCustomBuffers(e,t){let i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],a=r[3],n=r[4],o=r[5],l=this._webgpuProcessingContext.availableBuffers[n];if(!l){let e;let t="uniform"===s?WebGPUShaderProcessingContext.KnownUBOs[o]:null;t?(n=o,-1===(e=t.binding).groupIndex&&(e=this._webgpuProcessingContext.getNextFreeUBOBinding())):e=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:e},this._webgpuProcessingContext.availableBuffers[n]=l}this._addBufferBindingDescription(n,this._webgpuProcessingContext.availableBuffers[n],"read_write"===a?e0.Storage:"storage"===s?e0.ReadOnlyStorage:e0.Uniform,t);let h=l.binding.groupIndex,c=l.binding.bindingIndex,u=e.substring(0,r.index),d=`@group(${h}) @binding(${c}) `,_=e.substring(r.index);e=u+d+_,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(let t of this._stridedUniformArrays)e=e.replace(RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}};let WebGPUHardwareTexture=class WebGPUHardwareTexture{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return null!==(i=null===(t=this._webgpuMSAATexture)||void 0===t?void 0:t[e])&&void 0!==i?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(let e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=eK.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s){this.createView({format:this.format,dimension:i?eY.Cube:eY.E2d,mipLevelCount:t?math_scalar_Scalar.ILog2(Math.max(r,s))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:ej.All})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){let t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;null===(e=this._webgpuTexture)||void 0===e||e.destroy(),this.releaseMSAATexture(),null===(t=this._copyInvertYTempTexture)||void 0===t||t.destroy(),this.reset()}};let r5=` - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); - - layout(location = 0) out vec2 vTex; - - void main() { - vTex = tex[gl_VertexIndex]; - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,r6=` - layout(set = 0, binding = 0) uniform sampler imgSampler; - layout(set = 0, binding = 1) uniform texture2D img; - - layout(location = 0) in vec2 vTex; - layout(location = 0) out vec4 outColor; - - void main() { - outColor = texture(sampler2D(img, imgSampler), vTex); - } - `,r8=` - #extension GL_EXT_samplerless_texture_functions : enable - - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); - - layout(set = 0, binding = 0) uniform texture2D img; - - #ifdef INVERTY - layout(location = 0) out flat ivec2 vTextureSize; - #endif - - void main() { - #ifdef INVERTY - vTextureSize = textureSize(img, 0); - #endif - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,r7=` - #extension GL_EXT_samplerless_texture_functions : enable - - layout(set = 0, binding = 0) uniform texture2D img; - - #ifdef INVERTY - layout(location = 0) in flat ivec2 vTextureSize; - #endif - layout(location = 0) out vec4 outColor; - - void main() { - #ifdef INVERTY - vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); - #else - vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); - #endif - #ifdef PREMULTIPLYALPHA - color.rgb *= color.a; - #endif - outColor = color; - } - `,r9=` - #extension GL_EXT_samplerless_texture_functions : enable - - layout(set = 0, binding = 0) uniform texture2D img; - layout(set = 0, binding = 1) uniform Params { - float ofstX; - float ofstY; - float width; - float height; - }; - - #ifdef INVERTY - layout(location = 0) in flat ivec2 vTextureSize; - #endif - layout(location = 0) out vec4 outColor; - - void main() { - if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { - discard; - } - if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { - discard; - } - #ifdef INVERTY - vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); - #else - vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); - #endif - #ifdef PREMULTIPLYALPHA - color.rgb *= color.a; - #endif - outColor = color; - } - `,se=` - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - - void main() { - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,st=` - layout(set = 0, binding = 0) uniform Uniforms { - uniform vec4 color; - }; - - layout(location = 0) out vec4 outColor; - - void main() { - outColor = color; - } - `,si=` - struct VertexOutput { - @builtin(position) Position : vec4, - @location(0) fragUV : vec2 - } - - @vertex - fn main( - @builtin(vertex_index) VertexIndex : u32 - ) -> VertexOutput { - var pos = array, 4>( - vec2(-1.0, 1.0), - vec2( 1.0, 1.0), - vec2(-1.0, -1.0), - vec2( 1.0, -1.0) - ); - var tex = array, 4>( - vec2(0.0, 0.0), - vec2(1.0, 0.0), - vec2(0.0, 1.0), - vec2(1.0, 1.0) - ); - - var output: VertexOutput; - - output.Position = vec4(pos[VertexIndex], 0.0, 1.0); - output.fragUV = tex[VertexIndex]; - - return output; - } - `,sr=` - @group(0) @binding(0) var videoSampler: sampler; - @group(0) @binding(1) var videoTexture: texture_external; - - @fragment - fn main( - @location(0) fragUV: vec2 - ) -> @location(0) vec4 { - return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); - } - `,ss=` - @group(0) @binding(0) var videoSampler: sampler; - @group(0) @binding(1) var videoTexture: texture_external; - - @fragment - fn main( - @location(0) fragUV: vec2 - ) -> @location(0) vec4 { - return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y)); - } - `;(function(e){e[e.MipMap=0]="MipMap",e[e.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",e[e.Clear=2]="Clear",e[e.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst"})(tf||(tf={})),function(e){e[e.DontInvertY=0]="DontInvertY",e[e.InvertY=1]="InvertY"}(tm||(tm={}));let sa=[{vertex:r5,fragment:r6},{vertex:r8,fragment:r7},{vertex:se,fragment:st},{vertex:r8,fragment:r9}],sn={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};let WebGPUTextureHelper=class WebGPUTextureHelper{static ComputeNumMipmapLevels(e,t){return math_scalar_Scalar.ILog2(Math.max(e,t))+1}constructor(e,t,i,r,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=r,-1!==s.indexOf(ek.RG11B10UFloatRenderable)){let e=Object.keys(sn);sn[eK.RG11B10UFloat]=sn[e[e.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:e$.Linear}),this._videoSampler=e.createSampler({minFilter:e$.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,ez.Uniform|ez.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(eK.RGBA8Unorm),this._getVideoPipeline(eK.RGBA8Unorm)}_getPipeline(e,t=tf.MipMap,i){let r=t===tf.MipMap?1:t===tf.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===tf.Clear?8:t===tf.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let a="#version 450\n";(t===tf.InvertYPremultiplyAlpha||t===tf.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(a+="#define INVERTY\n"),i.premultiplyAlpha&&(a+="#define PREMULTIPLYALPHA\n"));let n=this._compiledShaders[r];if(!n){let e=this._glslang.compileGLSL(a+sa[t].vertex,"vertex"),i=this._glslang.compileGLSL(a+sa[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));let s=this._device.createShaderModule({code:e}),o=this._device.createShaderModule({code:i});n=this._compiledShaders[r]=[s,o]}let o=this._device.createRenderPipeline({layout:e6.Auto,vertex:{module:n[0],entryPoint:"main"},fragment:{module:n[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:e8.TriangleStrip,stripIndexFormat:ts.Uint16}});s=this._pipelines[e][r]=[o,o.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=tm.DontInvertY){let i=t===tm.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){let e=this._device.createShaderModule({code:si}),r=this._device.createShaderModule({code:0===i?sr:ss});t=this._videoCompiledShaders[i]=[e,r]}let s=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:e6.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:e8.TriangleStrip,stripIndexFormat:ts.Uint16}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}static _GetTextureTypeFromFormat(e){switch(e){case eK.R8Unorm:case eK.R8Snorm:case eK.R8Uint:case eK.R8Sint:case eK.RG8Unorm:case eK.RG8Snorm:case eK.RG8Uint:case eK.RG8Sint:case eK.RGBA8Unorm:case eK.RGBA8UnormSRGB:case eK.RGBA8Snorm:case eK.RGBA8Uint:case eK.RGBA8Sint:case eK.BGRA8Unorm:case eK.BGRA8UnormSRGB:case eK.RGB10A2UINT:case eK.RGB10A2Unorm:case eK.RGB9E5UFloat:case eK.RG11B10UFloat:case eK.Depth32FloatStencil8:case eK.BC7RGBAUnorm:case eK.BC7RGBAUnormSRGB:case eK.BC6HRGBUFloat:case eK.BC6HRGBFloat:case eK.BC5RGUnorm:case eK.BC5RGSnorm:case eK.BC3RGBAUnorm:case eK.BC3RGBAUnormSRGB:case eK.BC2RGBAUnorm:case eK.BC2RGBAUnormSRGB:case eK.BC4RUnorm:case eK.BC4RSnorm:case eK.BC1RGBAUnorm:case eK.BC1RGBAUnormSRGB:case eK.ETC2RGB8Unorm:case eK.ETC2RGB8UnormSRGB:case eK.ETC2RGB8A1Unorm:case eK.ETC2RGB8A1UnormSRGB:case eK.ETC2RGBA8Unorm:case eK.ETC2RGBA8UnormSRGB:case eK.EACR11Unorm:case eK.EACR11Snorm:case eK.EACRG11Unorm:case eK.EACRG11Snorm:case eK.ASTC4x4Unorm:case eK.ASTC4x4UnormSRGB:case eK.ASTC5x4Unorm:case eK.ASTC5x4UnormSRGB:case eK.ASTC5x5Unorm:case eK.ASTC5x5UnormSRGB:case eK.ASTC6x5Unorm:case eK.ASTC6x5UnormSRGB:case eK.ASTC6x6Unorm:case eK.ASTC6x6UnormSRGB:case eK.ASTC8x5Unorm:case eK.ASTC8x5UnormSRGB:case eK.ASTC8x6Unorm:case eK.ASTC8x6UnormSRGB:case eK.ASTC8x8Unorm:case eK.ASTC8x8UnormSRGB:case eK.ASTC10x5Unorm:case eK.ASTC10x5UnormSRGB:case eK.ASTC10x6Unorm:case eK.ASTC10x6UnormSRGB:case eK.ASTC10x8Unorm:case eK.ASTC10x8UnormSRGB:case eK.ASTC10x10Unorm:case eK.ASTC10x10UnormSRGB:case eK.ASTC12x10Unorm:case eK.ASTC12x10UnormSRGB:case eK.ASTC12x12Unorm:case eK.ASTC12x12UnormSRGB:break;case eK.R16Uint:case eK.R16Sint:case eK.RG16Uint:case eK.RG16Sint:case eK.RGBA16Uint:case eK.RGBA16Sint:case eK.Depth16Unorm:return 5;case eK.R16Float:case eK.RG16Float:case eK.RGBA16Float:return 2;case eK.R32Uint:case eK.R32Sint:case eK.RG32Uint:case eK.RG32Sint:case eK.RGBA32Uint:case eK.RGBA32Sint:return 7;case eK.R32Float:case eK.RG32Float:case eK.RGBA32Float:case eK.Depth32Float:return 1;case eK.Stencil8:throw"No fixed size for Stencil8 format!";case eK.Depth24Plus:throw"No fixed size for Depth24Plus format!";case eK.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case eK.R8Unorm:case eK.R8Snorm:case eK.R8Uint:case eK.R8Sint:return{width:1,height:1,length:1};case eK.R16Uint:case eK.R16Sint:case eK.R16Float:case eK.RG8Unorm:case eK.RG8Snorm:case eK.RG8Uint:case eK.RG8Sint:return{width:1,height:1,length:2};case eK.R32Uint:case eK.R32Sint:case eK.R32Float:case eK.RG16Uint:case eK.RG16Sint:case eK.RG16Float:case eK.RGBA8Unorm:case eK.RGBA8UnormSRGB:case eK.RGBA8Snorm:case eK.RGBA8Uint:case eK.RGBA8Sint:case eK.BGRA8Unorm:case eK.BGRA8UnormSRGB:case eK.RGB9E5UFloat:case eK.RGB10A2UINT:case eK.RGB10A2Unorm:case eK.RG11B10UFloat:break;case eK.RG32Uint:case eK.RG32Sint:case eK.RG32Float:case eK.RGBA16Uint:case eK.RGBA16Sint:case eK.RGBA16Float:return{width:1,height:1,length:8};case eK.RGBA32Uint:case eK.RGBA32Sint:case eK.RGBA32Float:return{width:1,height:1,length:16};case eK.Stencil8:throw"No fixed size for Stencil8 format!";case eK.Depth16Unorm:return{width:1,height:1,length:2};case eK.Depth24Plus:throw"No fixed size for Depth24Plus format!";case eK.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case eK.Depth32Float:break;case eK.Depth32FloatStencil8:return{width:1,height:1,length:5};case eK.BC7RGBAUnorm:case eK.BC7RGBAUnormSRGB:case eK.BC6HRGBUFloat:case eK.BC6HRGBFloat:case eK.BC5RGUnorm:case eK.BC5RGSnorm:case eK.BC3RGBAUnorm:case eK.BC3RGBAUnormSRGB:case eK.BC2RGBAUnorm:case eK.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case eK.BC4RUnorm:case eK.BC4RSnorm:case eK.BC1RGBAUnorm:case eK.BC1RGBAUnormSRGB:case eK.ETC2RGB8Unorm:case eK.ETC2RGB8UnormSRGB:case eK.ETC2RGB8A1Unorm:case eK.ETC2RGB8A1UnormSRGB:case eK.EACR11Unorm:case eK.EACR11Snorm:return{width:4,height:4,length:8};case eK.ETC2RGBA8Unorm:case eK.ETC2RGBA8UnormSRGB:case eK.EACRG11Unorm:case eK.EACRG11Snorm:case eK.ASTC4x4Unorm:case eK.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case eK.ASTC5x4Unorm:case eK.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case eK.ASTC5x5Unorm:case eK.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case eK.ASTC6x5Unorm:case eK.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case eK.ASTC6x6Unorm:case eK.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case eK.ASTC8x5Unorm:case eK.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case eK.ASTC8x6Unorm:case eK.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case eK.ASTC8x8Unorm:case eK.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case eK.ASTC10x5Unorm:case eK.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case eK.ASTC10x6Unorm:case eK.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case eK.ASTC10x8Unorm:case eK.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case eK.ASTC10x10Unorm:case eK.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case eK.ASTC12x10Unorm:case eK.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case eK.ASTC12x12Unorm:case eK.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static _IsHardwareTexture(e){return!!e.release}static _IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}setCommandEncoder(e){this._commandEncoderForCreation=e}static IsCompressedFormat(e){switch(e){case eK.BC7RGBAUnormSRGB:case eK.BC7RGBAUnorm:case eK.BC6HRGBFloat:case eK.BC6HRGBUFloat:case eK.BC5RGSnorm:case eK.BC5RGUnorm:case eK.BC4RSnorm:case eK.BC4RUnorm:case eK.BC3RGBAUnormSRGB:case eK.BC3RGBAUnorm:case eK.BC2RGBAUnormSRGB:case eK.BC2RGBAUnorm:case eK.BC1RGBAUnormSRGB:case eK.BC1RGBAUnorm:case eK.ETC2RGB8Unorm:case eK.ETC2RGB8UnormSRGB:case eK.ETC2RGB8A1Unorm:case eK.ETC2RGB8A1UnormSRGB:case eK.ETC2RGBA8Unorm:case eK.ETC2RGBA8UnormSRGB:case eK.EACR11Unorm:case eK.EACR11Snorm:case eK.EACRG11Unorm:case eK.EACRG11Snorm:case eK.ASTC4x4Unorm:case eK.ASTC4x4UnormSRGB:case eK.ASTC5x4Unorm:case eK.ASTC5x4UnormSRGB:case eK.ASTC5x5Unorm:case eK.ASTC5x5UnormSRGB:case eK.ASTC6x5Unorm:case eK.ASTC6x5UnormSRGB:case eK.ASTC6x6Unorm:case eK.ASTC6x6UnormSRGB:case eK.ASTC8x5Unorm:case eK.ASTC8x5UnormSRGB:case eK.ASTC8x6Unorm:case eK.ASTC8x6UnormSRGB:case eK.ASTC8x8Unorm:case eK.ASTC8x8UnormSRGB:case eK.ASTC10x5Unorm:case eK.ASTC10x5UnormSRGB:case eK.ASTC10x6Unorm:case eK.ASTC10x6UnormSRGB:case eK.ASTC10x8Unorm:case eK.ASTC10x8UnormSRGB:case eK.ASTC10x10Unorm:case eK.ASTC10x10UnormSRGB:case eK.ASTC12x10Unorm:case eK.ASTC12x10UnormSRGB:case eK.ASTC12x12Unorm:case eK.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return eK.Depth16Unorm;case 16:return eK.Depth24Plus;case 13:return eK.Depth24PlusStencil8;case 14:return eK.Depth32Float;case 18:return eK.Depth32FloatStencil8;case 19:return eK.Stencil8;case 36492:return i?eK.BC7RGBAUnormSRGB:eK.BC7RGBAUnorm;case 36495:return eK.BC6HRGBUFloat;case 36494:return eK.BC6HRGBFloat;case 33779:return i?eK.BC3RGBAUnormSRGB:eK.BC3RGBAUnorm;case 33778:return i?eK.BC2RGBAUnormSRGB:eK.BC2RGBAUnorm;case 33777:case 33776:return i?eK.BC1RGBAUnormSRGB:eK.BC1RGBAUnorm;case 37808:return i?eK.ASTC4x4UnormSRGB:eK.ASTC4x4Unorm;case 36196:case 37492:return i?eK.ETC2RGB8UnormSRGB:eK.ETC2RGB8Unorm;case 37496:return i?eK.ETC2RGBA8UnormSRGB:eK.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return eK.R8Snorm;case 7:return eK.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return eK.R8Sint;case 9:return eK.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return eK.RGBA8Sint;default:return eK.RGBA8Snorm}case 0:switch(t){case 6:return eK.R8Unorm;case 7:return eK.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?eK.RGBA8UnormSRGB:eK.RGBA8Unorm;case 12:return i?eK.BGRA8UnormSRGB:eK.BGRA8Unorm;case 8:return eK.R8Uint;case 9:return eK.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return eK.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return eK.RGBA8Unorm}case 4:switch(t){case 8:return eK.R16Sint;case 9:return eK.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return eK.RGBA16Sint}case 5:switch(t){case 8:return eK.R16Uint;case 9:return eK.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return eK.RGBA16Uint}case 6:switch(t){case 8:return eK.R32Sint;case 9:return eK.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return eK.RGBA32Sint}case 7:switch(t){case 8:return eK.R32Uint;case 9:return eK.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return eK.RGBA32Uint}case 1:switch(t){case 6:return eK.R32Float;case 7:return eK.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return eK.RGBA32Float}case 2:switch(t){case 6:return eK.R16Float;case 7:return eK.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return eK.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return eK.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return eK.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return eK.RGB10A2Unorm;case 11:return eK.RGB10A2UINT}}return i?eK.RGBA8UnormSRGB:eK.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case eK.R8Unorm:case eK.R8Snorm:case eK.R8Uint:case eK.R8Sint:case eK.BC4RUnorm:case eK.BC4RSnorm:case eK.R16Uint:case eK.R16Sint:case eK.Depth16Unorm:case eK.R16Float:case eK.R32Uint:case eK.R32Sint:case eK.R32Float:case eK.Depth32Float:case eK.Stencil8:case eK.Depth24Plus:case eK.EACR11Unorm:case eK.EACR11Snorm:return 1;case eK.RG8Unorm:case eK.RG8Snorm:case eK.RG8Uint:case eK.RG8Sint:case eK.Depth32FloatStencil8:case eK.BC5RGUnorm:case eK.BC5RGSnorm:case eK.RG16Uint:case eK.RG16Sint:case eK.RG16Float:case eK.RG32Uint:case eK.RG32Sint:case eK.RG32Float:case eK.Depth24PlusStencil8:case eK.EACRG11Unorm:case eK.EACRG11Snorm:return 2;case eK.RGB9E5UFloat:case eK.RG11B10UFloat:case eK.BC6HRGBUFloat:case eK.BC6HRGBFloat:case eK.ETC2RGB8Unorm:case eK.ETC2RGB8UnormSRGB:return 3;case eK.RGBA8Unorm:case eK.RGBA8UnormSRGB:case eK.RGBA8Snorm:case eK.RGBA8Uint:case eK.RGBA8Sint:case eK.BGRA8Unorm:case eK.BGRA8UnormSRGB:case eK.RGB10A2UINT:case eK.RGB10A2Unorm:case eK.BC7RGBAUnorm:case eK.BC7RGBAUnormSRGB:case eK.BC3RGBAUnorm:case eK.BC3RGBAUnormSRGB:case eK.BC2RGBAUnorm:case eK.BC2RGBAUnormSRGB:case eK.BC1RGBAUnorm:case eK.BC1RGBAUnormSRGB:case eK.RGBA16Uint:case eK.RGBA16Sint:case eK.RGBA16Float:case eK.RGBA32Uint:case eK.RGBA32Sint:case eK.RGBA32Float:case eK.ETC2RGB8A1Unorm:case eK.ETC2RGB8A1UnormSRGB:case eK.ETC2RGBA8Unorm:case eK.ETC2RGBA8UnormSRGB:case eK.ASTC4x4Unorm:case eK.ASTC4x4UnormSRGB:case eK.ASTC5x4Unorm:case eK.ASTC5x4UnormSRGB:case eK.ASTC5x5Unorm:case eK.ASTC5x5UnormSRGB:case eK.ASTC6x5Unorm:case eK.ASTC6x5UnormSRGB:case eK.ASTC6x6Unorm:case eK.ASTC6x6UnormSRGB:case eK.ASTC8x5Unorm:case eK.ASTC8x5UnormSRGB:case eK.ASTC8x6Unorm:case eK.ASTC8x6UnormSRGB:case eK.ASTC8x8Unorm:case eK.ASTC8x8UnormSRGB:case eK.ASTC10x5Unorm:case eK.ASTC10x5UnormSRGB:case eK.ASTC10x6Unorm:case eK.ASTC10x6UnormSRGB:case eK.ASTC10x8Unorm:case eK.ASTC10x8UnormSRGB:case eK.ASTC10x10Unorm:case eK.ASTC10x10UnormSRGB:case eK.ASTC12x10Unorm:case eK.ASTC12x10UnormSRGB:case eK.ASTC12x12Unorm:case eK.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case eK.Stencil8:case eK.Depth32FloatStencil8:case eK.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case eK.Depth32FloatStencil8:case eK.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case eK.Depth16Unorm:return eK.Depth16Unorm;case eK.Depth24Plus:case eK.Depth24PlusStencil8:return eK.Depth24Plus;case eK.Depth32Float:case eK.Depth32FloatStencil8:return eK.Depth32Float}return e}copyVideoToTexture(e,t,i,r=!1,s){var a,n,o,l;let h=void 0===s,[c,u]=this._getVideoPipeline(i,r?tm.InvertY:tm.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(n=(a=s).pushDebugGroup)||void 0===n||n.call(a,`copy video to texture - invertY=${r}`);let d=t._hardwareTexture,_={colorAttachments:[{view:d.underlyingResource.createView({format:i,dimension:eY.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:ej.All}),loadOp:th.Load,storeOp:tc.Store}]},p=s.beginRenderPass(_),f={layout:u,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},m=this._device.createBindGroup(f);p.setPipeline(c),p.setBindGroup(0,m),p.draw(4,1,0,0),p.end(),null===(l=(o=s).popDebugGroup)||void 0===l||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,a=!1,n=0,o=0,l=1,h=0,c=0,u=0,d=0,_,p){var f,m,g,v,x,b;let T;let S=0!==u,C=void 0===_,[E,y]=this._getPipeline(r,S?tf.InvertYPremultiplyAlphaWithOfst:tf.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:a});if(n=Math.max(n,0),C&&(_=this._device.createCommandEncoder({})),null===(m=(f=_).pushDebugGroup)||void 0===m||m.call(f,`internal process texture - invertY=${s} premultiplyAlpha=${a}`),WebGPUTextureHelper._IsHardwareTexture(e)?(T=e.underlyingResource,s&&!a&&1===l&&0===n||(e=void 0)):(T=e,e=void 0),!T)return;S&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,c,u,d]),0,16);let R=e,P=null!==(g=null==R?void 0:R._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,_,eX.CopySrc|eX.RenderAttachment|eX.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),A=null!==(v=null==R?void 0:R._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:P.createView({format:r,dimension:eY.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:th.Load,storeOp:tc.Store}]},M=_.beginRenderPass(A),I=S?null==R?void 0:R._copyInvertYBindGroupWithOfst:null==R?void 0:R._copyInvertYBindGroup;if(!I){let e={layout:y,entries:[{binding:0,resource:T.createView({format:r,dimension:eY.E2d,baseMipLevel:o,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:n})}]};S&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),I=this._device.createBindGroup(e)}M.setPipeline(E),M.setBindGroup(0,I),M.draw(4,1,0,0),M.end(),_.copyTextureToTexture({texture:P},{texture:T,mipLevel:o,origin:{x:0,y:0,z:n}},{width:t,height:i,depthOrArrayLayers:1}),R?(R._copyInvertYTempTexture=P,R._copyInvertYRenderPassDescr=A,S?R._copyInvertYBindGroupWithOfst=I:R._copyInvertYBindGroup=I):this._deferredReleaseTextures.push([P,null]),null===(b=(x=_).popDebugGroup)||void 0===b||b.call(x),C&&(this._device.queue.submit([_.finish()]),_=null)}copyWithInvertY(e,t,i,r){var s,a,n,o;let l=void 0===r,[h,c]=this._getPipeline(t,tf.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(r=this._device.createCommandEncoder({})),null===(a=(s=r).pushDebugGroup)||void 0===a||a.call(s,"internal copy texture with invertY");let u=r.beginRenderPass(i),d=this._device.createBindGroup({layout:c,entries:[{binding:0,resource:e}]});u.setPipeline(h),u.setBindGroup(0,d),u.draw(4,1,0,0),u.end(),null===(o=(n=r).popDebugGroup)||void 0===o||o.call(n),l&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,a=!1,n=eK.RGBA8Unorm,o=1,l,h=-1,c=0,u){o>1&&(o=4);let d=e.layers||1,_={width:e.width,height:e.height,depthOrArrayLayers:d},p=sn[n]?eX.RenderAttachment:0,f=WebGPUTextureHelper.IsCompressedFormat(n),m=t?WebGPUTextureHelper.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:eX.CopySrc|eX.CopyDst|eX.TextureBinding;c|=t&&!f?eX.CopySrc|p:0,f||a||(c|=p|eX.CopyDst);let v=this._device.createTexture({label:`Texture${a?"3D":"2D"}_${u?u+"_":""}${_.width}x${_.height}x${_.depthOrArrayLayers}_${t?"wmips":"womips"}_${n}_samples${o}`,size:_,dimension:a?eH.E3d:eH.E2d,format:n,usage:g|c,sampleCount:o,mipLevelCount:m});return WebGPUTextureHelper.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,n,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,n,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,a=eK.RGBA8Unorm,n=1,o,l=-1,h=0,c){n>1&&(n=4);let u=WebGPUTextureHelper.IsImageBitmapArray(e)?e[0].width:e.width,d=WebGPUTextureHelper.IsImageBitmapArray(e)?e[0].height:e.height,_=sn[a]?eX.RenderAttachment:0,p=WebGPUTextureHelper.IsCompressedFormat(a),f=t?WebGPUTextureHelper.ComputeNumMipmapLevels(u,d):1,m=l>=0?l:eX.CopySrc|eX.CopyDst|eX.TextureBinding;h|=t&&!p?eX.CopySrc|_:0,p||(h|=_|eX.CopyDst);let g=this._device.createTexture({label:`TextureCube_${c?c+"_":""}${u}x${d}x6_${t?"wmips":"womips"}_${a}_samples${n}`,size:{width:u,height:d,depthOrArrayLayers:6},dimension:eH.E2d,format:a,usage:m|h,sampleCount:n,mipLevelCount:f});return WebGPUTextureHelper.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,u,d,a,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,a,f,o)),g}generateCubeMipmaps(e,t,i,r){var s,a,n,o;let l=void 0===r;l&&(r=this._device.createCommandEncoder({})),null===(a=(s=r).pushDebugGroup)||void 0===a||a.call(s,`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,r);null===(o=(n=r).popDebugGroup)||void 0===o||o.call(n),l&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s){var a,n,o,l,h,c,u,d;let _;let p=void 0===s,[f,m]=this._getPipeline(t);if(r=Math.max(r,0),p&&(s=this._device.createCommandEncoder({})),null===(n=(a=s).pushDebugGroup)||void 0===n||n.call(a,`create mipmaps for face #${r} - ${i} levels`),WebGPUTextureHelper._IsHardwareTexture(e)?(_=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(_=e,e=void 0),!_)return;let g=e;for(let e=1;e15728640;)this._device.queue.writeBuffer(a,t+h,i.buffer,n+h,15728640),h+=15728640;this._device.queue.writeBuffer(a,t+h,i.buffer,n+h,s-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));let r=new Uint16Array(t);for(;e--;)i[e]=FromHalfFloat(r[e]);return i}readDataFromBuffer(e,t,i,r,s,a,n=0,o=0,l=null,h=!0,c=!1){let u=1===n?2:2===n?1:0;return new Promise((i,d)=>{e.mapAsync(eW.Read,o,t).then(()=>{let d=e.getMappedRange(o,t),_=l;if(c)_=null===_?allocateAndCopyTypedBuffer(n,t,!0,d):allocateAndCopyTypedBuffer(n,_.buffer,void 0,d);else if(null===_)switch(u){case 0:(_=new Uint8Array(t)).set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:(_=new Float32Array(t/4)).set(new Float32Array(d))}else switch(u){case 0:(_=new Uint8Array(_.buffer)).set(new Uint8Array(d));break;case 1:_=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:(_=new Float32Array(_.buffer)).set(new Float32Array(d))}if(s!==a){1!==u||c||(s*=2,a*=2);let e=new Uint8Array(_.buffer),t=s,i=0;for(let n=1;nd(e))})}releaseBuffer(e){return WebGPUBufferManager._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1,a=so[e.samplingMode]+sl[(e._comparisonFunction||514)-512+1]+sh[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(r=e._cachedWrapR)&&void 0!==r?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15);return a}static _GetSamplerFilterDescriptor(e,t){let i,r,s,a,n;let o=e.useMipMaps;switch(e.samplingMode){case 11:i=e$.Linear,r=e$.Linear,s=e$.Nearest,o||(a=n=0);break;case 3:case 3:i=e$.Linear,r=e$.Linear,o?s=e$.Linear:(s=e$.Nearest,a=n=0);break;case 8:i=e$.Nearest,r=e$.Nearest,o?s=e$.Linear:(s=e$.Nearest,a=n=0);break;case 4:i=e$.Nearest,r=e$.Nearest,s=e$.Nearest,o||(a=n=0);break;case 5:i=e$.Nearest,r=e$.Linear,s=e$.Nearest,o||(a=n=0);break;case 6:i=e$.Nearest,r=e$.Linear,o?s=e$.Linear:(s=e$.Nearest,a=n=0);break;case 7:i=e$.Nearest,r=e$.Linear,s=e$.Nearest,a=n=0;break;case 1:case 1:default:i=e$.Nearest,r=e$.Nearest,s=e$.Nearest,a=n=0;break;case 9:i=e$.Linear,r=e$.Nearest,s=e$.Nearest,o||(a=n=0);break;case 10:i=e$.Linear,r=e$.Nearest,o?s=e$.Linear:(s=e$.Nearest,a=n=0);break;case 2:case 2:i=e$.Linear,r=e$.Linear,s=e$.Nearest,a=n=0;break;case 12:i=e$.Linear,r=e$.Nearest,s=e$.Nearest,a=n=0}return t>1&&(0!==a||0!==n)&&s!==e$.Nearest?{magFilter:e$.Linear,minFilter:e$.Linear,mipmapFilter:e$.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:a,lodMaxClamp:n}}static _GetWrappingMode(e){switch(e){case 1:break;case 0:return eq.ClampToEdge;case 2:return eq.MirrorRepeat}return eq.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){let t=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,i=this._GetSamplerFilterDescriptor(e,t);return Object.assign(Object.assign(Object.assign({},i),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?WebGPUCacheSampler.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1})}static GetCompareFunction(e){switch(e){case 519:return eZ.Always;case 514:return eZ.Equal;case 516:return eZ.Greater;case 518:return eZ.GreaterEqual;case 513:default:return eZ.Less;case 515:return eZ.LessEqual;case 512:return eZ.Never;case 517:return eZ.NotEqual}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(e));t?i=0:0===i&&(i=WebGPUCacheSampler.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(e)),t||(this._samplers[i]=r)),r}};!function(e){e[e.StencilReadMask=0]="StencilReadMask",e[e.StencilWriteMask=1]="StencilWriteMask",e[e.DepthBias=2]="DepthBias",e[e.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",e[e.DepthStencilState=4]="DepthStencilState",e[e.MRTAttachments1=5]="MRTAttachments1",e[e.MRTAttachments2=6]="MRTAttachments2",e[e.RasterizationState=7]="RasterizationState",e[e.ColorStates=8]="ColorStates",e[e.ShaderStage=9]="ShaderStage",e[e.TextureStage=10]="TextureStage",e[e.VertexState=11]="VertexState",e[e.NumStates=12]="NumStates"}(tg||(tg={}));let sc={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},su={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},sd={[buffer_VertexBuffer.PositionKind]:!0,[buffer_VertexBuffer.NormalKind]:!0,[buffer_VertexBuffer.TangentKind]:!0,[buffer_VertexBuffer.UVKind]:!0,[buffer_VertexBuffer.UV2Kind]:!0,[buffer_VertexBuffer.UV3Kind]:!0,[buffer_VertexBuffer.UV4Kind]:!0,[buffer_VertexBuffer.UV5Kind]:!0,[buffer_VertexBuffer.UV6Kind]:!0,[buffer_VertexBuffer.ColorKind]:!0,[buffer_VertexBuffer.ColorInstanceKind]:!0,[buffer_VertexBuffer.MatricesIndicesKind]:!0,[buffer_VertexBuffer.MatricesWeightsKind]:!0,[buffer_VertexBuffer.MatricesIndicesExtraKind]:!0,[buffer_VertexBuffer.MatricesWeightsExtraKind]:!0};let WebGPUCacheRenderPipeline=class WebGPUCacheRenderPipeline{static _IsSignedType(e){switch(e){case buffer_VertexBuffer.BYTE:case buffer_VertexBuffer.SHORT:case buffer_VertexBuffer.INT:case buffer_VertexBuffer.FLOAT:return!0;case buffer_VertexBuffer.UNSIGNED_BYTE:case buffer_VertexBuffer.UNSIGNED_SHORT:case buffer_VertexBuffer.UNSIGNED_INT:return!1;default:throw Error(`Invalid type '${e}'`)}}constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,this._states=Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[eK.BGRA8Unorm],this.setColorFormat(eK.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(eK.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,r=0){if(i>1&&(i=4),this.disabled){let s=WebGPUCacheRenderPipeline._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),WebGPUCacheRenderPipeline.NumCacheMiss++,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return WebGPUCacheRenderPipeline.NumCacheHitWithHash++,this._parameter.pipeline;let s=WebGPUCacheRenderPipeline._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),WebGPUCacheRenderPipeline.NumCacheMiss++,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame=WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,a,n,o){this._depthWriteEnabled=n,this._depthTestEnabled=a,this._depthCompare=(null!=o?o:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[tg.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[tg.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=sn[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;let s=[0,0],a=0,n=0,o=0;for(let l=0;l=32&&(n=0,a++)}this._mrtFormats.length=o,(this._mrtAttachments1!==s[0]||this._mrtAttachments2!==s[1])&&(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[tg.MRTAttachments1]=s[0],this._states[tg.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:sn[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(null!=e?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(null!=e?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:su[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:su[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:su[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[tg.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[tg.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,a,n){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:su[i],this._stencilFrontPassOp=null===r?2:su[r],this._stencilFrontFailOp=null===s?1:su[s],this.setStencilReadMask(a),this.setStencilWriteMask(n)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return e8.TriangleList;case 2:case 3:return e8.PointList;case 1:case 4:return e8.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return e8.LineStrip;case 7:return e8.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return ti.Add;case 32778:return ti.Subtract;case 32779:return ti.ReverseSubtract;case 32775:return ti.Min;case 32776:return ti.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return tt.Zero;case 1:default:return tt.One;case 768:return tt.Src;case 769:return tt.OneMinusSrc;case 770:return tt.SrcAlpha;case 771:return tt.OneMinusSrcAlpha;case 772:return tt.DstAlpha;case 773:return tt.OneMinusDstAlpha;case 774:return tt.Dst;case 775:return tt.OneMinusDst;case 776:return tt.SrcAlphaSaturated;case 32769:case 32771:return tt.Constant;case 32770:case 32772:return tt.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:break;case 1:return eZ.Less;case 2:return eZ.Equal;case 3:return eZ.LessEqual;case 4:return eZ.Greater;case 5:return eZ.NotEqual;case 6:return eZ.GreaterEqual;case 7:return eZ.Always}return eZ.Never}static _GetStencilOpFunction(e){switch(e){case 0:return tr.Zero;case 1:break;case 2:return tr.Replace;case 3:return tr.IncrementClamp;case 4:return tr.DecrementClamp;case 5:return tr.Invert;case 6:return tr.IncrementWrap;case 7:return tr.DecrementWrap}return tr.Keep}static _GetVertexInputDescriptorFormat(e){let t=e.type,i=e.normalized,r=e.getSize();switch(t){case buffer_VertexBuffer.BYTE:switch(r){case 1:case 2:return i?ta.Snorm8x2:ta.Sint8x2;case 3:case 4:return i?ta.Snorm8x4:ta.Sint8x4}break;case buffer_VertexBuffer.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?ta.Unorm8x2:ta.Uint8x2;case 3:case 4:return i?ta.Unorm8x4:ta.Uint8x4}break;case buffer_VertexBuffer.SHORT:switch(r){case 1:case 2:return i?ta.Snorm16x2:ta.Sint16x2;case 3:case 4:return i?ta.Snorm16x4:ta.Sint16x4}break;case buffer_VertexBuffer.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?ta.Unorm16x2:ta.Uint16x2;case 3:case 4:return i?ta.Unorm16x4:ta.Uint16x4}break;case buffer_VertexBuffer.INT:switch(r){case 1:return ta.Sint32;case 2:return ta.Sint32x2;case 3:return ta.Sint32x3;case 4:return ta.Sint32x4}break;case buffer_VertexBuffer.UNSIGNED_INT:switch(r){case 1:return ta.Uint32;case 2:return ta.Uint32x2;case 3:return ta.Uint32x3;case 4:return ta.Uint32x4}break;case buffer_VertexBuffer.FLOAT:switch(r){case 1:return ta.Float32;case 2:return ta.Float32x2;case 3:return ta.Float32x3;case 4:return ta.Float32x4}}throw Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[tg.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.ShaderStage))}_setRasterizationState(e,t){let i=this._frontFace,r=this._cullEnabled?this._cullFace:0,s=this._clampDepth?1:0,a=this._alphaToCoverageEnabled?1:0,n=i-1+(r<<1)+(s<<3)+(a<<4)+(e<<5)+(t<<8);this._rasterizationState!==n&&(this._rasterizationState=n,this._states[tg.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((null===this._alphaBlendFuncParams[0]?2:sc[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:sc[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:sc[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:sc[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[tg.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.ColorStates))}_setDepthStencilState(){let e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[tg.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,tg.DepthStencilState))}_setVertexState(e){var t,i;let r;let s=this._statesLength,a=tg.VertexState,n=e._pipelineContext,o=n.shaderProcessingContext.attributeNamesFromEffect,l=n.shaderProcessingContext.attributeLocationsFromEffect,h=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}};let WebGPUMaterialContext=class WebGPUMaterialContext{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=WebGPUMaterialContext._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?WebGPUCacheSampler.GetSamplerHashCode(t):0;let s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,r,s;let a=this.textures[e],n=-1;a?n=null!==(r=null===(i=a.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:-1:this.textures[e]=a={texture:t,isFloatTexture:!1,isExternalTexture:!1},a.isExternalTexture&&this._numExternalTextures--,a.isFloatTexture&&this._numFloatTextures--,t?(a.isFloatTexture=1===t.type,a.isExternalTexture=ExternalTexture.IsExternalTexture(t),a.isFloatTexture&&this._numFloatTextures++,a.isExternalTexture&&this._numExternalTextures++):(a.isFloatTexture=!1,a.isExternalTexture=!1),a.texture=t;let o=n!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);o&&this.updateId++,this.isDirty||(this.isDirty=o)}};WebGPUMaterialContext._Counter=0;let WebGPUDrawContext=class WebGPUDrawContext{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,ez.CopyDst|ez.Indirect|ez.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=WebGPUDrawContext._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(null==t?void 0:t.uniqueId)!==(null===(i=this.buffers[e])||void 0===i?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}};WebGPUDrawContext._Counter=0;let WebGPUBindGroupCacheNode=class WebGPUBindGroupCacheNode{constructor(){this.values={}}};let WebGPUCacheBindGroups=class WebGPUCacheBindGroups{static get Statistics(){return{totalCreated:WebGPUCacheBindGroups.NumBindGroupsCreatedTotal,lastFrameCreated:WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame,lookupLastFrame:WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame,noLookupLastFrame:WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame=WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame,WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame=WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame,WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame=WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var r,s,a,n,o,l,h,c,u,d;let _;let p=WebGPUCacheBindGroups._Cache,f=this.disabled||i.forceBindGroupCreation;if(!f){if(!t.isDirty(i.updateId)&&!i.isDirty)return WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(let i of e.shaderProcessingContext.bufferNames){let e=null!==(s=null===(r=t.buffers[i])||void 0===r?void 0:r.uniqueId)&&void 0!==s?s:0,a=p.values[e];a||(a=new WebGPUBindGroupCacheNode,p.values[e]=a),p=a}for(let t of e.shaderProcessingContext.samplerNames){let e=null!==(n=null===(a=i.samplers[t])||void 0===a?void 0:a.hashCode)&&void 0!==n?n:0,r=p.values[e];r||(r=new WebGPUBindGroupCacheNode,p.values[e]=r),p=r}for(let t of e.shaderProcessingContext.textureNames){let e=null!==(h=null===(l=null===(o=i.textures[t])||void 0===o?void 0:o.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0,r=p.values[e];r||(r=new WebGPUBindGroupCacheNode,p.values[e]=r),p=r}_=p.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,_)return t.bindGroups=_,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++,_;_=[],t.bindGroups=_,f||(p.bindGroups=_),WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++;let m=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[n].resource=this._cacheSampler.getSampler(t,!1,e.hashCode)}else logger_Logger.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.texture||s.storageTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){logger_Logger.Error(`Trying to bind a null texture! entry=${JSON.stringify(s)}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||s.texture&&!t.view||s.storageTexture&&!t.viewForWriting)){logger_Logger.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, isReady=${null===(u=e.texture)||void 0===u?void 0:u.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[n].resource=s.storageTexture?t.viewForWriting:t.view}else logger_Logger.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.externalTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){logger_Logger.Error(`Trying to bind a null external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){logger_Logger.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}a[n].resource=this._device.importExternalTexture({source:t})}else logger_Logger.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.buffer){let e=t.buffers[l];if(e){let t=e.underlyingResource;a[n].resource.buffer=t,a[n].resource.size=e.capacity}else logger_Logger.Error(`Can't find buffer "${l}". entry=${JSON.stringify(s)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}let n=m[r];_[r]=this._device.createBindGroup({layout:n,entries:a})}return _}};WebGPUCacheBindGroups.NumBindGroupsCreatedTotal=0,WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame=0,WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame=0,WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame=0,WebGPUCacheBindGroups._Cache=new WebGPUBindGroupCacheNode,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame=0;let s_=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), -vec2(1.0,1.0), -vec2(-1.0,-1.0), -vec2(1.0,-1.0)}; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); -#define CUSTOM_VERTEX_MAIN_END -} -`;ShaderStore.ShadersStore.clearQuadVertexShader=s_;let sp=`uniform vec4 color;void main() {gl_FragColor=color;} -`;ShaderStore.ShadersStore.clearQuadPixelShader=sp;let WebGPUClearQuad=class WebGPUClearQuad{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new WebGPUCacheRenderPipelineTree(this._device,i,!t._caps.textureFloatLinearFiltering),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,r,s=1){var a,n;let o,l;let h=null,c=!!this._engine._currentRenderTarget;if(e)o=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?68719476736:0)+137438953472*u,l=this._keyTemp.join("_"),h=this._bundleCache[l])return h;o=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:s})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);let u=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),d=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),d.uniformBuffer.update();let _=c?this._engine._ubInvertY:this._engine._ubDontInvertY,p=d.uniformBuffer.getBuffer(),f=p.uniqueId+"-"+_.uniqueId,m=this._bindGroups[f];if(!m){let e=d.bindGroupLayouts[0];(m=this._bindGroups[f]=[]).push(this._device.createBindGroup({layout:e[0],entries:[]})),WebGPUShaderProcessingContext._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[WebGPUShaderProcessingContext._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:_.underlyingResource,size:_.capacity}},{binding:1,resource:{buffer:p.underlyingResource,size:p.capacity}}]}))}o.setPipeline(u);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0}))}};let WebGPUDurationMeasure=class WebGPUDurationMeasure{constructor(e,t){this._querySet=new WebGPUQuerySet(2,tu.Timestamp,e,t)}start(e){e.writeTimestamp(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp(this._querySet.querySet,1),this._querySet.readTwoValuesAndSubtract(0)}dispose(){this._querySet.dispose()}};let WebGPUOcclusionQuery=class WebGPUOcclusionQuery{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;let t=!1,i=this._engine._getCurrentRenderPassIndex();switch(i){case 0:t=void 0!==this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet;break;case 1:t=void 0!==this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet}return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();let e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e}))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}};let WebGPUTintWASM=class WebGPUTintWASM{async initTwgsl(e){return WebGPUTintWASM._twgsl?void 0:(e=e||{},(e=Object.assign(Object.assign({},WebGPUTintWASM._TWgslDefaultOptions),e)).twgsl)?(WebGPUTintWASM._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await tools_Tools.LoadBabylonScriptAsync(e.jsPath),self.twgsl)?(WebGPUTintWASM._twgsl=await self.twgsl(tools_Tools.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available.")}convertSpirV2WGSL(e,t=!1){let i=WebGPUTintWASM._twgsl.convertSpirV2WGSL(e,WebGPUTintWASM.DisableUniformityAnalysis||t);return WebGPUTintWASM.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),WebGPUTintWASM.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}};WebGPUTintWASM._TWgslDefaultOptions={jsPath:`${tools_Tools._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${tools_Tools._DefaultCdnUrl}/twgsl/twgsl.wasm`},WebGPUTintWASM.ShowWGSLShaderCode=!1,WebGPUTintWASM.DisableUniformityAnalysis=!1,WebGPUTintWASM._twgsl=null;let WebGPUSnapshotRendering=class WebGPUSnapshotRendering{constructor(e,t,i,r){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=r}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._mainPassBundleList.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endMainRenderPass(){this._record&&this._mainPassBundleList.push(this._bundleList.clone())}endRenderTargetPass(e,t){var i,r,s,a;if(this._play)null===(r=null===(i=t._bundleLists)||void 0===i?void 0:i[t._currentLayer])||void 0===r||r.run(e),1===this._mode&&this._engine._reportDrawCall(null===(a=null===(s=t._bundleLists)||void 0===s?void 0:s[t._currentLayer])||void 0===a?void 0:a.numDrawCalls);else{if(!this._record)return!1;t._bundleLists||(t._bundleLists=[]),t._bundleLists[t._currentLayer]=this._bundleListRenderTarget.clone(),t._bundleLists[t._currentLayer].run(e),this._bundleListRenderTarget.reset()}return!0}endFrame(e){if(this._record&&(this._mainPassBundleList.push(this._bundleList.clone()),this._record=!1,this._play=!0,this._mode=this._modeSaved),null!==e&&this._play)for(let t=0;t;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -@vertex -fn main(input : VertexInputs)->FragmentInputs { -#define CUSTOM_VERTEX_MAIN_BEGIN -vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -} -`;ShaderStore.ShadersStoreWGSL.postprocessVertexShader=sf;let sm={label:"TextureView_SwapChain_ResolveTarget",dimension:eH.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},sg={label:"TextureView_SwapChain",dimension:eH.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},sv="/* disable_uniformity_analysis */",sx=new math_color_Color4;let webgpuEngine_WebGPUEngine=class webgpuEngine_WebGPUEngine extends engine_Engine{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return logger_Logger.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){let e=this.name+this.version;return e}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){let i=new webgpuEngine_WebGPUEngine(e,t);return new Promise(e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>e(i))})}constructor(e,t={}){var i,r;if(super(null,null===(i=t.antialias)||void 0===i||i,t),this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._renderTargetEncoderDescriptor={label:"renderTarget"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null,null],this._currentRenderPass=null,this._mainRenderPassWrapper=new WebGPURenderPassWrapper,this._rttRenderPassWrapper=new WebGPURenderPassWrapper,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new observable_Observable,this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=[-1,-1],this._blendColorsCurrent=[[null,null,null,null],[null,null,null,null]],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=null!==(r=t.enableGPUDebugMarkers)&&void 0!==r&&r,logger_Logger.Log(`Babylon.js v${engine_Engine.Version} - ${this.description} engine`),!navigator.gpu){logger_Logger.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new WebGPUShaderProcessorGLSL,this._shaderProcessorWGSL=new WebGPUShaderProcessorWGSL}initAsync(e,t){var i;return this._initGlslang(null!=e?e:null===(i=this._options)||void 0===i?void 0:i.glslangOptions).then(e=>{var i;return this._glslang=e,this._tintWASM=webgpuEngine_WebGPUEngine.UseTWGSL?new WebGPUTintWASM:null,this._tintWASM?this._tintWASM.initTwgsl(null!=t?t:null===(i=this._options)||void 0===i?void 0:i.twgslOptions).then(()=>navigator.gpu.requestAdapter(this._options),e=>{throw logger_Logger.Error("Can not initialize twgsl!"),logger_Logger.Error(e),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},e=>{throw logger_Logger.Error("Can not initialize glslang!"),logger_Logger.Error(e),Error("WebGPU initializations stopped.")}).then(e=>{var t,i,r;if(e){this._adapter=e,this._adapterSupportedExtensions=[],null===(t=this._adapter.features)||void 0===t||t.forEach(e=>this._adapterSupportedExtensions.push(e)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(e=>{this._adapterInfo=e});let s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},a=null!==(r=null==s?void 0:s.requiredFeatures)&&void 0!==r?r:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(a){let e=[];for(let t of a)-1!==this._adapterSupportedExtensions.indexOf(t)&&e.push(t);s.requiredFeatures=e}if(this._options.setMaximumLimits&&!s.requiredLimits)for(let e in s.requiredLimits={},this._adapterSupportedLimits)s.requiredLimits[e]=this._adapterSupportedLimits[e];return this._adapter.requestDevice(s)}throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(e=>{var t,i;this._device=e,this._deviceEnabledExtensions=[],null===(t=this._device.features)||void 0===t||t.forEach(e=>this._deviceEnabledExtensions.push(e)),this._deviceLimits=e.limits;let r=-1;this._device.addEventListener("uncapturederror",e=>{++r{this._isDisposed||(this._contextWasLost=!0,logger_Logger.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(()=>this.initAsync()))})},e=>{logger_Logger.Error("Could not retrieve a WebGPU device."),logger_Logger.Error(e)}).then(()=>{this._bufferManager=new WebGPUBufferManager(this._device),this._textureHelper=new WebGPUTextureHelper(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new WebGPUCacheSampler(this._device),this._cacheBindGroups=new WebGPUCacheBindGroups(this._device,this._cacheSampler,this),this._timestampQuery=new WebGPUTimestampQuery(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new WebGPUOcclusionQuery(this,this._device,this._bufferManager):void 0,this._bundleList=new WebGPUBundleList(this._device),this._bundleListRenderTarget=new WebGPUBundleList(this._device),this._snapshotRendering=new WebGPUSnapshotRendering(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),ez.Uniform|ez.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),ez.Uniform|ez.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,console.log("%c frame #"+this._count+" - begin","background: #ffff00")),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new buffer_VertexBuffer(this,[0],"",!1,!1,1,!1,0,1),this._cacheRenderPipeline=new WebGPUCacheRenderPipelineTree(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new WebGPUDepthCullingState(this._cacheRenderPipeline),this._stencilStateComposer=new WebGPUStencilStateComposer(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new WebGPUClearQuad(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(e=>{logger_Logger.Error("Can not create WebGPU Device and/or context."),logger_Logger.Error(e),console.trace&&console.trace()})}_initGlslang(e){return(e=e||{},(e=Object.assign(Object.assign({},webgpuEngine_WebGPUEngine._GLSLslangDefaultOptions),e)).glslang)?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?tools_Tools.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(tools_Tools.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(ek.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(ek.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(ek.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(ek.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(ek.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(ek.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._caps.parallelShaderCompile=null,this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new WebGPUHardwareTexture],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){let e;if(!this._bufferManager)return;this.flushFramebuffer(!1),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};let t=new Float32Array([this.getRenderHeight(!0)]);if(this._bufferManager.setSubData(this._ubInvertY,4,t),this._bufferManager.setSubData(this._ubDontInvertY,4,t),this._options.antialias){let t={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:eH.E2d,format:this._options.swapChainFormat,usage:eX.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(t),e=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:eH.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new math_color_Color4(0,0,0,1),loadOp:th.Clear,storeOp:tc.Store}]}else e=[{view:void 0,clearValue:new math_color_Color4(0,0,0,1),loadOp:th.Clear,storeOp:tc.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?eK.Depth24PlusStencil8:eK.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);let i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:eH.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:eX.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);let r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:eH.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:th.Clear,depthStoreOp:tc.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?th.Clear:void 0,stencilStoreOp:this.isStencilEnable?tc.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:e,depthStencilAttachment:r}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:eX.RenderAttachment|eX.CopySrc,alphaMode:this.premultipliedAlpha?td.Premultiplied:td.Opaque})}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,s=t.indexOf(sv)>=0,a=i===q.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,n=i===q.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(a,n,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=e.indexOf(sv)>=0,a=t.indexOf(sv)>=0,n="#version 450\n",o=r===q.GLSL?this._compileShaderToSpirV(e,"vertex",i,n):this._getWGSLShader(e,"vertex",i),l=r===q.GLSL?this._compileShaderToSpirV(t,"fragment",i,n):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(o,l,r,s,a);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){let t=new ShaderCodeInliner(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new WebGPUPipelineContext(e,this)}createMaterialContext(){return new WebGPUMaterialContext}createDrawContext(){return new WebGPUDrawContext(this._bufferManager)}_preparePipelineContext(e,t,i,r,s,a,n,o){let l=e.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(o),console.log(t),console.log(i),console.log("***********************************************")),e.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:a},r?e.stages=this._compileRawPipelineStageDescriptor(t,i,l):e.stages=this._compilePipelineStageDescriptor(t,i,o,l)}getAttributes(e,t){let i=Array(t.length);for(let r=0;r0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=o.useSRGBBuffer,l.label=o.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,c,u||1,o.creationFlags),l}createTexture(e,t,i,r,s=3,a=null,n=null,o=null,l=null,h=null,c=null,u,d,_,p){return this._createTextureBase(e,t,i,r,s,a,n,(e,t,i,r,s,a,n,o)=>{var l;if(e.baseWidth=r.width,e.baseHeight=r.height,e.width=r.width,e.height=r.height,e.format=-1!==e.format?e.format:null!=h?h:5,e.type=-1!==e.type?e.type:0,o(e.width,e.height,r,t,e,()=>{}),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)a||n||this._generateMipmaps(e,this._uploadEncoder);else{let t=this._textureHelper.createGPUTextureForInternalTexture(e,r.width,r.height,void 0,_);!WebGPUTextureHelper.IsImageBitmap(r)||(this._textureHelper.updateTexture(r,e,r.width,r.height,e.depth,t.format,0,0,s,!1,0,0),a||n||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()},()=>!1,o,l,h,c,u,d,p)}wrapWebGPUTexture(e){let t=new WebGPUHardwareTexture(e),i=new internalTexture_InternalTexture(this,$.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;if(e.generateMipMaps){let i=null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource;i||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===$.RenderTarget||e.source===$.MultiRenderTarget?this._renderTargetEncoder:void 0)}}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;let s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){let r=this._currentEffect._pipelineContext,s=r.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){let e=i+WebGPUShaderProcessor.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e0;for(let t in e){let s=e[t],a=i[t],n=a.group,o=a.binding,l=s.type,h=s.object,c=s.indexInGroupEntries,u=this._bindGroupEntries[n];switch(u||(u=this._bindGroupEntries[n]=[]),l){case eF.Sampler:void 0!==c&&r?u[c].resource=this._cacheSampler.getSampler(h):(s.indexInGroupEntries=u.length,u.push({binding:o,resource:this._cacheSampler.getSampler(h)}));break;case eF.Texture:case eF.TextureWithoutSampler:{let e=h._texture._hardwareTexture;void 0!==c&&r?(l===eF.Texture&&(u[c++].resource=this._cacheSampler.getSampler(h._texture)),u[c].resource=e.view):(s.indexInGroupEntries=u.length,l===eF.Texture&&u.push({binding:o-1,resource:this._cacheSampler.getSampler(h._texture)}),u.push({binding:o,resource:e.view}));break}case eF.StorageTexture:{let e=h._texture._hardwareTexture;(e.textureAdditionalUsages&eX.StorageBinding)==0&&logger_Logger.Error(`computeDispatch: The texture (name=${h.name}, uniqueId=${h.uniqueId}) is not a storage texture!`,50),void 0!==c&&r?u[c].resource=e.viewForWriting:(s.indexInGroupEntries=u.length,u.push({binding:o,resource:e.viewForWriting}));break}case eF.ExternalTexture:{let e=h.underlyingResource;void 0!==c&&r?u[c].resource=this._device.importExternalTexture({source:e}):(s.indexInGroupEntries=u.length,u.push({binding:o,resource:this._device.importExternalTexture({source:e})}));break}case eF.UniformBuffer:case eF.StorageBuffer:{let e=(eF.UniformBuffer,h),t=e.getBuffer(),i=t.underlyingResource;void 0!==c&&r?(u[c].resource.buffer=i,u[c].resource.size=t.capacity):(s.indexInGroupEntries=u.length,u.push({binding:o,resource:{buffer:i,offset:0,size:t.capacity}}))}}}for(let e=0;e{this.computeDispatch(e,t,i,r,s,a,n)});return}let o=e._pipelineContext;o.computePipeline||(o.computePipeline=this._device.createComputePipeline({layout:e6.Auto,compute:o.stage}));let l=this._renderTargetEncoder,h=l.beginComputePass();h.setPipeline(o.computePipeline);let c=t.getBindGroups(i,o.computePipeline,n);for(let e=0;e{let i=t[0].width;this._setCubeMapTextureParams(e,!r),e.format=null!=n?n:-1;let a=this._textureHelper.createGPUTextureForInternalTexture(e,i,i);this._textureHelper.updateCubeTextures(t,a.underlyingResource,i,i,a.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!d)},webgpuEngine_WebGPUEngine.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},webgpuEngine_WebGPUEngine.prototype._debugPushGroup=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.pushDebugGroup(e)}else this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e])}},webgpuEngine_WebGPUEngine.prototype._debugPopGroup=function(e){if(this._options.enableGPUDebugMarkers){if(0===e||1===e){let t=0===e?this._renderEncoder:this._renderTargetEncoder;t.popDebugGroup()}else this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null])}},webgpuEngine_WebGPUEngine.prototype._debugInsertMarker=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.insertDebugMarker(e)}else this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e])}},webgpuEngine_WebGPUEngine.prototype._debugFlushPendingCommands=function(){for(let e=0;e{let i=d.width,a=n(e);if(!a)return;let h=[0,2,4,1,3,5];if(o){let e=4===r,t=o(a),n=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r>r,o=[];for(let i=0;i<6;i++){let n=t[r][l[i]];e&&(n=engine_rawTexture_convertRGBtoRGBATextureData(n,a,a,s)),o.push(new Uint8Array(n.buffer,n.byteOffset,n.byteLength))}this._textureHelper.updateCubeTextures(o,n.underlyingResource,a,a,n.format,u,!1,0,0)}}else{let e=[];for(let t=0;t<6;t++)e.push(a[h[t]]);this.updateRawCubeTexture(d,e,r,s,u)}d.isReady=!0,null==t||t.removePendingData(d),l&&l()};return this._loadFile(e,e=>{internalCallback(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)}),d},webgpuEngine_WebGPUEngine.prototype.createRawTexture3D=function(e,t,i,r,s,a,n,o,l=null,h=0,c=0){let u=$.Raw3D,d=new internalTexture_InternalTexture(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=a,d.samplingMode=o,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,c),this.updateRawTexture3D(d,e,s,n,l,h),this._internalTexturesCache.push(d),d},webgpuEngine_WebGPUEngine.prototype.updateRawTexture3D=function(e,t,i,r,s=null,a=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture,n=4===i;n&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,a));let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},webgpuEngine_WebGPUEngine.prototype.createRawTexture2DArray=function(e,t,i,r,s,a,n,o,l=null,h=0,c=0){let u=$.Raw2DArray,d=new internalTexture_InternalTexture(this,u);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=a,d.samplingMode=o,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,r,c),this.updateRawTexture2DArray(d,e,s,n,l,h),this._internalTexturesCache.push(d),d},webgpuEngine_WebGPUEngine.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,a=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture,n=4===i;n&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,a));let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},webgpuEngine_WebGPUEngine.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,a=null,n=!0,o=!1,l=0,h=0){let c=e._hardwareTexture;return n&&this.flushFramebuffer(),this._textureHelper.readPixels(c.underlyingResource,l,h,t,i,c.format,r,s,a,o)},webgpuEngine_WebGPUEngine.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};let WebGPURenderTargetWrapper=class WebGPURenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{};function IsExternalTexture(e){return!!e&&void 0!==e.underlyingResource}webgpuEngine_WebGPUEngine.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new WebGPURenderTargetWrapper(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},webgpuEngine_WebGPUEngine.prototype.createRenderTargetTexture=function(e,t){var i,r,s;let a=this._createHardwareRenderTargetWrapper(!1,!1,e),n={};void 0!==t&&"object"==typeof t?(n.generateMipMaps=t.generateMipMaps,n.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,n.generateStencilBuffer=n.generateDepthBuffer&&t.generateStencilBuffer,n.samplingMode=void 0===t.samplingMode?3:t.samplingMode,n.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,n.noColorAttachment=!!t.noColorAttachment,n.samples=t.samples,n.label=t.label):(n.generateMipMaps=t,n.generateDepthBuffer=!0,n.generateStencilBuffer=!1,n.samplingMode=3,n.creationFlags=0,n.noColorAttachment=!1);let o=n.noColorAttachment?null:this._createInternalTexture(e,t,!0,$.RenderTarget);return a.label=null!==(r=n.label)&&void 0!==r?r:"RenderTargetWrapper",a._samples=null!==(s=n.samples)&&void 0!==s?s:1,a._generateDepthBuffer=n.generateDepthBuffer,a._generateStencilBuffer=!!n.generateStencilBuffer,a.setTextures(o),(a._generateDepthBuffer||a._generateStencilBuffer)&&a.createDepthStencilTexture(0,this._caps.textureFloatLinearFiltering&&(void 0===n.samplingMode||2===n.samplingMode||2===n.samplingMode||3===n.samplingMode||3===n.samplingMode||5===n.samplingMode||6===n.samplingMode||7===n.samplingMode||11===n.samplingMode),a._generateStencilBuffer,a.samples,n.generateStencilBuffer?13:14,n.label?n.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!n.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,n.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!n.generateMipMaps&&(o.generateMipMaps=!1)),a},webgpuEngine_WebGPUEngine.prototype._createDepthStencilTexture=function(e,t){let i=new internalTexture_InternalTexture(this,$.DepthStencil);i.label=t.label;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);return i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},webgpuEngine_WebGPUEngine.prototype._setupDepthStencilTexture=function(e,t,i,r,s,a=1){let n=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=n,e.baseHeight=o,e.width=n,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=a,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},webgpuEngine_WebGPUEngine.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t&&(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t),t},webgpuEngine_WebGPUEngine.prototype.createRenderTargetCubeTexture=function(e,t){var i;let r=this._createHardwareRenderTargetWrapper(!1,!0,e),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,r.label=null!==(i=s.label)&&void 0!==i?i:"RenderTargetWrapper",r._generateDepthBuffer=s.generateDepthBuffer,r._generateStencilBuffer=s.generateStencilBuffer;let a=new internalTexture_InternalTexture(this,$.RenderTarget);return a.width=e,a.height=e,a.depth=0,a.isReady=!0,a.isCube=!0,a.samples=s.samples,a.generateMipMaps=s.generateMipMaps,a.samplingMode=s.samplingMode,a.type=s.type,a.format=s.format,this._internalTexturesCache.push(a),r.setTextures(a),(r._generateDepthBuffer||r._generateStencilBuffer)&&r.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,r._generateStencilBuffer,r.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(a.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(a),t&&t.createMipMaps&&!s.generateMipMaps&&(a.generateMipMaps=!1),r},effect_Effect.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},webgpuEngine_WebGPUEngine.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},effect_Effect.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},webgpuEngine_WebGPUEngine.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,32|t,i)},webgpuEngine_WebGPUEngine.prototype.updateStorageBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.readFromStorageBuffer=function(e,t,i,r){i=i||e.capacity;let s=this._bufferManager.createRawBuffer(i,ez.MapRead|ez.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderTargetEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,s,0,i),new Promise((e,t)=>{this.onEndFrameObservable.addOnce(()=>{s.mapAsync(eW.Read,0,i).then(()=>{let t=s.getMappedRange(0,i),a=r;if(void 0===a)(a=new Uint8Array(i)).set(new Uint8Array(t));else{let e=a.constructor;(a=new e(a.buffer)).set(new e(t))}s.unmap(),this._bufferManager.releaseBuffer(s),e(a)},e=>t(e))})})},webgpuEngine_WebGPUEngine.prototype.setStorageBuffer=function(e,t){var i,r;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(r=null==t?void 0:t.getBuffer())&&void 0!==r?r:null)},webgpuEngine_WebGPUEngine.prototype.createUniformBuffer=function(e,t){let i;i=e instanceof Array?new Float32Array(e):e;let r=this._bufferManager.createBuffer(i,ez.Uniform|ez.CopyDst,t);return r},webgpuEngine_WebGPUEngine.prototype.createDynamicUniformBuffer=function(e,t){return this.createUniformBuffer(e,t)},webgpuEngine_WebGPUEngine.prototype.updateUniformBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Float32Array?t:new Float32Array(t)).byteLength:s=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},webgpuEngine_WebGPUEngine.prototype.bindUniformBlock=function(){},webgpuEngine_WebGPUEngine.prototype.updateVideoTexture=function(e,t,i){var r;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;(null===(r=e._hardwareTexture)||void 0===r?void 0:r.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),IsExternalTexture(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0):t&&this.createImageBitmap(t).then(t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0}).catch(()=>{e.isReady=!0})};let ClipboardEventTypes=class ClipboardEventTypes{};ClipboardEventTypes.COPY=1,ClipboardEventTypes.CUT=2,ClipboardEventTypes.PASTE=3;let planeRotationGizmo_PlaneRotationGizmo=class planeRotationGizmo_PlaneRotationGizmo extends gizmo_Gizmo{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=math_color_Color3.Gray(),i=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer,r=32,s=null,a=!1,n=1){var o;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new observable_Observable,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new math_vector_Vector3,this._parent=s,this._coloredMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new math_color_Color3(.1,.1,.1)),this._hoverMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=math_color_Color3.Yellow(),this._disableMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._disableMaterial.diffuseColor=math_color_Color3.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new mesh_Mesh("",i.utilityLayerScene);let{rotationMesh:l,collider:h}=this._createGizmoMesh(this._gizmoMesh,n,r);this._rotationDisplayPlane=planeBuilder_CreatePlane("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),effect_Effect.ShadersStore.rotationGizmoVertexShader=planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader,effect_Effect.ShadersStore.rotationGizmoFragmentShader=planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader,this._rotationShaderMaterial=new shaderMaterial_ShaderMaterial("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles"]}),this._rotationShaderMaterial.backFaceCulling=!1,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,gizmo_Gizmo.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new pointerDragBehavior_PointerDragBehavior({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);let c=new math_vector_Vector3,u=new math_vector_Matrix,d=new math_vector_Vector3,_=new math_vector_Vector3;this.dragBehavior.onDragStartObservable.add(e=>{this.attachedNode&&(c.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(u),math_vector_Vector3.TransformCoordinatesToRef(e.dragPlanePoint,u,c),this._angles.x=Math.atan2(c.y,c.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,c.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});let p={snapDistance:0},f=0,m=new math_vector_Matrix,g=new math_vector_Quaternion;this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let r=new math_vector_Vector3(1,1,1),s=new math_vector_Quaternion(0,0,0,1),a=new math_vector_Vector3(0,0,0);this.attachedNode.getWorldMatrix().decompose(r,s,a);let n=.001>=Math.abs(Math.abs(r.x)-Math.abs(r.y))&&.001>=Math.abs(Math.abs(r.x)-Math.abs(r.z));if(!n&&this.updateGizmoRotationToMatchAttachedMesh){logger_Logger.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}s.normalize();let o=this.updateGizmoPositionToMatchAttachedMesh?a:this._rootMesh.absolutePosition,l=t.dragPlanePoint.subtract(o).normalize(),h=c.subtract(o).normalize(),v=math_vector_Vector3.Cross(l,h),x=math_vector_Vector3.Dot(l,h),b=Math.atan2(v.length(),x)*this.sensitivity;d.copyFrom(e),_.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(u),_=math_vector_Vector3.TransformCoordinates(d,u));let T=!1;if(i.utilityLayerScene.activeCamera){let e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();math_vector_Vector3.Dot(e,_)>0&&(d.scaleInPlace(-1),_.scaleInPlace(-1),T=!0)}let S=math_vector_Vector3.Dot(_,v)>0;S&&(b=-b),math_vector_TmpVectors.Vector3[0].set(b,0,0),this.dragBehavior.validateDrag(math_vector_TmpVectors.Vector3[0])||(b=0);let C=!1;if(0!=this.snapDistance){if(Math.abs(f+=b)>this.snapDistance){let e=Math.floor(Math.abs(f)/this.snapDistance);f<0&&(e*=-1),f%=this.snapDistance,b=this.snapDistance*e,C=!0}else b=0}let E=Math.sin(b/2);if(g.set(d.x*E,d.y*E,d.z*E,Math.cos(b/2)),m.determinant()>0){let e=new math_vector_Vector3;g.toEulerAnglesToRef(e),math_vector_Quaternion.RotationYawPitchRollToRef(e.y,-e.x,-e.z,g)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(g,s),s.normalize(),math_vector_Matrix.ComposeToRef(r,s,a,this.attachedNode.getWorldMatrix());else{g.toRotationMatrix(math_vector_TmpVectors.Matrix[0]);let e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(math_vector_TmpVectors.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}c.copyFrom(t.dragPlanePoint),C&&(p.snapDistance=b,this.onSnapObservable.notifyObservers(p)),this._angles.y+=b,this.angle+=T?-b:b,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});let v=i._getSharedGizmoLight();v.includedOnlyMeshes=v.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));let x={colliderMeshes:[h],gizmoMeshes:[l],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(o=this._parent)||void 0===o||o.addToAxisCache(this._gizmoMesh,x),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle,this._isHovered=-1!=x.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=x.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(x.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(x.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){let r=CreateTorus("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;let s=CreateTorus("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,gizmo_Gizmo.PreserveScaling),e.addChild(r,gizmo_Gizmo.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}};planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle=9*Math.PI/20,planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader=` - precision highp float; - attribute vec3 position; - attribute vec2 uv; - uniform mat4 worldViewProjection; - varying vec3 vPosition; - varying vec2 vUV; - void main(void) { - gl_Position = worldViewProjection * vec4(position, 1.0); - vUV = uv; - }`,planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader=` - precision highp float; - varying vec2 vUV; - varying vec3 vPosition; - uniform vec3 angles; - #define twopi 6.283185307 - void main(void) { - vec2 uv = vUV - vec2(0.5); - float angle = atan(uv.y, uv.x) + 3.141592; - float delta = gl_FrontFacing ? angles.y : -angles.y; - float begin = angles.x - delta * angles.z; - float start = (begin < (begin + delta)) ? begin : (begin + delta); - float end = (begin > (begin + delta)) ? begin : (begin + delta); - float len = sqrt(dot(uv,uv)); - float opacity = 1. - step(0.5, len); - - float base = abs(floor(start / twopi)) * twopi; - start += base; - end += base; - - float intensity = 0.; - for (int i = 0; i < 5; i++) - { - intensity += max(step(start, angle) - step(end, angle), 0.); - angle += twopi; - } - gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity; - }`;let ShadowLight=class ShadowLight extends light_Light{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0}_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=math_vector_Vector3.Zero()),math_vector_Vector3.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=math_vector_Vector3.Zero()),math_vector_Vector3.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=math_vector_Vector3.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=math_vector_Vector3.Cross(this.direction,math_axis_Axis.Y),t=math_vector_Vector3.Cross(e,this.direction);return math_vector_Vector3.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=math_vector_Vector3.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?this._currentRenderId=this.getScene().getRenderId():(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=math_vector_Matrix.Identity()),math_vector_Matrix.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,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}};__decorate([serializeAsVector3()],ShadowLight.prototype,"position",null),__decorate([serializeAsVector3()],ShadowLight.prototype,"direction",null),__decorate([serialize()],ShadowLight.prototype,"shadowMinZ",null),__decorate([serialize()],ShadowLight.prototype,"shadowMaxZ",null),node_Node.AddNodeConstructor("Light_Type_1",(e,t)=>()=>new DirectionalLight(e,math_vector_Vector3.Zero(),t));let DirectionalLight=class DirectionalLight extends ShadowLight{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,i){super(e,i),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 light_Light.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;t&&math_vector_Matrix.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,i){let r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let e=math_vector_Vector3.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(let a=0;athis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}let s=this._orthoRight-this._orthoLeft,a=this._orthoTop-this._orthoBottom,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;math_vector_Matrix.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-a*this.shadowOrthoScale,this._orthoTop+a*this.shadowOrthoScale,l?o:n,l?n: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._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):e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}};function CreateHemisphere(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);let r=sphereBuilder_CreateSphere("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=discBuilder_CreateDisc("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;let a=mesh_Mesh.MergeMeshes([s,r],!0);return a.name=e,a}__decorate([serialize()],DirectionalLight.prototype,"shadowFrustumSize",null),__decorate([serialize()],DirectionalLight.prototype,"shadowOrthoScale",null),__decorate([serialize()],DirectionalLight.prototype,"autoUpdateExtends",void 0),__decorate([serialize()],DirectionalLight.prototype,"autoCalcShadowZBounds",void 0),__decorate([serialize("orthoLeft")],DirectionalLight.prototype,"_orthoLeft",void 0),__decorate([serialize("orthoRight")],DirectionalLight.prototype,"_orthoRight",void 0),__decorate([serialize("orthoTop")],DirectionalLight.prototype,"_orthoTop",void 0),__decorate([serialize("orthoBottom")],DirectionalLight.prototype,"_orthoBottom",void 0),mesh_Mesh.CreateHemisphere=(e,t,i,r)=>CreateHemisphere(e,{segments:t,diameter:i},r),node_Node.AddNodeConstructor("Light_Type_2",(e,t)=>()=>new SpotLight(e,math_vector_Vector3.Zero(),math_vector_Vector3.Zero(),0,0,t));let SpotLight=class SpotLight extends ShadowLight{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()&&(SpotLight._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):SpotLight._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,i,r,s,a){super(e,a),this._innerAngle=0,this._projectionTextureMatrix=math_vector_Matrix.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=math_vector_Vector3.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=math_vector_Vector3.Zero(),this._projectionTextureViewLightMatrix=math_vector_Matrix.Zero(),this._projectionTextureProjectionLightMatrix=math_vector_Matrix.Zero(),this._projectionTextureScalingMatrix=math_vector_Matrix.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return light_Light.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,a=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;math_vector_Matrix.PerspectiveFovLHToRef(s,1,o?n:a,o?a:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.direction,this._projectionTextureViewTargetVector),math_vector_Matrix.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);math_vector_Matrix.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof texture_Texture){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;math_vector_Matrix.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("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=math_vector_Vector3.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=math_vector_Vector3.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?math_vector_Vector3.Normalize(this.transformedDirection):math_vector_Vector3.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){let t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){let t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady())}};__decorate([serialize()],SpotLight.prototype,"angle",null),__decorate([serialize()],SpotLight.prototype,"innerAngle",null),__decorate([serialize()],SpotLight.prototype,"shadowAngleScale",null),__decorate([serialize()],SpotLight.prototype,"exponent",void 0),__decorate([serialize()],SpotLight.prototype,"projectionTextureLightNear",null),__decorate([serialize()],SpotLight.prototype,"projectionTextureLightFar",null),__decorate([serialize()],SpotLight.prototype,"projectionTextureUpDirection",null),__decorate([serializeAsTexture("projectedLightTexture")],SpotLight.prototype,"_projectionTexture",void 0);let LightGizmo=class LightGizmo extends gizmo_Gizmo{constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){super(e),this._cachedPosition=new math_vector_Vector3,this._cachedForward=new math_vector_Vector3(0,0,1),this._pointerObserver=null,this.onClickedObservable=new observable_Observable,this._light=null,this.attachedMesh=new abstractMesh_AbstractMesh("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new transformNode_TransformNode("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new standardMaterial_StandardMaterial("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new math_color_Color3(.5,.5,.5),this._material.specularColor=new math_color_Color3(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(e=>{this._light&&(this._isHovered=!!(e.pickInfo&&-1!=this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))},pointerEvents_PointerEventTypes.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){console.warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof HemisphericLight?this._lightMesh=LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof DirectionalLight?this._lightMesh=LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof SpotLight?this._lightMesh=LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._lightMesh.parent=this._rootMesh;let t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new math_vector_Quaternion,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);let t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(math_vector_TmpVectors.Vector3[0]),e=math_vector_TmpVectors.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position){if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{let e=this.attachedMesh.position;this._light.position=new math_vector_Vector3(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}}if(this._light.direction){let e=this._getMeshForward();math_vector_Vector3.DistanceSquared(e,this._cachedForward)>1e-4?(this._light.direction=new math_vector_Vector3(e.x,e.y,e.z),this._cachedForward.copyFrom(e)):math_vector_Vector3.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){let t=new mesh_Mesh("hemisphereLight",e),i=CreateHemisphere(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(3,e);return r.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){let t=new mesh_Mesh("pointLight",e),i=sphereBuilder_CreateSphere(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(5,e);return r.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){let t=new mesh_Mesh("spotLight",e),i=sphereBuilder_CreateSphere(t.name,{segments:10,diameter:1},e);i.parent=t;let r=CreateHemisphere(t.name,{segments:10,diameter:2},e);r.parent=t,r.rotation.x=-Math.PI/2;let s=this._CreateLightLines(2,e);return s.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){let t=new mesh_Mesh("directionalLight",e),i=new mesh_Mesh(t.name,e);i.parent=t;let r=sphereBuilder_CreateSphere(t.name,{diameter:1.2,segments:10},e);r.parent=i;let s=cylinderBuilder_CreateCylinder(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let a=s.clone(t.name);a.scaling.y=.5,a.position.x+=1.25;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;let o=cylinderBuilder_CreateCylinder(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,(a=o.clone(t.name)).position.y=1.5,a.position.x+=1.25,(n=o.clone(t.name)).position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(LightGizmo._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}};LightGizmo._Scale=.007,LightGizmo._CreateLightLines=(e,t)=>{let i=new mesh_Mesh("root",t);i.rotation.x=Math.PI/2;let r=new mesh_Mesh("linePivot",t);r.parent=i;let s=cylinderBuilder_CreateCylinder("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){let t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<5)return i;let a=r.clone("linePivotClone");return a.rotation.z=Math.PI,i};let CameraGizmo=class CameraGizmo extends gizmo_Gizmo{constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new observable_Observable,this._camera=null,this._invProjection=new math_vector_Matrix,this._material=new standardMaterial_StandardMaterial("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new math_color_Color3(.5,.5,.5),this._material.specularColor=new math_color_Color3(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(e=>{this._camera&&(this._isHovered=!!(e.pickInfo&&-1!=this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))},pointerEvents_PointerEventTypes.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=CameraGizmo._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=CameraGizmo._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._cameraMesh.parent=this._rootMesh,this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;let t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){let t=new mesh_Mesh("rootCameraGizmo",e),i=new mesh_Mesh(t.name,e);i.parent=t;let r=boxBuilder_CreateBox(t.name,{width:1,height:.8,depth:.5},e);r.parent=i;let s=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;let a=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);a.parent=i,a.position.y=.5,a.position.x=.4,a.rotation.x=.5*Math.PI;let n=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(CameraGizmo._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e){let t=new mesh_Mesh("rootCameraGizmo",e),i=new mesh_Mesh(t.name,e);i.parent=t;for(let t=0;t<4;t+=2)for(let r=0;r<4;r+=2){let s=linesBuilder_CreateLines("lines",{points:[new math_vector_Vector3(-1+r,-1+t,-1),new math_vector_Vector3(-1+r,-1+t,1)]},e);s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=linesBuilder_CreateLines("lines",{points:[new math_vector_Vector3(-1,-1+r,-1+t),new math_vector_Vector3(1,-1+r,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=linesBuilder_CreateLines("lines",{points:[new math_vector_Vector3(-1+r,-1,-1+t),new math_vector_Vector3(-1+r,1,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return t}};CameraGizmo._Scale=.05,ShaderStore.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";let sb=`vec4 pack(float depth) -{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} -float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;ShaderStore.IncludesShadersStore.packingFunctions=sb;let sT=`#ifdef DOF -factor=sampleCoC(sampleCoord{X}); -computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; -#else -computedWeight=KERNEL_WEIGHT{X}; -#endif -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; -#else -blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; -#endif -`;ShaderStore.IncludesShadersStore.kernelBlurFragment=sT;let sS=`#ifdef DOF -factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; -#else -computedWeight=KERNEL_DEP_WEIGHT{X}; -#endif -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; -#else -blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; -#endif -`;ShaderStore.IncludesShadersStore.kernelBlurFragment2=sS;let sC=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; -#ifdef DOF -uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } -#endif -#include[0..varyingCount] -#ifdef PACKEDFLOAT -#include -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float computedWeight=0.0; -#ifdef PACKEDFLOAT -float blend=0.; -#else -vec4 blend=vec4(0.); -#endif -#ifdef DOF -float sumOfWeights=CENTER_WEIGHT; -float factor=0.0; -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; -#else -blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; -#endif -#endif -#include[0..varyingCount] -#include[0..depCount] -#ifdef PACKEDFLOAT -gl_FragColor=pack(blend); -#else -gl_FragColor=blend; -#endif -#ifdef DOF -gl_FragColor/=sumOfWeights; -#endif -}`;ShaderStore.ShadersStore.kernelBlurPixelShader=sC,ShaderStore.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";let sE=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; -#include[0..varyingCount] -const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -sampleCenter=(position*madd+madd); -#include[0..varyingCount] -gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.kernelBlurVertexShader=sE;let BlurPostProcess=class BlurPostProcess extends postProcess_PostProcess{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s,a=texture_Texture.BILINEAR_SAMPLINGMODE,n,o,l=0,h="",c=!1,u=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],r,s,a,n,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,u),this._blockCompilation=c,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add(e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,a){this._updateParameters(s,a)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],a=[],n=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){let t=1/3;return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(-(e*e/(2*t*t)))}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new BlurPostProcess(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}};__decorate([serialize("kernel")],BlurPostProcess.prototype,"_kernel",void 0),__decorate([serialize("packedFloat")],BlurPostProcess.prototype,"_packedFloat",void 0),__decorate([generateSerializableMember(4,void 0)],BlurPostProcess.prototype,"direction",void 0),h["BABYLON.BlurPostProcess"]=BlurPostProcess;let MirrorTexture=class MirrorTexture extends renderTargetTexture_RenderTargetTexture{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){let e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){let e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,a=texture_Texture.BILINEAR_SAMPLINGMODE,n=!0){let o;if(super(e,t,i,r,!0,s,!1,a,n),this.mirrorPlane=new math_plane_Plane(0,1,0,1),this._transformMatrix=math_vector_Matrix.Zero(),this._mirrorMatrix=math_vector_Matrix.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateGammaSpace()});let l=i.getEngine();l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add(()=>{var t;null===(t=l._debugPushGroup)||void 0===t||t.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)}),this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),math_vector_Matrix.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),o=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=math_vector_Vector3.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=o})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){let e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new BlurPostProcess("horizontal blur",new math_vector_Vector2(1,0),this._blurKernelX,this._blurRatio,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new BlurPostProcess("vertical blur",new math_vector_Vector2(0,1),this._blurKernelY,this._blurRatio,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new MirrorTexture(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;let e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();let t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}};texture_Texture._CreateMirror=(e,t,i,r)=>new MirrorTexture(e,t,i,r);let cubeTexture_CubeTexture=class cubeTexture_CubeTexture extends baseTexture_BaseTexture{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(math_vector_Matrix.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach(e=>r+=e),new cubeTexture_CubeTexture(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){let s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;let a=new cubeTexture_CubeTexture(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,a}constructor(e,t,i=null,r=!1,s=null,a=null,n=null,o=5,l=!1,h=null,c=!1,u=.8,d=0,_,p){var f;if(super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new observable_Observable,this.boundingBoxPosition=math_vector_Vector3.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new math_vector_Matrix,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this._format=o,this.isCube=!0,this._textureMatrix=math_vector_Matrix.Identity(),this._createPolynomials=c,this.coordinatesMode=texture_Texture.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=h,this._loaderOptions=_,this._useSRGBBuffer=p,this._lodScale=u,this._lodOffset=d,!e&&!s)return;this.updateURL(e,h,a,l,n,i,null===(f=this.getScene())||void 0===f?void 0:f.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,r=!1,s=null,a=null,n=!1,o=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);let l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),c=0===h.indexOf(".dds"),u=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(u?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(d||u||c||a||(a=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,a){for(let t=0;t-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem)))return;let r=math_vector_TmpVectors.Vector3[0],s=math_vector_TmpVectors.Quaternion[0],a=math_vector_TmpVectors.Vector3[1];this._textureMatrix.decompose(r,s,a),s.z*=-1,s.w*=-1,math_vector_Matrix.ComposeToRef(r,s,a,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(null===(e=this.getScene())||void 0===e?void 0:e.useRightHandedSystem)?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;let r=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);let onLoadProcessing=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},errorHandler=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?tools_Tools.SetImmediate(()=>onLoadProcessing()):this._texture.onLoadedObservable.add(()=>onLoadProcessing()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,r,this._lodScale,this._lodOffset,e,errorHandler,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,r,this._files,this._noMipmap,e,errorHandler,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>{var r;let s=!1;return e.prefiltered&&(s=e.prefiltered),new cubeTexture_CubeTexture(i+(null!==(r=e.url)&&void 0!==r?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=math_vector_Vector3.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=math_vector_Vector3.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{let t=new cubeTexture_CubeTexture(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t},this);return t.uniqueId=e,t}};__decorate([serialize()],cubeTexture_CubeTexture.prototype,"url",void 0),__decorate([serializeAsVector3()],cubeTexture_CubeTexture.prototype,"boundingBoxPosition",void 0),__decorate([serializeAsVector3()],cubeTexture_CubeTexture.prototype,"boundingBoxSize",null),__decorate([serialize("rotationY")],cubeTexture_CubeTexture.prototype,"rotationY",null),__decorate([serialize("files")],cubeTexture_CubeTexture.prototype,"_files",void 0),__decorate([serialize("forcedExtension")],cubeTexture_CubeTexture.prototype,"_forcedExtension",void 0),__decorate([serialize("extensions")],cubeTexture_CubeTexture.prototype,"_extensions",void 0),__decorate([generateSerializableMember(12,"textureMatrix")],cubeTexture_CubeTexture.prototype,"_textureMatrix",void 0),__decorate([generateSerializableMember(12,"textureMatrixRefraction")],cubeTexture_CubeTexture.prototype,"_textureMatrixRefraction",void 0),texture_Texture._CubeTextureParser=cubeTexture_CubeTexture.Parse,h["BABYLON.CubeTexture"]=cubeTexture_CubeTexture;let sy=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; -#ifdef USEHIGHLIGHTANDSHADOWCOLORS -uniform vec4 vPrimaryColorShadow; -#endif -uniform float shadowLevel;uniform float alpha; -#ifdef DIFFUSE -uniform vec2 vDiffuseInfos; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; -#endif -#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) -uniform vec3 vBackgroundCenter; -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 vReflectionControl; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) -uniform mat4 view; -#endif -#ifdef PROJECTED_GROUND -uniform vec2 projectedGroundInfos; -#endif -`;ShaderStore.IncludesShadersStore.backgroundFragmentDeclaration=sy;let sR=`layout(std140,column_major) uniform;uniform Material -{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; -#include -`;ShaderStore.IncludesShadersStore.backgroundUboDeclaration=sR;let sP=`#ifdef TEXTURELODSUPPORT -#extension GL_EXT_shader_texture_lod : enable -#endif -precision highp float; -#include<__decl__backgroundFragment> -#include -varying vec3 vPositionW; -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef DIFFUSE -#if DIFFUSEDIRECTUV==1 -#define vDiffuseUV vMainUV1 -#elif DIFFUSEDIRECTUV==2 -#define vDiffuseUV vMainUV2 -#else -varying vec2 vDiffuseUV; -#endif -uniform sampler2D diffuseSampler; -#endif -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include -#endif -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE; -#endif -#ifndef SHADOWONLY -#define SHADOWONLY; -#endif -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include -#include -#include -#include -#ifdef REFLECTIONFRESNEL -#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} -#endif -#ifdef PROJECTED_GROUND -float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; } -vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q) -vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=vec3(0.0,1.0,0.0); -#endif -float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; -#include[0..maxSimultaneousLights] -#ifdef SHADOWINUSE -globalShadow/=shadowLightCount; -#else -globalShadow=1.0; -#endif -#ifndef BACKMAT_SHADOWONLY -vec4 reflectionColor=vec4(1.,1.,1.,1.); -#ifdef REFLECTION -#ifdef PROJECTED_GROUND -vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); -#else -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords=reflectionVector; -#else -vec2 reflectionCoords=reflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -reflectionCoords/=reflectionVector.z; -#endif -reflectionCoords.y=1.0-reflectionCoords.y; -#endif -#ifdef REFLECTIONBLUR -float reflectionLOD=vReflectionInfos.y; -#ifdef TEXTURELODSUPPORT -reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); -#else -float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( -sampleReflection(reflectionSamplerHigh,reflectionCoords), -reflectionSpecularMid, -lodReflectionNormalizedDoubled -);} else {reflectionColor=mix( -reflectionSpecularMid, -sampleReflection(reflectionSamplerLow,reflectionCoords), -lodReflectionNormalizedDoubled-1.0 -);} -#endif -#else -vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; -#endif -#ifdef RGBDREFLECTION -reflectionColor.rgb=fromRGBD(reflectionColor); -#endif -#ifdef GAMMAREFLECTION -reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); -#endif -#ifdef REFLECTIONBGR -reflectionColor.rgb=reflectionColor.bgr; -#endif -reflectionColor.rgb*=vReflectionInfos.x; -#endif -vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; -#ifdef DIFFUSE -vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); -#ifdef GAMMADIFFUSE -diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); -#endif -diffuseMap.rgb*=vDiffuseInfos.y; -#ifdef DIFFUSEHASALPHA -finalAlpha*=diffuseMap.a; -#endif -diffuseColor=diffuseMap.rgb; -#endif -#ifdef REFLECTIONFRESNEL -vec3 colorBase=diffuseColor; -#else -vec3 colorBase=reflectionColor.rgb*diffuseColor; -#endif -colorBase=max(colorBase,0.0); -#ifdef USERGBCOLOR -vec3 finalColor=colorBase; -#else -#ifdef USEHIGHLIGHTANDSHADOWCOLORS -vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); -#else -vec3 mainColor=vPrimaryColor.rgb; -#endif -vec3 finalColor=colorBase*mainColor; -#endif -#ifdef REFLECTIONFRESNEL -vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; -#ifdef REFLECTIONFALLOFF -float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; -#endif -finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); -#endif -#ifdef OPACITYFRESNEL -float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; -#endif -#ifdef SHADOWINUSE -finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); -#endif -vec4 color=vec4(finalColor,finalAlpha); -#else -vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); -#endif -#include -#ifdef IMAGEPROCESSINGPOSTPROCESS -#if !defined(SKIPFINALCOLORCLAMP) -color.rgb=clamp(color.rgb,0.,30.0); -#endif -#else -color=applyImageProcessing(color); -#endif -#ifdef PREMULTIPLYALPHA -color.rgb*=color.a; -#endif -#ifdef NOISE -color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); -#endif -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -} -`;ShaderStore.ShadersStore.backgroundPixelShader=sP;let sA=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; -#ifdef DIFFUSE -uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -`;ShaderStore.IncludesShadersStore.backgroundVertexDeclaration=sA;let sM=`precision highp float; -#include<__decl__backgroundVertex> -#include -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include -#include -#include -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 -varying vec2 vDiffuseUV; -#endif -#include -#include -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=position; -#endif -#include -#include -#include -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} -#else -gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#endif -vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normal); -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); -#ifdef EQUIRECTANGULAR_RELFECTION_FOV -mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} -#endif -#endif -#ifndef UV1 -vec2 uv=vec2(0.,0.); -#endif -#ifndef UV2 -vec2 uv2=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uv; -#endif -#ifdef MAINUV2 -vMainUV2=uv2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 -if (vDiffuseInfos.x==0.) -{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} -else -{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} -#endif -#include -#include -#include[0..maxSimultaneousLights] -#ifdef VERTEXCOLOR -vColor=color; -#endif -#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -#define CUSTOM_VERTEX_MAIN_END -} -`;ShaderStore.ShadersStore.backgroundVertexShader=sM;let BackgroundMaterialDefines=class BackgroundMaterialDefines extends MaterialDefines{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.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.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!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.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}};let BackgroundMaterial=class BackgroundMaterial extends PushMaterial{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=BackgroundMaterial.StandardReflectance0*t,this.reflectionReflectance90=BackgroundMaterial.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=BackgroundMaterial.StandardReflectance0+(1-BackgroundMaterial.StandardReflectance0)*t,this.reflectionReflectance90=BackgroundMaterial.StandardReflectance90+(1-BackgroundMaterial.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}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){super(e,t),this.primaryColor=math_color_Color3.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=math_vector_Vector3.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new SmartArray(16),this._reflectionControls=math_vector_Vector4.Zero(),this._white=math_color_Color3.White(),this._primaryShadowColor=math_color_Color3.Black(),this._primaryHighlightColor=math_color_Color3.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!!this._diffuseTexture&&!!this._diffuseTexture.isRenderTarget||!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new BackgroundMaterialDefines);let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=r.getEngine();if(MaterialHelper.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(r,s),s._areTexturesDirty){if(s._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE"),s.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,s.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,s.OPACITYFRESNEL=this._opacityFresnel}else s.DIFFUSE=!1,s.DIFFUSEDIRECTUV=0,s.DIFFUSEHASALPHA=!1,s.GAMMADIFFUSE=!1,s.OPACITYFRESNEL=!1;let e=this._reflectionTexture;if(e&&MaterialFlags.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(s.REFLECTION=!0,s.GAMMAREFLECTION=e.gammaSpace,s.RGBDREFLECTION=e.isRGBD,s.REFLECTIONBLUR=this._reflectionBlur>0,s.LODINREFLECTIONALPHA=e.lodLevelInAlpha,s.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,s.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===texture_Texture.INVCUBIC_MODE&&(s.INVERTCUBICMAP=!0),s.REFLECTIONMAP_3D=e.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case texture_Texture.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case texture_Texture.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case texture_Texture.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case texture_Texture.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case texture_Texture.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case texture_Texture.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.CUBIC_MODE:case texture_Texture.INVCUBIC_MODE:default:s.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(s.REFLECTIONFRESNEL=!0,s.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1)}else s.REFLECTION=!1,s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1,s.REFLECTIONBLUR=!1,s.REFLECTIONMAP_3D=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.INVERTCUBICMAP=!1,s.REFLECTIONMAP_OPPOSITEZ=!1,s.LODINREFLECTIONALPHA=!1,s.GAMMAREFLECTION=!1,s.RGBDREFLECTION=!1}s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.USERGBCOLOR=this._useRGBColor,s.NOISE=this._enableNoise}if(s._areLightsDirty&&(s.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),s.BACKMAT_SHADOWONLY=this._shadowOnly),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(s._areMiscDirty&&(s.REFLECTIONMAP_3D&&this._enableGroundProjection?(s.PROJECTED_GROUND=!0,s.REFLECTIONMAP_SKYBOX=!0):s.PROJECTED_GROUND=!1),MaterialHelper.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),MaterialHelper.PrepareDefinesForFrameBoundValues(r,a,this,s,i,null,t.getRenderingMesh().hasThinInstances),MaterialHelper.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&(e.createNormals(!0),logger_Logger.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();let i=new EffectFallbacks;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),MaterialHelper.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);let n=[buffer_VertexBuffer.PositionKind];s.NORMAL&&n.push(buffer_VertexBuffer.NormalKind),s.UV1&&n.push(buffer_VertexBuffer.UVKind),s.UV2&&n.push(buffer_VertexBuffer.UV2Kind),MaterialHelper.PrepareAttributesForBones(n,e,s,i),MaterialHelper.PrepareAttributesForInstances(n,s);let o=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos"];addClipPlaneUniforms(o);let l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(o,s),ImageProcessingConfiguration.PrepareSamplers(l,s)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});let c=s.toString(),u=r.getEngine().createEffect("background",{attributes:n,uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:c,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},a);t.setEffect(u,s,this._materialContext),this.buildUniformLayout()}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)&&(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.materialDefines;if(!s)return;let a=i.effect;if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e),MaterialHelper.BindBonesParameters(t,this._activeEffect);let n=this._mustRebind(r,a,t.visibility);if(n){this._uniformBuffer.bindToEffect(a,"Material"),this.bindViewProjection(a);let e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(r.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),MaterialHelper.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&MaterialFlags.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&MaterialFlags.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),bindClipPlane(this._activeEffect,this,r),r.bindEyePosition(a)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(a,"Material"),this._needToBindSceneUbo=!0);(n||!this.isFrozen)&&(r.lightsEnabled&&MaterialHelper.BindLights(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(a),MaterialHelper.BindFogParameters(r,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return decorators_SerializationHelper.Clone(()=>new BackgroundMaterial(e,this.getScene()),this)}serialize(){let e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return decorators_SerializationHelper.Parse(()=>new BackgroundMaterial(e.name,t),e,t,i)}};BackgroundMaterial.StandardReflectance0=.05,BackgroundMaterial.StandardReflectance90=.5,__decorate([serializeAsColor3()],BackgroundMaterial.prototype,"_primaryColor",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"primaryColor",void 0),__decorate([serializeAsColor3()],BackgroundMaterial.prototype,"__perceptualColor",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_primaryColorShadowLevel",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_primaryColorHighlightLevel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"primaryColorHighlightLevel",null),__decorate([serializeAsTexture()],BackgroundMaterial.prototype,"_reflectionTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionTexture",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionBlur",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionBlur",void 0),__decorate([serializeAsTexture()],BackgroundMaterial.prototype,"_diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"diffuseTexture",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"shadowLights",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_shadowLevel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"shadowLevel",void 0),__decorate([serializeAsVector3()],BackgroundMaterial.prototype,"_sceneCenter",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"sceneCenter",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_opacityFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"opacityFresnel",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionFresnel",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionFalloffDistance",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionFalloffDistance",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionAmount",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionAmount",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionReflectance0",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionReflectance0",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_reflectionReflectance90",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionReflectance90",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_useRGBColor",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"useRGBColor",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_enableNoise",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"enableNoise",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_maxSimultaneousLights",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"_shadowOnly",void 0),__decorate([expandToProperty("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"shadowOnly",void 0),__decorate([generateSerializableMember(9,void 0)],BackgroundMaterial.prototype,"_imageProcessingConfiguration",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],BackgroundMaterial.prototype,"enableGroundProjection",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"projectedGroundRadius",void 0),__decorate([serialize()],BackgroundMaterial.prototype,"projectedGroundHeight",void 0),h["BABYLON.BackgroundMaterial"]=BackgroundMaterial;let EnvironmentHelper=class EnvironmentHelper{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new math_color_Color3(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new math_color_Color3(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:math_vector_Vector3.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=Object.assign(Object.assign({},EnvironmentHelper._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new observable_Observable,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){let t=Object.assign(Object.assign({},this._options),e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new math_color_Color4(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof baseTexture_BaseTexture){this._scene.environmentTexture=this._options.environmentTexture;return}let e=cubeTexture_CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new mesh_Mesh("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;let e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};let r=this._scene.getWorldExtends(e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof ArcRotateCamera&&this._scene.activeCamera.upperRadiusLimit&&(t=e=2*this._scene.activeCamera.upperRadiusLimit);let a=s.length();a>e&&(t=e=2*a),e*=1.1,t*=1.5,(i=r.min.add(s.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=planeBuilder_CreatePlane("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(()=>{this._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof baseTexture_BaseTexture){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new texture_Texture(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture}}_setupGroundMirrorTexture(e){let t=texture_Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,texture_Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new math_plane_Plane(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new BackgroundMaterial("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof baseTexture_BaseTexture){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new cubeTexture_CubeTexture(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=texture_Texture.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture}}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}};EnvironmentHelper._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",EnvironmentHelper._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",EnvironmentHelper._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";let TextureDome=class TextureDome extends transformNode_TransformNode{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=TextureDome.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new observable_Observable,this.onLoadObservable=new observable_Observable,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=void 0===i.autoPlay||!!i.autoPlay,i.loop=void 0===i.loop||!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=sphereBuilder_CreateSphere(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:mesh_Mesh.BACKSIDE},r);let a=this._material=new BackgroundMaterial(e+"_material",r);a.useEquirectangularFOV=!0,a.fovMultiplier=1,a.opacityFresnel=!1;let n=this._initTexture(t,r,i);if(this.texture=n,this._mesh.material=a,this._mesh.parent=this,this._halfDomeMask=sphereBuilder_CreateSphere("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:mesh_Mesh.BACKSIDE},r),this._halfDomeMask.rotate(math_axis_Axis.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce(()=>{this._setReady(!0)}),i.faceForward&&r.activeCamera){let e=r.activeCamera,t=math_vector_Vector3.Forward(),i=math_vector_Vector3.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(math_vector_Vector3.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case TextureDome.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case TextureDome.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;let e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=e:this._texture.uOffset=t});break}case TextureDome.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0})}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}};TextureDome.MODE_MONOSCOPIC=0,TextureDome.MODE_TOPBOTTOM=1,TextureDome.MODE_SIDEBYSIDE=2;let PhotoDome=class PhotoDome extends TextureDome{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new texture_Texture(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)})}};PhotoDome.MODE_MONOSCOPIC=TextureDome.MODE_MONOSCOPIC,PhotoDome.MODE_TOPBOTTOM=TextureDome.MODE_TOPBOTTOM,PhotoDome.MODE_SIDEBYSIDE=TextureDome.MODE_SIDEBYSIDE;let sI=0,GetEnvironmentBRDFTexture=e=>{if(!e.environmentBRDFTexture){let t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;let i=e._blockEntityCollection;e._blockEntityCollection=!1;let r=texture_Texture.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"+sI++,e,!0,!1,texture_Texture.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;let s=e.getEngine().getLoadedTexturesCache(),a=s.indexOf(r.getInternalTexture());-1!==a&&s.splice(a,1),r.isRGBD=!0,r.wrapU=texture_Texture.CLAMP_ADDRESSMODE,r.wrapV=texture_Texture.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,RGBDTextureTools.ExpandRGBDTexture(r);let n=e.getEngine().onContextRestoredObservable.add(()=>{r.isRGBD=!0;let checkReady=()=>{r.isReady()?RGBDTextureTools.ExpandRGBDTexture(r):tools_Tools.SetImmediate(checkReady)};checkReady()});e.onDisposeObservable.add(()=>{e.getEngine().onContextRestoredObservable.remove(n)})}return e.environmentBRDFTexture};let MaterialBRDFDefines=class MaterialBRDFDefines extends MaterialDefines{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}};let pbrBRDFConfiguration_PBRBRDFConfiguration=class pbrBRDFConfiguration_PBRBRDFConfiguration extends MaterialPluginBase{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new MaterialBRDFDefines,t),this._useEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],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"}};pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useEnergyConservation",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSmithVisibilityHeightCorrelated",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSphericalHarmonics",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);let sD=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; -#ifdef ALBEDO -uniform vec2 vAlbedoInfos; -#endif -#ifdef AMBIENT -uniform vec4 vAmbientInfos; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#ifdef OPACITY -uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos; -#endif -#ifdef REFLECTIVITY -uniform vec3 vReflectivityInfos; -#endif -#ifdef MICROSURFACEMAP -uniform vec2 vMicroSurfaceSamplerInfos; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) -uniform mat4 view; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos; -#ifdef REALTIME_FILTERING -uniform vec2 vReflectionFilteringInfo; -#endif -uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; -#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) -uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; -#endif -#ifdef CLEARCOAT -uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; -#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) -uniform vec4 vClearCoatInfos; -#endif -#ifdef CLEARCOAT_TEXTURE -uniform mat4 clearCoatMatrix; -#endif -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS -uniform mat4 clearCoatRoughnessMatrix; -#endif -#ifdef CLEARCOAT_BUMP -uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; -#endif -#ifdef CLEARCOAT_TINT -uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; -#ifdef CLEARCOAT_TINT_TEXTURE -uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; -#endif -#endif -#endif -#ifdef IRIDESCENCE -uniform vec4 vIridescenceParams; -#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) -uniform vec4 vIridescenceInfos; -#endif -#ifdef IRIDESCENCE_TEXTURE -uniform mat4 iridescenceMatrix; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -uniform mat4 iridescenceThicknessMatrix; -#endif -#endif -#ifdef ANISOTROPIC -uniform vec3 vAnisotropy; -#ifdef ANISOTROPIC_TEXTURE -uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; -#endif -#endif -#ifdef SHEEN -uniform vec4 vSheenColor; -#ifdef SHEEN_ROUGHNESS -uniform float vSheenRoughness; -#endif -#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) -uniform vec4 vSheenInfos; -#endif -#ifdef SHEEN_TEXTURE -uniform mat4 sheenMatrix; -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -uniform mat4 sheenRoughnessMatrix; -#endif -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; -#ifdef REALTIME_FILTERING -uniform vec2 vRefractionFilteringInfo; -#endif -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; -#endif -uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; -#endif -#ifdef PREPASS -#ifdef SS_SCATTERING -uniform float scatteringDiffusionProfile; -#endif -#endif -#if DEBUGMODE>0 -uniform vec2 vDebugMode; -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos; -#endif -#include -#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; -#else -uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; -#endif -#endif -#define ADDITIONAL_FRAGMENT_DECLARATION -`;ShaderStore.IncludesShadersStore.pbrFragmentDeclaration=sD;let sO=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; -#define ADDITIONAL_UBO_DECLARATION -}; -#include -#include -`;ShaderStore.IncludesShadersStore.pbrUboDeclaration=sO;let sB=`varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#include[1..7] -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#endif -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -`;ShaderStore.IncludesShadersStore.pbrFragmentExtraDeclaration=sB;let sN=`#ifdef _DEFINENAME_ -#if _DEFINENAME_DIRECTUV==1 -#define v_VARYINGNAME_UV vMainUV1 -#elif _DEFINENAME_DIRECTUV==2 -#define v_VARYINGNAME_UV vMainUV2 -#elif _DEFINENAME_DIRECTUV==3 -#define v_VARYINGNAME_UV vMainUV3 -#elif _DEFINENAME_DIRECTUV==4 -#define v_VARYINGNAME_UV vMainUV4 -#elif _DEFINENAME_DIRECTUV==5 -#define v_VARYINGNAME_UV vMainUV5 -#elif _DEFINENAME_DIRECTUV==6 -#define v_VARYINGNAME_UV vMainUV6 -#else -varying vec2 v_VARYINGNAME_UV; -#endif -#endif -`;ShaderStore.IncludesShadersStore.samplerFragmentAlternateDeclaration=sN;let sF=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) -#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) -#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) -#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) -#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) -#ifdef CLEARCOAT -#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) -#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D clearCoatRoughnessSampler; -#endif -#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) -#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) -#endif -#ifdef IRIDESCENCE -#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) -#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) -#endif -#ifdef SHEEN -#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) -#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D sheenRoughnessSampler; -#endif -#endif -#ifdef ANISOTROPIC -#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) -#endif -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#ifdef USEIRRADIANCEMAP -uniform samplerCube irradianceSampler; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; -#endif -#ifdef USEIRRADIANCEMAP -uniform sampler2D irradianceSampler; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#endif -#ifdef ENVIRONMENTBRDF -uniform sampler2D environmentBrdfSampler; -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -#ifdef SS_REFRACTIONMAP_3D -#define sampleRefraction(s,c) textureCube(s,c) -uniform samplerCube refractionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; -#endif -#else -#define sampleRefraction(s,c) texture2D(s,c) -uniform sampler2D refractionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; -#endif -#endif -#endif -#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) -#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) -#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) -#endif -`;ShaderStore.IncludesShadersStore.pbrFragmentSamplersDeclaration=sF;let sw=`bool testLightingForSSS(float diffusionProfile) -{return diffusionProfile<1.;}`;ShaderStore.IncludesShadersStore.subSurfaceScatteringFunctions=sw;let sL=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} -vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} -vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { -float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;ShaderStore.IncludesShadersStore.importanceSampling=sL;let sV=`#define MINIMUMVARIANCE 0.0005 -float convertRoughnessToAverageSlope(float roughness) -{return square(roughness)+MINIMUMVARIANCE;} -float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} -vec2 getAARoughnessFactors(vec3 normalVector) { -#ifdef SPECULARAA -vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); -#else -return vec2(0.); -#endif -} -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_LEGACY -vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} -vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} -#else -vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} -vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} -#endif -#endif -#if defined(CLEARCOAT) || defined(SS_REFRACTION) -vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} -vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} -vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} -vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), -cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), -clearCoatIntensity);return clearCoatAbsorption;} -#endif -#ifdef MICROSURFACEAUTOMATIC -float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) -{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} -#endif -`;ShaderStore.IncludesShadersStore.pbrHelperFunctions=sV;let sU=`#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 -+ vSphericalL1_1*(normal.y) -+ vSphericalL10*(normal.z) -+ vSphericalL11*(normal.x) -+ vSphericalL2_2*(normal.y*normal.x) -+ vSphericalL2_1*(normal.y*normal.z) -+ vSphericalL20*((3.0*normal.z*normal.z)-1.0) -+ vSphericalL21*(normal.z*normal.x) -+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} -#else -vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} -#endif -#endif -`;ShaderStore.IncludesShadersStore.harmonicsFunctions=sU;let sk=`struct preLightingInfo -{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; -#ifdef IRIDESCENCE -float iridescenceIntensity; -#endif -};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} -preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} -preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; -#ifdef SPECULARTERM -result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); -#endif -return result;}`;ShaderStore.IncludesShadersStore.pbrDirectLightingSetupFunctions=sk;let sG=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) -{return max(0.,1.0-length(lightOffset)/range);} -float computeDistanceLightFalloff_Physical(float lightDistanceSquared) -{return 1.0/maxEps(lightDistanceSquared);} -float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) -{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} -float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) -{ -#ifdef USEPHYSICALLIGHTFALLOFF -return computeDistanceLightFalloff_Physical(lightDistanceSquared); -#elif defined(USEGLTFLIGHTFALLOFF) -return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); -#else -return computeDistanceLightFalloff_Standard(lightOffset,range); -#endif -} -float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) -{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) -{falloff=max(0.,pow(cosAngle,exponent));} -return falloff;} -float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) -{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; -float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} -float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) -{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} -float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) -{ -#ifdef USEPHYSICALLIGHTFALLOFF -return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); -#elif defined(USEGLTFLIGHTFALLOFF) -return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); -#else -return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); -#endif -}`;ShaderStore.IncludesShadersStore.pbrDirectLightingFalloffFunctions=sG;let sz=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -#ifdef MS_BRDF_ENERGY_CONSERVATION -vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} -#endif -#ifdef ENVIRONMENTBRDF -vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); -#ifdef ENVIRONMENTBRDF_RGBD -brdfLookup.rgb=fromRGBD(brdfLookup.rgba); -#endif -return brdfLookup.rgb;} -vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { -#ifdef BRDF_V_HEIGHT_CORRELATED -vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; -#else -vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; -#endif -return reflectance;} -vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { -#ifdef BRDF_V_HEIGHT_CORRELATED -vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); -#else -vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; -#endif -return reflectance;} -#endif -/* NOT USED -#if defined(SHEEN) && defined(SHEEN_SOFTER) -float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) -{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} -#endif -*/ -#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) -vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) -/** -* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. -* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table -*/ -vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} -#endif -vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) -{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} -float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) -{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} -#ifdef CLEARCOAT -vec3 getR0RemappedForClearCoat(vec3 f0) { -#ifdef CLEARCOAT_DEFAULTIOR -#ifdef MOBILE -return saturate(f0*(f0*0.526868+0.529324)-0.0482256); -#else -return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); -#endif -#else -vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); -#endif -} -#endif -#ifdef IRIDESCENCE -const mat3 XYZ_TO_REC709=mat3( -3.2404542,-0.9692660, 0.0556434, --1.5371385, 1.8760108,-0.2040259, --0.4985314, 0.0415560, 1.0572252 -);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} -vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} -float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} -vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} -vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} -float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0 -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -float radicalInverse_VdC(uint bits) -{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } -vec2 hammersley(uint i,uint N) -{return vec2(float(i)/float(N),radicalInverse_VdC(i));} -#else -float vanDerCorpus(int n,int base) -{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) -{if(n>0) -{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} -return result;} -vec2 hammersley(int i,int N) -{return vec2(float(i)/float(N),vanDerCorpus(i,2));} -#endif -float log4(float x) {return log2(x)/2.;} -const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; -#define inline -vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -for(uint i=0u; i0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c;}} -result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} -#define inline -vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{vec3 n=normalize(inputN);if (alphaG==0.) {vec3 c=textureCube(inputTexture,n).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -for(uint i=0u; i0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c*NoL;}} -result=result/weight;return result;}} -#endif -#endif -`;ShaderStore.IncludesShadersStore.hdrFilteringFunctions=sW;let sH=`#define CLEARCOATREFLECTANCE90 1.0 -struct lightingInfo -{vec3 diffuse; -#ifdef SPECULARTERM -vec3 specular; -#endif -#ifdef CLEARCOAT -vec4 clearCoat; -#endif -#ifdef SHEEN -vec3 sheen; -#endif -};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { -#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) -float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; -#else -return roughness; -#endif -} -vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} -vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} -#define inline -vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} -#ifdef SS_TRANSLUCENCY -vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} -#endif -#ifdef SPECULARTERM -vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); -#ifdef IRIDESCENCE -fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); -#endif -float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); -#ifdef BRDF_V_HEIGHT_CORRELATED -float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); -#else -float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); -#endif -vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} -#endif -#ifdef ANISOTROPIC -vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); -#ifdef IRIDESCENCE -fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); -#endif -float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} -#endif -#ifdef CLEARCOAT -vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( -clearCoatTerm*info.attenuation*NccdotL*lightColor, -1.0-fresnel -);} -vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} -#endif -#ifdef SHEEN -vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER -float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); -#else */ -float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ -float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} -#endif -`;ShaderStore.IncludesShadersStore.pbrDirectLightingFunctions=sH;let sX=`#if defined(REFLECTION) || defined(SS_REFRACTION) -float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} -float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} -#endif -#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) -float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} -#endif -#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) -float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} -#endif -#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) -#define UNPACK_LOD(x) (1.0-x)*255.0 -float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} -#endif -`;ShaderStore.IncludesShadersStore.pbrIBLFunctions=sX;let sY=`struct albedoOpacityOutParams -{vec3 surfaceAlbedo;float alpha;}; -#define pbr_inline -void albedoOpacityBlock( -in vec4 vAlbedoColor, -#ifdef ALBEDO -in vec4 albedoTexture, -in vec2 albedoInfos, -#endif -#ifdef OPACITY -in vec4 opacityMap, -in vec2 vOpacityInfos, -#endif -#ifdef DETAIL -in vec4 detailColor, -in vec4 vDetailInfos, -#endif -#ifdef DECAL -in vec4 decalColor, -in vec4 vDecalInfos, -#endif -out albedoOpacityOutParams outParams -) -{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; -#ifdef ALBEDO -#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) -alpha*=albedoTexture.a; -#endif -#ifdef GAMMAALBEDO -surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); -#else -surfaceAlbedo*=albedoTexture.rgb; -#endif -surfaceAlbedo*=albedoInfos.y; -#endif -#ifndef DECAL_AFTER_DETAIL -#include -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -surfaceAlbedo*=vColor.rgb; -#endif -#ifdef DETAIL -float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; -#endif -#ifdef DECAL_AFTER_DETAIL -#include -#endif -#define CUSTOM_FRAGMENT_UPDATE_ALBEDO -#ifdef OPACITY -#ifdef OPACITYRGB -alpha=getLuminance(opacityMap.rgb); -#else -alpha*=opacityMap.a; -#endif -alpha*=vOpacityInfos.y; -#endif -#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) -alpha*=vColor.a; -#endif -#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) -#ifdef ALPHATEST -#if DEBUGMODE != 88 -if (alpha0 -#ifdef METALLICWORKFLOW -vec2 metallicRoughness; -#ifdef REFLECTIVITY -vec4 surfaceMetallicColorMap; -#endif -#ifndef FROSTBITE_REFLECTANCE -vec3 metallicF0; -#endif -#else -#ifdef REFLECTIVITY -vec4 surfaceReflectivityColorMap; -#endif -#endif -#endif -}; -#define pbr_inline -void reflectivityBlock( -in vec4 vReflectivityColor, -#ifdef METALLICWORKFLOW -in vec3 surfaceAlbedo, -in vec4 metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -in vec3 reflectivityInfos, -in vec4 surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -in vec3 ambientOcclusionColorIn, -#endif -#ifdef MICROSURFACEMAP -in vec4 microSurfaceTexel, -#endif -#ifdef DETAIL -in vec4 detailColor, -in vec4 vDetailInfos, -#endif -out reflectivityOutParams outParams -) -{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; -#ifdef METALLICWORKFLOW -vec2 metallicRoughness=surfaceReflectivityColor.rg; -#ifdef REFLECTIVITY -#if DEBUGMODE>0 -outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; -#endif -#ifdef AOSTOREINMETALMAPRED -vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); -#endif -#ifdef METALLNESSSTOREINMETALMAPBLUE -metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; -#else -metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; -#endif -#ifdef ROUGHNESSSTOREINMETALMAPALPHA -metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; -#else -#ifdef ROUGHNESSSTOREINMETALMAPGREEN -metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; -#endif -#endif -#endif -#ifdef DETAIL -float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); -#endif -#ifdef MICROSURFACEMAP -metallicRoughness.g*=microSurfaceTexel.r; -#endif -#if DEBUGMODE>0 -outParams.metallicRoughness=metallicRoughness; -#endif -#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS -microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; -#ifdef FROSTBITE_REFLECTANCE -outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); -#else -vec3 metallicF0=metallicReflectanceFactors.rgb; -#if DEBUGMODE>0 -outParams.metallicF0=metallicF0; -#endif -outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); -#endif -#else -#ifdef REFLECTIVITY -surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; -#if DEBUGMODE>0 -outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; -#endif -#ifdef MICROSURFACEFROMREFLECTIVITYMAP -microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; -#else -#ifdef MICROSURFACEAUTOMATIC -microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); -#endif -#ifdef MICROSURFACEMAP -microSurface*=microSurfaceTexel.r; -#endif -#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE -#endif -#endif -#endif -microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} -`;ShaderStore.IncludesShadersStore.pbrBlockReflectivity=sj;let sK=`struct ambientOcclusionOutParams -{vec3 ambientOcclusionColor; -#if DEBUGMODE>0 && defined(AMBIENT) -vec3 ambientOcclusionColorMap; -#endif -}; -#define pbr_inline -void ambientOcclusionBlock( -#ifdef AMBIENT -in vec3 ambientOcclusionColorMap_, -in vec4 vAmbientInfos, -#endif -out ambientOcclusionOutParams outParams -) -{vec3 ambientOcclusionColor=vec3(1.,1.,1.); -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; -#ifdef AMBIENTINGRAYSCALE -ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); -#endif -ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); -#if DEBUGMODE>0 -outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; -#endif -#endif -outParams.ambientOcclusionColor=ambientOcclusionColor;} -`;ShaderStore.IncludesShadersStore.pbrBlockAmbientOcclusion=sK;let sq=`#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -struct alphaFresnelOutParams -{float alpha;}; -#define pbr_inline -void alphaFresnelBlock( -in vec3 normalW, -in vec3 viewDirectionW, -in float alpha, -in float microSurface, -out alphaFresnelOutParams outParams -) -{float opacityPerceptual=alpha; -#ifdef LINEARALPHAFRESNEL -float opacity0=opacityPerceptual; -#else -float opacity0=opacityPerceptual*opacityPerceptual; -#endif -float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; -#ifdef ALPHATEST -if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) -vec3 anisotropyMapData; -#endif -}; -#define pbr_inline -void anisotropicBlock( -in vec3 vAnisotropy, -in float roughness, -#ifdef ANISOTROPIC_TEXTURE -in vec3 anisotropyMapData, -#endif -in mat3 TBN, -in vec3 normalW, -in vec3 viewDirectionW, -out anisotropicOutParams outParams -) -{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); -#ifdef ANISOTROPIC_TEXTURE -anisotropy*=anisotropyMapData.b; -#if DEBUGMODE>0 -outParams.anisotropyMapData=anisotropyMapData; -#endif -anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; -#ifdef ANISOTROPIC_LEGACY -anisotropyDirection.rg*=anisotropyMapData.rg; -#else -anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); -#endif -#endif -mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockAnisotropic=s$;let sQ=`#ifdef REFLECTION -struct reflectionOutParams -{vec4 environmentRadiance;vec3 environmentIrradiance; -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords; -#else -vec2 reflectionCoords; -#endif -#ifdef SS_TRANSLUCENCY -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -vec3 irradianceVector; -#endif -#endif -#endif -}; -#define pbr_inline -void createReflectionCoords( -in vec3 vPositionW, -in vec3 normalW, -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#ifdef REFLECTIONMAP_3D -out vec3 reflectionCoords -#else -out vec2 reflectionCoords -#endif -) -{ -#ifdef ANISOTROPIC -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); -#else -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -reflectionCoords=reflectionVector; -#else -reflectionCoords=reflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -reflectionCoords/=reflectionVector.z; -#endif -reflectionCoords.y=1.0-reflectionCoords.y; -#endif -} -#define pbr_inline -#define inline -void sampleReflectionTexture( -in float alphaG, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -const vec3 reflectionCoords, -#else -in sampler2D reflectionSampler, -const vec2 reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -out vec4 environmentRadiance -) -{ -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); -#elif defined(LINEARSPECULARREFLECTION) -float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); -#else -float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); -#endif -#ifdef LODBASEDMICROSFURACE -reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; -#ifdef LODINREFLECTIONALPHA -float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); -#else -float requestedReflectionLOD=reflectionLOD; -#endif -#ifdef REALTIME_FILTERING -environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); -#else -environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); -#endif -#else -float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( -sampleReflection(reflectionSamplerHigh,reflectionCoords), -environmentMid, -lodReflectionNormalizedDoubled -);} else {environmentRadiance=mix( -environmentMid, -sampleReflection(reflectionSamplerLow,reflectionCoords), -lodReflectionNormalizedDoubled-1.0 -);} -#endif -#ifdef RGBDREFLECTION -environmentRadiance.rgb=fromRGBD(environmentRadiance); -#endif -#ifdef GAMMAREFLECTION -environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); -#endif -environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} -#define pbr_inline -#define inline -void reflectionBlock( -in vec3 vPositionW, -in vec3 normalW, -in float alphaG, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -#else -in sampler2D reflectionSampler, -#endif -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -in vec3 vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -in mat4 reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -in samplerCube irradianceSampler, -#else -in sampler2D irradianceSampler, -#endif -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -out reflectionOutParams outParams -) -{vec4 environmentRadiance=vec4(0.,0.,0.,0.); -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords=vec3(0.); -#else -vec2 reflectionCoords=vec2(0.); -#endif -createReflectionCoords( -vPositionW, -normalW, -#ifdef ANISOTROPIC -anisotropicOut, -#endif -reflectionCoords -);sampleReflectionTexture( -alphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -roughness, -#endif -#ifdef REFLECTIONMAP_3D -reflectionSampler, -reflectionCoords, -#else -reflectionSampler, -reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentRadiance -);vec3 environmentIrradiance=vec3(0.,0.,0.); -#ifdef USESPHERICALFROMREFLECTIONMAP -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -environmentIrradiance=vEnvironmentIrradiance; -#else -#ifdef ANISOTROPIC -vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; -#else -vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -irradianceVector.z*=-1.0; -#endif -#ifdef INVERTCUBICMAP -irradianceVector.y*=-1.0; -#endif -#if defined(REALTIME_FILTERING) -environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); -#else -environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); -#endif -#ifdef SS_TRANSLUCENCY -outParams.irradianceVector=irradianceVector; -#endif -#endif -#elif defined(USEIRRADIANCEMAP) -vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; -#ifdef RGBDREFLECTION -environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); -#endif -#ifdef GAMMAREFLECTION -environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); -#endif -#endif -environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockReflection=sQ;let sZ=`#ifdef SHEEN -struct sheenOutParams -{float sheenIntensity;vec3 sheenColor;float sheenRoughness; -#ifdef SHEEN_LINKWITHALBEDO -vec3 surfaceAlbedo; -#endif -#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -float sheenAlbedoScaling; -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -vec3 finalSheenRadianceScaled; -#endif -#if DEBUGMODE>0 -#ifdef SHEEN_TEXTURE -vec4 sheenMapData; -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -vec3 sheenEnvironmentReflectance; -#endif -#endif -}; -#define pbr_inline -#define inline -void sheenBlock( -in vec4 vSheenColor, -#ifdef SHEEN_ROUGHNESS -in float vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -in vec4 sheenMapRoughnessData, -#endif -#endif -in float roughness, -#ifdef SHEEN_TEXTURE -in vec4 sheenMapData, -in float sheenMapLevel, -#endif -in float reflectance, -#ifdef SHEEN_LINKWITHALBEDO -in vec3 baseColor, -in vec3 surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -in float NdotV, -in vec3 environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -in vec2 AARoughnessFactors, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -in vec3 reflectionCoords, -#else -in sampler2D reflectionSampler, -in vec2 reflectionCoords, -#endif -in float NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -in float seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -in float eho, -#endif -#endif -out sheenOutParams outParams -) -{float sheenIntensity=vSheenColor.a; -#ifdef SHEEN_TEXTURE -#if DEBUGMODE>0 -outParams.sheenMapData=sheenMapData; -#endif -#endif -#ifdef SHEEN_LINKWITHALBEDO -float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; -#ifdef SHEEN_TEXTURE -sheenIntensity*=sheenMapData.a; -#endif -#else -vec3 sheenColor=vSheenColor.rgb; -#ifdef SHEEN_TEXTURE -#ifdef SHEEN_GAMMATEXTURE -sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); -#else -sheenColor.rgb*=sheenMapData.rgb; -#endif -sheenColor.rgb*=sheenMapLevel; -#endif -#ifdef SHEEN_ROUGHNESS -float sheenRoughness=vSheenRoughness; -#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE -#if defined(SHEEN_TEXTURE) -sheenRoughness*=sheenMapData.a; -#endif -#elif defined(SHEEN_TEXTURE_ROUGHNESS) -#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL -sheenRoughness*=sheenMapData.a; -#else -sheenRoughness*=sheenMapRoughnessData.a; -#endif -#endif -#else -float sheenRoughness=roughness; -#ifdef SHEEN_TEXTURE -sheenIntensity*=sheenMapData.a; -#endif -#endif -#if !defined(SHEEN_ALBEDOSCALING) -sheenIntensity*=(1.-reflectance); -#endif -sheenColor*=sheenIntensity; -#endif -#ifdef ENVIRONMENTBRDF -/*#ifdef SHEEN_SOFTER -vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); -#else*/ -#ifdef SHEEN_ROUGHNESS -vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); -#else -vec3 environmentSheenBrdf=environmentBrdf; -#endif -/*#endif*/ -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); -#ifdef SPECULARAA -sheenAlphaG+=AARoughnessFactors.y; -#endif -vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( -sheenAlphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -sheenRoughness, -#endif -reflectionSampler, -reflectionCoords, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentSheenRadiance -);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -sheenEnvironmentReflectance*=seo; -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -sheenEnvironmentReflectance*=eho; -#endif -#if DEBUGMODE>0 -outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; -#endif -outParams.finalSheenRadianceScaled= -environmentSheenRadiance.rgb * -sheenEnvironmentReflectance * -vLightingIntensity.z; -#endif -#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; -#endif -outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockSheen=sZ;let sJ=`struct clearcoatOutParams -{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; -#ifdef REFLECTION -vec3 finalClearCoatRadianceScaled; -#endif -#ifdef CLEARCOAT_TINT -vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; -#endif -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -vec3 energyConservationFactorClearCoat; -#endif -#if DEBUGMODE>0 -#ifdef CLEARCOAT_BUMP -mat3 TBNClearCoat; -#endif -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData; -#endif -#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -vec4 clearCoatTintMapData; -#endif -#ifdef REFLECTION -vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; -#endif -float clearCoatNdotV; -#endif -}; -#ifdef CLEARCOAT -#define pbr_inline -#define inline -void clearcoatBlock( -in vec3 vPositionW, -in vec3 geometricNormalW, -in vec3 viewDirectionW, -in vec2 vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -in vec4 clearCoatMapRoughnessData, -#endif -in vec3 specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -in vec2 clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -in vec4 vClearCoatTintParams, -in float clearCoatColorAtDistance, -in vec4 vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -in vec4 clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -in vec2 vClearCoatBumpInfos, -in vec4 clearCoatBumpMapData, -in vec2 vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -in mat3 vTBN, -#else -in vec2 vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -in mat4 normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -in vec3 faceNormal, -#endif -#ifdef REFLECTION -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -#else -in sampler2D reflectionSampler, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -in float ambientMonochrome, -#endif -#endif -#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) -in float frontFacingMultiplier, -#endif -out clearcoatOutParams outParams -) -{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; -#ifdef CLEARCOAT_TEXTURE -clearCoatIntensity*=clearCoatMapData.x; -#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE -clearCoatRoughness*=clearCoatMapData.y; -#endif -#if DEBUGMODE>0 -outParams.clearCoatMapData=clearCoatMapData; -#endif -#endif -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL -clearCoatRoughness*=clearCoatMapData.y; -#else -clearCoatRoughness*=clearCoatMapRoughnessData.y; -#endif -#endif -outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; -#ifdef CLEARCOAT_TINT -vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; -#ifdef CLEARCOAT_TINT_TEXTURE -#ifdef CLEARCOAT_TINT_GAMMATEXTURE -clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); -#else -clearCoatColor*=clearCoatTintMapData.rgb; -#endif -clearCoatThickness*=clearCoatTintMapData.a; -#if DEBUGMODE>0 -outParams.clearCoatTintMapData=clearCoatTintMapData; -#endif -#endif -outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; -#endif -#ifdef CLEARCOAT_REMAP_F0 -vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); -#else -vec3 specularEnvironmentR0Updated=specularEnvironmentR0; -#endif -outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; -#ifdef CLEARCOAT_BUMP -#ifdef NORMALXYSCALE -float clearCoatNormalScale=1.0; -#else -float clearCoatNormalScale=vClearCoatBumpInfos.y; -#endif -#if defined(TANGENT) && defined(NORMAL) -mat3 TBNClearCoat=vTBN; -#else -vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); -#endif -#if DEBUGMODE>0 -outParams.TBNClearCoat=TBNClearCoat; -#endif -#ifdef OBJECTSPACE_NORMALMAP -clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); -#else -clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); -#endif -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; -#endif -outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); -#if DEBUGMODE>0 -outParams.clearCoatNdotV=clearCoatNdotV; -#endif -#ifdef CLEARCOAT_TINT -vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); -#endif -#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) -vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); -#endif -#if defined(REFLECTION) -float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); -#ifdef SPECULARAA -clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; -#endif -vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -clearCoatReflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -vec3 clearCoatReflectionCoords=clearCoatReflectionVector; -#else -vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -clearCoatReflectionCoords/=clearCoatReflectionVector.z; -#endif -clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; -#endif -sampleReflectionTexture( -clearCoatAlphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -clearCoatNdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -clearCoatRoughness, -#endif -reflectionSampler, -clearCoatReflectionCoords, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentClearCoatRadiance -); -#if DEBUGMODE>0 -outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; -#endif -#endif -#endif -#else -vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); -#endif -clearCoatEnvironmentReflectance*=clearCoatIntensity; -#if DEBUGMODE>0 -outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; -#endif -outParams.finalClearCoatRadianceScaled= -environmentClearCoatRadiance.rgb * -clearCoatEnvironmentReflectance * -vLightingIntensity.z; -#endif -#if defined(CLEARCOAT_TINT) -outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); -#endif -float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); -#endif -} -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockClearcoat=sJ;let s0=`struct iridescenceOutParams -{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; -#ifdef IRIDESCENCE -#define pbr_inline -#define inline -void iridescenceBlock( -in vec4 vIridescenceParams, -in float viewAngle, -in vec3 specularEnvironmentR0, -#ifdef IRIDESCENCE_TEXTURE -in vec2 iridescenceMapData, -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -in vec2 iridescenceThicknessMapData, -#endif -#ifdef CLEARCOAT -in float NdotVUnclamped, -#ifdef CLEARCOAT_TEXTURE -in vec2 clearCoatMapData, -#endif -#endif -out iridescenceOutParams outParams -) -{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; -#ifdef IRIDESCENCE_TEXTURE -iridescenceIntensity*=iridescenceMapData.x; -#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE -iridescenceThicknessWeight=iridescenceMapData.g; -#endif -#endif -#if defined(IRIDESCENCE_THICKNESS_TEXTURE) -iridescenceThicknessWeight=iridescenceThicknessMapData.g; -#endif -float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; -#ifdef CLEARCOAT -float clearCoatIntensity=vClearCoatParams.x; -#ifdef CLEARCOAT_TEXTURE -clearCoatIntensity*=clearCoatMapData.x; -#endif -topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); -#endif -vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockIridescence=s0;let s1=`struct subSurfaceOutParams -{vec3 specularEnvironmentReflectance; -#ifdef SS_REFRACTION -vec3 finalRefraction;vec3 surfaceAlbedo; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -float alpha; -#endif -#ifdef REFLECTION -float refractionFactorForIrradiance; -#endif -#endif -#ifdef SS_TRANSLUCENCY -vec3 transmittance;float translucencyIntensity; -#ifdef REFLECTION -vec3 refractionIrradiance; -#endif -#endif -#if DEBUGMODE>0 -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap; -#endif -#ifdef SS_REFRACTION -vec4 environmentRefraction;vec3 refractionTransmittance; -#endif -#endif -}; -#ifdef SUBSURFACE -#define pbr_inline -#define inline -void subSurfaceBlock( -in vec3 vSubSurfaceIntensity, -in vec2 vThicknessParam, -in vec4 vTintColor, -in vec3 normalW, -in vec3 specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -in vec4 thicknessMap, -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -in vec4 refractionIntensityMap, -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -in vec4 translucencyIntensityMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -in mat4 reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -in vec3 irradianceVector_, -#endif -#if defined(REALTIME_FILTERING) -in samplerCube reflectionSampler, -in vec2 vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -in samplerCube irradianceSampler, -#else -in sampler2D irradianceSampler, -#endif -#endif -#endif -#endif -#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) -in vec3 surfaceAlbedo, -#endif -#ifdef SS_REFRACTION -in vec3 vPositionW, -in vec3 viewDirectionW, -in mat4 view, -in vec4 vRefractionInfos, -in mat4 refractionMatrix, -in vec4 vRefractionMicrosurfaceInfos, -in vec4 vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -in float alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -in float NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -in float roughness, -#endif -in float alphaG, -#ifdef SS_REFRACTIONMAP_3D -in samplerCube refractionSampler, -#ifndef LODBASEDMICROSFURACE -in samplerCube refractionSamplerLow, -in samplerCube refractionSamplerHigh, -#endif -#else -in sampler2D refractionSampler, -#ifndef LODBASEDMICROSFURACE -in sampler2D refractionSamplerLow, -in sampler2D refractionSamplerHigh, -#endif -#endif -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -in vec2 vRefractionFilteringInfo, -#endif -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -in vec3 refractionPosition, -in vec3 refractionSize, -#endif -#endif -#ifdef SS_TRANSLUCENCY -in vec3 vDiffusionDistance, -#endif -out subSurfaceOutParams outParams -) -{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; -#ifdef SS_REFRACTION -float refractionIntensity=vSubSurfaceIntensity.x; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; -#endif -#endif -#ifdef SS_TRANSLUCENCY -float translucencyIntensity=vSubSurfaceIntensity.y; -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -#if defined(SS_USE_GLTF_TEXTURES) -float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; -#else -float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; -#endif -#if DEBUGMODE>0 -outParams.thicknessMap=thicknessMap; -#endif -#ifdef SS_MASK_FROM_THICKNESS_TEXTURE -#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) -#if defined(SS_USE_GLTF_TEXTURES) -refractionIntensity*=thicknessMap.r; -#else -refractionIntensity*=thicknessMap.g; -#endif -#endif -#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) -translucencyIntensity*=thicknessMap.b; -#endif -#endif -#else -float thickness=vThicknessParam.y; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -#ifdef SS_USE_GLTF_TEXTURES -refractionIntensity*=refractionIntensityMap.r; -#else -refractionIntensity*=refractionIntensityMap.g; -#endif -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -translucencyIntensity*=translucencyIntensityMap.b; -#endif -#ifdef SS_TRANSLUCENCY -thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; -#endif -#ifdef SS_REFRACTION -vec4 environmentRefraction=vec4(0.,0.,0.,0.); -#ifdef ANISOTROPIC -vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y); -#else -vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y); -#endif -#ifdef SS_REFRACTIONMAP_OPPOSITEZ -refractionVector.z*=-1.0; -#endif -#ifdef SS_REFRACTIONMAP_3D -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); -#endif -refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); -#else -#ifdef SS_USE_THICKNESS_AS_DEPTH -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); -#else -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); -#endif -vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; -#endif -#ifdef SS_HAS_THICKNESS -float ior=vRefractionInfos.y; -#else -float ior=vRefractionMicrosurfaceInfos.w; -#endif -#ifdef SS_LODINREFRACTIONALPHA -float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); -#elif defined(SS_LINEARSPECULARREFRACTION) -float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); -#else -float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); -#endif -#ifdef LODBASEDMICROSFURACE -refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; -#ifdef SS_LODINREFRACTIONALPHA -float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); -#else -float requestedRefractionLOD=refractionLOD; -#endif -#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) -environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); -#else -environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); -#endif -#else -float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( -sampleRefraction(refractionSamplerHigh,refractionCoords), -environmentRefractionMid, -lodRefractionNormalizedDoubled -);} else {environmentRefraction=mix( -environmentRefractionMid, -sampleRefraction(refractionSamplerLow,refractionCoords), -lodRefractionNormalizedDoubled-1.0 -);} -#endif -#ifdef SS_RGBDREFRACTION -environmentRefraction.rgb=fromRGBD(environmentRefraction); -#endif -#ifdef SS_GAMMAREFRACTION -environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); -#endif -environmentRefraction.rgb*=vRefractionInfos.x; -#endif -#ifdef SS_REFRACTION -vec3 refractionTransmittance=vec3(refractionIntensity); -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); -#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) -float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; -#else -vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); -#endif -#ifdef SS_ALBEDOFORREFRACTIONTINT -environmentRefraction.rgb*=surfaceAlbedo.rgb; -#endif -outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); -#ifdef REFLECTION -outParams.refractionFactorForIrradiance=(1.-refractionIntensity); -#endif -#ifdef UNUSED_MULTIPLEBOUNCES -vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); -#endif -refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; -#if DEBUGMODE>0 -outParams.refractionTransmittance=refractionTransmittance; -#endif -outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; -#if DEBUGMODE>0 -outParams.environmentRefraction=environmentRefraction; -#endif -#endif -#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) -vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -irradianceVector.z*=-1.0; -#endif -#ifdef INVERTCUBICMAP -irradianceVector.y*=-1.0; -#endif -#else -vec3 irradianceVector=irradianceVector_; -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) -#if defined(REALTIME_FILTERING) -vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); -#else -vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); -#endif -#elif defined(USEIRRADIANCEMAP) -#ifdef REFLECTIONMAP_3D -vec3 irradianceCoords=irradianceVector; -#else -vec2 irradianceCoords=irradianceVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -irradianceCoords/=irradianceVector.z; -#endif -irradianceCoords.y=1.0-irradianceCoords.y; -#endif -vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); -#ifdef RGBDREFLECTION -refractionIrradiance.rgb=fromRGBD(refractionIrradiance); -#endif -#ifdef GAMMAREFLECTION -refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); -#endif -#else -vec4 refractionIrradiance=vec4(0.); -#endif -refractionIrradiance.rgb*=transmittance; -#ifdef SS_ALBEDOFORTRANSLUCENCYTINT -refractionIrradiance.rgb*=surfaceAlbedo.rgb; -#endif -outParams.refractionIrradiance=refractionIrradiance.rgb; -#endif -} -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockSubSurface=s1;let s2=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; -#endif -vec3 geometricNormalW=normalW; -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockNormalGeometric=s2;let s3=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) -vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; -#if defined(TWOSIDEDLIGHTING) -faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; -#endif -normalW*=sign(dot(normalW,faceNormal)); -#endif -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockNormalFinal=s3;let s4=`#ifdef LIGHTMAP -vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); -#ifdef RGBDLIGHTMAP -lightmapColor.rgb=fromRGBD(lightmapColor); -#endif -#ifdef GAMMALIGHTMAP -lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); -#endif -lightmapColor.rgb*=vLightmapInfos.y; -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockLightmapInit=s4;let s5=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); -#ifdef SPECULARAA -alphaG+=AARoughnessFactors.y; -#endif -#if defined(ENVIRONMENTBRDF) -vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -#ifdef AMBIENTINGRAYSCALE -float ambientMonochrome=aoOut.ambientOcclusionColor.r; -#else -float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); -#endif -float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); -#endif -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); -#endif -#endif -#endif -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockGeometryInfo=s5;let s6=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; -#ifdef METALLICWORKFLOW -vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); -#else -vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); -#endif -#ifdef ALPHAFRESNEL -float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockReflectance0=s6;let s8=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); -#ifdef RADIANCEOCCLUSION -specularEnvironmentReflectance*=seo; -#endif -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -specularEnvironmentReflectance*=eho; -#endif -#endif -#endif -#else -vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); -#endif -#ifdef CLEARCOAT -specularEnvironmentReflectance*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -specularEnvironmentReflectance*=clearcoatOut.absorption; -#endif -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockReflectance=s8;let s7=`vec3 diffuseBase=vec3(0.,0.,0.); -#ifdef SPECULARTERM -vec3 specularBase=vec3(0.,0.,0.); -#endif -#ifdef CLEARCOAT -vec3 clearCoatBase=vec3(0.,0.,0.); -#endif -#ifdef SHEEN -vec3 sheenBase=vec3(0.,0.,0.); -#endif -preLightingInfo preInfo;lightingInfo info;float shadow=1.; -float aggShadow=0.;float numLights=0.; -#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) -vec3 absorption=vec3(0.); -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockDirectLighting=s7;let s9=`aggShadow=aggShadow/numLights; -#if defined(ENVIRONMENTBRDF) -#ifdef MS_BRDF_ENERGY_CONSERVATION -vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); -#endif -#endif -#ifndef METALLICWORKFLOW -#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION -surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; -#endif -#endif -#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) -surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; -#endif -#ifdef REFLECTION -vec3 finalIrradiance=reflectionOut.environmentIrradiance; -#if defined(CLEARCOAT) -finalIrradiance*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -finalIrradiance*=clearcoatOut.absorption; -#endif -#endif -#if defined(SS_REFRACTION) -finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; -#endif -#if defined(SS_TRANSLUCENCY) -finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; -#endif -finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; -#endif -#ifdef SPECULARTERM -vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalSpecularScaled*=energyConservationFactor; -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -finalSpecularScaled*=sheenOut.sheenAlbedoScaling; -#endif -#endif -#ifdef REFLECTION -vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalRadianceScaled*=energyConservationFactor; -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -finalRadianceScaled*=sheenOut.sheenAlbedoScaling; -#endif -#endif -#ifdef SHEEN -vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; -#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) -sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; -#endif -#endif -#endif -#ifdef CLEARCOAT -vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; -#endif -#ifdef SS_REFRACTION -subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; -#ifdef CLEARCOAT_TINT -subSurfaceOut.finalRefraction*=clearcoatOut.absorption; -#endif -#endif -#endif -#ifdef ALPHABLEND -float luminanceOverAlpha=0.0; -#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) -luminanceOverAlpha+=getLuminance(finalRadianceScaled); -#if defined(CLEARCOAT) -luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); -#endif -#endif -#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) -luminanceOverAlpha+=getLuminance(finalSpecularScaled); -#endif -#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) -luminanceOverAlpha+=getLuminance(finalClearCoatScaled); -#endif -#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) -alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); -#endif -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockFinalLitComponents=s9;let ae=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; -#ifdef EMISSIVE -vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; -#ifdef GAMMAEMISSIVE -finalEmissive*=toLinearSpace(emissiveColorTex.rgb); -#else -finalEmissive*=emissiveColorTex.rgb; -#endif -finalEmissive*= vEmissiveInfos.y; -#endif -finalEmissive*=vLightingIntensity.y; -#ifdef AMBIENT -vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); -#else -vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; -#endif -finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; -`;ShaderStore.IncludesShadersStore.pbrBlockFinalUnlitComponents=ae;let at=`vec4 finalColor=vec4( -#ifndef UNLIT -#ifdef REFLECTION -finalIrradiance + -#endif -#ifdef SPECULARTERM -finalSpecularScaled + -#endif -#ifdef SHEEN -finalSheenScaled + -#endif -#ifdef CLEARCOAT -finalClearCoatScaled + -#endif -#ifdef REFLECTION -finalRadianceScaled + -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) -sheenOut.finalSheenRadianceScaled + -#endif -#ifdef CLEARCOAT -clearcoatOut.finalClearCoatRadianceScaled + -#endif -#endif -#ifdef SS_REFRACTION -subSurfaceOut.finalRefraction + -#endif -#endif -finalAmbient + -finalDiffuse, -alpha); -#ifdef LIGHTMAP -#ifndef LIGHTMAPEXCLUDED -#ifdef USELIGHTMAPASSHADOWMAP -finalColor.rgb*=lightmapColor.rgb; -#else -finalColor.rgb+=lightmapColor.rgb; -#endif -#endif -#endif -finalColor.rgb+=finalEmissive; -#define CUSTOM_FRAGMENT_BEFORE_FOG -finalColor=max(finalColor,0.0); -`;ShaderStore.IncludesShadersStore.pbrBlockFinalColorComposition=at;let ai=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) -#if !defined(SKIPFINALCOLORCLAMP) -finalColor.rgb=clamp(finalColor.rgb,0.,30.0); -#endif -#else -finalColor=applyImageProcessing(finalColor); -#endif -finalColor.a*=visibility; -#ifdef PREMULTIPLYALPHA -finalColor.rgb*=finalColor.a; -#endif -`;ShaderStore.IncludesShadersStore.pbrBlockImageProcessing=ai;let ar=`#if DEBUGMODE>0 -if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { -#if DEBUGMODE==1 -gl_FragColor.rgb=vPositionW.rgb; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==2 && defined(NORMAL) -gl_FragColor.rgb=vNormalW.rgb; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) -gl_FragColor.rgb=TBN[0]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) -gl_FragColor.rgb=TBN[1]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==5 -gl_FragColor.rgb=normalW; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==6 && defined(MAINUV1) -gl_FragColor.rgb=vec3(vMainUV1,0.0); -#elif DEBUGMODE==7 && defined(MAINUV2) -gl_FragColor.rgb=vec3(vMainUV2,0.0); -#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) -gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) -gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==10 && defined(CLEARCOAT) -gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==11 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicNormal; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==12 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicTangent; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==13 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==20 && defined(ALBEDO) -gl_FragColor.rgb=albedoTexture.rgb; -#ifndef GAMMAALBEDO -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==21 && defined(AMBIENT) -gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; -#elif DEBUGMODE==22 && defined(OPACITY) -gl_FragColor.rgb=opacityMap.rgb; -#elif DEBUGMODE==23 && defined(EMISSIVE) -gl_FragColor.rgb=emissiveColorTex.rgb; -#ifndef GAMMAEMISSIVE -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==24 && defined(LIGHTMAP) -gl_FragColor.rgb=lightmapColor.rgb; -#ifndef GAMMALIGHTMAP -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; -#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); -#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; -#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) -gl_FragColor.rgb=sheenOut.sheenMapData.rgb; -#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) -gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; -#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) -gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; -#elif DEBUGMODE==32 && defined(BUMP) -gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; -#elif DEBUGMODE==40 && defined(SS_REFRACTION) -gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==41 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; -#ifndef GAMMAREFLECTION -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) -gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==50 -gl_FragColor.rgb=diffuseBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==51 && defined(SPECULARTERM) -gl_FragColor.rgb=specularBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==52 && defined(CLEARCOAT) -gl_FragColor.rgb=clearCoatBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==53 && defined(SHEEN) -gl_FragColor.rgb=sheenBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==54 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; -#ifndef GAMMAREFLECTION -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==60 -gl_FragColor.rgb=surfaceAlbedo.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==61 -gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) -gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); -#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.metallicF0; -#elif DEBUGMODE==63 -gl_FragColor.rgb=vec3(roughness); -#elif DEBUGMODE==64 -gl_FragColor.rgb=vec3(alphaG); -#elif DEBUGMODE==65 -gl_FragColor.rgb=vec3(NdotV); -#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) -gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==67 && defined(CLEARCOAT) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); -#elif DEBUGMODE==68 && defined(CLEARCOAT) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); -#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) -gl_FragColor.rgb=subSurfaceOut.transmittance; -#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) -gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; -#elif DEBUGMODE==72 -gl_FragColor.rgb=vec3(microSurface); -#elif DEBUGMODE==73 -gl_FragColor.rgb=vAlbedoColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) -gl_FragColor.rgb=vReflectivityColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==75 -gl_FragColor.rgb=vEmissiveColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) -gl_FragColor.rgb=vec3(seo); -#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) -gl_FragColor.rgb=vec3(eho); -#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) -gl_FragColor.rgb=vec3(energyConservationFactor); -#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -gl_FragColor.rgb=specularEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) -gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==86 && defined(ALPHABLEND) -gl_FragColor.rgb=vec3(luminanceOverAlpha); -#elif DEBUGMODE==87 -gl_FragColor.rgb=vec3(alpha); -#elif DEBUGMODE==88 && defined(ALBEDO) -gl_FragColor.rgb=vec3(albedoTexture.a); -#else -float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); -#endif -gl_FragColor.rgb*=vDebugMode.y; -#ifdef DEBUGMODE_NORMALIZE -gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; -#endif -#ifdef DEBUGMODE_GAMMA -gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); -#endif -gl_FragColor.a=1.0; -#ifdef PREPASS -gl_FragData[0]=toLinearSpace(gl_FragColor); -gl_FragData[1]=vec4(0.,0.,0.,0.); -#endif -#ifdef DEBUGMODE_FORCERETURN -return; -#endif -} -#endif -`;ShaderStore.IncludesShadersStore.pbrDebug=ar;let as=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#extension GL_OES_standard_derivatives : enable -#endif -#ifdef LODBASEDMICROSFURACE -#extension GL_EXT_shader_texture_lod : enable -#endif -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -#include[SCENE_MRT_COUNT] -precision highp float; -#include -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE -#endif -#include<__decl__pbrFragment> -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef REFLECTION -#include -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -#include -#include -#include -albedoOpacityOutParams albedoOpacityOut; -#ifdef ALBEDO -vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#endif -#ifdef DECAL -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#endif -albedoOpacityBlock( -vAlbedoColor, -#ifdef ALBEDO -albedoTexture, -vAlbedoInfos, -#endif -#ifdef OPACITY -opacityMap, -vOpacityInfos, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -#ifdef DECAL -decalColor, -vDecalInfos, -#endif -albedoOpacityOut -);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; -#define CUSTOM_FRAGMENT_UPDATE_ALPHA -#include -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS -ambientOcclusionOutParams aoOut; -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; -#endif -ambientOcclusionBlock( -#ifdef AMBIENT -ambientOcclusionColorMap, -vAmbientInfos, -#endif -aoOut -); -#include -#ifdef UNLIT -vec3 diffuseBase=vec3(1.,1.,1.); -#else -vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; -#if defined(REFLECTIVITY) -vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; -#ifndef METALLICWORKFLOW -#ifdef REFLECTIVITY_GAMMA -surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); -#endif -surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; -#endif -#endif -#if defined(MICROSURFACEMAP) -vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; -#endif -#ifdef METALLICWORKFLOW -vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; -#ifdef REFLECTANCE -vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); -#ifdef REFLECTANCE_GAMMA -reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); -#endif -metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; -#endif -#ifdef METALLIC_REFLECTANCE -vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); -#ifdef METALLIC_REFLECTANCE_GAMMA -metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); -#endif -#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY -metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; -#endif -metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; -#endif -#endif -reflectivityBlock( -vReflectivityColor, -#ifdef METALLICWORKFLOW -surfaceAlbedo, -metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -vReflectivityInfos, -surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor, -#endif -#ifdef MICROSURFACEMAP -microSurfaceTexel, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -reflectivityOut -);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; -#ifdef METALLICWORKFLOW -surfaceAlbedo=reflectivityOut.surfaceAlbedo; -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; -#endif -#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( -normalW, -viewDirectionW, -alpha, -microSurface, -alphaFresnelOut -);alpha=alphaFresnelOut.alpha; -#endif -#endif -#include -#ifdef ANISOTROPIC -anisotropicOutParams anisotropicOut; -#ifdef ANISOTROPIC_TEXTURE -vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; -#endif -anisotropicBlock( -vAnisotropy, -roughness, -#ifdef ANISOTROPIC_TEXTURE -anisotropyMapData, -#endif -TBN, -normalW, -viewDirectionW, -anisotropicOut -); -#endif -#ifdef REFLECTION -reflectionOutParams reflectionOut; -#ifndef USE_CUSTOM_REFLECTION -reflectionBlock( -vPositionW, -normalW, -alphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -roughness, -#endif -reflectionSampler, -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -irradianceSampler, -#endif -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -reflectionOut -); -#else -#define CUSTOM_REFLECTION -#endif -#endif -#include -#ifdef SHEEN -sheenOutParams sheenOut; -#ifdef SHEEN_TEXTURE -vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); -#endif -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; -#endif -sheenBlock( -vSheenColor, -#ifdef SHEEN_ROUGHNESS -vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -sheenMapRoughnessData, -#endif -#endif -roughness, -#ifdef SHEEN_TEXTURE -sheenMapData, -vSheenInfos.y, -#endif -reflectance, -#ifdef SHEEN_LINKWITHALBEDO -baseColor, -surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -NdotV, -environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -AARoughnessFactors, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -vLightingIntensity, -reflectionSampler, -reflectionOut.reflectionCoords, -NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -eho, -#endif -#endif -sheenOut -); -#ifdef SHEEN_LINKWITHALBEDO -surfaceAlbedo=sheenOut.surfaceAlbedo; -#endif -#endif -#ifdef CLEARCOAT -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; -#endif -#endif -#ifdef IRIDESCENCE -iridescenceOutParams iridescenceOut; -#ifdef IRIDESCENCE_TEXTURE -vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; -#endif -iridescenceBlock( -vIridescenceParams, -NdotV, -specularEnvironmentR0, -#ifdef IRIDESCENCE_TEXTURE -iridescenceMapData, -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -iridescenceThicknessMapData, -#endif -#ifdef CLEARCOAT -NdotVUnclamped, -#ifdef CLEARCOAT_TEXTURE -clearCoatMapData, -#endif -#endif -iridescenceOut -);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; -#endif -clearcoatOutParams clearcoatOut; -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; -#endif -#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); -#endif -#ifdef CLEARCOAT_BUMP -vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); -#endif -clearcoatBlock( -vPositionW, -geometricNormalW, -viewDirectionW, -vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -clearCoatMapRoughnessData, -#endif -specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -vClearCoatTintParams, -clearCoatColorAtDistance, -vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -vClearCoatBumpInfos, -clearCoatBumpMapData, -vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -vTBN, -#else -vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -faceNormal, -#endif -#ifdef REFLECTION -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -vLightingIntensity, -reflectionSampler, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -ambientMonochrome, -#endif -#endif -#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) -(gl_FrontFacing ? 1. : -1.), -#endif -clearcoatOut -); -#else -clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; -#endif -#include -subSurfaceOutParams subSurfaceOut; -#ifdef SUBSURFACE -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); -#endif -subSurfaceBlock( -vSubSurfaceIntensity, -vThicknessParam, -vTintColor, -normalW, -specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -thicknessMap, -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -refractionIntensityMap, -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -translucencyIntensityMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -reflectionOut.irradianceVector, -#endif -#if defined(REALTIME_FILTERING) -reflectionSampler, -vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -irradianceSampler, -#endif -#endif -#endif -#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) -surfaceAlbedo, -#endif -#ifdef SS_REFRACTION -vPositionW, -viewDirectionW, -view, -vRefractionInfos, -refractionMatrix, -vRefractionMicrosurfaceInfos, -vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -roughness, -#endif -alphaG, -refractionSampler, -#ifndef LODBASEDMICROSFURACE -refractionSamplerLow, -refractionSamplerHigh, -#endif -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -vRefractionFilteringInfo, -#endif -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -vRefractionPosition, -vRefractionSize, -#endif -#endif -#ifdef SS_TRANSLUCENCY -vDiffusionDistance, -#endif -subSurfaceOut -); -#ifdef SS_REFRACTION -surfaceAlbedo=subSurfaceOut.surfaceAlbedo; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha=subSurfaceOut.alpha; -#endif -#endif -#else -subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; -#endif -#include -#include[0..maxSimultaneousLights] -#include -#endif -#include -#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION -#include -#include -#include(color,finalColor) -#include -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); -#endif -#ifdef PREPASS_VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_ALBEDO_SQRT -vec3 sqAlbedo=sqrt(surfaceAlbedo); -#endif -#ifdef PREPASS_IRRADIANCE -vec3 irradiance=finalDiffuse; -#ifndef UNLIT -#ifdef REFLECTION -irradiance+=finalIrradiance; -#endif -#endif -#ifdef SS_SCATTERING -gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); -irradiance/=sqAlbedo; -#else -gl_FragData[0]=finalColor; -float scatteringDiffusionProfile=255.; -#endif -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); -#else -gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); -#endif -#ifdef PREPASS_DEPTH -gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_NORMAL -#ifdef PREPASS_NORMAL_WORLDSPACE -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); -#else -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); -#endif -#endif -#ifdef PREPASS_ALBEDO_SQRT -gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); -#endif -#ifdef PREPASS_REFLECTIVITY -#ifndef UNLIT -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=finalColor; -#endif -#include -#if ORDER_INDEPENDENT_TRANSPARENCY -if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} -#endif -#include -#define CUSTOM_FRAGMENT_MAIN_END -} -`;ShaderStore.ShadersStore.pbrPixelShader=as;let aa=`uniform mat4 view;uniform mat4 viewProjection; -#ifdef ALBEDO -uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; -#endif -#ifdef AMBIENT -uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; -#endif -#ifdef OPACITY -uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; -#endif -#ifdef REFLECTIVITY -uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; -#endif -#ifdef METALLIC_REFLECTANCE -uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; -#endif -#ifdef REFLECTANCE -uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; -#endif -#ifdef MICROSURFACEMAP -uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; -#endif -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) -uniform vec4 vClearCoatInfos; -#endif -#ifdef CLEARCOAT_TEXTURE -uniform mat4 clearCoatMatrix; -#endif -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS -uniform mat4 clearCoatRoughnessMatrix; -#endif -#ifdef CLEARCOAT_BUMP -uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; -#endif -#ifdef CLEARCOAT_TINT_TEXTURE -uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; -#endif -#endif -#ifdef IRIDESCENCE -#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) -uniform vec4 vIridescenceInfos; -#endif -#ifdef IRIDESCENCE_TEXTURE -uniform mat4 iridescenceMatrix; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -uniform mat4 iridescenceThicknessMatrix; -#endif -#endif -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_TEXTURE -uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; -#endif -#endif -#ifdef SHEEN -#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) -uniform vec4 vSheenInfos; -#endif -#ifdef SHEEN_TEXTURE -uniform mat4 sheenMatrix; -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -uniform mat4 sheenRoughnessMatrix; -#endif -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; -#endif -#endif -#ifdef NORMAL -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; -#else -uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; -#endif -#endif -#endif -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos;uniform mat4 detailMatrix; -#endif -#include -#define ADDITIONAL_VERTEX_DECLARATION -`;ShaderStore.IncludesShadersStore.pbrVertexDeclaration=aa;let an=`precision highp float; -#include<__decl__pbrVertex> -#define CUSTOM_VERTEX_BEGIN -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#ifdef TANGENT -attribute vec4 tangent; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#include[2..7] -#include[1..7] -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include -#include -#include -#include -#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) -#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) -#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) -#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) -#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) -#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) -#ifdef CLEARCOAT -#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) -#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) -#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) -#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) -#endif -#ifdef IRIDESCENCE -#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) -#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) -#endif -#ifdef SHEEN -#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) -#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) -#endif -#ifdef ANISOTROPIC -#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) -#endif -#ifdef SUBSURFACE -#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) -#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) -#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) -#endif -varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#include -#endif -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include -#include -#include -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); -#include -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#if DEBUGMODE>0 -vClipSpacePosition=gl_Position; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#include[2..7] -#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) -#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) -#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) -#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) -#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) -#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) -#ifdef CLEARCOAT -#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) -#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) -#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) -#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) -#endif -#ifdef IRIDESCENCE -#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) -#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) -#endif -#ifdef SHEEN -#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) -#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) -#endif -#ifdef ANISOTROPIC -#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) -#endif -#ifdef SUBSURFACE -#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) -#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) -#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) -#endif -#include -#include -#include -#include[0..maxSimultaneousLights] -#include -#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -#include -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.pbrVertexShader=an;let MaterialClearCoatDefines=class MaterialClearCoatDefines extends MaterialDefines{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_TEXTURE_ROUGHNESS_IDENTICAL=!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}};let pbrClearCoatConfiguration_PBRClearCoatConfiguration=class pbrClearCoatConfiguration_PBRClearCoatConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new MaterialClearCoatDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this.indexOfRefraction=pbrClearCoatConfiguration_PBRClearCoatConfiguration._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=math_color_Color3.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.ClearCoatTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!MaterialFlags.ClearCoatTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())&&(!i.getCaps().standardDerivatives||!this._bumpTexture||!MaterialFlags.ClearCoatBumpTextureEnabled||!!r||!!this._bumpTexture.isReady())&&(!this._isTintEnabled||!this._tintTexture||!MaterialFlags.ClearCoatTintTextureEnabled||!!this._tintTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&MaterialFlags.ClearCoatTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&MaterialFlags.ClearCoatBumpTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!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,i,r){var s,a,n,o,l,h,c,u;if(!this._isEnabled)return;let d=r.materialDefines,_=this._material.isFrozen,p=this._material._disableBumpMap,f=this._material._invertNormalMapX,m=this._material._invertNormalMapY,g=d.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!_||!e.isSync){g&&MaterialFlags.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),MaterialHelper.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&MaterialFlags.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(a=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==a?a:0,null!==(o=null===(n=this._texture)||void 0===n?void 0:n.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(u=null===(c=this._textureRoughness)||void 0===c?void 0:c.level)&&void 0!==u?u:0),this._texture&&MaterialHelper.BindTextureMatrix(this._texture,e,"clearCoat"),!this._textureRoughness||g||d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE||MaterialHelper.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&MaterialFlags.ClearCoatTextureEnabled&&!p&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),MaterialHelper.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",f?1:-1,m?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",f?-1:1,m?-1:1)),this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),MaterialHelper.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let r=1-this._indexOfRefraction,_=1+this._indexOfRefraction,v=Math.pow(-r/_,2),x=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",v,x,r,_),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&&MaterialFlags.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!g&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&MaterialFlags.ClearCoatBumpTextureEnabled&&!p&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&MaterialFlags.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){var t,i,r,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(r=this._bumpTexture)||void 0===r||r.dispose(),null===(s=this._tintTexture)||void 0===s||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}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"}]}}};pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction=1.5,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"isEnabled",void 0),__decorate([serialize()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"intensity",void 0),__decorate([serialize()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"roughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"indexOfRefraction",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"useRoughnessFromMainTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"textureRoughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"remapF0OnInterfaceChange",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"bumpTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"isTintEnabled",void 0),__decorate([serializeAsColor3()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintColor",void 0),__decorate([serialize()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintColorAtDistance",void 0),__decorate([serialize()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintThickness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintTexture",void 0);let MaterialIridescenceDefines=class MaterialIridescenceDefines extends MaterialDefines{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}};let pbrIridescenceConfiguration_PBRIridescenceConfiguration=class pbrIridescenceConfiguration_PBRIridescenceConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new MaterialIridescenceDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness,this.maximumThickness=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness,this.indexOfRefraction=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.IridescenceTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._thicknessTexture||!MaterialFlags.IridescenceTextureEnabled||!!this._thicknessTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=null!==this._texture&&this._texture._texture===(null===(i=this._thicknessTexture)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.IridescenceTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&MaterialFlags.IridescenceTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(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_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,r){var s,a,n,o,l,h,c,u;if(!this._isEnabled)return;let d=r.materialDefines,_=this._material.isFrozen,p=d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&_&&e.isSync||(p&&MaterialFlags.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),MaterialHelper.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&MaterialFlags.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(a=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==a?a:0,null!==(o=null===(n=this._texture)||void 0===n?void 0:n.level)&&void 0!==o?o:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(u=null===(c=this._thicknessTexture)||void 0===c?void 0:c.level)&&void 0!==u?u:0),this._texture&&MaterialHelper.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||p||d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||MaterialHelper.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&MaterialFlags.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!p&&!d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&MaterialFlags.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}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"}]}}};pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness=100,pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness=400,pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction=1.3,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"isEnabled",void 0),__decorate([serialize()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"intensity",void 0),__decorate([serialize()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"minimumThickness",void 0),__decorate([serialize()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"maximumThickness",void 0),__decorate([serialize()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"indexOfRefraction",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"texture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"thicknessTexture",void 0);let MaterialAnisotropicDefines=class MaterialAnisotropicDefines extends MaterialDefines{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}};let pbrAnisotropicConfiguration_PBRAnisotropicConfiguration=class pbrAnisotropicConfiguration_PBRAnisotropicConfiguration extends MaterialPluginBase{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()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new MaterialAnisotropicDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new math_vector_Vector2(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||!this._texture||!MaterialFlags.AnisotropicTextureEnabled||!!this._texture.isReadyOrNotBlocking()}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(buffer_VertexBuffer.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.AnisotropicTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&MaterialFlags.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),MaterialHelper.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&MaterialFlags.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,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}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,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"isEnabled",void 0),__decorate([serialize()],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"intensity",void 0),__decorate([generateSerializableMember(4,void 0)],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"direction",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"legacy",void 0);let MaterialSheenDefines=class MaterialSheenDefines extends MaterialDefines{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,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}};let pbrSheenConfiguration_PBRSheenConfiguration=class pbrSheenConfiguration_PBRSheenConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new MaterialSheenDefines,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=math_color_Color3.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[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.SheenTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!MaterialFlags.SheenTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;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.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.SheenTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&MaterialFlags.SheenTextureEnabled?MaterialHelper.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var s,a,n,o,l,h,c,u;if(!this._isEnabled)return;let d=r.materialDefines,_=this._material.isFrozen,p=d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&_&&e.isSync||(p&&MaterialFlags.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),MaterialHelper.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&MaterialFlags.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(a=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==a?a:0,null!==(o=null===(n=this._texture)||void 0===n?void 0:n.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(u=null===(c=this._textureRoughness)||void 0===c?void 0:c.level)&&void 0!==u?u:0),this._texture&&MaterialHelper.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||p||d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||MaterialHelper.BindTextureMatrix(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&&MaterialFlags.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!p&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}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"}]}}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"isEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"linkSheenWithAlbedo",void 0),__decorate([serialize()],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"intensity",void 0),__decorate([serializeAsColor3()],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"color",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"texture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"useRoughnessFromMainTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"roughness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"textureRoughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"albedoScaling",void 0);let MaterialSubSurfaceDefines=class MaterialSubSurfaceDefines extends MaterialDefines{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!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_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_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}};let pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration=class pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration extends MaterialPluginBase{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){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new MaterialSubSurfaceDefines,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!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=math_color_Color3.White(),this.tintColorAtDistance=1,this.diffusionDistance=math_color_Color3.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;let e=this._getRefractionTexture(t);if(e&&MaterialFlags.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1;return}if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!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;let i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,r=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(r||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&MaterialHelper.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&!s&&MaterialHelper.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&!s&&MaterialHelper.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){let i=this._getRefractionTexture(t);i&&MaterialFlags.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;r.getRenderingMesh().getWorldMatrix().decompose(math_vector_TmpVectors.Vector3[0]);let s=Math.max(Math.abs(math_vector_TmpVectors.Vector3[0].x),Math.abs(math_vector_TmpVectors.Vector3[0].y),Math.abs(math_vector_TmpVectors.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,a=this._material.isFrozen,n=this._material.realTimeFiltering,o=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!a||!e.isSync){if(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),MaterialHelper.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),MaterialHelper.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),MaterialHelper.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&MaterialFlags.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;!l.isCube&&l.depth&&(t=l.depth);let i=l.getSize().width,r=this.volumeIndexOfRefraction;e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),n&&e.updateFloat2("vRefractionFilteringInfo",i,math_scalar_Scalar.Log2(i)),l.boundingBoxSize&&(e.updateVector3("vRefractionPosition",l.boundingBoxPosition),e.updateVector3("vRefractionSize",l.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.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0)}t.texturesEnabled&&(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&MaterialFlags.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){MaterialFlags.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!MaterialFlags.RefractionTextureEnabled&&!!this._refractionTexture&&!!this._refractionTexture.isRenderTarget}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}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)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")}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"}]}}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isRefractionEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isTranslucencyEnabled",void 0),__decorate([serialize(),expandToProperty("_markScenePrePassDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isScatteringEnabled",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"_scatteringDiffusionProfileIndex",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionIntensity",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"translucencyIntensity",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useAlbedoToTintRefraction",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useAlbedoToTintTranslucency",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"thicknessTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"indexOfRefraction",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"_volumeIndexOfRefraction",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"volumeIndexOfRefraction",null),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"invertRefractionY",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"linkRefractionWithTransparency",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"minimumThickness",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"maximumThickness",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useThicknessAsDepth",void 0),__decorate([serializeAsColor3()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"tintColor",void 0),__decorate([serialize()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"tintColorAtDistance",void 0),__decorate([serializeAsColor3()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"diffusionDistance",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useMaskFromThicknessTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionIntensityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"translucencyIntensityTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useGltfStyleTextures",void 0);let ao={effect:null,subMesh:null};let PBRMaterialDefines=class PBRMaterialDefines extends MaterialDefines{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_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_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=!1,this.TONEMAPPING_ACES=!1,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}};let pbrBaseMaterial_PBRBaseMaterial=class pbrBaseMaterial_PBRBaseMaterial extends PushMaterial{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new math_vector_Vector4(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=pbrBaseMaterial_PBRBaseMaterial.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=math_color_Color3.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new math_color_Color3(0,0,0),this._albedoColor=new math_color_Color3(1,1,1),this._reflectivityColor=new math_color_Color3(1,1,1),this._reflectionColor=new math_color_Color3(1,1,1),this._emissiveColor=new math_color_Color3(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=pbrBaseMaterial_PBRBaseMaterial.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=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new SmartArray(16),this._globalAmbientColor=new math_color_Color3(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new pbrBRDFConfiguration_PBRBRDFConfiguration(this),this.clearCoat=new pbrClearCoatConfiguration_PBRClearCoatConfiguration(this),this.iridescence=new pbrIridescenceConfiguration_PBRIridescenceConfiguration(this),this.anisotropy=new pbrAnisotropicConfiguration_PBRAnisotropicConfiguration(this),this.sheen=new pbrSheenConfiguration_PBRSheenConfiguration(this),this.subSurface=new pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration(this),this.detailMap=new material_detailMapConfiguration_DetailMapConfiguration(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),MaterialFlags.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this.getScene()),this.prePassConfiguration=new PrePassConfiguration}get hasRenderTargetTextures(){return!!MaterialFlags.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}get _disableAlphaBlending(){var e;return this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE||this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){var e;return!!this._forceAlphaTest||(null===(e=this.subSurface)||void 0===e||!e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var r;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(ec.GetDefineNames,this._eventInfo),t.materialDefines=new PBRMaterialDefines(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let a=this.getScene(),n=a.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,a.texturesEnabled)){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let e=this._getReflectionTexture();if(e&&MaterialFlags.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(r=e.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(MaterialFlags.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()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(n.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;n.getCaps().standardDerivatives||e.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)||(e.createNormals(!0),logger_Logger.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));let o=t.effect,l=s._areLightsDisposed,h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),c=!1;if(h){if(this._onEffectCreatedObservable&&(ao.effect=h,ao.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ao)),this.allowShaderHotSwapping&&o&&!h.isReady()){if(h=o,s.markAsUnprocessed(),c=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else a.resetCachedMaterial(),t.setEffect(h,s,this._materialContext)}return!!(t.effect&&t.effect.isReady())&&(s._renderId=a.getRenderId(),t.effect._wasPreviouslyReady=!c,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return null!=this._metallic||null!=this._roughness||!!this._metallicTexture}_prepareEffect(e,t,i=null,r=null,s=null,a=null,n){if(this._prepareDefines(e,t,s,a,n),!t.isDirty)return null;t.markAsProcessed();let o=this.getScene(),l=o.getEngine(),h=new EffectFallbacks,c=0;t.USESPHERICALINVERTEX&&h.addFallback(c++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(c,"FOG"),t.SPECULARAA&&h.addFallback(c,"SPECULARAA"),t.POINTSIZE&&h.addFallback(c,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(c,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(c,"PARALLAX"),t.PARALLAX_RHS&&h.addFallback(c,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&h.addFallback(c++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(c++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(c++,"TANGENT"),t.BUMP&&h.addFallback(c++,"BUMP"),c=MaterialHelper.HandleFallbacksForShadows(t,h,this._maxSimultaneousLights,c++),t.SPECULARTERM&&h.addFallback(c++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(c++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(c++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(c++,"LIGHTMAP"),t.NORMAL&&h.addFallback(c++,"NORMAL"),t.AMBIENT&&h.addFallback(c++,"AMBIENT"),t.EMISSIVE&&h.addFallback(c++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(c++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(c++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");let u=[buffer_VertexBuffer.PositionKind];t.NORMAL&&u.push(buffer_VertexBuffer.NormalKind),t.TANGENT&&u.push(buffer_VertexBuffer.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&u.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&u.push(buffer_VertexBuffer.ColorKind),t.INSTANCESCOLOR&&u.push(buffer_VertexBuffer.ColorInstanceKind),MaterialHelper.PrepareAttributesForBones(u,e,t,h),MaterialHelper.PrepareAttributesForInstances(u,t),MaterialHelper.PrepareAttributesForMorphTargets(u,e,t),MaterialHelper.PrepareAttributesForBakedVertexAnimation(u,e,t);let d="pbr",_=["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"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=c,this._eventInfo.defines=t,this._eventInfo.uniforms=_,this._eventInfo.attributes=u,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(ec.PrepareEffect,this._eventInfo),PrePassConfiguration.AddUniforms(_),PrePassConfiguration.AddSamplers(p),addClipPlaneUniforms(_),ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(_,t),ImageProcessingConfiguration.PrepareSamplers(p,t)),MaterialHelper.PrepareUniformsAndSamplersList({uniformsNames:_,uniformBuffersNames:f,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});let g={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,_,f,p,t,u,g));let v=t.toString(),x=l.createEffect(d,{attributes:u,uniformsNames:_,uniformBuffersNames:f,samplers:p,defines:v,fallbacks:h,onCompiled:i,onError:r,indexParameters:m,processFinalCode:g.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},l);return this._eventInfo.customCode=void 0,x}_prepareDefines(e,t,i=null,r=null,s=!1){var a;let n=this.getScene(),o=n.getEngine();MaterialHelper.PrepareDefinesForLights(n,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(n,t);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(MaterialHelper.PrepareDefinesForPrePass(n,t,this.canRenderToMRT&&!l),MaterialHelper.PrepareDefinesForOIT(n,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++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,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&MaterialFlags.AmbientTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&MaterialFlags.OpacityTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;let e=this._getReflectionTexture();if(e&&MaterialFlags.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,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===texture_Texture.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 texture_Texture.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case texture_Texture.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case texture_Texture.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case texture_Texture.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case texture_Texture.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case texture_Texture.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.CUBIC_MODE:case texture_Texture.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==texture_Texture.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.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;if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled?(MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,MaterialFlags.SpecularTextureEnabled){if(this._metallicTexture?(MaterialHelper.PrepareDefinesForMergedUV(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?(MaterialHelper.PrepareDefinesForMergedUV(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){let e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(a=this._reflectanceTexture)||void 0===a?void 0:a._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(MaterialHelper.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(MaterialHelper.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap?(MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&MaterialFlags.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&&MaterialFlags.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===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===pbrBaseMaterial_PBRBaseMaterial.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=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,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&&(MaterialHelper.PrepareDefinesForMisc(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(buffer_VertexBuffer.NormalKind),t.DEBUGMODE=this._debugMode),MaterialHelper.PrepareDefinesForFrameBoundValues(n,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),MaterialHelper.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(ec.GetDefineNames,this._eventInfo);let s=new PBRMaterialDefines(this._eventInfo.defineNames),a=this._prepareEffect(e,s,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(ao.effect=a,ao.subMesh=null,this._onEffectCreatedObservable.notifyObservers(ao)),a.isReady()?t&&t(this):a.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){let 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,i){var r,s,a,n;let o=this.getScene(),l=i.materialDefines;if(!l)return;let h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);let c=o.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let u=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);MaterialHelper.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let d=null,_=this._uniformBuffer;if(u){if(this.bindViewProjection(h),d=this._getReflectionTexture(),!_.useUbo||!this.isFrozen||!_.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&(_.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),MaterialHelper.BindTextureMatrix(this._albedoTexture,_,"albedo")),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&(_.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),MaterialHelper.BindTextureMatrix(this._ambientTexture,_,"ambient")),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&(_.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),MaterialHelper.BindTextureMatrix(this._opacityTexture,_,"opacity")),d&&MaterialFlags.ReflectionTextureEnabled){if(_.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),_.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){let e=d;_.updateVector3("vReflectionPosition",e.boundingBoxPosition),_.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){let e=d.getSize().width;_.updateFloat2("vReflectionFilteringInfo",e,math_scalar_Scalar.Log2(e))}if(!l.USEIRRADIANCEMAP){let e=d.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&e){if(l.SPHERICAL_HARMONICS){let t=e.preScaledHarmonics;_.updateVector3("vSphericalL00",t.l00),_.updateVector3("vSphericalL1_1",t.l1_1),_.updateVector3("vSphericalL10",t.l10),_.updateVector3("vSphericalL11",t.l11),_.updateVector3("vSphericalL2_2",t.l2_2),_.updateVector3("vSphericalL2_1",t.l2_1),_.updateVector3("vSphericalL20",t.l20),_.updateVector3("vSphericalL21",t.l21),_.updateVector3("vSphericalL22",t.l22)}else _.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),_.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),_.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),_.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),_.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),_.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),_.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),_.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),_.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}}_.updateFloat3("vReflectionMicrosurfaceInfos",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&(_.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),MaterialHelper.BindTextureMatrix(this._emissiveTexture,_,"emissive")),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&(_.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),MaterialHelper.BindTextureMatrix(this._lightmapTexture,_,"lightmap")),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?(_.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),MaterialHelper.BindTextureMatrix(this._metallicTexture,_,"reflectivity")):this._reflectivityTexture&&(_.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),MaterialHelper.BindTextureMatrix(this._reflectivityTexture,_,"reflectivity")),this._metallicReflectanceTexture&&(_.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),MaterialHelper.BindTextureMatrix(this._metallicReflectanceTexture,_,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(_.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),MaterialHelper.BindTextureMatrix(this._reflectanceTexture,_,"reflectance")),this._microSurfaceTexture&&(_.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),MaterialHelper.BindTextureMatrix(this._microSurfaceTexture,_,"microSurfaceSampler"))),this._bumpTexture&&c.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&(_.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),MaterialHelper.BindTextureMatrix(this._bumpTexture,_,"bump"),o._mirroredCameraPosition?_.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):_.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&_.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){TmpColors.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,TmpColors.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,_.updateColor4("vReflectivityColor",TmpColors.Color3[0],1);let e=null!==(s=null===(r=this.subSurface)||void 0===r?void 0:r._indexOfRefraction)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((e-1)/(e+1),2)*this._metallicF0Factor,TmpColors.Color3[0]);let t=this._metallicF0Factor;_.updateColor4("vMetallicReflectanceFactors",TmpColors.Color3[0],t)}else _.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);_.updateColor3("vEmissiveColor",MaterialFlags.EmissiveTextureEnabled?this._emissiveColor:math_color_Color3.BlackReadOnly),_.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(a=this.subSurface)||void 0===a?void 0:a._linkRefractionWithTransparency)?_.updateColor4("vAlbedoColor",this._albedoColor,1):_.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*o.environmentIntensity,this._lightingInfos.w=this._specularIntensity,_.updateVector4("vLightingIntensity",this._lightingInfos),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),_.updateColor3("vAmbientColor",this._globalAmbientColor),_.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}o.texturesEnabled&&(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&_.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&_.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&_.setTexture("opacitySampler",this._opacityTexture),d&&MaterialFlags.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?_.setTexture("reflectionSampler",d):(_.setTexture("reflectionSampler",d._lodTextureMid||d),_.setTexture("reflectionSamplerLow",d._lodTextureLow||d),_.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&_.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&_.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&_.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&_.setTexture("lightmapSampler",this._lightmapTexture),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?_.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&_.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&_.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&_.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&_.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&c.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&_.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),bindClipPlane(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(u||!this.isFrozen)&&(o.lightsEnabled&&!this._disableLighting&&MaterialHelper.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==scene_Scene.FOGMODE_NONE||d||this.subSurface.refractionTexture||t.receiveShadows||l.PREPASS)&&this.bindView(h),MaterialHelper.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&MaterialHelper.BindMorphTargetParameters(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(n=t.bakedVertexAnimationManager)||void 0===n||n.bind(h,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),MaterialHelper.BindLogDepth(l,this._activeEffect,o)),this._afterBind(t,this._activeEffect),_.update()}getAnimatables(){let 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(){let 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(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;let t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,r,s,a,n,o,l,h,c,u,d,_;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(a=this._reflectionTexture)||void 0===a||a.dispose(),null===(n=this._emissiveTexture)||void 0===n||n.dispose(),null===(o=this._metallicTexture)||void 0===o||o.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(c=this._lightmapTexture)||void 0===c||c.dispose(),null===(u=this._metallicReflectanceTexture)||void 0===u||u.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.dispose(),null===(_=this._microSurfaceTexture)||void 0===_||_.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}};pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE=material_Material.MATERIAL_OPAQUE,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST=material_Material.MATERIAL_ALPHATEST,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND=material_Material.MATERIAL_ALPHABLEND,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND=material_Material.MATERIAL_ALPHATESTANDBLEND,pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL=0,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF=1,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD=2,__decorate([generateSerializableMember(9,void 0)],pbrBaseMaterial_PBRBaseMaterial.prototype,"_imageProcessingConfiguration",void 0),__decorate([expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrBaseMaterial_PBRBaseMaterial.prototype,"debugMode",void 0),__decorate([serialize()],pbrBaseMaterial_PBRBaseMaterial.prototype,"useLogarithmicDepth",null);let pbrMaterial_PBRMaterial=class pbrMaterial_PBRMaterial extends pbrBaseMaterial_PBRBaseMaterial{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===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF:this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.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){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=math_color_Color3.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new math_color_Color3(0,0,0),this.albedoColor=new math_color_Color3(1,1,1),this.reflectivityColor=new math_color_Color3(1,1,1),this.reflectionColor=new math_color_Color3(1,1,1),this.emissiveColor=new math_color_Color3(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=GetEnvironmentBRDFTexture(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=decorators_SerializationHelper.Clone(()=>new pbrMaterial_PBRMaterial(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new pbrMaterial_PBRMaterial(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),material_Material._parsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};function FourCCToInt32(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function Int32ToFourCC(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}pbrMaterial_PBRMaterial.PBRMATERIAL_OPAQUE=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATEST=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHABLEND=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND,pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"directIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"environmentIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"specularIntensity",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"disableBumpMap",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"albedoTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTextureStrength",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"opacityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectionTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectivityTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallic",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"roughness",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicF0Factor",void 0),__decorate([serializeAsColor3(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicReflectanceColor",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicReflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectanceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"microSurfaceTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"bumpTexture",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],pbrMaterial_PBRMaterial.prototype,"lightmapTexture",void 0),__decorate([serializeAsColor3("ambient"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientColor",void 0),__decorate([serializeAsColor3("albedo"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"albedoColor",void 0),__decorate([serializeAsColor3("reflectivity"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectivityColor",void 0),__decorate([serializeAsColor3("reflection"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectionColor",void 0),__decorate([serializeAsColor3("emissive"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveColor",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"microSurface",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useLightmapAsShadowmap",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"useAlphaFromAlbedoTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"forceAlphaTest",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"alphaCutOff",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useSpecularOverAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRoughnessFromMetallicTextureGreen",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useMetallnessFromMetallicTextureBlue",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAmbientInGrayScale",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),__decorate([serialize()],pbrMaterial_PBRMaterial.prototype,"usePhysicalLightFalloff",null),__decorate([serialize()],pbrMaterial_PBRMaterial.prototype,"useGLTFLightFalloff",null),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRadianceOverAlpha",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useObjectSpaceNormalMap",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useParallax",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useParallaxOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"parallaxScaleBias",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],pbrMaterial_PBRMaterial.prototype,"disableLighting",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"forceIrradianceInFragment",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],pbrMaterial_PBRMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"invertNormalMapX",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"invertNormalMapY",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"twoSidedLighting",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAlphaFresnel",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useLinearAlphaFresnel",void 0),__decorate([expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"environmentBRDFTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"forceNormalForward",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"enableSpecularAntiAliasing",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useHorizonOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRadianceOcclusion",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrMaterial_PBRMaterial.prototype,"unlit",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsMiscDirty")],pbrMaterial_PBRMaterial.prototype,"applyDecalMapAfterDetailMap",void 0),h["BABYLON.PBRMaterial"]=pbrMaterial_PBRMaterial;let al=FourCCToInt32("DXT1"),ah=FourCCToInt32("DXT3"),ac=FourCCToInt32("DXT5"),au=FourCCToInt32("DX10");let DDSTools=class DDSTools{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),r=1;131072&t[2]&&(r=Math.max(1,t[7]));let s=t[21],a=s===au?i[32]:0,n=0;switch(s){case 113:n=2;break;case 116:n=1;break;case au:if(10===a){n=2;break}2===a&&(n=1)}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:(4&t[20])==4,isRGB:(64&t[20])==64,isLuminance:(131072&t[20])==131072,isCube:(512&t[28])==512,isCompressed:s===al||s===ah||s===ac,dxgiFormat:a,textureType:n}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,a){let n=new Float32Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,r,s,a,n,o){let l=new Uint8Array(r),h=new Uint8Array(s,i),c=0;for(let i=0;i0?r.sphericalPolynomial=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:p[4],right:d[0],left:d[1],up:d[2],down:d[3],front:d[4],back:d[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}};DDSTools.StoreLODInAlphaChannel=!1,ThinEngine.prototype.createPrefilteredCubeTexture=function(e,t,i,r,s=null,a=null,n,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,e=>{if(!e){s&&s(null);return}let a=e.texture;if(l?e.info.sphericalPolynomial&&(a._sphericalPolynomial=e.info.sphericalPolynomial):a._sphericalPolynomial=new SphericalPolynomial,a._source=$.CubePrefiltered,this.getCaps().textureLOD){s&&s(a);return}let n=this._gl,o=e.width;if(!o)return;let h=[];for(let s=0;s<3;s++){let l=s/2,c=1-l,u=math_scalar_Scalar.Log2(o)*i+r,d=r+(u-r)*c,_=Math.round(Math.min(Math.max(d,0),u)),p=new internalTexture_InternalTexture(this,$.Temp);if(p.type=a.type,p.format=a.format,p.width=Math.pow(2,Math.max(math_scalar_Scalar.Log2(o)-_,0)),p.height=p.width,p.isCube=!0,p._cachedWrapU=0,p._cachedWrapV=0,this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,p,!0),p.samplingMode=2,n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_CUBE_MAP,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),e.isDDS){let t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),DDSTools.UploadDDSLevels(this,p,i,t,!0,6,_)}else logger_Logger.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null);let f=new baseTexture_BaseTexture(t);f._isCube=!0,f._texture=p,p.isReady=!0,h.push(f)}a._lodTextureHigh=h[2],a._lodTextureMid=h[1],a._lodTextureLow=h[0],s&&s(a)},a,n,o,l,i,r)};let _DDSTextureLoader=class _DDSTextureLoader{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,r){let s;let a=t.getEngine(),n=!1,o=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,a._unpackFlipY(s.isCompressed),DDSTools.UploadDDSLevels(a,t,r,s,n,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:a.generateMipMapsForCubemap(t)}else s=DDSTools.GetDDSInfo(e),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new SphericalPolynomial),n=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,a._unpackFlipY(s.isCompressed),DDSTools.UploadDDSLevels(a,t,e,s,n,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:a.generateMipMapsForCubemap(t,!1);a._setCubeMapTextureParams(t,n,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){let r=DDSTools.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1==1;i(r.width,r.height,s,r.isFourCC,()=>{DDSTools.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}};engine_Engine._TextureLoaders.push(new _DDSTextureLoader);let _ENVTextureLoader=class _ENVTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let a=GetEnvInfo(e);if(a){t.width=a.width,t.height=a.width;try{UploadEnvSpherical(t,a),UploadEnvLevelsAsync(t,e,a).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},e=>{null==s||s("Can not upload environment levels",e)})}catch(e){null==s||s("Can not upload environment file",e)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}};engine_Engine._TextureLoaders.push(new _ENVTextureLoader);let KhronosTextureContainer=class KhronosTextureContainer{constructor(e,t){if(this.data=e,this.isInvalid=!1,!KhronosTextureContainer.IsValid(e)){this.isInvalid=!0,logger_Logger.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=r.getUint32(0,!0),a=67305985===s;if(this.glType=r.getUint32(1*i,a),this.glTypeSize=r.getUint32(2*i,a),this.glFormat=r.getUint32(3*i,a),this.glInternalFormat=r.getUint32(4*i,a),this.glBaseInternalFormat=r.getUint32(5*i,a),this.pixelWidth=r.getUint32(6*i,a),this.pixelHeight=r.getUint32(7*i,a),this.pixelDepth=r.getUint32(8*i,a),this.numberOfArrayElements=r.getUint32(9*i,a),this.numberOfFaces=r.getUint32(10*i,a),this.numberOfMipmapLevels=r.getUint32(11*i,a),this.bytesOfKeyValueData=r.getUint32(12*i,a),0!==this.glType){logger_Logger.Error("only compressed formats currently supported"),this.isInvalid=!0;return}if(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth){logger_Logger.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(0!==this.numberOfArrayElements){logger_Logger.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){logger_Logger.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=KhronosTextureContainer.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case KhronosTextureContainer.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case KhronosTextureContainer.TEX_2D:case KhronosTextureContainer.COMPRESSED_3D:case KhronosTextureContainer.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=KhronosTextureContainer.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,a=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}};KhronosTextureContainer.HEADER_LEN=64,KhronosTextureContainer.COMPRESSED_2D=0,KhronosTextureContainer.COMPRESSED_3D=1,KhronosTextureContainer.TEX_2D=2,KhronosTextureContainer.TEX_3D=3;let WorkerPool=class WorkerPool{constructor(e){this._pendingActions=[],this._workerInfos=e.map(e=>({workerPromise:Promise.resolve(e),idle:!0}))}dispose(){for(let 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(let t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{let t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0})})}};let AutoReleaseWorkerPool=class AutoReleaseWorkerPool extends WorkerPool{constructor(e,t,i=AutoReleaseWorkerPool.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e)){if(this._workerInfos.length{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(e=>{e.terminate()});let t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)},this._options.idleTimeElapsedBeforeRelease))})})}};function applyConfig(e){e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}AutoReleaseWorkerPool.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},function(e){e[e.ETC1S=0]="ETC1S",e[e.UASTC4x4=1]="UASTC4x4"}(tv||(tv={})),function(e){e[e.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",e[e.BC7_RGBA=1]="BC7_RGBA",e[e.BC3_RGBA=2]="BC3_RGBA",e[e.BC1_RGB=3]="BC1_RGB",e[e.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",e[e.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",e[e.ETC2_RGBA=6]="ETC2_RGBA",e[e.ETC1_RGB=7]="ETC1_RGB",e[e.RGBA32=8]="RGBA32",e[e.R8=9]="R8",e[e.RG8=10]="RG8"}(tx||(tx={})),function(e){e[e.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",e[e.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",e[e.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",e[e.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",e[e.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",e[e.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",e[e.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",e[e.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",e[e.RGBA8Format=32856]="RGBA8Format",e[e.R8Format=33321]="R8Format",e[e.RG8Format=33323]="RG8Format"}(tb||(tb={}));let DefaultKTX2DecoderOptions=class DefaultKTX2DecoderOptions{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;let e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[tx.BC1_RGB,tx.BC3_RGBA],yes:{transcodeFormat:tx.RGBA32,engineFormat:tb.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}};let KhronosTextureContainer2=class KhronosTextureContainer2{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(KhronosTextureContainer2._WorkerPoolPromise||KhronosTextureContainer2._DecoderModulePromise)return;let t={jsDecoderModule:tools_Tools.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:tools_Tools.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:tools_Tools.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?KhronosTextureContainer2._WorkerPoolPromise=new Promise(i=>{let r=`${applyConfig}(${workerFunc})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new AutoReleaseWorkerPool(e,()=>new Promise((e,i)=>{let r=new Worker(s),onError=e=>{r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),i(e)},onMessage=t=>{"init"===t.data.action&&(r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),e(r))};r.addEventListener("error",onError),r.addEventListener("message",onMessage),r.postMessage({action:"init",urls:t})})))}):"undefined"==typeof KTX2DECODER?KhronosTextureContainer2._DecoderModulePromise=tools_Tools.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,applyConfig(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,KhronosTextureContainer2._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=KhronosTextureContainer2.DefaultNumWorkers){this._engine=e,KhronosTextureContainer2._Initialize(t)}uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(KhronosTextureContainer2._WorkerPoolPromise)return KhronosTextureContainer2._WorkerPoolPromise.then(r=>new Promise((a,n)=>{r.push((r,o)=>{let onError=e=>{r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),n(e),o()},onMessage=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),e.data.success)try{this._createTexture(e.data.decodedData,t,i),a()}catch(e){n({message:e})}else n({message:e.data.msg});o()}};r.addEventListener("error",onError),r.addEventListener("message",onMessage),r.postMessage({action:"setDefaultDecoderOptions",options:KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions()});let l=new Uint8Array(e.byteLength);l.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:l,caps:s,options:i},[l.buffer])})}));if(KhronosTextureContainer2._DecoderModulePromise)return KhronosTextureContainer2._DecoderModulePromise.then(i=>(KhronosTextureContainer2.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((s,a)=>{i.decode(e,r).then(e=>{this._createTexture(e,t),s()}).catch(e=>{a({message:e})})})));throw Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let r=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,r=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}};function workerFunc(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;importScripts(i.jsDecoderModule),applyConfig(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=t.data.options;break;case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(e=>{let t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})})}}}function mapSRGBToLinear(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}KhronosTextureContainer2.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},KhronosTextureContainer2.DefaultNumWorkers=KhronosTextureContainer2.GetDefaultNumWorkers(),KhronosTextureContainer2.DefaultDecoderOptions=new DefaultKTX2DecoderOptions;let _KTXTextureLoader=class _KTXTextureLoader{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),a=new KhronosTextureContainer(e,6),n=a.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),a.uploadLevels(t,t.generateMipMaps),t.width=a.pixelWidth,t.height=a.pixelHeight,s._setCubeMapTextureParams(t,n,a.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(KhronosTextureContainer.IsValid(e)){t._invertVScale=!t.invertY;let r=new KhronosTextureContainer(e,1),s=mapSRGBToLinear(r.glInternalFormat);s?(t.format=s,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else if(KhronosTextureContainer2.IsValid(e)){let s=new KhronosTextureContainer2(t.getEngine());s.uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},e=>{logger_Logger.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,()=>{},!0)})}else logger_Logger.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0)}};engine_Engine._TextureLoaders.unshift(new _KTXTextureLoader);let WebXRCamera=class WebXRCamera extends FreeCamera{constructor(e,t,i){super(e,math_vector_Vector3.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=math_vector_Quaternion.Identity(),this._referencedPosition=new math_vector_Vector3,this._trackingState=eN.NOT_TRACKING,this.onXRCameraInitializedObservable=new observable_Observable,this.onBeforeCameraTeleport=new observable_Observable,this.onAfterCameraTeleport=new observable_Observable,this.onTrackingStateChanged=new observable_Observable,this.compensateOnFirstFrame=!0,this._rotate180=new math_vector_Quaternion(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new math_vector_Quaternion,this.cameraRigMode=camera_Camera.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new math_viewport_Viewport(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new math_viewport_Viewport(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;let i=e.computeWorldMatrix();i.decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,math_vector_Quaternion.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){let t=math_vector_TmpVectors.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();let i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),math_vector_Quaternion.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(eN.NOT_TRACKING);return}let t=e.emulatedPosition?eN.TRACKING_LOST:eN.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){let e={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(e),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){let t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;let i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach((e,t)=>{var i;let r=this.rigCameras[t];r.isLeftCamera||r.isRightCamera||("right"===e.eye?r._isRightCamera=!0:"left"!==e.eye||(r._isLeftCamera=!0));let s=e.transform.position,a=e.transform.orientation;r.parent=this.parent,r.position.set(s.x,s.y,s.z),r.rotationQuaternion.set(a.x,a.y,a.z,a.w),this._scene.useRightHandedSystem?r.rotationQuaternion.multiplyInPlace(this._rotate180):(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1),math_vector_Matrix.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,r._projectionMatrix),this._scene.useRightHandedSystem||r._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(r._projectionMatrix);let n=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==n?void 0:n._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=n):(this._xrSessionManager.trySetViewportForView(r.viewport,e),r.outputRenderTarget=n||this._xrSessionManager.getRenderTargetTextureForView(e)),r.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){let e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){let e=math_vector_TmpVectors.Matrix[0],t=math_vector_TmpVectors.Matrix[1],i=math_vector_TmpVectors.Matrix[2];math_vector_Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),math_vector_Matrix.ComposeToRef(WebXRCamera._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);let r=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(r)}}};WebXRCamera._ScaleReadOnly=math_vector_Vector3.One();let WebXRExperienceHelper=class WebXRExperienceHelper{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new observable_Observable,this.onStateChangedObservable=new observable_Observable,this.state=eB.NOT_IN_XR,this.sessionManager=new WebXRSessionManager(e),this.camera=new WebXRCamera("webxr",e,this.sessionManager),this.featuresManager=new WebXRFeaturesManager(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){let t=new WebXRExperienceHelper(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(e=>{throw t._setState(eB.NOT_IN_XR),t.dispose(),e})}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),r={}){var s,a,n;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(eB.ENTERING_XR),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&logger_Logger.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);let o=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(webXRFeaturesManager_WebXRFeatureName.LAYERS)||(l.baseLayer=o),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(a=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===a?void 0:a.attachedToElement),null===(n=this._nonVRCamera)||void 0===n||n.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce(()=>{this.state!==eB.EXITING_XR&&this._setState(eB.EXITING_XR),this.camera.rigCameras.forEach(e=>{e.outputRenderTarget=null}),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(eB.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(eB.IN_XR)}),this.sessionManager}catch(e){throw console.log(e),console.log(e.message),this._setState(eB.NOT_IN_XR),e}}exitXRAsync(){return this.state!==eB.IN_XR?Promise.resolve():(this._setState(eB.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){let t=(null==e?void 0:e.fps)?e.fps:1e3,i=1/t*1e3,r=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,updateSpectatorCamera=()=>{if(this._spectatorCamera){let e=this.sessionManager.currentTimestamp-this._lastTimestamp;e>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[r].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[r].absoluteRotation))}};if(this._spectatorMode){if(r>=this.camera.rigCameras.length)throw Error("the preferred camera index is beyond the length of rig camera array.");let onStateChanged=()=>{this.state===eB.IN_XR?(this._spectatorCamera=new universalCamera_UniversalCamera("webxr-spectator",math_vector_Vector3.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new math_vector_Quaternion,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera),this._scene.onAfterRenderCameraObservable.add(e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===eB.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera),this._scene.activeCameras=null)};this.onStateChangedObservable.add(onStateChanged),onStateChanged()}else this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}};let WebXRControllerComponent=class WebXRControllerComponent{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new observable_Observable,this.onButtonStateChangedObservable=new observable_Observable}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return -1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){let i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}};WebXRControllerComponent.BUTTON_TYPE="button",WebXRControllerComponent.SQUEEZE_TYPE="squeeze",WebXRControllerComponent.THUMBSTICK_TYPE="thumbstick",WebXRControllerComponent.TOUCHPAD_TYPE="touchpad",WebXRControllerComponent.TRIGGER_TYPE="trigger";let WebXRAbstractMotionController=class WebXRAbstractMotionController{constructor(e,t,i,r,s=!1,a){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=a,this._initComponent=e=>{if(!e)return;let t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new WebXRControllerComponent(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new observable_Observable,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach(e=>this.getComponent(e).dispose()),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach(e=>{e.setEnabled(!1)}),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map(e=>this.components[e]).filter(t=>t.type===e)}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){let e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath();return e?logger_Logger.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{let meshesLoaded=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){let e=this._controllerCache.filter(e=>e.filename===t.filename&&e.path===t.path);if(e[0]){e[0].meshes.forEach(e=>e.setEnabled(!0)),meshesLoaded(e[0].meshes);return}}sceneLoader_SceneLoader.ImportMesh("",t.path,t.filename,this.scene,e=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:e})),meshesLoaded(e)},null,(e,i)=>{logger_Logger.Log(i),logger_Logger.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)})})}updateFromXRFrame(e){this.getComponentIds().forEach(e=>this.getComponent(e).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(e=>e.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(e=>e.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;let r=i?.5*t+.5:t;math_vector_Quaternion.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),math_vector_Vector3.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=math_vector_Quaternion.FromEulerAngles(0,Math.PI,0)}};let WebXRGenericTriggerMotionController=class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,ad[i],t,i),this.profileId=WebXRGenericTriggerMotionController.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=math_vector_Quaternion.FromEulerAngles(0,Math.PI,0)}_updateModel(){}};WebXRGenericTriggerMotionController.ProfileId="generic-trigger";let ad={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};let WebXRProfiledMotionController=class WebXRProfiledMotionController extends WebXRAbstractMotionController{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){let e=sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb");return e||logger_Logger.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach(i=>{let r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{let s=t.type===WebXRControllerComponent.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===WebXRControllerComponent.TOUCHPAD_TYPE&&!this._touchDots[i]){let t=sphereBuilder_CreateSphere(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new standardMaterial_StandardMaterial(i+"mat",this.scene),t.material.diffuseColor=math_color_Color3.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}})})}_setRootMesh(e){let t;this.rootMesh=new mesh_Mesh(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{let t=this.getComponent(e);if(!t.hasChanges)return;let i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach(e=>{let s=r.visualResponses[e],a=t.value;if("xAxis"===s.componentProperty?a=t.axes.x:"yAxis"===s.componentProperty&&(a=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],a,"button"!==s.componentProperty);else{let r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}})})}};let a_=[];let WebXRMotionControllerManager=class WebXRMotionControllerManager{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){let t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){let r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");let s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),!this.UseOnlineRepository)return this._LoadProfilesFromAvailableControllers(r,e,t);{let i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch(()=>s.call(this,r,e,t))}}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=tools_Tools.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e.toString())),this._ProfilesList}static ClearControllerCache(){a_.forEach(e=>{e.meshes.forEach(e=>{e.dispose(!1,!0)})}),a_.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=tools_Tools.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then(e=>JSON.parse(e))),this._ProfileLoadingPromises[e])).then(e=>new WebXRProfiledMotionController(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:a_))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;rnew WebXRGenericTriggerMotionController(t,e.gamepad,e.handedness)),WebXRMotionControllerManager.DefaultFallbacks();let ap=0;let WebXRInputSource=class WebXRInputSource{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new math_vector_Vector3,this._disposed=!1,this.onDisposeObservable=new observable_Observable,this.onMeshLoadedObservable=new observable_Observable,this.onMotionControllerInitObservable=new observable_Observable,this._uniqueId=`controller-${ap++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new abstractMesh_AbstractMesh(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new math_vector_Quaternion,this.inputSource.gripSpace&&(this.grip=new abstractMesh_AbstractMesh(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new math_vector_Quaternion),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&WebXRMotionControllerManager.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then(e=>{var t;e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach(e=>e.renderingGroupId=this._options.renderingGroupId)),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&(null===(t=this.motionController)||void 0===t||t.dispose())})},()=>{tools_Tools.Warn("Could not find a matching motion controller for the registered input source")})}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){let i=t&&this.grip?this.grip:this.pointer;math_vector_Vector3.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){let r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){let e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z);let t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){let r=e.getPose(this.inputSource.gripSpace,t);if(r){let e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}};let WebXRInput=class WebXRInput{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new observable_Observable,this.onControllerRemovedObservable=new observable_Observable,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(e=>e.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(e=>{this.controllers.forEach(t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera)})}),this._options.customControllersRepositoryURL&&(WebXRMotionControllerManager.BaseRepositoryUrl=this._options.customControllersRepositoryURL),WebXRMotionControllerManager.UseOnlineRepository=!this._options.disableOnlineControllerRepository,WebXRMotionControllerManager.UseOnlineRepository)try{WebXRMotionControllerManager.UpdateProfilesList().catch(()=>{WebXRMotionControllerManager.UseOnlineRepository=!1})}catch(e){WebXRMotionControllerManager.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){let i=this.controllers.map(e=>e.inputSource);for(let t of e)if(-1===i.indexOf(t)){let e=new WebXRInputSource(this.xrSessionManager.scene,t,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}let r=[],s=[];this.controllers.forEach(e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)}),this.controllers=r,s.forEach(e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),WebXRMotionControllerManager.ClearControllerCache()}};let WebXRControllerPointerSelection=class WebXRControllerPointerSelection extends WebXRAbstractFeature{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),disabledByNearInteraction:!1,id:WebXRControllerPointerSelection._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new math_vector_Vector3,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new math_color_Color3(.9,.9,.9),this.laserPointerDefaultColor=new math_color_Color3(.7,.7,.7),this.selectionMeshDefaultColor=new math_color_Color3(.8,.8,.8),this.selectionMeshPickedColor=new math_color_Color3(.3,.3,1),this._identityMatrix=math_vector_Matrix.Identity(),this._screenCoordinatesRef=math_vector_Vector3.Zero(),this._viewportRef=new math_viewport_Viewport(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){let e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),disabledByNearInteraction:!1,id:WebXRControllerPointerSelection._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;i{let t;let i=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}if(i.laserPointer.isVisible=this.displayLaserPointer,i.xrController)t=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);else{if(!i.webXRCamera)return;t=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay)}if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&t){let e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;!r||(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),math_vector_Vector3.ProjectToRef(t,this._identityMatrix,e.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));let s=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,a.isVisible=!1,t.pick.hit){if(this._pickingMoved(s,t.pick))o&&!this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),o=!1,n=0;else if(n>i/10&&(a.isVisible=!0),(n+=this._scene.getEngine().getDeltaTime())>=i)this._scene.simulatePointerDown(t.pick,l),o=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),a.isVisible=!1;else{let e=1-n/i;a.scaling.set(e,e,e)}}else o=!1,n=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}}),void 0!==this._options.renderingGroupId&&(a.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&o&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),a.dispose()})}_attachScreenRayMode(e){let t=this._controllers[e.uniqueId],i=!1,r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),t.pick&&(!this._options.disablePointerUpOnTouchOut||!i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){let t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);let i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))}),e.inputSource.gamepad){let init=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(r=>{if(r.changes.pressed){let s=r.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)):!s||this._options.enablePointerSelectionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)}})};e.motionController?init(e.motionController):e.onMotionControllerInitObservable.add(init)}else{let selectStartListener=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)},selectEndListener=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)};t.eventListeners={selectend:selectEndListener,selectstart:selectStartListener},this._xrSessionManager.session.addEventListener("selectstart",selectStartListener),this._xrSessionManager.session.addEventListener("selectend",selectEndListener)}}_convertNormalToDirectionOfRay(e,t){if(e){let i=Math.acos(math_vector_Vector3.Dot(e,t.direction));i{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){let e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new PickingInfo,e),t.finalPointerUpTriggered=!0})}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){tools_Tools.Warn("controller already detached.")}})}}_generateNewMeshPair(e){let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():cylinderBuilder_CreateCylinder("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;let r=new standardMaterial_StandardMaterial("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;let s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():CreateTorus("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;let a=new standardMaterial_StandardMaterial("targetMat",t);return a.specularColor=math_color_Color3.Black(),a.emissiveColor=this.selectionMeshDefaultColor,a.backFaceCulling=!1,s.material=a,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));let r=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance,s=this._tmpVectorForPickCompare.length();return s>r}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}};WebXRControllerPointerSelection._IdCounter=200,WebXRControllerPointerSelection.Name=webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION,WebXRControllerPointerSelection.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name,(e,t)=>()=>new WebXRControllerPointerSelection(e,t),WebXRControllerPointerSelection.Version,!0),subMesh_SubMesh.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,a){let n=math_vector_TmpVectors.Vector3[0],o=math_vector_TmpVectors.Vector3[1],l=Infinity;for(let a=this.indexStart;a{if(this._controllers[e.uniqueId])return;let{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:tT.DEHYDRATED,grabRay:new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:WebXRNearInteraction._IdCounter++,pickedPointVisualCue:s},this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new math_color_Color3(.8,.8,.8),this.selectionMeshPickedColor=new math_color_Color3(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=tS.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case tT.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===tT.HOVER)break;case tT.HOVER:e.touchCollisionMeshFunction(!0),tT.TOUCH}else switch(e.currentAnimationState){case tT.TOUCH:if(e.touchCollisionMeshFunction(!1),t===tT.HOVER)break;case tT.HOVER:e.hydrateCollisionMeshFunction(!1),tT.DEHYDRATED}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;let s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(math_vector_TmpVectors.Vector3[0]),s.grabRay.direction.copyFrom(math_vector_TmpVectors.Vector3[0]),this._options.nearInteractionControllerMode!==tS.CENTERED_IN_FRONT||(null===(r=s.xrController)||void 0===r?void 0:r.inputSource.hand)||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var i;let r=this._controllers[t],s=null===(i=r.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!r.xrController||!s&&(!this._options.nearInteractionControllerMode||!r.xrController.inputSource.gamepad)){r.pick=null;return}if(r.hoverInteraction=!1,r.nearInteraction=!1,!r.xrController)return;if(s){let i=s.get("index-finger-tip");if(i){let r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){let e=this._scene.useRightHandedSystem?1:-1;math_vector_TmpVectors.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),math_vector_TmpVectors.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,math_vector_TmpVectors.Vector3[0],math_vector_TmpVectors.Quaternion[0])}}}else if(r.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==tS.DISABLED){let e=r.xrController.pointer;r.xrController.grip&&this._options.nearInteractionControllerMode===tS.CENTERED_ON_CONTROLLER&&(e=r.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}let accuratePickInfo=(e,t)=>t&&t.hit?e&&e.hit?t.distance{let t=new PickingInfo,i=!1,r=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),r&&!i&&(t=e),t};if(!r.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,this._hoverRadius,this._utilityLayerScene,e=>this._nearInteractionPredicate(e)));let i=this._pickWithSphere(r,this._hoverRadius,this._scene,e=>this._nearInteractionPredicate(e)),a=accuratePickInfo(i,t);if(a&&a.hit&&(e=populateNearInteractionInfo(a)).hit&&(r.hoverInteraction=!0),r.hoverInteraction){let t=null,i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,i,this._utilityLayerScene,e=>this._nearPickPredicate(e)));let a=this._pickWithSphere(r,i,this._scene,e=>this._nearPickPredicate(e)),n=accuratePickInfo(a,t),o=populateNearInteractionInfo(n);o.hit&&(e=o,r.nearInteraction=!0)}r.stalePick=r.pick,r.pick=e,r.pick&&r.pick.pickedPoint&&r.pick.hit?(r.meshUnderPointer=r.pick.pickedMesh,r.pickedPointVisualCue.position.copyFrom(r.pick.pickedPoint),r.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!0)):(r.meshUnderPointer=null,r.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!1))}let a=tT.DEHYDRATED;r.grabInteraction||r.nearInteraction?a=tT.TOUCH:r.hoverInteraction&&(a=tT.HOVER),this._handleTransitionAnimation(r,a)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,t=sphereBuilder_CreateSphere("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=math_vector_Quaternion.Identity();let i=new standardMaterial_StandardMaterial("targetMat",e);return i.specularColor=math_color_Color3.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){let t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))});let grabCheck=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!r||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){let init=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;grabCheck(t)}}):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;grabCheck(t)}}))};e.motionController?init(e.motionController):e.onMotionControllerInitObservable.add(init)}else{let selectStartListener=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},selectEndListener=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:selectEndListener,selectstart:selectStartListener},this._xrSessionManager.session.addEventListener("selectstart",selectStartListener),this._xrSessionManager.session.addEventListener("selectend",selectEndListener)}}_detachController(e){let t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach(e=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{let e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new PickingInfo,e)}),delete this._controllers[e],this._attachedController===e)){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,t=sphereBuilder_CreateSphere("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:NodeMaterial.ParseFromSnippetAsync("8RUNKL#3",e).then(e=>{t.material=e});let i=new QuadraticEase;i.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);let r=new math_vector_Vector3(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),a=new math_vector_Vector3(s,s,s),n=this._controllerPickRadius*(7/6),o=new math_vector_Vector3(n,n,n),l=.8*this._controllerPickRadius,h=new math_vector_Vector3(l,l,l),c=1.5*this._controllerPickRadius,u=new math_vector_Vector3(c,c,c),d=[{frame:0,value:r},{frame:10,value:u},{frame:18,value:a}],_=[{frame:0,value:a},{frame:10,value:h},{frame:18,value:r}],p=[{frame:0,value:math_vector_Vector3.ZeroReadOnly},{frame:12,value:o},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:math_vector_Vector3.ZeroReadOnly},{frame:15,value:math_vector_Vector3.ZeroReadOnly}],m=new animation_Animation("touch","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),g=new animation_Animation("release","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),v=new animation_Animation("hydrate","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),x=new animation_Animation("dehydrate","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),x.setEasingFunction(i),m.setKeys(d),g.setKeys(_),v.setKeys(p),x.setKeys(f),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{let r=i?m:g;e.beginDirectAnimation(t,[r],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{let r=i?v:x;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[r],0,15,!1,1,()=>{i||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){let s=new PickingInfo;if(s.distance=Infinity,e.touchCollisionMesh&&e.xrController){let a=e.touchCollisionMesh.position,n=boundingSphere_BoundingSphere.CreateFromCenterAndRadius(a,t);for(let t=0;ts&&(r=0,c.copyFrom(t.center)),-1!==r&&r()=>new WebXRNearInteraction(e,t),WebXRNearInteraction.Version,!0);let WebXREnterExitUIButton=class WebXREnterExitUIButton{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}};let WebXREnterExitUI=class WebXREnterExitUI{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new observable_Observable,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw tools_Tools.Warn("WebXR can only be served over HTTPS"),Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";let e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor",r="undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A",s=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+r+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';let a=document.createElement("style");a.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(a);let n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new WebXREnterExitUIButton(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}let i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce(()=>{this.dispose()}))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;let i=this._buttons.map(t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode));e.onStateChangedObservable.add(e=>{e==eB.NOT_IN_XR&&this._updateButtons(null)});let r=await Promise.all(i);r.forEach((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):tools_Tools.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){let r=new WebXREnterExitUI(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==eB.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==eB.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(r){this._updateButtons(null);let t=this._buttons[e].element,i=t.title;t.title="Error entering XR session : "+i,t.classList.add("xr-error"),this.options.onError&&this.options.onError(r)}}dispose(){let e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach(e=>{e.update(this._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}};function setAndStartTimer(e){var t;let i=0,r=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};let s=e.contextObservable.add(t=>{let a=Date.now();i=a-r;let n={startTime:r,currentTime:a,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(n),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(n)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(n))},e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}!function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(tC||(tC={}));let AdvancedTimer=class AdvancedTimer{constructor(e){var t,i;this.onEachCountObservable=new observable_Observable,this.onTimerAbortedObservable=new observable_Observable,this.onTimerEndedObservable=new observable_Observable,this.onStateChangedObservable=new observable_Observable,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{let t=Date.now();this._timer=t-this._startTime;let i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},r=this._breakOnNextTick||this._breakCondition(i);r||this._timer>=this._timeToEnd?this._stop(i,r):this.onEachCountObservable.notifyObservers(i)},this._setState(tC.INIT),this._contextObservable=e.contextObservable,this._observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{},this._breakCondition=null!==(i=e.breakCondition)&&void 0!==i?i:()=>!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(this._state===tC.STARTED)throw 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(tC.STARTED)}stop(){this._state===tC.STARTED&&(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(tC.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}};let WebXRMotionControllerTeleportation=class WebXRMotionControllerTeleportation extends WebXRAbstractFeature{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){let t=this._options.teleportationTargetMesh.getChildMeshes(!1,e=>"rotationCone"===e.name);t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new math_color_Color4(1,1,1,1),this._tmpRay=new ray_Ray(new math_vector_Vector3,new math_vector_Vector3),this._tmpVector=new math_vector_Vector3,this._tmpQuaternion=new math_vector_Quaternion,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new observable_Observable,this.teleportationEnabled=!0,this._rotationEnabled=!0,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1}};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let initMotionController=()=>{if(e.motionController){let i=e.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){let i=e.motionController.getMainComponent();if(!i)return;t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add(()=>{if(this.teleportationEnabled&&i.changes.pressed){if(i.changes.pressed.current){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;let r=this._options.timeToTeleport||3e3;setAndStartTimer({timeout:r,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else t.teleportationState.forward=!1,this._currentTeleportationControllerId=""}})}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add(i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,math_vector_Quaternion.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);let e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,e=>-1!==this._floorMeshes.indexOf(e));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;let e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);math_vector_Quaternion.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))})}};e.motionController?initMotionController():e.onMotionControllerInitObservable.addOnce(()=>{initMotionController()})}else this._xrSessionManager.scene.onPointerObservable.add(i=>{if(i.type===pointerEvents_PointerEventTypes.POINTERDOWN){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;let i=this._options.timeToTeleport||3e3;setAndStartTimer({timeout:i,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else i.type===pointerEvents_PointerEventTypes.POINTERUP&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="")})},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new math_color_Color4(1,0,0,.75),this._setTargetMeshVisibility(!1)}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)}removeFloorMesh(e){let t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];let t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){let t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t){for(let i=0;i{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;let t=this._floorMeshes.indexOf(e);return -1!==t&&this._floorMeshes[t].absolutePosition.y!!this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e)||-1!==this._floorMeshes.indexOf(e));if(a&&a.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(a.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(a);return}a&&a.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(a),this._setTargetMeshVisibility(!0),this._showParabolicPath(a))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{let i=new DynamicTexture("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;let r=i.getContext();r.beginPath(),r.arc(256,256,200,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),i.update();let s=new standardMaterial_StandardMaterial("teleportationPlaneMaterial",e);s.diffuseTexture=i,t.material=s}let i=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){let t=new animation_Animation("animationInnerCircle","position.y",30,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);let s=new SineEase;s.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}let r=cylinderBuilder_CreateCylinder("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(math_axis_Axis.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{let t=new standardMaterial_StandardMaterial("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new math_color_Color3(.3,.3,1):t.diffuseColor=new math_color_Color3(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){let t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){let s=t*t;this._snapToPositions.forEach(t=>{let a=math_vector_Vector3.DistanceSquared(t,e);a<=s&&a{t.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=Curve3.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,a=Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=linesBuilder_CreateLines("teleportation path line",{points:r.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:a},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){let t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint)){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){let e=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,math_vector_Quaternion.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}};WebXRMotionControllerTeleportation.Name=webXRFeaturesManager_WebXRFeatureName.TELEPORTATION,WebXRMotionControllerTeleportation.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name,(e,t)=>()=>new WebXRMotionControllerTeleportation(e,t),WebXRMotionControllerTeleportation.Version,!0);let WebXRDefaultExperience=class WebXRDefaultExperience{constructor(){}static CreateAsync(e,t={}){let i=new WebXRDefaultExperience;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){let r=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new WebXREnterExitUI(e,r)}return WebXRExperienceHelper.CreateAsync(e).then(e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new WebXRInput(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){let e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name,t.useStablePlugins?"stable":"latest",Object.assign({floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId},t.teleportationOptions)),i.teleportation.setSelectionFeature(i.pointerSelection))}return(t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI)?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(e=>(logger_Logger.Error("Error initializing XR"),logger_Logger.Error(e),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}};function removeSource(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}scene_Scene.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled()),s=r.max.subtract(r.min),a=r.min.add(s.scale(.5)),n=1.5*s.length();if(isFinite(n)||(n=1,a.copyFromFloats(0,0,0)),e){let e=new ArcRotateCamera("default camera",-(Math.PI/2),Math.PI/2,n,a,this);e.lowerRadiusLimit=.01*n,e.wheelPrecision=100/n,t=e}else{let e=new FreeCamera("default camera",new math_vector_Vector3(a.x,a.y,-n),this);e.setTarget(a),t=e}t.minZ=.01*n,t.maxZ=1e3*n,t.speed=.2*n,this.activeCamera=t,i&&t.attachControl()}},scene_Scene.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},scene_Scene.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return logger_Logger.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);let a=boxBuilder_CreateBox("hdrSkyBox",{size:i},this);if(t){let t=new pbrMaterial_PBRMaterial("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=texture_Texture.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,a.material=t}else{let t=new standardMaterial_StandardMaterial("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=texture_Texture.SKYBOX_MODE),t.disableLighting=!0,a.material=t}return a.isPickable=!1,a.infiniteDistance=!0,a.ignoreCameraMaxZ=!0,a},scene_Scene.prototype.createDefaultEnvironment=function(e){return EnvironmentHelper?new EnvironmentHelper(e,this):null},scene_Scene.prototype.createDefaultVRExperience=function(e={}){return new VRExperienceHelper(this,e)},scene_Scene.prototype.createDefaultXRExperienceAsync=function(e={}){return WebXRDefaultExperience.CreateAsync(this,e).then(e=>e)};let VideoTexture=class VideoTexture extends texture_Texture{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new observable_Observable),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):logger_Logger.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((null==e?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}if(!this.video.muted){logger_Logger.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(e=>{this._processError(e)});return}}this._processError(e)})}constructor(e,t,i,r=!1,s=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,n={},o,l=5){var h,c;super(null,i,!r,s),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||tools_Tools.IsExponentOfTwo(this.video.videoWidth)&&tools_Tools.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=texture_Texture.WRAP_ADDRESSMODE,this.wrapV=texture_Texture.WRAP_ADDRESSMODE):(this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=null!==(e=this._format)&&void 0!==e?e:5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{let e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture||this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return tools_Tools.SetCorsBehavior(e.currentSrc,e),e;let t=document.createElement("video");return"string"==typeof e?(tools_Tools.SetCorsBehavior(e,t),t.src=e):(tools_Tools.SetCorsBehavior(e[0],t),e.forEach(e=>{let i=document.createElement("source");i.src=e,t.appendChild(i)})),this.onDisposeObservable.addOnce(()=>{removeSource(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){!e||this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture())}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new VideoTexture(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),null===(e=this._externalTexture)||void 0===e||e.dispose()}static CreateFromStreamAsync(e,t,i,r=!0){let s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(void 0!==s.mozSrcObject?s.mozSrcObject=t:"object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise(t=>{let onPlaying=()=>{let i=new VideoTexture("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&i.onDisposeObservable.addOnce(()=>{s.remove()}),i.onDisposeObservable.addOnce(()=>{removeSource(s)}),t(i),s.removeEventListener("playing",onPlaying)};s.addEventListener("playing",onPlaying),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){let s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),a=await this.CreateFromStreamAsync(e,s,t,r);return a.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(e=>{e.stop()})}),a}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then(function(e){t&&t(e)}).catch(function(e){logger_Logger.Error(e.name)})}};__decorate([serialize("settings")],VideoTexture.prototype,"_settings",void 0),__decorate([serialize("src")],VideoTexture.prototype,"_currentSrc",void 0),__decorate([serialize()],VideoTexture.prototype,"isVideo",void 0),texture_Texture._CreateVideoTexture=(e,t,i,r=!1,s=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,n={},o,l=5)=>new VideoTexture(e,t,i,r,s,a,n,o,l),h["BABYLON.VideoTexture"]=VideoTexture;let VideoDome=class VideoDome extends TextureDome{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){let r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new VideoTexture((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,texture_Texture.TRILINEAR_SAMPLINGMODE,r);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(e=>{var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===this.mesh&&this._texture.video.play()},pointerEvents_PointerEventTypes.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}};VideoDome.MODE_MONOSCOPIC=TextureDome.MODE_MONOSCOPIC,VideoDome.MODE_TOPBOTTOM=TextureDome.MODE_TOPBOTTOM,VideoDome.MODE_SIDEBYSIDE=TextureDome.MODE_SIDEBYSIDE;let af=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) -#include -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; -#endif -#ifdef VERTEXALPHA -varying vec4 vColor; -#endif -uniform vec4 glowColor;uniform float glowIntensity; -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include -vec4 finalColor=glowColor; -#ifdef DIFFUSE -vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); -#ifdef DIFFUSE_ISLINEAR -albedoTexture=toGammaSpace(albedoTexture); -#endif -#ifdef GLOW -finalColor.a*=albedoTexture.a; -#endif -#ifdef HIGHLIGHT -finalColor.a=albedoTexture.a; -#endif -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); -#ifdef OPACITYRGB -finalColor.a*=getLuminance(opacityMap.rgb); -#else -finalColor.a*=opacityMap.a; -#endif -finalColor.a*=opacityIntensity; -#endif -#ifdef VERTEXALPHA -finalColor.a*=vColor.a; -#endif -#ifdef ALPHATEST -if (finalColor.a -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -uniform mat4 viewProjection;varying vec4 vPosition; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity;uniform mat4 opacityMatrix; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; -#endif -#ifdef VERTEXALPHA -attribute vec4 color;varying vec4 vColor; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef CUBEMAP -vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#else -vPosition=viewProjection*worldPos;gl_Position=vPosition; -#endif -#ifdef DIFFUSE -#ifdef DIFFUSEUV1 -vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef DIFFUSEUV2 -vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef OPACITY -#ifdef OPACITYUV1 -vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef OPACITYUV2 -vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef EMISSIVE -#ifdef EMISSIVEUV1 -vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef EMISSIVEUV2 -vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef VERTEXALPHA -vColor=color; -#endif -#include -}`;ShaderStore.ShadersStore.glowMapGenerationVertexShader=am;let EffectLayer=class EffectLayer{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);let a=this._scene.getEngine();if(r.length){for(a.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){let e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=e})}}_addCustomEffectDefines(e){}_isReady(e,t,i){var r;let s=this._scene.getEngine(),a=e.getMesh(),n=null===(r=a._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[s.currentRenderPassId];if(n)return n.isReadyForSubMesh(a,e,t);let o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);let l=[],h=[buffer_VertexBuffer.PositionKind],c=!1,u=!1;if(o){let e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),u=!0):a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(l.push("#define DIFFUSEUV1"),c=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));let r=o.opacityTexture;r&&(l.push("#define OPACITY"),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&1===r.coordinatesIndex?(l.push("#define OPACITYUV2"),u=!0):a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(l.push("#define OPACITYUV1"),c=!0))}i&&(l.push("#define EMISSIVE"),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),u=!0):a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(l.push("#define EMISSIVEUV1"),c=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),a.useVertexColors&&a.isVerticesDataPresent(buffer_VertexBuffer.ColorKind)&&a.hasVertexAlpha&&o.transparencyMode!==material_Material.MATERIAL_OPAQUE&&(h.push(buffer_VertexBuffer.ColorKind),l.push("#define VERTEXALPHA")),c&&(h.push(buffer_VertexBuffer.UVKind),l.push("#define UV1")),u&&(h.push(buffer_VertexBuffer.UV2Kind),l.push("#define UV2"));let d=new EffectFallbacks;if(a.useBones&&a.computeBonesUsingShaders){h.push(buffer_VertexBuffer.MatricesIndicesKind),h.push(buffer_VertexBuffer.MatricesWeightsKind),a.numBoneInfluencers>4&&(h.push(buffer_VertexBuffer.MatricesIndicesExtraKind),h.push(buffer_VertexBuffer.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers);let e=a.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),a.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,a)}else l.push("#define NUM_BONE_INFLUENCERS 0");let _=a.morphTargetManager,p=0;_&&_.numInfluencers>0&&(l.push("#define MORPHTARGETS"),p=_.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+p),_.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(h,a,p)),t&&(l.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),prepareStringDefinesForClipPlanes(o,this._scene,l),this._addCustomEffectDefines(l);let f=e._getDrawWrapper(void 0,!0),m=f.defines,g=l.join("\n");if(m!==g){let e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];addClipPlaneUniforms(e),f.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:p}),g)}return f.effect.isReady()}render(){for(let e=0;en.setMatrix("world",t))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(a)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){let r=tools_Tools.Instantiate(e.customType);return r.Parse(e,t,i)}};EffectLayer._SceneComponentInitialization=e=>{throw _WarnImport("EffectLayerSceneComponent")},__decorate([serialize()],EffectLayer.prototype,"name",void 0),__decorate([generateSerializableMember(8,void 0)],EffectLayer.prototype,"neutralColor",void 0),__decorate([serialize()],EffectLayer.prototype,"isEnabled",void 0),__decorate([serializeAsCameraReference()],EffectLayer.prototype,"camera",null),__decorate([serialize()],EffectLayer.prototype,"renderingGroupId",null),__decorate([serialize()],EffectLayer.prototype,"disableBoundingBoxesFromEffectLayer",void 0),AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER,(e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(e)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.removeEffectLayer(e),t&&e.dispose()})}dispose(){let e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){let i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(let s of r){if(!s.hasMesh(e))continue;let r=s._mainTexture;for(let a of(this._engine.currentRenderPassId=r.renderPassId,e.subMeshes))if(!s.isReady(a,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1,i=this.scene.effectLayers;if(i&&i.length>0){for(let r of(this._previousStencilState=this._engine.getStencilBuffer(),i))if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===camera_Camera.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==camera_Camera.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_EFFECTLAYER);t||(t=new EffectLayerSceneComponent(e),e._addComponent(t))};let ag=`varying vec2 vUV;uniform sampler2D textureSampler; -#ifdef EMISSIVE -uniform sampler2D textureSampler2; -#endif -uniform float offset; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV); -#ifdef EMISSIVE -baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; -#else -baseColor.a=abs(offset-baseColor.a); -#ifdef STROKE -float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; -#endif -#endif -#if LDR -baseColor=clamp(baseColor,0.,1.0); -#endif -gl_FragColor=baseColor; -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.glowMapMergePixelShader=ag;let av=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.glowMapMergeVertexShader=av,AbstractScene.prototype.getGlowLayerByName=function(e){var t;for(let i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===GlowLayer.EffectName)return this.effectLayers[i];return null};let GlowLayer=class GlowLayer extends EffectLayer{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;let t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new math_color_Color4(0,0,0,1),this._options=Object.assign({mainTextureRatio:GlowLayer.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return GlowLayer.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[buffer_VertexBuffer.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;let r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];let a=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new BlurPostProcess("GlowLayerHBP1",new math_vector_Vector2(1,0),a,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new BlurPostProcess("GlowLayerVBP1",new math_vector_Vector2(0,1),a,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new BlurPostProcess("GlowLayerHBP2",new math_vector_Vector2(1,0),a,{width:r,height:s},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new BlurPostProcess("GlowLayerVBP2",new math_vector_Vector2(0,1),a,{width:r,height:s},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(()=>{let e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);let t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(null!=t?t:e,!0)}}),this._postProcesses.map(e=>{e.autoClear=!1})}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;let s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);let t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(material_Material.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var r;let s=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){let e=null!==(r=i.emissiveIntensity)&&void 0!==r?r:1;s*=e,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){let t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){let t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(()=>{this._disposeMesh(e)})}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){let e;let t=decorators_SerializationHelper.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;enew GlowLayer(e.name,t,e.options),e,t,i);for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)})}};let HighlightLayer=class HighlightLayer extends EffectLayer{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new observable_Observable,this.onAfterBlurObservable=new observable_Observable,this._instanceGlowingMeshStencilReference=HighlightLayer.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=HighlightLayer.NeutralColor,this._engine.isStencilEnable||logger_Logger.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return HighlightLayer.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[buffer_VertexBuffer.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?engine_Engine.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new renderTargetTexture_RenderTargetTexture("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerHBP",new math_vector_Vector2(1,0),this._options.blurHorizontalSize,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerVBP",new math_vector_Vector2(0,1),this._options.blurVerticalSize,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new BlurPostProcess("HighlightLayerHBP",new math_vector_Vector2(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new BlurPostProcess("HighlightLayerVBP",new math_vector_Vector2(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(e=>{e.autoClear=!1})}needStencil(){return!0}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,a=this._meshes[r.uniqueId];return a&&a.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);let i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(material_Material.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(material_Material.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return(!this._excludedMeshes||!this._excludedMeshes[e.uniqueId])&&!!super.hasMesh(e)}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];if(!t){let t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add(e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)}),t.afterRender=e.onAfterRenderObservable.add(e=>{e.getEngine().setStencilBuffer(t.stencilState)}),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!(this._meshes&&super.hasMesh(e))&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(e=>{this.isEnabled&&this._defaultStencilReference(e)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];for(let i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(let e in this._excludedMeshes){let t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){let e=decorators_SerializationHelper.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(let t in this._meshes){let i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(let t in this._excludedMeshes){let i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){let r;let s=decorators_SerializationHelper.Parse(()=>new HighlightLayer(e.name,t,e.options),e,t,i);for(r=0;r -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV); -#ifdef LINEAR -baseColor.rgb=toGammaSpace(baseColor.rgb); -#endif -#ifdef ALPHATEST -if (baseColor.a<0.4) -discard; -#endif -gl_FragColor=baseColor*color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.layerPixelShader=ab;let aT=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.layerVertexShader=aT;let LensFlare=class LensFlare{static AddFlare(e,t,i,r,s){return new LensFlare(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new math_color_Color3(1,1,1),this.texture=r?new texture_Texture(r,s.getScene(),!0):null,this._system=s;let a=s.scene.getEngine();this._drawWrapper=new drawWrapper_DrawWrapper(a),this._drawWrapper.effect=a.createEffect("lensFlare",[buffer_VertexBuffer.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();let e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}};let aS=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.lensFlarePixelShader=aS;let aC=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.lensFlareVertexShader=aC;let LensFlareSystem=class LensFlareSystem{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||engineStore_EngineStore.LastCreatedScene,LensFlareSystem._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&(e.layerMask&i.activeCamera.layerMask)!=0;let r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(r,s,buffer_VertexBuffer.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){let 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)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=math_vector_Vector3.Project(t,math_vector_Matrix.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=math_vector_Vector3.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);let i=this._scene.useRightHandedSystem,r=t.z>0&&!i||t.z<0&&i;return!!r&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;let e=this.getEmitterPosition(),t=e.subtract(this._scene.activeCamera.globalPosition),i=t.length();t.normalize();let r=new ray_Ray(this._scene.activeCamera.globalPosition,t),s=this._scene.pickWithRay(r,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>i}render(){let e,t;if(!this._scene.activeCamera)return!1;let i=this._scene.getEngine(),r=this._scene.activeCamera.viewport,s=r.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(s)||!this._isVisible())return!1;let a=(e=this._positionXs.x+s.width-this.borderLimit?this._positionX-s.x-s.width+this.borderLimit:0)>(t=this._positionYs.y+s.height-this.borderLimit?this._positionY-s.y-s.height+this.borderLimit:0)?e:t;(a-=this.viewportBorder)>this.borderLimit&&(a=this.borderLimit);let n=1-math_scalar_Scalar.Clamp(a/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(s.x+=this.viewportBorder,s.y+=this.viewportBorder,s.width-=2*this.viewportBorder,s.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);let o=s.x+s.width/2,l=s.y+s.height/2,h=o-this._positionX,c=l-this._positionY;i.setState(!1),i.setDepthBuffer(!1);for(let e=0;e{throw _WarnImport("LensFlareSystemSceneComponent")},AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM,(e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,a=e.lensFlareSystems.length;s{this.scene.addLensFlareSystem(e)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()})}serialize(e){e.lensFlareSystems=[];let t=this.scene.lensFlareSystems;for(let i of t)e.lensFlareSystems.push(i.serialize())}dispose(){let e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){let t=this.scene.lensFlareSystems;for(let i of(tools_Tools.StartPerformanceCounter("Lens flares",t.length>0),t))(e.layerMask&i.layerMask)!=0&&i.render();tools_Tools.EndPerformanceCounter("Lens flares",t.length>0)}}};LensFlareSystem._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_LENSFLARESYSTEM);t||(t=new LensFlareSystemSceneComponent(e),e._addComponent(t))};let aE=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} -float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); -vec2 P2=floor(0.5*mod(_P,4.0)); -return 4.0*bayerDither2(P1)+bayerDither2(P2);} -float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); -vec2 P2=floor(0.5 *mod(_P,4.0)); -vec2 P4=floor(0.25*mod(_P,8.0)); -return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} -`;ShaderStore.IncludesShadersStore.bayerDitherFunctions=aE;let ay=`#if SM_FLOAT==0 -#include -#endif -#if SM_SOFTTRANSPARENTSHADOW==1 -#include -uniform float softTransparentShadowSM; -#endif -varying float vDepthMetricSM; -#if SM_USEDISTANCE==1 -uniform vec3 lightDataSM;varying vec3 vPositionWSM; -#endif -uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -varying float zSM; -#endif -`;ShaderStore.IncludesShadersStore.shadowMapFragmentExtraDeclaration=ay;let aR=`float depthSM=vDepthMetricSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -#if SM_USEDISTANCE==1 -depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -#ifdef USE_REVERSE_DEPTHBUFFER -depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#endif -#ifdef USE_REVERSE_DEPTHBUFFER -gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); -#else -gl_FragDepth=clamp(depthSM,0.0,1.0); -#endif -#elif SM_USEDISTANCE==1 -depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#if SM_ESM==1 -depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); -#endif -#if SM_FLOAT==1 -gl_FragColor=vec4(depthSM,1.0,1.0,1.0); -#else -gl_FragColor=pack(depthSM); -#endif -return;`;ShaderStore.IncludesShadersStore.shadowMapFragment=aR;let aP=`#include -#ifdef ALPHATEXTURE -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include -#ifdef ALPHATEXTURE -float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; -#ifdef ALPHATESTVALUE -if (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard; -#else -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; -#endif -#endif -#include -}`;ShaderStore.ShadersStore.shadowMapPixelShader=aP;let aA=`uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; -`;ShaderStore.IncludesShadersStore.sceneVertexDeclaration=aA;let aM=`uniform mat4 world;uniform float visibility; -`;ShaderStore.IncludesShadersStore.meshVertexDeclaration=aM;let aI=`#include -#include -`;ShaderStore.IncludesShadersStore.shadowMapVertexDeclaration=aI;let aD=`layout(std140,column_major) uniform; -#include -#include -`;ShaderStore.IncludesShadersStore.shadowMapUboDeclaration=aD;let aO=`#if SM_NORMALBIAS==1 -uniform vec3 lightDataSM; -#endif -uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; -#if SM_USEDISTANCE==1 -varying vec3 vPositionWSM; -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -varying float zSM; -#endif -`;ShaderStore.IncludesShadersStore.shadowMapVertexExtraDeclaration=aO;let aB=`#if SM_NORMALBIAS==1 -#if SM_DIRECTIONINLIGHTDATA==1 -vec3 worldLightDirSM=normalize(-lightDataSM.xyz); -#else -vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); -#endif -float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; -#endif -`;ShaderStore.IncludesShadersStore.shadowMapVertexNormalBias=aB;let aN=`#if SM_USEDISTANCE==1 -vPositionWSM=worldPos.xyz; -#endif -#if SM_DEPTHTEXTURE==1 -#ifdef IS_NDC_HALF_ZRANGE -#define BIASFACTOR 0.5 -#else -#define BIASFACTOR 1.0 -#endif -#ifdef USE_REVERSE_DEPTHBUFFER -gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; -#else -gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; -#endif -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -zSM=gl_Position.z;gl_Position.z=0.0; -#elif SM_USEDISTANCE==0 -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#endif -`;ShaderStore.IncludesShadersStore.shadowMapVertexMetric=aN;let aF=`attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef INSTANCES -attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; -#endif -#include -#include<__decl__shadowMapVertex> -#ifdef ALPHATEXTURE -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normWorldSM=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vec3 vNormalW=normalize(normWorldSM*normalUpdated); -#endif -#endif -#include -gl_Position=viewProjection*worldPos; -#include -#ifdef ALPHATEXTURE -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#include -}`;ShaderStore.ShadersStore.shadowMapVertexShader=aF;let aw=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) -for (int y=-OFFSET; y<=OFFSET; y++) -colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;ShaderStore.ShadersStore.depthBoxBlurPixelShader=aw;let aL=`#if SM_SOFTTRANSPARENTSHADOW==1 -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; -#endif -`;ShaderStore.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=aL;let shadowGenerator_ShadowGenerator=class shadowGenerator_ShadowGenerator{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}if(e===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}if(e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCF);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCF)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCSS);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return shadowGenerator_ShadowGenerator.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(let t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(let t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,r,s){this.onBeforeShadowMapRenderObservable=new observable_Observable,this.onAfterShadowMapRenderObservable=new observable_Observable,this.onBeforeShadowMapRenderMeshObservable=new observable_Observable,this.onAfterShadowMapRenderMeshObservable=new observable_Observable,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=shadowGenerator_ShadowGenerator.FILTER_NONE,this._filteringQuality=shadowGenerator_ShadowGenerator.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=math_vector_Vector3.Zero(),this._viewMatrix=math_vector_Matrix.Zero(),this._projectionMatrix=math_vector_Matrix.Zero(),this._transformMatrix=math_vector_Matrix.Zero(),this._cachedPosition=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new math_vector_Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=math_vector_Matrix.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=r?r:null,this._useRedTextureType=!!s;let a=t._shadowGenerators;a||(a=t._shadowGenerators=new Map),a.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),shadowGenerator_ShadowGenerator._SceneComponentInitialization(this._scene);let n=this._scene.getEngine().getCaps();i?n.textureFloatRender&&n.textureFloatLinearFiltering?this._textureType=1:n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:n.textureHalfFloatRender&&n.textureHalfFloatLinearFiltering?this._textureType=2:n.textureFloatRender&&n.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){let e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new renderTargetTexture_RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new renderTargetTexture_RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,r)=>this._renderForShadowMap(e,t,i,r),this._shadowMap.customIsReadyFunction=()=>!0;let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var t,i;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){null===(t=e._debugPopGroup)||void 0===t||t.call(e,1);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))});let t=new math_color_Color4(0,0,0,0),i=new math_color_Color4(1,1,1,1);this._shadowMap.onClearObservable.add(e=>{this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let e=RenderingManager.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new BlurPostProcess(this._light.name+"KernelBlurY",new math_vector_Vector2(0,1),this.blurKernel,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new postProcess_PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;sa._getWorldMatrixDeterminant(),c=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;h&&(c=0===c?1:0);let u=0===c;o.setState(l.backFaceCulling,void 0,void 0,u,l.cullBackFaces);let d=s._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;let _=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||s.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e)){if(this.isReady(e,_,t)){e._renderId=n.getRenderId();let i=l.shadowDepthWrapper,h=null!==(r=null==i?void 0:i.getEffect(e,this,o.currentRenderPassId))&&void 0!==r?r:e._getDrawWrapper(),c=drawWrapper_DrawWrapper.GetEffect(h);o.enableEffect(h),_||s._bind(e,c,l.fillMode),this.getTransformMatrix(),c.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?c.setVector3("lightDataSM",this._cachedDirection):c.setVector3("lightDataSM",this._cachedPosition);let u=this._getCamera();if(u&&c.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(u),this.getLight().getDepthMinZ(u)+this.getLight().getDepthMaxZ(u)),t&&this.enableSoftTransparentShadow&&c.setFloat("softTransparentShadowSM",a.visibility*l.alpha),i)e._setMainDrawWrapperOverride(h),i.standalone?i.baseMaterial.bindForSubMesh(a.getWorldMatrix(),s,e):l.bindForSubMesh(a.getWorldMatrix(),s,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(c.setTexture("diffuseSampler",this._opacityTexture),c.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){let e=s.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(s);if(!t)return;c.setTexture("boneSampler",t),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",e.getTransformMatrices(s))}MaterialHelper.BindMorphTargetParameters(s,c),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(c),bindClipPlane(c,l,n)}this._useUBO||i||this._bindCustomEffectForRenderSubMeshForShadowMap(e,c,a),MaterialHelper.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();let p=a.getWorldMatrix();_&&(a.getMeshUniformBuffer().bindToEffect(c,"Mesh"),a.transferToEffect(p)),this.forceBackFacesOnly&&o.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(s),this.onBeforeShadowMapRenderObservable.notifyObservers(c),s._processRendering(a,e,c,l.fillMode,d,_,(e,t)=>{a===s||e?(a.getMeshUniformBuffer().bindToEffect(c,"Mesh"),a.transferToEffect(e?t:p)):(s.getMeshUniformBuffer().bindToEffect(c,"Mesh"),s.transferToEffect(t))}),this.forceBackFacesOnly&&o.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(c),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}_applyFilterValues(){this._shadowMap&&(this.filter===shadowGenerator_ShadowGenerator.FILTER_NONE||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS?this._shadowMap.updateSamplingMode(texture_Texture.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i=Object.assign({useInstances:!1},t),r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let a=[];for(let e of s)a.push(...e.subMeshes);if(0===a.length){e&&e(this);return}let n=0,checkReady=()=>{var t,r;if(this._scene&&this._scene.getEngine()){for(;this.isReady(a[n],i.useInstances,null!==(r=null===(t=a[n].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(a[n].getMesh()))&&void 0!==r&&r);)if(++n>=a.length){e&&e(this);return}setTimeout(checkReady,16)}};checkReady()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var r;let s=e.getMaterial(),a=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;let n=[];if(this._prepareShadowDefines(e,t,n,i),a){if(!a.isReadyForSubMesh(e,n,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let i=e._getDrawWrapper(void 0,!0),a=i.effect,o=i.defines,l=[buffer_VertexBuffer.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(buffer_VertexBuffer.NormalKind)&&(l.push(buffer_VertexBuffer.NormalKind),n.push("#define NORMAL"),h.nonUniformScaling&&n.push("#define NONUNIFORMSCALING"));let c=s.needAlphaTesting();if((c||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let e=null!==(r=s.alphaCutOff)&&void 0!==r?r:shadowGenerator_ShadowGenerator.DEFAULT_ALPHA_CUTOFF;n.push("#define ALPHATEXTURE"),c&&n.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(l.push(buffer_VertexBuffer.UVKind),n.push("#define UV1")),h.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(buffer_VertexBuffer.UV2Kind),n.push("#define UV2"))}let u=new EffectFallbacks;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(buffer_VertexBuffer.MatricesIndicesKind),l.push(buffer_VertexBuffer.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(buffer_VertexBuffer.MatricesIndicesExtraKind),l.push(buffer_VertexBuffer.MatricesWeightsExtraKind));let e=h.skeleton;n.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&u.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?n.push("#define BONETEXTURE"):n.push("#define BonesPerMesh "+(e.bones.length+1))}else n.push("#define NUM_BONE_INFLUENCERS 0");let d=h.morphTargetManager,_=0;if(d&&d.numInfluencers>0&&(n.push("#define MORPHTARGETS"),_=d.numInfluencers,n.push("#define NUM_MORPH_INFLUENCERS "+_),d.isUsingTextureForTargets&&n.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(l,h,_)),prepareStringDefinesForClipPlanes(s,this._scene,n),t&&(n.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let e of this.customShaderOptions.defines)-1===n.indexOf(e)&&n.push(e);let p=n.join("\n");if(o!==p){o=p;let e="shadowMap",t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],r=["diffuseSampler","boneSampler","morphTargets"];if(addClipPlaneUniforms(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(let e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(let e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}let s=this._scene.getEngine();a=s.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:["Scene","Mesh"],samplers:r,defines:p,fallbacks:u,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:_}},s),i.setEffect(a,o)}if(!a.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),(!this._kernelBlurXPostprocess||!!this._kernelBlurXPostprocess.isReady())&&(!this._kernelBlurYPostprocess||!!this._kernelBlurYPostprocess.isReady())&&(!this._boxBlurPostprocess||!!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){let i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let a=this.getShadowMap();a&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a.getSize().width,1/a.getSize().width,this.frustumEdgeFalloff,e)):this._filter===shadowGenerator_ShadowGenerator.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/a.getSize().width,this._contactHardeningLightSizeUVRatio*a.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/a.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e))}getTransformMatrix(){let e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),math_vector_Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(math_vector_Vector3.Dot(this._lightDirection,math_vector_Vector3.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),math_vector_Matrix.LookAtLHToRef(t,t.add(this._lightDirection),math_vector_Vector3.Up(),this._viewMatrix);let e=this.getShadowMap();if(e){let t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t)for(let e of(this._shadowMap.renderList||(this._shadowMap.renderList=[]),t))this._shadowMap.renderList.push(e);else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){let[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var e;let t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=null===(e=this._camera)||void 0===e?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let e=0;e{throw _WarnImport("ShadowGeneratorSceneComponent")};let aV=`#ifdef ALPHATEST -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include -varying float vDepthMetric; -#ifdef PACKED -#include -#endif -#ifdef STORE_CAMERASPACE_Z -varying vec4 vViewPos; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#ifdef STORE_CAMERASPACE_Z -#ifdef PACKED -gl_FragColor=pack(vViewPos.z); -#else -gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); -#endif -#else -#ifdef NONLINEARDEPTH -#ifdef PACKED -gl_FragColor=pack(gl_FragCoord.z); -#else -gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); -#endif -#else -#ifdef PACKED -gl_FragColor=pack(vDepthMetric); -#else -gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); -#endif -#endif -#endif -}`;ShaderStore.ShadersStore.depthPixelShader=aV;let aU=`attribute vec3 position; -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -uniform mat4 viewProjection;uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#ifdef STORE_CAMERASPACE_Z -uniform mat4 view;varying vec4 vViewPos; -#endif -varying float vDepthMetric; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#include -gl_Position=viewProjection*worldPos; -#ifdef STORE_CAMERASPACE_Z -vViewPos=view*worldPos; -#else -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); -#else -vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); -#endif -#endif -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`;ShaderStore.ShadersStore.depthVertexShader=aU;let DepthRenderer=class DepthRenderer{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=texture_Texture.TRILINEAR_SAMPLINGMODE,a=!1,n){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=a,this.isPacked=0===t,this.isPacked?this.clearColor=new math_color_Color4(1,1,1,1):this.clearColor=new math_color_Color4(a?1e8:1,0,0,1),DepthRenderer._SceneComponentInitialization(this._scene);let o=e.getEngine();this._camera=i,s===texture_Texture.NEAREST_SAMPLINGMODE||(1!==t||o._caps.textureFloatLinearFiltering||(s=texture_Texture.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(s=texture_Texture.NEAREST_SAMPLINGMODE));let l=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new renderTargetTexture_RenderTargetTexture(null!=n?n:"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(e=>{e.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{var e;null===(e=o._debugPushGroup)||void 0===e||e.call(o,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)}),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{var t,i;let r=e.getRenderingMesh(),s=e.getEffectiveMesh(),a=this._scene,n=a.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||s.infiniteDistance||o.disableDepthWrite||0===e.verticesCount||e._renderId===a.getRenderId())return;let l=0>s._getWorldMatrixDeterminant(),h=null!==(t=r.overrideMaterialSideOrientation)&&void 0!==t?t:o.sideOrientation;l&&(h=0===h?1:0);let c=0===h;n.setState(o.backFaceCulling,0,!1,c,this.reverseCulling?!o.cullBackFaces:o.cullBackFaces);let u=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(u.mustReturn)return;let d=n.getCaps().instancedArrays&&(null!==u.visibleInstances[e._id]&&void 0!==u.visibleInstances[e._id]||r.hasThinInstances),_=this._camera||a.activeCamera;if(this.isReady(e,d)&&_){let t,l;e._renderId=a.getRenderId();let h=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[n.currentRenderPassId],c=e._getDrawWrapper();!c&&h&&(c=h._getDrawWrapper());let p=_.mode===camera_Camera.ORTHOGRAPHIC_CAMERA;if(!c)return;let f=c.effect;if(n.enableEffect(c),d||r._bind(e,f,o.fillMode),h?h.bindForSubMesh(s.getWorldMatrix(),s,e):(f.setMatrix("viewProjection",a.getTransformMatrix()),f.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&f.setMatrix("view",a.getViewMatrix())),p?(t=!n.useReverseDepthBuffer&&n.isNDCHalfZRange?0:1,l=n.useReverseDepthBuffer&&n.isNDCHalfZRange?0:1):(t=n.useReverseDepthBuffer&&n.isNDCHalfZRange?_.minZ:n.isNDCHalfZRange?0:_.minZ,l=n.useReverseDepthBuffer&&n.isNDCHalfZRange?0:_.maxZ),f.setFloat2("depthValues",t,t+l),!h){if(o.needAlphaTesting()){let e=o.getAlphaTestTexture();e&&(f.setTexture("diffuseSampler",e),f.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){let e=r.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(r);if(!t)return;f.setTexture("boneSampler",t),f.setFloat("boneTextureWidth",4*(e.bones.length+1))}else f.setMatrices("mBones",e.getTransformMatrices(r))}bindClipPlane(f,o,a),MaterialHelper.BindMorphTargetParameters(r,f),r.morphTargetManager&&r.morphTargetManager.isUsingTextureForTargets&&r.morphTargetManager._bind(f)}r._processRendering(s,e,f,o.fillMode,u,d,(e,t)=>f.setMatrix("world",t))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s4&&(h.push(buffer_VertexBuffer.MatricesIndicesExtraKind),h.push(buffer_VertexBuffer.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));let t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");let c=s.morphTargetManager,u=0;c&&c.numInfluencers>0&&(u=c.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+u),c.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(h,s,u)),t&&(l.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),prepareStringDefinesForClipPlanes(o,a,l);let d=e._getDrawWrapper(void 0,!0),_=d.defines,p=l.join("\n");if(_!==p){let e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];addClipPlaneUniforms(e),d.setEffect(r.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],p,void 0,void 0,void 0,{maxSimultaneousMorphTargets:u}),p)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer){let i=this._scene._depthRenderer[t];i===this&&e.push(t)}if(e.length>0)for(let t of(this._depthMap.dispose(),e))delete this._scene._depthRenderer[t]}};DepthRenderer._SceneComponentInitialization=e=>{throw _WarnImport("DepthRendererSceneComponent")};let ak=`varying vec2 vUV;uniform sampler2D textureSampler; -#if defined(INITIAL) -uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); -#ifdef DEPTH_REDUX -float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); -#else -float maxz=max(max(max(f1,f2),f3),f4); -#endif -glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(MAIN) -uniform vec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(ONEBEFORELAST) -uniform ivec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(LAST) -void main(void) -{glFragColor=vec4(0.);if (true) { -discard;}} -#endif -`;ShaderStore.ShadersStore.minmaxReduxPixelShader=ak;let MinMaxReducer=class MinMaxReducer{constructor(e){this.onAfterReductionPerformed=new observable_Observable,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new PostProcessManager(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){var s,a,n,o;if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;let l=this._camera.getScene(),h=new postProcess_PostProcess("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,l.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);h.autoClear=!1,h.forceFullscreenViewport=r;let c=this._sourceTexture.getRenderWidth(),u=this._sourceTexture.getRenderHeight();h.onApply=(s=c,a=u,e=>{e.setTexture("sourceTexture",this._sourceTexture),e.setFloat2("texSize",s,a)}),this._reductionSteps.push(h);let d=1;for(;c>1||u>1;){c=Math.max(Math.round(c/2),1),u=Math.max(Math.round(u/2),1);let e=new postProcess_PostProcess("Reduction phase "+d,"minmaxRedux",["texSize"],null,{width:c,height:u},null,1,l.getEngine(),!1,"#define "+(1==c&&1==u?"LAST":1==c||1==u?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=(n=c,o=u,e=>{1==n||1==o?e.setInt2("texSize",n,o):e.setFloat2("texSize",n,o)}),this._reductionSteps.push(e),d++,1==c&&1==u){let func=(e,t,i)=>{let r=new Float32Array(4*e*t),s={min:0,max:0};return()=>{l.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),s.min=r[0],s.max=r[1],this.onAfterReductionPerformed.notifyObservers(s)}};e.onAfterRenderObservable.add(func(c,u,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var e,t;let i=this._camera.getScene().getEngine();null===(e=i._debugPushGroup)||void 0===e||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),null===(t=i._debugPopGroup)||void 0===t||t.call(i,1)}),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return CascadedShadowGenerator.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),(t!=this._minDistance||i!=this._maxDistance)&&this.setMinMaxDistance(t,i)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return null!==(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)&&void 0!==i?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(null===(t=this._depthReducer)||void 0===t?void 0:t.depthRenderer)&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,a=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,n=t+s*r,o=t+a*r,l=o-n,h=o/n;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==shadowGenerator_ShadowGenerator.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let a=this.getShadowMap();if(!a)return;let n=a.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,a),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===shadowGenerator_ShadowGenerator.FILTER_PCSS){for(let e=0;enew CascadedShadowGenerator(e,t,void 0,i));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}};CascadedShadowGenerator._FrustumCornersNDCSpace=[new math_vector_Vector3(-1,1,-1),new math_vector_Vector3(1,1,-1),new math_vector_Vector3(1,-1,-1),new math_vector_Vector3(-1,-1,-1),new math_vector_Vector3(-1,1,1),new math_vector_Vector3(1,1,1),new math_vector_Vector3(1,-1,1),new math_vector_Vector3(-1,-1,1)],CascadedShadowGenerator.CLASSNAME="CascadedShadowGenerator",CascadedShadowGenerator.DEFAULT_CASCADES_COUNT=4,CascadedShadowGenerator.MIN_CASCADES_COUNT=2,CascadedShadowGenerator.MAX_CASCADES_COUNT=4,CascadedShadowGenerator._SceneComponentInitialization=e=>{throw _WarnImport("ShadowGeneratorSceneComponent")},AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR,(e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_SHADOWGENERATOR);t||(t=new ShadowGeneratorSceneComponent(e),e._addComponent(t))},node_Node.AddNodeConstructor("Light_Type_0",(e,t)=>()=>new PointLight(e,math_vector_Vector3.Zero(),t));let PointLight=class PointLight extends ShadowLight{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.recreateShadowMap()}}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return light_Light.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new math_vector_Vector3(1,0,0);case 1:return new math_vector_Vector3(-1,0,0);case 2:return new math_vector_Vector3(0,-1,0);case 3:return new math_vector_Vector3(0,1,0);case 4:return new math_vector_Vector3(0,0,1);case 5:return new math_vector_Vector3(0,0,-1)}return math_vector_Vector3.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;let s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,n=this.getScene().getEngine().useReverseDepthBuffer;math_vector_Matrix.PerspectiveFovLHToRef(this.shadowAngle,1,n?a:s,n?s:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,n)}_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}};__decorate([serialize()],PointLight.prototype,"shadowAngle",null);let DefaultLoadingScreen=class DefaultLoadingScreen{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{let e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";let e=`@-webkit-keyframes spin1 {\ - 0% { -webkit-transform: rotate(0deg);} - 100% { -webkit-transform: rotate(360deg);} - }\ - @keyframes spin1 {\ - 0% { transform: rotate(0deg);} - 100% { transform: rotate(360deg);} - }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);let t=!!window.SVGSVGElement,i=new Image;DefaultLoadingScreen.DefaultLogoUrl?i.src=DefaultLoadingScreen.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";let r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";let s=new Image;if(DefaultLoadingScreen.DefaultSpinnerUrl?s.src=DefaultLoadingScreen.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!t){let e={w:16,h:18.5},t={w:30,h:30};i.style.width=`${e.w}vh`,i.style.height=`${e.h}vh`,i.style.left=`calc(50% - ${e.w/2}vh)`,i.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${t.w}vh`,s.style.height=`${t.h}vh`,s.style.left=`calc(50% - ${t.w/2}vh)`,s.style.top=`calc(50% - ${t.h/2}vh)`}r.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}};DefaultLoadingScreen.DefaultLogoUrl="",DefaultLoadingScreen.DefaultSpinnerUrl="",engine_Engine.DefaultLoadingScreenFactory=e=>new DefaultLoadingScreen(e);let PanoramaToCubeMapTools=class PanoramaToCubeMapTools{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";let a=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),n=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),o=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s),l=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),h=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),c=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s);return{front:a,back:n,left:o,right:l,up:h,down:c,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,a=!1){let n=new ArrayBuffer(e*e*12),o=new Float32Array(n),l=a?Math.max(1,Math.round(r/4/e)):1,h=1/l,c=h*h,u=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),_=1/e,p=0;for(let a=0;aMath.PI;)s-=2*Math.PI;let n=s/Math.PI,o=Math.round((n=.5*n+.5)*i);o<0?o=0:o>=i&&(o=i-1);let l=Math.round(a/Math.PI*r);l<0?l=0:l>=r&&(l=r-1);let h=r-l-1,c=t[h*i*3+3*o+0],u=t[h*i*3+3*o+1],d=t[h*i*3+3*o+2];return{r:c,g:u,b:d}}};PanoramaToCubeMapTools.FACE_LEFT=[new math_vector_Vector3(-1,-1,-1),new math_vector_Vector3(1,-1,-1),new math_vector_Vector3(-1,1,-1),new math_vector_Vector3(1,1,-1)],PanoramaToCubeMapTools.FACE_RIGHT=[new math_vector_Vector3(1,-1,1),new math_vector_Vector3(-1,-1,1),new math_vector_Vector3(1,1,1),new math_vector_Vector3(-1,1,1)],PanoramaToCubeMapTools.FACE_FRONT=[new math_vector_Vector3(1,-1,-1),new math_vector_Vector3(1,-1,1),new math_vector_Vector3(1,1,-1),new math_vector_Vector3(1,1,1)],PanoramaToCubeMapTools.FACE_BACK=[new math_vector_Vector3(-1,-1,1),new math_vector_Vector3(-1,-1,-1),new math_vector_Vector3(-1,1,1),new math_vector_Vector3(-1,1,-1)],PanoramaToCubeMapTools.FACE_DOWN=[new math_vector_Vector3(1,1,-1),new math_vector_Vector3(1,1,1),new math_vector_Vector3(-1,1,-1),new math_vector_Vector3(-1,1,1)],PanoramaToCubeMapTools.FACE_UP=[new math_vector_Vector3(-1,-1,-1),new math_vector_Vector3(-1,-1,1),new math_vector_Vector3(1,-1,-1),new math_vector_Vector3(1,-1,1)];let HDRTools=class HDRTools{static _Ldexp(e,t){return t>1023?898846567431158e293*e*Math.pow(2,t-1023):t<-1074?5e-324*e*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,r,s,a){s>0?(s=this._Ldexp(1,s-136),e[a+0]=t*s,e[a+1]=i*s,e[a+2]=r*s):(e[a+0]=0,e[a+1]=0,e[a+2]=0)}static _ReadStringLine(e,t){let i="",r="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:n+=r.length+1}}static GetCubeMapTextureData(e,t,i=!1){let r=new Uint8Array(e),s=this.RGBE_ReadHeader(r),a=this.RGBE_ReadPixels(r,s),n=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(a,s.width,s.height,t,i);return n}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i,r,s,a,n,o=t.height,l=t.width,h=t.dataPosition,c=0,u=0,d=0,_=new ArrayBuffer(4*l),p=new Uint8Array(_),f=new ArrayBuffer(t.width*t.height*12),m=new Float32Array(f);for(;o>0;){if(i=e[h++],r=e[h++],s=e[h++],a=e[h++],2!=i||2!=r||128&s||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((s<<8|a)!=l)throw"HDR Bad header format, wrong scan line width";for(d=0,c=0;d<4;d++)for(u=(d+1)*l;c128){if(0==(n=i-128)||n>u-c)throw"HDR Bad Format, bad scanline data (run)";for(;n-- >0;)p[c++]=r}else{if(0==(n=i)||n>u-c)throw"HDR Bad Format, bad scanline data (non-run)";if(p[c++]=r,--n>0)for(let t=0;t0;){for(n=0;n -#include -#include -#include -uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;ShaderStore.ShadersStore.hdrFilteringPixelShader=aj;let HDRFiltering=class HDRFiltering{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);let i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){let t=e.getSize().width,i=math_scalar_Scalar.ILog2(t)+1,r=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();let a=e.getInternalTexture();a&&this._engine.updateTextureSamplingMode(3,a,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let n=[[new math_vector_Vector3(0,0,-1),new math_vector_Vector3(0,-1,0),new math_vector_Vector3(1,0,0)],[new math_vector_Vector3(0,0,1),new math_vector_Vector3(0,-1,0),new math_vector_Vector3(-1,0,0)],[new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,1),new math_vector_Vector3(0,1,0)],[new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,0,-1),new math_vector_Vector3(0,-1,0)],[new math_vector_Vector3(1,0,0),new math_vector_Vector3(0,-1,0),new math_vector_Vector3(0,0,1)],[new math_vector_Vector3(-1,0,0),new math_vector_Vector3(0,-1,0),new math_vector_Vector3(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",n[e][0]),r.setVector3("right",n[e][1]),r.setVector3("front",n[e][2]);for(let a=0;a{this._effectRenderer=new EffectRenderer(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(logger_Logger.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}};let hdrCubeTexture_HDRCubeTexture=class hdrCubeTexture_HDRCubeTexture extends baseTexture_BaseTexture{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(math_vector_Matrix.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,a=!1,n=!1,o=null,l=null,h=!1){var c;if(super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=math_vector_Vector3.Zero(),this.onLoadObservable=new observable_Observable,!e)return;this._coordinatesMode=texture_Texture.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=math_vector_Matrix.Identity(),this._prefilterOnLoad=n,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),o&&o()},this._onError=l,this.gammaSpace=a,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?tools_Tools.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(null===(c=this.getScene())||void 0===c?void 0:c.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture()}getClassName(){return"HDRCubeTexture"}_loadTexture(){let e=this._getEngine(),t=e.getCaps(),i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){let t=this._onLoad,i=new HDRFiltering(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;let t=HDRTools.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){let e=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}let r=[],s=null,a=null;for(let e=0;e<6;e++){2===i?a=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));let o=t[hdrCubeTexture_HDRCubeTexture._FacesMapping[e]];if(this.gammaSpace||a||s){for(let e=0;e255){let e=255/a;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}}a?r.push(a):s?r.push(s):r.push(o)}return r},null,this._onLoad,this._onError)}clone(){let e=new hdrCubeTexture_HDRCubeTexture(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let r=null;return e.name&&!e.isRenderTarget&&((r=new hdrCubeTexture_HDRCubeTexture(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=math_vector_Vector3.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=math_vector_Vector3.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}};hdrCubeTexture_HDRCubeTexture._FacesMapping=["right","left","up","down","front","back"],h["BABYLON.HDRCubeTexture"]=hdrCubeTexture_HDRCubeTexture;let MorphTarget=class MorphTarget{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let 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,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new observable_Observable,this._onDataLayoutChanged=new observable_Observable,this._animationPropertiesOverride=null,this._scene=i||engineStore_EngineStore.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){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){let e=decorators_SerializationHelper.Clone(()=>new MorphTarget(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(){let 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())),decorators_SerializationHelper.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){let i=new MorphTarget(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=[],this._targetInfluenceChangedObservers=[],this._targetDataLayoutChangedObservers=[],this._activeTargets=new SmartArray(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=[],this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,e||(e=engineStore_EngineStore.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}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(){var e;return morphTargetManager_MorphTargetManager.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(null===(e=this._scene)||void 0===e?void 0:e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}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){let 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)}clone(){let e=new morphTargetManager_MorphTargetManager(this._scene);for(let t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){let e={};for(let t of(e.id=this.uniqueId,e.targets=[],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 i=-1;for(let e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;let r=e.getPositions();if(r){let e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e){logger_Logger.Error("Incompatible target. Targets must all have the same vertices count.");return}}}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;ee&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){let 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();let e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4),i=0;for(let r=0;r-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new morphTargetManager_MorphTargetManager(t);for(let r of(i._uniqueId=e.id,e.targets))i.addTarget(MorphTarget.Parse(r,t));return i}};morphTargetManager_MorphTargetManager.EnableTextureStorage=!0,morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode=8;let PhysicsRaycastResult=class PhysicsRaycastResult{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=math_vector_Vector3.Zero(),this._hitPointWorld=math_vector_Vector3.Zero(),this._rayFromWorld=math_vector_Vector3.Zero(),this._rayToWorld=math_vector_Vector3.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=null!=i?i:-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=math_vector_Vector3.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=math_vector_Vector3.Zero(),t=math_vector_Vector3.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0}};let PhysicsEngine=class PhysicsEngine{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw _WarnImport("CannonJSPlugin")}constructor(e,t=PhysicsEngine.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new math_vector_Vector3(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach(function(e){e.dispose()}),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){let t=this._impostors.indexOf(e);if(t>-1){let i=this._impostors.splice(t,1);i.length&&this.getPhysicsPlugin().removePhysicsBody(e)}}addJoint(e,t,i){let r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){let r=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach(e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)}),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e);if(!t){logger_Logger.Warn("It was not possible to create a physics body for this object.");return}let i=e.physicsBody;i&&this.removePhysicsBody(e);let r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},a=e.getParam("nativeOptions");for(let e in a)Object.prototype.hasOwnProperty.call(a,e)&&(s[e]=a[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(t){let r=i[t];e.physicsBody[t].set(r.x,r.y,r.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){let processMesh=t=>{if(!t.rotationQuaternion)return;let i=t.getPhysicsImpostor();if(i){let r=i.parent;if(r!==e&&t.parent){let r=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);i.physicsBody&&(this.removePhysicsBody(i),i.physicsBody=null),i.parent=e,i.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(i),new this.BJSCANNON.Vec3(r.x,r.y,r.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=i.getParam("mass")}}t.getChildMeshes(!0).filter(e=>!!e.physicsImpostor).forEach(processMesh)};t.filter(e=>!!e.physicsImpostor).forEach(processMesh)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,a={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case PhysicsJoint.HingeJoint:case PhysicsJoint.Hinge2Joint:t=new this.BJSCANNON.HingeConstraint(i,r,a);break;case PhysicsJoint.DistanceJoint:t=new this.BJSCANNON.DistanceConstraint(i,r,s.maxDistance||2);break;case PhysicsJoint.SpringJoint:t=new this.BJSCANNON.Spring(i,r,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:a.pivotA,localAnchorB:a.pivotB});break;case PhysicsJoint.LockJoint:t=new this.BJSCANNON.LockConstraint(i,r,a);break;case PhysicsJoint.PointToPointJoint:case PhysicsJoint.BallAndSocketJoint:default:t=new this.BJSCANNON.PointToPointConstraint(i,a.pivotA,r,a.pivotB,a.maxForce)}t.collideConnected=!!s.collision,e.joint.physicsJoint=t,e.joint.type!==PhysicsJoint.SpringJoint?this.world.addConstraint(t):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){t.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==PhysicsJoint.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r1e3*i));e++);this.time+=r;let o=this.time%i,l=o/i,h=this.bodies;for(let i=0;i!==h.length;i++){let r=h[i];r.type!==t.Body.STATIC&&r.sleepState!==t.Body.SLEEPING?(r.position.vsub(r.previousPosition,e),e.scale(l,e),r.position.vadd(e,r.interpolatedPosition)):(r.interpolatedPosition.set(r.position.x,r.position.y,r.position.z),r.interpolatedQuaternion.set(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}};PhysicsEngine.DefaultPluginFactory=()=>new CannonJSPlugin;let OimoJSPlugin=class OimoJSPlugin{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=math_vector_Vector3.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new PhysicsRaycastResult}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach(function(e){e.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e});let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}let e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];if(!e||!t){i=i.next;continue}e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){let r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){logger_Logger.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){var t;let i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach(function(e){e.physicsImpostor&&r.push(e.physicsImpostor)});let checkWithEpsilon=e=>Math.max(e,.001),s=new math_vector_Quaternion;r.forEach(t=>{if(!t.object.rotationQuaternion)return;let r=t.object.rotationQuaternion;s.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);let a=s.toEulerAngles(),n=t.getObjectExtents();if(t===e){let t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{let e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(57.29577951308232*a.x,57.29577951308232*a.y,57.29577951308232*a.z)}switch(t.object.rotationQuaternion.copyFrom(s),t.type){case physicsImpostor_PhysicsImpostor.ParticleImpostor:logger_Logger.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case physicsImpostor_PhysicsImpostor.SphereImpostor:{let e=n.x,t=n.y,r=n.z,s=Math.max(checkWithEpsilon(e),checkWithEpsilon(t),checkWithEpsilon(r))/2;i.type.push("sphere"),i.size.push(s),i.size.push(s),i.size.push(s);break}case physicsImpostor_PhysicsImpostor.CylinderImpostor:{let e=checkWithEpsilon(n.x)/2,t=checkWithEpsilon(n.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case physicsImpostor_PhysicsImpostor.PlaneImpostor:case physicsImpostor_PhysicsImpostor.BoxImpostor:default:{let e=checkWithEpsilon(n.x),t=checkWithEpsilon(n.y),r=checkWithEpsilon(n.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r)}}t.object.rotationQuaternion=r}),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(s),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,a=s.nativeParams||{},n={body1:i,body2:r,axe1:a.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:a.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:a.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:a.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:a.min,max:a.max,collision:a.collision||s.collision,spring:a.spring,world:this.world};switch(e.joint.type){case PhysicsJoint.BallAndSocketJoint:t="jointBall";break;case PhysicsJoint.SpringJoint:logger_Logger.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"),n.min=s.length||n.min,n.max=Math.max(n.min,n.max);case PhysicsJoint.DistanceJoint:t="jointDistance",n.max=s.maxDistance;break;case PhysicsJoint.PrismaticJoint:t="jointPrisme";break;case PhysicsJoint.SliderJoint:t="jointSlide";break;case PhysicsJoint.WheelJoint:t="jointWheel";break;case PhysicsJoint.HingeJoint:default:t="jointHinge"}n.type=t,e.joint.physicsJoint=this.world.add(n)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){logger_Logger.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{let t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){let t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.linearVelocity;return t?new math_vector_Vector3(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new math_vector_Vector3(t.x,t.y,t.z):null}setBodyMass(e,t){let i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?logger_Logger.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){let i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){let i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return logger_Logger.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){logger_Logger.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}};let AmmoJSPlugin=class AmmoJSPlugin{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new math_vector_Quaternion,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new math_vector_Vector3,this._tmpContactNormal=new math_vector_Vector3,this._tmpVec3=new math_vector_Vector3,this._tmpMatrix=new math_vector_Matrix,"function"==typeof t){logger_Logger.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}if(this.bjsAMMO=t,!this.isSupported()){logger_Logger.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint);let t=e.getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new PhysicsRaycastResult,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(i))for(let e of i._onPhysicsCollideCallbacks)for(let t of e.otherImpostors)(i.physicsBody.isActive()||t.physicsBody.isActive())&&this._isImpostorPairInContact(i,t)&&(i.onCollide({body:t.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),t.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===physicsImpostor_PhysicsImpostor.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){let t,i,r,s;let a=e.physicsBody.get_m_nodes(),n=a.size(),o=[];for(let e=0;e{this.bjsAMMO.destroy(e)}),e._pluginData.toDispose=[]))}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData;switch(s.mainPivot||(s.mainPivot=new math_vector_Vector3(0,0,0)),s.connectedPivot||(s.connectedPivot=new math_vector_Vector3(0,0,0)),e.joint.type){case PhysicsJoint.DistanceJoint:{let e=s.maxDistance;e&&(s.mainPivot=new math_vector_Vector3(0,-e/2,0),s.connectedPivot=new math_vector_Vector3(0,e/2,0)),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case PhysicsJoint.HingeJoint:{s.mainAxis||(s.mainAxis=new math_vector_Vector3(0,0,0)),s.connectedAxis||(s.connectedAxis=new math_vector_Vector3(0,0,0));let e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),a=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);t=new this.bjsAMMO.btHingeConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,a);break}case PhysicsJoint.BallAndSocketJoint:t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:logger_Logger.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(t,!e.joint.jointData.collision),e.joint.physicsJoint=t}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s,a=i.getIndices();a||(a=[]);let n=i.getVerticesData(buffer_VertexBuffer.PositionKind);if(n||(n=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?math_vector_Quaternion.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):math_vector_Quaternion.Identity();let r=math_vector_Matrix.Compose(math_vector_Vector3.One(),e,t.position);r.invertToRef(this._tmpMatrix);let a=i.computeWorldMatrix(!1);s=a.multiply(this._tmpMatrix)}else math_vector_Matrix.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),s=this._tmpMatrix;let o=a.length/3;for(let t=0;t{r+=this._addMeshVerts(e,t,i)})}return r}_softVertexData(e){let t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(buffer_VertexBuffer.PositionKind);i||(i=[]);let r=t.getVerticesData(buffer_VertexBuffer.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);let s=[],a=[];for(let e=0;ee*e),o=n.reduce((e,t)=>e+t);if(0===o)i=(t=s.length)/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;let r=e.getParam("path"),s=e.getParam("shape");if(null===s)return logger_Logger.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;i=(t=r.length)-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let l=e.getParam("fixedPoints");l=l>3?3:l;let h=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,l);return h.get_m_cfg().set_collisions(17),h}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let a=i.getVerticesData(buffer_VertexBuffer.PositionKind);a||(a=[]),i.computeWorldMatrix(!1);let n=s.length/3;for(let t=0;t{r+=this._addHullVerts(e,t,i)})}return r}_createShape(e,t=!1){let i;let r=e.object,s=e.getObjectExtents();if(!t){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];i=new this.bjsAMMO.btCompoundShape;let r=0;if(t.forEach(e=>{let t=e.getPhysicsImpostor();if(t){if(t.type==physicsImpostor_PhysicsImpostor.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";let s=this._createShape(t),a=e.parent.getWorldMatrix().clone(),n=new math_vector_Vector3;a.decompose(n),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*n.x,e.position.y*n.y,e.position.z*n.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,s),t.dispose(),r++}}),r>0){if(e.type!=physicsImpostor_PhysicsImpostor.NoImpostor){let t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,t))}return i}this.bjsAMMO.destroy(i),i=null}switch(e.type){case physicsImpostor_PhysicsImpostor.SphereImpostor:if(math_scalar_Scalar.WithinEpsilon(s.x,s.y,1e-4)&&math_scalar_Scalar.WithinEpsilon(s.x,s.z,1e-4))i=new this.bjsAMMO.btSphereShape(s.x/2);else{let e=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(e,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case physicsImpostor_PhysicsImpostor.CapsuleImpostor:{let e=s.x/2;i=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case physicsImpostor_PhysicsImpostor.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case physicsImpostor_PhysicsImpostor.PlaneImpostor:case physicsImpostor_PhysicsImpostor.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case physicsImpostor_PhysicsImpostor.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)i=this.onCreateCustomMeshImpostor(e);else{let t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);let s=this._addMeshVerts(t,r,r);i=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case physicsImpostor_PhysicsImpostor.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)i=this.onCreateCustomConvexHullImpostor(e);else{let t=new this.bjsAMMO.btConvexHullShape,s=this._addHullVerts(t,r,r);0==s?(e._pluginData.toDispose.push(t),i=new this.bjsAMMO.btCompoundShape):i=t}break;case physicsImpostor_PhysicsImpostor.NoImpostor:i=new this.bjsAMMO.btSphereShape(s.x/2);break;case physicsImpostor_PhysicsImpostor.CustomImpostor:i=this._createCustom(e);break;case physicsImpostor_PhysicsImpostor.SoftbodyImpostor:i=this._createSoftbody(e);break;case physicsImpostor_PhysicsImpostor.ClothImpostor:i=this._createCloth(e);break;case physicsImpostor_PhysicsImpostor.RopeImpostor:i=this._createRope(e);break;default:logger_Logger.Warn("The impostor type is not currently supported by the ammo plugin.")}return i}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>.001||Math.abs(r.getOrigin().y()-t.y)>.001||Math.abs(r.getOrigin().z()-t.z)>.001||Math.abs(r.getRotation().x()-i.x)>.001||Math.abs(r.getRotation().y()-i.y)>.001||Math.abs(r.getRotation().z()-i.z)>.001||Math.abs(r.getRotation().w()-i.w)>.001){if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){let t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(!(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity()))return null;let i=new math_vector_Vector3(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(!(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity()))return null;let i=new math_vector_Vector3(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(logger_Logger.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===physicsImpostor_PhysicsImpostor.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):logger_Logger.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(logger_Logger.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):logger_Logger.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(logger_Logger.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):logger_Logger.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(logger_Logger.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):logger_Logger.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,a=!1){let n=e.segments;e.physicsBody.appendAnchor(Math.round((n-1)*i)+n*(n-1-Math.round((n-1)*r)),t.physicsBody,a,s)}appendHook(e,t,i,r=1,s=!1){let a=Math.round(e.segments*i);e.physicsBody.appendAnchor(a,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){logger_Logger.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){logger_Logger.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){let i=t.physicsBody;i.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){let t=e.getObjectExtents();return t.x/2}getBoxSizeToRef(e,t){let i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);let r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}};AmmoJSPlugin._DISABLE_COLLISION_FLAG=4,AmmoJSPlugin._KINEMATIC_FLAG=2,AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG=4,AbstractScene.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return -1;let t=this.reflectionProbes.indexOf(e);return -1!==t&&this.reflectionProbes.splice(t,1),t},AbstractScene.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};let reflectionProbe_ReflectionProbe=class reflectionProbe_ReflectionProbe{constructor(e,t,i,r=!0,s=!1,a=!1){let n;if(this.name=e,this._viewMatrix=math_vector_Matrix.Identity(),this._target=math_vector_Vector3.Zero(),this._add=math_vector_Vector3.Zero(),this._invertYAxis=!1,this.position=math_vector_Vector3.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){let e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new renderTargetTexture_RenderTargetTexture(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!a,this._renderTargetTexture.invertZ=i.useRightHandedSystem;let l=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);let t=i.useRightHandedSystem?math_vector_Matrix.LookAtRHToRef:math_vector_Matrix.LookAtLHToRef,r=i.useRightHandedSystem?math_vector_Matrix.PerspectiveFovRH:math_vector_Matrix.PerspectiveFovLH;t(this.position,this._target,math_vector_Vector3.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position}),this._renderTargetTexture.onBeforeBindObservable.add(()=>{var t,r;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(r=(t=i.getEngine())._debugPushGroup)||void 0===r||r.call(t,`reflection probe generation for ${e}`,1),n=this._scene.imageProcessingConfiguration.applyByPostProcess,a&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=n,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),null===(t=(e=i.getEngine())._debugPopGroup)||void 0===t||t.call(e,1)})}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){let e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){let e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){let e=decorators_SerializationHelper.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;ir||new reflectionProbe_ReflectionProbe(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i)).cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}};__decorate([serializeAsMeshReference()],reflectionProbe_ReflectionProbe.prototype,"_attachedMesh",void 0),__decorate([serializeAsVector3()],reflectionProbe_ReflectionProbe.prototype,"position",void 0);let BabylonFileLoaderConfiguration=class BabylonFileLoaderConfiguration{};BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine=void 0;let aK={},aq={},parseMaterialByPredicate=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,a=t.materials.length;s{for(let r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},logOperation=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),loadDetailLevels=(e,t)=>{if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){let i=t._waitingData.lods.ids,r=t.isEnabled(!1);if(t._waitingData.lods.distances){let s=t._waitingData.lods.distances;if(s.length>=i.length){let a=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let r=0;r0&&t.addLODLevel(a,null),!0===r&&t.setEnabled(!0)}else tools_Tools.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},findParent=(e,t,i)=>{if("number"!=typeof e){let r=i.getLastEntryById(e);if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r}let r=aK[e];if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r},findMaterial=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):aq[e],loadAssetContainer=(e,t,i,r,s=!1)=>{let a=new AssetContainer(e),n="importScene has failed JSON parse";try{let r,s;var o=JSON.parse(t);n="";let l=sceneLoader_SceneLoader.loggingLevel===sceneLoader_SceneLoader.DETAILED_LOGGING;if(void 0!==o.environmentTexture&&null!==o.environmentTexture){let t=void 0===o.isPBR||o.isPBR;if(o.environmentTextureType&&"BABYLON.HDRCubeTexture"===o.environmentTextureType){let r=o.environmentTextureSize?o.environmentTextureSize:128,s=new hdrCubeTexture_HDRCubeTexture((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,r,!0,!t,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(s.rotationY=o.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof o.environmentTexture){let t=cubeTexture_CubeTexture.Parse(o.environmentTexture,e,i);e.environmentTexture=t}else if(o.environmentTexture.endsWith(".env")){let t=new cubeTexture_CubeTexture((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}else{let t=cubeTexture_CubeTexture.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}if(!0===o.createDefaultSkybox){let i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=o.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}a.environmentTexture=e.environmentTexture}if(void 0!==o.environmentIntensity&&null!==o.environmentIntensity&&(e.environmentIntensity=o.environmentIntensity),void 0!==o.lights&&null!==o.lights)for(r=0,s=o.lights.length;r{-1==a.textures.indexOf(e)&&(a.textures.push(e),e._parentContainer=a)})}}if(void 0!==o.multiMaterials&&null!==o.multiMaterials)for(r=0,s=o.multiMaterials.length;r{-1==a.textures.indexOf(e)&&(a.textures.push(e),e._parentContainer=a)})}if(void 0!==o.morphTargetManagers&&null!==o.morphTargetManagers)for(let t of o.morphTargetManagers){let i=morphTargetManager_MorphTargetManager.Parse(t,e);a.morphTargetManagers.push(i),i._parentContainer=a}if(void 0!==o.skeletons&&null!==o.skeletons)for(r=0,s=o.skeletons.length;r{e&&(a.geometries.push(e),e._parentContainer=a)})}if(void 0!==o.transformNodes&&null!==o.transformNodes)for(r=0,s=o.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach(i=>{t.subMaterials.push(findMaterial(i,e))}),t._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(t=>{null!==t._waitingMaterialId&&(t.material=findMaterial(t._waitingMaterialId,e),t._waitingMaterialId=null)}),r=0,s=e.skeletons.length;r{if(t._waitingTransformNodeId){let i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}}),t._hasWaitingData=null)}for(r=0,s=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""}),AbstractScene.Parse(o,e,a,i),r=0,s=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,a,n,o)=>{var l;let h="importMesh has failed JSON parse";try{var c=JSON.parse(i);h="";let o=sceneLoader_SceneLoader.loggingLevel===sceneLoader_SceneLoader.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;let u=[],d=new Map,_=[];if(void 0!==c.transformNodes&&null!==c.transformNodes)for(let e=0,i=c.transformNodes.length;e{!0!==e&&c.geometries[i]&&Array.isArray(c.geometries[i])&&c.geometries[i].forEach(s=>{s.id===l.geometryId&&("vertexData"===i&&Geometry.Parse(s,t,r),e=!0)})}),!1===e&&logger_Logger.Warn("Geometry not found for mesh "+l.id)}if(l.materialUniqueId||l.materialId){let e=l.materialUniqueId?f:p,i=-1!==e.indexOf(l.materialUniqueId||l.materialId);if(!1===i&&void 0!==c.multiMaterials&&null!==c.multiMaterials){let loadSubMaterial=(i,s)=>{e.push(i);let a=parseMaterialByPredicate(s,c,t,r);a&&a.material&&(aq[a.parsedMaterial.uniqueId||a.parsedMaterial.id]=a.material,h+="\n Material "+a.material.toString(o))};for(let r=0,s=c.multiMaterials.length;rloadSubMaterial(e,t=>t.uniqueId===e)):s.materials.forEach(e=>loadSubMaterial(e,t=>t.id===e)),e.push(s.uniqueId||s.id);let r=multiMaterial_MultiMaterial.ParseMultiMaterial(s,t);aq[s.uniqueId||s.id]=r,r&&(i=!0,h+="\n Multi-Material "+r.toString(o));break}}}if(!1===i){e.push(l.materialUniqueId||l.materialId);let i=parseMaterialByPredicate(e=>l.materialUniqueId&&e.uniqueId===l.materialUniqueId||e.id===l.materialId,c,t,r);i&&i.material?(aq[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,h+="\n Material "+i.material.toString(o)):logger_Logger.Warn("Material not found for mesh "+l.id)}}if(null!==l.skeletonId&&void 0!==l.skeletonId&&-1!==c.skeletonId&&void 0!==c.skeletons&&null!==c.skeletons){let e=a.indexOf(l.skeletonId)>-1;if(!e)for(let e=0,i=c.skeletons.length;e-1&&void 0!==c.morphTargetManagers&&null!==c.morphTargetManagers){let e=m.indexOf(l.morphTargetManagerId)>-1;if(!e)for(let e=0,i=c.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach(i=>{e.subMaterials.push(findMaterial(i,t))}),e._waitingSubMaterialsUniqueIds=[]}),t.meshes.forEach(e=>{null!==e._waitingMaterialId&&(e.material=findMaterial(e._waitingMaterialId,t),e._waitingMaterialId=null)});for(let e=0,i=t.transformNodes.length;e-1&&_.splice(e,1)}i._waitingParentId=null}i._waitingData.lods&&loadDetailLevels(t,i)}for(let e of _)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){let i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}}),i._hasWaitingData=null)}for(let e=0,r=t.meshes.length;e{e._loadedUniqueId=""}),!0}catch(t){let e=logOperation("importMesh",c?c.producer:"Unknown")+h;if(o)o(e,t);else throw logger_Logger.Log(e),t}finally{null!==h&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&logger_Logger.Log(logOperation("importMesh",c?c.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?h:"")),aq={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var a=JSON.parse(t);if(s="",void 0!==a.useDelayedTextureLoading&&null!==a.useDelayedTextureLoading&&(e.useDelayedTextureLoading=a.useDelayedTextureLoading&&!sceneLoader_SceneLoader.ForceFullSceneLoadingForIncremental),void 0!==a.autoClear&&null!==a.autoClear&&(e.autoClear=a.autoClear),void 0!==a.clearColor&&null!==a.clearColor&&(e.clearColor=math_color_Color4.FromArray(a.clearColor)),void 0!==a.ambientColor&&null!==a.ambientColor&&(e.ambientColor=math_color_Color3.FromArray(a.ambientColor)),void 0!==a.gravity&&null!==a.gravity&&(e.gravity=math_vector_Vector3.FromArray(a.gravity)),void 0!==a.useRightHandedSystem&&(e.useRightHandedSystem=!!a.useRightHandedSystem),a.fogMode&&0!==a.fogMode)switch(e.fogMode=a.fogMode,e.fogColor=math_color_Color3.FromArray(a.fogColor),e.fogStart=a.fogStart,e.fogEnd=a.fogEnd,e.fogDensity=a.fogDensity,s+=" Fog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(a.physicsEnabled){let t;"cannon"===a.physicsEngine||a.physicsEngine===CannonJSPlugin.name?t=new CannonJSPlugin(void 0,void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):"oimo"===a.physicsEngine||a.physicsEngine===OimoJSPlugin.name?t=new OimoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):("ammo"===a.physicsEngine||a.physicsEngine===AmmoJSPlugin.name)&&(t=new AmmoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(a.physicsEngine?a.physicsEngine:"oimo")+" enabled\n";let i=a.physicsGravity?math_vector_Vector3.FromArray(a.physicsGravity):null;e.enablePhysics(i,t)}void 0!==a.metadata&&null!==a.metadata&&(e.metadata=a.metadata),void 0!==a.collisionsEnabled&&null!==a.collisionsEnabled&&(e.collisionsEnabled=a.collisionsEnabled);let n=loadAssetContainer(e,t,i,r,!0);if(!n)return!1;return a.autoAnimate&&e.beginAnimation(e,a.autoAnimateFrom,a.autoAnimateTo,a.autoAnimateLoop,a.autoAnimateSpeed||1),void 0!==a.activeCameraID&&null!==a.activeCameraID&&e.setActiveCameraById(a.activeCameraID),!0}catch(t){let e=logOperation("importScene",a?a.producer:"Unknown")+s;if(r)r(e,t);else throw logger_Logger.Log(e),t}finally{null!==s&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&logger_Logger.Log(logOperation("importScene",a?a.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>{let s=loadAssetContainer(e,t,i,r);return s}});let FresnelParameters=class FresnelParameters{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,engine_Engine.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||math_color_Color3.White(),this.rightColor=e.rightColor||math_color_Color3.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){let e=new FresnelParameters;return DeepCopier.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new FresnelParameters({isEnabled:e.isEnabled,leftColor:math_color_Color3.FromArray(e.leftColor),rightColor:math_color_Color3.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}};decorators_SerializationHelper._FresnelParametersParser=FresnelParameters.Parse;let PBRBaseSimpleMaterial=class PBRBaseSimpleMaterial extends pbrBaseMaterial_PBRBaseMaterial{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new math_color_Color3(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],PBRBaseSimpleMaterial.prototype,"maxSimultaneousLights",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsLightsDirty")],PBRBaseSimpleMaterial.prototype,"disableLighting",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],PBRBaseSimpleMaterial.prototype,"environmentTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"invertNormalMapX",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"invertNormalMapY",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],PBRBaseSimpleMaterial.prototype,"normalTexture",void 0),__decorate([serializeAsColor3("emissive"),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"emissiveColor",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"emissiveTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],PBRBaseSimpleMaterial.prototype,"occlusionStrength",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],PBRBaseSimpleMaterial.prototype,"occlusionTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],PBRBaseSimpleMaterial.prototype,"alphaCutOff",void 0),__decorate([serialize()],PBRBaseSimpleMaterial.prototype,"doubleSided",null),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty",null)],PBRBaseSimpleMaterial.prototype,"lightmapTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"useLightmapAsShadowmap",void 0);let PBRMetallicRoughnessMaterial=class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){let t=decorators_SerializationHelper.Clone(()=>new PBRMetallicRoughnessMaterial(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new PBRMetallicRoughnessMaterial(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};__decorate([serializeAsColor3(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],PBRMetallicRoughnessMaterial.prototype,"baseColor",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],PBRMetallicRoughnessMaterial.prototype,"baseTexture",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRMetallicRoughnessMaterial.prototype,"metallic",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],PBRMetallicRoughnessMaterial.prototype,"roughness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],PBRMetallicRoughnessMaterial.prototype,"metallicRoughnessTexture",void 0),h["BABYLON.PBRMetallicRoughnessMaterial"]=PBRMetallicRoughnessMaterial;let PBRSpecularGlossinessMaterial=class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){let t=decorators_SerializationHelper.Clone(()=>new PBRSpecularGlossinessMaterial(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){let r=decorators_SerializationHelper.Parse(()=>new PBRSpecularGlossinessMaterial(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};__decorate([serializeAsColor3("diffuse"),expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoColor")],PBRSpecularGlossinessMaterial.prototype,"diffuseColor",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],PBRSpecularGlossinessMaterial.prototype,"diffuseTexture",void 0),__decorate([serializeAsColor3("specular"),expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],PBRSpecularGlossinessMaterial.prototype,"specularColor",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_microSurface")],PBRSpecularGlossinessMaterial.prototype,"glossiness",void 0),__decorate([serializeAsTexture(),expandToProperty("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],PBRSpecularGlossinessMaterial.prototype,"specularGlossinessTexture",void 0),h["BABYLON.PBRSpecularGlossinessMaterial"]=PBRSpecularGlossinessMaterial;let ColorGradingTexture=class ColorGradingTexture extends baseTexture_BaseTexture{constructor(e,t,i=null){if(super(t),!e)return;if(this._textureMatrix=math_vector_Matrix.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{let e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){let e;let t=this._getEngine();e=t._features.support3DTextures?t.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=e,this._texture.isReady=!1,this.isCube=!1,this.is3D=t._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;let callback=i=>{let r;if("string"!=typeof i)return;let s=null,a=null,n=i.split("\n"),o=0,l=0,h=0,c=0,u=0;for(let e=0;e0&&(e+1)%4==0)s[e]=255;else{let t=a[e];s[e]=t/u*255}e.is3D?(e.updateSize(o,o,o),t.updateRawTexture3D(e,s,5,!1)):(e.updateSize(o*o,o),t.updateRawTexture(e,s,5,!1)),e.isReady=!0,this._triggerOnLoad()},i=this.getScene();return i?i._loadFile(this.url,callback):t._loadFile(this.url,callback),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){let e=new ColorGradingTexture(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&((i=new ColorGradingTexture(e.name,t)).name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}};ColorGradingTexture._NoneEmptyLineRegex=/\S+/,h["BABYLON.ColorGradingTexture"]=ColorGradingTexture;let equiRectangularCubeTexture_EquiRectangularCubeTexture=class equiRectangularCubeTexture_EquiRectangularCubeTexture extends baseTexture_BaseTexture{constructor(e,t,i,r=!1,s=!0,a=null,n=null,o=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw Error("Image url is not set");this._coordinatesMode=texture_Texture.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=o,this._noMipmap=r,this.gammaSpace=s,this._onLoad=a,this._onError=n,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?a&&(this._texture.isReady?tools_Tools.SetImmediate(()=>a()):this._texture.onLoadedObservable.add(a)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){let i=this.getScene();if(!i)return;let r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r;let s=document.createElement("canvas");LoadImage(this.url,t=>{this._width=t.width,this._height=t.height,s.width=this._width,s.height=this._height;let i=s.getContext("2d");i.drawImage(t,0,0);let r=i.getImageData(0,0,t.width,t.height);this._buffer=r.data.buffer,s.remove(),e()},(e,s)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,s)},i?i.offlineProvider:null)}_loadTexture(){let e=this.getScene();if(!e)return;let t=(()=>{let e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){let r=t[equiRectangularCubeTexture_EquiRectangularCubeTexture._FacesMapping[e]];i.push(r)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){let t=new DataView(e),i=new Float32Array(3*e.byteLength/4),r=0;for(let s=0;st.length){logger_Logger.Error("Unable to load TGA file - Not enough data");return}c+=u.id_length;let d=!1,_=!1,p=!1;switch(u.image_type){case 9:d=!0;case 1:_=!0;break;case 10:d=!0;case 2:break;case 11:d=!0;case 3:p=!0}let f=u.pixel_size>>3,m=u.width*u.height*f;if(_&&(r=t.subarray(c,c+=u.colormap_length*(u.colormap_size>>3))),d){let e,r,s;i=new Uint8Array(m);let a=0,n=new Uint8Array(f);for(;c>4){default:case 2:s=0,n=1,h=u.width,a=0,o=1,l=u.height;break;case 0:s=0,n=1,h=u.width,a=u.height-1,o=-1,l=-1;break;case 3:s=u.width-1,n=-1,h=-1,a=0,o=1,l=u.height;break;case 1:s=u.width-1,n=-1,h=-1,a=u.height-1,o=-1,l=-1}let g="_getImageData"+(p?"Grey":"")+u.pixel_size+"bits",v=a$[g](u,r,i,a,o,l,s,n,h),x=e.getEngine();x._uploadDataToTextureDirectly(e,v)}function _getImageData8bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u,d=0,_,p,f=new Uint8Array(h*c*4);for(p=r;p!==a;p+=s)for(_=n;_!==l;_+=o,d++)u=i[d],f[(_+h*p)*4+3]=255,f[(_+h*p)*4+2]=t[3*u+0],f[(_+h*p)*4+1]=t[3*u+1],f[(_+h*p)*4+0]=t[3*u+2];return f}function _getImageData16bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u,d=0,_,p,f=new Uint8Array(h*c*4);for(p=r;p!==a;p+=s)for(_=n;_!==l;_+=o,d+=2){u=i[d+0]+(i[d+1]<<8);let e=((31744&u)>>10)*255/31|0,t=((992&u)>>5)*255/31|0,r=(31&u)*255/31|0;f[(_+h*p)*4+0]=e,f[(_+h*p)*4+1]=t,f[(_+h*p)*4+2]=r,f[(_+h*p)*4+3]=32768&u?0:255}return f}function _getImageData24bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u=0,d,_,p=new Uint8Array(h*c*4);for(_=r;_!==a;_+=s)for(d=n;d!==l;d+=o,u+=3)p[(d+h*_)*4+3]=255,p[(d+h*_)*4+2]=i[u+0],p[(d+h*_)*4+1]=i[u+1],p[(d+h*_)*4+0]=i[u+2];return p}function _getImageData32bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u=0,d,_,p=new Uint8Array(h*c*4);for(_=r;_!==a;_+=s)for(d=n;d!==l;d+=o,u+=4)p[(d+h*_)*4+2]=i[u+0],p[(d+h*_)*4+1]=i[u+1],p[(d+h*_)*4+0]=i[u+2],p[(d+h*_)*4+3]=i[u+3];return p}function _getImageDataGrey8bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u,d=0,_,p,f=new Uint8Array(h*c*4);for(p=r;p!==a;p+=s)for(_=n;_!==l;_+=o,d++)u=i[d],f[(_+h*p)*4+0]=u,f[(_+h*p)*4+1]=u,f[(_+h*p)*4+2]=u,f[(_+h*p)*4+3]=255;return f}function _getImageDataGrey16bits(e,t,i,r,s,a,n,o,l){let h=e.width,c=e.height,u=0,d,_,p=new Uint8Array(h*c*4);for(_=r;_!==a;_+=s)for(d=n;d!==l;d+=o,u+=2)p[(d+h*_)*4+0]=i[u+0],p[(d+h*_)*4+1]=i[u+0],p[(d+h*_)*4+2]=i[u+0],p[(d+h*_)*4+3]=i[u+1];return p}HtmlElementTexture._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};let a$={GetTGAHeader,UploadContent,_getImageData8bits,_getImageData16bits,_getImageData24bits,_getImageData32bits,_getImageDataGrey8bits,_getImageDataGrey16bits};let _TGATextureLoader=class _TGATextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=GetTGAHeader(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{UploadContent(t,r)})}};engine_Engine._TextureLoaders.push(new _TGATextureLoader);let _HDRTextureLoader=class _HDRTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=HDRTools.RGBE_ReadHeader(r),a=HDRTools.RGBE_ReadPixels(r,s),n=s.width*s.height,o=new Float32Array(4*n);for(let e=0;e{let e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,o)})}};engine_Engine._TextureLoaders.push(new _HDRTextureLoader),function(e){e[e.cTFETC1=0]="cTFETC1",e[e.cTFETC2=1]="cTFETC2",e[e.cTFBC1=2]="cTFBC1",e[e.cTFBC3=3]="cTFBC3",e[e.cTFBC4=4]="cTFBC4",e[e.cTFBC5=5]="cTFBC5",e[e.cTFBC7=6]="cTFBC7",e[e.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",e[e.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",e[e.cTFASTC_4x4=10]="cTFASTC_4x4",e[e.cTFATC_RGB=11]="cTFATC_RGB",e[e.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",e[e.cTFRGBA32=13]="cTFRGBA32",e[e.cTFRGB565=14]="cTFRGB565",e[e.cTFBGR565=15]="cTFBGR565",e[e.cTFRGBA4444=16]="cTFRGBA4444",e[e.cTFFXT1_RGB=17]="cTFFXT1_RGB",e[e.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",e[e.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",e[e.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",e[e.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11"}(tE||(tE={}));let aQ={JSModuleURL:`${tools_Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${tools_Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},aZ=null,aJ=null,a0=0,_CreateWorkerAsync=()=>(aZ||(aZ=new Promise((e,t)=>{aJ?e(aJ):tools_Tools.LoadFileAsync(tools_Tools.GetBabylonScriptURL(aQ.WasmModuleURL)).then(i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");let r=URL.createObjectURL(new Blob([`(${basis_workerFunc})()`],{type:"application/javascript"}));aJ=new Worker(r);let initHandler=i=>{"init"===i.data.action?(aJ.removeEventListener("message",initHandler),e(aJ)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};aJ.addEventListener("message",initHandler),aJ.postMessage({action:"init",url:tools_Tools.GetBabylonScriptURL(aQ.JSModuleURL),wasmBinary:i})}).catch(t)})),aZ),TranscodeAsync=(e,t)=>{let i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise((e,r)=>{_CreateWorkerAsync().then(()=>{let s=a0++,messageHandler=t=>{"transcode"===t.data.action&&t.data.id===s&&(aJ.removeEventListener("message",messageHandler),t.data.success?e(t.data):r("Transcode is not supported on this device"))};aJ.addEventListener("message",messageHandler);let a=new Uint8Array(i.byteLength);a.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),aJ.postMessage({action:"transcode",id:s,imageData:a,config:t,ignoreSupportedFormats:!1},[a.buffer])},e=>{r(e)})})},BindTexture=(e,t)=>{var i,r;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(r=t._gl)||void 0===r?void 0:r.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},LoadTextureFromTranscodeResult=(e,t)=>{let i=e.getEngine();for(let r=0;r{i._releaseTexture(t),BindTexture(e,i)})}else e._invertVScale=!e.invertY,e.width=s.width+3&-4,e.height=s.height+3&-4,e.samplingMode=2,BindTexture(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0)}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[r].levels.length>1;let a=a1.GetInternalFormatFromBasisFormat(t.format,i);e.format=a,BindTexture(e,i),t.fileInfo.images[r].levels.forEach((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,a,t.width,t.height,t.transcodedPixels,r,s)}),i._features.basisNeedsPOT&&(math_scalar_Scalar.Log2(e.width)%1!=0||math_scalar_Scalar.Log2(e.height)%1!=0)&&(tools_Tools.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=texture_Texture.CLAMP_ADDRESSMODE,e._cachedWrapV=texture_Texture.CLAMP_ADDRESSMODE)}}},a1={JSModuleURL:aQ.JSModuleURL,WasmModuleURL:aQ.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case tE.cTFETC1:i=36196;break;case tE.cTFBC1:i=33776;break;case tE.cTFBC4:i=33779;break;case tE.cTFASTC_4x4:i=37808;break;case tE.cTFETC2:i=37496;break;case tE.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync,LoadTextureFromTranscodeResult};function basis_workerFunc(){let e={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFRGB565:14},t=null;function GetSupportedTranscodeFormat(t,i){let r=null;return t.supportedCompressionFormats&&(r=t.supportedCompressionFormats.astc?e.cTFASTC_4x4:t.supportedCompressionFormats.bc7?e.cTFBC7:t.supportedCompressionFormats.s3tc?i.hasAlpha?e.cTFBC3:e.cTFBC1:t.supportedCompressionFormats.pvrtc?i.hasAlpha?e.cTFPVRTC1_4_RGBA:e.cTFPVRTC1_4_RGB:t.supportedCompressionFormats.etc2?e.cTFETC2:t.supportedCompressionFormats.etc1?e.cTFETC1:e.cTFRGB565),r}function GetFileInfo(e){let t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t>2&3],a[h++]=s[n>>4&3],a[h++]=s[n>>6&3]}}return a}onmessage=i=>{if("init"===i.data.action){if(!t){try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}t=BASIS({wasmBinary:i.data.wasmBinary})}null!==t&&t.then(e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})})}else if("transcode"===i.data.action){let t=i.data.config,r=i.data.imageData,s=new BASIS.BasisFile(r),a=GetFileInfo(s),n=i.data.ignoreSupportedFormats?null:GetSupportedTranscodeFormat(i.data.config,a),o=!1;null===n&&(o=!0,n=a.hasAlpha?e.cTFBC3:e.cTFBC1);let l=!0;s.startTranscoding()||(l=!1);let h=[];for(let e=0;e{let i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;LoadTextureFromTranscodeResult(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(e=>{tools_Tools.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(e)})}loadData(e,t,i){let r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};TranscodeAsync(e,s).then(e=>{let r=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(r.width,r.height,s,-1!==e.format,()=>{LoadTextureFromTranscodeResult(t,e)})}).catch(e=>{tools_Tools.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),tools_Tools.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,()=>{},!0)})}};engine_Engine._TextureLoaders.push(new _BasisTextureLoader);let MultiRenderTarget=class MultiRenderTarget extends renderTargetTexture_RenderTargetTexture{get isSupported(){var e,t;return null!==(t=null===(e=this._engine)||void 0===e?void 0:e.getCaps().drawBuffersExtension)&&void 0!==t&&t}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(a))}_initTypes(e,t,i,r,s,a,n,o,l,h){for(let c=0;c{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;let i=null===(e=this._renderTarget)||void 0===e?void 0:e.textures;if(i){for(let e=i.length-1;e>=0;e--)this._textures[e]._texture=null;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null}}};let TexturePackerFrame=class TexturePackerFrame{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}};let TexturePacker=class TexturePacker{constructor(e,t,i,r){var s,a,n,o,l,h,c,u,d,_,p,f,m;return this.name=e,this.meshes=t,this.scene=r,this.options=i,this.options.map=null!==(s=this.options.map)&&void 0!==s?s:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=null!==(a=this.options.uvsIn)&&void 0!==a?a:buffer_VertexBuffer.UVKind,this.options.uvsOut=null!==(n=this.options.uvsOut)&&void 0!==n?n:buffer_VertexBuffer.UVKind,this.options.layout=null!==(o=this.options.layout)&&void 0!==o?o:TexturePacker.LAYOUT_STRIP,this.options.layout===TexturePacker.LAYOUT_COLNUM&&(this.options.colnum=null!==(l=this.options.colnum)&&void 0!==l?l:8),this.options.updateInputMeshes=null===(h=this.options.updateInputMeshes)||void 0===h||h,this.options.disposeSources=null===(c=this.options.disposeSources)||void 0===c||c,this._expecting=0,this.options.fillBlanks=null===(u=this.options.fillBlanks)||void 0===u||u,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(d=this.options.customFillColor)&&void 0!==d?d:"black"),this.options.frameSize=null!==(_=this.options.frameSize)&&void 0!==_?_:256,this.options.paddingRatio=null!==(p=this.options.paddingRatio)&&void 0!==p?p:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(f=this.options.paddingMode)&&void 0!==f?f:TexturePacker.SUBUV_WRAP,this.options.paddingMode===TexturePacker.SUBUV_COLOR&&(this.options.paddingColor=null!==(m=this.options.paddingColor)&&void 0!==m?m:new math_color_Color4(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){let t=this._calculateSize(),i=new math_vector_Vector2(1,1).divide(t),r=0,s=this._expecting,a=this.meshes.length,n=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(o,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{r++,u.update(!1);let i=d.getImageData(0,0,h,h),a=this.sets[p],n=a.getContext();if(n.putImageData(i,t.x*_.x,t.y*_.y),u.dispose(),a.update(!1),r==s){done(),e();return}},p=n[a]||"_blank";if(c&&null!==c[p]){let e=c[p],t=new Image;e instanceof DynamicTexture?t.src=e.getContext().canvas.toDataURL("image/png"):t.src=e.url,tools_Tools.SetCorsBehavior(t.src,t),t.onload=()=>{d.fillStyle="rgba(0,0,0,0)",d.fillRect(0,0,h,h),u.update(!1),d.setTransform(1,0,0,-1,0,0);let e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)d.drawImage(t,0,0,t.width,t.height,l+o*e[i],l+o*e[i+1]-h,o,o);break;case 1:for(let e=0;e{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length){e();return}let t=0,doneCheck=i=>{if(t++,this.options.map){for(let e=0;e{doneCheck(s)})}}catch(e){return t(e)}})}dispose(){let e=Object.keys(this.sets);for(let t=0;t{let i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesIndices"===e.name&&t(e));i||(i=new InputBlock("matricesIndices")).setAsAttribute("matricesIndices"),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesWeights"===e.name&&t(e));i||(i=new InputBlock("matricesWeights")).setAsAttribute("matricesWeights"),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(ev.World),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){MaterialHelper.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&MaterialHelper.PrepareDefinesForBones(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");let t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});let i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});let r=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 -`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName} * ${i}; -`,e.compilationString+=`#else -`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName}; -`,e.compilationString+=`#endif -`,this}};h["BABYLON.BonesBlock"]=BonesBlock;let InstancesBlock=class InstancesBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Vertex),this.registerInput("world0",ed.Vector4),this.registerInput("world1",ed.Vector4),this.registerInput("world2",ed.Vector4),this.registerInput("world3",ed.Vector4),this.registerInput("world",ed.Matrix,!0),this.registerOutput("output",ed.Matrix),this.registerOutput("instanceID",ed.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world0"===e.name&&t(e));i||(i=new InputBlock("world0")).setAsAttribute("world0"),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world1"===e.name&&t(e));i||(i=new InputBlock("world1")).setAsAttribute("world1"),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world2"===e.name&&t(e));i||(i=new InputBlock("world2")).setAsAttribute("world2"),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world3"===e.name&&t(e));i||(i=new InputBlock("world3")).setAsAttribute("world3"),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world"===e.name&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(ev.World),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let a=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),a=!0),s&&!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)!==i.THIN_INSTANCES&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),a=!0),a&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);let t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);let i=this._outputs[0],r=this._outputs[1],s=this.world0,a=this.world1,n=this.world2,o=this.world3;return e.compilationString+=`#ifdef INSTANCES -`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${a.associatedVariableName}, ${n.associatedVariableName}, ${o.associatedVariableName}); -`,e.compilationString+=`#ifdef THIN_INSTANCES -`,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; -`,e.compilationString+=`#endif -`,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(r,e)+` = float(gl_InstanceID); -`:e.compilationString+=this._declareOutput(r,e)+` = 0.0; -`,e.compilationString+=`#else -`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; -`,e.compilationString+=this._declareOutput(r,e)+` = 0.0; -`,e.compilationString+=`#endif -`,this}};h["BABYLON.InstancesBlock"]=InstancesBlock;let MorphTargetsBlock=class MorphTargetsBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Vertex),this.registerInput("position",ed.Vector3),this.registerInput("normal",ed.Vector3),this.registerInput("tangent",ed.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(ed.Color4|ed.Vector4|ed.Vector3),this.registerInput("uv",ed.Vector2),this.registerOutput("positionOutput",ed.Vector3),this.registerOutput("normalOutput",ed.Vector3),this.registerOutput("tangentOutput",ed.Vector4),this.registerOutput("uvOutput",ed.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new InputBlock("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new InputBlock("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&t(e));i||(i=new InputBlock("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute("uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){let t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&MaterialHelper.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(MaterialHelper.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){let s=this.position,a=this.normal,n=this.tangent,o=this.uv,l=this.positionOutput,h=this.normalOutput,c=this.tangentOutput,u=this.uvOutput,d=r.NUM_MORPH_INFLUENCERS,_=i.morphTargetManager,p=_&&_.supportsNormals&&r.NORMAL,f=_&&_.supportsTangents&&r.TANGENT,m=_&&_.supportsUVs&&r.UV1,g="";(null==_?void 0:_.isUsingTextureForTargets)&&d>0&&(g+=`float vertexID; -`);for(let e=0;e0)for(let t=0;t!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.isSystemValue&&e.systemValue===ev.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(ev.World),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new InputBlock("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&e.type===ed.Vector4&&t(e));i||(i=new InputBlock("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var r,s,a,n;let o=this.normal,l=this.tangent,h=o.isConnected;(null===(r=o.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(s=o.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let c=l.isConnected;(null===(a=l.connectInputBlock)||void 0===a?void 0:a.isAttribute)&&!e.isVerticesDataPresent(null===(n=l.connectInputBlock)||void 0===n?void 0:n.name)&&(c=!1);let u=h&&c;i.setValue("TBNBLOCK",u,!0)}_buildBlock(e){super._buildBlock(e);let t=this.normal,i=this.tangent,r=this.world,s=this.TBN,a=this.row0,n=this.row1,o=this.row2;return e.target===e_.Fragment&&(e.compilationString+=` - // ${this.name} - vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; - vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); - vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; - mat3 ${s.associatedVariableName} = mat3(${r.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); - `,a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); -`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); -`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); -`),e.sharedData.blocksWithDefines.push(this)),this}};h["BABYLON.TBNBlock"]=TBNBlock;let PerturbNormalBlock=class PerturbNormalBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",ed.Vector4,!1),this.registerInput("worldNormal",ed.Vector4,!1),this.registerInput("worldTangent",ed.Vector4,!0),this.registerInput("uv",ed.Vector2,!1),this.registerInput("normalMapColor",ed.Color3,!1),this.registerInput("strength",ed.Float,!1),this.registerInput("viewDirection",ed.Vector3,!0),this.registerInput("parallaxScale",ed.Float,!0),this.registerInput("parallaxHeight",ed.Float,!0),this.registerInput("TBN",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,ef.Input,TBNBlock,"TBNBlock")),this.registerInput("world",ed.Matrix,!0),this.registerOutput("output",ed.Vector4),this.registerOutput("uvOffset",ed.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){let r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute(),i.output.connectTo(this.uv)}if(!this.strength.isConnected){let e=new InputBlock("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,a=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let n=null;this.normalMapColor.connectedPoint&&(n=this.normalMapColor.connectedPoint._ownerBlock.samplerName);let o=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&n||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?` -#if !defined(NORMALXYSCALE) -1.0/ -#endif -${e._emitFloat(this.strength.connectInputBlock.value)}`:` -#if !defined(NORMALXYSCALE) -1.0/ -#endif -${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let c={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},u=this.TBN;u.isConnected?e.compilationString+=` - #ifdef TBNBLOCK - mat3 vTBN = ${u.associatedVariableName}; - #endif - `:a.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz); -`,e.compilationString+=`vec3 tbnTangent = normalize(${a.associatedVariableName}.xyz); -`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; -`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); -`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[c,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});let d=o&&n?`texture2D(${n}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o&&this.useParallaxOcclusion?n:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${o?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:r.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:o?this.viewDirection.associatedVariableName:"vec3(0.)"},c]}),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; -`+`${this._codeVariableName}.invertY = ${this.invertY}; -${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; -${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; -`}serialize(){let e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}};__decorate([editableInPropertyPage("Invert X axis",em.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"invertX",void 0),__decorate([editableInPropertyPage("Invert Y axis",em.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"invertY",void 0),__decorate([editableInPropertyPage("Use parallax occlusion",em.Boolean)],PerturbNormalBlock.prototype,"useParallaxOcclusion",void 0),__decorate([editableInPropertyPage("Object Space Mode",em.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"useObjectSpaceNormalMap",void 0),h["BABYLON.PerturbNormalBlock"]=PerturbNormalBlock;let DiscardBlock=class DiscardBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.registerInput("value",ed.Float,!0),this.registerInput("cutoff",ed.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard; -`,this}};h["BABYLON.DiscardBlock"]=DiscardBlock;let FrontFacingBlock=class FrontFacingBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerOutput("output",ed.Float,e_.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===e_.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0; -`,this}};h["BABYLON.FrontFacingBlock"]=FrontFacingBlock;let DerivativeBlock=class DerivativeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerInput("input",ed.AutoDetect,!1),this.registerOutput("dx",ed.BasedOnInput),this.registerOutput("dy",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName}); -`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName}); -`),this}};h["BABYLON.DerivativeBlock"]=DerivativeBlock;let FragCoordBlock=class FragCoordBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerOutput("xy",ed.Vector2,e_.Fragment),this.registerOutput("xyz",ed.Vector3,e_.Fragment),this.registerOutput("xyzw",ed.Vector4,e_.Fragment),this.registerOutput("x",ed.Float,e_.Fragment),this.registerOutput("y",ed.Float,e_.Fragment),this.registerOutput("z",ed.Float,e_.Fragment),this.registerOutput("w",ed.Float,e_.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(let i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name}; -`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===e_.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}};h["BABYLON.FragCoordBlock"]=FragCoordBlock;let ScreenSizeBlock=class ScreenSizeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerOutput("xy",ed.Vector2,e_.Fragment),this.registerOutput("x",ed.Float,e_.Fragment),this.registerOutput("y",ed.Float,e_.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){let t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; -`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===e_.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}};h["BABYLON.ScreenSizeBlock"]=ScreenSizeBlock;let ScreenSpaceBlock=class ScreenSpaceBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerInput("vector",ed.AutoDetect),this.registerInput("worldViewProjection",ed.Matrix),this.registerOutput("output",ed.Vector2),this.registerOutput("x",ed.Float),this.registerOutput("y",ed.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.WorldViewProjection&&t(e));i||(i=new InputBlock("worldViewProjection")).setAsSystemValue(ev.WorldViewProjection),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;let r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case ed.Vector3:e.compilationString+=`vec4 ${s} = ${r} * vec4(${t.associatedVariableName}, 1.0); -`;break;case ed.Vector4:e.compilationString+=`vec4 ${s} = ${r} * ${t.associatedVariableName}; -`}return e.compilationString+=`${s}.xy /= ${s}.w;`,e.compilationString+=`${s}.xy = ${s}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${s}.xy; -`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x; -`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y; -`),this}};h["BABYLON.ScreenSpaceBlock"]=ScreenSpaceBlock;let TwirlBlock=class TwirlBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerInput("input",ed.Vector2),this.registerInput("strength",ed.Float),this.registerInput("center",ed.Vector2),this.registerInput("offset",ed.Vector2),this.registerOutput("output",ed.Vector2),this.registerOutput("x",ed.Float),this.registerOutput("y",ed.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){let e=new InputBlock("center");e.value=new math_vector_Vector2(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){let e=new InputBlock("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){let e=new InputBlock("offset");e.value=new math_vector_Vector2(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);let t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),a=e._getFreeVariableName("result");return e.compilationString+=` - vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; - float ${i} = ${this.strength.associatedVariableName} * length(${t}); - float ${r} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; - float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; - vec2 ${a} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); - `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${a}; -`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${a}.x; -`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${a}.y; -`),this}};h["BABYLON.TwirlBlock"]=TwirlBlock;let HeightToNormalBlock=class HeightToNormalBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",ed.Float),this.registerInput("worldPosition",ed.Vector3),this.registerInput("worldNormal",ed.Vector3),this.registerInput("worldTangent",ed.AutoDetect,!0),this.registerOutput("output",ed.Vector4),this.registerOutput("xyz",ed.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);let i=this.generateInWorldSpace?"":` - vec3 biTangent = cross(normal, tangent); - mat3 TBN = mat3(tangent, biTangent, normal); - `,r=this.generateInWorldSpace?"":` - result = TBN * result; - result = result * vec3(0.5) + vec3(0.5); - `,s=` - vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { - ${i} - ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} - ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} - vec3 worlddX = dFdx(position); - vec3 worlddY = dFdy(position); - vec3 crossX = cross(normal, worlddX); - vec3 crossY = cross(normal, worlddY); - float d = abs(dot(crossY, worlddX)); - vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); - inToNormal.y *= -1.0; - vec3 result = normalize((d * normal) - inToNormal); - ${r} - return vec4(result, 0.); - }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",s,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName}); -`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; -`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; -${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; -${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; -`}serialize(){let e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}};__decorate([editableInPropertyPage("Generate in world space instead of tangent space",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"generateInWorldSpace",void 0),__decorate([editableInPropertyPage("Force normalization for the worldNormal input",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"automaticNormalizationNormal",void 0),__decorate([editableInPropertyPage("Force normalization for the worldTangent input",em.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"automaticNormalizationTangent",void 0),h["BABYLON.HeightToNormalBlock"]=HeightToNormalBlock;let FragDepthBlock=class FragDepthBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.registerInput("depth",ed.Float,!0),this.registerInput("worldPos",ed.Vector4,!0),this.registerInput("viewProjection",ed.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; -`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` - vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; - float v = p.z / p.w; - #ifndef IS_NDC_HALF_ZRANGE - v = v * 0.5 + 0.5; - #endif - gl_FragDepth = v; - - `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}};h["BABYLON.FragDepthBlock"]=FragDepthBlock;let ShadowMapBlock=class ShadowMapBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.registerInput("worldPosition",ed.Vector4,!1),this.registerInput("viewProjection",ed.Matrix,!1),this.registerInput("worldNormal",ed.AutoDetect,!0),this.registerOutput("depth",ed.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName}; -`,e.compilationString+=`vec3 vPositionWSM; -`,e.compilationString+=`float vDepthMetricSM = 0.0; -`,e.compilationString+=`float zSM; -`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; -`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` - #if SM_DEPTHTEXTURE == 1 - #ifdef IS_NDC_HALF_ZRANGE - gl_FragDepth = (clipPos.z / clipPos.w); - #else - gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; - #endif - #endif - `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); -`,this}};h["BABYLON.ShadowMapBlock"]=ShadowMapBlock;let PrePassOutputBlock=class PrePassOutputBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment,!0),this.registerInput("viewDepth",ed.Float,!0),this.registerInput("worldPosition",ed.AutoDetect,!0),this.registerInput("viewNormal",ed.AutoDetect,!0),this.registerInput("reflectivity",ed.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(ed.Vector3|ed.Vector4|ed.Color3|ed.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);let t=this.worldPosition,i=this.viewNormal,r=this.viewDepth,s=this.reflectivity;e.sharedData.blocksWithDefines.push(this);let a=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",a),e.compilationString+=`#if defined(PREPASS)\r -`,e.compilationString+=`#ifdef PREPASS_DEPTH\r -`,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${r.associatedVariableName}, 0.0, 0.0, 1.0);\r -`:e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=`#ifdef PREPASS_POSITION\r -`,t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===ed.Vector4?t.associatedVariableName+".a":"1.0"});\r -`:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=`#ifdef PREPASS_NORMAL\r -`,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===ed.Vector4?i.associatedVariableName+".a":"1.0"});\r -`:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r -`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===ed.Vector4?s.associatedVariableName+".a":"1.0"});\r -`:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=`#endif\r -`,this}};h["BABYLON.PrePassOutputBlock"]=PrePassOutputBlock;let FogBlock=class FogBlock extends NodeMaterialBlock{constructor(e){super(e,e_.VertexAndFragment,!1),this.registerInput("worldPosition",ed.Vector4,!1,e_.Vertex),this.registerInput("view",ed.Matrix,!1,e_.Vertex),this.registerInput("input",ed.AutoDetect,!1,e_.Fragment),this.registerInput("fogColor",ed.AutoDetect,!1,e_.Fragment),this.registerOutput("output",ed.Color3,e_.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(ev.View),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.FogColor&&t(e));i||(i=new InputBlock("fogColor",void 0,ed.Color3)).setAsSystemValue(ev.FogColor),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){let r=e.getScene();i.setValue("FOG",t.fogEnabled&&MaterialHelper.GetFogState(e,r))}bind(e,t,i){if(!i)return;let r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===e_.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});let t=e._getFreeVariableName("fog"),i=this.input,r=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");let s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG -`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); -`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${r.associatedVariableName}.rgb; -`,e.compilationString+=`#else -${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb; -`,e.compilationString+=`#endif -`}else{let t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz; -`}return this}};h["BABYLON.FogBlock"]=FogBlock;let LightBlock=class LightBlock extends NodeMaterialBlock{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?e_.Fragment:e_.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex}constructor(e){super(e,e_.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",ed.Vector4,!1,e_.Vertex),this.registerInput("worldNormal",ed.Vector4,!1,e_.Fragment),this.registerInput("cameraPosition",ed.Vector3,!1,e_.Fragment),this.registerInput("glossiness",ed.Float,!0,e_.Fragment),this.registerInput("glossPower",ed.Float,!0,e_.Fragment),this.registerInput("diffuseColor",ed.Color3,!0,e_.Fragment),this.registerInput("specularColor",ed.Color3,!0,e_.Fragment),this.registerInput("view",ed.Matrix,!0),this.registerOutput("diffuseOutput",ed.Color3,e_.Fragment),this.registerOutput("specularOutput",ed.Color3,e_.Fragment),this.registerOutput("shadow",ed.Float,e_.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(ev.CameraPosition),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;let r=e.getScene();if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};MaterialHelper.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else MaterialHelper.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;MaterialHelper.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;let r=i.getScene();this.light?MaterialHelper.BindLight(this.light,this._lightId,r,e,!0):MaterialHelper.BindLights(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){let t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));let r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; -`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; -`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; -`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==e_.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=`//${this.name}`,i=this.worldPosition,r=i.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${r}; -`,t),e.compilationString+=`${r} = ${i.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):r="v_"+r+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}); -`),e.compilationString+=`lightingInfo info; -`,e.compilationString+=`float shadow = 1.; -`,e.compilationString+=`float aggShadow = 0.; -`,e.compilationString+=`float numLights = 0.; -`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; -`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); -`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); -`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; -`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),0===this._lightId&&(e.compilationString+=`aggShadow = aggShadow / numLights; -`);let s=this.diffuseOutput,a=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; -`,a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; -`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = aggShadow; -`),this}serialize(){let e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}};__decorate([editableInPropertyPage("Generate only fragment code",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:LightBlock._OnGenerateOnlyFragmentCodeChanged}})],LightBlock.prototype,"generateOnlyFragmentCode",void 0),h["BABYLON.LightBlock"]=LightBlock;let ImageSourceBlock=class ImageSourceBlock extends NodeMaterialBlock{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,e_.VertexAndFragment),this.registerOutput("source",ed.Object,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,ef.Output,ImageSourceBlock,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===e_.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};h["BABYLON.ImageSourceBlock"]=ImageSourceBlock;let TextureBlock=class TextureBlock extends NodeMaterialBlock{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _IsPrePassTextureBlock(e){return(null==e?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return TextureBlock._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!TextureBlock._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?e_.Fragment:e_.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",ed.AutoDetect,!1,e_.VertexAndFragment),this.registerInput("source",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,ef.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerInput("layer",ed.Float,!0),this.registerInput("lod",ed.Float,!0),this.registerOutput("rgba",ed.Color4,e_.Neutral),this.registerOutput("rgb",ed.Color3,e_.Neutral),this.registerOutput("r",ed.Float,e_.Neutral),this.registerOutput("g",ed.Float,e_.Neutral),this.registerOutput("b",ed.Float,e_.Neutral),this.registerOutput("a",ed.Float,e_.Neutral),this.registerOutput("level",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return e_.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return e_.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===e_.Fragment)return e_.Fragment;if(e.target===e_.Vertex)break;if(e.target===e_.Neutral||e.target===e_.VertexAndFragment){let t=e.ownerBlock;if(t.target===e_.Fragment)return e_.Fragment;for(let i of(e=null,t.inputs))if(i.connectedPoint){e=i.connectedPoint;break}}}return e_.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){if(e.mode===eb.PostProcess){let i=e.getBlockByPredicate(e=>"uv"===e.name&&t(e));i&&i.connectTo(this)}else{let i=e.mode===eb.Particle?"particle_uv":"uv",r=e.getInputBlockByPredicate(e=>e.isAttribute&&e.name===i&&t(e));r||(r=new InputBlock("uv")).setAsAttribute(i),r.output.connectTo(this.uv)}}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),void 0==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==e_.Fragment}_injectVertexCode(e){let t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName} -`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0)); -`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) -`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,e.compilationString+=`#endif -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}_getUVW(e){var t,i,r;let s=e,a=null!==(r=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==r&&r;if(a){let t=this.layer.isConnected?this.layer.associatedVariableName:"0";s=`vec3(${e}, ${t})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){let t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName} -`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix}); -`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) -`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix}); -`,e.compilationString+=`#endif -`}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===e_.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix}); -`;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} - ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); - #endif - `),e.compilationString+=`#ifdef ${this._gammaDefineName} - ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); - #endif - `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===e_.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; -`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,r,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===e_.Vertex||this._fragmentOnly||e.target===e_.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===e_.Fragment||this._isMixed&&e.target===e_.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==e_.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((null===(s=null===(r=this._texture)||void 0===r?void 0:r._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));let a=`//${this.name}`;for(let t of(e._emitFunctionFromInclude("helperFunctions",a),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; -`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};h["BABYLON.TextureBlock"]=TextureBlock;let ReflectionTextureBaseBlock=class ReflectionTextureBaseBlock extends NodeMaterialBlock{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?e_.Fragment:e_.VertexAndFragment)}constructor(e){super(e,e_.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new InputBlock("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(ev.World),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(ev.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){let r=this._getTexture();i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize&&(e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)))}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===e_.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");let i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; -`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} -${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; -#endif -`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) -${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); -#endif -`),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} -`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; -`,e._samplerDeclaration+=`#else -`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; -`,e._samplerDeclaration+=`#endif -`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,r=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);let s=this._reflectionMatrixName,a=`normalize(${this._directionWName})`,n=`${this._positionUVWName}`,o=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=` - #ifdef ${this._defineMirroredEquirectangularFixedName} - vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${a}); - #endif - - #ifdef ${this._defineEquirectangularFixedName} - vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${a}); - #endif - - #ifdef ${this._defineEquirectangularName} - vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - - #ifdef ${this._defineSphericalName} - vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s}); - #endif - - #ifdef ${this._definePlanarName} - vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - - #ifdef ${this._defineCubicName} - #ifdef ${this._defineLocalCubicName} - vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${o}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); - #else - vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - #endif - - #ifdef ${this._defineProjectionName} - vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s}); - #endif - - #ifdef ${this._defineSkyboxName} - vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${n}, ${s}); - #endif - - #ifdef ${this._defineExplicitName} - vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); - #endif -`;return r||(h+=`#ifdef ${this._defineOppositeZ} - ${this._reflectionVectorName}.z *= -1.0; - #endif -`),i||(h+=` - #ifdef ${this._define3DName} - vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; - #else - vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; - #ifdef ${this._defineProjectionName} - ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; - #endif - ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; - #endif -`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i="vec"+(0===t.length?"4":t.length-1),r=`${i} ${this._reflectionColorName}; - #ifdef ${this._define3DName} -`;return e?r+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; -`:r+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; -`,r+=` - #else -`,e?r+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; -`:r+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; -`,r+=`#endif -`}writeOutputs(e,t){let i="";if(e.target===e_.Fragment)for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; -`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){let t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); -`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); -`;return e+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=cubeTexture_CubeTexture.Parse(e.texture,t,i):this.texture=texture_Texture.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}};__decorate([editableInPropertyPage("Generate only fragment code",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged}})],ReflectionTextureBaseBlock.prototype,"generateOnlyFragmentCode",void 0),h["BABYLON.ReflectionTextureBaseBlock"]=ReflectionTextureBaseBlock;let ReflectionTextureBlock=class ReflectionTextureBlock extends ReflectionTextureBaseBlock{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex}constructor(e){super(e),this.registerInput("position",ed.AutoDetect,!1,e_.Vertex),this.registerInput("worldPosition",ed.Vector4,!1,e_.Vertex),this.registerInput("worldNormal",ed.Vector4,!1,e_.Fragment),this.registerInput("world",ed.Matrix,!1,e_.Vertex),this.registerInput("cameraPosition",ed.Vector3,!1,e_.Fragment),this.registerInput("view",ed.Matrix,!1,e_.Fragment),this.registerOutput("rgb",ed.Color3,e_.Fragment),this.registerOutput("rgba",ed.Color4,e_.Fragment),this.registerOutput("r",ed.Float,e_.Fragment),this.registerOutput("g",ed.Float,e_.Fragment),this.registerOutput("b",ed.Float,e_.Fragment),this.registerOutput("a",ed.Float,e_.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(ev.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==e_.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);let t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); -`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}};h["BABYLON.ReflectionTextureBlock"]=ReflectionTextureBlock;let SceneDepthBlock=class SceneDepthBlock extends NodeMaterialBlock{constructor(e){super(e,e_.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",ed.AutoDetect,!1,e_.VertexAndFragment),this.registerOutput("depth",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?e_.VertexAndFragment:e_.Fragment}_getTexture(e){let t=e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ);return t.getDepthMap()}bind(e,t){let i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===ed.Vector3?"3":t.type===ed.Vector4?"4":"2"))}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===e_.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); -`;return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); -`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); -`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===e_.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}if(this.uv.ownerBlock.target===e_.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.bindableBlocks.indexOf(this)&&e.sharedData.bindableBlocks.push(this),e.target!==e_.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(e=>e.isConnectedInFragmentShader)){for(let t of(e._emit2DSampler(this._samplerName),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){let e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}};__decorate([editableInPropertyPage("Use non linear depth",em.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],SceneDepthBlock.prototype,"useNonLinearDepth",void 0),__decorate([editableInPropertyPage("Store Camera space Z",em.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],SceneDepthBlock.prototype,"storeCameraSpaceZ",void 0),__decorate([editableInPropertyPage("Force 32 bits float",em.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>null==e?void 0:e.disableDepthRenderer()}})],SceneDepthBlock.prototype,"force32itsFloat",void 0),h["BABYLON.SceneDepthBlock"]=SceneDepthBlock;let ClipPlanesBlock=class ClipPlanesBlock extends NodeMaterialBlock{constructor(e){super(e,e_.VertexAndFragment,!0),this.registerInput("worldPosition",ed.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return e_.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var r,s,a,n,o,l;let h=e.getScene(),c=null!==(r=t.clipPlane)&&void 0!==r?!!r:!!h.clipPlane,u=null!==(s=t.clipPlane2)&&void 0!==s?!!s:!!h.clipPlane2,d=null!==(a=t.clipPlane3)&&void 0!==a?!!a:!!h.clipPlane3,_=null!==(n=t.clipPlane4)&&void 0!==n?!!n:!!h.clipPlane4,p=null!==(o=t.clipPlane5)&&void 0!==o?!!o:!!h.clipPlane5,f=null!==(l=t.clipPlane6)&&void 0!==l?!!l:!!h.clipPlane6;i.setValue("CLIPPLANE",c,!0),i.setValue("CLIPPLANE2",u,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",_,!0),i.setValue("CLIPPLANE5",p,!0),i.setValue("CLIPPLANE6",f,!0)}bind(e,t,i){if(!i)return;let r=i.getScene();bindClipPlane(e,t,r)}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;if(e.target!==e_.Fragment){let i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}};h["BABYLON.ClipPlanesBlock"]=ClipPlanesBlock;let PrePassTextureBlock=class PrePassTextureBlock extends NodeMaterialBlock{get texture(){return null}set texture(e){}constructor(e,t=e_.VertexAndFragment){super(e,t,!1),this.registerOutput("position",ed.Object,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("position",this,ef.Output,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("depth",ed.Object,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("depth",this,ef.Output,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("normal",ed.Object,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("normal",this,ef.Output,ImageSourceBlock,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==e_.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){let i=t.getScene(),r=i.enablePrePassRenderer();if(!r)return;let s=r.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[r.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[r.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[r.getIndex(6)]))}};h["BABYLON.PrePassTextureBlock"]=PrePassTextureBlock;let NodeMaterialTeleportInBlock=class NodeMaterialTeleportInBlock extends NodeMaterialBlock{get endpoints(){return this._endpoints}constructor(e){super(e,e_.Neutral),this._endpoints=[],this.registerInput("input",ed.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){for(let e of(super.dispose(),this._endpoints))this.detachFromEndpoint(e);this._endpoints=[]}};h["BABYLON.NodeMaterialTeleportInBlock"]=NodeMaterialTeleportInBlock;let NodeMaterialTeleportOutBlock=class NodeMaterialTeleportOutBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",ed.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){(this._target&e)==0&&(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName}; -`)}clone(e,t=""){let i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); -`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}};h["BABYLON.NodeMaterialTeleportOutBlock"]=NodeMaterialTeleportOutBlock;let AddBlock=class AddBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(ed.Float),this._inputs[1].acceptedConnectionPointTypes.push(ed.Float)}getClassName(){return"AddBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; -`,this}};h["BABYLON.AddBlock"]=AddBlock;let ScaleBlock=class ScaleBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.AutoDetect),this.registerInput("factor",ed.Float),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; -`,this}};h["BABYLON.ScaleBlock"]=ScaleBlock;let ClampBlock=class ClampBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)}); -`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; -`+`${this._codeVariableName}.maximum = ${this.maximum}; -`}serialize(){let e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}};__decorate([editableInPropertyPage("Minimum",em.Float)],ClampBlock.prototype,"minimum",void 0),__decorate([editableInPropertyPage("Maximum",em.Float)],ClampBlock.prototype,"maximum",void 0),h["BABYLON.ClampBlock"]=ClampBlock;let CrossBlock=class CrossBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ed.Vector2),this._inputs[1].excludedConnectionPointTypes.push(ed.Float),this._inputs[1].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); -`,this}};h["BABYLON.CrossBlock"]=CrossBlock;let CustomBlock=class CustomBlock extends NodeMaterialBlock{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),a=e._getGLType(r.type);t=t.replace(s,a),i=i.replace(s,a)}),this._outputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),a=e._getGLType(r.type);t=t.replace(s,a),i=i.replace(s,a)}),e._emitFunction(i,t,""),this._outputs.forEach(t=>{e.compilationString+=this._declareOutput(t,e)+";\n"}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((t,i)=>{var s,a,n;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(n=null===(a=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===a?void 0:a.samplerName)&&void 0!==n?n:t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0}),this._outputs.forEach((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName}),e.compilationString+=");\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; -`}serialize(){let e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,r;this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=e_[e.target],null===(t=e.inParameters)||void 0===t||t.forEach((e,t)=>{let i=ed[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject(e.name,this,ef.Input,ImageSourceBlock,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})}),null===(i=e.outParameters)||void 0===i||i.forEach((e,t)=>{this.registerOutput(e.name,ed[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])}),null===(r=e.inLinkedConnectionTypes)||void 0===r||r.forEach(e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(ev.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); -`,this}};h["BABYLON.ViewDirectionBlock"]=ViewDirectionBlock;let FresnelBlock=class FresnelBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("worldNormal",ed.Vector4),this.registerInput("viewDirection",ed.Vector3),this.registerInput("bias",ed.Float),this.registerInput("power",ed.Float),this.registerOutput("fresnel",ed.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){let t=new ViewDirectionBlock("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){let e=new InputBlock("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){let e=new InputBlock("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName}); -`,this}};h["BABYLON.FresnelBlock"]=FresnelBlock;let MaxBlock=class MaxBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}};h["BABYLON.MaxBlock"]=MaxBlock;let MinBlock=class MinBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}};h["BABYLON.MinBlock"]=MinBlock;let DistanceBlock=class DistanceBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.Float),this._inputs[1].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); -`,this}};h["BABYLON.DistanceBlock"]=DistanceBlock;let LengthBlock=class LengthBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerOutput("output",ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName}); -`,this}};h["BABYLON.LengthBlock"]=LengthBlock;let NegateBlock=class NegateBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName}; -`,this}};h["BABYLON.NegateBlock"]=NegateBlock;let PowBlock=class PowBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerInput("power",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); -`,this}};h["BABYLON.PowBlock"]=PowBlock;let RandomNumberBlock=class RandomNumberBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("seed",ed.AutoDetect),this.registerOutput("output",ed.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Vector2|ed.Vector3|ed.Vector4|ed.Color3|ed.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy); -`,this}};h["BABYLON.RandomNumberBlock"]=RandomNumberBlock;let ArcTan2Block=class ArcTan2Block extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("x",ed.Float),this.registerInput("y",ed.Float),this.registerOutput("output",ed.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); -`,this}};h["BABYLON.ArcTan2Block"]=ArcTan2Block;let SmoothStepBlock=class SmoothStepBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerInput("edge0",ed.Float),this.registerInput("edge1",ed.Float),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName}); -`,this}};h["BABYLON.SmoothStepBlock"]=SmoothStepBlock;let ReciprocalBlock=class ReciprocalBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return this.input.type===ed.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); -`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; -`,this}};h["BABYLON.ReciprocalBlock"]=ReciprocalBlock;let ReplaceColorBlock=class ReplaceColorBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerInput("reference",ed.AutoDetect),this.registerInput("distance",ed.Float),this.registerInput("replacement",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(ed.Float),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.Float),this._inputs[1].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[3].excludedConnectionPointTypes.push(ed.Float),this._inputs[3].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`; -`,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { -`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; -`,e.compilationString+=`} else { -`,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; -`,e.compilationString+=`} -`,this}};h["BABYLON.ReplaceColorBlock"]=ReplaceColorBlock;let PosterizeBlock=class PosterizeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("value",ed.AutoDetect),this.registerInput("steps",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[1].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName}); -`,this}};h["BABYLON.PosterizeBlock"]=PosterizeBlock,function(e){e[e.SawTooth=0]="SawTooth",e[e.Square=1]="Square",e[e.Triangle=2]="Triangle"}(ty||(ty={}));let WaveBlock=class WaveBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.kind=ty.SawTooth,this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];switch(this.kind){case ty.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); -`;break;case ty.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); -`;break;case ty.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; -`}return this}serialize(){let e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}};h["BABYLON.WaveBlock"]=WaveBlock;let GradientBlockColorStep=class GradientBlockColorStep{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}};let GradientBlock=class GradientBlock extends NodeMaterialBlock{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,e_.Neutral),this.colorSteps=[new GradientBlockColorStep(0,math_color_Color3.Black()),new GradientBlockColorStep(1,math_color_Color3.White())],this.onValueChangedObservable=new observable_Observable,this.registerInput("gradient",ed.AutoDetect),this.registerOutput("output",ed.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Float|ed.Vector2|ed.Vector3|ed.Vector4|ed.Color3|ed.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){let t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.); -`;return}let i=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; -`,e.compilationString+=`float ${r}; -`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==ed.Float&&(s+=".x");for(let t=1;ti.getWorldMatrix().determinant()?-1:1)}_buildBlock(e){return e.target===e_.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}};h["BABYLON.AnisotropyBlock"]=AnisotropyBlock;let ReflectionBlock=class ReflectionBlock extends ReflectionTextureBaseBlock{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",ed.AutoDetect,!1,e_.Vertex),this.registerInput("world",ed.Matrix,!1,e_.Vertex),this.registerInput("color",ed.Color3,!0,e_.Fragment),this.registerOutput("reflection",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",this,ef.Output,ReflectionBlock,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!r.invertZ:r.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",r.gammaSpace,!0),i.setValue("RGBDREFLECTION",r.isRGBD,!0),r&&r.coordinatesMode!==texture_Texture.SKYBOX_MODE&&r.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,r){super.bind(e,t,i);let s=this._getTexture();if(!s||!r)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);let a=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,a,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,a,math_scalar_Scalar.Log2(a));let n=r.materialDefines,o=s.sphericalPolynomial;if(n.USESPHERICALFROMREFLECTIONMAP&&o){if(n.SPHERICAL_HARMONICS){let t=o.preScaledHarmonics;e.setVector3("vSphericalL00",t.l00),e.setVector3("vSphericalL1_1",t.l1_1),e.setVector3("vSphericalL10",t.l10),e.setVector3("vSphericalL11",t.l11),e.setVector3("vSphericalL2_2",t.l2_2),e.setVector3("vSphericalL2_1",t.l2_1),e.setVector3("vSphericalL20",t.l20),e.setVector3("vSphericalL21",t.l21),e.setVector3("vSphericalL22",t.l22)}else e.setFloat3("vSphericalX",o.x.x,o.x.y,o.x.z),e.setFloat3("vSphericalY",o.y.x,o.y.y,o.y.z),e.setFloat3("vSphericalZ",o.z.x,o.z.y,o.z.z),e.setFloat3("vSphericalXX_ZZ",o.xx.x-o.zz.x,o.xx.y-o.zz.y,o.xx.z-o.zz.z),e.setFloat3("vSphericalYY_ZZ",o.yy.x-o.zz.x,o.yy.y-o.zz.y,o.yy.z-o.zz.z),e.setFloat3("vSphericalZZ",o.zz.x,o.zz.y,o.zz.z),e.setFloat3("vSphericalXY",o.xy.x,o.xy.y,o.xy.z),e.setFloat3("vSphericalYZ",o.yz.x,o.yz.y,o.yz.z),e.setFloat3("vSphericalZX",o.zx.x,o.zx.y,o.zx.z)}}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});let i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) - vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; - #ifdef ${this._defineOppositeZ} - ${i}.z *= -1.0; - #endif - ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i}); - #endif -`}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",` - #ifdef ${this._define3DName} - #define sampleReflection(s, c) textureCube(s, c) - #else - #define sampleReflection(s, c) texture2D(s, c) - #endif -`,`//${this.name}`),e._emitFunction("sampleReflectionLod",` - #ifdef ${this._define3DName} - #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) - #else - #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) - #endif -`,`//${this.name}`);let r=` - vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { - ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)} - return ${this._reflectionVectorName}; - } -`;return e._emitFunction("computeReflectionCoordsPBR",r,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION - vec2 ${this._vReflectionInfosName} = vec2(1., 0.); - - reflectionOutParams reflectionOut; - - reflectionBlock( - ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz, - ${t}, - alphaG, - ${this._vReflectionMicrosurfaceInfosName}, - ${this._vReflectionInfosName}, - ${this.reflectionColor}, - #ifdef ANISOTROPIC - anisotropicOut, - #endif - #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) - NdotVUnclamped, - #endif - #ifdef ${this._defineLinearSpecularReflection} - roughness, - #endif - #ifdef ${this._define3DName} - ${this._cubeSamplerName}, - #else - ${this._2DSamplerName}, - #endif - #if defined(NORMAL) && defined(USESPHERICALINVERTEX) - ${this._vEnvironmentIrradianceName}, - #endif - #ifdef USESPHERICALFROMREFLECTIONMAP - #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) - ${this._reflectionMatrixName}, - #endif - #endif - #ifdef USEIRRADIANCEMAP - irradianceSampler, // ** not handled ** - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${this._define3DName} - ${this._cubeSamplerName}, - ${this._cubeSamplerName}, - #else - ${this._2DSamplerName}, - ${this._2DSamplerName}, - #endif - #endif - #ifdef REALTIME_FILTERING - ${this._vReflectionFilteringInfoName}, - #endif - reflectionOut - ); - #endif -`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==e_.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace}; -`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics}; -${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment}; -`}serialize(){var e,t;let i=super.serialize();return i.useSphericalHarmonics=this.useSphericalHarmonics,i.forceIrradianceInFragment=this.forceIrradianceInFragment,i.gammaSpace=null===(t=null===(e=this.texture)||void 0===e?void 0:e.gammaSpace)||void 0===t||t,i}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}};__decorate([editableInPropertyPage("Spherical Harmonics",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],ReflectionBlock.prototype,"useSphericalHarmonics",void 0),__decorate([editableInPropertyPage("Force irradiance in fragment",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],ReflectionBlock.prototype,"forceIrradianceInFragment",void 0),h["BABYLON.ReflectionBlock"]=ReflectionBlock;let ClearCoatBlock=class ClearCoatBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",ed.Float,!1,e_.Fragment),this.registerInput("roughness",ed.Float,!0,e_.Fragment),this.registerInput("indexOfRefraction",ed.Float,!0,e_.Fragment),this.registerInput("normalMapColor",ed.Color3,!0,e_.Fragment),this.registerInput("uv",ed.Vector2,!0,e_.Fragment),this.registerInput("tintColor",ed.Color3,!0,e_.Fragment),this.registerInput("tintAtDistance",ed.Float,!0,e_.Fragment),this.registerInput("tintThickness",ed.Float,!0,e_.Fragment),this.registerInput("worldTangent",ed.Vector4,!0),this.registerInput("worldNormal",ed.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(ed.Color4|ed.Vector4|ed.Vector3),this.registerInput("TBN",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,ef.Input,TBNBlock,"TBNBlock")),this.registerOutput("clearcoat",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",this,ef.Output,ClearCoatBlock,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new InputBlock("ClearCoat intensity",e_.Fragment,ed.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var r,s;super.bind(e,t,i);let a=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,n=1-a,o=1+a,l=Math.pow(-n/o,2);e.setFloat4("vClearCoatRefractionParams",l,1/a,n,o);let h=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,c=(null==h?void 0:h.perturbedNormal.isConnected)?h.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",(null==c?void 0:c.invertX)?1:-1,(null==c?void 0:c.invertY)?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",(null==c?void 0:c.invertX)?-1:1,(null==c?void 0:c.invertY)?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_generateTBNSpace(e,t,i){let r="",s=`//${this.name}`,a=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let n={search:/defined\(TANGENT\)/g,replace:a.isConnected?"defined(TANGENT)":"defined(IGNORE)"},o=this.TBN;return o.isConnected?e.compilationString+=` - #ifdef TBNBLOCK - mat3 vTBN = ${o.associatedVariableName}; - #endif - `:a.isConnected&&(r+=`vec3 tbnNormal = normalize(${i}.xyz); -vec3 tbnTangent = normalize(${a.associatedVariableName}.xyz); -vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; -mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); -`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[n]}),r}static GetCode(e,t,i,r,s,a,n){let o="",l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",h=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",c=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",u=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",_=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",p=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");let i=t.worldNormal;o+=`vec3 vGeometricNormaClearCoatW = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"}; -`}else o+=`vec3 vGeometricNormaClearCoatW = geometricNormalW; -`;return s&&t&&(o+=t._generateTBNSpace(e,r,n),a=t.worldTangent.isConnected),o+=`clearcoatOutParams clearcoatOut; - - #ifdef CLEARCOAT - vec2 vClearCoatParams = vec2(${l}, ${h}); - vec4 vClearCoatTintParams = vec4(${d}, ${_}); - - clearcoatBlock( - ${r}.xyz, - vGeometricNormaClearCoatW, - viewDirectionW, - vClearCoatParams, - specularEnvironmentR0, - #ifdef CLEARCOAT_TEXTURE - vec2(0.), - #endif - #ifdef CLEARCOAT_TINT - vClearCoatTintParams, - ${p}, - vClearCoatRefractionParams, - #ifdef CLEARCOAT_TINT_TEXTURE - vec4(0.), - #endif - #endif - #ifdef CLEARCOAT_BUMP - vec2(0., 1.), - vec4(${c}, 0.), - ${u}, - #if defined(${a?"TANGENT":"IGNORE"}) && defined(NORMAL) - vTBN, - #else - vClearCoatTangentSpaceParams, - #endif - #ifdef OBJECTSPACE_NORMALMAP - normalMatrix, - #endif - #endif - #if defined(FORCENORMALFORWARD) && defined(NORMAL) - faceNormal, - #endif - #ifdef REFLECTION - ${null==i?void 0:i._vReflectionMicrosurfaceInfosName}, - ${null==i?void 0:i._vReflectionInfosName}, - ${null==i?void 0:i.reflectionColor}, - vLightingIntensity, - #ifdef ${null==i?void 0:i._define3DName} - ${null==i?void 0:i._cubeSamplerName}, - #else - ${null==i?void 0:i._2DSamplerName}, - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${null==i?void 0:i._define3DName} - ${null==i?void 0:i._cubeSamplerName}, - ${null==i?void 0:i._cubeSamplerName}, - #else - ${null==i?void 0:i._2DSamplerName}, - ${null==i?void 0:i._2DSamplerName}, - #endif - #endif - #endif - #if defined(ENVIRONMENTBRDF) && !defined(${null==i?void 0:i._defineSkyboxName}) - #ifdef RADIANCEOCCLUSION - ambientMonochrome, - #endif - #endif - #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) - (gl_FrontFacing ? 1. : -1.), - #endif - clearcoatOut - ); - #else - clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; - #endif -`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===e_.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange}; -`}serialize(){let e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.remapF0OnInterfaceChange=null===(r=e.remapF0OnInterfaceChange)||void 0===r||r}};__decorate([editableInPropertyPage("Remap F0 on interface change",em.Boolean,"ADVANCED")],ClearCoatBlock.prototype,"remapF0OnInterfaceChange",void 0),h["BABYLON.ClearCoatBlock"]=ClearCoatBlock;let IridescenceBlock=class IridescenceBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._isUnique=!0,this.registerInput("intensity",ed.Float,!0,e_.Fragment),this.registerInput("indexOfRefraction",ed.Float,!0,e_.Fragment),this.registerInput("thickness",ed.Float,!0,e_.Fragment),this.registerOutput("iridescence",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("iridescence",this,ef.Output,IridescenceBlock,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new InputBlock("Iridescence intensity",e_.Fragment,ed.Float);e.value=1,e.output.connectTo(this.intensity);let t=new InputBlock("Iridescence ior",e_.Fragment,ed.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);let i=new InputBlock("Iridescence thickness",e_.Fragment,ed.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t=(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1.",i=(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction,r=(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness;return`iridescenceOutParams iridescenceOut; - - #ifdef IRIDESCENCE - iridescenceBlock( - vec4(${t}, ${i}, 1., ${r}), - NdotV, - specularEnvironmentR0, - #ifdef CLEARCOAT - NdotVUnclamped, - #endif - iridescenceOut - ); - - float iridescenceIntensity = iridescenceOut.iridescenceIntensity; - specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; - #endif -`}_buildBlock(e){return e.target===e_.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){let e=super.serialize();return e}_deserialize(e,t,i){super._deserialize(e,t,i)}};h["BABYLON.IridescenceBlock"]=IridescenceBlock;let RefractionBlock=class RefractionBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",ed.Float,!1,e_.Fragment),this.registerInput("tintAtDistance",ed.Float,!0,e_.Fragment),this.registerInput("volumeIndexOfRefraction",ed.Float,!0,e_.Fragment),this.registerOutput("refraction",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",this,ef.Output,RefractionBlock,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=()=>!0){if(!this.intensity.isConnected){let e=new InputBlock("Refraction intensity",e_.Fragment,ed.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(ev.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){var r,s,a,n;super.bind(e,t,i);let o=this._getTexture();if(!o)return;o.isCube?e.setTexture(this._cubeSamplerName,o):e.setTexture(this._2DSamplerName,o),e.setMatrix(this._refractionMatrixName,o.getRefractionTextureMatrix());let l=1;!o.isCube&&o.depth&&(l=o.depth);let h=null!==(n=null!==(s=null===(r=this.volumeIndexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:null===(a=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===a?void 0:a.value)&&void 0!==n?n:1.5;e.setFloat4(this._vRefractionInfosName,o.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset,1/h);let c=o.getSize().width;e.setFloat2(this._vRefractionFilteringInfoName,c,math_scalar_Scalar.Log2(c)),o.boundingBoxSize&&(e.setVector3("vRefractionPosition",o.boundingBoxPosition),e.setVector3("vRefractionSize",o.boundingBoxSize))}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName} -`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; -`,e._samplerDeclaration+=`#else -`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; -`,e._samplerDeclaration+=`#endif -`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",` - #ifdef ${this._define3DName} - #define sampleRefraction(s, c) textureCube(s, c) - #else - #define sampleRefraction(s, c) texture2D(s, c) - #endif -`,`//${this.name}`),e._emitFunction("sampleRefractionLod",` - #ifdef ${this._define3DName} - #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) - #else - #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) - #endif -`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=(this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}"); -`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); -`)+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; -${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; -${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; -`}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=cubeTexture_CubeTexture.Parse(e.texture,t,i):this.texture=texture_Texture.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}};__decorate([editableInPropertyPage("Link refraction to transparency",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"linkRefractionWithTransparency",void 0),__decorate([editableInPropertyPage("Invert refraction Y",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"invertRefractionY",void 0),__decorate([editableInPropertyPage("Use thickness as depth",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"useThicknessAsDepth",void 0),h["BABYLON.RefractionBlock"]=RefractionBlock;let SubSurfaceBlock=class SubSurfaceBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Fragment),this._isUnique=!0,this.registerInput("thickness",ed.Float,!1,e_.Fragment),this.registerInput("tintColor",ed.Color3,!0,e_.Fragment),this.registerInput("translucencyIntensity",ed.Float,!0,e_.Fragment),this.registerInput("translucencyDiffusionDist",ed.Color3,!0,e_.Fragment),this.registerInput("refraction",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",this,ef.Input,RefractionBlock,"RefractionBlock")),this.registerOutput("subsurface",ed.Object,e_.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",this,ef.Output,SubSurfaceBlock,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){let e=new InputBlock("SubSurface thickness",e_.Fragment,ed.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0)}static GetCode(e,t,i,r){var s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x;let b=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",T=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",S=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",C=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",E=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,y=(null==E?void 0:E.tintAtDistance.isConnected)?E.tintAtDistance.associatedVariableName:"1.",R=(null==E?void 0:E.intensity.isConnected)?E.intensity.associatedVariableName:"1.",P=(null==E?void 0:E.view.isConnected)?E.view.associatedVariableName:"";return""+(null!==(a=null==E?void 0:E.getCode(e))&&void 0!==a?a:"")+`subSurfaceOutParams subSurfaceOut; - - #ifdef SUBSURFACE - vec2 vThicknessParam = vec2(0., ${b}); - vec4 vTintColor = vec4(${T}, ${y}); - vec3 vSubSurfaceIntensity = vec3(${R}, ${S}, 0.); - - subSurfaceBlock( - vSubSurfaceIntensity, - vThicknessParam, - vTintColor, - normalW, - specularEnvironmentReflectance, - #ifdef SS_THICKNESSANDMASK_TEXTURE - vec4(0.), - #endif - #ifdef REFLECTION - #ifdef SS_TRANSLUCENCY - ${null==i?void 0:i._reflectionMatrixName}, - #ifdef USESPHERICALFROMREFLECTIONMAP - #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) - reflectionOut.irradianceVector, - #endif - #if defined(REALTIME_FILTERING) - ${null==i?void 0:i._cubeSamplerName}, - ${null==i?void 0:i._vReflectionFilteringInfoName}, - #endif - #endif - #ifdef USEIRRADIANCEMAP - irradianceSampler, - #endif - #endif - #endif - #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) - surfaceAlbedo, - #endif - #ifdef SS_REFRACTION - ${r}.xyz, - viewDirectionW, - ${P}, - ${null!==(n=null==E?void 0:E._vRefractionInfosName)&&void 0!==n?n:""}, - ${null!==(o=null==E?void 0:E._refractionMatrixName)&&void 0!==o?o:""}, - ${null!==(l=null==E?void 0:E._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""}, - vLightingIntensity, - #ifdef SS_LINKREFRACTIONTOTRANSPARENCY - alpha, - #endif - #ifdef ${null!==(h=null==E?void 0:E._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"} - NdotVUnclamped, - #endif - #ifdef ${null!==(c=null==E?void 0:E._defineLinearSpecularRefraction)&&void 0!==c?c:"IGNORE"} - roughness, - #endif - alphaG, - #ifdef ${null!==(u=null==E?void 0:E._define3DName)&&void 0!==u?u:"IGNORE"} - ${null!==(d=null==E?void 0:E._cubeSamplerName)&&void 0!==d?d:""}, - #else - ${null!==(_=null==E?void 0:E._2DSamplerName)&&void 0!==_?_:""}, - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${null!==(p=null==E?void 0:E._define3DName)&&void 0!==p?p:"IGNORE"} - ${null!==(f=null==E?void 0:E._cubeSamplerName)&&void 0!==f?f:""}, - ${null!==(m=null==E?void 0:E._cubeSamplerName)&&void 0!==m?m:""}, - #else - ${null!==(g=null==E?void 0:E._2DSamplerName)&&void 0!==g?g:""}, - ${null!==(v=null==E?void 0:E._2DSamplerName)&&void 0!==v?v:""}, - #endif - #endif - #ifdef ANISOTROPIC - anisotropicOut, - #endif - #ifdef REALTIME_FILTERING - ${null!==(x=null==E?void 0:E._vRefractionFilteringInfoName)&&void 0!==x?x:""}, - #endif - #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC - vRefractionPosition, - vRefractionSize, - #endif - #endif - #ifdef SS_TRANSLUCENCY - ${C}, - #endif - subSurfaceOut - ); - - #ifdef SS_REFRACTION - surfaceAlbedo = subSurfaceOut.surfaceAlbedo; - #ifdef SS_LINKREFRACTIONTOTRANSPARENCY - alpha = subSurfaceOut.alpha; - #endif - #endif - #else - subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; - #endif -`}_buildBlock(e){return e.target===e_.Fragment&&e.sharedData.blocksWithDefines.push(this),this}};h["BABYLON.SubSurfaceBlock"]=SubSurfaceBlock;let a3={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};let PBRMetallicRoughnessBlock=class PBRMetallicRoughnessBlock extends NodeMaterialBlock{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?e_.Fragment:e_.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?e_.Fragment:e_.Vertex}constructor(e){super(e,e_.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=math_color_Color3.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",ed.Vector4,!1,e_.Vertex),this.registerInput("worldNormal",ed.Vector4,!1,e_.Fragment),this.registerInput("view",ed.Matrix,!1),this.registerInput("cameraPosition",ed.Vector3,!1,e_.Fragment),this.registerInput("perturbedNormal",ed.Vector4,!0,e_.Fragment),this.registerInput("baseColor",ed.Color3,!0,e_.Fragment),this.registerInput("metallic",ed.Float,!1,e_.Fragment),this.registerInput("roughness",ed.Float,!1,e_.Fragment),this.registerInput("ambientOcc",ed.Float,!0,e_.Fragment),this.registerInput("opacity",ed.Float,!0,e_.Fragment),this.registerInput("indexOfRefraction",ed.Float,!0,e_.Fragment),this.registerInput("ambientColor",ed.Color3,!0,e_.Fragment),this.registerInput("reflection",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",this,ef.Input,ReflectionBlock,"ReflectionBlock")),this.registerInput("clearcoat",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",this,ef.Input,ClearCoatBlock,"ClearCoatBlock")),this.registerInput("sheen",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("sheen",this,ef.Input,SheenBlock,"SheenBlock")),this.registerInput("subsurface",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",this,ef.Input,SubSurfaceBlock,"SubSurfaceBlock")),this.registerInput("anisotropy",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("anisotropy",this,ef.Input,AnisotropyBlock,"AnisotropyBlock")),this.registerInput("iridescence",ed.Object,!0,e_.Fragment,new NodeMaterialConnectionPointCustomObject("iridescence",this,ef.Input,IridescenceBlock,"IridescenceBlock")),this.registerOutput("ambientClr",ed.Color3,e_.Fragment),this.registerOutput("diffuseDir",ed.Color3,e_.Fragment),this.registerOutput("specularDir",ed.Color3,e_.Fragment),this.registerOutput("clearcoatDir",ed.Color3,e_.Fragment),this.registerOutput("sheenDir",ed.Color3,e_.Fragment),this.registerOutput("diffuseInd",ed.Color3,e_.Fragment),this.registerOutput("specularInd",ed.Color3,e_.Fragment),this.registerOutput("clearcoatInd",ed.Color3,e_.Fragment),this.registerOutput("sheenInd",ed.Color3,e_.Fragment),this.registerOutput("refraction",ed.Color3,e_.Fragment),this.registerOutput("lighting",ed.Color3,e_.Fragment),this.registerOutput("shadow",ed.Float,e_.Fragment),this.registerOutput("alpha",ed.Float,e_.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(ev.CameraPosition),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===ev.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(ev.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));let r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",0>r.indexOf(".")?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);let s=e.getScene(),a=s.getEngine();if(a._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty){if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};MaterialHelper.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else MaterialHelper.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,MaterialHelper.PrepareDefinesForMultiview(s,i)}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;MaterialHelper.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return(!this._environmentBRDFTexture||!!this._environmentBRDFTexture.isReady())&&(!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var r,s;if(!i)return;let a=i.getScene();this.light?MaterialHelper.BindLight(this.light,this._lightId,a,e,!0):MaterialHelper.BindLights(a,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);let n=this._scene.ambientColor;n&&e.setColor3("ambientFromScene",n);let o=a.useRightHandedSystem===(null!=a._mirroredCameraPosition);e.setFloat(this._invertNormalName,o?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);let l=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((l-1)/(l+1),2)*this._metallicF0Factor,TmpColors.Color3[0]);let h=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,TmpColors.Color3[0],h),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;let r=this.worldPosition,s=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));let a="v_"+r.associatedVariableName;e._emitVaryingFromString(a,"vec4")&&(e.compilationString+=`${a} = ${r.associatedVariableName}; -`);let n=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;n&&(n.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==n?void 0:n.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 -`,e._injectAtEnd+=`vClipSpacePosition = gl_Position; -`,e._injectAtEnd+=`#endif -`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:r.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${r.associatedVariableName}; -`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; -`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; -`,t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+`albedoOpacityBlock( - vec4(${t}, 1.), - #ifdef ALBEDO - vec4(1.), - vec2(1., 1.), - #endif - #ifdef OPACITY - vec4(${i}), - vec2(1., 1.), - #endif - albedoOpacityOut - ); - - vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; - float alpha = albedoOpacityOut.alpha; -`}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; -`,t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+`ambientOcclusionBlock( - #ifdef AMBIENT - vec3(${t}), - vec4(0., 1.0, 1.0, 0.), - #endif - aoOut - ); -`}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; -`;return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo; - - reflectivityBlock( - vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), - #ifdef METALLICWORKFLOW - surfaceAlbedo, - ${this._vMetallicReflectanceFactorsName}, - #endif - #ifdef REFLECTIVITY - vec3(0., 0., 1.), - vec4(1.), - #endif - #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) - aoOut.ambientOcclusionColor, - #endif - #ifdef MICROSURFACEMAP - microSurfaceTexel, <== not handled! - #endif - reflectivityOut - ); - - float microSurface = reflectivityOut.microSurface; - float roughness = reflectivityOut.roughness; - - #ifdef METALLICWORKFLOW - surfaceAlbedo = reflectivityOut.surfaceAlbedo; - #endif - #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) - aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; - #endif -`}_buildBlock(e){var t,i,r,s,a,n,o,l,h,c,u,d,_,p,f,m,g,v,x,b,T,S,C,E,y,R,P,A,M,I,D,O,B,N,F,w,L,V,U,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this._scene));let z=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;if(z&&(z.worldPositionConnectionPoint=this.worldPosition,z.cameraPositionConnectionPoint=this.cameraPosition,z.worldNormalConnectionPoint=this.worldNormal,z.viewConnectionPoint=this.view),e.target!==e_.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);let W=`//${this.name}`,H=this.perturbedNormal,X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X}; -`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 -`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); -`,e.compilationString+=`#endif -`):X="v_"+X,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",W),e._emitFunctionFromInclude("importanceSampling",W),e._emitFunctionFromInclude("pbrHelperFunctions",W),e._emitFunctionFromInclude("imageProcessingDeclaration",W),e._emitFunctionFromInclude("imageProcessingFunctions",W),e._emitFunctionFromInclude("shadowsFragmentFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",W),e._emitFunctionFromInclude("pbrBRDFFunctions",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(i=null==z?void 0:z._defineSkyboxName)&&void 0!==i?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",W),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",W),e._emitFunctionFromInclude("pbrBlockReflectivity",W),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",W),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",W),e._emitFunctionFromInclude("pbrBlockAnisotropic",W),e._emitUniformFromString("vLightingIntensity","vec4"),(null==z?void 0:z.generateOnlyFragmentCode)&&(e.compilationString+=z.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName}); -`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz); -`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; -`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"}; -`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",W),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",W),e.compilationString+=`#ifdef UNLIT - vec3 diffuseBase = vec3(1., 1., 1.); - #else -`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(r=null==z?void 0:z._defineSkyboxName)&&void 0!==r?r:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});let Y=this.anisotropy.isConnected?null===(a=this.anisotropy.connectedPoint)||void 0===a?void 0:a.ownerBlock:null;Y&&(Y.worldPositionConnectionPoint=this.worldPosition,Y.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=Y.getCode(e,!this.perturbedNormal.isConnected)),z&&z.hasTexture&&(e.compilationString+=z.getCode(e,Y?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(n=null==z?void 0:z._define3DName)&&void 0!==n?n:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(o=null==z?void 0:z._defineOppositeZ)&&void 0!==o?o:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(l=null==z?void 0:z._defineProjectionName)&&void 0!==l?l:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(h=null==z?void 0:z._defineSkyboxName)&&void 0!==h?h:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(c=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==c?c:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(u=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==u?u:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(d=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==d?d:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});let j=this.sheen.isConnected?null===(_=this.sheen.connectedPoint)||void 0===_?void 0:_.ownerBlock:null;j&&(e.compilationString+=j.getCode(z)),e._emitFunctionFromInclude("pbrBlockSheen",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(p=null==z?void 0:z._define3DName)&&void 0!==p?p:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(f=null==z?void 0:z._defineSkyboxName)&&void 0!==f?f:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(m=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==m?m:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(g=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==g?g:"LINEARSPECULARREFLECTION"}]});let K=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=IridescenceBlock.GetCode(K),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});let q=this.clearcoat.isConnected?null===(x=this.clearcoat.connectedPoint)||void 0===x?void 0:x.ownerBlock:null,$=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Q=this.perturbedNormal.isConnected&&(null===(T=(null===(b=this.perturbedNormal.connectedPoint)||void 0===b?void 0:b.ownerBlock).worldTangent)||void 0===T?void 0:T.isConnected),Z=this.anisotropy.isConnected&&(null===(S=this.anisotropy.connectedPoint)||void 0===S?void 0:S.ownerBlock).worldTangent.isConnected,J=Q||!this.perturbedNormal.isConnected&&Z;e.compilationString+=ClearCoatBlock.GetCode(e,q,z,X,$,J,this.worldNormal.associatedVariableName),$&&(J=null!==(C=null==q?void 0:q.worldTangent.isConnected)&&void 0!==C&&C),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(E=null==z?void 0:z._define3DName)&&void 0!==E?E:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(y=null==z?void 0:z._defineOppositeZ)&&void 0!==y?y:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(R=null==z?void 0:z._defineProjectionName)&&void 0!==R?R:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(P=null==z?void 0:z._defineSkyboxName)&&void 0!==P?P:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(A=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==A?A:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(M=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==M?M:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:J?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(I=null==z?void 0:z._defineSkyboxName)&&void 0!==I?I:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(D=null==z?void 0:z._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});let ee=this.subsurface.isConnected?null===(O=this.subsurface.connectedPoint)||void 0===O?void 0:O.ownerBlock:null,et=this.subsurface.isConnected?null===(N=(null===(B=this.subsurface.connectedPoint)||void 0===B?void 0:B.ownerBlock).refraction.connectedPoint)||void 0===N?void 0:N.ownerBlock:null;et&&(et.viewConnectionPoint=this.view,et.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=SubSurfaceBlock.GetCode(e,ee,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(F=null==z?void 0:z._define3DName)&&void 0!==F?F:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(w=null==z?void 0:z._defineOppositeZ)&&void 0!==w?w:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(L=null==z?void 0:z._defineProjectionName)&&void 0!==L?L:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(V=null==et?void 0:et._define3DName)&&void 0!==V?V:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(U=null==et?void 0:et._defineLODRefractionAlpha)&&void 0!==U?U:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==et?void 0:et._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==et?void 0:et._defineOppositeZ)&&void 0!==G?G:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",W),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:X+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{repeatKey:"maxSimultaneousLights",replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",W),e.compilationString+=`#endif -`;let ei=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",er=pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();for(let t of(-1===er.indexOf(".")&&(er+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:ei+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:er}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",W,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",W,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",W,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:X},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]}),this._outputs))if(t.hasEndpoints){let i=a3[t.name];if(i){let[r,s]=i;s&&(e.compilationString+=`#if ${s} -`),e.compilationString+=`${this._declareOutput(t,e)} = ${r}; -`,s&&(e.compilationString+=`#else -`,e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.); -`,e.compilationString+=`#endif -`)}else console.error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; -${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; -${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; -${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; -${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; -${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; -${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; -${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; -${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; -${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; -${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; -${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; -${this._codeVariableName}.unlit = ${this.unlit}; -${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; -${this._codeVariableName}.debugMode = ${this.debugMode}; -${this._codeVariableName}.debugLimit = ${this.debugLimit}; -${this._codeVariableName}.debugFactor = ${this.debugFactor}; -`}serialize(){let e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){var r,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(r=e.lightFalloff)&&void 0!==r?r:0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=null!==(s=e.realTimeFilteringQuality)&&void 0!==s?s:8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}};__decorate([editableInPropertyPage("Direct lights",em.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"directIntensity",void 0),__decorate([editableInPropertyPage("Environment lights",em.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"environmentIntensity",void 0),__decorate([editableInPropertyPage("Specular highlights",em.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"specularIntensity",void 0),__decorate([editableInPropertyPage("Light falloff",em.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF},{label:"Standard",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD}]})],PBRMetallicRoughnessBlock.prototype,"lightFalloff",void 0),__decorate([editableInPropertyPage("Alpha Testing",em.Boolean,"OPACITY")],PBRMetallicRoughnessBlock.prototype,"useAlphaTest",void 0),__decorate([editableInPropertyPage("Alpha CutOff",em.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"alphaTestCutoff",void 0),__decorate([editableInPropertyPage("Alpha blending",em.Boolean,"OPACITY")],PBRMetallicRoughnessBlock.prototype,"useAlphaBlending",void 0),__decorate([editableInPropertyPage("Radiance over alpha",em.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useRadianceOverAlpha",void 0),__decorate([editableInPropertyPage("Specular over alpha",em.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useSpecularOverAlpha",void 0),__decorate([editableInPropertyPage("Specular anti-aliasing",em.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"enableSpecularAntiAliasing",void 0),__decorate([editableInPropertyPage("Realtime filtering",em.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"realTimeFiltering",void 0),__decorate([editableInPropertyPage("Realtime filtering quality",em.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],PBRMetallicRoughnessBlock.prototype,"realTimeFilteringQuality",void 0),__decorate([editableInPropertyPage("Energy Conservation",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useEnergyConservation",void 0),__decorate([editableInPropertyPage("Radiance occlusion",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useRadianceOcclusion",void 0),__decorate([editableInPropertyPage("Horizon occlusion",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useHorizonOcclusion",void 0),__decorate([editableInPropertyPage("Unlit",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"unlit",void 0),__decorate([editableInPropertyPage("Force normal forward",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"forceNormalForward",void 0),__decorate([editableInPropertyPage("Generate only fragment code",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged}})],PBRMetallicRoughnessBlock.prototype,"generateOnlyFragmentCode",void 0),__decorate([editableInPropertyPage("Debug mode",em.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],PBRMetallicRoughnessBlock.prototype,"debugMode",void 0),__decorate([editableInPropertyPage("Split position",em.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"debugLimit",void 0),__decorate([editableInPropertyPage("Output factor",em.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"debugFactor",void 0),h["BABYLON.PBRMetallicRoughnessBlock"]=PBRMetallicRoughnessBlock;let ModBlock=class ModBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("left",ed.AutoDetect),this.registerInput("right",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}};h["BABYLON.ModBlock"]=ModBlock;let MatrixBuilderBlock=class MatrixBuilderBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("row0",ed.Vector4),this.registerInput("row1",ed.Vector4),this.registerInput("row2",ed.Vector4),this.registerInput("row3",ed.Vector4),this.registerOutput("output",ed.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){let e=new InputBlock("row0");e.value=new math_vector_Vector4(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){let e=new InputBlock("row1");e.value=new math_vector_Vector4(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){let e=new InputBlock("row2");e.value=new math_vector_Vector4(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){let e=new InputBlock("row3");e.value=new math_vector_Vector4(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,a=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${a.associatedVariableName}); -`,this}};h["BABYLON.MatrixBuilder"]=MatrixBuilderBlock,function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(tR||(tR={}));let ConditionalBlock=class ConditionalBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.condition=tR.LessThan,this.registerInput("a",ed.Float),this.registerInput("b",ed.Float),this.registerInput("true",ed.AutoDetect,!0),this.registerInput("false",ed.AutoDetect,!0),this.registerOutput("output",ed.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=ed.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case tR.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case tR.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case tR.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case tR.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case tR.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case tR.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case tR.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${r}; -`;break;case tR.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${r}; -`;break;case tR.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${r}; -`}return this}serialize(){let e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${tR[this.condition]}; -`;return e}};h["BABYLON.ConditionalBlock"]=ConditionalBlock;let CloudBlock=class CloudBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.octaves=6,this.registerInput("seed",ed.AutoDetect),this.registerInput("chaos",ed.AutoDetect,!0),this.registerInput("offsetX",ed.Float,!0),this.registerInput("offsetY",ed.Float,!0),this.registerInput("offsetZ",ed.Float,!0),this.registerOutput("output",ed.Float),this._inputs[0].acceptedConnectionPointTypes.push(ed.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(ed.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var t,i;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let r=` - - float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } - - // Based on Morgan McGuire @morgan3d - // https://www.shadertoy.com/view/4dS3Wd - float cloudNoise(in vec2 x, in vec2 chaos) { - vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); - - vec2 i = floor(x); - vec2 f = fract(x); - - float n = dot(i, step); - - vec2 u = f * f * (3.0 - 2.0 * f); - return mix( - mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), - mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), - u.y - ); - } - - float cloudNoise(in vec3 x, in vec3 chaos) { - vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); - - vec3 i = floor(x); - vec3 f = fract(x); - - float n = dot(i, step); - - vec3 u = f * f * (3.0 - 2.0 * f); - return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), - mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), - mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), - mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); - }`,s=` - float fbm(in vec2 st, in vec2 chaos) { - // Initial values - float value = 0.0; - float amplitude = .5; - float frequency = 0.; - - // Loop of octaves - for (int i = 0; i < OCTAVES; i++) { - value += amplitude * cloudNoise(st, chaos); - st *= 2.0; - amplitude *= 0.5; - } - return value; - } - - float fbm(in vec3 x, in vec3 chaos) { - // Initial values - float value = 0.0; - float amplitude = 0.5; - for (int i = 0; i < OCTAVES; ++i) { - value += amplitude * cloudNoise(x, chaos); - x = x * 2.0; - amplitude *= 0.5; - } - return value; - }`,a=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",r,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,s.replace(/fbm/gi,a).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");let n=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===ed.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${n} = ${this.seed.associatedVariableName}; -`,this.offsetX.isConnected&&(e.compilationString+=`${n}.x += 0.1 * ${this.offsetX.associatedVariableName}; -`),this.offsetY.isConnected&&(e.compilationString+=`${n}.y += 0.1 * ${this.offsetY.associatedVariableName}; -`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${n}.z += 0.1 * ${this.offsetZ.associatedVariableName}; -`);let l="";return l=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===ed.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${a}(${n}, ${l}); -`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; -`;return e}serialize(){let e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}};__decorate([editableInPropertyPage("Octaves",em.Int)],CloudBlock.prototype,"octaves",void 0),h["BABYLON.CloudBlock"]=CloudBlock;let VoronoiNoiseBlock=class VoronoiNoiseBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("seed",ed.Vector2),this.registerInput("offset",ed.Float),this.registerInput("density",ed.Float),this.registerOutput("output",ed.Float),this.registerOutput("cells",ed.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){ - mat2 m = mat2(15.27, 47.63, 99.41, 89.98); - vec2 uv = fract(sin(m * seed) * 46839.32); - return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); - } - `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ - vec2 g = floor(seed * density); - vec2 f = fract(seed * density); - float t = 8.0; - vec3 res = vec3(8.0, 0.0, 0.0); - - for(int y=-1; y<=1; y++) - { - for(int x=-1; x<=1; x++) - { - vec2 lattice = vec2(x,y); - vec2 randomOffset = voronoiRandom(lattice + g, offset); - float d = distance(lattice + randomOffset, f); - if(d < res.x) - { - res = vec3(d, randomOffset.x, randomOffset.y); - outValue = res.x; - cells = res.y; - } - } - } - } - `,e._emitFunction("voronoi",t,"// Voronoi");let i=e._getFreeVariableName("tempOutput"),r=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; -`,e.compilationString+=`float ${r} = 0.0; -`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${r}); -`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; -`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${r}; -`),this}};h["BABYLON.VoronoiNoiseBlock"]=VoronoiNoiseBlock;let ElbowBlock=class ElbowBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==e_.VertexAndFragment)return t.target;if(e.connectedPoint.target!==e_.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName}; -`,this}};h["BABYLON.ElbowBlock"]=ElbowBlock;let TriPlanarBlock=class TriPlanarBlock extends NodeMaterialBlock{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?(null===(e=this.sourceY.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(null===(e=this.sourceZ)||void 0===e?void 0:e.isConnected)?(null===(t=this.sourceY.connectedPoint)||void 0===t?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return(null==e?void 0:e.isConnected)?e.connectedPoint.ownerBlock:null}get samplerName(){let e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceY))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get samplerZName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceZ))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:engineStore_EngineStore.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,e_.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",ed.AutoDetect,!1),this.registerInput("normal",ed.AutoDetect,!1),this.registerInput("sharpness",ed.Float,!0),this.registerInput("source",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,ef.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerInput("sourceY",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("sourceY",this,ef.Input,ImageSourceBlock,"ImageSourceBlock")),t||this.registerInput("sourceZ",ed.Object,!0,e_.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("sourceZ",this,ef.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("rgba",ed.Color4,e_.Neutral),this.registerOutput("rgb",ed.Color3,e_.Neutral),this.registerOutput("r",ed.Float,e_.Neutral),this.registerOutput("g",ed.Float,e_.Neutral),this.registerOutput("b",ed.Float,e_.Neutral),this.registerOutput("a",ed.Float,e_.Neutral),this.registerOutput("level",ed.Float,e_.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(ed.Color3|ed.Vector3|ed.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;let r=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:r,a=null!==(i=this.samplerZName)&&void 0!==i?i:r,n=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",o=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),c=e._getFreeVariableName("w"),u=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),_=e._getFreeVariableName("uvy"),p=e._getFreeVariableName("uvz");e.compilationString+=` - vec3 ${u} = ${this.normal.associatedVariableName}.xyz; - - vec2 ${d} = ${this.position.associatedVariableName}.yz; - vec2 ${_} = ${this.position.associatedVariableName}.zx; - vec2 ${p} = ${this.position.associatedVariableName}.xy; - `,this.projectAsCube&&(e.compilationString+=` - ${d}.xy = ${d}.yx; - - if (${u}.x >= 0.0) { - ${d}.x = -${d}.x; - } - if (${u}.y < 0.0) { - ${_}.y = -${_}.y; - } - if (${u}.z < 0.0) { - ${p}.x = -${p}.x; - } - `),e.compilationString+=` - vec4 ${o} = texture2D(${r}, ${d}); - vec4 ${l} = texture2D(${s}, ${_}); - vec4 ${h} = texture2D(${a}, ${p}); - - // blend weights - vec3 ${c} = pow(abs(${u}), vec3(${n})); - - // blend and return - vec4 ${this._tempTextureRead} = (${o}*${c}.x + ${l}*${c}.y + ${h}*${c}.z) / (${c}.x + ${c}.y + ${c}.z); - `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} - ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); - #endif - `),e.compilationString+=`#ifdef ${this._gammaDefineName} - ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); - #endif - `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; -`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e),this._outputs))i.hasEndpoints&&"level"!==i.name&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; -${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; -`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};__decorate([editableInPropertyPage("Project as cube",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],TriPlanarBlock.prototype,"projectAsCube",void 0),h["BABYLON.TriPlanarBlock"]=TriPlanarBlock;let BiPlanarBlock=class BiPlanarBlock extends TriPlanarBlock{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;let i=this.samplerName,r=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",a=e._getFreeVariableName("dpdx"),n=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),c=e._getFreeVariableName("me"),u=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),_=e._getFreeVariableName("y");e.compilationString+=` - // grab coord derivatives for texturing - vec3 ${a} = dFdx(${this.position.associatedVariableName}.xyz); - vec3 ${n} = dFdy(${this.position.associatedVariableName}.xyz); - vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); - - // determine major axis (in x; yz are following axis) - ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : - (${o}.y>${o}.z) ? ivec3(1,2,0) : - ivec3(2,0,1) ; - // determine minor axis (in x; yz are following axis) - ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : - (${o}.y<${o}.z) ? ivec3(1,2,0) : - ivec3(2,0,1) ; - // determine median axis (in x; yz are following axis) - ivec3 ${c} = ivec3(3) - ${h} - ${l}; - - // project+fetch - vec4 ${u} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), - vec2(${a}[${l}.y],${a}[${l}.z]), - vec2(${n}[${l}.y],${n}[${l}.z]) ); - vec4 ${d} = textureGrad( ${r}, vec2( ${this.position.associatedVariableName}[${c}.y], ${this.position.associatedVariableName}[${c}.z]), - vec2(${a}[${c}.y],${a}[${c}.z]), - vec2(${n}[${c}.y],${n}[${c}.z]) ); - - // blend factors - vec2 ${_} = vec2(${o}[${l}.x],${o}[${c}.x]); - // make local support - ${_} = clamp( (${_}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); - // shape transition - ${_} = pow( ${_}, vec2(${s}/8.0) ); - // blend and return - vec4 ${this._tempTextureRead} = (${u}*${_}.x + ${d}*${_}.y) / (${_}.x + ${_}.y); - `}};h["BABYLON.BiPlanarBlock"]=BiPlanarBlock;let MatrixDeterminantBlock=class MatrixDeterminantBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.Matrix),this.registerOutput("output",ed.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName}); -`,this}};h["BABYLON.MatrixDeterminantBlock"]=MatrixDeterminantBlock;let MatrixTransposeBlock=class MatrixTransposeBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.registerInput("input",ed.Matrix),this.registerOutput("output",ed.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); -`,this}};h["BABYLON.MatrixTransposeBlock"]=MatrixTransposeBlock,function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Tangent=2]="Tangent",e[e.VertexColor=3]="VertexColor",e[e.UV1=4]="UV1",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6"}(tP||(tP={}));let MeshAttributeExistsBlock=class MeshAttributeExistsBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.attributeType=tP.None,this.registerInput("input",ed.AutoDetect),this.registerInput("fallback",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(e=>{var t;if(this.attributeType)return;let i=e.ownerBlock;if(i instanceof InputBlock&&i.isAttribute)switch(i.name){case"color":this.attributeType=tP.VertexColor;break;case"normal":this.attributeType=tP.Normal;break;case"tangent":this.attributeType=tP.Tangent;break;case"uv":this.attributeType=tP.UV1;break;case"uv2":this.attributeType=tP.UV2;break;case"uv3":this.attributeType=tP.UV3;break;case"uv4":this.attributeType=tP.UV4;break;case"uv5":this.attributeType=tP.UV5;break;case"uv6":this.attributeType=tP.UV6}else if(i instanceof MorphTargetsBlock)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=tP.Normal;break;case"tangentOutput":this.attributeType=tP.Tangent;break;case"uvOutput":this.attributeType=tP.UV1}})}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case tP.VertexColor:t="VERTEXCOLOR_NME";break;case tP.Normal:t="NORMAL";break;case tP.Tangent:t="TANGENT";break;case tP.UV1:t="UV1";break;case tP.UV2:t="UV2";break;case tP.UV3:t="UV3";break;case tP.UV4:t="UV4";break;case tP.UV5:t="UV5";break;case tP.UV6:t="UV6"}let i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} -`),e.compilationString+=`${i} = ${this.input.associatedVariableName}; -`,t&&(e.compilationString+=`#else -`,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; -`,e.compilationString+=`#endif -`),this}serialize(){let e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.attributeType=null!==(r=e.attributeType)&&void 0!==r?r:tP.None}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.attributeType = ${this.attributeType}; -`}};__decorate([editableInPropertyPage("Attribute lookup",em.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:tP.None},{label:"Normal",value:tP.Normal},{label:"Tangent",value:tP.Tangent},{label:"Vertex Color",value:tP.VertexColor},{label:"UV1",value:tP.UV1},{label:"UV2",value:tP.UV2},{label:"UV3",value:tP.UV3},{label:"UV4",value:tP.UV4},{label:"UV5",value:tP.UV5},{label:"UV6",value:tP.UV6}]})],MeshAttributeExistsBlock.prototype,"attributeType",void 0),h["BABYLON.MeshAttributeExistsBlock"]=MeshAttributeExistsBlock,function(e){e[e.EaseInSine=0]="EaseInSine",e[e.EaseOutSine=1]="EaseOutSine",e[e.EaseInOutSine=2]="EaseInOutSine",e[e.EaseInQuad=3]="EaseInQuad",e[e.EaseOutQuad=4]="EaseOutQuad",e[e.EaseInOutQuad=5]="EaseInOutQuad",e[e.EaseInCubic=6]="EaseInCubic",e[e.EaseOutCubic=7]="EaseOutCubic",e[e.EaseInOutCubic=8]="EaseInOutCubic",e[e.EaseInQuart=9]="EaseInQuart",e[e.EaseOutQuart=10]="EaseOutQuart",e[e.EaseInOutQuart=11]="EaseInOutQuart",e[e.EaseInQuint=12]="EaseInQuint",e[e.EaseOutQuint=13]="EaseOutQuint",e[e.EaseInOutQuint=14]="EaseInOutQuint",e[e.EaseInExpo=15]="EaseInExpo",e[e.EaseOutExpo=16]="EaseOutExpo",e[e.EaseInOutExpo=17]="EaseInOutExpo",e[e.EaseInCirc=18]="EaseInCirc",e[e.EaseOutCirc=19]="EaseOutCirc",e[e.EaseInOutCirc=20]="EaseInOutCirc",e[e.EaseInBack=21]="EaseInBack",e[e.EaseOutBack=22]="EaseOutBack",e[e.EaseInOutBack=23]="EaseInOutBack",e[e.EaseInElastic=24]="EaseInElastic",e[e.EaseOutElastic=25]="EaseOutElastic",e[e.EaseInOutElastic=26]="EaseInOutElastic"}(tA||(tA={}));let CurveBlock=class CurveBlock extends NodeMaterialBlock{constructor(e){super(e,e_.Neutral),this.type=tA.EaseInOutSine,this.registerInput("input",ed.AutoDetect),this.registerOutput("output",ed.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(ed.Matrix),this._inputs[0].excludedConnectionPointTypes.push(ed.Object),this._inputs[0].excludedConnectionPointTypes.push(ed.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if("float"===t)return this._duplicateEntryDirect(e);let i=parseInt(t.replace("vec","")),r=` - vec${i} ret = vec${i}(0.0); - `;for(let t=1;t<=i;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+"return ret;\n"}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="",r="",s="";switch(this.input.type){case ed.Float:s="float";break;case ed.Vector2:s="vec2";break;case ed.Vector3:case ed.Color3:s="vec3";break;case ed.Vector4:case ed.Color4:s="vec4"}switch(r=tA[this.type]+"_"+s,this.type){case tA.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case tA.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case tA.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case tA.EaseInQuad:i="return v * v";break;case tA.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case tA.EaseInOutQuad:i=this._duplicateVector("VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0",s);break;case tA.EaseInCubic:i="return v * v * v";break;case tA.EaseOutCubic:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s);break;case tA.EaseInOutCubic:i=this._duplicateVector("VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0",s);break;case tA.EaseInQuart:i="return v * v * v * v";break;case tA.EaseOutQuart:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s);break;case tA.EaseInOutQuart:i=this._duplicateVector("VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0",s);break;case tA.EaseInQuint:i="return v * v * v * v * v";break;case tA.EaseOutQuint:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s);break;case tA.EaseInOutQuint:i=this._duplicateVector("VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0",s);break;case tA.EaseInExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)",s);break;case tA.EaseOutExpo:i=this._duplicateVector("VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)",s);break;case tA.EaseInOutExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0",s);break;case tA.EaseInCirc:i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s);break;case tA.EaseOutCirc:i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s);break;case tA.EaseInOutCirc:i=this._duplicateVector("VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0",s);break;case tA.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case tA.EaseOutBack:i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s);break;case tA.EaseInOutBack:i=this._duplicateVector("VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0",s);break;case tA.EaseInElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))",s);break;case tA.EaseOutElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0",s);break;case tA.EaseInOutElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0",s)}return e._emitFunction(r,`${s} ${r}(${s} v) {${i};} -`,""),e.compilationString+=this._declareOutput(t,e)+` = ${r}(${this.input.associatedVariableName}); -`,this}serialize(){let e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${tA[this.type]}; -`;return e}};h["BABYLON.CurveBlock"]=CurveBlock;let DecalMapDefines=class DecalMapDefines extends MaterialDefines{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}};let DecalMapConfiguration=class DecalMapConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new DecalMapDefines,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;return!this._isEnabled||null==s||!s.texture||!MaterialFlags.DecalMapEnabled||!t.texturesEnabled||s.isReady()}prepareDefines(e,t,i){let r=i.decalMap;if(this._isEnabled&&(null==r?void 0:r.texture)&&MaterialFlags.DecalMapEnabled&&t.texturesEnabled){let t=!e.DECAL||e.GAMMADECAL!==r.texture.gammaSpace;t&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=r.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,MaterialHelper.PrepareDefinesForMergedUV(r.texture,e,"DECAL")}else{let t=e.DECAL;t&&e.markAsTexturesDirty(),e.DECAL=!1}}hardBindForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;if(!this._isEnabled||!(null==s?void 0:s.texture)||!MaterialFlags.DecalMapEnabled||!t.texturesEnabled)return;let a=this._material.isFrozen,n=s.texture;e.useUbo&&a&&e.isSync||(e.updateFloat4("vDecalInfos",n.coordinatesIndex,0,0,0),MaterialHelper.BindTextureMatrix(n,e,"decal")),e.setTexture("decalSampler",n)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}};__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],DecalMapConfiguration.prototype,"isEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllSubMeshesAsTexturesDirty")],DecalMapConfiguration.prototype,"smoothAlpha",void 0),h["BABYLON.DecalMapConfiguration"]=DecalMapConfiguration,function(e){e[e.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",e[e.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",e[e.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE"}(tM||(tM={})),function(e){e[e.COLOR_MODE_SET=0]="COLOR_MODE_SET",e[e.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",e[e.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY"}(tI||(tI={})),function(e){e[e.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",e[e.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE"}(tD||(tD={}));let greasedLineMaterialDefaults_GreasedLineMaterialDefaults=class greasedLineMaterialDefaults_GreasedLineMaterialDefaults{};greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR=math_color_Color3.White(),greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED=1,greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH=.1;let greasedLineTools_GreasedLineTools=class greasedLineTools_GreasedLineTools{static ConvertPoints(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof math_vector_Vector3){let t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof math_vector_Vector3){let t=[];return e.forEach(e=>{t.push(e.flatMap(e=>[e.x,e.y,e.z]))}),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){let t=[];return e.forEach(e=>{t.push(Array.from(e))}),t}return[]}static OmitZeroLengthPredicate(e,t,i){let r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r}static OmitDuplicatesPredicate(e,t,i,r){let s=[];return greasedLineTools_GreasedLineTools._SearchInPoints(e,t,r)||s.push([e,t]),greasedLineTools_GreasedLineTools._SearchInPoints(t,i,r)||s.push([t,i]),greasedLineTools_GreasedLineTools._SearchInPoints(i,e,r)||s.push([i,e]),0===s.length?null:s}static _SearchInPoints(e,t,i){var r,s,a;for(let n of i)for(let i=0;i{let s=e.getVerticesData(buffer_VertexBuffer.PositionKind),a=e.getIndices();if(s&&a)for(let n=0,o=0;n[e.x,e.y,e.z])}static GetPointsCountInfo(e){let t=Array(e.length),i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){let t;if(0===e.length)return 0;t="number"==typeof e[0]?greasedLineTools_GreasedLineTools.ToVector3Array(e):e;let i=math_vector_TmpVectors.Vector3[0],r=0;for(let e=0;e{if(e.length>t){let i=greasedLineTools_GreasedLineTools.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t));i.forEach(e=>{r.push(e)})}else r.push(e.point1),r.push(e.point2)}),r}static SegmentizeLineBySegmentCount(e,t){let i="number"==typeof e[0]?greasedLineTools_GreasedLineTools.ToVector3Array(e):e,r=greasedLineTools_GreasedLineTools.GetLineLength(i)/t;return greasedLineTools_GreasedLineTools.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){let t=[];for(let i=0;ie.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){let s=t*i,a=0,n=0,o=e.length;for(let t=0;t[e.x,e.y,e.z])}static GetArrowCap(e,t,i,r,s,a=0,n=0){let o=[e.clone(),e.add(t.multiplyByFloats(i,i,i))];return{points:o,widths:[r,s,a,n]}}static GetPointsFromText(e,t,i,r,s=0,a=!0){let n=[],o=CreateTextShapePaths(e,t,i,r);for(let e of o){for(let t of e.paths){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);n.push(e)}if(a)for(let t of e.holes){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);n.push(e)}}return n}static Color3toRGBAUint8(e){let t=new Uint8Array(4*e.length);for(let i=0,r=0;i{greasedLineTools_GreasedLineTools.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){let e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?` - uniform vec4 grl_aspect_resolution_lineWidth; - uniform mat4 grl_projection; - `:"",fragment:` - uniform vec4 grl_dashOptions; - uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; - uniform vec3 grl_singleColor; - `}}get isEnabled(){return!0}bindForSubMesh(e){var t;if(this._cameraFacing){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}else throw Error("GreasedLinePluginMaterial requires an active camera.");let i=math_vector_TmpVectors.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}let i=math_vector_TmpVectors.Vector4[0];i.x=greasedLineTools_GreasedLineTools.BooleanToNumber(this.useDash),i.y=this._dashArray,i.z=this.dashOffset,i.w=this.dashRatio,e.updateVector4("grl_dashOptions",i);let r=math_vector_TmpVectors.Vector4[1];r.x=this.colorMode,r.y=this.visibility,r.z=this.colorsTexture?this.colorsTexture.getSize().width:0,r.w=greasedLineTools_GreasedLineTools.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",r),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",null!==(t=this.colorsTexture)&&void 0!==t?t:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===tD.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){let e={CUSTOM_VERTEX_DEFINITIONS:` - attribute float grl_widths; - attribute vec3 grl_offsets; - attribute float grl_colorPointers; - - varying float grlCounters; - varying float grlColorPointer; - - #ifdef GREASED_LINE_CAMERA_FACING - attribute vec4 grl_previousAndSide; - attribute vec4 grl_nextAndCounters; - - vec2 grlFix( vec4 i, float aspect ) { - vec2 res = i.xy / i.w; - res.x *= aspect; - return res; - } - #else - attribute vec3 grl_slopes; - attribute float grl_counters; - #endif - `,CUSTOM_VERTEX_UPDATE_POSITION:` - #ifdef GREASED_LINE_CAMERA_FACING - vec3 grlPositionOffset = grl_offsets; - positionUpdated += grlPositionOffset; - #else - positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); - #endif - `,CUSTOM_VERTEX_MAIN_END:` - grlColorPointer = grl_colorPointers; - - #ifdef GREASED_LINE_CAMERA_FACING - - float grlAspect = grl_aspect_resolution_lineWidth.x; - float grlBaseWidth = grl_aspect_resolution_lineWidth.w; - - - vec3 grlPrevious = grl_previousAndSide.xyz; - float grlSide = grl_previousAndSide.w; - - vec3 grlNext = grl_nextAndCounters.xyz; - grlCounters = grl_nextAndCounters.w; - - mat4 grlMatrix = viewProjection * finalWorld; - vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); - vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); - vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); - - vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); - vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); - vec2 grlNextP = grlFix( grlNextPos, grlAspect ); - - float grlWidth = grlBaseWidth * grl_widths; - - vec2 grlDir; - if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); - else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); - else { - vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); - vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); - grlDir = normalize( grlDir1 + grlDir2 ); - } - vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); - #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM - grlNormal.xy *= -.5 * grlWidth; - #else - grlNormal.xy *= .5 * grlWidth; - #endif - - grlNormal *= grl_projection; - - #ifdef GREASED_LINE_SIZE_ATTENUATION - grlNormal.xy *= grlFinalPosition.w; - grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; - #endif - - grlFinalPosition.xy += grlNormal.xy * grlSide; - gl_Position = grlFinalPosition; - - vPositionW = vec3(grlFinalPosition); - #else - grlCounters = grl_counters; - #endif - `};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:` - varying float grlCounters; - varying float grlColorPointer; - uniform sampler2D grl_colors; - `,CUSTOM_FRAGMENT_MAIN_END:` - float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; - float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; - float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; - float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; - - float grlUseDash = grl_dashOptions.x; - float grlDashArray = grl_dashOptions.y; - float grlDashOffset = grl_dashOptions.z; - float grlDashRatio = grl_dashOptions.w; - - gl_FragColor.a *= step(grlCounters, grlVisibility); - if( gl_FragColor.a == 0. ) discard; - - if(grlUseDash == 1.){ - gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); - if (gl_FragColor.a == 0.) discard; - } - - #ifdef GREASED_LINE_HAS_COLOR - if (grlColorMode == ${tI.COLOR_MODE_SET}.) { - gl_FragColor.rgb = grl_singleColor; - } else if (grlColorMode == ${tI.COLOR_MODE_ADD}.) { - gl_FragColor.rgb += grl_singleColor; - } else if (grlColorMode == ${tI.COLOR_MODE_MULTIPLY}.) { - gl_FragColor.rgb *= grl_singleColor; - } - #else - if (grlUseColors == 1.) { - #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE - vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); - #else - vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); - #endif - if (grlColorMode == ${tI.COLOR_MODE_SET}.) { - gl_FragColor = grlColor; - } else if (grlColorMode == ${tI.COLOR_MODE_ADD}.) { - gl_FragColor += grlColor; - } else if (grlColorMode == ${tI.COLOR_MODE_MULTIPLY}.) { - gl_FragColor *= grlColor; - } - } - #endif - - `}:null}dispose(){var e;null===(e=this.colorsTexture)||void 0===e||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,a,n;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(a=this.colorsTexture)||void 0===a||a.dispose();return}if(!t||i){if(this.colorsTexture&&o===e.length&&!i){let t=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else null===(n=this.colorsTexture)||void 0===n||n.dispose(),this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,t||this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;super.parse(e,t,i);let s=e.greasedLineMaterialOptions;null===(r=this.colorsTexture)||void 0===r||r.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var t;null===(t=e.colorsTexture)||void 0===t||t.dispose(),this._colors&&(e.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${e._material.name}-colors-texture`,this._colors,e.colorsSampling,this._scene)),e.setColor(this.color,!0),e.colorsDistributionType=this.colorsDistributionType,e.colorsSampling=this.colorsSampling,e.colorMode=this.colorMode,e.useColors=this.useColors,e.visibility=this.visibility,e.useDash=this.useDash,e.dashCount=this.dashCount,e.dashRatio=this.dashRatio,e.dashOffset=this.dashOffset,e.width=this.width,e.sizeAttenuation=this.sizeAttenuation,e.resolution=this.resolution,e.markAllDefinesAsDirty()}};greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",h[`BABYLON.${greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`]=greasedLinePluginMaterial_GreasedLinePluginMaterial;let a4=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} -if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { -textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} -if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} -`;ShaderStore.ShadersStore.greasedLinePixelShader=a4;let a5=`precision highp float; -#include -attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; -#ifdef GREASED_LINE_CAMERA_FACING -attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} -#else -attribute vec3 grl_slopes;attribute float grl_counters; -#endif -void main() { -#include -grlColorPointer=grl_colorPointers; -#ifdef GREASED_LINE_CAMERA_FACING -float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=viewProjection*finalWorld ;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} -vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); -#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM -grlNormal.xy*=-.5*grlWidth; -#else -grlNormal.xy*=.5*grlWidth; -#endif -grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} -grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; -#else -grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; -#endif -} -`;ShaderStore.ShadersStore.greasedLineVertexShader=a5;let greasedLineSimpleMaterial_GreasedLineSimpleMaterial=class greasedLineSimpleMaterial_GreasedLineSimpleMaterial extends shaderMaterial_ShaderMaterial{constructor(e,t,i){var r,s,a,n,o,l,h,c,u,d,_,p,f,m;let g=[`COLOR_DISTRIBUTION_TYPE_LINE ${tD.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${tD.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${tI.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${tI.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${tI.COLOR_MODE_MULTIPLY}.`],v=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&g.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(g.push("GREASED_LINE_CAMERA_FACING"),v.push("grl_previousAndSide","grl_nextAndCounters")):(v.push("grl_slopes"),v.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:v,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:g}),this._color=math_color_Color3.White(),this._colorsDistributionType=tD.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR};let x=t.getEngine();this.visibility=null!==(r=i.visibility)&&void 0!==r?r:1,this.useDash=null!==(s=i.useDash)&&void 0!==s&&s,this.dashRatio=null!==(a=i.dashRatio)&&void 0!==a?a:.5,this.dashOffset=null!==(n=i.dashOffset)&&void 0!==n?n:0,this.dashCount=null!==(o=i.dashCount)&&void 0!==o?o:1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH,this.sizeAttenuation=null!==(l=i.sizeAttenuation)&&void 0!==l&&l,this.color=null!==(h=i.color)&&void 0!==h?h:math_color_Color3.White(),this.useColors=null!==(c=i.useColors)&&void 0!==c&&c,this.colorsDistributionType=null!==(u=i.colorDistributionType)&&void 0!==u?u:tD.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(d=i.colorsSampling)&&void 0!==d?d:rawTexture_RawTexture.NEAREST_NEAREST,this.colorMode=null!==(_=i.colorMode)&&void 0!==_?_:tI.COLOR_MODE_SET,this._colors=null!==(p=i.colors)&&void 0!==p?p:null,this._cameraFacing=null===(f=i.cameraFacing)||void 0===f||f,this.resolution=null!==(m=i.resolution)&&void 0!==m?m:new math_vector_Vector2(x.getRenderWidth(),x.getRenderHeight()),i.colorsTexture&&(this.colorsTexture=i.colorsTexture),this._colors&&this.setColors(this._colors),x.onDisposeObservable.add(()=>{greasedLineTools_GreasedLineTools.DisposeEmptyColorsTexture()})}dispose(){var e;null===(e=this._colorsTexture)||void 0===e||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new math_vector_Vector2(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,a,n;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(a=this._colorsTexture)||void 0===a||a.dispose();return}if(!t||i){if(this._colorsTexture&&o===e.length&&!i){let t=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else null===(n=this._colorsTexture)||void 0===n||n.dispose(),this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}}get colorsTexture(){var e;return null!==(e=this._colorsTexture)&&void 0!==e?e:null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=null!=e?e:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r,s;let a=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),a.color&&(this.color=a.color),a.colorDistributionType&&(this.colorsDistributionType=a.colorDistributionType),a.colorsSampling&&(this.colorsSampling=a.colorsSampling),a.colorMode&&(this.colorMode=a.colorMode),a.useColors&&(this.useColors=a.useColors),a.visibility&&(this.visibility=a.visibility),a.useDash&&(this.useDash=a.useDash),a.dashCount&&(this.dashCount=a.dashCount),a.dashRatio&&(this.dashRatio=a.dashRatio),a.dashOffset&&(this.dashOffset=a.dashOffset),a.width&&(this.width=a.width),a.sizeAttenuation&&(this.sizeAttenuation=a.sizeAttenuation),a.resolution&&(this.resolution=a.resolution),a.colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`,a.colors,this.colorsSampling,this.getScene()):greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(t),this._cameraFacing=null===(s=a.cameraFacing)||void 0===s||s,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}};let a6=`#if defined(DBG_ENABLED) -attribute float dbg_initialPass; -varying vec3 dbg_vBarycentric; -flat varying vec3 dbg_vVertexWorldPos; -flat varying float dbg_vPass; -#endif`,a8=`#if defined(DBG_ENABLED) -float dbg_vertexIndex = mod(float(gl_VertexID), 3.); -if (dbg_vertexIndex == 0.0) { - dbg_vBarycentric = vec3(1.,0.,0.); -} -else if (dbg_vertexIndex == 1.0) { - dbg_vBarycentric = vec3(0.,1.,0.); -} -else { - dbg_vBarycentric = vec3(0.,0.,1.); -} - -dbg_vVertexWorldPos = vPositionW; -dbg_vPass = dbg_initialPass; -#endif`,a7=`#if defined(DBG_ENABLED) -uniform vec3 dbg_shadedDiffuseColor; -uniform vec4 dbg_shadedSpecularColorPower; -uniform vec3 dbg_thicknessRadiusScale; - -#if DBG_MODE == 2 || DBG_MODE == 3 - uniform vec3 dbg_vertexColor; -#endif - -#if DBG_MODE == 1 - uniform vec3 dbg_wireframeTrianglesColor; -#elif DBG_MODE == 3 - uniform vec3 dbg_wireframeVerticesColor; -#elif DBG_MODE == 4 || DBG_MODE == 5 - uniform vec3 dbg_uvPrimaryColor; - uniform vec3 dbg_uvSecondaryColor; -#elif DBG_MODE == 7 - uniform vec3 dbg_materialColor; -#endif -#endif`,a9=`#if defined(DBG_ENABLED) -varying vec3 dbg_vBarycentric; -flat varying vec3 dbg_vVertexWorldPos; -flat varying float dbg_vPass; - -#if !defined(DBG_MULTIPLY) - vec3 dbg_applyShading(vec3 color) { - vec3 N = vNormalW.xyz; - vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); - vec3 H = normalize(L + L); - float LdotN = clamp(dot(L,N), 0., 1.); - float HdotN = clamp(dot(H,N), 0., 1.); - float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); - color *= (LdotN / PI); - color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); - return color; - } -#endif - -#if DBG_MODE == 1 || DBG_MODE == 3 - float dbg_edgeFactor() { - vec3 d = fwidth(dbg_vBarycentric); - vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); - return min(min(a3.x, a3.y), a3.z); - } -#endif - -#if DBG_MODE == 2 || DBG_MODE == 3 - float dbg_cornerFactor() { - vec3 worldPos = vPositionW; - float dist = length(worldPos - dbg_vVertexWorldPos); - float camDist = length(worldPos - vEyePosition.xyz); - float d = sqrt(camDist) * .001; - return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); - } -#endif - -#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) - float dbg_checkerboardFactor(vec2 uv) { - vec2 f = fract(uv * dbg_thicknessRadiusScale.z); - f -= .5; - return (f.x * f.y) > 0. ? 1. : 0.; - } -#endif -#endif`,ne=`#if defined(DBG_ENABLED) -vec3 dbg_color = vec3(1.); -#if DBG_MODE == 1 - dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); -#elif DBG_MODE == 2 || DBG_MODE == 3 - float dbg_cornerFactor = dbg_cornerFactor(); - if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; - dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); - #if DBG_MODE == 3 - dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); - #endif -#elif DBG_MODE == 4 && defined(UV1) - dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); -#elif DBG_MODE == 5 && defined(UV2) - dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); -#elif DBG_MODE == 6 && defined(VERTEXCOLOR) - dbg_color = vColor.rgb; -#elif DBG_MODE == 7 - dbg_color = dbg_materialColor; -#endif - -#if defined(DBG_MULTIPLY) - gl_FragColor *= vec4(dbg_color, 1.); -#else - #if DBG_MODE != 6 - gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); - #else - gl_FragColor = vec4(dbg_color, 1.); - #endif -#endif -#endif`,nt=[new math_color_Color3(.98,.26,.38),new math_color_Color3(.47,.75,.3),new math_color_Color3(0,.26,.77),new math_color_Color3(.97,.6,.76),new math_color_Color3(.19,.63,.78),new math_color_Color3(.98,.8,.6),new math_color_Color3(.65,.43,.15),new math_color_Color3(.15,.47,.22),new math_color_Color3(.67,.71,.86),new math_color_Color3(.09,.46,.56),new math_color_Color3(.8,.98,.02),new math_color_Color3(.39,.29,.13),new math_color_Color3(.53,.63,.06),new math_color_Color3(.95,.96,.41),new math_color_Color3(1,.72,.94),new math_color_Color3(.63,.08,.31),new math_color_Color3(.66,.96,.95),new math_color_Color3(.22,.14,.19),new math_color_Color3(.14,.65,.59),new math_color_Color3(.93,1,.68),new math_color_Color3(.93,.14,.44),new math_color_Color3(.47,.86,.67),new math_color_Color3(.85,.07,.78),new math_color_Color3(.53,.64,.98),new math_color_Color3(.43,.37,.56),new math_color_Color3(.71,.65,.25),new math_color_Color3(.66,.19,.01),new math_color_Color3(.94,.53,.12),new math_color_Color3(.41,.44,.44),new math_color_Color3(.24,.71,.96),new math_color_Color3(.57,.28,.56),new math_color_Color3(.44,.98,.42)];!function(e){e[e.NONE=0]="NONE",e[e.TRIANGLES=1]="TRIANGLES",e[e.VERTICES=2]="VERTICES",e[e.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",e[e.UV0=4]="UV0",e[e.UV1=5]="UV1",e[e.VERTEXCOLORS=6]="VERTEXCOLORS",e[e.MATERIALIDS=7]="MATERIALIDS"}(tO||(tO={}));let MeshDebugDefines=class MeshDebugDefines extends MaterialDefines{constructor(){super(...arguments),this.DBG_MODE=tO.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}};let MeshDebugPluginMaterial=class MeshDebugPluginMaterial extends MaterialPluginBase{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,r,s,a,n,o,l,h,c,u,d,_,p;let f=new MeshDebugDefines;f.DBG_MODE=null!==(i=t.mode)&&void 0!==i?i:f.DBG_MODE,f.DBG_MULTIPLY=null!==(r=t.multiply)&&void 0!==r?r:f.DBG_MULTIPLY,super(e,"MeshDebug",200,f,!0,!0),this._mode=f.DBG_MODE,this._multiply=f.DBG_MULTIPLY,this.shadedDiffuseColor=null!==(s=t.shadedDiffuseColor)&&void 0!==s?s:new math_color_Color3(1,1,1),this.shadedSpecularColor=null!==(a=t.shadedSpecularColor)&&void 0!==a?a:new math_color_Color3(.8,.8,.8),this.shadedSpecularPower=null!==(n=t.shadedSpecularPower)&&void 0!==n?n:10,this.wireframeThickness=null!==(o=t.wireframeThickness)&&void 0!==o?o:.7,this.wireframeTrianglesColor=null!==(l=t.wireframeTrianglesColor)&&void 0!==l?l:new math_color_Color3(0,0,0),this.wireframeVerticesColor=null!==(h=t.wireframeVerticesColor)&&void 0!==h?h:new math_color_Color3(.8,.8,.8),this.vertexColor=null!==(c=t.vertexColor)&&void 0!==c?c:new math_color_Color3(0,0,0),this.vertexRadius=null!==(u=t.vertexRadius)&&void 0!==u?u:1.2,this.uvScale=null!==(d=t.uvScale)&&void 0!==d?d:20,this.uvPrimaryColor=null!==(_=t.uvPrimaryColor)&&void 0!==_?_:new math_color_Color3(1,1,1),this.uvSecondaryColor=null!==(p=t.uvSecondaryColor)&&void 0!==p?p:new math_color_Color3(.5,.5,.5),this._materialColor=MeshDebugPluginMaterial.MaterialColors[MeshDebugPluginMaterial._PluginCount++%MeshDebugPluginMaterial.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().webGLVersion){logger_Logger.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=tO.VERTICES&&this._mode!=tO.TRIANGLES&&this._mode!=tO.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||logger_Logger.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:a7}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:a6,CUSTOM_VERTEX_MAIN_END:a8}:{CUSTOM_FRAGMENT_DEFINITIONS:a9,CUSTOM_FRAGMENT_MAIN_END:ne}}static Reset(){this._PluginCount=0,this.MaterialColors=nt}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let rollback=()=>{};if(0==e.getTotalIndices())return rollback;if(t){let t=e.getVerticesDataKinds(),i=e.getIndices(),r={};for(let i of t)r[i]=e.getVerticesData(i);rollback=function(){for(let s of(e.setIndices(i),t)){let t=e.getVertexBuffer(s).getStrideSize();e.setVerticesData(s,r[s],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let i=Array.from(e.getIndices()),r=[];for(let e=0;e{DracoDecoderModule({wasmBinary:e}).then(e=>{t({module:e})})})}function decodeMesh(e,t,i,r,s){let a=null,n=null,o=null;try{let l;a=new e.Decoder,(n=new e.DecoderBuffer).Init(t,t.byteLength);let h=a.GetEncodedGeometryType(n);switch(h){case e.TRIANGULAR_MESH:{let t=new e.Mesh;if(!(l=a.DecodeBufferToMesh(n,t)).ok()||0===t.ptr)throw Error(l.error_msg());let i=t.num_faces(),s=3*i,h=4*s,c=e._malloc(h);try{a.GetTrianglesUInt32Array(t,h,c);let i=new Uint32Array(s);i.set(new Uint32Array(e.HEAPF32.buffer,c,s)),r(i)}finally{e._free(c)}o=t;break}case e.POINT_CLOUD:{let t=new e.PointCloud;if(!(l=a.DecodeBufferToPointCloud(n,t)).ok()||!t.ptr)throw Error(l.error_msg());o=t;break}default:throw Error(`Invalid geometry type ${h}`)}let c=o.num_points(),processAttribute=(t,i,r,a)=>{let n=a.data_type(),o=a.num_components(),l=a.normalized(),h=a.byte_stride(),u=a.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}},_=d[n];if(!_)throw Error(`Invalid data type ${n}`);let p=c*o,f=p*_.typedArrayConstructor.BYTES_PER_ELEMENT,m=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(i,a,n,f,m);let e=new _.typedArrayConstructor(_.heap.buffer,m,p);s(r,e.slice(),o,u,h,l)}finally{e._free(m)}};if(i)for(let e in i){let t=i[e],r=a.GetAttributeByUniqueId(o,t);processAttribute(a,o,e,r)}else{let t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(let e in t){let i=a.GetAttributeId(o,t[e]);if(-1!==i){let t=a.GetAttribute(o,i);processAttribute(a,o,e,t)}}}return c}finally{o&&e.destroy(o),n&&e.destroy(n),a&&e.destroy(a)}}function worker(){let e;onmessage=t=>{let i=t.data;switch(i.id){case"init":{let t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw Error("Draco decoder module is not available");e.then(e=>{let t=decodeMesh(e,i.dataView,i.attributes,e=>{postMessage({id:"indices",data:e},[e.buffer])},(e,t,i,r,s,a)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:s,normalized:a},[t.buffer])});postMessage({id:"decodeMeshDone",totalVertices:t})})}}}MeshDebugPluginMaterial._PluginCount=0,MeshDebugPluginMaterial.MaterialColors=nt,__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"_materialColor",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"_isEnabled",void 0),__decorate([serialize(),expandToProperty("_markAllDefinesAsDirty")],MeshDebugPluginMaterial.prototype,"mode",void 0),__decorate([serialize(),expandToProperty("_markAllDefinesAsDirty")],MeshDebugPluginMaterial.prototype,"multiply",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"shadedDiffuseColor",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"shadedSpecularColor",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"shadedSpecularPower",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"wireframeThickness",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"wireframeTrianglesColor",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"wireframeVerticesColor",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"vertexColor",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"vertexRadius",void 0),__decorate([serialize()],MeshDebugPluginMaterial.prototype,"uvScale",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"uvPrimaryColor",void 0),__decorate([serializeAsColor3()],MeshDebugPluginMaterial.prototype,"uvSecondaryColor",void 0),h["BABYLON.MeshDebugPluginMaterial"]=MeshDebugPluginMaterial,Object.defineProperty(standardMaterial_StandardMaterial.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new DecalMapConfiguration(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(pbrBaseMaterial_PBRBaseMaterial.prototype,"decalMap",{get:function(){if(!this._decalMap){if(this._uniformBufferLayoutBuilt)return null;this._decalMap=new DecalMapConfiguration(this)}return this._decalMap},enumerable:!0,configurable:!0}),Object.defineProperty(abstractMesh_AbstractMesh.prototype,"decalMap",{get:function(){return this._decalMap},set:function(e){this._decalMap=e},enumerable:!0,configurable:!0});let DracoCompression=class DracoCompression{static get DecoderAvailable(){let e=DracoCompression.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 DracoCompression._Default||(DracoCompression._Default=new DracoCompression),DracoCompression._Default}constructor(e=DracoCompression.DefaultNumWorkers){let t=DracoCompression.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:tools_Tools.GetBabylonScriptURL(t.wasmUrl,!0),wasmBinaryPromise:tools_Tools.LoadFileAsync(tools_Tools.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:tools_Tools.GetBabylonScriptURL(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then(t=>{let r=`${decodeMesh}(${worker})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));return new AutoReleaseWorkerPool(e,()=>new Promise((e,r)=>{let a=new Worker(s),onError=e=>{a.removeEventListener("error",onError),a.removeEventListener("message",onMessage),r(e)},onMessage=t=>{"initDone"===t.data.id&&(a.removeEventListener("error",onError),a.removeEventListener("message",onMessage),e(a))};a.addEventListener("error",onError),a.addEventListener("message",onMessage),a.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))}):this._decoderModulePromise=i.wasmBinaryPromise.then(e=>{if(!i.url)throw Error("Draco decoder module is not available");return tools_Tools.LoadBabylonScriptAsync(i.url).then(()=>createDecoderAsync(e))})}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then(e=>{e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then(()=>{}):this._decoderModulePromise?this._decoderModulePromise.then(()=>{}):Promise.resolve()}_decodeMeshAsync(e,t,i){let r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),applyGltfNormalizedOverride=(e,t)=>i&&void 0!==i[e]?(t!==i[e]&&logger_Logger.Warn(`Normalized flag from Draco data (${t}) does not match normalized flag from glTF accessor (${i[e]}). Using flag from glTF accessor.`),i[e]):t;if(this._workerPoolPromise)return this._workerPoolPromise.then(e=>new Promise((i,s)=>{e.push((e,a)=>{let n=null,o=[],onError=t=>{e.removeEventListener("error",onError),e.removeEventListener("message",onMessage),s(t),a()},onMessage=t=>{let r=t.data;switch(r.id){case"decodeMeshDone":e.removeEventListener("error",onError),e.removeEventListener("message",onMessage),i({indices:n,attributes:o,totalVertices:r.totalVertices}),a();break;case"indices":n=r.data;break;case"attribute":o.push({kind:r.kind,data:r.data,size:r.size,byteOffset:r.byteOffset,byteStride:r.byteStride,normalized:applyGltfNormalizedOverride(r.kind,r.normalized)})}};e.addEventListener("error",onError),e.addEventListener("message",onMessage);let l=r.slice();e.postMessage({id:"decodeMesh",dataView:l,attributes:t},[l.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(e=>{let i=null,s=[],a=decodeMesh(e.module,r,t,e=>{i=e},(e,t,i,r,a,n)=>{s.push({kind:e,data:t,size:i,byteOffset:r,byteStride:a,normalized:n})});return{indices:i,attributes:s,totalVertices:a}});throw Error("Draco decoder module is not available")}decodeMeshToGeometryAsync(e,t,i,r){return this._decodeMeshAsync(i,r).then(i=>{let r=new Geometry(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new buffer_VertexBuffer(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}_decodeMeshToGeometryForGltfAsync(e,t,i,r,s){return this._decodeMeshAsync(i,r,s).then(i=>{let r=new Geometry(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new buffer_VertexBuffer(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}decodeMeshAsync(e,t){return this._decodeMeshAsync(e,t).then(e=>{let t=new mesh_vertexData_VertexData;for(let i of(e.indices&&(t.indices=e.indices),e.attributes)){let r=buffer_VertexBuffer.GetFloatData(i.data,i.size,buffer_VertexBuffer.GetDataType(i.data),i.byteOffset,i.byteStride,i.normalized,e.totalVertices);t.set(r,i.kind)}return t})}};DracoCompression.Configuration={decoder:{wasmUrl:`${tools_Tools._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${tools_Tools._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${tools_Tools._DefaultCdnUrl}/draco_decoder_gltf.js`}},DracoCompression.DefaultNumWorkers=DracoCompression.GetDefaultNumWorkers(),DracoCompression._Default=null;let MeshoptCompression=class MeshoptCompression{static get Default(){return MeshoptCompression._Default||(MeshoptCompression._Default=new MeshoptCompression),MeshoptCompression._Default}constructor(){let e=MeshoptCompression.Configuration.decoder;this._decoderModulePromise=tools_Tools.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then(()=>{let a=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(a,t,i,e,r,s),a})}};MeshoptCompression.Configuration={decoder:{url:`${tools_Tools._DefaultCdnUrl}/meshopt_decoder.js`}},MeshoptCompression._Default=null;let ni=0;let Vertex=class Vertex{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){var e,t;return new Vertex(this.pos.clone(),this.normal.clone(),null===(e=this.uv)||void 0===e?void 0:e.clone(),null===(t=this.vertColor)||void 0===t?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Vertex(math_vector_Vector3.Lerp(this.pos,e.pos,t),math_vector_Vector3.Lerp(this.normal,e.normal,t),this.uv&&e.uv?math_vector_Vector2.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?math_color_Color4.Lerp(this.vertColor,e.vertColor,t):void 0)}};let csg_Plane=class csg_Plane{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){let r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;let a=math_vector_Vector3.Normalize(math_vector_Vector3.Cross(r,s));return new csg_Plane(a,math_vector_Vector3.Dot(a,e))}clone(){return new csg_Plane(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let a,n;let o=0,l=[];for(a=0;acsg_Plane.EPSILON?1:0;o|=t,l.push(t)}switch(o){case 0:(math_vector_Vector3.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{let t;let i=[],o=[];for(a=0;a=3&&(t=new csg_Polygon(i,e.shared)).plane&&r.push(t),o.length>=3&&(t=new csg_Polygon(o,e.shared)).plane&&s.push(t)}}}};csg_Plane.EPSILON=1e-5;let csg_Polygon=class csg_Polygon{constructor(e,t){this.vertices=e,this.shared=t,this.plane=csg_Plane.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){let e=this.vertices.map(e=>e.clone());return new csg_Polygon(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}};let csg_Node=class csg_Node{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=[],e&&this.build(e)}clone(){let e=new csg_Node;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(e=>e.clone()),e}invert(){for(let e=0;ee.clone()),e.copyTransformAttributes(this),e}union(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){let e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){let i;let r=this.matrix.clone();r.invert();let s=this._polygons,a=[],n=[],o=[],l=null,h=null,c=math_vector_Vector3.Zero(),u=math_vector_Vector3.Zero(),d=math_vector_Vector2.Zero(),_=new math_color_Color4(0,0,0,0),p=[0,0,0],f={};for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId);let l=this.toVertexData(e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:Infinity,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),r=o[e.shared.meshId][e.shared.subMeshId]},()=>{r.indexStart=Math.min(n,r.indexStart),r.indexEnd=Math.max(n,r.indexEnd),n++});if(l.applyToMesh(s),i){let e=0,t;for(let i in s.subMeshes=[],o){for(let a in t=-1,o[i])r=o[i][a],subMesh_SubMesh.CreateFromIndices(r.materialIndex+e,r.indexStart,r.indexEnd-r.indexStart+1,s),t=Math.max(r.materialIndex,t);e+=++t}}return s}toMesh(e,t=null,i,r){let s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}};let nr=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vNormalW=normalize(normWorldSM*normalUpdated); -#endif -vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);} -`;ShaderStore.ShadersStore.meshUVSpaceRendererVertexShader=nr;let ns=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} -gl_FragColor=texture2D(textureSampler,vDecalTC);} -`;ShaderStore.ShadersStore.meshUVSpaceRendererPixelShader=ns,mesh_Mesh._TrailMeshParser=(e,t)=>TrailMesh.Parse(e,t);let TrailMesh=class TrailMesh extends mesh_Mesh{constructor(e,t,i,r=1,s=60,a=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=a,this._generator=t,this.diameter=r,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){let e=this.getVerticesData(buffer_VertexBuffer.PositionKind),t=this.getVerticesData(buffer_VertexBuffer.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*this._sectionPolygonPointsCount;i{let i=this._getSimplifier(e);i.simplify(t,i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{let t=this._getSimplifier(e),runDecimation=(i,r)=>{t.simplify(i,t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()})};AsyncLoop.Run(e.settings.length,t=>{runDecimation(e.settings[t.index],()=>{t.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){return e.simplificationType,tB.QUADRATIC,new QuadraticErrorSimplification(e.mesh)}};!function(e){e[e.QUADRATIC=0]="QUADRATIC"}(tB||(tB={}));let DecimationTriangle=class DecimationTriangle{constructor(e){this._vertices=e,this.error=[,,,,],this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}};let DecimationVertex=class DecimationVertex{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new QuadraticMatrix,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}};let QuadraticMatrix=class QuadraticMatrix{constructor(e){this.data=Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,a,n,o,l){let h=this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[o]+this.data[t]*this.data[a]*this.data[n]-this.data[i]*this.data[s]*this.data[n]-this.data[e]*this.data[a]*this.data[o]-this.data[t]*this.data[r]*this.data[l];return h}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){let t=new QuadraticMatrix;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}};let Reference=class Reference{constructor(e,t){this.vertexId=e,this.triangleId=t}};let QuadraticErrorSimplification=class QuadraticErrorSimplification{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=.001}simplify(e,t){this._initDecimatedMesh(),AsyncLoop.Run(this._mesh.subMeshes.length,t=>{this._initWithMesh(t.index,()=>{this._runDecimation(e,t.index,()=>{t.executeNext()})},e.optimizeMesh)},()=>{setTimeout(()=>{t(this._reconstructedMesh)},0)})}_runDecimation(e,t,i){let r=~~(this._triangles.length*e.quality),s=0,a=this._triangles.length,iterationFunction=(e,t)=>{setTimeout(()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{let t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i)&&!r.deleted&&!r.isDirty){for(let e=0;e<3;++e)if(r.error[e]t.indexOf(!0)||0>i.indexOf(!0))continue;let h=[];if(l.forEach(e=>{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))}),h.length%2!=0)continue;a.q=n.q.add(a.q),a.updatePosition(o);let c=this._references.length;s=this._updateTriangles(a,a,t,s),s=this._updateTriangles(a,n,i,s);let u=this._references.length-c;if(u<=a.triangleCount){if(u)for(let e=0;ea-s<=r)},0)};AsyncLoop.Run(this.decimationIterations,e=>{a-s<=r?e.breakLoop():iterationFunction(e.index,()=>{e.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];let r=this._mesh.getVerticesData(buffer_VertexBuffer.PositionKind),s=this._mesh.getIndices(),a=this._mesh.subMeshes[e],findInVertices=e=>{if(i){for(let t=0;t>0,e=>{if(!r)return;let t=e+a.verticesStart,i=math_vector_Vector3.FromArray(r,3*t),s=findInVertices(i)||new DecimationVertex(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),n.push(s.id)},()=>{AsyncLoop.SyncAsyncForLoop(a.indexCount/3,this.syncIterations,e=>{if(!s)return;let t=a.indexStart/3+e,i=3*t,r=s[i+0],o=s[i+1],l=s[i+2],h=this._vertices[n[r-a.verticesStart]],c=this._vertices[n[o-a.verticesStart]],u=this._vertices[n[l-a.verticesStart]],d=new DecimationTriangle([h,c,u]);d.originalOffset=i,this._triangles.push(d)},()=>{this._init(t)})})}_init(e){AsyncLoop.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];t.normal=math_vector_Vector3.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-math_vector_Vector3.Dot(t.normal,t._vertices[0].position)))},()=>{AsyncLoop.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])},()=>{e()})})}_reconstructMesh(e){let t,i,r;let s=[];for(t=0;t{a.push(e.position.x),a.push(e.position.y),a.push(e.position.z),h&&h.length&&(n.push(h[3*t]),n.push(h[3*t+1]),n.push(h[3*t+2])),c&&c.length&&(o.push(c[2*t]),o.push(c[2*t+1])),u&&u.length&&(l.push(u[4*t]),l.push(u[4*t+1]),l.push(u[4*t+2]),l.push(u[4*t+3])),++d})}let _=this._reconstructedMesh.getTotalIndices(),p=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];let m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(t=0;t{let t=g[i.originalOffset+e],r=i._vertices[e].originalOffsets.indexOf(t);r<0&&(r=0),m.push(i._vertices[e].id+r+p)});this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.PositionKind,a),n.length>0&&this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.NormalKind,n),o.length>0&&this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.UVKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(buffer_VertexBuffer.ColorKind,l);let v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach(e=>{subMesh_SubMesh.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),subMesh_SubMesh.AddToMesh(v.materialIndex,p,d,_,3*s.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new mesh_Mesh(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,s){for(let a=0;a.999)return!0;let d=math_vector_Vector3.Cross(c,u).normalize();if(r[a]=!1,.2>math_vector_Vector3.Dot(d,n.normal))return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;rgreasedLineMesh_GreasedLineMesh.Parse(e,t);let greasedLineMesh_GreasedLineMesh=class greasedLineMesh_GreasedLineMesh extends GreasedLineBaseMesh{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(greasedLineTools_GreasedLineTools.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i{var i;let r=[],s=[],a=[],n=greasedLineTools_GreasedLineTools.GetLineLength(e);for(let i=0,o=0;o0&&(n=greasedLineMesh_GreasedLineMesh._CopyV3(o,e),i.push(n[0],n[1],n[2]),i.push(n[0],n[1],n[2]));return n=greasedLineMesh_GreasedLineMesh._CompareV3(a-1,0,e)?greasedLineMesh_GreasedLineMesh._CopyV3(1,e):greasedLineMesh_GreasedLineMesh._CopyV3(a-1,e),i.push(n[0],n[1],n[2]),i.push(n[0],n[1],n[2]),{previous:t,next:i,uvs:s,side:r}}_createVertexBuffers(){let e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new Buffer(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));let r=new Buffer(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_nextAndCounters",0,4));let s=new Buffer(t,this._widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;let a=new Buffer(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(a.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=a,e}};greasedLineMesh_GreasedLineMesh._V_START=new math_vector_Vector3,greasedLineMesh_GreasedLineMesh._V_END=new math_vector_Vector3,greasedLineMesh_GreasedLineMesh._V_OFFSET_START=new math_vector_Vector3,greasedLineMesh_GreasedLineMesh._V_OFFSET_END=new math_vector_Vector3,mesh_Mesh._GreasedLineRibbonMeshParser=(e,t)=>greasedLineRibbonMesh_GreasedLineRibbonMesh.Parse(e,t);let greasedLineRibbonMesh_GreasedLineRibbonMesh=class greasedLineRibbonMesh_GreasedLineRibbonMesh extends GreasedLineBaseMesh{constructor(e,t,i,r){var s;if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=null!==(s=i.widths)&&void 0!==s?s:[],this._ribbonWidths=[],this._pathsOptions=null!=r?r:[],i.points&&this.addPoints(greasedLineTools_GreasedLineTools.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{let i=greasedLineRibbonMesh_GreasedLineRibbonMesh._ConvertToRibbonPath(e,o.ribbonOptions,this._scene.useRightHandedSystem,s?s[t]:s);a=this._preprocess(i,a,o)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var i,r,s;let a=e.length;if(a<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";let n=[],o=[],l=e[0];for(let t=0;t2)for(let e=0;e0&&(h[0]+=1,h[1]+=1),o.push(h[1]+(e%2!=0?a:0),h[0],h[2]),c&&o.push(h[0],h[1]+(e%2!=0?a:0),h[2])}else for(let e=0;ee.y&&e.x>e.z?i?greasedLineRibbonMesh_GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion:greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion:greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(n,n,n),s.push(c.add(h)),a.push(c.subtract(h))}r||(s.push(o[o.length-1].add(h)),a.push(o[o.length-1].subtract(h)))}return[s,a]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&(null==i?void 0:i.x)!==1?e.y===t.y?greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ:e.z===t.z?greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XY:greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ:greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={},s=[];DeepCopier.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),DeepCopier.DeepCopy(i,r,["instance"],void 0,!0);let a=new greasedLineRibbonMesh_GreasedLineRibbonMesh(e,this._scene,r,s);return t&&(a.parent=t),a.material=this.material,a}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){let i=e.lineOptions,r=e.name,s=e.pathOptions,a=new greasedLineRibbonMesh_GreasedLineRibbonMesh(r,t,i,s);return a}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){let t=e.length;this._vSegmentLengths=Array(t),this._vTotalLengths=Array(t);let i=0;for(let r=0;r=this._thinInstanceDataStorage.instancesCount)return!1;let r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},mesh_Mesh.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),!!this._userThinInstanceBuffersStorage&&!!this._userThinInstanceBuffersStorage.data[e]&&!(t>=this._thinInstanceDataStorage.instancesCount)&&(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),r&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(mesh_Mesh.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;let r=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData,s=r?r.length/16:0;e<=s&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),mesh_Mesh.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind);let r=new Buffer(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},mesh_Mesh.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!1){var s,a,n;i=i||16,"matrix"===e?(null===(s=this._thinInstanceDataStorage.matrixBuffer)||void 0===s||s.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(a=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===a||a.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),null===t?(null===(n=this._userThinInstanceBuffersStorage)||void 0===n?void 0:n.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]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new buffer_VertexBuffer(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},mesh_Mesh.prototype.thinInstanceBufferUpdated=function(e){var t,i,r;"matrix"===e?null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):"previousMatrix"===e?null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},mesh_Mesh.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var r;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===buffer_VertexBuffer.ColorKind&&(e=buffer_VertexBuffer.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},mesh_Mesh.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];let e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}getConnectedValue(e){var t,i,r;return this.isConnected?(null===(t=this._connectedPoint)||void 0===t?void 0:t._storedFunction)?null===(i=this._connectedPoint)||void 0===i?void 0:i._storedFunction(e):null===(r=this._connectedPoint)||void 0===r?void 0:r._storedValue:this.value}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=[],this._type=tU.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new observable_Observable,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===tk.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==tU.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?tk.Compatible:tk.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return tk.TypeIncompatible;let r=i,s=t;return(this.direction===tG.Input&&(r=t,s=i),r.isAnAncestorOf(s))?tk.HierarchyIssue:tk.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t0&&!this._outputs.some(e=>e.hasEndpoints)&&!this.isDebug)return!1;for(let t of(this._buildId=e.buildId,this._inputs)){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}let i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&console.log(`Building ${this.name} [${this.getClassName()}]`);let t=precisionDate_PrecisionDate.Now;for(let i of(this._buildBlock(e),this._buildExecutionTime=precisionDate_PrecisionDate.Now-t,this._outputs))for(let t of i.endpoints){let i=t.ownerBlock;i&&i.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach(e=>{let t=this.inputs.find(t=>t.name===e.name);if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value)){if("number"===e.valueType)t.value=e.value;else{let i=h[e.valueType];i&&(t.value=i.FromArray(e.value))}}}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame}; -`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); -`}return t}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` -// ${this.getClassName()} -`;for(let i of(this.comments&&(r+=`// ${this.comments} -`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); -`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,a=s.ownerBlock;-1===t.indexOf(a)&&(r+=a._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){let e=this.serialize(),t=h[e.customType];if(t){let i=new t;return i._deserialize(e),i}return null}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose();this.onBuildObservable.clear()}};__decorate([serialize("comment")],NodeGeometryBlock.prototype,"comments",void 0);let GeometryOutputBlock=class GeometryOutputBlock extends NodeGeometryBlock{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",tU.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}};h["BABYLON.GeometryOutputBlock"]=GeometryOutputBlock,function(e){e[e.None=0]="None",e[e.Positions=1]="Positions",e[e.Normals=2]="Normals",e[e.Tangents=3]="Tangents",e[e.UV=4]="UV",e[e.UV2=5]="UV2",e[e.UV3=6]="UV3",e[e.UV4=7]="UV4",e[e.UV5=8]="UV5",e[e.UV6=9]="UV6",e[e.Colors=10]="Colors",e[e.VertexID=11]="VertexID",e[e.FaceID=12]="FaceID",e[e.GeometryID=13]="GeometryID",e[e.CollectionID=14]="CollectionID",e[e.LoopID=15]="LoopID",e[e.InstanceID=16]="InstanceID"}(tz||(tz={}));let NodeGeometryBuildState=class NodeGeometryBuildState{constructor(){this._rotationMatrix=new math_vector_Matrix,this._scalingMatrix=new math_vector_Matrix,this._positionMatrix=new math_vector_Matrix,this._scalingRotationMatrix=new math_vector_Matrix,this._transformMatrix=new math_vector_Matrix,this._tempVector3=new math_vector_Vector3,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;let i=this.executionContext.getExecutionIndex();switch(e){case tz.Positions:if(this.executionContext.getOverridePositionsContextualValue)return this.executionContext.getOverridePositionsContextualValue();if(!this.geometryContext||!this.geometryContext.positions)return math_vector_Vector3.Zero();return math_vector_Vector3.FromArray(this.geometryContext.positions,3*i);case tz.Normals:if(this.executionContext.getOverrideNormalsContextualValue)return this.executionContext.getOverrideNormalsContextualValue();if(!this.geometryContext||!this.geometryContext.normals)return math_vector_Vector3.Zero();return math_vector_Vector3.FromArray(this.geometryContext.normals,3*i);case tz.Colors:if(!this.geometryContext||!this.geometryContext.colors)return math_vector_Vector4.Zero();return math_vector_Vector4.FromArray(this.geometryContext.colors,4*i);case tz.Tangents:if(!this.geometryContext||!this.geometryContext.tangents)return math_vector_Vector4.Zero();return math_vector_Vector4.FromArray(this.geometryContext.tangents,4*i);case tz.UV:if(this.executionContext.getOverrideUVs1ContextualValue)return this.executionContext.getOverrideUVs1ContextualValue();if(!this.geometryContext||!this.geometryContext.uvs)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs,2*i);case tz.UV2:if(!this.geometryContext||!this.geometryContext.uvs2)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs2,2*i);case tz.UV3:if(!this.geometryContext||!this.geometryContext.uvs3)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs3,2*i);case tz.UV4:if(!this.geometryContext||!this.geometryContext.uvs4)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs4,2*i);case tz.UV5:if(!this.geometryContext||!this.geometryContext.uvs5)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs5,2*i);case tz.UV6:if(!this.geometryContext||!this.geometryContext.uvs6)return math_vector_Vector2.Zero();return math_vector_Vector2.FromArray(this.geometryContext.uvs6,2*i);case tz.VertexID:return i;case tz.FaceID:return this.executionContext.getExecutionFaceIndex();case tz.LoopID:return this.executionContext.getExecutionLoopIndex();case tz.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case tz.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case tz.CollectionID:if(!this.geometryContext||!this.geometryContext.metadata)return 0;return this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){let i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case tU.Vector2:return new math_vector_Vector2(i,i);case tU.Vector3:return new math_vector_Vector3(i,i,i);case tU.Vector4:return new math_vector_Vector4(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;let s=e.getConnectedValue(this);if((null===(r=e._connectedPoint)||void 0===r?void 0:r.type)===t)return s;switch(t){case tU.Vector2:return new math_vector_Vector2(s,s);case tU.Vector3:return new math_vector_Vector3(s,s,s);case tU.Vector4:return new math_vector_Vector4(s,s,s,s)}return null}emitErrors(){let e="";for(let t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. -`;for(let t of this.noContextualData)e+=`Contextual input ${tz[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block). -`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){math_vector_Matrix.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),math_vector_Matrix.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),math_vector_Matrix.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${tz[this._contextualSource]}; -`;let t=[],i="";switch(this.type){case tU.Float:case tU.Int:i=`${this.value}`;break;case tU.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case tU.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case tU.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),(this.type===tU.Float||this.type===tU.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){let e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=h[e.valueType];t&&(this._storedValue=t.FromArray(e.value))}}}};h["BABYLON.GeometryInputBlock"]=GeometryInputBlock;let BoxBlock=class BoxBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",tU.Float,!0,1),this.registerInput("width",tU.Float,!0,0),this.registerInput("height",tU.Float,!0,0),this.registerInput("depth",tU.Float,!0,0),this.registerInput("subdivisions",tU.Int,!0,1),this.registerInput("subdivisionsX",tU.Int,!0,0),this.registerInput("subdivisionsY",tU.Int,!0,0),this.registerInput("subdivisionsZ",tU.Int,!0,0),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){let e=new GeometryInputBlock("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){let e=new GeometryInputBlock("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){let t={},func=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);let i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),a=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),a&&(t.depthSegments=a),CreateSegmentedBoxVertexData(t)};if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BoxBlock.prototype,"evaluateContext",void 0),h["BABYLON.BoxBlock"]=BoxBlock;let NodeGeometry=class NodeGeometry{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=NodeGeometry._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new observable_Observable,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){tools_Tools.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){let i=e&&e.editorURL?e.editorURL:NodeGeometry.EditorURL;tools_Tools.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){let t=Object.assign({nodeGeometry:this},e);this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";let r=precisionDate_PrecisionDate.Now;this._initializeBlock(this.outputBlock,i);let s=new NodeGeometryBuildState;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=NodeGeometry._BuildIdGenerator++),this._buildExecutionTime=precisionDate_PrecisionDate.Now-r,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;let i=new mesh_Mesh(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){for(let i of(e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();let i={};for(let t of e.blocks){let e=h[t.customType];if(e){let r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let r=i[t];r.attachToEndpoint(e)}}for(let r=0;re.targetConnectionName)&&!t||this._restoreConnections(a,e,i)}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){let r=e.locations||e.editorData.locations;for(let e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);let s=[];for(let e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let a=i[s.id];if(a){for(let n of s.inputs)if(i[n.targetBlockId]===e&&n.targetConnectionName===r.name){let e=a.getInputByName(n.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(a,t,i);continue}}}}generateCode(){let e=[],t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); -`;for(let s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="// Connections\n"+this.outputBlock._dumpCodeForOutputConnections(e)+"// Output nodes\n"+`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; -`+`nodeGeometry.build(); -`),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}setToDefault(){this.clear(),this.editorData=null;let e=new BoxBlock("Box");e.autoConfigure();let t=new GeometryOutputBlock("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){let t=this.serialize(),i=decorators_SerializationHelper.Clone(()=>new NodeGeometry(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){let t=e?{}:decorators_SerializationHelper.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];for(let r of(e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[],i))t.blocks.push(r.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){let t=new NodeGeometry(e);return t.setToDefault(),t.build(),t}static Parse(e){let t=decorators_SerializationHelper.Parse(()=>new NodeGeometry(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(NodeGeometry.CreateDefault("blank")):new Promise((r,s)=>{let a=new webRequest_WebRequest;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let n=JSON.parse(JSON.parse(a.responseText).jsonPayload),o=JSON.parse(n.nodeGeometry);t||(t=decorators_SerializationHelper.Parse(()=>new NodeGeometry(e),o,null)),t.parseSerializedObject(o),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)}}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};NodeGeometry._BuildIdGenerator=0,NodeGeometry.EditorURL=`${tools_Tools._DefaultCdnUrl}/v${engine_Engine.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,NodeGeometry.SnippetUrl="https://snippet.babylonjs.com",__decorate([serialize()],NodeGeometry.prototype,"name",void 0),__decorate([serialize("comment")],NodeGeometry.prototype,"comment",void 0);let GeometryOptimizeBlock=class GeometryOptimizeBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=.001,this.registerInput("geometry",tU.Geometry),this.registerOutput("output",tU.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e),i=[],r={};for(let e=0;er[e]),s};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`+`${this._codeVariableName}.epsilon = ${this.epsilon}; -`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryOptimizeBlock.prototype,"evaluateContext",void 0),__decorate([editableInPropertyPage("Epsilon",em.Float,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryOptimizeBlock.prototype,"epsilon",void 0),h["BABYLON.GeometryOptimizeBlock"]=GeometryOptimizeBlock;let PlaneBlock=class PlaneBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",tU.Float,!0,1),this.registerInput("width",tU.Float,!0,0),this.registerInput("height",tU.Float,!0,0),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){let e=new GeometryInputBlock("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){let t={},func=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),CreatePlaneVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],PlaneBlock.prototype,"evaluateContext",void 0),h["BABYLON.PlaneBlock"]=PlaneBlock;let MeshBlock=class MeshBlock extends NodeGeometryBlock{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",tU.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}let e=mesh_vertexData_VertexData.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){let e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=mesh_vertexData_VertexData.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=mesh_vertexData_VertexData.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}};__decorate([editableInPropertyPage("Serialize cached data",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],MeshBlock.prototype,"serializedCachedData",void 0),h["BABYLON.MeshBlock"]=MeshBlock;let IcoSphereBlock=class IcoSphereBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",tU.Float,!0,1),this.registerInput("radiusX",tU.Float,!0,0),this.registerInput("radiusY",tU.Float,!0,0),this.registerInput("radiusZ",tU.Float,!0,0),this.registerInput("subdivisions",tU.Int,!0,4),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),CreateIcoSphereVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],IcoSphereBlock.prototype,"evaluateContext",void 0),h["BABYLON.IcoSphereBlock"]=IcoSphereBlock;let SphereBlock=class SphereBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",tU.Int,!0,32),this.registerInput("diameter",tU.Float,!0,1),this.registerInput("diameterX",tU.Float,!0,0),this.registerInput("diameterY",tU.Float,!0,0),this.registerInput("diameterZ",tU.Float,!0,0),this.registerInput("arc",tU.Float,!0,1),this.registerInput("slice",tU.Float,!0,1),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},func=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),CreateSphereVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SphereBlock.prototype,"evaluateContext",void 0),h["BABYLON.SphereBlock"]=SphereBlock;let GridBlock=class GridBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",tU.Float,!0,1),this.registerInput("height",tU.Float,!0,1),this.registerInput("subdivisions",tU.Int,!0,1),this.registerInput("subdivisionsX",tU.Int,!0,0),this.registerInput("subdivisionsY",tU.Int,!0,0),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},func=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),CreateGroundVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GridBlock.prototype,"evaluateContext",void 0),h["BABYLON.GridBlock"]=GridBlock;let TorusBlock=class TorusBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",tU.Float,!0,1),this.registerInput("thickness",tU.Float,!0,.5),this.registerInput("tessellation",tU.Int,!0,16),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},func=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),CreateTorusVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],TorusBlock.prototype,"evaluateContext",void 0),h["BABYLON.TorusBlock"]=TorusBlock;let CylinderBlock=class CylinderBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",tU.Float,!0,25),this.registerInput("diameter",tU.Float,!0,1),this.registerInput("diameterTop",tU.Float,!0,-1),this.registerInput("diameterBottom",tU.Float,!0,-1),this.registerInput("subdivisions",tU.Int,!0,1),this.registerInput("tessellation",tU.Int,!0,24),this.registerInput("arc",tU.Float,!0,1),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},func=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),CreateCylinderVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CylinderBlock.prototype,"evaluateContext",void 0),h["BABYLON.CylinderBlock"]=CylinderBlock;let CapsuleBlock=class CapsuleBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",tU.Float,!0,1),this.registerInput("radius",tU.Float,!0,.25),this.registerInput("tessellation",tU.Int,!0,16),this.registerInput("subdivisions",tU.Int,!0,2),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),CreateCapsuleVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CapsuleBlock.prototype,"evaluateContext",void 0),h["BABYLON.CapsuleBlock"]=CapsuleBlock;let DiscBlock=class DiscBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",tU.Float,!0,.5),this.registerInput("tessellation",tU.Int,!0,64),this.registerInput("arc",tU.Float,!0,1),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),CreateDiscVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],DiscBlock.prototype,"evaluateContext",void 0),h["BABYLON.DiscBlock"]=DiscBlock;let NullBlock=class NullBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerOutput("geometry",tU.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}};h["BABYLON.NullBlock"]=NullBlock;let SetPositionsBlock=class SetPositionsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("positions",tU.Vector3),this.registerOutput("output",tU.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}let t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndext.getConnectedValue(e)+i.getConnectedValue(e):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case tW.Subtract:e=r?e=>t.getConnectedValue(e)-i.getConnectedValue(e):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case tW.Multiply:e=r?e=>t.getConnectedValue(e)*i.getConnectedValue(e):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case tW.Divide:e=r?e=>t.getConnectedValue(e)/i.getConnectedValue(e):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case tW.Min:if(r)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case tU.Vector2:e=e=>math_vector_Vector2.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tU.Vector3:e=e=>math_vector_Vector3.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tU.Vector4:e=e=>math_vector_Vector4.Minimize(t.getConnectedValue(e),e.adapt(i,t.type))}break;case tW.Max:if(r)e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case tU.Vector2:e=e=>math_vector_Vector2.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tU.Vector3:e=e=>math_vector_Vector3.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case tU.Vector4:e=e=>math_vector_Vector4.Maximize(t.getConnectedValue(e),e.adapt(i,t.type))}}this.output._storedFunction=i=>t.type===tU.Int?0|e(i):e(i)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${tW[this.operation]}; -`;return e}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}};__decorate([editableInPropertyPage("Operation",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:tW.Add},{label:"Subtract",value:tW.Subtract},{label:"Multiply",value:tW.Multiply},{label:"Divide",value:tW.Divide},{label:"Max",value:tW.Max},{label:"Min",value:tW.Min}]})],MathBlock.prototype,"operation",void 0),h["BABYLON.MathBlock"]=MathBlock;let MapRangeBlock=class MapRangeBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("value",tU.AutoDetect),this.registerInput("fromMin",tU.Float,!0,0),this.registerInput("fromMax",tU.Float,!0,1),this.registerInput("toMin",tU.Float,!0,0),this.registerInput("toMax",tU.Float,!0,1),this.registerOutput("output",tU.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tU.Vector2),this._inputs[0].excludedConnectionPointTypes.push(tU.Vector3),this._inputs[0].excludedConnectionPointTypes.push(tU.Vector4),this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{let t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),a=this.toMax.getConnectedValue(e),n=(t-i)/(r-i)*(a-s)+s;return this.output.type===tU.Int?Math.floor(n):n}}};h["BABYLON.MapRangeBlock"]=MapRangeBlock,function(e){e[e.Equal=0]="Equal",e[e.NotEqual=1]="NotEqual",e[e.LessThan=2]="LessThan",e[e.GreaterThan=3]="GreaterThan",e[e.LessOrEqual=4]="LessOrEqual",e[e.GreaterOrEqual=5]="GreaterOrEqual",e[e.Xor=6]="Xor",e[e.Or=7]="Or",e[e.And=8]="And"}(tH||(tH={}));let ConditionBlock=class ConditionBlock extends NodeGeometryBlock{constructor(e){super(e),this.test=tH.Equal,this.registerInput("left",tU.Float),this.registerInput("right",tU.Float,!0,0),this.registerInput("ifTrue",tU.AutoDetect,!0,1),this.registerInput("ifFalse",tU.AutoDetect,!0,0),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=tU.Float,this._inputs[0].acceptedConnectionPointTypes.push(tU.Int),this._inputs[1].acceptedConnectionPointTypes.push(tU.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e),r=!1;switch(this.test){case tH.Equal:r=math_scalar_Scalar.WithinEpsilon(t,i,.001);break;case tH.NotEqual:r=t!==i;break;case tH.LessThan:r=ti;break;case tH.LessOrEqual:r=t<=i;break;case tH.GreaterOrEqual:r=t>=i;break;case tH.Xor:r=!!t&&!i||!t&&!!i;break;case tH.Or:r=!!t||!!i;break;case tH.And:r=!!t&&!!i}return r};this.output._storedFunction=e=>func(e)?this.ifTrue.getConnectedValue(e):this.ifFalse.getConnectedValue(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${tH[this.test]}; -`;return e}serialize(){let e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}};__decorate([editableInPropertyPage("Test",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:tH.Equal},{label:"NotEqual",value:tH.NotEqual},{label:"LessThan",value:tH.LessThan},{label:"GreaterThan",value:tH.GreaterThan},{label:"LessOrEqual",value:tH.LessOrEqual},{label:"GreaterOrEqual",value:tH.GreaterOrEqual},{label:"Xor",value:tH.Xor},{label:"Or",value:tH.Or},{label:"And",value:tH.And}]})],ConditionBlock.prototype,"test",void 0),h["BABYLON.ConditionBlock"]=ConditionBlock,function(e){e[e.None=0]="None",e[e.LoopID=1]="LoopID",e[e.InstanceID=2]="InstanceID"}(tX||(tX={}));let RandomBlock=class RandomBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentLockId=-1,this.lockMode=tX.None,this.registerInput("min",tU.AutoDetect),this.registerInput("max",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture),this._inputs[1].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[1].excludedConnectionPointTypes.push(tU.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){let e=new GeometryInputBlock("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){let e=new GeometryInputBlock("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case tU.Int:case tU.Float:e=e=>{let t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case tU.Vector2:e=e=>{let t=this.min.getConnectedValue(e)||math_vector_Vector2.Zero(),i=this.max.getConnectedValue(e)||math_vector_Vector2.Zero();return new math_vector_Vector2(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case tU.Vector3:e=e=>{let t=this.min.getConnectedValue(e)||math_vector_Vector3.Zero(),i=this.max.getConnectedValue(e)||math_vector_Vector3.Zero();return new math_vector_Vector3(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case tU.Vector4:e=e=>{let t=this.min.getConnectedValue(e)||math_vector_Vector4.Zero(),i=this.max.getConnectedValue(e)||math_vector_Vector4.Zero();return new math_vector_Vector4(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==tX.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case tX.InstanceID:i=t.getContextualValue(tz.InstanceID,!0)||0;break;case tX.LoopID:i=t.getContextualValue(tz.LoopID,!0)||0}return this._currentLockId!==i&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${tX[this.lockMode]}; -`;return e}serialize(){let e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}};__decorate([editableInPropertyPage("LockMode",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:tX.None},{label:"LoopID",value:tX.LoopID},{label:"InstanceID",value:tX.InstanceID}]})],RandomBlock.prototype,"lockMode",void 0),h["BABYLON.RandomBlock"]=RandomBlock;let NoiseBlock=class NoiseBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("offset",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scale",tU.Float,!0,1),this.registerInput("octaves",tU.Float,!0,2,0,16),this.registerInput("roughness",tU.Float,!0,.5,0,1),this.registerOutput("output",tU.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,r){let s=15&e,a=s<8?t:i,n=12===s||14==s?t:r,o=s<4?i:n;return this._negateIf(a,s&a)+this._negateIf(o,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let r,s,a;return r=s=a=3735928584,a+=i,s+=t,r+=e,a^=s,a-=this._hashBitRotate(s,14),r^=a,r-=this._hashBitRotate(a,11),s^=r,s-=this._hashBitRotate(r,25),a^=s,a-=this._hashBitRotate(s,16),r^=a,r-=this._hashBitRotate(a,4),s^=r,s-=this._hashBitRotate(r,14),a^=s,a-=this._hashBitRotate(s,24)}_mix(e,t,i,r,s,a,n,o,l,h,c){let u=1-l,d=1-h;return(1-c)*(d*(e*u+t*l)+h*(i*u+r*l))+c*(d*(s*u+a*l)+h*(n*u+o*l))}_perlinNoise(e){let t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,a=e.y-i,n=e.z-r,o=this._fade(s),l=this._fade(a),h=this._fade(n);return this._mix(this._noiseGrad(this._hash(t,i,r),s,a,n),this._noiseGrad(this._hash(t+1,i,r),s-1,a,n),this._noiseGrad(this._hash(t,i+1,r),s,a-1,n),this._noiseGrad(this._hash(t+1,i+1,r),s-1,a-1,n),this._noiseGrad(this._hash(t,i,r+1),s,a,n-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,a,n-1),this._noiseGrad(this._hash(t,i+1,r+1),s,a-1,n-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,a-1,n-1),o,l,h)}_perlinSigned(e){return .982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){let a=new math_vector_Vector3(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z),n=1,o=1,l=0,h=0;e=math_scalar_Scalar.Clamp(e,0,15);let c=0|e;for(let e=0;e<=c;e++){let e=this._perlin(a.scale(n));h+=e*o,l+=o,o*=math_scalar_Scalar.Clamp(t,0,1),n*=2}let u=e-Math.floor(e);if(0==u)return h/l;let d=this._perlin(a.scale(n)),_=h+d*o;return(1-u)*(h/=l)+u*(_/=l+o)}_buildBlock(){this.output._storedFunction=e=>{let t=e.getContextualValue(tz.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),a=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,a)}}};h["BABYLON.NoiseBlock"]=NoiseBlock;let MergeGeometryBlock=class MergeGeometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",tU.Geometry),this.registerInput("geometry1",tU.Geometry,!0),this.registerInput("geometry2",tU.Geometry,!0),this.registerInput("geometry3",tU.Geometry,!0),this.registerInput("geometry4",tU.Geometry,!0),this.registerOutput("output",tU.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{let t=this.geometry0.getConnectedValue(e),i=[];if(this.geometry1.isConnected){let t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){let t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){let t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){let t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],MergeGeometryBlock.prototype,"evaluateContext",void 0),h["BABYLON.MergeGeometryBlock"]=MergeGeometryBlock;let GeometryCollectionBlock=class GeometryCollectionBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",tU.Geometry,!0),this.registerInput("geometry1",tU.Geometry,!0),this.registerInput("geometry2",tU.Geometry,!0),this.registerInput("geometry3",tU.Geometry,!0),this.registerInput("geometry4",tU.Geometry,!0),this.registerInput("geometry5",tU.Geometry,!0),this.registerInput("geometry6",tU.Geometry,!0),this.registerInput("geometry7",tU.Geometry,!0),this.registerInput("geometry8",tU.Geometry,!0),this.registerInput("geometry9",tU.Geometry,!0),this.registerOutput("output",tU.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){let s=e.getConnectedValue(t);s&&(s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s))}}_buildBlock(e){let func=e=>{let t=[];return(this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length)?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryCollectionBlock.prototype,"evaluateContext",void 0),h["BABYLON.GeometryCollectionBlock"]=GeometryCollectionBlock;let GeometryElbowBlock=class GeometryElbowBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("input",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}};h["BABYLON.GeometryElbowBlock"]=GeometryElbowBlock;let ComputeNormalsBlock=class ComputeNormalsBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",tU.Geometry),this.registerOutput("output",tU.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),mesh_vertexData_VertexData.ComputeNormals(t.positions,t.indices,t.normals),t}}};h["BABYLON.ComputeNormalsBlock"]=ComputeNormalsBlock;let VectorConverterBlock=class VectorConverterBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("xyzw ",tU.Vector4,!0),this.registerInput("xyz ",tU.Vector3,!0),this.registerInput("xy ",tU.Vector2,!0),this.registerInput("zw ",tU.Vector2,!0),this.registerInput("x ",tU.Float,!0),this.registerInput("y ",tU.Float,!0),this.registerInput("z ",tU.Float,!0),this.registerInput("w ",tU.Float,!0),this.registerOutput("xyzw",tU.Vector4),this.registerOutput("xyz",tU.Vector3),this.registerOutput("xy",tU.Vector2),this.registerOutput("zw",tU.Vector2),this.registerOutput("x",tU.Float),this.registerOutput("y",tU.Float),this.registerOutput("z",tU.Float),this.registerOutput("w",tU.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,a=this.xyIn,n=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,c=this.xyzOut,u=this.xyOut,d=this.zwOut,_=this.xOut,p=this.yOut,f=this.zOut,m=this.wOut,getData=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,c=0,u=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(c=i.getConnectedValue(e)),r.isConnected&&(u=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),a.isConnected){let t=a.getConnectedValue(e);t&&(h=t.x,c=t.y)}if(n.isConnected){let t=n.getConnectedValue(e);t&&(u=t.x,d=t.y)}if(o.isConnected){let t=o.getConnectedValue(e);t&&(h=t.x,c=t.y,u=t.z)}return new math_vector_Vector4(h,c,u,d)};h._storedFunction=e=>getData(e),c._storedFunction=e=>{let t=getData(e);return new math_vector_Vector3(t.x,t.y,t.z)},u._storedFunction=e=>{let t=getData(e);return new math_vector_Vector2(t.x,t.y)},d._storedFunction=e=>{let t=getData(e);return new math_vector_Vector2(t.z,t.w)},_._storedFunction=e=>getData(e).x,p._storedFunction=e=>getData(e).y,f._storedFunction=e=>getData(e).z,m._storedFunction=e=>getData(e).w}};h["BABYLON.VectorConverterBlock"]=VectorConverterBlock;let NormalizeVectorBlock=class NormalizeVectorBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("input",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(tU.Float),this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize()}};h["BABYLON.NormalizeVectorBlock"]=NormalizeVectorBlock;let SetMaterialIDBlock=class SetMaterialIDBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("id",tU.Int,!0,0),this.registerOutput("output",tU.Geometry),this.id.acceptedConnectionPointTypes.push(tU.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;let i=new VertexDataMaterialInfo;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetMaterialIDBlock.prototype,"evaluateContext",void 0),h["BABYLON.SetMaterialIDBlock"]=SetMaterialIDBlock,function(e){e[e.Cos=0]="Cos",e[e.Sin=1]="Sin",e[e.Abs=2]="Abs",e[e.Exp=3]="Exp",e[e.Round=4]="Round",e[e.Floor=5]="Floor",e[e.Ceiling=6]="Ceiling",e[e.Sqrt=7]="Sqrt",e[e.Log=8]="Log",e[e.Tan=9]="Tan",e[e.ArcTan=10]="ArcTan",e[e.ArcCos=11]="ArcCos",e[e.ArcSin=12]="ArcSin",e[e.Sign=13]="Sign",e[e.Negate=14]="Negate",e[e.OneMinus=15]="OneMinus",e[e.Reciprocal=16]="Reciprocal",e[e.ToDegrees=17]="ToDegrees",e[e.ToRadians=18]="ToRadians"}(tY||(tY={}));let GeometryTrigonometryBlock=class GeometryTrigonometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.operation=tY.Cos,this.registerInput("input",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case tY.Cos:t=e=>Math.cos(e);break;case tY.Sin:t=e=>Math.sin(e);break;case tY.Abs:t=e=>Math.abs(e);break;case tY.Exp:t=e=>Math.exp(e);break;case tY.Round:t=e=>Math.round(e);break;case tY.Floor:t=e=>Math.floor(e);break;case tY.Ceiling:t=e=>Math.ceil(e);break;case tY.Sqrt:t=e=>Math.sqrt(e);break;case tY.Log:t=e=>Math.log(e);break;case tY.Tan:t=e=>Math.tan(e);break;case tY.ArcTan:t=e=>Math.atan(e);break;case tY.ArcCos:t=e=>Math.acos(e);break;case tY.ArcSin:t=e=>Math.asin(e);break;case tY.Sign:t=e=>Math.sign(e);break;case tY.Negate:t=e=>-e;break;case tY.OneMinus:t=e=>1-e;break;case tY.Reciprocal:t=e=>1/e;break;case tY.ToRadians:t=e=>e*Math.PI/180;break;case tY.ToDegrees:t=e=>180*e/Math.PI}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case tU.Int:case tU.Float:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return t(i)};break;case tU.Vector2:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new math_vector_Vector2(t(i.x),t(i.y))};break;case tU.Vector3:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new math_vector_Vector3(t(i.x),t(i.y),t(i.z))};break;case tU.Vector4:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new math_vector_Vector4(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${tY[this.operation]}; -`;return e}};__decorate([editableInPropertyPage("Operation",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:tY.Cos},{label:"Sin",value:tY.Sin},{label:"Abs",value:tY.Abs},{label:"Exp",value:tY.Exp},{label:"Round",value:tY.Round},{label:"Floor",value:tY.Floor},{label:"Ceiling",value:tY.Ceiling},{label:"Sqrt",value:tY.Sqrt},{label:"Log",value:tY.Log},{label:"Tan",value:tY.Tan},{label:"ArcTan",value:tY.ArcTan},{label:"ArcCos",value:tY.ArcCos},{label:"ArcSin",value:tY.ArcSin},{label:"Sign",value:tY.Sign},{label:"Negate",value:tY.Negate},{label:"OneMinus",value:tY.OneMinus},{label:"Reciprocal",value:tY.Reciprocal},{label:"ToDegrees",value:tY.ToDegrees},{label:"ToRadians",value:tY.ToRadians}]})],GeometryTrigonometryBlock.prototype,"operation",void 0),h["BABYLON.GeometryTrigonometryBlock"]=GeometryTrigonometryBlock;let GeometryTransformBlock=class GeometryTransformBlock extends NodeGeometryBlock{constructor(e){super(e),this._rotationMatrix=new math_vector_Matrix,this._scalingMatrix=new math_vector_Matrix,this._translationMatrix=new math_vector_Matrix,this._scalingRotationMatrix=new math_vector_Matrix,this._transformMatrix=new math_vector_Matrix,this.evaluateContext=!0,this.registerInput("value",tU.AutoDetect),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("translation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tU.Float),this._inputs[0].excludedConnectionPointTypes.push(tU.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t;let i=this.value.getConnectedValue(e);if(!i)return null;if(this.matrix.isConnected)t=this.matrix.getConnectedValue(e);else{let i=this.scaling.getConnectedValue(e),r=this.rotation.getConnectedValue(e),s=this.translation.getConnectedValue(e);math_vector_Matrix.ScalingToRef(i.x,i.y,i.z,this._scalingMatrix),math_vector_Matrix.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),math_vector_Matrix.TranslationToRef(s.x,s.y,s.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),t=this._transformMatrix}switch(this.value.type){case tU.Geometry:{let e=i.clone();return e.transform(t),e}case tU.Vector2:return math_vector_Vector2.Transform(i,t);case tU.Vector3:return math_vector_Vector3.TransformCoordinates(i,t);case tU.Vector4:return math_vector_Vector4.TransformCoordinates(i,t)}return null};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTransformBlock.prototype,"evaluateContext",void 0),h["BABYLON.GeometryTransformBlock"]=GeometryTransformBlock;let RotationXBlock=class RotationXBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",tU.Float,!1,0),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>math_vector_Matrix.RotationX(this.angle.getConnectedValue(e))}};h["BABYLON.RotationXBlock"]=RotationXBlock;let RotationYBlock=class RotationYBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",tU.Float,!1,0),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>math_vector_Matrix.RotationY(this.angle.getConnectedValue(e))}};h["BABYLON.RotationYBlock"]=RotationYBlock;let RotationZBlock=class RotationZBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",tU.Float,!1,0),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>math_vector_Matrix.RotationZ(this.angle.getConnectedValue(e))}};h["BABYLON.RotationZBlock"]=RotationZBlock;let ScalingBlock=class ScalingBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("scale",tU.Vector3,!1,math_vector_Vector3.One()),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){let e=new GeometryInputBlock("Scale");e.value=new math_vector_Vector3(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.scale.getConnectedValue(e);return math_vector_Matrix.Scaling(t.x,t.y,t.z)}}};h["BABYLON.ScalingBlock"]=ScalingBlock;let AlignBlock=class AlignBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("source",tU.Vector3,!0,math_vector_Vector3.Up()),this.registerInput("target",tU.Vector3,!0,math_vector_Vector3.Left()),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new math_vector_Matrix;return t.normalize(),i.normalize(),math_vector_Matrix.RotationAlignToRef(t,i,r,!0),r}}};h["BABYLON.AlignBlock"]=AlignBlock;let TranslationBlock=class TranslationBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("translation",tU.Vector3,!1,math_vector_Vector3.Zero()),this.registerOutput("matrix",tU.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){let e=new GeometryInputBlock("Translation");e.value=new math_vector_Vector3(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.translation.getConnectedValue(e);return math_vector_Matrix.Translation(t.x,t.y,t.z)}}};h["BABYLON.TranslationBlock"]=TranslationBlock;let InstantiateOnVerticesBlock=class InstantiateOnVerticesBlock extends NodeGeometryBlock{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("instance",tU.Geometry,!0),this.registerInput("density",tU.Float,!0,1,0,1),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.scaling.acceptedConnectionPointTypes.push(tU.Float),this.registerOutput("output",tU.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3,i=[],r=new math_vector_Vector3,s=[],a=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexMath.abs(s[a]-e)&&.001>Math.abs(s[a+1]-t)&&.001>Math.abs(s[a+2]-i)){r=!0;break}r||(this._indexTranslation[s.length/3]=this._currentIndex,s.push(e,t,i))}t=(a=s).length/3}else this._indexTranslation=null;for(this._currentIndex=0;this._currentIndexs)continue;r.fromArray(a,3*this._currentIndex);let n=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(n,r,t,i)}else{let t=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly),s=this.rotation.getConnectedValue(e)||math_vector_Vector3.ZeroReadOnly;e._instantiate(n,r,s,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; -`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`}serialize(){let e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnVerticesBlock.prototype,"evaluateContext",void 0),__decorate([editableInPropertyPage("Remove duplicated positions",em.Boolean,"ADVANCED",{notifiers:{update:!0}})],InstantiateOnVerticesBlock.prototype,"removeDuplicatedPositions",void 0),h["BABYLON.InstantiateOnVerticesBlock"]=InstantiateOnVerticesBlock;let InstantiateOnFacesBlock=class InstantiateOnFacesBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentPosition=new math_vector_Vector3,this._currentUV=new math_vector_Vector2,this._vertex0=new math_vector_Vector3,this._vertex1=new math_vector_Vector3,this._vertex2=new math_vector_Vector3,this._tempVector0=new math_vector_Vector3,this._tempVector1=new math_vector_Vector3,this._uv0=new math_vector_Vector2,this._uv1=new math_vector_Vector2,this._uv2=new math_vector_Vector2,this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("instance",tU.Geometry,!0),this.registerInput("count",tU.Int,!0,256),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.scaling.acceptedConnectionPointTypes.push(tU.Float),this.registerOutput("output",tU.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),math_vector_Vector3.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r,a=0,n=[],o=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),r=Math.random();if(i>r){let e=i;i=r,r=e}let l=i,h=r-i,c=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+c*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+c*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+c*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+c*this._uv2.x,l*this._uv0.y+h*this._uv1.y+c*this._uv2.y),!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length){a-=s;continue}let u=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,n)}else{let t=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly),i=this.rotation.getConnectedValue(e)||math_vector_Vector3.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,n)}o++,this._currentLoopIndex++}}if(n.length){if(1===n.length)this._vertexData=n[0];else{let e=n.splice(0,1)[0];this._vertexData=e.merge(n,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnFacesBlock.prototype,"evaluateContext",void 0),h["BABYLON.InstantiateOnFacesBlock"]=InstantiateOnFacesBlock;let InstantiateOnVolumeBlock=class InstantiateOnVolumeBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentPosition=new math_vector_Vector3,this._vertex0=new math_vector_Vector3,this._vertex1=new math_vector_Vector3,this._vertex2=new math_vector_Vector3,this.evaluateContext=!0,this.registerInput("geometry",tU.Geometry),this.registerInput("instance",tU.Geometry,!0),this.registerInput("count",tU.Int,!0,256),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.scaling.acceptedConnectionPointTypes.push(tU.Float),this.registerOutput("output",tU.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=[],s=extractMinAndMax(this._vertexData.positions,0,this._vertexData.positions.length/3),a=s.minimum,n=s.maximum,o=new math_vector_Vector3(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let s=0;s0&&h++}if(h%2==0){s--;continue}if(!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length)continue;let c=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,r)}else{let t=e.adaptInput(this.scaling,tU.Vector3,math_vector_Vector3.OneReadOnly),i=this.rotation.getConnectedValue(e)||math_vector_Vector3.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,r)}this._currentLoopIndex++}if(r.length){if(1===r.length)this._vertexData=r[0];else{let e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnVolumeBlock.prototype,"evaluateContext",void 0),h["BABYLON.InstantiateOnVolumeBlock"]=InstantiateOnVolumeBlock;let InstantiateBaseBlock=class InstantiateBaseBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",tU.Geometry,!0),this.registerInput("count",tU.Int,!0,1),this.registerOutput("output",tU.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateBaseBlock.prototype,"evaluateContext",void 0);let InstantiateBlock=class InstantiateBlock extends InstantiateBaseBlock{constructor(e){super(e),this.registerInput("matrix",tU.Matrix,!0),this.registerInput("position",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("rotation",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerInput("scaling",tU.Vector3,!0,math_vector_Vector3.One()),this.scaling.acceptedConnectionPointTypes.push(tU.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){let func=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=math_vector_Matrix.Identity(),s=math_vector_Vector3.Zero(),a=math_vector_Vector3.Zero(),n=math_vector_Vector3.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=math_vector_Matrix.Identity(),s=math_vector_Matrix.Identity(),a=math_vector_Matrix.Identity(),n=math_vector_Vector3.Zero(),o=math_vector_Vector3.Zero(),l=math_vector_Vector3.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}};h["BABYLON.IntFloatConverterBlock"]=IntFloatConverterBlock;let DebugBlock=class DebugBlock extends NodeGeometryBlock{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",tU.AutoDetect),this.registerOutput("output",tU.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tU.Geometry),this._inputs[0].excludedConnectionPointTypes.push(tU.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];let func=e=>{let t=this.input.getConnectedValue(e);return null==t?this.log.push("null"):this.log.push(t.toString()),t};this.output.isConnected?this.output._storedFunction=func:this.output._storedValue=func(e)}};h["BABYLON.DebugBlock"]=DebugBlock;let GeometryInfoBlock=class GeometryInfoBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",tU.Geometry),this.registerOutput("output",tU.Geometry),this.registerOutput("id",tU.Int),this.registerOutput("collectionId",tU.Int),this.registerOutput("verticesCount",tU.Int),this.registerOutput("facesCount",tU.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}};h["BABYLON.GeometryInfoBlock"]=GeometryInfoBlock,function(e){e[e.Spherical=0]="Spherical",e[e.Cylindrical=1]="Cylindrical",e[e.Cubic=2]="Cubic"}(tj||(tj={}));let MappingBlock=class MappingBlock extends NodeGeometryBlock{constructor(e){super(e),this.mapping=tj.Spherical,this.registerInput("position",tU.Vector3),this.registerInput("normal",tU.Vector3),this.registerInput("center",tU.Vector3,!0,math_vector_Vector3.Zero()),this.registerOutput("uv",tU.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}let e=math_vector_Vector3.Zero(),func=t=>{let i=this.position.getConnectedValue(t)||math_vector_Vector3.Zero(),r=this.normal.getConnectedValue(t)||math_vector_Vector3.Zero(),s=this.center.getConnectedValue(t),a=math_vector_Vector2.Zero();switch(this.mapping){case tj.Spherical:{i.subtractToRef(s,e);let t=e.length();t>0&&(a.x=Math.acos(e.y/t)/Math.PI,(0!==e.x||0!==e.z)&&(a.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case tj.Cylindrical:{i.subtractToRef(s,e);let t=e.length();t>0&&(a.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),a.y=(e.y+1)/2);break}case tj.Cubic:{let e=Math.abs(r.x),t=Math.abs(r.y),n=Math.abs(r.z),o=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),l=0,h=0;e>=t&&e>=n?(l=i.y/o-s.y,h=i.z/o-s.z):t>=e&&t>=n?(l=i.x/o-s.x,h=i.z/o-s.z):(l=i.x/o-s.x,h=i.y/o-s.y),a.x=(l+1)/2,a.y=(h+1)/2}}return a};this.uv._storedFunction=e=>func(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${tj[this.mapping]}; -`;return e}serialize(){let e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}};__decorate([editableInPropertyPage("Mapping",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:tj.Spherical},{label:"Cylindrical",value:tj.Cylindrical},{label:"Cubic",value:tj.Cubic}]})],MappingBlock.prototype,"mapping",void 0),h["BABYLON.MappingBlock"]=MappingBlock;let MatrixComposeBlock=class MatrixComposeBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("matrix0",tU.Matrix),this.registerInput("matrix1",tU.Matrix),this.registerOutput("output",tU.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;let t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}};h["BABYLON.MatrixComposeBlock"]=MatrixComposeBlock;let TeleportInBlock=class TeleportInBlock extends NodeGeometryBlock{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",tU.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this.endpoints){let i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(let e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}};h["BABYLON.TeleportInBlock"]=TeleportInBlock;let TeleportOutBlock=class TeleportOutBlock extends NodeGeometryBlock{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",tU.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){let e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); -`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}};h["BABYLON.TeleportOutBlock"]=TeleportOutBlock;let GeometryTextureBlock=class GeometryTextureBlock extends NodeGeometryBlock{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",tU.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{let r=new Image,s=document.createElement("canvas"),a=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,a.drawImage(r,0,0);let e=a.getImageData(0,0,r.width,r.height),i=e.data,n=new Float32Array(i.length);for(let e=0;e{this._data=null,i()},r.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}let r=e.getSize();rF.GetTextureDataAsync(e,r.width,r.height).then(async e=>{let i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){let func=e=>{let t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;let i=this.coordinates.getConnectedValue(e);if(!i)return null;let r=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),s=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),a=Math.floor(r*(t.width-1)),n=Math.floor(s*(t.height-1)),o=a+t.width*n;return math_vector_Vector4.FromArray(t.data,4*o)};this.rgba._storedFunction=e=>func(e),this.rgb._storedFunction=e=>{let t=func(e);return t?t.toVector3():null},this.r._storedFunction=e=>{let t=func(e);return t?t.x:null},this.g._storedFunction=e=>{let t=func(e);return t?t.y:null},this.b._storedFunction=e=>{let t=func(e);return t?t.z:null},this.a._storedFunction=e=>{let t=func(e);return t?t.w:null}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates}; -`;return e}serialize(){let e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}};__decorate([editableInPropertyPage("Clamp Coordinates",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTextureFetchBlock.prototype,"clampCoordinates",void 0),h["BABYLON.GeometryTextureFetchBlock"]=GeometryTextureFetchBlock;let BoundingBlock=class BoundingBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",tU.Geometry),this.registerOutput("min",tU.Vector3),this.registerOutput("max",tU.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);if(!t)return null;let i=extractMinAndMax(t.positions,0,t.positions.length/3);return i.minimum},this.max._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);if(!t)return null;let i=extractMinAndMax(t.positions,0,t.positions.length/3);return i.maximum}}};h["BABYLON.BoundingBlock"]=BoundingBlock,function(e){e[e.Intersect=0]="Intersect",e[e.Subtract=1]="Subtract",e[e.Union=2]="Union"}(tK||(tK={}));let BooleanGeometryBlock=class BooleanGeometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.operation=tK.Intersect,this.registerInput("geometry0",tU.Geometry),this.registerInput("geometry1",tU.Geometry),this.registerOutput("output",tU.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{let t;let i=this.geometry0.getConnectedValue(e),r=this.geometry1.getConnectedValue(e);if(!i||!r)return null;let s=i.positions.length/3;!i.normals&&r.normals&&(i.normals=Array(i.positions.length)),!r.normals&&i.normals&&(r.normals=Array(r.positions.length)),!i.uvs&&r.uvs&&(i.uvs=Array(2*s)),!r.uvs&&i.uvs&&(r.uvs=Array(2*s)),!i.colors&&r.colors&&(i.colors=Array(4*s)),!r.colors&&i.colors&&(r.colors=Array(4*s));let a=CSG.FromVertexData(i),n=CSG.FromVertexData(r);switch(this.operation){case tK.Intersect:t=a.intersect(n);break;case tK.Subtract:t=a.subtract(n);break;case tK.Union:t=a.union(n)}return t.toVertexData()};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`+`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${tK[this.operation]}; -`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}};__decorate([editableInPropertyPage("Evaluate context",em.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BooleanGeometryBlock.prototype,"evaluateContext",void 0),__decorate([editableInPropertyPage("Operation",em.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:tK.Intersect},{label:"Subtract",value:tK.Subtract},{label:"Union",value:tK.Union}]})],BooleanGeometryBlock.prototype,"operation",void 0),h["BABYLON.BooleanGeometryBlock"]=BooleanGeometryBlock,engine_Engine.OfflineProviderFactory=(e,t,i=!1)=>new Database(e,t,i);let Database=class Database{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=Database._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,Database.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,tools_Tools.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){let noManifestFile=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},createManifestURL=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){let e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`},t=!1,i=createManifestURL(),r=new webRequest_WebRequest;navigator.onLine&&(t=!0,i=i+(null==i.match(/\?/)?"?":"&")+Date.now()),r.open("GET",i),r.addEventListener("load",()=>{if(200===r.status||Database._ValidateXHRData(r,1))try{let t=JSON.parse(r.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&Database._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){noManifestFile()}else noManifestFile()},!1),r.addEventListener("error",()=>{if(t){t=!1;let e=createManifestURL();r.open("GET",e),r.send()}else noManifestFile()},!1);try{r.send()}catch(t){logger_Logger.Error("Error on XHR send request."),e(!1)}}open(e,t){let handleError=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline)){if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;let t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{handleError()},t.onblocked=()=>{logger_Logger.Error("IDB request blocked. Please reload the page."),handleError()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){logger_Logger.Error("Error while creating object stores. Exception: "+e.message),handleError()}}}}else this._isSupported=!1,t&&t()}loadImage(e,t){let i=Database._ReturnFullUrlLocation(e),saveAndLoadImage=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?saveAndLoadImage():this._loadImageFromDBAsync(i,t,saveAndLoadImage)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;let s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{logger_Logger.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};let a=s.objectStore("textures").get(e);a.onsuccess=e=>{r=e.target.result},a.onerror=()=>{logger_Logger.Error("Error loading texture "+e+" from DB."),t.src=e}}else logger_Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){let generateBlobUrl=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(Database._IsUASupportingBlobStorage){let r=new webRequest_WebRequest;r.open("GET",e),r.responseType="blob",r.addEventListener("load",()=>{if(200===r.status&&this._db){i=r.response;let s=this._db.transaction(["textures"],"readwrite");s.onabort=e=>{try{let t=e.target,i=t.error;i&&"QuotaExceededError"===i.name&&(this._hasReachedQuota=!0)}catch(e){}generateBlobUrl()},s.oncomplete=()=>{generateBlobUrl()};let a={textureUrl:e,data:i};try{let e=s.objectStore("textures").put(a);e.onsuccess=()=>{},e.onerror=()=>{generateBlobUrl()}}catch(i){25===i.code&&(Database._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{logger_Logger.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else logger_Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,()=>{this._saveVersionIntoDBAsync(e,t)})}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{let s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};let a=s.objectStore("versions").get(e);a.onsuccess=e=>{r=e.target.result},a.onerror=()=>{logger_Logger.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){logger_Logger.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else logger_Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{let i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};let r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{logger_Logger.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){logger_Logger.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){let a=Database._ReturnFullUrlLocation(e),saveAndLoadFile=()=>{this._saveFileAsync(a,t,i,s,r)};this._checkVersionFromDB(a,e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(a,t,i,s,r):this._loadFileAsync(a,t,saveAndLoadFile):r&&r()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let r,s;r=-1!==e.indexOf(".babylon")?"scenes":"textures";let a=this._db.transaction([r]);a.oncomplete=()=>{s?t(s.data):i()},a.onabort=()=>{i()};let n=a.objectStore(r).get(e);n.onsuccess=e=>{s=e.target.result},n.onerror=()=>{logger_Logger.Error("Error loading file "+e+" from DB."),i()}}else logger_Logger.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let a,n;a=-1!==e.indexOf(".babylon")?"scenes":"textures";let o=new webRequest_WebRequest;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(200===o.status||o.status<400&&Database._ValidateXHRData(o,r?6:1)){if(n=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){let i;let r=this._db.transaction([a],"readwrite");r.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(n)},r.oncomplete=()=>{t(n)},i="scenes"===a?{sceneUrl:e,data:n,version:this._manifestVersionFound}:{textureUrl:e,data:n};try{let e=r.objectStore(a).put(i);e.onsuccess=()=>{},e.onerror=()=>{logger_Logger.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(n)}}else t(n)}else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{logger_Logger.Error("error on XHR request."),s&&s()},!1),o.send()}else logger_Logger.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){let i=GetTGAHeader(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){let t=new Uint8Array(e.response,0,3);if(68===t[0]&&68===t[1]&&83===t[2])return!0}}catch(e){}return!1}};Database._IsUASupportingBlobStorage=!0,Database.IDBStorageEnabled=!1,Database._ParseURL=e=>{let t=document.createElement("a");t.href=e;let i=e.substring(0,e.lastIndexOf("#")),r=e.substring(i.lastIndexOf("/")+1,e.length),s=e.substring(0,e.indexOf(r,0));return s},Database._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?Database._ParseURL(window.location.href)+e:e;let UniformBufferEffectCommonAccessor=class UniformBufferEffectCommonAccessor{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}};let na=`#version 300 es -void main() {discard;} -`;ShaderStore.ShadersStore.gpuUpdateParticlesPixelShader=na;let nn=`#version 300 es -#define PI 3.14159 -uniform float currentCount;uniform float timeDelta;uniform float stopFactor; -#ifndef LOCAL -uniform mat4 emitterWM; -#endif -uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; -#ifndef COLORGRADIENTS -uniform vec4 color1;uniform vec4 color2; -#endif -uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; -#ifdef BOXEMITTER -uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; -#endif -#ifdef POINTEMITTER -uniform vec3 direction1;uniform vec3 direction2; -#endif -#ifdef HEMISPHERICEMITTER -uniform float radius;uniform float radiusRange;uniform float directionRandomizer; -#endif -#ifdef SPHEREEMITTER -uniform float radius;uniform float radiusRange; -#ifdef DIRECTEDSPHEREEMITTER -uniform vec3 direction1;uniform vec3 direction2; -#else -uniform float directionRandomizer; -#endif -#endif -#ifdef CYLINDEREMITTER -uniform float radius;uniform float height;uniform float radiusRange; -#ifdef DIRECTEDCYLINDEREMITTER -uniform vec3 direction1;uniform vec3 direction2; -#else -uniform float directionRandomizer; -#endif -#endif -#ifdef CONEEMITTER -uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; -#endif -in vec3 position; -#ifdef CUSTOMEMITTER -in vec3 initialPosition; -#endif -in float age;in float life;in vec4 seed;in vec3 size; -#ifndef COLORGRADIENTS -in vec4 color; -#endif -in vec3 direction; -#ifndef BILLBOARD -in vec3 initialDirection; -#endif -#ifdef ANGULARSPEEDGRADIENTS -in float angle; -#else -in vec2 angle; -#endif -#ifdef ANIMATESHEET -in float cellIndex; -#ifdef ANIMATESHEETRANDOMSTART -in float cellStartOffset; -#endif -#endif -#ifdef NOISE -in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; -#endif -out vec3 outPosition; -#ifdef CUSTOMEMITTER -out vec3 outInitialPosition; -#endif -out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; -#ifndef COLORGRADIENTS -out vec4 outColor; -#endif -out vec3 outDirection; -#ifndef BILLBOARD -out vec3 outInitialDirection; -#endif -#ifdef ANGULARSPEEDGRADIENTS -out float outAngle; -#else -out vec2 outAngle; -#endif -#ifdef ANIMATESHEET -out float outCellIndex; -#ifdef ANIMATESHEETRANDOMSTART -out float outCellStartOffset; -#endif -#endif -#ifdef NOISE -out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; -#endif -#ifdef SIZEGRADIENTS -uniform sampler2D sizeGradientSampler; -#endif -#ifdef ANGULARSPEEDGRADIENTS -uniform sampler2D angularSpeedGradientSampler; -#endif -#ifdef VELOCITYGRADIENTS -uniform sampler2D velocityGradientSampler; -#endif -#ifdef LIMITVELOCITYGRADIENTS -uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; -#endif -#ifdef DRAGGRADIENTS -uniform sampler2D dragGradientSampler; -#endif -#ifdef NOISE -uniform vec3 noiseStrength;uniform sampler2D noiseSampler; -#endif -#ifdef ANIMATESHEET -uniform vec4 cellInfos; -#endif -vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} -vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} -void main() {float newAge=age+timeDelta; -if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; -#ifdef SIZEGRADIENTS -outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; -#else -outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; -#endif -outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; -#ifndef COLORGRADIENTS -outColor=color1+(color2-color1)*randoms.b; -#endif -#ifndef ANGULARSPEEDGRADIENTS -outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; -#else -outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; -#endif -#ifdef POINTEMITTER -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; -#elif defined(BOXEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; -#elif defined(HEMISPHERICEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; -#elif defined(SPHEREEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); -#ifdef DIRECTEDSPHEREEMITTER -newDirection=normalize(direction1+(direction2-direction1)*randoms3); -#else -newDirection=normalize(newPosition+directionRandomizer*randoms3); -#endif -#elif defined(CYLINDEREMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); -#ifdef DIRECTEDCYLINDEREMITTER -newDirection=direction1+(direction2-direction1)*randoms3; -#else -angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); -#endif -#elif defined(CONEEMITTER) -vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; -#ifdef CONEEMITTERSPAWNPOINT -float h=0.0001; -#else -float h=randoms2.y*height.y;h=1.-h*h; -#endif -float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); -if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } -#elif defined(CUSTOMEMITTER) -newPosition=initialPosition;outInitialPosition=initialPosition; -#else -newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); -#endif -float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; -#ifdef LOCAL -outPosition=newPosition; -#else -outPosition=(emitterWM*vec4(newPosition,1.)).xyz; -#endif -#ifdef CUSTOMEMITTER -outDirection=direction; -#ifndef BILLBOARD -outInitialDirection=direction; -#endif -#else -#ifdef LOCAL -vec3 initial=newDirection; -#else -vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; -#endif -outDirection=initial*power; -#ifndef BILLBOARD -outInitialDirection=initial; -#endif -#endif -#ifdef ANIMATESHEET -outCellIndex=cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -outCellStartOffset=randoms.a*outLife; -#endif -#endif -#ifdef NOISE -outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; -#endif -} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; -#ifdef VELOCITYGRADIENTS -directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; -#endif -#ifdef DRAGGRADIENTS -directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; -#endif -#if defined(CUSTOMEMITTER) -outPosition=position+(direction-position)*ageGradient; -outInitialPosition=initialPosition; -#else -outPosition=position+direction*directionScale; -#endif -outLife=life;outSeed=seed; -#ifndef COLORGRADIENTS -outColor=color; -#endif -#ifdef SIZEGRADIENTS -outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; -#else -outSize=size; -#endif -#ifndef BILLBOARD -outInitialDirection=initialDirection; -#endif -#ifdef CUSTOMEMITTER -outDirection=direction; -#else -vec3 updatedDirection=direction+gravity*timeDelta; -#ifdef LIMITVELOCITYGRADIENTS -float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} -#endif -outDirection=updatedDirection; -#ifdef NOISE -float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; -#endif -#endif -#ifdef ANGULARSPEEDGRADIENTS -float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; -#else -outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); -#endif -#ifdef ANIMATESHEET -float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; -#else -float cellStartOffset=0.; -#endif -float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} -else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} -outCellIndex=float(int(cellInfos.x+ratio*dist)); -#endif -}}`;ShaderStore.ShadersStore.gpuUpdateParticlesVertexShader=nn;let WebGL2ParticleSystem=class WebGL2ParticleSystem{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateEffect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof CustomParticleEmitter&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new effect_Effect("gpuUpdateParticles",this._updateEffectOptions,this._engine),new UniformBufferEffectCommonAccessor(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){let e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);let r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e, -age : f32, -size : vec3, -life : f32, -seed : vec4, -direction : vec3, -dummy0: f32, -#ifdef CUSTOMEMITTER -initialPosition : vec3, -dummy1: f32, -#endif -#ifndef COLORGRADIENTS -color : vec4, -#endif -#ifndef BILLBOARD -initialDirection : vec3, -dummy2: f32, -#endif -#ifdef NOISE -noiseCoordinates1 : vec3, -dummy3: f32, -noiseCoordinates2 : vec3, -dummy4: f32, -#endif -#ifdef ANGULARSPEEDGRADIENTS -angle : f32, -#else -angle : vec2, -#endif -#ifdef ANIMATESHEET -cellIndex : f32, -#ifdef ANIMATESHEETRANDOMSTART -cellStartOffset : f32, -#endif -#endif -};struct Particles {particles : array,};struct SimParams {currentCount : f32, -timeDelta : f32, -stopFactor : f32, -randomTextureSize: i32, -lifeTime : vec2, -emitPower : vec2, -#ifndef COLORGRADIENTS -color1 : vec4, -color2 : vec4, -#endif -sizeRange : vec2, -scaleRange : vec4, -angleRange : vec4, -gravity : vec3, -#ifdef LIMITVELOCITYGRADIENTS -limitVelocityDamping : f32, -#endif -#ifdef ANIMATESHEET -cellInfos : vec4, -#endif -#ifdef NOISE -noiseStrength : vec3, -#endif -#ifndef LOCAL -emitterWM : mat4x4, -#endif -#ifdef BOXEMITTER -direction1 : vec3, -direction2 : vec3, -minEmitBox : vec3, -maxEmitBox : vec3, -#endif -#ifdef CONEEMITTER -radius : vec2, -coneAngle : f32, -height : vec2, -directionRandomizer : f32, -#endif -#ifdef CYLINDEREMITTER -radius : f32, -height : f32, -radiusRange : f32, -#ifdef DIRECTEDCYLINDEREMITTER -direction1 : vec3, -direction2 : vec3, -#else -directionRandomizer : f32, -#endif -#endif -#ifdef HEMISPHERICEMITTER -radius : f32, -radiusRange : f32, -directionRandomizer : f32, -#endif -#ifdef POINTEMITTER -direction1 : vec3, -direction2 : vec3, -#endif -#ifdef SPHEREEMITTER -radius : f32, -radiusRange : f32, -#ifdef DIRECTEDSPHEREEMITTER -direction1 : vec3, -direction2 : vec3, -#else -directionRandomizer : f32, -#endif -#endif -};@binding(0) @group(0) var params : SimParams;@binding(1) @group(0) var particlesIn : Particles;@binding(2) @group(0) var particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d;@binding(4) @group(0) var randomTexture2 : texture_2d; -#ifdef SIZEGRADIENTS -@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d; -#endif -#ifdef ANGULARSPEEDGRADIENTS -@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d; -#endif -#ifdef VELOCITYGRADIENTS -@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d; -#endif -#ifdef LIMITVELOCITYGRADIENTS -@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d; -#endif -#ifdef DRAGGRADIENTS -@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d; -#endif -#ifdef NOISE -@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d; -#endif -fn getRandomVec3(offset : f32,vertexID : f32)->vec3 {return textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} -fn getRandomVec4(offset : f32,vertexID : f32)->vec4 {return textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} -@compute @workgroup_size(64) -fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} -let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4=particlesIn.particles[index].seed;let direction : vec3=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3;var newDirection : vec3;let randoms : vec4=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; -#ifdef SIZEGRADIENTS -sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r; -#else -sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; -#endif -particlesOut.particles[index].size=vec3( -sizex, -params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, -params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); -#ifndef COLORGRADIENTS -particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; -#endif -#ifndef ANGULARSPEEDGRADIENTS -particlesOut.particles[index].angle=vec2( -params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, -params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); -#else -particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; -#endif -#if defined(POINTEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=vec3(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#elif defined(BOXEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#elif defined(HEMISPHERICEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); -#elif defined(SPHEREEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ); -#ifdef DIRECTEDSPHEREEMITTER -newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); -#else -newDirection=normalize(newPosition+params.directionRandomizer*randoms3); -#endif -#elif defined(CYLINDEREMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); -#ifdef DIRECTEDCYLINDEREMITTER -newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#else -angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); -#endif -#elif defined(CONEEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; -#ifdef CONEEMITTERSPAWNPOINT -let h : f32=0.0001; -#else -var h : f32=randoms2.y*params.height.y;h=1.-h*h; -#endif -var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3(randX,randY,randZ); -if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } -#elif defined(CUSTOMEMITTER) -newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; -#else -newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5)); -#endif -let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; -#ifdef LOCAL -particlesOut.particles[index].position=newPosition; -#else -particlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz; -#endif -#ifdef CUSTOMEMITTER -particlesOut.particles[index].direction=direction; -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=direction; -#endif -#else -#ifdef LOCAL -let initial : vec3=newDirection; -#else -let initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz; -#endif -particlesOut.particles[index].direction=initial*power; -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=initial; -#endif -#endif -#ifdef ANIMATESHEET -particlesOut.particles[index].cellIndex=params.cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -particlesOut.particles[index].cellStartOffset=randoms.a*outLife; -#endif -#endif -#ifdef NOISE -particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; -#endif -} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; -#ifdef VELOCITYGRADIENTS -directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r; -#endif -#ifdef DRAGGRADIENTS -directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r); -#endif -let position : vec3=particlesIn.particles[index].position; -#if defined(CUSTOMEMITTER) -particlesOut.particles[index].position=position+(direction-position)*ageGradient; -particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; -#else -particlesOut.particles[index].position=position+direction*directionScale; -#endif -particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; -#ifndef COLORGRADIENTS -particlesOut.particles[index].color=particlesIn.particles[index].color; -#endif -#ifdef SIZEGRADIENTS -particlesOut.particles[index].size=vec3( -textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r, -particlesIn.particles[index].size.yz); -#else -particlesOut.particles[index].size=particlesIn.particles[index].size; -#endif -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; -#endif -#ifdef CUSTOMEMITTER -particlesOut.particles[index].direction=direction; -#else -var updatedDirection : vec3=direction+params.gravity*timeDelta; -#ifdef LIMITVELOCITYGRADIENTS -let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} -#endif -particlesOut.particles[index].direction=updatedDirection; -#ifdef NOISE -let noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; -#endif -#endif -#ifdef ANGULARSPEEDGRADIENTS -let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; -#else -let angle : vec2=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y); -#endif -#ifdef ANIMATESHEET -var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; -#else -let cellStartOffset : f32=0.; -#endif -var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} -else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} -particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); -#endif -}} -`;ShaderStore.ShadersStoreWGSL.gpuUpdateParticlesComputeShader=no;let ComputeShaderParticleSystem=class ComputeShaderParticleSystem{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){var t;let i={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new ComputeShader("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new UniformBuffer(this._engine),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new UniformBufferEffectCommonAccessor(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){let t=new StorageBuffer(this._engine,4*e.length,11);return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let e=0;ee){i(t[0],t[0],1);return}for(let r=0;r=s.gradient&&e<=a.gradient){let t=(e-s.gradient)/(a.gradient-s.gradient);i(s,a,t);return}}let r=t.length-1;i(t[r],t[r],1)}};let Particle=class Particle{constructor(e){if(this.particleSystem=e,this.position=math_vector_Vector3.Zero(),this.direction=math_vector_Vector3.Zero(),this.color=new math_color_Color4(0,0,0,0),this.colorStep=new math_color_Color4(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new math_vector_Vector2(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new math_color_Color4(0,0,0,0),this._currentColor2=new math_color_Color4(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=Particle._Count++,!this.particleSystem.isAnimationSheetEnabled)return;this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e,t=this.age,i=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===i?(i=1,t=this._randomCellOffset):t+=this._randomCellOffset);let r=this._initialEndSpriteCellID-this._initialStartSpriteCellID;e=this._initialSpriteCellLoop?math_scalar_Scalar.Clamp(t*i%this.lifeTime/this.lifeTime):math_scalar_Scalar.Clamp(t*i/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+e*r|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){let t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){let e=math_vector_TmpVectors.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else{let t=e.particleSystem.emitter;t.copyFrom(this.position)}this.direction.scaleToRef(e.inheritedVelocityAmount/2,math_vector_TmpVectors.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(math_vector_TmpVectors.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=Particle._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new math_vector_Vector4(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}};Particle._Count=0,function(e){e[e.ATTACHED=0]="ATTACHED",e[e.END=1]="END"}(tq||(tq={}));let SubEmitter=class SubEmitter{constructor(e){if(this.particleSystem=e,this.type=tq.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){let t=h["BABYLON.AbstractMesh"];e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(e){if(e instanceof math_vector_Vector3)e=e.clone();else if(-1!==e.getClassName().indexOf("Mesh")){let t=h["BABYLON.Mesh"];(e=new t("",e.getScene())).isVisible=!1}}else e=new math_vector_Vector3;let t=new SubEmitter(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){let t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw _WarnImport("ParseParticle")}static Parse(e,t,i){let r=e.particleSystem,s=new SubEmitter(SubEmitter._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}};let nl=`#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; -#include -#include -#include -#include -#include -#ifdef RAMPGRADIENT -varying vec4 remapRanges;uniform sampler2D rampSampler; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; -#ifdef RAMPGRADIENT -float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); -#endif -#ifdef BLENDMULTIPLYMODE -float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); -#endif -#include -#ifdef IMAGEPROCESSINGPOSTPROCESS -baseColor.rgb=toLinearSpace(baseColor.rgb); -#else -#ifdef IMAGEPROCESSING -baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); -#endif -#endif -gl_FragColor=baseColor; -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.particlesPixelShader=nl;let nh=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; -#ifdef ANIMATESHEET -attribute float cellIndex; -#endif -#ifndef BILLBOARD -attribute vec3 direction; -#endif -#ifdef BILLBOARDSTRETCHED -attribute vec3 direction; -#endif -#ifdef RAMPGRADIENT -attribute vec4 remapData; -#endif -attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; -#ifdef ANIMATESHEET -uniform vec3 particlesInfos; -#endif -varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; -#ifdef RAMPGRADIENT -varying vec4 remapRanges; -#endif -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include -#include -#ifdef BILLBOARD -uniform vec3 eyePosition; -#endif -vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} -#ifdef BILLBOARDSTRETCHED -vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); -#ifdef BILLBOARDSTRETCHED_LOCAL -vec3 row1=direction; -#else -vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); -#endif -mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; -#ifdef BILLBOARD -vec3 rotatedCorner; -#ifdef BILLBOARDY -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; -#elif defined(BILLBOARDSTRETCHED) -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; -#else -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; -#endif -#ifdef RAMPGRADIENT -remapRanges=remapData; -#endif -gl_Position=projection*vec4(viewPos,1.0); -#else -vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); -#endif -vColor=color; -#ifdef ANIMATESHEET -float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; -#else -vUV=offset; -#endif -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=vec4(vPositionW,1.0); -#endif -#include -#include -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.particlesVertexShader=nh;let particleSystem_ParticleSystem=class particleSystem_ParticleSystem extends BaseParticleSystem{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new drawWrapper_DrawWrapper(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new observable_Observable),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,a=.01){super(e),this._emitterInverseWorldMatrix=math_vector_Matrix.Identity(),this._inheritedVelocityOffset=new math_vector_Vector3,this.onDisposeObservable=new observable_Observable,this.onStoppedObservable=new observable_Observable,this._particles=[],this._stockParticles=[],this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new math_color_Color4(0,0,0,0),this._colorDiff=new math_color_Color4(0,0,0,0),this._scaledDirection=math_vector_Vector3.Zero(),this._scaledGravity=math_vector_Vector3.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=e=>{let t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;if(0!==this._stockParticles.length?(e=this._stockParticles.pop())._reset():e=new Particle(this),this._subEmitters&&this._subEmitters.length>0){let t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(t=>{if(t.type===tq.ATTACHED){let i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;let t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(t=>{if(t.type===tq.END){let i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})},this._capacity=t,this._epsilon=a,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=math_vector_Matrix.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||engineStore_EngineStore.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new drawWrapper_DrawWrapper(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new BoxParticleEmitter;let n=null;this.updateFunction=e=>{var t;let i=null;this.noiseTexture&&(i=this.noiseTexture.getSize(),null===(t=this.noiseTexture.getContent())||void 0===t||t.then(e=>{n=e}));let r=e===this._particles;for(let t=0;ts.lifeTime){let e=s.age-o,t=s.lifeTime-o;a=t*a/e,s.age=s.lifeTime}let l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?GradientHelper.GetCurrentGradient(l,this._colorGradients,(e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),math_color_Color4.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)}):(s.colorStep.scaleToRef(a,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._angularSpeedGradients,(e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=math_scalar_Scalar.Lerp(s._currentAngularSpeed1,s._currentAngularSpeed2,i)}),s.angle+=s.angularSpeed*a;let h=a;if(this._velocityGradients&&this._velocityGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._velocityGradients,(e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=math_scalar_Scalar.Lerp(s._currentVelocity1,s._currentVelocity2,i)}),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._limitVelocityGradients,(e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);let r=math_scalar_Scalar.Lerp(s._currentLimitVelocity1,s._currentLimitVelocity2,i),a=s.direction.length();a>r&&s.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._dragGradients,(e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);let r=math_scalar_Scalar.Lerp(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)}),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),math_vector_Vector3.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),n&&i&&s._randomNoiseCoordinates1){let e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,i.width,i.height,n),t=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,i.width,i.height,n),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,i.width,i.height,n),o=math_vector_TmpVectors.Vector3[0],l=math_vector_TmpVectors.Vector3[1];o.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),o.scaleToRef(a,l),s.direction.addInPlace(l)}if(this.gravity.scaleToRef(a,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._sizeGradients,(e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=math_scalar_Scalar.Lerp(s._currentSize1,s._currentSize2,i)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._colorRemapGradients,(e,t,i)=>{let r=math_scalar_Scalar.Lerp(e.factor1,t.factor1,i),a=math_scalar_Scalar.Lerp(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=a-r}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._alphaRemapGradients,(e,t,i)=>{let r=math_scalar_Scalar.Lerp(e.factor1,t.factor1,i),a=math_scalar_Scalar.Lerp(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=a-r})),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime){this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach(e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),s._attachedSubEmitters=null),this.recycleParticle(s),r&&t--;continue}}}}_addFactorGradient(e,t,i,r){let s=new FactorGradient(t,i,r);e.push(s),e.sort((e,t)=>e.gradientt.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(let r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;let e=new Uint8Array(4*this._rawTextureWidth),t=TmpColors.Color3[0];for(let i=0;i{math_color_Color3.LerpToRef(r.color,s.color,a,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255})}this._rampGradientsTexture=rawTexture_RawTexture.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);let i=new Color3Gradient(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);let r=new ColorGradient(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((e,t)=>e.gradientt.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(let i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(let e of this._drawWrappers)if(e)for(let t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5;let a=e*i%i|0,n=t*r%r|0;return s[(a+n*i)*4]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){let e;this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);let t=this._engine,i=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*i),this._vertexBuffer=new Buffer(t,this._vertexData,!0,i);let r=0,s=this._vertexBuffer.createVertexBuffer(buffer_VertexBuffer.PositionKind,r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[buffer_VertexBuffer.PositionKind]=s,r+=3;let a=this._vertexBuffer.createVertexBuffer(buffer_VertexBuffer.ColorKind,r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[buffer_VertexBuffer.ColorKind]=a,r+=4;let n=this._vertexBuffer.createVertexBuffer("angle",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=n,r+=1;let o=this._vertexBuffer.createVertexBuffer("size",r,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,r+=2,this._isAnimationSheetEnabled){let e=this._vertexBuffer.createVertexBuffer("cellIndex",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,r+=1}if(!this._isBillboardBased||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL){let e=this._vertexBuffer.createVertexBuffer("direction",r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,r+=3}if(this._useRampGradients){let e=this._vertexBuffer.createVertexBuffer("remapData",r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,r+=4}if(this._useInstancing){let i=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Buffer(t,i,!1,2),e=this._spriteBuffer.createVertexBuffer("offset",0,2)}else e=this._vertexBuffer.createVertexBuffer("offset",r,2,this._vertexBufferSize,this._useInstancing),r+=2;this._vertexBuffers.offset=e,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}let e=[],t=[],i=0;for(let r=0;r{e instanceof particleSystem_ParticleSystem?this._subEmitters.push([new SubEmitter(e)]):e instanceof SubEmitter?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[]),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);let e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){!this._stopped&&(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL)&&(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(math_vector_Vector3.TransformNormalToRef(e,this._emitterWorldMatrix,math_vector_TmpVectors.Vector3[0]),e=math_vector_TmpVectors.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(math_vector_Vector3.TransformNormalToRef(e,this._emitterWorldMatrix,math_vector_TmpVectors.Vector3[0]),e=math_vector_TmpVectors.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;let e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){let t;if(this._alive=this._particles.length>0,this.emitter.position){let e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{let e=this.emitter;this._emitterWorldMatrix=math_vector_Matrix.Translation(e.x,e.y,e.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){let e=math_scalar_Scalar.Clamp(this._actualFrame/this.targetStopDuration);GradientHelper.GetCurrentGradient(e,this._lifeTimeGradients,(i,r)=>{let s=i.getFactor(),a=r.getFactor(),n=(e-i.gradient)/(r.gradient-i.gradient);t.lifeTime=math_scalar_Scalar.Lerp(s,a,n)})}else t.lifeTime=math_scalar_Scalar.RandomRange(this.minLifeTime,this.maxLifeTime);let e=math_scalar_Scalar.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),math_vector_Vector3.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=math_scalar_Scalar.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(math_scalar_Scalar.RandomRange(this.minScaleX,this.maxScaleX),math_scalar_Scalar.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){let e=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(e,this._startSizeGradients,(e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);let s=math_scalar_Scalar.Lerp(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)})}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=math_scalar_Scalar.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=math_scalar_Scalar.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{let e=math_scalar_Scalar.RandomRange(0,1);math_color_Color4.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new math_vector_Vector4(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new math_vector_Vector3(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new math_vector_Vector3(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){let r=[buffer_VertexBuffer.PositionKind,buffer_VertexBuffer.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1){let i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return addClipPlaneUniforms(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&prepareStringDefinesForClipPlanes(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===particleSystem_ParticleSystem.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case particleSystem_ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED:case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case particleSystem_ParticleSystem.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...particleSystem_ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...particleSystem_ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ImageProcessingConfiguration.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0,s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let a=s[e];a||((a=new drawWrapper_DrawWrapper(this._engine)).drawContext&&(a.drawContext.useInstancing=this._useInstancing),s[e]=a);let n=i.join("\n");if(a.defines!==n){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),a.setEffect(this._engine.createEffect("particles",e,t,i,n),n)}return a}animate(e=!1){var t;let i;if(this._started){if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){let t=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(t,this._emitRateGradients,(t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=math_scalar_Scalar.Lerp(this._currentEmitRate1,this._currentEmitRate2,r)})}i=e*this._scaledUpdateSpeed>>0,this._newPartsExcess+=e*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&!this._alive&&(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this)),!e){let e=0;for(let t=0;t=0&&(d.invertToRef(math_vector_TmpVectors.Matrix[0]),c.setMatrix("invView",math_vector_TmpVectors.Matrix[0])),void 0!==this._vertexArrayObject?(null===(r=this._scene)||void 0===r?void 0:r.forceWireframe)?u.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,c):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,c)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?u.bindBuffers(this._vertexBuffers,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBuffer:this._indexBuffer,c):u.bindBuffers(this._vertexBuffers,(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._linesIndexBufferUseInstancing:null,c),this.useLogarithmicDepth&&this._scene&&MaterialHelper.BindLogDepth(_,c,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(c),e){case particleSystem_ParticleSystem.BLENDMODE_ADD:u.setAlphaMode(1);break;case particleSystem_ParticleSystem.BLENDMODE_ONEONE:u.setAlphaMode(6);break;case particleSystem_ParticleSystem.BLENDMODE_STANDARD:u.setAlphaMode(2);break;case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY:u.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(c),this._useInstancing?(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?u.drawElementsType(6,0,10,this._particles.length):u.drawArraysType(7,0,4,this._particles.length):(null===(l=this._scene)||void 0===l?void 0:l.forceWireframe)?u.drawElementsType(1,0,10*this._particles.length):u.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;let e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD?this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY)+this._render(particleSystem_ParticleSystem.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,a=this._engine;if(a.createEffectForParticles&&null!=this.customShader){s=this.customShader;let e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=a.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}let n=this.serialize(i),o=particleSystem_ParticleSystem.Parse(n,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,this.preventAutoStart||o.start(),o}serialize(e=!1){let t={};if(particleSystem_ParticleSystem._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters)for(let i of(t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray(),this._subEmitters)){let r=[];for(let t of i)r.push(t.serialize(e));t.subEmitters.push(r)}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){let i=t.emitter;e.emitterId=i.id}else{let i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,decorators_SerializationHelper.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;let r=t.getColorGradients();if(r)for(let t of(e.colorGradients=[],r)){let i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}let s=t.getRampGradients();if(s){for(let t of(e.rampGradients=[],s)){let i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}let a=t.getColorRemapGradients();if(a)for(let t of(e.colorRemapGradients=[],a)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}let n=t.getAlphaRemapGradients();if(n)for(let t of(e.alphaRemapGradients=[],n)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}let o=t.getSizeGradients();if(o)for(let t of(e.sizeGradients=[],o)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}let l=t.getAngularSpeedGradients();if(l)for(let t of(e.angularSpeedGradients=[],l)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}let h=t.getVelocityGradients();if(h)for(let t of(e.velocityGradients=[],h)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}let c=t.getDragGradients();if(c)for(let t of(e.dragGradients=[],c)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}let u=t.getEmitRateGradients();if(u)for(let t of(e.emitRateGradients=[],u)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}let d=t.getStartSizeGradients();if(d)for(let t of(e.startSizeGradients=[],d)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}let _=t.getLifeTimeGradients();if(_)for(let t of(e.lifeTimeGradients=[],_)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}let p=t.getLimitVelocityGradients();if(p){for(let t of(e.limitVelocityGradients=[],p)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,r){var s,a,n;let o,l;o=i instanceof ThinEngine?null:i;let c=h["BABYLON.Texture"];if(c&&o&&(e.texture?t.particleTexture=c.Parse(e.texture,o,r):e.textureName&&(t.particleTexture=new c(r+e.textureName,o,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&o?t.emitter=o.getLastMeshById(e.emitterId):t.emitter=math_vector_Vector3.FromArray(e.emitter):t.emitter=math_vector_Vector3.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let i=0;i0?l.shaderOptions.defines.join("\n"):"";o=a.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,t)}let h=new particleSystem_ParticleSystem(n,s||e.capacity,t,o,e.isAnimationSheetEnabled);if(h.customShader=l,h._rootUrl=i,e.id&&(h.id=e.id),e.subEmitters)for(let r of(h.subEmitters=[],e.subEmitters)){let e=[];for(let s of r)e.push(SubEmitter.Parse(s,t,i));h.subEmitters.push(e)}return particleSystem_ParticleSystem._Parse(e,h,t,i),e.textureMask&&(h.textureMask=math_color_Color4.FromArray(e.textureMask)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),r||h.preventAutoStart||h.start(),h}};particleSystem_ParticleSystem.BILLBOARDMODE_Y=2,particleSystem_ParticleSystem.BILLBOARDMODE_ALL=7,particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED=8,particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL=9,SubEmitter._ParseParticleSystem=particleSystem_ParticleSystem.Parse;let nc=`#ifdef CLIPPLANE -in float fClipDistance; -#endif -#ifdef CLIPPLANE2 -in float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -in float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -in float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -in float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -in float fClipDistance6; -#endif -`;ShaderStore.IncludesShadersStore.clipPlaneFragmentDeclaration2=nc;let nu=`precision highp float; -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; -#include -#include -#include -#include -#include -void main() { -#include -vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; -#ifdef BLENDMULTIPLYMODE -float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); -#endif -#include -#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); -#else -#ifdef IMAGEPROCESSING -gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); -#endif -#endif -} -`;ShaderStore.ShadersStore.gpuRenderParticlesPixelShader=nu;let nd=`#ifdef CLIPPLANE -uniform vec4 vClipPlane;out float fClipDistance; -#endif -#ifdef CLIPPLANE2 -uniform vec4 vClipPlane2;out float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -uniform vec4 vClipPlane3;out float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -uniform vec4 vClipPlane4;out float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -uniform vec4 vClipPlane5;out float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -uniform vec4 vClipPlane6;out float fClipDistance6; -#endif -`;ShaderStore.IncludesShadersStore.clipPlaneVertexDeclaration2=nd;let n_=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; -#ifdef LOCAL -uniform mat4 emitterWM; -#endif -attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; -#ifndef BILLBOARD -attribute vec3 initialDirection; -#endif -#ifdef BILLBOARDSTRETCHED -attribute vec3 direction; -#endif -attribute float angle; -#ifdef ANIMATESHEET -attribute float cellIndex; -#endif -attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include -#include -#ifdef COLORGRADIENTS -uniform sampler2D colorGradientSampler; -#else -uniform vec4 colorDead;attribute vec4 color; -#endif -#ifdef ANIMATESHEET -uniform vec3 sheetInfos; -#endif -#ifdef BILLBOARD -uniform vec3 eyePosition; -#endif -vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; -#ifdef LOCAL -return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; -#else -return (position+worldOffset)+alignedCorner; -#endif -} -#ifdef BILLBOARDSTRETCHED -vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; -#ifdef LOCAL -return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; -#else -return (position+worldOffset)+alignedCorner; -#endif -} -#endif -void main() { -#ifdef ANIMATESHEET -float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; -#else -vUV=uv; -#endif -float ratio=age/life; -#ifdef COLORGRADIENTS -vColor=texture2D(colorGradientSampler,vec2(ratio,0)); -#else -vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); -#endif -vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; -#ifdef BILLBOARD -vec4 rotatedCorner;rotatedCorner.w=0.; -#ifdef BILLBOARDY -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); -#elif defined(BILLBOARDSTRETCHED) -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); -#else -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; -#ifdef LOCAL -vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; -#else -vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; -#endif -vPositionW=(invView*viewPosition).xyz; -#endif -#else -vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); -#endif -gl_Position=projection*viewPosition; -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=vec4(vPositionW,1.0); -#endif -#include -#include -}`;ShaderStore.ShadersStore.gpuRenderParticlesVertexShader=n_;let GPUParticleSystem=class GPUParticleSystem extends BaseParticleSystem{static get IsSupported(){if(!engineStore_EngineStore.LastCreatedEngine)return!1;let e=engineStore_EngineStore.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]))}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new drawWrapper_DrawWrapper(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new observable_Observable),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);let i=new ColorGradient(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(let t in this._drawWrappers){let i=this._drawWrappers[t];null===(e=i.drawContext)||void 0===e||e.reset()}}_addFactorGradient(e,t,i){let r=new FactorGradient(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){e&&(i&&e.sort((e,t)=>e.gradientt.gradient?1:0),this[t]&&(this[t].dispose(),this[t]=null))}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new observable_Observable,this.onStoppedObservable=new observable_Observable,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=math_vector_Matrix.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||engineStore_EngineStore.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!h["BABYLON.ComputeShaderParticleSystem"])throw Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new h["BABYLON.ComputeShaderParticleSystem"](this,this._engine)}else{if(!h["BABYLON.WebGL2ParticleSystem"])throw Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new h["BABYLON.WebGL2ParticleSystem"](this,this._engine)}this._customWrappers={0:new drawWrapper_DrawWrapper(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new drawWrapper_DrawWrapper(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;let a=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),n=t;isFinite(n)&&(a.capacity=n),this._capacity=a.capacity,this._maxActiveParticleCount=a.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new BoxParticleEmitter;let o=Math.min(this._engine.getCaps().maxTextureSize,a.randomTextureSize),l=[];for(let e=0;e0;)i.push(0)}let n=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),o=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new Buffer(t,o,!1,this._attributesStrideSize),this._buffer1=new Buffer(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new Buffer(t,n,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),!!this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||((r=new drawWrapper_DrawWrapper(this._engine)).drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);let s=i.join("\n");if(r.defines!==s){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){let s=[buffer_VertexBuffer.PositionKind,"age","life","size","angle"];return e||s.push(buffer_VertexBuffer.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",buffer_VertexBuffer.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){let i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return addClipPlaneUniforms(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&prepareStringDefinesForClipPlanes(this,this._scene,e),t===particleSystem_ParticleSystem.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case particleSystem_ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case particleSystem_ParticleSystem.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED)),e.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareUniforms(e,this._imageProcessingConfigurationDefines),ImageProcessingConfiguration.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,!this._stopped&&this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){let i=this[t];if(!e||!e.length||i)return;let r=new Float32Array(this._rawTextureWidth);for(let t=0;t{r[t]=math_scalar_Scalar.Lerp(e.factor1,i.factor1,s)})}this[t]=rawTexture_RawTexture.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;let e=new Uint8Array(4*this._rawTextureWidth),t=TmpColors.Color4[0];for(let i=0;i{math_color_Color4.LerpToRef(r.color1,s.color1,a,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a})}this._colorGradientsTexture=rawTexture_RawTexture.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,r,s,a,n;let o=this._getWrapper(e),l=o.effect;this._engine.enableEffect(o);let h=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||math_vector_Matrix.IdentityReadOnly;if(l.setMatrix("view",h),l.setMatrix("projection",null!==(r=this.defaultProjectionMatrix)&&void 0!==r?r:this._scene.getProjectionMatrix()),l.setTexture("diffuseSampler",this.particleTexture),l.setVector2("translationPivot",this.translationPivot),l.setVector3("worldOffset",this.worldOffset),this.isLocal&&l.setMatrix("emitterWM",t),this._colorGradientsTexture?l.setTexture("colorGradientSampler",this._colorGradientsTexture):l.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();l.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;l.setVector3("eyePosition",e.globalPosition)}let c=l.defines;if(this._scene&&bindClipPlane(l,this,this._scene),c.indexOf("#define BILLBOARDMODE_ALL")>=0){let e=h.clone();e.invert(),l.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&MaterialHelper.BindLogDepth(c,l,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(l),e){case particleSystem_ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case particleSystem_ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case particleSystem_ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,l,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(l),(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e){if(this.emitter.position){let t=this.emitter;e=t.getWorldMatrix()}else{let t=this.emitter;e=math_vector_TmpVectors.Matrix[0],math_vector_Matrix.TranslationToRef(t.x,t.y,t.z,e)}}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);let t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){let i;if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){let e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;if(this.emitter.position){let e=this.emitter;i=e.getWorldMatrix()}else{let e=this.emitter;i=math_vector_TmpVectors.Matrix[0],math_vector_Matrix.TranslationToRef(e.x,e.y,e.z,i)}let r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD?this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY,i)+this._render(particleSystem_ParticleSystem.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){let checkUpdateEffect=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?this._initialize(!0):setTimeout(checkUpdateEffect,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),checkUpdateEffect()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(let e in this._drawWrappers){let t=this._drawWrappers[e];t.dispose()}if(this._drawWrappers={},this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?s.shaderOptions.defines.join("\n"):"";r[0]=a.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}let n=this.serialize(i),o=GPUParticleSystem.Parse(n,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,o}serialize(e=!1){let t={};return particleSystem_ParticleSystem._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){let a;let n=e.name;a=t instanceof ThinEngine?t:t.getEngine();let o=new GPUParticleSystem(n,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(o._rootUrl=i,e.customShader&&a.createEffectForParticles){let t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=a.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,o);o.setCustomEffect(r,0),o.customShader=t}return e.id&&(o.id=e.id),e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),particleSystem_ParticleSystem._Parse(e,o,t,i),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o}};let ParticleSystemSet=class ParticleSystemSet{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){for(let t of(this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1),this.systems))t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};let r=sphereBuilder_CreateSphere("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;let s=new standardMaterial_StandardMaterial("emitterSphereMaterial",i);for(let t of(s.emissiveColor=e.color,r.material=s,this.systems))t.emitter=r;this._emitterNode=r}start(e){for(let t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(let e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){let t={};for(let i of(t.systems=[],this.systems))t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){let s=new ParticleSystemSet,a=this.BaseAssetsUrl+"/textures/";for(let n of(t=t||engineStore_EngineStore.LastCreatedScene,e.systems))s.systems.push(i?GPUParticleSystem.Parse(n,t,a,!0,r):particleSystem_ParticleSystem.Parse(n,t,a,!0,r));if(e.emitter){let i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:math_color_Color3.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}};ParticleSystemSet.BaseAssetsUrl="https://assets.babylonjs.com/particles";let ParticleHelper=class ParticleHelper{static CreateDefault(e,t=500,i,r=!1){let s;return(s=r?new GPUParticleSystem("default system",{capacity:t},i):new particleSystem_ParticleSystem("default system",t,i)).emitter=e,s.particleTexture=new texture_Texture("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new math_color_Color4(1,1,1,1),s.color2=new math_color_Color4(1,1,1,1),s.colorDead=new math_color_Color4(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,r){t||(t=engineStore_EngineStore.LastCreatedScene);let s={};return t.addPendingData(s),new Promise((a,n)=>{if(i&&!GPUParticleSystem.IsSupported)return t.removePendingData(s),n("Particle system with GPU is not supported.");tools_Tools.LoadFile(`${ParticleHelper.BaseAssetsUrl}/systems/${e}.json`,e=>{t.removePendingData(s);let n=JSON.parse(e.toString());return a(ParticleSystemSet.Parse(n,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(s),n(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){let t=new ParticleSystemSet;for(let i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",a){return new Promise((n,o)=>{let l=new webRequest_WebRequest;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let t;let o=JSON.parse(l.responseText);t=r?GPUParticleSystem.Parse(o,i,s,!1,a):particleSystem_ParticleSystem.Parse(o,i,s,!1,a),e&&(t.name=e),n(t)}else o("Unable to load the particle system")}}),l.open("GET",t),l.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){let e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise((a,n)=>{let o=new webRequest_WebRequest;o.addEventListener("readystatechange",()=>{if(4==o.readyState){if(200==o.status){let n;let l=JSON.parse(JSON.parse(o.responseText).jsonPayload),h=JSON.parse(l.particleSystem);(n=i?GPUParticleSystem.Parse(h,t,r,!1,s):particleSystem_ParticleSystem.Parse(h,t,r,!1,s)).snippetId=e,a(n)}else n("Unable to load the snippet "+e)}}),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()})}};ParticleHelper.BaseAssetsUrl=ParticleSystemSet.BaseAssetsUrl,ParticleHelper.SnippetUrl="https://snippet.babylonjs.com",ParticleHelper.CreateFromSnippetAsync=ParticleHelper.ParseFromSnippetAsync,AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM,(e,t,i,r)=>{let s=AbstractScene.GetIndividualParser(sceneComponent_SceneComponentConstants.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let a=0,n=e.particleSystems.length;a{if(e.activeParticleCount){let r=GPUParticleSystem.Parse(e,t,i);return r}{let r=particleSystem_ParticleSystem.Parse(e,t,i);return r}}),engine_Engine.prototype.createEffectForParticles=function(e,t=[],i=[],r="",s,a,n,o){var l;let h=[],c=[],u=[];return o?o.fillUniformsAttributesAndSamplerNames(c,h,u):(h=particleSystem_ParticleSystem._GetAttributeNamesOrOptions(),c=particleSystem_ParticleSystem._GetEffectCreationOptions()),-1===r.indexOf(" BILLBOARD")&&(r+="\n#define BILLBOARD\n"),(null==o?void 0:o.isAnimationSheetEnabled)&&-1===r.indexOf(" ANIMATESHEET")&&(r+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==o?void 0:o.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,c.concat(t),u.concat(i),r,s,a,n)},mesh_Mesh.prototype.getEmittedParticleSystems=function(){let e=[];for(let t=0;t{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),abstractMesh_AbstractMesh.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},abstractMesh_AbstractMesh.prototype.applyImpulse=function(e,t){return this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t),this},abstractMesh_AbstractMesh.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor&&this.physicsImpostor.createJoint(e.physicsImpostor,PhysicsJoint.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this};let physicsEngine_PhysicsEngine=class physicsEngine_PhysicsEngine{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw _WarnImport("")}constructor(e,t=physicsEngine_PhysicsEngine.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new math_vector_Vector3(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){let t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){let r=new PhysicsRaycastResult;return this._physicsPlugin.raycast(e,t,r,i),r}};(function(e){e[e.FREE=0]="FREE",e[e.LIMITED=1]="LIMITED",e[e.LOCKED=2]="LOCKED"})(tQ||(tQ={})),function(e){e[e.LINEAR_X=0]="LINEAR_X",e[e.LINEAR_Y=1]="LINEAR_Y",e[e.LINEAR_Z=2]="LINEAR_Z",e[e.ANGULAR_X=3]="ANGULAR_X",e[e.ANGULAR_Y=4]="ANGULAR_Y",e[e.ANGULAR_Z=5]="ANGULAR_Z",e[e.LINEAR_DISTANCE=6]="LINEAR_DISTANCE"}(tZ||(tZ={})),function(e){e[e.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e[e.DISTANCE=2]="DISTANCE",e[e.HINGE=3]="HINGE",e[e.SLIDER=4]="SLIDER",e[e.LOCK=5]="LOCK",e[e.PRISMATIC=6]="PRISMATIC",e[e.SIX_DOF=7]="SIX_DOF"}(tJ||(tJ={})),function(e){e[e.SPHERE=0]="SPHERE",e[e.CAPSULE=1]="CAPSULE",e[e.CYLINDER=2]="CYLINDER",e[e.BOX=3]="BOX",e[e.CONVEX_HULL=4]="CONVEX_HULL",e[e.CONTAINER=5]="CONTAINER",e[e.MESH=6]="MESH",e[e.HEIGHTFIELD=7]="HEIGHTFIELD"}(t0||(t0={})),function(e){e[e.NONE=0]="NONE",e[e.VELOCITY=1]="VELOCITY",e[e.POSITION=2]="POSITION"}(t1||(t1={})),function(e){e.COLLISION_STARTED="COLLISION_STARTED",e.COLLISION_CONTINUED="COLLISION_CONTINUED",e.COLLISION_FINISHED="COLLISION_FINISHED",e.TRIGGER_ENTERED="TRIGGER_ENTERED",e.TRIGGER_EXITED="TRIGGER_EXITED"}(t2||(t2={})),function(e){e[e.STATIC=0]="STATIC",e[e.ANIMATED=1]="ANIMATED",e[e.DYNAMIC=2]="DYNAMIC"}(t3||(t3={})),function(e){e[e.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",e[e.MINIMUM=1]="MINIMUM",e[e.MAXIMUM=2]="MAXIMUM",e[e.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",e[e.MULTIPLY=4]="MULTIPLY"}(t4||(t4={})),scene_Scene.prototype.getPhysicsEngine=function(){return this._physicsEngine},scene_Scene.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE);i||(i=new PhysicsEngineSceneComponent(this),this._addComponent(i));try{if(t&&(null==t?void 0:t.getPluginVersion())!==1){if((null==t?void 0:t.getPluginVersion())===2)this._physicsEngine=new physicsEngine_PhysicsEngine(e,t);else throw Error("Unsupported Physics plugin version.")}else this._physicsEngine=new PhysicsEngine(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return logger_Logger.Error(e.message),!1}},scene_Scene.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},scene_Scene.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},scene_Scene.prototype.deleteCompoundImpostor=function(e){let t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},scene_Scene.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){let t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};let PhysicsEngineSceneComponent=class PhysicsEngineSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new observable_Observable,this.scene.onAfterPhysicsObservable=new observable_Observable,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}};Object.defineProperty(transformNode_TransformNode.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0}),transformNode_TransformNode.prototype.getPhysicsBody=function(){return this.physicsBody},transformNode_TransformNode.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};let HelperTools=class HelperTools{static GetContactPointToRef(e,t,i,r,s){let a=e.getScene().getPhysicsEngine(),n=null==a?void 0:a.getPluginVersion();if(1===n){let s=new ray_Ray(t,i),a=s.intersectsMesh(e);if(a.hit&&a.pickedPoint)return r.copyFrom(a.pickedPoint),!0}else if(2===n)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){var i,r,s;return e.getMotionType(t)===t3.STATIC||(null!==(r=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==r?r:0)===0||(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){let s=math_vector_TmpVectors.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}};let PhysicsUpdraftEvent=class PhysicsUpdraftEvent{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=math_vector_Vector3.Zero(),this._originDirection=math_vector_Vector3.Zero(),this._cylinderPosition=math_vector_Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new PhysicsUpdraftEventOptions),this._options),this._origin.addToRef(new math_vector_Vector3(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new math_vector_Vector3(0,this._options.height,0),this._originTop),this._options.updraftMode===t6.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout(()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)},0))}_getHitData(e,t){let i;i=this._options.updraftMode===t6.Perpendicular?this._originDirection:e.subtract(this._originTop);let r=math_vector_Vector3.Distance(this._origin,e),s=-1*this._options.strength,a=i.multiplyByFloats(s,s,s);t.force.copyFrom(a),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(HelperTools.HasAppliedForces(e))return!1;let r=e.getObjectCenterWorld(i);return!!HelperTools.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){let e=PhysicsUpdraftEvent._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=cylinderBuilder_CreateCylinder("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}};PhysicsUpdraftEvent._HitData={force:new math_vector_Vector3,contactPoint:new math_vector_Vector3,distanceFromOrigin:0};let PhysicsVortexEvent=class PhysicsVortexEvent{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=math_vector_Vector3.Zero(),this._cylinderPosition=math_vector_Vector3.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new PhysicsVortexEventOptions),this._options),this._origin.addToRef(new math_vector_Vector3(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new math_vector_Vector3(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout(()=>{this._dataFetched||this._cylinder.dispose()},0))}_getHitData(e,t,i){let r,s,a;let n=PhysicsVortexEvent.originOnPlane;n.set(this._origin.x,t.y,this._origin.z);let o=math_vector_TmpVectors.Vector3[0];t.subtractToRef(n,o);let l=math_vector_TmpVectors.Vector3[1],h=HelperTools.GetContactPointToRef(e,n,o,l,i.instanceIndex);if(!h)return!1;let c=math_vector_Vector3.Distance(l,n),u=c/this._options.radius,d=math_vector_TmpVectors.Vector3[2];if(l.normalizeToRef(d),u>this._options.centripetalForceThreshold&&d.negateInPlace(),u>this._options.centripetalForceThreshold)r=d.x*this._options.centripetalForceMultiplier,s=d.y*this._options.updraftForceMultiplier,a=d.z*this._options.centripetalForceMultiplier;else{let e=math_vector_Vector3.Cross(n,t).normalize();r=(e.x+d.x)*this._options.centrifugalForceMultiplier,s=this._originTop.y*this._options.updraftForceMultiplier,a=(e.z+d.z)*this._options.centrifugalForceMultiplier}let _=math_vector_TmpVectors.Vector3[3];return _.set(r,s,a),_.scaleInPlace(this._options.strength),i.force.copyFrom(_),i.contactPoint.copyFrom(t),i.distanceFromOrigin=u,!0}_getBodyHitData(e,t,i){if(HelperTools.HasAppliedForces(e,i))return!1;let r=e.transformNode,s=e.getObjectCenterWorld(i);return!!HelperTools.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass||"Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){let e=PhysicsVortexEvent.hitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=cylinderBuilder_CreateCylinder("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}};PhysicsVortexEvent.originOnPlane=math_vector_Vector3.Zero(),PhysicsVortexEvent.hitData={force:new math_vector_Vector3,contactPoint:new math_vector_Vector3,distanceFromOrigin:0};let PhysicsUpdraftEventOptions=class PhysicsUpdraftEventOptions{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=t6.Center}};let PhysicsVortexEventOptions=class PhysicsVortexEventOptions{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}};(function(e){e[e.Constant=0]="Constant",e[e.Linear=1]="Linear"})(t5||(t5={})),function(e){e[e.Center=0]="Center",e[e.Perpendicular=1]="Perpendicular"}(t6||(t6={}));let np=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); -vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;ShaderStore.ShadersStore.blackAndWhitePixelShader=np;let BlackAndWhitePostProcess=class BlackAndWhitePostProcess extends postProcess_PostProcess{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,s,a){super(e,"blackAndWhite",["degree"],null,t,i,r,s,a),this.degree=1,this.onApplyObservable.add(e=>{e.setFloat("degree",this.degree)})}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new BlackAndWhitePostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([serialize()],BlackAndWhitePostProcess.prototype,"degree",void 0),h["BABYLON.BlackAndWhitePostProcess"]=BlackAndWhitePostProcess;let postProcessRenderEffect_PostProcessRenderEffect=class postProcessRenderEffect_PostProcessRenderEffect{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(let e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){let t=this._postProcesses[e];for(let e=0;e{let t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)}),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){let t=tools_Tools.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){let t=tools_Tools.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}};let nf=`#include -varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;ShaderStore.ShadersStore.extractHighlightsPixelShader=nf;let ExtractHighlightsPostProcess=class ExtractHighlightsPostProcess extends postProcess_PostProcess{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,s,a,o=0,l=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,s,a,null,o,void 0,null,l),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,n)),e.setFloat("exposure",this._exposure)})}};__decorate([serialize()],ExtractHighlightsPostProcess.prototype,"threshold",void 0),h["BABYLON.ExtractHighlightsPostProcess"]=ExtractHighlightsPostProcess;let nm=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } -`;ShaderStore.ShadersStore.bloomMergePixelShader=nm;let BloomMergePostProcess=class BloomMergePostProcess extends postProcess_PostProcess{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,a,n,o,l,h=0,c=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,a,n,o,l,null,h,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)}),c||this.updateEffect()}};__decorate([serialize()],BloomMergePostProcess.prototype,"weight",void 0),h["BABYLON.BloomMergePostProcess"]=BloomMergePostProcess;let BloomEffect=class BloomEffect extends postProcessRenderEffect_PostProcessRenderEffect{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,r,s=0,a=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new ExtractHighlightsPostProcess("highlights",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,a),this._blurX=new BlurPostProcess("horizontal blur",new math_vector_Vector2(1,0),10,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,a),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new BlurPostProcess("vertical blur",new math_vector_Vector2(0,1),10,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,a),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new BloomMergePostProcess("bloomMerge",this._downscale,this._blurY,i,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,a),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)})}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new ChromaticAberrationPostProcess(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}};__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"aberrationAmount",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"radialIntensity",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"direction",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"centerPosition",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"screenWidth",void 0),__decorate([serialize()],ChromaticAberrationPostProcess.prototype,"screenHeight",void 0),h["BABYLON.ChromaticAberrationPostProcess"]=ChromaticAberrationPostProcess;let nv=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float depth=texture2D(depthSampler,vUV).r; -#define CUSTOM_COC_DEPTH -float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; -#define CUSTOM_COC_PIXELDISTANCE -float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} -`;ShaderStore.ShadersStore.circleOfConfusionPixelShader=nv;let CircleOfConfusionPostProcess=class CircleOfConfusionPostProcess extends postProcess_PostProcess{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,a,n,o=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,s,a,n,null,o,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(e=>{if(!this._depthTexture){logger_Logger.Warn("No depth texture set on CircleOfConfusionPostProcess");return}e.setTexture("depthSampler",this._depthTexture);let t=this.lensSize/this.fStop,i=t*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",i);let r=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",r.minZ,r.maxZ-r.minZ)})}set depthTexture(e){this._depthTexture=e}};__decorate([serialize()],CircleOfConfusionPostProcess.prototype,"lensSize",void 0),__decorate([serialize()],CircleOfConfusionPostProcess.prototype,"fStop",void 0),__decorate([serialize()],CircleOfConfusionPostProcess.prototype,"focusDistance",void 0),__decorate([serialize()],CircleOfConfusionPostProcess.prototype,"focalLength",void 0),h["BABYLON.CircleOfConfusionPostProcess"]=CircleOfConfusionPostProcess;let nx=`uniform sampler2D textureSampler; -uniform sampler2D colorTable; -varying vec2 vUV;const float SLICE_COUNT=16.0; -vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; -float slicePixelSize=sliceSize/width; -float sliceInnerSize=slicePixelSize*(width-1.0); -float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;ShaderStore.ShadersStore.colorCorrectionPixelShader=nx;let ColorCorrectionPostProcess=class ColorCorrectionPostProcess extends postProcess_PostProcess{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,a,n){super(e,"colorCorrection",null,["colorTable"],i,r,s,a,n);let o=(null==r?void 0:r.getScene())||null;this._colorTableTexture=new texture_Texture(t,o,!0,!1,texture_Texture.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new ColorCorrectionPostProcess(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([serialize()],ColorCorrectionPostProcess.prototype,"colorTableUrl",void 0),h["BABYLON.ColorCorrectionPostProcess"]=ColorCorrectionPostProcess;let nb=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = -texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + -texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + -texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + -texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + -texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + -texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + -texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + -texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + -texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = -kernel[0] + -kernel[1] + -kernel[2] + -kernel[3] + -kernel[4] + -kernel[5] + -kernel[6] + -kernel[7] + -kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} -gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;ShaderStore.ShadersStore.convolutionPixelShader=nb;let ConvolutionPostProcess=class ConvolutionPostProcess extends postProcess_PostProcess{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,a,n,o=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,a,n,null,o),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new ConvolutionPostProcess(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}};ConvolutionPostProcess.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],ConvolutionPostProcess.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],ConvolutionPostProcess.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],ConvolutionPostProcess.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],ConvolutionPostProcess.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],ConvolutionPostProcess.GaussianKernel=[0,1,0,1,1,1,0,1,0],__decorate([serialize()],ConvolutionPostProcess.prototype,"kernel",void 0),h["BABYLON.ConvolutionPostProcess"]=ConvolutionPostProcess;let DepthOfFieldBlurPostProcess=class DepthOfFieldBlurPostProcess extends BlurPostProcess{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,a,n,o=null,l=texture_Texture.BILINEAR_SAMPLINGMODE,h,c,u=0,d=!1,_=5){super(e,i,r,s,a,2,h,c,u,`#define DOF 1 -`,d,_),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add(e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",n)})}};__decorate([serialize()],DepthOfFieldBlurPostProcess.prototype,"direction",void 0),h["BABYLON.DepthOfFieldBlurPostProcess"]=DepthOfFieldBlurPostProcess;let nT=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; -#if BLUR_LEVEL>0 -uniform sampler2D blurStep1; -#endif -#if BLUR_LEVEL>1 -uniform sampler2D blurStep2; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; -#if BLUR_LEVEL==0 -vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); -#endif -#if BLUR_LEVEL==1 -if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} -#endif -#if BLUR_LEVEL==2 -if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} -#endif -} -`;ShaderStore.ShadersStore.depthOfFieldMergePixelShader=nT;let DepthOfFieldMergePostProcess=class DepthOfFieldMergePostProcess extends postProcess_PostProcess{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,a,n,o,l,h=0,c=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,a,n,o,l,null,h,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)})}),c||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,a){e||(e="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,a)}};!function(e){e[e.Low=0]="Low",e[e.Medium=1]="Medium",e[e.High=2]="High"}(t8||(t8={}));let DepthOfFieldEffect=class DepthOfFieldEffect extends postProcessRenderEffect_PostProcessRenderEffect{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=t8.Low,r=0,s=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];let a=e.getEngine(),n=a.isWebGPU||a.webGLVersion>1?6:5;this._circleOfConfusion=new CircleOfConfusionPostProcess("circleOfConfusion",t,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,r,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,l=15;switch(i){case t8.High:o=3,l=51;break;case t8.Medium:o=2,l=31;break;default:l=15,o=1}let h=l/Math.pow(2,o-1),c=1;for(let t=0;tnew DisplayPassPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};h["BABYLON.DisplayPassPostProcess"]=DisplayPassPostProcess;let nC=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;ShaderStore.ShadersStore.filterPixelShader=nC;let FilterPostProcess=class FilterPostProcess extends postProcess_PostProcess{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,a,n){super(e,"filter",["kernelMatrix"],null,i,r,s,a,n),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new FilterPostProcess(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([generateSerializableMember(12,void 0)],FilterPostProcess.prototype,"kernelMatrix",void 0),h["BABYLON.FilterPostProcess"]=FilterPostProcess;let nE=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); -#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) -void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); -#ifndef MALI -if(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) -{lumaN=lumaW;} -if (!horzSpan) -{lumaS=lumaE;} -if (horzSpan) -{lengthSign=texelSize.y;} -float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) -{lengthSign=-lengthSign;} -float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) -{posB.x+=lengthSign*0.5;} -if (horzSpan) -{posB.y+=lengthSign*0.5;} -vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) -{lumaNN=lumaSS;} -float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) -{posN.x-=offNP.x*3.0;} -if (!doneN) -{posN.y-=offNP.y*3.0;} -bool doneNP=(!doneN) || (!doneP);if (!doneP) -{posP.x+=offNP.x*3.0;} -if (!doneP) -{posP.y+=offNP.y*3.0;} -if (doneNP) -{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} -float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) -{dstN=posM.y-posN.y;} -if (!horzSpan) -{dstP=posP.y-posM.y;} -bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{let t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)})}_getDefines(){let e=this.getEngine();if(!e)return null;let t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new FxaaPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};h["BABYLON.FxaaPostProcess"]=FxaaPostProcess;let nR=`#include -uniform sampler2D textureSampler; -uniform float intensity;uniform float animatedSeed;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;ShaderStore.ShadersStore.grainPixelShader=nR;let GrainPostProcess=class GrainPostProcess extends postProcess_PostProcess{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,a,n=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,a,null,n,void 0,null,o),this.intensity=30,this.animated=!1,this.onApplyObservable.add(e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new GrainPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([serialize()],GrainPostProcess.prototype,"intensity",void 0),__decorate([serialize()],GrainPostProcess.prototype,"animated",void 0),h["BABYLON.GrainPostProcess"]=GrainPostProcess;let nP=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;ShaderStore.ShadersStore.highlightsPixelShader=nP;let nA=`varying vec2 vUV;uniform sampler2D textureSampler; -#include -#include -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 result=texture2D(textureSampler,vUV); -#ifdef IMAGEPROCESSING -#ifndef FROMLINEARSPACE -result.rgb=toLinearSpace(result.rgb); -#endif -result=applyImageProcessing(result); -#else -#ifdef FROMLINEARSPACE -result=applyImageProcessing(result); -#endif -#endif -gl_FragColor=result;}`;ShaderStore.ShadersStore.imageProcessingPixelShader=nA;let ImageProcessingPostProcess=class ImageProcessingPostProcess extends postProcess_PostProcess{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null,t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){let i=t.scenes;e=i[i.length-1]}else e=engineStore_EngineStore.LastCreatedScene;e?this._imageProcessingConfiguration=e.imageProcessingConfiguration:this._imageProcessingConfiguration=new ImageProcessingConfiguration}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){let e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,a,n=0,o){super(e,"imageProcessing",[],[],t,i,r,s,a,null,n,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(let t in this._defines)this._defines[t]&&(e+=`#define ${t}; -`);let t=["textureSampler"],i=["scale"];ImageProcessingConfiguration&&(ImageProcessingConfiguration.PrepareSamplers(t,this._defines),ImageProcessingConfiguration.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}};__decorate([serialize()],ImageProcessingPostProcess.prototype,"_fromLinearSpace",void 0);let nM=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -layout(location=0) out vec4 glFragData[{X}]; -#endif -`;ShaderStore.IncludesShadersStore.mrtFragmentDeclaration=nM;let nI=`#extension GL_EXT_draw_buffers : require -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -precision highp float; -#ifdef BUMP -varying mat4 vWorldView;varying vec3 vNormalW; -#else -varying vec3 vNormalV; -#endif -varying vec4 vViewPos; -#if defined(POSITION) || defined(BUMP) -varying vec3 vPositionW; -#endif -#ifdef VELOCITY -varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#ifdef NEED_UV -varying vec2 vUV; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#if defined(REFLECTIVITY) -#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) -uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; -#endif -#ifdef ALBEDOTEXTURE -varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; -#endif -#ifdef REFLECTIVITYCOLOR -uniform vec3 reflectivityColor; -#endif -#ifdef ALBEDOCOLOR -uniform vec3 albedoColor; -#endif -#ifdef METALLIC -uniform float metallic; -#endif -#if defined(ROUGHNESS) || defined(GLOSSINESS) -uniform float glossiness; -#endif -#endif -#if defined(ALPHATEST) && defined(NEED_UV) -uniform sampler2D diffuseSampler; -#endif -#include -#include[RENDER_TARGET_COUNT] -#include -#include -#include -void main() { -#include -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -vec3 normalOutput; -#ifdef BUMP -vec3 normalW=normalize(vNormalW); -#include -#ifdef NORMAL_WORLDSPACE -normalOutput=normalW; -#else -normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); -#endif -#else -normalOutput=normalize(vNormalV); -#endif -#ifdef PREPASS -#ifdef PREPASS_DEPTH -gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); -#endif -#ifdef PREPASS_NORMAL -gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); -#endif -#else -gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); -#endif -#ifdef POSITION -gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); -#endif -#ifdef VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); -#endif -#ifdef REFLECTIVITY -vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); -#ifdef METALLICWORKFLOW -float metal=1.0;float roughness=1.0; -#ifdef ORMTEXTURE -metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; -#endif -#ifdef METALLIC -metal*=metallic; -#endif -#ifdef ROUGHNESS -roughness*=(1.0-glossiness); -#endif -reflectivity.a-=roughness;vec3 color=vec3(1.0); -#ifdef ALBEDOTEXTURE -color=texture2D(albedoSampler,vAlbedoUV).rgb; -#ifdef GAMMAALBEDO -color=toLinearSpace(color); -#endif -#endif -#ifdef ALBEDOCOLOR -color*=albedoColor.xyz; -#endif -reflectivity.rgb=mix(vec3(0.04),color,metal); -#else -#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) -reflectivity=texture2D(reflectivitySampler,vReflectivityUV); -#ifdef GAMMAREFLECTIVITYTEXTURE -reflectivity.rgb=toLinearSpace(reflectivity.rgb); -#endif -#else -#ifdef REFLECTIVITYCOLOR -reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; -#endif -#endif -#ifdef GLOSSINESSS -reflectivity.a*=glossiness; -#endif -#endif -gl_FragData[REFLECTIVITY_INDEX]=reflectivity; -#endif -} -`;ShaderStore.ShadersStore.geometryPixelShader=nI,ShaderStore.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";let nD=`#include -`;ShaderStore.IncludesShadersStore.geometryUboDeclaration=nD;let nO=`precision highp float; -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include<__decl__geometryVertex> -#include -attribute vec3 position;attribute vec3 normal; -#ifdef NEED_UV -varying vec2 vUV; -#ifdef ALPHATEST -uniform mat4 diffuseMatrix; -#endif -#ifdef BUMP -uniform mat4 bumpMatrix;varying vec2 vBumpUV; -#endif -#ifdef REFLECTIVITY -uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#ifdef BUMP -varying mat4 vWorldView; -#endif -#ifdef BUMP -varying vec3 vNormalW; -#else -varying vec3 vNormalV; -#endif -varying vec4 vViewPos; -#if defined(POSITION) || defined(BUMP) -varying vec3 vPositionW; -#endif -#ifdef VELOCITY -uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position;vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include -#include -vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); -#ifdef BUMP -vWorldView=view*finalWorld;vNormalW=normalUpdated; -#else -#ifdef NORMAL_WORLDSPACE -vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); -#else -vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); -#endif -#endif -vViewPos=view*worldPos; -#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if NUM_BONE_INFLUENCERS>0 -mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#endif -#if defined(POSITION) || defined(BUMP) -vPositionW=worldPos.xyz/worldPos.w; -#endif -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#include -#ifdef NEED_UV -#ifdef UV1 -#if defined(ALPHATEST) && defined(ALPHATEST_UV1) -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#else -vUV=uv; -#endif -#ifdef BUMP_UV1 -vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef REFLECTIVITY_UV1 -vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef ALBEDO_UV1 -vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#endif -#ifdef UV2 -#if defined(ALPHATEST) && defined(ALPHATEST_UV2) -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#else -vUV=uv2; -#endif -#ifdef BUMP_UV2 -vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef REFLECTIVITY_UV2 -vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef ALBEDO_UV2 -vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#endif -#include -} -`;ShaderStore.ShadersStore.geometryVertexShader=nO;let nB=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];addClipPlaneUniforms(nB);let GeometryBufferRenderer=class GeometryBufferRenderer{_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===GeometryBufferRenderer.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===GeometryBufferRenderer.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===GeometryBufferRenderer.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case GeometryBufferRenderer.POSITION_TEXTURE_TYPE:return this._positionIndex;case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case GeometryBufferRenderer.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case GeometryBufferRenderer.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return -1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return this._ratio}constructor(e,t=1,i=15){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new math_color_Color4(0,0,0,0),this._clearDepthColor=new math_color_Color4(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratio=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,GeometryBufferRenderer._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[buffer_VertexBuffer.PositionKind,buffer_VertexBuffer.NormalKind],a=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&MaterialFlags.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&r.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(s.push(buffer_VertexBuffer.UVKind),r.push("#define UV1")),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(s.push(buffer_VertexBuffer.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),-1!==this._depthIndex&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(a)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),a.useBones&&a.computeBonesUsingShaders?(s.push(buffer_VertexBuffer.MatricesIndicesKind),s.push(buffer_VertexBuffer.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(buffer_VertexBuffer.MatricesIndicesExtraKind),s.push(buffer_VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");let n=a.morphTargetManager,o=0;n&&n.numInfluencers>0&&(o=n.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+o),n.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(s,a,o)),t&&(r.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),prepareStringDefinesForClipPlanes(i,this._scene,r);let l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),c=h.defines,u=r.join("\n");return c!==u&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:nB,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:u,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:o}},l),u),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){if(this._resizeObserver){let e=this._scene.getEngine();e.onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null}this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],t=2;return e.push("gBuffer_Depth","gBuffer_Normal"),this._enablePosition&&(this._positionIndex=t,t++,e.push("gBuffer_Position")),this._enableVelocity&&(this._velocityIndex=t,t++,e.push("gBuffer_Velocity")),this._enableReflectivity&&(this._reflectivityIndex=t,t++,e.push("gBuffer_Reflectivity")),[t,e]}_createRenderTargets(){let e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices(),r=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2),this._multiRenderTarget=new MultiRenderTarget("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:r,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let s=[!0],a=[!1],n=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?l:o),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(h),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(o)}),this._resizeObserver=e.onResizeObservable.add(()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})});let renderSubMesh=e=>{let t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),a=e.getMaterial();if(!a)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:math_vector_Matrix.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){let e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}let n=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(n.mustReturn)return;let o=s.getCaps().instancedArrays&&(null!==n.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,o)){let h;let c=e._getDrawWrapper();if(!c)return;let u=c.effect;s.enableEffect(c),o||t._bind(e,u,a.fillMode),this._useUbo?(MaterialHelper.BindSceneUniformBuffer(u,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(u.setMatrix("viewProjection",r.getTransformMatrix()),u.setMatrix("view",r.getViewMatrix()));let d=t._instanceDataStorage;if(!d.isFrozen&&(a.backFaceCulling||null!==t.overrideMaterialSideOrientation)){let e=i._getWorldMatrixDeterminant();null===(h=t.overrideMaterialSideOrientation)&&(h=a.sideOrientation),e<0&&(h=h===material_Material.ClockWiseSideOrientation?material_Material.CounterClockWiseSideOrientation:material_Material.ClockWiseSideOrientation)}else h=d.sideOrientation;if(a._preBind(c,h),a.needAlphaTesting()){let e=a.getAlphaTestTexture();e&&(u.setTexture("diffuseSampler",e),u.setMatrix("diffuseMatrix",e.getTextureMatrix()))}a.bumpTexture&&r.getEngine().getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&(u.setFloat3("vBumpInfos",a.bumpTexture.coordinatesIndex,1/a.bumpTexture.level,a.parallaxScaleBias),u.setMatrix("bumpMatrix",a.bumpTexture.getTextureMatrix()),u.setTexture("bumpSampler",a.bumpTexture),u.setFloat2("vTangentSpaceParams",a.invertNormalMapX?-1:1,a.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===a.getClassName()?(null!==a.metallicRoughnessTexture&&(u.setTexture("reflectivitySampler",a.metallicRoughnessTexture),u.setMatrix("reflectivityMatrix",a.metallicRoughnessTexture.getTextureMatrix())),null!==a.metallic&&u.setFloat("metallic",a.metallic),null!==a.roughness&&u.setFloat("glossiness",1-a.roughness),null!==a.baseTexture&&(u.setTexture("albedoSampler",a.baseTexture),u.setMatrix("albedoMatrix",a.baseTexture.getTextureMatrix())),null!==a.baseColor&&u.setColor3("albedoColor",a.baseColor)):"PBRSpecularGlossinessMaterial"===a.getClassName()?(null!==a.specularGlossinessTexture?(u.setTexture("reflectivitySampler",a.specularGlossinessTexture),u.setMatrix("reflectivityMatrix",a.specularGlossinessTexture.getTextureMatrix())):null!==a.specularColor&&u.setColor3("reflectivityColor",a.specularColor),null!==a.glossiness&&u.setFloat("glossiness",a.glossiness)):"PBRMaterial"===a.getClassName()?(null!==a.metallicTexture&&(u.setTexture("reflectivitySampler",a.metallicTexture),u.setMatrix("reflectivityMatrix",a.metallicTexture.getTextureMatrix())),null!==a.metallic&&u.setFloat("metallic",a.metallic),null!==a.roughness&&u.setFloat("glossiness",1-a.roughness),null!==a.roughness||null!==a.metallic||null!==a.metallicTexture?(null!==a.albedoTexture&&(u.setTexture("albedoSampler",a.albedoTexture),u.setMatrix("albedoMatrix",a.albedoTexture.getTextureMatrix())),null!==a.albedoColor&&u.setColor3("albedoColor",a.albedoColor)):(null!==a.reflectivityTexture?(u.setTexture("reflectivitySampler",a.reflectivityTexture),u.setMatrix("reflectivityMatrix",a.reflectivityTexture.getTextureMatrix())):null!==a.reflectivityColor&&u.setColor3("reflectivityColor",a.reflectivityColor),null!==a.microSurface&&u.setFloat("glossiness",a.microSurface))):"StandardMaterial"===a.getClassName()&&(null!==a.specularTexture&&(u.setTexture("reflectivitySampler",a.specularTexture),u.setMatrix("reflectivityMatrix",a.specularTexture.getTextureMatrix())),null!==a.specularColor&&u.setColor3("reflectivityColor",a.specularColor))),bindClipPlane(u,a,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&(u.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),this._enableVelocity&&u.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])),MaterialHelper.BindMorphTargetParameters(t,u),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(u),this._enableVelocity&&(u.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),u.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),o&&t.hasThinInstances&&u.setMatrix("world",l),t._processRendering(i,e,u,a.fillMode,n,o,(e,t)=>{e||u.setMatrix("world",t)})}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i{let a;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),a=0;a{throw _WarnImport("GeometryBufferRendererSceneComponent")};let MotionBlurConfiguration=class MotionBlurConfiguration{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}};Object.defineProperty(scene_Scene.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),scene_Scene.prototype.enableGeometryBufferRenderer=function(e=1,t=15){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new GeometryBufferRenderer(this,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},scene_Scene.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};let GeometryBufferRendererSceneComponent=class GeometryBufferRendererSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}};GeometryBufferRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);t||(t=new GeometryBufferRendererSceneComponent(e),e._addComponent(t))};let nN=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; -#ifdef OBJECT_BASED -uniform sampler2D velocitySampler; -#else -uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#ifdef GEOMETRY_SUPPORTED -#ifdef OBJECT_BASED -vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount) -break;vec2 offset=vUV+velocity*(hlim+float(i)); -#if defined(WEBGPU) -result+=texture2DLodEXT(textureSampler,offset,0.0); -#else -result+=texture2D(textureSampler,offset); -#endif -} -gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; -#else -vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; -vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples) -break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); -#if defined(WEBGPU) -result+=texture2DLodEXT(textureSampler,offset1,0.0); -#else -result+=texture2D(textureSampler,offset1); -#endif -} -gl_FragColor=result/float(nSamples); -#endif -#else -gl_FragColor=texture2D(textureSampler,vUV); -#endif -} -`;ShaderStore.ShadersStore.motionBlurPixelShader=nN;let MotionBlurPostProcess=class MotionBlurPostProcess extends postProcess_PostProcess{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,a,n,o=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,a,n,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",o,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new MotionBlurConfiguration)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}let i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return logger_Logger.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=math_vector_Matrix.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new math_vector_Vector2(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){let t=math_vector_TmpVectors.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new math_vector_Vector2(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){let e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new MotionBlurPostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}};__decorate([serialize()],MotionBlurPostProcess.prototype,"motionStrength",void 0),__decorate([serialize()],MotionBlurPostProcess.prototype,"motionBlurSamples",null),__decorate([serialize()],MotionBlurPostProcess.prototype,"isObjectBased",null),h["BABYLON.MotionBlurPostProcess"]=MotionBlurPostProcess,ShaderStore.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";let RefractionPostProcess=class RefractionPostProcess extends postProcess_PostProcess{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,a,n,o,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],a,n,o,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(e=>{this._refTexture=this._refTexture||new texture_Texture(t,e.getScene())}),this.onApplyObservable.add(e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new RefractionPostProcess(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};__decorate([serialize()],RefractionPostProcess.prototype,"color",void 0),__decorate([serialize()],RefractionPostProcess.prototype,"depth",void 0),__decorate([serialize()],RefractionPostProcess.prototype,"colorLevel",void 0),__decorate([serialize()],RefractionPostProcess.prototype,"refractionTextureUrl",void 0),h["BABYLON.RefractionPostProcess"]=RefractionPostProcess;let nF=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + -texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + -texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + -texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - -color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;ShaderStore.ShadersStore.sharpenPixelShader=nF;let SharpenPostProcess=class SharpenPostProcess extends postProcess_PostProcess{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,a,n=0,o=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,a,null,n,void 0,null,o),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new SharpenPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};__decorate([serialize()],SharpenPostProcess.prototype,"colorAmount",void 0),__decorate([serialize()],SharpenPostProcess.prototype,"edgeAmount",void 0),h["BABYLON.SharpenPostProcess"]=SharpenPostProcess;let postProcessRenderPipeline_PostProcessRenderPipeline=class postProcessRenderPipeline_PostProcessRenderPipeline{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=[],this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(let e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){let i=this._renderEffects[e];i&&i._enable(tools_Tools.MakeArray(t||this._cameras))}_disableEffect(e,t){let i=this._renderEffects[e];i&&i._disable(tools_Tools.MakeArray(t||this._cameras))}_attachCameras(e,t){let i;let r=tools_Tools.MakeArray(e||this._cameras);if(!r)return;let s=[];for(i=0;i0){let i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){let e=Object.keys(this._renderEffects);for(let t of e){let e=this._renderEffects[t].getPostProcesses();if(e)for(let t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}};__decorate([serialize()],postProcessRenderPipeline_PostProcessRenderPipeline.prototype,"_name",void 0);let PostProcessRenderPipelineManager=class PostProcessRenderPipelineManager{constructor(){this._renderPipelines={}}get supportedPipelines(){let e=[];for(let t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){let i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){let r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){let i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t._rebuild()}}dispose(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.dispose()}}};Object.defineProperty(scene_Scene.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(sceneComponent_SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new PostProcessRenderPipelineManagerSceneComponent(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new PostProcessRenderPipelineManager}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});let PostProcessRenderPipelineManagerSceneComponent=class PostProcessRenderPipelineManagerSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}};let DefaultRenderingPipeline=class DefaultRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){let e=this.bloom;this.bloom=new BloomEffect(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen,!0),this.depthOfField=new DepthOfFieldEffect(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=n.getHardwareScalingLevel(),this._resizeObserver=n.onResizeObservable.add(()=>{this._hardwareScaleLevel=n.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new BloomEffect(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new ChromaticAberrationPostProcess("ChromaticAberration",n.getRenderWidth(),n.getRenderHeight(),1,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new postProcessRenderEffect_PostProcessRenderEffect(n,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new GrainPostProcess("Grain",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new postProcessRenderEffect_PostProcessRenderEffect(n,this.GrainPostProcessId,()=>this.grain,!0);let o=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add(()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,o?tools_Tools.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),o=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){let e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;let e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(let e of this._cameras){let t=this._scene.enableDepthRenderer(e);t.useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);let e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new ImageProcessingPostProcess("imageProcessing",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e,this.ImageProcessingPostProcessId,()=>this.imageProcessing,!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new FxaaPostProcess("fxaa",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&logger_Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew DefaultRenderingPipeline(e._name,e._name._hdr,t),e,t,i)}};__decorate([serialize()],DefaultRenderingPipeline.prototype,"sharpenEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomKernel",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"_bloomWeight",void 0),__decorate([serialize()],DefaultRenderingPipeline.prototype,"_bloomThreshold",void 0),__decorate([serialize()],DefaultRenderingPipeline.prototype,"_hdr",void 0),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomWeight",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomThreshold",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomScale",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"bloomEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"depthOfFieldEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"depthOfFieldBlurLevel",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"fxaaEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"samples",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"imageProcessingEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"glowLayerEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"chromaticAberrationEnabled",null),__decorate([serialize()],DefaultRenderingPipeline.prototype,"grainEnabled",null),h["BABYLON.DefaultRenderingPipeline"]=DefaultRenderingPipeline;let nw=`uniform sampler2D textureSampler; -uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } -else { lum_threshold=0.5+0.44*threshold; } -luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} -float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); -#ifdef PENTAGON -blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); -#else -blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); -#endif -blurred/=39.0;gl_FragColor=blurred;}`;ShaderStore.ShadersStore.lensHighlightsPixelShader=nw;let nL=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; -uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; -#define PI 3.14159265 -#define TWOPI 6.28318530 -#define inverse_focal_length 0.1 -vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) -{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} -vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } -vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} -float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} -float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} -vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} -if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} -col/=total_weight; -if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} -return col;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); -vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); -float depth=texture2D(depthSampler,distorted_coords).r; -float distance=near+(far-near)*depth; -vec4 color=texture2D(textureSampler,vUV); -float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } -float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} -float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} -else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} -if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} -if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} -`;ShaderStore.ShadersStore.depthOfFieldPixelShader=nL;let SSAO2Configuration=class SSAO2Configuration{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}};let nV=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSAO -float scales[16]=float[16]( -0.1, -0.11406250000000001, -0.131640625, -0.15625, -0.187890625, -0.2265625, -0.272265625, -0.325, -0.384765625, -0.4515625, -0.525390625, -0.60625, -0.694140625, -0.7890625, -0.891015625, -1.0 -);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() -{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;} -float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} -occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} -#endif -#ifdef BLUR -uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; -#ifndef BLUR_BYPASS -uniform sampler2D depthSampler; -#ifdef BLUR_LEGACY -#define inline -float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} -#endif -#endif -void main() -{float result=0.0; -#ifdef BLUR_BYPASS -result=textureLod(textureSampler,vUV,0.0).r; -#else -#ifdef BLUR_H -vec2 step=vec2(1.0/outSize,0.0); -#else -vec2 step=vec2(0.0,1.0/outSize); -#endif -#ifdef BLUR_LEGACY -result=blur13Bilateral(textureSampler,vUV,step); -#else -float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;let t=a?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=a?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},n.samples=this.textureSamples,n}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,23283064365386963e-26*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){let i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new math_vector_Vector3(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){let e;let t=this.samples,i=[],r=0;for(;r{var t,i,r,s;if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===camera_Camera.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{let a=this._scene.getEngine().getRenderWidth()/2,n=this._scene.getEngine().getRenderHeight()/2,o=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-a,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:a,h=null!==(r=this._scene.activeCamera.orthoBottom)&&void 0!==r?r:-n,c=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:n;e.setMatrix3x3("depthProjection",SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",(l-o)*.5),e.setFloat("yViewport",(c-h)*.5)}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new SSAO2Configuration)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new postProcess_PostProcess("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{let t=this._scene.activeCamera.viewport;e.setVector4("viewport",math_vector_TmpVectors.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){let e=new Uint8Array(65536),t=math_vector_Vector2.Zero();for(let i=0;inew SSAO2RenderingPipeline(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}};SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],__decorate([serialize()],SSAO2RenderingPipeline.prototype,"totalStrength",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"maxZ",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"minZAspect",void 0),__decorate([serialize("epsilon")],SSAO2RenderingPipeline.prototype,"_epsilon",void 0),__decorate([serialize("samples")],SSAO2RenderingPipeline.prototype,"_samples",void 0),__decorate([serialize("textureSamples")],SSAO2RenderingPipeline.prototype,"_textureSamples",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"_forceGeometryBuffer",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"_ratio",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"_textureType",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"radius",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"base",void 0),__decorate([serialize("bypassBlur")],SSAO2RenderingPipeline.prototype,"_bypassBlur",void 0),__decorate([serialize("expensiveBlur")],SSAO2RenderingPipeline.prototype,"_expensiveBlur",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"bilateralSamples",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"bilateralSoften",void 0),__decorate([serialize()],SSAO2RenderingPipeline.prototype,"bilateralTolerance",void 0),h["BABYLON.SSAO2RenderingPipeline"]=SSAO2RenderingPipeline;let nk=`uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSAO -uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) -{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} -void main() -{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){for(let i of(super._attachCameras(e,t),this._cameras))this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{let e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e}),this._blurVPostProcess.onActivateObservable.add(()=>{let e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){let t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new postProcess_PostProcess("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new postProcess_PostProcess("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",math_vector_TmpVectors.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){let e=new Uint8Array(1048576);for(let t=0;t0.0) -hitCoord-=dir;else -hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} -projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} -/** -* Tests the given world position (hitCoord) according to the given reflection vector (dir) -* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). -*/ -ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) -{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){let t=i.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){let t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}let s=t.activeCamera;if(!s)return;let a=s.getViewMatrix(!0),n=s.getProjectionMatrix(!0);e.setMatrix("projection",n),e.setMatrix("view",a),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){let e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new ScreenSpaceReflectionPostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"threshold",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"strength",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"reflectionSpecularFalloffExponent",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"step",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"roughnessFactor",void 0),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"enableSmoothReflections",null),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"reflectionSamples",null),__decorate([serialize()],ScreenSpaceReflectionPostProcess.prototype,"smoothSteps",null),h["BABYLON.ScreenSpaceReflectionPostProcess"]=ScreenSpaceReflectionPostProcess;let nz=`uniform sampler2D textureSampler;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -#if defined(PASS_POST_PROCESS) -void main(void) -{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} -#endif -#if defined(DOWN_SAMPLE_X4) -uniform vec2 dsOffsets[16];void main(void) -{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} -#endif -#if defined(BRIGHT_PASS) -uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) -{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth) -accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} -accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} -#endif -#if defined(VLSMERGE) -uniform sampler2D originalSampler;void main(void) -{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} -#endif -#if defined(LUMINANCE) -uniform vec2 lumOffsets[4];void main() -{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) -{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); -#ifdef WEIGHTED_AVERAGE -float GreyValue=dot(color.rgb,weight); -#endif -#ifdef BRIGHTNESS -float GreyValue=max(color.r,max(color.g,color.b)); -#endif -#ifdef HSL_COMPONENT -float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); -#endif -#ifdef MAGNITUDE -float GreyValue=length(color.rgb); -#endif -maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} -average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} -#endif -#if defined(LUMINANCE_DOWN_SAMPLE) -uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; -#ifdef FINAL_DOWN_SAMPLER -#include -#endif -void main() -{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) -{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} -average/=9.0; -#ifdef FINAL_DOWN_SAMPLER -gl_FragColor=pack(average); -#else -gl_FragColor=vec4(average,average,0.0,1.0); -#endif -} -#endif -#if defined(HDR) -uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() -{vec4 color=texture2D(textureAdderSampler,vUV); -#ifndef AUTO_EXPOSURE -vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; -#endif -gl_FragColor=color;} -#endif -#if defined(LENS_FLARE) -#define GHOSTS 3 -uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) -{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} -float noise(in vec2 p) -{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), -hash(i+vec2(1.0,0.0)),u.x), -mix(hash(i+vec2(0.0,1.0)), -hash(i+vec2(1.0,1.0)),u.x),u.y);} -float fbm(vec2 p) -{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} -vec3 pattern(vec2 uv) -{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} -float luminance(vec3 color) -{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} -vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) -{return vec4( -texture2D(tex,texcoord+direction*distortion.r).r, -texture2D(tex,texcoord+direction*distortion.g).g, -texture2D(tex,texcoord+direction*distortion.b).b, -1.0 -);} -void main(void) -{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples) -break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} -gl_FragColor=result/float(nSamples);} -#endif -`;ShaderStore.ShadersStore.standardPixelShader=nz;let StandardRenderingPipeline=class StandardRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){let t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){let t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e){let e=this._scene.enableGeometryBufferRenderer();if(!e){logger_Logger.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){let e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new ScreenSpaceReflectionPostProcess("HDRPass",t,e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new postProcess_PostProcess("HDRPass","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.originalPostProcess}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRPassPostProcess",()=>this.originalPostProcess,!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new postProcess_PostProcess("HDRDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new postProcess_PostProcess("HDRVLSFinal","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new postProcess_PostProcess("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new postProcess_PostProcess("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRPostHDReDepthOfFieldSource",()=>this.hdrFinalPostProcess,!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new FxaaPostProcess("fxaa",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&logger_Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){let i=Array(32);this.downSampleX4PostProcess=new postProcess_PostProcess("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0,r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let a=-2;a<2;a++)i[t]=(e+.5)*(1/r),i[t+1]=(a+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){let i=Array(8);this.brightPassPostProcess=new postProcess_PostProcess("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{let t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){let s=e.getEngine(),a=new BlurPostProcess("HDRBlurH_"+i,new math_vector_Vector2(1,0),this[r],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),n=new BlurPostProcess("HDRBlurV_"+i,new math_vector_Vector2(0,1),this[r],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);a.onActivateObservable.add(()=>{let e=a.width/s.getRenderWidth();a.kernel=this[r]*e}),n.onActivateObservable.add(()=>{let e=n.height/s.getRenderHeight();n.kernel=this.horizontalBlur?64*e:this[r]*e}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBlurH"+i,()=>a,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBlurV"+i,()=>n,!0)),this.blurHPostProcesses.push(a),this.blurVPostProcesses.push(n)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new postProcess_PostProcess("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){let i=e.enableGeometryBufferRenderer();i.enablePosition=!0;let r=i.getGBuffer();this.volumetricLightPostProcess=new postProcess_PostProcess("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));let s=math_vector_Vector2.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){let t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new postProcess_PostProcess("HDRVLSMerge","standard",[],["originalSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,StandardRenderingPipeline.LuminanceSteps);this.luminancePostProcess=new postProcess_PostProcess("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);let r=[];this.luminancePostProcess.onApply=e=>{let t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let r=StandardRenderingPipeline.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");let a=new postProcess_PostProcess("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(a)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((t,i)=>{let r=Array(18);t.onApply=e=>{if(!s)return;let a=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[a]=e/s.width,r[a+1]=t/s.height,a+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{let t=e.getEngine().readPixels(0,0,1,1),i=new math_vector_Vector4(6030862941101084e-23,1/65025,1/255,1);t.then(e=>{let t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100})}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLuminanceDownSample"+i,()=>t,!0))})}_createHdrPostProcess(e,t){let i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new postProcess_PostProcess("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,a=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{let e=(a-s)/1e3;this._hdrCurrentLuminancer-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=math_scalar_Scalar.Clamp(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),a=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new postProcess_PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new postProcess_PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));let i=new math_vector_Vector2(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};let r=math_vector_Matrix.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=math_vector_Matrix.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);let t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2),a=math_vector_Vector3.Dot(t.toVector3(),new math_vector_Vector3(1,0,0))+math_vector_Vector3.Dot(i.toVector3(),new math_vector_Vector3(0,0,1));a*=4;let n=math_vector_Matrix.FromValues(.5*Math.cos(a),-Math.sin(a),0,0,Math.sin(a),.5*Math.cos(a),0,0,0,0,1,0,0,0,0,1),o=s.multiply(n).multiply(r);e.setMatrix("lensStarMatrix",o),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new postProcess_PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){let i=new MotionBlurPostProcess("HDRMotionBlur",e,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new postProcess_PostProcess("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=math_vector_Matrix.Identity(),s=math_vector_Matrix.Identity(),a=math_vector_Matrix.Identity(),n=math_vector_Vector2.Zero();this.motionBlurPostProcess.onApply=t=>{(a=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=a,n.x=this.motionBlurPostProcess.width,n.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",n),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){if(this._scene.getEngine().getCaps().drawBuffersExtension){let e=this._scene.enableGeometryBufferRenderer();return e.getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew StandardRenderingPipeline(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&decorators_SerializationHelper.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}};StandardRenderingPipeline.LuminanceSteps=6,__decorate([serialize()],StandardRenderingPipeline.prototype,"brightThreshold",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"blurWidth",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"horizontalBlur",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"exposure",null),__decorate([serializeAsTexture("lensTexture")],StandardRenderingPipeline.prototype,"lensTexture",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"volumetricLightCoefficient",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"volumetricLightPower",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"volumetricLightBlurScale",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"hdrMinimumLuminance",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"hdrDecreaseRate",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"hdrIncreaseRate",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"hdrAutoExposure",null),__decorate([serializeAsTexture("lensColorTexture")],StandardRenderingPipeline.prototype,"lensColorTexture",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareStrength",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareGhostDispersal",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareHaloWidth",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareDistortionStrength",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"lensFlareBlurWidth",void 0),__decorate([serializeAsTexture("lensStarTexture")],StandardRenderingPipeline.prototype,"lensStarTexture",void 0),__decorate([serializeAsTexture("lensFlareDirtTexture")],StandardRenderingPipeline.prototype,"lensFlareDirtTexture",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"depthOfFieldDistance",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"depthOfFieldBlurWidth",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"motionStrength",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"objectBasedMotionBlur",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"_ratio",void 0),__decorate([serialize()],StandardRenderingPipeline.prototype,"BloomEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"DepthOfFieldEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"LensFlareEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"HDREnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"VLSEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"MotionBlurEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"fxaaEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"screenSpaceReflectionsEnabled",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"volumetricLightStepsCount",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"motionBlurSamples",null),__decorate([serialize()],StandardRenderingPipeline.prototype,"samples",null),h["BABYLON.StandardRenderingPipeline"]=StandardRenderingPipeline;let ScreenSpaceReflections2Configuration=class ScreenSpaceReflections2Configuration{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}};let nW=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } -/** -param csOrigin Camera-space ray origin,which must be -within the view volume and must have z>0.01 and project within the valid screen rectangle -param csDirection Unit length camera-space ray direction -param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates -(**not** [-1,+1] normalized device coordinates). -param csZBuffer The camera-space Z buffer -param csZBufferSize Dimensions of csZBuffer -param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer -param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value -for clipping rays headed towards the camera -param stride Step in horizontal or vertical pixels between samples. This is a float -because integer math is slow on GPUs,but should be set to an integer>=1 -param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units -to conceal banding artifacts,plus the stride ray offset. -param maxSteps Maximum number of iterations. Higher gives better images but may be slow -param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss -param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. -1 is a reasonable value,depending on the scene you may need to set this value to 2 -param hitPixel Pixel coordinates of the first intersection with the scene -param numIterations number of iterations performed -param csHitPoint Camera space location of the ray hit -*/ -#define inline -bool traceScreenSpaceRay1( -vec3 csOrigin, -vec3 csDirection, -mat4 projectToPixelMatrix, -sampler2D csZBuffer, -vec2 csZBufferSize, -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -sampler2D csZBackBuffer, -float csZBackSizeFactor, -#endif -float csZThickness, -float nearPlaneZ, -float stride, -float jitterFraction, -float maxSteps, -float maxRayTraceDistance, -float selfCollisionNumSkip, -out vec2 startPixel, -out vec2 hitPixel, -out vec3 csHitPoint, -out float numIterations -#ifdef SSRAYTRACE_DEBUG -,out vec3 debugColor -#endif -) -{ -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; -#else -float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);} -if ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));} -P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); -#endif -P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { -float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} -sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); -#else -hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); -#endif -#else -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); -#else -hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); -#endif -#endif -} -pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} -#ifdef SSRAYTRACE_ENABLE_REFINEMENT -if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || -(refinementStepCount<=stride*1.4) && -(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} -#endif -return hit;} -/** -texCoord: in the [0,1] range -depth: depth in view space (range [znear,zfar]]) -*/ -vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -ndc.z=-projection[2].z-projection[3].z/depth; -#else -ndc.z=projection[2].z+projection[3].z/depth; -#endif -ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} -`;ShaderStore.IncludesShadersStore.screenSpaceRayTrace=nW;let nH=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSR_SUPPORTED -uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -uniform sampler2D backDepthSampler;uniform float backSizeFactor; -#endif -#ifdef SSR_USE_ENVIRONMENT_CUBE -uniform samplerCube envCubeSampler; -#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; -#include -#include -#include -vec3 hash(vec3 a) -{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} -float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; -#ifdef SSR_ATTENUATE_SCREEN_BORDERS -vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); -#endif -#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE -attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); -#endif -#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS -attenuation*=1.0-(numIterations/maxSteps); -#endif -#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION -vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; -#endif -return attenuation;} -#endif -void main() -{ -#ifdef SSR_SUPPORTED -vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); -#ifndef SSR_DISABLE_REFLECTIVITY_TEST -if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { -#ifdef SSR_USE_BLUR -gl_FragColor=vec4(0.); -#else -gl_FragColor=colorFull; -#endif -return;} -#endif -#ifdef SSR_INPUT_IS_GAMMA_SPACE -color=toLinearSpace(color); -#endif -vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; -float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); -#ifdef SSR_USE_ENVIRONMENT_CUBE -vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); -#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC -vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); -#endif -#ifdef SSR_INVERTCUBICMAP -wReflectedVector.y*=-1.0; -#endif -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -wReflectedVector.z*=-1.0; -#endif -vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; -#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE -envColor=toLinearSpace(envColor); -#endif -#else -vec3 envColor=color; -#endif -float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; -#ifdef SSRAYTRACE_DEBUG -vec3 debugColor; -#endif -#ifdef SSR_ATTENUATE_FACING_CAMERA -reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); -#endif -if (reflectionAttenuation>0.0) { -#ifdef SSR_USE_BLUR -vec3 jitt=vec3(0.); -#else -float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; -#endif -vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); -rayHasHit=traceScreenSpaceRay1( -csPosition, -normalize(csReflectedVector+jitt), -projectionPixel, -depthSampler, -texSize, -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -backDepthSampler, -backSizeFactor, -#endif -thickness, -nearPlaneZ, -stepSize, -jitter, -maxSteps, -maxDistance, -selfCollisionNumSkip, -startPixel, -hitPixel, -hitPoint, -numIterations -#ifdef SSRAYTRACE_DEBUG -,debugColor -#endif -);} -#ifdef SSRAYTRACE_DEBUG -gl_FragColor=vec4(debugColor,1.);return; -#endif -vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; -#ifdef SSR_INPUT_IS_GAMMA_SPACE -reflectedColor=toLinearSpace(reflectedColor); -#endif -reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} -#ifndef SSR_BLEND_WITH_FRESNEL -SSR*=fresnel; -#endif -#ifdef SSR_USE_BLUR -float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; -float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} -gl_FragColor=vec4(SSR,blur_radius/255.0); -#else -#ifdef SSR_BLEND_WITH_FRESNEL -vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#else -vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#endif -vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); -#ifdef SSR_OUTPUT_IS_GAMMA_SPACE -finalColor=toGammaSpace(finalColor); -#endif -gl_FragColor=vec4(finalColor,colorFull.a); -#endif -#else -gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); -#endif -} -`;ShaderStore.ShadersStore.screenSpaceReflection2PixelShader=nH;let nX=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) -{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} -void main() -{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} -float blurRadius=colorFull.a*255.0; -vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} -`;ShaderStore.ShadersStore.screenSpaceReflection2BlurPixelShader=nX;let nY=`uniform sampler2D textureSampler; -uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; -#include -#ifdef SSR_BLEND_WITH_FRESNEL -#include -#include -uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; -#endif -void main() -{ -#ifdef SSRAYTRACE_DEBUG -gl_FragColor=texture2D(textureSampler,vUV); -#else -vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); -#ifndef SSR_DISABLE_REFLECTIVITY_TEST -if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} -#endif -#ifdef SSR_INPUT_IS_GAMMA_SPACE -color=toLinearSpace(color); -#endif -#ifdef SSR_BLEND_WITH_FRESNEL -vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#else -vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#endif -vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); -#ifdef SSR_OUTPUT_IS_GAMMA_SPACE -finalColor=toGammaSpace(finalColor); -#endif -gl_FragColor=vec4(finalColor,color.a); -#endif -} -`;ShaderStore.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader=nY;let nj=math_vector_Matrix.Compose(new math_vector_Vector3(.5,.5,.5),math_vector_Quaternion.Identity(),new math_vector_Vector3(.5,.5,.5)),nK=math_vector_Matrix.Compose(new math_vector_Vector3(.5,.5,1),math_vector_Quaternion.Identity(),new math_vector_Vector3(.5,.5,0));let SSRRenderingPipeline=class SSRRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;let t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){let e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!1,s=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0,e.generateNormalsInWorldSpace&&console.error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{let e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty(),e.generateNormalsInWorldSpace&&console.error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!"))}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var e,t;let i=this._scene.getEngine(),r=this._prePassRenderer,s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(r&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){let e=r.getRenderTarget();e&&e.textures&&(s=e.textures[r.getIndex(4)].getSize())}else(null===(t=this._ssrPostProcess)||void 0===t?void 0:t.inputTexture)&&(s.width=this._ssrPostProcess.inputTexture.width,s.height=this._ssrPostProcess.inputTexture.height);return s}_updateEffectDefines(){var e;let t=[];(this._geometryBufferRenderer||this._prePassRenderer)&&t.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&t.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&t.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(t.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&t.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&t.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&t.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&t.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&t.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&t.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&t.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&t.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&t.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&t.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&t.push("#define SSR_USE_BLUR"),this._debug&&t.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&t.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&t.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&t.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&t.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),null===(e=this._ssrPostProcess)||void 0===e||e.updateEffect(t.join("\n"))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;let t=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){let t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new DepthRenderer(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),t.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;let e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){let t=null!==(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))&&void 0!==e?e:-1;-1!==t&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,r;for(let s=0;s{this._resizeDepthRenderer();let t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){let i=t.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){let t=i.getIndex(5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));let r=this._scene.activeCamera;if(!r)return;let s=r.getViewMatrix(!0),a=r.getProjectionMatrix(!0);a.invertToRef(math_vector_TmpVectors.Matrix[0]),s.invertToRef(math_vector_TmpVectors.Matrix[1]),e.setMatrix("projection",a),e.setMatrix("view",s),e.setMatrix("invView",math_vector_TmpVectors.Matrix[1]),e.setMatrix("invProjectionMatrix",math_vector_TmpVectors.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);let n=this._getTextureSize();math_vector_Matrix.ScalingToRef(n.width,n.height,1,math_vector_TmpVectors.Matrix[2]),a.multiplyToRef(this._scene.getEngine().isWebGPU?nK:nj,math_vector_TmpVectors.Matrix[3]),math_vector_TmpVectors.Matrix[3].multiplyToRef(math_vector_TmpVectors.Matrix[2],math_vector_TmpVectors.Matrix[4]),e.setMatrix("projectionPixel",math_vector_TmpVectors.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new ScreenSpaceReflections2Configuration)}_createBlurAndCombinerPostProcesses(){let e=this._scene.getEngine();this._blurPostProcessX=new postProcess_PostProcess("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(e=>{var t,i;let r=null!==(i=null===(t=this._blurPostProcessX)||void 0===t?void 0:t.inputTexture.width)&&void 0!==i?i:this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/r,0)}),this._blurPostProcessY=new postProcess_PostProcess("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(e=>{var t,i;let r=null!==(i=null===(t=this._blurPostProcessY)||void 0===t?void 0:t.inputTexture.height)&&void 0!==i?i:this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/r)});let t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"],r="";this._debug&&(r+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(r+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(r+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(r+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new postProcess_PostProcess("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(e=>{var t;let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(r||i){if(r&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){let t=r.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[r.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){let t=i.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",i.getGBuffer().textures[t]),this.useFresnel&&(e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("depthSampler",i.getGBuffer().textures[0]))}else if(r){let t=r.getIndex(3);if(e.setTexture("reflectivitySampler",r.getRenderTarget().textures[t]),this.useFresnel){let t=r.getIndex(5),i=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[i]),e.setTexture("depthSampler",r.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();i.invertToRef(math_vector_TmpVectors.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",math_vector_TmpVectors.Matrix[0])}}}})}serialize(){let e=decorators_SerializationHelper.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return decorators_SerializationHelper.Parse(()=>new SSRRenderingPipeline(e._name,t,e._ratio),e,t,i)}};__decorate([serialize()],SSRRenderingPipeline.prototype,"samples",null),__decorate([serialize()],SSRRenderingPipeline.prototype,"maxDistance",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"step",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"thickness",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"strength",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"reflectionSpecularFalloffExponent",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"maxSteps",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"roughnessFactor",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"selfCollisionNumSkip",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"_reflectivityThreshold",void 0),__decorate([serialize("_ssrDownsample")],SSRRenderingPipeline.prototype,"_ssrDownsample",void 0),__decorate([serialize()],SSRRenderingPipeline.prototype,"ssrDownsample",null),__decorate([serialize("blurDispersionStrength")],SSRRenderingPipeline.prototype,"_blurDispersionStrength",void 0),__decorate([serialize("blurDownsample")],SSRRenderingPipeline.prototype,"_blurDownsample",void 0),__decorate([serialize("enableSmoothReflections")],SSRRenderingPipeline.prototype,"_enableSmoothReflections",void 0),__decorate([serialize("environmentTexture")],SSRRenderingPipeline.prototype,"_environmentTexture",void 0),__decorate([serialize("environmentTextureIsProbe")],SSRRenderingPipeline.prototype,"_environmentTextureIsProbe",void 0),__decorate([serialize("attenuateScreenBorders")],SSRRenderingPipeline.prototype,"_attenuateScreenBorders",void 0),__decorate([serialize("attenuateIntersectionDistance")],SSRRenderingPipeline.prototype,"_attenuateIntersectionDistance",void 0),__decorate([serialize("attenuateIntersectionIterations")],SSRRenderingPipeline.prototype,"_attenuateIntersectionIterations",void 0),__decorate([serialize("attenuateFacingCamera")],SSRRenderingPipeline.prototype,"_attenuateFacingCamera",void 0),__decorate([serialize("attenuateBackfaceReflection")],SSRRenderingPipeline.prototype,"_attenuateBackfaceReflection",void 0),__decorate([serialize("clipToFrustum")],SSRRenderingPipeline.prototype,"_clipToFrustum",void 0),__decorate([serialize("useFresnel")],SSRRenderingPipeline.prototype,"_useFresnel",void 0),__decorate([serialize("enableAutomaticThicknessComputation")],SSRRenderingPipeline.prototype,"_enableAutomaticThicknessComputation",void 0),__decorate([serialize("backfaceDepthTextureDownsample")],SSRRenderingPipeline.prototype,"_backfaceDepthTextureDownsample",void 0),__decorate([serialize("backfaceForceDepthWriteTransparentMeshes")],SSRRenderingPipeline.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),__decorate([serialize("isEnabled")],SSRRenderingPipeline.prototype,"_isEnabled",void 0),__decorate([serialize("inputTextureColorIsInGammaSpace")],SSRRenderingPipeline.prototype,"_inputTextureColorIsInGammaSpace",void 0),__decorate([serialize("generateOutputInGammaSpace")],SSRRenderingPipeline.prototype,"_generateOutputInGammaSpace",void 0),__decorate([serialize("debug")],SSRRenderingPipeline.prototype,"_debug",void 0),h["BABYLON.SSRRenderingPipeline"]=SSRRenderingPipeline;let nq=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; -#if defined(HABLE_TONEMAPPING) -const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; -#endif -float Luminance(vec3 c) -{return dot(c,vec3(0.22,0.707,0.071));} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 colour=texture2D(textureSampler,vUV).rgb; -#if defined(REINHARD_TONEMAPPING) -float lum=Luminance(colour.rgb); -float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); -colour*=scale/lum; -#elif defined(HABLE_TONEMAPPING) -colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; -#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) -colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; -#elif defined(PHOTOGRAPHIC_TONEMAPPING) -colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); -#endif -gl_FragColor=vec4(colour.rgb,1.0);}`;ShaderStore.ShadersStore.tonemapPixelShader=nq,function(e){e[e.Hable=0]="Hable",e[e.Reinhard=1]="Reinhard",e[e.HejiDawson=2]="HejiDawson",e[e.Photographic=3]="Photographic"}(t7||(t7={}));let n$=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -uniform mat4 viewProjection;uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`;ShaderStore.ShadersStore.volumetricLightScatteringPassVertexShader=nQ;let nZ=`#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV; -#endif -#if defined(ALPHATEST) -uniform sampler2D diffuseSampler; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#if defined(ALPHATEST) -vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) -discard; -#endif -gl_FragColor=vec4(0.0,0.0,0.0,1.0);} -`;ShaderStore.ShadersStore.volumetricLightScatteringPassPixelShader=nZ;let VolumetricLightScatteringPostProcess=class VolumetricLightScatteringPostProcess extends postProcess_PostProcess{get useDiffuseColor(){return logger_Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){logger_Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,s=100,a=texture_Texture.BILINEAR_SAMPLINGMODE,n,o,l){var h,c;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,a,n,o,"#define NUM_SAMPLES "+s),this._screenCoordinates=math_vector_Vector2.Zero(),this.customMeshPosition=math_vector_Vector3.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,n=(l=null!==(c=null!==(h=null==i?void 0:i.getScene())&&void 0!==h?h:l)&&void 0!==c?c:this._scene).getEngine(),this._viewPort=new math_viewport_Viewport(0,0,1,1).toGlobal(n.getRenderWidth(),n.getRenderHeight()),this.mesh=null!=r?r:VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh",l),this._createPass(l,t.passRatio||t),this.onActivate=e=>{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add(e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;let r=e.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);let s=null===(i=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(r,e,t);let a=[],n=[buffer_VertexBuffer.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&a.push("#define ALPHATEST"),r.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(n.push(buffer_VertexBuffer.UVKind),a.push("#define UV1")),r.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(n.push(buffer_VertexBuffer.UV2Kind),a.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(n.push(buffer_VertexBuffer.MatricesIndicesKind),n.push(buffer_VertexBuffer.MatricesWeightsKind),a.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),a.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):a.push("#define NUM_BONE_INFLUENCERS 0"),t&&(a.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(n),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES"));let l=e._getDrawWrapper(void 0,!0),h=l.defines,c=a.join("\n");return h!==c&&l.setEffect(r.getScene().getEngine().createEffect("volumetricLightScatteringPass",n,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],c,void 0,void 0,void 0,{maxSimultaneousMorphTargets:r.numBoneInfluencers}),c),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){let t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){let i;let r=e.getEngine();this._volumetricLightScatteringRTT=new renderTargetTexture_RenderTargetTexture("volumetricLightScatteringMap",{width:r.getRenderWidth()*t,height:r.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;let s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);let renderSubMesh=e=>{var t;let i=e.getRenderingMesh(),r=e.getEffectiveMesh();if(this._meshExcluded(i))return;r._internalAbstractMeshDataInfo._isActiveIntermediate=!1;let s=e.getMaterial();if(!s)return;let a=i.getScene(),n=a.getEngine();n.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);let o=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;let l=n.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){let h=null===(t=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[n.currentRenderPassId],c=e._getDrawWrapper();if(i!==this.mesh||c||(c=s._getDrawWrapper()),!c)return;let u=c.effect;if(n.enableEffect(c),l||i._bind(e,u,s.fillMode),i===this.mesh)s.bind(r.getWorldMatrix(),i);else if(h)h.bindForSubMesh(r.getWorldMatrix(),r,e);else{if(u.setMatrix("viewProjection",a.getTransformMatrix()),s&&s.needAlphaTesting()){let e=s.getAlphaTestTexture();u.setTexture("diffuseSampler",e),e&&u.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&u.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&u.setMatrix("world",r.getWorldMatrix()),i._processRendering(r,e,u,material_Material.TriangleFillMode,o,l,(e,t)=>{e||u.setMatrix("world",t)})}},a=new math_color_Color4(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{i=e.clearColor,e.clearColor=a}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=i}),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{let a;let n=e.getEngine();if(s.length){for(n.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0),n.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));let t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):logger_Logger.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){let e=engineStore_EngineStore.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return decorators_SerializationHelper.Parse(()=>new ScreenSpaceCurvaturePostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};__decorate([serialize()],ScreenSpaceCurvaturePostProcess.prototype,"ridge",void 0),__decorate([serialize()],ScreenSpaceCurvaturePostProcess.prototype,"valley",void 0),h["BABYLON.ScreenSpaceCurvaturePostProcess"]=ScreenSpaceCurvaturePostProcess;let n0=`uniform vec4 color; -`;ShaderStore.IncludesShadersStore.boundingBoxRendererFragmentDeclaration=n0;let n1=`#ifdef WEBGL2 -uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -#else -layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; -#endif -`;ShaderStore.IncludesShadersStore.boundingBoxRendererUboDeclaration=n1;let n2=`#include<__decl__boundingBoxRendererFragment> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.boundingBoxRendererPixelShader=n2;let n3=`uniform mat4 world;uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -`;ShaderStore.IncludesShadersStore.boundingBoxRendererVertexDeclaration=n3;let n4=`attribute vec3 position; -#include<__decl__boundingBoxRendererVertex> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec4 worldPos=world*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -} -`;ShaderStore.ShadersStore.boundingBoxRendererVertexShader=n4,Object.defineProperty(scene_Scene.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),scene_Scene.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new BoundingBoxRenderer(this)),this._boundingBoxRenderer},Object.defineProperty(abstractMesh_AbstractMesh.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});let BoundingBoxRenderer=class BoundingBoxRenderer{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_BOUNDINGBOXRENDERER,this.frontColor=new math_color_Color3(1,1,1),this.backColor=new math_color_Color3(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new observable_Observable,this.onAfterBoxRenderingObservable=new observable_Observable,this.onResourcesReadyObservable=new observable_Observable,this.enabled=!0,this.renderList=new SmartArray(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new UniformBuffer(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new UniformBuffer(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new shaderMaterial_ShaderMaterial("colorShader",this.scene,"boundingBoxRenderer",{attributes:[buffer_VertexBuffer.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new shaderMaterial_ShaderMaterial("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[buffer_VertexBuffer.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=CreateBoxVertexData({size:1});this._vertexBuffers[buffer_VertexBuffer.PositionKind]=new buffer_VertexBuffer(e,t.positions,buffer_VertexBuffer.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){let e=this._vertexBuffers[buffer_VertexBuffer.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;let r=this.scene.getEngine();r.setDepthWrite(!1);let s=this.scene.getTransformMatrix();for(let a=0;a{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_DEPTHRENDERER);t||(t=new DepthRendererSceneComponent(e),e._addComponent(t))};let n5=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( -frontColor.rgb+alphaMultiplier*backColor.rgb, -frontColor.a+backColor.a -);}`;ShaderStore.ShadersStore.oitFinalPixelShader=n5;let n6=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { -discard;}}`;ShaderStore.ShadersStore.oitBackBlendPixelShader=n6;let DepthPeelingEffectConfiguration=class DepthPeelingEffectConfiguration{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}};let DepthPeelingRenderer=class DepthPeelingRenderer{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){let t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new SmartArray(10),this._excludedSubMeshes=new SmartArray(10),this._excludedMeshes=[],this._colorCache=[new math_color_Color4(DepthPeelingRenderer._DEPTH_CLEAR_VALUE,DepthPeelingRenderer._DEPTH_CLEAR_VALUE,0,0),new math_color_Color4(-DepthPeelingRenderer._MIN_DEPTH,DepthPeelingRenderer._MAX_DEPTH,0,0),new math_color_Color4(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){logger_Logger.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let e=0;e -uniform vec4 color; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.linePixelShader=n8;let n7=`#include -#include -attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#include -mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=finalWorld*vec4(position,1.0); -#include -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.lineVertexShader=n7,abstractMesh_AbstractMesh.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},abstractMesh_AbstractMesh.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new EdgesRenderer(this,e,t,!0,i),this},Object.defineProperty(abstractMesh_AbstractMesh.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),LinesMesh.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new LineEdgesRenderer(this,e,t),this},InstancedLinesMesh.prototype.enableEdgesRendering=function(e=.95,t=!1){return LinesMesh.prototype.enableEdgesRendering.apply(this,arguments),this};let FaceAdjacencies=class FaceAdjacencies{constructor(){this.edges=[],this.edgesConnectedCount=0}};let EdgesRenderer=class EdgesRenderer{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){let t=new shaderMaterial_ShaderMaterial("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,r=!0,s){var a;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=[],this._linesNormals=[],this._linesIndices=[],this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new SmartArray(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=s?s:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new drawWrapper_DrawWrapper(e.getEngine())),this._prepareRessources(),r&&(null===(a=null==s?void 0:s.useAlternateEdgeFinder)||void 0===a||a?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=EdgesRenderer._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[buffer_VertexBuffer.PositionKind];e&&e._rebuild(),(e=this._buffers[buffer_VertexBuffer.NormalKind])&&e._rebuild();let t=this._source.getScene(),i=t.getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[buffer_VertexBuffer.PositionKind];t&&(t.dispose(),this._buffers[buffer_VertexBuffer.PositionKind]=null),(t=this._buffers[buffer_VertexBuffer.NormalKind])&&(t.dispose(),this._buffers[buffer_VertexBuffer.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),null===(e=this._drawWrapper)||void 0===e||e.dispose()}_processEdgeForAdjacencies(e,t,i,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,r,s){let a;if(void 0===t)a=!0;else{let r=math_vector_Vector3.Dot(i[e],i[t]);a=r{i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?s=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(s=2);for(let t=0;t<3;++t)t===s?e[t].sort((e,t)=>e[1]t[1]?1:0):e[t].sort((e,t)=>e[1]>t[1]?-1:e[1]=s+1;--a)makePointList(e[a%3],n,a!==s+2?r[i[t+(a+1)%3]]:-1);let l=n.length;i.push(r[i[t+s]],a[0],n[0]),i.push(r[i[t+(s+1)%3]],n[l-1],a[o-1]);let h=o<=l,c=h?o:l,u=h?l:o,d=h?o-1:l-1,_=h?0:1,p=o+l-2,f=0,m=0,g=h?a:n,v=h?n:a,x=0;for(;p-- >0;){let e;_?i.push(g[f],v[m]):i.push(v[m],g[f]),(x+=c)>=u&&fs){let e=r;r=s,s=e}let n=r+"_"+s,o=m[n];if(o){if(!o.done){let e=math_vector_Vector3.Dot(t,o.normal);e0||this._source.hasThinInstances)}render(){let e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}let i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances,s=0;if(r){if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){let e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;enull!=e),this._scene.autoClear=!0;let r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;let s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),a=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0],n=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),a?n=a:this._needsCompositionForThisPass?n=e.imageProcessingPostProcess:s&&(n=s),this._bindFrameBuffer(),this._linkInternalTexture(e,n)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e))){for(let r=0;r=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw _WarnImport("PrePassRendererSceneComponent")},PrePassRenderer.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(scene_Scene.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),scene_Scene.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new PrePassRenderer(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,logger_Logger.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},scene_Scene.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};let PrePassRendererSceneComponent=class PrePassRendererSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;let s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){let t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}};PrePassRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_PREPASSRENDERER);t||(t=new PrePassRendererSceneComponent(e),e._addComponent(t))};let n9=`#define rcp(x) 1./x -#define GOLDEN_RATIO 1.618033988749895 -#define TWO_PI 6.2831855 -vec2 Golden2dSeq(int i,float n) -{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} -vec2 SampleDiskGolden(int i,int sampleCount) -{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;ShaderStore.IncludesShadersStore.fibonacci=n9,ShaderStore.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";let oe=`#include -#include -#include -#include -varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; -#define rcp(x) 1./x -#define Sq(x) x*x -#define SSS_BILATERAL_FILTER true -vec3 EvalBurleyDiffusionProfile(float r,vec3 S) -{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); -vec3 expSum=exp_13*(1.+exp_13*exp_13); -return (S*rcp(8.*PI))*expSum; } -vec2 SampleBurleyDiffusionProfile(float u,float rcpS) -{u=1.-u; -float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); -float p=(g*n)*n; -float c=1.+p+n; -float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); -float x=(3./LOG2_E)*log2(c)-d; -float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; -return vec2(r,rcpPdf);} -vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) -{ -#ifndef SSS_BILATERAL_FILTER -z=0.; -#endif -float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; -#if SSS_CLAMP_ARTIFACT -return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); -#else -return EvalBurleyDiffusionProfile(r,S)*area; -#endif -} -void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, -float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) -{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; -float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; -vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; -float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) -{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} -else -{}} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) -{centerDepth=texture2D(depthSampler,vUV).r;} -if (!passedStencilTest) { -gl_FragColor=inputColor;return;} -float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; -vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; -float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) -{ -#ifdef DEBUG_SSS_SAMPLES -vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; -#endif -gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} -#ifdef DEBUG_SSS_SAMPLES -vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; -#endif -float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); -vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration){logger_Logger.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}let i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}};let SubSurfaceConfiguration=class SubSurfaceConfiguration{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=sceneComponent_SceneComponentConstants.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new math_color_Color3(1,1,1)),this._scene=e,SubSurfaceConfiguration._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return logger_Logger.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw _WarnImport("SubSurfaceSceneComponent")},AbstractScene.AddParser(sceneComponent_SceneComponentConstants.NAME_SUBSURFACE,(e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_SUBSURFACE);t||(t=new SubSurfaceSceneComponent(e),e._addComponent(t))};let ot=`#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -uniform vec4 color; -#ifdef ALPHATEST -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#include -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.outlinePixelShader=ot;let oi=`attribute vec3 position;attribute vec3 normal; -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -uniform float offset; -#include -uniform mat4 viewProjection; -#ifdef ALPHATEST -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position;vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -vec3 offsetPosition=positionUpdated+(normalUpdated*offset); -#include -#include -#include -vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; -#ifdef ALPHATEST -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#include -#include -} -`;ShaderStore.ShadersStore.outlineVertexShader=oi,scene_Scene.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new OutlineRenderer(this)),this._outlineRenderer},Object.defineProperty(mesh_Mesh.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(mesh_Mesh.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});let OutlineRenderer=class OutlineRenderer{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{_.setMatrix("world",t)}),a.setZOffset(0),a.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];let r=[],s=[buffer_VertexBuffer.PositionKind,buffer_VertexBuffer.NormalKind],a=e.getMesh(),n=e.getMaterial();if(!n)return!1;let o=a.getScene();n.needAlphaTesting()&&(r.push("#define ALPHATEST"),a.isVerticesDataPresent(buffer_VertexBuffer.UVKind)&&(s.push(buffer_VertexBuffer.UVKind),r.push("#define UV1")),a.isVerticesDataPresent(buffer_VertexBuffer.UV2Kind)&&(s.push(buffer_VertexBuffer.UV2Kind),r.push("#define UV2"))),n.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),prepareStringDefinesForClipPlanes(n,o,r),a.useBones&&a.computeBonesUsingShaders?(s.push(buffer_VertexBuffer.MatricesIndicesKind),s.push(buffer_VertexBuffer.MatricesWeightsKind),a.numBoneInfluencers>4&&(s.push(buffer_VertexBuffer.MatricesIndicesExtraKind),s.push(buffer_VertexBuffer.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+a.numBoneInfluencers),r.push("#define BonesPerMesh "+(a.skeleton?a.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");let l=a.morphTargetManager,h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(s,a,h)),t&&(r.push("#define INSTANCES"),MaterialHelper.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));let c=e._getDrawWrapper(i,!0),u=c.defines,d=r.join("\n");if(u!==d){let e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];addClipPlaneUniforms(e),c.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return c.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){let r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(OutlineRenderer._StencilReference),this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){let e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}};OutlineRenderer._StencilReference=4;let FluidRenderingObject=class FluidRenderingObject{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!(null===(e=this.vertexBuffers)||void 0===e?void 0:e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new observable_Observable,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){let e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new EffectWrapper({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new EffectWrapper({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;let e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){let e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;let t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){let e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;let t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;null===(e=this._depthEffectWrapper)||void 0===e||e.dispose(),null===(t=this._thicknessEffectWrapper)||void 0===t||t.dispose()}};let FluidRenderingObjectParticleSystem=class FluidRenderingObjectParticleSystem extends FluidRenderingObject{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add(()=>{this._engine.setAlphaMode(2)})))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}};let FluidRenderingTextures=class FluidRenderingTextures{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){let e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,r,s,a,n=1,o=6,l=1,h=6,c=!1,u=null,d=!0,_=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new observable_Observable,this._name=e,this._scene=t,this._camera=u,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=a,this._textureType=n,this._textureFormat=o,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=c,this._generateDepthBuffer=d,this._samples=_,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==a,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){let[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});let e=this._rt.texture;e.incrementReferences(),this._texture=new texture_Texture(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,r,s,a=!1){let n=this._scene.getEngine(),o=new math_vector_Vector2(Math.floor(this._blurTextureSizeX/r),Math.floor(this._blurTextureSizeY/r)),l=1===t&&n.getCaps().textureFloatLinearFiltering||2===t&&n.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:o.x,height:o.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),c=h.texture;c.incrementReferences();let u=new texture_Texture(null,this._scene);if(u.name="rttBlurred"+s,u._texture=c,u.wrapU=texture_Texture.CLAMP_ADDRESSMODE,u.wrapV=texture_Texture.CLAMP_ADDRESSMODE,u.anisotropicFilteringLevel=1,a){let r=new postProcess_PostProcess("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,n,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),r.onSizeChangedObservable.add(()=>{r._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(r);let s=new postProcess_PostProcess("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,n,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.onApplyObservable.add(e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),s.onSizeChangedObservable.add(()=>{s._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s),r.autoClear=!1,s.autoClear=!1;let a=[];for(let e=0;e<2*this._blurNumIterations;++e)a[e]=1&e?s:r;return[h,u,a]}{let r=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new postProcess_PostProcess("BilateralBlurX","fluidRenderingBilateralBlur",r,null,1,null,1,n,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),s.onSizeChangedObservable.add(()=>{s._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s);let a=new postProcess_PostProcess("BilateralBlurY","fluidRenderingBilateralBlur",r,null,1,null,1,n,!0,null,t,void 0,void 0,void 0,i);a.samples=this._samples,a.onApplyObservable.add(e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),a.onSizeChangedObservable.add(()=>{a._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(a),s.autoClear=!1,a.autoClear=!1;let o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?a:s;return[h,u,o]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((null!==(t=null===(e=this._camera)||void 0===e?void 0:e.fov)&&void 0!==t?t:45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,r;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),null===(e=this._rt)||void 0===e||e.dispose(),this._rt=null,null===(t=this._texture)||void 0===t||t.dispose(),this._texture=null,null===(i=this._rtBlur)||void 0===i||i.dispose(),this._rtBlur=null,null===(r=this._textureBlurred)||void 0===r||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}};!function(e){e[e.DepthTexture=0]="DepthTexture",e[e.DepthBlurredTexture=1]="DepthBlurredTexture",e[e.ThicknessTexture=2]="ThicknessTexture",e[e.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",e[e.DiffuseTexture=4]="DiffuseTexture",e[e.Normals=5]="Normals",e[e.DiffuseRendering=6]="DiffuseRendering"}(t9||(t9={}));let FluidRenderingTargetRenderer=class FluidRenderingTargetRenderer{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new math_color_Color3(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new math_vector_Vector3(-2,-1,1).normalize(),this._debugFeature=t9.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new observable_Observable,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=null!=t?t:e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new math_vector_Matrix,this._depthClearColor=new math_color_Color4(1e6,1e6,1e6,1),this._thicknessClearColor=new math_color_Color4(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;let r=null!==(e=this._depthMapSize)&&void 0!==e?e:this._engine.getRenderWidth(),s=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new FluidRenderingTextures("Depth",this._scene,r,s,r,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){let e=null!==(t=this._diffuseMapSize)&&void 0!==t?t:this._engine.getRenderWidth(),i=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new FluidRenderingTextures("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}let a=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),n=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new FluidRenderingTextures("Thickness",this._scene,a,n,a,n,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){(null===e||e===this._depthRenderTarget)&&this._setBlurDepthParameters(),(null===e||e===this._thicknessRenderTarget)&&this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){var e;let t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;let a=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,n=new math_vector_Vector2(1/a.getSize().width,1/a.getSize().height);if(this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap){let t=null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture;t&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT"))}this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),r.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===t9.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===t9.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),(this._debugFeature===t9.DepthTexture||this._debugFeature===t9.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new postProcess_PostProcess("FluidRendering","fluidRenderingRender",i,r,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(e=>{var i,r,s,a,o,l,h,c,u,d,_,p,f,m,g,v,x,b,T,S,C,E,y;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&e.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(a=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==a?a:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==r?r:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(c=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==c?c:null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(l=null===(o=this._diffuseRenderTarget.texture)||void 0===o?void 0:o.getInternalTexture())&&void 0!==l?l:null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&e.setTextureSampler("bgDepthSamplerSampler",null!==(u=this._bgDepthTexture)&&void 0!==u?u:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(f=null===(p=this._thicknessRenderTarget.textureBlur)||void 0===p?void 0:p.getInternalTexture())&&void 0!==f?f:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(_=null===(d=this._thicknessRenderTarget.texture)||void 0===d?void 0:d.getInternalTexture())&&void 0!==_?_:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){let i=null!==(m=this._environmentMap)&&void 0!==m?m:this._scene.environmentTexture;i&&(e.setTexture("reflectionSampler",i),t.isWebGPU&&e.setTextureSampler("reflectionSamplerSampler",null!==(g=null==i?void 0:i.getInternalTexture())&&void 0!==g?g:null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",n),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case t9.DepthTexture:i=this._depthRenderTarget.texture;break;case t9.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case t9.ThicknessTexture:i=null!==(x=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==x?x:null;break;case t9.ThicknessBlurredTexture:i=(null===(b=this._thicknessRenderTarget)||void 0===b?void 0:b.enableBlur)?null!==(S=null===(T=this._thicknessRenderTarget)||void 0===T?void 0:T.textureBlur)&&void 0!==S?S:null:null!==(E=null===(C=this._thicknessRenderTarget)||void 0===C?void 0:C.texture)&&void 0!==E?E:null;break;case t9.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==t9.Normals&&(e.setTexture("debugSampler",i),t.isWebGPU&&e.setTextureSampler("debugSamplerSampler",null!==(y=null==i?void 0:i.getInternalTexture())&&void 0!==y?y:null))}})}_clearTargets(){var e,t,i;(null===(e=this._depthRenderTarget)||void 0===e?void 0:e.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(t=this._diffuseRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(i=this._thicknessRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var t,i,r,s,a,n;if(this._needInitialization||!e.isReady())return;let o=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(null===(t=this._depthRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(i=this._diffuseRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(r=this._thicknessRenderTarget)||void 0===r?void 0:r.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),null===(s=this._depthRenderTarget)||void 0===s||s.applyBlurPostProcesses(),null===(a=this._diffuseRenderTarget)||void 0===a||a.applyBlurPostProcesses(),null===(n=this._thicknessRenderTarget)||void 0===n||n.applyBlurPostProcesses(),o&&this._engine.bindFramebuffer(o)}dispose(e=!1){var t,i,r,s;e||(null===(t=this._depthRenderTarget)||void 0===t||t.dispose(),this._depthRenderTarget=null,null===(i=this._diffuseRenderTarget)||void 0===i||i.dispose(),this._diffuseRenderTarget=null,null===(r=this._thicknessRenderTarget)||void 0===r||r.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),null===(s=this._renderPostProcess)||void 0===s||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}};let FluidRenderingObjectCustomParticles=class FluidRenderingObjectCustomParticles extends FluidRenderingObject{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(let t in e){let i;let r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new buffer_VertexBuffer(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new EffectWrapper({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new buffer_VertexBuffer(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&null!==(t=null===(e=this._diffuseEffectWrapper)||void 0===e?void 0:e.effect.isReady())&&void 0!==t&&t}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){let e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;let t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;for(let t in super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose(),this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}};let or=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; -#include -void main(void) -{vec4 color=texture2D(textureSampler,vUV); -#ifdef DEPTH_TEXTURE -gl_FragDepth=color.r; -#else -if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} -gl_FragColor=color; -#endif -} -`;ShaderStore.ShadersStore.copyTextureToTexturePixelShader=or,function(e){e[e.None=0]="None",e[e.ToLinearSpace=1]="ToLinearSpace",e[e.ToGammaSpace=2]="ToGammaSpace"}(ie||(ie={}));let CopyTextureToTexture=class CopyTextureToTexture{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new EffectRenderer(e),this._effectWrapper=new EffectWrapper({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add(()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)})}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=ie.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;let r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}};let FluidRenderingDepthTextureCopy=class FluidRenderingDepthTextureCopy{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new CopyTextureToTexture(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}};let os=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; -#ifdef FLUIDRENDERING_VELOCITY -attribute vec3 velocity;varying float velocityNorm; -#endif -void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; -#ifdef FLUIDRENDERING_VELOCITY -velocityNorm=length(velocity); -#endif -} -`;ShaderStore.ShadersStore.fluidRenderingParticleDepthVertexShader=os;let oa=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; -#ifdef FLUIDRENDERING_VELOCITY -varying float velocityNorm; -#endif -void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); -#ifndef FLUIDRENDERING_RHS -normal.z=-normal.z; -#endif -vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; -#ifdef WEBGPU -gl_FragDepth=clipSpacePos.z/clipSpacePos.w; -#else -gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; -#endif -#ifdef FLUIDRENDERING_RHS -realViewPos.z=-realViewPos.z; -#endif -#ifdef FLUIDRENDERING_VELOCITY -glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); -#else -glFragColor=vec4(realViewPos.z,0.,0.,1.); -#endif -} -`;ShaderStore.ShadersStore.fluidRenderingParticleDepthPixelShader=oa;let on=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} -`;ShaderStore.ShadersStore.fluidRenderingParticleThicknessVertexShader=on;let oo=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} -`;ShaderStore.ShadersStore.fluidRenderingParticleThicknessPixelShader=oo;let ol=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} -`;ShaderStore.ShadersStore.fluidRenderingParticleDiffuseVertexShader=ol;let oh=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} -`;ShaderStore.ShadersStore.fluidRenderingParticleDiffusePixelShader=oh;let oc=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} -int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} -glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} -`;ShaderStore.ShadersStore.fluidRenderingBilateralBlurPixelShader=oc;let ou=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} -float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} -sum/=wsum;glFragColor=vec4(sum.rgb,1.);} -`;ShaderStore.ShadersStore.fluidRenderingStandardBlurPixelShader=ou;let od=`/* disable_uniformity_analysis */ -#define IOR 1.333 -#define ETA 1.0/IOR -#define F0 0.02 -uniform sampler2D textureSampler;uniform sampler2D depthSampler; -#ifdef FLUIDRENDERING_DIFFUSETEXTURE -uniform sampler2D diffuseSampler; -#else -uniform vec3 diffuseColor; -#endif -#ifdef FLUIDRENDERING_FIXED_THICKNESS -uniform float thickness;uniform sampler2D bgDepthSampler; -#else -uniform float minimumThickness;uniform sampler2D thicknessSampler; -#endif -#ifdef FLUIDRENDERING_ENVIRONMENT -uniform samplerCube reflectionSampler; -#endif -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) -uniform sampler2D debugSampler; -#endif -uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; -#ifdef FLUIDRENDERING_RHS -ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; -#else -ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; -#endif -ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} -vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} -void main(void) {vec2 texCoord=vUV; -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) -vec4 color=texture2D(debugSampler,texCoord); -#ifdef FLUIDRENDERING_DEBUG_DEPTH -glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} -#else -glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} -#endif -return; -#endif -vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; -#ifndef FLUIDRENDERING_FIXED_THICKNESS -float thickness=texture2D(thicknessSampler,texCoord).x; -#else -float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; -#endif -vec4 backColor=texture2D(textureSampler,texCoord); -#ifndef FLUIDRENDERING_FIXED_THICKNESS -if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { -#else -if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { -#endif -glFragColor=backColor;return;} -vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} -vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} -vec3 normal=normalize(cross(ddy,ddx)); -#ifdef FLUIDRENDERING_RHS -normal=-normal; -#endif -#ifndef WEBGPU -if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} -#endif -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) -glFragColor=vec4(normal*0.5+0.5,1.0);return; -#endif -vec3 rayDir=normalize(viewPos); -#ifdef FLUIDRENDERING_DIFFUSETEXTURE -vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; -#endif -vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); -#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING -float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; -#endif -vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); -vec3 refractionColor=transmitted.rgb*transmittance; -#ifdef FLUIDRENDERING_ENVIRONMENT -vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; -#else -vec3 finalColor=refractionColor+specular; -#endif -#ifdef FLUIDRENDERING_VELOCITY -float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); -#endif -glFragColor=vec4(finalColor,transmitted.a);} -`;function IsParticleSystemObject(e){return!!e.particleSystem}ShaderStore.ShadersStore.fluidRenderingRenderPixelShader=od,Object.defineProperty(scene_Scene.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),scene_Scene.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new FluidRenderer(this)),this._fluidRenderer},scene_Scene.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};let FluidRendererSceneComponent=class FluidRendererSceneComponent{constructor(e){this.name=sceneComponent_SceneComponentConstants.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(sceneComponent_SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(sceneComponent_SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._prepareRendering()}_afterCameraDraw(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._render(e)}rebuild(){this.scene._fluidRenderer&&(this.scene.disableFluidRenderer(),this.scene.enableFluidRenderer())}dispose(){this.scene.disableFluidRenderer()}};let FluidRenderer=class FluidRenderer{static _SceneComponentInitialization(e){let t=e._getComponent(sceneComponent_SceneComponentConstants.NAME_FLUIDRENDERER);t||(t=new FluidRendererSceneComponent(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,FluidRenderer._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){let t=this._getParticleSystemIndex(e);return -1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){let s=new FluidRenderingObjectParticleSystem(this._scene,e);s.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new FluidRenderingTargetRenderer(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==t&&(i.generateDiffuseTexture=t);let a={object:s,targetRenderer:i};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}addCustomParticles(e,t,i,r,s){let a=new FluidRenderingObjectCustomParticles(this._scene,e,t);a.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),r||(r=new FluidRenderingTargetRenderer(this._scene,s),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==i&&(r.generateDiffuseTexture=i);let n={object:a,targetRenderer:r};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}removeRenderObject(e,t=!0){let i=this.renderObjects.indexOf(e);return -1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort((e,t)=>e.object.priorityt.object.priority?1:0)}_removeUnusedTargetRenderers(){let e={};for(let t=0;t{var e;for(let t of(s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,a[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`),a)){let i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,r=null==i?void 0:i.texture;if(i&&r){let e=r.width+"_"+r.height,t=n[e];t||(t=n[e]=new FluidRenderingDepthTextureCopy(this._engine,r.width,r.height)),t.depthRTWrapper._shareDepth(i)}}})}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=this._cameras.get(t),s=r[1],a=e.get(t);if(a)for(let e in s)a[1][e]||s[e].dispose();else for(let e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){let e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)})}_setUseVelocityForRenderObject(){for(let e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(let e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var t;for(let t=0;t{let t=e[1];for(let e in t)t[e].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}};let ThinSprite=class ThinSprite{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}};let Sprite=class Sprite extends ThinSprite{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=[],this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new observable_Observable,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new math_color_Color4(1,1,1,1),this.position=math_vector_Vector3.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e0)for(let a=0;a=s.distance))&&(s=o,i))break}return s||new PickingInfo},scene_Scene.prototype._internalMultiPickSprites=function(e,t,i){if(!PickingInfo)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(sceneComponent_SceneComponentConstants.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();let e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){let a=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return a&&(a.ray=e?e.ray:null),a}_pointerMove(e,t,i,r,s){let a=this.scene;return r?a.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,a.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(a.setPointerOverSprite(i.pickedSprite),!a.doNotHandleCursors&&s&&(a._pointerOverSprite&&a._pointerOverSprite.actionManager&&a._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=a._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=a.hoverCursor)):a.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){let s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,ActionEvent.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,ActionEvent.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,ActionEvent.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,ActionEvent.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){let a=this.scene;if(a.spriteManagers&&a.spriteManagers.length>0){let i=a.pickSprite(e,t,this._spritePredicate,!1,a.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,ActionEvent.CreateNewFromSprite(i.pickedSprite,a,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,ActionEvent.CreateNewFromSprite(i.pickedSprite,a,r)),s&&i.pickedSprite.actionManager.processTrigger(6,ActionEvent.CreateNewFromSprite(i.pickedSprite,a,r)))),a._pickedDownSprite&&a._pickedDownSprite.actionManager&&a._pickedDownSprite!==i.pickedSprite&&a._pickedDownSprite.actionManager.processTrigger(16,ActionEvent.CreateNewFromSprite(a._pickedDownSprite,a,r)))}return i}};let o_=`#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); -#endif -`;ShaderStore.IncludesShadersStore.imageProcessingCompatibility=o_;let op=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -#ifdef PIXEL_PERFECT -vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} -#endif -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#ifdef PIXEL_PERFECT -vec2 uv=uvPixelPerfect(vUV); -#else -vec2 uv=vUV; -#endif -vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) -{if (color.a<0.95) -discard;} -color*=vColor; -#include -gl_FragColor=color; -#include -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.spritesPixelShader=op;let of=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; -vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); -vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; -#ifdef FOG -vFogDistance=viewPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.spritesVertexShader=of;let SpriteRenderer=class SpriteRenderer{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,r=null){let s;this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new Buffer(e,this._vertexData,!0,this._vertexBufferSize);let a=this._buffer.createVertexBuffer(buffer_VertexBuffer.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),n=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),o=6;if(this._useInstancing){let t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new Buffer(e,t,!1,2),s=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else s=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;let l=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),c=this._buffer.createVertexBuffer(buffer_VertexBuffer.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[buffer_VertexBuffer.PositionKind]=a,this._vertexBuffers.options=n,this._vertexBuffers.offsets=s,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[buffer_VertexBuffer.ColorKind]=c,this._createEffects()}_createEffects(){var e,t,i,r;null===(e=this._drawWrapperBase)||void 0===e||e.dispose(),null===(t=this._drawWrapperFog)||void 0===t||t.dispose(),null===(i=this._drawWrapperDepth)||void 0===i||i.dispose(),null===(r=this._drawWrapperFogDepth)||void 0===r||r.dispose(),this._drawWrapperBase=new drawWrapper_DrawWrapper(this._engine),this._drawWrapperFog=new drawWrapper_DrawWrapper(this._engine),this._drawWrapperDepth=new drawWrapper_DrawWrapper(this._engine,!1),this._drawWrapperFogDepth=new drawWrapper_DrawWrapper(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);let s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[buffer_VertexBuffer.PositionKind,"options","offsets","inverts","cellInfo",buffer_VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],s),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[buffer_VertexBuffer.PositionKind,"options","offsets","inverts","cellInfo",buffer_VertexBuffer.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],s+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,r,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let a=this._drawWrapperBase,n=this._drawWrapperDepth,o=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(a=this._drawWrapperFog,n=this._drawWrapperFogDepth,o=!0);let l=a.effect;if(!l.isReady())return;let h=this._engine,c=!!(this._scene&&this._scene.useRightHandedSystem),u=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length),_=0,p=!0;for(let i=0;i>0;t._xOffset=(t.cellIndex-i*e)*this.cellWidth/s.width,t._yOffset=i*this.cellHeight/s.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._useInstancing?o-=2:(this._vertexData[o+6]=i,this._vertexData[o+7]=r),a?this._vertexData[o+8]=t.invertU?0:1:this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0,this._vertexData[o+10]=t._xOffset,this._vertexData[o+11]=t._yOffset,this._vertexData[o+12]=t._xSize/s.width,this._vertexData[o+13]=t._ySize/s.height,this._vertexData[o+14]=t.color.r,this._vertexData[o+15]=t.color.g,this._vertexData[o+16]=t.color.b,this._vertexData[o+17]=t.color.a}_buildIndexBuffer(){let e=[],t=0;for(let i=0;i{e.cellRef||(e.cellIndex=0);let i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=engineStore_EngineStore.LastCreatedScene),s._getComponent(sceneComponent_SceneComponentConstants.NAME_SPRITE)||s._addComponent(new SpriteSceneComponent(s)),this._fromPacked=o,this._scene=s;let h=this._scene.getEngine();if(this._spriteRenderer=new SpriteRenderer(h,i,a,s),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(void 0!==r)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new texture_Texture(t,s,!0,!1,n)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if((e="string"==typeof t?JSON.parse(t):t).frames.length){let t={};for(let i=0;i0);let r=e.substring(0,t-1)+".json";tools_Tools.LoadFile(r,e=>{try{let t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON format. Please check documentation for format specifications.")}},void 0,void 0,!1,()=>{logger_Logger.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1})}}_checkTextureAlpha(e,t,i,r,s){if(!e.useAlphaForPicking||!this.texture)return!0;let a=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(a.width*a.height*4),this.texture.readPixels(0,0,this._textureContent));let n=math_vector_TmpVectors.Vector3[0];n.copyFrom(t.direction),n.normalize(),n.scaleInPlace(i),n.addInPlace(t.origin);let o=(n.x-r.x)/(s.x-r.x),l=1-(n.y-r.y)/(s.y-r.y),h=e._xOffset*a.width+o*e._xSize|0,c=e._yOffset*a.height+l*e._ySize|0,u=this._textureContent[(h+c*a.width)*4+3];return u>.5}intersects(e,t,i,r){let s=Math.min(this.capacity,this.sprites.length),a=math_vector_Vector3.Zero(),n=math_vector_Vector3.Zero(),o=Number.MAX_VALUE,l=null,h=math_vector_TmpVectors.Vector3[0],c=math_vector_TmpVectors.Vector3[1],u=t.getViewMatrix(),d=e,_=e;for(let t=0;te){if(!this._checkTextureAlpha(s,d,e,a,n))continue;if(_=d,o=e,l=s,r)break}}}}if(l){let e=new PickingInfo;u.invertToRef(math_vector_TmpVectors.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=o;let t=math_vector_TmpVectors.Vector3[2];return t.copyFrom(_.direction),t.normalize(),t.scaleInPlace(o),_.origin.addToRef(t,h),e.pickedPoint=math_vector_Vector3.TransformCoordinates(h,math_vector_TmpVectors.Matrix[0]),e}return null}multiIntersects(e,t,i){let r;let s=Math.min(this.capacity,this.sprites.length),a=math_vector_Vector3.Zero(),n=math_vector_Vector3.Zero(),o=[],l=math_vector_TmpVectors.Vector3[0].copyFromFloats(0,0,0),h=math_vector_TmpVectors.Vector3[1].copyFromFloats(0,0,0),c=t.getViewMatrix();for(let t=0;t{let n=new webRequest_WebRequest;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let t=JSON.parse(n.responseText),a=spriteManager_SpriteManager.Parse(t,i||engineStore_EngineStore.LastCreatedScene,r);e&&(a.name=e),s(a)}else a("Unable to load the sprite manager")}}),n.open("GET",t),n.send()})}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new spriteManager_SpriteManager("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,s)=>{let a=new webRequest_WebRequest;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let s=JSON.parse(JSON.parse(a.responseText).jsonPayload),n=JSON.parse(s.spriteManager),o=spriteManager_SpriteManager.Parse(n,t||engineStore_EngineStore.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),a.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),a.send()})}};spriteManager_SpriteManager.SnippetUrl="https://snippet.babylonjs.com",spriteManager_SpriteManager.CreateFromSnippetAsync=spriteManager_SpriteManager.ParseFromSnippetAsync;let om=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( -texture2D(frameMap,vec2(fX,0.),0.), -texture2D(frameMap,vec2(fX,fdStep*1.),0.), -texture2D(frameMap,vec2(fX,fdStep*2.),0.), -vec4(0.) -);} -void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); -#ifdef FLIPU -tileUV.y=1.0-tileUV.y; -#endif -vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;} -animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} -mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} -vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} -color.xyz*=colorMul;gl_FragColor=color;}`;ShaderStore.ShadersStore.spriteMapPixelShader=om;let og=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; -gl_Position=worldViewProjection*p;}`;ShaderStore.ShadersStore.spriteMapVertexShader=og,function(e){e[e.INIT=0]="INIT",e[e.RUNNING=1]="RUNNING",e[e.DONE=2]="DONE",e[e.ERROR=3]="ERROR"}(it||(it={})),observable_Observable.prototype.notifyObserversWithPromise=async function(e,t=-1,i,r,s){let a=Promise.resolve(e);if(!this.observers.length)return a;let n=this._eventState;return n.mask=t,n.target=i,n.currentTarget=r,n.skipNextObservers=!1,n.userInfo=s,this.observers.forEach(i=>{!n.skipNextObservers&&!i._willBeUnregistered&&i.mask&t&&(a=i.scope?a.then(t=>(n.lastReturnValue=t,i.callback.apply(i.scope,[e,n]))):a.then(t=>(n.lastReturnValue=t,i.callback(e,n))),i.unregisterOnNextCall&&this._deferUnregister(i))}),await a,e};let SceneOptimization=class SceneOptimization{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}};let MergeMeshesOptimization=class MergeMeshesOptimization extends SceneOptimization{constructor(){super(...arguments),this._canBeMerged=e=>e instanceof mesh_Mesh&&!e.isDisposed()&&!!e.isVisible&&!!e.isEnabled()&&!(e.instances.length>0)&&!e.skeleton&&!e.hasLODLevels&&0!==e.getTotalVertices()}static get UpdateSelectionTree(){return MergeMeshesOptimization._UpdateSelectionTree}static set UpdateSelectionTree(e){MergeMeshesOptimization._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){let r=e.meshes.slice(0),s=r.length;for(let e=0;e{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),ov[e.id]=!0)},SerializeMesh=(e,t)=>{let i={},r=e._geometry;return r&&!e.getScene().getGeometryById(r.id)&&SerializeGeometry(r,t.geometries),e.serialize&&e.serialize(i),i},FinalizeSingleNode=(e,t)=>{if(e._isMesh){if(1===e.delayLoadState||0===e.delayLoadState){let serializeMaterial=i=>{t.materials=t.materials||[],e.material&&!t.materials.some(t=>t.id===e.material.id)&&t.materials.push(i.serialize())};if(e.material&&!e.material.doNotSerialize){if(e.material instanceof multiMaterial_MultiMaterial){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some(t=>t.id===e.material.id))for(let i of(t.multiMaterials.push(e.material.serialize()),e.material.subMaterials))i&&serializeMaterial(i)}else serializeMaterial(e.material)}else e.material||serializeMaterial(e.getScene().defaultMaterial);let i=e._geometry;i&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),SerializeGeometry(i,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(SerializeMesh(e,t))}}else"TransformNode"===e.getClassName()?t.transformNodes.push(e.serialize()):-1!==e.getClassName().indexOf("Camera")?t.cameras.push(e.serialize()):-1!==e.getClassName().indexOf("Light")&&t.lights.push(e.serialize())};let sceneSerializer_SceneSerializer=class sceneSerializer_SceneSerializer{static ClearCache(){ov=[]}static Serialize(e){return sceneSerializer_SceneSerializer._Serialize(e)}static _Serialize(e,t=!0){let i,r,s;let a={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&texture_Texture.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),sceneSerializer_SceneSerializer.ClearCache(),a.useDelayedTextureLoading=e.useDelayedTextureLoading,a.autoClear=e.autoClear,a.clearColor=e.clearColor.asArray(),a.ambientColor=e.ambientColor.asArray(),a.gravity=e.gravity.asArray(),a.collisionsEnabled=e.collisionsEnabled,a.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(a.fogMode=e.fogMode,a.fogColor=e.fogColor.asArray(),a.fogStart=e.fogStart,a.fogEnd=e.fogEnd,a.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){let t=e.getPhysicsEngine();t&&(a.physicsEnabled=!0,a.physicsGravity=t.gravity.asArray(),a.physicsEngine=t.getPhysicsPluginName())}for(let t of(e.metadata&&(a.metadata=e.metadata),a.morphTargetManagers=[],e.meshes)){let e=t.morphTargetManager;e&&a.morphTargetManagers.push(e.serialize())}for(i=0,a.lights=[];i0){a.animationGroups=[];for(let t=0;t0)for(i=0,a.reflectionProbes=[];it)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){let r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],sceneSerializer_SceneSerializer.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r{0>e.indexOf(t)&&!t.doNotSerialize&&e.push(t)}),t&&e[r].parent&&0>e.indexOf(e[r].parent)&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach(e=>{FinalizeSingleNode(e,r)}),r}};let VideoRecorder=class VideoRecorder{static IsSupported(e){let t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!VideoRecorder.IsSupported(e))throw"Your browser does not support recording so far.";let i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options=Object.assign(Object.assign({},VideoRecorder._DefaultOptions),t);let r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(let e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout(()=>{this.stopRecording()},1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise((e,t)=>{this._resolve=e,this._reject=t})}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),this._reject)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();let e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&tools_Tools.Download(e,this._fileName)}};VideoRecorder._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let ox=null;function CreateScreenshot(e,t,i,r,s="image/png",a=!1,n){let{height:o,width:l}=_GetScreenshotSize(e,t,i);if(!(o&&l)){logger_Logger.Error("Invalid 'size' parameter !");return}ox||(ox=document.createElement("canvas")),ox.width=l,ox.height=o;let h=ox.getContext("2d"),c=e.getRenderWidth()/e.getRenderHeight(),u=l,d=u/c;d>o&&(u=(d=o)*c);let _=Math.max(0,l-u)/2,p=Math.max(0,o-d)/2,f=t.getScene();f.activeCamera!==t?CreateScreenshotUsingRenderTarget(e,t,i,e=>{if(a){let t=new Blob([e]);tools_Tools.DownloadBlob(t),r&&r("")}else r&&r(e)},s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,n):e.onEndFrameObservable.addOnce(()=>{let t=e.getRenderingCanvas();h&&t&&h.drawImage(t,_,p,u,d),ox&&(a?(tools_Tools.EncodeScreenshotCanvasData(ox,void 0,s,void 0,n),r&&r("")):tools_Tools.EncodeScreenshotCanvasData(ox,r,s,void 0,n))})}function CreateScreenshotAsync(e,t,i,r="image/png",s){return new Promise((a,n)=>{CreateScreenshot(e,t,i,e=>{void 0!==e?a(e):n(Error("Data is undefined"))},r,void 0,s)})}function CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",a=1,n=!1,o,l=!1,h=!1,c=!0,u,d){let{height:_,width:p,finalWidth:f,finalHeight:m}=_GetScreenshotSize(e,t,i);if(!(_&&p)){logger_Logger.Error("Invalid 'size' parameter !");return}let g={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(p,_);let v=t.getScene(),x=new renderTargetTexture_RenderTargetTexture("screenShot",{width:p,height:_},v,!1,!1,0,!1,texture_Texture.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,a);x.renderList=v.meshes.slice(),x.samples=a,x.renderSprites=l,x.activeCamera=t,x.forceLayerMaskCheck=c,null==d||d(x);let renderWhenReady=()=>{x.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce(()=>{f===p&&m===_?x.readPixels(void 0,void 0,void 0,!1).then(e=>{dumpTools_DumpTools.DumpData(p,_,e,r,s,o,!0,void 0,u),x.dispose()}):ApplyPostProcess("pass",x.getInternalTexture(),v,void 0,void 0,void 0,f,m).then(t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then(e=>{dumpTools_DumpTools.DumpData(f,m,e,r,s,o,!0,void 0,u),t.dispose()})})}),x.render(!0),v.incrementRenderId(),v.resetCachedMaterial(),e.setSize(g.width,g.height),t.getProjectionMatrix(!0),v.render()):setTimeout(renderWhenReady,16)},renderToTexture=()=>{v.incrementRenderId(),v.resetCachedMaterial(),renderWhenReady()};if(n){let e=new FxaaPostProcess("antialiasing",1,v.activeCamera);x.addPostProcess(e),e.getEffect().isReady()?renderToTexture():e.getEffect().onCompiled=()=>{renderToTexture()}}else renderToTexture()}function CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,a=!1,n,o=!1,l=!1,h=!0,c){return new Promise((u,d)=>{CreateScreenshotUsingRenderTarget(e,t,i,e=>{void 0!==e?u(e):d(Error("Data is undefined"))},r,s,a,n,o,l,h,c)})}function _GetScreenshotSize(e,t,i){let r=0,s=0,a=0,n=0;if("object"==typeof i){let o=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*o,s=i.width*o):i.width&&!i.height?r=Math.round((s=i.width*o)/e.getAspectRatio(t)):i.height&&!i.width?s=Math.round((r=i.height*o)*e.getAspectRatio(t)):r=Math.round((s=Math.round(e.getRenderWidth()*o))/e.getAspectRatio(t)),i.finalWidth&&i.finalHeight?(n=i.finalHeight,a=i.finalWidth):i.finalWidth&&!i.finalHeight?n=Math.round((a=i.finalWidth)/e.getAspectRatio(t)):i.finalHeight&&!i.finalWidth?a=Math.round((n=i.finalHeight)*e.getAspectRatio(t)):(a=s,n=r)}else isNaN(i)||(r=i,s=i,a=i,n=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),a&&(a=Math.floor(a)),n&&(n=Math.floor(n)),{height:0|r,width:0|s,finalWidth:0|a,finalHeight:0|n}}tools_Tools.CreateScreenshot=CreateScreenshot,tools_Tools.CreateScreenshotAsync=CreateScreenshotAsync,tools_Tools.CreateScreenshotUsingRenderTarget=CreateScreenshotUsingRenderTarget,tools_Tools.CreateScreenshotUsingRenderTargetAsync=CreateScreenshotUsingRenderTargetAsync,function(e){e[e.Checkbox=0]="Checkbox",e[e.Slider=1]="Slider",e[e.Vector3=2]="Vector3",e[e.Quaternion=3]="Quaternion",e[e.Color3=4]="Color3",e[e.String=5]="String",e[e.Button=6]="Button",e[e.Options=7]="Options",e[e.Tab=8]="Tab",e[e.FileButton=9]="FileButton",e[e.Vector2=10]="Vector2"}(ii||(ii={}));let DataStorage=class DataStorage{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(t){let e={};return{getItem:t=>{let i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){let i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){let i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){let i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}};DataStorage._Storage=DataStorage._GetStorage(),function(e){let Alphabet=class Alphabet{serialize(){let e={},t=Array(this._characterToIdx.size);return this._characterToIdx.forEach((e,i)=>{t[e]=i}),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){let t=JSON.parse(e),i=new Alphabet(t.characters);return i._insertionCosts=t.insertionCosts,i._deletionCosts=t.deletionCosts,i._substitutionCosts=t.substitutionCosts,i}constructor(e,t=null,i=null,r=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,r=null!=r?r:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=Array(e.length),this._deletionCosts=Array(e.length),this._substitutionCosts=Array(e.length);for(let a=0;aSequence._MAX_SEQUENCE_LENGTH)throw Error("Sequences longer than "+Sequence._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map(e=>this._alphabet.getCharacterIdx(e))}distance(e){return Sequence._Distance(this,e)}static _Distance(e,t){let i=e._alphabet;if(i!==t._alphabet)throw Error("Cannot Levenshtein compare Sequences built from different alphabets.");let r=e._characters,s=t._characters,a=r.length,n=s.length,o=Sequence._CostMatrix;o[0][0]=0;for(let e=0;eArray(Sequence._MAX_SEQUENCE_LENGTH+1)),e.Sequence=Sequence}(ir||(ir={}));let Trajectory=class Trajectory{serialize(){return JSON.stringify(this)}static Deserialize(e){let t=JSON.parse(e),i=new Trajectory(t._segmentLength);return i._points=t._points.map(e=>new math_vector_Vector3(e._x,e._y,e._z)),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{let getT=()=>this._segmentLength/math_vector_Vector3.Distance(this._points[t-1],e);for(let i=getT();i<=1;i=getT()){let r=this._points[t-1].scale(1-i);e.scaleAndAddToRef(i,r),this._points.push(r),++t}}}resampleAtTargetResolution(e){let t=new Trajectory(this.getLength()/e);return this._points.forEach(e=>{t.add(e)}),t}tokenize(e){let t=[],i=new math_vector_Vector3;for(let r=2;r.98)&&(math_vector_Vector3.CrossToRef(Trajectory._ForwardDir,Trajectory._InverseFromVec,Trajectory._UpDir),Trajectory._UpDir.normalize(),math_vector_Matrix.LookAtLHToRef(e,t,Trajectory._UpDir,Trajectory._LookMatrix),i.subtractToRef(t,Trajectory._FromToVec),Trajectory._FromToVec.normalize(),math_vector_Vector3.TransformNormalToRef(Trajectory._FromToVec,Trajectory._LookMatrix,r),!0)}static _TokenizeSegment(e,t){Trajectory._BestMatch=0,Trajectory._Score=math_vector_Vector3.Dot(e,t[0]),Trajectory._BestScore=Trajectory._Score;for(let i=1;iTrajectory._BestScore&&(Trajectory._BestMatch=i,Trajectory._BestScore=Trajectory._Score);return Trajectory._BestMatch}};Trajectory._ForwardDir=new math_vector_Vector3,Trajectory._InverseFromVec=new math_vector_Vector3,Trajectory._UpDir=new math_vector_Vector3,Trajectory._FromToVec=new math_vector_Vector3,Trajectory._LookMatrix=new math_vector_Matrix;let TrajectoryDescriptor=class TrajectoryDescriptor{serialize(){return JSON.stringify(this._sequences.map(e=>e.serialize()))}static Deserialize(e,t){let i=new TrajectoryDescriptor;return i._sequences=JSON.parse(e).map(e=>ir.Sequence.Deserialize(e,t)),i}static CreateFromTrajectory(e,t,i){return TrajectoryDescriptor.CreateFromTokenizationPyramid(TrajectoryDescriptor._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){let i=new TrajectoryDescriptor;return i._sequences=e.map(e=>new ir.Sequence(e,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION){let r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t=0;for(let i=0;ie.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){let i=JSON.parse(e),r=new TrajectoryClass;return r._descriptors=i.descriptors.map(e=>TrajectoryDescriptor.Deserialize(e,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){let e;this._centroidIdx=-1;let t=this._descriptors.map(t=>(e=0,this._descriptors.forEach(i=>{e+=t.distance(i)}),e));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,TrajectoryClass._MIN_AVERAGE_DISTANCE))}};TrajectoryClass._MIN_AVERAGE_DISTANCE=1;let Reflector=class Reflector{constructor(e,t,i){this._scene=e,logger_Logger.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{let t=e.data;if(t.startsWith(Reflector._SERVER_PREFIX)){let e=t.substr(Reflector._SERVER_PREFIX.length);logger_Logger.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),this._handleServerMessage(e);return}logger_Logger.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{logger_Logger.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&sceneSerializer_SceneSerializer.SerializeAsync(this._scene).then(e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)})}_handleClientMessage(){}};Reflector._SERVER_PREFIX="$$";let DynamicFloat32Array=class DynamicFloat32Array{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){let e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}};let ob="timestamp",oT="numPoints",oS=/\r/g;let PerformanceViewerCollector=class PerformanceViewerCollector{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{let e=precisionDate_PrecisionDate.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength,r=0;if(i>0){let e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+PerformanceViewerCollector.NumberOfPointsOffset)+PerformanceViewerCollector.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())}),this.datasetObservable.hasObservers()){let i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new EventState(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var r;return this._strategies.has(e)&&!t?void 0:(this._strategies.has(e)&&t&&(null===(r=this._strategies.get(e))||void 0===r||r.dispose(),this._strategies.delete(e)),this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0,s=t.onAfterRenderObservable.add(()=>{r=i,i=0}),a=this._customEventObservable.add(t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)});return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(a)}}},category:i}),{name:e})}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){let e=t(this._scene);if(this._strategies.has(e.id)){e.dispose();continue}this.datasets.ids.push(e.id),i&&(i=i.replace(RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255;i+=("0"+r.toString(16)).substr(-2)}return i}getCurrentSlice(){let e=precisionDate_PrecisionDate.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasetObservable.hasObservers()&&i.push(t.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){let r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new DynamicFloat32Array(1800),this.datasets.ids.length=0,this.datasets.startingIndices=new DynamicFloat32Array(1800),this._datasetMeta.clear(),this._strategies.forEach(e=>e.dispose()),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){let i=e.replace(oS,"").split("\n").map(e=>e.split(",").filter(e=>e.length>0)).filter(e=>e.length>0),r=PerformanceViewerCollector.NumberOfPointsOffset;if(i.length<2)return!1;let s={ids:[],data:new DynamicFloat32Array(1800),startingIndices:new DynamicFloat32Array(1800)},[a,...n]=i;if(a.length<2||a[0]!==ob||a[r]!==oT)return!1;let o=new Map;for(let e=PerformanceViewerCollector.SliceDataOffset;ee.dispose()),this._strategies.clear(),!t)for(let e of this.datasets.ids){let t=o.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${ob},${oT}`;for(let t=0;t{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}};function CreateObservableScheduler(e){let t=[],i=[],r=[],s=e.add(()=>{let e=t.length;for(let s=0;s{t.push(e),i.push(s),r.push(a)},dispose:()=>{e.remove(s)}}}scene_Scene.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new PerformanceViewerCollector(this)),this._perfCollector},observable_Observable.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){let e=CreateObservableScheduler(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return runCoroutineAsync(e,this._coroutineScheduler)},observable_Observable.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};let oC=`#ifdef GL_ES -precision highp float; -#endif -#define M_PI 3.1415926535897932384626433832795 -varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( -- sin( longitude )*sin( latitude ), -cos( latitude ), -- cos( longitude )*sin( latitude ) -);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;ShaderStore.ShadersStore.equirectangularPanoramaPixelShader=oC;let WebXRHitTestLegacy=class WebXRHitTestLegacy extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this._direction=new math_vector_Vector3(0,0,-1),this._mat=new math_vector_Matrix,this._onSelectEnabled=!1,this._origin=new math_vector_Vector3(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new observable_Observable,this._onHitTestResults=e=>{let t=e.map(e=>{let t=math_vector_Matrix.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}});this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&WebXRHitTestLegacy.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",tools_Tools.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(e=>{let t=r||(e=>!!e.hitMatrix);return e.filter(t)})}static XRHitTestWithSelectEvent(e,t){let i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);let r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;math_vector_Matrix.FromArrayToRef(t.transform.matrix,0,this._mat),math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),math_vector_Vector3.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();let i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}};WebXRHitTestLegacy.Name=webXRFeaturesManager_WebXRFeatureName.HIT_TEST,WebXRHitTestLegacy.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name,(e,t)=>()=>new WebXRHitTestLegacy(e,t),WebXRHitTestLegacy.Version,!1);let oE=0;let WebXRAnchorSystem=class WebXRAnchorSystem extends WebXRAbstractFeature{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new observable_Observable,this.onAnchorRemovedObservable=new observable_Observable,this.onAnchorUpdatedObservable=new observable_Observable,this._tmpVector=new math_vector_Vector3,this._tmpQuaternion=new math_vector_Quaternion,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new math_vector_Vector3,i=new math_vector_Quaternion){this._populateTmpTransformation(t,i);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{let t=await e.xrHitResult.createAnchor(r);return new Promise((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})})}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new math_vector_Quaternion,i=!1){this._populateTmpTransformation(e,t);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){let e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;let t=e.trackedAnchors;if(t){let i=this._trackedAnchors.filter(e=>!t.has(e.xrAnchor)).map(e=>{let t=this._trackedAnchors.indexOf(e);return t}),r=0;i.forEach(e=>{let t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++}),t.forEach(t=>{if(this._lastFrameDetected.has(t)){let i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new math_vector_Quaternion,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){tools_Tools.Warn("Anchor could not be updated")}}else{let i={id:oE++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);let s=this._futureAnchors.filter(e=>e.nativeAnchor===t),a=s[0];a&&(a.resolve(r),a.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then(e=>{t.nativeAnchor=e},e=>{t.resolved=!0,t.reject(e)}),t.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new WebXRAnchorSystem(e,t),WebXRAnchorSystem.Version);let oy=0;let WebXRPlaneDetector=class WebXRPlaneDetector extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new observable_Observable,this.onPlaneRemovedObservable=new observable_Observable,this.onPlaneUpdatedObservable=new observable_Observable,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){let e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;let i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{let i={id:oy++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}}),this._lastFrameDetected=i}}_init(){let internalInit=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){internalInit();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),internalInit()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(e=>{let t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new math_vector_Vector3(e.x,e.y,e.z*t)});let r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new math_vector_Matrix;math_vector_Matrix.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new WebXRPlaneDetector(e,t),WebXRPlaneDetector.Version);let WebXRBackgroundRemover=class WebXRBackgroundRemover extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new observable_Observable}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){let t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper){if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){let i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){let i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{let i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(t=>t.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}};WebXRBackgroundRemover.Name=webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER,WebXRBackgroundRemover.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name,(e,t)=>()=>new WebXRBackgroundRemover(e,t),WebXRBackgroundRemover.Version,!0);let WebXRControllerPhysics=class WebXRControllerPhysics extends WebXRAbstractFeature{_createPhysicsImpostor(e){let t=this._options.physicsProperties.impostorType||physicsImpostor_PhysicsImpostor.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=sphereBuilder_CreateSphere("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new math_vector_Quaternion;let s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);let a=new physicsImpostor_PhysicsImpostor(r,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:a,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||logger_Logger.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce(t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce(()=>{let i=new physicsImpostor_PhysicsImpostor(t.rootMesh,physicsImpostor_PhysicsImpostor.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new math_vector_Quaternion,this._tmpVector=new math_vector_Vector3,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{let t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)})}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._options.enableHeadsetImpostor){let e=this._options.headsetImpostorParams||{impostorType:physicsImpostor_PhysicsImpostor.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=sphereBuilder_CreateSphere("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new math_vector_Quaternion,this._headsetMesh.isVisible=!1,this._headsetImpostor=new physicsImpostor_PhysicsImpostor(this._headsetMesh,e.impostorType,Object.assign({mass:0},e))}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){let t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties=Object.assign(Object.assign({},this._options.physicsProperties),e)}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),null===(t=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===t?void 0:t.linearVelocity){let e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(null===(i=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===i?void 0:i.angularVelocity){let e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(e=>{var t,i;let r=this._controllers[e],s=r.xrController.grip||r.xrController.pointer,a=r.oldPos||r.impostorMesh.position;if(null===(t=r.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){let e=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(a,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);a.copyFrom(s.position),this._debugMode&&console.log(this._tmpVector,"linear");let n=r.oldRotation||r.impostorMesh.rotationQuaternion;if(null===(i=r.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){let e=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!n.equalsWithEpsilon(s.rotationQuaternion)){n.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);let e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{let t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}r.impostor.setAngularVelocity(this._tmpVector)}n.copyFrom(s.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")})}_detachController(e){let t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}};WebXRControllerPhysics.Name=webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS,WebXRControllerPhysics.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name,(e,t)=>()=>new WebXRControllerPhysics(e,t),WebXRControllerPhysics.Version,!0);let WebXRHitTest=class WebXRHitTest extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new math_vector_Matrix,this._tmpPos=new math_vector_Vector3,this._tmpQuat=new math_vector_Quaternion,this._initHitTestSource=e=>{if(!e)return;let t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};if(this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),!i.space){tools_Tools.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(i).then(e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new observable_Observable,this.paused=!1,this.xrNativeFeatureName="hit-test",tools_Tools.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){let e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then(e=>{this._transientXrHitTestSource=e})}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){let t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}if(this._transientXrHitTestSource){let t=e.getHitTestResultsForTransientInput(this._transientXrHitTestSource);t.forEach(e=>{this._processWebXRHitTestResult(e.results,e.inputSource)})}}}_processWebXRHitTestResult(e,t){let i=[];e.forEach(e=>{let r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;let s=r.transform.position,a=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(a.x,a.y,a.z,a.w),math_vector_Matrix.FromFloat32ArrayToRefScaled(r.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());let n={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(n)}),this.onHitTestResultObservable.notifyObservers(i)}};WebXRHitTest.Name=webXRFeaturesManager_WebXRFeatureName.HIT_TEST,WebXRHitTest.Version=2,WebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name,(e,t)=>()=>new WebXRHitTest(e,t),WebXRHitTest.Version,!1);let WebXRFeaturePointSystem=class WebXRFeaturePointSystem extends WebXRAbstractFeature{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new observable_Observable,this.onFeaturePointsUpdatedObservable=new observable_Observable,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;let t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw Error("Received malformed feature point cloud of length: "+t.length);let e=t.length/5,i=[],r=[];for(let s=0;s0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}};WebXRFeaturePointSystem.Name=webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS,WebXRFeaturePointSystem.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name,e=>()=>new WebXRFeaturePointSystem(e),WebXRFeaturePointSystem.Version);let oR=0;let WebXRMeshDetector=class WebXRMeshDetector extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new observable_Observable,this.onMeshRemovedObservable=new observable_Observable,this.onMeshUpdatedObservable=new observable_Observable,this.xrNativeFeatureName="mesh-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach(e=>{this.onMeshRemovedObservable.notifyObservers(e)}),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;let i=null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes;if(i){let t=new Set;this._detectedMeshes.forEach((e,r)=>{i.has(r)||t.add(r)}),t.forEach(e=>{let t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))}),i.forEach(t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{let i={id:oR++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}})}}catch(e){console.log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){if(t.xrMesh=e,t.worldParentNode=this._options.worldParentNode,this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=e.positions,t.normals=e.normals;else{t.positions=new Float32Array(e.positions.length);for(let i=0;i()=>new WebXRMeshDetector(e,t),WebXRMeshDetector.Version,!1),function(e){e[e.NotReceived=0]="NotReceived",e[e.Waiting=1]="Waiting",e[e.Received=2]="Received"}(is||(is={}));let WebXRImageTracking=class WebXRImageTracking extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new observable_Observable,this.onTrackableImageFoundObservable=new observable_Observable,this.onTrackedImageUpdatedObservable=new observable_Observable,this._trackableScoreStatus=is.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach(e=>{e.originalBitmap.close()}),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};let e=this.options.images.map(e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src));try{let t=await Promise.all(e);return this._originalTrackingRequest=t.map((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch(e){return tools_Tools.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===is.Waiting)return;if(this._trackableScoreStatus===is.NotReceived){this._checkScoresAsync();return}let t=e.getImageTrackingResults();for(let i of t){let t=!1,r=i.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);let a=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(a){let e=s.transformationMatrix;math_vector_Matrix.FromArrayToRef(a.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}let n=i.trackingState,o="emulated"===n;s.emulated!==o&&(s.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==is.NotReceived)return;this._trackableScoreStatus=is.Waiting;let e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||0===e.length){this._trackableScoreStatus=is.NotReceived;return}for(let t=0;t0?is.Received:is.NotReceived}};WebXRImageTracking.Name=webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING,WebXRImageTracking.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name,(e,t)=>()=>new WebXRImageTracking(e,t),WebXRImageTracking.Version,!1);let WebXRDomOverlay=class WebXRDomOverlay extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",tools_Tools.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!!super.attach()&&!!this._xrSessionManager.session.domOverlayState&&null!==this._xrSessionManager.session.domOverlayState.type&&(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0)}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return tools_Tools.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){let e=document.querySelector(this.options.element);if(null===e)return tools_Tools.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}};WebXRDomOverlay.Name=webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY,WebXRDomOverlay.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name,(e,t)=>()=>new WebXRDomOverlay(e,t),WebXRDomOverlay.Version,!1);let WebXRControllerMovement=class WebXRControllerMovement extends WebXRAbstractFeature{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){var i,r,s,a,n,o;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new math_vector_Quaternion,this._tmpRotationMatrix=math_vector_Matrix.Identity(),this._tmpTranslationDirection=new math_vector_Vector3,this._tmpMovementTranslation=new math_vector_Vector3,this._tempCacheQuaternion=new math_vector_Quaternion,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let initController=()=>{if(e.motionController)for(let i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(let t of i.allowedComponentTypes){let i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){let t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness||null===r)continue;let s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add(e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add(()=>{r.changes.pressed&&i.buttonChangedhandler(r.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};e.motionController?initController():e.onMotionControllerInitObservable.addOnce(()=>{initController()})}},!t||void 0===t.xrInput){tools_Tools.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=WebXRControllerMovement.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(r=t.movementSpeed)&&void 0!==r?r:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(a=t.rotationEnabled)||void 0===a||a,rotationSpeed:null!==(n=t.rotationSpeed)&&void 0!==n?n:1,rotationThreshold:null!==(o=t.rotationThreshold)&&void 0!==o?o:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){let e=this._xrSessionManager.scene.getEngine().getDeltaTime(),t=.001*e*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=t,math_vector_Quaternion.RotationYawPitchRollToRef(t,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(math_vector_Quaternion.RotationYawPitchRollToRef(3*t,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(math_vector_Matrix.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),math_vector_Vector3.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){let t=this._controllers[e];if(t){for(let e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}};WebXRControllerMovement.Name=webXRFeaturesManager_WebXRFeatureName.MOVEMENT,WebXRControllerMovement.REGISTRATIONS={default:[{allowedComponentTypes:[WebXRControllerComponent.THUMBSTICK_TYPE,WebXRControllerComponent.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[WebXRControllerComponent.THUMBSTICK_TYPE,WebXRControllerComponent.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},WebXRControllerMovement.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name,(e,t)=>()=>new WebXRControllerMovement(e,t),WebXRControllerMovement.Version,!0);let WebXRLightEstimation=class WebXRLightEstimation extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=math_vector_Vector3.Up().negateInPlace(),this._lightColor=math_color_Color3.White(),this._intensity=1,this._sphericalHarmonics=new SphericalHarmonics,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new observable_Observable,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){let e=Date.now();if(e-this._cubeMapPollTime{this._xrLightProbe=e,this.options.disableCubeMapReflection||(!this._reflectionCubeMap&&(this._reflectionCubeMap=new baseTexture_BaseTexture(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))}),!0}detach(){let e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){let e=Date.now();if(e-this._lightEstimationPollTime()=>new WebXRLightEstimation(e,t),WebXRLightEstimation.Version,!1);let WebXREyeTracking=class WebXREyeTracking extends WebXRAbstractFeature{constructor(e){super(e),this.onEyeTrackingStartedObservable=new observable_Observable,this.onEyeTrackingEndedObservable=new observable_Observable,this.onEyeTrackingFrameUpdateObservable=new observable_Observable,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new ray_Ray(math_vector_Vector3.Zero(),math_vector_Vector3.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){let t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z);let e=t.transform.orientation;math_vector_TmpVectors.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?math_vector_Vector3.RightHandedForwardReadOnly.rotateByQuaternionToRef(math_vector_TmpVectors.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,math_vector_TmpVectors.Quaternion[0].z*=-1,math_vector_TmpVectors.Quaternion[0].w*=-1,math_vector_Vector3.LeftHandedForwardReadOnly.rotateByQuaternionToRef(math_vector_TmpVectors.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}};WebXREyeTracking.Name=webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING,WebXREyeTracking.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXREyeTracking.Name,e=>()=>new WebXREyeTracking(e),WebXREyeTracking.Version,!1);let CircleBuffer=class CircleBuffer{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}};let FirstStepDetector=class FirstStepDetector{constructor(){this._samples=new CircleBuffer(20),this._entropy=0,this.onFirstStepDetected=new observable_Observable}update(e,t,i,r){let s,a;this._samples.push(e,t);let n=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=math_vector_Vector2.Distance(n,this._samples.at(1)),this._entropy>this._entropyThreshold)return;for(s=this._samePointCheckStartIdx;so&&(l=t,o=e);if(os*this._squaredProjectionDistanceThreshold)return;let _=math_vector_TmpVectors.Vector3[0];_.set(i,r,0);let p=math_vector_TmpVectors.Vector3[1];p.set(c.x,c.y,0);let f=math_vector_Vector3.Cross(_,p).z>0,m=n.clone(),g=n.clone();h.subtractToRef(n,c),f?(c.scaleAndAddToRef(this._axisToApexShrinkFactor,m),c.scaleAndAddToRef(this._axisToApexExtendFactor,g)):(c.scaleAndAddToRef(this._axisToApexExtendFactor,m),c.scaleAndAddToRef(this._axisToApexShrinkFactor,g)),this.onFirstStepDetected.notifyObservers({leftApex:m,rightApex:g,currentPosition:n,currentStepDirection:f?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),!(this._axisLength<.03))}get _vitalityThreshold(){return .1}get forward(){return this._forward}};let Walker=class Walker{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new FirstStepDetector,this._walker=null,this._movement=new math_vector_Vector2,this._millisecondsSinceLastUpdate=Walker._MillisecondsPerUpdate,this.movementThisFrame=math_vector_Vector3.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(e=>{this._walker||(this._walker=new WalkingTracker(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add(()=>{console.log("Footfall!")}),this._walker.onMovement.add(e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)}))})}update(e,t){if(t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=Walker._MillisecondsPerUpdate){if(this._millisecondsSinceLastUpdate-=Walker._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker){let t=this._walker.update(e.x,e.z);t||(this._walker=null)}this._movement.scaleInPlace(.85)}this.movementThisFrame.set(this._movement.x,0,this._movement.y)}};let WebXRWalkingLocomotion=class WebXRWalkingLocomotion extends WebXRAbstractFeature{static get Name(){return webXRFeaturesManager_WebXRFeatureName.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new math_vector_Vector3,this._forward=new math_vector_Vector3,this._position=new math_vector_Vector3,this._movement=new math_vector_Vector3,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&logger_Logger.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!!(this.isCompatible&&super.attach())&&(this._walker=new Walker(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){let t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;let i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||math_vector_Vector3.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}};WebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name,(e,t)=>()=>new WebXRWalkingLocomotion(e,t),WebXRWalkingLocomotion.Version,!1);let WebXRCompositionLayerWrapper=class WebXRCompositionLayerWrapper extends WebXRLayerWrapper{constructor(e,t,i,r,s,a){super(e,t,i,r,a),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=a}};let WebXRCompositionLayerRenderTargetTextureProvider=class WebXRCompositionLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,r,s,a;let n=this._lastSubImages.get(t),o="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(r=e.colorTextureHeight)&&void 0!==r?r:e.textureHeight;if(!this._renderTargetTextures[o]||(null==n?void 0:n.textureWidth)!==l||(null==n?void 0:n.textureHeight)!==h){let t;let i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,r=null!==(a=e.depthStencilTextureHeight)&&void 0!==a?a:h;(l===i||h===r)&&(t=e.depthStencilTexture),this._renderTargetTextures[o]=this._createRenderTargetTexture(l,h,null,e.colorTexture,t,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:l,framebufferHeight:h}}return this._lastSubImages.set(t,e),this._renderTargetTextures[o]}_getSubImageForEye(e){let t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){let t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,r;let s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,a=null!==(r=t.colorTextureWidth)&&void 0!==r?r:t.textureHeight,n=t.viewport;e.x=n.x/s,e.y=n.y/a,e.width=n.width/s,e.height=n.height/a}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}};let WebXRProjectionLayerWrapper=class WebXRProjectionLayerWrapper extends WebXRCompositionLayerWrapper{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,e=>new WebXRProjectionLayerRenderTargetTextureProvider(e,i,this)),this.layer=e}};let WebXRProjectionLayerRenderTargetTextureProvider=class WebXRProjectionLayerRenderTargetTextureProvider extends WebXRCompositionLayerRenderTargetTextureProvider{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){let t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}};let oP={},oA={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};let WebXRLayers=class WebXRLayers extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;let t=Object.assign({},oA),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return!!super.detach()&&(this._existingLayers.length=0,!0)}createXRWebGLLayer(e=oP){let t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new WebXRWebGLLayerWrapper(t)}createProjectionLayer(e=oA,t=!1){if(t&&"texture-array"!==e.textureType)throw Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");let i=this._xrWebGLBinding.createProjectionLayer(e);return new WebXRProjectionLayerWrapper(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;let t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map(e=>e.layer),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}};WebXRLayers.Name=webXRFeaturesManager_WebXRFeatureName.LAYERS,WebXRLayers.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRLayers.Name,(e,t)=>()=>new WebXRLayers(e,t),WebXRLayers.Version,!1);let WebXRDepthSensing=class WebXRDepthSensing extends WebXRAbstractFeature{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){var e,t;if(!this._cachedWebGLTexture)return null;let i=this._xrSessionManager.scene.getEngine(),r=new internalTexture_InternalTexture(i,$.Unknown);return r.isCube=!1,r.invertY=!1,r._useSRGBBuffer=!1,r.format="ushort"===this.depthDataFormat?2:5,r.generateMipMaps=!1,r.type="ushort"===this.depthDataFormat?5:1,r.samplingMode=7,r.width=null!==(e=this.width)&&void 0!==e?e:0,r.height=null!==(t=this.height)&&void 0!==t?t:0,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new WebGLHardwareTexture(this._cachedWebGLTexture,i._gl),r}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new observable_Observable,this.xrNativeFeatureName="depth-sensing",tools_Tools.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){if(!super.attach(e))return!1;let t=null==this._xrSessionManager.session.depthDataFormat||null==this._xrSessionManager.session.depthUsage;return!t&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;null===(e=this._cachedDepthImageTexture)||void 0===e||e.dispose()}_onXRFrame(e){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(let t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:tools_Tools.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{data:s,width:a,height:n,rawValueToMeters:o,getDepthInMeters:l}=r;switch(this._width=a,this._height=n,this._rawValueToMeters=o,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=rawTexture_RawTexture.CreateRTexture(null,a,n,this._xrSessionManager.scene,!1,!0,texture_Texture.NEAREST_SAMPLINGMODE,engine_Engine.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(e=>e*o));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(e=>e*o))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{texture:s,width:a,height:n}=r;this._width=a,this._height=n,this._cachedWebGLTexture=s;let o=this._xrSessionManager.scene,l=o.getEngine(),h=l.wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=rawTexture_RawTexture.CreateRTexture(null,a,n,o,!1,!0,texture_Texture.NEAREST_SAMPLINGMODE,"ushort"===i?engine_Engine.TEXTURETYPE_UNSIGNED_BYTE:engine_Engine.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=h}getXRSessionInitExtension(){let e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise(i=>{if(e&&t){let e=this.options.usagePreference.map(e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),t=this.options.dataFormatPreference.map(e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:e,dataFormatPreference:t}})}else i({})})}};WebXRDepthSensing.Name=webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING,WebXRDepthSensing.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRDepthSensing.Name,(e,t)=>()=>new WebXRDepthSensing(e,t),WebXRDepthSensing.Version,!1);let oM=`precision highp float; -#define CUSTOM_FRAGMENT_BEGIN -varying vec4 clipPos;varying vec4 previousClipPos; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; -#define CUSTOM_FRAGMENT_MAIN_END -}`;ShaderStore.ShadersStore.velocityPixelShader=oM;let oI=`#define CUSTOM_VERTEX_BEGIN -#define VELOCITY -attribute vec3 position; -#include -uniform mat4 viewProjection;uniform mat4 previousViewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; -#endif -varying vec4 clipPos;varying vec4 previousClipPos; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} -#elif -clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;ShaderStore.ShadersStore.velocityVertexShader=oI;let XRSpaceWarpRenderTarget=class XRSpaceWarpRenderTarget extends renderTargetTexture_RenderTargetTexture{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[math_vector_Matrix.Identity(),math_vector_Matrix.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new shaderMaterial_ShaderMaterial("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)}),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;let i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach(e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(e=>{e[0].material=e[1]})}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}};let WebXRSpaceWarpRenderTargetTextureProvider=class WebXRSpaceWarpRenderTargetTextureProvider{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){let t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw Error('For Space Warp, the base layer type should "XRProjectionLayer".');let i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw Error("Engine is disposed");let a=new XRSpaceWarpRenderTarget(r,s,this._scene,{width:e,height:t}),n=a.renderTarget;return i&&(n._framebuffer=i),n._colorTextureArray=r,n._depthStencilTextureArray=s,a.disableRescaling(),a.renderListPredicate=()=>!0,a}_getRenderTargetForSubImage(e,t){let i=this._lastSubImages.get(t),r=this._renderTargetTextures.get(t.eye),s=e.motionVectorTextureWidth,a=e.motionVectorTextureHeight;return r&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==a||(r=this._createRenderTargetTexture(s,a,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:a}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){let i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){let t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){let t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}};let WebXRSpaceWarp=class WebXRSpaceWarp extends WebXRAbstractFeature{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[webXRFeaturesManager_WebXRFeatureName.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;let i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}};WebXRSpaceWarp.Name=webXRFeaturesManager_WebXRFeatureName.SPACE_WARP,WebXRSpaceWarp.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name,e=>()=>new WebXRSpaceWarp(e),WebXRSpaceWarp.Version,!1);let WebXRGenericHandController=class WebXRGenericHandController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,oD[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}};WebXRMotionControllerManager.RegisterController("generic-hand-select-grasp",(e,t)=>new WebXRGenericHandController(t,e.gamepad,e.handedness));let oD={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};let WebXRMicrosoftMixedRealityController=class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,oO["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";e="left"===this.handedness?WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME:WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME;let t=WebXRMicrosoftMixedRealityController.MODEL_BASE_URL+"default/";return{filename:e,path:t}}_getModelLoadingConstraints(){let e=sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb");return e||logger_Logger.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){let i=this._mapping.buttons[e],r=i.rootNodeName;if(!r){logger_Logger.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);return}let s=this._getChildByName(this.rootMesh,r);if(!s){logger_Logger.Warn("Missing button mesh with name: "+r);return}if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){let t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add(e=>{this._lerpTransform(i,e.value)},void 0,!0)}else logger_Logger.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(e=>{let t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach(i=>{if(!this.rootMesh)return;let r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);if(!s){logger_Logger.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add(e=>{let t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)},void 0,!0):logger_Logger.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){let t;this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew WebXRMicrosoftMixedRealityController(t,e.gamepad,e.handedness));let oO={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};let WebXROculusTouchMotionController=class WebXROculusTouchMotionController extends WebXRAbstractMotionController{constructor(e,t,i,r=!1,s=!1){super(e,oB[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";e="left"===this.handedness?WebXROculusTouchMotionController.MODEL_LEFT_FILENAME:WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME;let t=this._isQuest()?WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL:WebXROculusTouchMotionController.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){let t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach(e=>{let r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add(r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-(.2*r.value),this._modelRootNode.getChildren()[3].position.y=-(.005*r.value),this._modelRootNode.getChildren()[3].position.z=-(.005*r.value));return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=math_vector_Quaternion.FromEulerAngles(0,Math.PI,0)),e.forEach(e=>{e.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}};WebXROculusTouchMotionController.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",WebXROculusTouchMotionController.MODEL_LEFT_FILENAME="left.babylon",WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME="right.babylon",WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",WebXRMotionControllerManager.RegisterController("oculus-touch",(e,t)=>new WebXROculusTouchMotionController(t,e.gamepad,e.handedness)),WebXRMotionControllerManager.RegisterController("oculus-touch-legacy",(e,t)=>new WebXROculusTouchMotionController(t,e.gamepad,e.handedness,!0));let oB={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};let WebXRHTCViveMotionController=class WebXRHTCViveMotionController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,oN[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){let e=WebXRHTCViveMotionController.MODEL_FILENAME,t=WebXRHTCViveMotionController.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add(t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-(.15*t.value);return;case"xr-standard-touchpad":case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new mesh_Mesh(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=math_vector_Quaternion.FromEulerAngles(0,Math.PI,0))}_updateModel(){}};WebXRHTCViveMotionController.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",WebXRHTCViveMotionController.MODEL_FILENAME="wand.babylon",WebXRMotionControllerManager.RegisterController("htc-vive",(e,t)=>new WebXRHTCViveMotionController(t,e.gamepad,e.handedness));let oN={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};let NativeXRFrame=class NativeXRFrame{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>{var e;return null!==(e=this._nativeImpl._imageTrackingResults)&&void 0!==e?e:[]}}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;let i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];let r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw Error("This function is not available in Babylon Native")}};RegisterNativeTypeAsync("NativeXRFrame",NativeXRFrame),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(ia||(ia={}));let FlowGraphConnection=class FlowGraphConnection{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=guid_RandomGUID(),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 Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName(),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){let i=tools_Tools.Instantiate(e.className),r=new i(e.name,e._connectionType,t);return r.deserialize(e),r}};let RichType=class RichType{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new RichType(e.typeName,e.defaultValue)}};let oF=new RichType("any",void 0),ow=new RichType("string",""),oL=new RichType("number",0),oV=new RichType("boolean",!1),oU=new RichType("Vector2",math_vector_Vector2.Zero()),ok=new RichType("Vector3",math_vector_Vector3.Zero()),oG=new RichType("Vector4",math_vector_Vector4.Zero()),oz=new RichType("Matrix",math_vector_Matrix.Identity()),oW=new RichType("Color3",math_color_Color3.Black()),oH=new RichType("Color4",new math_color_Color4(0,0,0,0)),oX=new RichType("Quaternion",math_vector_Quaternion.Identity());function getRichTypeFromValue(e){switch(typeof e){case"string":return ow;case"number":return oL;case"boolean":return oV;case"object":if(e instanceof math_vector_Vector2)return oU;if(e instanceof math_vector_Vector3)return ok;if(e instanceof math_vector_Vector4)return oG;if(e instanceof math_color_Color3)return oW;else if(e instanceof math_color_Color4)return oH;else if(e instanceof math_vector_Quaternion)return oX;else return oF;default:return oF}}let FlowGraphDataConnection=class FlowGraphDataConnection extends FlowGraphConnection{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return this.connectionType===ia.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===ia.Output?(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){let i=FlowGraphConnection.Parse(e,t);return i.richType=RichType.Parse(e.richType),i}};h.FGDataConnection=FlowGraphDataConnection;let FlowGraphBlock=class FlowGraphBlock{constructor(e){this.config=e,this.uniqueId=guid_RandomGUID(),this.configure()}configure(){var e,t;this.name=null!==(t=null===(e=this.config)||void 0===e?void 0:e.name)&&void 0!==t?t:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}_registerDataInput(e,t){let i=new FlowGraphDataConnection(e,ia.Input,this,t);return this.dataInputs.push(i),i}_registerDataOutput(e,t){let i=new FlowGraphDataConnection(e,ia.Output,this,t);return this.dataOutputs.push(i),i}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.config=this.config,e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName(),this.dataInputs)){let i={};t.serialize(i),e.dataInputs.push(i)}for(let t of this.dataOutputs){let i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e){let t=tools_Tools.Instantiate(e.className),i=new t(e.config);i.uniqueId=e.uniqueId;for(let t=0;t{t(r,i,e._userVariables)}),e._connectionValues={},this._connectionValues.forEach((i,r)=>{t(r,i,e._connectionValues)})}getClassName(){return"FGContext"}static Parse(e={},t,i=defaultValueParseFunction){let r=t.createContext();for(let t in r.uniqueId=e.uniqueId,e._userVariables){let s=i(t,e._userVariables,r._configuration.scene);r._userVariables.set(t,s)}for(let t in e._connectionValues){let s=i(t,e._connectionValues,r._configuration.scene);r._connectionValues.set(t,s)}return r}};__decorate([serialize()],FlowGraphContext.prototype,"uniqueId",void 0);let FlowGraphVariableDefinitions=class FlowGraphVariableDefinitions{constructor(){this._definitions=new Map}defineVariable(e,t){this._definitions.set(e,t)}generateContext(e){let t=new FlowGraphContext(e);return this._definitions.forEach((e,i)=>{t.setVariable(i,e)}),t}serialize(e){this._definitions.forEach((t,i)=>{e[i]=t})}deserialize(e){for(let t in this._definitions.clear(),e)this._definitions.set(t,e[t])}};!function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(io||(io={}));let FlowGraph=class FlowGraph{constructor(e){this.variableDefinitions=new FlowGraphVariableDefinitions,this._eventBlocks=[],this._executionContexts=[],this.state=io.Stopped,this._scene=e.scene,this._eventCoordinator=e.eventCoordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){let e=this.variableDefinitions.generateContext({scene:this._scene,eventCoordinator:this._eventCoordinator});return this._executionContexts.push(e),e}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==io.Started)for(let e of(this.state=io.Started,0===this._executionContexts.length&&this.createContext(),this._executionContexts))for(let t of this._eventBlocks)t._startPendingTasks(e)}dispose(){if(this.state!==io.Stopped){for(let e of(this.state=io.Stopped,this._executionContexts))e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}visitAllBlocks(e){let t=[],i=new Set;for(let e of this._eventBlocks)t.push(e),i.add(e.uniqueId);for(;t.length>0;){let r=t.pop();for(let s of(e(r),r.dataInputs))for(let e of s._connectedPoint)i.has(e._ownerBlock.uniqueId)||(t.push(e._ownerBlock),i.add(e._ownerBlock.uniqueId));if(r instanceof FlowGraphExecutionBlock)for(let e of r.signalOutputs)for(let r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId))}}serialize(e={},t){for(let i of(e.variableDefinitions={},this.variableDefinitions.serialize(e.variableDefinitions),e.allBlocks=[],this.visitAllBlocks(t=>{let i={};t.serialize(i),e.allBlocks.push(i)}),e.executionContexts=[],this._executionContexts)){let r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(let i of e)for(let e of i.dataOutputs)if(e.uniqueId===t)return e;throw Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(let i of e)if(i instanceof FlowGraphExecutionBlock){for(let e of i.signalInputs)if(e.uniqueId===t)return e}throw Error("Could not find signal in connection with unique id "+t)}static Parse(e,t,i){let r=t.createGraph();r.variableDefinitions.deserialize(e.variableDefinitions);let s=[];for(let t of e.allBlocks){let e=FlowGraphBlock.Parse(t);s.push(e),e instanceof FlowGraphEventBlock&&r.addEventBlock(e)}for(let e of s){for(let t of e.dataInputs)for(let e of t.connectedPointIds){let i=FlowGraph.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof FlowGraphExecutionBlock)for(let t of e.signalOutputs)for(let e of t.connectedPointIds){let i=FlowGraph.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(let t of e.executionContexts)FlowGraphContext.Parse(t,r,i);return r}};let FlowGraphEventCoordinator=class FlowGraphEventCoordinator{constructor(){this._customEventsMap=new Map}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new observable_Observable,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){let i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}};let FlowGraphCoordinator=class FlowGraphCoordinator{constructor(e){var t;this._config=e,this._flowGraphs=[],this.eventCoordinator=new FlowGraphEventCoordinator,this._config.scene.onDisposeObservable.add(()=>{this.dispose()});let i=null!==(t=FlowGraphCoordinator.SceneCoordinators.get(this._config.scene))&&void 0!==t?t:[];i.push(this)}createGraph(){let e=new FlowGraph({scene:this._config.scene,eventCoordinator:this.eventCoordinator});return this._flowGraphs.push(e),e}removeGraph(e){let t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){var e;this._flowGraphs.forEach(e=>e.dispose()),this._flowGraphs.length=0;let t=null!==(e=FlowGraphCoordinator.SceneCoordinators.get(this._config.scene))&&void 0!==e?e:[],i=t.indexOf(this);-1!==i&&t.splice(i,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{let r={};i.serialize(r,t),e._flowGraphs.push(r)})}static Parse(e,t,i){var r;let s=new FlowGraphCoordinator({scene:t});return null===(r=e._flowGraphs)||void 0===r||r.forEach(e=>{FlowGraph.Parse(e,s,i)}),s}};FlowGraphCoordinator.SceneCoordinators=new Map;let FlowGraphWithOnDoneExecutionBlock=class FlowGraphWithOnDoneExecutionBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onDone=this._registerSignalOutput("onDone")}};let FlowGraphLogBlock=class FlowGraphLogBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.message=this._registerDataInput("message",oF)}_execute(e){let t=this.message.getValue(e);console.log(t),this.onDone._activateSignal(e)}getClassName(){return"FGLogBlock"}};h.FGLogBlock=FlowGraphLogBlock;let FlowGraphSetVariableBlock=class FlowGraphSetVariableBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.variableName=this._registerDataInput("variableName",ow),this.input=this._registerDataInput("input",oF)}_execute(e){let t=this.variableName.getValue(e),i=this.input.getValue(e);e.setVariable(t,i),this.onDone._activateSignal(e)}getClassName(){return"FGSetVariableBlock"}};h.FGSetVariableBlock=FlowGraphSetVariableBlock;let FlowGraphSetPropertyBlock=class FlowGraphSetPropertyBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.target=this._registerDataInput("target",oF),this.property=this._registerDataInput("property",ow),this.value=this._registerDataInput("value",oF)}_setProperty(e,t,i){let r=t.split("."),s=e;for(let e=0;er)this.timeRemaining.setValue(0,e),this.onDone._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s);else{let t=r-(s-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}};h.FGThrottleBlock=FlowGraphThrottleBlock;let FlowGraphTimerBlock=class FlowGraphTimerBlock extends FlowGraphAsyncExecutionBlock{constructor(e){super(e),this.timeout=this._registerDataInput("timeout",oL),this.onTimerDone=this._registerSignalOutput("onTimerDone")}_preparePendingTasks(e){let t=this.timeout.getValue(e);if(void 0!==t&&t>=0){let i=e._getExecutionVariable(this,"runningTimers")||[],r=e.configuration.scene,s=new AdvancedTimer({timeout:t,contextObservable:r.onBeforeRenderObservable,onEnded:()=>this._onEnded(s,e)});s.start(),i.push(s),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onEnded(e,t){let i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):tools_Tools.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.onTimerDone._activateSignal(t)}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"runningTimers")||[];for(let e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return"FGTimerBlock"}};h.FGTimerBlock=FlowGraphTimerBlock;let FlowGraphMultiGateBlock=class FlowGraphMultiGateBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this._registerDataOutput("currentIndex",oL)}configure(){super.configure(),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)a=0;else if(a>=this.config.numberOutputFlows&&!this.config.loop)return;if(0===(s=s.filter(e=>e!==a)).length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(e=>e)){this.onDone._activateSignal(e);for(let e=0;e=i&&(this.onDone._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}};h.FGDebounceBlock=FlowGraphDebounceBlock;let FlowGraphFlipFlopBlock=class FlowGraphFlipFlopBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this._registerDataOutput("isOn",oV)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}};h.FGFlipFlopBlock=FlowGraphFlipFlopBlock;let FlowGraphPlayAnimationBlock=class FlowGraphPlayAnimationBlock extends FlowGraphAsyncExecutionBlock{constructor(e){super(e),this.target=this._registerDataInput("target",oF),this.animation=this._registerDataInput("animation",oF),this.speed=this._registerDataInput("speed",oL),this.loop=this._registerDataInput("loop",oV),this.from=this._registerDataInput("from",oL),this.to=this._registerDataInput("to",oL),this.onAnimationEnd=this._registerSignalOutput("onAnimationEnd"),this.runningAnimatable=this._registerDataOutput("runningAnimatable",oF)}_preparePendingTasks(e){var t;let i=this.target.getValue(e),r=this.animation.getValue(e);if(!i||!r)throw Error("Cannot play animation without target or animation");let s=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[],a=this.runningAnimatable.getValue(e);if(a&&a.paused)a.restart();else{let t=e.configuration.scene,a=t.beginDirectAnimation(i,[r],this.from.getValue(e),this.to.getValue(e),this.loop.getValue(e),this.speed.getValue(e),()=>this._onAnimationEnd(a,e));this.runningAnimatable.setValue(a,e),s.push(a)}e._setExecutionVariable(this,"runningAnimatables",s)}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onAnimationEnd(e,t){var i;let r=null!==(i=t._getExecutionVariable(this,"runningAnimatables"))&&void 0!==i?i:[],s=r.indexOf(e);-1!==s&&r.splice(s,1),t._removePendingBlock(this),this.onAnimationEnd._activateSignal(t)}_cancelPendingTasks(e){var t;let i=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[];for(let e of i)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return"FGPlayAnimationBlock"}};h.FGPlayAnimationBlock=FlowGraphPlayAnimationBlock;let FlowGraphStopAnimationBlock=class FlowGraphStopAnimationBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.animationToStop=this._registerDataInput("animationToStop",oF)}_execute(e){let t=this.animationToStop.getValue(e);t.stop(),this.onDone._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}};h.FGStopAnimationBlock=FlowGraphStopAnimationBlock;let FlowGraphPauseAnimationBlock=class FlowGraphPauseAnimationBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.animationToPause=this._registerDataInput("animationToPause",oF)}_execute(e){let t=this.animationToPause.getValue(e);t.pause(),this.onDone._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}};h.FGPauseAnimationBlock=FlowGraphPauseAnimationBlock;let FlowGraphPlayAudioBlock=class FlowGraphPlayAudioBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.audio=this._registerDataInput("audio",oF)}_execute(e,t){let i=this.audio.getValue(e);i instanceof Sound&&i.play(),this.onDone._activateSignal(e)}getClassName(){return"FGPlayAudioBlock"}};h.FGPlayAudioBlock=FlowGraphPlayAudioBlock;let FlowGraphStopAudioBlock=class FlowGraphStopAudioBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.audio=this._registerDataInput("audio",oF)}_execute(e,t){let i=this.audio.getValue(e);i instanceof Sound&&i.stop()}getClassName(){return"FGStopAudioBlock"}};h.FGStopAudioBlock=FlowGraphStopAudioBlock;let FlowGraphConditionalDataBlock=class FlowGraphConditionalDataBlock extends FlowGraphBlock{constructor(e){super(e),this.condition=this._registerDataInput("condition",oV),this.trueValue=this._registerDataInput("trueValue",oF),this.falseValue=this._registerDataInput("falseValue",oF),this.output=this._registerDataOutput("output",oF)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}};h.FGConditionalDataBlock=FlowGraphConditionalDataBlock;let FlowGraphGetVariableBlock=class FlowGraphGetVariableBlock extends FlowGraphBlock{constructor(e){super(e),this.variableName=this._registerDataInput("variableName",ow),this.output=this._registerDataOutput("output",oF)}_updateOutputs(e){let t=this.variableName.getValue(e);e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return"FGGetVariableBlock"}};h.FGGetVariableBlock=FlowGraphGetVariableBlock;let FlowGraphCoordinateTransformBlock=class FlowGraphCoordinateTransformBlock extends FlowGraphBlock{constructor(e){super(e),this.sourceSystem=this._registerDataInput("sourceSystem",oF),this.destinationSystem=this._registerDataInput("destinationSystem",oF),this.inputCoordinates=this._registerDataInput("inputCoordinates",ok),this.outputCoordinates=this._registerDataOutput("outputCoordinates",ok)}_updateOutputs(e){let t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),a=i.getWorldMatrix(),n=math_vector_TmpVectors.Matrix[0].copyFrom(a);n.invert();let o=math_vector_TmpVectors.Matrix[1];n.multiplyToRef(s,o);let l=this.outputCoordinates.getValue(e);math_vector_Vector3.TransformCoordinatesToRef(r,o,l)}getClassName(){return"FGCoordinateTransformBlock"}};h.FGCoordinateTransformBlock=FlowGraphCoordinateTransformBlock;let FlowGraphConstantBlock=class FlowGraphConstantBlock extends FlowGraphBlock{constructor(e){super(e),this.config=e,this.output=this._registerDataOutput("output",getRichTypeFromValue(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}};h.FGConstantBlock=FlowGraphConstantBlock;let oY="cachedOperationValue",oj="cachedExecutionId";let FlowGraphCachedOperationBlock=class FlowGraphCachedOperationBlock extends FlowGraphBlock{constructor(e,t){super(t),this.output=this._registerDataOutput("output",e)}_updateOutputs(e){let t=e._getExecutionVariable(this,oj),i=e._getExecutionVariable(this,oY);if(void 0!==i&&t===e.executionId)this.output.setValue(i,e);else{let t=this._doOperation(e);e._setExecutionVariable(this,oY,t),e._setExecutionVariable(this,oj,e.executionId),this.output.setValue(t,e)}}};let FlowGraphBinaryOperationBlock=class FlowGraphBinaryOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r,s,a){super(i,a),this._operation=r,this._className=s,this.leftInput=this._registerDataInput("leftInput",e),this.rightInput=this._registerDataInput("rightInput",t)}_doOperation(e){return this._operation(this.leftInput.getValue(e),this.rightInput.getValue(e))}getClassName(){return this._className}};let FlowGraphUnaryOperationBlock=class FlowGraphUnaryOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.input=this._registerDataInput("input",e)}_doOperation(e){return this._operation(this.input.getValue(e))}getClassName(){return this._className}};let oK="FGBitwise",oq="AndBlock",o$="OrBlock",oQ="XorBlock",oZ="NotBlock",oJ="LeftShiftBlock",o0="RightShiftBlock",o1="CountLeadingZerosBlock",o2="CountTrailingZerosBlock";let FlowGraphBitwiseAndBlock=class FlowGraphBitwiseAndBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e&t,`${oK}${oq}`,e)}};h[`${oK}${oq}`]=FlowGraphBitwiseAndBlock;let FlowGraphBitwiseOrBlock=class FlowGraphBitwiseOrBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e|t,`${oK}${o$}`,e)}};h[`${oK}${o$}`]=FlowGraphBitwiseOrBlock;let FlowGraphBitwiseXorBlock=class FlowGraphBitwiseXorBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e^t,`${oK}${oQ}`,e)}};h[`${oK}${oQ}`]=FlowGraphBitwiseXorBlock;let FlowGraphBitwiseNotBlock=class FlowGraphBitwiseNotBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>~e,`${oK}${oZ}`,e)}};h[`${oK}${oZ}`]=FlowGraphBitwiseNotBlock;let FlowGraphBitwiseLeftShiftBlock=class FlowGraphBitwiseLeftShiftBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e<e>>t,`${oK}${o0}`,e)}};h[`${oK}${o0}`]=FlowGraphBitwiseRightShiftBlock;let FlowGraphCountLeadingZerosBlock=class FlowGraphCountLeadingZerosBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.clz32(e),`${oK}${o1}`,e)}};h[`${oK}${o1}`]=FlowGraphCountLeadingZerosBlock;let FlowGraphCountTrailingZerosBlock=class FlowGraphCountTrailingZerosBlock extends FlowGraphUnaryOperationBlock{_ctrz(e){return 0==(e>>>=0)?32:31-Math.clz32(e&=-e)}constructor(e){super(oL,oL,e=>this._ctrz(e),`${oK}${o2}`,e)}};h[`${oK}${o2}`]=FlowGraphCountTrailingZerosBlock;let o3="FGLogic",o4="AndBlock",o5="OrBlock",o6="NotBlock";let FlowGraphLogicAndBlock=class FlowGraphLogicAndBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oV,oV,oV,(e,t)=>e&&t,`${o3}${o4}`,e)}};h[`${o3}${o4}`]=FlowGraphLogicAndBlock;let FlowGraphLogicOrBlock=class FlowGraphLogicOrBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oV,oV,oV,(e,t)=>e||t,`${o3}${o5}`,e)}};h[`${o3}${o5}`]=FlowGraphLogicOrBlock;let FlowGraphLogicNotBlock=class FlowGraphLogicNotBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oV,oV,e=>!e,`${o3}${o6}`,e)}};h[`${o3}${o6}`]=FlowGraphLogicNotBlock;let FlowGraphConstantOperationBlock=class FlowGraphConstantOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}};let o8="FGAddNumberBlock";let FlowGraphAddNumberBlock=class FlowGraphAddNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e+t,o8,e)}};h[o8]=FlowGraphAddNumberBlock;let o7="FGSubtractNumberBlock";let FlowGraphSubtractNumberBlock=class FlowGraphSubtractNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e-t,o7,e)}};h[o7]=FlowGraphSubtractNumberBlock;let o9="FGMultiplyNumberBlock";let FlowGraphMultiplyNumberBlock=class FlowGraphMultiplyNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e*t,o9,e)}};h[o9]=FlowGraphMultiplyNumberBlock;let le="FGDivideNumberBlock";let FlowGraphDivideNumberBlock=class FlowGraphDivideNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e/t,le,e)}};h[le]=FlowGraphDivideNumberBlock;let lt="FGModNumberBlock";let FlowGraphModNumberBlock=class FlowGraphModNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e%t,lt,e)}};h[lt]=FlowGraphModNumberBlock;let li="FGPowNumberBlock";let FlowGraphPowNumberBlock=class FlowGraphPowNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.pow(e,t),li,e)}};h[li]=FlowGraphPowNumberBlock;let lr="FGIsNaNNumberBlock";let FlowGraphIsNaNNumberBlock=class FlowGraphIsNaNNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oV,e=>isNaN(e),lr,e)}};h[lr]=FlowGraphIsNaNNumberBlock;let ls="FGIsInfinityNumberBlock";let FlowGraphIsInfinityNumberBlock=class FlowGraphIsInfinityNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oV,e=>!isFinite(e),ls,e)}};h[ls]=FlowGraphIsInfinityNumberBlock;let la="FGSqrtNumberBlock";let FlowGraphSqrtNumberBlock=class FlowGraphSqrtNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.sqrt(e),la,e)}};h[la]=FlowGraphSqrtNumberBlock;let ln="FGAbsNumberBlock";let FlowGraphAbsNumberBlock=class FlowGraphAbsNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.abs(e),ln,e)}};h[ln]=FlowGraphAbsNumberBlock;let lo="FGNegateNumberBlock";let FlowGraphNegateNumberBlock=class FlowGraphNegateNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>-e,lo,e)}};h[lo]=FlowGraphNegateNumberBlock;let ll="FGFloorNumberBlock";let FlowGraphFloorNumberBlock=class FlowGraphFloorNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.floor(e),ll,e)}};h[ll]=FlowGraphFloorNumberBlock;let lh="FGCeilNumberBlock";let FlowGraphCeilNumberBlock=class FlowGraphCeilNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.ceil(e),lh,e)}};h[lh]=FlowGraphCeilNumberBlock;let lc="FGRoundNumberBlock";let FlowGraphRoundNumberBlock=class FlowGraphRoundNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.round(e/Math.pow(10,t))/Math.pow(10,t),lc,e)}};h[lc]=FlowGraphRoundNumberBlock;let lu="FGTruncNumberBlock";let FlowGraphTruncNumberBlock=class FlowGraphTruncNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.trunc(e),lu,e)}};h[lu]=FlowGraphTruncNumberBlock;let ld="FGExpNumberBlock";let FlowGraphExpNumberBlock=class FlowGraphExpNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.exp(e),ld,e)}};h[ld]=FlowGraphExpNumberBlock;let l_="FGLog10NumberBlock";let FlowGraphLog10NumberBlock=class FlowGraphLog10NumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.log10(e),l_,e)}};h[l_]=FlowGraphLog10NumberBlock;let lp="FGLogNumberBlock";let FlowGraphLogNumberBlock=class FlowGraphLogNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.log(e),lp,e)}};h[lp]=FlowGraphLogNumberBlock;let lf="FGLnNumberBlock";let FlowGraphLnNumberBlock=class FlowGraphLnNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.log(e)/Math.LN2,lf,e)}};h[lf]=FlowGraphLnNumberBlock;let lm="FGSineNumberBlock";let FlowGraphSinNumberBlock=class FlowGraphSinNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.sin(e),lm,e)}};h[lm]=FlowGraphSinNumberBlock;let lg="FGCosNumberBlock";let FlowGraphCosNumberBlock=class FlowGraphCosNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.cos(e),lg,e)}};h[lg]=FlowGraphCosNumberBlock;let lv="FGTanNumberBlock";let FlowGraphTanNumberBlock=class FlowGraphTanNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.tan(e),lv,e)}};h[lv]=FlowGraphTanNumberBlock;let lx="FGASineNumberBlock";let FlowGraphASinNumberBlock=class FlowGraphASinNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.asin(e),lx,e)}};h[lx]=FlowGraphASinNumberBlock;let lb="FGACosNumberBlock";let FlowGraphACosNumberBlock=class FlowGraphACosNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.acos(e),lb,e)}};h[lb]=FlowGraphACosNumberBlock;let lT="FGATanNumberBlock";let FlowGraphATanNumberBlock=class FlowGraphATanNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(oL,oL,e=>Math.atan(e),lT,e)}};h[lT]=FlowGraphATanNumberBlock;let lS="FGENumberBlock";let FlowGraphENumberBlock=class FlowGraphENumberBlock extends FlowGraphConstantOperationBlock{constructor(e){super(oL,()=>Math.E,lS,e)}};h[lS]=FlowGraphENumberBlock;let lC="FGPiNumberBlock";let FlowGraphPiNumberBlock=class FlowGraphPiNumberBlock extends FlowGraphConstantOperationBlock{constructor(e){super(oL,()=>Math.PI,lC,e)}};h[lC]=FlowGraphPiNumberBlock;let lE="FGATan2NumberBlock";let FlowGraphATan2NumberBlock=class FlowGraphATan2NumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.atan2(e,t),lE,e)}};h[lE]=FlowGraphATan2NumberBlock;let ly="FGRandomNumberBlock";let FlowGraphRandomNumberBlock=class FlowGraphRandomNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>e+Math.random()*(t-e),ly,e)}};h[ly]=FlowGraphRandomNumberBlock;let lR="FGMinNumberBlock";let FlowGraphMinNumberBlock=class FlowGraphMinNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.min(e,t),lR,e)}};h[lR]=FlowGraphMinNumberBlock;let lP="FGMaxNumberBlock";let FlowGraphMaxNumberBlock=class FlowGraphMaxNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oL,(e,t)=>Math.max(e,t),lP,e)}};h[lP]=FlowGraphMaxNumberBlock;let lA="FGEqualsNumberBlock";let FlowGraphEqualsNumberBlock=class FlowGraphEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>e===t,lA,e)}};h[lA]=FlowGraphEqualsNumberBlock;let lM="FGGreaterThanNumberBlock";let FlowGraphGreaterThanNumberBlock=class FlowGraphGreaterThanNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>e>t,lM,e)}};h[lM]=FlowGraphGreaterThanNumberBlock;let lI="FGGreaterThanOrEqualsNumberBlock";let FlowGraphGreaterThanOrEqualsNumberBlock=class FlowGraphGreaterThanOrEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>e>=t,lI,e)}};h[lI]=FlowGraphGreaterThanOrEqualsNumberBlock;let lD="FGLessThanNumberBlock";let FlowGraphLessThanNumberBlock=class FlowGraphLessThanNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oL,oL,oV,(e,t)=>ee<=t,lO,e)}};h[lO]=FlowGraphLessThanOrEqualsNumberBlock;let lB="FGMixNumberBlock";let FlowGraphMixNumberBlock=class FlowGraphMixNumberBlock extends FlowGraphBlock{constructor(e){super(e),this.leftInput=this._registerDataInput("leftInput",oL),this.rightInput=this._registerDataInput("rightInput",oL),this.alphaInput=this._registerDataInput("alphaInput",oL),this.resultOutput=this._registerDataOutput("resultOutput",oL)}_updateOutputs(e){let t=this.leftInput.getValue(e),i=this.rightInput.getValue(e),r=this.alphaInput.getValue(e);this.resultOutput.setValue(t+(i-t)*r,e)}getClassName(){return lB}};h[lB]=FlowGraphMixNumberBlock;let lN="FGAddVector2Block";let FlowGraphAddVector2Block=class FlowGraphAddVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oU,oU,(e,t)=>e.add(t),lN,e)}};h[lN]=FlowGraphAddVector2Block;let lF="FGSubtractVector2Block";let FlowGraphSubtractVector2Block=class FlowGraphSubtractVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oU,oU,(e,t)=>e.subtract(t),lF,e)}};h[lF]=FlowGraphSubtractVector2Block;let lw="FGMultiplyVector2Block";let FlowGraphMultiplyVector2Block=class FlowGraphMultiplyVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oU,oU,(e,t)=>e.multiply(t),lw,e)}};h[lw]=FlowGraphMultiplyVector2Block;let lL="FGDivideVector2Block";let FlowGraphDivideVector2Block=class FlowGraphDivideVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oU,oU,(e,t)=>e.divide(t),lL,e)}};h[lL]=FlowGraphDivideVector2Block;let lV="FGScaleVector2Block";let FlowGraphScaleVector2Block=class FlowGraphScaleVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oU,oL,oU,(e,t)=>e.scale(t),lV,e)}};h[lV]=FlowGraphScaleVector2Block;let lU="FGLengthVector2Block";let FlowGraphLengthVector2Block=class FlowGraphLengthVector2Block extends FlowGraphUnaryOperationBlock{constructor(e){super(oU,oL,e=>e.length(),lU,e)}};h[lU]=FlowGraphLengthVector2Block;let lk="FGNormalizeVector2Block";let FlowGraphNormalizeVector2Block=class FlowGraphNormalizeVector2Block extends FlowGraphUnaryOperationBlock{constructor(e){super(oU,oU,e=>{let t=e.clone();return t.normalize(),t},lk,e)}};h[lk]=FlowGraphNormalizeVector2Block;let FlowGraphCreateVector2Block=class FlowGraphCreateVector2Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=math_vector_Vector2.Zero(),this.x=this._registerDataInput("x",oL),this.y=this._registerDataInput("y",oL),this.vector=this._registerDataOutput("vector",oU)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this.vector.setValue(this._cachedVector,e)}};h.FGCreateVector2Block=FlowGraphCreateVector2Block;let FlowGraphSplitVector2Block=class FlowGraphSplitVector2Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",oU),this.x=this._registerDataOutput("x",oL),this.y=this._registerDataOutput("y",oL)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e)}};h.FGSplitVector2Block=FlowGraphSplitVector2Block;let FlowGraphRotate2dVector2Block=class FlowGraphRotate2dVector2Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=math_vector_Vector2.Zero(),this.input=this._registerDataInput("input",oU),this.angle=this._registerDataInput("angle",oL),this.output=this._registerDataOutput("output",oU)}_updateOutputs(e){let t=this.input.getValue(e),i=this.angle.getValue(e);this._cachedVector.x=t.x*Math.cos(i)-t.y*Math.sin(i),this._cachedVector.y=t.x*Math.sin(i)+t.y*Math.cos(i),this.output.setValue(this._cachedVector,e)}};h.FGRotate2dVector2Block=FlowGraphRotate2dVector2Block;let lG="FGAddVector3Block";let FlowGraphAddVector3Block=class FlowGraphAddVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>e.add(t),lG,e)}};h[lG]=FlowGraphAddVector3Block;let lz="FGSubtractVector3Block";let FlowGraphSubtractVector3Block=class FlowGraphSubtractVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>e.subtract(t),lz,e)}};h[lz]=FlowGraphSubtractVector3Block;let lW="FGMultiplyVector3Block";let FlowGraphMultiplyVector3Block=class FlowGraphMultiplyVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>e.multiply(t),lW,e)}};h[lW]=FlowGraphMultiplyVector3Block;let lH="FGDivideVector3Block";let FlowGraphDivideVector3Block=class FlowGraphDivideVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>e.divide(t),lH,e)}};h[lH]=FlowGraphDivideVector3Block;let lX="FGScaleVector3Block";let FlowGraphScaleVector3Block=class FlowGraphScaleVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,oL,ok,(e,t)=>e.scale(t),lX,e)}};h[lX]=FlowGraphScaleVector3Block;let lY="FGLengthVector3Block";let FlowGraphLengthVector3Block=class FlowGraphLengthVector3Block extends FlowGraphUnaryOperationBlock{constructor(e){super(ok,oL,e=>e.length(),lY,e)}};h[lY]=FlowGraphLengthVector3Block;let lj="FGNormalizeVector3Block";let FlowGraphNormalizeVector3Block=class FlowGraphNormalizeVector3Block extends FlowGraphUnaryOperationBlock{constructor(e){super(ok,ok,e=>e.normalizeToNew(),lj,e)}};h[lj]=FlowGraphNormalizeVector3Block;let lK="FGDotVector3Block";let FlowGraphDotVector3Block=class FlowGraphDotVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,oL,(e,t)=>math_vector_Vector3.Dot(e,t),lK,e)}};h[lK]=FlowGraphDotVector3Block;let lq="FGCrossVector3Block";let FlowGraphCrossVector3Block=class FlowGraphCrossVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ok,ok,ok,(e,t)=>math_vector_Vector3.Cross(e,t),lq,e)}};h[lq]=FlowGraphCrossVector3Block;let l$="FGCreateVector3Block";let FlowGraphCreateVector3Block=class FlowGraphCreateVector3Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=math_vector_Vector3.Zero(),this.x=this._registerDataInput("x",oL),this.y=this._registerDataInput("y",oL),this.z=this._registerDataInput("y",oL),this.vector=this._registerDataOutput("vector",ok)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this._cachedVector.z=this.z.getValue(e),this.vector.setValue(this._cachedVector,e)}getClassName(){return l$}};h[l$]=FlowGraphCreateVector3Block;let lQ="FGSplitVector3Block";let FlowGraphSplitVector3Block=class FlowGraphSplitVector3Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",ok),this.x=this._registerDataOutput("x",oL),this.y=this._registerDataOutput("y",oL),this.z=this._registerDataOutput("z",oL)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e),this.z.setValue(t.z,e)}getClassName(){return lQ}};h[lQ]=FlowGraphSplitVector3Block;let lZ="FGRotateVector3Block";let FlowGraphRotate3dVector3Block=class FlowGraphRotate3dVector3Block extends FlowGraphBlock{constructor(e){super(e),this._cachedQuaternion=new math_vector_Quaternion,this.input=this._registerDataInput("input",ok),this.angle=this._registerDataInput("angle",oL),this.output=this._registerDataOutput("output",ok)}_updateOutputs(e){let t=math_vector_Quaternion.RotationAxisToRef(this.axis.getValue(e),this.angle.getValue(e),this._cachedQuaternion),i=this.input.getValue(e),r=this.output.getValue(e);i.applyRotationQuaternionToRef(t,r)}getClassName(){return lZ}};h[lZ]=FlowGraphRotate3dVector3Block;let lJ="FGTransformVector3Block";let FlowGraphTransformVector3Block=class FlowGraphTransformVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,ok,ok,(e,t)=>math_vector_Vector3.TransformCoordinatesToRef(t,e,this._cachedResult),lJ,e),this._cachedResult=math_vector_Vector3.Zero()}};h[lJ]=FlowGraphTransformVector3Block;let l0="FGAddVector4Block";let FlowGraphAddVector4Block=class FlowGraphAddVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oG,oG,(e,t)=>e.add(t),l0,e)}};h[l0]=FlowGraphAddVector4Block;let l1="FGSubtractVector4Block";let FlowGraphSubtractVector4Block=class FlowGraphSubtractVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oG,oG,(e,t)=>e.subtract(t),l1,e)}};h[l1]=FlowGraphSubtractVector4Block;let l2="FGMultiplyVector4Block";let FlowGraphMultiplyVector4Block=class FlowGraphMultiplyVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oG,oG,(e,t)=>e.multiply(t),l2,e)}};h[l2]=FlowGraphMultiplyVector4Block;let l3="FGDivideVector4Block";let FlowGraphDivideVector4Block=class FlowGraphDivideVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oG,oG,(e,t)=>e.divide(t),l3,e)}};h[l3]=FlowGraphDivideVector4Block;let l4="FGScaleVector4Block";let FlowGraphScaleVector4Block=class FlowGraphScaleVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(oG,oL,oG,(e,t)=>e.scale(t),l4,e)}};h[l4]=FlowGraphScaleVector4Block;let l5="FGLengthVector4Block";let FlowGraphLengthVector4Block=class FlowGraphLengthVector4Block extends FlowGraphUnaryOperationBlock{constructor(e){super(oG,oL,e=>e.length(),l5,e)}};h[l5]=FlowGraphLengthVector4Block;let l6="FGNormalizeVector4Block";let FlowGraphNormalizeVector4Block=class FlowGraphNormalizeVector4Block extends FlowGraphUnaryOperationBlock{constructor(e){super(oG,oG,e=>{let t=e.clone();return t.normalize(),t},l6,e)}getClassName(){return l6}};h[l6]=FlowGraphNormalizeVector4Block;let l8="FGCreateVector4Block";let FlowGraphCreateVector4Block=class FlowGraphCreateVector4Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=math_vector_Vector4.Zero(),this.x=this._registerDataInput("x",oL),this.y=this._registerDataInput("y",oL),this.z=this._registerDataInput("y",oL),this.w=this._registerDataInput("w",oL),this.vector=this._registerDataOutput("vector",oG)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this._cachedVector.z=this.z.getValue(e),this._cachedVector.w=this.w.getValue(e),this.vector.setValue(this._cachedVector,e)}getClassName(){return l8}};h[l8]=FlowGraphCreateVector4Block;let l7="FGSplitVector4Block";let FlowGraphSplitVector4Block=class FlowGraphSplitVector4Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",oG),this.x=this._registerDataOutput("x",oL),this.y=this._registerDataOutput("y",oL),this.z=this._registerDataOutput("z",oL),this.w=this._registerDataOutput("w",oL)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e),this.z.setValue(t.z,e),this.w.setValue(t.w,e)}getClassName(){return l7}};h[l7]=FlowGraphSplitVector4Block;let l9="FGAddMatrixBlock";let FlowGraphAddMatrixBlock=class FlowGraphAddMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oz,oz,(e,t)=>e.addToRef(t,this._cachedMatrix),l9,e),this._cachedMatrix=math_vector_Matrix.Zero()}};h[l9]=FlowGraphAddMatrixBlock;let he="FGAddMatrixAndNumberBlock";let FlowGraphAddMatrixAndNumberBlock=class FlowGraphAddMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oL,oz,(e,t)=>{for(let i=0;ie.addToRef(t.scaleToRef(-1,math_vector_TmpVectors.Matrix[0]),this._cachedMatrix),ht,e),this._cachedMatrix=math_vector_Matrix.Zero()}};h[ht]=FlowGraphSubtractMatrixBlock;let hi="FGSubtractMatrixAndNumberBlock";let FlowGraphSubtractMatrixAndNumberBlock=class FlowGraphSubtractMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oL,oz,(e,t)=>{for(let i=0;ie.multiplyToRef(t,this._cachedMatrix),hr,e),this._cachedMatrix=math_vector_Matrix.Zero()}};h[hr]=FlowGraphMultiplyMatrixBlock;let hs="FGDivideMatrixBlock";let FlowGraphDivideMatrixBlock=class FlowGraphDivideMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oz,oz,(e,t)=>e.multiplyToRef(t.invertToRef(math_vector_TmpVectors.Matrix[0]),this._cachedResultMatrix),hs,e),this._cachedResultMatrix=math_vector_Matrix.Zero()}};h[hs]=FlowGraphDivideMatrixBlock;let ha="FGDivideMatrixAndNumberBlock";let FlowGraphDivideMatrixAndNumberBlock=class FlowGraphDivideMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oz,oL,oz,(e,t)=>{for(let i=0;ie.scaleToRef(t,this._cachedMatrix),hn,e),this._cachedMatrix=math_vector_Matrix.Zero()}};h[hn]=FlowGraphScaleMatrixBlock;let ho="FGClampMatrixBlock";let FlowGraphClampMatrixBlock=class FlowGraphClampMatrixBlock extends FlowGraphBlock{constructor(e){super(e),this._cachedArray=new Float32Array(16),this._cachedMatrix=math_vector_Matrix.Identity(),this.input=this._registerDataInput("input",oz),this.min=this._registerDataInput("min",oL),this.max=this._registerDataInput("max",oL),this.output=this._registerDataOutput("output",oz)}_updateOutputs(e){let t=this.input.getValue(e),i=this.min.getValue(e),r=this.max.getValue(e);for(let e=0;emath_vector_Matrix.FromQuaternionToRef(e,this._cachedMatrix),hc,e),this._cachedMatrix=new math_vector_Matrix}};h[hc]=FlowGraphQuaternionToRotationMatrixBlock;let hu="FGGetTransformationMatrixBlock";let FlowGraphGetTransformationMatrixBlock=class FlowGraphGetTransformationMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(oF,oF,oz,(e,t)=>{let i=e.getWorldMatrix(),r=t.getWorldMatrix(),s=r.invertToRef(math_vector_TmpVectors.Matrix[0]),a=s.multiplyToRef(i,this._cachedResult);return a},hu,e),this._cachedResult=math_vector_Matrix.Zero()}};h[hu]=FlowGraphGetTransformationMatrixBlock;let FlowGraphMeshPickEventBlock=class FlowGraphMeshPickEventBlock extends FlowGraphEventBlock{constructor(e){super(e),this.config=e}configure(){super.configure(),this._meshVariableName=this.config.meshVariableName}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){let i=e.getVariable(this._meshVariableName);t=i.getScene().onPointerObservable.add(t=>{var r;t.type===pointerEvents_PointerEventTypes.POINTERPICK&&(null===(r=t.pickInfo)||void 0===r?void 0:r.pickedMesh)===i&&this._execute(e)});let r=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){let t=e.getVariable(this._meshVariableName),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return"FGMeshPickEventBlock"}};h.FGMeshPickEventBlock=FlowGraphMeshPickEventBlock;let FlowGraphSceneReadyEventBlock=class FlowGraphSceneReadyEventBlock extends FlowGraphEventBlock{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){let t=e.configuration.scene,i=t.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneReadyObserver"),i=e.configuration.scene;i.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return"FGSceneReadyEventBlock"}};h.FGSceneReadyEventBlock=FlowGraphSceneReadyEventBlock;let FlowGraphReceiveCustomEventBlock=class FlowGraphReceiveCustomEventBlock extends FlowGraphEventBlock{constructor(e){super(e),this.config=e,this.eventData=this._registerDataOutput("eventData",oF)}_preparePendingTasks(e){let t=e.configuration.eventCoordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=t.add(t=>{this.eventData.setValue(t,e),this._execute(e)})}_cancelPendingTasks(e){let t=e.configuration.eventCoordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):tools_Tools.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`)}getClassName(){return"FGReceiveCustomEventBlock"}};h.FGReceiveCustomEventBlock=FlowGraphReceiveCustomEventBlock;let FlowGraphSceneTickEventBlock=class FlowGraphSceneTickEventBlock extends FlowGraphEventBlock{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){let t=e.configuration.scene,i=t.onBeforeRenderObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneBeforeRender"),i=e.configuration.scene;i.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return"FGSceneTickEventBlock"}};h.FGSceneTickEventBlock=FlowGraphSceneTickEventBlock}}; \ No newline at end of file diff --git a/.next/server/middleware-build-manifest.js b/.next/server/middleware-build-manifest.js index 9d01363..d05a5b3 100644 --- a/.next/server/middleware-build-manifest.js +++ b/.next/server/middleware-build-manifest.js @@ -1 +1 @@ -self.__BUILD_MANIFEST={polyfillFiles:["static/chunks/polyfills-c67a75d1b6f99dc8.js"],devFiles:[],ampDevFiles:[],lowPriorityFiles:["static/P9X42g8nWZ62i2biioMqg/_buildManifest.js","static/P9X42g8nWZ62i2biioMqg/_ssgManifest.js"],rootMainFiles:["static/chunks/webpack-c42a79c5d8b7c910.js","static/chunks/fd9d1056-ba10bf844a47945b.js","static/chunks/472-51fd3a56159f1e5b.js","static/chunks/main-app-cf3eb22ffef632f7.js"],pages:{"/_app":["static/chunks/webpack-c42a79c5d8b7c910.js","static/chunks/framework-8883d1e9be70c3da.js","static/chunks/main-07bf56c05aa7cd6e.js","static/chunks/pages/_app-1534f180665c857f.js"],"/_error":["static/chunks/webpack-c42a79c5d8b7c910.js","static/chunks/framework-8883d1e9be70c3da.js","static/chunks/main-07bf56c05aa7cd6e.js","static/chunks/pages/_error-b646007f40c4f0a8.js"]},ampFirstPages:[]}; \ No newline at end of file +self.__BUILD_MANIFEST={polyfillFiles:["static/chunks/polyfills-c67a75d1b6f99dc8.js"],devFiles:[],ampDevFiles:[],lowPriorityFiles:["static/xSz9x0FW88Rb7utFdR6Fp/_buildManifest.js","static/xSz9x0FW88Rb7utFdR6Fp/_ssgManifest.js"],rootMainFiles:["static/chunks/webpack-d8e064491704869d.js","static/chunks/fd9d1056-519edff8920177a7.js","static/chunks/938-d733aaafb07bca99.js","static/chunks/main-app-76ef2d05c58d6354.js"],pages:{"/_app":["static/chunks/webpack-d8e064491704869d.js","static/chunks/framework-8883d1e9be70c3da.js","static/chunks/main-556b0a2270f92b03.js","static/chunks/pages/_app-98cb51ec6f9f135f.js"],"/_error":["static/chunks/webpack-d8e064491704869d.js","static/chunks/framework-8883d1e9be70c3da.js","static/chunks/main-556b0a2270f92b03.js","static/chunks/pages/_error-e87e5963ec1b8011.js"]},ampFirstPages:[]}; \ No newline at end of file diff --git a/.next/server/pages/404.html b/.next/server/pages/404.html index de3baee..f051e9e 100644 --- a/.next/server/pages/404.html +++ b/.next/server/pages/404.html @@ -1 +1 @@ -404: This page could not be found.sukadia.dev

404

This page could not be found.

\ No newline at end of file +404: This page could not be found.sukadia.dev

404

This page could not be found.

\ No newline at end of file diff --git a/.next/server/pages/500.html b/.next/server/pages/500.html index fe03c36..ebde08c 100644 --- a/.next/server/pages/500.html +++ b/.next/server/pages/500.html @@ -1 +1 @@ -500: Internal Server Error

500

Internal Server Error.

\ No newline at end of file +500: Internal Server Error

500

Internal Server Error.

\ No newline at end of file diff --git a/.next/server/pages/_app.js b/.next/server/pages/_app.js index fe4e34d..b7619ae 100644 --- a/.next/server/pages/_app.js +++ b/.next/server/pages/_app.js @@ -1 +1 @@ -"use strict";(()=>{var e={};e.id=888,e.ids=[888],e.modules={6689:e=>{e.exports=require("react")}};var r=require("../webpack-runtime.js");r.C(e);var __webpack_exec__=e=>r(r.s=e),_=r.X(0,[310,840],()=>__webpack_exec__(2840));module.exports=_})(); \ No newline at end of file +"use strict";(()=>{var e={};e.id=888,e.ids=[888],e.modules={4096:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return u}});let n=r(167)._(r(6689)),o=r(4316);async function i(e){let{Component:t,ctx:r}=e;return{pageProps:await (0,o.loadGetInitialProps)(t,r)}}class u extends n.default.Component{render(){let{Component:e,pageProps:t}=this.props;return n.default.createElement(e,t)}}u.origGetInitialProps=i,u.getInitialProps=i,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4316:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{WEB_VITALS:function(){return r},execOnce:function(){return n},isAbsoluteUrl:function(){return i},getLocationOrigin:function(){return u},getURL:function(){return s},getDisplayName:function(){return a},isResSent:function(){return c},normalizeRepeatedSlashes:function(){return l},loadGetInitialProps:function(){return f},SP:function(){return d},ST:function(){return p},DecodeError:function(){return g},NormalizeError:function(){return m},PageNotFoundError:function(){return P},MissingStaticPage:function(){return y},MiddlewareNotFoundError:function(){return E},stringifyError:function(){return _}});let r=["CLS","FCP","FID","INP","LCP","TTFB"];function n(e){let t,r=!1;return function(){for(var n=arguments.length,o=Array(n),i=0;io.test(e);function u(){let{protocol:e,hostname:t,port:r}=window.location;return e+"//"+t+(r?":"+r:"")}function s(){let{href:e}=window.location,t=u();return e.substring(t.length)}function a(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function c(e){return e.finished||e.headersSent}function l(e){let t=e.split("?");return t[0].replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function f(e,t){let r=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await f(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(r&&c(r))return n;if(!n)throw Error('"'+a(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.');return n}let d="undefined"!=typeof performance,p=d&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);class g extends Error{}class m extends Error{}class P extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}}class y extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}}class E extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}}function _(e){return JSON.stringify({message:e.message,stack:e.stack})}},6689:e=>{e.exports=require("react")},167:(e,t)=>{t._=t._interop_require_default=function(e){return e&&e.__esModule?e:{default:e}}}};var t=require("../webpack-runtime.js");t.C(e);var r=t(t.s=4096);module.exports=r})(); \ No newline at end of file diff --git a/.next/server/pages/_app.js.nft.json b/.next/server/pages/_app.js.nft.json index 2859415..7b13a40 100644 --- a/.next/server/pages/_app.js.nft.json +++ b/.next/server/pages/_app.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../node_modules/next/dist/pages/_app.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/next/dist/pages/_app.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../package.json","../../package.json","../chunks/329.js","../chunks/337.js","../chunks/638.js","../chunks/969.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file diff --git a/.next/server/pages/_document.js b/.next/server/pages/_document.js index 35a176d..7d256e3 100644 --- a/.next/server/pages/_document.js +++ b/.next/server/pages/_document.js @@ -1 +1 @@ -"use strict";(()=>{var e={};e.id=660,e.ids=[660,888],e.modules={2785:e=>{e.exports=require("next/dist/compiled/next-server/pages.runtime.prod.js")},6689:e=>{e.exports=require("react")},1017:e=>{e.exports=require("path")}};var r=require("../webpack-runtime.js");r.C(e);var __webpack_exec__=e=>r(r.s=e),s=r.X(0,[310,676],()=>__webpack_exec__(8676));module.exports=s})(); \ No newline at end of file +"use strict";(()=>{var e={};e.id=660,e.ids=[660],e.modules={2785:e=>{e.exports=require("next/dist/compiled/next-server/pages.runtime.prod.js")},6689:e=>{e.exports=require("react")},1017:e=>{e.exports=require("path")}};var r=require("../webpack-runtime.js");r.C(e);var s=e=>r(r.s=e),t=r.X(0,[329],()=>s(2329));module.exports=t})(); \ No newline at end of file diff --git a/.next/server/pages/_document.js.nft.json b/.next/server/pages/_document.js.nft.json index 096bf32..af272fe 100644 --- a/.next/server/pages/_document.js.nft.json +++ b/.next/server/pages/_document.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../node_modules/client-only/index.js","../../../node_modules/client-only/package.json","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/jsonwebtoken/index.js","../../../node_modules/next/dist/compiled/jsonwebtoken/package.json","../../../node_modules/next/dist/compiled/lru-cache/index.js","../../../node_modules/next/dist/compiled/lru-cache/package.json","../../../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../../../node_modules/next/dist/compiled/node-html-parser/index.js","../../../node_modules/next/dist/compiled/node-html-parser/package.json","../../../node_modules/next/dist/lib/semver-noop.js","../../../node_modules/next/dist/pages/_document.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../../../node_modules/react-dom/package.json","../../../node_modules/react-dom/server.browser.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../node_modules/styled-jsx/dist/index/index.js","../../../node_modules/styled-jsx/index.js","../../../node_modules/styled-jsx/package.json","../../../package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/client-only/index.js","../../../node_modules/client-only/package.json","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/jsonwebtoken/index.js","../../../node_modules/next/dist/compiled/jsonwebtoken/package.json","../../../node_modules/next/dist/compiled/lru-cache/index.js","../../../node_modules/next/dist/compiled/lru-cache/package.json","../../../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../../../node_modules/next/dist/compiled/node-html-parser/index.js","../../../node_modules/next/dist/compiled/node-html-parser/package.json","../../../node_modules/next/dist/lib/semver-noop.js","../../../node_modules/next/dist/pages/_document.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../../../node_modules/react-dom/package.json","../../../node_modules/react-dom/server.browser.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../node_modules/styled-jsx/dist/index/index.js","../../../node_modules/styled-jsx/index.js","../../../node_modules/styled-jsx/package.json","../../../package.json","../../package.json","../chunks/329.js","../chunks/337.js","../chunks/638.js","../chunks/969.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file diff --git a/.next/server/pages/_error.js b/.next/server/pages/_error.js index 54b6e4e..efae585 100644 --- a/.next/server/pages/_error.js +++ b/.next/server/pages/_error.js @@ -1 +1 @@ -"use strict";(()=>{var e={};e.id=820,e.ids=[820,888,660],e.modules={6051:(e,t,r)=>{r.r(t),r.d(t,{config:()=>d,default:()=>c,getServerSideProps:()=>S,getStaticPaths:()=>g,getStaticProps:()=>_,reportWebVitals:()=>P,routeModule:()=>f,unstable_getServerProps:()=>x,unstable_getServerSideProps:()=>h,unstable_getStaticParams:()=>v,unstable_getStaticPaths:()=>m,unstable_getStaticProps:()=>b});var a=r(7093),s=r(5244),i=r(1323),l=r(8676),o=r.n(l),n=r(2840),p=r.n(n),u=r(2534);let c=(0,i.l)(u,"default"),_=(0,i.l)(u,"getStaticProps"),g=(0,i.l)(u,"getStaticPaths"),S=(0,i.l)(u,"getServerSideProps"),d=(0,i.l)(u,"config"),P=(0,i.l)(u,"reportWebVitals"),b=(0,i.l)(u,"unstable_getStaticProps"),m=(0,i.l)(u,"unstable_getStaticPaths"),v=(0,i.l)(u,"unstable_getStaticParams"),x=(0,i.l)(u,"unstable_getServerProps"),h=(0,i.l)(u,"unstable_getServerSideProps"),f=new a.PagesRouteModule({definition:{kind:s.x.PAGES,page:"/_error",pathname:"/_error",bundlePath:"",filename:""},components:{App:p(),Document:o()},userland:u})},2785:e=>{e.exports=require("next/dist/compiled/next-server/pages.runtime.prod.js")},6689:e=>{e.exports=require("react")},1017:e=>{e.exports=require("path")}};var t=require("../webpack-runtime.js");t.C(e);var __webpack_exec__=e=>t(t.s=e),r=t.X(0,[310,676,840,2],()=>__webpack_exec__(6051));module.exports=r})(); \ No newline at end of file +"use strict";(()=>{var e={};e.id=820,e.ids=[820,660],e.modules={1323:(e,t)=>{Object.defineProperty(t,"l",{enumerable:!0,get:function(){return function e(t,r){return r in t?t[r]:"then"in t&&"function"==typeof t.then?t.then(t=>e(t,r)):"function"==typeof t&&"default"===r?t:void 0}}})},6051:(e,t,r)=>{r.r(t),r.d(t,{config:()=>m,default:()=>f,getServerSideProps:()=>g,getStaticPaths:()=>p,getStaticProps:()=>c,reportWebVitals:()=>h,routeModule:()=>S,unstable_getServerProps:()=>_,unstable_getServerSideProps:()=>v,unstable_getStaticParams:()=>P,unstable_getStaticPaths:()=>b,unstable_getStaticProps:()=>y});var n=r(7093),a=r(5244),o=r(1323),l=r(2329),u=r.n(l),i=r(4096),d=r.n(i),s=r(4788);let f=(0,o.l)(s,"default"),c=(0,o.l)(s,"getStaticProps"),p=(0,o.l)(s,"getStaticPaths"),g=(0,o.l)(s,"getServerSideProps"),m=(0,o.l)(s,"config"),h=(0,o.l)(s,"reportWebVitals"),y=(0,o.l)(s,"unstable_getStaticProps"),b=(0,o.l)(s,"unstable_getStaticPaths"),P=(0,o.l)(s,"unstable_getStaticParams"),_=(0,o.l)(s,"unstable_getServerProps"),v=(0,o.l)(s,"unstable_getServerSideProps"),S=new n.PagesRouteModule({definition:{kind:a.x.PAGES,page:"/_error",pathname:"/_error",bundlePath:"",filename:""},components:{App:d(),Document:u()},userland:s})},4096:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return l}});let n=r(167)._(r(6689)),a=r(4316);async function o(e){let{Component:t,ctx:r}=e;return{pageProps:await (0,a.loadGetInitialProps)(t,r)}}class l extends n.default.Component{render(){let{Component:e,pageProps:t}=this.props;return n.default.createElement(e,t)}}l.origGetInitialProps=o,l.getInitialProps=o,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4788:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return d}});let n=r(167),a=n._(r(6689)),o=n._(r(5156)),l={400:"Bad Request",404:"This page could not be found",405:"Method Not Allowed",500:"Internal Server Error"};function u(e){let{res:t,err:r}=e;return{statusCode:t&&t.statusCode?t.statusCode:r?r.statusCode:404}}let i={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{lineHeight:"48px"},h1:{display:"inline-block",margin:"0 20px 0 0",paddingRight:23,fontSize:24,fontWeight:500,verticalAlign:"top"},h2:{fontSize:14,fontWeight:400,lineHeight:"28px"},wrap:{display:"inline-block"}};class d extends a.default.Component{render(){let{statusCode:e,withDarkMode:t=!0}=this.props,r=this.props.title||l[e]||"An unexpected error has occurred";return a.default.createElement("div",{style:i.error},a.default.createElement(o.default,null,a.default.createElement("title",null,e?e+": "+r:"Application error: a client-side exception has occurred")),a.default.createElement("div",{style:i.desc},a.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}"+(t?"@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}":"")}}),e?a.default.createElement("h1",{className:"next-error-h1",style:i.h1},e):null,a.default.createElement("div",{style:i.wrap},a.default.createElement("h2",{style:i.h2},this.props.title||e?r:a.default.createElement(a.default.Fragment,null,"Application error: a client-side exception has occurred (see the browser console for more information)"),"."))))}}d.displayName="ErrorPage",d.getInitialProps=u,d.origGetInitialProps=u,("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6793:(e,t)=>{function r(e){let{ampFirst:t=!1,hybrid:r=!1,hasQuery:n=!1}=void 0===e?{}:e;return t||r&&n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return r}})},5156:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{defaultHead:function(){return d},default:function(){return p}});let n=r(167),a=r(8760)._(r(6689)),o=n._(r(1537)),l=r(8039),u=r(1988),i=r(6793);function d(e){void 0===e&&(e=!1);let t=[a.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(a.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function s(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===a.default.Fragment?e.concat(a.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}r(5709);let f=["name","httpEquiv","charSet","itemProp"];function c(e,t){let{inAmpMode:r}=t;return e.reduce(s,[]).reverse().concat(d(r).reverse()).filter(function(){let e=new Set,t=new Set,r=new Set,n={};return a=>{let o=!0,l=!1;if(a.key&&"number"!=typeof a.key&&a.key.indexOf("$")>0){l=!0;let t=a.key.slice(a.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(a.type){case"title":case"base":t.has(a.type)?o=!1:t.add(a.type);break;case"meta":for(let e=0,t=f.length;e{let n=e.key||t;if(!r&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,a.default.cloneElement(e,t)}return a.default.cloneElement(e,{key:n})})}let p=function(e){let{children:t}=e,r=(0,a.useContext)(l.AmpStateContext),n=(0,a.useContext)(u.HeadManagerContext);return a.default.createElement(o.default,{reduceComponentsToState:c,headManager:n,inAmpMode:(0,i.isInAmpMode)(r)},t)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1537:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return l}});let n=r(6689),a=()=>{},o=()=>{};function l(e){var t;let{headManager:r,reduceComponentsToState:l}=e;function u(){if(r&&r.mountedInstances){let t=n.Children.toArray(Array.from(r.mountedInstances).filter(Boolean));r.updateHead(l(t,e))}}return null==r||null==(t=r.mountedInstances)||t.add(e.children),u(),a(()=>{var t;return null==r||null==(t=r.mountedInstances)||t.add(e.children),()=>{var t;null==r||null==(t=r.mountedInstances)||t.delete(e.children)}}),a(()=>(r&&(r._pendingUpdate=u),()=>{r&&(r._pendingUpdate=u)})),o(()=>(r&&r._pendingUpdate&&(r._pendingUpdate(),r._pendingUpdate=null),()=>{r&&r._pendingUpdate&&(r._pendingUpdate(),r._pendingUpdate=null)})),null}},5709:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return r}});let r=e=>{}},5244:(e,t)=>{var r;Object.defineProperty(t,"x",{enumerable:!0,get:function(){return r}}),function(e){e.PAGES="PAGES",e.PAGES_API="PAGES_API",e.APP_PAGE="APP_PAGE",e.APP_ROUTE="APP_ROUTE"}(r||(r={}))},8039:(e,t,r)=>{e.exports=r(7093).vendored.contexts.AmpContext},1988:(e,t,r)=>{e.exports=r(7093).vendored.contexts.HeadManagerContext},2785:e=>{e.exports=require("next/dist/compiled/next-server/pages.runtime.prod.js")},6689:e=>{e.exports=require("react")},1017:e=>{e.exports=require("path")},8760:(e,t)=>{function r(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(r=function(e){return e?n:t})(e)}t._=t._interop_require_wildcard=function(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=r(t);if(n&&n.has(e))return n.get(e);var a={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var l in e)if("default"!==l&&Object.prototype.hasOwnProperty.call(e,l)){var u=o?Object.getOwnPropertyDescriptor(e,l):null;u&&(u.get||u.set)?Object.defineProperty(a,l,u):a[l]=e[l]}return a.default=e,n&&n.set(e,a),a}}};var t=require("../webpack-runtime.js");t.C(e);var r=e=>t(t.s=e),n=t.X(0,[329],()=>r(6051));module.exports=n})(); \ No newline at end of file diff --git a/.next/server/pages/_error.js.nft.json b/.next/server/pages/_error.js.nft.json index e79ee65..e9cbbef 100644 --- a/.next/server/pages/_error.js.nft.json +++ b/.next/server/pages/_error.js.nft.json @@ -1 +1 @@ -{"version":1,"files":["../../../node_modules/client-only/index.js","../../../node_modules/client-only/package.json","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/jsonwebtoken/index.js","../../../node_modules/next/dist/compiled/jsonwebtoken/package.json","../../../node_modules/next/dist/compiled/lru-cache/index.js","../../../node_modules/next/dist/compiled/lru-cache/package.json","../../../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../../../node_modules/next/dist/compiled/node-html-parser/index.js","../../../node_modules/next/dist/compiled/node-html-parser/package.json","../../../node_modules/next/dist/lib/semver-noop.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../../../node_modules/react-dom/package.json","../../../node_modules/react-dom/server.browser.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../node_modules/styled-jsx/dist/index/index.js","../../../node_modules/styled-jsx/index.js","../../../node_modules/styled-jsx/package.json","../../package.json","../chunks/106.js","../chunks/2.js","../chunks/201.js","../chunks/310.js","../chunks/323.js","../chunks/622.js","../chunks/676.js","../chunks/837.js","../chunks/840.js","../chunks/862.js","../chunks/984.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file +{"version":1,"files":["../../../node_modules/client-only/index.js","../../../node_modules/client-only/package.json","../../../node_modules/next/dist/compiled/@opentelemetry/api/index.js","../../../node_modules/next/dist/compiled/@opentelemetry/api/package.json","../../../node_modules/next/dist/compiled/jsonwebtoken/index.js","../../../node_modules/next/dist/compiled/jsonwebtoken/package.json","../../../node_modules/next/dist/compiled/lru-cache/index.js","../../../node_modules/next/dist/compiled/lru-cache/package.json","../../../node_modules/next/dist/compiled/next-server/pages.runtime.prod.js","../../../node_modules/next/dist/compiled/node-html-parser/index.js","../../../node_modules/next/dist/compiled/node-html-parser/package.json","../../../node_modules/next/dist/lib/semver-noop.js","../../../node_modules/next/dist/server/lib/trace/constants.js","../../../node_modules/next/dist/server/lib/trace/tracer.js","../../../node_modules/next/package.json","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.development.js","../../../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../../../node_modules/react-dom/package.json","../../../node_modules/react-dom/server.browser.js","../../../node_modules/react/cjs/react.development.js","../../../node_modules/react/cjs/react.production.min.js","../../../node_modules/react/index.js","../../../node_modules/react/package.json","../../../node_modules/styled-jsx/dist/index/index.js","../../../node_modules/styled-jsx/index.js","../../../node_modules/styled-jsx/package.json","../../package.json","../chunks/329.js","../chunks/337.js","../chunks/638.js","../chunks/969.js","../chunks/font-manifest.json","../webpack-runtime.js"]} \ No newline at end of file diff --git a/.next/server/server-reference-manifest.js b/.next/server/server-reference-manifest.js index 371b677..de3bc9a 100644 --- a/.next/server/server-reference-manifest.js +++ b/.next/server/server-reference-manifest.js @@ -1 +1 @@ -self.__RSC_SERVER_MANIFEST="{\"node\":{},\"edge\":{},\"encryptionKey\":\"WRFGN+OZylAMLdNPfPxNWoeXs/0b6moepWL3+7eExas=\"}" \ No newline at end of file +self.__RSC_SERVER_MANIFEST="{\"node\":{},\"edge\":{},\"encryptionKey\":\"MzQ/e9h8Xz4GdhHvoHxDk6HsRe+KO1QCgwP0dm0ye4s=\"}" \ No newline at end of file diff --git a/.next/server/server-reference-manifest.json b/.next/server/server-reference-manifest.json index 1465bdc..b58a0f8 100644 --- a/.next/server/server-reference-manifest.json +++ b/.next/server/server-reference-manifest.json @@ -1 +1 @@ -{"node":{},"edge":{},"encryptionKey":"WRFGN+OZylAMLdNPfPxNWoeXs/0b6moepWL3+7eExas="} \ No newline at end of file +{"node":{},"edge":{},"encryptionKey":"MzQ/e9h8Xz4GdhHvoHxDk6HsRe+KO1QCgwP0dm0ye4s="} \ No newline at end of file diff --git a/.next/server/webpack-runtime.js b/.next/server/webpack-runtime.js index 5757df7..96af56b 100644 --- a/.next/server/webpack-runtime.js +++ b/.next/server/webpack-runtime.js @@ -1 +1 @@ -(()=>{"use strict";var e={},_={};function __webpack_require__(r){var a=_[r];if(void 0!==a)return a.exports;var t=_[r]={exports:{}},u=!0;try{e[r].call(t.exports,t,t.exports,__webpack_require__),u=!1}finally{u&&delete _[r]}return t.exports}__webpack_require__.m=e,__webpack_require__.amdO={},__webpack_require__.n=e=>{var _=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(_,{a:_}),_},(()=>{var e,_=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;__webpack_require__.t=function(r,a){if(1&a&&(r=this(r)),8&a||"object"==typeof r&&r&&(4&a&&r.__esModule||16&a&&"function"==typeof r.then))return r;var t=Object.create(null);__webpack_require__.r(t);var u={};e=e||[null,_({}),_([]),_(_)];for(var i=2&a&&r;"object"==typeof i&&!~e.indexOf(i);i=_(i))Object.getOwnPropertyNames(i).forEach(e=>u[e]=()=>r[e]);return u.default=()=>r,__webpack_require__.d(t,u),t}})(),__webpack_require__.d=(e,_)=>{for(var r in _)__webpack_require__.o(_,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:_[r]})},__webpack_require__.f={},__webpack_require__.e=e=>Promise.all(Object.keys(__webpack_require__.f).reduce((_,r)=>(__webpack_require__.f[r](e,_),_),[])),__webpack_require__.u=e=>""+e+".js",__webpack_require__.o=(e,_)=>Object.prototype.hasOwnProperty.call(e,_),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},__webpack_require__.X=(e,_,r)=>{var a=_;r||(_=e,r=()=>__webpack_require__(__webpack_require__.s=a)),_.map(__webpack_require__.e,__webpack_require__);var t=r();return void 0===t?e:t},(()=>{var e={658:1},installChunk=_=>{var r=_.modules,a=_.ids,t=_.runtime;for(var u in r)__webpack_require__.o(r,u)&&(__webpack_require__.m[u]=r[u]);t&&t(__webpack_require__);for(var i=0;i{e[_]||(658!=_?installChunk(require("./chunks/"+__webpack_require__.u(_))):e[_]=1)},module.exports=__webpack_require__,__webpack_require__.C=installChunk})()})(); \ No newline at end of file +(()=>{"use strict";var e={},r={};function t(o){var a=r[o];if(void 0!==a)return a.exports;var n=r[o]={exports:{}},u=!0;try{e[o].call(n.exports,n,n.exports,t),u=!1}finally{u&&delete r[o]}return n.exports}t.m=e,t.amdO={},t.n=e=>{var r=e&&e.__esModule?()=>e.default:()=>e;return t.d(r,{a:r}),r},(()=>{var e,r=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__;t.t=function(o,a){if(1&a&&(o=this(o)),8&a||"object"==typeof o&&o&&(4&a&&o.__esModule||16&a&&"function"==typeof o.then))return o;var n=Object.create(null);t.r(n);var u={};e=e||[null,r({}),r([]),r(r)];for(var f=2&a&&o;"object"==typeof f&&!~e.indexOf(f);f=r(f))Object.getOwnPropertyNames(f).forEach(e=>u[e]=()=>o[e]);return u.default=()=>o,t.d(n,u),n}})(),t.d=(e,r)=>{for(var o in r)t.o(r,o)&&!t.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:r[o]})},t.f={},t.e=e=>Promise.all(Object.keys(t.f).reduce((r,o)=>(t.f[o](e,r),r),[])),t.u=e=>""+e+".js",t.o=(e,r)=>Object.prototype.hasOwnProperty.call(e,r),t.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.X=(e,r,o)=>{var a=r;o||(r=e,o=()=>t(t.s=a)),r.map(t.e,t);var n=o();return void 0===n?e:n},(()=>{var e={658:1},r=r=>{var o=r.modules,a=r.ids,n=r.runtime;for(var u in o)t.o(o,u)&&(t.m[u]=o[u]);n&&n(t);for(var f=0;f{e[o]||(658!=o?r(require("./chunks/"+t.u(o))):e[o]=1)},module.exports=t,t.C=r})()})(); \ No newline at end of file diff --git a/.next/static/P9X42g8nWZ62i2biioMqg/_buildManifest.js b/.next/static/P9X42g8nWZ62i2biioMqg/_buildManifest.js deleted file mode 100644 index 4c143f6..0000000 --- a/.next/static/P9X42g8nWZ62i2biioMqg/_buildManifest.js +++ /dev/null @@ -1 +0,0 @@ -self.__BUILD_MANIFEST={__rewrites:{afterFiles:[],beforeFiles:[],fallback:[]},"/_error":["static/chunks/pages/_error-b646007f40c4f0a8.js"],sortedPages:["/_app","/_error"]},self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB(); \ No newline at end of file diff --git a/.next/static/chunks/173-2ffa9652644381a8.js b/.next/static/chunks/173-2ffa9652644381a8.js deleted file mode 100644 index 8a88dc8..0000000 --- a/.next/static/chunks/173-2ffa9652644381a8.js +++ /dev/null @@ -1,11507 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[173],{8811:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return dynamic}});let r=i(1024);i(2265);let s=r._(i(7075));function convertModule(e){return{default:(null==e?void 0:e.default)||e}}function dynamic(e,t){let i=s.default,r={loading:e=>{let{error:t,isLoading:i,pastDelay:r}=e;return null}};"function"==typeof e&&(r.loader=e),Object.assign(r,t);let n=r.loader;return i({...r,loader:()=>null!=n?n().then(convertModule):Promise.resolve(convertModule(()=>null))})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9167:function(e,t,i){function NoSSR(e){let{children:t}=e;return t}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NoSSR",{enumerable:!0,get:function(){return NoSSR}}),i(1283)},7075:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let r=i(1024),s=r._(i(2265)),n=i(9167);function Loadable(e){let t=Object.assign({loader:null,loading:null,ssr:!0},e);function LoadableComponent(e){let i=t.loading,r=s.default.createElement(i,{isLoading:!0,pastDelay:!0,error:null}),a=t.ssr?s.default.Fragment:n.NoSSR,o=t.lazy;return s.default.createElement(s.default.Suspense,{fallback:r},s.default.createElement(a,null,s.default.createElement(o,e)))}return t.lazy=s.default.lazy(t.loader),LoadableComponent.displayName="LoadableComponent",LoadableComponent}let a=Loadable},622:function(e,t,i){/** - * @license React - * react-jsx-runtime.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var r=i(2265),s=Symbol.for("react.element"),n=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function q(e,t,i){var r,n={},h=null,u=null;for(r in void 0!==i&&(h=""+i),void 0!==t.key&&(h=""+t.key),void 0!==t.ref&&(u=t.ref),t)a.call(t,r)&&!l.hasOwnProperty(r)&&(n[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===n[r]&&(n[r]=t[r]);return{$$typeof:s,type:e,key:h,ref:u,props:n,_owner:o.current}}t.Fragment=n,t.jsx=q,t.jsxs=q},7437:function(e,t,i){e.exports=i(622)},3621:function(e,t,i){i.d(t,{O:function(){return AbstractActionManager}});let AbstractActionManager=class AbstractActionManager{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(let e in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in AbstractActionManager.Triggers)if(Object.prototype.hasOwnProperty.call(AbstractActionManager.Triggers,t)){let i=parseInt(t);if(i===e)return!0}return!1}};AbstractActionManager.Triggers={}},9528:function(e,t,i){i.d(t,{V:function(){return ActionEvent}});let ActionEvent=class ActionEvent{constructor(e,t,i,r,s,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=n}static CreateNew(e,t,i){let r=e.getScene();return new ActionEvent(e,r.pointerX,r.pointerY,r.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,r){return new ActionEvent(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,r)}static CreateNewFromScene(e,t){return new ActionEvent(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,r){return new ActionEvent(e,t.x,t.y,null,i,r)}}},1295:function(e,t,i){i.d(t,{l:function(){return Buffer},o:function(){return VertexBuffer}});var r=i(9185);let Buffer=class Buffer{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,n=!1,a=!1,o=!1,l,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=a,this._divisor=l||1,this._label=h,t instanceof r.h?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,r,s,n=!1,a){let o=n?t:t*Float32Array.BYTES_PER_ELEMENT,l=r?n?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new VertexBuffer(this._engine,this,e,this._updatable,!0,l,void 0===s?this._instanced:s,o,i,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(){this._buffer=null,this.create(this._data)}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),0===t&&void 0===i?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}};let VertexBuffer=class VertexBuffer{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){let t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get totalVertices(){let 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,i,r,s,n,a,o,l,h,u=!1,c=!1,d=1,p=!1){var _,f,m,g,v;this._isDisposed=!1;let x=!1;if(this.engine=e,"object"==typeof r&&null!==r?(x=null!==(_=r.updatable)&&void 0!==_&&_,s=r.postponeInternalCreation,n=r.stride,a=r.instanced,o=r.offset,l=r.size,h=r.type,u=null!==(f=r.normalized)&&void 0!==f&&f,c=null!==(m=r.useBytes)&&void 0!==m&&m,d=null!==(g=r.divisor)&&void 0!==g?g:1,p=null!==(v=r.takeBufferOwnership)&&void 0!==v&&v,this._label=r.label):x=!!r,t instanceof Buffer?(this._buffer=t,this._ownsBuffer=p):(this._buffer=new Buffer(e,t,x,n,s,a,c,d,this._label),this._ownsBuffer=!0),this.uniqueId=VertexBuffer._Counter++,this._kind=i,void 0===h){let e=this.getData();this.type=e?VertexBuffer.GetDataType(e):VertexBuffer.FLOAT}else this.type=h;let T=VertexBuffer.GetTypeByteLength(this.type);c?(this._size=l||(n?n/T:VertexBuffer.DeduceStride(i)),this.byteStride=n||this._buffer.byteStride||this._size*T,this.byteOffset=o||0):(this._size=l||n||VertexBuffer.DeduceStride(i),this.byteStride=n?n*T:this._buffer.byteStride||this._size*T,this.byteOffset=(o||0)*T),this.normalized=u,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(){var e;null===(e=this._buffer)||void 0===e||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){let i=this.getData();return i?(e=null!=e?e:this.totalVertices,VertexBuffer.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t)):null}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/VertexBuffer.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/VertexBuffer.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*VertexBuffer.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,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){VertexBuffer.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case VertexBuffer.UVKind:case VertexBuffer.UV2Kind:case VertexBuffer.UV3Kind:case VertexBuffer.UV4Kind:case VertexBuffer.UV5Kind:case VertexBuffer.UV6Kind:return 2;case VertexBuffer.NormalKind:case VertexBuffer.PositionKind:return 3;case VertexBuffer.ColorKind:case VertexBuffer.ColorInstanceKind:case VertexBuffer.MatricesIndicesKind:case VertexBuffer.MatricesIndicesExtraKind:case VertexBuffer.MatricesWeightsKind:case VertexBuffer.MatricesWeightsExtraKind:case VertexBuffer.TangentKind:return 4;default:throw Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?VertexBuffer.BYTE:e instanceof Uint8Array?VertexBuffer.UNSIGNED_BYTE:e instanceof Int16Array?VertexBuffer.SHORT:e instanceof Uint16Array?VertexBuffer.UNSIGNED_SHORT:e instanceof Int32Array?VertexBuffer.INT:e instanceof Uint32Array?VertexBuffer.UNSIGNED_INT:VertexBuffer.FLOAT}static GetTypeByteLength(e){switch(e){case VertexBuffer.BYTE:case VertexBuffer.UNSIGNED_BYTE:return 1;case VertexBuffer.SHORT:case VertexBuffer.UNSIGNED_SHORT:return 2;case VertexBuffer.INT:case VertexBuffer.UNSIGNED_INT:case VertexBuffer.FLOAT:return 4;default:throw Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,s,n,a,o){if(e instanceof Array){let s=t/4,a=i/4;for(let t=0;ta[t]=e),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==r||e.length!==h){if(e instanceof Array){let t=r/4;return e.slice(t,t+h)}if(e instanceof ArrayBuffer)return new Float32Array(e,r,h);{let t=e.byteOffset+r;if(o){let i=new Float32Array(h),r=new Float32Array(e.buffer,t,h);return i.set(r),i}let i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,h)}}return o?e.slice():e}};VertexBuffer._Counter=0,VertexBuffer.BYTE=5120,VertexBuffer.UNSIGNED_BYTE=5121,VertexBuffer.SHORT=5122,VertexBuffer.UNSIGNED_SHORT=5123,VertexBuffer.INT=5124,VertexBuffer.UNSIGNED_INT=5125,VertexBuffer.FLOAT=5126,VertexBuffer.PositionKind="position",VertexBuffer.NormalKind="normal",VertexBuffer.TangentKind="tangent",VertexBuffer.UVKind="uv",VertexBuffer.UV2Kind="uv2",VertexBuffer.UV3Kind="uv3",VertexBuffer.UV4Kind="uv4",VertexBuffer.UV5Kind="uv5",VertexBuffer.UV6Kind="uv6",VertexBuffer.ColorKind="color",VertexBuffer.ColorInstanceKind="instanceColor",VertexBuffer.MatricesIndicesKind="matricesIndices",VertexBuffer.MatricesWeightsKind="matricesWeights",VertexBuffer.MatricesIndicesExtraKind="matricesIndicesExtra",VertexBuffer.MatricesWeightsExtraKind="matricesWeightsExtra"},9185:function(e,t,i){i.d(t,{h:function(){return DataBuffer}});let DataBuffer=class DataBuffer{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=DataBuffer._Counter++}};DataBuffer._Counter=0},555:function(e,t,i){i.d(t,{V:function(){return Camera}});var r=i(9956),s=i(1760),n=i(8355),a=i(5132),o=i(4800),l=i(78),h=i(208),u=i(9626),c=i(3048),d=i(6131),p=i(6329),_=i(2975);let Camera=class Camera extends h.N{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,r;let s=0,n=0;if(this.mode===Camera.PERSPECTIVE_CAMERA)this.fovMode===Camera.FOVMODE_VERTICAL_FIXED?(n=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*n):n=(s=2*this.minZ*Math.tan(this.fov/2))/this.getEngine().getAspectRatio(this);else{let a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:a)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-a),n=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(r=this.orthoBottom)&&void 0!==r?r:-o)}return s*n}set orthoLeft(e){for(let t of(this._orthoLeft=e,this._rigCameras))t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){for(let t of(this._orthoRight=e,this._rigCameras))t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){for(let t of(this._orthoBottom=e,this._rigCameras))t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){for(let t of(this._orthoTop=e,this._rigCameras))t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){for(let t of(this._mode=e,this._rigCameras))t.mode=e}get mode(){return this._mode}constructor(e,t,i,r=!0){super(e,i),this._position=l.P.Zero(),this._upVector=l.P.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=Camera.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new p.l(0,0,1,1),this.layerMask=268435455,this.fovMode=Camera.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=Camera.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new o.y$,this.onProjectionMatrixChangedObservable=new o.y$,this.onAfterCheckInputsObservable=new o.y$,this.onRestoreStateObservable=new o.y$,this.isRigCamera=!1,this._rigCameras=[],this._skipRendering=!1,this._projectionMatrix=new l.y3,this._postProcesses=[],this._activeMeshes=new n.t(256),this._globalPosition=l.P.Zero(),this._computedViewMatrix=l.y3.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=l.y3.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=l._f.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!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}_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 i=0;i-1?(u.Y.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){let 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 l.y3.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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){var t,i,r,s,n,a,o,h,u,c,d,p,_,f,m,g,v,x,T;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;let S=this.getEngine(),C=this.getScene(),E=S.useReverseDepthBuffer;if(this.mode===Camera.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=S.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),(C.useRightHandedSystem?l.y3.PerspectiveFovRHToRef:l.y3.PerspectiveFovLHToRef)(this.fov,S.getAspectRatio(this),E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===Camera.FOVMODE_VERTICAL_FIXED,S.isNDCHalfZRange,this.projectionPlaneTilt,E);else{let e=S.getRenderWidth()/2,b=S.getRenderHeight()/2;C.useRightHandedSystem?this.oblique?l.y3.ObliqueOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(r=this.orthoBottom)&&void 0!==r?r:-b,null!==(s=this.orthoTop)&&void 0!==s?s:b,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,S.isNDCHalfZRange):l.y3.OrthoOffCenterRHToRef(null!==(n=this.orthoLeft)&&void 0!==n?n:-e,null!==(a=this.orthoRight)&&void 0!==a?a:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-b,null!==(h=this.orthoTop)&&void 0!==h?h:b,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this._projectionMatrix,S.isNDCHalfZRange):this.oblique?l.y3.ObliqueOffCenterLHToRef(null!==(u=this.orthoLeft)&&void 0!==u?u:-e,null!==(c=this.orthoRight)&&void 0!==c?c:e,null!==(d=this.orthoBottom)&&void 0!==d?d:-b,null!==(p=this.orthoTop)&&void 0!==p?p:b,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,S.isNDCHalfZRange):l.y3.OrthoOffCenterLHToRef(null!==(_=this.orthoLeft)&&void 0!==_?_:-e,null!==(f=this.orthoRight)&&void 0!==f?f:e,null!==(m=this.orthoBottom)&&void 0!==m?m:-b,null!==(g=this.orthoTop)&&void 0!==g?g:b,E?this.maxZ:this.minZ,E?this.minZ:this.maxZ,this._projectionMatrix,S.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=null===(v=this.oblique)||void 0===v?void 0:v.angle,this._cache.obliqueLength=null===(x=this.oblique)||void 0===x?void 0:x.length,this._cache.obliqueOffset=null===(T=this.oblique)||void 0===T?void 0:T.offset,this._cache.renderWidth=S.getRenderWidth(),this._cache.renderHeight=S.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?l.P.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?_.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=_.i.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),!t||!(this.rigCameras.length>0))return e.isInFrustum(this._frustumPlanes);{let t=!1;return this.rigCameras.forEach(i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)}),t}}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,d.S)("Ray")}getForwardRayToRef(e,t=100,i,r){throw(0,d.S)("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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){let 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!==Camera.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){let t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=a.w1.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==Camera.RIG_MODE_NONE){let e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);let 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 l.y3.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=a.w1.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;eCamera._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=Camera.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=s.p4.Parse(r,e,t);if(void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n.inputs&&(n.inputs.parse(e),n._setupInputs()),e.upVector&&(n.upVector=l.P.FromArray(e.upVector)),n.setPosition&&(n.position.copyFromFloats(0,0,0),n.setPosition(l.P.FromArray(e.position))),e.target&&n.setTarget&&n.setTarget(l.P.FromArray(e.target)),e.cameraRigMode){let t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};n.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;tthis.parent._getWorldMatrixDeterminant()&&(e*=-1),e}};Camera._CreateDefaultParsedCamera=(e,t)=>{throw(0,d.S)("UniversalCamera")},Camera.PERSPECTIVE_CAMERA=0,Camera.ORTHOGRAPHIC_CAMERA=1,Camera.FOVMODE_VERTICAL_FIXED=0,Camera.FOVMODE_HORIZONTAL_FIXED=1,Camera.RIG_MODE_NONE=0,Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Camera.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Camera.RIG_MODE_VR=20,Camera.RIG_MODE_CUSTOM=22,Camera.ForceAttachControlToAlwaysPreventDefault=!1,(0,r.gn)([(0,s.hd)("position")],Camera.prototype,"_position",void 0),(0,r.gn)([(0,s.hd)("upVector")],Camera.prototype,"_upVector",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"orthoLeft",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"orthoRight",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"orthoBottom",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"orthoTop",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"fov",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"projectionPlaneTilt",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"minZ",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"maxZ",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"inertia",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"mode",null),(0,r.gn)([(0,s.qC)()],Camera.prototype,"layerMask",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"fovMode",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"cameraRigMode",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"interaxialDistance",void 0),(0,r.gn)([(0,s.qC)()],Camera.prototype,"isStereoscopicSideBySide",void 0)},6491:function(e,t,i){i.d(t,{c:function(){return IntersectionInfo}});let IntersectionInfo=class IntersectionInfo{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}},5790:function(e,t,i){i.d(t,{a:function(){return _MeshCollisionData}});var r=i(78);let _MeshCollisionData=class _MeshCollisionData{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new r.P(0,0,0),this._diffPositionForCollisions=new r.P(0,0,0),this._collisionResponse=!0}}},2248:function(e,t,i){i.d(t,{p:function(){return PickingInfo}});var r=i(78),s=i(1295);let PickingInfo=class PickingInfo{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){let i;if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(s.o.NormalKind))return null;let n=this.pickedMesh.getIndices();(null==n?void 0:n.length)===0&&(n=null);let a=r.jp.Vector3[0],o=r.jp.Vector3[1],l=r.jp.Vector3[2];if(t){let e=this.pickedMesh.getVerticesData(s.o.NormalKind),t=n?r.P.FromArrayToRef(e,3*n[3*this.faceId],a):a.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),h=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+1],o):o.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),u=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]);t=t.scale(this.bu),h=h.scale(this.bv),u=u.scale(1-this.bu-this.bv),i=new r.P(t.x+h.x+u.x,t.y+h.y+u.y,t.z+h.z+u.z)}else{let e=this.pickedMesh.getVerticesData(s.o.PositionKind),t=n?r.P.FromArrayToRef(e,3*n[3*this.faceId],a):a.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),h=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+1],o):o.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),u=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]),c=t.subtract(h),d=u.subtract(h);i=r.P.Cross(c,d)}let transformNormalToWorld=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(r.jp.Matrix[0].copyFrom(i),(i=r.jp.Matrix[0]).setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(r.jp.Matrix[1]),i=r.jp.Matrix[1]),r.P.TransformNormalToRef(t,i,t)};if(e&&transformNormalToWorld(this.pickedMesh,i),this.ray){let t=r.jp.Vector3[0].copyFrom(i);e||transformNormalToWorld(this.pickedMesh,t),r.P.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=s.o.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let n=r.FM.FromArray(i,2*t[3*this.faceId]),a=r.FM.FromArray(i,2*t[3*this.faceId+1]),o=r.FM.FromArray(i,2*t[3*this.faceId+2]);return n=n.scale(this.bu),a=a.scale(this.bv),o=o.scale(1-this.bu-this.bv),new r.FM(n.x+a.x+o.x,n.y+a.y+o.y)}}},6705:function(e,t,i){i.d(t,{e:function(){return CompatibilityOptions}});let CompatibilityOptions=class CompatibilityOptions{};CompatibilityOptions.UseOpenGLOrientationForUV=!1},4347:function(e,t,i){i.d(t,{k:function(){return BoundingBox}});var r=i(4254),s=i(78),n=i(9806);let BoundingBox=class BoundingBox{constructor(e,t,i){this.vectors=r.B.BuildArray(8,s.P.Zero),this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.extendSize=s.P.Zero(),this.extendSizeWorld=s.P.Zero(),this.directions=r.B.BuildArray(3,s.P.Zero),this.vectorsWorld=r.B.BuildArray(8,s.P.Zero),this.minimumWorld=s.P.Zero(),this.maximumWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){let r=e.x,n=e.y,a=e.z,o=t.x,l=t.y,h=t.z,u=this.vectors;this.minimum.copyFromFloats(r,n,a),this.maximum.copyFromFloats(o,l,h),u[0].copyFromFloats(r,n,a),u[1].copyFromFloats(o,l,h),u[2].copyFromFloats(o,n,a),u[3].copyFromFloats(r,l,a),u[4].copyFromFloats(r,n,h),u[5].copyFromFloats(o,l,a),u[6].copyFromFloats(r,l,h),u[7].copyFromFloats(o,n,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||s.y3.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){let t=BoundingBox._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,n=i.scaleInPlace(.5*s),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){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,n=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)n[e].copyFrom(a[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){let o=n[r];s.P.TransformCoordinatesToRef(a[r],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}s.P.FromArrayToRef(e.m,0,r[0]),s.P.FromArrayToRef(e.m,4,r[1]),s.P.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return BoundingBox.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,o=i.x,l=i.y,h=i.z,u=e.x,c=e.y,d=e.z,p=-n.kn;return!(o-uu-r)&&!(l-cc-s)&&!(h-dd-a)}intersectsSphere(e){return BoundingBox.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,n=i.y,a=i.z,o=r.x,l=r.y,h=r.z,u=e.x,c=e.y,d=e.z,p=t.x,_=t.y,f=t.z;return!(op)&&!(l_)&&!(hf)}dispose(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){let n=BoundingBox._TmpVector3[0];s.P.ClampToRef(i,e,t,n);let a=s.P.DistanceSquared(i,n);return a<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let t=0;t<8;++t)if(0>r.dotCoordinate(e[t]))return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}};BoundingBox._TmpVector3=r.B.BuildArray(3,s.P.Zero)},5681:function(e,t,i){i.d(t,{j:function(){return BoundingInfo}});var r=i(4254),s=i(78),n=i(4347),a=i(3592);let o={min:0,max:0},l={min:0,max:0},computeBoxExtents=(e,t,i)=>{let r=s.P.Dot(t.centerWorld,e),n=Math.abs(s.P.Dot(t.directions[0],e))*t.extendSize.x,a=Math.abs(s.P.Dot(t.directions[1],e))*t.extendSize.y,o=Math.abs(s.P.Dot(t.directions[2],e))*t.extendSize.z,l=n+a+o;i.min=r-l,i.max=r+l},axisOverlap=(e,t,i)=>(computeBoxExtents(e,t,o),computeBoxExtents(e,i,l),!(o.min>l.max||l.min>o.max));let BoundingInfo=class BoundingInfo{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new n.k(e,t,i),this.boundingSphere=new a.K(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}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){let i=BoundingInfo._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=BoundingInfo._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let t=s.P.Minimize(this.minimum,e),i=s.P.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){let t=s.jp.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let i=s.jp.Vector3[0];return s.P.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),s.P.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!!((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(1===t||3===t||this.boundingBox.isInFrustum(e))}get diagonalLength(){let e=this.boundingBox,t=e.maximumWorld.subtractToRef(e.minimumWorld,BoundingInfo._TmpVector3[0]);return t.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(!a.K.Intersects(this.boundingSphere,e.boundingSphere)||!n.k.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!!(axisOverlap(i.directions[0],i,r)&&axisOverlap(i.directions[1],i,r)&&axisOverlap(i.directions[2],i,r)&&axisOverlap(r.directions[0],i,r)&&axisOverlap(r.directions[1],i,r)&&axisOverlap(r.directions[2],i,r)&&axisOverlap(s.P.Cross(i.directions[0],r.directions[0]),i,r)&&axisOverlap(s.P.Cross(i.directions[0],r.directions[1]),i,r)&&axisOverlap(s.P.Cross(i.directions[0],r.directions[2]),i,r)&&axisOverlap(s.P.Cross(i.directions[1],r.directions[0]),i,r)&&axisOverlap(s.P.Cross(i.directions[1],r.directions[1]),i,r)&&axisOverlap(s.P.Cross(i.directions[1],r.directions[2]),i,r)&&axisOverlap(s.P.Cross(i.directions[2],r.directions[0]),i,r)&&axisOverlap(s.P.Cross(i.directions[2],r.directions[1]),i,r)&&axisOverlap(s.P.Cross(i.directions[2],r.directions[2]),i,r))}};BoundingInfo._TmpVector3=r.B.BuildArray(2,s.P.Zero)},3592:function(e,t,i){i.d(t,{K:function(){return BoundingSphere}});var r=i(4254),s=i(78);let BoundingSphere=class BoundingSphere{constructor(e,t,i){this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);let r=s.P.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||s.y3.IdentityReadOnly)}scale(e){let t=this.radius*e,i=BoundingSphere._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),n=this.center.addToRef(r,i[2]);return this.reConstruct(s,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{s.P.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=BoundingSphere._TmpVector3[0];s.P.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){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(0>e[i].dotCoordinate(t))return!1;return!0}intersectsPoint(e){let t=s.P.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld=r.Fz.LeftClick&&i<=r.Fz.RightClick&&(h.type=1===s?"pointerdown":"pointerup",h.button=i-2),h}static _CreateWheelEvent(e,t,i,s,a,o){let l=this._CreateMouseEvent(e,t,i,s,a,o);switch(l.pointerId=1,l.type="wheel",l.deltaMode=n.G.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case r.Fz.MouseWheelX:l.deltaX=s;break;case r.Fz.MouseWheelY:l.deltaY=s;break;case r.Fz.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,n,a){let o=this._CreateEvent(a),l=n.pollInput(e,t,r.Fz.Horizontal),h=n.pollInput(e,t,r.Fz.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=n.pollInput(e,t,r.FP.DeltaHorizontal),o.movementY=n.pollInput(e,t,r.FP.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,n),o.clientX=l,o.clientY=h,o.x=l,o.y=h,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){let n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=r.Yi.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=1===t?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(r.Yi.Keyboard),s=i&&1===t.pollInput(r.Yi.Keyboard,0,18),n=i&&1===t.pollInput(r.Yi.Keyboard,0,17),a=i&&(1===t.pollInput(r.Yi.Keyboard,0,91)||1===t.pollInput(r.Yi.Keyboard,0,92)||1===t.pollInput(r.Yi.Keyboard,0,93)),o=i&&1===t.pollInput(r.Yi.Keyboard,0,16);e.altKey=s,e.ctrlKey=n,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}};let NativeDeviceInputSystem=class NativeDeviceInputSystem{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(e,t,r,s)=>{let n=DeviceEventFactory.CreateDeviceEvent(e,t,r,s,this);i(e,t,n)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===r.Yi.Mouse||e===r.Yi.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}};var a=i(7209),o=i(5132);let l=Object.keys(r.Fz).length/2;let WebDeviceInputSystem=class WebDeviceInputSystem{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=o.w1.IsSafari(),this._usingMacOS=(0,a.up)()&&/(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=(0,a.up)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=(0,a.up)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=o.w1.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let s=this._inputs[e][t];if(!s)throw`Unable to find device ${r.Yi[e]}`;e>=r.Yi.DualShock&&e<=r.Yi.DualSense&&this._updateDevice(e,t,i);let n=s[i];if(void 0===n)throw`Unable to find input ${i} for device ${r.Yi[e]} in slot ${t}`;return i===r.Fz.Move&&o.w1.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this===null||void 0===this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let e of this._inputs)if(e)for(let t in e){let i=+t,r=e[i];if(r)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.Yi.Keyboard,0,255));let t=this._inputs[r.Yi.Keyboard][0];t&&(t[e.keyCode]=1,e.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&!this._metaKeys.includes(e.keyCode)&&this._metaKeys.push(e.keyCode),this._onInputChanged(r.Yi.Keyboard,0,e))},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.Yi.Keyboard,0,255));let t=this._inputs[r.Yi.Keyboard][0];if(t){if(t[e.keyCode]=0,e.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(let e of this._metaKeys){let i=DeviceEventFactory.CreateDeviceEvent(r.Yi.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(r.Yi.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(r.Yi.Keyboard,0,e)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[r.Yi.Keyboard][0];for(let t=0;t{let t=this._getPointerType(e),i=t===r.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===r.Yi.Touch&&-1===i){let r=this._activeTouchIds.indexOf(-1);if(r>=0)i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i);else{o.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);let s=this._inputs[t][i];s&&(e.inputIndex=r.Fz.Move,s[r.Fz.Horizontal]=e.clientX,s[r.Fz.Vertical]=e.clientY,t===r.Yi.Touch&&0===s[r.Fz.LeftClick]&&(s[r.Fz.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,e),this._usingSafari||-1===e.button||(e.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,e)))},this._pointerDownEvent=e=>{let t=this._getPointerType(e),i=t===r.Yi.Mouse?0:e.pointerId;if(t===r.Yi.Touch){let t=this._activeTouchIds.indexOf(-1);if(t>=0)i=t,this._activeTouchIds[t]=e.pointerId;else{o.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===r.Yi.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);let s=this._inputs[t][i];if(s){let n=s[r.Fz.Horizontal],a=s[r.Fz.Vertical];if(t===r.Yi.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){}s[r.Fz.Horizontal]=e.clientX,s[r.Fz.Vertical]=e.clientY,s[e.button+2]=1,e.inputIndex=e.button+2,this._onInputChanged(t,i,e),(n!==e.clientX||a!==e.clientY)&&(e.inputIndex=r.Fz.Move,this._onInputChanged(t,i,e))}},this._pointerUpEvent=e=>{var t,i,s,n,a;let o=this._getPointerType(e),l=o===r.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(o===r.Yi.Touch){if(-1===l)return;this._activeTouchIds[l]=-1}let h=null===(t=this._inputs[o])||void 0===t?void 0:t[l];if(h&&0!==h[e.button+2]){let t=h[r.Fz.Horizontal],u=h[r.Fz.Vertical];h[r.Fz.Horizontal]=e.clientX,h[r.Fz.Vertical]=e.clientY,h[e.button+2]=0,void 0===e.pointerId&&(e.pointerId=this._mouseId),(t!==e.clientX||u!==e.clientY)&&(e.inputIndex=r.Fz.Move,this._onInputChanged(o,l,e)),e.inputIndex=e.button+2,o===r.Yi.Mouse&&this._mouseId>=0&&(null===(s=(i=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(a=(n=this._elementToAttachTo).hasPointerCapture)||void 0===a?void 0:a.call(n,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(o,l,e),o===r.Yi.Touch&&this._onDeviceDisconnected(o,l)}},this._pointerCancelEvent=e=>{var t,i,s,n;if("mouse"===e.pointerType){let e=this._inputs[r.Yi.Mouse][0];this._mouseId>=0&&(null===(i=(t=this._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=r.Fz.LeftClick;t<=r.Fz.BrowserForward;t++)if(1===e[t]){e[t]=0;let i=DeviceEventFactory.CreateDeviceEvent(r.Yi.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Mouse,0,i)}}else{let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;(null===(n=(s=this._elementToAttachTo).hasPointerCapture)||void 0===n?void 0:n.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[r.Yi.Touch][t][r.Fz.LeftClick]=0;let i=DeviceEventFactory.CreateDeviceEvent(r.Yi.Touch,t,r.Fz.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(r.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(r.Yi.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1,noop=function(){};try{let t=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",noop,t),this._elementToAttachTo.removeEventListener("test",noop,t)}catch(e){}this._pointerBlurEvent=()=>{var e,t,i,s,n;if(this.isDeviceAvailable(r.Yi.Mouse)){let i=this._inputs[r.Yi.Mouse][0];this._mouseId>=0&&(null===(t=(e=this._elementToAttachTo).hasPointerCapture)||void 0===t?void 0:t.call(e,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let e=r.Fz.LeftClick;e<=r.Fz.BrowserForward;e++)if(1===i[e]){i[e]=0;let t=DeviceEventFactory.CreateDeviceEvent(r.Yi.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Mouse,0,t)}}if(this.isDeviceAvailable(r.Yi.Touch)){let e=this._inputs[r.Yi.Touch];for(let t=0;t{let t=r.Yi.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,l));let i=this._inputs[t][0];i&&(i[r.Fz.MouseWheelX]=e.deltaX||0,i[r.Fz.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[r.Fz.MouseWheelZ]=e.deltaZ||0,void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[r.Fz.MouseWheelX]&&(e.inputIndex=r.Fz.MouseWheelX,this._onInputChanged(t,0,e)),0!==i[r.Fz.MouseWheelY]&&(e.inputIndex=r.Fz.MouseWheelY,this._onInputChanged(t,0,e)),0!==i[r.Fz.MouseWheelZ]&&(e.inputIndex=r.Fz.MouseWheelZ,this._onInputChanged(t,0,e)))},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(r.Yi.Mouse)){let e=this._inputs[r.Yi.Mouse][0];e[r.Fz.MouseWheelX]=0,e[r.Fz.MouseWheelY]=0,e[r.Fz.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return -1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?r.Yi.DualSense:r.Yi.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?r.Yi.Xbox:-1!==e.indexOf("057e")?r.Yi.Switch:r.Yi.Generic}_getPointerType(e){let t=r.Yi.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=r.Yi.Touch),t}};var h=i(6327);let InternalDeviceSourceManager=class InternalDeviceSourceManager{constructor(e){this._registeredManagers=[],this._refCount=0,this.registerManager=e=>{for(let t=0;t{let t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};let t=Object.keys(r.Yi).length/2;this._devices=Array(t);let onDeviceConnected=(e,t)=>{for(let i of(this._devices[e]||(this._devices[e]=[]),this._devices[e][t]||(this._devices[e][t]=t),this._registeredManagers)){let r=new h.p(this._deviceInputSystem,e,t);i._addDevice(r)}},onDeviceDisconnected=(e,t)=>{var i;for(let r of((null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t],this._registeredManagers))r._removeDevice(e,t)},onInputChanged=(e,t,i)=>{if(i)for(let r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new NativeDeviceInputSystem(onDeviceConnected,onDeviceDisconnected,onInputChanged):this._deviceInputSystem=new WebDeviceInputSystem(e,onDeviceConnected,onDeviceDisconnected,onInputChanged)}dispose(){this._deviceInputSystem.dispose()}};let DeviceSourceManager=class DeviceSourceManager{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){let t=Object.keys(r.Yi).length/2;this._devices=Array(t),this._firstDevice=Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new InternalDeviceSourceManager(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s.y$(e=>{for(let t of this._devices)if(t)for(let i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)}),this.onDeviceDisconnectedObservable=new s.y$,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]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,r;let s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(r=this._devices[e])||void 0===r?void 0:r[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;null===(s=null===(r=this._devices[e])||void 0===r?void 0:r[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case r.Yi.Keyboard:case r.Yi.Mouse:this._firstDevice[e]=0;break;case r.Yi.Touch:case r.Yi.DualSense:case r.Yi.DualShock:case r.Yi.Xbox:case r.Yi.Switch:case r.Yi.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()}},9255:function(e,t,i){i.d(t,{A:function(){return allocateAndCopyTypedBuffer}});var r=i(6465);function allocateAndCopyTypedBuffer(e,t,i=!1,r){switch(e){case 3:{let e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{let e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{let e=new Int16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{let e=new Uint16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{let e=new Int32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{let e=new Uint32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{let e=new Float32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Float32Array(r)),e}}let s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}r.B.prototype._readTexturePixelsSync=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){var u,c;let d=this._gl;if(!d)throw Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let e=d.createFramebuffer();if(!e)throw Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}d.bindFramebuffer(d.FRAMEBUFFER,this._dummyFramebuffer),r>-1?d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_CUBE_MAP_POSITIVE_X+r,null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,s):d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,s);let p=void 0!==e.type?this._getWebGLTextureType(e.type):d.UNSIGNED_BYTE;return o?n||(n=allocateAndCopyTypedBuffer(e.type,4*t*i)):p===d.UNSIGNED_BYTE?(n||(n=new Uint8Array(4*t*i)),p=d.UNSIGNED_BYTE):(n||(n=new Float32Array(4*t*i)),p=d.FLOAT),a&&this.flushFramebuffer(),d.readPixels(l,h,t,i,d.RGBA,p,n),d.bindFramebuffer(d.FRAMEBUFFER,this._currentFramebuffer),n},r.B.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,n,a,o,l,h))}},68:function(e,t,i){var r=i(6465),s=i(998);r.B.prototype.createUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create uniform buffer");let r=new s.M(i);return this.bindUniformBuffer(r),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),r.references=1,r},r.B.prototype.createDynamicUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create dynamic uniform buffer");let r=new s.M(i);return this.bindUniformBuffer(r),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),r.references=1,r},r.B.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},r.B.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},r.B.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},r.B.prototype.bindUniformBlock=function(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)}},7790:function(e,t,i){i.d(t,{L:function(){return ShaderProcessor}});let ShaderCodeNode=class ShaderCodeNode{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,r,s,n,a,o,l;let h="";if(this.line){let u=this.line,c=t.processor;if(c){c.lineProcessor&&(u=c.lineProcessor(u,t.isFragment,t.processingContext));let h=null!==(r=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==r?r:"attribute",d=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(n=t.processor)||void 0===n?void 0:n.varyingFragmentKeywordName:!t.isFragment&&(null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName)?null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName:"varying";!t.isFragment&&c.attributeProcessor&&this.line.startsWith(h)?u=c.attributeProcessor(this.line,e,t.processingContext):c.varyingProcessor&&((null===(l=c.varyingCheck)||void 0===l?void 0:l.call(c,this.line,t.isFragment))||!c.varyingCheck&&this.line.startsWith(d))?u=c.varyingProcessor(this.line,t.isFragment,e,t.processingContext):c.uniformProcessor&&c.uniformRegexp&&c.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&c.uniformBufferRegexp&&c.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):c.textureProcessor&&c.textureRegexp&&c.textureRegexp.test(this.line)?u=c.textureProcessor(this.line,t.isFragment,e,t.processingContext):(c.uniformProcessor||c.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?c.uniformProcessor&&(u=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&(u=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,c.endOfUniformBufferProcessor&&(u=c.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}h+=u+"\n"}return this.children.forEach(i=>{h+=i.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}};let ShaderCodeCursor=class ShaderCodeCursor{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{let e=t.split(";");for(let t=0;t{""!==(n=n.trim())&&(i.push(n),n="")},push=e=>{rShaderDefineExpression._Stack[r],pop=()=>-1===r?"!!INVALID EXPRESSION!!":ShaderDefineExpression._Stack[r--],s=0,n="";for(;s1){for(pushOperand();-1!==r&&ShaderDefineExpression._OperatorPriority[peek()]>=ShaderDefineExpression._OperatorPriority[a];)i.push(pop());push(a),s++}else n+=t;s++}for(pushOperand();-1!==r;)"("===peek()?pop():i.push(pop());return ShaderDefineExpression._InfixToPostfixCache.size>=ShaderDefineExpression.InfixToPostfixCacheLimitSize&&ShaderDefineExpression.ClearCache(),ShaderDefineExpression._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(ShaderDefineExpression._InfixToPostfixCache.entries()).sort((e,t)=>e[1].accessTime-t[1].accessTime);for(let t=0;t":i=r>s;break;case"<":i=r=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}};var r=i(6131),s=i(5550);let n=/defined\s*?\((.+?)\)/g,a=/defined\s*?\[(.+?)\]/g,o=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,l=/__decl__/,h=/light\{X\}.(\w*)/g,u=/\{X\}/g,c=[];let ShaderProcessor=class ShaderProcessor{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,r){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));let s=this._ProcessShaderConversion(e,t,r);i(s,e)})}static PreProcess(e,t,i,r){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e));let s=this._ApplyPreProcessing(e,t,r);i(s,e)})}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;let r=t.shouldUseHighPrecisionShader;return -1===e.indexOf("precision highp float")?e=r?"precision highp float;\n"+e:"precision mediump float;\n"+e:r||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){let t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new ShaderDefineIsDefinedOperator(t[1].trim(),"!"===e[0]);let i="",r=0;for(i of["==","!=",">=","<=","<",">"])if((r=e.indexOf(i))>-1)break;if(-1===r)return new ShaderDefineIsDefinedOperator(e);let s=e.substring(0,r).trim(),n=e.substring(r+i.length).trim();return new ShaderDefineArithmeticOperator(s,i,n)}static _BuildSubExpression(e){e=e.replace(n,"defined[$1]");let t=ShaderDefineExpression.infixToPostfix(e),i=[];for(let e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;let s="&&"==e?new ShaderDefineAndOperator:new ShaderDefineOrOperator;"string"==typeof t&&(t=t.replace(a,"defined($1)")),"string"==typeof r&&(r=r.replace(a,"defined($1)")),s.leftOperand="string"==typeof r?this._ExtractOperation(r):r,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(a,"defined($1)")),"string"==typeof r?this._ExtractOperation(r):r}static _BuildExpression(e,t){let i=new ShaderCodeTestNode,r=e.substring(0,t),s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),"#ifdef"===r?i.testExpression=new ShaderDefineIsDefinedOperator(s):"#ifndef"===r?i.testExpression=new ShaderDefineIsDefinedOperator(s,!0):i.testExpression=this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let r=e.currentLine;for(;this._MoveCursor(e,i);){r=e.currentLine;let s=r.substring(0,5).toLowerCase();if("#else"===s){let i=new ShaderCodeNode;t.children.push(i),this._MoveCursor(e,i);return}if("#elif"===s){let e=this._BuildExpression(r,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;let i=e.currentLine;if(i.indexOf("#")>=0){let r=ShaderProcessor._MoveCursorRegex.exec(i);if(r&&r.length){let s=r[0];switch(s){case"#ifdef":{let r=new ShaderCodeConditionNode;t.children.push(r);let s=this._BuildExpression(i,6);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let r=new ShaderCodeConditionNode;t.children.push(r);let s=this._BuildExpression(i,7);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#if":{let r=new ShaderCodeConditionNode,s=this._BuildExpression(i,3);t.children.push(r),r.children.push(s),this._MoveCursorWithinIf(e,r,s)}}continue}}let r=new ShaderCodeNode;if(r.line=i,t.children.push(r),"#"===i[0]&&"d"===i[1]){let e=i.replace(";","").split(" ");r.additionalDefineKey=e[1],3===e.length&&(r.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){let r=new ShaderCodeNode,s=new ShaderCodeCursor;return s.lineIndex=-1,s.lines=e.split("\n"),this._MoveCursor(s,r),r.process(t,i)}static _PreparePreProcessors(e,t){var i;let r=e.defines,n={};for(let e of r){let t=e.replace("#define","").replace(";","").trim(),i=t.split(" ");n[i[0]]=i.length>1?i[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===s.x.GLSL&&(n.GL_ES="true"),n.__VERSION__=e.version,n[e.platformName]="true",t._getGlobalDefines(n),n}static _ProcessShaderConversion(e,t,i){let r=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===s.x.GLSL&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;let n=t.defines,a=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,n,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,a,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,n,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ApplyPreProcessing(e,t,i){var r,s;let n=e,a=t.defines,o=this._PreparePreProcessors(t,i);return(null===(r=t.processor)||void 0===r?void 0:r.preProcessor)&&(n=t.processor.preProcessor(n,a,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,o,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ProcessIncludes(e,t,i){let r;for(c.length=0;null!==(r=o.exec(e));)c.push(r);let s=String(e),n=[e],a=!1;for(let e of c){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(l,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),t.includesShadersStore[r]){let i=t.includesShadersStore[r];if(e[2]){let t=e[3].split(",");for(let e=0;et+"{X}")),i+=a.replace(u,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(h,(e,t)=>t+"{X}")),i=i.replace(u,r)}let s=[];for(let t of n){let r=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}else{let e=t.shadersRepository+"ShadersInclude/"+r+".fx";ShaderProcessor._FileToolsLoadFile(e,e=>{t.includesShadersStore[r]=e,this._ProcessIncludes(n.join(""),t,i)});return}}c.length=0,s=n.join(""),a?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,s,n,a){throw(0,r.S)("FileTools")}};ShaderProcessor._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/},7666:function(e,t,i){i.d(t,{C:function(){return WebGL2ShaderProcessor}});var r=i(5550);let s=/(flat\s)?\s*varying\s*.*/;let WebGL2ShaderProcessor=class WebGL2ShaderProcessor{constructor(){this.shaderLanguage=r.x.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return s.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){let r=-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("),i){let 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,(r||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else{let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}return e}}},5342:function(e,t,i){i.d(t,{B:function(){return WebGLHardwareTexture}});let WebGLHardwareTexture=class WebGLHardwareTexture{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw 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(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return null!==(i=null===(t=this._MSAARenderBuffers)||void 0===t?void 0:t[e])&&void 0!==i?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},856:function(e,t,i){i.d(t,{y:function(){return WebGLPipelineContext}});let WebGLPipelineContext=class WebGLPipelineContext{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)}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this.engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let u=this.engine.getUniforms(this,i);for(u.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l{n[e]=t}),h.getAttributes(this,a)))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setInt4(this._uniforms[e],t,i,r,s)&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setUInt4(this._uniforms[e],t,i,r,s)&&(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.toArray())&&(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){let i=this._valueCache[e];(void 0===i||i!==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,i){this._cacheFloat2(e,t,i)&&!this.engine.setFloat2(this._uniforms[e],t,i)&&(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,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setFloat3(this._uniforms[e],t,i,r)&&(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,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setFloat4(this._uniforms[e],t,i,r,s)&&(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(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}}},5410:function(e,t,i){i.d(t,{f:function(){return WebGLShaderProcessor}});var r=i(5550);let WebGLShaderProcessor=class WebGLShaderProcessor{constructor(){this.shaderLanguage=r.x.GLSL}postProcessor(e,t,i,r,s){return s.getCaps().drawBuffersExtension||(e=e.replace(/#extension.+GL_EXT_draw_buffers.+(enable|require)/g,"")),e}}},8906:function(e,t,i){i.d(t,{D:function(){return Engine}});var r=i(4800),s=i(3912),n=i(7209),a=i(6030),o=i(6131),l=i(6465),h=i(8786),u=i(7263),c=i(998),d=i(9626),p=i(5342);i(6628),i(9255),i(6529);let Engine=class Engine extends l.B{static get NpmPackage(){return l.B.NpmPackage}static get Version(){return l.B.Version}static get Instances(){return a.l.Instances}static get LastCreatedEngine(){return a.l.LastCreatedEngine}static get LastCreatedScene(){return a.l.LastCreatedScene}_createImageBitmapFromSource(e,t){let i=new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{this.createImageBitmap(s,t).then(e=>{i(e)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e});return i}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){let r=this.createCanvas(t,i),s=r.getContext("2d");if(!s)throw Error("Unable to get 2d context for resizeImageBitmap");s.drawImage(e,0,0);let n=s.getImageData(0,0,t,i).data;return n}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};let t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!Engine.audioEngine&&this._creationOptions.audioEngine&&Engine.AudioEngineFactory&&(Engine.audioEngine=Engine.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),(0,n.n5)()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&Engine._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==Engine.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;null===(e=this._onPointerLockChange)||void 0===e||e.call(this)}getAspectRatio(e,t=!1){let i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){let i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}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)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){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()}restoreStencilState(){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)}setDirectViewport(e,t,i,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((r,s)=>{this._loadFile(e,e=>{r(e)},void 0,t,i,(e,t)=>{s(t)})})}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))}setTextureFromPostProcess(e,t,i){var r;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==s?void 0:s.texture)&&void 0!==r?r:null,i)}setTextureFromPostProcessOutput(e,t,i){var r,s;this._bindTexture(e,null!==(s=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries(),e._rebuildTextures();super._rebuildBuffers()}_renderFrame(){for(let e=0;e0?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()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){!this.isFullscreen&&(this._pointerLockRequested=e,this._renderingCanvas&&Engine._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&Engine._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&Engine._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){Engine._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this.onEndFrameObservable.notifyObservers(this)}setSize(e,t,i=!1){if(!this._renderingCanvas||!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e1&&s){let t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,s),e.transformFeedback=t}return r.linkProgram(n),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,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)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){let t=++Engine._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;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,r,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),s&&s()}))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,r=0,n=0){let a=new p.B(e,this._gl),o=new s.l(this,s.S.Unknown,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=n,o.width=r,o.height=n,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,o,a,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion){d.Y.Error("WebGL 1 does not support texture comparison.");return}let i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create instance buffer");let i=new c.M(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){let r=this._gl;return new Promise((s,n)=>{let check=()=>{let a=r.clientWaitSync(e,t,0);if(a==r.WAIT_FAILED){n();return}if(a==r.TIMEOUT_EXPIRED){setTimeout(check,i);return}s()};check()})}_readPixelsAsync(e,t,i,r,s,n,a){if(this._webGLVersion<2)throw Error("_readPixelsAsync only work on WebGL2+");let o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,r,s,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);let h=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(o.flush(),this._clientWaitAsync(h,0,10).then(()=>(o.deleteSync(h),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),a))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===a.l.Instances.length&&Engine.audioEngine&&(Engine.audioEngine.dispose(),Engine.audioEngine=null);let e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),(0,n.n5)()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();let t=a.l.Instances.indexOf(this);t>=0&&a.l.Instances.splice(t,1),Engine.Instances.length||a.l.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!(0,n.CG)())return;let e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!(0,n.CG)())return;let e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=Engine.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){let t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){let e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){let t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);let i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";let r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:n,descent:n-s}}};Engine.ALPHA_DISABLE=0,Engine.ALPHA_ADD=1,Engine.ALPHA_COMBINE=2,Engine.ALPHA_SUBTRACT=3,Engine.ALPHA_MULTIPLY=4,Engine.ALPHA_MAXIMIZED=5,Engine.ALPHA_ONEONE=6,Engine.ALPHA_PREMULTIPLIED=7,Engine.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Engine.ALPHA_INTERPOLATE=9,Engine.ALPHA_SCREENMODE=10,Engine.DELAYLOADSTATE_NONE=0,Engine.DELAYLOADSTATE_LOADED=1,Engine.DELAYLOADSTATE_LOADING=2,Engine.DELAYLOADSTATE_NOTLOADED=4,Engine.NEVER=512,Engine.ALWAYS=519,Engine.LESS=513,Engine.EQUAL=514,Engine.LEQUAL=515,Engine.GREATER=516,Engine.GEQUAL=518,Engine.NOTEQUAL=517,Engine.KEEP=7680,Engine.REPLACE=7681,Engine.INCR=7682,Engine.DECR=7683,Engine.INVERT=5386,Engine.INCR_WRAP=34055,Engine.DECR_WRAP=34056,Engine.TEXTURE_CLAMP_ADDRESSMODE=0,Engine.TEXTURE_WRAP_ADDRESSMODE=1,Engine.TEXTURE_MIRROR_ADDRESSMODE=2,Engine.TEXTUREFORMAT_ALPHA=0,Engine.TEXTUREFORMAT_LUMINANCE=1,Engine.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Engine.TEXTUREFORMAT_RGB=4,Engine.TEXTUREFORMAT_RGBA=5,Engine.TEXTUREFORMAT_RED=6,Engine.TEXTUREFORMAT_R=6,Engine.TEXTUREFORMAT_RG=7,Engine.TEXTUREFORMAT_RED_INTEGER=8,Engine.TEXTUREFORMAT_R_INTEGER=8,Engine.TEXTUREFORMAT_RG_INTEGER=9,Engine.TEXTUREFORMAT_RGB_INTEGER=10,Engine.TEXTUREFORMAT_RGBA_INTEGER=11,Engine.TEXTURETYPE_UNSIGNED_BYTE=0,Engine.TEXTURETYPE_UNSIGNED_INT=0,Engine.TEXTURETYPE_FLOAT=1,Engine.TEXTURETYPE_HALF_FLOAT=2,Engine.TEXTURETYPE_BYTE=3,Engine.TEXTURETYPE_SHORT=4,Engine.TEXTURETYPE_UNSIGNED_SHORT=5,Engine.TEXTURETYPE_INT=6,Engine.TEXTURETYPE_UNSIGNED_INTEGER=7,Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Engine.TEXTURETYPE_UNSIGNED_INT_24_8=12,Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Engine.TEXTURE_NEAREST_SAMPLINGMODE=1,Engine.TEXTURE_BILINEAR_SAMPLINGMODE=2,Engine.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Engine.TEXTURE_NEAREST_LINEAR=7,Engine.TEXTURE_NEAREST_NEAREST=1,Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Engine.TEXTURE_LINEAR_LINEAR=2,Engine.TEXTURE_LINEAR_NEAREST=12,Engine.TEXTURE_EXPLICIT_MODE=0,Engine.TEXTURE_SPHERICAL_MODE=1,Engine.TEXTURE_PLANAR_MODE=2,Engine.TEXTURE_CUBIC_MODE=3,Engine.TEXTURE_PROJECTION_MODE=4,Engine.TEXTURE_SKYBOX_MODE=5,Engine.TEXTURE_INVCUBIC_MODE=6,Engine.TEXTURE_EQUIRECTANGULAR_MODE=7,Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Engine.SCALEMODE_FLOOR=1,Engine.SCALEMODE_NEAREST=2,Engine.SCALEMODE_CEILING=3,Engine._RescalePostProcessFactory=null,Engine._RenderPassIdCounter=0},6030:function(e,t,i){i.d(t,{l:function(){return EngineStore}});var r=i(4800);let EngineStore=class EngineStore{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}};EngineStore.Instances=[],EngineStore.OnEnginesDisposedObservable=new r.y$,EngineStore._LastCreatedScene=null,EngineStore.UseFallbackTexture=!0,EngineStore.FallbackTexture=""},4548:function(e,t,i){i.d(t,{Z:function(){return PerformanceConfigurator}});let PerformanceConfigurator=class PerformanceConfigurator{static SetMatrixPrecision(e){if(PerformanceConfigurator.MatrixTrackPrecisionChange=!1,e&&!PerformanceConfigurator.MatrixUse64Bits&&PerformanceConfigurator.MatrixTrackedMatrices)for(let e=0;e=h.Fz.MouseWheelX&&t.inputIndex<=h.Fz.MouseWheelZ?r.kD.POINTERWHEEL:r.kD.POINTERMOVE;s.onPointerMove&&(e=e||this._pickMove(t),s.onPointerMove(t,e,o)),e?(i=new r.R5(o,t,e),this._setRayOnPointerInfo(e,t)):(i=new r.R5(o,t,null,this),this._movePointerInfo=i),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,o)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&i._pickingAvailable&&!e.ray&&(e.ray=i.createPickingRay(t.offsetX,t.offsetY,a.y3.Identity(),i.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,i){let s=this._scene,n=new r.FV(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,e.originMesh&&(n.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable}_pickMove(e){let t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){let r=i.getEngine(),s=r.getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&s&&this._pointerOverMesh){let e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(s.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=h.Fz.Move,this._checkPrePointerObservable(e,i,r.kD.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,r.kD.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){let i;let s=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(5,o.V.CreateNew(e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(2,o.V.CreateNew(e.pickedMesh,t,e));break;case 1:i.processTrigger(4,o.V.CreateNew(e.pickedMesh,t,e));break;case 2:i.processTrigger(3,o.V.CreateNew(e.pickedMesh,t,e))}i.hasSpecificTrigger(8)&&window.setTimeout(()=>{let e=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh,!1,s.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&i&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>InputManager.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(8,o.V.CreateNew(e.pickedMesh,t)))},InputManager.LongPressDelay)}}else for(let i of s._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n=r.kD.POINTERDOWN;e?(s.onPointerDown&&s.onPointerDown(t,e,n),i=new r.R5(n,t,e),this._setRayOnPointerInfo(e,t)):i=new r.R5(n,t,null,this),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,n)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let s=new PointerEvent("pointerup",t);s.inputIndex=h.Fz.Move;let n=new _ClickInfo;i?n.doubleClick=!0:n.singleClick=!0,this._checkPrePointerObservable(e,s,r.kD.POINTERUP)||this._processPointerUp(e,s,n)}_processPointerUp(e,t,i){let s=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){let i=r.kD.POINTERPICK,n=new r.R5(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,i)}let n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(7,o.V.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(1,o.V.CreateNew(e.pickedMesh,t,e));let r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,o.V.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,o.V.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let n=new r.R5(r.kD.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,r.kD.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,r.kD.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=r.kD.POINTERTAP:i.doubleClick&&(n=r.kD.POINTERDOUBLETAP),n){let i=new r.R5(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(i,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,a=null){let c=this._scene,d=c.getEngine();a||(a=d.getInputElement()),this._alreadyAttached&&this.detachControl(),a&&(this._alreadyAttachedTo=a),this._deviceSourceManager=new u.U(d),this._initActionManager=e=>{if(!this._meshPickProceed){let t=!c.skipPointerUpPicking&&(0!==c._registeredActions||this._checkForPicking()||c.onPointerUp)?c.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c.pointerUpPredicate,c.pointerUpFastCheck,c.cameraToUseForPointers):null;this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>InputManager.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){let t=this._delayedClicks[e].evt,i=r.kD.POINTERTAP,s=new r.R5(i,t,this._currentPickResult);c.onPointerObservable.hasObservers()&&c.onPointerObservable.hasSpecificMask(i)&&c.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,n)=>{var a,o;let l=new _ClickInfo;this._currentPickResult=null;let h=null,u=e.hasSpecificMask(r.kD.POINTERPICK)||t.hasSpecificMask(r.kD.POINTERPICK)||e.hasSpecificMask(r.kD.POINTERTAP)||t.hasSpecificMask(r.kD.POINTERTAP)||e.hasSpecificMask(r.kD.POINTERDOUBLETAP)||t.hasSpecificMask(r.kD.POINTERDOUBLETAP);!u&&s.O&&(h=this._initActionManager(h,l))&&(u=h.hasPickTriggers);let c=!1;if(u){let u=i.button;if(l.hasSwiped=this._isPointerSwiping(),!l.hasSwiped){let d=!InputManager.ExclusiveDoubleClickMode;if(!d&&(d=!e.hasSpecificMask(r.kD.POINTERDOUBLETAP)&&!t.hasSpecificMask(r.kD.POINTERDOUBLETAP))&&!s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l))&&(d=!h.hasSpecificTrigger(6)),d)(Date.now()-this._previousStartingPointerTime>InputManager.DoubleClickDelay||u!==this._previousButtonPressed)&&(l.singleClick=!0,n(l,this._currentPickResult),c=!0);else{let e={evt:i,clickInfo:l,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,u,l,n),InputManager.DoubleClickDelay)};this._delayedClicks[u]=e}let p=e.hasSpecificMask(r.kD.POINTERDOUBLETAP)||t.hasSpecificMask(r.kD.POINTERDOUBLETAP);!p&&s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l))&&(p=h.hasSpecificTrigger(6)),p&&(u===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>InputManager.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>InputManager.DragMovementThreshold),d.isPointerLock&&d._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=h.Fz.MouseWheelX&&e.inputIndex<=h.Fz.MouseWheelZ?r.kD.POINTERWHEEL:r.kD.POINTERMOVE)||!c.cameraToUseForPointers&&!c.activeCamera)return;if(c.skipPointerMovePicking){this._processPointerMove(new n.p,e);return}c.pointerMovePredicate||(c.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||c.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0));let t=c._registeredActions>0||c.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;let i;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,InputManager.ExclusiveDoubleClickMode){for(let i=0;ie.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0)),this._pickedDownMesh=null,i=!c.skipPointerDownPicking&&(0!==c._registeredActions||this._checkForPicking()||c.onPointerDown)?c.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c.pointerDownPredicate,c.pointerDownFastCheck,c.cameraToUseForPointers):new n.p,this._processPointerDown(i,e))},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),c.preventDefaultOnPointerUp&&a&&(e.preventDefault(),a.focus()),this._initClickEvent(c.onPrePointerObservable,c.onPointerObservable,e,(t,i)=>{if(c.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,r.kD.POINTERUP)){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1);return}!t.hasSwiped&&(t.singleClick&&c.onPrePointerObservable.hasSpecificMask(r.kD.POINTERTAP)&&this._checkPrePointerObservable(null,e,r.kD.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&c.onPrePointerObservable.hasSpecificMask(r.kD.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,r.kD.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[e.pointerId]){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(c.cameraToUseForPointers||c.activeCamera)&&(c.pointerUpPredicate||(c.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0)),!this._meshPickProceed&&(s.O&&s.O.HasTriggers||this._checkForPicking()||c.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=e=>{let t=l.OG.KEYDOWN;if(c.onPreKeyboardObservable.hasObservers()){let i=new l.WZ(t,e);if(c.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(c.onKeyboardObservable.hasObservers()){let i=new l.NG(t,e);c.onKeyboardObservable.notifyObservers(i,t)}c.actionManager&&c.actionManager.processTrigger(14,o.V.CreateNewFromScene(c,e))},this._onKeyUp=e=>{let t=l.OG.KEYUP;if(c.onPreKeyboardObservable.hasObservers()){let i=new l.WZ(t,e);if(c.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(c.onKeyboardObservable.hasObservers()){let i=new l.NG(t,e);c.onKeyboardObservable.notifyObservers(i,t)}c.actionManager&&c.actionManager.processTrigger(15,o.V.CreateNewFromScene(c,e))},this._deviceSourceManager.onDeviceConnectedObservable.add(r=>{r.deviceType===h.Yi.Mouse?r.onInputChangedObservable.add(s=>{s.inputIndex===h.Fz.LeftClick||s.inputIndex===h.Fz.MiddleClick||s.inputIndex===h.Fz.RightClick||s.inputIndex===h.Fz.BrowserBack||s.inputIndex===h.Fz.BrowserForward?t&&1===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===h.Fz.Move?this._onPointerMove(s):(s.inputIndex===h.Fz.MouseWheelX||s.inputIndex===h.Fz.MouseWheelY||s.inputIndex===h.Fz.MouseWheelZ)&&this._onPointerMove(s))}):r.deviceType===h.Yi.Touch?r.onInputChangedObservable.add(s=>{s.inputIndex===h.Fz.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===h.Fz.Move&&this._onPointerMove(s)}):r.deviceType===h.Yi.Keyboard&&r.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,i,r){let s;if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let n=this._meshUnderPointerId[t];n&&(s=n._getActionManagerForTrigger(10))&&s.processTrigger(10,o.V.CreateNew(n,r,{pointerId:t})),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,(s=e._getActionManagerForTrigger(9))&&s.processTrigger(9,o.V.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){for(let t in this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null),this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}};InputManager.DragMovementThreshold=10,InputManager.LongPressDelay=500,InputManager.DoubleClickDelay=300,InputManager.ExclusiveDoubleClickMode=!1},6972:function(e,t,i){i.d(t,{m:function(){return LightConstants}});let LightConstants=class LightConstants{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}};LightConstants.FALLOFF_DEFAULT=0,LightConstants.FALLOFF_PHYSICAL=1,LightConstants.FALLOFF_GLTF=2,LightConstants.FALLOFF_STANDARD=3,LightConstants.LIGHTMAP_DEFAULT=0,LightConstants.LIGHTMAP_SPECULAR=1,LightConstants.LIGHTMAP_SHADOWSONLY=2,LightConstants.INTENSITYMODE_AUTOMATIC=0,LightConstants.INTENSITYMODE_LUMINOUSPOWER=1,LightConstants.INTENSITYMODE_LUMINOUSINTENSITY=2,LightConstants.INTENSITYMODE_ILLUMINANCE=3,LightConstants.INTENSITYMODE_LUMINANCE=4,LightConstants.LIGHTTYPEID_POINTLIGHT=0,LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT=1,LightConstants.LIGHTTYPEID_SPOTLIGHT=2,LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT=3},2697:function(e,t,i){i.d(t,{Z:function(){return SceneLoaderFlags}});let SceneLoaderFlags=class SceneLoaderFlags{static get ForceFullSceneLoadingForIncremental(){return SceneLoaderFlags._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){SceneLoaderFlags._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return SceneLoaderFlags._ShowLoadingScreen}static set ShowLoadingScreen(e){SceneLoaderFlags._ShowLoadingScreen=e}static get loggingLevel(){return SceneLoaderFlags._LoggingLevel}static set loggingLevel(e){SceneLoaderFlags._LoggingLevel=e}static get CleanBoneMatrixWeights(){return SceneLoaderFlags._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){SceneLoaderFlags._CleanBoneMatrixWeights=e}};SceneLoaderFlags._ForceFullSceneLoadingForIncremental=!1,SceneLoaderFlags._ShowLoadingScreen=!0,SceneLoaderFlags._CleanBoneMatrixWeights=!1,SceneLoaderFlags._LoggingLevel=0},3912:function(e,t,i){i.d(t,{S:function(){return s},l:function(){return InternalTexture}});var r,s,n=i(4800),a=i(7584);(r=s||(s={}))[r.Unknown=0]="Unknown",r[r.Url=1]="Url",r[r.Temp=2]="Temp",r[r.Raw=3]="Raw",r[r.Dynamic=4]="Dynamic",r[r.RenderTarget=5]="RenderTarget",r[r.MultiRenderTarget=6]="MultiRenderTarget",r[r.Cube=7]="Cube",r[r.CubeRaw=8]="CubeRaw",r[r.CubePrefiltered=9]="CubePrefiltered",r[r.Raw3D=10]="Raw3D",r[r.Raw2DArray=11]="Raw2DArray",r[r.DepthStencil=12]="DepthStencil",r[r.CubeRawRGBD=13]="CubeRawRGBD",r[r.Depth=14]="Depth";let InternalTexture=class InternalTexture extends a.a{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,i=!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 n.y$,this.onErrorObservable=new n.y$,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=s.Unknown,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._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._engine=e,this._source=t,this._uniqueId=InternalTexture._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var e;let t;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){let e=this.onRebuildCallback(this),swapAndSetIsReady=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};e.isAsync?e.proxy.then(swapAndSetIsReady):swapAndSetIsReady(e.proxy);return}switch(this.source){case s.Temp:break;case s.Url:t=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e: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);return;case s.Raw:(t=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,void 0,this._useSRGBBuffer))._swapAndDie(this,!1),this.isReady=!0;break;case s.Raw3D:(t=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case s.Raw2DArray:(t=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case s.Dynamic:(t=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this,!1),this._engine.updateDynamicTexture(this,this._engine.getRenderingCanvas(),this.invertY,void 0,void 0,!0);break;case s.Cube:t=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{t._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case s.CubeRaw:(t=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this,!1),this.isReady=!0;break;case s.CubeRawRGBD:return;case s.CubePrefiltered:(t=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,e=>{e&&e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension))._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var i;null===(i=this._hardwareTexture)||void 0===i||i.setUsage(e._source,this.generateMipMaps,this.isCube,this.width,this.height),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);let r=this._engine.getLoadedTexturesCache(),s=r.indexOf(this);-1!==s&&r.splice(s,1),-1===(s=r.indexOf(e))&&r.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null)}};InternalTexture._Counter=0},7584:function(e,t,i){i.d(t,{a:function(){return TextureSampler}});let TextureSampler=class TextureSampler{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=1,t=1,i=1,r=1,s=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,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}}},6962:function(e,t,i){function addClipPlaneUniforms(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")}function prepareStringDefinesForClipPlanes(e,t,i){var r,s,n,a,o,l;let h=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),u=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),c=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),d=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),p=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),u&&i.push("#define CLIPPLANE2"),c&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),_&&i.push("#define CLIPPLANE6")}function prepareDefinesForClipPlanes(e,t,i){var r,s,n,a,o,l;let h=!1,u=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),p=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),_=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==u&&(i.CLIPPLANE=u,h=!0),i.CLIPPLANE2!==c&&(i.CLIPPLANE2=c,h=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,h=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,h=!0),i.CLIPPLANE5!==_&&(i.CLIPPLANE5=_,h=!0),i.CLIPPLANE6!==f&&(i.CLIPPLANE6=f,h=!0),h}function bindClipPlane(e,t,i){var r,s,n,a,o,l;let h=null!==(r=t.clipPlane)&&void 0!==r?r:i.clipPlane;setClipPlane(e,"vClipPlane",h),setClipPlane(e,"vClipPlane2",h=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2),setClipPlane(e,"vClipPlane3",h=null!==(n=t.clipPlane3)&&void 0!==n?n:i.clipPlane3),setClipPlane(e,"vClipPlane4",h=null!==(a=t.clipPlane4)&&void 0!==a?a:i.clipPlane4),setClipPlane(e,"vClipPlane5",h=null!==(o=t.clipPlane5)&&void 0!==o?o:i.clipPlane5),setClipPlane(e,"vClipPlane6",h=null!==(l=t.clipPlane6)&&void 0!==l?l:i.clipPlane6)}function setClipPlane(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{AN:function(){return prepareDefinesForClipPlanes},an:function(){return bindClipPlane},lK:function(){return prepareStringDefinesForClipPlanes},qx:function(){return addClipPlaneUniforms}})},9087:function(e,t,i){i.d(t,{U:function(){return ColorCurves}});var r=i(9956),s=i(1760),n=i(2983);let ColorCurves=class ColorCurves{constructor(){this._dirty=!0,this._tempColor=new n.HE(0,0,0,0),this._globalCurve=new n.HE(0,0,0,0),this._highlightsCurve=new n.HE(0,0,0,0),this._midtonesCurve=new n.HE(0,0,0,0),this._shadowsCurve=new n.HE(0,0,0,0),this._positiveCurve=new n.HE(0,0,0,0),this._negativeCurve=new n.HE(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,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="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(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,r,s){null!=e&&(e=ColorCurves._Clamp(e,0,360),t=ColorCurves._Clamp(t,-100,100),i=ColorCurves._Clamp(i,-100,100),r=ColorCurves._Clamp(r,-100,100),t=.5*ColorCurves._ApplyColorGradingSliderNonlinear(t),r=ColorCurves._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),ColorCurves._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){let t=Math.abs(e/=100);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100}static _FromHSBToRef(e,t,i,r){let s=ColorCurves._Clamp(e,0,360),n=ColorCurves._Clamp(t/100,0,1),a=ColorCurves._Clamp(i/100,0,1);if(0===n)r.r=a,r.g=a,r.b=a;else{s/=60;let e=Math.floor(s),t=s-e,i=a*(1-n),o=a*(1-n*t),l=a*(1-n*(1-t));switch(e){case 0:r.r=a,r.g=l,r.b=i;break;case 1:r.r=o,r.g=a,r.b=i;break;case 2:r.r=i,r.g=a,r.b=l;break;case 3:r.r=i,r.g=o,r.b=a;break;case 4:r.r=l,r.g=i,r.b=a;break;default:r.r=a,r.g=i,r.b=o}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return s.p4.Clone(()=>new ColorCurves,this)}serialize(){return s.p4.Serialize(this)}static Parse(e){return s.p4.Parse(()=>new ColorCurves,e,null,null)}};(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_globalHue",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_globalDensity",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_globalSaturation",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_globalExposure",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_highlightsHue",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_highlightsDensity",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_highlightsSaturation",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_highlightsExposure",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_midtonesHue",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_midtonesDensity",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_midtonesSaturation",void 0),(0,r.gn)([(0,s.qC)()],ColorCurves.prototype,"_midtonesExposure",void 0),s.p4._ColorCurvesParser=ColorCurves.Parse},1606:function(e,t,i){i.d(t,{q:function(){return DrawWrapper}});let DrawWrapper=class DrawWrapper{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(r=this.drawContext)||void 0===r||r.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}}},1088:function(e,t,i){i.d(t,{Q:function(){return Effect}});var r=i(4800),s=i(7209),n=i(9626),a=i(7790),o=i(513),l=i(5550);let Effect=class Effect{static get ShadersRepository(){return o.v.ShadersRepository}static set ShadersRepository(e){o.v.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new r.y$),this._onBindObservable}constructor(e,t,i,s=null,n,a=null,o=null,h=null,u=null,c,d="",p=l.x.GLSL){var _,f,m;if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new r.y$,this.onErrorObservable=new r.y$,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!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=d,t.attributes){if(this._engine=i,this._attributesNames=t.attributes,this._uniformsNames=t.uniformsNames.concat(t.samplers),this._samplerList=t.samplers.slice(),this.defines=t.defines,this.onError=t.onError,this.onCompiled=t.onCompiled,this._fallbacks=t.fallbacks,this._indexParameters=t.indexParameters,this._transformFeedbackVaryings=t.transformFeedbackVaryings||null,this._multiTarget=!!t.multiTarget,this._shaderLanguage=null!==(_=t.shaderLanguage)&&void 0!==_?_:l.x.GLSL,t.uniformBuffersNames){this._uniformBuffersNamesList=t.uniformBuffersNames.slice();for(let e=0;e{if(u[0]&&u[1]){h.isFragment=!0;let[e,i]=u;a.L.Process(i,h,(i,r)=>{this._fragmentSourceCodeBeforeMigration=r,this._processFinalCode&&(i=this._processFinalCode("fragment",i));let s=a.L.Finalize(e,i,h);h=null,this._useFinalCode(s.vertexCode,s.fragmentCode,n,t)},this._engine)}};this._loadShader(i,"Vertex","",e=>{a.L.Initialize(h),a.L.Process(e,h,(t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,this._processFinalCode&&(t=this._processFinalCode("vertex",t)),u[0]=t,shadersLoaded()},this._engine)}),this._loadShader(r,"Fragment","Pixel",e=>{this._rawFragmentSourceCode=e,u[1]=e,shadersLoaded()})}_useFinalCode(e,t,i,r=!1){if(i){let r=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(r)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){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){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let n;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=(0,s.v)(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}let a=o.v.GetShadersStore(this._shaderLanguage);if(a[e+t+"Shader"]){r(a[e+t+"Shader"]);return}if(i&&a[e+i+"Shader"]){r(a[e+i+"Shader"]);return}n="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:o.v.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",r)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{let e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,r);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?n._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,rebuildRebind,null,this._transformFeedbackVaryings,this._key):n._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,rebuildRebind,r,this._transformFeedbackVaryings,this._key),n._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,i,this._attributes),i)for(let e=0;e=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,r,s;this._compilationError=e.message;let a=this._attributesNames,o=this._fallbacks;if(n.Y.Error("Unable to compile effect:"),n.Y.Error("Uniforms: "+this._uniformsNames.map(function(e){return" "+e})),n.Y.Error("Attributes: "+a.map(function(e){return" "+e})),n.Y.Error("Defines:\n"+this.defines),Effect.LogShaderCodeOnCompilationError){let e=null,t=null,a=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([a,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),a&&(n.Y.Error("Vertex code:"),n.Y.Error(a))),(null===(r=this._pipelineContext)||void 0===r?void 0:r._getFragmentShaderCode())&&([a,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),a&&(n.Y.Error("Fragment code:"),n.Y.Error(a))),e&&n.Y.Error(e),t&&n.Y.Error(t)}n.Y.Error("Error: "+this._compilationError);let notifyErrors=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,notifyErrors()),o?(this._pipelineContext=null,o.hasMoreFallbacks?(this._allFallbacksProcessed=!1,n.Y.Error("Trying next fallback."),this.defines=o.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,notifyErrors(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||notifyErrors())}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)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){let i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){let r=this._samplerList.indexOf(e);for(let e=1;enew ImageProcessingConfiguration,this)}serialize(){return s.p4.Serialize(this)}static Parse(e){let t=s.p4.Parse(()=>new ImageProcessingConfiguration,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}};ImageProcessingConfiguration.TONEMAPPING_STANDARD=0,ImageProcessingConfiguration.TONEMAPPING_ACES=1,ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY=0,ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE=1,(0,r.gn)([(0,s.N$)()],ImageProcessingConfiguration.prototype,"colorCurves",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_colorCurvesEnabled",void 0),(0,r.gn)([(0,s.oU)("colorGradingTexture")],ImageProcessingConfiguration.prototype,"_colorGradingTexture",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_colorGradingEnabled",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_colorGradingWithGreenDepth",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_colorGradingBGR",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_exposure",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_toneMappingEnabled",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_toneMappingType",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_contrast",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteStretch",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteCenterX",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteCenterY",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteWeight",void 0),(0,r.gn)([(0,s.XX)()],ImageProcessingConfiguration.prototype,"vignetteColor",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"vignetteCameraFov",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_vignetteBlendMode",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_vignetteEnabled",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_ditheringEnabled",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_ditheringIntensity",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_skipFinalColorClamp",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_applyByPostProcess",void 0),(0,r.gn)([(0,s.qC)()],ImageProcessingConfiguration.prototype,"_isEnabled",void 0),s.p4._ImageProcessingConfigurationParser=ImageProcessingConfiguration.Parse},2515:function(e,t,i){i.d(t,{F:function(){return Material}});var r=i(9956),s=i(1760),n=i(5132),a=i(4800),o=i(6030),l=i(1091),h=i(9691),u=i(9626),c=i(1564),d=i(3385),p=i(1606);let MaterialStencilState=class MaterialStencilState{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}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){s.p4.Clone(()=>e,this)}serialize(){return s.p4.Serialize(this)}parse(e,t,i){s.p4.Parse(()=>this,e,t,i)}};(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"func",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"funcRef",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"funcMask",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"opStencilFail",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"opDepthFail",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"opStencilDepthPass",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"mask",null),(0,r.gn)([(0,s.qC)()],MaterialStencilState.prototype,"enabled",null);var _=i(6540),f=i(4885);let Material=class Material{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(1===t||1===e)&&this.markAsDirty(Material.MiscDirtyFlag+Material.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(Material.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(Material.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 a.y$),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 a.y$),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new a.y$),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(Material.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(Material.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case Material.WireFrameFillMode:case Material.LineListDrawMode:case Material.LineLoopDrawMode:case Material.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?Material.WireFrameFillMode:Material.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case Material.PointFillMode:case Material.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?Material.PointFillMode:Material.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(Material.MiscDirtyFlag))}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!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.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new a.y$,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,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 MaterialStencilState,this._useUBO=!1,this._fillMode=Material.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=()=>void 0,this._callbackPluginEventIsReadyForSubMesh=()=>void 0,this._callbackPluginEventPrepareDefines=()=>void 0,this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>void 0,this._callbackPluginEventHardBindForSubMesh=()=>void 0,this._callbackPluginEventBindForSubMesh=()=>void 0,this._callbackPluginEventHasRenderTargetTextures=()=>void 0,this._callbackPluginEventFillRenderTargetTextures=()=>void 0,this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;let r=t||o.l.LastCreatedScene;if(!r)return;this._scene=r,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||n.w1.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new p.q(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=Material.ClockWiseSideOrientation:this.sideOrientation=Material.CounterClockWiseSideOrientation,this._uniformBuffer=new h.M(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),Material.OnEventObservable.notifyObservers(this,f.S.Created)}toString(e){let t="Name: "+this.name;return t}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,i){let r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===Material.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===Material.MATERIAL_OPAQUE||this._transparencyMode===Material.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){let t=this.getScene().meshes;for(let i of t)if(i.subMeshes)for(let t of i.subMeshes)t.getMaterial()===this&&t.effect&&(t.effect._wasPreviouslyReady=!1,t.effect._wasPreviouslyUsingInstances=null,t.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(Material.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),r=null==t?this.sideOrientation:t,s=r===Material.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,s,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),s}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(f.S.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i.effect;r&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,d.G.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){let e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){let e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){if(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction){let e=this._scene.getEngine();e.setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){let e=this._scene.getEngine();e.setDepthWrite(this._cachedDepthWriteState)}if(this.disableColorWrite){let e=this._scene.getEngine();e.setColorWrite(this._cachedColorWriteState)}}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(f.S.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(f.S.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(f.S.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),Material._parsePlugins(i,e,this._scene,t),this.pluginManager)for(let t of this.pluginManager._plugins){let i=e.pluginManager.getPlugin(t.name);t.copyTo(i)}}getBindedMeshes(){if(this.meshMap){let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}{let e=this._scene.meshes;return e.filter(e=>e.material===this)}}forceCompilation(e,t,i,r){let s=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let checkReady=()=>{if(!this._scene||!this._scene.getEngine())return;let i=n.clipPlane;if(s.clipPlane&&(n.clipPlane=new c.J(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){let t=new l.P(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(checkReady,16)))}i&&(this.allowShaderHotSwapping=a,n&&r&&r(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(checkReady,16);s.clipPlane&&(n.clipPlane=i)};checkReady()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,e=>{r(e)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(Material._DirtyCallbackArray.length=0,e&Material.TextureDirtyFlag&&Material._DirtyCallbackArray.push(Material._TextureDirtyCallBack),e&Material.LightDirtyFlag&&Material._DirtyCallbackArray.push(Material._LightsDirtyCallBack),e&Material.FresnelDirtyFlag&&Material._DirtyCallbackArray.push(Material._FresnelDirtyCallBack),e&Material.AttributesDirtyFlag&&Material._DirtyCallbackArray.push(Material._AttributeDirtyCallBack),e&Material.MiscDirtyFlag&&Material._DirtyCallbackArray.push(Material._MiscDirtyCallBack),e&Material.PrePassDirtyFlag&&Material._DirtyCallbackArray.push(Material._PrePassDirtyCallBack),Material._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(Material._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){let e=this.getScene().meshes;for(let t of e)if(t.subMeshes)for(let e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let t=this.getScene().meshes;for(let i of t)if(i.subMeshes){for(let t of i.subMeshes)if(t.getMaterial(!1)===this)for(let i of t._drawWrappers)i&&i.defines&&i.defines.markAllAsDirty&&this._materialContext===i.materialContext&&e(i.defines)}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(Material._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(Material._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(Material._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(Material._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(Material._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(Material._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(Material._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(Material._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(Material._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==_.a.BackwardCompatible){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(f.S.Disposed,this._eventInfo),this._parentContainer){let e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i){if(this.meshMap)for(let t in this.meshMap){let i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else{let t=r.meshes;for(let i of t)i.material!==this||i.sourceMesh||(i.material=null,this.releaseVertexArrayObject(i,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){let i=e.geometry;if(i){if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(let r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){let e=s.p4.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(let t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return u.Y.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";let r=n.w1.Instantiate(e.customType),s=r.Parse(e,t,i);return s._loadedUniqueId=e.uniqueId,s}static _parsePlugins(e,t,i,r){var s;if(e.plugins)for(let a in e.plugins){let o=e.plugins[a],l=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(o.name);if(!l){let e=n.w1.Instantiate("BABYLON."+a);e&&(l=new e(t))}null==l||l.parse(o,i,r)}}};Material.TriangleFillMode=0,Material.WireFrameFillMode=1,Material.PointFillMode=2,Material.PointListDrawMode=3,Material.LineListDrawMode=4,Material.LineLoopDrawMode=5,Material.LineStripDrawMode=6,Material.TriangleStripDrawMode=7,Material.TriangleFanDrawMode=8,Material.ClockWiseSideOrientation=0,Material.CounterClockWiseSideOrientation=1,Material.TextureDirtyFlag=1,Material.LightDirtyFlag=2,Material.FresnelDirtyFlag=4,Material.AttributesDirtyFlag=8,Material.MiscDirtyFlag=16,Material.PrePassDirtyFlag=32,Material.AllDirtyFlag=63,Material.MATERIAL_OPAQUE=0,Material.MATERIAL_ALPHATEST=1,Material.MATERIAL_ALPHABLEND=2,Material.MATERIAL_ALPHATESTANDBLEND=3,Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,Material.MATERIAL_NORMALBLENDMETHOD_RNM=1,Material.OnEventObservable=new a.y$,Material._AllDirtyCallBack=e=>e.markAllAsDirty(),Material._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),Material._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),Material._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),Material._MiscDirtyCallBack=e=>e.markAsMiscDirty(),Material._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),Material._LightsDirtyCallBack=e=>e.markAsLightDirty(),Material._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),Material._FresnelAndMiscDirtyCallBack=e=>{Material._FresnelDirtyCallBack(e),Material._MiscDirtyCallBack(e)},Material._TextureAndMiscDirtyCallBack=e=>{Material._TextureDirtyCallBack(e),Material._MiscDirtyCallBack(e)},Material._DirtyCallbackArray=[],Material._RunDirtyCallBacks=e=>{for(let t of Material._DirtyCallbackArray)t(e)},(0,r.gn)([(0,s.qC)()],Material.prototype,"id",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"uniqueId",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"name",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"metadata",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"checkReadyOnEveryCall",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"checkReadyOnlyOnce",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"state",void 0),(0,r.gn)([(0,s.qC)("alpha")],Material.prototype,"_alpha",void 0),(0,r.gn)([(0,s.qC)("backFaceCulling")],Material.prototype,"_backFaceCulling",void 0),(0,r.gn)([(0,s.qC)("cullBackFaces")],Material.prototype,"_cullBackFaces",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"sideOrientation",void 0),(0,r.gn)([(0,s.qC)("alphaMode")],Material.prototype,"_alphaMode",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"_needDepthPrePass",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"disableDepthWrite",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"disableColorWrite",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"forceDepthWrite",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"depthFunction",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"separateCullingPass",void 0),(0,r.gn)([(0,s.qC)("fogEnabled")],Material.prototype,"_fogEnabled",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"pointSize",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"zOffset",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"zOffsetUnits",void 0),(0,r.gn)([(0,s.qC)()],Material.prototype,"pointsCloud",null),(0,r.gn)([(0,s.qC)()],Material.prototype,"fillMode",null),(0,r.gn)([(0,s.qC)()],Material.prototype,"transparencyMode",null)},5377:function(e,t,i){i.d(t,{H:function(){return MaterialDefines}});let MaterialDefines=class MaterialDefines{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(let 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(){for(let e of(this._keys.length=0,Object.keys(this)))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(let 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;tthis._setDefaultValue(e))}_setDefaultValue(e){var t,i,r,s,n;let a=null!==(r=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==r?r:typeof this[e],o=null===(n=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===n?void 0:n.default;switch(a){case"number":this[e]=null!=o?o:0;break;case"string":this[e]=null!=o?o:"";break;default:this[e]=null!=o&&o}}toString(){let e="";for(let t=0;t0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){let i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!i&&!!i.isEnabled}static PrepareDefinesForAttributes(e,t,i,r,s=!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(o.o.NormalKind),t._needNormals&&e.isVerticesDataPresent(o.o.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){let i=e.useVertexColors&&e.isVerticesDataPresent(o.o.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent(o.o.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){let i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){let r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(r!==t.ORDER_INDEPENDENT_TRANSPARENCY||s!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){let r=t.PREPASS;if(!t._arePrePassDirty)return;let s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i0&&(a.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=l.m.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==l.m.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}static PrepareDefinesForLights(e,t,i,r,s=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0,o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(let n of t.lightSources)if(this.PrepareDefinesForLight(e,t,n,a,i,r,o),++a===s)break}i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e0&&(s=r+n,t.addFallback(s,"LIGHT"+n)),!e.SHADOWS&&(e["SHADOW"+n]&&t.addFallback(r,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(r,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(r,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(r,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(r,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(r,"SHADOWCLOSEESM"+n));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){let s=i.NUM_MORPH_INFLUENCERS;if(s>0&&a.l.LastCreatedEngine){let n=a.l.LastCreatedEngine.getCaps().maxVertexAttribs,l=t.morphTargetManager;if(null==l?void 0:l.isUsingTextureForTargets)return;let h=l&&l.supportsNormals&&i.NORMAL,u=l&&l.supportsTangents&&i.TANGENT,c=l&&l.supportsUVs&&i.UV1;for(let i=0;in&&r.Y.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){let r=i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES;r&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,r){i.NUM_BONE_INFLUENCERS>0&&(r.addCPUSkinningFallback(0,t),e.push(o.o.MatricesIndicesKind),e.push(o.o.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(o.o.MatricesIndicesExtraKind),e.push(o.o.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(o.o.ColorInstanceKind)}static PushAttributesForInstances(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"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,r,s,n=!0){e._bindLight(t,i,r,s,n)}static BindLights(e,t,i,r,s=4){let n=Math.min(t.lightSources.length,s);for(let s=0;s-1){let i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{let s=r.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),MaterialHelper._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){let i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){let e=i.activeCamera;e.mode===s.V.ORTHOGRAPHIC_CAMERA&&r.Y.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}};MaterialHelper._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},MaterialHelper._TempFogColor=h.Wo.Black()},4885:function(e,t,i){var r,s;i.d(t,{S:function(){return r}}),(s=r||(r={}))[s.Created=1]="Created",s[s.Disposed=2]="Disposed",s[s.GetDefineNames=4]="GetDefineNames",s[s.PrepareUniformBuffer=8]="PrepareUniformBuffer",s[s.IsReadyForSubMesh=16]="IsReadyForSubMesh",s[s.PrepareDefines=32]="PrepareDefines",s[s.BindForSubMesh=64]="BindForSubMesh",s[s.PrepareEffect=128]="PrepareEffect",s[s.GetAnimatables=256]="GetAnimatables",s[s.GetActiveTextures=512]="GetActiveTextures",s[s.HasTexture=1024]="HasTexture",s[s.FillRenderTargetTextures=2048]="FillRenderTargetTextures",s[s.HasRenderTargetTextures=4096]="HasRenderTargetTextures",s[s.HardBindForSubMesh=8192]="HardBindForSubMesh"},5461:function(e,t,i){i.d(t,{G:function(){return MultiMaterial}});var r=i(2515),s=i(1803),n=i(3048);let MultiMaterial=class MultiMaterial extends r.F{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){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}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){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new MultiMaterial(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,s.$&&s.$.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(e=>i.subMaterials.push(t.getLastMaterialById(e))),i}};(0,n.H)("BABYLON.MultiMaterial",MultiMaterial)},5550:function(e,t,i){var r,s;i.d(t,{x:function(){return r}}),(s=r||(r={}))[s.GLSL=0]="GLSL",s[s.WGSL=1]="WGSL"},9691:function(e,t,i){i.d(t,{M:function(){return UniformBuffer}});var r=i(9626),s=i(5132);i(68);let UniformBuffer=class UniformBuffer{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=r?r:"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){let e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let i=this._uniformLocationPointer-e;for(let e=0;e0){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:i},16==t)t*=i;else{let e=4-t;t=t*i+e*i}r=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(UniformBuffer._UpdatedUbosInFrame[this._name]||(UniformBuffer._UpdatedUbosInFrame[this._name]=0),UniformBuffer._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer){r.Y.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e=0&&n<=1?(o=s,l=a):n>=1&&n<=2?(o=a,l=s):n>=2&&n<=3?(l=s,h=a):n>=3&&n<=4?(l=a,h=s):n>=4&&n<=5?(o=a,h=s):n>=5&&n<=6&&(o=s,h=a);let u=i-s;r.set(o+u,l+u,h+u)}static FromHSV(e,t,i){let r=new Color3(0,0,0);return Color3.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new Color3(0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return Color3.FromInts(t,i,r)}static FromArray(e,t=0){return new Color3(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new Color3(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new Color3(0,0,0);return Color3.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,c=e.r*o+i.r*l+t.r*h+r.r*u,d=e.g*o+i.g*l+t.g*h+r.g*u,p=e.b*o+i.b*l+t.b*h+r.b*u;return new Color3(c,d,p)}static Hermite1stDerivative(e,t,i,r,s){let n=Color3.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b}static Red(){return new Color3(1,0,0)}static Green(){return new Color3(0,1,0)}static Blue(){return new Color3(0,0,1)}static Black(){return new Color3(0,0,0)}static get BlackReadOnly(){return Color3._BlackReadOnly}static White(){return new Color3(1,1,1)}static Purple(){return new Color3(.5,0,.5)}static Magenta(){return new Color3(1,0,1)}static Yellow(){return new Color3(1,1,0)}static Gray(){return new Color3(.5,.5,.5)}static Teal(){return new Color3(0,1,1)}static Random(){return new Color3(Math.random(),Math.random(),Math.random())}};Color3._BlackReadOnly=Color3.Black();let Color4=class Color4{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}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 Color4.FromArrayToRef(e,t,this),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 Color4(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new Color4(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,this}scale(e){return new Color4(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=r.R.Clamp(this.r,e,t),i.g=r.R.Clamp(this.g,e,t),i.b=r.R.Clamp(this.b,e,t),i.a=r.R.Clamp(this.a,e,t),this}multiply(e){return new Color4(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}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 397*(e=397*(e=397*e^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)}clone(){return new Color4(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}toHexString(e=!1){let t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+r.R.ToHex(t)+r.R.ToHex(i)+r.R.ToHex(s);let n=Math.round(255*this.a);return"#"+r.R.ToHex(t)+r.R.ToHex(i)+r.R.ToHex(s)+r.R.ToHex(n)}toLinearSpace(e=!1){let t=new Color4;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=colorChannelToLinearSpaceExact(this.r),e.g=colorChannelToLinearSpaceExact(this.g),e.b=colorChannelToLinearSpaceExact(this.b)):(e.r=colorChannelToLinearSpace(this.r),e.g=colorChannelToLinearSpace(this.g),e.b=colorChannelToLinearSpace(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new Color4;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=colorChannelToGammaSpaceExact(this.r),e.g=colorChannelToGammaSpaceExact(this.g),e.b=colorChannelToGammaSpaceExact(this.b)):(e.r=colorChannelToGammaSpace(this.r),e.g=colorChannelToGammaSpace(this.g),e.b=colorChannelToGammaSpace(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new Color4(0,0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return Color4.FromInts(t,i,r,s)}static Lerp(e,t,i){let r=new Color4(0,0,0,0);return Color4.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,c=e.r*o+i.r*l+t.r*h+r.r*u,d=e.g*o+i.g*l+t.g*h+r.g*u,p=e.b*o+i.b*l+t.b*h+r.b*u,_=e.a*o+i.a*l+t.a*h+r.a*u;return new Color4(c,d,p,_)}static Hermite1stDerivative(e,t,i,r,s){let n=new Color4;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b,n.a=(a-s)*6*e.a+(3*a-4*s+1)*t.a+(-a+s)*6*i.a+(3*a-2*s)*r.a}static FromColor3(e,t=1){return new Color4(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new Color4(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new Color4(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){let t=[];for(let i=0;inew Color4(0,0,0,0)),(0,a.H)("BABYLON.Color3",Color3),(0,a.H)("BABYLON.Color4",Color4)},9806:function(e,t,i){i.d(t,{Nn:function(){return s},Q_:function(){return n},kn:function(){return a},zp:function(){return r}});let r=1/2.2,s=2.2,n=(1+Math.sqrt(5))/2,a=.001},2975:function(e,t,i){i.d(t,{i:function(){return Frustum}});var r=i(1564);let Frustum=class Frustum{static GetPlanes(e){let t=[];for(let e=0;e<6;e++)t.push(new r.J(0,0,0,0));return Frustum.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){Frustum.GetNearPlaneToRef(e,t[0]),Frustum.GetFarPlaneToRef(e,t[1]),Frustum.GetLeftPlaneToRef(e,t[2]),Frustum.GetRightPlaneToRef(e,t[3]),Frustum.GetTopPlaneToRef(e,t[4]),Frustum.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(0>t[i].dotCoordinate(e))return!1;return!0}}},7383:function(e,t,i){i.d(t,{k:function(){return extractMinAndMax},y:function(){return extractMinAndMaxIndexed}});var r=i(9956),s=i(78),n=i(1760);let MathHelpers=class MathHelpers{static extractMinAndMaxIndexed(e,t,i,r,s,n){for(let a=i;a!Array.isArray(e)&&!Array.isArray(t))],MathHelpers,"extractMinAndMaxIndexed",null),(0,r.gn)([n.G6.filter((...[e])=>!Array.isArray(e))],MathHelpers,"extractMinAndMax",null)},1564:function(e,t,i){i.d(t,{J:function(){return Plane}});var r=i(78);let Plane=class Plane{constructor(e,t,i,s){this.normal=new r.P(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new Plane(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){return 397*this.normal.getHashCode()^(0|this.d)}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),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){let t=Plane._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,s=this.normal.y,n=this.normal.z,a=this.d,o=r*i[0]+s*i[1]+n*i[2]+a*i[3],l=r*i[4]+s*i[5]+n*i[6]+a*i[7],h=r*i[8]+s*i[9]+n*i[10]+a*i[11],u=r*i[12]+s*i[13]+n*i[14]+a*i[15];return new Plane(o,l,h,u)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r;let s=t.x-e.x,n=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,u=n*h-a*l,c=a*o-s*h,d=s*l-n*o,p=Math.sqrt(u*u+c*c+d*d);return r=0!==p?1/p:0,this.normal.x=u*r,this.normal.y=c*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){let i=r.P.Dot(this.normal,e);return i<=t}signedDistanceTo(e){return r.P.Dot(e,this.normal)+this.d}static FromArray(e){return new Plane(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new Plane(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new Plane(0,0,0,0);return t.normalize(),i.normal=t,i.d=-(t.x*e.x+t.y*e.y+t.z*e.z),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){let s=-(t.x*e.x+t.y*e.y+t.z*e.z);return r.P.Dot(i,t)+s}};Plane._TmpMatrix=r.y3.Identity()},5762:function(e,t,i){i.d(t,{R:function(){return Scalar}});let Scalar=class Scalar{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){let t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}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,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=Scalar.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){let i=Scalar.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let r=Scalar.Clamp(i);return t*(r=-2*r*r*r+3*r*r)+e*(1-r)}static MoveTowards(e,t,i){return Math.abs(t-e)<=i?t:e+Scalar.Sign(t-e)*i}static MoveTowardsAngle(e,t,i){let r=Scalar.DeltaAngle(e,t),s=0;return-i180&&(r-=360),e+r*Scalar.Clamp(i)}static InverseLerp(e,t,i){return e!=t?Scalar.Clamp((i-e)/(t-e)):0}static Hermite(e,t,i,r,s){let n=s*s,a=s*n;return e*(2*a-3*n+1)+i*(-2*a+3*n)+t*(a-2*n+s)+r*(a-n)}static Hermite1stDerivative(e,t,i,r,s){let n=s*s;return(n-s)*6*e+(3*n-4*s+1)*t+(-n+s)*6*i+(3*n-2*s)*r}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=Scalar.TwoPi*Math.floor((e+Math.PI)/Scalar.TwoPi)}static HCF(e,t){let i=e%t;return 0===i?t:Scalar.HCF(t,i)}};Scalar.TwoPi=2*Math.PI},6329:function(e,t,i){i.d(t,{l:function(){return Viewport}});let Viewport=class Viewport{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new Viewport(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new Viewport(this.x,this.y,this.width,this.height)}}},998:function(e,t,i){i.d(t,{M:function(){return WebGLDataBuffer}});var r=i(9185);let WebGLDataBuffer=class WebGLDataBuffer extends r.h{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},7042:function(e,t,i){i.d(t,{x:function(){return AbstractMesh}});var r=i(4800),s=i(6540),n=i(78),a=i(8906),o=i(1295),l=i(2696),h=i(8061),u=i(2248),c=i(5681),d=i(9691),p=i(5790),_=i(6131),f=i(7383),m=i(2983),g=i(9806),v=i(524),x=i(3048);let _FacetDataStorage=class _FacetDataStorage{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=n.P.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}};let _InternalAbstractMeshDataInfo=class _InternalAbstractMeshDataInfo{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new _FacetDataStorage,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 p.a,this._enableDistantPicking=!1,this._rawBoundingInfo=null}};let AbstractMesh=class AbstractMesh extends h.Y{static get BILLBOARDMODE_NONE(){return h.Y.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return h.Y.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return h.Y.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return h.Y.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return h.Y.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return h.Y.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;let t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty(e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()})}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._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){var t;return null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[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}get _positions(){return null}set skeleton(e){let 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 _InternalAbstractMeshDataInfo,this._waitingMaterialId=null,this.cullingStrategy=AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new r.y$,this.onCollisionPositionChangeObservable=new r.y$,this.onMaterialChangedObservable=new r.y$,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=m.Wo.Red(),this.outlineWidth=.02,this.overlayColor=m.Wo.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 n.P(.5,1,.5),this.ellipsoidOffset=new n.P(0,0,0),this.edgesWidth=1,this.edgesColor=new m.HE(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=[],this._unIndexed=!1,this._lightSources=[],this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new r.y$,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>a.D.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new d.M(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case s.a.Aggressive:this.doNotSyncBoundingInfo=!0;case s.a.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){let 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);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode]+", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==h.Y.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){return this.actionManager&&(t||this.actionManager.isRecursive)&&(!e||this.actionManager.hasSpecificTrigger(e))?this.actionManager: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(let e of this.subMeshes)e._rebuild()}_resyncLightSources(){for(let e of(this._lightSources.length=0,this.getScene().lights))e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;it.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(let 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,i,r){return this}updateVerticesData(e,t,i,r){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(){var e;return null!==(e=this.rawBoundingInfo)&&void 0!==e?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new c.j(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(o.o.MatricesIndicesKind)&&this.isVerticesDataPresent(o.o.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===h.Y.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,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){let r=new n.y3,s=this.rotationQuaternion?this.rotationQuaternion:n._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z);s.toRotationMatrix(r);let a=n.P.Zero(),o=this.definedFacingForward?-1:1;return n.P.TransformCoordinatesFromFloatsToRef(e*o,t,i*o,r,a),a}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new n.P(e*r,t,i*r)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){let i=(0,f.k)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new c.j(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t0){let e=t.getPositions();e&&(i[s]+=(e[s]-i[s])*r)}}if(e++,r===o.o.PositionKind&&this._positions&&3===e){e=0;let r=3*t;this._positions[t++].copyFromFloats(i[r],i[r+1],i[r+2])}}}if(i&&e&&this.skeleton){let e=this.getVerticesData(o.o.MatricesIndicesKind),t=this.getVerticesData(o.o.MatricesWeightsKind);if(t&&e){let s=this.numBoneInfluencers>4,a=s?this.getVerticesData(o.o.MatricesIndicesExtraKind):null,l=s?this.getVerticesData(o.o.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),u=n.jp.Vector3[0],c=n.jp.Matrix[0],d=n.jp.Matrix[1],p=0;for(let _=0;_0&&(n.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*e[p+f]),m,d),c.addToSelf(d));if(s)for(f=0;f<4;f++)(m=l[p+f])>0&&(n.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*a[p+f]),m,d),c.addToSelf(d));r===o.o.NormalKind?n.P.TransformNormalFromFloatsToRef(i[_],i[_+1],i[_+2],c,u):n.P.TransformCoordinatesFromFloatsToRef(i[_],i[_+1],i[_+2],c,u),u.toArray(i,_),r===o.o.PositionKind&&this._positions&&this._positions[_/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,o.o.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,o.o.PositionKind)}_getPositionData(e,t){var i;let r=this.getVerticesData(o.o.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),r&&(e&&this.skeleton||t&&this.morphTargetManager)){if(r=r.slice(),this._generatePointsArray(),this._positions){let e=this._positions;this._internalAbstractMeshDataInfo._positions=Array(e.length);for(let t=0;t1||!r.IsGlobal)&&r.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,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let i of this.getChildMeshes())if(i.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){let t=this.getAbsolutePosition();t.addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);let i=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=i.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,i.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s1)||n._checkCollision(e))&&this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=n.jp.Matrix[0],i=n.jp.Matrix[1];return n.y3.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,a=!1){let o=new u.p,l=this.getClassName(),h="InstancedLinesMesh"===l||"LinesMesh"===l||"GreasedLineMesh"===l?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(c.boundingSphere,h)||!e.intersectsBox(c.boundingBox,h)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:n.P.Distance(e.origin,c.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let d=null,p=this._scene.getIntersectingSubMeshCandidates(this,e),_=p.length,f=!1;for(let e=0;e<_;e++){let t=p.data[e],i=t.getMaterial();if(i&&(7==i.fillMode||0==i.fillMode||1==i.fillMode||2==i.fillMode||4==i.fillMode)){f=!0;break}}if(!f)return o.hit=!0,o.pickedMesh=this,o.distance=n.P.Distance(e.origin,c.boundingSphere.center),o.subMeshId=-1,o;for(let r=0;r<_;r++){let s=p.data[r];if(_>1&&!s.canIntersects(e))continue;let n=s.intersects(e,this._positions,this.getIndices(),t,i);if(n&&(t||!d||n.distancee!==this&&e.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(this))&&e.excludedMeshes.splice(t,1);let i=e.getShadowGenerators();if(i){let e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){let e=i.value,r=e.getShadowMap();r&&r.renderList&&-1!==(t=r.renderList.indexOf(this))&&r.renderList.splice(t,1)}}}),("InstancedMesh"!==this.getClassName()||"InstancedLinesMesh"!==this.getClassName())&&this.releaseSubMeshes();let n=r.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,n.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),n.wipeCaches(),r.removeMesh(this),this._parentContainer){let 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(i=0;i65535){t=!0;break}t?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){let t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:n.P.Zero()}e.depthSortedFacets=[];for(let t=0;tg.kn?s.maximum.x-s.minimum.x:g.kn,e.bbSize.y=s.maximum.y-s.minimum.y>g.kn?s.maximum.y-s.minimum.y:g.kn,e.bbSize.z=s.maximum.z-s.minimum.z>g.kn?s.maximum.z-s.minimum.z:g.kn;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),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=s,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),n.P.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&l.x.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let t=e.depthSortedIndices.length/3|0;for(let r=0;rs.subDiv.max||a<0||a>s.subDiv.max||o<0||o>s.subDiv.max?null:s.facetPartitioning[n+s.subDiv.max*a+s.subDiv.max*s.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let o=this.getWorldMatrix(),l=n.jp.Matrix[5];o.invertToRef(l);let h=n.jp.Vector3[8];n.P.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);let u=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,r,s,a);return r&&n.P.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),u}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,n=!0){let a,o,l,h=null,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=this.getFacetLocalPositions(),x=this.getFacetLocalNormals(),T=this.getFacetsAtLocalCoordinates(e,t,i);if(!T)return null;let S=Number.MAX_VALUE,C=S;for(let E=0;E=0||s&&!n&&p<=0)&&(p=o.x*l.x+o.y*l.y+o.z*l.z,_=-(o.x*e+o.y*t+o.z*i-p)/(o.x*o.x+o.y*o.y+o.z*o.z),f=e+o.x*_,m=t+o.y*_,g=i+o.z*_,(C=(u=f-e)*u+(c=m-t)*c+(d=g-i)*d)e.emitter===this)}};AbstractMesh.OCCLUSION_TYPE_NONE=0,AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC=1,AbstractMesh.OCCLUSION_TYPE_STRICT=2,AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,AbstractMesh.CULLINGSTRATEGY_STANDARD=0,AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,x.H)("BABYLON.AbstractMesh",AbstractMesh)},1687:function(e,t,i){i.d(t,{Z:function(){return Geometry}});var r=i(78),s=i(2983),n=i(2696),a=i(1295),o=i(1091),l=i(2697),h=i(5681),u=i(5132),c=i(1803),d=i(7383),p=i(6030),_=i(6705);let Geometry=class Geometry{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){let t=new Geometry(Geometry.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){if(this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||p.l.LastCreatedScene,!this._scene)return;this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable)),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){for(let t of(this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects(),this._meshes))t._markSubMeshesAsAttributesDirty()}load(e,t){if(2!==this.delayLoadState){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t;let i=new n.x;i.indices=[];let r=this.getIndices();if(r)for(let e=0;e0){let r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(a.o.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){let r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(a.o.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){let r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(a.o.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){let r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(a.o.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(a.o.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(a.o.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){let r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(a.o.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){let r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){let r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(a.o.MatricesIndicesKind,i,e.matricesIndices._updatable)}}if(e.matricesIndicesExtra){if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(a.o.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{let i=[];for(let t=0;t>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(a.o.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}}e.matricesWeights&&(Geometry._CleanMatricesWeights(e,t),t.setVerticesData(a.o.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(a.o.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{let r=t.getScene().getLastSkeletonById(e.skeletonId);if(!r)return;i=r.bones.length}let r=t.getVerticesData(a.o.MatricesIndicesKind),s=t.getVerticesData(a.o.MatricesIndicesExtraKind),n=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,u=n.length;for(let e=0;eh-1)&&(a=h-1),t>.001){let i=1/t;for(let t=0;t<4;t++)n[e+t]*=i;if(o)for(let t=0;t<4;t++)o[e+t]*=i}else a>=4?(o[e+a-4]=1-t,s[e+a-4]=i):(n[e+a]=1-t,r[e+a]=i)}t.setVerticesData(a.o.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(a.o.MatricesIndicesExtraKind,s)}static Parse(e,t,i){let s=new Geometry(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,c.$&&c.$.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new h.j(r.P.FromArray(e.boundingBoxMinimum),r.P.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(a.o.UVKind),e.hasUVs2&&s._delayInfo.push(a.o.UV2Kind),e.hasUVs3&&s._delayInfo.push(a.o.UV3Kind),e.hasUVs4&&s._delayInfo.push(a.o.UV4Kind),e.hasUVs5&&s._delayInfo.push(a.o.UV5Kind),e.hasUVs6&&s._delayInfo.push(a.o.UV6Kind),e.hasColors&&s._delayInfo.push(a.o.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(a.o.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(a.o.MatricesWeightsKind),s._delayLoadingFunction=n.x.ImportVertexData):n.x.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}},2696:function(e,t,i){i.d(t,{D:function(){return VertexDataMaterialInfo},x:function(){return VertexData}});var r=i(9956),s=i(78),n=i(1295),a=i(6131),o=i(2983),l=i(9626),h=i(1760),u=i(7521),c=i(3477),d=i(1091);let VertexDataMaterialInfo=class VertexDataMaterialInfo{};let VertexData=class VertexData{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=(0,u.vp)(this._applyToCoroutine.bind(this)),this.uniqueId=VertexData._UniqueIDGenerator,VertexData._UniqueIDGenerator++}set(e,t){switch(e.length||l.Y.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case n.o.PositionKind:this.positions=e;break;case n.o.NormalKind:this.normals=e;break;case n.o.TangentKind:this.tangents=e;break;case n.o.UVKind:this.uvs=e;break;case n.o.UV2Kind:this.uvs2=e;break;case n.o.UV3Kind:this.uvs3=e;break;case n.o.UV4Kind:this.uvs4=e;break;case n.o.UV5Kind:this.uvs5=e;break;case n.o.UV6Kind:this.uvs6=e;break;case n.o.ColorKind:this.colors=e;break;case n.o.MatricesIndicesKind:this.matricesIndices=e;break;case n.o.MatricesWeightsKind:this.matricesWeights=e;break;case n.o.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case n.o.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,i){if(this.positions&&(e.setVerticesData(n.o.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(n.o.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(n.o.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(n.o.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(n.o.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(n.o.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(n.o.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(n.o.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(n.o.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(n.o.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(n.o.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(n.o.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1)for(let t of(e.subMeshes=[],this.materialInfos))new d.P(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,e);return this}_update(e,t,i){return this.positions&&e.updateVerticesData(n.o.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(n.o.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(n.o.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(n.o.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(n.o.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(n.o.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(n.o.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(n.o.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(n.o.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(n.o.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(n.o.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(n.o.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let n=s.jp.Vector3[0],a=s.jp.Vector3[1];for(let o=i;oe.determinant();return this.positions&&VertexData._TransformVector3Coordinates(this.positions,e),this.normals&&VertexData._TransformVector3Normals(this.normals,e),this.tangents&&VertexData._TransformVector4Normals(this.tangents,e),t&&this.indices&&VertexData._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];let e=[];for(let t of this.materialInfos){let i=new VertexData;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let e=t.indexStart;e({vertexData:e})):[{vertexData:e}];return(0,u.s3)(this._mergeCoroutine(void 0,n,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,o=!1){var l,h,u,c;this._validate();let d=t.map(e=>e.vertexData),p=this;for(let e of d)if(e){if(e._validate(),o)!this.normals!=!e.normals&&(this.normals?e.normals=new Float32Array(e.positions.length):this.normals=new Float32Array(this.positions.length)),!this.tangents!=!e.tangents&&(this.tangents?e.tangents=new Float32Array(e.positions.length/3*4):this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs!=!e.uvs&&(this.uvs?e.uvs=new Float32Array(e.positions.length/3*2):this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2!=!e.uvs2&&(this.uvs2?e.uvs2=new Float32Array(e.positions.length/3*2):this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3!=!e.uvs3&&(this.uvs3?e.uvs3=new Float32Array(e.positions.length/3*2):this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4!=!e.uvs4&&(this.uvs4?e.uvs4=new Float32Array(e.positions.length/3*2):this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5!=!e.uvs5&&(this.uvs5?e.uvs5=new Float32Array(e.positions.length/3*2):this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6!=!e.uvs6&&(this.uvs6?e.uvs6=new Float32Array(e.positions.length/3*2):this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors!=!e.colors&&(this.colors?(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)):(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1))),!this.matricesIndices!=!e.matricesIndices&&(this.matricesIndices?e.matricesIndices=new Float32Array(e.positions.length/3*4):this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights!=!e.matricesWeights&&(this.matricesWeights?e.matricesWeights=new Float32Array(e.positions.length/3*4):this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra!=!e.matricesIndicesExtra&&(this.matricesIndicesExtra?e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4):this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra!=!e.matricesWeightsExtra&&(this.matricesWeightsExtra?e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4):this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4));else if(!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 Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let i=0,r=0,s=0,n=[],a=null,o=[];for(let t of this.splitBasedOnMaterialID())o.push({vertexData:t,transform:e});for(let e of t)if(e.vertexData)for(let t of e.vertexData.splitBasedOnMaterialID())o.push({vertexData:t,transform:e.transform});for(let e of(o.sort((e,t)=>{let i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}),o)){let t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{let e=new VertexDataMaterialInfo;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,n.push(e),a=e}r+=t.indices.length,s+=t.positions.length/3}let l=o.splice(0,1)[0];p=l.vertexData,e=l.transform,d=o.map(e=>e.vertexData),t=o,this.materialInfos=n}let _=d.reduce((e,t)=>{var i,r;return e+(null!==(r=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==r?r:0)},null!==(h=null===(l=p.indices)||void 0===l?void 0:l.length)&&void 0!==h?h:0),f=s||d.some(e=>e.indices===p.indices),m=f?null===(u=p.indices)||void 0===u?void 0:u.slice():p.indices;if(_>0){let s=null!==(c=null==m?void 0:m.length)&&void 0!==c?c:0;if(m||(m=Array(_)),m.length!==_){if(Array.isArray(m))m.length=_;else{let e=i||m instanceof Uint32Array?new Uint32Array(_):new Uint16Array(_);e.set(m),m=e}e&&0>e.determinant()&&VertexData._FlipFaces(m,0,s)}let n=p.positions?p.positions.length/3:0;for(let{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;ti.determinant()&&VertexData._FlipFaces(m,s,e.indices.length),n+=e.positions.length/3,s+=e.indices.length,r&&(yield)}}return this.indices=m,this.positions=VertexData._MergeElement(n.o.PositionKind,p.positions,e,t.map(e=>[e.vertexData.positions,e.transform])),r&&(yield),p.normals&&(this.normals=VertexData._MergeElement(n.o.NormalKind,p.normals,e,t.map(e=>[e.vertexData.normals,e.transform])),r&&(yield)),p.tangents&&(this.tangents=VertexData._MergeElement(n.o.TangentKind,p.tangents,e,t.map(e=>[e.vertexData.tangents,e.transform])),r&&(yield)),p.uvs&&(this.uvs=VertexData._MergeElement(n.o.UVKind,p.uvs,e,t.map(e=>[e.vertexData.uvs,e.transform])),r&&(yield)),p.uvs2&&(this.uvs2=VertexData._MergeElement(n.o.UV2Kind,p.uvs2,e,t.map(e=>[e.vertexData.uvs2,e.transform])),r&&(yield)),p.uvs3&&(this.uvs3=VertexData._MergeElement(n.o.UV3Kind,p.uvs3,e,t.map(e=>[e.vertexData.uvs3,e.transform])),r&&(yield)),p.uvs4&&(this.uvs4=VertexData._MergeElement(n.o.UV4Kind,p.uvs4,e,t.map(e=>[e.vertexData.uvs4,e.transform])),r&&(yield)),p.uvs5&&(this.uvs5=VertexData._MergeElement(n.o.UV5Kind,p.uvs5,e,t.map(e=>[e.vertexData.uvs5,e.transform])),r&&(yield)),p.uvs6&&(this.uvs6=VertexData._MergeElement(n.o.UV6Kind,p.uvs6,e,t.map(e=>[e.vertexData.uvs6,e.transform])),r&&(yield)),p.colors&&(this.colors=VertexData._MergeElement(n.o.ColorKind,p.colors,e,t.map(e=>[e.vertexData.colors,e.transform])),r&&(yield)),p.matricesIndices&&(this.matricesIndices=VertexData._MergeElement(n.o.MatricesIndicesKind,p.matricesIndices,e,t.map(e=>[e.vertexData.matricesIndices,e.transform])),r&&(yield)),p.matricesWeights&&(this.matricesWeights=VertexData._MergeElement(n.o.MatricesWeightsKind,p.matricesWeights,e,t.map(e=>[e.vertexData.matricesWeights,e.transform])),r&&(yield)),p.matricesIndicesExtra&&(this.matricesIndicesExtra=VertexData._MergeElement(n.o.MatricesIndicesExtraKind,p.matricesIndicesExtra,e,t.map(e=>[e.vertexData.matricesIndicesExtra,e.transform])),r&&(yield)),p.matricesWeightsExtra&&(this.matricesWeightsExtra=VertexData._MergeElement(n.o.MatricesWeightsExtraKind,p.matricesWeightsExtra,e,t.map(e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(e=>null!==e[0]&&void 0!==e[0]);if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((e,t)=>e+t[0].length,t.length),o=e===n.o.PositionKind?VertexData._TransformVector3Coordinates:e===n.o.NormalKind?VertexData._TransformVector3Normals:e===n.o.TangentKind?VertexData._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let e=new Float32Array(a);e.set(t),i&&o(e,i,0,t.length);let r=t.length;for(let[t,i]of s)e.set(t,r),i&&o(e,i,r,t.length),r+=t.length;return e}{let e=Array(a);for(let i=0;i{let i=n.o.DeduceStride(e);if(t.length%i!=0)throw Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},e=getElementCount(n.o.PositionKind,this.positions),validateElementCount=(t,i)=>{let r=getElementCount(t,i);if(r!==e)throw Error("The "+t+"s element count ("+r+") does not match the positions count ("+e+")")};this.normals&&validateElementCount(n.o.NormalKind,this.normals),this.tangents&&validateElementCount(n.o.TangentKind,this.tangents),this.uvs&&validateElementCount(n.o.UVKind,this.uvs),this.uvs2&&validateElementCount(n.o.UV2Kind,this.uvs2),this.uvs3&&validateElementCount(n.o.UV3Kind,this.uvs3),this.uvs4&&validateElementCount(n.o.UV4Kind,this.uvs4),this.uvs5&&validateElementCount(n.o.UV5Kind,this.uvs5),this.uvs6&&validateElementCount(n.o.UV6Kind,this.uvs6),this.colors&&validateElementCount(n.o.ColorKind,this.colors),this.matricesIndices&&validateElementCount(n.o.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&validateElementCount(n.o.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&validateElementCount(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&validateElementCount(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return VertexData.Parse(e)}serialize(){let 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)),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)for(let t of(e.materialInfos=[],this.materialInfos)){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}return e}static ExtractFromMesh(e,t,i){return VertexData._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return VertexData._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new VertexData;return e.isVerticesDataPresent(n.o.PositionKind)&&(r.positions=e.getVerticesData(n.o.PositionKind,t,i)),e.isVerticesDataPresent(n.o.NormalKind)&&(r.normals=e.getVerticesData(n.o.NormalKind,t,i)),e.isVerticesDataPresent(n.o.TangentKind)&&(r.tangents=e.getVerticesData(n.o.TangentKind,t,i)),e.isVerticesDataPresent(n.o.UVKind)&&(r.uvs=e.getVerticesData(n.o.UVKind,t,i)),e.isVerticesDataPresent(n.o.UV2Kind)&&(r.uvs2=e.getVerticesData(n.o.UV2Kind,t,i)),e.isVerticesDataPresent(n.o.UV3Kind)&&(r.uvs3=e.getVerticesData(n.o.UV3Kind,t,i)),e.isVerticesDataPresent(n.o.UV4Kind)&&(r.uvs4=e.getVerticesData(n.o.UV4Kind,t,i)),e.isVerticesDataPresent(n.o.UV5Kind)&&(r.uvs5=e.getVerticesData(n.o.UV5Kind,t,i)),e.isVerticesDataPresent(n.o.UV6Kind)&&(r.uvs6=e.getVerticesData(n.o.UV6Kind,t,i)),e.isVerticesDataPresent(n.o.ColorKind)&&(r.colors=e.getVerticesData(n.o.ColorKind,t,i)),e.isVerticesDataPresent(n.o.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(n.o.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(n.o.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(n.o.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(n.o.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(n.o.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(n.o.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(n.o.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw(0,a.S)("ribbonBuilder")}static CreateBox(e){throw(0,a.S)("boxBuilder")}static CreateTiledBox(e){throw(0,a.S)("tiledBoxBuilder")}static CreateTiledPlane(e){throw(0,a.S)("tiledPlaneBuilder")}static CreateSphere(e){throw(0,a.S)("sphereBuilder")}static CreateCylinder(e){throw(0,a.S)("cylinderBuilder")}static CreateTorus(e){throw(0,a.S)("torusBuilder")}static CreateLineSystem(e){throw(0,a.S)("linesBuilder")}static CreateDashedLines(e){throw(0,a.S)("linesBuilder")}static CreateGround(e){throw(0,a.S)("groundBuilder")}static CreateTiledGround(e){throw(0,a.S)("groundBuilder")}static CreateGroundFromHeightMap(e){throw(0,a.S)("groundBuilder")}static CreatePlane(e){throw(0,a.S)("planeBuilder")}static CreateDisc(e){throw(0,a.S)("discBuilder")}static CreatePolygon(e,t,i,r,s,n,o){throw(0,a.S)("polygonBuilder")}static CreateIcoSphere(e){throw(0,a.S)("icoSphereBuilder")}static CreatePolyhedron(e){throw(0,a.S)("polyhedronBuilder")}static CreateCapsule(e={orientation:s.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw(0,a.S)("capsuleBuilder")}static CreateTorusKnot(e){throw(0,a.S)("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=0,x=0,T=0,S=0,C=0,E=0,b=0,y=!1,P=!1,R=!1,A=!1,I=1,M=0,D=null;r&&(y=!!r.facetNormals,P=!!r.facetPositions,R=!!r.facetPartitioning,I=!0===r.useRightHandedSystem?-1:1,M=r.ratio||0,A=!!r.depthSort,D=r.distanceTo,A&&void 0===D&&(D=s.P.Zero()));let O=0,N=0,F=0,B=0;for(R&&r&&r.bbSize&&(O=r.subDiv.X*M/r.bbSize.x,N=r.subDiv.Y*M/r.bbSize.y,F=r.subDiv.Z*M/r.bbSize.z,B=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),n=0;n!Array.isArray(e))],VertexData,"_TransformVector3Coordinates",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],VertexData,"_TransformVector3Normals",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],VertexData,"_TransformVector4Normals",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],VertexData,"_FlipFaces",null)},4926:function(e,t,i){i.d(t,{g:function(){return MeshLODLevel}});let MeshLODLevel=class MeshLODLevel{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}},1091:function(e,t,i){i.d(t,{P:function(){return SubMesh}});var r=i(1295),s=i(6491),n=i(5681),a=i(7383),o=i(1606);let SubMesh=class SubMesh{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines}set materialDefines(e){var t;let i=null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0);i.defines=e}_getDrawWrapper(e,t=!1){e=null!=e?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new o.q(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null}get _drawWrapper(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e){this._removeDrawWrapper(e);return}for(let e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,n,a,o=!0){return new SubMesh(e,t,i,r,s,n,a,o)}constructor(e,t,i,r,s,n,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,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,l&&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(){let e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){var t;let i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){let e=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return i}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){let t;if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(r.o.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){let e=this._renderingMesh.getBoundingInfo();t={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else t=(0,a.y)(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new n.j(t.minimum,t.maximum),this}_checkCollision(e){let t=this.getBoundingInfo();return t._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){let t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){let 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){let i=[];for(let t=this.indexStart;to&&(o=t)}return new SubMesh(e,a,o-a+1,t,i,r,s,n)}}},8061:function(e,t,i){i.d(t,{Y:function(){return TransformNode}});var r=i(9956),s=i(1760),n=i(4800),a=i(78),o=i(208),l=i(524);let h=a.y3.Compose(a.P.One(),a._f.FromEulerAngles(0,Math.PI,0),a.P.Zero());let TransformNode=class TransformNode extends o.N{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&TransformNode.BILLBOARDMODE_USE_POSITION)!=0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==TransformNode.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new a.P(0,0,1),this._up=new a.P(0,1,0),this._right=new a.P(1,0,0),this._position=a.P.Zero(),this._rotation=a.P.Zero(),this._rotationQuaternion=null,this._scaling=a.P.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=TransformNode.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=a.y3.Zero(),this._usePivotMatrix=!1,this._absolutePosition=a.P.Zero(),this._absoluteScaling=a.P.Zero(),this._absoluteRotationQuaternion=a._f.Identity(),this._pivotMatrix=a.y3.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new n.y$,this._nonUniformScaling=!1,i&&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}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 a.P.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return a.P.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return a.P.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._poseMatrix=e.clone(),this}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=a.y3.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===TransformNode.BILLBOARDMODE_NONE&&!e.pivotMatrixUpdated&&!this._infiniteDistance&&!this._position._isDirty&&!this._scaling._isDirty&&(!this._rotationQuaternion||!this._rotationQuaternion._isDirty)&&!this._rotation._isDirty}_initCache(){super._initCache();let 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=a.y3.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||a._f.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){let t,i,r;if(!e)return this;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let e=a.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),a.P.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=a.P.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=a.jp.Matrix[0];return this._localMatrix.invertToRef(e),a.P.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=a.P.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=l.T.LOCAL){let n=TransformNode._LookAtVectorCache,o=s===l.T.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,r),s===l.T.WORLD&&this.parent){if(this.rotationQuaternion){let e=a.jp.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);let t=a.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{let e=a.jp.Quaternion[0];a._f.FromEulerVectorToRef(this.rotation,e);let t=a.jp.Matrix[0];e.toRotationMatrix(t);let i=a.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}}return this}getDirection(e){let t=a.P.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return a.P.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?a._f.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=l.T.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==l.T.WORLD){let t=a.jp.Matrix[0];i.invertToRef(t),e=a.P.TransformCoordinates(e,t)}return this.setPivotMatrix(a.y3.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=a.P.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(){let e=a.P.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),a.P.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=a.jp.Quaternion[0],s=a.jp.Vector3[0],n=a.jp.Vector3[1],o=a.jp.Matrix[1];a.y3.IdentityToRef(o);let l=a.jp.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=TransformNode._TmpRotation,a._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),a.y3.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(n,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(a.y3.Identity()),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),0>e.getFinalMatrix().determinant()&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(0>this.parent.getWorldMatrix().determinant()&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null):e&&(this.parent=this._currentParentWhenAttachingToBone),this}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==l.T.LOCAL){if(this.parent){let i=this.parent.getWorldMatrix(),r=a.jp.Matrix[0];i.invertToRef(r),e=a.P.TransformNormal(e,r),0>i.determinant()&&(t*=-1)}(r=a._f.RotationAxisToRef(e,t,TransformNode._RotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=a._f.RotationAxisToRef(e,t,TransformNode._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=a._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=a.jp.Vector3[0],s=a.jp.Vector3[1],n=a.jp.Vector3[2],o=a.jp.Quaternion[0],l=a.jp.Matrix[0],h=a.jp.Matrix[1],u=a.jp.Matrix[2],c=a.jp.Matrix[3];return e.subtractToRef(this.position,r),a.y3.TranslationToRef(r.x,r.y,r.z,l),a.y3.TranslationToRef(-r.x,-r.y,-r.z,h),a.y3.RotationAxisToRef(t,i,u),h.multiplyToRef(u,c),c.multiplyToRef(l,c),c.decompose(s,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(i&&i!==l.T.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{let e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=a.jp.Quaternion[1],a._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=a.jp.Quaternion[0];return a._f.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==TransformNode.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){let i;if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let r=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===r||this.isSynchronized()))return this._currentRenderId=r,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=r,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let n=this._getEffectiveParent(),o=TransformNode._TmpScaling,l=this._position;if(this._infiniteDistance&&!this.parent&&t){let e=t.getWorldMatrix(),i=new a.P(e.m[12],e.m[13],e.m[14]);(l=TransformNode._TmpTranslation).copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(o.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,i=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){let e=this.rotation.lengthSquared();e&&(this._rotationQuaternion.multiplyInPlace(a._f.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else i=TransformNode._TmpRotation,a._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,i);if(this._usePivotMatrix){let e=a.jp.Matrix[1];a.y3.ScalingToRef(o.x,o.y,o.z,e);let t=a.jp.Matrix[0];i.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,a.jp.Matrix[4]),a.jp.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(l.x,l.y,l.z)}else a.y3.ComposeToRef(o,i,l,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),a.jp.Matrix[7])}else a.jp.Matrix[7].copyFrom(n.getWorldMatrix());let e=a.jp.Vector3[5],t=a.jp.Vector3[6],i=a.jp.Quaternion[0];a.jp.Matrix[7].decompose(t,i,e),a.y3.ScalingToRef(t.x,t.y,t.z,a.jp.Matrix[7]),a.jp.Matrix[7].setTranslation(e),TransformNode.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(a.jp.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),a.jp.Matrix[6]),a.jp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){let e=a.jp.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),a.jp.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&a.jp.Matrix[1].multiplyToRef(h,a.jp.Matrix[1]),a.jp.Matrix[1].setTranslationFromFloats(0,0,0),a.jp.Matrix[1].invertToRef(a.jp.Matrix[0]),(this.billboardMode&TransformNode.BILLBOARDMODE_ALL)!==TransformNode.BILLBOARDMODE_ALL){a.jp.Matrix[0].decompose(void 0,a.jp.Quaternion[0],void 0);let e=a.jp.Vector3[1];a.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&TransformNode.BILLBOARDMODE_X)!==TransformNode.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&TransformNode.BILLBOARDMODE_Y)!==TransformNode.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&TransformNode.BILLBOARDMODE_Z)!==TransformNode.BILLBOARDMODE_Z&&(e.z=0),a.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,a.jp.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.jp.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){let e=a.jp.Vector3[0];this._worldMatrix.getTranslationToRef(e);let i=t.globalPosition;this._worldMatrix.invertToRef(a.jp.Matrix[1]);let r=a.jp.Vector3[1];a.P.TransformCoordinatesToRef(i,a.jp.Matrix[1],r),r.normalize();let s=-Math.atan2(r.z,r.x)+Math.PI/2,n=Math.sqrt(r.x*r.x+r.z*r.z),o=-Math.atan2(r.y,n);if(a._f.RotationYawPitchRollToRef(s,o,0,a.jp.Quaternion[0]),(this.billboardMode&TransformNode.BILLBOARDMODE_ALL)!==TransformNode.BILLBOARDMODE_ALL){let e=a.jp.Vector3[1];a.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&TransformNode.BILLBOARDMODE_X)!==TransformNode.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&TransformNode.BILLBOARDMODE_Y)!==TransformNode.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&TransformNode.BILLBOARDMODE_Z)!==TransformNode.BILLBOARDMODE_Z&&(e.z=0),a.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,a.jp.Matrix[0])}else a.y3.FromQuaternionToRef(a.jp.Quaternion[0],a.jp.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.jp.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._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=a.y3.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let e=this.getChildren();for(let t=0;tnew TransformNode(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;inew TransformNode(e.name,t),e,t,i);return e.localMatrix?r.setPreTransformMatrix(a.y3.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(a.y3.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r}getChildTransformNodes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&e instanceof TransformNode),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){let e=this.getChildTransformNodes(!0);for(let t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);return 0===o||(this.scaling.scaleInPlace(1/o),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r))),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}};TransformNode.BILLBOARDMODE_NONE=0,TransformNode.BILLBOARDMODE_X=1,TransformNode.BILLBOARDMODE_Y=2,TransformNode.BILLBOARDMODE_Z=4,TransformNode.BILLBOARDMODE_ALL=7,TransformNode.BILLBOARDMODE_USE_POSITION=128,TransformNode.BillboardUseParentOrientation=!1,TransformNode._TmpRotation=a._f.Zero(),TransformNode._TmpScaling=a.P.Zero(),TransformNode._TmpTranslation=a.P.Zero(),TransformNode._LookAtVectorCache=new a.P(0,0,0),TransformNode._RotationAxisCache=new a._f,(0,r.gn)([(0,s.hd)("position")],TransformNode.prototype,"_position",void 0),(0,r.gn)([(0,s.hd)("rotation")],TransformNode.prototype,"_rotation",void 0),(0,r.gn)([(0,s.mv)("rotationQuaternion")],TransformNode.prototype,"_rotationQuaternion",void 0),(0,r.gn)([(0,s.hd)("scaling")],TransformNode.prototype,"_scaling",void 0),(0,r.gn)([(0,s.qC)("billboardMode")],TransformNode.prototype,"_billboardMode",void 0),(0,r.gn)([(0,s.qC)()],TransformNode.prototype,"scalingDeterminant",void 0),(0,r.gn)([(0,s.qC)("infiniteDistance")],TransformNode.prototype,"_infiniteDistance",void 0),(0,r.gn)([(0,s.qC)()],TransformNode.prototype,"ignoreNonUniformScaling",void 0),(0,r.gn)([(0,s.qC)()],TransformNode.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)},1146:function(e,t,i){i.d(t,{q:function(){return AndOrNotEvaluator}});let AndOrNotEvaluator=class AndOrNotEvaluator{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,e=>(e=e.slice(1,e.length-1),AndOrNotEvaluator._HandleParenthesisContent(e,t))):AndOrNotEvaluator._HandleParenthesisContent(e,t))||"false"!==e&&AndOrNotEvaluator.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);let r=e.split("||");for(let e in r)if(Object.prototype.hasOwnProperty.call(r,e)){let s=AndOrNotEvaluator._SimplifyNegation(r[e].trim()),n=s.split("&&");if(n.length>1)for(let e=0;e(e=e.replace(/[\s]/g,()=>"")).length%2?"!":"")).trim())?e="false":"!false"===e&&(e="true"),e}}},4254:function(e,t,i){i.d(t,{B:function(){return ArrayTools},M:function(){return _ObserveArray}});let ArrayTools=class ArrayTools{static BuildArray(e,t){let i=[];for(let r=0;r{let i=newFunction.previous;if(!i)return;let r=newFunction.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),newFunction.next=void 0,newFunction.previous=void 0}}let r=["push","splice","pop","shift","unshift"];function _ObserveArray(e,t){let i=r.map(i=>_observeArrayfunction(e,i,t));return()=>{i.forEach(e=>{null==e||e()})}}},7521:function(e,t,i){function inlineScheduler(e,t,i){try{let r=e.next();r.done?t(r):r.value?r.value.then(()=>{r.value=void 0,t(r)},i):t(r)}catch(e){i(e)}}function createYieldingScheduler(e=25){let t;return(i,r,s)=>{let n=performance.now();void 0===t||n-t>e?(t=n,setTimeout(()=>{inlineScheduler(i,r,s)},0)):inlineScheduler(i,r,s)}}function runCoroutine(e,t,i,r,s){let resume=()=>{let n;let onStep=e=>{e.done?i(e.value):void 0===n?n=!0:resume()};do n=void 0,s&&s.aborted?r(Error("Aborted")):t(e,onStep,r),void 0===n&&(n=!1);while(n)};resume()}function runCoroutineSync(e,t){let i;return runCoroutine(e,inlineScheduler,e=>i=e,e=>{throw e},t),i}function runCoroutineAsync(e,t,i){return new Promise((r,s)=>{runCoroutine(e,t,r,s,i)})}function makeSyncFunction(e,t){return(...i)=>runCoroutineSync(e(...i),t)}i.d(t,{KO:function(){return createYieldingScheduler},WP:function(){return inlineScheduler},s3:function(){return runCoroutineSync},sM:function(){return runCoroutineAsync},vp:function(){return makeSyncFunction}})},1760:function(e,t,i){i.d(t,{G6:function(){return nativeOverride},N$:function(){return serializeAsColorCurves},QC:function(){return serializeAsVector2},RR:function(){return serializeAsMeshReference},VE:function(){return serializeAsCameraReference},XX:function(){return serializeAsColor4},hd:function(){return serializeAsVector3},mv:function(){return serializeAsQuaternion},n9:function(){return serializeAsColor3},oQ:function(){return serializeAsMatrix},oU:function(){return serializeAsTexture},p4:function(){return SerializationHelper},qC:function(){return serialize},qQ:function(){return serializeAsFresnelParameters},rX:function(){return serializeAsImageProcessingConfiguration},wz:function(){return expandToProperty}});var r=i(1803),s=i(78),n=i(6131),a=i(2983);let o={},l={},_copySource=function(e,t,i,s={}){let n=e();r.$&&r.$.HasTags(t)&&r.$.AddTagsTo(n,r.$.GetTags(t,!0));let a=getMergedStore(n),o={};for(let e in a){let r=a[e],l=t[e],h=r.type;if(null!=l&&("uniqueId"!==e||SerializationHelper.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:n[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?n[e]=o[l.uniqueId]:(n[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=n[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[e]=i?l:l.clone()}}return n};function getDirectStore(e){let t=e.getClassName();return o[t]||(o[t]={}),o[t]}function getMergedStore(e){let t=e.getClassName();if(l[t])return l[t];l[t]={};let i=l[t],r=e,s=t;for(;s;){let e;let t=o[s];for(let e in t)i[e]=t[e];let n=!1;do{if(!(e=Object.getPrototypeOf(r)).getClassName){n=!0;break}if(e.getClassName()!==s)break;r=e}while(e);if(n)break;s=e.getClassName(),r=e}return i}function generateSerializableMember(e,t){return(i,r)=>{let s=getDirectStore(i);s[r]||(s[r]={type:e,sourceName:t})}}function generateExpandMember(e,t=null){return(i,r)=>{let s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]===t||(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}function expandToProperty(e,t=null){return generateExpandMember(e,t)}function serialize(e){return generateSerializableMember(0,e)}function serializeAsTexture(e){return generateSerializableMember(1,e)}function serializeAsColor3(e){return generateSerializableMember(2,e)}function serializeAsFresnelParameters(e){return generateSerializableMember(3,e)}function serializeAsVector2(e){return generateSerializableMember(4,e)}function serializeAsVector3(e){return generateSerializableMember(5,e)}function serializeAsMeshReference(e){return generateSerializableMember(6,e)}function serializeAsColorCurves(e){return generateSerializableMember(7,e)}function serializeAsColor4(e){return generateSerializableMember(8,e)}function serializeAsImageProcessingConfiguration(e){return generateSerializableMember(9,e)}function serializeAsQuaternion(e){return generateSerializableMember(10,e)}function serializeAsMatrix(e){return generateSerializableMember(12,e)}function serializeAsCameraReference(e){return generateSerializableMember(11,e)}let SerializationHelper=class SerializationHelper{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{let n=s;if("undefined"!=typeof _native&&_native[t]){let e=_native[t];n=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=n,n(...i)}}SerializationHelper.AllowLoadingUniqueId=!1,SerializationHelper._ImageProcessingConfigurationParser=e=>{throw(0,n.S)("ImageProcessingConfiguration")},SerializationHelper._FresnelParametersParser=e=>{throw(0,n.S)("FresnelParameters")},SerializationHelper._ColorCurvesParser=e=>{throw(0,n.S)("ColorCurves")},SerializationHelper._TextureParser=(e,t,i)=>{throw(0,n.S)("Texture")},nativeOverride.filter=function(e){return(t,i,r)=>nativeOverride(t,i,r,e)}},3189:function(e,t,i){i.d(t,{j:function(){return DeepCopier}});var r=i(9626);let CloneValue=(e,t,i)=>!e||e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&("SubMesh"===e.getClassName()||"PhysicsBody"===e.getClassName())?e.clone(t):e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?Object.assign({},e):null;function GetAllPropertyNames(e){let t=[];do Object.getOwnPropertyNames(e).forEach(function(e){-1===t.indexOf(e)&&t.push(e)});while(e=Object.getPrototypeOf(e));return t}let DeepCopier=class DeepCopier{static DeepCopy(e,t,i,s,n=!1){let a=GetAllPropertyNames(e);for(let o of a){if("_"===o[0]&&(!s||-1===s.indexOf(o))||o.endsWith("Observable")||i&&-1!==i.indexOf(o))continue;let a=e[o],l=typeof a;if("function"!==l)try{if("object"===l){if(a instanceof Uint8Array)t[o]=Uint8Array.from(a);else if(a instanceof Array){if(t[o]=[],a.length>0){if("object"==typeof a[0])for(let e=0;e(e.__proto__=t,e));let r={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};let RuntimeError=class RuntimeError extends BaseError{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",BaseError._setPrototypeOf(this,RuntimeError.prototype)}}},1166:function(e,t,i){let r;i.d(t,{$K:function(){return DecodeBase64UrlToBinary},$M:function(){return SetCorsBehavior},FV:function(){return RequestFile},Ip:function(){return ReadFile},VL:function(){return IsBase64DataUrl},r6:function(){return LoadImage},rN:function(){return g},vP:function(){return LoadFile}});var s=i(2962),n=i(7209),a=i(4800),o=i(320),l=i(9983),h=i(3477),u=i(9005),c=i(7790),d=i(6465),p=i(6030),_=i(9626),f=i(4490);let m=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);let LoadFileError=class LoadFileError extends h.LH{constructor(e,t){super(e,h.SM.LoadFileError),this.name="LoadFileError",h.GU._setPrototypeOf(this,LoadFileError.prototype),t instanceof s.g?this.request=t:this.file=t}};let RequestFileError=class RequestFileError extends h.LH{constructor(e,t){super(e,h.SM.RequestFileError),this.request=t,this.name="RequestFileError",h.GU._setPrototypeOf(this,RequestFileError.prototype)}};let ReadFileError=class ReadFileError extends h.LH{constructor(e,t){super(e,h.SM.ReadFileError),this.file=t,this.name="ReadFileError",h.GU._setPrototypeOf(this,ReadFileError.prototype)}};let g={DefaultRetryStrategy:l.b.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e},_CleanUrl=e=>e=e.replace(/#/gm,"%23"),SetCorsBehavior=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&g.CorsBehavior){if("string"==typeof g.CorsBehavior||g.CorsBehavior instanceof String)t.crossOrigin=g.CorsBehavior;else{let i=g.CorsBehavior(e);i&&(t.crossOrigin=i)}}},LoadImage=(e,t,i,r,n="",a)=>{var l;let h;let c=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(h=URL.createObjectURL(new Blob([e],{type:n})),c=!0):h=`data:${n};base64,`+(0,u.Gh)(e):e instanceof Blob?(h=URL.createObjectURL(e),c=!0):(h=_CleanUrl(e),h=g.PreprocessUrl(e));let d=p.l.LastCreatedEngine,onErrorHandler=t=>{if(i){let r=h||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if("undefined"==typeof Image||null!==(l=null==d?void 0:d._features.forceBitmapOverHTMLImageElement)&&void 0!==l&&l)return LoadFile(h,r=>{d.createImageBitmap(new Blob([r],{type:n}),Object.assign({premultiplyAlpha:"none"},a)).then(e=>{t(e),c&&URL.revokeObjectURL(h)}).catch(t=>{i&&i("Error while trying to load image: "+e,t)})},void 0,r||void 0,!0,(e,t)=>{onErrorHandler(t)}),null;let _=new Image;SetCorsBehavior(h,_);let f=[],unloadHandlersList=()=>{f.forEach(e=>{e.target.removeEventListener(e.name,e.handler)}),f.length=0};f.push({target:_,name:"load",handler:()=>{unloadHandlersList(),t(_),c&&_.src&&URL.revokeObjectURL(_.src)}}),f.push({target:_,name:"error",handler:e=>{unloadHandlersList(),onErrorHandler(e),c&&_.src&&URL.revokeObjectURL(_.src)}}),f.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==_.src)return;unloadHandlersList();let t=Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);p.l.UseFallbackTexture=!1,onErrorHandler(t),c&&_.src&&URL.revokeObjectURL(_.src),_.src=""}}),f.forEach(e=>{e.target.addEventListener(e.name,e.handler)});let m="blob:"===h.substring(0,5),v="data:"===h.substring(0,5),noOfflineSupport=()=>{m||v||!s.g.IsCustomRequestAvailable?_.src=h:LoadFile(h,(e,t,i)=>{let r=!n&&i?i:n,s=new Blob([e],{type:r}),a=URL.createObjectURL(s);c=!0,_.src=a},void 0,r||void 0,!0,(e,t)=>{onErrorHandler(t)})};if(!m&&!v&&r&&r.enableTexturesOffline)r.open(()=>{r&&r.loadImage(h,_)},noOfflineSupport);else{if(-1!==h.indexOf("file:")){let e=decodeURIComponent(h.substring(5).toLowerCase());if(o.X.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(o.X.FilesToLoad[e])}catch(i){t=URL.createObjectURL(o.X.FilesToLoad[e])}_.src=t,c=!0}catch(e){_.src=""}return _}}noOfflineSupport()}return _},ReadFile=(e,t,i,r,s)=>{let n=new FileReader,o={onCompleteObservable:new a.y$,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),s&&(n.onerror=()=>{s(new ReadFileError(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),r?n.readAsArrayBuffer(e):n.readAsText(e),o},LoadFile=(e,t,i,r,s,n,l)=>{if(e.name)return ReadFile(e,t,i,s,n?e=>{n(void 0,e)}:void 0);if(-1!==e.indexOf("file:")){let r=decodeURIComponent(e.substring(5).toLowerCase());0===r.indexOf("./")&&(r=r.substring(2));let a=o.X.FilesToLoad[r];if(a)return ReadFile(a,t,i,s,n?e=>n(void 0,new LoadFileError(e.message,e.file)):void 0)}let{match:h,type:u}=TestBase64DataUrl(e);if(h){let i={onCompleteObservable:new a.y$,abort:()=>()=>{}};try{let i=s?DecodeBase64UrlToBinary(e):DecodeBase64UrlToString(e);t(i,void 0,u)}catch(e){n?n(void 0,e):_.Y.Error(e.message||"Failed to parse the Data URL")}return f.Q.SetImmediate(()=>{i.onCompleteObservable.notifyObservers(i)}),i}return RequestFile(e,(e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))},i,r,s,n?e=>{n(e.request,new LoadFileError(e.message,e.request))}:void 0,l)},RequestFile=(e,t,i,r,o,l,h)=>{e=_CleanUrl(e),e=g.PreprocessUrl(e);let u=g.BaseUrl+e,c=!1,d={onCompleteObservable:new a.y$,abort:()=>c=!0},requestFile=()=>{let e,r=new s.g,a=null,unbindEvents=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",onLoadEnd))},onLoadEnd=()=>{unbindEvents(),d.onCompleteObservable.notifyObservers(d),d.onCompleteObservable.clear(),i=void 0,e=null,onLoadEnd=null,l=void 0,h=void 0,t=void 0};d.abort=()=>{c=!0,onLoadEnd&&onLoadEnd(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==a&&(clearTimeout(a),a=null),r=null};let handleError=e=>{let t=e.message||"Unknown error";l&&r?l(new RequestFileError(t,r)):_.Y.Error(t)},retryLoop=d=>{if(r){if(r.open("GET",u),h)try{h(r)}catch(e){handleError(e);return}o&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),onLoadEnd&&r.addEventListener("loadend",onLoadEnd),e=()=>{if(!c&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!(0,n.CG)()||IsFileURL())){try{t&&t(o?r.response:r.responseText,r)}catch(e){handleError(e)}return}let i=g.DefaultRetryStrategy;if(i){let e=i(u,r,d);if(-1!==e){unbindEvents(),r=new s.g,a=setTimeout(()=>retryLoop(d+1),e);return}}let h=new RequestFileError("Error status: "+r.status+" "+r.statusText+" - Unable to load "+u,r);l&&l(h)}},r.addEventListener("readystatechange",e),r.send()}};retryLoop(0)};if(r&&r.enableSceneOffline){let noOfflineSupport=e=>{e&&e.status>400?l&&l(e):requestFile()};r.open(()=>{r&&r.loadFile(g.BaseUrl+e,e=>{!c&&t&&t(e),d.onCompleteObservable.notifyObservers(d)},i?e=>{!c&&i&&i(e)}:void 0,noOfflineSupport,o)},noOfflineSupport)}else requestFile();return d},IsFileURL=()=>"undefined"!=typeof location&&"file:"===location.protocol,IsBase64DataUrl=e=>m.test(e),TestBase64DataUrl=e=>{let t=m.exec(e);if(null===t||0===t.length)return{match:!1,type:""};{let e=t[0].replace("data:","").replace("base64,","");return{match:!0,type:e}}};function DecodeBase64UrlToBinary(e){return(0,u.HQ)(e.split(",")[1])}let DecodeBase64UrlToString=e=>(0,u.rP)(e.split(",")[1]);d.B._FileToolsLoadImage=LoadImage,d.B._FileToolsLoadFile=LoadFile,c.L._FileToolsLoadFile=LoadFile,Object.defineProperty(r={DecodeBase64UrlToBinary:DecodeBase64UrlToBinary,DecodeBase64UrlToString:DecodeBase64UrlToString,DefaultRetryStrategy:g.DefaultRetryStrategy,BaseUrl:g.BaseUrl,CorsBehavior:g.CorsBehavior,PreprocessUrl:g.PreprocessUrl,IsBase64DataUrl:IsBase64DataUrl,IsFileURL:IsFileURL,LoadFile:LoadFile,LoadImage:LoadImage,ReadFile:ReadFile,RequestFile:RequestFile,SetCorsBehavior:SetCorsBehavior},"DefaultRetryStrategy",{get:function(){return g.DefaultRetryStrategy},set:function(e){g.DefaultRetryStrategy=e}}),Object.defineProperty(r,"BaseUrl",{get:function(){return g.BaseUrl},set:function(e){g.BaseUrl=e}}),Object.defineProperty(r,"PreprocessUrl",{get:function(){return g.PreprocessUrl},set:function(e){g.PreprocessUrl=e}}),Object.defineProperty(r,"CorsBehavior",{get:function(){return g.CorsBehavior},set:function(e){g.CorsBehavior=e}})},320:function(e,t,i){i.d(t,{X:function(){return FilesInputStore}});let FilesInputStore=class FilesInputStore{};FilesInputStore.FilesToLoad={}},1032:function(e,t,i){i.d(t,{f:function(){return RandomGUID}});function RandomGUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}},4406:function(e,t,i){i.d(t,{K:function(){return InstantiationTools}});var r=i(9626),s=i(3048);let InstantiationTools=class InstantiationTools{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=(0,s.q)(e);if(t)return t;r.Y.Warn(e+" not found, you may have missed an import.");let i=e.split("."),n=window||this;for(let e=0,t=i.length;ee<10?"0"+e:""+e,t=new Date;return"["+padStr(t.getHours())+":"+padStr(t.getMinutes())+":"+padStr(t.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){if(void 0!==i&&!Logger._CheckLimit(t,i))return;let r=Logger._FormatMessage(t),s=this._Levels[e];s.logFunc&&s.logFunc("BJS - "+r);let n=`
${r}

`;Logger._AddLogEntry(n),Logger._GenerateLimitMessage(t,e)}static get LogCache(){return Logger._LogCache}static ClearLogCache(){Logger._LogCache="",Logger._LogLimitOutputs={},Logger.errorsCount=0}static set LogLevels(e){Logger.Log=Logger._LogDisabled,Logger.Warn=Logger._LogDisabled,Logger.Error=Logger._LogDisabled,[Logger.MessageLogLevel,Logger.WarningLogLevel,Logger.ErrorLogLevel].forEach(t=>{if((e&t)===t){let e=this._Levels[t];Logger[e.name]=Logger._LogEnabled.bind(Logger,t)}})}};Logger.NoneLogLevel=0,Logger.MessageLogLevel=1,Logger.WarningLogLevel=2,Logger.ErrorLogLevel=4,Logger.AllLogLevel=7,Logger.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",Logger._LogCache="",Logger._LogLimitOutputs={},Logger._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],Logger.errorsCount=0,Logger.Log=Logger._LogEnabled.bind(Logger,Logger.MessageLogLevel),Logger.Warn=Logger._LogEnabled.bind(Logger,Logger.WarningLogLevel),Logger.Error=Logger._LogEnabled.bind(Logger,Logger.ErrorLogLevel)},4800:function(e,t,i){i.d(t,{he:function(){return EventState},y$:function(){return Observable}});let EventState=class EventState{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}};let Observer=class Observer{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}};let Observable=class Observable{static FromPromise(e,t){let i=new Observable;return e.then(e=>{i.notifyObservers(e)}).catch(e=>{if(t)t.notifyObservers(e);else throw e}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=[],this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new EventState(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,s=!1){if(!e)return null;let n=new Observer(e,t,r);return n.unregisterOnNextCall=s,i?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;let t=this._observers.indexOf(e);return -1!==t&&(this._deferUnregister(e),!0)}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return -1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,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,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let n=this._eventState;for(let a of(n.mask=t,n.target=i,n.currentTarget=r,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=s,this._observers))if(!a._willBeUnregistered&&(a.mask&t&&(a.unregisterOnNextCall&&this._deferUnregister(a),a.scope?n.lastReturnValue=a.callback.apply(a.scope,[e,n]):n.lastReturnValue=a.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let 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(){let e=new Observable;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}},7263:function(e,t,i){i.d(t,{z:function(){return PerfCounter}});var r=i(7662);let PerfCounter=class PerfCounter{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){PerfCounter.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){PerfCounter.Enabled&&(this._startMonitoringTime=r.F.Now)}endMonitoring(e=!0){if(!PerfCounter.Enabled)return;e&&this.fetchNewFrame();let t=r.F.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;let e=r.F.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}};PerfCounter.Enabled=!0},8786:function(e,t,i){i.d(t,{A:function(){return PerformanceMonitor}});var r=i(7662);let PerformanceMonitor=class PerformanceMonitor{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new RollingAverage(e)}sampleFrame(e=r.F.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){let 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(){let 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()}};let RollingAverage=class RollingAverage{constructor(e){this._samples=Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let 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;let 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){let t=this._samples.length;return(e%t+t)%t}}},7662:function(e,t,i){i.d(t,{F:function(){return PrecisionDate}});var r=i(7209);let PrecisionDate=class PrecisionDate{static get Now(){return(0,r.CG)()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},9983:function(e,t,i){i.d(t,{b:function(){return RetryStrategy}});let RetryStrategy=class RetryStrategy{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},8355:function(e,t,i){i.d(t,{f:function(){return SmartArrayNoDuplicate},t:function(){return SmartArray}});let SmartArray=class SmartArray{constructor(e){this.length=0,this.data=Array(e),this._id=SmartArray._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return -1!==this.indexOf(e)}};SmartArray._GlobalId=0;let SmartArrayNoDuplicate=class SmartArrayNoDuplicate extends SmartArray{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=(this.length+e.length)*2);for(let t=0;tthis.add(e,t))}get(e){let t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e))&&this.add(e,i),i}getOrAdd(e,t){let i=this.get(e);return void 0!==i?i:(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){let 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(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}}},9005:function(e,t,i){i.d(t,{Gh:function(){return EncodeArrayBufferToBase64},HQ:function(){return DecodeBase64ToBinary},rP:function(){return DecodeBase64ToString}});let EncodeArrayBufferToBase64=e=>{let t,i,r,s,n,a,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",u=0,c=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;u>2,n=(3&t)<<4|i>>4,a=(15&i)<<2|r>>6,o=63&r,isNaN(i)?a=o=64:isNaN(r)&&(o=64),h+=l.charAt(s)+l.charAt(n)+l.charAt(a)+l.charAt(o);return h},DecodeBase64ToString=e=>atob(e),DecodeBase64ToBinary=e=>{let t=DecodeBase64ToString(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;eTags.HasTags(e),e.addTags=t=>Tags.AddTagsTo(e,t),e.removeTags=t=>Tags.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>Tags.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;let t=e._tags;for(let 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)return e._tags;{let t=[];for(let i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}}static AddTagsTo(e,t){if(!t||"string"!=typeof t)return;let i=t.split(" ");i.forEach(function(t){Tags._AddTagTo(e,t)})}static _AddTagTo(e,t){""===(t=t.trim())||"true"===t||"false"===t||t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(Tags.EnableFor(e),e._tags[t]=!0)}static RemoveTagsFrom(e,t){if(!Tags.HasTags(e))return;let i=t.split(" ");for(let t in i)Tags._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?Tags.HasTags(e):r.q.Eval(t,t=>Tags.HasTags(e)&&e._tags[t]))}}},4490:function(e,t,i){i.d(t,{Q:function(){return TimingTools}});var r=i(7209);let TimingTools=class TimingTools{static SetImmediate(e){(0,r.CG)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},5132:function(e,t,i){i.d(t,{$g:function(){return AsyncLoop},w1:function(){return Tools}});var r=i(4800),s=i(7209),n=i(9626),a=i(3189),o=i(7662),l=i(6131),h=i(2962),u=i(6030),c=i(1166),d=i(4490),p=i(4406),_=i(1032);let Tools=class Tools{static get BaseUrl(){return c.rN.BaseUrl}static set BaseUrl(e){c.rN.BaseUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||!(-1===e.indexOf("://")||-1===e.indexOf(".")||-1===e.indexOf("/")||e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){(0,c.vP)(e,e=>{i(e)},void 0,void 0,t,(e,t)=>{r(t)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(Tools.ScriptBaseUrl&&e.startsWith(Tools._DefaultCdnUrl)){let t="/"===Tools.ScriptBaseUrl[Tools.ScriptBaseUrl.length-1]?Tools.ScriptBaseUrl.substring(0,Tools.ScriptBaseUrl.length-1):Tools.ScriptBaseUrl;e=e.replace(Tools._DefaultCdnUrl,t)}return e=Tools.ScriptPreprocessUrl(e),t&&(e=Tools.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=Tools.GetBabylonScriptURL(e),Tools.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=Tools.GetBabylonScriptURL(e),Tools.LoadScriptAsync(e)}static LoadScript(e,t,i,r){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}if(!(0,s.CG)()){null==i||i(`Cannot load script '${e}' outside of a window or a worker`);return}let n=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},n.appendChild(a)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(e,t)=>{i(t||Error(e))})})}static ReadFileAsDataURL(e,t,i){let s=new FileReader,n={onCompleteObservable:new r.y$,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,r,s){return(0,c.Ip)(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]),i=window.URL,r=i.createObjectURL(t);return r}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){a.j.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{let r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,n=new Uint8Array(s);for(let e=0;et(e)):e.toBlob(function(e){t(e)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let e=new Date,i=(e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2);t="screenshot_"+i+".png"}Tools.Download(e,t)}else if(e&&"undefined"!=typeof URL){let t=URL.createObjectURL(e),i=window.open("");if(!i)return;let r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(Tools._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(e=>{let i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{let e=i.result;t(e)}});return}let r=e.toDataURL(i,s);t(r)}}else this.ToBlob(e,function(e){e&&Tools.DownloadBlob(e,r),t&&t("")},i,s)}static Download(e,t){if("undefined"==typeof URL)return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",n=!1,a){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,a=!1,o,h=!1,u=!1,c=!0,d){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,a,o=!1,h=!1,u=!0,c){throw(0,l.S)("ScreenshotTools")}static RandomId(){return(0,_.f)()}static IsBase64(e){return(0,c.VL)(e)}static DecodeBase64(e){return(0,c.$K)(e)}static get errorsCount(){return n.Y.errorsCount}static Log(e){n.Y.Log(e)}static Warn(e){n.Y.Warn(e)}static Error(e){n.Y.Error(e)}static get LogCache(){return n.Y.LogCache}static ClearLogCache(){n.Y.ClearLogCache()}static set LogLevels(e){n.Y.LogLevels=e}static set PerformanceLogLevel(e){if((e&Tools.PerformanceUserMarkLogLevel)===Tools.PerformanceUserMarkLogLevel){Tools.StartPerformanceCounter=Tools._StartUserMark,Tools.EndPerformanceCounter=Tools._EndUserMark;return}if((e&Tools.PerformanceConsoleLogLevel)===Tools.PerformanceConsoleLogLevel){Tools.StartPerformanceCounter=Tools._StartPerformanceConsole,Tools.EndPerformanceCounter=Tools._EndPerformanceConsole;return}Tools.StartPerformanceCounter=Tools._StartPerformanceCounterDisabled,Tools.EndPerformanceCounter=Tools._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Tools._Performance){if(!(0,s.CG)())return;Tools._Performance=window.performance}t&&Tools._Performance.mark&&Tools._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Tools._Performance.mark&&(Tools._Performance.mark(e+"-End"),Tools._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Tools._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Tools._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return o.F.Now}static GetClassName(e,t=!1){let i=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let r=t?e:Object.getPrototypeOf(e);i=r.constructor.__bjsclassName__}i||(i=typeof e)}return i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return!!(0,s.up)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}};Tools.UseCustomRequestHeaders=!1,Tools.CustomRequestHeaders=h.g.CustomRequestHeaders,Tools.GetDOMTextContent=s.v,Tools._DefaultCdnUrl="https://cdn.babylonjs.com",Tools.GetAbsoluteUrl="object"==typeof document?e=>{let t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Tools.NoneLogLevel=n.Y.NoneLogLevel,Tools.MessageLogLevel=n.Y.MessageLogLevel,Tools.WarningLogLevel=n.Y.WarningLogLevel,Tools.ErrorLogLevel=n.Y.ErrorLogLevel,Tools.AllLogLevel=n.Y.AllLogLevel,Tools.IsWindowObjectExist=s.CG,Tools.PerformanceNoneLogLevel=0,Tools.PerformanceUserMarkLogLevel=1,Tools.PerformanceConsoleLogLevel=2,Tools.StartPerformanceCounter=Tools._StartPerformanceCounterDisabled,Tools.EndPerformanceCounter=Tools._EndPerformanceCounterDisabled;let AsyncLoop=class AsyncLoop{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?r.breakLoop():setTimeout(()=>{for(let n=0;n=e)break;if(i(a),s&&s()){r.breakLoop();break}}r.executeNext()},n)},r)}};u.l.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"},3048:function(e,t,i){i.d(t,{H:function(){return RegisterClass},q:function(){return GetClass}});let r={};function RegisterClass(e,t){r[e]=t}function GetClass(e){return r[e]}},7531:function(e,t,i){i.d(t,{K:function(){return UniqueIdGenerator}});let UniqueIdGenerator=class UniqueIdGenerator{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}};UniqueIdGenerator._UniqueIdCounter=1},2962:function(e,t,i){function createXMLHttpRequest(){return"undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest}i.d(t,{g:function(){return WebRequest}});let WebRequest=class WebRequest{constructor(){this._xhr=createXMLHttpRequest(),this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(WebRequest.CustomRequestHeaders).length>0||WebRequest.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(let e in WebRequest.CustomRequestHeaders){let t=WebRequest.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return WebRequest.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,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){WebRequest.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(let e of WebRequest.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}return 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)}};WebRequest.CustomRequestHeaders={},WebRequest.CustomRequestModifiers=[],WebRequest.SkipRequestModificationForBabylonCDN=!0},5184:function(e,t,i){i.d(t,{O:function(){return PostProcessManager}});var r=i(1295);let PostProcessManager=class PostProcessManager{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[r.o.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[r.o.PositionKind]=new r.o(this._scene.getEngine(),e,r.o.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let 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(){let e=this._vertexBuffers[r.o.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){let i=this._scene.activeCamera;return!!(i&&(t=t||i._postProcesses.filter(e=>null!=e))&&0!==t.length&&this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0)}directRender(e,t=null,i=!1,r=0,s=0,n=!1){var a;let o=this._scene.getEngine();for(let l=0;lnull!=e)).length||!this._scene.postProcessesEnabled)return;let o=this._scene.getEngine();for(let l=0,h=r.length;lt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.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,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&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;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;ie=e.concat(t.bones)),e}};AbstractScene._BabylonFileParsers={},AbstractScene._IndividualBabylonFileParsers={}},9111:function(e,t,i){let r,s;i.d(t,{YfP:function(){return ArcRotateCamera},HEv:function(){return rg.HE},Dso:function(){return postProcess_PostProcess},xsS:function(){return rN.x},xeF:function(){return sg.x},vGS:function(){return s_.v},w1W:function(){return rW.w1},Pa4:function(){return rm.P},fWK:function(){return webgpuEngine_WebGPUEngine}});var n,a,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,C,E,b,y,P,R,A,I,M,D,O,N,F,B,L,w,U,V,k,G,z,W,H,X,Y,j,K,$,Q,Z,J,ee,et,ei,er,es,en,ea,eo,el,eh,eu,ec,ed,ep,e_,ef,em,eg,ev,ex,eT,eS,eC,eE,eb,ey,eP,eR,eA,eI,eM,eD,eO,eN,eF,eB,eL,ew,eU,eV,ek,eG,ez,eW,eH,eX,eY,ej,eq,eK,e$,eQ,eZ,eJ,e0,e1,e2,e3,e4,e5,e6,e8,e7,e9,te,tt,ti,tr,ts,tn,ta,to,tl,th,tu,tc,td,tp,t_,tf,tm,tg,tv,tx,tT,tS,tC,tE,tb,ty,tP,tR,tA,tI,tM,tD,tO,tN,tF,tB,tL,tw,tU,tV,tk,tG,tz,tW,tH,tX,tY,tj,tq,tK,t$,tQ,tZ,tJ,t0,t1,t2,t3,t4,t5,t6,t8,t7,t9,ie,it,ii,ir,is,ia,io,il,ih,iu,ic,id,ip,i_,im,ig,iv,ix,iT,iS,iC,iE,ib,iy,iP,iR,iA,iI,iM,iD,iO,iN,iF,iB,iL,iw,iU,iV,ik,iG,iz,iW,iH,iX,iY,ij,iq,iK,i$,iQ,iZ,iJ,i0,i1,i2,i3,i4,i5,i6,i8,i7,i9,re,rt,ri,rr,rs,rn,ra,ro,rl,rh,ru,rc,rd,rp=i(800),r_=i(3621),rf=i(4800),rm=i(78),rg=i(2983),rv=i(3048);let Action=class Action{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new rf.y$,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){let e=this._condition;if(!e)return!0;let t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){let t=this._evaluateConditionForCurrentFrame();t&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){}_serialize(e,t){let i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){let e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}};Action._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof rm.FM?e.x+", "+e.y:e instanceof rm.P?e.x+", "+e.y+", "+e.z:e instanceof rg.Wo?e.r+", "+e.g+", "+e.b:e instanceof rg.HE?e.r+", "+e.g+", "+e.b+", "+e.a:e,Action._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),(0,rv.H)("BABYLON.Action",Action);var rx=i(9528);let Condition=class Condition{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}};let ValueCondition=class ValueCondition extends Condition{static get IsEqual(){return ValueCondition._IsEqual}static get IsDifferent(){return ValueCondition._IsDifferent}static get IsGreater(){return ValueCondition._IsGreater}static get IsLesser(){return ValueCondition._IsLesser}constructor(e,t,i,r,s=ValueCondition.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case ValueCondition.IsGreater:return this._effectiveTarget[this._property]>this.value;case ValueCondition.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1);let t=this._scene.meshes.filter(e=>e.actionManager===this);for(let e of t)e.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=ActionManager.OnPickTrigger&&t.trigger<=ActionManager.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=ActionManager.OnPickTrigger&&t.trigger<=ActionManager.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===ActionManager.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(rT.Y.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,ActionManager.Triggers[e.trigger]?ActionManager.Triggers[e.trigger]++:ActionManager.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){let t=this.actions.indexOf(e);return -1!==t&&(this.actions.splice(t,1),ActionManager.Triggers[e.trigger]-=1,0===ActionManager.Triggers[e.trigger]&&delete ActionManager.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{let i=(0,rv.q)("BABYLON."+e);return i&&new i(...t)},parseParameter=(e,t,i,r)=>{if(null===r){let e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}let s=r.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;let o=[],l=null,h=null,u=e.combine&&e.combine.length>0;if(2===e.type?o.push(r):o.push(t),u){let t=[];for(let i=0;i0){let e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:ActionManager[s.name],parameter:t}}else r=ActionManager[s.name];for(let e=0;e=0?o.referenceFrame:0,u=0,c=l._keys[0],d=l._keys.length-1,p=l._keys[d],_={referenceValue:c.value,referencePosition:rm.jp.Vector3[0],referenceQuaternion:rm.jp.Quaternion[0],referenceScaling:rm.jp.Vector3[1],keyPosition:rm.jp.Vector3[2],keyQuaternion:rm.jp.Quaternion[1],keyScaling:rm.jp.Vector3[3]},f=c.frame,m=p.frame;if(o.range){let e=l.getRange(o.range);e&&(f=e.from,m=e.to)}else f=null!==(n=o.fromFrame)&&void 0!==n?n:f,m=null!==(a=o.toFrame)&&void 0!==a?a:m;if(f!==c.frame&&(u=l.createKeyForFrame(f)),m!==p.frame&&(d=l.createKeyForFrame(m)),1===l._keys.length){let e=l._getKeyValue(l._keys[0]);_.referenceValue=e.clone?e.clone():e}else if(h<=c.frame){let e=l._getKeyValue(c.value);_.referenceValue=e.clone?e.clone():e}else if(h>=p.frame){let e=l._getKeyValue(p.value);_.referenceValue=e.clone?e.clone():e}else{rR.key=0;let e=l._interpolate(h,rR);_.referenceValue=e.clone?e.clone():e}l.dataType===animation_Animation.ANIMATIONTYPE_QUATERNION?_.referenceValue.normalize().conjugateInPlace():l.dataType===animation_Animation.ANIMATIONTYPE_MATRIX&&(_.referenceValue.decompose(_.referenceScaling,_.referenceQuaternion,_.referencePosition),_.referenceQuaternion.normalize().conjugateInPlace());let g=Number.MAX_VALUE,v=o.clipKeys?[]:null;for(let e=u;e<=d;e++){let t=l._keys[e];if(v&&(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},g===Number.MAX_VALUE&&(g=t.frame),t.frame-=g,v.push(t)),!e||l.dataType===animation_Animation.ANIMATIONTYPE_FLOAT||t.value!==c.value)switch(l.dataType){case animation_Animation.ANIMATIONTYPE_MATRIX:t.value.decompose(_.keyScaling,_.keyQuaternion,_.keyPosition),_.keyPosition.subtractInPlace(_.referencePosition),_.keyScaling.divideInPlace(_.referenceScaling),_.referenceQuaternion.multiplyToRef(_.keyQuaternion,_.keyQuaternion),rm.y3.ComposeToRef(_.keyScaling,_.keyQuaternion,_.keyPosition,t.value);break;case animation_Animation.ANIMATIONTYPE_QUATERNION:_.referenceValue.multiplyToRef(t.value,t.value);break;case animation_Animation.ANIMATIONTYPE_VECTOR2:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_COLOR3:case animation_Animation.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(_.referenceValue,t.value);break;case animation_Animation.ANIMATIONTYPE_SIZE:t.value.width-=_.referenceValue.width,t.value.height-=_.referenceValue.height;break;default:t.value-=_.referenceValue}}return v&&l.setKeys(v,!0),l}static TransitionTo(e,t,i,r,s,n,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;let l=s*(a/1e3);n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);let h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=o,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=[],this._events=[],this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=void 0===s?animation_Animation.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=animation_Animation._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType]+", nKeys: "+(this._keys?this._keys.length:"none")+", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;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=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let r=this._keys,s=r.length,n=t.key;for(;n>=0&&e=r[n+1].frame;)++n;if(t.key=n,n<0)return i?void 0:this._getKeyValue(r[0].value);if(n+1>s-1)return i?void 0:this._getKeyValue(r[s-1].value);let a=r[n],o=r[n+1];if(i&&(e===a.frame||e===o.frame))return;let l=this._getKeyValue(a.value),h=this._getKeyValue(o.value);if(a.interpolation===td.STEP)return o.frame>e?l:h;let u=void 0!==a.outTangent&&void 0!==o.inTangent,c=o.frame-a.frame,d=(e-a.frame)/c,p=this.getEasingFunction();switch(null!==p&&(d=p.ease(d)),this.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:{let e=u?this.floatInterpolateFunctionWithTangents(l,a.outTangent*c,h,o.inTangent*c,d):this.floatInterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return t.offsetValue*t.repeatCount+e}break}case animation_Animation.ANIMATIONTYPE_QUATERNION:{let e=u?this.quaternionInterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.quaternionInterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:break;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.addInPlace(t.offsetValue.scale(t.repeatCount))}return e}case animation_Animation.ANIMATIONTYPE_VECTOR3:{let e=u?this.vector3InterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.vector3InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_VECTOR2:{let e=u?this.vector2InterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.vector2InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_SIZE:switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(l,h,d);case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return this.sizeInterpolateFunction(l,h,d).add(t.offsetValue.scale(t.repeatCount))}break;case animation_Animation.ANIMATIONTYPE_COLOR3:{let e=u?this.color3InterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.color3InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_COLOR4:{let e=u?this.color4InterpolateFunctionWithTangents(l,a.outTangent.scale(c),h,o.inTangent.scale(c),d):this.color4InterpolateFunction(l,h,d);switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:return e;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return e.add(t.offsetValue.scale(t.repeatCount))}break}case animation_Animation.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case animation_Animation.ANIMATIONLOOPMODE_CYCLE:case animation_Animation.ANIMATIONLOOPMODE_CONSTANT:case animation_Animation.ANIMATIONLOOPMODE_YOYO:if(animation_Animation.AllowMatricesInterpolation)return this.matrixInterpolateFunction(l,h,d,t.workValue);return l;case animation_Animation.ANIMATIONLOOPMODE_RELATIVE:return l}}return 0}matrixInterpolateFunction(e,t,i,r){return animation_Animation.AllowMatrixDecomposeForInterpolation?r?(rm.y3.DecomposeLerpToRef(e,t,i,r),r):rm.y3.DecomposeLerp(e,t,i):r?(rm.y3.LerpToRef(e,t,i,r),r):rm.y3.Lerp(e,t,i)}clone(){let e=new animation_Animation(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)for(let t in e._ranges={},this._ranges){let i=this._ranges[t];i&&(e._ranges[t]=i.clone())}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){rR.key=0;let t=this._interpolate(e,rR,!0);if(!t)return rR.key===e?rR.key:rR.key+1;let i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(rR.key+1,0,i),rR.key+1}serialize(){let 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;let t=this.dataType;e.keys=[];let i=this.getKeys();for(let r=0;r=2&&(r=l.values[1]),l.values.length>=3&&(a=l.values[2]),l.values.length>=4&&(o=l.values[3]);break;case animation_Animation.ANIMATIONTYPE_QUATERNION:if(t=rm._f.FromArray(l.values),l.values.length>=8){let e=rm._f.FromArray(l.values.slice(4,8));e.equals(rm._f.Zero())||(r=e)}if(l.values.length>=12){let e=rm._f.FromArray(l.values.slice(8,12));e.equals(rm._f.Zero())||(a=e)}l.values.length>=13&&(o=l.values[12]);break;case animation_Animation.ANIMATIONTYPE_MATRIX:t=rm.y3.FromArray(l.values),l.values.length>=17&&(o=l.values[16]);break;case animation_Animation.ANIMATIONTYPE_COLOR3:t=rg.Wo.FromArray(l.values),l.values[3]&&(r=rg.Wo.FromArray(l.values[3])),l.values[4]&&(a=rg.Wo.FromArray(l.values[4])),l.values[5]&&(o=l.values[5]);break;case animation_Animation.ANIMATIONTYPE_COLOR4:t=rg.HE.FromArray(l.values),l.values[4]&&(r=rg.HE.FromArray(l.values[4])),l.values[5]&&(a=rg.HE.FromArray(l.values[5])),l.values[6]&&(o=rg.HE.FromArray(l.values[6]));break;case animation_Animation.ANIMATIONTYPE_VECTOR3:default:t=rm.P.FromArray(l.values),l.values[3]&&(r=rm.P.FromArray(l.values[3])),l.values[4]&&(a=rm.P.FromArray(l.values[4])),l.values[5]&&(o=l.values[5])}let h={};h.frame=l.frame,h.value=t,void 0!=r&&(h.inTangent=r),void 0!=a&&(h.outTangent=a),void 0!=o&&(h.interpolation=o),n.push(h)}if(r.setKeys(n),e.ranges)for(i=0;i{let s=new rP.g;s.addEventListener("readystatechange",()=>{if(4==s.readyState){if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){let e=[];for(let i of t)e.push(this.Parse(i));i(e)}else{let r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")}}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{let r=new rP.g;r.addEventListener("readystatechange",()=>{if(4==r.readyState){if(200==r.status){let i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){let r=JSON.parse(i.animations),s=[];for(let t of r.animations){let i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{let r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)}}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}};animation_Animation._UniqueIdGenerator=0,animation_Animation.AllowMatricesInterpolation=!1,animation_Animation.AllowMatrixDecomposeForInterpolation=!0,animation_Animation.SnippetUrl="https://snippet.babylonjs.com",animation_Animation.ANIMATIONTYPE_FLOAT=0,animation_Animation.ANIMATIONTYPE_VECTOR3=1,animation_Animation.ANIMATIONTYPE_QUATERNION=2,animation_Animation.ANIMATIONTYPE_MATRIX=3,animation_Animation.ANIMATIONTYPE_COLOR3=4,animation_Animation.ANIMATIONTYPE_COLOR4=7,animation_Animation.ANIMATIONTYPE_VECTOR2=5,animation_Animation.ANIMATIONTYPE_SIZE=6,animation_Animation.ANIMATIONLOOPMODE_RELATIVE=0,animation_Animation.ANIMATIONLOOPMODE_CYCLE=1,animation_Animation.ANIMATIONLOOPMODE_CONSTANT=2,animation_Animation.ANIMATIONLOOPMODE_YOYO=4,animation_Animation.CreateFromSnippetAsync=animation_Animation.ParseFromSnippetAsync,(0,rv.H)("BABYLON.Animation",animation_Animation),ry.N._AnimationRangeFactory=(e,t,i)=>new AnimationRange(e,t,i);let InterpolateValueAction=class InterpolateValueAction extends Action{constructor(e,t,i,r,s=1e3,n,a,o){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new rf.y$,this.propertyPath=i,this.value=r,this.duration=s,this.stopOtherAnimations=a,this.onInterpolationDone=o,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){let e;let t=this._actionManager.getScene(),i=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=animation_Animation.ANIMATIONTYPE_FLOAT;else if(this.value instanceof rg.Wo)e=animation_Animation.ANIMATIONTYPE_COLOR3;else if(this.value instanceof rm.P)e=animation_Animation.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof rm.y3)e=animation_Animation.ANIMATIONTYPE_MATRIX;else if(this.value instanceof rm._f)e=animation_Animation.ANIMATIONTYPE_QUATERNION;else{rT.Y.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}let r=new animation_Animation("InterpolateValueAction",this._property,100*(1e3/this.duration),e,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(i),this.stopOtherAnimations&&t.stopAnimation(this._effectiveTarget),t.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()})}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[Action._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:Action._SerializeValueAsString(this.value)},{name:"duration",value:Action._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:Action._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}};(0,rv.H)("BABYLON.InterpolateValueAction",InterpolateValueAction);let rA=Object.freeze(new rm._f(0,0,0,0)),rI=Object.freeze(rm.P.Zero()),rM=Object.freeze(rm.FM.Zero()),rD=Object.freeze(Size.Zero()),rO=Object.freeze(rg.Wo.Black());let RuntimeAnimation=class RuntimeAnimation{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,i,r){if(this._events=[],this._currentFrame=0,this._originalValue=[],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._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===animation_Animation.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=rm.y3.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){let e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(let 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];let s=t.getEvents();s&&s.length>0&&s.forEach(e=>{this._events.push(e._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e[i[0]];for(let e=1;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);let i=this._events;if(i.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);let c=i-t,d=e*(l.framePerSecond*s)/1e3+this._absoluteFrameOffset,p=0;if(r&&this._animationState.loopMode===animation_Animation.ANIMATIONLOOPMODE_YOYO){let e=(d-t)/c;d=Math.abs(Math.sin(e*Math.PI))*c+t}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&d>=c)u=!1,p=l._getKeyValue(this._maxValue);else if(!r&&t>=i&&d<=c)u=!1,p=l._getKeyValue(this._minValue);else if(this._animationState.loopMode!==animation_Animation.ANIMATIONLOOPMODE_CYCLE){let e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=animation_Animation.ANIMATIONLOOPMODE_CYCLE;let r=l._interpolate(t,this._animationState),s=l._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),l.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-r;break;case animation_Animation.ANIMATIONTYPE_QUATERNION:case animation_Animation.ANIMATIONTYPE_VECTOR3:case animation_Animation.ANIMATIONTYPE_VECTOR2:case animation_Animation.ANIMATIONTYPE_SIZE:case animation_Animation.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(r)}this._highLimitsCache[e]=s}p=this._highLimitsCache[e],a=this._offsetsCache[e]}if(void 0===a)switch(l.dataType){case animation_Animation.ANIMATIONTYPE_FLOAT:a=0;break;case animation_Animation.ANIMATIONTYPE_QUATERNION:a=rA;break;case animation_Animation.ANIMATIONTYPE_VECTOR3:a=rI;break;case animation_Animation.ANIMATIONTYPE_VECTOR2:a=rM;break;case animation_Animation.ANIMATIONTYPE_SIZE:a=rD;break;case animation_Animation.ANIMATIONTYPE_COLOR3:a=rO}if(this._host&&this._host.syncRoot){let e=this._host.syncRoot,i=(e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame);o=t+c*i}else o=d>0&&t>i||d<0&&t0&&this.currentFrame>o||s<0&&this.currentFrame0?0:l.getKeys().length-1}this._currentFrame=o,this._animationState.repeatCount=0===c?0:d/c>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=a;let f=l._interpolate(o,this._animationState);if(this.setValue(f,n),_.length){for(let e=0;e<_.length;e++)if(c>0&&o>=_[e].frame&&_[e].frame>=t||c<0&&o<=_[e].frame&&_[e].frame<=t){let t=_[e];t.isDone||(t.onlyOnce&&(_.splice(e,1),e--),t.isDone=!0,t.action(o))}}return u||(this._stopped=!0),u}};var rN=i(6540),rF=i(7662),rB=i(4254),rL=i(524);let Bone=class Bone extends ry.N{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,i=null,r=null,s=null,n=null,a=null){var o;super(e,t.getScene()),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=null!==(o=null==r?void 0:r.clone())&&void 0!==o?o:rm.y3.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=n?n:this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new rm.y3,this._absoluteBindMatrix=new rm.y3,this._absoluteInverseBindMatrix=new rm.y3,this._finalMatrix=new rm.y3,t.bones.push(this),this.setParent(i,!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){let 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(){var e;if(this._linkedTransformNode){let t=rm.jp.Vector3[0],i=rm.jp.Quaternion[0],r=rm.jp.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:rm._f.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}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=rm.P.Zero(),this._localRotation=rm._f.Zero(),this._localPosition=rm.P.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,rm.y3.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?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;ethis._absoluteBindMatrix.determinant()?-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=rL.T.LOCAL,i,r=!0){let s=this.getLocalMatrix();if(t==rL.T.LOCAL)r?(s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z)):s.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let n=Bone._TmpMats[0],a=Bone._TmpVecs[0];this.parent?i&&t?(n.copyFrom(this.parent.getAbsoluteMatrix()),n.multiplyToRef(t,n)):n.copyFrom(this.parent.getAbsoluteMatrix()):rm.y3.IdentityToRef(n),r&&n.setTranslationFromFloats(0,0,0),n.invert(),rm.P.TransformCoordinatesToRef(e,n,a),r?(s.addAtIndex(12,a.x),s.addAtIndex(13,a.y),s.addAtIndex(14,a.z)):s.setTranslationFromFloats(a.x,a.y,a.z)}this._markAsDirtyAndDecompose()}translate(e,t=rL.T.LOCAL,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=rL.T.LOCAL,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,rL.T.WORLD,t)}scale(e,t,i,r=!1){let s=this.getLocalMatrix(),n=Bone._TmpMats[0];for(let r of(rm.y3.ScalingToRef(e,t,i,n),n.multiplyToRef(s,s),n.invert(),this.children)){let s=r.getLocalMatrix();s.multiplyToRef(n,s),s.multiplyAtIndex(12,e),s.multiplyAtIndex(13,t),s.multiplyAtIndex(14,i),r._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(let s of this.children)s.scale(e,t,i,r)}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,i,r=rL.T.LOCAL,s){if(r===rL.T.LOCAL){let n=Bone._TmpQuat;rm._f.RotationYawPitchRollToRef(e,t,i,n),this.setRotationQuaternion(n,r,s);return}let n=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,s))return;let a=Bone._TmpMats[1];rm.y3.RotationYawPitchRollToRef(e,t,i,a),n.multiplyToRef(a,a),this._rotateWithMatrix(a,r,s)}rotate(e,t,i=rL.T.LOCAL,r){let s=Bone._TmpMats[0];s.setTranslationFromFloats(0,0,0),rm.y3.RotationAxisToRef(e,t,s),this._rotateWithMatrix(s,i,r)}setAxisAngle(e,t,i=rL.T.LOCAL,r){if(i===rL.T.LOCAL){let s=Bone._TmpQuat;rm._f.RotationAxisToRef(e,t,s),this.setRotationQuaternion(s,i,r);return}let s=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;let n=Bone._TmpMats[1];rm.y3.RotationAxisToRef(e,t,n),s.multiplyToRef(n,n),this._rotateWithMatrix(n,i,r)}setRotation(e,t=rL.T.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=rL.T.LOCAL,i){if(t===rL.T.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}let r=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=Bone._TmpMats[1];rm.y3.FromQuaternionToRef(e,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,t,i)}setRotationMatrix(e,t=rL.T.LOCAL,i){if(t===rL.T.LOCAL){let r=Bone._TmpQuat;rm._f.FromRotationMatrixToRef(e,r),this.setRotationQuaternion(r,t,i);return}let r=Bone._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=Bone._TmpMats[1];s.copyFrom(e),r.multiplyToRef(e,s),this._rotateWithMatrix(s,t,i)}_rotateWithMatrix(e,t=rL.T.LOCAL,i){let r=this.getLocalMatrix(),s=r.m[12],n=r.m[13],a=r.m[14],o=this.getParent(),l=Bone._TmpMats[3],h=Bone._TmpMats[4];o&&t==rL.T.WORLD?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):t==rL.T.WORLD&&i?(l.copyFrom(i.getWorldMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(s,n,a),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){let i=Bone._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),rm.y3.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):rm.y3.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=rL.T.LOCAL,t=null){let i=rm.P.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=rL.T.LOCAL,t,i){if(e==rL.T.LOCAL){let e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let r=Bone._TmpMats[0];t&&e?(r.copyFrom(this.getAbsoluteMatrix()),r.multiplyToRef(e,r)):r=this.getAbsoluteMatrix(),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){let t=rm.P.Zero();return this.getPositionToRef(rL.T.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(rL.T.WORLD,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);let e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}let e=this.children,t=e.length;for(let i=0;i-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(s)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i-1){let s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){let r=s[i];(!e||r.animation.name==e)&&(!t||t(r.target))&&(r.dispose(),s.splice(i,1))}0==s.length&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else{let e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);let t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){let t;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 i=!1,r=this._runtimeAnimations;for(t=0;t0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;let t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;let i=this._animationTime;for(let e=0;ee.playOrder-t.playOrder)},rN.x.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,n=1,a,o,l,h,u=!1){let c=this.beginAnimation(e,t,i,s,n,a,o,!1,l,h,u);return c.weight=r,c},rN.x.prototype.beginAnimation=function(e,t,i,r,s=1,n,a,o=!0,l,h,u=!1){t>i&&s>0&&(s*=-1),o&&this.stopAnimation(e,void 0,l),a||(a=new Animatable(this,e,t,i,r,s,n,void 0,h,u));let c=!l||l(e);if(e.animations&&c&&a.appendAnimations(e,e.animations),e.getAnimatables){let u=e.getAnimatables();for(let e=0;er&&n>0)n*=-1;else if(r>i&&n<0){let e=r;r=i,i=e}let h=new Animatable(this,e,i,r,s,n,a,t,o,l);return h},rN.x.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,n,a,o,l,h=!1){let u=e.getDescendants(t),c=[];for(let t of(c.push(this.beginDirectAnimation(e,i,r,s,n,a,o,l,h)),u))c.push(this.beginDirectAnimation(t,i,r,s,n,a,o,l,h));return c},rN.x.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,s),o.scaleAndAddToRef(l,i)}s.normalize()}for(let t=0;t0)s.copyFrom(r);else if(1===e.animations.length){if(rm._f.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,n,a=1;if(e.totalWeight<1){let t=1-e.totalWeight;n=[],(i=[]).push(r),n.push(t)}else{if(2===e.animations.length&&(rm._f.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],a=e.totalWeight}for(let t=0;t=h&&n.frame<=u&&(r?(o=n.value.clone(),f?(a=o.getTranslation(),o.setTranslation(a.scaleInPlace(m))):g&&s?(a=o.getTranslation(),o.setTranslation(a.multiplyInPlace(s))):o=n.value):o=n.value,v.push({frame:n.frame+i,value:o}));return this.animations[0].createRange(t,h+i,u+i),!0};var rw=i(9806);(a=tp||(tp={}))[a.CW=0]="CW",a[a.CCW=1]="CCW";let Angle=class Angle{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){let i=t.subtract(e),r=Math.atan2(i.y,i.x);return new Angle(r)}static FromRadians(e){return new Angle(e)}static FromDegrees(e){return new Angle(e*Math.PI/180)}};let Arc2=class Arc2{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,n=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new rm.FM((s*(t.y-i.y)-n*(e.y-t.y))/a,((e.x-t.x)*n-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=Angle.BetweenTwoPoints(this.centerPoint,this.startPoint);let o=this.startAngle.degrees(),l=Angle.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=Angle.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-o>180&&(l-=360),l-o<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-o<0?tp.CW:tp.CCW,this.angle=Angle.FromDegrees(this.orientation===tp.CW?o-h:h-o)}};let math_path_Path2=class math_path_Path2{constructor(e,t){this._points=[],this._length=0,this.closed=!1,this._points.push(new rm.FM(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new rm.FM(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let n=this._points[this._points.length-1],a=new rm.FM(e,t),o=new rm.FM(i,r),l=new Arc2(n,a,o),h=l.angle.radians()/s;l.orientation===tp.CW&&(h*=-1);let u=l.startAngle.radians()+h;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r,n=this._points[this._points.length-1];for(let a=0;a<=s;a++){let o=a/s,l=equation(o,n.x,e,i),h=equation(o,n.y,t,r);this.addLineTo(l,h)}return this}addBezierCurveTo(e,t,i,r,s,n,a=36){if(this.closed)return this;let equation=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s,o=this._points[this._points.length-1];for(let l=0;l<=a;l++){let h=l/a,u=equation(h,o.x,e,i,s),c=equation(h,o.y,t,r,n);this.addLineTo(u,c)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(o<0&&(i=this._points[s],a=-a,n=this._points[r],o=-o),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{let r=o*(e.x-i.x)-a*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1],i=this._points[0];e+=i.subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r1)return rm.FM.Zero();let t=e*this.length(),i=0;for(let e=0;e=i&&t<=o){let e=a.normalize(),r=t-i;return new rm.FM(s.x+e.x*r,s.y+e.y*r)}i=o}return rm.FM.Zero()}static StartingAt(e,t){return new math_path_Path2(e,t)}};let Path3D=class Path3D{constructor(e,t=null,i,r=!1){this.path=e,this._curve=[],this._distances=[],this._tangents=[],this._normals=[],this._binormals=[],this._pointAtData={id:0,point:rm.P.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:rm.y3.Identity()};for(let t=0;tt){let i=e;e=t,t=i}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),n=this.getPointAt(t),a=this.getPreviousPointIndexAt(t)+1,o=[];return 0!==e&&(s++,o.push(r)),o.push(...i.slice(s,a)),(1!==t||1===e)&&o.push(n),new Path3D(o,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i;let r=e.length();if(0===r&&(r=1),null==t){let t;t=rE.R.WithinEpsilon(Math.abs(e.y)/r,1,rw.kn)?rE.R.WithinEpsilon(Math.abs(e.x)/r,1,rw.kn)?rE.R.WithinEpsilon(Math.abs(e.z)/r,1,rw.kn)?rm.P.Zero():new rm.P(0,0,1):new rm.P(1,0,0):new rm.P(0,-1,0),i=rm.P.Cross(e,t)}else i=rm.P.Cross(e,t),rm.P.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){let i;if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let r=this.getPoints();if(e<=0)return this._setPointAtData(0,0,r[0],0,t);if(e>=1)return this._setPointAtData(1,1,r[r.length-1],r.length-1,t);let s=r[0],n=0,a=e*this.length();for(let o=1;oa){let r=n-a,h=r/l,u=s.subtract(i),c=i.add(u.scaleInPlace(h));return this._setPointAtData(e,1-h,c,o-1,t)}s=i}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=rm.y3.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),n=this._tangents[t].clone(),a=this._normals[t].clone(),o=this._binormals[t].clone(),l=rm._f.RotationQuaternionFromAxis(r,s,i),h=rm._f.RotationQuaternionFromAxis(a,o,n),u=rm._f.Slerp(l,h,this._pointAtData.subPosition);u.toRotationMatrix(this._pointAtData.interpolationMatrix)}}};let Curve3=class Curve3{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;let s=[],equation=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let n=0;n<=r;n++)s.push(new rm.P(equation(n/r,e.x,t.x,i.x),equation(n/r,e.y,t.y,i.y),equation(n/r,e.z,t.z,i.z)));return new Curve3(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;let n=[],equation=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let a=0;a<=s;a++)n.push(new rm.P(equation(a/s,e.x,t.x,i.x,r.x),equation(a/s,e.y,t.y,i.y,r.y),equation(a/s,e.z,t.z,i.z,r.z)));return new Curve3(n)}static CreateHermiteSpline(e,t,i,r,s){let n=[],a=1/s;for(let o=0;o<=s;o++)n.push(rm.P.Hermite(e,t,i,r,o*a));return new Curve3(n)}static CreateCatmullRomSpline(e,t,i){let r=[],s=1/t,n=0;if(i){let i=e.length;for(let a=0;a=.5?(1-this.easeInCore((1-e)*2))*.5+.5:.5*this.easeInCore(2*e)}};EasingFunction.EASINGMODE_EASEIN=0,EasingFunction.EASINGMODE_EASEOUT=1,EasingFunction.EASINGMODE_EASEINOUT=2;let CircleEase=class CircleEase extends EasingFunction{easeInCore(e){return 1-Math.sqrt(1-(e=Math.max(0,Math.min(1,e)))*e)}};let BackEase=class BackEase extends EasingFunction{constructor(e=1){super(),this.amplitude=e}easeInCore(e){let t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}};let ExponentialEase=class ExponentialEase extends EasingFunction{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)}};let QuadraticEase=class QuadraticEase extends EasingFunction{easeInCore(e){return e*e}};let SineEase=class SineEase extends EasingFunction{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}};var rU=i(1803);let TargetedAnimation=class TargetedAnimation{getClassName(){return"TargetedAnimation"}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}};let AnimationGroup=class AnimationGroup{syncWithMask(){if(!this.mask){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);let a=new AnimationGroup(e[0].name+"_merged",e[0]._scene,r);for(let r of e){for(let e of(i&&r.normalize(s,n),r.targetedAnimations))a.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return a}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=[],this._animatables=[],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._parentContainer=null,this.onAnimationEndObservable=new rf.y$,this.onAnimationLoopObservable=new rf.y$,this.onAnimationGroupLoopObservable=new rf.y$,this.onAnimationGroupEndObservable=new rf.y$,this.onAnimationGroupPauseObservable=new rf.y$,this.onAnimationGroupPlayObservable=new rf.y$,this.metadata=null,this._animationLoopFlags=[],this._scene=t||rS.l.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new TargetedAnimation;i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-1;t--){let i=this._targetedAnimations[t];i.animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let i=0;ie){let t={frame:e,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};s.splice(0,0,t)}if(a.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount!==this._numActiveAnimatables||(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{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;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){let 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){let t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){let r=new AnimationGroup(e||this.name,this._scene,this._weight,this._playOrder);for(let e of(r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask,this._targetedAnimations))r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){let 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;ta[0].frame&&(e=a[0].frame),t=t&&e<=i||s&&r.frame>=t&&r.frame<=i){let e={frame:r.frame,value:r.value.clone?r.value.clone():r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation,lockedTangent:r.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,c.push(e)}}if(0===c.length){o.splice(e,1),e--;continue}n>c[0].frame&&(n=c[0].frame),a{let i=new instancedMesh_InstancedMesh(e,t);if(t.instancedBuffers)for(let e in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e];return i};let instancedMesh_InstancedMesh=class instancedMesh_InstancedMesh extends rG.x{constructor(e,t){for(let i of(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(),t.getAnimationRanges()))null!=i&&this.createAnimationRange(i.name,i.from,i.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){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.receiveShadows)!==e&&rW.w1.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.material)!==e&&rW.w1.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.visibility)!==e&&rW.w1.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.skeleton)!==e&&rW.w1.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&&rT.Y.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,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),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 i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||rT.Y.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){let i=this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0;if(i)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!==rk.Y.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new rm.y3);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,rm.jp.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(rm.jp.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){let 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;e0)||-1!==this.includedOnlyMeshes.indexOf(e))&&(!this.excludedMeshes||!(this.excludedMeshes.length>0)||-1===this.excludedMeshes.indexOf(e))&&(0===this.includeOnlyWithLayerMask||(this.includeOnlyWithLayerMask&e.layerMask)!=0)&&(0===this.excludeWithLayerMask||!(this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.dispose()}this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){let e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(let 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){let i=light_Light.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=rb.p4.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=rb.p4.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)})),rb.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){let r=ry.N.Construct("Light_Type_"+e,t,i);return r||null}static Parse(e,t){let i=light_Light.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=rb.p4.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{let r=t.apply(e,i);for(let e of i)e._resyncLightSource(this);return r};let i=e.splice;for(let t of(e.splice=(t,r)=>{let s=i.apply(e,[t,r]);for(let e of s)e._resyncLightSource(this);return s},e))t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._resyncMeshes(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===light_Light.INTENSITYMODE_AUTOMATIC&&(i=t===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?light_Light.INTENSITYMODE_ILLUMINANCE:light_Light.INTENSITYMODE_LUMINOUSINTENSITY),t){case light_Light.LIGHTTYPEID_POINTLIGHT:case light_Light.LIGHTTYPEID_SPOTLIGHT:switch(i){case light_Light.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case light_Light.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case light_Light.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case light_Light.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case light_Light.INTENSITYMODE_ILLUMINANCE:e=1;break;case light_Light.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);let i=2*Math.PI*(1-Math.cos(t));e=i}}break;case light_Light.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){let e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}};light_Light.FALLOFF_DEFAULT=rY.m.FALLOFF_DEFAULT,light_Light.FALLOFF_PHYSICAL=rY.m.FALLOFF_PHYSICAL,light_Light.FALLOFF_GLTF=rY.m.FALLOFF_GLTF,light_Light.FALLOFF_STANDARD=rY.m.FALLOFF_STANDARD,light_Light.LIGHTMAP_DEFAULT=rY.m.LIGHTMAP_DEFAULT,light_Light.LIGHTMAP_SPECULAR=rY.m.LIGHTMAP_SPECULAR,light_Light.LIGHTMAP_SHADOWSONLY=rY.m.LIGHTMAP_SHADOWSONLY,light_Light.INTENSITYMODE_AUTOMATIC=rY.m.INTENSITYMODE_AUTOMATIC,light_Light.INTENSITYMODE_LUMINOUSPOWER=rY.m.INTENSITYMODE_LUMINOUSPOWER,light_Light.INTENSITYMODE_LUMINOUSINTENSITY=rY.m.INTENSITYMODE_LUMINOUSINTENSITY,light_Light.INTENSITYMODE_ILLUMINANCE=rY.m.INTENSITYMODE_ILLUMINANCE,light_Light.INTENSITYMODE_LUMINANCE=rY.m.INTENSITYMODE_LUMINANCE,light_Light.LIGHTTYPEID_POINTLIGHT=rY.m.LIGHTTYPEID_POINTLIGHT,light_Light.LIGHTTYPEID_DIRECTIONALLIGHT=rY.m.LIGHTTYPEID_DIRECTIONALLIGHT,light_Light.LIGHTTYPEID_SPOTLIGHT=rY.m.LIGHTTYPEID_SPOTLIGHT,light_Light.LIGHTTYPEID_HEMISPHERICLIGHT=rY.m.LIGHTTYPEID_HEMISPHERICLIGHT,(0,rH.gn)([(0,rb.n9)()],light_Light.prototype,"diffuse",void 0),(0,rH.gn)([(0,rb.n9)()],light_Light.prototype,"specular",void 0),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"falloffType",void 0),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"range",null),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"intensityMode",null),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"radius",null),(0,rH.gn)([(0,rb.qC)()],light_Light.prototype,"_renderPriority",void 0),(0,rH.gn)([(0,rb.wz)("_reorderLightsInScene")],light_Light.prototype,"renderPriority",void 0),(0,rH.gn)([(0,rb.qC)("shadowEnabled")],light_Light.prototype,"_shadowEnabled",void 0),(0,rH.gn)([(0,rb.qC)("excludeWithLayerMask")],light_Light.prototype,"_excludeWithLayerMask",void 0),(0,rH.gn)([(0,rb.qC)("includeOnlyWithLayerMask")],light_Light.prototype,"_includeOnlyWithLayerMask",void 0),(0,rH.gn)([(0,rb.qC)("lightmapMode")],light_Light.prototype,"_lightmapMode",void 0);var rj=i(555);let KeepAssets=class KeepAssets extends rp.p{};let InstantiatedEntries=class InstantiatedEntries{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}};let AssetContainer=class AssetContainer extends rp.p{constructor(e){if(super(),this._wasAddedToScene=!1,!(e=e||rS.l.LastCreatedScene))return;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(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of this.particleSystems)e.rebuild();for(let e of this.textures)e._rebuild()})}_topologicalSort(e){let t=new Map;for(let i of e)t.set(i.uniqueId,i);let i={dependsOn:new Map,dependedBy:new Map};for(let t of e){let e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(let r of e){let e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof instancedMesh_InstancedMesh){let n=r.sourceMesh;t.has(n.uniqueId)&&(s.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}let n=i.dependedBy.get(e);for(let s of r.getDescendants()){let r=s.uniqueId;if(t.has(r)){n.add(r);let t=i.dependsOn.get(r);t.add(e)}}}let r=[],s=[];for(let r of e){let e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}for(;s.length>0;){let e=s.shift();r.push(e);let n=i.dependedBy.get(e.uniqueId);for(let r of Array.from(n.values())){let n=i.dependsOn.get(r);n.delete(e.uniqueId),0===n.size&&t.get(r)&&(s.push(t.get(r)),t.delete(r))}}return t.size>0&&(console.error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(e=>console.error(e.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId)))for(let s of(e.push(i),t.add(i.uniqueId),i.getDescendants(!0)))this._addNodeAndDescendantsToList(e,t,s,r)}_isNodeInContainer(e){return e instanceof rV.Kj&&-1!==this.meshes.indexOf(e)||e instanceof rk.Y&&-1!==this.transformNodes.indexOf(e)||e instanceof light_Light&&-1!==this.lights.indexOf(e)||e instanceof rj.V&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return rT.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return rT.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return rT.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return rT.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||rW.w1.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},n=new InstantiatedEntries,a=[],o=[],l=Object.assign({doNotInstantiate:!0},i),onClone=(t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof rV.Kj&&i.morphTargetManager){let e=t.morphTargetManager;i.morphTargetManager=e.clone();for(let t=0;t{if(onClone(i,a),i.parent){let e=r[i.parent.uniqueId],t=s[e];t?a.parent=t:a.parent=i.parent}if(a.position&&i.position&&a.position.copyFrom(i.position),a.rotationQuaternion&&i.rotationQuaternion&&a.rotationQuaternion.copyFrom(i.rotationQuaternion),a.rotation&&i.rotation&&a.rotation.copyFrom(i.rotation),a.scaling&&i.scaling&&a.scaling.copyFrom(i.scaling),a.material&&a.material){if(t){let t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){for(let n of t.subMaterials)n&&(i=n.clone(e?e(n.name):"Clone of "+n.name),o.push(n),r[n.uniqueId]=i.uniqueId,s[i.uniqueId]=i);t.subMaterials=t.subMaterials.map(e=>e&&s[r[e.uniqueId]])}}"InstancedMesh"!==a.getClassName()&&(a.material=s[r[t.uniqueId]])}else"MultiMaterial"===a.material.getClassName()?-1===this.scene.multiMaterials.indexOf(a.material)&&this.scene.addMultiMaterial(a.material):-1===this.scene.materials.indexOf(a.material)&&this.scene.addMaterial(a.material)}null===a.parent&&n.rootNodes.push(a)};return c.forEach(e=>{if("InstancedMesh"===e.getClassName()){let t=e.sourceMesh,i=r[t.uniqueId],n="number"==typeof i?s[i]:t,a=n.createInstance(e.name);onNewCreated(e,a)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);let i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw Error(`Could not clone or instantiate node on Asset Container ${e.name}`);onNewCreated(e,i)}}),this.skeletons.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name);for(let e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){let t=s[r[e.uniqueId]];if(!t||t.isAnInstance||(t.skeleton=i,-1!==a.indexOf(i)))continue;for(let e of(a.push(i),i.bones))e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)}),this.animationGroups.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name,e=>{let t=s[r[e.uniqueId]];return t||e});n.animationGroups.push(i)}),n}addAllToScene(){if(!this._wasAddedToScene){for(let e of(this._isValidHierarchy()||rW.w1.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture),this.scene._serializableComponents))e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of(this.cameras.forEach(i=>{(!e||e(i))&&(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{(!e||e(i))&&(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{(!e||e(i))&&(this.scene.addMesh(i),t.push(i))}),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(i=>{(!e||e(i))&&(this.scene.addTransformNode(i),t.push(i))}),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)}),t))i.parent&&-1===this.scene.getNodes().indexOf(i.parent)&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){for(let e of(this._isValidHierarchy()||rW.w1.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),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(){for(let e of(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),this.scene._serializableComponents))e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(let r of e){let e=!0;if(i){for(let t of i)if(r===t){e=!1;break}}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){for(let t in this._wasAddedToScene=!1,void 0===e&&(e=new KeepAssets),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(){let e=new rV.Kj("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=rS.l.LastCreatedScene,t,i=null){if(!e)return rT.Y.Error("No scene available to merge animations to"),[];let r=i||(t=>{let i=null,r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i}),s=this.getNodes();s.forEach(e=>{let t=r(e);if(null!==t){for(let i of e.animations){let e=t.animations.filter(e=>e.targetProperty===i.targetProperty);for(let i of e){let e=t.animations.indexOf(i,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}});let n=[];return this.animationGroups.slice().forEach(e=>{n.push(e.clone(e.name,r)),e.animatables.forEach(e=>{e.stop()})}),t.forEach(t=>{let i=r(t.target);i&&(e.beginAnimation(i,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))}),n}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;let t=[],i=new Set;for(t.push(e);t.length>0;){let e=t.pop();if(e instanceof rV.Kj?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof rk.Y?this.transformNodes.push(e):e instanceof light_Light?this.lights.push(e):e instanceof rj.V&&this.cameras.push(e),e instanceof rG.x){if(e.material&&-1===this.materials.indexOf(e.material))for(let t of(this.materials.push(e.material),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(let r of e.getChildren())i.has(r)||t.push(r);i.add(e)}this.populateRootNodes()}};var rq=i(8906),rK=i(7209);rq.D.AudioEngineFactory=(e,t,i)=>new AudioEngine(e,t,i);let AudioEngine=class AudioEngine{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=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 rf.y$,this.onAudioLockedObservable=new rf.y$,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,rK.CG)())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);let r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if((null===(e=this._audioContext)||void 0===e?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?null===(t=this._audioContext)||void 0===t||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(null===(e=this._audioContext)||void 0===e?void 0:e.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,rT.Y.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";let e=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",t=document.createElement("style");t.appendChild(document.createTextNode(".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }")),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))}};var r$=i(6131);let Sound=class Sound{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((null===(e=rq.D.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){let e=this.isPaused?0:rq.D.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;let t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){var n,a,o,l,h;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 rf.y$,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=rm.P.Zero(),this._localDirection=new rm.P(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,!(i=i||rS.l.LastCreatedScene))return;if(this._scene=i,Sound._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{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&&rT.Y.Error("XHR "+e.status+" error on: "+t+"."),rT.Y.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:e=!1}e?!r&&(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):rT.Y.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){rT.Y.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),rq.D.audioEngine&&!rq.D.audioEngine.WarnedWebAudioUnsupported&&(rT.Y.Error("Web Audio is not supported by your browser."),rq.D.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.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){var t;(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.audioContext)&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.audioContext)&&rq.D.audioEngine.audioContext.decodeAudioData(e,e=>{this._audioBufferLoaded(e)},e=>{rT.Y.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)})}setAudioBuffer(e){var t;(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,r,s,n,a,o,l,h,u,c;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(r=e.useCustomAttenuation)&&void 0!==r?r:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(n=e.refDistance)&&void 0!==n?n:this.refDistance,this.distanceModel=null!==(a=e.distanceModel)&&void 0!==a?a:this.distanceModel,this._playbackRate=null!==(o=e.playbackRate)&&void 0!==o?o:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this.spatialSound=null!==(h=e.spatialSound)&&void 0!==h?h:this._spatialSound,this._setOffset(null!==(u=e.offset)&&void 0!==u?u:void 0),this.setVolume(null!==(c=e.volume)&&void 0!==c?c: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(){var e,t;(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&rq.D.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:rq.D.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,null===(e=this._soundPanner)||void 0===e||e.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.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(){var e;(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){let tryToPlay=()=>{var e,t;if(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.unlocked){let e=this._htmlAudioElement.play();void 0!==e&&e.catch(()=>{var e,t;null===(e=rq.D.audioEngine)||void 0===e||e.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(t=rq.D.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(t=rq.D.audioEngine)||void 0===t?void 0:t.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))};tryToPlay()}}else{let tryToPlay=()=>{var s,n,a,o;if(null===(s=rq.D.audioEngine)||void 0===s?void 0:s.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){let e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=null===(n=rq.D.audioEngine)||void 0===n?void 0:n.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!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?(null===(a=rq.D.audioEngine)||void 0===a?void 0:a.audioContext.currentTime)+e:rq.D.audioEngine.audioContext.currentTime;let s=((this.isPaused?this.currentTime:0)+(null!==(o=this._offset)&&void 0!==o?o:0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};(null===(a=rq.D.audioEngine)||void 0===a?void 0:a.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var e;(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.audioContext.state)==="suspended"?(rq.D.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=rq.D.audioEngine.onAudioUnlockedObservable.addOnce(()=>{tryToPlay()}))):tryToPlay()},500):tryToPlay()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){rT.Y.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){var t;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((null===(t=rq.D.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){let t=e?rq.D.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=()=>void 0),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1}else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>void 0,this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=rq.D.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=rq.D.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&rq.D.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(rq.D.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,rq.D.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,rq.D.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){var t;if(e.getBoundingInfo){let t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{let setBufferAndRun=()=>{this._isReadyToPlay?(t._audioBuffer=this.getAudioBuffer(),t._isReadyToPlay=!0,t.autoplay&&t.play(0,this._offset,this._length)):setTimeout(setBufferAndRun,300)},e={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},t=new Sound(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,e);return this.useCustomAttenuation&&t.setAttenuationFunction(this._customAttenuationFunction),t.setPosition(this._position),t.setPlaybackRate(this._playbackRate),setBufferAndRun(),t}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){let 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,i,r){let s,n;let a=e.name;s=e.url?i+e.url:i+a;let o={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};if(r){let setBufferAndRun=()=>{r._isReadyToPlay?(n._audioBuffer=r.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play(0,n._offset,n._length)):setTimeout(setBufferAndRun,300)};n=new Sound(a,new ArrayBuffer(0),t,null,o),setBufferAndRun()}else n=new Sound(a,s,t,()=>{t.removePendingData(n)},o),t.addPendingData(n);if(e.position){let t=rm.P.FromArray(e.position);n.setPosition(t)}if(e.isDirectional&&(n.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){let t=rm.P.FromArray(e.localDirectionToMesh);n.setLocalDirectionToMesh(t)}if(e.connectedMeshId){let i=t.getMeshById(e.connectedMeshId);i&&n.attachToMesh(i)}return e.metadata&&(n.metadata=e.metadata),n}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(null===(e=rq.D.audioEngine)||void 0===e||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}};Sound._SceneComponentInitialization=e=>{throw(0,r$.S)("AudioSceneComponent")};let SoundTrack=class SoundTrack{constructor(e,t={}){if(this.id=-1,this._isInitialized=!1,!(e=e||rS.l.LastCreatedScene))return;this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}_initializeSoundTrackAudioGraph(){var e;(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&rq.D.audioEngine.audioContext&&(this._outputAudioNode=rq.D.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(rq.D.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(rq.D.audioEngine&&rq.D.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){let t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=rq.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=rq.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e{var s;let n;let a=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,l=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)})}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach(e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()})}dispose(){let e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){let e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){let e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),rm.P.TransformNormalToRef(AudioSceneComponent._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(rQ.l.NAME_AUDIO);t||(t=new AudioSceneComponent(e),e._addComponent(t))};let BakedVertexAnimationManager=class BakedVertexAnimationManager{constructor(e){if(this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,!(e=e||rS.l.LastCreatedScene))return;this._scene=e,this.animationParameters=new rm.Lt(0,0,0,30)}_markSubMeshesAsAttributesDirty(){for(let e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;let i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){let e=new BakedVertexAnimationManager(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,r=30){this.animationParameters=new rm.Lt(e,t,i,r)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){rb.p4.Clone(()=>e,this)}serialize(){return rb.p4.Serialize(this)}parse(e,t,i){rb.p4.Parse(()=>this,e,t,i)}};(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markSubMeshesAsAttributesDirty")],BakedVertexAnimationManager.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markSubMeshesAsAttributesDirty")],BakedVertexAnimationManager.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],BakedVertexAnimationManager.prototype,"animationParameters",void 0),(0,rH.gn)([(0,rb.qC)()],BakedVertexAnimationManager.prototype,"time",void 0);var rZ=i(1032),rJ=i(1166);let thinTexture_ThinTexture=class thinTexture_ThinTexture{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(null==e?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=Size.Zero(),this._cachedBaseSize=Size.Zero(),this._initialSamplingMode=2,this._texture=thinTexture_ThinTexture._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(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;this._texture._size&&(this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size)}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.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight):(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)}};let baseTexture_BaseTexture=class baseTexture_BaseTexture extends thinTexture_ThinTexture{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,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){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,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=(0,rZ.f)()),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=0,this.wrapR=1,this.anisotropicFilteringLevel=baseTexture_BaseTexture.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 rf.y$,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?baseTexture_BaseTexture._IsScene(e)?this._scene=e:this._engine=e:this._scene=rS.l.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}checkTransformsAreIdentical(e){return null!==e}getTextureMatrix(){return rm.y3.IdentityReadOnly}getReflectionTextureMatrix(){return rm.y3.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,n){let a=this._getEngine();if(!a)return null;let o=a._getUseSRGBBuffer(!!s,t),l=a.getLoadedTexturesCache();for(let a=0;a=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let 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;let t=rb.p4.Serialize(this);return rb.p4.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0===i){t();return}for(let r=0;r{0==--i&&t()}):0==--i&&t()}}}static _IsScene(e){return"Scene"===e.getClassName()}};baseTexture_BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"uniqueId",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"name",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"metadata",void 0),(0,rH.gn)([(0,rb.qC)("hasAlpha")],baseTexture_BaseTexture.prototype,"_hasAlpha",void 0),(0,rH.gn)([(0,rb.qC)("getAlphaFromRGB")],baseTexture_BaseTexture.prototype,"_getAlphaFromRGB",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"level",void 0),(0,rH.gn)([(0,rb.qC)("coordinatesIndex")],baseTexture_BaseTexture.prototype,"_coordinatesIndex",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"optimizeUVAllocation",void 0),(0,rH.gn)([(0,rb.qC)("coordinatesMode")],baseTexture_BaseTexture.prototype,"_coordinatesMode",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"wrapU",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"wrapV",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"wrapR",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"anisotropicFilteringLevel",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"isCube",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"is3D",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"is2DArray",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"gammaSpace",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"invertZ",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"lodLevelInAlpha",void 0),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"lodGenerationOffset",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"lodGenerationScale",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"linearSpecularLOD",null),(0,rH.gn)([(0,rb.oU)()],baseTexture_BaseTexture.prototype,"irradianceTexture",null),(0,rH.gn)([(0,rb.qC)()],baseTexture_BaseTexture.prototype,"isRenderTarget",void 0);var r0=i(4490),r1=i(4406),r2=i(1564),r3=i(9005);function GenerateBase64StringFromPixelData(e,t,i=!1){let r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT,i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}let n=document.createElement("canvas");n.width=r,n.height=s;let a=n.getContext("2d");if(!a)return null;let o=a.createImageData(r,s),l=o.data;if(l.set(e),a.putImageData(o,0,0),i){let e=document.createElement("canvas");e.width=r,e.height=s;let t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}function GenerateBase64StringFromTexture(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=e._readPixelsSync(t,i);return s?GenerateBase64StringFromPixelData(s,e.getSize(),r.invertY):null}async function GenerateBase64StringFromTextureAsync(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=await e.readPixels(t,i);return s?GenerateBase64StringFromPixelData(s,e.getSize(),r.invertY):null}var r4=i(6705);let texture_Texture=class texture_Texture extends baseTexture_BaseTexture{static _CreateVideoTexture(e,t,i,r=!1,s=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,a={},o,l=5){throw(0,r$.S)("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,i,r,s=texture_Texture.TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,l=!1,h,u,c,d,p){var _,f,m,g,v,x,T,S,C,E;let b;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._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 rf.y$,this._isBlocking=!0,this.name=e||"",this.url=e;let y=!1,P=null,R=!0;"object"==typeof i&&null!==i?(b=null!==(_=i.noMipmap)&&void 0!==_&&_,r=null!==(f=i.invertY)&&void 0!==f?f:!r4.e.UseOpenGLOrientationForUV,s=null!==(m=i.samplingMode)&&void 0!==m?m:texture_Texture.TRILINEAR_SAMPLINGMODE,n=null!==(g=i.onLoad)&&void 0!==g?g:null,a=null!==(v=i.onError)&&void 0!==v?v:null,o=null!==(x=i.buffer)&&void 0!==x?x:null,l=null!==(T=i.deleteBuffer)&&void 0!==T&&T,h=i.format,u=i.mimeType,c=i.loaderOptions,d=i.creationFlags,y=null!==(S=i.useSRGBBuffer)&&void 0!==S&&S,P=null!==(C=i.internalTexture)&&void 0!==C?C:null,R=null!==(E=i.gammaSpace)&&void 0!==E?E:R):b=!!i,this._gammaSpace=R,this._noMipmap=b,this._invertY=void 0===r?!r4.e.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=o,this._deleteBuffer=l,this._mimeType=u,this._loaderOptions=c,this._creationFlags=d,this._useSRGBBuffer=y,this._forcedExtension=p,h&&(this._format=h);let A=this.getScene(),I=this._getEngine();if(!I)return;I.onBeforeTextureInitObservable.notifyObservers(this);let load=()=>{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&&A&&A.resetCachedMaterial()},errorHandler=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!P){this._delayedOnLoad=load,this._delayedOnError=errorHandler;return}if(this._texture=null!=P?P:this._getFromCache(this.url,b,s,this._invertY,y,this.isCube),this._texture){if(this._texture.isReady)r0.Q.SetImmediate(()=>load());else{let e=this._texture.onLoadedObservable.add(load);this._texture.onErrorObservable.add(t=>{var i;errorHandler(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)})}}else if(A&&A.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=load,this._delayedOnError=errorHandler;else{try{this._texture=I.createTexture(this.url,b,this._invertY,A,s,load,errorHandler,this._buffer,void 0,this._format,this._forcedExtension,u,c,d,y)}catch(e){throw errorHandler("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,e=>e.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;let e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?r0.Q.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,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,rm.P.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}checkTransformsAreIdentical(e){return null!==e&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}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=rm.y3.Zero(),this._rowGenerationMatrix=new rm.y3,this._t0=rm.P.Zero(),this._t1=rm.P.Zero(),this._t2=rm.P.Zero()),rm.y3.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(rm.y3.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,rm.jp.Matrix[0]),rm.y3.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,rm.jp.Matrix[1]),rm.y3.ScalingToRef(this._cachedUScale,this._cachedVScale,0,rm.jp.Matrix[2]),rm.y3.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,rm.jp.Matrix[3]),rm.jp.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rm.jp.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rm.jp.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rm.jp.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),rm.y3.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));let t=this.getScene();return t&&this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e||this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode&&(this.coordinatesMode!==texture_Texture.PROJECTION_MODE||this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag))return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=rm.y3.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=rm.y3.Zero());let 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 texture_Texture.PLANAR_MODE:rm.y3.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 texture_Texture.PROJECTION_MODE:{rm.y3.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:rm.y3.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let 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 rb.p4.Clone(()=>new texture_Texture(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;let i=this.name;!texture_Texture.SerializeBuffers&&this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let r=super.serialize(texture_Texture._SerializeInternalTextureUniqueId);return r?((texture_Texture.SerializeBuffers||texture_Texture.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(r.base64String=this._buffer,r.name=r.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?r.base64String="data:image/png;base64,"+(0,r3.Gh)(this._buffer):(texture_Texture.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(r.base64String=!this._engine||this._engine._features.supportSyncTextureRead?GenerateBase64StringFromTexture(this):GenerateBase64StringFromTextureAsync(this))),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r._creationFlags=this._creationFlags,r._useSRGBBuffer=this._useSRGBBuffer,texture_Texture._SerializeInternalTextureUniqueId&&(r.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),r.noMipmap=this._noMipmap,this.name=i,r):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){let r;if(e.customType){let r=r1.K.Instantiate(e.customType),s=r.Parse(e,t,i);return e.samplingMode&&s.updateSamplingMode&&s._samplingMode&&s._samplingMode!==e.samplingMode&&s.updateSamplingMode(e.samplingMode),s}if(e.isCube&&!e.isRenderTarget)return texture_Texture._CubeTextureParser(e,t,i);let s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;if(s){let i=t.getEngine().getLoadedTexturesCache();for(let t of i)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}let onLoaded=t=>{var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){let i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{var s,n,a;let o=!0;if(e.noMipmap&&(o=!1),e.mirrorPlane){let i=texture_Texture._CreateMirror(e.name,e.renderTargetSize,t,o);return i._waitingRenderList=e.renderList,i.mirrorPlane=r2.J.FromArray(e.mirrorPlane),onLoaded(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{onLoaded(s)},null!==(n=e._creationFlags)&&void 0!==n?n:0,null!==(a=e._useSRGBBuffer)&&void 0!==a&&a)).name=e.name;else{let n;n=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||texture_Texture.UseSerializedUrlIfAny)&&(n=e.url);let a={noMipmap:!o,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{onLoaded(s)},internalTexture:r};s=new texture_Texture(n,t,a)}return s}},e,t);return n}static CreateFromBase64String(e,t,i,r,s,n=texture_Texture.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=5,h){return new texture_Texture("data:"+t,i,r,s,n,a,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,r=!1,s,n=!0,a=texture_Texture.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new texture_Texture(e,i,s,n,a,o,l,t,r,h,void 0,void 0,u)}};texture_Texture.SerializeBuffers=!0,texture_Texture.ForceSerializeBuffers=!1,texture_Texture.OnTextureLoadErrorObservable=new rf.y$,texture_Texture._SerializeInternalTextureUniqueId=!1,texture_Texture._CubeTextureParser=(e,t,i)=>{throw(0,r$.S)("CubeTexture")},texture_Texture._CreateMirror=(e,t,i,r)=>{throw(0,r$.S)("MirrorTexture")},texture_Texture._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw(0,r$.S)("RenderTargetTexture")},texture_Texture.NEAREST_SAMPLINGMODE=1,texture_Texture.NEAREST_NEAREST_MIPLINEAR=8,texture_Texture.BILINEAR_SAMPLINGMODE=2,texture_Texture.LINEAR_LINEAR_MIPNEAREST=11,texture_Texture.TRILINEAR_SAMPLINGMODE=3,texture_Texture.LINEAR_LINEAR_MIPLINEAR=3,texture_Texture.NEAREST_NEAREST_MIPNEAREST=4,texture_Texture.NEAREST_LINEAR_MIPNEAREST=5,texture_Texture.NEAREST_LINEAR_MIPLINEAR=6,texture_Texture.NEAREST_LINEAR=7,texture_Texture.NEAREST_NEAREST=1,texture_Texture.LINEAR_NEAREST_MIPNEAREST=9,texture_Texture.LINEAR_NEAREST_MIPLINEAR=10,texture_Texture.LINEAR_LINEAR=2,texture_Texture.LINEAR_NEAREST=12,texture_Texture.EXPLICIT_MODE=0,texture_Texture.SPHERICAL_MODE=1,texture_Texture.PLANAR_MODE=2,texture_Texture.CUBIC_MODE=3,texture_Texture.PROJECTION_MODE=4,texture_Texture.SKYBOX_MODE=5,texture_Texture.INVCUBIC_MODE=6,texture_Texture.EQUIRECTANGULAR_MODE=7,texture_Texture.FIXED_EQUIRECTANGULAR_MODE=8,texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,texture_Texture.CLAMP_ADDRESSMODE=0,texture_Texture.WRAP_ADDRESSMODE=1,texture_Texture.MIRROR_ADDRESSMODE=2,texture_Texture.UseSerializedUrlIfAny=!1,(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"url",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"uOffset",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"vOffset",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"uScale",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"vScale",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"uAng",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"vAng",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"wAng",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"uRotationCenter",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"vRotationCenter",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"wRotationCenter",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"homogeneousRotationInUVTransform",void 0),(0,rH.gn)([(0,rb.qC)()],texture_Texture.prototype,"isBlocking",null),(0,rv.H)("BABYLON.Texture",texture_Texture),rb.p4._TextureParser=texture_Texture.Parse;var r5=i(3912),r6=i(6465);function _convertRGBtoRGBATextureData(e,t,i,r){let s;let n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r{let i=p.width,n=a(e);if(n){if(o){let e=this._getWebGLTextureType(s),t=this._getInternalFormat(r),a=this._getRGBABufferInternalSizedFormat(s),l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);let h=o(n);for(let r=0;r>r;for(let i=0;i<6;i++){let o=h[r][i];l&&(o=_convertRGBtoRGBATextureData(o,n,n,s)),d.texImage2D(i,r,a,n,n,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,n,r,s,c);p.isReady=!0,null==t||t.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,e=>{internalCallback(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(p),h&&e&&h(e.status+" "+e.statusText,i)}),p},r6.B.prototype.createRawTexture2DArray=_makeCreateRawTextureFunction(!1),r6.B.prototype.createRawTexture3D=_makeCreateRawTextureFunction(!0),r6.B.prototype.updateRawTexture2DArray=_makeUpdateRawTextureFunction(!1),r6.B.prototype.updateRawTexture3D=_makeUpdateRawTextureFunction(!0);let rawTexture_RawTexture=class rawTexture_RawTexture extends texture_Texture{constructor(e,t,i,r,s,n=!0,a=!1,o=3,l=0,h,u){if(super(null,s,!n,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,!this._engine)return;this._engine._caps.textureFloatLinearFiltering||1!==l||(o=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(o=1),this._texture=this._engine.createRawTexture(e,t,i,r,n,a,o,null,l,null!=h?h:0,null!=u&&u),this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,r,s=!0,n=!1,a=3){return new rawTexture_RawTexture(e,t,i,1,r,s,n,a)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new rawTexture_RawTexture(e,t,i,2,r,s,n,a)}static CreateAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new rawTexture_RawTexture(e,t,i,0,r,s,n,a)}static CreateRGBTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new rawTexture_RawTexture(e,t,i,4,r,s,n,a,o,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new rawTexture_RawTexture(e,t,i,5,r,s,n,a,o,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=!1){return new rawTexture_RawTexture(e,t,i,5,r,s,n,a,o,1,l)}static CreateRTexture(e,t,i,r,s=!0,n=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,o=1){return new rawTexture_RawTexture(e,t,i,6,r,s,n,a,o)}static CreateRStorageTexture(e,t,i,r,s=!0,n=!1,a=texture_Texture.TRILINEAR_SAMPLINGMODE,o=1){return new rawTexture_RawTexture(e,t,i,6,r,s,n,a,o,1)}};var r8=i(6114);let AutoRotationBehavior=class AutoRotationBehavior{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;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===r8.kD.POINTERDOWN){this._isPointerDown=!0;return}e.type===r8.kD.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let e=rF.F.Now,t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();let i=e-this._lastInteractionTime-this._idleRotationWaitTime,r=Math.max(Math.min(i/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*r,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=null!=e?e:rF.F.Now}_reachTargetAlpha(){return!!this._attachedCamera&&!!this.targetAlpha&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(!e)return;e.computeWorldMatrix(!0);let 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||(BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode),this._radiusBounceTransition=animation_Animation.CreateAnimation("radius",animation_Animation.ANIMATIONTYPE_FLOAT,60,BouncingBehavior.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=animation_Animation.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()}};BouncingBehavior.EasingFunction=new BackEase(.3),BouncingBehavior.EasingMode=EasingFunction.EASINGMODE_EASEOUT;let FramingBehavior=class FramingBehavior{constructor(){this.onTargetFramingAnimationEndObservable=new rf.y$,this._mode=FramingBehavior.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=[],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;let t=this._attachedCamera.getScene();FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===r8.kD.POINTERDOWN){this._isPointerDown=!0;return}e.type===r8.kD.POINTERUP&&(this._isPointerDown=!1)}),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add(e=>{e&&this.zoomOnMesh(e,void 0,()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()})}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()})}detach(){if(!this._attachedCamera)return;let 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,i=null){e.computeWorldMatrix(!0);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new rm.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}))&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===FramingBehavior.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=rF.F.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>.5*Math.PI&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=animation_Animation.CreateAnimation("beta",animation_Animation.ANIMATIONTYPE_FLOAT,60,FramingBehavior.EasingFunction));let e=animation_Animation.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=rF.F.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)}};FramingBehavior.EasingFunction=new ExponentialEase,FramingBehavior.EasingMode=EasingFunction.EASINGMODE_EASEINOUT,FramingBehavior.IgnoreBoundsSizeMode=0,FramingBehavior.FitFrustumSidesMode=1;var r7=i(2248),r9=i(6491);let ray_Ray=class ray_Ray{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new ray_Ray(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r,s,n,a;let o=ray_Ray._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),l=ray_Ray._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),h=0,u=Number.MAX_VALUE;if(1e-7>Math.abs(this.direction.x)){if(this.origin.xl.x)return!1}else if(r=1/this.direction.x,s=(o.x-this.origin.x)*r,(n=(l.x-this.origin.x)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.y)){if(this.origin.yl.y)return!1}else if(r=1/this.direction.y,s=(o.y-this.origin.y)*r,(n=(l.y-this.origin.y)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.z)){if(this.origin.zl.z)return!1}else if(r=1/this.direction.z,s=(o.z-this.origin.z)*r,(n=(l.z-this.origin.z)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,n=i*i+r*r+s*s,a=e.radius+t,o=a*a;if(n<=o)return!0;let l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&n-l*l<=o}intersectsTriangle(e,t,i){let r=ray_Ray._TmpVector3[0],s=ray_Ray._TmpVector3[1],n=ray_Ray._TmpVector3[2],a=ray_Ray._TmpVector3[3],o=ray_Ray._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),rm.P.CrossToRef(this.direction,s,n);let l=rm.P.Dot(r,n);if(0===l)return null;let h=1/l;this.origin.subtractToRef(e,a);let u=rm.P.Dot(a,n)*h;if(u<0||u>1)return null;rm.P.CrossToRef(a,r,o);let c=rm.P.Dot(this.direction,o)*h;if(c<0||u+c>1)return null;let d=rm.P.Dot(s,o)*h;return d>this.length?null:new r9.c(1-u-c,u,d)}intersectsPlane(e){let t;let i=rm.P.Dot(e.normal,this.direction);if(999999997475243e-21>Math.abs(i))return null;{let r=rm.P.Dot(e.normal,this.origin);return(t=(-e.d-r)/i)<0?t<-.000000999999997475243?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let e=(this.origin.y-t)/this.direction.y;if(e>0)return null;return new rm.P(this.origin.x+-(this.direction.x*e),t,this.origin.z+-(this.direction.z*e))}case"x":{let e=(this.origin.x-t)/this.direction.x;if(e>0)return null;return new rm.P(t,this.origin.y+-(this.direction.y*e),this.origin.z+-(this.direction.z*e))}case"z":{let e=(this.origin.z-t)/this.direction.z;if(e>0)return null;return new rm.P(this.origin.x+-(this.direction.x*e),this.origin.y+-(this.direction.y*e),t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,n=!1){let a=rm.jp.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?ray_Ray.TransformToRef(this,a,this._tmpRay):this._tmpRay=ray_Ray.Transform(this,a),e.intersects(this._tmpRay,t,i,r,s,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=rm.jp.Vector3[0],n=rm.jp.Vector3[1],a=rm.jp.Vector3[2],o=rm.jp.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(ray_Ray._Rayl,a),r.addToRef(a,n),e.subtractToRef(r,o);let l=rm.P.Dot(s,s),h=rm.P.Dot(s,a),u=rm.P.Dot(a,a),c=rm.P.Dot(s,o),d=rm.P.Dot(a,o),p=l*u-h*h,_,f=p,m,g=p;pf&&(_=f,m=d+h,g=u)),m<0?(m=0,0>-c?_=0:-c>l?_=f:(_=-c,f=l)):m>g&&(m=g,-c+h<0?_=0:-c+h>l?_=f:(_=-c+h,f=l));let v=Math.abs(_)0&&x<=this.length&&C.lengthSquared()=e.distance))?h:null},rN.x.prototype._internalPick=function(e,t,i,r,s){let n=null,a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=ray_Ray.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay),i,r,!0);return n&&(n.ray=this.createPickingRay(e,t,rm.y3.Identity(),s||null)),n},Object.defineProperty(rN.x.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),rN.x.prototype.pick=function(e,t,i,r,s,n,a=!1){let o=this._internalPick((i,r)=>(this._tempPickingRay||(this._tempPickingRay=ray_Ray.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,r),this._tempPickingRay),i,r,!1,n);return o&&(o.ray=this.createPickingRay(e,t,rm.y3.Identity(),s||null)),o},rN.x.prototype.pickWithRay=function(e,t,i,r){let s=this._internalPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=rm.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ray_Ray.Zero()),ray_Ray.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s},rN.x.prototype.multiPick=function(e,t,i,r,s){return this._internalMultiPick(i=>this.createPickingRay(e,t,i,r||null),i,s)},rN.x.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=rm.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=ray_Ray.Zero()),ray_Ray.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i)},rj.V.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new ray_Ray(rm.P.Zero(),rm.P.Zero(),e),e,t,i)},rj.V.prototype.getForwardRayToRef=function(e,t=100,i,r){return i||(i=this.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(this.position),rm.jp.Vector3[2].set(0,0,this._scene.useRightHandedSystem?-1:1),rm.P.TransformNormalToRef(rm.jp.Vector3[2],i,rm.jp.Vector3[3]),rm.P.NormalizeToRef(rm.jp.Vector3[3],e.direction),e};let pivotTools_PivotTools=class pivotTools_PivotTools{static _RemoveAndStorePivotPoint(e){e&&0===pivotTools_PivotTools._PivotCached&&(e.getPivotPointToRef(pivotTools_PivotTools._OldPivotPoint),pivotTools_PivotTools._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(rm.y3.IdentityReadOnly),pivotTools_PivotTools._OldPivotPoint.subtractToRef(e.getPivotPoint(),pivotTools_PivotTools._PivotTranslation),pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1,1,1),pivotTools_PivotTools._PivotTmpVector.subtractInPlace(e.scaling),pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation),e.position.addInPlace(pivotTools_PivotTools._PivotTmpVector))),pivotTools_PivotTools._PivotCached++}static _RestorePivotPoint(e){e&&!pivotTools_PivotTools._OldPivotPoint.equalsToFloats(0,0,0)&&1===pivotTools_PivotTools._PivotCached&&(e.setPivotPoint(pivotTools_PivotTools._OldPivotPoint),e._postMultiplyPivotMatrix=pivotTools_PivotTools._PivotPostMultiplyPivotMatrix,pivotTools_PivotTools._PivotTmpVector.copyFromFloats(1,1,1),pivotTools_PivotTools._PivotTmpVector.subtractInPlace(e.scaling),pivotTools_PivotTools._PivotTmpVector.multiplyInPlace(pivotTools_PivotTools._PivotTranslation),e.position.subtractInPlace(pivotTools_PivotTools._PivotTmpVector)),this._PivotCached--}};pivotTools_PivotTools._PivotCached=0,pivotTools_PivotTools._OldPivotPoint=new rm.P,pivotTools_PivotTools._PivotTranslation=new rm.P,pivotTools_PivotTools._PivotTmpVector=new rm.P,pivotTools_PivotTools._PivotPostMultiplyPivotMatrix=!1;var se=i(2696);function CreatePlaneVertexData(e){let t=[],i=[],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,l=n/2,h=a/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,r4.e.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,r4.e.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,r4.e.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,r4.e.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),se.x._ComputeSides(o,i,t,r,s,e.frontUVs,e.backUVs);let u=new se.x;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function planeBuilder_CreatePlane(e,t={},i=null){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreatePlaneVertexData(t);return s.applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}se.x.CreatePlane=CreatePlaneVertexData,rV.Kj.CreatePlane=(e,t,i,r,s)=>planeBuilder_CreatePlane(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);let pointerDragBehavior_PointerDragBehavior=class pointerDragBehavior_PointerDragBehavior{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new rf.y$,this.onDragStartObservable=new rf.y$,this.onDragEndObservable=new rf.y$,this.onEnabledObservable=new rf.y$,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new rm.P(0,0,0),this._alternatePickedPoint=new rm.P(0,0,0),this._worldDragAxis=new rm.P(0,0,0),this._targetPosition=new rm.P(0,0,0),this._attachedToElement=!1,this._startDragRay=new ray_Ray(new rm.P,new rm.P),this._lastPointerRay={},this._dragDelta=new rm.P,this._pointA=new rm.P(0,0,0),this._pointC=new rm.P(0,0,0),this._localAxis=new rm.P(0,0,0),this._lookAt=new rm.P(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,pointerDragBehavior_PointerDragBehavior._PlaneScene||(this._debugMode?pointerDragBehavior_PointerDragBehavior._PlaneScene=this._scene:(pointerDragBehavior_PointerDragBehavior._PlaneScene=new rN.x(this._scene.getEngine(),{virtual:!0}),pointerDragBehavior_PointerDragBehavior._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{pointerDragBehavior_PointerDragBehavior._PlaneScene.dispose(),pointerDragBehavior_PointerDragBehavior._PlaneScene=null}))),this._dragPlane=planeBuilder_CreatePlane("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:rV.Kj.DOUBLESIDE},pointerDragBehavior_PointerDragBehavior._PlaneScene),this.lastDragPosition=new rm.P(0,0,0);let i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(e=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(e.type==r8.kD.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==r8.kD.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==e.event.pointerId&&(this._activeDragButton===e.event.button||-1===this._activeDragButton)&&this.releaseDrag();else if(e.type==r8.kD.POINTERMOVE){let t=e.event.pointerId;if(this.currentDraggingPointerId===pointerDragBehavior_PointerDragBehavior._AnyMouseId&&t!==pointerDragBehavior_PointerDragBehavior._AnyMouseId){let i=e.event,r="mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent;r&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new ray_Ray(new rm.P,new rm.P)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let e=!1;pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}})}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){let e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=pointerDragBehavior_PointerDragBehavior._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===pointerDragBehavior_PointerDragBehavior._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);let r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;let t=this._pickWithRayOnDragPlane(e);if(t){pivotTools_PivotTools._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?rm.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=rm.P.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),pivotTools_PivotTools._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(rm.P.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(!this._useAlternatePickedPointAboveMaxDragAngle)return null;{this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*rm.P.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);let t=rm.P.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}}let i=pointerDragBehavior_PointerDragBehavior._PlaneScene.pickWithRay(e,e=>e==this._dragPlane);return i&&i.hit&&i.pickedMesh&&i.pickedPoint?i.pickedPoint:null}_updateDragPlanePosition(e,t){this._pointA.copyFrom(t),this._options.dragAxis?(this.useObjectOrientationForDragging?rm.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragAxis),e.origin.subtractToRef(this._pointA,this._pointC),this._pointC.normalize(),Math.abs(rm.P.Dot(this._localAxis,this._pointC))>.999?Math.abs(rm.P.Dot(rm.P.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(rm.P.Right()):this._lookAt.copyFrom(rm.P.UpReadOnly):(rm.P.CrossToRef(this._localAxis,this._pointC,this._lookAt),rm.P.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?rm.P.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}};pointerDragBehavior_PointerDragBehavior._AnyMouseId=-2;let webXRFeaturesManager_WebXRFeatureName=class webXRFeaturesManager_WebXRFeatureName{};webXRFeaturesManager_WebXRFeatureName.ANCHOR_SYSTEM="xr-anchor-system",webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER="xr-background-remover",webXRFeaturesManager_WebXRFeatureName.HIT_TEST="xr-hit-test",webXRFeaturesManager_WebXRFeatureName.MESH_DETECTION="xr-mesh-detection",webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS="xr-physics-controller",webXRFeaturesManager_WebXRFeatureName.PLANE_DETECTION="xr-plane-detection",webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION="xr-controller-pointer-selection",webXRFeaturesManager_WebXRFeatureName.TELEPORTATION="xr-controller-teleportation",webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS="xr-feature-points",webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING="xr-hand-tracking",webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING="xr-image-tracking",webXRFeaturesManager_WebXRFeatureName.NEAR_INTERACTION="xr-near-interaction",webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY="xr-dom-overlay",webXRFeaturesManager_WebXRFeatureName.MOVEMENT="xr-controller-movement",webXRFeaturesManager_WebXRFeatureName.LIGHT_ESTIMATION="xr-light-estimation",webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING="xr-eye-tracking",webXRFeaturesManager_WebXRFeatureName.WALKING_LOCOMOTION="xr-walking-locomotion",webXRFeaturesManager_WebXRFeatureName.LAYERS="xr-layers",webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING="xr-depth-sensing",webXRFeaturesManager_WebXRFeatureName.SPACE_WARP="xr-space-warp";let WebXRFeaturesManager=class WebXRFeaturesManager{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){let s=this._AvailableFeatures[e][t];if(!s)throw Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){let t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){let t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){let t="string"==typeof e?e:e.Name,i=this._features[t];return!!i&&!!i.enabled&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,s=!0){let n="string"==typeof e?e:e.Name,a=0;if("string"==typeof t){if(!t)throw Error(`Error in provided version - ${n} (${t})`);if(-1===(a="stable"===t?WebXRFeaturesManager.GetStableVersionOfFeature(n):"latest"===t?WebXRFeaturesManager.GetLatestVersionOfFeature(n):+t)||isNaN(a))throw Error(`feature not found - ${n} (${t})`)}else a=t;let o=WebXRFeaturesManager._ConflictingFeatures[n];if(void 0!==o&&-1!==this.getEnabledFeatures().indexOf(o))throw Error(`Feature ${n} cannot be enabled while ${o} is enabled.`);let l=this._features[n],h=WebXRFeaturesManager.ConstructFeature(n,a,this._xrSessionManager,i);if(!h)throw Error(`feature not found - ${n}`);l&&this.disableFeature(n);let u=h();if(u.dependsOn){let e=u.dependsOn.every(e=>!!this._features[e]);if(!e)throw Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`)}if(u.isCompatible())return this._features[n]={featureImplementation:u,enabled:!0,version:a,required:s},r?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(!s)return rW.w1.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),u;throw Error("required feature not compatible")}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){let t=this.getEnabledFeatures();for(let i of t){let t=this._features[i],r=t.featureImplementation.xrNativeFeatureName;if(r&&(t.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),t.featureImplementation.getXRSessionInitExtension){let i=await t.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),i)}}return e}};WebXRFeaturesManager._AvailableFeatures={},WebXRFeaturesManager._ConflictingFeatures={[webXRFeaturesManager_WebXRFeatureName.TELEPORTATION]:webXRFeaturesManager_WebXRFeatureName.MOVEMENT,[webXRFeaturesManager_WebXRFeatureName.MOVEMENT]:webXRFeaturesManager_WebXRFeatureName.TELEPORTATION};let WebXRAbstractFeature=class WebXRAbstractFeature{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName=""}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,e=>this._onXRFrame(e)),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(e=>{e.observable.remove(e.observer)}),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}};let PhysicsJoint=class PhysicsJoint{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}};PhysicsJoint.DistanceJoint=0,PhysicsJoint.HingeJoint=1,PhysicsJoint.BallAndSocketJoint=2,PhysicsJoint.WheelJoint=3,PhysicsJoint.SliderJoint=4,PhysicsJoint.PrismaticJoint=5,PhysicsJoint.UniversalJoint=6,PhysicsJoint.Hinge2Joint=PhysicsJoint.WheelJoint,PhysicsJoint.PointToPointJoint=8,PhysicsJoint.SpringJoint=9,PhysicsJoint.LockJoint=10,rV.Kj._PhysicsImpostorParser=function(e,t,i){return new physicsImpostor_PhysicsImpostor(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};let physicsImpostor_PhysicsImpostor=class physicsImpostor_PhysicsImpostor{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=[],this._onAfterPhysicsStepCallbacks=[],this._onPhysicsCollideCallbacks=[],this._deltaPosition=rm.P.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new rm._f,this._tmpQuat2=new rm._f,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new rm._f),!this._options.disableBidirectionalTransformation&&this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(e=>{e(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(e=>{e(this)}),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,physicsImpostor_PhysicsImpostor._TmpVecs[0]),this.object.translate(physicsImpostor_PhysicsImpostor._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;let t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter(e=>-1!==e.otherImpostors.indexOf(t)).forEach(i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)}))},!this.object){rT.Y.Error("No object was provided. A physics object is obligatory");return}if(this.object.parent&&0!==i.mass&&rT.Y.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),!this._scene)return;this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=rm._f.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new rm._f),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&rT.Y.Warn("You must affect impostors to children before affecting impostor to parent.")):rT.Y.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){if(this.object.parent instanceof rG.x){let e=this.object.parent;return e.physicsImpostor}return null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(!this.object.getBoundingInfo)return physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE;{let e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION;let i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);let r=this.object.getBoundingInfo(),s=r.boundingBox.extendSize.scale(2).multiplyInPlace(t);return s.x=Math.abs(s.x),s.y=Math.abs(s.y),s.z=Math.abs(s.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),s}}getObjectCenter(){if(!this.object.getBoundingInfo)return this.object.position;{let e=this.object.getBoundingInfo();return e.boundingBox.centerWorld}}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):rm.P.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):rm.P.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){let t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):rT.Y.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){let t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):rT.Y.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e];this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:i})}unregisterOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e],r=-1,s=this._onPhysicsCollideCallbacks.some((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){let t=e.otherImpostors.every(e=>i.indexOf(e)>-1);return t&&(r=s),t}return!1});s?this._onPhysicsCollideCallbacks.splice(r,1):rT.Y.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):rm._f.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){let r=new PhysicsJoint(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;let n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor&&this._physicsEngine&&n.appendAnchor(this,e,t,i,r,s),this}addHook(e,t,i,r){if(!this._physicsEngine)return this;let s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor&&this._physicsEngine&&s.appendHook(this,e,t,i,r),this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new physicsImpostor_PhysicsImpostor(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach(e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new rm._f),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,s){let n=physicsImpostor_PhysicsImpostor._TmpVecs[0],a=this.object;if(a.rotationQuaternion){if(s){let i=physicsImpostor_PhysicsImpostor._TmpQuat;a.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,rL.T.WORLD,t)}else e.setRotationQuaternion(a.rotationQuaternion,rL.T.WORLD,t)}n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==r&&(r=i.length()),n.x*=r,n.y*=r,n.z*=r),e.getParent()?(n.addInPlace(a.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(a.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,r,s,n){let a=this.object;if(a.rotationQuaternion){if(s){let i=physicsImpostor_PhysicsImpostor._TmpQuat;e.getRotationQuaternionToRef(rL.T.WORLD,t,i),i.multiplyToRef(s,a.rotationQuaternion)}else e.getRotationQuaternionToRef(rL.T.WORLD,t,a.rotationQuaternion)}let o=physicsImpostor_PhysicsImpostor._TmpVecs[0],l=physicsImpostor_PhysicsImpostor._TmpVecs[1];n||((n=physicsImpostor_PhysicsImpostor._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,o),null==r&&i&&(r=i.length()),null!=r&&(o.x+=l.x*r,o.y+=l.y*r,o.z+=l.z*r),a.setAbsolutePosition(o)}};physicsImpostor_PhysicsImpostor.DEFAULT_OBJECT_SIZE=new rm.P(1,1,1),physicsImpostor_PhysicsImpostor.IDENTITY_QUATERNION=rm._f.Identity(),physicsImpostor_PhysicsImpostor._TmpVecs=rB.B.BuildArray(3,rm.P.Zero),physicsImpostor_PhysicsImpostor._TmpQuat=rm._f.Identity(),physicsImpostor_PhysicsImpostor.NoImpostor=0,physicsImpostor_PhysicsImpostor.SphereImpostor=1,physicsImpostor_PhysicsImpostor.BoxImpostor=2,physicsImpostor_PhysicsImpostor.PlaneImpostor=3,physicsImpostor_PhysicsImpostor.MeshImpostor=4,physicsImpostor_PhysicsImpostor.CapsuleImpostor=6,physicsImpostor_PhysicsImpostor.CylinderImpostor=7,physicsImpostor_PhysicsImpostor.ParticleImpostor=8,physicsImpostor_PhysicsImpostor.HeightmapImpostor=9,physicsImpostor_PhysicsImpostor.ConvexHullImpostor=10,physicsImpostor_PhysicsImpostor.CustomImpostor=100,physicsImpostor_PhysicsImpostor.RopeImpostor=101,physicsImpostor_PhysicsImpostor.ClothImpostor=102,physicsImpostor_PhysicsImpostor.SoftbodyImpostor=103;var st=i(2697),si=i(3477);(l=tf||(tf={}))[l.Clean=0]="Clean",l[l.Stop=1]="Stop",l[l.Sync=2]="Sync",l[l.NoSync=3]="NoSync";let sceneLoader_SceneLoader=class sceneLoader_SceneLoader{static get ForceFullSceneLoadingForIncremental(){return st.Z.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){st.Z.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return st.Z.ShowLoadingScreen}static set ShowLoadingScreen(e){st.Z.ShowLoadingScreen=e}static get loggingLevel(){return st.Z.loggingLevel}static set loggingLevel(e){st.Z.loggingLevel=e}static get CleanBoneMatrixWeights(){return st.Z.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){st.Z.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return sceneLoader_SceneLoader._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){let t=sceneLoader_SceneLoader._RegisteredPlugins[e];return t||(rT.Y.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"),sceneLoader_SceneLoader.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(let t in sceneLoader_SceneLoader._RegisteredPlugins){let i=sceneLoader_SceneLoader._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return sceneLoader_SceneLoader._RegisteredPlugins[t]}return sceneLoader_SceneLoader.GetDefaultPlugin()}static _GetPluginForFilename(e){let t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));let i=e.lastIndexOf("."),r=e.substring(i,e.length).toLowerCase();return sceneLoader_SceneLoader._GetPluginForExtension(r)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r=e.rawData?"binary data":e.url,s="Unable to load from "+r;return t?s+=`: ${t}`:i&&(s+=`: ${i}`),s}static _LoadData(e,t,i,r,s,n,a,o){let l;let h=sceneLoader_SceneLoader._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";let u=a?sceneLoader_SceneLoader._GetPluginForExtension(a):h?sceneLoader_SceneLoader._GetPluginForDirectLoad(e.url):sceneLoader_SceneLoader._GetPluginForFilename(e.url);if(e.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";if(!(l=void 0!==u.plugin.createPlugin?u.plugin.createPlugin():u.plugin))throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(sceneLoader_SceneLoader.OnPluginActivatedObservable.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!(0,rJ.VL)(e.url))){if(l.directLoad){let e=l.directLoad(t,h);e.then?e.then(e=>{i(l,e)}).catch(e=>{s("Error in directLoad of _loadData: "+e,e)}):i(l,e)}else i(l,h);return l}let c=u.isBinary,dataCallback=(e,r)=>{if(t.isDisposed){s("Scene has been disposed");return}i(l,e,r)},d=null,p=!1,_=l.onDisposeObservable;_&&_.add(()=>{p=!0,d&&(d.abort(),d=null),n()});let manifestChecked=()=>{if(p)return;let errorCallback=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";d=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,dataCallback,r,c,errorCallback,o):t._loadFile(e.file||e.url,dataCallback,r,!0,c,errorCallback)},f=t.getEngine(),m=f.enableOfflineSupport;if(m){let i=!1;for(let r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}m=!i}return m&&rq.D.OfflineProviderFactory?t.offlineProvider=rq.D.OfflineProviderFactory(e.url,manifestChecked,f.disableManifestCheck):manifestChecked(),l}static _GetFileInfo(e,t){let i,r;let s=null,n=null;if(t){if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r="arrayBuffer",n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,r="";else{if("/"===t.substr(0,1))return rW.w1.Error("Wrong sceneFilename parameter"),null;i=e+t,r=t}}else i=e,r=rW.w1.GetFilename(e),e=rW.w1.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:n}}static GetPluginForExtension(e){return sceneLoader_SceneLoader._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!sceneLoader_SceneLoader._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){let t=e.extensions;sceneLoader_SceneLoader._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{let t=e.extensions;Object.keys(t).forEach(i=>{sceneLoader_SceneLoader._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",r=rS.l.LastCreatedScene,s=null,n=null,a=null,o=null,l=""){if(!r)return rT.Y.Error("No scene available to import mesh to"),null;let h=sceneLoader_SceneLoader._GetFileInfo(t,i);if(!h)return null;let u={};r.addPendingData(u);let disposeHandler=()=>{r.removePendingData(u)},errorHandler=(e,t)=>{let i=sceneLoader_SceneLoader._FormatErrorMessage(h,e,t);a?a(r,i,new si.LH(i,si.SM.SceneLoaderError,t)):rT.Y.Error(i),disposeHandler()},c=n?e=>{try{n(e)}catch(e){errorHandler("Error in onProgress callback: "+e,e)}}:void 0,successHandler=(e,t,i,n,a,o,l)=>{if(r.importedMeshesFiles.push(h.url),s)try{s(e,t,i,n,a,o,l)}catch(e){errorHandler("Error in onSuccess callback: "+e,e)}r.removePendingData(u)};return sceneLoader_SceneLoader._LoadData(h,r,(t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){let s=[],n=[],a=[];t.importMesh(e,r,i,h.rootUrl,s,n,a,errorHandler)&&(r.loadingPluginName=t.name,successHandler(s,n,a,[],[],[],[]))}else t.importMeshAsync(e,r,i,h.rootUrl,c,h.name).then(e=>{r.loadingPluginName=t.name,successHandler(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)}).catch(e=>{errorHandler(e.message,e)})},c,errorHandler,disposeHandler,o,l)}static ImportMeshAsync(e,t,i="",r=rS.l.LastCreatedScene,s=null,n=null,a=""){return new Promise((o,l)=>{sceneLoader_SceneLoader.ImportMesh(e,t,i,r,(e,t,i,r,s,n,a)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:n,lights:a})},s,(e,t,i)=>{l(i||Error(t))},n,a)})}static Load(e,t="",i=rS.l.LastCreatedEngine,r=null,s=null,n=null,a=null,o=""){return i?sceneLoader_SceneLoader.Append(e,t,new rN.x(i),r,s,n,a,o):(rW.w1.Error("No engine available"),null)}static LoadAsync(e,t="",i=rS.l.LastCreatedEngine,r=null,s=null,n=""){return new Promise((a,o)=>{sceneLoader_SceneLoader.Load(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static Append(e,t="",i=rS.l.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return rT.Y.Error("No scene available to append to"),null;let l=sceneLoader_SceneLoader._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let disposeHandler=()=>{i.removePendingData(h)};sceneLoader_SceneLoader.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));let errorHandler=(e,t)=>{let r=sceneLoader_SceneLoader._FormatErrorMessage(l,e,t);n?n(i,r,new si.LH(r,si.SM.SceneLoaderError,t)):rT.Y.Error(r),disposeHandler()},u=s?e=>{try{s(e)}catch(e){errorHandler("Error in onProgress callback",e)}}:void 0,successHandler=()=>{if(r)try{r(i)}catch(e){errorHandler("Error in onSuccess callback",e)}i.removePendingData(h)};return sceneLoader_SceneLoader._LoadData(l,i,(e,t)=>{e.load?!e.load(i,t,l.rootUrl,errorHandler)||(i.loadingPluginName=e.name,successHandler()):e.loadAsync(i,t,l.rootUrl,u,l.name).then(()=>{i.loadingPluginName=e.name,successHandler()}).catch(e=>{errorHandler(e.message,e)})},u,errorHandler,disposeHandler,a,o)}static AppendAsync(e,t="",i=rS.l.LastCreatedScene,r=null,s=null,n=""){return new Promise((a,o)=>{sceneLoader_SceneLoader.Append(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static LoadAssetContainer(e,t="",i=rS.l.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return rT.Y.Error("No scene available to load asset container to"),null;let l=sceneLoader_SceneLoader._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let disposeHandler=()=>{i.removePendingData(h)},errorHandler=(e,t)=>{let r=sceneLoader_SceneLoader._FormatErrorMessage(l,e,t);n?n(i,r,new si.LH(r,si.SM.SceneLoaderError,t)):rT.Y.Error(r),disposeHandler()},u=s?e=>{try{s(e)}catch(e){errorHandler("Error in onProgress callback",e)}}:void 0,successHandler=e=>{if(r)try{r(e)}catch(e){errorHandler("Error in onSuccess callback",e)}i.removePendingData(h)};return sceneLoader_SceneLoader._LoadData(l,i,(e,t)=>{if(e.loadAssetContainer){let r=e.loadAssetContainer(i,t,l.rootUrl,errorHandler);r&&(r.populateRootNodes(),i.loadingPluginName=e.name,successHandler(r))}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,u,l.name).then(t=>{t.populateRootNodes(),i.loadingPluginName=e.name,successHandler(t)}).catch(e=>{errorHandler(e.message,e)}):errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},u,errorHandler,disposeHandler,a,o)}static LoadAssetContainerAsync(e,t="",i=rS.l.LastCreatedScene,r=null,s=null){return new Promise((n,a)=>{sceneLoader_SceneLoader.LoadAssetContainer(e,t,i,e=>{n(e)},r,(e,t,i)=>{a(i||Error(t))},s)})}static ImportAnimations(e,t="",i=rS.l.LastCreatedScene,r=!0,s=tf.Clean,n=null,a=null,o=null,l=null,h=null){if(!i){rT.Y.Error("No scene available to load animations to");return}if(r){for(let e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(e=>{e.dispose()});let e=i.getNodes();e.forEach(e=>{e.animations&&(e.animations=[])})}else switch(s){case tf.Clean:i.animationGroups.slice().forEach(e=>{e.dispose()});break;case tf.Stop:i.animationGroups.forEach(e=>{e.stop()});break;case tf.Sync:i.animationGroups.forEach(e=>{e.reset(),e.restart()});break;case tf.NoSync:break;default:rT.Y.Error("Unknown animation group loading mode value '"+s+"'");return}let u=i.animatables.length;this.LoadAssetContainer(e,t,i,e=>{e.mergeAnimationsTo(i,i.animatables.slice(u),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)},o,l,h)}static ImportAnimationsAsync(e,t="",i=rS.l.LastCreatedScene,r=!0,s=tf.Clean,n=null,a=null,o=null,l=null,h=null){return new Promise((a,l)=>{sceneLoader_SceneLoader.ImportAnimations(e,t,i,r,s,n,e=>{a(e)},o,(e,t,i)=>{l(i||Error(t))},h)})}};sceneLoader_SceneLoader.NO_LOGGING=0,sceneLoader_SceneLoader.MINIMAL_LOGGING=1,sceneLoader_SceneLoader.SUMMARY_LOGGING=2,sceneLoader_SceneLoader.DETAILED_LOGGING=3,sceneLoader_SceneLoader.OnPluginActivatedObservable=new rf.y$,sceneLoader_SceneLoader._RegisteredPlugins={},sceneLoader_SceneLoader._ShowingLoadingScreen=!1;var sr=i(2515);let PushMaterial=class PushMaterial extends sr.F{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new rm.y3,this._storeEffectOnSubMeshes=i}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){let 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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}};(h=tm||(tm={}))[h.Float=1]="Float",h[h.Int=2]="Int",h[h.Vector2=4]="Vector2",h[h.Vector3=8]="Vector3",h[h.Vector4=16]="Vector4",h[h.Color3=32]="Color3",h[h.Color4=64]="Color4",h[h.Matrix=128]="Matrix",h[h.Object=256]="Object",h[h.AutoDetect=1024]="AutoDetect",h[h.BasedOnInput=2048]="BasedOnInput",h[h.All=4095]="All",(u=tg||(tg={}))[u.Vertex=1]="Vertex",u[u.Fragment=2]="Fragment",u[u.Neutral=4]="Neutral",u[u.VertexAndFragment=3]="VertexAndFragment";var ss=i(1088);let NodeMaterialBuildState=class NodeMaterialBuildState{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){let t=e.sharedData.emitComments,i=this.target===tg.Fragment;this.compilationString=` -${t?"//Entry point\n":""}void main(void) { -${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` -${t?"//Constants\n":""}${this._constantDeclaration} -${this.compilationString}`);let r="";for(let e in this.functions)r+=this.functions[e]+` -`;for(let e in this.compilationString=` -${r} -${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} -${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} -${this._injectAtEnd}`),this.compilationString=`${this.compilationString} -}`,this.sharedData.varyingDeclaration&&(this.compilationString=` -${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration} -${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` -${t?"//Samplers\n":""}${this._samplerDeclaration} -${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` -${t?"//Uniforms\n":""}${this._uniformDeclaration} -${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` -${t?"//Attributes\n":""}${this._attributeDeclaration} -${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString),this.extensions){let t=this.extensions[e];this.compilationString=` -${t} -${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return(e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e])?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e)?e+this.sharedData.variableNames[e]:e:(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2D ${e}; -`,this.samplers.push(e))}_emit2DArraySampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; -`,this.samplers.push(e))}_getGLType(e){switch(e){case tm.Float:return"float";case tm.Int:return"int";case tm.Vector2:return"vec2";case tm.Color3:case tm.Vector3:return"vec3";case tm.Color4:case tm.Vector4:return"vec4";case tm.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} -${t} -#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` -`+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] -`;let r=ss.Q.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(r=t+` -`+r),!i)return r;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] -`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""} -`,this.sharedData.emitComments&&(this.functions[s]=t+` -`+this.functions[s]);return}if(this.functions[s]=ss.Q.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+` -`+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;ee.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tg.Vertex||(e.ownerBlock.target===tg.Neutral||e.ownerBlock.target===tg.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===tg.Vertex)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tg.Vertex||e.target===tg.Vertex||(e.ownerBlock.target===tg.Neutral||e.ownerBlock.target===tg.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===tg.Fragment)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tg.Fragment||(e.ownerBlock.target===tg.Neutral||e.ownerBlock.target===tg.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=[],this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=tm.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new rf.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=tg.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===tv.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(t.target===tg.Fragment){if(i.target===tg.Vertex)return tv.TargetIncompatible;for(let e of i.outputs)if(e.ownerBlock.target!=tg.Neutral&&e.isConnectedInVertexShader)return tv.TargetIncompatible}if(this.type!==e.type&&e.innerType!==tm.AutoDetect)return NodeMaterialConnectionPoint.AreEquivalentTypes(this.type,e.type)?tv.Compatible:e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&NodeMaterialConnectionPoint.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?tv.Compatible:tv.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return tv.TypeIncompatible;let r=i,s=t;return(this.direction===tx.Input&&(r=t,s=i),r.isAnAncestorOf(s))?tv.HierarchyIssue:tv.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}};var sa=i(7531);let NodeMaterialBlock=class NodeMaterialBlock{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){(this._target&e)==0&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}constructor(e,t=tg.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=[],this._outputs=[],this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===tg.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=sa.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===tg.Neutral}initialize(e){}bind(e,t,i,r){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){let t=e.connectedPoint;return t?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return -1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,s){return(s=null!=s?s:new NodeMaterialConnectionPoint(e,this,tx.Input)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=null!=r?r:new NodeMaterialConnectionPoint(e,this,tx.Output)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(let t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===tm.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(let t of this._outputs)if(!e||!e.target||e.target===tg.Neutral||(e.target&t.target)!=0)return t;return null}getSiblingOutput(e){let t=this._outputs.indexOf(e);return -1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){let s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput))&&this.target!==tg.Vertex&&!!((this.target===tg.VertexAndFragment||this.target===tg.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);let s=null!=t._vertexState,n=e._buildTarget===tg.Vertex&&e.target!==tg.VertexAndFragment;if(s&&((e.target&e._buildTarget)==0||(e.target&i.target)==0||this.target!==tg.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){let e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName}; -`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){for(let t of["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"])if(e===t)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(let t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(let i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==tg.Neutral&&((i.target&this.target)==0||(i.target&e.target)==0))continue;let r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&console.log(`${e.target===tg.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case tg.Vertex:e.sharedData.checks.emitVertex=!0;break;case tg.Fragment:e.sharedData.checks.emitFragment=!0}for(let i of(!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` -//${this.name} -`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target,this._outputs))if((i.target&e.target)!=0)for(let r of i.endpoints){let i=r.ownerBlock;i&&(i.target&e.target)!=0&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; -${e}.visibleOnFrame = ${this.visibleOnFrame}; -${e}.target = ${this.target}; -`}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` -// ${this.getClassName()} -`;for(let i of(this.comments&&(r+=`// ${this.comments} -`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); -`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,n=s.ownerBlock;-1===t.indexOf(n)&&(r+=n._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); -`}return t}clone(e,t=""){let i=this.serialize(),r=(0,rv.q)(i.customType);if(r){let s=new r;return s._deserialize(i,e,t),s}return null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var r;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(r=e.target)&&void 0!==r?r:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose()}};let TransformBlock=class TransformBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.complementW=1,this.complementZ=0,this.target=tg.Vertex,this.registerInput("vector",tm.AutoDetect),this.registerInput("transform",tm.Matrix),this.registerOutput("output",tm.Vector4),this.registerOutput("xyz",tm.Vector3),this._inputs[0].onConnectionObservable.add(e=>{if(e.ownerBlock.isInput){let t=e.ownerBlock;("normal"===t.name||"tangent"===t.name)&&(this.complementW=0)}})}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){let r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),e.sharedData.blocksWithDefines.push(this);let s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName}); -`,e.compilationString+=`#ifdef NONUNIFORMSCALING -`,e.compilationString+=`${s} = transposeMat3(inverseMat3(${s})); -`,e.compilationString+=`#endif -`,t.connectedPoint.type){case tm.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); -`;break;case tm.Vector3:case tm.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); -`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); -`}}else{let r=i.associatedVariableName;switch(t.connectedPoint.type){case tm.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); -`;break;case tm.Vector3:case tm.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); -`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * ${t.associatedVariableName}; -`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; -`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){let e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; -`+`${this._codeVariableName}.complementW = ${this.complementW}; -`}};(0,rv.H)("BABYLON.TransformBlock",TransformBlock);let VertexOutputBlock=class VertexOutputBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Vertex,!0),this.registerInput("vector",tm.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e){for(let t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);let t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName}; -`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; -`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; -`),this}};function editableInPropertyPage(e,t=tT.Boolean,i="PROPERTIES",r){return(s,n)=>{let a=s._propStore;a||(a=[],s._propStore=a),a.push({propertyName:n,displayName:e,type:t,groupName:i,options:null!=r?r:{}})}}(0,rv.H)("BABYLON.VertexOutputBlock",VertexOutputBlock),(p=tT||(tT={}))[p.Boolean=0]="Boolean",p[p.Float=1]="Float",p[p.Int=2]="Int",p[p.Vector2=3]="Vector2",p[p.List=4]="List";var so=i(3385);let FragmentOutputBlock=class FragmentOutputBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",tm.Color4,!0),this.registerInput("rgb",tm.AutoDetect,!0),this.registerInput("a",tm.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){this.useLogarithmicDepth&&i&&so.G.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);let t=this.rgba,i=this.rgb,r=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||r.isConnected,e.sharedData.blocksWithDefines.push(this),this.useLogarithmicDepth&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");let s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)r.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); -`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; -`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===tm.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t}); -`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t}); -`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor); -`,e.compilationString+=`#endif -`,this.useLogarithmicDepth&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; -`),e.compilationString+=`#if defined(PREPASS)\r -`,e.compilationString+=`gl_FragData[0] = gl_FragColor;\r -`,e.compilationString+=`#endif\r -`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; -`}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(r=e.useLogarithmicDepth)&&void 0!==r&&r}};(0,rH.gn)([editableInPropertyPage("Convert to gamma space",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],FragmentOutputBlock.prototype,"convertToGammaSpace",void 0),(0,rH.gn)([editableInPropertyPage("Convert to linear space",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],FragmentOutputBlock.prototype,"convertToLinearSpace",void 0),(0,rH.gn)([editableInPropertyPage("Use logarithmic depth",tT.Boolean,"PROPERTIES")],FragmentOutputBlock.prototype,"useLogarithmicDepth",void 0),(0,rv.H)("BABYLON.FragmentOutputBlock",FragmentOutputBlock),(_=tS||(tS={}))[_.Uniform=0]="Uniform",_[_.Attribute=1]="Attribute",_[_.Varying=2]="Varying",_[_.Undefined=3]="Undefined",(f=tC||(tC={}))[f.World=1]="World",f[f.View=2]="View",f[f.Projection=3]="Projection",f[f.ViewProjection=4]="ViewProjection",f[f.WorldView=5]="WorldView",f[f.WorldViewProjection=6]="WorldViewProjection",f[f.CameraPosition=7]="CameraPosition",f[f.FogColor=8]="FogColor",f[f.DeltaTime=9]="DeltaTime",f[f.CameraParameters=10]="CameraParameters",f[f.MaterialAlpha=11]="MaterialAlpha";var sl=i(2975),sh=i(6329);(m=tE||(tE={}))[m.None=0]="None",m[m.Time=1]="Time",m[m.RealTime=2]="RealTime";let su={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},sc={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},sd={particle_texturemask:!0};let InputBlock=class InputBlock extends NodeMaterialBlock{get type(){if(this._type===tm.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=tm.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=tm.Vector2,this._type;case"Vector3":return this._type=tm.Vector3,this._type;case"Vector4":return this._type=tm.Vector4,this._type;case"Color3":return this._type=tm.Color3,this._type;case"Color4":return this._type=tm.Color4,this._type;case"Matrix":return this._type=tm.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=tm.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=tm.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=tm.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=tm.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case tC.World:case tC.WorldView:case tC.WorldViewProjection:case tC.View:case tC.ViewProjection:case tC.Projection:this._type=tm.Matrix;break;case tC.CameraPosition:this._type=tm.Vector3;break;case tC.FogColor:this._type=tm.Color3;break;case tC.DeltaTime:case tC.MaterialAlpha:this._type=tm.Float;break;case tC.CameraParameters:this._type=tm.Vector4}}return this._type}constructor(e,t=tg.Vertex,i=tm.AutoDetect){super(e,t,!1),this._mode=tS.Undefined,this._animationType=tE.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new rf.y$,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=tS.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===tm.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=tS.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=tS.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===tS.Undefined}get isUniform(){return this._mode===tS.Uniform}set isUniform(e){this._mode=e?tS.Uniform:tS.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===tS.Attribute}set isAttribute(e){this._mode=e?tS.Attribute:tS.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===tS.Varying}set isVarying(e){this._mode=e?tS.Varying:tS.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=tS.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case tE.Time:this.type===tm.Float&&(this.value+=.01*e.getAnimationRatio());break;case tE.RealTime:this.type===tm.Float&&(this.value=(rF.F.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)} -`:`#ifdef ${e} -`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case tm.Float:this.value=0;break;case tm.Vector2:this.value=rm.FM.Zero();break;case tm.Vector3:this.value=rm.P.Zero();break;case tm.Vector4:this.value=rm.Lt.Zero();break;case tm.Color3:this.value=rg.Wo.White();break;case tm.Color4:this.value=new rg.HE(1,1,1,1);break;case tm.Matrix:this.value=rm.y3.Identity()}}_emitConstant(e){switch(this.type){case tm.Float:return`${e._emitFloat(this.value)}`;case tm.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case tm.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case tm.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case tm.Color3:return rg.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&rg.zZ.Color3[0].toGammaSpaceToRef(rg.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rg.zZ.Color3[0].toLinearSpaceToRef(rg.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${rg.zZ.Color3[0].r}, ${rg.zZ.Color3[0].g}, ${rg.zZ.Color3[0].b})`;case tm.Color4:return rg.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&rg.zZ.Color4[0].toGammaSpaceToRef(rg.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rg.zZ.Color4[0].toLinearSpaceToRef(rg.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${rg.zZ.Color4[0].r}, ${rg.zZ.Color4[0].g}, ${rg.zZ.Color4[0].b}, ${rg.zZ.Color4[0].a})`}return""}get _noContextSwitch(){return sc[this.name]}_emit(e,t){var i;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)}; -`;return}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName}; -`,t&&(e._uniformDeclaration+=`#endif -`);let i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case tC.WorldView:i.needWorldViewMatrix=!0;break;case tC.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==tE.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=null!==(i=su[this.name])&&void 0!==i?i:this.name,this.target===tg.Vertex&&e._vertexState){sc[this.name]?sd[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t);return}if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),sc[this.name]?sd[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName}; -`,t&&(e._attributeDeclaration+=`#endif -`))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;let s=this.associatedVariableName;switch(this._systemValue){case tC.World:e.setMatrix(s,t);break;case tC.WorldView:e.setMatrix(s,i);break;case tC.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;let r=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case tC.World:case tC.WorldView:case tC.WorldViewProjection:break;case tC.View:e.setMatrix(r,t.getViewMatrix());break;case tC.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case tC.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case tC.CameraPosition:t.bindEyePosition(e,r,!0);break;case tC.FogColor:e.setColor3(r,t.fogColor);break;case tC.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case tC.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case tC.MaterialAlpha:e.setFloat(r,i.alpha)}return}let s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case tm.Float:e.setFloat(r,s);break;case tm.Int:e.setInt(r,s);break;case tm.Color3:rg.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&rg.zZ.Color3[0].toGammaSpaceToRef(rg.zZ.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rg.zZ.Color3[0].toLinearSpaceToRef(rg.zZ.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,rg.zZ.Color3[0]);break;case tm.Color4:rg.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&rg.zZ.Color4[0].toGammaSpaceToRef(rg.zZ.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rg.zZ.Color4[0].toLinearSpaceToRef(rg.zZ.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,rg.zZ.Color4[0]);break;case tm.Vector2:e.setVector2(r,s);break;case tm.Vector3:e.setVector3(r,s);break;case tm.Vector4:e.setVector4(r,s);break;case tm.Matrix:e.setMatrix(r,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); -`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${tC[this._systemValue]}); -`;if(this.isUniform){let t=[],i="";switch(this.type){case tm.Float:i=`${this.value}`;break;case tm.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case tm.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case tm.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case tm.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case tm.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case tm.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===tm.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${tE[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){let e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===tS.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===tS.Attribute&&e.type===tm.Vector3&&(this._type=tm.Vector4),e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=(0,rv.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}};(0,rv.H)("BABYLON.InputBlock",InputBlock);let CurrentScreenBlock=class CurrentScreenBlock extends NodeMaterialBlock{constructor(e){super(e,tg.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",tm.AutoDetect,!1,tg.VertexAndFragment),this.registerOutput("rgba",tm.Color4,tg.Neutral),this.registerOutput("rgb",tm.Color3,tg.Neutral),this.registerOutput("r",tm.Float,tg.Neutral),this.registerOutput("g",tm.Float,tg.Neutral),this.registerOutput("b",tm.Float,tg.Neutral),this.registerOutput("a",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?tg.VertexAndFragment:tg.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec2")}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tg.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); -`;return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); -`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); -`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tg.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.blockingBlocks.indexOf(this)&&e.sharedData.blockingBlocks.push(this),0>e.sharedData.textureBlocks.indexOf(this)&&e.sharedData.textureBlocks.push(this),0>e.sharedData.blocksWithDefines.indexOf(this)&&e.sharedData.blocksWithDefines.push(this),e.target!==tg.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e),this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};(0,rv.H)("BABYLON.CurrentScreenBlock",CurrentScreenBlock);let ParticleTextureBlock=class ParticleTextureBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",tm.AutoDetect,!1,tg.VertexAndFragment),this.registerOutput("rgba",tm.Color4,tg.Neutral),this.registerOutput("rgb",tm.Color3,tg.Neutral),this.registerOutput("r",tm.Float,tg.Neutral),this.registerOutput("g",tm.Float,tg.Neutral),this.registerOutput("b",tm.Float,tg.Neutral),this.registerOutput("a",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"particle_uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute("particle_uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,e.compilationString+=`#ifdef ${this._linearDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`,e.compilationString+=`#ifdef ${this._gammaDefineName} -`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); -`,e.compilationString+=`#endif -`}_buildBlock(e){if(super._buildBlock(e),e.target===tg.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); -`,this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};(0,rv.H)("BABYLON.ParticleTextureBlock",ParticleTextureBlock);let ParticleRampGradientBlock=class ParticleRampGradientBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._isUnique=!0,this.registerInput("color",tm.Color4,!1,tg.Fragment),this.registerOutput("rampColor",tm.Color4,tg.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==tg.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` - #ifdef RAMPGRADIENT - vec4 baseColor = ${this.color.associatedVariableName}; - float alpha = ${this.color.associatedVariableName}.a; - - float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); - - vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); - baseColor.rgb *= rampColor.rgb; - - // Remapped alpha - float finalAlpha = baseColor.a; - baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); - - ${this._declareOutput(this.rampColor,e)} = baseColor; - #else - ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; - #endif - `,this}};(0,rv.H)("BABYLON.ParticleRampGradientBlock",ParticleRampGradientBlock);let ParticleBlendMultiplyBlock=class ParticleBlendMultiplyBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._isUnique=!0,this.registerInput("color",tm.Color4,!1,tg.Fragment),this.registerInput("alphaTexture",tm.Float,!1,tg.Fragment),this.registerInput("alphaColor",tm.Float,!1,tg.Fragment),this.registerOutput("blendColor",tm.Color4,tg.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==tg.Vertex)return e.compilationString+=` - #ifdef BLENDMULTIPLYMODE - ${this._declareOutput(this.blendColor,e)}; - float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; - ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); - ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; - #else - ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; - #endif - `,this}};(0,rv.H)("BABYLON.ParticleBlendMultiplyBlock",ParticleBlendMultiplyBlock);let EffectFallbacks=class EffectFallbacks{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=[]),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._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;let i=this._mesh.getScene();for(let e=0;e0&&(r.computeBonesUsingShaders=!1);continue}if(r.computeBonesUsingShaders&&0!==r.numBoneInfluencers){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes)for(let e of r.subMeshes){let i=e.effect;if(i===t){r.computeBonesUsingShaders=!1;break}}}}}else{let t=this._defines[this._currentRank];if(t)for(let i=0;i0}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 texture(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t: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,i=!1){if(this.samples===e&&!i)return e;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){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=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){var a;return null===(a=this._depthStencilTexture)||void 0===a||a.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:n},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var e,t,i,r,s,n,a,o;let l=null;if(this._isMulti){let i=this.textures;if(i&&i.length>0){let r=!1,s=i.length,n=i[i.length-1]._source;(n===r5.S.Depth||n===r5.S.DepthStencil)&&(r=!0,s--);let a=[],o=[],h=[],u=[],c=[],d=[],p=[],_={};for(let r=0;r1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let t=0;t<(null===(e=this._textures)||void 0===e?void 0:e.length);++t)this._textures[t].dispose();this._textures=null}dispose(e=!1){var t;e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}};let WebGLRenderTargetWrapper=class WebGLRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height)).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}_shareDepth(e){super._shareDepth(e);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let s=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,s,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var s,n,a,o;if(!e._hardwareTexture)return;let l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){let l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(n=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==n?n:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=null!==(o=null!=i?i:null===(a=this.faceIndices)||void 0===a?void 0:a[t])&&void 0!==o?o:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{let s=this._context,n=s["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,n,a,e._hardwareTexture.underlyingResource,r)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let s=null!==(r=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==r?r:this.textures.length;for(let e=0;e1&&(15===a.format?c=r.DEPTH_COMPONENT16:16===a.format?c=r.DEPTH_COMPONENT24:17===a.format||13===a.format?c=r.DEPTH24_STENCIL8:14===a.format?c=r.DEPTH_COMPONENT32F:18===a.format&&(c=r.DEPTH32F_STENCIL8)),a.is2DArray?r.texImage3D(n,0,c,a.width,a.height,s,0,u,h,null):r.texImage2D(n,0,c,a.width,a.height,0,u,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),i._depthStencilBuffer){let e=this._currentFramebuffer;this._bindUnboundFramebuffer(i._framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null}return a},r6.B.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);let r=e.texture._hardwareTexture;if(r.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){let s=i.createFramebuffer();if(!s)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);let n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBAMultiSampleBufferFormat(e.texture.type),i.COLOR_ATTACHMENT0,!1);if(!n)throw Error("Unable to create multi sampled framebuffer");r.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};var sm=i(1606),sg=i(5550);let postProcess_PostProcess=class postProcess_PostProcess{static RegisterShaderCodeProcessing(e,t){if(!t){delete postProcess_PostProcess._CustomShaderCodeProcessing[null!=e?e:""];return}postProcess_PostProcess._CustomShaderCodeProcessing[null!=e?e:""]=t}static _GetShaderCodeProcessing(e){var t;return null!==(t=postProcess_PostProcess._CustomShaderCodeProcessing[e])&&void 0!==t?t:postProcess_PostProcess._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)})}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,i,r,s,n,a=1,o,l,h=null,u=0,c="postprocess",d,p=!1,_=5,f=sg.x.GLSL){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new sp.t(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new rm.FM(1,1),this._texelSize=rm.FM.Zero(),this.onActivateObservable=new rf.y$,this.onSizeChangedObservable=new rf.y$,this.onApplyObservable=new rf.y$,this.onBeforeRenderObservable=new rf.y$,this.onAfterRenderObservable=new rf.y$,this.name=e,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=s,this.renderTargetSamplingMode=a||1,this._reusable=l||!1,this._textureType=u,this._textureFormat=_,this._shaderLanguage=f,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=c,this._parameters=i||[],this._parameters.push("scale"),this._indexParameters=d,this._drawWrapper=new sm.q(this._engine),p||this.updateEffect(h)}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 sp.t(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,n,a,o){var l,h;let u=postProcess_PostProcess._GetShaderCodeProcessing(this.name);if(null==u?void 0:u.defineCustomBindings){let r=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];r.push(...this._parameters);let s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=u.defineCustomBindings(this.name,e,r,s),t=r,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=a?a:this._vertexUrl,fragment:null!=o?o:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:[],samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:null!=s?s:null,onError:null!=n?n:null,indexParameters:r||this._indexParameters,processCodeAfterIncludes:(null==u?void 0:u.processCodeAfterIncludes)?(e,t)=>u.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==u?void 0:u.processFinalCode)?(e,t)=>u.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)}),this._flushTextureCache(),this._renderId++}if(this._shareOutputWithPostProcess)n=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)n=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let e;n=this.inputTexture;for(let t=0;t=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&&-1!==(t=this._scene.postProcesses.indexOf(this))&&this._scene.postProcesses.splice(t,1),this._parentContainer){let e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(-1!==(t=this._engine.postProcesses.indexOf(this))&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),0===(t=e._postProcesses.indexOf(this))&&e._postProcesses.length>0){let e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){let e=rb.p4.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(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=postProcess_PostProcess.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,i){let r=(0,rv.q)(e.customType);if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new postProcess_PostProcess(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,i,r)}};postProcess_PostProcess._CustomShaderCodeProcessing={},(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"uniqueId",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"name",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"width",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"height",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"renderTargetSamplingMode",void 0),(0,rH.gn)([(0,rb.XX)()],postProcess_PostProcess.prototype,"clearColor",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"autoClear",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"forceAutoClearInAlphaMode",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"alphaMode",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"alphaConstants",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"enablePixelPerfectMode",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"forceFullscreenViewport",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"scaleMode",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"alwaysForcePOT",void 0),(0,rH.gn)([(0,rb.qC)("samples")],postProcess_PostProcess.prototype,"_samples",void 0),(0,rH.gn)([(0,rb.qC)()],postProcess_PostProcess.prototype,"adaptScaleToCurrentViewport",void 0),(0,rv.H)("BABYLON.PostProcess",postProcess_PostProcess);let VectorMergerBlock=class VectorMergerBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",tm.Vector4,!0),this.registerInput("xyz ",tm.Vector3,!0),this.registerInput("xy ",tm.Vector2,!0),this.registerInput("zw ",tm.Vector2,!0),this.registerInput("x",tm.Float,!0),this.registerInput("y",tm.Float,!0),this.registerInput("z",tm.Float,!0),this.registerInput("w",tm.Float,!0),this.registerOutput("xyzw",tm.Vector4),this.registerOutput("xyz",tm.Vector3),this.registerOutput("xy",tm.Vector2),this.registerOutput("zw",tm.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){let t=this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle;return"."+t.substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.x,i=this.y,r=this.z,s=this.w,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],u=this._outputs[1],c=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; -`)):o.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${o.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(3)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; -`)):(n.isConnected?(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${a.associatedVariableName})${this._buildSwizzle(4)}; -`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; -`)):(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${a.associatedVariableName})${this._buildSwizzle(4)}; -`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; -`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; -`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; -`)),d.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; -`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; -`)),this}serialize(){let e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){var r,s,n,a;super._deserialize(e,t,i),this.xSwizzle=null!==(r=e.xSwizzle)&&void 0!==r?r:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(n=e.zSwizzle)&&void 0!==n?n:"z",this.wSwizzle=null!==(a=e.wSwizzle)&&void 0!==a?a:"w"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; -${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; -${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; -${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; -`}};(0,rv.H)("BABYLON.VectorMergerBlock",VectorMergerBlock);let RemapBlock=class RemapBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.sourceRange=new rm.FM(-1,1),this.targetRange=new rm.FM(0,1),this.registerInput("input",tm.AutoDetect),this.registerInput("sourceMin",tm.Float,!0),this.registerInput("sourceMax",tm.Float,!0),this.registerInput("targetMin",tm.Float,!0),this.registerInput("targetMax",tm.Float,!0),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${s}) / (${r} - ${i}); -`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); -`+`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); -`}serialize(){let e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=rm.FM.FromArray(e.sourceRange),this.targetRange=rm.FM.FromArray(e.targetRange)}};(0,rH.gn)([editableInPropertyPage("From",tT.Vector2)],RemapBlock.prototype,"sourceRange",void 0),(0,rH.gn)([editableInPropertyPage("To",tT.Vector2)],RemapBlock.prototype,"targetRange",void 0),(0,rv.H)("BABYLON.RemapBlock",RemapBlock);let MultiplyBlock=class MultiplyBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(tm.Float),this._inputs[1].acceptedConnectionPointTypes.push(tm.Float)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; -`,this}};(0,rv.H)("BABYLON.MultiplyBlock",MultiplyBlock),(g=tb||(tb={}))[g.Material=0]="Material",g[g.PostProcess=1]="PostProcess",g[g.Particle=2]="Particle",g[g.ProceduralTexture=3]="ProceduralTexture";var sv=i(1974);let BoxParticleEmitter=class BoxParticleEmitter{constructor(){this.direction1=new rm.P(0,1,0),this.direction2=new rm.P(0,1,0),this.minEmitBox=new rm.P(-.5,-.5,-.5),this.maxEmitBox=new rm.P(.5,.5,.5)}startDirectionFunction(e,t,i,r){let s=rE.R.RandomRange(this.direction1.x,this.direction2.x),n=rE.R.RandomRange(this.direction1.y,this.direction2.y),a=rE.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.x=s,t.y=n,t.z=a;return}rm.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){let s=rE.R.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),n=rE.R.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=rE.R.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=s,t.y=n,t.z=a;return}rm.P.TransformCoordinatesFromFloatsToRef(s,n,a,e,t)}clone(){let e=new BoxParticleEmitter;return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){rm.P.FromArrayToRef(e.direction1,0,this.direction1),rm.P.FromArrayToRef(e.direction2,0,this.direction2),rm.P.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),rm.P.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}};let ConeParticleEmitter=class ConeParticleEmitter{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?rm.jp.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),rm.jp.Vector3[0]).normalize();let s=rE.R.RandomRange(0,this.directionRandomizer),n=rE.R.RandomRange(0,this.directionRandomizer),a=rE.R.RandomRange(0,this.directionRandomizer);t.x=rm.jp.Vector3[0].x+s,t.y=rm.jp.Vector3[0].y+n,t.z=rm.jp.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,r){let s;let n=rE.R.RandomRange(0,2*Math.PI);s=this.emitFromSpawnPointOnly?1e-4:1-(s=rE.R.RandomRange(0,this.heightRange))*s;let a=this._radius-rE.R.RandomRange(0,this._radius*this.radiusRange);a*=s;let o=a*Math.sin(n),l=a*Math.cos(n),h=s*this._height;if(r){t.x=o,t.y=h,t.z=l;return}rm.P.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){let e=new ConeParticleEmitter(this._radius,this._angle,this.directionRandomizer);return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}};let CylinderParticleEmitter=class CylinderParticleEmitter{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=rm.P.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),rm.P.TransformNormalToRef(this._tempVector,s,this._tempVector);let n=rE.R.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),a=Math.atan2(this._tempVector.x,this._tempVector.z);if(a+=rE.R.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}rm.P.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){let s=rE.R.RandomRange(-this.height/2,this.height/2),n=rE.R.RandomRange(0,2*Math.PI),a=rE.R.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1),o=Math.sqrt(a)*this.radius,l=o*Math.cos(n),h=o*Math.sin(n);if(r){t.copyFromFloats(l,s,h);return}rm.P.TransformCoordinatesFromFloatsToRef(l,s,h,e,t)}clone(){let e=new CylinderParticleEmitter(this.radius,this.directionRandomizer);return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}};let CylinderDirectedParticleEmitter=class CylinderDirectedParticleEmitter extends CylinderParticleEmitter{constructor(e=1,t=1,i=1,r=new rm.P(0,1,0),s=new rm.P(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t){let i=rE.R.RandomRange(this.direction1.x,this.direction2.x),r=rE.R.RandomRange(this.direction1.y,this.direction2.y),s=rE.R.RandomRange(this.direction1.z,this.direction2.z);rm.P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new CylinderDirectedParticleEmitter(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){let e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}};let HemisphericParticleEmitter=class HemisphericParticleEmitter{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=rE.R.RandomRange(0,this.directionRandomizer),a=rE.R.RandomRange(0,this.directionRandomizer),o=rE.R.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}rm.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-rE.R.RandomRange(0,this.radius*this.radiusRange),n=rE.R.RandomRange(0,1),a=rE.R.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,Math.abs(h),u);return}rm.P.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),u,e,t)}clone(){let e=new HemisphericParticleEmitter(this.radius,this.directionRandomizer);return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}};let PointParticleEmitter=class PointParticleEmitter{constructor(){this.direction1=new rm.P(0,1,0),this.direction2=new rm.P(0,1,0)}startDirectionFunction(e,t,i,r){let s=rE.R.RandomRange(this.direction1.x,this.direction2.x),n=rE.R.RandomRange(this.direction1.y,this.direction2.y),a=rE.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}rm.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}rm.P.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){let e=new PointParticleEmitter;return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){rm.P.FromArrayToRef(e.direction1,0,this.direction1),rm.P.FromArrayToRef(e.direction2,0,this.direction2)}};let SphereParticleEmitter=class SphereParticleEmitter{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=rE.R.RandomRange(0,this.directionRandomizer),a=rE.R.RandomRange(0,this.directionRandomizer),o=rE.R.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}rm.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-rE.R.RandomRange(0,this.radius*this.radiusRange),n=rE.R.RandomRange(0,1),a=rE.R.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,h,u);return}rm.P.TransformCoordinatesFromFloatsToRef(l,h,u,e,t)}clone(){let e=new SphereParticleEmitter(this.radius,this.directionRandomizer);return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}};let SphereDirectedParticleEmitter=class SphereDirectedParticleEmitter extends SphereParticleEmitter{constructor(e=1,t=new rm.P(0,1,0),i=new rm.P(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){let i=rE.R.RandomRange(this.direction1.x,this.direction2.x),r=rE.R.RandomRange(this.direction1.y,this.direction2.y),s=rE.R.RandomRange(this.direction1.z,this.direction2.z);rm.P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new SphereDirectedParticleEmitter(this.radius,this.direction1,this.direction2);return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){let e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}};let CustomParticleEmitter=class CustomParticleEmitter{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){let s=rm.jp.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);let e=rm.jp.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(r){t.copyFrom(s);return}rm.P.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){let s=rm.jp.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r){t.copyFrom(s);return}rm.P.TransformCoordinatesToRef(s,e,t)}clone(){let e=new CustomParticleEmitter;return rC.j.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e}parse(e){}};let MeshParticleEmitter=class MeshParticleEmitter{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(rz.o.PositionKind),this._normals=e.getVerticesData(rz.o.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=rm.P.Zero(),this._mesh=null,this.direction1=new rm.P(0,1,0),this.direction2=new rm.P(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){rm.P.TransformNormalToRef(this._storedNormal,e,t);return}let s=rE.R.RandomRange(this.direction1.x,this.direction2.x),n=rE.R.RandomRange(this.direction1.y,this.direction2.y),a=rE.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}rm.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;let s=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),a=Math.random()*(1-n),o=1-n-a,l=this._indices[s],h=this._indices[s+1],u=this._indices[s+2],c=rm.jp.Vector3[0],d=rm.jp.Vector3[1],p=rm.jp.Vector3[2],_=rm.jp.Vector3[3];rm.P.FromArrayToRef(this._positions,3*l,c),rm.P.FromArrayToRef(this._positions,3*h,d),rm.P.FromArrayToRef(this._positions,3*u,p),_.x=n*c.x+a*d.x+o*p.x,_.y=n*c.y+a*d.y+o*p.y,_.z=n*c.z+a*d.z+o*p.z,r?t.copyFromFloats(_.x,_.y,_.z):rm.P.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(rm.P.FromArrayToRef(this._normals,3*l,c),rm.P.FromArrayToRef(this._normals,3*h,d),rm.P.FromArrayToRef(this._normals,3*u,p),this._storedNormal.x=n*c.x+a*d.x+o*p.x,this._storedNormal.y=n*c.y+a*d.y+o*p.y,this._storedNormal.z=n*c.z+a*d.z+o*p.z)}clone(){let e=new MeshParticleEmitter(this.mesh);return rC.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;let t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){rm.P.FromArrayToRef(e.direction1,0,this.direction1),rm.P.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}};i(6529);let BaseParticleSystem=class BaseParticleSystem{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:rm.P.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:rm.P.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:rm.P.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:rm.P.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(let i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=rm.P.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new rm.P(10,10,10),this.onAnimationEnd=null,this.blendMode=BaseParticleSystem.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new rm.FM(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new rm.P(0,0,0),this._useLogarithmicDepth=!1,this.gravity=rm.P.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new rg.HE(1,1,1,1),this.color2=new rg.HE(1,1,1,1),this.colorDead=new rg.HE(0,0,0,1),this.textureMask=new rg.HE(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new sv.b,this.id=e,this.name=e}createPointEmitter(e,t){let i=new PointParticleEmitter;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){let i=new HemisphericParticleEmitter(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){let i=new SphereParticleEmitter(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new rm.P(0,1,0),i=new rm.P(0,1,0)){let r=new SphereDirectedParticleEmitter(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){let s=new CylinderParticleEmitter(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new rm.P(0,1,0),s=new rm.P(0,1,0)){let n=new CylinderDirectedParticleEmitter(e,t,i,r,s);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){let i=new ConeParticleEmitter(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){let s=new BoxParticleEmitter;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}};BaseParticleSystem.BLENDMODE_ONEONE=0,BaseParticleSystem.BLENDMODE_STANDARD=1,BaseParticleSystem.BLENDMODE_ADD=2,BaseParticleSystem.BLENDMODE_MULTIPLY=3,BaseParticleSystem.BLENDMODE_MULTIPLYADD=4;let ColorSplitterBlock=class ColorSplitterBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("rgba",tm.Color4,!0),this.registerInput("rgb ",tm.Color3,!0),this.registerOutput("rgb",tm.Color3),this.registerOutput("r",tm.Float),this.registerOutput("g",tm.Float),this.registerOutput("b",tm.Float),this.registerOutput("a",tm.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);let t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;let i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],a=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; -`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.r; -`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g; -`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b; -`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.a; -`),this}};(0,rv.H)("BABYLON.ColorSplitterBlock",ColorSplitterBlock);var sx=i(5184),sT=i(2195);r6.B.prototype.createRenderTargetCubeTexture=function(e,t){let i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);let s=this._gl,n=new r5.l(this,r5.S.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);let a=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,rT.Y.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,a.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,a.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);let o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n.format=r.format,this._internalTexturesCache.push(n),i.setTextures(n),i};let sS={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};let EffectRenderer=class EffectRenderer{constructor(e,t=sS){var i,r;this._fullscreenViewport=new sh.l(0,0,1,1);let s=null!==(i=t.positions)&&void 0!==i?i:sS.positions,n=null!==(r=t.indices)&&void 0!==r?r:sS.indices;this.engine=e,this._vertexBuffers={[rz.o.PositionKind]:new rz.o(e,s,rz.o.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{for(let t in this._indexBuffer=e.createIndexBuffer(n),this._vertexBuffers){let e=this._vertexBuffers[t];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(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){let e=this._vertexBuffers[rz.o.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[rz.o.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}};let EffectWrapper=class EffectWrapper{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new rf.y$;let i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)}));let r=e.defines?e.defines.join("\n"):"";this._drawWrapper=new sm.q(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"],i,e.samplerNames,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new ss.Q(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._wasPreviouslyReady=!1,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}};let sC="passPixelShader",sE=`varying vec2 vUV;uniform sampler2D textureSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);}`;s_.v.ShadersStore[sC]=sE;let sb={name:sC,shader:sE};let dumpTools_DumpTools=class dumpTools_DumpTools{static _CreateDumpRenderer(){if(!dumpTools_DumpTools._DumpToolsEngine){let e;let t=null,i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new r6.B(e,!1,i)}catch(r){e=document.createElement("canvas"),t=new r6.B(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;let r=new EffectRenderer(t),s=new EffectWrapper({engine:t,name:sb.name,fragmentShader:sb.shader,samplerNames:["textureSampler"]});dumpTools_DumpTools._DumpToolsEngine={canvas:e,engine:t,renderer:r,wrapper:s}}return dumpTools_DumpTools._DumpToolsEngine}static async DumpFramebuffer(e,t,i,r,s="image/png",n,a){let o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);dumpTools_DumpTools.DumpData(e,t,l,r,s,n,!0,void 0,a)}static DumpDataAsync(e,t,i,r="image/png",s,n=!1,a=!1,o){return new Promise(l=>{dumpTools_DumpTools.DumpData(e,t,i,e=>l(e),r,s,n,a,o)})}static DumpData(e,t,i,r,s="image/png",n,a=!1,o=!1,l){let h=dumpTools_DumpTools._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){let e=new Uint8Array(i.length),t=i.length;for(;t--;){let r=i[t];e[t]=Math.round(255*rE.R.Clamp(r))}i=e}let u=h.engine.createRawTexture(i,e,t,5,!1,!a,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",u),h.renderer.draw(),o?rW.w1.ToBlob(h.canvas,e=>{let t=new FileReader;t.onload=e=>{let t=e.target.result;r&&r(t)},t.readAsArrayBuffer(e)},s,l):rW.w1.EncodeScreenshotCanvasData(h.canvas,r,s,n,l),u.dispose()}static Dispose(){dumpTools_DumpTools._DumpToolsEngine&&(dumpTools_DumpTools._DumpToolsEngine.wrapper.dispose(),dumpTools_DumpTools._DumpToolsEngine.renderer.dispose(),dumpTools_DumpTools._DumpToolsEngine.engine.dispose()),dumpTools_DumpTools._DumpToolsEngine=null}};rW.w1.DumpData=dumpTools_DumpTools.DumpData,rW.w1.DumpDataAsync=dumpTools_DumpTools.DumpDataAsync,rW.w1.DumpFramebuffer=dumpTools_DumpTools.DumpFramebuffer;let renderTargetTexture_RenderTargetTexture=class renderTargetTexture_RenderTargetTexture extends texture_Texture{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,rB.M)(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 i;i=Array.isArray(e)?e:[e];for(let e=0;e{var i;let r=this._renderList?this._renderList.length:0;(0===t&&r>0||0===r)&&(null===(i=this.getScene())||void 0===i||i.meshes.forEach(e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new rf.y$,this.onAfterUnbindObservable=new rf.y$,this.onBeforeRenderObservable=new rf.y$,this.onAfterRenderObservable=new rf.y$,this.onClearObservable=new rf.y$,this.onResizeObservable=new rf.y$,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=rm.P.Zero(),!(i=this.getScene()))return;let P=this.getScene().getEngine();if(this._gammaSpace=y,this._coordinatesMode=texture_Texture.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=P.onResizeObservable.add(()=>{}),this._generateMipMaps=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new sT.$(i),this._renderingManager._useSceneAutoClearSetup=!0,u)return;this._renderTargetOptions={generateMipMaps:r,type:n,format:null!==(E=this._format)&&void 0!==E?E:void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:p,creationFlags:_,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:b,label:this.name},this.samplingMode===texture_Texture.NEAREST_SAMPLINGMODE&&(this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE),d||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=texture_Texture.INVCUBIC_MODE,this._textureMatrix=rm.y3.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0===p||(this.samples=p))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14){var n;null===(n=this._renderTarget)||void 0===n||n.createDepthStencilTexture(e,t,i,r,s)}_releaseRenderPassId(){if(this._scene){let e=this._scene.getEngine();for(let t=0;t0&&(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(){let e=this._size.layers;return e||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;let i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;let r=this.getScene();r&&(this._processSizeParameter(e,!1),i?this._renderTarget=r.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=r.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,i=!1){var r;let s=this.getScene();if(!s)return i;let n=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){this.renderList=[];for(let e=0;e1||this.activeCamera&&this.activeCamera!==s.activeCamera)&&s.setTransformMatrix(s.activeCamera.getViewMatrix(),s.activeCamera.getProjectionMatrix(!0)),n.setViewport(s.activeCamera.viewport)),s.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){let i=e*t,r=rq.D.NearestPOT(i+16384/(128+i));return Math.min(rq.D.FloorPOT(e),r)}_prepareRenderingManager(e,t,i,r){let s=this.getScene();if(!s)return;this._renderingManager.reset();let n=s.getRenderId();for(let a=0;a{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,s=null){var n,a,o,l,h,u;let c=this.getScene();if(!c)return;let d=c.getEngine();null===(n=d._debugPushGroup)||void 0===n||n.call(d,`render to face #${e} layer #${r}`,1),this._prepareFrame(c,e,r,t),this.is2DArray?(d.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(d.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));let p=d.snapshotRendering&&1===d.snapshotRenderingMode;if(p)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0);else{let n=null,u=this.renderList?this.renderList:c.getActiveMeshes().data,p=this.renderList?this.renderList.length:c.getActiveMeshes().length;for(let t of(this.getCustomRenderList&&(n=this.getCustomRenderList(this.is2DArray?r:e,u,p)),n?this._prepareRenderingManager(n,n.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(u,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),n=u),c._beforeRenderTargetClearStage))t.action(this,e,r);for(let t of(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),c._beforeRenderTargetDrawStage))t.action(this,e,r);for(let t of(this._renderingManager.render(this.customRenderFunction,n,this.renderParticles,this.renderSprites),c._afterRenderTargetDrawStage))t.action(this,e,r);let _=null!==(o=null===(a=this._texture)||void 0===a?void 0:a.generateMipMaps)&&void 0!==o&&o;for(let i of(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&c.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e),c._afterRenderTargetPostProcessStage))i.action(this,e,r);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),i&&dumpTools_DumpTools.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),d)}this._unbindFrameBuffer(d,e),this._texture&&this.isCube&&5===e&&d.generateMipMapsForCubemap(this._texture),null===(u=d._debugPopGroup)||void 0===u||u.call(d,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){let e=this.getSize(),t=new renderTargetTexture_RenderTargetTexture(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;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&t.customRenderTargets.splice(i,1),t.cameras))(i=e.customRenderTargets.indexOf(this))>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}};renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE=0,renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME=1,renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,texture_Texture._CreateRenderTargetTexture=(e,t,i,r,s)=>new renderTargetTexture_RenderTargetTexture(e,t,i,r);let ProceduralTextureSceneComponent=class ProceduralTextureSceneComponent{constructor(e){this.name=rQ.l.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(rQ.l.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){rW.w1.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}};let sy=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.proceduralVertexShader=sy;let proceduralTexture_ProceduralTexture=class proceduralTexture_ProceduralTexture extends texture_Texture{constructor(e,t,i,r,s=null,n=!0,a=!1,o=0){super(null,r,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new rf.y$,this.onBeforeGenerationObservable=new rf.y$,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=[],this._samplers=[],this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null;let l=(r=this.getScene()||rS.l.LastCreatedScene)._getComponent(rQ.l.NAME_PROCEDURALTEXTURE);l||(l=new ProceduralTextureSceneComponent(r),r._addComponent(l)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=o,this._generateMipMaps=n,this._drawWrapper=new sm.q(this._fullEngine),this.setFragment(i),this._fallbackTexture=s;let h=this._createRtWrapper(a,t,n,o);this._texture=h.texture;let u=[];u.push(1,1),u.push(-1,1),u.push(-1,-1),u.push(1,-1),this._vertexBuffers[rz.o.PositionKind]=new rz.o(this._fullEngine,u,rz.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,{generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r}),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then(e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){let e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){let e=this._vertexBuffers[rz.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=renderTargetTexture_RenderTargetTexture.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}isReady(){let e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;let t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;let i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[rz.o.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var e;null===(e=this._rtWrapper)||void 0===e||e.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0})),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;let i=this._texture.isCube;this._rtWrapper.dispose();let r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return -1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;let r=this.getScene();if(!r)return;let s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(let e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(let e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(let e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(let e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(let e in this._colors4){let t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(let e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(let e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;null===(t=s._debugPushGroup)||void 0===t||t.call(s,`procedural texture generation for ${this.name}`,1);let n=s.currentViewport;if(this.isCube)for(let e=0;e<6;e++)s.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(sr.F.TriangleFillMode,0,6);else s.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(sr.F.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),n&&s.setViewport(n),this.isCube&&s.generateMipMapsForCubemap(this._texture),null===(i=s._debugPopGroup)||void 0===i||i.call(s,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){let e=this.getSize(),t=new proceduralTexture_ProceduralTexture(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){let e=this.getScene();if(!e)return;let t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);let i=this._vertexBuffers[rz.o.PositionKind];i&&(i.dispose(),this._vertexBuffers[rz.o.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}};(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"autoClear",void 0),(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"_generateMipMaps",void 0),(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"_size",void 0),(0,rH.gn)([(0,rb.qC)()],proceduralTexture_ProceduralTexture.prototype,"refreshRate",null),(0,rv.H)("BABYLON.ProceduralTexture",proceduralTexture_ProceduralTexture),(v=ty||(ty={}))[v.Cos=0]="Cos",v[v.Sin=1]="Sin",v[v.Abs=2]="Abs",v[v.Exp=3]="Exp",v[v.Exp2=4]="Exp2",v[v.Round=5]="Round",v[v.Floor=6]="Floor",v[v.Ceiling=7]="Ceiling",v[v.Sqrt=8]="Sqrt",v[v.Log=9]="Log",v[v.Tan=10]="Tan",v[v.ArcTan=11]="ArcTan",v[v.ArcCos=12]="ArcCos",v[v.ArcSin=13]="ArcSin",v[v.Fract=14]="Fract",v[v.Sign=15]="Sign",v[v.Radians=16]="Radians",v[v.Degrees=17]="Degrees";let TrigonometryBlock=class TrigonometryBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.operation=ty.Cos,this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="";switch(this.operation){case ty.Cos:i="cos";break;case ty.Sin:i="sin";break;case ty.Abs:i="abs";break;case ty.Exp:i="exp";break;case ty.Exp2:i="exp2";break;case ty.Round:i="round";break;case ty.Floor:i="floor";break;case ty.Ceiling:i="ceil";break;case ty.Sqrt:i="sqrt";break;case ty.Log:i="log";break;case ty.Tan:i="tan";break;case ty.ArcTan:i="atan";break;case ty.ArcCos:i="acos";break;case ty.ArcSin:i="asin";break;case ty.Fract:i="fract";break;case ty.Sign:i="sign";break;case ty.Radians:i="radians";break;case ty.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); -`,this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${ty[this.operation]}; -`;return e}};(0,rv.H)("BABYLON.TrigonometryBlock",TrigonometryBlock);let sP={effect:null,subMesh:null};let NodeMaterialDefines=class NodeMaterialDefines extends sn.H{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!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=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}};let NodeMaterial=class NodeMaterial extends PushMaterial{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||rS.l.LastCreatedScene),this._buildId=NodeMaterial._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new rm.y3,this._cachedWorldViewProjectionMatrix=new rm.y3,this._optimizers=[],this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new rf.y$,this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[],this._mode=tb.Material,this.forceAlphaBlending=!1,this._options=Object.assign({emitComments:!1},i),this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){rW.w1.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(let t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){let t=this._optimizers.indexOf(e);if(!(t>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){let t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return(e.target&tg.Vertex)!=0&&this._addVertexOutputNode(e),(e.target&tg.Fragment)!=0&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||((e.target&tg.Vertex)!=0&&this._removeVertexOutputNode(e),(e.target&tg.Fragment)!=0&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=tg.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){let t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=tg.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){let t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){e.target===tg.VertexAndFragment?i.push(e):t.target===tg.Fragment&&e.target===tg.Vertex&&e._preparationId!==this._buildId&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){let t=e.getClassName();for(let e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(let s of e.inputs){s.associatedVariableName="";let n=s.connectedPoint;if(n){let s=n.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}for(let s of(e.isTeleportOut&&e.entryPoint&&this._processInitializeOnLink(e.entryPoint,t,i,r),e.outputs))s.associatedVariableName=""}_resetDualBlocks(e,t){for(let i of(e.target===tg.VertexAndFragment&&(e.buildId=t),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._resetDualBlocks(e.entryPoint,t)}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;let r=this.getScene().getEngine(),s=this._mode===tb.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new NodeMaterialBuildState,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=tg.Vertex,this._fragmentCompilationState=new NodeMaterialBuildState,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=tg.Fragment,this._sharedData=new NodeMaterialBuildStateSharedData,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;let n=[],a=[];for(let e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,a,i);for(let e of this._fragmentOutputNodes)a.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);for(let e of(this.optimize(),n))e.build(this._vertexCompilationState,n);for(let e of(this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState,a))this._resetDualBlocks(e,this._buildId-1);for(let e of a)e.build(this._fragmentCompilationState,a);this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=NodeMaterial._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(console.log("Vertex shader:"),console.log(this._vertexCompilationState.compilationString),console.log("Fragment shader:"),console.log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this);let o=this.getScene().meshes;for(let e of o)if(e.subMeshes)for(let t of e.subMeshes){if(t.getMaterial()!==this||!t.materialDefines)continue;let e=t.materialDefines;e.markAllAsDirty(),e.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();let l=this.getScene().prePassRenderer;l&&l.markAsDirty()}optimize(){for(let e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){let i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(rz.o.NormalKind),t.TANGENT=e.isVerticesDataPresent(rz.o.TangentKind);let n=e.useVertexColors&&e.isVerticesDataPresent(rz.o.ColorKind);t.VERTEXCOLOR_NME=n;let a=!1;for(let i=1;i<=6;++i){let r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),a=a||t["UV"+i]!==r}let o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;so.G.PrepareDefinesForPrePass(this.getScene(),t,!o),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||a)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){let e=this.getBlockByPredicate(e=>"PrePassOutputBlock"===e.getClassName()),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){let e=this.getAllTextureBlocks().filter(e=>"PrePassTextureBlock"===e.getClassName()),t=[];for(let i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){let t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");for(let r of(i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]})),t))i.texturesRequired.includes(r)||i.texturesRequired.push(r);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,n=0,a=5){return this.mode!==tb.PostProcess?(console.log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,n,a)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,n,a=0,o=5){let l=this.name+this._buildId,h=new NodeMaterialDefines,u=new rG.x(l+"PostProcess",this.getScene()),c=this._buildId;return this._processDefines(u,h),ss.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new postProcess_PostProcess(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,n,h.toString(),a,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,o),e.nodeMaterialSource=this,e.onApplyObservable.add(t=>{c!==this._buildId&&(delete ss.Q.ShadersStore[l+"VertexShader"],delete ss.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),c=this._buildId);let i=this._processDefines(u,h);i&&(ss.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),r0.Q.SetImmediate(()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l))),this._checkInternals(t)}),e}createProceduralTexture(e,t){if(this.mode!==tb.ProceduralTexture)return console.log("Incompatible material mode"),null;let i=this.name+this._buildId,r=new proceduralTexture_ProceduralTexture(i,e,null,t),s=new rG.x(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};let n=new NodeMaterialDefines,a=this._processDefines(s,n);ss.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[rz.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==a?void 0:a.fallbacks,void 0);r.nodeMaterialSource=this,r._setEffect(o);let l=this._buildId;return r.onBeforeGenerationObservable.add(()=>{l!==this._buildId&&(delete ss.Q.ShadersStore[i+"VertexShader"],delete ss.Q.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);let e=this._processDefines(s,n);e&&(ss.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),r0.Q.SetImmediate(()=>{o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[rz.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==e?void 0:e.fallbacks,void 0),r._setEffect(o)})),this._checkInternals(o)}),r}_createEffectForParticles(e,t,i,r,s,n,a,o=""){let l=this.name+this._buildId+"_"+t;n||(n=new NodeMaterialDefines),a||(a=this.getScene().getMeshByName(this.name+"Particle"))||((a=new rG.x(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId,u=[],c=o;if(!s){let o=this._processDefines(a,n);ss.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),c=u.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==o?void 0:o.fallbacks,i,r,e),e.setCustomEffect(s,t)}s.onBindObservable.add(s=>{h!==this._buildId&&(delete ss.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),u.length=0,e.fillDefines(u,t);let d=u.join("\n");d!==c&&(n.markAllAsDirty(),c=d);let p=this._processDefines(a,n);if(p){ss.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==p?void 0:p.fallbacks,i,r,e),e.setCustomEffect(s,t),this._createEffectForParticles(e,t,i,r,s,n,a,o);return}this._checkInternals(s)})}_checkInternals(e){if(this._sharedData.animatedInputs){let e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(let t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(let t of this._sharedData.bindableBlocks)t.bind(e,this);for(let t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==tb.Particle){console.log("Incompatible material mode");return}this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,BaseParticleSystem.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==tb.Material){console.log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let s=null,n=this.getScene();if(so.G.PrepareDefinesForCamera(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(r=>{r.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(s=>{s.prepareDefines(e,this,t,i,r)}),t.isDirty){let i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)});let r=[];this._sharedData.dynamicUniformBlocks.forEach(e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)});let n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(e=>{let t=n.indexOf(e);-1===t&&n.push(e)});let a=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(e=>{let t=a.indexOf(e);-1===t&&a.push(e)});let o=new EffectFallbacks;this._sharedData.blocksWithFallbacks.forEach(t=>{t.provideFallbacks(e,o)}),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:n,mergedSamplers:a,fallbacks:o}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;let r=this.getScene();if(this._sharedData.animatedInputs){let e=r.getFrameId();if(this._animationFrame!==e){for(let e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new NodeMaterialDefines);let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some(t=>!t.isReady(e,this,s,i)))return!1;let a=this._processDefines(e,s,i,t);if(a){let e=t.effect,i=s.toString(),o=n.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:s.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},n);if(o){if(this._onEffectCreatedObservable&&(sP.effect=o,sP.subMesh=t,this._onEffectCreatedObservable.notifyObservers(sP)),this.allowShaderHotSwapping&&e&&!o.isReady()){if(o=e,s.markAsUnprocessed(),a.lightDisposed)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(o,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader -${this._vertexCompilationState.compilationString} - -// Fragment shader -${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){let t=this.getScene();if(!this._activeEffect)return;let i=this._sharedData.hints;for(let r of(i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._sharedData.inputBlocks))r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);let n=this._mustRebind(r,s,t.visibility),a=this._sharedData;if(n){for(let e of a.bindableBlocks)e.bind(s,this,t,i);for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);for(let e of a.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){let e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter(e=>e.texture).map(e=>e.texture)),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){let e=[];for(let t of this.attachedBlocks)NodeMaterial._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(let t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(let e of this.getTextureBlocks().filter(e=>e.texture).map(e=>e.texture))e.dispose();for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){let t=Object.assign({nodeMaterial:this},e);this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise(t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){let i=e&&e.editorURL?e.editorURL:NodeMaterial.EditorURL;rW.w1.LoadBabylonScript(i,()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()})}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position");let t=new InputBlock("World");t.setAsSystemValue(tC.World);let i=new TransformBlock("WorldPos");e.connectTo(i),t.connectTo(i);let r=new InputBlock("ViewProjection");r.setAsSystemValue(tC.ViewProjection);let s=new TransformBlock("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);let n=new VertexOutputBlock("VertexOutput");s.connectTo(n);let a=new InputBlock("color");a.value=new rg.HE(.8,.8,.8,1);let o=new FragmentOutputBlock("FragmentOutput");a.connectTo(o),this.addOutputNode(n),this.addOutputNode(o),this._mode=tb.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position2d");let t=new InputBlock("Constant1");t.isConstant=!0,t.value=1;let i=new VectorMergerBlock("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new VertexOutputBlock("VertexOutput");i.connectTo(r);let s=new InputBlock("Scale");s.visibleInInspector=!0,s.value=new rm.FM(1,1);let n=new RemapBlock("uv0");e.connectTo(n);let a=new MultiplyBlock("UV scale");n.connectTo(a),s.connectTo(a);let o=new CurrentScreenBlock("CurrentScreen");a.connectTo(o),o.texture=new texture_Texture("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());let l=new FragmentOutputBlock("FragmentOutput");o.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=tb.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;let e=new InputBlock("Position");e.setAsAttribute("position2d");let t=new InputBlock("Constant1");t.isConstant=!0,t.value=1;let i=new VectorMergerBlock("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new VertexOutputBlock("VertexOutput");i.connectTo(r);let s=new InputBlock("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=tE.Time,s.isConstant=!1;let n=new InputBlock("Color3");n.value=new rg.Wo(1,1,1),n.isConstant=!1;let a=new FragmentOutputBlock("FragmentOutput"),o=new VectorMergerBlock("VectorMerger");o.visibleInInspector=!1;let l=new TrigonometryBlock("Cos");l.operation=ty.Cos,e.connectTo(o),s.output.connectTo(l.input),l.output.connectTo(o.z),o.xyzOut.connectTo(a.rgb),this.addOutputNode(r),this.addOutputNode(a),this._mode=tb.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;let e=new InputBlock("uv");e.setAsAttribute("particle_uv");let t=new ParticleTextureBlock("ParticleTexture");e.connectTo(t);let i=new InputBlock("Color");i.setAsAttribute("particle_color");let r=new MultiplyBlock("Texture * Color");t.connectTo(r),i.connectTo(r);let s=new ParticleRampGradientBlock("ParticleRampGradient");r.connectTo(s);let n=new ColorSplitterBlock("ColorSplitter");i.connectTo(n);let a=new ParticleBlendMultiplyBlock("ParticleBlendMultiply");s.connectTo(a),t.connectTo(a,{output:"a"}),n.connectTo(a,{output:"a"});let o=new FragmentOutputBlock("FragmentOutput");a.connectTo(o),this.addOutputNode(o),this._mode=tb.Particle}async loadAsync(e,t=""){return NodeMaterial.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}generateCode(){let e=[],t=[],i=["const","var","let"];for(let e of this._vertexOutputNodes)this._gatherBlocks(e,t);let r=[];for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); -`;for(let r of(s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${tb[this.mode]}; -`,t))r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(let t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));for(let t of(e=[],s+="\n// Connections\n",this._vertexOutputNodes))s+=t._dumpCodeForOutputConnections(e);for(let t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(let e of(s+="\n// Output nodes\n",this._vertexOutputNodes))s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); -`;for(let e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); -`;return s+`nodeMaterial.build(); -`}serialize(e){let t=e?{}:rb.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{for(let e of(t.customType="BABYLON.NodeMaterial",t.outputNodes=[],this._vertexOutputNodes))this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}for(let e of(t.blocks=[],i))t.blocks.push(e.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var r;i||this.clear();let s={};for(let i of e.blocks){let e=(0,rv.q)(i.customType);if(e){let r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let i=s[t];i.attachToEndpoint(e)}}for(let t=0;tnew NodeMaterial(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){let e=[];return this.getActiveTextures().forEach(t=>{let i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((e,t)=>{i.onLoadedObservable.addOnce(()=>{e()}),i.onErrorObservable.addOnce(e=>{t(e)})}))}),Promise.all(e)}static Parse(e,t,i=""){let r=rb.p4.Parse(()=>new NodeMaterial(e.name,t),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,r="",s=!1,n){let a=null!=n?n:new NodeMaterial(e,i),o=await i._loadFileAsync(t),l=JSON.parse(o);return a.parseSerializedObject(l,r),s||a.build(),a}static ParseFromSnippetAsync(e,t=rS.l.LastCreatedScene,i="",r,s=!1,n=!1){return"_BLANK"===e?Promise.resolve(NodeMaterial.CreateDefault("blank",t)):new Promise((a,o)=>{let l=new rP.g;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let h=JSON.parse(JSON.parse(l.responseText).jsonPayload),u=JSON.parse(h.nodeMaterial);r||((r=rb.p4.Parse(()=>new NodeMaterial(e,t),u,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(u),r.snippetId=e;try{s||r.build()}catch(e){o(e)}n?r.whenTexturesReadyAsync().then(()=>{a(r)}).catch(e=>{o(e)}):a(r)}else o("Unable to load the snippet "+e)}}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}static CreateDefault(e,t){let i=new NodeMaterial(e,t);return i.setToDefault(),i.build(),i}};function CreateIcoSphereVertexData(e){let t;let i=e.sideOrientation||se.x.DEFAULTSIDE,r=e.radius||1,s=void 0===e.flat||e.flat,n=0|(e.subdivisions||4),a=e.radiusX||r,o=e.radiusY||r,l=e.radiusZ||r,h=(1+Math.sqrt(5))/2,u=[-1,h,-0,1,h,0,-1,-h,0,1,-h,0,0,-1,-h,0,1,-h,0,-1,h,0,1,h,h,0,1,h,0,-1,-h,0,1,-h,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],p=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=138/1024,f=239/1024,m=60/1024,g=26/1024,v=-40/1024,x=20/1024,T=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],S=[],C=[],E=[],b=[],y=0,P=[,,,],R=[,,,];for(t=0;t<3;t++)P[t]=rm.P.Zero(),R[t]=rm.FM.Zero();for(let e=0;e<20;e++){for(t=0;t<3;t++){let i=c[3*e+t];P[t].copyFromFloats(u[3*d[i]],u[3*d[i]+1],u[3*d[i]+2]),P[t].normalize(),R[t].copyFromFloats(p[2*i]*_+m+T[e]*v,p[2*i+1]*f+g+T[e]*x)}let interp_vertex=(e,t,i,r)=>{let h;let u=rm.P.Lerp(P[0],P[2],t/n),c=rm.P.Lerp(P[1],P[2],t/n),d=n===t?P[2]:rm.P.Lerp(u,c,e/(n-t));if(d.normalize(),s){let e=rm.P.Lerp(P[0],P[2],r/n),t=rm.P.Lerp(P[1],P[2],r/n);h=rm.P.Lerp(e,t,i/(n-r))}else h=new rm.P(d.x,d.y,d.z);h.x/=a,h.y/=o,h.z/=l,h.normalize();let p=rm.FM.Lerp(R[0],R[2],t/n),_=rm.FM.Lerp(R[1],R[2],t/n),f=n===t?R[2]:rm.FM.Lerp(p,_,e/(n-t));C.push(d.x*a,d.y*o,d.z*l),E.push(h.x,h.y,h.z),b.push(f.x,r4.e.UseOpenGLOrientationForUV?1-f.y:f.y),S.push(y),y++};for(let e=0;eCreateIcoSphere(e,t,i),(x=tP||(tP={})).WRIST="wrist",x.THUMB="thumb",x.INDEX="index",x.MIDDLE="middle",x.RING="ring",x.LITTLE="little",(T=tR||(tR={})).WRIST="wrist",T.THUMB_METACARPAL="thumb-metacarpal",T.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",T.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",T.THUMB_TIP="thumb-tip",T.INDEX_FINGER_METACARPAL="index-finger-metacarpal",T.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",T.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",T.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",T.INDEX_FINGER_TIP="index-finger-tip",T.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",T.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",T.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",T.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",T.MIDDLE_FINGER_TIP="middle-finger-tip",T.RING_FINGER_METACARPAL="ring-finger-metacarpal",T.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",T.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",T.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",T.RING_FINGER_TIP="ring-finger-tip",T.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",T.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",T.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",T.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",T.PINKY_FINGER_TIP="pinky-finger-tip";let sR=[tR.WRIST,tR.THUMB_METACARPAL,tR.THUMB_PHALANX_PROXIMAL,tR.THUMB_PHALANX_DISTAL,tR.THUMB_TIP,tR.INDEX_FINGER_METACARPAL,tR.INDEX_FINGER_PHALANX_PROXIMAL,tR.INDEX_FINGER_PHALANX_INTERMEDIATE,tR.INDEX_FINGER_PHALANX_DISTAL,tR.INDEX_FINGER_TIP,tR.MIDDLE_FINGER_METACARPAL,tR.MIDDLE_FINGER_PHALANX_PROXIMAL,tR.MIDDLE_FINGER_PHALANX_INTERMEDIATE,tR.MIDDLE_FINGER_PHALANX_DISTAL,tR.MIDDLE_FINGER_TIP,tR.RING_FINGER_METACARPAL,tR.RING_FINGER_PHALANX_PROXIMAL,tR.RING_FINGER_PHALANX_INTERMEDIATE,tR.RING_FINGER_PHALANX_DISTAL,tR.RING_FINGER_TIP,tR.PINKY_FINGER_METACARPAL,tR.PINKY_FINGER_PHALANX_PROXIMAL,tR.PINKY_FINGER_PHALANX_INTERMEDIATE,tR.PINKY_FINGER_PHALANX_DISTAL,tR.PINKY_FINGER_TIP],sA={[tP.WRIST]:[tR.WRIST],[tP.THUMB]:[tR.THUMB_METACARPAL,tR.THUMB_PHALANX_PROXIMAL,tR.THUMB_PHALANX_DISTAL,tR.THUMB_TIP],[tP.INDEX]:[tR.INDEX_FINGER_METACARPAL,tR.INDEX_FINGER_PHALANX_PROXIMAL,tR.INDEX_FINGER_PHALANX_INTERMEDIATE,tR.INDEX_FINGER_PHALANX_DISTAL,tR.INDEX_FINGER_TIP],[tP.MIDDLE]:[tR.MIDDLE_FINGER_METACARPAL,tR.MIDDLE_FINGER_PHALANX_PROXIMAL,tR.MIDDLE_FINGER_PHALANX_INTERMEDIATE,tR.MIDDLE_FINGER_PHALANX_DISTAL,tR.MIDDLE_FINGER_TIP],[tP.RING]:[tR.RING_FINGER_METACARPAL,tR.RING_FINGER_PHALANX_PROXIMAL,tR.RING_FINGER_PHALANX_INTERMEDIATE,tR.RING_FINGER_PHALANX_DISTAL,tR.RING_FINGER_TIP],[tP.LITTLE]:[tR.PINKY_FINGER_METACARPAL,tR.PINKY_FINGER_PHALANX_PROXIMAL,tR.PINKY_FINGER_PHALANX_INTERMEDIATE,tR.PINKY_FINGER_PHALANX_DISTAL,tR.PINKY_FINGER_TIP]};let WebXRHand=class WebXRHand{get handMesh(){return this._handMesh}getHandPartMeshes(e){return sA[e].map(e=>this._jointMeshes[sR.indexOf(e)])}getJointMesh(e){return this._jointMeshes[sR.indexOf(e)]}constructor(e,t,i,r,s=!1,n=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=n,this._jointScaleFactor=a,this._jointTransforms=Array(sR.length),this._jointTransformMatrices=new Float32Array(16*sR.length),this._tempJointMatrix=new rm.y3,this._jointRadii=new Float32Array(sR.length),this._scene=t[0].getScene();for(let e=0;e{e.rootMesh&&e.rootMesh.setEnabled(!1)})),this.xrController.onMotionControllerInitObservable.add(e=>{e.onModelLoadedObservable.add(e=>{e.rootMesh&&e.rootMesh.setEnabled(!1)}),e.rootMesh&&e.rootMesh.setEnabled(!1)})}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(e=>e.alwaysSelectAsActiveMesh=!0),this._handMesh.skeleton){let e=this._handMesh.skeleton;sR.forEach((i,r)=>{let s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){let i=this.xrController.inputSource.hand;if(!i)return;let r=sR.map(e=>i[e]||i.get(e)),s=!1;if(e.fillPoses&&e.fillJointRadii)s=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){s=!0;for(let i=0;i{let i=this._jointTransforms[t];rm.y3.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);let r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),!this._scene.useRightHandedSystem&&(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}};let WebXRHandTracking=class WebXRHandTracking extends WebXRAbstractFeature{static _GenerateTrackedJointMeshes(e){let t={};return["left","right"].map(i=>{var r,s,n,a,o;let l=[],h=(null===(r=e.jointMeshes)||void 0===r?void 0:r.sourceMesh)||CreateIcoSphere("jointParent",WebXRHandTracking._ICOSPHERE_PARAMS);h.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t{var r,s,n,a,o;let l={};(null===(s=null===(r=WebXRHandTracking._RightHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===s?void 0:s.isDisposed())&&(WebXRHandTracking._RightHandGLB=null),(null===(a=null===(n=WebXRHandTracking._LeftHandGLB)||void 0===n?void 0:n.meshes[1])||void 0===a?void 0:a.isDisposed())&&(WebXRHandTracking._LeftHandGLB=null);let h=!!(WebXRHandTracking._RightHandGLB&&WebXRHandTracking._LeftHandGLB),u=await Promise.all([WebXRHandTracking._RightHandGLB||sceneLoader_SceneLoader.ImportMeshAsync("",WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL,WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),WebXRHandTracking._LeftHandGLB||sceneLoader_SceneLoader.ImportMeshAsync("",WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL,WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);WebXRHandTracking._RightHandGLB=u[0],WebXRHandTracking._LeftHandGLB=u[1];let c=new NodeMaterial("handShader",e,{emitComments:!1});await c.loadAsync(WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL),c.needDepthPrePass=!0,c.transparencyMode=sr.F.MATERIAL_ALPHABLEND,c.alphaMode=2,c.build(!1);let d=Object.assign({base:rg.Wo.FromInts(116,63,203),fresnel:rg.Wo.FromInts(149,102,229),fingerColor:rg.Wo.FromInts(177,130,255),tipFresnel:rg.Wo.FromInts(220,200,255)},null===(o=null==t?void 0:t.handMeshes)||void 0===o?void 0:o.customColors),p={base:c.getBlockByName("baseColor"),fresnel:c.getBlockByName("fresnelColor"),fingerColor:c.getBlockByName("fingerColor"),tipFresnel:c.getBlockByName("tipFresnelColor")};p.base.value=d.base,p.fresnel.value=d.fresnel,p.fingerColor.value=d.fingerColor,p.tipFresnel.value=d.tipFresnel,["left","right"].forEach(t=>{let i="left"==t?WebXRHandTracking._LeftHandGLB:WebXRHandTracking._RightHandGLB;if(!i)throw Error("Could not load hand model");let r=i.meshes[1];r._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,r.material=c.clone(`${t}HandShaderClone`,!0),r.isVisible=!1,l[t]=r,h||e.useRightHandedSystem||i.meshes[1].rotate(rL.RD.Y,Math.PI)}),c.dispose(),i({left:l.left,right:l.right})})}static _GenerateDefaultHandMeshRigMapping(e){let t="right"==e?"R":"L";return{[tR.WRIST]:`wrist_${t}`,[tR.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[tR.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[tR.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[tR.THUMB_TIP]:`thumb_tip_${t}`,[tR.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[tR.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[tR.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[tR.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[tR.INDEX_FINGER_TIP]:`index_tip_${t}`,[tR.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[tR.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[tR.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[tR.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[tR.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[tR.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[tR.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[tR.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[tR.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[tR.RING_FINGER_TIP]:`ring_tip_${t}`,[tR.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[tR.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[tR.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[tR.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[tR.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this.onHandAddedObservable=new rf.y$,this.onHandRemovedObservable=new rf.y$,this._attachHand=e=>{var t,i,r;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;let s=e.inputSource.handedness,n=new WebXRHand(e,this._handResources.jointMeshes[s],this._handResources.handMeshes&&this._handResources.handMeshes[s],this._handResources.rigMappings&&this._handResources.rigMappings[s],null===(t=this.options.handMeshes)||void 0===t?void 0:t.meshesUseLeftHandedCoordinates,null===(i=this.options.jointMeshes)||void 0===i?void 0:i.invisible,null===(r=this.options.jointMeshes)||void 0===r?void 0:r.scaleFactor);this._attachedHands[e.uniqueId]=n,this._trackingHands[s]=n,this.onHandAddedObservable.notifyObservers(n)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";let i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};let e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach(e=>{let t=e[0],i=e[1];t.forEach((e,t)=>{i[sR[t]]=e})}),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){var e,t,i,r;return!!super.attach()&&(this._handResources={jointMeshes:WebXRHandTracking._GenerateTrackedJointMeshes(this.options),handMeshes:(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||null,rigMappings:(null===(t=this.options.handMeshes)||void 0===t?void 0:t.customRigMappings)||null},(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)||(null===(r=this.options.handMeshes)||void 0===r?void 0:r.disableDefaultMeshes)||WebXRHandTracking._GenerateDefaultHandMeshesAsync(rS.l.LastCreatedScene,this.options).then(e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:WebXRHandTracking._GenerateDefaultHandMeshRigMapping("left"),right:WebXRHandTracking._GenerateDefaultHandMeshRigMapping("right")},null===(t=this._trackingHands.left)||void 0===t||t.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),null===(i=this._trackingHands.right)||void 0===i||i.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)}),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){var t,i;null===(t=this._trackingHands.left)||void 0===t||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),null===(i=this._trackingHands.right)||void 0===i||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;let i=this.getHandByControllerId(e);if(i){let r="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[r])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[r]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach(e=>this._detachHandById(e)),!0)}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),!this._handResources.handMeshes||(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),WebXRHandTracking._RightHandGLB=null,WebXRHandTracking._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(e=>e.dispose()),this._handResources.jointMeshes.right.forEach(e=>e.dispose()))}};WebXRHandTracking.Name=webXRFeaturesManager_WebXRFeatureName.HAND_TRACKING,WebXRHandTracking.Version=1,WebXRHandTracking.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",WebXRHandTracking.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",WebXRHandTracking.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",WebXRHandTracking.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",WebXRHandTracking._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},WebXRHandTracking._RightHandGLB=null,WebXRHandTracking._LeftHandGLB=null,WebXRFeaturesManager.AddWebXRFeature(WebXRHandTracking.Name,(e,t)=>()=>new WebXRHandTracking(e,t),WebXRHandTracking.Version,!1),(S=tA||(tA={}))[S.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",S[S.RADIAL_SIDE=1]="RADIAL_SIDE",S[S.ULNAR_SIDE=2]="ULNAR_SIDE",S[S.BELOW_WRIST=3]="BELOW_WRIST",(C=tI||(tI={}))[C.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",C[C.HAND_ROTATION=1]="HAND_ROTATION",(E=tM||(tM={}))[E.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",E[E.PALM_UP=1]="PALM_UP",E[E.GAZE_FOCUS=2]="GAZE_FOCUS",E[E.PALM_AND_GAZE=3]="PALM_AND_GAZE";let BoneIKController=class BoneIKController{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=rm.P.Zero(),this.poleTargetPosition=rm.P.Zero(),this.poleTargetLocalOffset=rm.P.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=rm._f.Identity(),this._bone1Mat=rm.y3.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=rm.P.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;let r=t.getParent();if(!r){this._notEnoughInformation=!0,rT.Y.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length){this._notEnoughInformation=!0,rT.Y.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();let s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){let e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);let t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=rm.P.Distance(t,i),this._bone1Length=rm.P.Distance(i,r)}else{e.computeWorldMatrix(!0);let t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;let i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=rm.P.Distance(i,r)}this._bone1.getRotationMatrixToRef(rL.T.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;let t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;let e=this.targetPosition,t=this.poleTargetPosition,i=BoneIKController._TmpMats[0],r=BoneIKController._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&rm.P.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);let s=BoneIKController._TmpVecs[0],n=BoneIKController._TmpVecs[1],a=BoneIKController._TmpVecs[2],o=BoneIKController._TmpVecs[3],l=BoneIKController._TmpVecs[4],h=BoneIKController._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,o),o.normalize(),rm.P.CrossToRef(o,l,n),n.normalize(),rm.P.CrossToRef(o,n,a),a.normalize(),rm.y3.FromXYZAxesToRef(a,o,n,i);let u=this._bone1Length,c=this._bone2Length,d=rm.P.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let p=(c*c+d*d-u*u)/(2*c*d),_=(d*d+u*u-c*c)/(2*d*u);p>1&&(p=1),_>1&&(_=1),p<-1&&(p=-1),_<-1&&(_=-1);let f=Math.acos(p),m=Math.acos(_),g=-f-m;if(this._rightHandedSystem)rm.y3.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),rm.y3.RotationAxisToRef(this._bendAxis,m,r),r.multiplyToRef(i,i);else{let e=BoneIKController._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,rm.y3.RotationAxisToRef(e,-m,r),r.multiplyToRef(i,i)}this.poleAngle&&(rm.y3.RotationAxisToRef(o,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||rm._f.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),rm._f.FromRotationMatrixToRef(i,h),rm._f.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),g=this._bone2Ang*(1-this.slerpAmount)+g*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,rL.T.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,rL.T.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,g,rL.T.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=g}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new rm._f),e.getRotationQuaternionToRef(rL.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}};BoneIKController._TmpVecs=[rm.P.Zero(),rm.P.Zero(),rm.P.Zero(),rm.P.Zero(),rm.P.Zero(),rm.P.Zero()],BoneIKController._TmpQuat=rm._f.Identity(),BoneIKController._TmpMats=[rm.y3.Identity(),rm.y3.Identity()];let BoneLookController=class BoneLookController{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=rm.P.Up(),this.upAxisSpace=rL.T.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=rm._f.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=rm.P.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=rL.RD.Y,t=rL.RD.X;null!=r.yawAxis&&(e=r.yawAxis.clone()).normalize(),null!=r.pitchAxis&&(t=r.pitchAxis.clone()).normalize();let i=rm.P.Cross(t,e);this._transformYawPitch=rm.y3.Identity(),rm.y3.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=rL.T.BONE||(this.upAxisSpace=rL.T.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}let e=this.bone,t=BoneLookController._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target,r=BoneLookController._TmpMats[0],s=BoneLookController._TmpMats[1],n=this.mesh,a=e.getParent(),o=BoneLookController._TmpVecs[1];o.copyFrom(this.upAxis),this.upAxisSpace==rL.T.BONE&&a?(this._transformYawPitch&&rm.P.TransformCoordinatesToRef(o,this._transformYawPitchInv,o),a.getDirectionToRef(o,this.mesh,o)):this.upAxisSpace==rL.T.LOCAL&&(n.getDirectionToRef(o,o),(1!=n.scaling.x||1!=n.scaling.y||1!=n.scaling.z)&&o.normalize());let l=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(l=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),l||h){let e=BoneLookController._TmpMats[2],r=BoneLookController._TmpMats[3];if(this.upAxisSpace==rL.T.BONE&&1==o.y&&a)a.getRotationMatrixToRef(rL.T.WORLD,this.mesh,e);else if(this.upAxisSpace!=rL.T.LOCAL||1!=o.y||a){let t=BoneLookController._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&rm.P.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),a?a.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);let i=rm.P.Cross(o,t);i.normalize(),t=rm.P.Cross(i,o),rm.y3.FromXYZAxesToRef(i,o,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(r);let s=null;if(h){let n=BoneLookController._TmpVecs[3];i.subtractToRef(t,n),rm.P.TransformCoordinatesToRef(n,r,n),s=Math.sqrt(n.x*n.x+n.z*n.z);let a=Math.atan2(n.y,s),o=a;a>this._maxPitch?(n.y=this._maxPitchTan*s,o=this._maxPitch):athis._maxYaw||oMath.PI?this._isAngleBetween(a,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(a,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,l=this._minYaw):o>this._maxYaw?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):oMath.PI){let e=BoneLookController._TmpVecs[8];e.copyFrom(rL.RD.Z),this._transformYawPitch&&rm.P.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);let t=BoneLookController._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),rm.P.TransformCoordinatesToRef(e,t,e),rm.P.TransformCoordinatesToRef(e,r,e);let i=Math.atan2(e.x,e.z),o=this._getAngleBetween(i,a),h=this._getAngleBetween(i,this._midYawConstraint);if(o>h){null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z));let e=this._getAngleBetween(i,this._maxYaw),t=this._getAngleBetween(i,this._minYaw);l=tMath.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI;let i=0;return(i=e<(t=t<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,t<(i=i<0?i+2*Math.PI:i)){if(e>t&&ei&&e0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):((!this._transformMatrices||this._isDirty)&&this.prepare(),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(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){for(let e of this.bones)if(e._linkedTransformNode){let 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(let e of this._meshesWithPoseMatrix){let t=e.getPoseMatrix(),i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){for(let i of(this._synchronizedWithMesh=e,this.bones))if(!i.getParent()){let e=i.getBindMatrix();e.multiplyToRef(t,rm.jp.Matrix[1]),i._updateAbsoluteBindMatrices(rm.jp.Matrix[1])}if(this.isUsingTextureForMatrices){let t=(this.bones.length+1)*4;e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=rawTexture_RawTexture.CreateRGBATexture(e._bonesTransformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))}}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=rawTexture_RawTexture.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),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{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){let 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(){var e;let t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(n.animation=r.animations[0].serialize()),t.ranges=[],this._ranges){let i=this._ranges[e];if(!i)continue;let r={};r.name=e,r.from=i.from,r.to=i.to,t.ranges.push(r)}}return t}static Parse(e,t){let i;let r=new skeleton_Skeleton(e.name,e.id,t);for(e.dimensionsAtRest&&(r.dimensionsAtRest=rm.P.FromArray(e.dimensionsAtRest)),r.needInitialSkinMatrix=e.needInitialSkinMatrix,i=0;i-1&&(n=r.bones[t.parentBoneIndex]);let a=t.rest?rm.y3.FromArray(t.rest):null,o=new Bone(t.name,r,n,rm.y3.FromArray(t.matrix),a,null,s);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(animation_Animation.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(r._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(i=0;i0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}};var sI=i(9185);let StorageBuffer=class StorageBuffer{constructor(e,t,i=3,r){this._engine=e,this._label=r,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i){return this._engine.readFromStorageBuffer(this._buffer,e,t,i)}dispose(){let e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}};let sM=(()=>{let e=new Uint8Array(4),t=new Uint32Array(e.buffer);return!!((t[0]=1)&e[0])})();Object.defineProperty(rz.o.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(rz.o.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(rz.o.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),rz.o.prototype._rebuild=function(){var e,t;null===(e=this._buffer)||void 0===e||e._rebuild(),null===(t=this._alignedBuffer)||void 0===t||t._rebuild()},rz.o.prototype.dispose=function(){var e;this._ownsBuffer&&this._buffer.dispose(),null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},rz.o.prototype._alignBuffer=function(){var e,t;let i,r;let s=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideMultiple4Bytes||this.byteStride%4==0||!s)return;let n=rz.o.GetTypeByteLength(this.type),a=this.byteStride+3&-4,o=a/n,l=this.totalVertices,h=l*a,u=h/n;if(Array.isArray(s)){let e=new Float32Array(s);i=new DataView(e.buffer,e.byteOffset,e.byteLength)}else i=s instanceof ArrayBuffer?new DataView(s,0,s.byteLength):new DataView(s.buffer,s.byteOffset,s.byteLength);r=this.type===rz.o.BYTE?new Int8Array(u):this.type===rz.o.UNSIGNED_BYTE?new Uint8Array(u):this.type===rz.o.SHORT?new Int16Array(u):this.type===rz.o.UNSIGNED_SHORT?new Uint16Array(u):this.type===rz.o.INT?new Int32Array(u):this.type===rz.o.UNSIGNED_INT?new Uint32Array(u):new Float32Array(u);let c=this.getSize(),d=this.byteOffset;for(let e=0;e{if(t.type!==r8.kD.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===sD.G.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,r8.kD.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"}};(0,rH.gn)([(0,rb.qC)()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionX",void 0),(0,rH.gn)([(0,rb.qC)()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionY",void 0),(0,rH.gn)([(0,rb.qC)()],BaseCameraMouseWheelInput.prototype,"wheelPrecisionZ",void 0);let BaseCameraPointersInput=class BaseCameraPointersInput{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=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=>{var a,o;let l=n.event,h="touch"===l.pointerType;if(n.type!==r8.kD.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;let u=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else if(n.type!==r8.kD.POINTERDOWN&&h&&(null===(a=this._pointA)||void 0===a?void 0:a.pointerId)!==l.pointerId&&(null===(o=this._pointB)||void 0===o?void 0:o.pointerId)!==l.pointerId)return;else if(n.type===r8.kD.POINTERDOWN&&(-1===this._currentActiveButton||h)){try{null==u||u.setPointerCapture(l.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else{if(null!==this._pointB)return;this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType}}-1!==this._currentActiveButton||h||(this._currentActiveButton=l.button),this.onButtonDown(l),!e&&(l.preventDefault(),i&&i.focus())}else if(n.type===r8.kD.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(n.type===r8.kD.POINTERUP&&(this._currentActiveButton===l.button||h)){try{null==u||u.releasePointerCapture(l.pointerId)}catch(e){}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(n.type===r8.kD.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&null===this._pointB){let e=l.clientX-this._pointA.x,t=l.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){let e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;let t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,o={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,r,a,s,o),s=o,r=a}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,r8.kD.POINTERDOWN|r8.kD.POINTERUP|r8.kD.POINTERMOVE|r8.kD.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let n=this.camera.getScene().getEngine().getHostWindow();n&&rW.w1.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&rW.w1.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let 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,i){}onMultiTouch(e,t,i,r,s,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}};(0,rH.gn)([(0,rb.qC)()],BaseCameraPointersInput.prototype,"buttons",void 0);var sO={};let CameraInputsManager=class CameraInputsManager{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){rT.Y.Warn("camera input of type "+t+" already exists on camera");return}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(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement)for(let t in e=!rj.V.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e,this.attached)this.attached[t].attachControl(e)}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){for(let e in this.checkInputs=()=>{},this.attached){let 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){let t={};for(let e in this.attached){let i=this.attached[e],r=rb.p4.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t)for(let e in this.clear(),t){let i=sO[e];if(i){let r=t[e],s=rb.p4.Parse(()=>new i,r,null);this.add(s)}}else for(let t in this.attached){let i=sO[this.attached[t].getClassName()];if(i){let r=rb.p4.Parse(()=>new i,e,null);this.remove(this.attached[t]),this.add(r)}}}};let Gamepad=class Gamepad{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=1,n=2,a=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=Gamepad.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,this._rightStickAxisX=n,this._rightStickAxisY=a,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){this._onleftstickchanged&&(this._leftStick.x!==e.x||this._leftStick.y!==e.y)&&this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){this._onrightstickchanged&&(this._rightStick.x!==e.x||this._rightStick.y!==e.y)&&this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}};Gamepad.GAMEPAD=0,Gamepad.GENERIC=1,Gamepad.XBOX=2,Gamepad.POSE_ENABLED=3,Gamepad.DUALSHOCK=4;let GenericPad=class GenericPad extends Gamepad{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new rf.y$,this.onButtonUpObservable=new rf.y$,this.type=Gamepad.GENERIC,this._buttons=Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type===Gamepad.POSE_ENABLED||this.gamepad&&e.type!==Gamepad.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.XBOX)}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){let e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){let i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){let i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}let i=this.gamepad.leftStick;if(i&&0!=i.y){let e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}};(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraGamepadInput.prototype,"gamepadRotationSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraGamepadInput.prototype,"gamepadMoveSensibility",void 0),sO.ArcRotateCameraGamepadInput=ArcRotateCameraGamepadInput;var sN=i(7534);let ArcRotateCameraKeyboardMoveInput=class ArcRotateCameraKeyboardMoveInput{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=[]}attachControl(e){e=rW.w1.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=>{let i=t.event;if(!i.metaKey){if(t.type===sN.OG.KEYDOWN){if(this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);-1===t&&this._keys.push(i.keyCode),i.preventDefault&&!e&&i.preventDefault()}}else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&!e&&i.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){let e=this.camera;for(let t=0;t0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==r8.kD.POINTERWHEEL)return;let i=t.event,r=0,s=i.deltaMode===sD.G.DOM_DELTA_LINE?40:1,n=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if((r=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius))>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=rE.R.Clamp(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else r=n/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,r8.kD.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;let e=this.camera,t=0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset;t&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=r2.J.FromPositionAndNormal(e.target,t)}_getPosition(){var e;let t=this.camera,i=t.getScene(),r=i.createPickingRay(i.pointerX,i.pointerY,rm.y3.Identity(),t,!1);(0!==t.targetScreenOffset.x||0!==t.targetScreenOffset.y)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=rm.P.TransformNormal(this._viewOffset,t._cameraTransformMatrix),r.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=null!==(e=r.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),r.origin.addInPlace(r.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;let r=this.camera,s=1-r.inertia;if(r.lowerRadiusLimit){let i=null!==(t=r.lowerRadiusLimit)&&void 0!==t?t:0;r.radius-(r.inertialRadiusOffset+e)/st&&(e=(r.radius-t)*s-r.inertialRadiusOffset)}let n=e/s,a=n/r.radius,o=this._getPosition(),l=rm.jp.Vector3[6];o.subtractToRef(r.target,l),l.scaleInPlace(a),l.scaleInPlace(s),this._inertialPanning.addInPlace(l),r.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,n)):this.multiTouchPanning?this._computeMultiTouchPanning(s,n):this.pinchZoom&&this._computePinchZoom(i,r))}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}};ArcRotateCameraPointersInput.MinimumRadiusForPinch=.001,(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"buttons",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"angularSensibilityX",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"angularSensibilityY",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"pinchPrecision",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"pinchDeltaPercentage",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"useNaturalPinchZoom",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"pinchZoom",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"panningSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"multiTouchPanning",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCameraPointersInput.prototype,"multiTouchPanAndZoom",void 0),sO.ArcRotateCameraPointersInput=ArcRotateCameraPointersInput;let ArcRotateCameraInputsManager=class ArcRotateCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addMouseWheel(){return this.add(new ArcRotateCameraMouseWheelInput),this}addPointers(){return this.add(new ArcRotateCameraPointersInput),this}addKeyboard(){return this.add(new ArcRotateCameraKeyboardMoveInput),this}};ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation=function(){return this.add(new ArcRotateCameraVRDeviceOrientationInput),this};let ArcRotateCameraVRDeviceOrientationInput=class ArcRotateCameraVRDeviceOrientationInput{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);let t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):rW.w1.Warn("Permission not granted.")}).catch(e=>{rW.w1.Error(e)}):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}};sO.ArcRotateCameraVRDeviceOrientationInput=ArcRotateCameraVRDeviceOrientationInput;let FlyCameraKeyboardInput=class FlyCameraKeyboardInput{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=[]}attachControl(e){e=rW.w1.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=>{let i=t.event;if(t.type===sN.OG.KEYDOWN){if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);-1===t&&this._keys.push(i.keyCode),e||i.preventDefault()}}else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t{this._pointerInput(e)},r8.kD.POINTERDOWN|r8.kD.POINTERUP|r8.kD.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add(()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)})}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){let t=e.event,i=this.camera,r=i.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType||e.type!==r8.kD.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;let s=t.target;if(e.type===r8.kD.POINTERDOWN){try{null==s||s.setPointerCapture(t.pointerId)}catch(e){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),r.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===r8.kD.POINTERUP){try{null==s||s.releasePointerCapture(t.pointerId)}catch(e){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===r8.kD.POINTERMOVE){if(!this._previousPosition){r.isPointerLock&&this._onMouseMove(e.event);return}let i=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(i,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){let t=this.camera,i=t.getEngine();if(!i.isPointerLock)return;let r=e.movementX,s=e.movementY;this._rotateCamera(r,s),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){let i;let r=this.camera,s=r._calculateHandednessMultiplier();e*=s;let n=e/this.angularSensibility,a=t/this.angularSensibility,o=rm._f.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z);if(this.buttonsPitch.some(e=>e===this.activeButton)&&(i=rm._f.RotationAxis(rL.RD.X,a),o.multiplyInPlace(i)),this.buttonsYaw.some(e=>e===this.activeButton)){i=rm._f.RotationAxis(rL.RD.Y,n),o.multiplyInPlace(i);let e=r.bankedTurnLimit+r._trackRoll;if(r.bankedTurn&&-ee===this.activeButton)&&(i=rm._f.RotationAxis(rL.RD.Z,-n),r._trackRoll-=n,o.multiplyInPlace(i)),o.toEulerAnglesToRef(r.rotation)}};(0,rH.gn)([(0,rb.qC)()],FlyCameraMouseInput.prototype,"buttons",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCameraMouseInput.prototype,"angularSensibility",void 0),sO.FlyCameraMouseInput=FlyCameraMouseInput;let FollowCameraKeyboardMoveInput=class FollowCameraKeyboardMoveInput{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=[]}attachControl(e){e=rW.w1.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=>{let i=t.event;if(!i.metaKey){if(t.type===sN.OG.KEYDOWN){if(this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);-1===t&&this._keys.push(i.keyCode),i.preventDefault&&!e&&i.preventDefault()}}else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&!e&&i.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(){this._onKeyboardObserver&&this._keys.forEach(e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)})}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}};(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetIncr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetDecr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierAlt",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysHeightOffsetModifierShift",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetIncr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetDecr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierAlt",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRotationOffsetModifierShift",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusIncr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusDecr",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierAlt",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierCtrl",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"keysRadiusModifierShift",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"heightSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"rotationSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraKeyboardMoveInput.prototype,"radiusSensibility",void 0),sO.FollowCameraKeyboardMoveInput=FollowCameraKeyboardMoveInput;let FollowCameraMouseWheelInput=class FollowCameraMouseWheelInput{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==r8.kD.POINTERWHEEL)return;let i=t.event,r=0,s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(console.assert(this.axisControlRadius+this.axisControlHeight+this.axisControlRotation<=1,"wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,r8.kD.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}};(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"axisControlRadius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"axisControlHeight",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"axisControlRotation",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"wheelPrecision",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraMouseWheelInput.prototype,"wheelDeltaPercentage",void 0),sO.FollowCameraMouseWheelInput=FollowCameraMouseWheelInput;let FollowCameraPointersInput=class FollowCameraPointersInput extends BaseCameraPointersInput{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,n){if(0===i&&null===s||0===r&&null===n)return;let a=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;let e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";console.assert(this.axisXControlRotation+this.axisXControlHeight+this.axisXControlRadius<=1,e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),console.assert(this.axisYControlRotation+this.axisYControlHeight+this.axisYControlRadius<=1,e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),console.assert(this.axisPinchControlRotation+this.axisPinchControlHeight+this.axisPinchControlRadius<=1,e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}};(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"angularSensibilityX",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"angularSensibilityY",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"pinchPrecision",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"pinchDeltaPercentage",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisXControlRadius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisXControlHeight",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisXControlRotation",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisYControlRadius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisYControlHeight",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisYControlRotation",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisPinchControlRadius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisPinchControlHeight",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCameraPointersInput.prototype,"axisPinchControlRotation",void 0),sO.FollowCameraPointersInput=FollowCameraPointersInput;let FreeCameraKeyboardMoveInput=class FreeCameraKeyboardMoveInput{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=[]}attachControl(e){e=rW.w1.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=>{let i=t.event;if(!i.metaKey){if(t.type===sN.OG.KEYDOWN){if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);-1===t&&this._keys.push(i.keyCode),e||i.preventDefault()}}else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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){let e=this.camera;for(let t=0;t{let s=r.event,n="touch"===s.pointerType;if(!this.touchEnabled&&n||r.type!==r8.kD.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;let a=s.target;if(r.type===r8.kD.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==a||a.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},!e&&(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===r8.kD.POINTERUP){if(n&&this._activePointerId!==s.pointerId||!n&&this._currentActiveButton!==s.button)return;try{null==a||a.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===r8.kD.POINTERMOVE&&(this._activePointerId===s.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let t=this.camera._calculateHandednessMultiplier(),i=(s.clientX-this._previousPosition.x)*t,r=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=r/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:r}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;let r=this.camera._calculateHandednessMultiplier(),s=i.movementX*r;this.camera.cameraRotation.y+=s/this.angularSensibility;let n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,r8.kD.POINTERDOWN|r8.kD.POINTERUP|r8.kD.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.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"}};(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseInput.prototype,"buttons",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseInput.prototype,"angularSensibility",void 0),sO.FreeCameraMouseInput=FreeCameraMouseInput,(b=tD||(tD={}))[b.MoveRelative=0]="MoveRelative",b[b.RotateRelative=1]="RotateRelative",b[b.MoveScene=2]="MoveScene";let FreeCameraMouseWheelInput=class FreeCameraMouseWheelInput extends BaseCameraMouseWheelInput{constructor(){super(...arguments),this._moveRelative=rm.P.Zero(),this._rotateRelative=rm.P.Zero(),this._moveScene=rm.P.Zero(),this._wheelXAction=tD.MoveRelative,this._wheelXActionCoordinate=rL.c7.X,this._wheelYAction=tD.MoveRelative,this._wheelYActionCoordinate=rL.c7.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){(null!==e||this._wheelXAction===tD.MoveRelative)&&(this._wheelXAction=tD.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==tD.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){(null!==e||this._wheelYAction===tD.MoveRelative)&&(this._wheelYAction=tD.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==tD.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){(null!==e||this._wheelZAction===tD.MoveRelative)&&(this._wheelZAction=tD.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==tD.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){(null!==e||this._wheelXAction===tD.RotateRelative)&&(this._wheelXAction=tD.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==tD.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){(null!==e||this._wheelYAction===tD.RotateRelative)&&(this._wheelYAction=tD.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==tD.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){(null!==e||this._wheelZAction===tD.RotateRelative)&&(this._wheelZAction=tD.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==tD.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){(null!==e||this._wheelXAction===tD.MoveScene)&&(this._wheelXAction=tD.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==tD.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){(null!==e||this._wheelYAction===tD.MoveScene)&&(this._wheelYAction=tD.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==tD.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){(null!==e||this._wheelZAction===tD.MoveScene)&&(this._wheelZAction=tD.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==tD.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);let e=rm.y3.Zero();this.camera.getViewMatrix().invertToRef(e);let t=rm.P.Zero();rm.P.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,i){if(0===e||null===t||null===i)return;let r=null;switch(t){case tD.MoveRelative:r=this._moveRelative;break;case tD.RotateRelative:r=this._rotateRelative;break;case tD.MoveScene:r=this._moveScene}switch(i){case rL.c7.X:r.set(e,0,0);break;case rL.c7.Y:r.set(0,e,0);break;case rL.c7.Z:r.set(0,0,e)}}};(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelXMoveRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelYMoveRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelZMoveRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelXRotateRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelYRotateRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelZRotateRelative",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelXMoveScene",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelYMoveScene",null),(0,rH.gn)([(0,rb.qC)()],FreeCameraMouseWheelInput.prototype,"wheelZMoveScene",null),sO.FreeCameraMouseWheelInput=FreeCameraMouseWheelInput;let FreeCameraTouchInput=class FreeCameraTouchInput{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=[],this._isSafari=rW.w1.IsSafari()}attachControl(e){e=rW.w1.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s){if(i.type===r8.kD.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===r8.kD.POINTERUP){e||r.preventDefault();let i=this._pointerPressed.indexOf(r.pointerId);if(-1===i||(this._pointerPressed.splice(i,1),0!=i))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===r8.kD.POINTERMOVE){if(e||r.preventDefault(),!t)return;let i=this._pointerPressed.indexOf(r.pointerId);if(0!=i)return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,r8.kD.POINTERDOWN|r8.kD.POINTERUP|r8.kD.POINTERMOVE),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){let e=this.camera.getEngine(),t=e.getInputElement();t&&t.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||0===this._offsetX&&0===this._offsetY)return;let e=this.camera,t=e._calculateHandednessMultiplier();e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility;let i=this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1;if(i)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{let t=e._computeLocalCameraSpeed(),i=new rm.P(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);rm.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(rm.P.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}};(0,rH.gn)([(0,rb.qC)()],FreeCameraTouchInput.prototype,"touchAngularSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraTouchInput.prototype,"touchMoveSensibility",void 0),sO.FreeCameraTouchInput=FreeCameraTouchInput;let FreeCameraInputsManager=class FreeCameraInputsManager extends CameraInputsManager{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new FreeCameraKeyboardMoveInput),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new FreeCameraMouseInput(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new FreeCameraMouseWheelInput,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new FreeCameraTouchInput),this}clear(){super.clear(),this._mouseInput=null}};FreeCameraInputsManager.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new FreeCameraDeviceOrientationInput,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};let FreeCameraDeviceOrientationInput=class FreeCameraDeviceOrientationInput{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1,eventHandler=()=>{window.removeEventListener("deviceorientation",eventHandler),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",eventHandler),i("WaitForOrientationChangeAsync timed out"))},e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"==e?window.addEventListener("deviceorientation",eventHandler):rW.w1.Warn("Permission not granted.")}).catch(e=>{rW.w1.Error(e)}):window.addEventListener("deviceorientation",eventHandler)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new rm._f,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new rf.y$,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-rW.w1.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?rW.w1.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?rW.w1.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?rW.w1.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new rm._f(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new rm._f),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){let e=this.camera.getScene().getEngine().getHostWindow();if(e){let eventHandler=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e?eventHandler():rW.w1.Warn("Permission not granted.")}).catch(e=>{rW.w1.Error(e)}):eventHandler()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(rm._f.RotationYawPitchRollToRef(rW.w1.ToRadians(this._alpha),rW.w1.ToRadians(this._beta),-rW.w1.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}};sO.FreeCameraDeviceOrientationInput=FreeCameraDeviceOrientationInput;let FreeCameraGamepadInput=class FreeCameraGamepadInput{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=rm.y3.Identity(),this._deltaTransform=rm.P.Zero(),this._vector3=rm.P.Zero(),this._vector2=rm.FM.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===Gamepad.POSE_ENABLED||this.gamepad&&e.type!==Gamepad.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(Gamepad.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){let e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):rm.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);let r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),rm.P.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}};(0,rH.gn)([(0,rb.qC)()],FreeCameraGamepadInput.prototype,"gamepadAngularSensibility",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCameraGamepadInput.prototype,"gamepadMoveSensibility",void 0),sO.FreeCameraGamepadInput=FreeCameraGamepadInput;var sF=i(1186);(y=tO||(tO={}))[y.X=0]="X",y[y.Y=1]="Y",y[y.Z=2]="Z";let VirtualJoystick=class VirtualJoystick{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;let i=Object.assign(Object.assign({},VirtualJoystick._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,VirtualJoystick._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=tO.X,this._axisTargetedByUpAndDown=tO.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new sF.x,this.deltaPosition=rm.P.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{VirtualJoystick._VJCanvasWidth=window.innerWidth,VirtualJoystick._VJCanvasHeight=window.innerHeight,VirtualJoystick.Canvas&&(VirtualJoystick.Canvas.width=VirtualJoystick._VJCanvasWidth,VirtualJoystick.Canvas.height=VirtualJoystick._VJCanvasHeight),VirtualJoystick._HalfWidth=VirtualJoystick._VJCanvasWidth/2},!VirtualJoystick.Canvas){window.addEventListener("resize",this._onResize,!1),VirtualJoystick.Canvas=document.createElement("canvas"),VirtualJoystick._VJCanvasWidth=window.innerWidth,VirtualJoystick._VJCanvasHeight=window.innerHeight,VirtualJoystick.Canvas.width=window.innerWidth,VirtualJoystick.Canvas.height=window.innerHeight,VirtualJoystick.Canvas.style.width="100%",VirtualJoystick.Canvas.style.height="100%",VirtualJoystick.Canvas.style.position="absolute",VirtualJoystick.Canvas.style.backgroundColor="transparent",VirtualJoystick.Canvas.style.top="0px",VirtualJoystick.Canvas.style.left="0px",VirtualJoystick.Canvas.style.zIndex="5",VirtualJoystick.Canvas.style.touchAction="none",VirtualJoystick.Canvas.setAttribute("touch-action","none");let e=VirtualJoystick.Canvas.getContext("2d");if(!e)throw Error("Unable to create canvas for virtual joystick");VirtualJoystick._VJCanvasContext=e,VirtualJoystick._VJCanvasContext.strokeStyle="#ffffff",VirtualJoystick._VJCanvasContext.lineWidth=2,document.body.appendChild(VirtualJoystick.Canvas)}VirtualJoystick._HalfWidth=VirtualJoystick.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&VirtualJoystick._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new rm.FM(0,0),this._joystickPreviousPointerPos=new rm.FM(0,0),this._joystickPointerStartPos=new rm.FM(0,0),this._deltaJoystickVector=new rm.FM(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},VirtualJoystick.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),VirtualJoystick.Canvas.addEventListener("contextmenu",e=>{e.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){e.preventDefault(),(!0===this._leftJoystick?e.clientXVirtualJoystick._HalfWidth)&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):VirtualJoystick._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){let t=new rm.FM(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){let t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){let e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?VirtualJoystick._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.lineWidth=2,VirtualJoystick._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath(),VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.lineWidth=6,VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?VirtualJoystick._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle=this._joystickColor,VirtualJoystick._VJCanvasContext.lineWidth=2,VirtualJoystick._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(VirtualJoystick._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.fillStyle="white",VirtualJoystick._VJCanvasContext.beginPath(),VirtualJoystick._VJCanvasContext.strokeStyle="red",VirtualJoystick._VJCanvasContext.lineWidth=6,VirtualJoystick._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),VirtualJoystick._VJCanvasContext.stroke(),VirtualJoystick._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){VirtualJoystick.Canvas&&(VirtualJoystick.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),VirtualJoystick.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(VirtualJoystick.Canvas),VirtualJoystick.Canvas=null),this._released=!0}};VirtualJoystick._GlobalJoystickIndex=0,VirtualJoystick._AlwaysVisibleSticks=0,FreeCameraInputsManager.prototype.addVirtualJoystick=function(){return this.add(new FreeCameraVirtualJoystickInput),this};let FreeCameraVirtualJoystickInput=class FreeCameraVirtualJoystickInput{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){let e=this.camera,t=50*e._computeLocalCameraSpeed(),i=rm.y3.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=rm.P.TransformCoordinates(new rm.P(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new VirtualJoystick(!0),this._leftjoystick.setAxisForUpDown(tO.Z),this._leftjoystick.setAxisForLeftRight(tO.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new VirtualJoystick(!1),this._rightjoystick.setAxisForUpDown(tO.X),this._rightjoystick.setAxisForLeftRight(tO.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}};sO.FreeCameraVirtualJoystickInput=FreeCameraVirtualJoystickInput;let targetCamera_TargetCamera=class targetCamera_TargetCamera extends rj.V{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=rm.P.Zero(),this._tmpTargetVector=rm.P.Zero(),this.cameraDirection=new rm.P(0,0,0),this.cameraRotation=new rm.FM(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new rm._f,this.rotation=new rm.P(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=rm.P.Zero(),this._initialFocalDistance=1,this._viewMatrix=rm.y3.Zero(),this._camMatrix=rm.y3.Zero(),this._cameraTransformMatrix=rm.y3.Zero(),this._cameraRotationMatrix=rm.y3.Zero(),this._referencePoint=new rm.P(0,0,1),this._transformedReferencePoint=rm.P.Zero(),this._deferredPositionUpdate=new rm.P,this._deferredRotationQuaternionUpdate=new rm._f,this._deferredRotationUpdate=new rm.P,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=rm.P.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();let 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){let e=this.lockedTarget,t=e.computeWorldMatrix();t.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 rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new rm._f(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let 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;let 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(){let 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+=rw.kn),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),rm.y3.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);let 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&&rm._f.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){this.parent.getWorldMatrix().invertToRef(rm.jp.Matrix[0]),rm.P.TransformNormalToRef(this.cameraDirection,rm.jp.Matrix[0],rm.jp.Vector3[0]),this._deferredPositionUpdate.addInPlace(rm.jp.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=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(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint&&(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion)){let e=this._deferredRotationUpdate.lengthSquared();e&&(rm._f.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._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>rq.D.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new FreeCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=rW.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new rm.P(0,0,0),this.cameraRotation=new rm.FM(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?rm.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=rm.P.Zero(),this._transformedDirection=rm.P.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"}};(0,rH.gn)([(0,rb.hd)()],FreeCamera.prototype,"ellipsoid",void 0),(0,rH.gn)([(0,rb.hd)()],FreeCamera.prototype,"ellipsoidOffset",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCamera.prototype,"checkCollisions",void 0),(0,rH.gn)([(0,rb.qC)()],FreeCamera.prototype,"applyGravity",void 0),ry.N.AddNodeConstructor("TouchCamera",(e,t)=>()=>new TouchCamera(e,rm.P.Zero(),t));let TouchCamera=class TouchCamera extends FreeCamera{get touchAngularSensibility(){let e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){let e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){let e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}};ry.N.AddNodeConstructor("ArcRotateCamera",(e,t)=>()=>new ArcRotateCamera(e,0,0,1,rm.P.Zero(),t));let ArcRotateCamera=class ArcRotateCamera extends targetCamera_TargetCamera{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 rm.y3,this._upToYMatrix=new rm.y3,this._upVector=rm.P.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){rm.y3.RotationAlignToRef(rm.P.UpReadOnly,this._upVector,this._yToUpMatrix),rm.y3.RotationAlignToRef(this._upVector,rm.P.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let 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 BouncingBehavior,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 FramingBehavior,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 AutoRotationBehavior,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,n,a=!0){super(e,rm.P.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=rm.P.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=rm.FM.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new rm.y3,this.panningAxis=new rm.P(1,1,0),this._transformedDirection=new rm.P,this.mapPanning=!1,this.onMeshTargetChangedObservable=new rf.y$,this.checkCollisions=!1,this.collisionRadius=new rm.P(.5,.5,.5),this._previousPosition=rm.P.Zero(),this._collisionVelocity=rm.P.Zero(),this._newPosition=rm.P.Zero(),this._computationVector=rm.P.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);let r=Math.cos(this.alpha),s=Math.sin(this.alpha),n=Math.cos(this.beta),a=Math.sin(this.beta);0===a&&(a=1e-4);let o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*a,this.radius*n,this.radius*s*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=(l=l.clone()).negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=rm.P.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new ArcRotateCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new rm.P(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=rm.FM.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){let e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}let 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!!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,i=!0,r=2){let s=arguments;t=rW.w1.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[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(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){let e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier(),i=this.inertialAlphaOffset*t;this.beta<=0&&(i*=-1),this.alpha+=i*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)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.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)&&rm.P.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);let 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);let 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,i=!1,r=!1){var s;if(r=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:r,e.getBoundingInfo)t?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{let t=this._getTargetPosition();if(t&&!i&&t.equals(e))return;this._targetHost=null,this._target=e,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&rm.P.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let 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&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=rV.Kj.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){let t=e||this.getScene().meshes;i=rV.Kj.MinMax(t),r=rm.P.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=rV.Kj.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rj.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case rj.V.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}let r=new ArcRotateCamera(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case rj.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case rj.V.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=rm.P.Distance(e,t),s=this.getScene().getEngine(),n=s.getAspectRatio(this),a=Math.tan(this.fov/2),o=a*n,l=.5*r*i;return Math.max(l*Math.sqrt(1+1/(o*o)),l*Math.sqrt(1+1/(a*a)))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}};(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"alpha",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"beta",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"radius",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,rH.gn)([(0,rb.hd)("target")],ArcRotateCamera.prototype,"_target",void 0),(0,rH.gn)([(0,rb.RR)("targetHost")],ArcRotateCamera.prototype,"_targetHost",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialAlphaOffset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialBetaOffset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialRadiusOffset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"lowerAlphaLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"upperAlphaLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"lowerBetaLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"upperBetaLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"lowerRadiusLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"upperRadiusLimit",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialPanningX",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"inertialPanningY",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"pinchToPanMaxDistance",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"panningDistanceLimit",void 0),(0,rH.gn)([(0,rb.hd)()],ArcRotateCamera.prototype,"panningOriginTarget",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"panningInertia",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"zoomToMouseLocation",null),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"zoomOnFactor",void 0),(0,rH.gn)([(0,rb.QC)()],ArcRotateCamera.prototype,"targetScreenOffset",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"allowUpsideDown",void 0),(0,rH.gn)([(0,rb.qC)()],ArcRotateCamera.prototype,"useInputToRestoreState",void 0),ry.N.AddNodeConstructor("DeviceOrientationCamera",(e,t)=>()=>new DeviceOrientationCamera(e,rm.P.Zero(),t));let DeviceOrientationCamera=class DeviceOrientationCamera extends FreeCamera{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new rm._f,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new rm._f,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add(e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new rm._f),rm._f.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))}))})}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=rL.RD.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new rm._f),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}};let FlyCameraInputsManager=class FlyCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addKeyboard(){return this.add(new FlyCameraKeyboardInput),this}addMouse(){return this.add(new FlyCameraMouseInput),this}};let FlyCamera=class FlyCamera extends targetCamera_TargetCamera{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){let e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){let t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){let e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){let t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new rm.P(1,1,1),this.ellipsoidOffset=new rm.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=rm.P.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=rm.P.Zero(),this._diffPosition=rm.P.Zero(),this._newPosition=rm.P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>rq.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new FlyCameraInputsManager(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=rW.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new rm.P(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?rm.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=rm.P.Zero(),this._transformedDirection=rm.P.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()}restoreRoll(e){let t=this._trackRoll,i=this.rotation.z,r=t-i;Math.abs(r)>=.001&&(this.rotation.z+=r/e,.001>=Math.abs(t-this.rotation.z)&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}};(0,rH.gn)([(0,rb.hd)()],FlyCamera.prototype,"ellipsoid",void 0),(0,rH.gn)([(0,rb.hd)()],FlyCamera.prototype,"ellipsoidOffset",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCamera.prototype,"checkCollisions",void 0),(0,rH.gn)([(0,rb.qC)()],FlyCamera.prototype,"applyGravity",void 0);let FollowCameraInputsManager=class FollowCameraInputsManager extends CameraInputsManager{constructor(e){super(e)}addKeyboard(){return this.add(new FollowCameraKeyboardMoveInput),this}addMouseWheel(){return this.add(new FollowCameraMouseWheelInput),this}addPointers(){return this.add(new FollowCameraPointersInput),this}addVRDeviceOrientation(){return console.warn("DeviceOrientation support not yet implemented for FollowCamera."),this}};ry.N.AddNodeConstructor("FollowCamera",(e,t)=>()=>new FollowCamera(e,rm.P.Zero(),t)),ry.N.AddNodeConstructor("ArcFollowCamera",(e,t)=>()=>new ArcFollowCamera(e,0,0,1,null,t));let FollowCamera=class FollowCamera extends targetCamera_TargetCamera{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new FollowCameraInputsManager(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;let t=rm.jp.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);let i=Math.atan2(t.m[8],t.m[10]),r=rW.w1.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),n=s.x+Math.sin(r)*this.radius,a=s.z+Math.cos(r)*this.radius,o=n-this.position.x,l=s.y+this.heightOffset-this.position.y,h=a-this.position.z,u=o*this.cameraAcceleration*2,c=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new rm.P(this.position.x+u,this.position.y+c,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=rW.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}};(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"radius",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"lowerRadiusLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"upperRadiusLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"rotationOffset",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"lowerRotationOffsetLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"upperRotationOffsetLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"heightOffset",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"lowerHeightOffsetLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"upperHeightOffsetLimit",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"cameraAcceleration",void 0),(0,rH.gn)([(0,rb.qC)()],FollowCamera.prototype,"maxCameraSpeed",void 0),(0,rH.gn)([(0,rb.RR)("lockedTargetId")],FollowCamera.prototype,"lockedTarget",void 0);let ArcFollowCamera=class ArcFollowCamera extends targetCamera_TargetCamera{constructor(e,t,i,r,s,n){super(e,rm.P.Zero(),n),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=rm.P.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);let e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}};(P=tN||(tN={}))[P.A=0]="A",P[P.B=1]="B",P[P.X=2]="X",P[P.Y=3]="Y",P[P.LB=4]="LB",P[P.RB=5]="RB",P[P.Back=8]="Back",P[P.Start=9]="Start",P[P.LeftStick=10]="LeftStick",P[P.RightStick=11]="RightStick",(R=tF||(tF={}))[R.Up=12]="Up",R[R.Down=13]="Down",R[R.Left=14]="Left",R[R.Right=15]="Right";let Xbox360Pad=class Xbox360Pad extends Gamepad{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new rf.y$,this.onButtonUpObservable=new rf.y$,this.onPadDownObservable=new rf.y$,this.onPadUpObservable=new rf.y$,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=Gamepad.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,tN.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,tN.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,tN.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,tN.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,tN.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,tN.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,tN.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,tN.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,tN.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,tN.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,tF.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,tF.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,tF.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,tF.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}};(A=tB||(tB={}))[A.Cross=0]="Cross",A[A.Circle=1]="Circle",A[A.Square=2]="Square",A[A.Triangle=3]="Triangle",A[A.L1=4]="L1",A[A.R1=5]="R1",A[A.Share=8]="Share",A[A.Options=9]="Options",A[A.LeftStick=10]="LeftStick",A[A.RightStick=11]="RightStick",(I=tL||(tL={}))[I.Up=12]="Up",I[I.Down=13]="Down",I[I.Left=14]="Left",I[I.Right=15]="Right";let DualShockPad=class DualShockPad extends Gamepad{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new rf.y$,this.onButtonUpObservable=new rf.y$,this.onPadDownObservable=new rf.y$,this.onPadUpObservable=new rf.y$,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=Gamepad.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,tB.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,tB.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,tB.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,tB.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,tB.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,tB.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,tB.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,tB.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,tB.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,tB.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,tL.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,tL.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,tL.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,tL.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}};let GamepadManager=class GamepadManager{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new rf.y$,(0,rK.CG)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new rf.y$(e=>{for(let t in this._babylonGamepads){let i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}}),this._onGamepadConnectedEvent=e=>{let t;let i=e.gamepad;i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected||(this._babylonGamepads[i.index]?((t=this._babylonGamepads[i.index]).browserGamepad=i,t._isConnected=!0):t=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(t),this._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=e=>{let t=e.gamepad;for(let e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){let t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport){if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){let e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}}get gamepads(){return this._babylonGamepads}getGamepadByType(e=Gamepad.XBOX){for(let t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(e=>{e.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);let i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new Xbox360Pad(e.id,e.index,e,r):i?new DualShockPad(e.id,e.index,e):new GenericPad(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){for(let e in this._updateGamepadObjects(),this._babylonGamepads){let t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch(e){-1===this._loggedErrors.indexOf(t.index)&&(rW.w1.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&rq.D.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new universalCamera_UniversalCamera(e,rm.P.Zero(),t));let universalCamera_UniversalCamera=class universalCamera_UniversalCamera extends TouchCamera{get gamepadAngularSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}};rj.V._CreateDefaultParsedCamera=(e,t)=>new universalCamera_UniversalCamera(e,rm.P.Zero(),t),ry.N.AddNodeConstructor("GamepadCamera",(e,t)=>()=>new GamepadCamera(e,rm.P.Zero(),t));let GamepadCamera=class GamepadCamera extends universalCamera_UniversalCamera{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}};let sB=`varying vec2 vUV;uniform samplerCube textureSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 uv=vUV*2.0-1.0; -#ifdef POSITIVEX -gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); -#endif -#ifdef NEGATIVEX -gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); -#endif -#ifdef POSITIVEY -gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); -#endif -#ifdef NEGATIVEY -gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); -#endif -#ifdef POSITIVEZ -gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); -#endif -#ifdef NEGATIVEZ -gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); -#endif -}`;s_.v.ShadersStore.passCubePixelShader=sB;let PassPostProcess=class PassPostProcess extends postProcess_PostProcess{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,n,a=0,o=!1){super(e,"pass",null,null,t,i,r,s,n,void 0,a,void 0,null,o)}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new PassPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}};(0,rv.H)("BABYLON.PassPostProcess",PassPostProcess),rq.D._RescalePostProcessFactory=e=>new PassPostProcess("rescale",1,null,2,e,!1,0);let sL=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;s_.v.ShadersStore.anaglyphPixelShader=sL;let AnaglyphPostProcess=class AnaglyphPostProcess extends postProcess_PostProcess{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)})}};function setStereoscopicAnaglyphRigMode(e){e._rigCameras[0]._rigPostProcess=new PassPostProcess(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new AnaglyphPostProcess(e.name+"_anaglyph",1,e._rigCameras)}(0,rv.H)("BABYLON.AnaglyphPostProcess",AnaglyphPostProcess),ry.N.AddNodeConstructor("AnaglyphArcRotateCamera",(e,t,i)=>()=>new AnaglyphArcRotateCamera(e,0,0,1,rm.P.Zero(),i.interaxial_distance,t));let AnaglyphArcRotateCamera=class AnaglyphArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,n,a){super(e,t,i,r,s,a),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=n,this.setCameraRigMode(rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}};ry.N.AddNodeConstructor("AnaglyphFreeCamera",(e,t,i)=>()=>new AnaglyphFreeCamera(e,rm.P.Zero(),i.interaxial_distance,t));let AnaglyphFreeCamera=class AnaglyphFreeCamera extends FreeCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}};ry.N.AddNodeConstructor("AnaglyphGamepadCamera",(e,t,i)=>()=>new AnaglyphGamepadCamera(e,rm.P.Zero(),i.interaxial_distance,t));let AnaglyphGamepadCamera=class AnaglyphGamepadCamera extends GamepadCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}};ry.N.AddNodeConstructor("AnaglyphUniversalCamera",(e,t,i)=>()=>new AnaglyphUniversalCamera(e,rm.P.Zero(),i.interaxial_distance,t));let AnaglyphUniversalCamera=class AnaglyphUniversalCamera extends universalCamera_UniversalCamera{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>setStereoscopicAnaglyphRigMode(this),this.interaxialDistance=i,this.setCameraRigMode(rj.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}};let sw=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; -#ifdef IS_STEREOSCOPIC_HORIZ -useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); -#else -#ifdef IS_STEREOSCOPIC_INTERLACED -float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); -#else -useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); -#endif -#endif -if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} -gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} -`;s_.v.ShadersStore.stereoscopicInterlacePixelShader=sw;let StereoscopicInterlacePostProcessI=class StereoscopicInterlacePostProcessI extends postProcess_PostProcess{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,n,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,n,a,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new rm.FM(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new rm.FM(1/this.width,1/this.height)}),this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}};function setStereoscopicRigMode(e){let t=e.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,r=e.cameraRigMode===rj.V.RIG_MODE_STEREOSCOPIC_INTERLACED;r?(e._rigCameras[0]._rigPostProcess=new PassPostProcess(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new StereoscopicInterlacePostProcessI(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new sh.l(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new sh.l(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}ry.N.AddNodeConstructor("StereoscopicArcRotateCamera",(e,t,i)=>()=>new StereoscopicArcRotateCamera(e,0,0,1,rm.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicArcRotateCamera=class StereoscopicArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,n,a,o){super(e,t,i,r,s,o),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=a,this.setCameraRigMode(a?rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}};ry.N.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new StereoscopicFreeCamera(e,rm.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicFreeCamera=class StereoscopicFreeCamera extends FreeCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}};ry.N.AddNodeConstructor("StereoscopicGamepadCamera",(e,t,i)=>()=>new StereoscopicGamepadCamera(e,rm.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicGamepadCamera=class StereoscopicGamepadCamera extends GamepadCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}};ry.N.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new StereoscopicUniversalCamera(e,rm.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));let StereoscopicUniversalCamera=class StereoscopicUniversalCamera extends universalCamera_UniversalCamera{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>setStereoscopicRigMode(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?rj.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:rj.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}};ry.N.AddNodeConstructor("VirtualJoysticksCamera",(e,t)=>()=>new VirtualJoysticksCamera(e,rm.P.Zero(),t));let VirtualJoysticksCamera=class VirtualJoysticksCamera extends FreeCamera{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}};let VRCameraMetrics=class VRCameraMetrics{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return rm.y3.Translation(t,0,0)}get rightHMatrix(){let e=this.hScreenSize/4-this.lensSeparationDistance/2,t=4*e/this.hScreenSize;return rm.y3.Translation(-t,0,0)}get leftPreViewMatrix(){return rm.y3.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return rm.y3.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){let e=new VRCameraMetrics;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}};let sU=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; -float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) -gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;s_.v.ShadersStore.vrDistortionCorrectionPixelShader=sU;let VRDistortionCorrectionPostProcess=class VRDistortionCorrectionPostProcess extends postProcess_PostProcess{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,texture_Texture.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new rm.FM(2,2/this.aspectRatio),this._scaleFactor=new rm.FM(.5*(1/this._postProcessScaleFactor),.5*(1/this._postProcessScaleFactor)*this.aspectRatio),this._lensCenter=new rm.FM(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)}),this.onApplyObservable.add(e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}};let sV=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;s_.v.ShadersStore.vrMultiviewToSingleviewPixelShader=sV;let MultiviewRenderTarget=class MultiviewRenderTarget extends renderTargetTexture_RenderTargetTexture{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}};function createMultiviewUbo(e,t){let i=new rX.M(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}rq.D.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){let s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";let n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=s.createFramebuffer();let a=new r5.l(this,r5.S.Unknown,!0);return a.width=e,a.height=t,a.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),n._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=r,a.isReady=!0,n.setTextures(a),n._depthStencilTexture=a,n},rq.D.prototype.bindMultiviewFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"},rq.D.prototype.bindSpaceWarpFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw Error("Invalid Space Warp framebuffer")},rj.V.prototype._useMultiviewToSingleView=!1,rj.V.prototype._multiviewTexture=null,rj.V.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=e||this._multiviewTexture.getRenderHeight()!=t)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:e,height:t})):this._multiviewTexture=new MultiviewRenderTarget(this.getScene(),{width:e,height:t})};let sk=rN.x.prototype.createSceneUniformBuffer;rN.x.prototype._transformMatrixR=rm.y3.Zero(),rN.x.prototype._multiviewSceneUbo=null,rN.x.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=createMultiviewUbo(this.getEngine(),"scene_multiview")},rN.x.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?createMultiviewUbo(this.getEngine(),e):sk.bind(this)(e)},rN.x.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,rm.jp.Matrix[0]),sl.i.GetRightPlaneToRef(rm.jp.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},rN.x.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{}),this.onApplyObservable.add(e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)})}};function setVRRigMode(e,t){let i=t.vrCameraMetrics||VRCameraMetrics.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new sh.l(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new rm.y3,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new sh.l(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new rm.y3,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new VRMultiviewToSingleviewPostProcess("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(rT.Y.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}ry.N.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(e,t)=>()=>new VRDeviceOrientationArcRotateCamera(e,0,0,1,rm.P.Zero(),t));let VRDeviceOrientationArcRotateCamera=class VRDeviceOrientationArcRotateCamera extends ArcRotateCamera{constructor(e,t,i,r,s,n,a=!0,o=VRCameraMetrics.GetDefault()){super(e,t,i,r,s,n),this._setRigMode=e=>setVRRigMode(this,e),o.compensateDistortion=a,this.setCameraRigMode(rj.V.RIG_MODE_VR,{vrCameraMetrics:o}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}};ry.N.AddNodeConstructor("VRDeviceOrientationFreeCamera",(e,t)=>()=>new VRDeviceOrientationFreeCamera(e,rm.P.Zero(),t));let VRDeviceOrientationFreeCamera=class VRDeviceOrientationFreeCamera extends DeviceOrientationCamera{constructor(e,t,i,r=!0,s=VRCameraMetrics.GetDefault()){super(e,t,i),this._setRigMode=e=>setVRRigMode(this,e),s.compensateDistortion=r,this.setCameraRigMode(rj.V.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}};ry.N.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(e,t)=>()=>new VRDeviceOrientationGamepadCamera(e,rm.P.Zero(),t));let VRDeviceOrientationGamepadCamera=class VRDeviceOrientationGamepadCamera extends VRDeviceOrientationFreeCamera{constructor(e,t,i,r=!0,s=VRCameraMetrics.GetDefault()){super(e,t,i,r,s),this._setRigMode=e=>setVRRigMode(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}};let PrePassConfiguration=class PrePassConfiguration{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}};var sG=i(4885);let MaterialFlags=class MaterialFlags{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,rq.D.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,rq.D.MarkAllMaterialsAsDirty(1))}};MaterialFlags._DiffuseTextureEnabled=!0,MaterialFlags._DetailTextureEnabled=!0,MaterialFlags._DecalMapEnabled=!0,MaterialFlags._AmbientTextureEnabled=!0,MaterialFlags._OpacityTextureEnabled=!0,MaterialFlags._ReflectionTextureEnabled=!0,MaterialFlags._EmissiveTextureEnabled=!0,MaterialFlags._SpecularTextureEnabled=!0,MaterialFlags._BumpTextureEnabled=!0,MaterialFlags._LightmapTextureEnabled=!0,MaterialFlags._RefractionTextureEnabled=!0,MaterialFlags._ColorGradingTextureEnabled=!0,MaterialFlags._FresnelEnabled=!0,MaterialFlags._ClearCoatTextureEnabled=!0,MaterialFlags._ClearCoatBumpTextureEnabled=!0,MaterialFlags._ClearCoatTintTextureEnabled=!0,MaterialFlags._SheenTextureEnabled=!0,MaterialFlags._AnisotropicTextureEnabled=!0,MaterialFlags._ThicknessTextureEnabled=!0,MaterialFlags._RefractionIntensityTextureEnabled=!0,MaterialFlags._TranslucencyIntensityTextureEnabled=!0,MaterialFlags._IridescenceTextureEnabled=!0;let sz=`#ifdef DECAL -uniform vec4 vDecalInfos; -#endif -`;s_.v.IncludesShadersStore.decalFragmentDeclaration=sz;let sW=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; -#ifdef SPECULARTERM -uniform vec4 vSpecularColor; -#endif -uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; -#ifdef DIFFUSE -uniform vec2 vDiffuseInfos; -#endif -#ifdef AMBIENT -uniform vec2 vAmbientInfos; -#endif -#ifdef OPACITY -uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#ifdef ALPHATEST -uniform float alphaCutOff; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) -uniform mat4 view; -#endif -#ifdef REFRACTION -uniform vec4 vRefractionInfos; -#ifndef REFRACTIONMAP_3D -uniform mat4 refractionMatrix; -#endif -#ifdef REFRACTIONFRESNEL -uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; -#endif -#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) -uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; -#endif -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -uniform vec2 vSpecularInfos; -#endif -#ifdef DIFFUSEFRESNEL -uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; -#endif -#ifdef OPACITYFRESNEL -uniform vec4 opacityParts; -#endif -#ifdef EMISSIVEFRESNEL -uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos; -#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) -uniform mat4 reflectionMatrix; -#endif -#ifndef REFLECTIONMAP_SKYBOX -#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; -#endif -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos; -#endif -#include -#define ADDITIONAL_FRAGMENT_DECLARATION -`;s_.v.IncludesShadersStore.defaultFragmentDeclaration=sW;let sH=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; -#ifdef MULTIVIEW -mat4 viewProjectionR; -#endif -mat4 view;mat4 projection;vec4 vEyePosition;}; -`;s_.v.IncludesShadersStore.sceneUboDeclaration=sH;let sX=`#ifdef WEBGL2 -uniform mat4 world;uniform float visibility; -#else -layout(std140,column_major) uniform;uniform Mesh -{mat4 world;float visibility;}; -#endif -#define WORLD_UBO -`;s_.v.IncludesShadersStore.meshUboDeclaration=sX;let sY=`layout(std140,column_major) uniform;uniform Material -{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; -#define ADDITIONAL_UBO_DECLARATION -}; -#include -#include -`;s_.v.IncludesShadersStore.defaultUboDeclaration=sY;let sj=`#ifdef PREPASS -#extension GL_EXT_draw_buffers : require -layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; -#ifdef PREPASS_DEPTH -varying highp vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; -#endif -#endif -`;s_.v.IncludesShadersStore.prePassDeclaration=sj;let sq=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY -#extension GL_EXT_draw_buffers : require -layout(location=0) out vec2 depth; -layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; -#define MAX_DEPTH 99999.0 -highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; -#endif -`;s_.v.IncludesShadersStore.oitDeclaration=sq;let sK=`#ifdef MAINUV{X} -varying vec2 vMainUV{X}; -#endif -`;s_.v.IncludesShadersStore.mainUVVaryingDeclaration=sK;let s$=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; -const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; -#define saturate(x) clamp(x,0.0,1.0) -#define absEps(x) abs(x)+Epsilon -#define maxEps(x) max(x,Epsilon) -#define saturateEps(x) clamp(x,Epsilon,1.0) -mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( -vec3(i0.x,i1.x,i2.x), -vec3(i0.y,i1.y,i2.y), -vec3(i0.z,i1.z,i2.z) -);return outMatrix;} -mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), -b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), -b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} -#if USE_EXACT_SRGB_CONVERSIONS -vec3 toLinearSpaceExact(vec3 color) -{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); -#else -return -vec3( -color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, -color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, -color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); -#endif -} -vec3 toGammaSpaceExact(vec3 color) -{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); -#else -return -vec3( -color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, -color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, -color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); -#endif -} -#endif -float toLinearSpace(float color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; -#else -return pow(color,LinearEncodePowerApprox); -#endif -} -vec3 toLinearSpace(vec3 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return toLinearSpaceExact(color); -#else -return pow(color,vec3(LinearEncodePowerApprox)); -#endif -} -vec4 toLinearSpace(vec4 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return vec4(toLinearSpaceExact(color.rgb),color.a); -#else -return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); -#endif -} -float toGammaSpace(float color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; -#else -return pow(color,GammaEncodePowerApprox); -#endif -} -vec3 toGammaSpace(vec3 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return toGammaSpaceExact(color); -#else -return pow(color,vec3(GammaEncodePowerApprox)); -#endif -} -vec4 toGammaSpace(vec4 color) -{ -#if USE_EXACT_SRGB_CONVERSIONS -return vec4(toGammaSpaceExact(color.rgb),color.a); -#else -return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); -#endif -} -float square(float value) -{return value*value;} -vec3 square(vec3 value) -{return value*value;} -float pow5(float value) {float sq=value*value;return sq*sq*value;} -float getLuminance(vec3 color) -{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} -float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} -float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} -const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } -vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} -vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} -`;s_.v.IncludesShadersStore.helperFunctions=s$;let sQ=`#ifdef LIGHT{X} -uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; -#ifdef SPECULARTERM -uniform vec4 vLightSpecular{X}; -#else -vec4 vLightSpecular{X}=vec4(0.); -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DArrayShadow shadowSampler{X}; -#else -uniform highp sampler2DArray shadowSampler{X}; -#endif -#ifdef SHADOWCSMDEBUG{X} -const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] -( -vec3 ( 1.5,0.0,0.0 ), -vec3 ( 0.0,1.5,0.0 ), -vec3 ( 0.0,0.0,5.5 ), -vec3 ( 1.5,0.0,5.5 ), -vec3 ( 1.5,1.5,0.0 ), -vec3 ( 1.0,1.0,1.0 ), -vec3 ( 0.0,1.0,5.5 ), -vec3 ( 0.5,3.5,0.75 ) -);vec3 shadowDebug{X}; -#endif -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -int index{X}=-1; -#else -int index{X}=SHADOWCSMNUM_CASCADES{X}-1; -#endif -float diff{X}=0.; -#elif defined(SHADOWCUBE{X}) -uniform samplerCube shadowSampler{X}; -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DShadow shadowSampler{X}; -#else -uniform sampler2D shadowSampler{X}; -#endif -uniform mat4 lightMatrix{X}; -#endif -uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; -#endif -#ifdef SPOTLIGHT{X} -uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; -#elif defined(POINTLIGHT{X}) -uniform vec4 vLightFalloff{X}; -#elif defined(HEMILIGHT{X}) -uniform vec3 vLightGround{X}; -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; -#endif -#endif -`;s_.v.IncludesShadersStore.lightFragmentDeclaration=sQ;let sZ=`#ifdef LIGHT{X} -uniform Light{X} -{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; -#ifdef SPOTLIGHT{X} -vec4 vLightDirection;vec4 vLightFalloff; -#elif defined(POINTLIGHT{X}) -vec4 vLightFalloff; -#elif defined(HEMILIGHT{X}) -vec3 vLightGround; -#endif -vec4 shadowsInfo;vec2 depthValues;} light{X}; -#ifdef PROJECTEDLIGHTTEXTURE{X} -uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DArrayShadow shadowSampler{X}; -#else -uniform highp sampler2DArray shadowSampler{X}; -#endif -#ifdef SHADOWCSMDEBUG{X} -const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] -( -vec3 ( 1.5,0.0,0.0 ), -vec3 ( 0.0,1.5,0.0 ), -vec3 ( 0.0,0.0,5.5 ), -vec3 ( 1.5,0.0,5.5 ), -vec3 ( 1.5,1.5,0.0 ), -vec3 ( 1.0,1.0,1.0 ), -vec3 ( 0.0,1.0,5.5 ), -vec3 ( 0.5,3.5,0.75 ) -);vec3 shadowDebug{X}; -#endif -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -int index{X}=-1; -#else -int index{X}=SHADOWCSMNUM_CASCADES{X}-1; -#endif -float diff{X}=0.; -#elif defined(SHADOWCUBE{X}) -uniform samplerCube shadowSampler{X}; -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; -#if defined(SHADOWPCSS{X}) -uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; -#elif defined(SHADOWPCF{X}) -uniform highp sampler2DShadow shadowSampler{X}; -#else -uniform sampler2D shadowSampler{X}; -#endif -uniform mat4 lightMatrix{X}; -#endif -#endif -#endif -`;s_.v.IncludesShadersStore.lightUboDeclaration=sZ;let sJ=`struct lightingInfo -{vec3 diffuse; -#ifdef SPECULARTERM -vec3 specular; -#endif -#ifdef NDOTL -float ndl; -#endif -};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) -{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} -else -{lightVectorW=normalize(-lightData.xyz);} -float ndl=max(0.,dot(vNormal,lightVectorW)); -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=ndl*diffuseColor*attenuation; -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; -#endif -return result;} -lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) -{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=ndl*diffuseColor*attenuation; -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; -#endif -return result;} -result.diffuse=vec3(0.); -#ifdef SPECULARTERM -result.specular=vec3(0.); -#endif -#ifdef NDOTL -result.ndl=0.; -#endif -return result;} -lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; -#ifdef NDOTL -result.ndl=ndl; -#endif -result.diffuse=mix(groundColor,diffuseColor,ndl); -#ifdef SPECULARTERM -vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; -#endif -return result;} -#define inline -vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;s_.v.IncludesShadersStore.lightsFragmentFunctions=sJ;let s0=`#ifdef SHADOWS -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -#ifndef SHADOWFLOAT -float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} -#endif -float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) -{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} -#define inline -float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) -{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; -#ifndef SHADOWFLOAT -float shadow=unpack(textureCube(shadowSampler,directionToLight)); -#else -float shadow=textureCube(shadowSampler,directionToLight).x; -#endif -return depth>shadow ? darkness : 1.0;} -#define inline -float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) -{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); -#ifndef SHADOWFLOAT -if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} -#endif -#define inline -float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} -#define inline -float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); -#ifndef SHADOWFLOAT -if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) -{return 1.0;} -else -{float shadowPixelDepth=clamp(depthMetric,0.,1.0); -#ifndef SHADOWFLOAT -float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); -#else -float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; -#endif -float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} -#ifdef IS_NDC_HALF_ZRANGE -#define ZINCLIP clipSpace.z -#else -#define ZINCLIP uvDepth.z -#endif -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define GREATEST_LESS_THAN_ONE 0.99999994 -/* disable_uniformity_analysis */ -#define inline -float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} -#define inline -float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -#define inline -float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) -{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; -uv+=0.5; -vec2 st=fract(uv); -vec2 base_uv=floor(uv)-0.5; -base_uv*=shadowMapSizeAndInverse.y; -vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} -const vec3 PoissonSamplers32[64]=vec3[64]( -vec3(0.06407013,0.05409927,0.), -vec3(0.7366577,0.5789394,0.), -vec3(-0.6270542,-0.5320278,0.), -vec3(-0.4096107,0.8411095,0.), -vec3(0.6849564,-0.4990818,0.), -vec3(-0.874181,-0.04579735,0.), -vec3(0.9989998,0.0009880066,0.), -vec3(-0.004920578,-0.9151649,0.), -vec3(0.1805763,0.9747483,0.), -vec3(-0.2138451,0.2635818,0.), -vec3(0.109845,0.3884785,0.), -vec3(0.06876755,-0.3581074,0.), -vec3(0.374073,-0.7661266,0.), -vec3(0.3079132,-0.1216763,0.), -vec3(-0.3794335,-0.8271583,0.), -vec3(-0.203878,-0.07715034,0.), -vec3(0.5912697,0.1469799,0.), -vec3(-0.88069,0.3031784,0.), -vec3(0.5040108,0.8283722,0.), -vec3(-0.5844124,0.5494877,0.), -vec3(0.6017799,-0.1726654,0.), -vec3(-0.5554981,0.1559997,0.), -vec3(-0.3016369,-0.3900928,0.), -vec3(-0.5550632,-0.1723762,0.), -vec3(0.925029,0.2995041,0.), -vec3(-0.2473137,0.5538505,0.), -vec3(0.9183037,-0.2862392,0.), -vec3(0.2469421,0.6718712,0.), -vec3(0.3916397,-0.4328209,0.), -vec3(-0.03576927,-0.6220032,0.), -vec3(-0.04661255,0.7995201,0.), -vec3(0.4402924,0.3640312,0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.), -vec3(0.) -);const vec3 PoissonSamplers64[64]=vec3[64]( -vec3(-0.613392,0.617481,0.), -vec3(0.170019,-0.040254,0.), -vec3(-0.299417,0.791925,0.), -vec3(0.645680,0.493210,0.), -vec3(-0.651784,0.717887,0.), -vec3(0.421003,0.027070,0.), -vec3(-0.817194,-0.271096,0.), -vec3(-0.705374,-0.668203,0.), -vec3(0.977050,-0.108615,0.), -vec3(0.063326,0.142369,0.), -vec3(0.203528,0.214331,0.), -vec3(-0.667531,0.326090,0.), -vec3(-0.098422,-0.295755,0.), -vec3(-0.885922,0.215369,0.), -vec3(0.566637,0.605213,0.), -vec3(0.039766,-0.396100,0.), -vec3(0.751946,0.453352,0.), -vec3(0.078707,-0.715323,0.), -vec3(-0.075838,-0.529344,0.), -vec3(0.724479,-0.580798,0.), -vec3(0.222999,-0.215125,0.), -vec3(-0.467574,-0.405438,0.), -vec3(-0.248268,-0.814753,0.), -vec3(0.354411,-0.887570,0.), -vec3(0.175817,0.382366,0.), -vec3(0.487472,-0.063082,0.), -vec3(-0.084078,0.898312,0.), -vec3(0.488876,-0.783441,0.), -vec3(0.470016,0.217933,0.), -vec3(-0.696890,-0.549791,0.), -vec3(-0.149693,0.605762,0.), -vec3(0.034211,0.979980,0.), -vec3(0.503098,-0.308878,0.), -vec3(-0.016205,-0.872921,0.), -vec3(0.385784,-0.393902,0.), -vec3(-0.146886,-0.859249,0.), -vec3(0.643361,0.164098,0.), -vec3(0.634388,-0.049471,0.), -vec3(-0.688894,0.007843,0.), -vec3(0.464034,-0.188818,0.), -vec3(-0.440840,0.137486,0.), -vec3(0.364483,0.511704,0.), -vec3(0.034028,0.325968,0.), -vec3(0.099094,-0.308023,0.), -vec3(0.693960,-0.366253,0.), -vec3(0.678884,-0.204688,0.), -vec3(0.001801,0.780328,0.), -vec3(0.145177,-0.898984,0.), -vec3(0.062655,-0.611866,0.), -vec3(0.315226,-0.604297,0.), -vec3(-0.780145,0.486251,0.), -vec3(-0.371868,0.882138,0.), -vec3(0.200476,0.494430,0.), -vec3(-0.494552,-0.711051,0.), -vec3(0.612476,0.705252,0.), -vec3(-0.578845,-0.768792,0.), -vec3(-0.772454,-0.090976,0.), -vec3(0.504440,0.372295,0.), -vec3(0.155736,0.065157,0.), -vec3(0.391522,0.849605,0.), -vec3(-0.620106,-0.328104,0.), -vec3(0.789239,-0.419965,0.), -vec3(-0.545396,0.538133,0.), -vec3(-0.178564,-0.596057,0.) -); -#define inline -float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;} -else -{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) -#endif -#if defined(DETAIL) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) -#endif -#if defined(BUMP) && defined(PARALLAX) -const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; icurrRayHeight) -{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} -else -{currRayHeight-=stepSize;vLastOffset=vCurrOffset; -#ifdef PARALLAX_RHS -vCurrOffset-=stepSize*vMaxOffset; -#else -vCurrOffset+=stepSize*vMaxOffset; -#endif -lastSampledHeight=currSampledHeight;}} -return vCurrOffset;} -vec2 parallaxOffset(vec3 viewDir,float heightScale) -{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; -#ifdef PARALLAX_RHS -return texCoordOffset; -#else -return -texCoordOffset; -#endif -} -#endif -`;s_.v.IncludesShadersStore.bumpFragmentFunctions=s8;let s7=`#ifdef CLIPPLANE -varying float fClipDistance; -#endif -#ifdef CLIPPLANE2 -varying float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -varying float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -varying float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -varying float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -varying float fClipDistance6; -#endif -`;s_.v.IncludesShadersStore.clipPlaneFragmentDeclaration=s7;let s9=`#ifdef LOGARITHMICDEPTH -uniform float logarithmicDepthConstant;varying float vFragmentDepth; -#endif -`;s_.v.IncludesShadersStore.logDepthDeclaration=s9;let ne=`#ifdef FOG -#define FOGMODE_NONE 0. -#define FOGMODE_EXP 1. -#define FOGMODE_EXP2 2. -#define FOGMODE_LINEAR 3. -#define E 2.71828 -uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() -{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) -{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} -else if (FOGMODE_EXP==vFogInfos.x) -{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} -else if (FOGMODE_EXP2==vFogInfos.x) -{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} -return clamp(fogCoeff,0.0,1.0);} -#endif -`;s_.v.IncludesShadersStore.fogFragmentDeclaration=ne;let nt=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -if (false) {} -#endif -#ifdef CLIPPLANE -else if (fClipDistance>0.0) -{discard;} -#endif -#ifdef CLIPPLANE2 -else if (fClipDistance2>0.0) -{discard;} -#endif -#ifdef CLIPPLANE3 -else if (fClipDistance3>0.0) -{discard;} -#endif -#ifdef CLIPPLANE4 -else if (fClipDistance4>0.0) -{discard;} -#endif -#ifdef CLIPPLANE5 -else if (fClipDistance5>0.0) -{discard;} -#endif -#ifdef CLIPPLANE6 -else if (fClipDistance6>0.0) -{discard;} -#endif -`;s_.v.IncludesShadersStore.clipPlaneFragment=nt;let ni=`vec2 uvOffset=vec2(0.0,0.0); -#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) -#ifdef NORMALXYSCALE -float normalScale=1.0; -#elif defined(BUMP) -float normalScale=vBumpInfos.y; -#else -float normalScale=1.0; -#endif -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#elif defined(BUMP) -vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); -#else -vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); -#endif -#elif defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -mat3 TBN=vTBN; -#else -vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); -#endif -#endif -#ifdef PARALLAX -mat3 invTBN=transposeMat3(TBN); -#ifdef PARALLAXOCCLUSION -uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); -#else -uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); -#endif -#endif -#ifdef DETAIL -vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); -#endif -#ifdef BUMP -#ifdef OBJECTSPACE_NORMALMAP -#define CUSTOM_FRAGMENT_BUMP_FRAGMENT -normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); -#elif !defined(DETAIL) -normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); -#else -vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; -#if DETAIL_NORMALBLENDMETHOD==0 -detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); -#elif DETAIL_NORMALBLENDMETHOD==1 -detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; -#endif -normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); -#endif -#elif defined(DETAIL) -detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); -#endif -`;s_.v.IncludesShadersStore.bumpFragment=ni;let nr=`#ifdef DECAL -#ifdef GAMMADECAL -decalColor.rgb=toLinearSpace(decalColor.rgb); -#endif -#ifdef DECAL_SMOOTHALPHA -decalColor.a*=decalColor.a; -#endif -surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); -#endif -`;s_.v.IncludesShadersStore.decalFragment=nr;let ns=`#ifdef DEPTHPREPASS -gl_FragColor=vec4(0.,0.,0.,1.0);return; -#endif -`;s_.v.IncludesShadersStore.depthPrePass=ns;let nn=`#ifdef LIGHT{X} -#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) -#else -#ifdef PBR -#ifdef SPOTLIGHT{X} -preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(POINTLIGHT{X}) -preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(HEMILIGHT{X}) -preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#elif defined(DIRLIGHT{X}) -preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); -#endif -preInfo.NdotV=NdotV; -#ifdef SPOTLIGHT{X} -#ifdef LIGHT_FALLOFF_GLTF{X} -preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); -#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) -preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); -#elif defined(LIGHT_FALLOFF_STANDARD{X}) -preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); -#else -preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); -#endif -#elif defined(POINTLIGHT{X}) -#ifdef LIGHT_FALLOFF_GLTF{X} -preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); -#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) -preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); -#elif defined(LIGHT_FALLOFF_STANDARD{X}) -preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); -#else -preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); -#endif -#else -preInfo.attenuation=1.0; -#endif -#ifdef HEMILIGHT{X} -preInfo.roughness=roughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#ifdef IRIDESCENCE -preInfo.iridescenceIntensity=iridescenceIntensity; -#endif -#ifdef HEMILIGHT{X} -info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); -#elif defined(SS_TRANSLUCENCY) -info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); -#else -info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); -#endif -#ifdef SPECULARTERM -#ifdef ANISOTROPIC -info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#else -info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#endif -#ifdef SHEEN -#ifdef SHEEN_LINKWITHALBEDO -preInfo.roughness=sheenOut.sheenIntensity; -#else -#ifdef HEMILIGHT{X} -preInfo.roughness=sheenOut.sheenRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -#endif -info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); -#endif -#ifdef CLEARCOAT -#ifdef HEMILIGHT{X} -preInfo.roughness=clearcoatOut.clearCoatRoughness; -#else -preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); -#endif -info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); -#ifdef CLEARCOAT_TINT -absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; -#ifdef SPECULARTERM -info.specular*=absorption; -#endif -#endif -info.diffuse*=info.clearCoat.w; -#ifdef SPECULARTERM -info.specular*=info.clearCoat.w; -#endif -#ifdef SHEEN -info.sheen*=info.clearCoat.w; -#endif -#endif -#else -#ifdef SPOTLIGHT{X} -info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#elif defined(HEMILIGHT{X}) -info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); -#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) -info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); -#endif -#endif -#ifdef PROJECTEDLIGHTTEXTURE{X} -info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); -#endif -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -for (int i=0; i=0.) {index{X}=i;break;}} -#ifdef SHADOWCSMUSESHADOWMAXZ{X} -if (index{X}>=0) -#endif -{ -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; -#endif -#ifndef SHADOWCSMNOBLEND{X} -float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) -{index{X}+=1;float nextShadow=0.; -#if defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#elif defined(SHADOWMEDIUMQUALITY{X}) -nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#else -nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); -#endif -#else -nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -shadow=mix(nextShadow,shadow,diffRatio); -#ifdef SHADOWCSMDEBUG{X} -shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); -#endif -} -#endif -} -#elif defined(SHADOWCLOSEESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); -#else -shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWESM{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); -#else -shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPOISSON{X}) -#if defined(SHADOWCUBE{X}) -shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); -#else -shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCF{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#elif defined(SHADOWPCSS{X}) -#if defined(SHADOWLOWQUALITY{X}) -shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#elif defined(SHADOWMEDIUMQUALITY{X}) -shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#else -shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#else -#if defined(SHADOWCUBE{X}) -shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); -#else -shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); -#endif -#endif -#ifdef SHADOWONLY -#ifndef SHADOWINUSE -#define SHADOWINUSE -#endif -globalShadow+=shadow;shadowLightCount+=1.0; -#endif -#else -shadow=1.; -#endif -aggShadow+=shadow;numLights+=1.0; -#ifndef SHADOWONLY -#ifdef CUSTOMUSERLIGHTING -diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); -#ifdef SPECULARTERM -specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); -#endif -#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) -diffuseBase+=lightmapColor.rgb*shadow; -#ifdef SPECULARTERM -#ifndef LIGHTMAPNOSPECULAR{X} -specularBase+=info.specular*shadow*lightmapColor.rgb; -#endif -#endif -#ifdef CLEARCOAT -#ifndef LIGHTMAPNOSPECULAR{X} -clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; -#endif -#endif -#ifdef SHEEN -#ifndef LIGHTMAPNOSPECULAR{X} -sheenBase+=info.sheen.rgb*shadow; -#endif -#endif -#else -#ifdef SHADOWCSMDEBUG{X} -diffuseBase+=info.diffuse*shadowDebug{X}; -#else -diffuseBase+=info.diffuse*shadow; -#endif -#ifdef SPECULARTERM -specularBase+=info.specular*shadow; -#endif -#ifdef CLEARCOAT -clearCoatBase+=info.clearCoat.rgb*shadow; -#endif -#ifdef SHEEN -sheenBase+=info.sheen.rgb*shadow; -#endif -#endif -#endif -#endif -`;s_.v.IncludesShadersStore.lightFragment=nn;let na=`#ifdef LOGARITHMICDEPTH -gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; -#endif -`;s_.v.IncludesShadersStore.logDepthFragment=na;let no=`#ifdef FOG -float fog=CalcFogFactor(); -#ifdef PBR -fog=toLinearSpace(fog); -#endif -color.rgb=mix(vFogColor,color.rgb,fog); -#endif -`;s_.v.IncludesShadersStore.fogFragment=no;let nl=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY -float fragDepth=gl_FragCoord.z; -#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS -uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; -#endif -ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); -#ifdef USE_REVERSE_DEPTHBUFFER -float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; -#else -float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; -#endif -float alphaMultiplier=1.0-lastFrontColor.a; -#ifdef USE_REVERSE_DEPTHBUFFER -if (fragDepth>nearestDepth || fragDepthfurthestDepth) { -#endif -return;} -#ifdef USE_REVERSE_DEPTHBUFFER -if (fragDepthfurthestDepth) { -#else -if (fragDepth>nearestDepth && fragDepth -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -#include[SCENE_MRT_COUNT] -#include -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include[1..7] -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include -#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) -#ifdef REFRACTION -#ifdef REFRACTIONMAP_3D -uniform samplerCube refractionCubeSampler; -#else -uniform sampler2D refraction2DSampler; -#endif -#endif -#if defined(SPECULARTERM) -#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) -#endif -#include -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -uniform samplerCube reflectionCubeSampler; -#else -uniform sampler2D reflection2DSampler; -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include -#endif -#include -#include -#include -#include -#include -#include -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); -#endif -#include -#ifdef TWOSIDEDLIGHTING -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -#ifdef DIFFUSE -baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); -#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) -if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) -#endif -#include -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -baseColor.rgb*=vColor.rgb; -#endif -#ifdef DETAIL -baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); -#endif -#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) -#endif -#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE -vec3 baseAmbientColor=vec3(1.,1.,1.); -#ifdef AMBIENT -baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; -#endif -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS -#ifdef SPECULARTERM -float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; -#ifdef SPECULAR -vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; -#ifdef GLOSSINESS -glossiness=glossiness*specularMapColor.a; -#endif -#endif -#else -float glossiness=0.; -#endif -vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; -#ifdef SPECULARTERM -vec3 specularBase=vec3(0.,0.,0.); -#endif -float shadow=1.;float aggShadow=0.;float numLights=0.; -#ifdef LIGHTMAP -vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); -#ifdef RGBDLIGHTMAP -lightmapColor.rgb=fromRGBD(lightmapColor); -#endif -lightmapColor.rgb*=vLightmapInfos.y; -#endif -#include[0..maxSimultaneousLights] -aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); -#ifdef REFRACTION -vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); -#ifdef REFRACTIONMAP_3D -#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC -refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); -#endif -refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} -#else -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); -#endif -#ifdef RGBDREFRACTION -refractionColor.rgb=fromRGBD(refractionColor); -#endif -#ifdef IS_REFRACTION_LINEAR -refractionColor.rgb=toGammaSpace(refractionColor.rgb); -#endif -refractionColor.rgb*=vRefractionInfos.x; -#endif -vec4 reflectionColor=vec4(0.,0.,0.,1.); -#ifdef REFLECTION -vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -vReflectionUVW.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -#ifdef ROUGHNESS -float bias=vReflectionInfos.y; -#ifdef SPECULARTERM -#ifdef SPECULAR -#ifdef GLOSSINESS -bias*=(1.0-specularMapColor.a); -#endif -#endif -#endif -reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); -#else -reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); -#endif -#else -vec2 coords=vReflectionUVW.xy; -#ifdef REFLECTIONMAP_PROJECTION -coords/=vReflectionUVW.z; -#endif -coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); -#endif -#ifdef RGBDREFLECTION -reflectionColor.rgb=fromRGBD(reflectionColor); -#endif -#ifdef IS_REFLECTION_LINEAR -reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); -#endif -reflectionColor.rgb*=vReflectionInfos.x; -#ifdef REFLECTIONFRESNEL -float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); -#ifdef REFLECTIONFRESNELFROMSPECULAR -#ifdef SPECULARTERM -reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#else -reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#endif -#else -reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; -#endif -#endif -#endif -#ifdef REFRACTIONFRESNEL -float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#ifdef OPACITYRGB -opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; -#else -alpha*=opacityMap.a*vOpacityInfos.y; -#endif -#endif -#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) -alpha*=vColor.a; -#endif -#ifdef OPACITYFRESNEL -float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; -#endif -#ifdef ALPHATEST -#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS -if (alpha -#include -#ifdef IMAGEPROCESSINGPOSTPROCESS -color.rgb=toLinearSpace(color.rgb); -#else -#ifdef IMAGEPROCESSING -color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); -#endif -#endif -color.a*=visibility; -#ifdef PREMULTIPLYALPHA -color.rgb*=color.a; -#endif -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); -#endif -#ifdef PREPASS_VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_IRRADIANCE -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_DEPTH -gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_NORMAL -#ifdef PREPASS_NORMAL_WORLDSPACE -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); -#else -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); -#endif -#endif -#ifdef PREPASS_ALBEDO_SQRT -gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_REFLECTIVITY -#if defined(SPECULARTERM) -#if defined(SPECULAR) -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; -#endif -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=color; -#endif -#include -#if ORDER_INDEPENDENT_TRANSPARENCY -if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} -#endif -#define CUSTOM_FRAGMENT_MAIN_END -} -`;s_.v.ShadersStore.defaultPixelShader=nh;let nu=`#ifdef DECAL -uniform vec4 vDecalInfos;uniform mat4 decalMatrix; -#endif -`;s_.v.IncludesShadersStore.decalVertexDeclaration=nu;let nc=`uniform mat4 viewProjection;uniform mat4 view; -#ifdef DIFFUSE -uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; -#endif -#ifdef AMBIENT -uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; -#endif -#ifdef OPACITY -uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; -#endif -#if defined(SPECULAR) && defined(SPECULARTERM) -uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; -#endif -#ifdef REFLECTION -uniform mat4 reflectionMatrix; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos;uniform mat4 detailMatrix; -#endif -#include -#define ADDITIONAL_VERTEX_DECLARATION -`;s_.v.IncludesShadersStore.defaultVertexDeclaration=nc;let nd=`#ifdef UV{X} -attribute vec2 uv{X}; -#endif -`;s_.v.IncludesShadersStore.uvAttributeDeclaration=nd;let np=`#if NUM_BONE_INFLUENCERS>0 -attribute vec4 matricesIndices;attribute vec4 matricesWeights; -#if NUM_BONE_INFLUENCERS>4 -attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; -#endif -#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#ifdef BONETEXTURE -uniform highp sampler2D boneSampler;uniform float boneTextureWidth; -#else -uniform mat4 mBones[BonesPerMesh]; -#ifdef BONES_VELOCITY_ENABLED -uniform mat4 mPreviousBones[BonesPerMesh]; -#endif -#endif -#ifdef BONETEXTURE -#define inline -mat4 readMatrixFromRawSampler(sampler2D smp,float index) -{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} -#endif -#endif -#endif -`;s_.v.IncludesShadersStore.bonesDeclaration=np;let n_=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; -#ifdef INSTANCES -attribute vec4 bakedVertexAnimationSettingsInstanced; -#endif -#define inline -mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) -{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} -#endif -`;s_.v.IncludesShadersStore.bakedVertexAnimationDeclaration=n_;let nf=`#ifdef INSTANCES -attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; -#ifdef INSTANCESCOLOR -attribute vec4 instanceColor; -#endif -#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) -uniform mat4 world; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; -#ifdef THIN_INSTANCES -uniform mat4 previousWorld; -#endif -#endif -#else -#if !defined(WORLD_UBO) -uniform mat4 world; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -uniform mat4 previousWorld; -#endif -#endif -`;s_.v.IncludesShadersStore.instancesDeclaration=nf;let nm=`#ifdef PREPASS -#ifdef PREPASS_DEPTH -varying vec3 vViewPos; -#endif -#ifdef PREPASS_VELOCITY -uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#endif -`;s_.v.IncludesShadersStore.prePassVertexDeclaration=nm;let ng=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 -varying vec2 v_VARYINGNAME_UV; -#endif -`;s_.v.IncludesShadersStore.samplerVertexDeclaration=ng;let nv=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -varying mat3 vTBN; -#endif -#endif -`;s_.v.IncludesShadersStore.bumpVertexDeclaration=nv;let nx=`#ifdef CLIPPLANE -uniform vec4 vClipPlane;varying float fClipDistance; -#endif -#ifdef CLIPPLANE2 -uniform vec4 vClipPlane2;varying float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -uniform vec4 vClipPlane3;varying float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -uniform vec4 vClipPlane4;varying float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -uniform vec4 vClipPlane5;varying float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -uniform vec4 vClipPlane6;varying float fClipDistance6; -#endif -`;s_.v.IncludesShadersStore.clipPlaneVertexDeclaration=nx;let nT=`#ifdef FOG -varying vec3 vFogDistance; -#endif -`;s_.v.IncludesShadersStore.fogVertexDeclaration=nT;let nS=`#ifdef LIGHT{X} -uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; -#ifdef SPECULARTERM -uniform vec4 vLightSpecular{X}; -#else -vec4 vLightSpecular{X}=vec4(0.); -#endif -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#elif defined(SHADOWCUBE{X}) -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; -#endif -uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; -#endif -#ifdef SPOTLIGHT{X} -uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; -#elif defined(POINTLIGHT{X}) -uniform vec4 vLightFalloff{X}; -#elif defined(HEMILIGHT{X}) -uniform vec3 vLightGround{X}; -#endif -#endif -`;s_.v.IncludesShadersStore.lightVxFragmentDeclaration=nS;let nC=`#ifdef LIGHT{X} -uniform Light{X} -{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; -#ifdef SPOTLIGHT{X} -vec4 vLightDirection;vec4 vLightFalloff; -#elif defined(POINTLIGHT{X}) -vec4 vLightFalloff; -#elif defined(HEMILIGHT{X}) -vec3 vLightGround; -#endif -vec4 shadowsInfo;vec2 depthValues;} light{X}; -#ifdef SHADOW{X} -#ifdef SHADOWCSM{X} -uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; -#elif defined(SHADOWCUBE{X}) -#else -varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; -#endif -#endif -#endif -`;s_.v.IncludesShadersStore.lightVxUboDeclaration=nC;let nE=`#ifdef MORPHTARGETS -uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; -#ifdef MORPHTARGETS_TEXTURE -uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) -{ -float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} -#endif -#endif -`;s_.v.IncludesShadersStore.morphTargetsVertexGlobalDeclaration=nE;let nb=`#ifdef MORPHTARGETS -#ifndef MORPHTARGETS_TEXTURE -attribute vec3 position{X}; -#ifdef MORPHTARGETS_NORMAL -attribute vec3 normal{X}; -#endif -#ifdef MORPHTARGETS_TANGENT -attribute vec3 tangent{X}; -#endif -#ifdef MORPHTARGETS_UV -attribute vec2 uv_{X}; -#endif -#endif -#endif -`;s_.v.IncludesShadersStore.morphTargetsVertexDeclaration=nb;let ny=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -float vertexID; -#endif -#endif -`;s_.v.IncludesShadersStore.morphTargetsVertexGlobal=ny;let nP=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; -#endif -#else -positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; -#endif -#endif -#endif -`;s_.v.IncludesShadersStore.morphTargetsVertex=nP;let nR=`#ifdef INSTANCES -mat4 finalWorld=mat4(world0,world1,world2,world3); -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); -#endif -#ifdef THIN_INSTANCES -finalWorld=world*finalWorld; -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -finalPreviousWorld=previousWorld*finalPreviousWorld; -#endif -#endif -#else -mat4 finalWorld=world; -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -mat4 finalPreviousWorld=previousWorld; -#endif -#endif -`;s_.v.IncludesShadersStore.instancesVertex=nR;let nA=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#if NUM_BONE_INFLUENCERS>0 -mat4 influence; -#ifdef BONETEXTURE -influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; -#endif -#else -influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -#endif -finalWorld=finalWorld*influence; -#endif -#endif -`;s_.v.IncludesShadersStore.bonesVertex=nA;let nI=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -{ -#ifdef INSTANCES -#define BVASNAME bakedVertexAnimationSettingsInstanced -#else -#define BVASNAME bakedVertexAnimationSettings -#endif -float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; -#endif -finalWorld=finalWorld*VATInfluence;} -#endif -`;s_.v.IncludesShadersStore.bakedVertexAnimation=nI;let nM=`#ifdef PREPASS_DEPTH -vViewPos=(view*worldPos).rgb; -#endif -#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*worldPos; -#if NUM_BONE_INFLUENCERS>0 -mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#endif -`;s_.v.IncludesShadersStore.prePassVertex=nM;let nD=`#if !defined(UV{X}) && defined(MAINUV{X}) -vec2 uv{X}=vec2(0.,0.); -#endif -#ifdef MAINUV{X} -vMainUV{X}=uv{X}; -#endif -`;s_.v.IncludesShadersStore.uvVariableDeclaration=nD;let nO=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 -if (v_INFONAME_==0.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} -#ifdef UV2 -else if (v_INFONAME_==1.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} -#endif -#ifdef UV3 -else if (v_INFONAME_==2.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} -#endif -#ifdef UV4 -else if (v_INFONAME_==3.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} -#endif -#ifdef UV5 -else if (v_INFONAME_==4.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} -#endif -#ifdef UV6 -else if (v_INFONAME_==5.) -{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} -#endif -#endif -`;s_.v.IncludesShadersStore.samplerVertexImplementation=nO;let nN=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#if defined(TANGENT) && defined(NORMAL) -vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); -#endif -#endif -`;s_.v.IncludesShadersStore.bumpVertex=nN;let nF=`#ifdef CLIPPLANE -fClipDistance=dot(worldPos,vClipPlane); -#endif -#ifdef CLIPPLANE2 -fClipDistance2=dot(worldPos,vClipPlane2); -#endif -#ifdef CLIPPLANE3 -fClipDistance3=dot(worldPos,vClipPlane3); -#endif -#ifdef CLIPPLANE4 -fClipDistance4=dot(worldPos,vClipPlane4); -#endif -#ifdef CLIPPLANE5 -fClipDistance5=dot(worldPos,vClipPlane5); -#endif -#ifdef CLIPPLANE6 -fClipDistance6=dot(worldPos,vClipPlane6); -#endif -`;s_.v.IncludesShadersStore.clipPlaneVertex=nF;let nB=`#ifdef FOG -vFogDistance=(view*worldPos).xyz; -#endif -`;s_.v.IncludesShadersStore.fogVertex=nB;let nL=`#ifdef SHADOWS -#if defined(SHADOWCSM{X}) -vPositionFromCamera{X}=view*worldPos;for (int i=0; i -#define CUSTOM_VERTEX_BEGIN -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#ifdef TANGENT -attribute vec4 tangent; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#include[2..7] -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include -#include -#include -#include -#include[1..7] -#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) -#if defined(SPECULARTERM) -#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) -#endif -#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include -#include -#include -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -vPositionW=vec3(worldPos); -#include -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#include[2..7] -#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) -#if defined(SPECULARTERM) -#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) -#endif -#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) -#include -#include -#include -#include[0..maxSimultaneousLights] -#include -#include -#include -#define CUSTOM_VERTEX_MAIN_END -} -`;s_.v.ShadersStore.defaultVertexShader=nk;var nG=i(7790);let nz=RegExp("^([gimus]+)!");let MaterialPluginManager=class MaterialPluginManager{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;tthis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort((e,t)=>e.priority-t.priority),this._codeInjectionPoints={};let i={};for(let e of(i[MaterialPluginManager._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0},this._plugins))e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!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;t0&&t.uniforms.push(...this._uniformList),this._samplerList.length>0&&t.samplers.push(...this._samplerList),this._uboList.length>0&&t.uniformBuffersNames.push(...this._uboList),t.customCode=this._injectCustomCode(t,t.customCode);break;case sG.S.PrepareUniformBuffer:for(let e of(this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[],this._plugins)){let r=e.getUniforms();if(r){if(r.ubo)for(let e of r.ubo){if(e.size&&e.type){let r=null!==(i=e.arraySize)&&void 0!==i?i:0;t.ubo.addUniform(e.name,e.size,r),this._uboDeclaration+=`${e.type} ${e.name}${r>0?`[${r}]`:""}; -`}this._uniformList.push(e.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}e.getSamplers(this._samplerList),e.getUniformBuffersNames(this._uboList)}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var s,n;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let a=null===(s=this._codeInjectionPoints)||void 0===s?void 0:s[i];if(!a)return r;let o=null;for(let t in a){let s="";for(let r of this._activePlugins){let a=null===(n=r.getCustomCode(i))||void 0===n?void 0:n[t];if(a){if(r.resolveIncludes){if(null===o){let t=sg.x.GLSL;o={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:s_.v.GetShadersRepository(t),includesShadersStore:s_.v.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}o.isFragment="fragment"===i,nG.L._ProcessIncludes(a,o,e=>a=e)}s+=a+"\n"}}if(s.length>0){if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{let i=nz.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}0>e.indexOf("g")&&(e+="g");let i=r,n=new RegExp(t,e),a=n.exec(i);for(;null!==a;){let e=s;for(let t=0;t{UnregisterAllMaterialPlugins()});let nW=[],nH=null;function UnregisterAllMaterialPlugins(){nW.length=0,sr.F.OnEventObservable.remove(nH),nH=null}let MaterialPluginBase=class MaterialPluginBase{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new MaterialPluginManager(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;let i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){rb.p4.Clone(()=>e,this)}serialize(){return rb.p4.Serialize(this)}parse(e,t,i){rb.p4.Parse(()=>this,e,t,i)}};(0,rH.gn)([(0,rb.qC)()],MaterialPluginBase.prototype,"name",void 0),(0,rH.gn)([(0,rb.qC)()],MaterialPluginBase.prototype,"priority",void 0),(0,rH.gn)([(0,rb.qC)()],MaterialPluginBase.prototype,"resolveIncludes",void 0),(0,rH.gn)([(0,rb.qC)()],MaterialPluginBase.prototype,"registerForExtraEvents",void 0);let MaterialDetailMapDefines=class MaterialDetailMapDefines extends sn.H{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}};let material_detailMapConfiguration_DetailMapConfiguration=class material_detailMapConfiguration_DetailMapConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new MaterialDetailMapDefines,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=sr.F.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||!i.getCaps().standardDerivatives||!this._texture||!MaterialFlags.DetailTextureEnabled||!!this._texture.isReady()}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&MaterialFlags.DetailTextureEnabled&&this._isEnabled?(so.G.PrepareDefinesForMergedUV(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||!this._texture||!MaterialFlags.DetailTextureEnabled||(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),so.G.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&MaterialFlags.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){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}};(0,rH.gn)([(0,rb.oU)("detailTexture"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"diffuseBlendLevel",void 0),(0,rH.gn)([(0,rb.qC)()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"roughnessBlendLevel",void 0),(0,rH.gn)([(0,rb.qC)()],material_detailMapConfiguration_DetailMapConfiguration.prototype,"bumpLevel",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"normalBlendMethod",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],material_detailMapConfiguration_DetailMapConfiguration.prototype,"isEnabled",void 0);var nX=i(6962);let nY={effect:null,subMesh:null};let StandardMaterialDefines=class StandardMaterialDefines extends sn.H{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_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.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!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.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,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_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){for(let t of["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"])this[t]=t===e}};let standardMaterial_StandardMaterial=class standardMaterial_StandardMaterial extends PushMaterial{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}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}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new rg.Wo(0,0,0),this.diffuseColor=new rg.Wo(1,1,1),this.specularColor=new rg.Wo(1,1,1),this.emissiveColor=new rg.Wo(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new sp.t(16),this._worldViewProjectionMatrix=rm.y3.Zero(),this._globalAmbientColor=new rg.Wo(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new material_detailMapConfiguration_DetailMapConfiguration(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new PrePassConfiguration,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),standardMaterial_StandardMaterial.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),standardMaterial_StandardMaterial.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!standardMaterial_StandardMaterial.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||!!standardMaterial_StandardMaterial.RefractionTextureEnabled&&!!this._refractionTexture&&!!this._refractionTexture.isRenderTarget||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported,this._markAllSubMeshesAsMiscDirty()}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===sr.F.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==sr.F.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(sG.S.GetDefineNames,this._eventInfo),t.materialDefines=new StandardMaterialDefines(this._eventInfo.defineNames));let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();s._needNormals=so.G.PrepareDefinesForLights(r,e,s,!0,this._maxSimultaneousLights,this._disableLighting),so.G.PrepareDefinesForMultiview(r,s);let a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(so.G.PrepareDefinesForPrePass(r,s,this.canRenderToMRT&&!a),so.G.PrepareDefinesForOIT(r,s,a),s._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s._needUVs=!1;for(let e=1;e<=6;++e)s["MAINUV"+e]=!1;if(r.texturesEnabled){if(s.DIFFUSEDIRECTUV=0,s.BUMPDIRECTUV=0,s.AMBIENTDIRECTUV=0,s.OPACITYDIRECTUV=0,s.EMISSIVEDIRECTUV=0,s.SPECULARDIRECTUV=0,s.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===texture_Texture.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,s.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case texture_Texture.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case texture_Texture.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case texture_Texture.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case texture_Texture.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case texture_Texture.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case texture_Texture.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case texture_Texture.CUBIC_MODE:case texture_Texture.INVCUBIC_MODE:default:s.setReflectionMode("REFLECTIONMAP_CUBIC")}s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else s.REFLECTION=!1,s.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&standardMaterial_StandardMaterial.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;so.G.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAX_RHS=r.useRightHandedSystem,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAX_RHS=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube,s.RGBDREFRACTION=this._refractionTexture.isRGBD,s.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha,s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,s.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}s._areFresnelDirty&&(standardMaterial_StandardMaterial.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),so.G.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s,this._applyDecalMapAfterDetailMap),so.G.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),so.G.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(s.isDirty){let i=s._areLightsDisposed;s.markAsProcessed();let a=new EffectFallbacks;s.REFLECTION&&a.addFallback(0,"REFLECTION"),s.SPECULAR&&a.addFallback(0,"SPECULAR"),s.BUMP&&a.addFallback(0,"BUMP"),s.PARALLAX&&a.addFallback(1,"PARALLAX"),s.PARALLAX_RHS&&a.addFallback(1,"PARALLAX_RHS"),s.PARALLAXOCCLUSION&&a.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&a.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&a.addFallback(1,"FOG"),s.POINTSIZE&&a.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&a.addFallback(0,"LOGARITHMICDEPTH"),so.G.HandleFallbacksForShadows(s,a,this._maxSimultaneousLights),s.SPECULARTERM&&a.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&a.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&a.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&a.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&a.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&a.addFallback(4,"FRESNEL"),s.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");let l=[rz.o.PositionKind];s.NORMAL&&l.push(rz.o.NormalKind),s.TANGENT&&l.push(rz.o.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(rz.o.ColorKind),so.G.PrepareAttributesForBones(l,e,s,a),so.G.PrepareAttributesForInstances(l,s),so.G.PrepareAttributesForMorphTargets(l,e,s),so.G.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default",u=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],c=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=a,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=u,this._eventInfo.attributes=l,this._eventInfo.samplers=c,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(sG.S.PrepareEffect,this._eventInfo),PrePassConfiguration.AddUniforms(u),PrePassConfiguration.AddSamplers(c),sv.$&&(sv.$.PrepareUniforms(u,s),sv.$.PrepareSamplers(c,s)),so.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),(0,nX.qx)(u);let _={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,u,d,c,s,l,_));let f=s.toString(),m=t.effect,g=r.getEngine().createEffect(h,{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:f,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},n);if(this._eventInfo.customCode=void 0,g){if(this._onEffectCreatedObservable&&(nY.effect=g,nY.subMesh=t,this._onEffectCreatedObservable.notifyObservers(nY)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,s.markAsUnprocessed(),o=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var r;let s=this.getScene(),n=i.materialDefines;if(!n)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let o=a._forceRebindOnNextCall||this._mustRebind(s,a,t.visibility);so.G.BindBonesParameters(t,a);let l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||a._forceRebindOnNextCall){if(standardMaterial_StandardMaterial.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new rg.Wo(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),so.G.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),so.G.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),so.G.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){let e=this._reflectionTexture;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),so.G.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),so.G.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),so.G.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&standardMaterial_StandardMaterial.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),so.G.BindTextureMatrix(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled){let e=1;if(!this._refractionTexture.isCube&&(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let e=this._refractionTexture;l.updateVector3("vRefractionPosition",e.boundingBoxPosition),l.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",standardMaterial_StandardMaterial.EmissiveTextureEnabled?this.emissiveColor:rg.Wo.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&standardMaterial_StandardMaterial.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&standardMaterial_StandardMaterial.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&standardMaterial_StandardMaterial.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&standardMaterial_StandardMaterial.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&standardMaterial_StandardMaterial.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&standardMaterial_StandardMaterial.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&standardMaterial_StandardMaterial.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&standardMaterial_StandardMaterial.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&standardMaterial_StandardMaterial.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,nX.an)(a,this,s),this.bindEyePosition(a)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&so.G.BindLights(s,t,a,n,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==rN.x.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),so.G.BindFogParameters(s,t,a),n.NUM_MORPH_INFLUENCERS&&so.G.BindMorphTargetParameters(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(r=t.bakedVertexAnimationManager)||void 0===r||r.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&so.G.BindLogDepth(n,a,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),l.update()}getAnimatables(){let e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),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._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),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._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){let e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),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._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){var i,r,s,n,a,o,l,h,u;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._specularTexture)||void 0===o||o.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(u=this._refractionTexture)||void 0===u||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=rb.p4.Clone(()=>new standardMaterial_StandardMaterial(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=rb.p4.Parse(()=>new standardMaterial_StandardMaterial(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),sr.F._parsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return MaterialFlags.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){MaterialFlags.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return MaterialFlags.DetailTextureEnabled}static set DetailTextureEnabled(e){MaterialFlags.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return MaterialFlags.AmbientTextureEnabled}static set AmbientTextureEnabled(e){MaterialFlags.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return MaterialFlags.OpacityTextureEnabled}static set OpacityTextureEnabled(e){MaterialFlags.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return MaterialFlags.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){MaterialFlags.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return MaterialFlags.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){MaterialFlags.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return MaterialFlags.SpecularTextureEnabled}static set SpecularTextureEnabled(e){MaterialFlags.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return MaterialFlags.BumpTextureEnabled}static set BumpTextureEnabled(e){MaterialFlags.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return MaterialFlags.LightmapTextureEnabled}static set LightmapTextureEnabled(e){MaterialFlags.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return MaterialFlags.RefractionTextureEnabled}static set RefractionTextureEnabled(e){MaterialFlags.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return MaterialFlags.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){MaterialFlags.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return MaterialFlags.FresnelEnabled}static set FresnelEnabled(e){MaterialFlags.FresnelEnabled=e}};(0,rH.gn)([(0,rb.oU)("diffuseTexture")],standardMaterial_StandardMaterial.prototype,"_diffuseTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"diffuseTexture",void 0),(0,rH.gn)([(0,rb.oU)("ambientTexture")],standardMaterial_StandardMaterial.prototype,"_ambientTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"ambientTexture",void 0),(0,rH.gn)([(0,rb.oU)("opacityTexture")],standardMaterial_StandardMaterial.prototype,"_opacityTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"opacityTexture",void 0),(0,rH.gn)([(0,rb.oU)("reflectionTexture")],standardMaterial_StandardMaterial.prototype,"_reflectionTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"reflectionTexture",void 0),(0,rH.gn)([(0,rb.oU)("emissiveTexture")],standardMaterial_StandardMaterial.prototype,"_emissiveTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"emissiveTexture",void 0),(0,rH.gn)([(0,rb.oU)("specularTexture")],standardMaterial_StandardMaterial.prototype,"_specularTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"specularTexture",void 0),(0,rH.gn)([(0,rb.oU)("bumpTexture")],standardMaterial_StandardMaterial.prototype,"_bumpTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"bumpTexture",void 0),(0,rH.gn)([(0,rb.oU)("lightmapTexture")],standardMaterial_StandardMaterial.prototype,"_lightmapTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"lightmapTexture",void 0),(0,rH.gn)([(0,rb.oU)("refractionTexture")],standardMaterial_StandardMaterial.prototype,"_refractionTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"refractionTexture",void 0),(0,rH.gn)([(0,rb.n9)("ambient")],standardMaterial_StandardMaterial.prototype,"ambientColor",void 0),(0,rH.gn)([(0,rb.n9)("diffuse")],standardMaterial_StandardMaterial.prototype,"diffuseColor",void 0),(0,rH.gn)([(0,rb.n9)("specular")],standardMaterial_StandardMaterial.prototype,"specularColor",void 0),(0,rH.gn)([(0,rb.n9)("emissive")],standardMaterial_StandardMaterial.prototype,"emissiveColor",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"specularPower",void 0),(0,rH.gn)([(0,rb.qC)("useAlphaFromDiffuseTexture")],standardMaterial_StandardMaterial.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"useAlphaFromDiffuseTexture",void 0),(0,rH.gn)([(0,rb.qC)("useEmissiveAsIllumination")],standardMaterial_StandardMaterial.prototype,"_useEmissiveAsIllumination",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useEmissiveAsIllumination",void 0),(0,rH.gn)([(0,rb.qC)("linkEmissiveWithDiffuse")],standardMaterial_StandardMaterial.prototype,"_linkEmissiveWithDiffuse",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"linkEmissiveWithDiffuse",void 0),(0,rH.gn)([(0,rb.qC)("useSpecularOverAlpha")],standardMaterial_StandardMaterial.prototype,"_useSpecularOverAlpha",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useSpecularOverAlpha",void 0),(0,rH.gn)([(0,rb.qC)("useReflectionOverAlpha")],standardMaterial_StandardMaterial.prototype,"_useReflectionOverAlpha",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useReflectionOverAlpha",void 0),(0,rH.gn)([(0,rb.qC)("disableLighting")],standardMaterial_StandardMaterial.prototype,"_disableLighting",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],standardMaterial_StandardMaterial.prototype,"disableLighting",void 0),(0,rH.gn)([(0,rb.qC)("useObjectSpaceNormalMap")],standardMaterial_StandardMaterial.prototype,"_useObjectSpaceNormalMap",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useObjectSpaceNormalMap",void 0),(0,rH.gn)([(0,rb.qC)("useParallax")],standardMaterial_StandardMaterial.prototype,"_useParallax",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useParallax",void 0),(0,rH.gn)([(0,rb.qC)("useParallaxOcclusion")],standardMaterial_StandardMaterial.prototype,"_useParallaxOcclusion",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useParallaxOcclusion",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"parallaxScaleBias",void 0),(0,rH.gn)([(0,rb.qC)("roughness")],standardMaterial_StandardMaterial.prototype,"_roughness",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"indexOfRefraction",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"invertRefractionY",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"alphaCutOff",void 0),(0,rH.gn)([(0,rb.qC)("useLightmapAsShadowmap")],standardMaterial_StandardMaterial.prototype,"_useLightmapAsShadowmap",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useLightmapAsShadowmap",void 0),(0,rH.gn)([(0,rb.qQ)("diffuseFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_diffuseFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"diffuseFresnelParameters",void 0),(0,rH.gn)([(0,rb.qQ)("opacityFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_opacityFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelAndMiscDirty")],standardMaterial_StandardMaterial.prototype,"opacityFresnelParameters",void 0),(0,rH.gn)([(0,rb.qQ)("reflectionFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_reflectionFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"reflectionFresnelParameters",void 0),(0,rH.gn)([(0,rb.qQ)("refractionFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_refractionFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"refractionFresnelParameters",void 0),(0,rH.gn)([(0,rb.qQ)("emissiveFresnelParameters")],standardMaterial_StandardMaterial.prototype,"_emissiveFresnelParameters",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"emissiveFresnelParameters",void 0),(0,rH.gn)([(0,rb.qC)("useReflectionFresnelFromSpecular")],standardMaterial_StandardMaterial.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsFresnelDirty")],standardMaterial_StandardMaterial.prototype,"useReflectionFresnelFromSpecular",void 0),(0,rH.gn)([(0,rb.qC)("useGlossinessFromSpecularMapAlpha")],standardMaterial_StandardMaterial.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,rH.gn)([(0,rb.qC)("maxSimultaneousLights")],standardMaterial_StandardMaterial.prototype,"_maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],standardMaterial_StandardMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)("invertNormalMapX")],standardMaterial_StandardMaterial.prototype,"_invertNormalMapX",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"invertNormalMapX",void 0),(0,rH.gn)([(0,rb.qC)("invertNormalMapY")],standardMaterial_StandardMaterial.prototype,"_invertNormalMapY",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"invertNormalMapY",void 0),(0,rH.gn)([(0,rb.qC)("twoSidedLighting")],standardMaterial_StandardMaterial.prototype,"_twoSidedLighting",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],standardMaterial_StandardMaterial.prototype,"twoSidedLighting",void 0),(0,rH.gn)([(0,rb.qC)("applyDecalMapAfterDetailMap")],standardMaterial_StandardMaterial.prototype,"_applyDecalMapAfterDetailMap",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],standardMaterial_StandardMaterial.prototype,"applyDecalMapAfterDetailMap",void 0),(0,rH.gn)([(0,rb.qC)()],standardMaterial_StandardMaterial.prototype,"useLogarithmicDepth",null),(0,rv.H)("BABYLON.StandardMaterial",standardMaterial_StandardMaterial),rN.x.DefaultMaterialFactory=e=>new standardMaterial_StandardMaterial("default material",e),r6.B.prototype.createDynamicTexture=function(e,t,i,r){let s=new r5.l(this,r5.S.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?r6.B.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?r6.B.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},r6.B.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n=!1,a=!1){if(!e)return;let o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let u=this._getWebGLTextureType(e.type),c=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,c);o.texImage2D(l,0,d,c,u,t),e.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),e.isReady=!0};let DynamicTexture=class DynamicTexture extends texture_Texture{constructor(e,t,i=null,r=!1,s=3,n=5,a){super(null,i,!r,a,s,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let o=this._getEngine();if(!o)return;t.getContext?(this._canvas=t,this._texture=o.createDynamicTexture(t.width,t.height,r,s)):(this._canvas=o.createCanvas(1,1),t.width||0===t.width?this._texture=o.createDynamicTexture(t.width,t.height,r,s):this._texture=o.createDynamicTexture(t,t,r,s));let l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(){let e=this.getSize();this._context.fillRect(0,0,e.width,e.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,n,a,o=!0){let l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){let i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){let e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),o&&this.update(a)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new DynamicTexture(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){let e=this.getScene();e&&!e.isReady()&&rT.Y.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return DynamicTexture._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}};let WebXRLayerWrapper=class WebXRLayerWrapper{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){this.isFixedFoveationSupported&&(this.layer.fixedFoveation=Math.max(0,Math.min(1,e||0)))}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.createRenderTargetTextureProvider=s}};var nj=i(5342);let WebXRLayerRenderTargetTextureProvider=class WebXRLayerRenderTargetTextureProvider{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=[],this._engine=e.getEngine()}_createInternalTexture(e,t){let i=new r5.l(this._engine,r5.S.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new nj.B(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,n){if(!this._engine)throw Error("Engine is disposed");let a={width:e,height:t},o=n?new MultiviewRenderTarget(this._scene,a):new renderTargetTexture_RenderTargetTexture("XR renderTargetTexture",a,this._scene),l=o.renderTarget;if(l._samples=o.samples,(i||!r)&&(l._framebuffer=i),r){if(n)l._colorTextureArray=r;else{let e=this._createInternalTexture(a,r);l.setTexture(e,0),o._texture=e}}return s&&(n?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(a,s)),o.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(o.skipInitialClear=!0),this._renderTargetTextures.push(o),o}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.length=0}};let WebXRWebGLLayerWrapper=class WebXRWebGLLayerWrapper extends WebXRLayerWrapper{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new WebXRWebGLLayerRenderTargetTextureProvider(e.scene,this)),this.layer=e}};let WebXRWebGLLayerRenderTargetTextureProvider=class WebXRWebGLLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){let i=this._layer.getViewport(t);if(!i)return!1;let r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){let t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}};let WebXRManagedOutputCanvasOptions=class WebXRManagedOutputCanvasOptions{static GetDefaults(e){let t=new WebXRManagedOutputCanvasOptions;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}};let WebXRManagedOutputCanvas=class WebXRManagedOutputCanvas{constructor(e,t=WebXRManagedOutputCanvasOptions.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new rf.y$,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{let e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add(()=>{this._addCanvas()}),e.onXRSessionEnded.add(()=>{this._removeCanvas()})}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){let createLayer=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new WebXRWebGLLayerWrapper(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{rW.w1.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>createLayer()):Promise.resolve(createLayer())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(()=>{this._setCanvasSize(!0)})}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}};let NativeXRLayerWrapper=class NativeXRLayerWrapper extends WebXRLayerWrapper{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new NativeXRLayerRenderTargetTextureProvider(e,this)),this.layer=e}};let NativeXRLayerRenderTargetTextureProvider=class NativeXRLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}};let NativeXRRenderTarget=class NativeXRRenderTarget{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}};let WebXRSessionManager=class WebXRSessionManager{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new rf.y$,this.onXRReferenceSpaceChanged=new rf.y$,this.onXRSessionEnded=new rf.y$,this.onXRSessionInit=new rf.y$,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch(()=>{rT.Y.Warn("Could not end XR session.")})):Promise.resolve()}trySetViewportForView(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){let t=this.scene.getEngine();return this._xrNavigator.xr.native?new NativeXRRenderTarget(this):((e=e||WebXRManagedOutputCanvasOptions.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new WebXRManagedOutputCanvas(this,e))}initializeAsync(){return(this._xrNavigator=navigator,this._xrNavigator.xr)?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then(t=>(this.session=t,this._sessionMode=e,this.onXRSessionInit.notifyObservers(t),this.inXRSession=!0,this.session.addEventListener("end",()=>{var e;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&(null===(e=this._baseLayerRTTProvider)||void 0===e||e.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return WebXRSessionManager.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{var i;this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then(e=>e,e=>(rT.Y.Error("XR.requestReferenceSpace failed for the following reason: "),rT.Y.Error(e),rT.Y.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(e=>{let t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)},e=>{throw rT.Y.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))).then(e=>this.session.requestReferenceSpace("viewer").then(t=>(this.viewerReferenceSpace=t,e))).then(e=>(this.referenceSpace=this.baseReferenceSpace=e,this.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new NativeXRLayerWrapper(e.baseLayer):new WebXRWebGLLayerWrapper(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);let t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(e=>Promise.resolve(void 0===e||e)).catch(e=>(rT.Y.Warn(e),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e}get currentFrameRate(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate}get supportedFrameRates(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():(this.inXRSession||!t)&&this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null}set fixedFoveation(e){this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=Math.max(0,Math.min(1,e||0)))}get enabledFeatures(){var e,t;return null!==(t=null===(e=this.session)||void 0===e?void 0:e.enabledFeatures)&&void 0!==t?t:null}};(M=tw||(tw={}))[M.ENTERING_XR=0]="ENTERING_XR",M[M.EXITING_XR=1]="EXITING_XR",M[M.IN_XR=2]="IN_XR",M[M.NOT_IN_XR=3]="NOT_IN_XR",(D=tU||(tU={}))[D.NOT_TRACKING=0]="NOT_TRACKING",D[D.TRACKING_LOST=1]="TRACKING_LOST",D[D.TRACKING=2]="TRACKING",rV.Kj._GroundMeshParser=(e,t)=>GroundMesh.Parse(e,t);let GroundMesh=class GroundMesh extends rV.Kj{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),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=rm.jp.Matrix[5];i.invertToRef(r);let s=rm.jp.Vector3[8];if(rm.P.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return rm.P.TransformCoordinatesFromFloatsToRef(0,a,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new rm.P(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=rm.jp.Matrix[5];r.invertToRef(s);let n=rm.jp.Vector3[8];if(rm.P.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t);return rm.P.TransformNormalFromFloatsToRef(a.x,a.y,a.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];return te.maxHeight){h=!0;let t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){let r=new rm.P(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),u=(r.x+e.width/2)/e.width*(e.bufferWidth-1)|0,c=(1-(r.z+e.height/2)/e.height)*(e.bufferHeight-1)|0,d=(u+c*e.bufferWidth)*4,p=e.buffer[d]/255,_=e.buffer[d+1]/255,f=e.buffer[d+2]/255,m=e.buffer[d+3]/255;h&&(p=1-p,_=1-_,f=1-f);let g=p*o.r+_*o.g+f*o.b;m>=l?r.y=e.minHeight+(e.maxHeight-e.minHeight)*g:r.y=e.minHeight-rw.kn,s.push(r.x,r.y,r.z),n.push(0,0,0),a.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t=e.minHeight,u=s[3*a+1]>=e.minHeight,c=s[3*o+1]>=e.minHeight;h&&u&&c&&(r.push(n),r.push(a),r.push(o));let d=s[3*l+1]>=e.minHeight;d&&h&&c&&(r.push(l),r.push(n),r.push(o))}se.x.ComputeNormals(s,r,n);let u=new se.x;return u.indices=r,u.positions=s,u.normals=n,u.uvs=a,u}function CreateGround(e,t={},i){let r=new GroundMesh(e,i);r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ;let s=CreateGroundVertexData(t);return s.applyToMesh(r,t.updatable),r._setReady(!0),r}function CreateTiledGround(e,t,i=null){let r=new rV.Kj(e,i),s=CreateTiledGroundVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateGroundFromHeightMap(e,t,i={},r=null){let s=i.width||10,n=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new rg.Wo(.3,.59,.11),u=i.alphaFilter||0,c=i.updatable,d=i.onReady;r=r||rS.l.LastCreatedScene;let p=new GroundMesh(e,r);return p._subdivisionsX=a,p._subdivisionsY=a,p._width=s,p._height=n,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1),rW.w1.LoadImage(t,e=>{let t=e.width,i=e.height;if(r.isDisposed)return;let _=null==r?void 0:r.getEngine().resizeImageBitmap(e,t,i),f=CreateGroundFromHeightMapVertexData({width:s,height:n,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:h,buffer:_,bufferWidth:t,bufferHeight:i,alphaFilter:u});f.applyToMesh(p,c),d&&d(p),p._setReady(!0)},()=>{},r.offlineProvider),p}function CreateTorusVertexData(e){let t=[],i=[],r=[],s=[],n=e.diameter||1,a=e.thickness||.5,o=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,h=o+1;for(let e=0;e<=o;e++){let l=e/o,u=e*Math.PI*2/o-Math.PI/2,c=rm.y3.Translation(n/2,0,0).multiply(rm.y3.RotationY(u));for(let n=0;n<=o;n++){let u=1-n/o,d=n*Math.PI*2/o+Math.PI,p=Math.cos(d),_=Math.sin(d),f=new rm.P(p,_,0),m=f.scale(a/2),g=new rm.FM(l,u);m=rm.P.TransformCoordinates(m,c),f=rm.P.TransformNormal(f,c),i.push(m.x,m.y,m.z),r.push(f.x,f.y,f.z),s.push(g.x,r4.e.UseOpenGLOrientationForUV?1-g.y:g.y);let v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}se.x._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);let u=new se.x;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function CreateTorus(e,t={},i){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateTorusVertexData(t);return s.applyToMesh(r,t.updatable),r}se.x.CreateGround=CreateGroundVertexData,se.x.CreateTiledGround=CreateTiledGroundVertexData,se.x.CreateGroundFromHeightMap=CreateGroundFromHeightMapVertexData,rV.Kj.CreateGround=(e,t,i,r,s,n)=>CreateGround(e,{width:t,height:i,subdivisions:r,updatable:n},s),rV.Kj.CreateTiledGround=(e,t,i,r,s,n,a,o,l)=>CreateTiledGround(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:n,precision:a,updatable:l},o),rV.Kj.CreateGroundFromHeightMap=(e,t,i,r,s,n,a,o,l,h,u)=>CreateGroundFromHeightMap(e,t,{width:i,height:r,subdivisions:s,minHeight:n,maxHeight:a,updatable:l,onReady:h,alphaFilter:u},o),se.x.CreateTorus=CreateTorusVertexData,rV.Kj.CreateTorus=(e,t,i,r,s,n,a)=>CreateTorus(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:a,updatable:n},s);let VRExperienceHelperGazer=class VRExperienceHelperGazer{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=VRExperienceHelperGazer._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=CreateTorus("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;let t=new standardMaterial_StandardMaterial("targetMat",e);t.specularColor=rg.Wo.Black(),t.emissiveColor=new rg.Wo(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new ray_Ray(rm.P.Zero(),new rm.P(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}};VRExperienceHelperGazer._IdCounter=0;let VRExperienceHelperCameraGazer=class VRExperienceHelperCameraGazer extends VRExperienceHelperGazer{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){let t=this._getCamera();return t?t.getForwardRay(e):new ray_Ray(rm.P.Zero(),rm.P.Forward())}};let VRExperienceHelper=class VRExperienceHelper{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new rf.y$,this.onAfterEnteringVRObservable=new rf.y$,this.onExitingVRObservable=new rf.y$,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new rm.P(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new rm.P(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new rg.Wo(.2,.2,1),this._pickedGazeColor=new rg.Wo(0,0,1),this.onNewMeshSelected=new rf.y$,this.onNewMeshPicked=new rf.y$,this.onBeforeCameraTeleport=new rf.y$,this.onAfterCameraTeleport=new rf.y$,this.onSelectedMeshUnselected=new rf.y$,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==Gamepad.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged(e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))}),e.rightStick&&e.onrightstickchanged(e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)}),e.type===Gamepad.XBOX&&(e.onbuttondown(e=>{this._interactionsEnabled&&e===tN.A&&this._cameraGazer._selectionPointerDown()}),e.onbuttonup(e=>{this._interactionsEnabled&&e===tN.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=rm.P.Zero(),this._workingQuaternion=rm._f.Identity(),this._workingMatrix=rm.y3.Identity(),rT.Y.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement();let i="getVRDisplays"in navigator;if(i||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new rm.P(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new DeviceOrientationCamera("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof targetCamera_TargetCamera&&this._scene.activeCamera.rotation)){let e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(rm._f.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?WebXRSessionManager.IsSessionSupportedAsync("immersive-vr").then(i=>{i?(rT.Y.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new VRExperienceHelperCameraGazer(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(e=>{switch(e){case tw.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case tw.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case tw.IN_XR:this._hasEnteredVR=!0;break;case tw.NOT_IN_XR:this._hasEnteredVR=!1}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new VRExperienceHelperCameraGazer(()=>this.currentVRCamera,e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png",t=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";t+=".babylonVRicon.vrdisplaypresenting { display: none; }";let i=document.createElement("style");i.appendChild(document.createTextNode(t)),document.getElementsByTagName("head")[0].appendChild(i),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});let i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},r8.kD.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new CircleEase,this._circleEase.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===r8.kD.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===r8.kD.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===tw.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){let e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){rT.Y.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=rm._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){rT.Y.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===tw.IN_XR&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>(!!this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e)}removeFloorMesh(e){if(!this._floorMeshesCollection)return;let t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){let t=e.floorMeshes||[];if(!t.length){let i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr){t.forEach(e=>{this.xr.teleportation.addFloorMesh(e)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}if(!this.xrTestDone){let waitForXr=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(waitForXr),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(waitForXr);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);let t=new sv.$;t.vignetteColor=new rg.HE(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){(!this._teleportationRequestInitiated||t._teleportationRequestInitiated)&&(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated){if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;let e=rm._f.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,rm._f.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),rm.P.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);let r=new ray_Ray(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}}_createTeleportationCircles(){this._teleportationTarget=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;let e=new DynamicTexture("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;let t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();let i=new standardMaterial_StandardMaterial("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;let r=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;let s=new animation_Animation("animationInnerCircle","position.y",30,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),s.setKeys(n);let a=new SineEase;a.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),s.setEasingFunction(a),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof FreeCamera))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];let t=rm._f.FromRotationMatrix(rm.y3.RotationY(Math.PI/4*this._rotationAngle)),i=new animation_Animation("animationRotation","rotationQuaternion",90,animation_Animation.ANIMATIONTYPE_QUATERNION,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];let s=new animation_Animation("animationPP","vignetteWeight",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),s.setKeys(n),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);let a=new animation_Animation("animationPP2","vignetteStretch",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:10}),o.push({frame:6,value:0}),a.setKeys(o),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){let t,i;if(!(this.currentVRCamera instanceof FreeCamera))return;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED){i=90;let e=rm.P.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];let r=new animation_Animation("animationCameraTeleportation","position",90,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];let n=Math.round(i/2),a=new animation_Animation("animationPP","vignetteWeight",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:n,value:8}),o.push({frame:i,value:0}),a.setKeys(o),this._postProcessMove.animations.push(a);let l=new animation_Animation("animationPP2","vignetteStretch",90,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){if(!this.updateControllerLaserColor)return}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}};VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME=0,VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED=1;let intersectBoxAASphere=(e,t,i,r)=>!(e.x>i.x+r)&&!(i.x-r>t.x)&&!(e.y>i.y+r)&&!(i.y-r>t.y)&&!(e.z>i.z+r)&&!(i.z-r>t.z),nq=function(){let e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;let n=i*i-4*t*r;if(n<0)return e;let a=Math.sqrt(n),o=(-i-a)/(2*t),l=(-i+a)/(2*t);if(o>l){let e=l;l=o,o=e}return o>0&&o0&&l=0))}_canDoCollision(e,t,i,r){let s=rm.P.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+n+t)&&!!intersectBoxAASphere(i,r,this._basePointWorld,this._velocityWorldLength+n)}_testTriangle(e,t,i,r,s,n,a){let o;let l=!1;t||(t=[]),t[e]||(t[e]=new r2.J(0,0,0,0),t[e].copyFromPoints(i,r,s));let h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;let u=h.signedDistanceTo(this._basePoint),c=rm.P.Dot(h.normal,this._velocity);if(Collider.DoubleSidedCheck&&c>1e-4)return;if(0==c){if(Math.abs(u)>=1)return;l=!0,o=0}else{o=(-1-u)/c;let e=(1-u)/c;if(o>e){let t=e;e=o,o=t}if(o>1||e<0)return;o<0&&(o=0),o>1&&(o=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,p=1;if(!l&&(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(o,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,p=o,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*rm.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,a=nq(e,t,n,p);a.found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),(a=nq(e,t=2*rm.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),(a=nq(e,t=2*rm.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let o=this._edge.lengthSquared(),l=rm.P.Dot(this._edge,this._velocity),h=rm.P.Dot(this._edge,this._baseToVertex);if((a=nq(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rm.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=rm.P.Dot(this._edge,this._velocity),h=rm.P.Dot(this._edge,this._baseToVertex),(a=nq(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rm.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=rm.P.Dot(this._edge,this._velocity),h=rm.P.Dot(this._edge,this._baseToVertex),(a=nq(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rm.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){let e=p*p*this._velocitySquaredLength;(!this.collisionFound||e=r){s.copyFrom(e);return}let o=n?n.collisionMask:i.collisionMask;i._initialize(e,t,a);let l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew DefaultCollisionCoordinator,i(5790);let ComputeEffect=class ComputeEffect{constructor(e,t,i,r=""){var s,n;let a;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new rf.y$,this.onErrorObservable=new rf.y$,this.onBindObservable=new rf.y$,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=sg.x.WGSL,this.name=e,this._key=r,this._engine=i,this.uniqueId=ComputeEffect._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(n=t.entryPoint)&&void 0!==n?n:"main",this._shaderStore=s_.v.GetShadersStore(this._shaderLanguage),this._shaderRepository=s_.v.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=s_.v.GetIncludesShadersStore(this._shaderLanguage);let o=(0,rK.CG)()?this._engine.getHostDocument():null;e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=o?o.getElementById(e.computeElement):null)||(a=e.computeElement):a=e.compute||e;let l={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(a,"Compute","",i=>{nG.L.Initialize(l),nG.L.PreProcess(i,l,r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));let s=nG.L.Finalize(r,"",l);this._useFinalCode(s.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){let i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){let t=(0,rK.v)(e);r(t);return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){let t=window.atob(e.substr(7));r(t);return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getComputeShaderCode())&&void 0!==t?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){let e=this.defines,t=this._pipelineContext;this._isReady=!1;try{let i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,()=>{this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)}),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t){let i=null;if(t&&e){let r=t.match(/COMPUTE SHADER ERROR: 0:(\d+?):/);if(r&&2===r.length){let t=parseInt(r[1]),s=e.split("\n",-1);s.length>=t&&(i=`Offending line [${t}] in compute code: ${s[t-1]}`)}}return[e,i]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,rT.Y.Error("Unable to compile compute effect:"),rT.Y.Error("Defines:\n"+this.defines),ComputeEffect.LogShaderCodeOnCompilationError){let e=null,t=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getComputeShaderCode())&&([t,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),t&&(rT.Y.Error("Compute code:"),rT.Y.Error(t))),e&&rT.Y.Error(e)}rT.Y.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){s_.v.GetShadersStore(sg.x.WGSL)[`${e}ComputeShader`]=t}};ComputeEffect._UniqueIdSeed=0,ComputeEffect.LogShaderCodeOnCompilationError=!0,(O=tV||(tV={}))[O.Texture=0]="Texture",O[O.StorageTexture=1]="StorageTexture",O[O.UniformBuffer=2]="UniformBuffer",O[O.StorageBuffer=3]="StorageBuffer",O[O.TextureWithoutSampler=4]="TextureWithoutSampler",O[O.Sampler=5]="Sampler",O[O.ExternalTexture=6]="ExternalTexture",r6.B.prototype.createComputeEffect=function(e,t){throw Error("createComputeEffect: This engine does not support compute shaders!")},r6.B.prototype.createComputePipelineContext=function(){throw Error("createComputePipelineContext: This engine does not support compute shaders!")},r6.B.prototype.createComputeContext=function(){},r6.B.prototype.computeDispatch=function(e,t,i,r,s,n,a){throw Error("computeDispatch: This engine does not support compute shaders!")},r6.B.prototype.areAllComputeEffectsReady=function(){return!0},r6.B.prototype.releaseComputeEffects=function(){},r6.B.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},r6.B.prototype._rebuildComputeEffects=function(){},r6.B.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},r6.B.prototype._releaseComputeEffect=function(e){},r6.B.prototype._deleteComputePipelineContext=function(e){};var nK=i(7584);let ComputeShader=class ComputeShader{get options(){return this._options}get shaderPath(){return this._shaderPath}constructor(e,t,i,r={}){if(this._bindings={},this._samplers={},this._contextIsDirty=!1,this.onCompiled=null,this.onError=null,this.name=e,this._engine=t,this.uniqueId=sa.K.UniqueId,!this._engine.getCaps().supportComputeShaders){rT.Y.Error("This engine does not support compute shaders!");return}if(!r.bindingsMapping){rT.Y.Error("You must provide the binding mappings as browsers don't support reflection for wgsl shaders yet!");return}this._context=t.createComputeContext(),this._shaderPath=i,this._options=Object.assign({bindingsMapping:{},defines:[]},r)}getClassName(){return"ComputeShader"}setTexture(e,t,i=!0){let r=this._bindings[e];this._bindings[e]={type:i?tV.Texture:tV.TextureWithoutSampler,object:t,indexInGroupEntries:null==r?void 0:r.indexInGroupEntries},this._contextIsDirty||(this._contextIsDirty=!r||r.object!==t||r.type!==this._bindings[e].type)}setStorageTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tV.StorageTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setExternalTexture(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tV.ExternalTexture,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setVideoTexture(e,t){return!!t.externalTexture&&(this.setExternalTexture(e,t.externalTexture),!0)}setUniformBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tV.UniformBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setStorageBuffer(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||i.object!==t),this._bindings[e]={type:tV.StorageBuffer,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}setTextureSampler(e,t){let i=this._bindings[e];this._contextIsDirty||(this._contextIsDirty=!i||!t.compareSampler(i.object)),this._bindings[e]={type:tV.Sampler,object:t,indexInGroupEntries:null==i?void 0:i.indexInGroupEntries}}isReady(){let e=this._effect;for(let e in this._bindings){let t=this._bindings[e],i=t.type,r=t.object;switch(i){case tV.Texture:case tV.TextureWithoutSampler:case tV.StorageTexture:case tV.ExternalTexture:if(!r.isReady())return!1}}let t=[],i=this._shaderPath;if(this._options.defines)for(let e=0;e{let check=()=>{this.dispatch(e,t,i)?s():setTimeout(check,r)};check()})}serialize(){let e=rb.p4.Serialize(this);for(let t in e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={},this._bindings){let i=this._bindings[t],r=i.object;switch(i.type){case tV.Texture:case tV.TextureWithoutSampler:case tV.StorageTexture:{let s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type})}case tV.UniformBuffer:}}return e}static Parse(e,t,i){let r=rb.p4.Parse(()=>new ComputeShader(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(let s in e.textures){let n=e.bindings[s],a=texture_Texture.Parse(e.textures[s],t,i);n.type===tV.Texture?r.setTexture(s,a):n.type===tV.TextureWithoutSampler?r.setTexture(s,a,!1):r.setStorageTexture(s,a)}return r}};(0,rH.gn)([(0,rb.qC)()],ComputeShader.prototype,"name",void 0),(0,rv.H)("BABYLON.ComputeShader",ComputeShader);var n$=i(4347),nQ=i(5681),nZ=i(3592);let OctreeBlock=class OctreeBlock{constructor(e,t,i,r,s,n){this.entries=[],this._boundingVectors=[],this._capacity=i,this._depth=r,this._maxDepth=s,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{let i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},Octree.CreationFuncForSubMeshes=(e,t)=>{let i=e.getBoundingInfo();i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},rN.x.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(rQ.l.NAME_OCTREE);i||(i=new OctreeSceneComponent(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new Octree(Octree.CreationFuncForMeshes,e,t));let r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(rN.x.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),rG.x.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){let i=this.getScene(),r=i._getComponent(rQ.l.NAME_OCTREE);r||(r=new OctreeSceneComponent(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new Octree(Octree.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);let s=this.getBoundingInfo(),n=s.boundingBox;return this._submeshesOctree.update(n.minimumWorld,n.maximumWorld,this.subMeshes),this._submeshesOctree};let OctreeSceneComponent=class OctreeSceneComponent{constructor(e){if(this.name=rQ.l.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new ray_Ray(rm.P.Zero(),new rm.P(1,1,1)),!(e=e||rS.l.LastCreatedScene))return;this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t)}register(){this.scene.onMeshRemovedObservable.add(e=>{let t=this.scene.selectionOctree;if(null!=t){let i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{let t=this.scene.selectionOctree;null!=t&&t.addMesh(e)})}getActiveMeshCandidates(){var e;return(null===(e=this.scene._selectionOctree)||void 0===e?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){if(e._submeshesOctree&&e.useOctreeForRenderingSelection){let t=e._submeshesOctree.select(this.scene.frustumPlanes);return t}return this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForPicking){ray_Ray.TransformToRef(t,e.getWorldMatrix(),this._tempRay);let i=e._submeshesOctree.intersectsRay(this._tempRay);return i}return this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){let i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z),r=e._submeshesOctree.intersects(t._basePointWorld,i);return r}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}};function CreateCylinderVertexData(e){let t,i,r,s,n,a,o;let l=e.height||2,h=0===e.diameterTop?0:e.diameterTop||e.diameter||1,u=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;h=h||1e-5,u=u||1e-5;let c=0|(e.tessellation||24),d=0|(e.subdivisions||1),p=!!e.hasRings,_=!!e.enclose,f=0===e.cap?0:e.cap||rV.Kj.CAP_ALL,m=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,g=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,v=e.faceUV||[,,,],x=e.faceColors,T=2+(1+(1!==m&&_?2:0))*(p?d:1);for(t=0;t{let t,i,r;let s=e?h/2:u/2;if(0===s)return;let n=e?v[T-1]:v[0],a=null;x&&(a=e?x[T-1]:x[0]);let o=C.length/3,d=e?l/2:-l/2,p=new rm.P(0,d,0);C.push(p.x,p.y,p.z),E.push(0,e?1:-1,0);let _=n.y+(n.w-n.y)*.5;b.push(n.x+(n.z-n.x)*.5,r4.e.UseOpenGLOrientationForUV?1-_:_),a&&y.push(a.r,a.g,a.b,a.a);let f=new rm.FM(.5,.5);for(r=0;r<=c;r++){t=2*Math.PI*r*m/c;let o=Math.cos(-t),l=Math.sin(-t);i=new rm.P(o*s,d,l*s);let h=new rm.FM(o*f.x+.5,l*f.y+.5);C.push(i.x,i.y,i.z),E.push(0,e?1:-1,0);let u=n.y+(n.w-n.y)*h.y;b.push(n.x+(n.z-n.x)*h.x,r4.e.UseOpenGLOrientationForUV?1-u:u),a&&y.push(a.r,a.g,a.b,a.a)}for(r=0;r{void 0!==a&&a instanceof rN.x||(void 0!==a&&(l=o||rV.Kj.DEFAULTSIDE,o=a),a=n,n=1);let h={height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:n,sideOrientation:l,updatable:o};return cylinderBuilder_CreateCylinder(e,h,a)},ry.N.AddNodeConstructor("Light_Type_3",(e,t)=>()=>new HemisphericLight(e,rm.P.Zero(),t));let HemisphericLight=class HemisphericLight extends light_Light{constructor(e,t,i){super(e,i),this.groundColor=new rg.Wo(0,0,0),this.direction=t||rm.P.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=rm.P.Normalize(e.subtract(rm.P.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=rm.P.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){let i=rm.P.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=rm.y3.Identity()),this._worldMatrix}getTypeID(){return light_Light.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}};(0,rH.gn)([(0,rb.n9)()],HemisphericLight.prototype,"groundColor",void 0),(0,rH.gn)([(0,rb.hd)()],HemisphericLight.prototype,"direction",void 0);let utilityLayerRenderer_UtilityLayerRenderer=class utilityLayerRenderer_UtilityLayerRenderer{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return(t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera)?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new HemisphericLight("shared gizmo light",new rm.P(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=rg.Wo.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer?utilityLayerRenderer_UtilityLayerRenderer._CreateDefaultUtilityLayerFromScene(rS.l.LastCreatedScene):utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(e),utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=null}),utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer&&(utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=new utilityLayerRenderer_UtilityLayerRenderer(rS.l.LastCreatedScene),utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=null})),utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new rf.y$,this.utilityLayerScene=new rN.x(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(t=>{if(!this.utilityLayerScene.activeCamera||!this.pickingEnabled||!this.processAllEvents&&t.type!==r8.kD.POINTERMOVE&&t.type!==r8.kD.POINTERUP&&t.type!==r8.kD.POINTERDOWN&&t.type!==r8.kD.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;let i=t.event;if(e.isPointerCaptured(i.pointerId)){this._pointerCaptures[i.pointerId]=!1;return}let getNearPickDataForScene=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new r7.p;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},r=getNearPickDataForScene(this.utilityLayerScene);if(!t.ray&&r&&(t.ray=r.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=r8.kD.POINTERDOWN){t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new r8.R5(t.type,t.event,r),t.type),t.type===r8.kD.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)r&&r.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new r8.R5(t.type,t.event,r),t.type),t.skipOnPointerObservable=!0);else{let i=getNearPickDataForScene(e),s=t.event;i&&r&&(0===r.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):t.type===r8.kD.POINTERDOWN?this._pointerCaptures[s.pointerId]=!0:(t.type===r8.kD.POINTERMOVE||t.type===r8.kD.POINTERUP)&&(this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,i,s)):!this._pointerCaptures[s.pointerId]&&(r.distance0)):!this._pointerCaptures[s.pointerId]&&r.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,s),t.skipOnPointerObservable=!0):((t.type===r8.kD.POINTERMOVE||t.type===r8.kD.POINTERUP)&&this._lastPointerEvents[s.pointerId]&&(this.onPointerOutObservable.notifyObservers(s.pointerId),delete this._lastPointerEvents[s.pointerId]),this._notifyObservers(t,r,s))),t.type===r8.kD.POINTERUP&&this._pointerCaptures[s.pointerId]&&(this._pointerCaptures[s.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new r8.R5(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){let e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}};utilityLayerRenderer_UtilityLayerRenderer._DefaultUtilityLayer=null,utilityLayerRenderer_UtilityLayerRenderer._DefaultKeepDepthUtilityLayer=null,(N=tk||(tk={}))[N.Origin=0]="Origin",N[N.Pivot=1]="Pivot",(F=tG||(tG={}))[F.World=0]="World",F[F.Local=1]="Local";let gizmo_Gizmo=class gizmo_Gizmo{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach(e=>{e.dispose()}),e.parent=this._rootMesh,this._customMeshSet=!0}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;let t=e==tG.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=tk.Origin,this._updateScale=!0,this._coordinatesMode=tG.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=rm.y3.RotationY(Math.PI),this._rootMesh=new rV.Kj("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=rm._f.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(()=>{this._update()})}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh){if(this.anchorPoint==tk.Pivot&&e.getAbsolutePivotPoint){let t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{let t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new rm.P(0,0,0);this._rootMesh.position.copyFrom(i)}}if(this.updateGizmoRotationToMatchAttachedMesh){let t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName(),i=t?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,gizmo_Gizmo.PreserveScaling?i:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){let t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,rm.jp.Vector3[0]);let r=this.scaleRatio;if(t.mode==rj.V.ORTHOGRAPHIC_CAMERA){if(t.orthoTop&&t.orthoBottom){let e=t.orthoTop-t.orthoBottom;r*=e}}else{let e=t.getScene().useRightHandedSystem?rm.P.RightHandedForwardReadOnly:rm.P.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=rm.P.Dot(rm.jp.Vector3[0],i)}this._rootMesh.scaling.setAll(r),0>e._getWorldMatrixDeterminant()&&!gizmo_Gizmo.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_matrixChanged(){if(this._attachedNode){if(this._attachedNode._isCamera){let e,t;let i=this._attachedNode;if(i.parent){let t=rm.jp.Matrix[1];i.parent._worldMatrix.invertToRef(t),this._attachedNode._worldMatrix.multiplyToRef(t,rm.jp.Matrix[0]),e=rm.jp.Matrix[0]}else e=this._attachedNode._worldMatrix;i.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(e,rm.jp.Matrix[1]),t=rm.jp.Matrix[1]):t=e,t.decompose(rm.jp.Vector3[1],rm.jp.Quaternion[0],rm.jp.Vector3[0]);let r="FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName();if(r){let e=this._attachedNode;e.rotation=rm.jp.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(rm.jp.Quaternion[0]),e.rotationQuaternion.normalize())}i.position.copyFrom(rm.jp.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){let e=this._attachedNode;if(e.parent){let t=rm.jp.Matrix[0],i=rm.jp.Matrix[1];if(e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i),i.decompose(rm.jp.Vector3[0],rm.jp.Quaternion[0],e.position),rm.jp.Quaternion[0].normalize(),e.isUsingPivotMatrix()){let t=rm.jp.Quaternion[1];rm._f.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);let i=rm.jp.Matrix[2];rm.y3.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);let r=rm.jp.Matrix[2];t.toRotationMatrix(r);let s=e.getPivotMatrix(),n=rm.jp.Matrix[3];s.invertToRef(n),s.multiplyToRef(i,rm.jp.Matrix[4]),rm.jp.Matrix[4].multiplyToRef(r,rm.jp.Matrix[5]),rm.jp.Matrix[5].multiplyToRef(n,rm.jp.Matrix[6]),rm.jp.Matrix[6].getTranslationToRef(rm.jp.Vector3[1]),e.position.subtractInPlace(rm.jp.Vector3[1])}}else this._attachedNode._worldMatrix.decompose(rm.jp.Vector3[0],rm.jp.Quaternion[0],e.position,gizmo_Gizmo.PreserveScaling?e:void 0);rm.jp.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(rm.jp.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(rm.jp.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=rm.jp.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){let e=this._attachedNode,t=e.getParent();if(t){let i=rm.jp.Matrix[0],r=rm.jp.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r);let s=e.getLocalMatrix();s.copyFrom(r)}else{let t=e.getLocalMatrix();t.copyFrom(e.getFinalMatrix())}e.markAsDirty()}else{let e=this._attachedNode;if(e.getTypeID){let t=e.getTypeID();if(t===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT||t===light_Light.LIGHTTYPEID_SPOTLIGHT||t===light_Light.LIGHTTYPEID_POINTLIGHT){let t=e.parent;if(t){let i=rm.jp.Matrix[0],r=rm.jp.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,rm.jp.Quaternion[0],rm.jp.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,rm.jp.Quaternion[0],rm.jp.Vector3[0]);e.position=new rm.P(rm.jp.Vector3[0].x,rm.jp.Vector3[0].y,rm.jp.Vector3[0].z),e.direction&&(e.direction=new rm.P(e.direction.x,e.direction.y,e.direction.z))}}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach(e=>{e.material=t,e.color&&(e.color=t.diffuseColor)})}static GizmoAxisPointerObserver(e,t){let i=!1,r=e.utilityLayerScene.onPointerObservable.add(e=>{var r,s;if(e.pickInfo){if(e.type===r8.kD.POINTERMOVE){if(i)return;t.forEach(t=>{var i,r;if(t.colliderMeshes&&t.gizmoMeshes){let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,n=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=n,e.color&&(e.color=n.diffuseColor)})}})}if(e.type===r8.kD.POINTERDOWN&&t.has(null===(r=e.pickInfo.pickedMesh)||void 0===r?void 0:r.parent)){i=!0;let r=t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent);r.active=!0,t.forEach(t=>{var i,r;let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,n=(s||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=n,e.color&&(e.color=n.diffuseColor)})})}e.type===r8.kD.POINTERUP&&t.forEach(e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach(t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)})})}});return r}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}};gizmo_Gizmo.PreserveScaling=!1,Object.defineProperty(rN.x.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new DebugLayer(this)),this._debugLayer},enumerable:!0,configurable:!0}),(B=tz||(tz={}))[B.Properties=0]="Properties",B[B.Debug=1]="Debug",B[B.Statistics=2]="Statistics",B[B.Tools=3]="Tools",B[B.Settings=4]="Settings";let DebugLayer=class DebugLayer{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new rf.y$),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new rf.y$),this._onSelectionChangedObservable)}constructor(e){if(this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||rS.l.LastCreatedScene,!this._scene)return;this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(let e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(let e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}let t=Object.assign(Object.assign({},DebugLayer.Config),e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise(t=>{if(void 0===this.BJSINSPECTOR){let i=e&&e.inspectorURL?e.inspectorURL:DebugLayer.InspectorURL;rW.w1.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}};function CreateBoxVertexData(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],i=[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],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1,h=void 0===e.topBaseAt?1:e.topBaseAt,u=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,u=(u+4)%4;let c=[2,0,3,1][h],d=[2,0,1,3][u],p=[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(l){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],p=[-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]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],r=[17,18,19,16],s=[22,23,20,21];for(;c>0;)e.unshift(e.pop()),r.unshift(r.pop()),c--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),p=p.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}let _=[n/2,a/2,o/2];s=p.reduce((e,t,i)=>e.concat(t*_[i%3]),[]);let f=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,m=e.faceUV||Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new rm.Lt(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new rg.HE(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,r4.e.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,r4.e.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,r4.e.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),r.push(m[e].z,r4.e.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);se.x._ComputeSides(f,s,t,i,r,e.frontUVs,e.backUVs);let x=new se.x;if(x.indices=t,x.positions=s,x.normals=i,x.uvs=r,g){let e=f===se.x.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function CreateSegmentedBoxVertexData(e){let t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),a=0|(e.depthSegments||e.segments||1),o=new rm.y3,l=new rm.y3,h=new rm.y3,u=CreateGroundVertexData({width:t,height:r,subdivisionsX:s,subdivisionsY:a});rm.y3.TranslationToRef(0,-i/2,0,l),rm.y3.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),u.transform(h);let c=CreateGroundVertexData({width:t,height:r,subdivisionsX:s,subdivisionsY:a});rm.y3.TranslationToRef(0,i/2,0,h),c.transform(h);let d=CreateGroundVertexData({width:i,height:r,subdivisionsX:n,subdivisionsY:a});rm.y3.TranslationToRef(-t/2,0,0,l),rm.y3.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);let p=CreateGroundVertexData({width:i,height:r,subdivisionsX:n,subdivisionsY:a});rm.y3.TranslationToRef(t/2,0,0,l),rm.y3.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),p.transform(h);let _=CreateGroundVertexData({width:t,height:i,subdivisionsX:s,subdivisionsY:n});rm.y3.TranslationToRef(0,0,-r/2,l),rm.y3.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h);let f=CreateGroundVertexData({width:t,height:i,subdivisionsX:s,subdivisionsY:n});return rm.y3.TranslationToRef(0,0,r/2,l),rm.y3.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h),u.merge([c,p,d,_,f],!0),u}function boxBuilder_CreateBox(e,t={},i=null){let r=new rV.Kj(e,i);t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation;let s=CreateBoxVertexData(t);return s.applyToMesh(r,t.updatable),r}function CreateSphereVertexData(e){let t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,o=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new rm.P(i/2,r/2,s/2),u=2+t,c=2*u,d=[],p=[],_=[],f=[];for(let e=0;e<=u;e++){let t=e/u,i=t*Math.PI*a;for(let e=0;e<=c;e++){let r=e/c,s=r*Math.PI*2*n,a=rm.y3.RotationZ(-i),o=rm.y3.RotationY(s),l=rm.P.TransformCoordinates(rm.P.Up(),a),u=rm.P.TransformCoordinates(l,o),d=u.multiply(h),m=u.divide(h).normalize();p.push(d.x,d.y,d.z),_.push(m.x,m.y,m.z),f.push(r,r4.e.UseOpenGLOrientationForUV?1-t:t)}if(e>0){let t=p.length/3;for(let i=t-2*(c+1);i+c+21&&(d.push(i),d.push(i+1),d.push(i+c+1)),(em?m:Math.floor(g);let v=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,x=e.uvs,T=e.colors,S=[],C=[],E=[],b=[],y=[],P=[],R=[],A=[],I=[],M=[];if(d.length<2){let e=[],t=[];for(r=0;r0&&(o=n[s].subtract(n[s-1]).length()+R[i],y[i].push(o),R[i]=o),s++;_&&(s--,S.push(n[0].x,n[0].y,n[0].z),o=n[s].subtract(n[0]).length()+R[i],y[i].push(o),R[i]=o),I[i]=a+O,M[i]=D,D+=a+O}let N=null,F=null;for(r=0;r{let s=r[0].length,n=0,a=o._originalBuilderSideOrientation===rV.Kj.DOUBLESIDE?2:1;for(let l=1;l<=a;++l)for(let a=0;a1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);let h=2*Math.PI*o,u=1===o?h/a:h/(a-1),c=0;for(let e=0;e0||c>0){switch(m=-d,g=-p,v=d,x=p,s){case rV.Kj.CENTER:l/=2,m-=l,v+=l;break;case rV.Kj.LEFT:v+=l,_=-l/2;break;case rV.Kj.RIGHT:m-=l,_=l/2}switch(n){case rV.Kj.CENTER:c/=2,g-=c,x+=c;break;case rV.Kj.BOTTOM:x+=c,f=-c/2;break;case rV.Kj.TOP:g-=c,f=c/2}}let T=[],S=[],C=[];C[0]=[0,0,1,0,1,1,0,1],C[1]=[0,0,1,0,1,1,0,1],(t===rV.Kj.ROTATE_TILE||t===rV.Kj.ROTATE_ROW)&&(C[1]=[1,1,0,1,0,0,1,0]),(t===rV.Kj.FLIP_TILE||t===rV.Kj.FLIP_ROW)&&(C[1]=[1,0,0,0,0,1,1,1]),(t===rV.Kj.FLIP_N_ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_ROW)&&(C[1]=[0,1,1,1,1,0,0,0]);let E=[],b=[],y=[],P=0;for(let e=0;e0||c>0){let e,a,h,C;let R=c>0&&(n===rV.Kj.CENTER||n===rV.Kj.TOP),A=c>0&&(n===rV.Kj.CENTER||n===rV.Kj.BOTTOM),I=l>0&&(s===rV.Kj.CENTER||s===rV.Kj.RIGHT),M=l>0&&(s===rV.Kj.CENTER||s===rV.Kj.LEFT),D=[];if(R&&I&&(T.push(m+_,g+f,0),T.push(-d+_,g+f,0),T.push(-d+_,g+c+f,0),T.push(m+_,g+c+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,h=1,C=1,D=[e=1-l/i,a=1-c/r,h,a,h,C,e,C],t===rV.Kj.ROTATE_ROW&&(D=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),t===rV.Kj.FLIP_ROW&&(D=[1-e,a,1-h,a,1-h,C,1-e,C]),t===rV.Kj.FLIP_N_ROTATE_ROW&&(D=[e,1-a,h,1-a,h,1-C,e,1-C]),E=E.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R&&M&&(T.push(d+_,g+f,0),T.push(v+_,g+f,0),T.push(v+_,g+c+f,0),T.push(d+_,g+c+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,C=1,D=[e=0,a=1-c/r,h=l/i,a,h,C,e,C],(t===rV.Kj.ROTATE_ROW||t===rV.Kj.ROTATE_TILE&&o%2==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_ROW||t===rV.Kj.FLIP_TILE&&o%2==0)&&(D=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_ROW||t===rV.Kj.FLIP_N_ROTATE_TILE&&o%2==0)&&(D=[e,1-a,h,1-a,h,1-C,e,1-C]),E=E.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),A&&I&&(T.push(m+_,p+f,0),T.push(-d+_,p+f,0),T.push(-d+_,x+f,0),T.push(m+_,x+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,a=0,h=1,D=[e=1-l/i,a,h,a,h,C=c/r,e,C],(t===rV.Kj.ROTATE_ROW&&u%2==1||t===rV.Kj.ROTATE_TILE&&u%1==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_ROW&&u%2==1||t===rV.Kj.FLIP_TILE&&u%2==0)&&(D=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_ROW&&u%2==1||t===rV.Kj.FLIP_N_ROTATE_TILE&&u%2==0)&&(D=[e,1-a,h,1-a,h,1-C,e,1-C]),E=E.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),A&&M&&(T.push(d+_,p+f,0),T.push(v+_,p+f,0),T.push(v+_,x+f,0),T.push(d+_,x+f,0),y.push(P,P+1,P+3,P+1,P+2,P+3),P+=4,D=[e=0,a=0,h=l/i,a,h,C=c/r,e,C],(t===rV.Kj.ROTATE_ROW&&u%2==1||t===rV.Kj.ROTATE_TILE&&(u+o)%2==1)&&(D=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_ROW&&u%2==1||t===rV.Kj.FLIP_TILE&&(u+o)%2==1)&&(D=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_ROW&&u%2==1||t===rV.Kj.FLIP_N_ROTATE_TILE&&(u+o)%2==1)&&(D=[e,1-a,h,1-a,h,1-C,e,1-C]),E=E.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R){let s=[];e=0,a=1-c/r,h=1,C=1,s[0]=[e,a,h,a,h,C,e,C],s[1]=[e,a,h,a,h,C,e,C],(t===rV.Kj.ROTATE_TILE||t===rV.Kj.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-C,1-e,1-C]),(t===rV.Kj.FLIP_TILE||t===rV.Kj.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,C,1-e,C]),(t===rV.Kj.FLIP_N_ROTATE_TILE||t===rV.Kj.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-C,e,1-C]);for(let e=0;ee+E)),E+=x[e].length,i)for(let t=0;t<4;t++)v.push(i[e].r,i[e].g,i[e].b,i[e].a)}let b=new rm.P(0,0,a/2),y=rm.y3.RotationY(Math.PI);_=x[0].map(e=>rm.P.TransformNormal(e,y).add(b)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),f=T[0].map(e=>rm.P.TransformNormal(e,y)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),_=_.concat(x[1].map(e=>e.subtract(b)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[1].map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let P=new rm.P(s/2,0,0),R=rm.y3.RotationY(-Math.PI/2);_=_.concat(x[2].map(e=>rm.P.TransformNormal(e,R).add(P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[2].map(e=>rm.P.TransformNormal(e,R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let A=rm.y3.RotationY(Math.PI/2);_=_.concat(x[3].map(e=>rm.P.TransformNormal(e,A).subtract(P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[3].map(e=>rm.P.TransformNormal(e,A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let I=new rm.P(0,n/2,0),M=rm.y3.RotationX(Math.PI/2);_=_.concat(x[4].map(e=>rm.P.TransformNormal(e,M).add(I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[4].map(e=>rm.P.TransformNormal(e,M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let D=rm.y3.RotationX(-Math.PI/2);_=_.concat(x[5].map(e=>rm.P.TransformNormal(e,D).subtract(I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[5].map(e=>rm.P.TransformNormal(e,D)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),se.x._ComputeSides(c,_,g,f,m);let O=new se.x;if(O.indices=g,O.positions=_,O.normals=f,O.uvs=m,i){let e=c===se.x.DOUBLESIDE?v.concat(v):v;O.colors=e}return O}function CreateTorusKnotVertexData(e){let t,i;let r=[],s=[],n=[],a=[],o=e.radius||2,l=e.tube||.5,h=e.radialSegments||32,u=e.tubularSegments||32,c=e.p||2,d=e.q||3,p=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,getPos=e=>{let t=d/c*e,i=Math.cos(t),r=o*Math.sin(t)*.5;return new rm.P(o*(2+i)*.5*Math.cos(e),o*(2+i)*Math.sin(e)*.5,r)};for(t=0;t<=h;t++){let e=t%h,r=e/h*2*c*Math.PI,n=getPos(r),o=getPos(r+.01),d=o.subtract(n),p=o.add(n),_=rm.P.Cross(d,p);for(p=rm.P.Cross(_,d),_.normalize(),p.normalize(),i=0;iboxBuilder_CreateBox(e,{size:t,sideOrientation:s,updatable:r},i),se.x.CreateSphere=CreateSphereVertexData,rV.Kj.CreateSphere=(e,t,i,r,s,n)=>sphereBuilder_CreateSphere(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:s},r),rV.Kj.CreateCapsule=(e,t,i)=>capsuleBuilder_CreateCapsule(e,t,i),se.x.CreateCapsule=CreateCapsuleVertexData,se.x.CreateRibbon=CreateRibbonVertexData,rV.Kj.CreateRibbon=(e,t,i=!1,r,s,n,a=!1,o,l)=>CreateRibbon(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:a,sideOrientation:o,instance:l},n),se.x.CreateDisc=CreateDiscVertexData,rV.Kj.CreateDisc=(e,t,i,r=null,s,n)=>discBuilder_CreateDisc(e,{radius:t,tessellation:i,sideOrientation:n,updatable:s},r),se.x.CreateTiledPlane=CreateTiledPlaneVertexData,se.x.CreateTiledBox=CreateTiledBoxVertexData,se.x.CreateTorusKnot=CreateTorusKnotVertexData,rV.Kj.CreateTorusKnot=(e,t,i,r,s,n,a,o,l,h)=>CreateTorusKnot(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:n,q:a,sideOrientation:h,updatable:l},o);let nJ={effect:null,subMesh:null};let shaderMaterial_ShaderMaterial=class shaderMaterial_ShaderMaterial extends PushMaterial{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new rm.y3,this._cachedWorldViewProjectionMatrix=new rm.y3,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},r)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return -1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);let i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var r,s,n;let a=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){if(a){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{let e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}}let o=this.getScene(),l=o.getEngine(),h=[],u=[],c=new EffectFallbacks,d=this._shaderPath,p=this._options.uniforms,_=this._options.uniformBuffers,f=this._options.samplers;l.getCaps().multiview&&o.activeCamera&&o.activeCamera.outputRenderTarget&&o.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,h.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e4&&(u.push(rz.o.MatricesIndicesExtraKind),u.push(rz.o.MatricesWeightsExtraKind));let t=e.skeleton;h.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(h.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(h.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else h.push("#define NUM_BONE_INFLUENCERS 0");let m=0,g=e?e.morphTargetManager:null;if(g){let e=g.supportsUVs&&-1!==h.indexOf("#define UV1"),t=g.supportsTangents&&-1!==h.indexOf("#define TANGENT"),i=g.supportsNormals&&-1!==h.indexOf("#define NORMAL");m=g.numInfluencers,e&&h.push("#define MORPHTARGETS_UV"),t&&h.push("#define MORPHTARGETS_TANGENT"),i&&h.push("#define MORPHTARGETS_NORMAL"),m>0&&h.push("#define MORPHTARGETS"),g.isUsingTextureForTargets&&(h.push("#define MORPHTARGETS_TEXTURE"),-1===this._options.uniforms.indexOf("morphTargetTextureIndices")&&this._options.uniforms.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),h.push("#define NUM_MORPH_INFLUENCERS "+m);for(let r=0;r0&&((p=p.slice()).push("morphTargetInfluences"),p.push("morphTargetTextureInfo"),p.push("morphTargetTextureIndices"))}else h.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(h.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===this._options.uniforms.indexOf("bakedVertexAnimationSettings")&&this._options.uniforms.push("bakedVertexAnimationSettings"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTime")&&this._options.uniforms.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),so.G.PrepareAttributesForBakedVertexAnimation(u,e,h)}for(let e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&h.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,nX.qx)(p),(0,nX.lK)(this,o,h)),this.customShaderNameResolve&&(p=p.slice(),_=_.slice(),f=f.slice(),d=this.customShaderNameResolve(d,p,_,f,h,u));let v=a?i._getDrawWrapper():this._drawWrapper,x=null!==(r=null==v?void 0:v.effect)&&void 0!==r?r:null,T=null!==(s=null==v?void 0:v.defines)&&void 0!==s?s:null,S=h.join("\n"),C=x;return T!==S&&(C=l.createEffect(d,{attributes:u,uniformsNames:p,uniformBuffersNames:_,samplers:f,defines:S,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},l),a?i.setEffect(C,S,this._materialContext):v&&v.setEffect(C,S),this._onEffectCreatedObservable&&(nJ.effect=C,nJ.subMesh=null!==(n=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==n?n:null,this._onEffectCreatedObservable.notifyObservers(nJ))),C._wasPreviouslyUsingInstances=!!t,!!(null==C?void 0:C.isReady())&&(x!==C&&o.resetCachedMaterial(),C._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){let i=this.getScene(),r=null!=t?t:this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var r;this.bind(e,t,null===(r=i._drawWrapperOverride)||void 0===r?void 0:r.effect,i)}bind(e,t,i,r){var s;let n=r&&this._storeEffectOnSubMeshes,a=null!=i?i:n?r.effect:this.getEffect();if(!a)return;this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);let o=this._options.uniformBuffers,l=!1;if(a&&o&&o.length>0&&this.getScene().getEngine().supportsUniformBuffers)for(let i=0;i0&&so.G.BindMorphTargetParameters(t,a);let i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._textures)e.push(this._textures[t]);for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;tnew shaderMaterial_ShaderMaterial(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);for(let i in t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach(e=>{let t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))}),this.stencil.copyTo(t.stencil),this._textures)t.setTexture(i,this._textures[i]);for(let e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(let e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(let e in this._ints)t.setInt(e,this._ints[e]);for(let e in this._uints)t.setUInt(e,this._uints[e]);for(let e in this._floats)t.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(let e in this._colors3)t.setColor3(e,this._colors3[e]);for(let e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(let e in this._colors4)t.setColor4(e,this._colors4[e]);for(let e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(let e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(let e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(let e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(let e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(let e in this._matrices)t.setMatrix(e,this._matrices[e]);for(let e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(let e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(let e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(let e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(let e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(let e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(let e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(let e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(let e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){let t=this._textureArrays[e];for(let e=0;enew shaderMaterial_ShaderMaterial(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,texture_Texture.Parse(e.textures[r],t,i));for(r in e.textureArrays){let n=e.textureArrays[r],a=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>rg.Wo.FromArray(e));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,rg.HE.FromArray(e.colors4[r]));for(r in e.colors4Arrays){let t=e.colors4Arrays[r].reduce((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>rg.HE.FromArray(e));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,rm.FM.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,rm.P.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,rm.Lt.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,rm._f.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,rm.y3.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,n)=>{let a=new rP.g;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=this.Parse(t,i||rS.l.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the ShaderMaterial")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,s)=>{let n=new rP.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(s.shaderMaterial),o=this.Parse(a,t||rS.l.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}};shaderMaterial_ShaderMaterial.SnippetUrl="https://snippet.babylonjs.com",shaderMaterial_ShaderMaterial.CreateFromSnippetAsync=shaderMaterial_ShaderMaterial.ParseFromSnippetAsync,(0,rv.H)("BABYLON.ShaderMaterial",shaderMaterial_ShaderMaterial);let n0=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -#define VERTEXCOLOR -varying vec4 vColor; -#else -uniform vec4 color; -#endif -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -gl_FragColor=vColor; -#else -gl_FragColor=color; -#endif -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.colorPixelShader=n0;let n1=`attribute vec3 position; -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include -#include -#include -uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#include -#include -#include -vec4 worldPos=finalWorld*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#include -#include -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.colorVertexShader=n1,rV.Kj._LinesMeshParser=(e,t)=>LinesMesh.Parse(e,t);let LinesMesh=class LinesMesh extends rV.Kj{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,r=null,s,n,a,o){super(e,t,i,r,s),this.useVertexColor=n,this.useVertexAlpha=a,this.color=new rg.Wo(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let l={attributes:[rz.o.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===a?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(rz.o.ColorKind)):(l.uniforms.push("color"),this._color4=new rg.HE),o?this.material=o:(this.material=new shaderMaterial_ShaderMaterial("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=sr.F.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){let{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(sr.F.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(sr.F.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new LinesMesh(e,this.getScene(),t,this,i)}createInstance(e){let t=new InstancedLinesMesh(e,this);if(this.instancedBuffers)for(let e in t.instancedBuffers={},this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e];return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){let i=new LinesMesh(e.name,t);return i.color=rg.Wo.FromArray(e.color),i.alpha=e.alpha,i}};let InstancedLinesMesh=class InstancedLinesMesh extends instancedMesh_InstancedMesh{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}};function CreateLineSystemVertexData(e){let t=[],i=[],r=e.lines,s=e.colors,n=[],a=0;for(let e=0;e0&&(t.push(a-1),t.push(a)),a++}}let o=new se.x;return o.indices=t,o.positions=i,s&&(o.colors=n),o}function CreateDashedLinesVertexData(e){let t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,n=[],a=[],o=rm.P.Zero(),l=0,h=0,u=0,c=0,d=0,p=0,_=0;for(_=0;_{let t=rm.P.Zero(),i=e.length/6,n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0;for(c=0;clinesBuilder_CreateLines(e,{points:t,updatable:r,instance:s},i),rV.Kj.CreateDashedLines=(e,t,i,r,s,n=null,a,o)=>CreateDashedLines(e,{points:t,dashSize:i,gapSize:r,dashNb:s,updatable:a,instance:o},n);let IndexedVector2=class IndexedVector2 extends rm.FM{constructor(e,t){super(e.x,e.y),this.index=t}};let PolygonPoints=class PolygonPoints{constructor(){this.elements=[]}add(e){let t=[];return e.forEach(e=>{let i=new IndexedVector2(e,this.elements.length);t.push(i),this.elements.push(i)}),t}computeBounds(){let e=new rm.FM(this.elements[0].x,this.elements[0].y),t=new rm.FM(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}};let PolygonMeshBuilder=class PolygonMeshBuilder{_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new PolygonPoints,this._outlinepoints=new PolygonPoints,this._holes=[],this._epoints=[],this._eholes=[],this.bjsEarcut=r,this._name=e,this._scene=i||rS.l.LastCreatedScene,s=t instanceof math_path_Path2?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&rT.Y.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new PolygonPoints;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){let r=new rV.Kj(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(rz.o.PositionKind,s.positions,e),r.setVerticesData(rz.o.NormalKind,s.normals,e),r.setVerticesData(rz.o.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new se.x,r=[],s=[],n=[],a=this._points.computeBounds();this._points.elements.forEach(e=>{r.push(0,1,0),s.push(e.x,0,e.y),n.push((e.x-a.min.x)/a.width,(e.y-a.min.y)/a.height)});let o=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){let i=s.length/3;this._points.elements.forEach(t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),n.push(1-(t.x-a.min.x)/a.width,1-(t.y-a.min.y)/a.height)});let l=o.length;for(let e=0;e{this._addSide(s,r,n,o,a,i,e,!0,t)})}return i.indices=o,i.positions=s,i.normals=r,i.uvs=n,i}_addSide(e,t,i,r,s,n,a,o,l){let h=e.length/3,u=0;for(let c=0;cl?Cl?EMath.abs(c[e+1])&&(S=1),.001>Math.abs(c[e+1]-1)&&(S=0),.001>Math.abs(c[e+1]+1)&&(S=2),T=e/3,1===S?((f=T-_)%4<1.5?h?d[2*T]=o[S].x+(o[S].z-o[S].x)*x[Math.floor(f/4)]/v:d[2*T]=o[S].x:h?d[2*T]=o[S].x+(o[S].z-o[S].x)*x[Math.floor(f/4)+1]/v:d[2*T]=o[S].z,f%2==0?d[2*T+1]=r4.e.UseOpenGLOrientationForUV?1-o[S].w:o[S].w:d[2*T+1]=r4.e.UseOpenGLOrientationForUV?1-o[S].y:o[S].y):(d[2*T]=(1-d[2*T])*o[S].x+d[2*T]*o[S].z,d[2*T+1]=(1-d[2*T+1])*o[S].y+d[2*T+1]*o[S].w,r4.e.UseOpenGLOrientationForUV&&(d[2*T+1]=1-d[2*T+1])),r&&l.push(r[S].r,r[S].g,r[S].b,r[S].a);se.x._ComputeSides(t,u,p,c,d,s,n);let C=new se.x;if(C.indices=p,C.positions=u,C.normals=c,C.uvs=d,r){let e=t===se.x.DOUBLESIDE?l.concat(l):l;C.colors=e}return C}function CreatePolygon(e,t,i=null,r=earcut){t.sideOrientation=rV.Kj._GetDefaultSideOrientation(t.sideOrientation);let s=t.shape,n=t.holes||[],a=t.depth||0,o=t.smoothingThreshold||2,l=[],h=[];for(let e=0;e1),a=t.rotationFunction||(()=>0),o=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||rV.Kj.NO_CAP,u=t.updatable,c=t.firstNormal||null,d=t.adjustFrame||!1,p=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),_=t.instance,f=t.invertUV||!1;return _ExtrudeShapeGeneric(e,s,r,null,null,n,a,o,l,h,!0,i,!!u,p,_||null,f,t.frontUVs||null,t.backUVs||null,c,d)}function _ExtrudeShapeGeneric(e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x){let T,S;let extrusionPathArray=(e,t,i,r,s,n,a,o,l,h,u)=>{let c=i.getTangents(),d=i.getNormals(),p=i.getBinormals(),_=i.getDistances();if(u){for(let e=0;e0){let t=c[e-1];0>rm.P.Dot(t,c[e])&&c[e].scaleInPlace(-1),t=d[e-1],0>rm.P.Dot(t,d[e])&&d[e].scaleInPlace(-1),t=p[e-1],0>rm.P.Dot(t,p[e])&&p[e].scaleInPlace(-1)}}let f=0,m=h&&o?o:()=>null!==n?n:0,g=h&&a?a:()=>null!==s?s:1,v=l===rV.Kj.NO_CAP||l===rV.Kj.CAP_END?0:2,x=rm.jp.Matrix[0];for(let i=0;i{let t;let i=[],r=rm.P.Zero();for(t=0;t3?0:h,u,x);let C=CreateRibbon(e,{pathArray:S,closeArray:o,closePath:l,updatable:d,sideOrientation:p,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},c);return C._creationDataStorage.pathArray=S,C._creationDataStorage.path3D=T,C._creationDataStorage.cap=h,C}function CreateLathe(e,t,i=null){let r,s;let n=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,a=void 0===t.closed||t.closed,o=t.shape,l=t.radius||1,h=t.tessellation||64,u=t.clip||0,c=t.updatable,d=rV.Kj._GetDefaultSideOrientation(t.sideOrientation),p=t.cap||rV.Kj.NO_CAP,_=[],f=t.invertUV||!1,m=0,g=0,v=2*Math.PI/h*n;for(m=0;m<=h-u;m++){for(s=[],(p==rV.Kj.CAP_START||p==rV.Kj.CAP_ALL)&&(s.push(new rm.P(0,o[0].y,0)),s.push(new rm.P(Math.cos(m*v)*o[0].x*l,o[0].y,Math.sin(m*v)*o[0].x*l))),g=0;g1)?1:t.arc||1;let tubePathArray=(e,t,i,r,s,n,a,o)=>{let l,h,u,c;let d=t.getTangents(),p=t.getNormals(),_=t.getDistances(),f=2*Math.PI/s*o,m=n||(()=>r),g=rm.jp.Matrix[0],v=a===rV.Kj.NO_CAP||a===rV.Kj.CAP_END?0:2;for(let t=0;t{let r=[];for(let s=0;s3?0:u,t.arc);let _=CreateRibbon(e,{pathArray:s,closePath:!0,closeArray:!1,updatable:d,sideOrientation:p,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return _._creationDataStorage.pathArray=s,_._creationDataStorage.path3D=r,_._creationDataStorage.tessellation=l,_._creationDataStorage.cap=u,_._creationDataStorage.arc=t.arc,_._creationDataStorage.radius=o,_}function CreatePolyhedronVertexData(e){let t,i,r,s,n,a;let o=[];o[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},o[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},o[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},o[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},o[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},o[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},o[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},o[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},o[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},o[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},o[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},o[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},o[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},o[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},o[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};let l=e.type&&(e.type<0||e.type>=o.length)?0:e.type||0,h=e.size,u=e.sizeX||h||1,c=e.sizeY||h||1,d=e.sizeZ||h||1,p=e.custom||o[l],_=p.face.length,f=e.faceUV||Array(_),m=e.faceColors,g=void 0===e.flat||e.flat,v=0===e.sideOrientation?0:e.sideOrientation||se.x.DEFAULTSIDE,x=[],T=[],S=[],C=[],E=[],b=0,y=0,P=[],R=0,A=0;if(g)for(A=0;A<_;A++)m&&void 0===m[A]&&(m[A]=new rg.HE(1,1,1,1)),f&&void 0===f[A]&&(f[A]=new rm.Lt(0,0,1,1));if(g)for(A=0;A<_;A++){let e=p.face[A].length;for(R=0,s=.5*Math.tan((r=2*Math.PI/e)/2),n=.5;RCreatePolygon(e,{shape:t,holes:r,updatable:s,sideOrientation:n},i,a),rV.Kj.ExtrudePolygon=(e,t,i,r,s,n,a,o=earcut)=>ExtrudePolygon(e,{shape:t,holes:s,depth:i,updatable:n,sideOrientation:a},r,o),rV.Kj.ExtrudeShape=(e,t,i,r,s,n,a=null,o,l,h)=>{let u={shape:t,path:i,scale:r,rotation:s,cap:0===n?0:n||rV.Kj.NO_CAP,sideOrientation:l,instance:h,updatable:o};return ExtrudeShape(e,u,a)},rV.Kj.ExtrudeShapeCustom=(e,t,i,r,s,n,a,o,l,h,u,c)=>{let d={shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:a,cap:0===o?0:o||rV.Kj.NO_CAP,sideOrientation:u,instance:c,updatable:h};return ExtrudeShapeCustom(e,d,l)},rV.Kj.CreateLathe=(e,t,i,r,s,n,a)=>CreateLathe(e,{shape:t,radius:i,tessellation:r,sideOrientation:a,updatable:n},s),rV.Kj.CreateTube=(e,t,i,r,s,n,a,o,l,h)=>CreateTube(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:n,updatable:o,sideOrientation:l,instance:h},a),se.x.CreatePolyhedron=CreatePolyhedronVertexData,rV.Kj.CreatePolyhedron=(e,t,i)=>polyhedronBuilder_CreatePolyhedron(e,t,i);let n2=new rm.P(1,0,0),n3=new rm.P(-1,0,0),n4=new rm.P(0,1,0),n5=new rm.P(0,-1,0),n6=new rm.P(0,0,1),n8=new rm.P(0,0,-1);let DecalVertex=class DecalVertex{constructor(e=rm.P.Zero(),t=rm.P.Up(),i=rm.FM.Zero(),r=0,s=0,n=null,a=null,o=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=n,this.localNormalOverride=a,this.matrixIndicesOverride=o,this.matrixWeightsOverride=l}clone(){var e,t,i,r;return new DecalVertex(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,null===(e=this.localPositionOverride)||void 0===e?void 0:e.slice(),null===(t=this.localNormalOverride)||void 0===t?void 0:t.slice(),null===(i=this.matrixIndicesOverride)||void 0===i?void 0:i.slice(),null===(r=this.matrixWeightsOverride)||void 0===r?void 0:r.slice())}};function CreateDecal(e,t,i){var r,s,n,a;let o=!!t.skeleton,l=i.localMode||o,h=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,u=t.getIndices(),c=o?t.getPositionData(!0,!0):t.getVerticesData(rz.o.PositionKind),d=o?t.getNormalsData(!0,!0):t.getVerticesData(rz.o.NormalKind),p=l?o?t.getVerticesData(rz.o.PositionKind):c:null,_=l?o?t.getVerticesData(rz.o.NormalKind):d:null,f=t.getVerticesData(rz.o.UVKind),m=o?t.getVerticesData(rz.o.MatricesIndicesKind):null,g=o?t.getVerticesData(rz.o.MatricesWeightsKind):null,v=o?t.getVerticesData(rz.o.MatricesIndicesExtraKind):null,x=o?t.getVerticesData(rz.o.MatricesWeightsExtraKind):null,T=i.position||rm.P.Zero(),S=i.normal||rm.P.Up(),C=i.size||rm.P.One(),E=i.angle||0;if(!S){let e=new rm.P(0,0,1),i=t.getScene().activeCamera,r=rm.P.TransformCoordinates(e,i.getWorldMatrix());S=i.globalPosition.subtract(r)}let b=-Math.atan2(S.z,S.x)-Math.PI/2,y=Math.sqrt(S.x*S.x+S.z*S.z),P=Math.atan2(S.y,y),R=new se.x;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=o?[]:null,R.matricesWeights=o?[]:null,R.matricesIndicesExtra=v?[]:null,R.matricesWeightsExtra=x?[]:null;let A=0,extractDecalVector3=(e,t)=>{let r=new DecalVertex;if(!u||!c||!d)return r;let s=u[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new rm.P(c[3*s],c[3*s+1],c[3*s+2]),rm.P.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new rm.P(d[3*s],d[3*s+1],d[3*s+2]),rm.P.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&f){let e=f[2*s+1];r.uv=new rm.FM(f[2*s],r4.e.UseOpenGLOrientationForUV?1-e:e)}return r},I=[0,0,0,0],clip=(e,t)=>{if(0===e.length)return e;let i=.5*Math.abs(rm.P.Dot(C,t)),indexOf=(e,t,i,r)=>{for(let s=0;s{var s,n,a,o,l,h,u,c,d,f,v,x,T,S,C,E;let b=rm.P.GetClipFactor(e.position,r.position,t,i),y=I,P=I;if(m&&g){let t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(s=e.matrixIndicesOverride)&&void 0!==s?s:m,l=null!==(n=e.matrixWeightsOverride)&&void 0!==n?n:g,h=r.matrixIndicesOverride?0:r.vertexIdxForBones,u=null!==(a=r.matrixIndicesOverride)&&void 0!==a?a:m,c=null!==(o=r.matrixWeightsOverride)&&void 0!==o?o:g;y=[0,0,0,0],P=[0,0,0,0];let d=0;for(let e=0;e<4;++e)if(l[t+e]>0){let r=indexOf(u,i[t+e],h,4);y[d]=i[t+e],P[d]=rE.R.Lerp(l[t+e],r>=0?c[r]:0,b),d++}for(let e=0;e<4&&d<4;++e){let r=u[h+e];-1===indexOf(i,r,t,4)&&(y[d]=r,P[d]=rE.R.Lerp(0,c[h+e],b),d++)}let p=P[0]+P[1]+P[2]+P[3];P[0]/=p,P[1]/=p,P[2]/=p,P[3]/=p}let R=e.localPositionOverride?e.localPositionOverride[0]:null!==(l=null==p?void 0:p[e.vertexIdx])&&void 0!==l?l:0,A=e.localPositionOverride?e.localPositionOverride[1]:null!==(h=null==p?void 0:p[e.vertexIdx+1])&&void 0!==h?h:0,M=e.localPositionOverride?e.localPositionOverride[2]:null!==(u=null==p?void 0:p[e.vertexIdx+2])&&void 0!==u?u:0,D=r.localPositionOverride?r.localPositionOverride[0]:null!==(c=null==p?void 0:p[r.vertexIdx])&&void 0!==c?c:0,O=r.localPositionOverride?r.localPositionOverride[1]:null!==(d=null==p?void 0:p[r.vertexIdx+1])&&void 0!==d?d:0,N=r.localPositionOverride?r.localPositionOverride[2]:null!==(f=null==p?void 0:p[r.vertexIdx+2])&&void 0!==f?f:0,F=e.localNormalOverride?e.localNormalOverride[0]:null!==(v=null==_?void 0:_[e.vertexIdx])&&void 0!==v?v:0,B=e.localNormalOverride?e.localNormalOverride[1]:null!==(x=null==_?void 0:_[e.vertexIdx+1])&&void 0!==x?x:0,L=e.localNormalOverride?e.localNormalOverride[2]:null!==(T=null==_?void 0:_[e.vertexIdx+2])&&void 0!==T?T:0,w=r.localNormalOverride?r.localNormalOverride[0]:null!==(S=null==_?void 0:_[r.vertexIdx])&&void 0!==S?S:0,U=r.localNormalOverride?r.localNormalOverride[1]:null!==(C=null==_?void 0:_[r.vertexIdx+1])&&void 0!==C?C:0,V=r.localNormalOverride?r.localNormalOverride[2]:null!==(E=null==_?void 0:_[r.vertexIdx+2])&&void 0!==E?E:0,k=F+(w-F)*b,G=B+(U-B)*b,z=L+(V-L)*b,W=Math.sqrt(k*k+G*G+z*z);return new DecalVertex(rm.P.Lerp(e.position,r.position,b),rm.P.Lerp(e.normal,r.normal,b).normalize(),rm.FM.Lerp(e.uv,r.uv,b),-1,-1,p?[R+(D-R)*b,A+(O-A)*b,M+(N-M)*b]:null,_?[k/W,G/W,z/W]:null,y,P)},r=null;e.length>3&&(r=[]);for(let s=0;s0,p=u>0,_=c>0;switch((d?1:0)+(p?1:0)+(_?1:0)){case 0:e.length>3?(r.push(e[s]),r.push(e[s+1]),r.push(e[s+2])):r=e;break;case 1:if(r=null!=r?r:[],d&&(n=e[s+1],a=e[s+2],o=clipVertices(e[s],n),l=clipVertices(e[s],a)),p){n=e[s],a=e[s+2],o=clipVertices(e[s+1],n),l=clipVertices(e[s+1],a),r.push(o),r.push(a.clone()),r.push(n.clone()),r.push(a.clone()),r.push(o.clone()),r.push(l);break}_&&(n=e[s],a=e[s+1],o=clipVertices(e[s+2],n),l=clipVertices(e[s+2],a)),n&&a&&o&&l&&(r.push(n.clone()),r.push(a.clone()),r.push(o),r.push(l),r.push(o.clone()),r.push(a.clone()));break;case 2:r=null!=r?r:[],d||(a=clipVertices(n=e[s].clone(),e[s+1]),o=clipVertices(n,e[s+2]),r.push(n),r.push(a),r.push(o)),p||(a=clipVertices(n=e[s+1].clone(),e[s+2]),o=clipVertices(n,e[s]),r.push(n),r.push(a),r.push(o)),_||(a=clipVertices(n=e[s+2].clone(),e[s]),o=clipVertices(n,e[s+1]),r.push(n),r.push(a),r.push(o))}}return r},M=t instanceof rV.Kj?t:null,D=null==M?void 0:M._thinInstanceDataStorage.matrixData,O=(null==M?void 0:M.thinInstanceCount)||1,N=rm.jp.Matrix[0];N.copyFrom(rm.y3.IdentityReadOnly);for(let e=0;e=-t[0].normal.z&&0>=-t[1].normal.z&&0>=-t[2].normal.z)&&(t=clip(t,n2))&&(t=clip(t,n3))&&(t=clip(t,n4))&&(t=clip(t,n5))&&(t=clip(t,n6))&&(t=clip(t,n8)))for(let e=0;eCreateDecal(e,t,{position:i,normal:r,size:s,angle:n}),rV.Kj._GoldbergMeshParser=(e,t)=>GoldbergMesh.Parse(e,t);let GoldbergMesh=class GoldbergMesh extends rV.Kj{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(rT.Y.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(rT.Y.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(rT.Y.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(r=1),u.push(r,s);for(let e=0;e<6;e++)r=o.x+l*Math.cos(h+e*Math.PI/3),s=o.y+l*Math.sin(h+e*Math.PI/3),r<0&&(r=0),r>1&&(r=1),c.push(r,s);for(let e=n;erg.HE.FromArray(e)),i.faceCenters=i.faceCenters.map(e=>rm.P.FromArray(e)),i.faceZaxis=i.faceZaxis.map(e=>rm.P.FromArray(e)),i.faceXaxis=i.faceXaxis.map(e=>rm.P.FromArray(e)),i.faceYaxis=i.faceYaxis.map(e=>rm.P.FromArray(e));let r=new GoldbergMesh(e.name,t);return r.goldbergData=i,r}};let ShapePath=class ShapePath{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new math_path_Path2(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,n){this._currentPath.addBezierCurveTo(e,t,i,r,s,n,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}};function CreateShapePath(e,t,i,r,s,n){let a=n.glyphs[e]||n.glyphs["?"];if(!a)return null;let o=new ShapePath(s);if(a.o){let e=a.o.split(" ");for(let s=0,n=e.length;s - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include - - #include - - varying vec3 vColor; - - uniform vec3 colorBase; - uniform vec3 colorZero; - uniform vec3 colorQuarter; - uniform vec3 colorHalf; - uniform vec3 colorFull; - - uniform float targetBoneIndex; - - void main() { - vec3 positionUpdated = position; - - #include - #include - #include - - vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); - - vec3 color = colorBase; - float totalWeight = 0.; - if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ - totalWeight += matricesWeights[0]; - } - if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ - totalWeight += matricesWeights[1]; - } - if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ - totalWeight += matricesWeights[2]; - } - if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ - totalWeight += matricesWeights[3]; - } - - color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); - color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); - color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); - color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); - vColor = color; - - gl_Position = projection * view * worldPos; - }`,ss.Q.ShadersStore["boneWeights:"+l.name+"FragmentShader"]=` - precision highp float; - varying vec3 vPosition; - - varying vec3 vColor; - - void main() { - vec4 color = vec4(vColor, 1.0); - gl_FragColor = color; - } - `;let f=new shaderMaterial_ShaderMaterial("boneWeight:"+l.name,t,{vertex:"boneWeights:"+l.name,fragment:"boneWeights:"+l.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return f.setColor3("colorBase",h),f.setColor3("colorZero",u),f.setColor3("colorQuarter",c),f.setColor3("colorHalf",d),f.setColor3("colorFull",p),f.setFloat("targetBoneIndex",_),f.getClassName=()=>"BoneWeightShader",f.transparencyMode=sr.F.MATERIAL_OPAQUE,f}static CreateSkeletonMapShader(e,t){var i;let r=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new rg.Wo(1,.38,.18),location:0},{color:new rg.Wo(.59,.18,1),location:.2},{color:new rg.Wo(.59,1,.18),location:.4},{color:new rg.Wo(1,.87,.17),location:.6},{color:new rg.Wo(1,.17,.42),location:.8},{color:new rg.Wo(.17,.68,1),location:1}],n=r.bones.length+1,a=SkeletonViewer._CreateBoneMapColorBuffer(n,s,t),o=new shaderMaterial_ShaderMaterial("boneWeights:"+r.name,t,{vertexSource:`precision highp float; - - attribute vec3 position; - attribute vec2 uv; - - uniform mat4 view; - uniform mat4 projection; - uniform mat4 worldViewProjection; - uniform float colorMap[`+4*r.bones.length+`]; - - #include - #if NUM_BONE_INFLUENCERS == 0 - attribute vec4 matricesIndices; - attribute vec4 matricesWeights; - #endif - #include - #include - - varying vec3 vColor; - - void main() { - vec3 positionUpdated = position; - - #include - #include - #include - - vec3 color = vec3(0.); - bool first = true; - - for (int i = 0; i < 4; i++) { - int boneIdx = int(matricesIndices[i]); - float boneWgt = matricesWeights[i]; - - vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); - - if (boneWgt > 0.) { - if (first) { - first = false; - color = c; - } else { - color = mix(color, c, boneWgt); - } - } - } - - vColor = color; - - vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); - - gl_Position = projection * view * worldPos; - }`,fragmentSource:` - precision highp float; - varying vec3 vColor; - - void main() { - vec4 color = vec4( vColor, 1.0 ); - gl_FragColor = color; - } - `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",a),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=sr.F.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){let r=new DynamicTexture("temp",{width:e,height:1},i,!1),s=r.getContext(),n=s.createLinearGradient(0,0,e,0);t.forEach(e=>{n.addColorStop(e.location,e.color.toHexString())}),s.fillStyle=n,s.fillRect(0,0,e,1),r.update();let a=[],o=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eSkeletonViewer.DISPLAY_SPHERE_AND_SPURS&&(e=SkeletonViewer.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,n={}){var a,o,l,h,u,c,d,p,_,f,m,g,v,x;this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=n,this.color=rg.Wo.White(),this._debugLines=[],this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=null===(a=n.pauseAnimations)||void 0===a||a,n.returnToRest=null!==(o=n.returnToRest)&&void 0!==o&&o,n.displayMode=null!==(l=n.displayMode)&&void 0!==l?l:SkeletonViewer.DISPLAY_LINES,n.displayOptions=null!==(h=n.displayOptions)&&void 0!==h?h:{},n.displayOptions.midStep=null!==(u=n.displayOptions.midStep)&&void 0!==u?u:.235,n.displayOptions.midStepFactor=null!==(c=n.displayOptions.midStepFactor)&&void 0!==c?c:.155,n.displayOptions.sphereBaseSize=null!==(d=n.displayOptions.sphereBaseSize)&&void 0!==d?d:.15,n.displayOptions.sphereScaleUnit=null!==(p=n.displayOptions.sphereScaleUnit)&&void 0!==p?p:2,n.displayOptions.sphereFactor=null!==(_=n.displayOptions.sphereFactor)&&void 0!==_?_:.865,n.displayOptions.spurFollowsChild=null!==(f=n.displayOptions.spurFollowsChild)&&void 0!==f&&f,n.displayOptions.showLocalAxes=null!==(m=n.displayOptions.showLocalAxes)&&void 0!==m&&m,n.displayOptions.localAxesSize=null!==(g=n.displayOptions.localAxesSize)&&void 0!==g?g:.075,n.computeBonesUsingShaders=null===(v=n.computeBonesUsingShaders)||void 0===v||v,n.useAllBones=null===(x=n.useAllBones)||void 0===x||x;let T=t.getVerticesData(rz.o.MatricesIndicesKind),S=t.getVerticesData(rz.o.MatricesWeightsKind);if(this._boneIndices=new Set,!n.useAllBones&&T&&S)for(let e=0;eSkeletonViewer.DISPLAY_SPHERE_AND_SPURS&&(C=SkeletonViewer.DISPLAY_LINES),this.displayMode=C,this.update(),this._bindObs()}_bindObs(){this.displayMode===SkeletonViewer.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case SkeletonViewer.DISPLAY_LINES:this._displayLinesUpdate();break;case SkeletonViewer.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,n=0){let a=rm.jp.Matrix[0],o=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==n){let e=rm.jp.Matrix[1];rm.y3.IdentityToRef(e),e.setTranslationFromFloats(r,s,n),e.multiplyToRef(a,a)}o&&a.multiplyToRef(o.getAbsoluteMatrix(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]}_getLinesForBonesWithLength(e,t){let i=e.length,r=this.mesh,s=r.position,n=0;for(let r=0;r=0;n--){let t=e[n],a=t.getParent();if(!a||!this._boneIndices.has(t.getIndex())&&!this.options.useAllBones)continue;let o=this._debugLines[i];o||(o=[rm.P.Zero(),rm.P.Zero()],this._debugLines[i]=o),t.getAbsolutePositionToRef(r,o[0]),a.getAbsolutePositionToRef(r,o[1]),o[0].subtractInPlace(s),o[1].subtractInPlace(s),i++}}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(null===e||-1===e._index){t.copyFrom(rm.y3.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;let r=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,n=[],a=[],o=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,r.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY,l=this.options.displayOptions||{};for(let i=0;i{let s=new rm.y3;i.getLocalMatrix().multiplyToRef(h,s);let n=new rm.P;s.decompose(void 0,void 0,n);let c=rm.P.Distance(u,n);if(c>t&&(t=c),e)return;let d=n.clone().subtract(u.clone()),p=d.length(),_=d.normalize().scale(p),f=l.midStep||.165,m=l.midStepFactor||.215,g=_.scale(f),v=ExtrudeShapeCustom("skeletonViewer",{shape:[new rm.P(1,-1,0),new rm.P(1,1,0),new rm.P(-1,1,0),new rm.P(-1,-1,0),new rm.P(1,-1,0)],path:[rm.P.Zero(),g,_],scaleFunction:e=>{switch(e){case 0:case 2:break;case 1:return p*m}return 0},sideOrientation:rV.Kj.DEFAULTSIDE,updatable:!1},r),x=v.getTotalVertices(),T=[],S=[];for(let e=0;e9?S.push(i.getIndex(),0,0,0):S.push(o.getIndex(),0,0,0);v.position=u.clone(),v.setVerticesData(rz.o.MatricesWeightsKind,T,!1),v.setVerticesData(rz.o.MatricesIndicesKind,S,!1),v.convertToFlatShadedMesh(),a.push(v)});let c=l.sphereBaseSize||.2,d=sphereBuilder_CreateSphere("skeletonViewer",{segments:6,diameter:c,updatable:!0},r),p=d.getTotalVertices(),_=[],f=[];for(let e=0;e{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;let e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))})):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},rq.D.prototype._getGlAlgorithmType=function(e){return e===rG.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(rG.x.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(rG.x.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new _OcclusionDataStorage),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(rG.x.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(rG.x.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),rG.x.prototype._checkOcclusionQuery=function(){let e=this._occlusionDataStorage;if(e.occlusionType===rG.x.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;let t=this.getEngine();if(!t.getCaps().supportOcclusionQuery||!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery){let i=t.isQueryResultAvailable(this._occlusionQuery);if(i){let i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,-1===e.occlusionRetryCount||!(e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==rG.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==rG.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}let i=this.getScene();if(i.getBoundingBoxRenderer){let r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded},rq.D.prototype.createTransformFeedback=function(){let e=this._gl.createTransformFeedback();if(!e)throw Error("Unable to create Transform Feedback");return e},rq.D.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},rq.D.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},rq.D.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},rq.D.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},rq.D.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},rq.D.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},r6.B.prototype.createExternalTexture=function(e){return null},r6.B.prototype.setExternalTexture=function(e,t){throw Error("setExternalTexture: This engine does not support external textures!")},r6.B.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;let r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);let t=e._workingCanvas.getContext("2d");if(!t)throw Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},r6.B.prototype.restoreSingleAttachment=function(){let e=this._gl;this.bindAttachments([e.BACK])},r6.B.prototype.restoreSingleAttachmentForRenderTarget=function(){let e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},r6.B.prototype.buildTextureLayout=function(e){let t=this._gl,i=[];for(let r=0;r1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(l=t.depthTextureFormat));let x=this._gl,T=x.createFramebuffer();this._bindUnboundFramebuffer(T);let S=e.width||e,C=e.height||e,E=[],b=[],y=this.webGLVersion>1&&o&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),P=this._setupFramebufferDepthAttachments(!y&&a,!o&&n,S,C);v._framebuffer=T,v._depthStencilBuffer=P,v._generateDepthBuffer=!o&&n,v._generateStencilBuffer=!y&&a,v._attachments=b;for(let e=0;e1||this.isWebGPU);let f=this.webGLVersion>1,m=x[f?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(b.push(m),-1===o)continue;let v=new r5.l(this,r5.S.MultiRenderTarget);E[e]=v,x.activeTexture(x["TEXTURE"+e]),x.bindTexture(o,v._hardwareTexture.underlyingResource),x.texParameteri(o,x.TEXTURE_MAG_FILTER,h.mag),x.texParameteri(o,x.TEXTURE_MIN_FILTER,h.min),x.texParameteri(o,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(o,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE);let T=this._getRGBABufferInternalSizedFormat(i,a,n),y=this._getInternalFormat(a),P=this._getWebGLTextureType(i);if(f&&(35866===o||32879===o))35866===o?v.is2DArray=!0:v.is3D=!0,v.baseDepth=v.depth=l,x.texImage3D(o,0,T,S,C,l,0,y,P,null);else if(34067===o){for(let e=0;e<6;e++)x.texImage2D(x.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,T,S,C,0,y,P,null);v.isCube=!0}else x.texImage2D(x.TEXTURE_2D,0,T,S,C,0,y,P,null);s&&x.generateMipmap(o),this._bindTextureDirectly(o,null),v.baseWidth=S,v.baseHeight=C,v.width=S,v.height=C,v.isReady=!0,v.samples=1,v.generateMipMaps=s,v.samplingMode=t,v.type=i,v._useSRGBBuffer=n,v.format=a,this._internalTexturesCache.push(v)}if(o&&this._caps.depthTextureExtension){let e=new r5.l(this,r5.S.Depth),t=5,i=x.DEPTH_COMPONENT16,r=x.DEPTH_COMPONENT,n=x.UNSIGNED_SHORT,a=x.DEPTH_ATTACHMENT;this.webGLVersion<2?i=x.DEPTH_COMPONENT:14===l?(t=1,n=x.FLOAT,i=x.DEPTH_COMPONENT32F):18===l?(t=0,n=x.FLOAT_32_UNSIGNED_INT_24_8_REV,i=x.DEPTH32F_STENCIL8,r=x.DEPTH_STENCIL,a=x.DEPTH_STENCIL_ATTACHMENT):16===l?(t=0,n=x.UNSIGNED_INT,i=x.DEPTH_COMPONENT24,a=x.DEPTH_ATTACHMENT):(13===l||17===l)&&(t=12,n=x.UNSIGNED_INT_24_8,i=x.DEPTH24_STENCIL8,r=x.DEPTH_STENCIL,a=x.DEPTH_STENCIL_ATTACHMENT),x.activeTexture(x.TEXTURE0),x.bindTexture(x.TEXTURE_2D,e._hardwareTexture.underlyingResource),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MAG_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_MIN_FILTER,x.NEAREST),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_S,x.CLAMP_TO_EDGE),x.texParameteri(x.TEXTURE_2D,x.TEXTURE_WRAP_T,x.CLAMP_TO_EDGE),x.texImage2D(x.TEXTURE_2D,0,i,S,C,0,r,n,null),x.framebufferTexture2D(x.FRAMEBUFFER,a,x.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=S,e.baseHeight=C,e.width=S,e.height=C,e.isReady=!0,e.samples=1,e.generateMipMaps=s,e.samplingMode=1,e.format=l,e.type=t,E[h]=e,this._internalTexturesCache.push(e)}return v.setTextures(E),i&&x.drawBuffers(b),this._bindUnboundFramebuffer(null),v.setLayerAndFaceIndices(m,f),this.resetTextureCache(),v},r6.B.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let r=e._attachments.length;if(0===r)return 1;let s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);let n=!!e._depthStencilBuffer;if(n&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){let n=s.createFramebuffer();if(!n)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);let a=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(r.width,r.height,t,-1,this._getRGBAMultiSampleBufferFormat(r.type,r.format),o);if(!l)throw Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),r.samples=t,a.push(o)}i&&s.drawBuffers(a)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},r6.B.prototype._createDepthStencilCubeTexture=function(e,t,i){let r=new r5.l(this,r5.S.DepthStencil);if(r.isCube=!0,1===this.webGLVersion)return rT.Y.Error("Depth cube texture is not supported by WebGL 1."),r;let s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),n=this._gl;this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=r,i._depthStencilTextureWithStencil=s.generateStencil;for(let t=0;t<6;t++)s.generateStencil?n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH24_STENCIL8,e,e,0,n.DEPTH_STENCIL,n.UNSIGNED_INT_24_8,null):n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH_COMPONENT24,e,e,0,n.DEPTH_COMPONENT,n.UNSIGNED_INT,null);return this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(r),r},r6.B.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)},void 0,void 0,!0,(e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)})},r6.B.prototype._cascadeLoadFiles=function(e,t,i,r=null){let s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},r6.B.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,n){let a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(r[o],o,a,e,t,i,s,n)},r6.B.prototype._partialLoadImg=function(e,t,i,r,s,n,a=null,o){let l=(0,rZ.f)();(0,rJ.r6)(e,e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(l),6===i._internalCount&&n&&n(s,i)},(e,t)=>{r&&r.removePendingData(l),a&&a(e,t)},r?r.offlineProvider:null,o),r&&r.addPendingData(l)},r6.B.prototype._setCubeMapTextureParams=function(e,t,i){let r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),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),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},r6.B.prototype.createCubeTextureBase=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=null,p=null,_=!1){let f=c||new r5.l(this,r5.S.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!r,f._lodGenerationScale=h,f._lodGenerationOffset=u,f._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!r),f!==c&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=o,f._files=i);let m=e;this._transformTextureUrl&&!c&&(e=this._transformTextureUrl(e));let g=e.split("?")[0],v=g.lastIndexOf("."),x=o||(v>-1?g.substring(v).toLowerCase():""),T=null;for(let e of r6.B._TextureLoaders)if(e.canLoad(x)){T=e;break}if(T){let onloaddata=e=>{d&&d(f,e),T.loadCubeData(e,f,l,s,n)};i&&6===i.length?T.supportCascades?this._cascadeLoadFiles(t,e=>onloaddata(e.map(e=>new Uint8Array(e))),i,n):n?n("Textures type does not support cascades."):rT.Y.Warn("Texture loader does not support cascades."):this._loadFile(e,e=>onloaddata(new Uint8Array(e)),void 0,void 0,!0,(c,g)=>{e===m?n&&c&&n(c.status+" "+c.statusText,g):(rT.Y.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!r,s,n,a,o,l,h,u,f,d,p,_))})}else{if(!i)throw Error("Cannot load cubemap because files were not defined");this._cascadeLoadImgs(t,f,(e,t)=>{p&&p(e,t)},i,n)}return this._internalTexturesCache.push(f),f},r6.B.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),(e,t)=>{let i=this.needPOTTextures?r6.B.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);let o=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA,l=a?this._getInternalFormat(a):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(l=o);for(let e=0;e{this.unRegisterView(e)}),s},rq.D.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(let t of this.views)if(t.target===e){let e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},rq.D.prototype._renderViewStep=function(e){let t=e.target,i=t.getContext("2d");if(!i)return!0;let r=this.getRenderingCanvas();n9.notifyObservers(e);let s=e.camera,n=null,a=null;if(s){if(!(a=s.getScene())||a.activeCameras&&a.activeCameras.length)return!0;this.activeView=e,n=a.activeCamera,a.activeCamera=s}if(e.customResize)e.customResize(t);else{let e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!!r.width&&!!r.height&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),n&&a&&(a.activeCamera=n),ae.notifyObservers(e),!0)},rq.D.prototype._renderViews=function(){let e;if(!this.views||0===this.views.length)return!1;let t=this.getRenderingCanvas();if(!t)return!1;for(let t of this.views){if(!t.enabled)continue;let i=t.target;if(i===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return(!e||!!this._renderViewStep(e))&&(this.activeView=null,!0)};var at=i(9255);function transformTextureUrl(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(t=>e&&(e===t||e.match(RegExp("\\b"+t+"\\b","g")))))return e;let t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}r6.B.prototype.createStorageBuffer=function(e,t){throw Error("createStorageBuffer: Unsupported method in this engine!")},r6.B.prototype.updateStorageBuffer=function(e,t,i,r){},r6.B.prototype.readFromStorageBuffer=function(e,t,i,r){throw Error("readFromStorageBuffer: Unsupported method in this engine!")},r6.B.prototype.setStorageBuffer=function(e,t){throw Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(rq.D.prototype,"texturesSupported",{get:function(){let e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(rq.D.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),rq.D.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},rq.D.prototype.setTextureFormatToUse=function(e){let t=this.texturesSupported;for(let i=0,r=t.length;i{this._flush()})}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}};NativeDataStream.DEFAULT_BUFFER_SIZE=65536;let ai=[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))],ar=[()=>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],applySH3=(e,t)=>ai[e]*ar[e](t),as=[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];let SphericalHarmonics=class SphericalHarmonics{constructor(){this.preScaled=!1,this.l00=rm.P.Zero(),this.l1_1=rm.P.Zero(),this.l10=rm.P.Zero(),this.l11=rm.P.Zero(),this.l2_2=rm.P.Zero(),this.l2_1=rm.P.Zero(),this.l20=rm.P.Zero(),this.l21=rm.P.Zero(),this.l22=rm.P.Zero()}addLight(e,t,i){rm.jp.Vector3[0].set(t.r,t.g,t.b);let r=rm.jp.Vector3[0],s=rm.jp.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(applySH3(0,e),rm.jp.Vector3[2]),this.l00.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(1,e),rm.jp.Vector3[2]),this.l1_1.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(2,e),rm.jp.Vector3[2]),this.l10.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(3,e),rm.jp.Vector3[2]),this.l11.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(4,e),rm.jp.Vector3[2]),this.l2_2.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(5,e),rm.jp.Vector3[2]),this.l2_1.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(6,e),rm.jp.Vector3[2]),this.l20.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(7,e),rm.jp.Vector3[2]),this.l21.addInPlace(rm.jp.Vector3[2]),s.scaleToRef(applySH3(8,e),rm.jp.Vector3[2]),this.l22.addInPlace(rm.jp.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(as[0]),this.l1_1.scaleInPlace(as[1]),this.l10.scaleInPlace(as[2]),this.l11.scaleInPlace(as[3]),this.l2_2.scaleInPlace(as[4]),this.l2_1.scaleInPlace(as[5]),this.l20.scaleInPlace(as[6]),this.l21.scaleInPlace(as[7]),this.l22.scaleInPlace(as[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(ai[0]),this.l1_1.scaleInPlace(ai[1]),this.l10.scaleInPlace(ai[2]),this.l11.scaleInPlace(ai[3]),this.l2_2.scaleInPlace(ai[4]),this.l2_1.scaleInPlace(ai[5]),this.l20.scaleInPlace(ai[6]),this.l21.scaleInPlace(ai[7]),this.l22.scaleInPlace(ai[8])}updateFromArray(e){return rm.P.FromArrayToRef(e[0],0,this.l00),rm.P.FromArrayToRef(e[1],0,this.l1_1),rm.P.FromArrayToRef(e[2],0,this.l10),rm.P.FromArrayToRef(e[3],0,this.l11),rm.P.FromArrayToRef(e[4],0,this.l2_2),rm.P.FromArrayToRef(e[5],0,this.l2_1),rm.P.FromArrayToRef(e[6],0,this.l20),rm.P.FromArrayToRef(e[7],0,this.l21),rm.P.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return rm.P.FromFloatsToRef(e[0],e[1],e[2],this.l00),rm.P.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),rm.P.FromFloatsToRef(e[6],e[7],e[8],this.l10),rm.P.FromFloatsToRef(e[9],e[10],e[11],this.l11),rm.P.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),rm.P.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),rm.P.FromFloatsToRef(e[18],e[19],e[20],this.l20),rm.P.FromFloatsToRef(e[21],e[22],e[23],this.l21),rm.P.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){let t=new SphericalHarmonics;return t.updateFromArray(e)}static FromPolynomial(e){let t=new SphericalHarmonics;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}};let SphericalPolynomial=class SphericalPolynomial{constructor(){this.x=rm.P.Zero(),this.y=rm.P.Zero(),this.z=rm.P.Zero(),this.xx=rm.P.Zero(),this.yy=rm.P.Zero(),this.zz=rm.P.Zero(),this.xy=rm.P.Zero(),this.yz=rm.P.Zero(),this.zx=rm.P.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=SphericalHarmonics.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){rm.jp.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=rm.jp.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),rm.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),rm.jp.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(rm.jp.Vector3[0]).addInPlace(rm.jp.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(rm.jp.Vector3[0]).subtractInPlace(rm.jp.Vector3[1]),this.zz.copyFrom(e.l00),rm.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(rm.jp.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){let t=new SphericalPolynomial;return t.updateFromHarmonics(e)}static FromArray(e){let t=new SphericalPolynomial;return rm.P.FromArrayToRef(e[0],0,t.x),rm.P.FromArrayToRef(e[1],0,t.y),rm.P.FromArrayToRef(e[2],0,t.z),rm.P.FromArrayToRef(e[3],0,t.xx),rm.P.FromArrayToRef(e[4],0,t.yy),rm.P.FromArrayToRef(e[5],0,t.zz),rm.P.FromArrayToRef(e[6],0,t.yz),rm.P.FromArrayToRef(e[7],0,t.zx),rm.P.FromArrayToRef(e[8],0,t.xy),t}};let an=`varying vec2 vUV;uniform sampler2D textureSampler; -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;function CreateResizedCopy(e,t,i,r=!0){let s=e.getScene(),n=s.getEngine(),a=new renderTargetTexture_RenderTargetTexture("resized"+e.name,{width:t,height:i},s,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);a.wrapU=e.wrapU,a.wrapV=e.wrapV,a.uOffset=e.uOffset,a.vOffset=e.vOffset,a.uScale=e.uScale,a.vScale=e.vScale,a.uAng=e.uAng,a.vAng=e.vAng,a.wAng=e.wAng,a.coordinatesIndex=e.coordinatesIndex,a.level=e.level,a.anisotropicFilteringLevel=e.anisotropicFilteringLevel,a._texture.isReady=!1,e.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.wrapV=texture_Texture.CLAMP_ADDRESSMODE;let o=new PassPostProcess("pass",1,null,r?texture_Texture.BILINEAR_SAMPLINGMODE:texture_Texture.NEAREST_SAMPLINGMODE,n,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(t){t.setTexture("textureSampler",e)};let t=a.renderTarget;t&&(s.postProcessManager.directRender([o],t),n.unBindFramebuffer(t),a.disposeFramebufferObjects(),o.dispose(),a.getInternalTexture().isReady=!0)}),a}function ApplyPostProcess(e,t,i,r,s,n,a,o){let l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,r=null!=r?r:t.type,n=null!=n?n:t.format,a=null!=a?a:t.width,o=null!=o?o:t.height,-1===r&&(r=0),new Promise(h=>{let u=new postProcess_PostProcess("postprocess",e,null,null,1,null,s,l,!1,void 0,r,void 0,null,!1,n);u.externalTextureSamplerBinding=!0;let c=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:n});u.getEffect().executeWhenCompiled(()=>{u.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([u],c,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),u&&u.dispose(),c._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,h(t)})})}function ToHalfFloat(e){r||(r=new Float32Array(1),s=new Int32Array(r.buffer)),r[0]=e;let t=s[0],i=t>>16&32768,n=t>>12&2047,a=t>>23&255;return a<103?i:a>142?(i|=31744,i|=(255==a?0:1)&&8388607&t):a<113?(n|=2048,i|=(n>>114-a)+(n>>113-a&1)):(i|=a-112<<10|n>>1,i+=1&n)}function FromHalfFloat(e){let t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*6103515625e-14*(r/1024):31==i?r?NaN:(t?-1:1)*(1/0):(t?-1:1)*Math.pow(2,i-15)*(1+r/1024)}s_.v.ShadersStore.rgbdDecodePixelShader=an;let ProcessAsync=async(e,t,i,r,s)=>{let n;let a=e.getScene(),o=a.getEngine();n=e.isCube?new postProcess_PostProcess("lodCube","lodCube",["lod","gamma"],null,1,null,texture_Texture.NEAREST_NEAREST_MIPNEAREST,o,!1,["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"][r]):new postProcess_PostProcess("lod","lod",["lod","gamma"],null,1,null,texture_Texture.NEAREST_NEAREST_MIPNEAREST,o),await new Promise(e=>{n.getEffect().executeWhenCompiled(()=>{e(0)})});let l=new renderTargetTexture_RenderTargetTexture("temp",{width:t,height:i},a,!1);n.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",s),t.setBool("gamma",e.gammaSpace)};let h=e.getInternalTexture();try{if(l.renderTarget&&h){let r=h.samplingMode;0!==s?e.updateSamplingMode(texture_Texture.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(texture_Texture.NEAREST_NEAREST),a.postProcessManager.directRender([n],l.renderTarget,!0),e.updateSamplingMode(r);let u=await o.readPixels(0,0,t,i),c=new Uint8Array(u.buffer,0,u.byteLength);return o.unBindFramebuffer(l.renderTarget),c}throw Error("Render to texture failed.")}finally{l.dispose(),n.dispose()}};async function GetTextureDataAsync(e,t,i,r=0,s=0){return!e.isReady()&&e._texture&&await new Promise((t,i)=>{if(null===e._texture){i(0);return}e._texture.onLoadedObservable.addOnce(()=>{t(0)})}),await ProcessAsync(e,t,i,r,s)}let aa={CreateResizedCopy,ApplyPostProcess,ToHalfFloat,FromHalfFloat,GetTextureDataAsync};let RGBDTextureTools=class RGBDTextureTools{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,n=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(n=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let expandRGBDTexture=()=>{if(n){let r=new postProcess_PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);r.externalTextureSamplerBinding=!0;let s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});r.getEffect().executeWhenCompiled(()=>{r.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([r],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),r&&r.dispose(),s._swapAndDie(t),t.isReady=!0})}};s?expandRGBDTexture():e.onLoadObservable.addOnce(expandRGBDTexture)}static EncodeTextureToRGBD(e,t,i=0){return ApplyPostProcess("rgbdEncode",e,t,i,1,5)}};let FileFaceOrientation=class FileFaceOrientation{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}};let CubeMapToSphericalPolynomialTools=class CubeMapToSphericalPolynomialTools{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;let i,r;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();let s=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),a=e.readPixels(1,void 0,void 0,!1);e.isRenderTarget?(i=e.readPixels(3,void 0,void 0,!1),r=e.readPixels(2,void 0,void 0,!1)):(i=e.readPixels(2,void 0,void 0,!1),r=e.readPixels(3,void 0,void 0,!1));let o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,u=0;return(1==e.textureType||2==e.textureType)&&(u=1),new Promise(e=>{Promise.all([a,n,i,r,o,l]).then(([t,i,r,n,a,o])=>{let l={size:s,right:i,left:t,up:r,down:n,front:a,back:o,format:5,type:u,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(l))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){let t=new SphericalHarmonics,i=0,r=2/e.size,s=.5*r,n=s-1;for(let a=0;a<6;a++){let o=this._FileFaces[a],l=e[o.name],h=n,u=5===e.format?4:3;for(let a=0;ag){let t=g/e;_*=t,f*=t,m*=t}}else _=rE.R.Clamp(_,0,g),f=rE.R.Clamp(f,0,g),m=rE.R.Clamp(m,0,g);let v=new rg.Wo(_,f,m);t.addLight(d,v,p),i+=p,c+=r}h+=r}}let a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),SphericalPolynomial.FromHarmonics(t)}};CubeMapToSphericalPolynomialTools._FileFaces=[new FileFaceOrientation("right",new rm.P(1,0,0),new rm.P(0,0,-1),new rm.P(0,-1,0)),new FileFaceOrientation("left",new rm.P(-1,0,0),new rm.P(0,0,1),new rm.P(0,-1,0)),new FileFaceOrientation("up",new rm.P(0,1,0),new rm.P(1,0,0),new rm.P(0,0,1)),new FileFaceOrientation("down",new rm.P(0,-1,0),new rm.P(1,0,0),new rm.P(0,0,-1)),new FileFaceOrientation("front",new rm.P(0,0,1),new rm.P(1,0,0),new rm.P(0,-1,0)),new FileFaceOrientation("back",new rm.P(0,0,-1),new rm.P(-1,0,0),new rm.P(0,-1,0))],CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE=4096,CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS=!1,baseTexture_BaseTexture.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(baseTexture_BaseTexture.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;this._texture.isReady&&!this._texture._sphericalPolynomialPromise&&(this._texture._sphericalPolynomialPromise=CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});let ao=`varying vec2 vUV;uniform sampler2D textureSampler; -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;s_.v.ShadersStore.rgbdEncodePixelShader=ao;let al="image/png",ah=[134,22,135,150,246,214,150,54];function GetEnvInfo(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(let e=0;e2)throw Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "2".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:al})}function CreateImageDataArrayBufferViews(e,t){t=normalizeEnvInfo(t);let i=t.specular,r=rE.R.Log2(t.width);if(r=Math.round(r)+1,i.mipmaps.length!==6*r)throw Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);let s=Array(r);for(let t=0;t{if(i){let i=t.createTexture(null,!0,!0,null,1,null,e=>{d(e)},e);r.getEffect().executeWhenCompiled(()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,n,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),c())})}else{if(t._uploadImageToTexture(u,e,n,a),o){let i=l[a];i&&t._uploadImageToTexture(i._texture,e,n,0)}c()}})}function UploadLevelsAsync(e,t,i=al){if(!rW.w1.IsExponentOfTwo(e.width))throw Error("Texture size must be a power of two");let r=rE.R.ILog2(e.width)+1,s=e.getEngine(),n=!1,a=!1,o=null,l=null,h=null,u=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),u.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(n=!0,e.type=2):u.textureFloatRender&&u.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,a=!0,h={}),n)o=new postProcess_PostProcess("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=s.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,a){let t=e._lodGenerationScale,i=e._lodGenerationOffset;for(let n=0;n<3;n++){let a=n/2,o=1-a,l=(r-1)*t+i,u=i+(l-i)*o,c=Math.round(Math.min(Math.max(u,0),l)),d=new r5.l(s,r5.S.Temp);d.isCube=!0,d.invertY=!0,d.generateMipMaps=!1,s.updateTextureSamplingMode(2,d);let p=new baseTexture_BaseTexture(null);switch(p._isCube=!0,p._texture=d,h[c]=p,n){case 0:e._lodTextureLow=p;break;case 1:e._lodTextureMid=p;break;case 2:e._lodTextureHigh=p}}}let c=[];for(let r=0;r_OnImageReadyAsync(t,s,n,o,f,u,r,a,h,l,e));else{let t=new Image;t.src=f,d=new Promise((i,c)=>{t.onload=()=>{_OnImageReadyAsync(t,s,n,o,f,u,r,a,h,l,e).then(()=>i()).catch(e=>{c(e)})},t.onerror=e=>{c(e)}})}c.push(d)}if(t.length{l&&(s._releaseTexture(e),l._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 UploadEnvSpherical(e,t){t=normalizeEnvInfo(t);let i=t.irradiance;if(!i)return;let r=new SphericalPolynomial;rm.P.FromArrayToRef(i.x,0,r.x),rm.P.FromArrayToRef(i.y,0,r.y),rm.P.FromArrayToRef(i.z,0,r.z),rm.P.FromArrayToRef(i.xx,0,r.xx),rm.P.FromArrayToRef(i.yy,0,r.yy),rm.P.FromArrayToRef(i.zz,0,r.zz),rm.P.FromArrayToRef(i.yz,0,r.yz),rm.P.FromArrayToRef(i.zx,0,r.zx),rm.P.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function ExtractBetweenMarkers(e,t,i,r){let s=r,n=0,a="";for(;s=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function RemoveComments(e){let t=0,i="",r=!1,s=[];for(;t=0&&e.charAt(t)!==i;)t--;return t}function EscapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}let ShaderCodeInliner=class ShaderCodeInliner{get code(){return this._sourceCode}constructor(e,t=20){this.debug=!1,this._sourceCode=e,this._numMaxIterations=t,this._functionDescr=[],this.inlineToken="#define inline"}processCode(){this.debug&&console.log(`Start inlining process (code size=${this._sourceCode.length})...`),this._collectFunctions(),this._processInlining(this._numMaxIterations),this.debug&&console.log("End of inlining process.")}_collectFunctions(){let e=0;for(;e=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:n,type:s,parameters:d,body:u,callIndex:0}),e=h+1;let p=t>0?this._sourceCode.substring(0,t):"",_=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&console.log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(let t of this._functionDescr){let{name:i,type:r,parameters:s,body:n}=t,a=0;for(;a{let t=[],i=0,r=0;for(;i0?this._sourceCode.substring(0,o):"",m=h+1{let o=s[0];return IsIdentifierChar(e.charAt(o-1))||IsIdentifierChar(e.charAt(o+n))?t[r]:a})}return e}};ShaderCodeInliner._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;var au=i(7666);let NativePipelineContext=class NativePipelineContext{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){let e=this.compilationError.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this._engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);let u=this._engine.getUniforms(this,i);for(u.forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l{n[e]=t}),o.push(...h.getAttributes(this,a))}dispose(){this._uniforms={}}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setInt4(this._uniforms[e],t,i,r,s)&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setUInt4(this._uniforms[e],t,i,r,s)&&(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)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(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.toArray())&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}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,i){this._cacheFloat2(e,t,i)&&!this._engine.setFloat2(this._uniforms[e],t,i)&&(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,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setFloat3(this._uniforms[e],t,i,r)&&(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,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setFloat4(this._uniforms[e],t,i,r,s)&&(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(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)}};let NativeRenderTargetWrapper=class NativeRenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}};let NativeHardwareTexture=class NativeHardwareTexture{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}};function getNativeTextureFormat(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new si.LH(`Unsupported texture format or type: format ${e}, type ${t}.`,si.SM.UnsupportedTextureError)}function getNativeSamplingMode(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw Error(`Unsupported sampling mode: ${e}.`)}}function getNativeAddressMode(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw Error("Unexpected wrap mode: "+e+".")}}function getNativeStencilFunc(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw Error(`Unsupported stencil func mode: ${e}.`)}}function getNativeStencilOpFail(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw Error(`Unsupported stencil OpFail mode: ${e}.`)}}function getNativeStencilDepthFail(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw Error(`Unsupported stencil depthFail mode: ${e}.`)}}function getNativeStencilDepthPass(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw Error(`Unsupported stencil opPass mode: ${e}.`)}}function getNativeAlphaMode(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw Error(`Unsupported alpha mode: ${e}.`)}}function getNativeAttribType(e){switch(e){case rz.o.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case rz.o.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case rz.o.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case rz.o.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case rz.o.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw Error(`Unsupported attribute type: ${e}.`)}}let ac=new rf.y$;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{(e=t)&&ac.notifyObservers(e)}})}function AcquireNativeObjectAsync(){return new Promise(e=>{"undefined"==typeof _native?ac.addOnce(t=>e(t)):e(_native)})}async function RegisterNativeTypeAsync(e,t){(await AcquireNativeObjectAsync())[e]=t}let NativeDataBuffer=class NativeDataBuffer extends sI.h{};let CommandBufferEncoder=class CommandBufferEncoder{constructor(e){this._engine=e,this._pending=[],this._isCommandBufferScopeActive=!1,this._commandStream=NativeEngine._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}};let NativeEngine=class NativeEngine extends rq.D{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new CommandBufferEncoder(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==NativeEngine.PROTOCOL_VERSION)throw Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${NativeEngine.PROTOCOL_VERSION} (JS)`);this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!1,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},rW.w1.Log("Babylon Native (v"+rq.D.Version+") launched"),rW.w1.LoadScript=function(e,t,i,r){rW.w1.LoadFile(e,e=>{Function(e).apply(null),t&&t()},void 0,void 0,!1,(e,t)=>{i&&i("LoadScript Error",t)})},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function flat(){let e=isNaN(arguments[0])?1:Number(arguments[0]);return e?Array.prototype.reduce.call(this,function(t,i){return Array.isArray(i)?t.push.apply(t,flat.call(i,e-1)):t.push(i),t},[]):Array.prototype.slice.call(this)},writable:!0});let t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();let i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new au.C,this.onNewSceneAddedObservable.add(e=>{let t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new NativeDataStream}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,r=!1){if(this.useReverseDepthBuffer)throw Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){let r=this._normalizeIndexData(e),s=new NativeDataBuffer;return s.references=1,s.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,null!=t&&t)),s}createVertexBuffer(e,t,i){let r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new NativeDataBuffer;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,null!=t&&t)),s}_recordVertexArrayObject(e,t,i,r,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);let n=r.getAttributesNames();for(let i=0;i=0){let r=n[i],o=null;if(s&&(o=s[r]),o||(o=t[r]),o){let t=o.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,a,o.byteOffset,o.byteStride,o.getSize(),getNativeAttribType(o.type),o.normalized,o.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){let s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){return this._engine.getAttributes(e.nativeProgram,t)}drawElementsType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){return new NativePipelineContext(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,r,s,n,a,o){r?e.nativeProgram=this.createRawShaderProgram():e.nativeProgram=this.createShaderProgram(e,t,i,o)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){if(!this.isAsync(e)){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}createRawShaderProgram(){throw Error("Not Supported")}createShaderProgram(e,t,i,r){if(e.nativeProgram)throw Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=new ShaderCodeInliner(t);s.processCode(),t=s.code;let n=new ShaderCodeInliner(i);n.processCode(),i=n.code,t=r6.B._ConcatenateShader(t,r),i=r6.B._ConcatenateShader(i,r);let onSuccess=()=>{var t;e.isCompiled=!0,null===(t=e.onCompiled)||void 0===t||t.call(e),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,onSuccess,t=>{e.compilationError=t});try{let r=e.nativeProgram=this._engine.createProgram(t,i);return onSuccess(),r}catch(t){let e=null==t?void 0:t.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){let t=new ShaderCodeInliner(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){e&&e.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){return this._engine.getUniforms(e.nativeProgram,t)}bindUniformBlock(e,t,i){throw Error("Not Implemented")}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.nativeProgram);let i=e.getSamplers();for(let t=0;t{}};return e}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,getNativeStencilOpFail(this._stencilOpStencilFail),getNativeStencilDepthFail(this._stencilOpDepthFail),getNativeStencilDepthPass(this._stencilOpStencilDepthPass),getNativeStencilFunc(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;let i=getNativeAlphaMode(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){let i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){let r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new r5.l(this,r5.S.Raw);if(c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c.baseWidth=t,c.baseHeight=i,c.width=c.baseWidth,c.height=c.baseHeight,c._compression=o,c.type=l,c._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this.updateRawTexture(c,e,r,n,o,l,c._useSRGBBuffer),c._hardwareTexture){let e=c._hardwareTexture.underlyingResource,t=getNativeSamplingMode(a);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(c),c}createRawTexture2DArray(e,t,i,r,s,n,a,o,l=null,h=0){let u=new r5.l(this,r5.S.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=o,u.is2DArray=!0,u._hardwareTexture){let l=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,getNativeTextureFormat(s,h),n,a);let c=getNativeSamplingMode(o);this._setTextureSampling(l,c)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,r,s=null,n=0,a=!1){if(e){if(t&&e._hardwareTexture){let r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,getNativeTextureFormat(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_=!1){e=e||"";let f="data:"===e.substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new r5.l(this,r5.S.Url),v=e;!this._transformTextureUrl||m||l||o||(e=this._transformTextureUrl(e));let x=e.lastIndexOf("."),T=u||(x>-1?e.substring(x).toLowerCase():""),S=null;for(let e of rq.D._TextureLoaders)if(e.canLoad(T)){S=e;break}r&&r.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=s,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(g._buffer=o);let C=null;n&&!l&&(C=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);let onInternalError=(i,l)=>{r&&r.removePendingData(g),e===v?(C&&g.onLoadedObservable.remove(C),rS.l.UseFallbackTexture&&this.createTexture(rS.l.FallbackTexture,t,g.invertY,r,s,null,a,o,g),a&&a((i||"Unknown error")+(rS.l.UseFallbackTexture?" - Fallback texture was used":""),l)):(rT.Y.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,r,s,n,a,o,g,h,u,c,d))};if(S)throw Error("Loading textures from IInternalTextureLoader not yet implemented.");{let onload=e=>{if(!g._hardwareTexture){r&&r.removePendingData(g);return}let n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;let e=getNativeSamplingMode(s);this._setTextureSampling(n,e),r&&r.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>{throw Error("Could not load a native texture.")})};if(f&&o){if(o instanceof ArrayBuffer)onload(new Uint8Array(o));else if(ArrayBuffer.isView(o))onload(o);else if("string"==typeof o)onload(new Uint8Array(rW.w1.DecodeBase64(o)));else throw Error("Unsupported buffer type")}else m?onload(new Uint8Array(rW.w1.DecodeBase64(e))):this._loadFile(e,e=>onload(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{onInternalError("Unable to load "+(e&&e.responseURL,t))})}return g}wrapNativeTexture(e,t=!1,i=3){let r=new NativeHardwareTexture(e,this._engine),s=new r5.l(this,r5.S.Unknown,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){var r,s;let n=t.generateStencil||!1,a=t.samples||1,o=new r5.l(this,r5.S.DepthStencil),l=null!==(r=e.width)&&void 0!==r?r:e,h=null!==(s=e.height)&&void 0!==s?s:e,u=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,n,!0,a);return i._framebufferDepthStencil=u,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){let i=new Promise((t,i)=>{let r=this.createCanvasImage();r.onload=()=>{try{let e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e});return i}createImageBitmap(e,t){return new Promise((t,i)=>{if(Array.isArray(e)&&e.length){let i=this._engine.createImageBitmap(e[0]);if(i){t(i);return}}i("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=c||new r5.l(this,r5.S.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!r,_._lodGenerationScale=h,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(p,!!r),this._doNotHandleContextLost||(_._extension=o,_._files=i);let f=e.lastIndexOf("."),m=o||(f>-1?e.substring(f).toLowerCase():"");if(".env"===m){let onloaddata=e=>{let t=GetEnvInfo(e);_.width=t.width,_.height=t.width,UploadEnvSpherical(_,t);let i=t.specular;if(!i)throw Error("Nothing else parsed so far");_._lodGenerationScale=i.lodGenerationScale;let r=CreateImageDataArrayBufferViews(e,t);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,r,!1,_._useSRGBBuffer,()=>{_.isReady=!0,s&&s()},()=>{throw Error("Could not load a native cube texture.")})};if(i&&6===i.length)throw Error("Multi-file loading not allowed on env files.");this._loadFile(e,e=>onloaddata(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)})}else{if(!i||6!==i.length)throw Error("Cannot load cubemap because 6 files were not defined");let e=[i[0],i[3],i[1],i[4],i[2],i[5]];Promise.all(e.map(e=>rW.w1.LoadFileAsync(e).then(e=>new Uint8Array(e)))).then(e=>new Promise((t,i)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,e,!r,!0,_._useSRGBBuffer,t,i)})).then(()=>{_.isReady=!0,s&&s()},e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new NativeHardwareTexture(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){let r=new NativeRenderTargetWrapper(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=r5.S.Unknown){var s,n,a;let o;let l=!1,h=0,u=3,c=5,d=!1,p=1;void 0!==t&&"object"==typeof t?(l=!!t.generateMipMaps,h=void 0===t.type?0:t.type,u=void 0===t.samplingMode?3:t.samplingMode,c=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,p=null!==(s=t.samples)&&void 0!==s?s:1,o=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(1!==h||this._caps.textureFloatLinearFiltering)&&(2!==h||this._caps.textureHalfFloatLinearFiltering)||(u=1),1!==h||this._caps.textureFloat||(h=0,rT.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let _=new r5.l(this,r),f=null!==(n=e.width)&&void 0!==n?n:e,m=null!==(a=e.height)&&void 0!==a?a:e,g=e.layers||0;if(0!==g)throw Error("Texture layers are not supported in Babylon Native");let v=_._hardwareTexture.underlyingResource,x=getNativeTextureFormat(c,h);return this._engine.initializeTexture(v,f,m,l,x,!0,d,p),this._setTextureSampling(v,getNativeSamplingMode(u)),_._useSRGBBuffer=d,_.baseWidth=f,_.baseHeight=m,_.width=f,_.height=m,_.depth=g,_.isReady=!0,_.samples=p,_.generateMipMaps=l,_.samplingMode=u,_.type=h,_.format=c,_.label=o,this._internalTexturesCache.push(_),_}createRenderTargetTexture(e,t){var i,r,s,n;let a;let o=this._createHardwareRenderTargetWrapper(!1,!1,e),l=!0,h=!1,u=!1,c=1;void 0!==t&&"object"==typeof t&&(l=null===(i=t.generateDepthBuffer)||void 0===i||i,h=!!t.generateStencilBuffer,u=!!t.noColorAttachment,a=t.colorAttachment,c=null!==(r=t.samples)&&void 0!==r?r:1);let d=a||(u?null:this._createInternalTexture(e,t,!0,r5.S.RenderTarget)),p=null!==(s=e.width)&&void 0!==s?s:e,_=null!==(n=e.height)&&void 0!==n?n:e,f=this._engine.createFrameBuffer(d?d._hardwareTexture.underlyingResource:null,p,_,h,l,c);return o._framebuffer=f,o._generateDepthBuffer=l,o._generateStencilBuffer=h,o._samples=c,o.setTextures(d),o}updateRenderTargetTextureSampleCount(e,t){return rT.Y.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){let i=getNativeSamplingMode(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw Error("Required width/height for frame buffers not yet supported in NativeEngine.");e._framebufferDepthStencil?this._bindUnboundFramebuffer(e._framebufferDepthStencil):this._bindUnboundFramebuffer(e._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){let r=this._normalizeIndexData(t);e.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(e.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i,r){let s=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(e.nativeVertexBuffer,s.buffer,s.byteOffset+(null!=i?i:0),null!=r?r:s.byteLength)}_setTexture(e,t,i=!1,r=!1){let s;let n=this._boundUniforms[e];if(!n)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;return s=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!!s&&!!s._hardwareTexture&&(this._setTextureWrapMode(s._hardwareTexture.underlyingResource,getNativeAddressMode(t.wrapU),getNativeAddressMode(t.wrapV),getNativeAddressMode(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(n,s._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){let t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){let i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){let e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let e=new _native.Image;return e}updateTextureData(e,t,i,r,s,n,a=0,o=0,l=!1){throw Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,a=0){throw Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,r,s,n,a,o,l,h){var u,c,d,p;if(void 0!==r&&-1!==r)throw Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture(null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(c=null==n?void 0:n.buffer)&&void 0!==c?c:null,null!==(d=null==n?void 0:n.byteOffset)&&void 0!==d?d:0,null!==(p=null==n?void 0:n.byteLength)&&void 0!==p?p:0).then(e=>(n||(n=new Uint8Array(e)),n))}};NativeEngine.PROTOCOL_VERSION=8,NativeEngine._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new ValidatedNativeDataStream:new NativeDataStream};let ValidatedNativeDataStream=class ValidatedNativeDataStream extends NativeDataStream{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}};(L=tW||(tW={})).LowPower="low-power",L.HighPerformance="high-performance",(w=tH||(tH={})).DepthClipControl="depth-clip-control",w.Depth32FloatStencil8="depth32float-stencil8",w.TextureCompressionBC="texture-compression-bc",w.TextureCompressionETC2="texture-compression-etc2",w.TextureCompressionASTC="texture-compression-astc",w.TimestampQuery="timestamp-query",w.IndirectFirstInstance="indirect-first-instance",w.ShaderF16="shader-f16",w.RG11B10UFloatRenderable="rg11b10ufloat-renderable",w.BGRA8UnormStorage="bgra8unorm-storage",w.Float32Filterable="float32-filterable",(U=tX||(tX={})).Unmapped="unmapped",U.Pending="pending",U.Mapped="mapped",(V=tY||(tY={}))[V.MapRead=1]="MapRead",V[V.MapWrite=2]="MapWrite",V[V.CopySrc=4]="CopySrc",V[V.CopyDst=8]="CopyDst",V[V.Index=16]="Index",V[V.Vertex=32]="Vertex",V[V.Uniform=64]="Uniform",V[V.Storage=128]="Storage",V[V.Indirect=256]="Indirect",V[V.QueryResolve=512]="QueryResolve",(k=tj||(tj={}))[k.Read=1]="Read",k[k.Write=2]="Write",(G=tq||(tq={})).E1d="1d",G.E2d="2d",G.E3d="3d",(z=tK||(tK={}))[z.CopySrc=1]="CopySrc",z[z.CopyDst=2]="CopyDst",z[z.TextureBinding=4]="TextureBinding",z[z.StorageBinding=8]="StorageBinding",z[z.RenderAttachment=16]="RenderAttachment",(W=t$||(t$={})).E1d="1d",W.E2d="2d",W.E2dArray="2d-array",W.Cube="cube",W.CubeArray="cube-array",W.E3d="3d",(H=tQ||(tQ={})).All="all",H.StencilOnly="stencil-only",H.DepthOnly="depth-only",(X=tZ||(tZ={})).R8Unorm="r8unorm",X.R8Snorm="r8snorm",X.R8Uint="r8uint",X.R8Sint="r8sint",X.R16Uint="r16uint",X.R16Sint="r16sint",X.R16Float="r16float",X.RG8Unorm="rg8unorm",X.RG8Snorm="rg8snorm",X.RG8Uint="rg8uint",X.RG8Sint="rg8sint",X.R32Uint="r32uint",X.R32Sint="r32sint",X.R32Float="r32float",X.RG16Uint="rg16uint",X.RG16Sint="rg16sint",X.RG16Float="rg16float",X.RGBA8Unorm="rgba8unorm",X.RGBA8UnormSRGB="rgba8unorm-srgb",X.RGBA8Snorm="rgba8snorm",X.RGBA8Uint="rgba8uint",X.RGBA8Sint="rgba8sint",X.BGRA8Unorm="bgra8unorm",X.BGRA8UnormSRGB="bgra8unorm-srgb",X.RGB9E5UFloat="rgb9e5ufloat",X.RGB10A2UINT="rgb10a2uint",X.RGB10A2Unorm="rgb10a2unorm",X.RG11B10UFloat="rg11b10ufloat",X.RG32Uint="rg32uint",X.RG32Sint="rg32sint",X.RG32Float="rg32float",X.RGBA16Uint="rgba16uint",X.RGBA16Sint="rgba16sint",X.RGBA16Float="rgba16float",X.RGBA32Uint="rgba32uint",X.RGBA32Sint="rgba32sint",X.RGBA32Float="rgba32float",X.Stencil8="stencil8",X.Depth16Unorm="depth16unorm",X.Depth24Plus="depth24plus",X.Depth24PlusStencil8="depth24plus-stencil8",X.Depth32Float="depth32float",X.BC1RGBAUnorm="bc1-rgba-unorm",X.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",X.BC2RGBAUnorm="bc2-rgba-unorm",X.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",X.BC3RGBAUnorm="bc3-rgba-unorm",X.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",X.BC4RUnorm="bc4-r-unorm",X.BC4RSnorm="bc4-r-snorm",X.BC5RGUnorm="bc5-rg-unorm",X.BC5RGSnorm="bc5-rg-snorm",X.BC6HRGBUFloat="bc6h-rgb-ufloat",X.BC6HRGBFloat="bc6h-rgb-float",X.BC7RGBAUnorm="bc7-rgba-unorm",X.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",X.ETC2RGB8Unorm="etc2-rgb8unorm",X.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",X.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",X.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",X.ETC2RGBA8Unorm="etc2-rgba8unorm",X.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",X.EACR11Unorm="eac-r11unorm",X.EACR11Snorm="eac-r11snorm",X.EACRG11Unorm="eac-rg11unorm",X.EACRG11Snorm="eac-rg11snorm",X.ASTC4x4Unorm="astc-4x4-unorm",X.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",X.ASTC5x4Unorm="astc-5x4-unorm",X.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",X.ASTC5x5Unorm="astc-5x5-unorm",X.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",X.ASTC6x5Unorm="astc-6x5-unorm",X.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",X.ASTC6x6Unorm="astc-6x6-unorm",X.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",X.ASTC8x5Unorm="astc-8x5-unorm",X.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",X.ASTC8x6Unorm="astc-8x6-unorm",X.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",X.ASTC8x8Unorm="astc-8x8-unorm",X.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",X.ASTC10x5Unorm="astc-10x5-unorm",X.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",X.ASTC10x6Unorm="astc-10x6-unorm",X.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",X.ASTC10x8Unorm="astc-10x8-unorm",X.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",X.ASTC10x10Unorm="astc-10x10-unorm",X.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",X.ASTC12x10Unorm="astc-12x10-unorm",X.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",X.ASTC12x12Unorm="astc-12x12-unorm",X.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",X.Depth32FloatStencil8="depth32float-stencil8",(Y=tJ||(tJ={})).ClampToEdge="clamp-to-edge",Y.Repeat="repeat",Y.MirrorRepeat="mirror-repeat",(j=t0||(t0={})).Nearest="nearest",j.Linear="linear",(K=t1||(t1={})).Nearest="nearest",K.Linear="linear",($=t2||(t2={})).Never="never",$.Less="less",$.Equal="equal",$.LessEqual="less-equal",$.Greater="greater",$.NotEqual="not-equal",$.GreaterEqual="greater-equal",$.Always="always",(Q=t3||(t3={}))[Q.Vertex=1]="Vertex",Q[Q.Fragment=2]="Fragment",Q[Q.Compute=4]="Compute",(Z=t4||(t4={})).Uniform="uniform",Z.Storage="storage",Z.ReadOnlyStorage="read-only-storage",(J=t5||(t5={})).Filtering="filtering",J.NonFiltering="non-filtering",J.Comparison="comparison",(ee=t6||(t6={})).Float="float",ee.UnfilterableFloat="unfilterable-float",ee.Depth="depth",ee.Sint="sint",ee.Uint="uint",(t8||(t8={})).WriteOnly="write-only",(et=t7||(t7={})).Error="error",et.Warning="warning",et.Info="info",(ei=t9||(t9={})).Validation="validation",ei.Internal="internal",(ie||(ie={})).Auto="auto",(er=it||(it={})).PointList="point-list",er.LineList="line-list",er.LineStrip="line-strip",er.TriangleList="triangle-list",er.TriangleStrip="triangle-strip",(es=ii||(ii={})).CCW="ccw",es.CW="cw",(en=ir||(ir={})).None="none",en.Front="front",en.Back="back",(ea=is||(is={}))[ea.Red=1]="Red",ea[ea.Green=2]="Green",ea[ea.Blue=4]="Blue",ea[ea.Alpha=8]="Alpha",ea[ea.All=15]="All",(eo=ia||(ia={})).Zero="zero",eo.One="one",eo.Src="src",eo.OneMinusSrc="one-minus-src",eo.SrcAlpha="src-alpha",eo.OneMinusSrcAlpha="one-minus-src-alpha",eo.Dst="dst",eo.OneMinusDst="one-minus-dst",eo.DstAlpha="dst-alpha",eo.OneMinusDstAlpha="one-minus-dst-alpha",eo.SrcAlphaSaturated="src-alpha-saturated",eo.Constant="constant",eo.OneMinusConstant="one-minus-constant",(el=io||(io={})).Add="add",el.Subtract="subtract",el.ReverseSubtract="reverse-subtract",el.Min="min",el.Max="max",(eh=il||(il={})).Keep="keep",eh.Zero="zero",eh.Replace="replace",eh.Invert="invert",eh.IncrementClamp="increment-clamp",eh.DecrementClamp="decrement-clamp",eh.IncrementWrap="increment-wrap",eh.DecrementWrap="decrement-wrap",(eu=ih||(ih={})).Uint16="uint16",eu.Uint32="uint32",(ec=iu||(iu={})).Uint8x2="uint8x2",ec.Uint8x4="uint8x4",ec.Sint8x2="sint8x2",ec.Sint8x4="sint8x4",ec.Unorm8x2="unorm8x2",ec.Unorm8x4="unorm8x4",ec.Snorm8x2="snorm8x2",ec.Snorm8x4="snorm8x4",ec.Uint16x2="uint16x2",ec.Uint16x4="uint16x4",ec.Sint16x2="sint16x2",ec.Sint16x4="sint16x4",ec.Unorm16x2="unorm16x2",ec.Unorm16x4="unorm16x4",ec.Snorm16x2="snorm16x2",ec.Snorm16x4="snorm16x4",ec.Float16x2="float16x2",ec.Float16x4="float16x4",ec.Float32="float32",ec.Float32x2="float32x2",ec.Float32x3="float32x3",ec.Float32x4="float32x4",ec.Uint32="uint32",ec.Uint32x2="uint32x2",ec.Uint32x3="uint32x3",ec.Uint32x4="uint32x4",ec.Sint32="sint32",ec.Sint32x2="sint32x2",ec.Sint32x3="sint32x3",ec.Sint32x4="sint32x4",ec.UNORM10x10x10x2="unorm10-10-10-2",(ed=ic||(ic={})).Vertex="vertex",ed.Instance="instance",(ep=id||(id={})).Beginning="beginning",ep.End="end",(e_=ip||(ip={})).Beginning="beginning",e_.End="end",(ef=i_||(i_={})).Load="load",ef.Clear="clear",(em=im||(im={})).Store="store",em.Discard="discard",(eg=ig||(ig={})).Occlusion="occlusion",eg.Timestamp="timestamp",(ev=iv||(iv={})).Opaque="opaque",ev.Premultiplied="premultiplied",(ex=ix||(ix={})).Unknown="unknown",ex.Destroyed="destroyed",(eT=iT||(iT={})).Validation="validation",eT.OutOfMemory="out-of-memory",eT.Internal="internal";let WebGPUShaderProcessor=class WebGPUShaderProcessor{constructor(){this.shaderLanguage=sg.x.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let t=0;t=0&&(c.push(a[l]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=c,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){for(let e of(this.uniformBuffer=new rX.M(this.engine,void 0,void 0,"leftOver-"+this._name),this.shaderProcessingContext.leftOverUniforms)){let t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=WebGPUShaderProcessor.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.vertex}_getFragmentShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.fragment}};let ad={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};let WebGPUShaderProcessingContext=class WebGPUShaderProcessingContext{static get KnownUBOs(){return WebGPUShaderProcessingContext._SimplifiedKnownBindings?WebGPUShaderProcessingContext._SimplifiedKnownUBOs:WebGPUShaderProcessingContext._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){let e=WebGPUShaderProcessingContext.KnownUBOs,t=[];for(let i in e){let r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;let r=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=ad[e])&&void 0!==i?i:1)*(t||1),r}getVaryingNextLocation(e,t=0){var i;let r=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=ad[e])&&void 0!==i?i:1)*(t||1),r}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";let t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}};WebGPUShaderProcessingContext._SimplifiedKnownBindings=!0,WebGPUShaderProcessingContext._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},WebGPUShaderProcessingContext._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};let WebGPUShaderProcessorGLSL=class WebGPUShaderProcessorGLSL extends WebGPUShaderProcessor{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=sg.x.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0,s=e.indexOf("["),n=e.indexOf("]");if(s>0&&n>0){let t=e.substring(s+1,n);isNaN(r=+t)&&(r=+i[t.trim()]),e=e.substr(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){let i=`// Internals UBO -uniform ${WebGPUShaderProcessor.InternalsUBOName} { -float yFactor_; -float textureOutputHeight_; -}; -`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){let i=t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/;return i.test(e)}varyingProcessor(e,t,i){var r;this._preProcessors=i;let s=t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm,n=s.exec(e);if(null!==n){let s;let a=null!==(r=n[1])&&void 0!==r?r:"",o=n[2],l=n[3];t?(s=this._webgpuProcessingContext.availableVaryings[l],this._missingVaryings[s]="",void 0===s&&rT.Y.Warn(`Invalid fragment shader: The varying named "${l}" is not declared in the vertex shader! This declaration will be ignored.`)):(s=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(l,o,i)[2]),this._webgpuProcessingContext.availableVaryings[l]=s,this._missingVaryings[s]=`layout(location = ${s}) ${a} in ${o} ${l};`),e=e.replace(n[0],void 0===s?"":`layout(location = ${s}) ${a} ${t?"in":"out"} ${o} ${l};`)}return e}attributeProcessor(e,t){this._preProcessors=t;let i=this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm,r=i.exec(e);if(null!==r){let i=r[1],s=r[2],n=this._webgpuProcessingContext.getAttributeNextLocation(i,this._getArraySize(s,i,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;let a=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==a){let t=`_int_${s}_`;e=e.replace(r[0],`layout(location = ${n}) in ${a<0?-1===a?"int":"ivec"+-a:1===a?"uint":"uvec"+a} ${t}; ${i} ${s} = ${i}(${t});`)}else e=e.replace(r[0],`layout(location = ${n}) in ${i} ${s};`)}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;let s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let n=s[1],a=s[2];if(0===n.indexOf("sampler")||1===n.indexOf("sampler")){let s=0;[a,n,s]=this._getArraySize(a,n,i);let o=this._webgpuProcessingContext.availableTextures[a];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:t6.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}let l=null!==(r=WebGPUShaderProcessor._SamplerTypeByWebGLSamplerType[n])&&void 0!==r?r:"sampler",h=!!WebGPUShaderProcessor._IsComparisonSamplerByWebGPUSamplerType[l],u=h?t5.Comparison:t5.Filtering,c=a+WebGPUShaderProcessor.AutoSamplerSuffix,d=this._webgpuProcessingContext.availableSamplers[c];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:u});let p="u"===n.charAt(0)?"u":"i"===n.charAt(0)?"i":"";p&&(n=n.substr(1));let _=h?t6.Depth:"u"===p?t6.Uint:"i"===p?t6.Sint:t6.Float;o.sampleType=_;let f=s>0,m=d.binding.groupIndex,g=d.binding.bindingIndex,v=WebGPUShaderProcessor._SamplerFunctionByWebGLSamplerType[n],x=WebGPUShaderProcessor._TextureTypeByWebGLSamplerType[n],T=WebGPUShaderProcessor._GpuTextureViewDimensionByWebGPUTextureType[x];if(f){let t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${c};`),e=` -`;for(let i=0;i0?"\n":""}#define ${a}${i} ${p}${v}(${a}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(a)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${l} ${c}; - layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${p}${x} ${a}Texture; - #define ${a} ${p}${v}(${a}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[a]=o,this._webgpuProcessingContext.availableSamplers[c]=d,this._addSamplerBindingDescription(c,d,!t);for(let e=0;e=0,i=` - glFragCoord_ = gl_FragCoord; - if (yFactor_ == 1.) { - glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; - } - `,r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(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(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){let t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",t?"vec4 glFragCoord_;\n":""),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else{e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex");let i=-1!==t.indexOf("#define MULTIVIEW");if(i)return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}if(!i){let t=e.lastIndexOf("}");e=e.substring(0,t)+"gl_Position.y *= yFactor_;\n",s.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){let i=RegExp(t+"\\s*\\[(.+)?\\]","gm"),r=i.exec(e);for(;null!==r;){let s=r[1],n=+s;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+n),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { - `;for(let e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}]; -`:i+=` ${e.type} ${e.name}; -`;return i+"};\n\n"}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}let i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}};let ap=`#if NUM_BONE_INFLUENCERS>0 -attribute matricesIndices : vec4;attribute matricesWeights : vec4; -#if NUM_BONE_INFLUENCERS>4 -attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; -#endif -#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#ifdef BONETEXTURE -var boneSampler : texture_2d;uniform boneTextureWidth : f32; -#else -uniform mBones : array; -#ifdef BONES_VELOCITY_ENABLED -uniform mPreviousBones : array; -#endif -#endif -#ifdef BONETEXTURE -fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 -{let offset=i32(index) *4; -let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} -#endif -#endif -#endif -`;s_.v.IncludesShadersStoreWGSL.bonesDeclaration=ap;let a_=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE -#if NUM_BONE_INFLUENCERS>0 -var influence : mat4x4; -#ifdef BONETEXTURE -influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; -#endif -#else -influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; -#endif -#endif -finalWorld=finalWorld*influence; -#endif -#endif -`;s_.v.IncludesShadersStoreWGSL.bonesVertex=a_;let af=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; -#ifdef INSTANCES -attribute bakedVertexAnimationSettingsInstanced : vec4; -#endif -fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 -{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} -#endif -`;s_.v.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration=af;let am=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE -{ -#ifdef INSTANCES -let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; -#else -let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; -#endif -let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; -#endif -finalWorld=finalWorld*VATInfluence;} -#endif -`;s_.v.IncludesShadersStoreWGSL.bakedVertexAnimation=am;let ag=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -if (false) {} -#endif -#ifdef CLIPPLANE -else if (fragmentInputs.fClipDistance>0.0) -{discard;} -#endif -#ifdef CLIPPLANE2 -else if (fragmentInputs.fClipDistance2>0.0) -{discard;} -#endif -#ifdef CLIPPLANE3 -else if (fragmentInputs.fClipDistance3>0.0) -{discard;} -#endif -#ifdef CLIPPLANE4 -else if (fragmentInputs.fClipDistance4>0.0) -{discard;} -#endif -#ifdef CLIPPLANE5 -else if (fragmentInputs.fClipDistance5>0.0) -{discard;} -#endif -#ifdef CLIPPLANE6 -else if (fragmentInputs.fClipDistance6>0.0) -{discard;} -#endif -`;s_.v.IncludesShadersStoreWGSL.clipPlaneFragment=ag;let av=`#ifdef CLIPPLANE -varying fClipDistance: f32; -#endif -#ifdef CLIPPLANE2 -varying fClipDistance2: f32; -#endif -#ifdef CLIPPLANE3 -varying fClipDistance3: f32; -#endif -#ifdef CLIPPLANE4 -varying fClipDistance4: f32; -#endif -#ifdef CLIPPLANE5 -varying fClipDistance5: f32; -#endif -#ifdef CLIPPLANE6 -varying fClipDistance6: f32; -#endif -`;s_.v.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration=av;let ax=`#ifdef CLIPPLANE -vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); -#endif -#ifdef CLIPPLANE2 -vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); -#endif -#ifdef CLIPPLANE3 -vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); -#endif -#ifdef CLIPPLANE4 -vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); -#endif -#ifdef CLIPPLANE5 -vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); -#endif -#ifdef CLIPPLANE6 -vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); -#endif -`;s_.v.IncludesShadersStoreWGSL.clipPlaneVertex=ax;let aT=`#ifdef CLIPPLANE -uniform vClipPlane: vec4;varying fClipDistance: f32; -#endif -#ifdef CLIPPLANE2 -uniform vClipPlane2: vec4;varying fClipDistance2: f32; -#endif -#ifdef CLIPPLANE3 -uniform vClipPlane3: vec4;varying fClipDistance3: f32; -#endif -#ifdef CLIPPLANE4 -uniform vClipPlane4: vec4;varying fClipDistance4: f32; -#endif -#ifdef CLIPPLANE5 -uniform vClipPlane5: vec4;varying fClipDistance5: f32; -#endif -#ifdef CLIPPLANE6 -uniform vClipPlane6: vec4;varying fClipDistance6: f32; -#endif -`;s_.v.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration=aT;let aS=`#ifdef INSTANCES -attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; -#ifdef INSTANCESCOLOR -attribute instanceColor : vec4; -#endif -#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) -uniform world : mat4x4; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; -#ifdef THIN_INSTANCES -uniform previousWorld : mat4x4; -#endif -#endif -#else -#if !defined(WORLD_UBO) -uniform world : mat4x4; -#endif -#if defined(VELOCITY) || defined(PREPASS_VELOCITY) -uniform previousWorld : mat4x4; -#endif -#endif -`;s_.v.IncludesShadersStoreWGSL.instancesDeclaration=aS;let aC=`#ifdef INSTANCES -var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -var finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); -#endif -#ifdef THIN_INSTANCES -#if !defined(WORLD_UBO) -finalWorld=uniforms.world*finalWorld; -#else -finalWorld=mesh.world*finalWorld; -#endif -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -finalPreviousWorld=previousWorld*finalPreviousWorld; -#endif -#endif -#else -#if !defined(WORLD_UBO) -var finalWorld=uniforms.world; -#else -var finalWorld=mesh.world; -#endif -#if defined(PREPASS_VELOCITY) || defined(VELOCITY) -var finalPreviousWorld=previousWorld; -#endif -#endif -`;s_.v.IncludesShadersStoreWGSL.instancesVertex=aC;let aE=`struct Mesh {world : mat4x4, -visibility : f32,};var mesh : Mesh; -#define WORLD_UBO -`;s_.v.IncludesShadersStoreWGSL.meshUboDeclaration=aE;let ab=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#ifdef MORPHTARGETS_NORMAL -normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; -#endif -#else -positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; -#ifdef MORPHTARGETS_NORMAL -normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_TANGENT -tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; -#endif -#ifdef MORPHTARGETS_UV -uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; -#endif -#endif -#endif -`;s_.v.IncludesShadersStoreWGSL.morphTargetsVertex=ab;let ay=`#ifdef MORPHTARGETS -#ifndef MORPHTARGETS_TEXTURE -attribute position{X} : vec3; -#ifdef MORPHTARGETS_NORMAL -attribute normal{X} : vec3; -#endif -#ifdef MORPHTARGETS_TANGENT -attribute tangent{X} : vec3; -#endif -#ifdef MORPHTARGETS_UV -attribute uv_{X} : vec2; -#endif -#endif -#endif -`;s_.v.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration=ay;let aP=`#ifdef MORPHTARGETS -#ifdef MORPHTARGETS_TEXTURE -var vertexID : f32; -#endif -#endif -`;s_.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobal=aP;let aR=`#ifdef MORPHTARGETS -uniform morphTargetInfluences : array; -#ifdef MORPHTARGETS_TEXTURE -uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 -{ -let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} -#endif -#endif -`;s_.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration=aR;let aA=`struct Scene {viewProjection : mat4x4, -#ifdef MULTIVIEW -viewProjectionR : mat4x4, -#endif -view : mat4x4, -projection : mat4x4, -vEyePosition : vec4,};var scene : Scene; -`;s_.v.IncludesShadersStoreWGSL.sceneUboDeclaration=aA;let aI="fragmentOutputs.fragDepth",aM={texture_1d:t$.E1d,texture_2d:t$.E2d,texture_2d_array:t$.E2dArray,texture_3d:t$.E3d,texture_cube:t$.Cube,texture_cube_array:t$.CubeArray,texture_multisampled_2d:t$.E2d,texture_depth_2d:t$.E2d,texture_depth_2d_array:t$.E2dArray,texture_depth_cube:t$.Cube,texture_depth_cube_array:t$.CubeArray,texture_depth_multisampled_2d:t$.E2d,texture_storage_1d:t$.E1d,texture_storage_2d:t$.E2d,texture_storage_2d_array:t$.E2dArray,texture_storage_3d:t$.E3d,texture_external:null};let WebGPUShaderProcessorWGSL=class WebGPUShaderProcessorWGSL extends WebGPUShaderProcessor{constructor(){super(...arguments),this.shaderLanguage=sg.x.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let r=0,s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;let n=t.substring(e+1,s);for(isNaN(r=+n)&&(r=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${WebGPUShaderProcessor.InternalsUBOName} { - yFactor_: f32, - textureOutputHeight_: f32, -}; -var internals : ${WebGPUShaderProcessor.InternalsUBOName}; -`+RemoveComments(e)}varyingProcessor(e,t,i){let r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==r){let s;let n=r[2],a=r[1];t?void 0===(s=this._webgpuProcessingContext.availableVaryings[a])&&rT.Y.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`):(s=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(a,n,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=s,this._varyingsWGSL.push(` @location(${s}) ${a} : ${n},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){let i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){let r=i[2],s=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;let a=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==a){let e=`_int_${s}_`;this._attributesInputWGSL.push(`@location(${n}) ${e} : ${a<0?-1===a?"i32":"vec"+-a+"":1===a?"u32":"vec"+a+""},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = ${r}(vertexInputs_.${e});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${s} : ${r},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = vertexInputs_.${s};`);e=""}return e}uniformProcessor(e,t,i){let r=this.uniformRegexp.exec(e);if(null!==r){let t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){let r=this.textureRegexp.exec(e);if(null!==r){let s=r[1],n=r[2],a=!!r[3],o=r[4],l=o.indexOf("storage")>0,h=r[6],u=l?h.substring(0,h.indexOf(",")).trim():null,c=a?this._getArraySize(s,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)c=d.textures.length;else{d={isTextureArray:c>0,isStorageTexture:l,textures:[],sampleType:t6.Float},c=c||1;for(let e=0;e0,_=aM[o],f=p?t6.Depth:"u32"===h?t6.Uint:"i32"===h?t6.Sint:t6.Float;if(d.sampleType=f,void 0===_)throw`Can't get the texture dimension corresponding to the texture function "${o}"!`;for(let i=0;i=0?` - if (internals.yFactor_ == 1.) { - fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; - } - `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);let r=this._buildLeftOverUBO();e=r+e,t=r+t,e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join("\n")),s+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(s+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n"+this._attributesWGSL.join("\n")+"\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=s+n+e;let a=` - vertexInputs${this._hasNonFloatAttribute?"_":""} = input; -`;this._hasNonFloatAttribute&&(a+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n"+this._attributesConversionCodeWGSL.join("\n")+"\n");let o=` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; - return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",a,o),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4,\n",u=!1,c=0;for(;!u&&!((c=t.indexOf(aI,c))<0);){let e=c;for(u=!0;c>1&&"\n"!==t.charAt(c);){if("/"===t.charAt(c)&&"/"===t.charAt(c-1)){u=!1;break}c--}c=e+aI.length}return u&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=l+h+t,t=this._injectStartingAndEndingCode(t,"fn main"," fragmentInputs = input;\n "+i," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { -`;for(let t of this._webgpuProcessingContext.leftOverUniforms){let s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=WebGPUShaderProcessor.UniformSizes[s];if(t.length>0){if(n<=2){let n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} { - @size(16) - el: ${s}, - }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${n}, ${t.length}>, -`}else r+=` ${t.name} : array<${t.type}, ${t.length}>, -`}else r+=` ${t.name} : ${t.type}, -`}return r+="};\n",r=`${i} -${r}@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e}; -`}_processSamplers(e,t){let i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[2],a=s.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)===s.length-WebGPUShaderProcessor.AutoSamplerSuffix.length?s.substring(0,s.indexOf(WebGPUShaderProcessor.AutoSamplerSuffix)):null,o="sampler_comparison"===n?t5.Comparison:t5.Filtering;if(a){let e=this._webgpuProcessingContext.availableTextures[a];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:o},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);let h=e.substring(0,r.index),u=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `,c=e.substring(r.index);e=h+u+c,i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){let i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[3],a=r[4],o=r[5],l=this._webgpuProcessingContext.availableBuffers[a];if(!l){let e;let t="uniform"===s?WebGPUShaderProcessingContext.KnownUBOs[o]:null;t?(a=o,-1===(e=t.binding).groupIndex&&(e=this._webgpuProcessingContext.getNextFreeUBOBinding())):e=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:e},this._webgpuProcessingContext.availableBuffers[a]=l}this._addBufferBindingDescription(a,this._webgpuProcessingContext.availableBuffers[a],"read_write"===n?t4.Storage:"storage"===s?t4.ReadOnlyStorage:t4.Uniform,t);let h=l.binding.groupIndex,u=l.binding.bindingIndex,c=e.substring(0,r.index),d=`@group(${h}) @binding(${u}) `,p=e.substring(r.index);e=c+d+p,i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(let t of this._stridedUniformArrays)e=e.replace(RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}};let WebGPUHardwareTexture=class WebGPUHardwareTexture{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return null!==(i=null===(t=this._webgpuMSAATexture)||void 0===t?void 0:t[e])&&void 0!==i?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(let e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=tZ.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s){this.createView({format:this.format,dimension:i?t$.Cube:t$.E2d,mipLevelCount:t?rE.R.ILog2(Math.max(r,s))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:i?6:1,aspect:tQ.All})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){let t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;null===(e=this._webgpuTexture)||void 0===e||e.destroy(),this.releaseMSAATexture(),null===(t=this._copyInvertYTempTexture)||void 0===t||t.destroy(),this.reset()}};let aD=` - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); - - layout(location = 0) out vec2 vTex; - - void main() { - vTex = tex[gl_VertexIndex]; - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,aO=` - layout(set = 0, binding = 0) uniform sampler imgSampler; - layout(set = 0, binding = 1) uniform texture2D img; - - layout(location = 0) in vec2 vTex; - layout(location = 0) out vec4 outColor; - - void main() { - outColor = texture(sampler2D(img, imgSampler), vTex); - } - `,aN=` - #extension GL_EXT_samplerless_texture_functions : enable - - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); - - layout(set = 0, binding = 0) uniform texture2D img; - - #ifdef INVERTY - layout(location = 0) out flat ivec2 vTextureSize; - #endif - - void main() { - #ifdef INVERTY - vTextureSize = textureSize(img, 0); - #endif - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,aF=` - #extension GL_EXT_samplerless_texture_functions : enable - - layout(set = 0, binding = 0) uniform texture2D img; - - #ifdef INVERTY - layout(location = 0) in flat ivec2 vTextureSize; - #endif - layout(location = 0) out vec4 outColor; - - void main() { - #ifdef INVERTY - vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); - #else - vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); - #endif - #ifdef PREMULTIPLYALPHA - color.rgb *= color.a; - #endif - outColor = color; - } - `,aB=` - #extension GL_EXT_samplerless_texture_functions : enable - - layout(set = 0, binding = 0) uniform texture2D img; - layout(set = 0, binding = 1) uniform Params { - float ofstX; - float ofstY; - float width; - float height; - }; - - #ifdef INVERTY - layout(location = 0) in flat ivec2 vTextureSize; - #endif - layout(location = 0) out vec4 outColor; - - void main() { - if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { - discard; - } - if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { - discard; - } - #ifdef INVERTY - vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); - #else - vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); - #endif - #ifdef PREMULTIPLYALPHA - color.rgb *= color.a; - #endif - outColor = color; - } - `,aL=` - const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); - - void main() { - gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); - } - `,aw=` - layout(set = 0, binding = 0) uniform Uniforms { - uniform vec4 color; - }; - - layout(location = 0) out vec4 outColor; - - void main() { - outColor = color; - } - `,aU=` - struct VertexOutput { - @builtin(position) Position : vec4, - @location(0) fragUV : vec2 - } - - @vertex - fn main( - @builtin(vertex_index) VertexIndex : u32 - ) -> VertexOutput { - var pos = array, 4>( - vec2(-1.0, 1.0), - vec2( 1.0, 1.0), - vec2(-1.0, -1.0), - vec2( 1.0, -1.0) - ); - var tex = array, 4>( - vec2(0.0, 0.0), - vec2(1.0, 0.0), - vec2(0.0, 1.0), - vec2(1.0, 1.0) - ); - - var output: VertexOutput; - - output.Position = vec4(pos[VertexIndex], 0.0, 1.0); - output.fragUV = tex[VertexIndex]; - - return output; - } - `,aV=` - @group(0) @binding(0) var videoSampler: sampler; - @group(0) @binding(1) var videoTexture: texture_external; - - @fragment - fn main( - @location(0) fragUV: vec2 - ) -> @location(0) vec4 { - return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); - } - `,ak=` - @group(0) @binding(0) var videoSampler: sampler; - @group(0) @binding(1) var videoTexture: texture_external; - - @fragment - fn main( - @location(0) fragUV: vec2 - ) -> @location(0) vec4 { - return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y)); - } - `;(eS=iS||(iS={}))[eS.MipMap=0]="MipMap",eS[eS.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",eS[eS.Clear=2]="Clear",eS[eS.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst",(eC=iC||(iC={}))[eC.DontInvertY=0]="DontInvertY",eC[eC.InvertY=1]="InvertY";let aG=[{vertex:aD,fragment:aO},{vertex:aN,fragment:aF},{vertex:aL,fragment:aw},{vertex:aN,fragment:aB}],az={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};let WebGPUTextureHelper=class WebGPUTextureHelper{static ComputeNumMipmapLevels(e,t){return rE.R.ILog2(Math.max(e,t))+1}constructor(e,t,i,r,s){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._device=e,this._glslang=t,this._tintWASM=i,this._bufferManager=r,-1!==s.indexOf(tH.RG11B10UFloatRenderable)){let e=Object.keys(az);az[tZ.RG11B10UFloat]=az[e[e.length-1]]+1}this._mipmapSampler=e.createSampler({minFilter:t0.Linear}),this._videoSampler=e.createSampler({minFilter:t0.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,tY.Uniform|tY.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(tZ.RGBA8Unorm),this._getVideoPipeline(tZ.RGBA8Unorm)}_getPipeline(e,t=iS.MipMap,i){let r=t===iS.MipMap?1:t===iS.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===iS.Clear?8:t===iS.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let n="#version 450\n";(t===iS.InvertYPremultiplyAlpha||t===iS.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let a=this._compiledShaders[r];if(!a){let e=this._glslang.compileGLSL(n+aG[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+aG[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));let s=this._device.createShaderModule({code:e}),o=this._device.createShaderModule({code:i});a=this._compiledShaders[r]=[s,o]}let o=this._device.createRenderPipeline({layout:ie.Auto,vertex:{module:a[0],entryPoint:"main"},fragment:{module:a[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:it.TriangleStrip,stripIndexFormat:ih.Uint16}});s=this._pipelines[e][r]=[o,o.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=iC.DontInvertY){let i=t===iC.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){let e=this._device.createShaderModule({code:aU}),r=this._device.createShaderModule({code:0===i?aV:ak});t=this._videoCompiledShaders[i]=[e,r]}let s=this._device.createRenderPipeline({label:`CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:ie.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:it.TriangleStrip,stripIndexFormat:ih.Uint16}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}static _GetTextureTypeFromFormat(e){switch(e){case tZ.R8Unorm:case tZ.R8Snorm:case tZ.R8Uint:case tZ.R8Sint:case tZ.RG8Unorm:case tZ.RG8Snorm:case tZ.RG8Uint:case tZ.RG8Sint:case tZ.RGBA8Unorm:case tZ.RGBA8UnormSRGB:case tZ.RGBA8Snorm:case tZ.RGBA8Uint:case tZ.RGBA8Sint:case tZ.BGRA8Unorm:case tZ.BGRA8UnormSRGB:case tZ.RGB10A2UINT:case tZ.RGB10A2Unorm:case tZ.RGB9E5UFloat:case tZ.RG11B10UFloat:case tZ.Depth32FloatStencil8:case tZ.BC7RGBAUnorm:case tZ.BC7RGBAUnormSRGB:case tZ.BC6HRGBUFloat:case tZ.BC6HRGBFloat:case tZ.BC5RGUnorm:case tZ.BC5RGSnorm:case tZ.BC3RGBAUnorm:case tZ.BC3RGBAUnormSRGB:case tZ.BC2RGBAUnorm:case tZ.BC2RGBAUnormSRGB:case tZ.BC4RUnorm:case tZ.BC4RSnorm:case tZ.BC1RGBAUnorm:case tZ.BC1RGBAUnormSRGB:case tZ.ETC2RGB8Unorm:case tZ.ETC2RGB8UnormSRGB:case tZ.ETC2RGB8A1Unorm:case tZ.ETC2RGB8A1UnormSRGB:case tZ.ETC2RGBA8Unorm:case tZ.ETC2RGBA8UnormSRGB:case tZ.EACR11Unorm:case tZ.EACR11Snorm:case tZ.EACRG11Unorm:case tZ.EACRG11Snorm:case tZ.ASTC4x4Unorm:case tZ.ASTC4x4UnormSRGB:case tZ.ASTC5x4Unorm:case tZ.ASTC5x4UnormSRGB:case tZ.ASTC5x5Unorm:case tZ.ASTC5x5UnormSRGB:case tZ.ASTC6x5Unorm:case tZ.ASTC6x5UnormSRGB:case tZ.ASTC6x6Unorm:case tZ.ASTC6x6UnormSRGB:case tZ.ASTC8x5Unorm:case tZ.ASTC8x5UnormSRGB:case tZ.ASTC8x6Unorm:case tZ.ASTC8x6UnormSRGB:case tZ.ASTC8x8Unorm:case tZ.ASTC8x8UnormSRGB:case tZ.ASTC10x5Unorm:case tZ.ASTC10x5UnormSRGB:case tZ.ASTC10x6Unorm:case tZ.ASTC10x6UnormSRGB:case tZ.ASTC10x8Unorm:case tZ.ASTC10x8UnormSRGB:case tZ.ASTC10x10Unorm:case tZ.ASTC10x10UnormSRGB:case tZ.ASTC12x10Unorm:case tZ.ASTC12x10UnormSRGB:case tZ.ASTC12x12Unorm:case tZ.ASTC12x12UnormSRGB:break;case tZ.R16Uint:case tZ.R16Sint:case tZ.RG16Uint:case tZ.RG16Sint:case tZ.RGBA16Uint:case tZ.RGBA16Sint:case tZ.Depth16Unorm:return 5;case tZ.R16Float:case tZ.RG16Float:case tZ.RGBA16Float:return 2;case tZ.R32Uint:case tZ.R32Sint:case tZ.RG32Uint:case tZ.RG32Sint:case tZ.RGBA32Uint:case tZ.RGBA32Sint:return 7;case tZ.R32Float:case tZ.RG32Float:case tZ.RGBA32Float:case tZ.Depth32Float:return 1;case tZ.Stencil8:throw"No fixed size for Stencil8 format!";case tZ.Depth24Plus:throw"No fixed size for Depth24Plus format!";case tZ.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!"}return 0}static _GetBlockInformationFromFormat(e){switch(e){case tZ.R8Unorm:case tZ.R8Snorm:case tZ.R8Uint:case tZ.R8Sint:return{width:1,height:1,length:1};case tZ.R16Uint:case tZ.R16Sint:case tZ.R16Float:case tZ.RG8Unorm:case tZ.RG8Snorm:case tZ.RG8Uint:case tZ.RG8Sint:return{width:1,height:1,length:2};case tZ.R32Uint:case tZ.R32Sint:case tZ.R32Float:case tZ.RG16Uint:case tZ.RG16Sint:case tZ.RG16Float:case tZ.RGBA8Unorm:case tZ.RGBA8UnormSRGB:case tZ.RGBA8Snorm:case tZ.RGBA8Uint:case tZ.RGBA8Sint:case tZ.BGRA8Unorm:case tZ.BGRA8UnormSRGB:case tZ.RGB9E5UFloat:case tZ.RGB10A2UINT:case tZ.RGB10A2Unorm:case tZ.RG11B10UFloat:break;case tZ.RG32Uint:case tZ.RG32Sint:case tZ.RG32Float:case tZ.RGBA16Uint:case tZ.RGBA16Sint:case tZ.RGBA16Float:return{width:1,height:1,length:8};case tZ.RGBA32Uint:case tZ.RGBA32Sint:case tZ.RGBA32Float:return{width:1,height:1,length:16};case tZ.Stencil8:throw"No fixed size for Stencil8 format!";case tZ.Depth16Unorm:return{width:1,height:1,length:2};case tZ.Depth24Plus:throw"No fixed size for Depth24Plus format!";case tZ.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case tZ.Depth32Float:break;case tZ.Depth32FloatStencil8:return{width:1,height:1,length:5};case tZ.BC7RGBAUnorm:case tZ.BC7RGBAUnormSRGB:case tZ.BC6HRGBUFloat:case tZ.BC6HRGBFloat:case tZ.BC5RGUnorm:case tZ.BC5RGSnorm:case tZ.BC3RGBAUnorm:case tZ.BC3RGBAUnormSRGB:case tZ.BC2RGBAUnorm:case tZ.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case tZ.BC4RUnorm:case tZ.BC4RSnorm:case tZ.BC1RGBAUnorm:case tZ.BC1RGBAUnormSRGB:case tZ.ETC2RGB8Unorm:case tZ.ETC2RGB8UnormSRGB:case tZ.ETC2RGB8A1Unorm:case tZ.ETC2RGB8A1UnormSRGB:case tZ.EACR11Unorm:case tZ.EACR11Snorm:return{width:4,height:4,length:8};case tZ.ETC2RGBA8Unorm:case tZ.ETC2RGBA8UnormSRGB:case tZ.EACRG11Unorm:case tZ.EACRG11Snorm:case tZ.ASTC4x4Unorm:case tZ.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case tZ.ASTC5x4Unorm:case tZ.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case tZ.ASTC5x5Unorm:case tZ.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case tZ.ASTC6x5Unorm:case tZ.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case tZ.ASTC6x6Unorm:case tZ.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case tZ.ASTC8x5Unorm:case tZ.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case tZ.ASTC8x6Unorm:case tZ.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case tZ.ASTC8x8Unorm:case tZ.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case tZ.ASTC10x5Unorm:case tZ.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case tZ.ASTC10x6Unorm:case tZ.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case tZ.ASTC10x8Unorm:case tZ.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case tZ.ASTC10x10Unorm:case tZ.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case tZ.ASTC12x10Unorm:case tZ.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case tZ.ASTC12x12Unorm:case tZ.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static _IsHardwareTexture(e){return!!e.release}static _IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}setCommandEncoder(e){this._commandEncoderForCreation=e}static IsCompressedFormat(e){switch(e){case tZ.BC7RGBAUnormSRGB:case tZ.BC7RGBAUnorm:case tZ.BC6HRGBFloat:case tZ.BC6HRGBUFloat:case tZ.BC5RGSnorm:case tZ.BC5RGUnorm:case tZ.BC4RSnorm:case tZ.BC4RUnorm:case tZ.BC3RGBAUnormSRGB:case tZ.BC3RGBAUnorm:case tZ.BC2RGBAUnormSRGB:case tZ.BC2RGBAUnorm:case tZ.BC1RGBAUnormSRGB:case tZ.BC1RGBAUnorm:case tZ.ETC2RGB8Unorm:case tZ.ETC2RGB8UnormSRGB:case tZ.ETC2RGB8A1Unorm:case tZ.ETC2RGB8A1UnormSRGB:case tZ.ETC2RGBA8Unorm:case tZ.ETC2RGBA8UnormSRGB:case tZ.EACR11Unorm:case tZ.EACR11Snorm:case tZ.EACRG11Unorm:case tZ.EACRG11Snorm:case tZ.ASTC4x4Unorm:case tZ.ASTC4x4UnormSRGB:case tZ.ASTC5x4Unorm:case tZ.ASTC5x4UnormSRGB:case tZ.ASTC5x5Unorm:case tZ.ASTC5x5UnormSRGB:case tZ.ASTC6x5Unorm:case tZ.ASTC6x5UnormSRGB:case tZ.ASTC6x6Unorm:case tZ.ASTC6x6UnormSRGB:case tZ.ASTC8x5Unorm:case tZ.ASTC8x5UnormSRGB:case tZ.ASTC8x6Unorm:case tZ.ASTC8x6UnormSRGB:case tZ.ASTC8x8Unorm:case tZ.ASTC8x8UnormSRGB:case tZ.ASTC10x5Unorm:case tZ.ASTC10x5UnormSRGB:case tZ.ASTC10x6Unorm:case tZ.ASTC10x6UnormSRGB:case tZ.ASTC10x8Unorm:case tZ.ASTC10x8UnormSRGB:case tZ.ASTC10x10Unorm:case tZ.ASTC10x10UnormSRGB:case tZ.ASTC12x10Unorm:case tZ.ASTC12x10UnormSRGB:case tZ.ASTC12x12Unorm:case tZ.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return tZ.Depth16Unorm;case 16:return tZ.Depth24Plus;case 13:return tZ.Depth24PlusStencil8;case 14:return tZ.Depth32Float;case 18:return tZ.Depth32FloatStencil8;case 19:return tZ.Stencil8;case 36492:return i?tZ.BC7RGBAUnormSRGB:tZ.BC7RGBAUnorm;case 36495:return tZ.BC6HRGBUFloat;case 36494:return tZ.BC6HRGBFloat;case 33779:return i?tZ.BC3RGBAUnormSRGB:tZ.BC3RGBAUnorm;case 33778:return i?tZ.BC2RGBAUnormSRGB:tZ.BC2RGBAUnorm;case 33777:case 33776:return i?tZ.BC1RGBAUnormSRGB:tZ.BC1RGBAUnorm;case 37808:return i?tZ.ASTC4x4UnormSRGB:tZ.ASTC4x4Unorm;case 36196:case 37492:return i?tZ.ETC2RGB8UnormSRGB:tZ.ETC2RGB8Unorm;case 37496:return i?tZ.ETC2RGBA8UnormSRGB:tZ.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return tZ.R8Snorm;case 7:return tZ.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return tZ.R8Sint;case 9:return tZ.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return tZ.RGBA8Sint;default:return tZ.RGBA8Snorm}case 0:switch(t){case 6:return tZ.R8Unorm;case 7:return tZ.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?tZ.RGBA8UnormSRGB:tZ.RGBA8Unorm;case 12:return i?tZ.BGRA8UnormSRGB:tZ.BGRA8Unorm;case 8:return tZ.R8Uint;case 9:return tZ.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return tZ.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return tZ.RGBA8Unorm}case 4:switch(t){case 8:return tZ.R16Sint;case 9:return tZ.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tZ.RGBA16Sint}case 5:switch(t){case 8:return tZ.R16Uint;case 9:return tZ.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tZ.RGBA16Uint}case 6:switch(t){case 8:return tZ.R32Sint;case 9:return tZ.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tZ.RGBA32Sint}case 7:switch(t){case 8:return tZ.R32Uint;case 9:return tZ.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tZ.RGBA32Uint}case 1:switch(t){case 6:return tZ.R32Float;case 7:return tZ.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return tZ.RGBA32Float}case 2:switch(t){case 6:return tZ.R16Float;case 7:return tZ.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return tZ.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return tZ.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return tZ.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return tZ.RGB10A2Unorm;case 11:return tZ.RGB10A2UINT}}return i?tZ.RGBA8UnormSRGB:tZ.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case tZ.R8Unorm:case tZ.R8Snorm:case tZ.R8Uint:case tZ.R8Sint:case tZ.BC4RUnorm:case tZ.BC4RSnorm:case tZ.R16Uint:case tZ.R16Sint:case tZ.Depth16Unorm:case tZ.R16Float:case tZ.R32Uint:case tZ.R32Sint:case tZ.R32Float:case tZ.Depth32Float:case tZ.Stencil8:case tZ.Depth24Plus:case tZ.EACR11Unorm:case tZ.EACR11Snorm:return 1;case tZ.RG8Unorm:case tZ.RG8Snorm:case tZ.RG8Uint:case tZ.RG8Sint:case tZ.Depth32FloatStencil8:case tZ.BC5RGUnorm:case tZ.BC5RGSnorm:case tZ.RG16Uint:case tZ.RG16Sint:case tZ.RG16Float:case tZ.RG32Uint:case tZ.RG32Sint:case tZ.RG32Float:case tZ.Depth24PlusStencil8:case tZ.EACRG11Unorm:case tZ.EACRG11Snorm:return 2;case tZ.RGB9E5UFloat:case tZ.RG11B10UFloat:case tZ.BC6HRGBUFloat:case tZ.BC6HRGBFloat:case tZ.ETC2RGB8Unorm:case tZ.ETC2RGB8UnormSRGB:return 3;case tZ.RGBA8Unorm:case tZ.RGBA8UnormSRGB:case tZ.RGBA8Snorm:case tZ.RGBA8Uint:case tZ.RGBA8Sint:case tZ.BGRA8Unorm:case tZ.BGRA8UnormSRGB:case tZ.RGB10A2UINT:case tZ.RGB10A2Unorm:case tZ.BC7RGBAUnorm:case tZ.BC7RGBAUnormSRGB:case tZ.BC3RGBAUnorm:case tZ.BC3RGBAUnormSRGB:case tZ.BC2RGBAUnorm:case tZ.BC2RGBAUnormSRGB:case tZ.BC1RGBAUnorm:case tZ.BC1RGBAUnormSRGB:case tZ.RGBA16Uint:case tZ.RGBA16Sint:case tZ.RGBA16Float:case tZ.RGBA32Uint:case tZ.RGBA32Sint:case tZ.RGBA32Float:case tZ.ETC2RGB8A1Unorm:case tZ.ETC2RGB8A1UnormSRGB:case tZ.ETC2RGBA8Unorm:case tZ.ETC2RGBA8UnormSRGB:case tZ.ASTC4x4Unorm:case tZ.ASTC4x4UnormSRGB:case tZ.ASTC5x4Unorm:case tZ.ASTC5x4UnormSRGB:case tZ.ASTC5x5Unorm:case tZ.ASTC5x5UnormSRGB:case tZ.ASTC6x5Unorm:case tZ.ASTC6x5UnormSRGB:case tZ.ASTC6x6Unorm:case tZ.ASTC6x6UnormSRGB:case tZ.ASTC8x5Unorm:case tZ.ASTC8x5UnormSRGB:case tZ.ASTC8x6Unorm:case tZ.ASTC8x6UnormSRGB:case tZ.ASTC8x8Unorm:case tZ.ASTC8x8UnormSRGB:case tZ.ASTC10x5Unorm:case tZ.ASTC10x5UnormSRGB:case tZ.ASTC10x6Unorm:case tZ.ASTC10x6UnormSRGB:case tZ.ASTC10x8Unorm:case tZ.ASTC10x8UnormSRGB:case tZ.ASTC10x10Unorm:case tZ.ASTC10x10UnormSRGB:case tZ.ASTC12x10Unorm:case tZ.ASTC12x10UnormSRGB:case tZ.ASTC12x12Unorm:case tZ.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case tZ.Stencil8:case tZ.Depth32FloatStencil8:case tZ.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case tZ.Depth32FloatStencil8:case tZ.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case tZ.Depth16Unorm:return tZ.Depth16Unorm;case tZ.Depth24Plus:case tZ.Depth24PlusStencil8:return tZ.Depth24Plus;case tZ.Depth32Float:case tZ.Depth32FloatStencil8:return tZ.Depth32Float}return e}copyVideoToTexture(e,t,i,r=!1,s){var n,a,o,l;let h=void 0===s,[u,c]=this._getVideoPipeline(i,r?iC.InvertY:iC.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`copy video to texture - invertY=${r}`);let d=t._hardwareTexture,p={colorAttachments:[{view:d.underlyingResource.createView({format:i,dimension:t$.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:tQ.All}),loadOp:i_.Load,storeOp:im.Store}]},_=s.beginRenderPass(p),f={layout:c,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},m=this._device.createBindGroup(f);_.setPipeline(u),_.setBindGroup(0,m),_.draw(4,1,0,0),_.end(),null===(l=(o=s).popDebugGroup)||void 0===l||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,n=!1,a=0,o=0,l=1,h=0,u=0,c=0,d=0,p,_){var f,m,g,v,x,T;let S;let C=0!==c,E=void 0===p,[b,y]=this._getPipeline(r,C?iS.InvertYPremultiplyAlphaWithOfst:iS.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:n});if(a=Math.max(a,0),E&&(p=this._device.createCommandEncoder({})),null===(m=(f=p).pushDebugGroup)||void 0===m||m.call(f,`internal process texture - invertY=${s} premultiplyAlpha=${n}`),WebGPUTextureHelper._IsHardwareTexture(e)?(S=e.underlyingResource,s&&!n&&1===l&&0===a||(e=void 0)):(S=e,e=void 0),!S)return;C&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,u,c,d]),0,16);let P=e,R=null!==(g=null==P?void 0:P._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,p,tK.CopySrc|tK.RenderAttachment|tK.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),A=null!==(v=null==P?void 0:P._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:R.createView({format:r,dimension:t$.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:i_.Load,storeOp:im.Store}]},I=p.beginRenderPass(A),M=C?null==P?void 0:P._copyInvertYBindGroupWithOfst:null==P?void 0:P._copyInvertYBindGroup;if(!M){let e={layout:y,entries:[{binding:0,resource:S.createView({format:r,dimension:t$.E2d,baseMipLevel:o,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:a})}]};C&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),M=this._device.createBindGroup(e)}I.setPipeline(b),I.setBindGroup(0,M),I.draw(4,1,0,0),I.end(),p.copyTextureToTexture({texture:R},{texture:S,mipLevel:o,origin:{x:0,y:0,z:a}},{width:t,height:i,depthOrArrayLayers:1}),P?(P._copyInvertYTempTexture=R,P._copyInvertYRenderPassDescr=A,C?P._copyInvertYBindGroupWithOfst=M:P._copyInvertYBindGroup=M):this._deferredReleaseTextures.push([R,null]),null===(T=(x=p).popDebugGroup)||void 0===T||T.call(x),E&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,r){var s,n,a,o;let l=void 0===r,[h,u]=this._getPipeline(t,iS.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,"internal copy texture with invertY");let c=r.beginRenderPass(i),d=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});c.setPipeline(h),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,n=!1,a=tZ.RGBA8Unorm,o=1,l,h=-1,u=0,c){o>1&&(o=4);let d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},_=az[a]?tK.RenderAttachment:0,f=WebGPUTextureHelper.IsCompressedFormat(a),m=t?WebGPUTextureHelper.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:tK.CopySrc|tK.CopyDst|tK.TextureBinding;u|=t&&!f?tK.CopySrc|_:0,f||n||(u|=_|tK.CopyDst);let v=this._device.createTexture({label:`Texture${n?"3D":"2D"}_${c?c+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${a}_samples${o}`,size:p,dimension:n?tq.E3d:tq.E2d,format:a,usage:g|u,sampleCount:o,mipLevelCount:m});return WebGPUTextureHelper.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,a,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,a,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,n=tZ.RGBA8Unorm,a=1,o,l=-1,h=0,u){a>1&&(a=4);let c=WebGPUTextureHelper.IsImageBitmapArray(e)?e[0].width:e.width,d=WebGPUTextureHelper.IsImageBitmapArray(e)?e[0].height:e.height,p=az[n]?tK.RenderAttachment:0,_=WebGPUTextureHelper.IsCompressedFormat(n),f=t?WebGPUTextureHelper.ComputeNumMipmapLevels(c,d):1,m=l>=0?l:tK.CopySrc|tK.CopyDst|tK.TextureBinding;h|=t&&!_?tK.CopySrc|p:0,_||(h|=p|tK.CopyDst);let g=this._device.createTexture({label:`TextureCube_${u?u+"_":""}${c}x${d}x6_${t?"wmips":"womips"}_${n}_samples${a}`,size:{width:c,height:d,depthOrArrayLayers:6},dimension:tq.E2d,format:n,usage:m|h,sampleCount:a,mipLevelCount:f});return WebGPUTextureHelper.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,c,d,n,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,o)),g}generateCubeMipmaps(e,t,i,r){var s,n,a,o;let l=void 0===r;l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,r);null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s){var n,a,o,l,h,u,c,d;let p;let _=void 0===s,[f,m]=this._getPipeline(t);if(r=Math.max(r,0),_&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`create mipmaps for face #${r} - ${i} levels`),WebGPUTextureHelper._IsHardwareTexture(e)?(p=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(p=e,e=void 0),!p)return;let g=e;for(let e=1;e15728640;)this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,15728640),h+=15728640;this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,s-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));let r=new Uint16Array(t);for(;e--;)i[e]=FromHalfFloat(r[e]);return i}readDataFromBuffer(e,t,i,r,s,n,a=0,o=0,l=null,h=!0,u=!1){let c=1===a?2:2===a?1:0;return new Promise((i,d)=>{e.mapAsync(tj.Read,o,t).then(()=>{let d=e.getMappedRange(o,t),p=l;if(u)p=null===p?(0,at.A)(a,t,!0,d):(0,at.A)(a,p.buffer,void 0,d);else if(null===p)switch(c){case 0:(p=new Uint8Array(t)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:(p=new Float32Array(t/4)).set(new Float32Array(d))}else switch(c){case 0:(p=new Uint8Array(p.buffer)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:(p=new Float32Array(p.buffer)).set(new Float32Array(d))}if(s!==n){1!==c||u||(s*=2,n*=2);let e=new Uint8Array(p.buffer),t=s,i=0;for(let a=1;ad(e))})}releaseBuffer(e){return WebGPUBufferManager._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1,n=aW[e.samplingMode]+aH[(e._comparisonFunction||514)-512+1]+aX[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(r=e._cachedWrapR)&&void 0!==r?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15);return n}static _GetSamplerFilterDescriptor(e,t){let i,r,s,n,a;let o=e.useMipMaps;switch(e.samplingMode){case 11:i=t0.Linear,r=t0.Linear,s=t0.Nearest,o||(n=a=0);break;case 3:case 3:i=t0.Linear,r=t0.Linear,o?s=t0.Linear:(s=t0.Nearest,n=a=0);break;case 8:i=t0.Nearest,r=t0.Nearest,o?s=t0.Linear:(s=t0.Nearest,n=a=0);break;case 4:i=t0.Nearest,r=t0.Nearest,s=t0.Nearest,o||(n=a=0);break;case 5:i=t0.Nearest,r=t0.Linear,s=t0.Nearest,o||(n=a=0);break;case 6:i=t0.Nearest,r=t0.Linear,o?s=t0.Linear:(s=t0.Nearest,n=a=0);break;case 7:i=t0.Nearest,r=t0.Linear,s=t0.Nearest,n=a=0;break;case 1:case 1:default:i=t0.Nearest,r=t0.Nearest,s=t0.Nearest,n=a=0;break;case 9:i=t0.Linear,r=t0.Nearest,s=t0.Nearest,o||(n=a=0);break;case 10:i=t0.Linear,r=t0.Nearest,o?s=t0.Linear:(s=t0.Nearest,n=a=0);break;case 2:case 2:i=t0.Linear,r=t0.Linear,s=t0.Nearest,n=a=0;break;case 12:i=t0.Linear,r=t0.Nearest,s=t0.Nearest,n=a=0}return t>1&&(0!==n||0!==a)&&s!==t0.Nearest?{magFilter:t0.Linear,minFilter:t0.Linear,mipmapFilter:t0.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:n,lodMaxClamp:a}}static _GetWrappingMode(e){switch(e){case 1:break;case 0:return tJ.ClampToEdge;case 2:return tJ.MirrorRepeat}return tJ.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e){let t=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,i=this._GetSamplerFilterDescriptor(e,t);return Object.assign(Object.assign(Object.assign({},i),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?WebGPUCacheSampler.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:i.anisotropyEnabled?t:1})}static GetCompareFunction(e){switch(e){case 519:return t2.Always;case 514:return t2.Equal;case 516:return t2.Greater;case 518:return t2.GreaterEqual;case 513:default:return t2.Less;case 515:return t2.LessEqual;case 512:return t2.Never;case 517:return t2.NotEqual}}getSampler(e,t=!1,i=0){if(this.disabled)return this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(e));t?i=0:0===i&&(i=WebGPUCacheSampler.GetSamplerHashCode(e));let r=t?void 0:this._samplers[i];return r||(r=this._device.createSampler(WebGPUCacheSampler._GetSamplerDescriptor(e)),t||(this._samplers[i]=r)),r}};(eE=iE||(iE={}))[eE.StencilReadMask=0]="StencilReadMask",eE[eE.StencilWriteMask=1]="StencilWriteMask",eE[eE.DepthBias=2]="DepthBias",eE[eE.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",eE[eE.DepthStencilState=4]="DepthStencilState",eE[eE.MRTAttachments1=5]="MRTAttachments1",eE[eE.MRTAttachments2=6]="MRTAttachments2",eE[eE.RasterizationState=7]="RasterizationState",eE[eE.ColorStates=8]="ColorStates",eE[eE.ShaderStage=9]="ShaderStage",eE[eE.TextureStage=10]="TextureStage",eE[eE.VertexState=11]="VertexState",eE[eE.NumStates=12]="NumStates";let aY={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},aj={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},aq={[rz.o.PositionKind]:!0,[rz.o.NormalKind]:!0,[rz.o.TangentKind]:!0,[rz.o.UVKind]:!0,[rz.o.UV2Kind]:!0,[rz.o.UV3Kind]:!0,[rz.o.UV4Kind]:!0,[rz.o.UV5Kind]:!0,[rz.o.UV6Kind]:!0,[rz.o.ColorKind]:!0,[rz.o.ColorInstanceKind]:!0,[rz.o.MatricesIndicesKind]:!0,[rz.o.MatricesWeightsKind]:!0,[rz.o.MatricesIndicesExtraKind]:!0,[rz.o.MatricesWeightsExtraKind]:!0};let WebGPUCacheRenderPipeline=class WebGPUCacheRenderPipeline{static _IsSignedType(e){switch(e){case rz.o.BYTE:case rz.o.SHORT:case rz.o.INT:case rz.o.FLOAT:return!0;case rz.o.UNSIGNED_BYTE:case rz.o.UNSIGNED_SHORT:case rz.o.UNSIGNED_INT:return!1;default:throw Error(`Invalid type '${e}'`)}}constructor(e,t,i){this.mrtTextureCount=0,this._device=e,this._useTextureStage=i,this._states=Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[tZ.BGRA8Unorm],this.setColorFormat(tZ.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(tZ.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,r=0){if(i>1&&(i=4),this.disabled){let s=WebGPUCacheRenderPipeline._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),WebGPUCacheRenderPipeline.NumCacheMiss++,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,WebGPUCacheRenderPipeline.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return WebGPUCacheRenderPipeline.NumCacheHitWithHash++,this._parameter.pipeline;let s=WebGPUCacheRenderPipeline._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),WebGPUCacheRenderPipeline.NumCacheMiss++,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){WebGPUCacheRenderPipeline.NumPipelineCreationLastFrame=WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame,WebGPUCacheRenderPipeline._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,n,a,o){this._depthWriteEnabled=a,this._depthTestEnabled=n,this._depthCompare=(null!=o?o:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[iE.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[iE.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=az[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;let s=[0,0],n=0,a=0,o=0;for(let l=0;l=32&&(a=0,n++)}this._mrtFormats.length=o,(this._mrtAttachments1!==s[0]||this._mrtAttachments2!==s[1])&&(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[iE.MRTAttachments1]=s[0],this._states[iE.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:az[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(null!=e?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(null!=e?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:aj[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:aj[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:aj[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[iE.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[iE.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,n,a){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:aj[i],this._stencilFrontPassOp=null===r?2:aj[r],this._stencilFrontFailOp=null===s?1:aj[s],this.setStencilReadMask(n),this.setStencilWriteMask(a)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return it.TriangleList;case 2:case 3:return it.PointList;case 1:case 4:return it.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return it.LineStrip;case 7:return it.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return io.Add;case 32778:return io.Subtract;case 32779:return io.ReverseSubtract;case 32775:return io.Min;case 32776:return io.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return ia.Zero;case 1:default:return ia.One;case 768:return ia.Src;case 769:return ia.OneMinusSrc;case 770:return ia.SrcAlpha;case 771:return ia.OneMinusSrcAlpha;case 772:return ia.DstAlpha;case 773:return ia.OneMinusDstAlpha;case 774:return ia.Dst;case 775:return ia.OneMinusDst;case 776:return ia.SrcAlphaSaturated;case 32769:case 32771:return ia.Constant;case 32770:case 32772:return ia.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:break;case 1:return t2.Less;case 2:return t2.Equal;case 3:return t2.LessEqual;case 4:return t2.Greater;case 5:return t2.NotEqual;case 6:return t2.GreaterEqual;case 7:return t2.Always}return t2.Never}static _GetStencilOpFunction(e){switch(e){case 0:return il.Zero;case 1:break;case 2:return il.Replace;case 3:return il.IncrementClamp;case 4:return il.DecrementClamp;case 5:return il.Invert;case 6:return il.IncrementWrap;case 7:return il.DecrementWrap}return il.Keep}static _GetVertexInputDescriptorFormat(e){let t=e.type,i=e.normalized,r=e.getSize();switch(t){case rz.o.BYTE:switch(r){case 1:case 2:return i?iu.Snorm8x2:iu.Sint8x2;case 3:case 4:return i?iu.Snorm8x4:iu.Sint8x4}break;case rz.o.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?iu.Unorm8x2:iu.Uint8x2;case 3:case 4:return i?iu.Unorm8x4:iu.Uint8x4}break;case rz.o.SHORT:switch(r){case 1:case 2:return i?iu.Snorm16x2:iu.Sint16x2;case 3:case 4:return i?iu.Snorm16x4:iu.Sint16x4}break;case rz.o.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?iu.Unorm16x2:iu.Uint16x2;case 3:case 4:return i?iu.Unorm16x4:iu.Uint16x4}break;case rz.o.INT:switch(r){case 1:return iu.Sint32;case 2:return iu.Sint32x2;case 3:return iu.Sint32x3;case 4:return iu.Sint32x4}break;case rz.o.UNSIGNED_INT:switch(r){case 1:return iu.Uint32;case 2:return iu.Uint32x2;case 3:return iu.Uint32x3;case 4:return iu.Uint32x4}break;case rz.o.FLOAT:switch(r){case 1:return iu.Float32;case 2:return iu.Float32x2;case 3:return iu.Float32x3;case 4:return iu.Float32x4}}throw Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:WebGPUCacheRenderPipeline._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:WebGPUCacheRenderPipeline._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[iE.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.ShaderStage))}_setRasterizationState(e,t){let i=this._frontFace,r=this._cullEnabled?this._cullFace:0,s=this._clampDepth?1:0,n=this._alphaToCoverageEnabled?1:0,a=i-1+(r<<1)+(s<<3)+(n<<4)+(e<<5)+(t<<8);this._rasterizationState!==a&&(this._rasterizationState=a,this._states[iE.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((null===this._alphaBlendFuncParams[0]?2:aY[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:aY[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:aY[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:aY[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[iE.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.ColorStates))}_setDepthStencilState(){let e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[iE.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthStencilState))}_setVertexState(e){var t,i;let r;let s=this._statesLength,n=iE.VertexState,a=e._pipelineContext,o=a.shaderProcessingContext.attributeNamesFromEffect,l=a.shaderProcessingContext.attributeLocationsFromEffect,h=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}};let WebGPUMaterialContext=class WebGPUMaterialContext{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatTextures(){return this._numFloatTextures>0}constructor(){this.uniqueId=WebGPUMaterialContext._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?WebGPUCacheSampler.GetSamplerHashCode(t):0;let s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,r,s;let n=this.textures[e],a=-1;n?a=null!==(r=null===(i=n.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:-1:this.textures[e]=n={texture:t,isFloatTexture:!1,isExternalTexture:!1},n.isExternalTexture&&this._numExternalTextures--,n.isFloatTexture&&this._numFloatTextures--,t?(n.isFloatTexture=1===t.type,n.isExternalTexture=ExternalTexture.IsExternalTexture(t),n.isFloatTexture&&this._numFloatTextures++,n.isExternalTexture&&this._numExternalTextures++):(n.isFloatTexture=!1,n.isExternalTexture=!1),n.texture=t;let o=a!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);o&&this.updateId++,this.isDirty||(this.isDirty=o)}};WebGPUMaterialContext._Counter=0;let WebGPUDrawContext=class WebGPUDrawContext{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,tY.CopyDst|tY.Indirect|tY.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=WebGPUDrawContext._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(null==t?void 0:t.uniqueId)!==(null===(i=this.buffers[e])||void 0===i?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}};WebGPUDrawContext._Counter=0;let WebGPUBindGroupCacheNode=class WebGPUBindGroupCacheNode{constructor(){this.values={}}};let WebGPUCacheBindGroups=class WebGPUCacheBindGroups{static get Statistics(){return{totalCreated:WebGPUCacheBindGroups.NumBindGroupsCreatedTotal,lastFrameCreated:WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame,lookupLastFrame:WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame,noLookupLastFrame:WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame}}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame=WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame,WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame=WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame,WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame=WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var r,s,n,a,o,l,h,u,c,d;let p;let _=WebGPUCacheBindGroups._Cache,f=this.disabled||i.forceBindGroupCreation;if(!f){if(!t.isDirty(i.updateId)&&!i.isDirty)return WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(let i of e.shaderProcessingContext.bufferNames){let e=null!==(s=null===(r=t.buffers[i])||void 0===r?void 0:r.uniqueId)&&void 0!==s?s:0,n=_.values[e];n||(n=new WebGPUBindGroupCacheNode,_.values[e]=n),_=n}for(let t of e.shaderProcessingContext.samplerNames){let e=null!==(a=null===(n=i.samplers[t])||void 0===n?void 0:n.hashCode)&&void 0!==a?a:0,r=_.values[e];r||(r=new WebGPUBindGroupCacheNode,_.values[e]=r),_=r}for(let t of e.shaderProcessingContext.textureNames){let e=null!==(h=null===(l=null===(o=i.textures[t])||void 0===o?void 0:o.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0,r=_.values[e];r||(r=new WebGPUBindGroupCacheNode,_.values[e]=r),_=r}p=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,p)return t.bindGroups=p,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame++,p;p=[],t.bindGroups=p,f||(_.bindGroups=p),WebGPUCacheBindGroups.NumBindGroupsCreatedTotal++,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame++;let m=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._cacheSampler.getSampler(t,!1,e.hashCode)}else rT.Y.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.texture||s.storageTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){rT.Y.Error(`Trying to bind a null texture! entry=${JSON.stringify(s)}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||s.texture&&!t.view||s.storageTexture&&!t.viewForWriting)){rT.Y.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, isReady=${null===(c=e.texture)||void 0===c?void 0:c.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=s.storageTexture?t.viewForWriting:t.view}else rT.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.externalTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){rT.Y.Error(`Trying to bind a null external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){rT.Y.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._device.importExternalTexture({source:t})}else rT.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.buffer){let e=t.buffers[l];if(e){let t=e.underlyingResource;n[a].resource.buffer=t,n[a].resource.size=e.capacity}else rT.Y.Error(`Can't find buffer "${l}". entry=${JSON.stringify(s)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}let a=m[r];p[r]=this._device.createBindGroup({layout:a,entries:n})}return p}};WebGPUCacheBindGroups.NumBindGroupsCreatedTotal=0,WebGPUCacheBindGroups.NumBindGroupsCreatedLastFrame=0,WebGPUCacheBindGroups.NumBindGroupsLookupLastFrame=0,WebGPUCacheBindGroups.NumBindGroupsNoLookupLastFrame=0,WebGPUCacheBindGroups._Cache=new WebGPUBindGroupCacheNode,WebGPUCacheBindGroups._NumBindGroupsCreatedCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsLookupCurrentFrame=0,WebGPUCacheBindGroups._NumBindGroupsNoLookupCurrentFrame=0;let aQ=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), -vec2(1.0,1.0), -vec2(-1.0,-1.0), -vec2(1.0,-1.0)}; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); -#define CUSTOM_VERTEX_MAIN_END -} -`;s_.v.ShadersStore.clearQuadVertexShader=aQ;let aZ=`uniform vec4 color;void main() {gl_FragColor=color;} -`;s_.v.ShadersStore.clearQuadPixelShader=aZ;let WebGPUClearQuad=class WebGPUClearQuad{setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new WebGPUCacheRenderPipelineTree(this._device,i,!t._caps.textureFloatLinearFiltering),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,r,s=1){var n,a;let o,l;let h=null,u=!!this._engine._currentRenderTarget;if(e)o=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?68719476736:0)+137438953472*c,l=this._keyTemp.join("_"),h=this._bundleCache[l])return h;o=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:s})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&WebGPUTextureHelper.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);let c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),d=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),d.uniformBuffer.update();let p=u?this._engine._ubInvertY:this._engine._ubDontInvertY,_=d.uniformBuffer.getBuffer(),f=_.uniqueId+"-"+p.uniqueId,m=this._bindGroups[f];if(!m){let e=d.bindGroupLayouts[0];(m=this._bindGroups[f]=[]).push(this._device.createBindGroup({layout:e[0],entries:[]})),WebGPUShaderProcessingContext._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[WebGPUShaderProcessingContext._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:_.underlyingResource,size:_.capacity}}]}))}o.setPipeline(c);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0}))}};let WebGPUDurationMeasure=class WebGPUDurationMeasure{constructor(e,t){this._querySet=new WebGPUQuerySet(2,ig.Timestamp,e,t)}start(e){e.writeTimestamp(this._querySet.querySet,0)}async stop(e){return e.writeTimestamp(this._querySet.querySet,1),this._querySet.readTwoValuesAndSubtract(0)}dispose(){this._querySet.dispose()}};let WebGPUOcclusionQuery=class WebGPUOcclusionQuery{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;let t=!1,i=this._engine._getCurrentRenderPassIndex();switch(i){case 0:t=void 0!==this._engine._mainRenderPassWrapper.renderPassDescriptor.occlusionQuerySet;break;case 1:t=void 0!==this._engine._rttRenderPassWrapper.renderPassDescriptor.occlusionQuerySet}return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();let e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e}))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}};let WebGPUTintWASM=class WebGPUTintWASM{async initTwgsl(e){return WebGPUTintWASM._twgsl?void 0:(e=e||{},(e=Object.assign(Object.assign({},WebGPUTintWASM._TWgslDefaultOptions),e)).twgsl)?(WebGPUTintWASM._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await rW.w1.LoadBabylonScriptAsync(e.jsPath),self.twgsl)?(WebGPUTintWASM._twgsl=await self.twgsl(rW.w1.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available.")}convertSpirV2WGSL(e,t=!1){let i=WebGPUTintWASM._twgsl.convertSpirV2WGSL(e,WebGPUTintWASM.DisableUniformityAnalysis||t);return WebGPUTintWASM.ShowWGSLShaderCode&&(console.log(i),console.log("***********************************************")),WebGPUTintWASM.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}};WebGPUTintWASM._TWgslDefaultOptions={jsPath:`${rW.w1._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${rW.w1._DefaultCdnUrl}/twgsl/twgsl.wasm`},WebGPUTintWASM.ShowWGSLShaderCode=!1,WebGPUTintWASM.DisableUniformityAnalysis=!1,WebGPUTintWASM._twgsl=null;let WebGPUSnapshotRendering=class WebGPUSnapshotRendering{constructor(e,t,i,r){this._record=!1,this._play=!1,this._mainPassBundleList=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i,this._bundleListRenderTarget=r}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._mainPassBundleList.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endMainRenderPass(){this._record&&this._mainPassBundleList.push(this._bundleList.clone())}endRenderTargetPass(e,t){var i,r,s,n;if(this._play)null===(r=null===(i=t._bundleLists)||void 0===i?void 0:i[t._currentLayer])||void 0===r||r.run(e),1===this._mode&&this._engine._reportDrawCall(null===(n=null===(s=t._bundleLists)||void 0===s?void 0:s[t._currentLayer])||void 0===n?void 0:n.numDrawCalls);else{if(!this._record)return!1;t._bundleLists||(t._bundleLists=[]),t._bundleLists[t._currentLayer]=this._bundleListRenderTarget.clone(),t._bundleLists[t._currentLayer].run(e),this._bundleListRenderTarget.reset()}return!0}endFrame(e){if(this._record&&(this._mainPassBundleList.push(this._bundleList.clone()),this._record=!1,this._play=!0,this._mode=this._modeSaved),null!==e&&this._play)for(let t=0;t;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -@vertex -fn main(input : VertexInputs)->FragmentInputs { -#define CUSTOM_VERTEX_MAIN_BEGIN -vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -} -`;s_.v.ShadersStoreWGSL.postprocessVertexShader=aJ;let a0={label:"TextureView_SwapChain_ResolveTarget",dimension:tq.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},a1={label:"TextureView_SwapChain",dimension:tq.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},a2="/* disable_uniformity_analysis */",a3=new rg.HE;let webgpuEngine_WebGPUEngine=class webgpuEngine_WebGPUEngine extends rq.D{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return rT.Y.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){let e=this.name+this.version;return e}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){let i=new webgpuEngine_WebGPUEngine(e,t);return new Promise(e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>e(i))})}constructor(e,t={}){var i,r;if(super(null,null===(i=t.antialias)||void 0===i||i,t),this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._renderTargetEncoderDescriptor={label:"renderTarget"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null,null],this._currentRenderPass=null,this._mainRenderPassWrapper=new WebGPURenderPassWrapper,this._rttRenderPassWrapper=new WebGPURenderPassWrapper,this._pendingDebugCommands=[],this._onAfterUnbindFrameBufferObservable=new rf.y$,this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorsCurrent=[{x:0,y:0,w:0,h:0},{x:0,y:0,w:0,h:0}],this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=[-1,-1],this._blendColorsCurrent=[[null,null,null,null],[null,null,null,null]],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=null!==(r=t.enableGPUDebugMarkers)&&void 0!==r&&r,rT.Y.Log(`Babylon.js v${rq.D.Version} - ${this.description} engine`),!navigator.gpu){rT.Y.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new WebGPUShaderProcessorGLSL,this._shaderProcessorWGSL=new WebGPUShaderProcessorWGSL}initAsync(e,t){var i;return this._initGlslang(null!=e?e:null===(i=this._options)||void 0===i?void 0:i.glslangOptions).then(e=>{var i;return this._glslang=e,this._tintWASM=webgpuEngine_WebGPUEngine.UseTWGSL?new WebGPUTintWASM:null,this._tintWASM?this._tintWASM.initTwgsl(null!=t?t:null===(i=this._options)||void 0===i?void 0:i.twgslOptions).then(()=>navigator.gpu.requestAdapter(this._options),e=>{throw rT.Y.Error("Can not initialize twgsl!"),rT.Y.Error(e),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},e=>{throw rT.Y.Error("Can not initialize glslang!"),rT.Y.Error(e),Error("WebGPU initializations stopped.")}).then(e=>{var t,i,r;if(e){this._adapter=e,this._adapterSupportedExtensions=[],null===(t=this._adapter.features)||void 0===t||t.forEach(e=>this._adapterSupportedExtensions.push(e)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(e=>{this._adapterInfo=e});let s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},n=null!==(r=null==s?void 0:s.requiredFeatures)&&void 0!==r?r:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(n){let e=[];for(let t of n)-1!==this._adapterSupportedExtensions.indexOf(t)&&e.push(t);s.requiredFeatures=e}if(this._options.setMaximumLimits&&!s.requiredLimits)for(let e in s.requiredLimits={},this._adapterSupportedLimits)s.requiredLimits[e]=this._adapterSupportedLimits[e];return this._adapter.requestDevice(s)}throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(e=>{var t,i;this._device=e,this._deviceEnabledExtensions=[],null===(t=this._device.features)||void 0===t||t.forEach(e=>this._deviceEnabledExtensions.push(e)),this._deviceLimits=e.limits;let r=-1;this._device.addEventListener("uncapturederror",e=>{++r{this._isDisposed||(this._contextWasLost=!0,rT.Y.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(()=>this.initAsync()))})},e=>{rT.Y.Error("Could not retrieve a WebGPU device."),rT.Y.Error(e)}).then(()=>{this._bufferManager=new WebGPUBufferManager(this._device),this._textureHelper=new WebGPUTextureHelper(this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new WebGPUCacheSampler(this._device),this._cacheBindGroups=new WebGPUCacheBindGroups(this._device,this._cacheSampler,this),this._timestampQuery=new WebGPUTimestampQuery(this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new WebGPUOcclusionQuery(this,this._device,this._bufferManager):void 0,this._bundleList=new WebGPUBundleList(this._device),this._bundleListRenderTarget=new WebGPUBundleList(this._device),this._snapshotRendering=new WebGPUSnapshotRendering(this,this._snapshotRenderingMode,this._bundleList,this._bundleListRenderTarget),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),tY.Uniform|tY.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),tY.Uniform|tY.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,console.log("%c frame #"+this._count+" - begin","background: #ffff00")),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._renderTargetEncoder=this._device.createCommandEncoder(this._renderTargetEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new rz.o(this,[0],"",!1,!1,1,!1,0,1),this._cacheRenderPipeline=new WebGPUCacheRenderPipelineTree(this._device,this._emptyVertexBuffer,!this._caps.textureFloatLinearFiltering),this._depthCullingState=new WebGPUDepthCullingState(this._cacheRenderPipeline),this._stencilStateComposer=new WebGPUStencilStateComposer(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new WebGPUClearQuad(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(e=>{rT.Y.Error("Can not create WebGPU Device and/or context."),rT.Y.Error(e),console.trace&&console.trace()})}_initGlslang(e){return(e=e||{},(e=Object.assign(Object.assign({},webgpuEngine_WebGPUEngine._GLSLslangDefaultOptions),e)).glslang)?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?rW.w1.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(rW.w1.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(tH.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(tH.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(tH.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(tH.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(tH.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(tH.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._caps.parallelShaderCompile=null,this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new WebGPUHardwareTexture],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat}_initializeMainAttachments(){let e;if(!this._bufferManager)return;this.flushFramebuffer(!1),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};let t=new Float32Array([this.getRenderHeight(!0)]);if(this._bufferManager.setSubData(this._ubInvertY,4,t),this._bufferManager.setSubData(this._ubDontInvertY,4,t),this._options.antialias){let t={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tq.E2d,format:this._options.swapChainFormat,usage:tK.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(t),e=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:tq.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new rg.HE(0,0,0,1),loadOp:i_.Clear,storeOp:im.Store}]}else e=[{view:void 0,clearValue:new rg.HE(0,0,0,1),loadOp:i_.Clear,storeOp:im.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?tZ.Depth24PlusStencil8:tZ.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper);let i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tq.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:tK.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);let r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:tq.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:i_.Clear,depthStoreOp:im.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?i_.Clear:void 0,stencilStoreOp:this.isStencilEnable?im.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:e,depthStencilAttachment:r}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:tK.RenderAttachment|tK.CopySrc,alphaMode:this.premultipliedAlpha?iv.Premultiplied:iv.Opaque})}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,s=t.indexOf(a2)>=0,n=i===sg.x.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,a=i===sg.x.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,a,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=e.indexOf(a2)>=0,n=t.indexOf(a2)>=0,a="#version 450\n",o=r===sg.x.GLSL?this._compileShaderToSpirV(e,"vertex",i,a):this._getWGSLShader(e,"vertex",i),l=r===sg.x.GLSL?this._compileShaderToSpirV(t,"fragment",i,a):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(o,l,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){let t=new ShaderCodeInliner(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new WebGPUPipelineContext(e,this)}createMaterialContext(){return new WebGPUMaterialContext}createDrawContext(){return new WebGPUDrawContext(this._bufferManager)}_preparePipelineContext(e,t,i,r,s,n,a,o){let l=e.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(console.log(o),console.log(t),console.log(i),console.log("***********************************************")),e.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:n},r?e.stages=this._compileRawPipelineStageDescriptor(t,i,l):e.stages=this._compilePipelineStageDescriptor(t,i,o,l)}getAttributes(e,t){let i=Array(t.length);for(let r=0;r0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=o.useSRGBBuffer,l.label=o.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,u,c||1,o.creationFlags),l}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_){return this._createTextureBase(e,t,i,r,s,n,a,(e,t,i,r,s,n,a,o)=>{var l;if(e.baseWidth=r.width,e.baseHeight=r.height,e.width=r.width,e.height=r.height,e.format=-1!==e.format?e.format:null!=h?h:5,e.type=-1!==e.type?e.type:0,o(e.width,e.height,r,t,e,()=>{}),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)n||a||this._generateMipmaps(e,this._uploadEncoder);else{let t=this._textureHelper.createGPUTextureForInternalTexture(e,r.width,r.height,void 0,p);!WebGPUTextureHelper.IsImageBitmap(r)||(this._textureHelper.updateTexture(r,e,r.width,r.height,e.depth,t.format,0,0,s,!1,0,0),n||a||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()},()=>!1,o,l,h,u,c,d,_)}wrapWebGPUTexture(e){let t=new WebGPUHardwareTexture(e),i=new r5.l(this,r5.S.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;if(e.generateMipMaps){let i=null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource;i||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e,e.source===r5.S.RenderTarget||e.source===r5.S.MultiRenderTarget?this._renderTargetEncoder:void 0)}}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;let s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){let r=this._currentEffect._pipelineContext,s=r.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),s&&s.autoBindSampler){let e=i+WebGPUShaderProcessor.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e0;for(let t in e){let s=e[t],n=i[t],a=n.group,o=n.binding,l=s.type,h=s.object,u=s.indexInGroupEntries,c=this._bindGroupEntries[a];switch(c||(c=this._bindGroupEntries[a]=[]),l){case tV.Sampler:void 0!==u&&r?c[u].resource=this._cacheSampler.getSampler(h):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._cacheSampler.getSampler(h)}));break;case tV.Texture:case tV.TextureWithoutSampler:{let e=h._texture._hardwareTexture;void 0!==u&&r?(l===tV.Texture&&(c[u++].resource=this._cacheSampler.getSampler(h._texture)),c[u].resource=e.view):(s.indexInGroupEntries=c.length,l===tV.Texture&&c.push({binding:o-1,resource:this._cacheSampler.getSampler(h._texture)}),c.push({binding:o,resource:e.view}));break}case tV.StorageTexture:{let e=h._texture._hardwareTexture;(e.textureAdditionalUsages&tK.StorageBinding)==0&&rT.Y.Error(`computeDispatch: The texture (name=${h.name}, uniqueId=${h.uniqueId}) is not a storage texture!`,50),void 0!==u&&r?c[u].resource=e.viewForWriting:(s.indexInGroupEntries=c.length,c.push({binding:o,resource:e.viewForWriting}));break}case tV.ExternalTexture:{let e=h.underlyingResource;void 0!==u&&r?c[u].resource=this._device.importExternalTexture({source:e}):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._device.importExternalTexture({source:e})}));break}case tV.UniformBuffer:case tV.StorageBuffer:{let e=(tV.UniformBuffer,h),t=e.getBuffer(),i=t.underlyingResource;void 0!==u&&r?(c[u].resource.buffer=i,c[u].resource.size=t.capacity):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:{buffer:i,offset:0,size:t.capacity}}))}}}for(let e=0;e{this.computeDispatch(e,t,i,r,s,n,a)});return}let o=e._pipelineContext;o.computePipeline||(o.computePipeline=this._device.createComputePipeline({layout:ie.Auto,compute:o.stage}));let l=this._renderTargetEncoder,h=l.beginComputePass();h.setPipeline(o.computePipeline);let u=t.getBindGroups(i,o.computePipeline,a);for(let e=0;e{let i=t[0].width;this._setCubeMapTextureParams(e,!r),e.format=null!=a?a:-1;let n=this._textureHelper.createGPUTextureForInternalTexture(e,i,i);this._textureHelper.updateCubeTextures(t,n.underlyingResource,i,i,n.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!d)},webgpuEngine_WebGPUEngine.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},webgpuEngine_WebGPUEngine.prototype._debugPushGroup=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.pushDebugGroup(e)}else this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e])}},webgpuEngine_WebGPUEngine.prototype._debugPopGroup=function(e){if(this._options.enableGPUDebugMarkers){if(0===e||1===e){let t=0===e?this._renderEncoder:this._renderTargetEncoder;t.popDebugGroup()}else this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null])}},webgpuEngine_WebGPUEngine.prototype._debugInsertMarker=function(e,t){if(this._options.enableGPUDebugMarkers){if(0===t||1===t){let i=0===t?this._renderEncoder:this._renderTargetEncoder;i.insertDebugMarker(e)}else this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e])}},webgpuEngine_WebGPUEngine.prototype._debugFlushPendingCommands=function(){for(let e=0;e{let i=d.width,n=a(e);if(!n)return;let h=[0,2,4,1,3,5];if(o){let e=4===r,t=o(n),a=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r>r,o=[];for(let i=0;i<6;i++){let a=t[r][l[i]];e&&(a=engine_rawTexture_convertRGBtoRGBATextureData(a,n,n,s)),o.push(new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}this._textureHelper.updateCubeTextures(o,a.underlyingResource,n,n,a.format,c,!1,0,0)}}else{let e=[];for(let t=0;t<6;t++)e.push(n[h[t]]);this.updateRawCubeTexture(d,e,r,s,c)}d.isReady=!0,null==t||t.removePendingData(d),l&&l()};return this._loadFile(e,e=>{internalCallback(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)}),d},webgpuEngine_WebGPUEngine.prototype.createRawTexture3D=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=r5.S.Raw3D,d=new r5.l(this,c);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is3D=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,u),this.updateRawTexture3D(d,e,s,a,l,h),this._internalTexturesCache.push(d),d},webgpuEngine_WebGPUEngine.prototype.updateRawTexture3D=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture,a=4===i;a&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,n));let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},webgpuEngine_WebGPUEngine.prototype.createRawTexture2DArray=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=r5.S.Raw2DArray,d=new r5.l(this,c);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,r,u),this.updateRawTexture2DArray(d,e,s,a,l,h),this._internalTexturesCache.push(d),d},webgpuEngine_WebGPUEngine.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture,a=4===i;a&&(t=engine_rawTexture_convertRGBtoRGBATextureData(t,e.width,e.height,n));let o=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(o,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},webgpuEngine_WebGPUEngine.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){let u=e._hardwareTexture;return a&&this.flushFramebuffer(),this._textureHelper.readPixels(u.underlyingResource,l,h,t,i,u.format,r,s,n,o)},webgpuEngine_WebGPUEngine.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};let WebGPURenderTargetWrapper=class WebGPURenderTargetWrapper extends renderTargetWrapper_RenderTargetWrapper{};function IsExternalTexture(e){return!!e&&void 0!==e.underlyingResource}webgpuEngine_WebGPUEngine.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new WebGPURenderTargetWrapper(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},webgpuEngine_WebGPUEngine.prototype.createRenderTargetTexture=function(e,t){var i,r,s;let n=this._createHardwareRenderTargetWrapper(!1,!1,e),a={};void 0!==t&&"object"==typeof t?(a.generateMipMaps=t.generateMipMaps,a.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,a.generateStencilBuffer=a.generateDepthBuffer&&t.generateStencilBuffer,a.samplingMode=void 0===t.samplingMode?3:t.samplingMode,a.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,a.noColorAttachment=!!t.noColorAttachment,a.samples=t.samples,a.label=t.label):(a.generateMipMaps=t,a.generateDepthBuffer=!0,a.generateStencilBuffer=!1,a.samplingMode=3,a.creationFlags=0,a.noColorAttachment=!1);let o=a.noColorAttachment?null:this._createInternalTexture(e,t,!0,r5.S.RenderTarget);return n.label=null!==(r=a.label)&&void 0!==r?r:"RenderTargetWrapper",n._samples=null!==(s=a.samples)&&void 0!==s?s:1,n._generateDepthBuffer=a.generateDepthBuffer,n._generateStencilBuffer=!!a.generateStencilBuffer,n.setTextures(o),(n._generateDepthBuffer||n._generateStencilBuffer)&&n.createDepthStencilTexture(0,this._caps.textureFloatLinearFiltering&&(void 0===a.samplingMode||2===a.samplingMode||2===a.samplingMode||3===a.samplingMode||3===a.samplingMode||5===a.samplingMode||6===a.samplingMode||7===a.samplingMode||11===a.samplingMode),n._generateStencilBuffer,n.samples,a.generateStencilBuffer?13:14,a.label?a.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,a.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(o.generateMipMaps=!1)),n},webgpuEngine_WebGPUEngine.prototype._createDepthStencilTexture=function(e,t){let i=new r5.l(this,r5.S.DepthStencil);i.label=t.label;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);return i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},webgpuEngine_WebGPUEngine.prototype._setupDepthStencilTexture=function(e,t,i,r,s,n=1){let a=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},webgpuEngine_WebGPUEngine.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t&&(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t),t},webgpuEngine_WebGPUEngine.prototype.createRenderTargetCubeTexture=function(e,t){var i;let r=this._createHardwareRenderTargetWrapper(!1,!0,e),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,r.label=null!==(i=s.label)&&void 0!==i?i:"RenderTargetWrapper",r._generateDepthBuffer=s.generateDepthBuffer,r._generateStencilBuffer=s.generateStencilBuffer;let n=new r5.l(this,r5.S.RenderTarget);return n.width=e,n.height=e,n.depth=0,n.isReady=!0,n.isCube=!0,n.samples=s.samples,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),r.setTextures(n),(r._generateDepthBuffer||r._generateStencilBuffer)&&r.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,r._generateStencilBuffer,r.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(n.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(n),t&&t.createMipMaps&&!s.generateMipMaps&&(n.generateMipMaps=!1),r},ss.Q.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},webgpuEngine_WebGPUEngine.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},ss.Q.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},webgpuEngine_WebGPUEngine.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,32|t,i)},webgpuEngine_WebGPUEngine.prototype.updateStorageBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.readFromStorageBuffer=function(e,t,i,r){i=i||e.capacity;let s=this._bufferManager.createRawBuffer(i,tY.MapRead|tY.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderTargetEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,s,0,i),new Promise((e,t)=>{this.onEndFrameObservable.addOnce(()=>{s.mapAsync(tj.Read,0,i).then(()=>{let t=s.getMappedRange(0,i),n=r;if(void 0===n)(n=new Uint8Array(i)).set(new Uint8Array(t));else{let e=n.constructor;(n=new e(n.buffer)).set(new e(t))}s.unmap(),this._bufferManager.releaseBuffer(s),e(n)},e=>t(e))})})},webgpuEngine_WebGPUEngine.prototype.setStorageBuffer=function(e,t){var i,r;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(r=null==t?void 0:t.getBuffer())&&void 0!==r?r:null)},webgpuEngine_WebGPUEngine.prototype.createUniformBuffer=function(e,t){let i;i=e instanceof Array?new Float32Array(e):e;let r=this._bufferManager.createBuffer(i,tY.Uniform|tY.CopyDst,t);return r},webgpuEngine_WebGPUEngine.prototype.createDynamicUniformBuffer=function(e,t){return this.createUniformBuffer(e,t)},webgpuEngine_WebGPUEngine.prototype.updateUniformBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Float32Array?t:new Float32Array(t)).byteLength:s=t instanceof Float32Array?t:new Float32Array(t),this._bufferManager.setSubData(e,i,s,0,r)},webgpuEngine_WebGPUEngine.prototype.bindUniformBufferBase=function(e,t,i){this._currentDrawContext.setBuffer(i,e)},webgpuEngine_WebGPUEngine.prototype.bindUniformBlock=function(){},webgpuEngine_WebGPUEngine.prototype.updateVideoTexture=function(e,t,i){var r;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;(null===(r=e._hardwareTexture)||void 0===r?void 0:r.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),IsExternalTexture(t)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0):t&&this.createImageBitmap(t).then(t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0}).catch(()=>{e.isReady=!0})},i(856);let ClipboardEventTypes=class ClipboardEventTypes{};ClipboardEventTypes.COPY=1,ClipboardEventTypes.CUT=2,ClipboardEventTypes.PASTE=3;let planeRotationGizmo_PlaneRotationGizmo=class planeRotationGizmo_PlaneRotationGizmo extends gizmo_Gizmo{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=rg.Wo.Gray(),i=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer,r=32,s=null,n=!1,a=1){var o;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new rf.y$,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new rm.P,this._parent=s,this._coloredMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new rg.Wo(.1,.1,.1)),this._hoverMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=rg.Wo.Yellow(),this._disableMaterial=new standardMaterial_StandardMaterial("",i.utilityLayerScene),this._disableMaterial.diffuseColor=rg.Wo.Gray(),this._disableMaterial.alpha=.4,this._gizmoMesh=new rV.Kj("",i.utilityLayerScene);let{rotationMesh:l,collider:h}=this._createGizmoMesh(this._gizmoMesh,a,r);this._rotationDisplayPlane=planeBuilder_CreatePlane("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),ss.Q.ShadersStore.rotationGizmoVertexShader=planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader,ss.Q.ShadersStore.rotationGizmoFragmentShader=planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader,this._rotationShaderMaterial=new shaderMaterial_ShaderMaterial("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles"]}),this._rotationShaderMaterial.backFaceCulling=!1,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,gizmo_Gizmo.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new pointerDragBehavior_PointerDragBehavior({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);let u=new rm.P,c=new rm.y3,d=new rm.P,p=new rm.P;this.dragBehavior.onDragStartObservable.add(e=>{this.attachedNode&&(u.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(c),rm.P.TransformCoordinatesToRef(e.dragPlanePoint,c,u),this._angles.x=Math.atan2(u.y,u.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,u.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});let _={snapDistance:0},f=0,m=new rm.y3,g=new rm._f;this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let r=new rm.P(1,1,1),s=new rm._f(0,0,0,1),n=new rm.P(0,0,0);this.attachedNode.getWorldMatrix().decompose(r,s,n);let a=Math.abs(Math.abs(r.x)-Math.abs(r.y))<=rw.kn&&Math.abs(Math.abs(r.x)-Math.abs(r.z))<=rw.kn;if(!a&&this.updateGizmoRotationToMatchAttachedMesh){rT.Y.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}s.normalize();let o=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,l=t.dragPlanePoint.subtract(o).normalize(),h=u.subtract(o).normalize(),v=rm.P.Cross(l,h),x=rm.P.Dot(l,h),T=Math.atan2(v.length(),x)*this.sensitivity;d.copyFrom(e),p.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(c),p=rm.P.TransformCoordinates(d,c));let S=!1;if(i.utilityLayerScene.activeCamera){let e=i.utilityLayerScene.activeCamera.position.subtract(o).normalize();rm.P.Dot(e,p)>0&&(d.scaleInPlace(-1),p.scaleInPlace(-1),S=!0)}let C=rm.P.Dot(p,v)>0;C&&(T=-T),rm.jp.Vector3[0].set(T,0,0),this.dragBehavior.validateDrag(rm.jp.Vector3[0])||(T=0);let E=!1;if(0!=this.snapDistance){if(Math.abs(f+=T)>this.snapDistance){let e=Math.floor(Math.abs(f)/this.snapDistance);f<0&&(e*=-1),f%=this.snapDistance,T=this.snapDistance*e,E=!0}else T=0}let b=Math.sin(T/2);if(g.set(d.x*b,d.y*b,d.z*b,Math.cos(T/2)),m.determinant()>0){let e=new rm.P;g.toEulerAnglesToRef(e),rm._f.RotationYawPitchRollToRef(e.y,-e.x,-e.z,g)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(g,s),s.normalize(),rm.y3.ComposeToRef(r,s,n,this.attachedNode.getWorldMatrix());else{g.toRotationMatrix(rm.jp.Matrix[0]);let e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(rm.jp.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}u.copyFrom(t.dragPlanePoint),E&&(_.snapDistance=T,this.onSnapObservable.notifyObservers(_)),this._angles.y+=T,this.angle+=S?-T:T,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});let v=i._getSharedGizmoLight();v.includedOnlyMeshes=v.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));let x={colliderMeshes:[h],gizmoMeshes:[l],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(o=this._parent)||void 0===o||o.addToAxisCache(this._gizmoMesh,x),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle,this._isHovered=-1!=x.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=x.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(x.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(x.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){let r=CreateTorus("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;let s=CreateTorus("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,gizmo_Gizmo.PreserveScaling),e.addChild(r,gizmo_Gizmo.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}};planeRotationGizmo_PlaneRotationGizmo.MaxDragAngle=9*Math.PI/20,planeRotationGizmo_PlaneRotationGizmo._RotationGizmoVertexShader=` - precision highp float; - attribute vec3 position; - attribute vec2 uv; - uniform mat4 worldViewProjection; - varying vec3 vPosition; - varying vec2 vUV; - void main(void) { - gl_Position = worldViewProjection * vec4(position, 1.0); - vUV = uv; - }`,planeRotationGizmo_PlaneRotationGizmo._RotationGizmoFragmentShader=` - precision highp float; - varying vec2 vUV; - varying vec3 vPosition; - uniform vec3 angles; - #define twopi 6.283185307 - void main(void) { - vec2 uv = vUV - vec2(0.5); - float angle = atan(uv.y, uv.x) + 3.141592; - float delta = gl_FrontFacing ? angles.y : -angles.y; - float begin = angles.x - delta * angles.z; - float start = (begin < (begin + delta)) ? begin : (begin + delta); - float end = (begin > (begin + delta)) ? begin : (begin + delta); - float len = sqrt(dot(uv,uv)); - float opacity = 1. - step(0.5, len); - - float base = abs(floor(start / twopi)) * twopi; - start += base; - end += base; - - float intensity = 0.; - for (int i = 0; i < 5; i++) - { - intensity += max(step(start, angle) - step(end, angle), 0.); - angle += twopi; - } - gl_FragColor = vec4(1.,1.,0., min(intensity * 0.25, 0.8)) * opacity; - }`;let ShadowLight=class ShadowLight extends light_Light{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0}_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=rm.P.Zero()),rm.P.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=rm.P.Zero()),rm.P.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=rm.P.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=rm.P.Cross(this.direction,rL.RD.Y),t=rm.P.Cross(e,this.direction);return rm.P.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=rm.P.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?this._currentRenderId=this.getScene().getRenderId():(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=rm.y3.Identity()),rm.y3.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,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}};(0,rH.gn)([(0,rb.hd)()],ShadowLight.prototype,"position",null),(0,rH.gn)([(0,rb.hd)()],ShadowLight.prototype,"direction",null),(0,rH.gn)([(0,rb.qC)()],ShadowLight.prototype,"shadowMinZ",null),(0,rH.gn)([(0,rb.qC)()],ShadowLight.prototype,"shadowMaxZ",null),ry.N.AddNodeConstructor("Light_Type_1",(e,t)=>()=>new DirectionalLight(e,rm.P.Zero(),t));let DirectionalLight=class DirectionalLight extends ShadowLight{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,i){super(e,i),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 light_Light.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;t&&rm.y3.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,i){let r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let e=rm.P.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}let s=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;rm.y3.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?o:a,l?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._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):e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}};function CreateHemisphere(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);let r=sphereBuilder_CreateSphere("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=discBuilder_CreateDisc("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;let n=rV.Kj.MergeMeshes([s,r],!0);return n.name=e,n}(0,rH.gn)([(0,rb.qC)()],DirectionalLight.prototype,"shadowFrustumSize",null),(0,rH.gn)([(0,rb.qC)()],DirectionalLight.prototype,"shadowOrthoScale",null),(0,rH.gn)([(0,rb.qC)()],DirectionalLight.prototype,"autoUpdateExtends",void 0),(0,rH.gn)([(0,rb.qC)()],DirectionalLight.prototype,"autoCalcShadowZBounds",void 0),(0,rH.gn)([(0,rb.qC)("orthoLeft")],DirectionalLight.prototype,"_orthoLeft",void 0),(0,rH.gn)([(0,rb.qC)("orthoRight")],DirectionalLight.prototype,"_orthoRight",void 0),(0,rH.gn)([(0,rb.qC)("orthoTop")],DirectionalLight.prototype,"_orthoTop",void 0),(0,rH.gn)([(0,rb.qC)("orthoBottom")],DirectionalLight.prototype,"_orthoBottom",void 0),rV.Kj.CreateHemisphere=(e,t,i,r)=>CreateHemisphere(e,{segments:t,diameter:i},r),ry.N.AddNodeConstructor("Light_Type_2",(e,t)=>()=>new SpotLight(e,rm.P.Zero(),rm.P.Zero(),0,0,t));let SpotLight=class SpotLight extends ShadowLight{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()&&(SpotLight._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):SpotLight._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,i,r,s,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=rm.y3.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=rm.P.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=rm.P.Zero(),this._projectionTextureViewLightMatrix=rm.y3.Zero(),this._projectionTextureProjectionLightMatrix=rm.y3.Zero(),this._projectionTextureScalingMatrix=rm.y3.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return light_Light.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;rm.y3.PerspectiveFovLHToRef(s,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.direction,this._projectionTextureViewTargetVector),rm.y3.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=-i*t,s=1/Math.tan(this._angle/2);rm.y3.FromValuesToRef(s/1,0,0,0,0,s,0,0,0,0,i,1,0,0,r,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof texture_Texture){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;rm.y3.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("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=rm.P.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=rm.P.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?rm.P.Normalize(this.transformedDirection):rm.P.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){let t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){let t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady())}};(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"angle",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"innerAngle",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"shadowAngleScale",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"exponent",void 0),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"projectionTextureLightNear",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"projectionTextureLightFar",null),(0,rH.gn)([(0,rb.qC)()],SpotLight.prototype,"projectionTextureUpDirection",null),(0,rH.gn)([(0,rb.oU)("projectedLightTexture")],SpotLight.prototype,"_projectionTexture",void 0);let LightGizmo=class LightGizmo extends gizmo_Gizmo{constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){super(e),this._cachedPosition=new rm.P,this._cachedForward=new rm.P(0,0,1),this._pointerObserver=null,this.onClickedObservable=new rf.y$,this._light=null,this.attachedMesh=new rG.x("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new rk.Y("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new standardMaterial_StandardMaterial("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new rg.Wo(.5,.5,.5),this._material.specularColor=new rg.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(e=>{this._light&&(this._isHovered=!!(e.pickInfo&&-1!=this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))},r8.kD.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){console.warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof HemisphericLight?this._lightMesh=LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof DirectionalLight?this._lightMesh=LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof SpotLight?this._lightMesh=LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._lightMesh.parent=this._rootMesh;let t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new rm._f,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);let t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(rm.jp.Vector3[0]),e=rm.jp.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position){if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{let e=this.attachedMesh.position;this._light.position=new rm.P(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}}if(this._light.direction){let e=this._getMeshForward();rm.P.DistanceSquared(e,this._cachedForward)>1e-4?(this._light.direction=new rm.P(e.x,e.y,e.z),this._cachedForward.copyFrom(e)):rm.P.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){let t=new rV.Kj("hemisphereLight",e),i=CreateHemisphere(t.name,{segments:10,diameter:1},e);i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(3,e);return r.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){let t=new rV.Kj("pointLight",e),i=sphereBuilder_CreateSphere(t.name,{segments:10,diameter:1},e);i.rotation.x=Math.PI/2,i.parent=t;let r=this._CreateLightLines(5,e);return r.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){let t=new rV.Kj("spotLight",e),i=sphereBuilder_CreateSphere(t.name,{segments:10,diameter:1},e);i.parent=t;let r=CreateHemisphere(t.name,{segments:10,diameter:2},e);r.parent=t,r.rotation.x=-Math.PI/2;let s=this._CreateLightLines(2,e);return s.parent=t,t.scaling.scaleInPlace(LightGizmo._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){let t=new rV.Kj("directionalLight",e),i=new rV.Kj(t.name,e);i.parent=t;let r=sphereBuilder_CreateSphere(t.name,{diameter:1.2,segments:10},e);r.parent=i;let s=cylinderBuilder_CreateCylinder(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);s.parent=i;let n=s.clone(t.name);n.scaling.y=.5,n.position.x+=1.25;let a=s.clone(t.name);a.scaling.y=.5,a.position.x+=-1.25;let o=cylinderBuilder_CreateCylinder(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return o.position.y+=3,o.parent=i,(n=o.clone(t.name)).position.y=1.5,n.position.x+=1.25,(a=o.clone(t.name)).position.y=1.5,a.position.x+=-1.25,i.scaling.scaleInPlace(LightGizmo._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}};LightGizmo._Scale=.007,LightGizmo._CreateLightLines=(e,t)=>{let i=new rV.Kj("root",t);i.rotation.x=Math.PI/2;let r=new rV.Kj("linePivot",t);r.parent=i;let s=cylinderBuilder_CreateCylinder("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){let t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<5)return i;let n=r.clone("linePivotClone");return n.rotation.z=Math.PI,i};let CameraGizmo=class CameraGizmo extends gizmo_Gizmo{constructor(e=utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer){super(e),this._pointerObserver=null,this.onClickedObservable=new rf.y$,this._camera=null,this._invProjection=new rm.y3,this._material=new standardMaterial_StandardMaterial("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new rg.Wo(.5,.5,.5),this._material.specularColor=new rg.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(e=>{this._camera&&(this._isHovered=!!(e.pickInfo&&-1!=this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))},r8.kD.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=CameraGizmo._CreateCameraMesh(this.gizmoLayer.utilityLayerScene),this._cameraLinesMesh=CameraGizmo._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene),this._cameraMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._cameraMesh.parent=this._rootMesh,this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;let t=this.gizmoLayer._getSharedGizmoLight();t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){let t=new rV.Kj("rootCameraGizmo",e),i=new rV.Kj(t.name,e);i.parent=t;let r=boxBuilder_CreateBox(t.name,{width:1,height:.8,depth:.5},e);r.parent=i;let s=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);s.parent=i,s.position.y=.3,s.position.x=-.6,s.rotation.x=.5*Math.PI;let n=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);n.parent=i,n.position.y=.5,n.position.x=.4,n.rotation.x=.5*Math.PI;let a=cylinderBuilder_CreateCylinder(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return a.parent=i,a.position.y=0,a.position.x=.6,a.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(CameraGizmo._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e){let t=new rV.Kj("rootCameraGizmo",e),i=new rV.Kj(t.name,e);i.parent=t;for(let t=0;t<4;t+=2)for(let r=0;r<4;r+=2){let s=linesBuilder_CreateLines("lines",{points:[new rm.P(-1+r,-1+t,-1),new rm.P(-1+r,-1+t,1)]},e);s.parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=linesBuilder_CreateLines("lines",{points:[new rm.P(-1,-1+r,-1+t),new rm.P(1,-1+r,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1,(s=linesBuilder_CreateLines("lines",{points:[new rm.P(-1+r,-1,-1+t),new rm.P(-1+r,1,-1+t)]},e)).parent=i,s.alwaysSelectAsActiveMesh=!0,s.isPickable=!1}return t}};CameraGizmo._Scale=.05,s_.v.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";let a4=`vec4 pack(float depth) -{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} -float unpack(vec4 color) -{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;s_.v.IncludesShadersStore.packingFunctions=a4;let a5=`#ifdef DOF -factor=sampleCoC(sampleCoord{X}); -computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; -#else -computedWeight=KERNEL_WEIGHT{X}; -#endif -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; -#else -blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; -#endif -`;s_.v.IncludesShadersStore.kernelBlurFragment=a5;let a6=`#ifdef DOF -factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; -#else -computedWeight=KERNEL_DEP_WEIGHT{X}; -#endif -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; -#else -blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; -#endif -`;s_.v.IncludesShadersStore.kernelBlurFragment2=a6;let a8=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; -#ifdef DOF -uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } -#endif -#include[0..varyingCount] -#ifdef PACKEDFLOAT -#include -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float computedWeight=0.0; -#ifdef PACKEDFLOAT -float blend=0.; -#else -vec4 blend=vec4(0.); -#endif -#ifdef DOF -float sumOfWeights=CENTER_WEIGHT; -float factor=0.0; -#ifdef PACKEDFLOAT -blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; -#else -blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; -#endif -#endif -#include[0..varyingCount] -#include[0..depCount] -#ifdef PACKEDFLOAT -gl_FragColor=pack(blend); -#else -gl_FragColor=blend; -#endif -#ifdef DOF -gl_FragColor/=sumOfWeights; -#endif -}`;s_.v.ShadersStore.kernelBlurPixelShader=a8,s_.v.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";let a7=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; -#include[0..varyingCount] -const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -sampleCenter=(position*madd+madd); -#include[0..varyingCount] -gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.kernelBlurVertexShader=a7;let BlurPostProcess=class BlurPostProcess extends postProcess_PostProcess{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s,n=texture_Texture.BILINEAR_SAMPLINGMODE,a,o,l=0,h="",u=!1,c=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],r,s,n,a,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,c),this._blockCompilation=u,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add(e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,n){this._updateParameters(s,n)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],n=[],a=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){let t=1/3;return 1/(Math.sqrt(2*Math.PI)*t)*Math.exp(-(e*e/(2*t*t)))}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new BlurPostProcess(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}};(0,rH.gn)([(0,rb.qC)("kernel")],BlurPostProcess.prototype,"_kernel",void 0),(0,rH.gn)([(0,rb.qC)("packedFloat")],BlurPostProcess.prototype,"_packedFloat",void 0),(0,rH.gn)([(0,rb.QC)()],BlurPostProcess.prototype,"direction",void 0),(0,rv.H)("BABYLON.BlurPostProcess",BlurPostProcess);let MirrorTexture=class MirrorTexture extends renderTargetTexture_RenderTargetTexture{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){let e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){let e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,n=texture_Texture.BILINEAR_SAMPLINGMODE,a=!0){let o;if(super(e,t,i,r,!0,s,!1,n,a),this.mirrorPlane=new r2.J(0,1,0,1),this._transformMatrix=rm.y3.Zero(),this._mirrorMatrix=rm.y3.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateGammaSpace()});let l=i.getEngine();l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add(()=>{var t;null===(t=l._debugPushGroup)||void 0===t||t.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)}),this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),rm.y3.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),o=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=rm.P.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=o})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){let e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new BlurPostProcess("horizontal blur",new rm.FM(1,0),this._blurKernelX,this._blurRatio,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new BlurPostProcess("vertical blur",new rm.FM(0,1),this._blurKernelY,this._blurRatio,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new MirrorTexture(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;let e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();let t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}};texture_Texture._CreateMirror=(e,t,i,r)=>new MirrorTexture(e,t,i,r);let cubeTexture_CubeTexture=class cubeTexture_CubeTexture extends baseTexture_BaseTexture{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(rm.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach(e=>r+=e),new cubeTexture_CubeTexture(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){let s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;let n=new cubeTexture_CubeTexture(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,n}constructor(e,t,i=null,r=!1,s=null,n=null,a=null,o=5,l=!1,h=null,u=!1,c=.8,d=0,p,_){var f;if(super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new rf.y$,this.boundingBoxPosition=rm.P.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new rm.y3,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this._format=o,this.isCube=!0,this._textureMatrix=rm.y3.Identity(),this._createPolynomials=u,this.coordinatesMode=texture_Texture.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=h,this._loaderOptions=p,this._useSRGBBuffer=_,this._lodScale=c,this._lodOffset=d,!e&&!s)return;this.updateURL(e,h,n,l,a,i,null===(f=this.getScene())||void 0===f?void 0:f.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,r=!1,s=null,n=null,a=!1,o=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);let l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),u=0===h.indexOf(".dds"),c=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(c?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(d||c||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-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem)))return;let r=rm.jp.Vector3[0],s=rm.jp.Quaternion[0],n=rm.jp.Vector3[1];this._textureMatrix.decompose(r,s,n),s.z*=-1,s.w*=-1,rm.y3.ComposeToRef(r,s,n,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(null===(e=this.getScene())||void 0===e?void 0:e.useRightHandedSystem)?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;let r=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);let onLoadProcessing=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},errorHandler=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),texture_Texture.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?rW.w1.SetImmediate(()=>onLoadProcessing()):this._texture.onLoadedObservable.add(()=>onLoadProcessing()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,r,this._lodScale,this._lodOffset,e,errorHandler,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,r,this._files,this._noMipmap,e,errorHandler,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){let r=rb.p4.Parse(()=>{var r;let s=!1;return e.prefiltered&&(s=e.prefiltered),new cubeTexture_CubeTexture(i+(null!==(r=e.url)&&void 0!==r?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=rm.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=rm.P.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{let t=new cubeTexture_CubeTexture(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t},this);return t.uniqueId=e,t}};(0,rH.gn)([(0,rb.qC)()],cubeTexture_CubeTexture.prototype,"url",void 0),(0,rH.gn)([(0,rb.hd)()],cubeTexture_CubeTexture.prototype,"boundingBoxPosition",void 0),(0,rH.gn)([(0,rb.hd)()],cubeTexture_CubeTexture.prototype,"boundingBoxSize",null),(0,rH.gn)([(0,rb.qC)("rotationY")],cubeTexture_CubeTexture.prototype,"rotationY",null),(0,rH.gn)([(0,rb.qC)("files")],cubeTexture_CubeTexture.prototype,"_files",void 0),(0,rH.gn)([(0,rb.qC)("forcedExtension")],cubeTexture_CubeTexture.prototype,"_forcedExtension",void 0),(0,rH.gn)([(0,rb.qC)("extensions")],cubeTexture_CubeTexture.prototype,"_extensions",void 0),(0,rH.gn)([(0,rb.oQ)("textureMatrix")],cubeTexture_CubeTexture.prototype,"_textureMatrix",void 0),(0,rH.gn)([(0,rb.oQ)("textureMatrixRefraction")],cubeTexture_CubeTexture.prototype,"_textureMatrixRefraction",void 0),texture_Texture._CubeTextureParser=cubeTexture_CubeTexture.Parse,(0,rv.H)("BABYLON.CubeTexture",cubeTexture_CubeTexture);let a9=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; -#ifdef USEHIGHLIGHTANDSHADOWCOLORS -uniform vec4 vPrimaryColorShadow; -#endif -uniform float shadowLevel;uniform float alpha; -#ifdef DIFFUSE -uniform vec2 vDiffuseInfos; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; -#endif -#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) -uniform vec3 vBackgroundCenter; -#endif -#ifdef REFLECTIONFRESNEL -uniform vec4 vReflectionControl; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) -uniform mat4 view; -#endif -#ifdef PROJECTED_GROUND -uniform vec2 projectedGroundInfos; -#endif -`;s_.v.IncludesShadersStore.backgroundFragmentDeclaration=a9;let oe=`layout(std140,column_major) uniform;uniform Material -{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; -#include -`;s_.v.IncludesShadersStore.backgroundUboDeclaration=oe;let ot=`#ifdef TEXTURELODSUPPORT -#extension GL_EXT_shader_texture_lod : enable -#endif -precision highp float; -#include<__decl__backgroundFragment> -#include -varying vec3 vPositionW; -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef DIFFUSE -#if DIFFUSEDIRECTUV==1 -#define vDiffuseUV vMainUV1 -#elif DIFFUSEDIRECTUV==2 -#define vDiffuseUV vMainUV2 -#else -varying vec2 vDiffuseUV; -#endif -uniform sampler2D diffuseSampler; -#endif -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef TEXTURELODSUPPORT -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#include -#endif -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE; -#endif -#ifndef SHADOWONLY -#define SHADOWONLY; -#endif -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include -#include -#include -#include -#ifdef REFLECTIONFRESNEL -#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} -#endif -#ifdef PROJECTED_GROUND -float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; } -vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q) -vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=vec3(0.0,1.0,0.0); -#endif -float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; -#include[0..maxSimultaneousLights] -#ifdef SHADOWINUSE -globalShadow/=shadowLightCount; -#else -globalShadow=1.0; -#endif -#ifndef BACKMAT_SHADOWONLY -vec4 reflectionColor=vec4(1.,1.,1.,1.); -#ifdef REFLECTION -#ifdef PROJECTED_GROUND -vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); -#else -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords=reflectionVector; -#else -vec2 reflectionCoords=reflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -reflectionCoords/=reflectionVector.z; -#endif -reflectionCoords.y=1.0-reflectionCoords.y; -#endif -#ifdef REFLECTIONBLUR -float reflectionLOD=vReflectionInfos.y; -#ifdef TEXTURELODSUPPORT -reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); -#else -float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( -sampleReflection(reflectionSamplerHigh,reflectionCoords), -reflectionSpecularMid, -lodReflectionNormalizedDoubled -);} else {reflectionColor=mix( -reflectionSpecularMid, -sampleReflection(reflectionSamplerLow,reflectionCoords), -lodReflectionNormalizedDoubled-1.0 -);} -#endif -#else -vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; -#endif -#ifdef RGBDREFLECTION -reflectionColor.rgb=fromRGBD(reflectionColor); -#endif -#ifdef GAMMAREFLECTION -reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); -#endif -#ifdef REFLECTIONBGR -reflectionColor.rgb=reflectionColor.bgr; -#endif -reflectionColor.rgb*=vReflectionInfos.x; -#endif -vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; -#ifdef DIFFUSE -vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); -#ifdef GAMMADIFFUSE -diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); -#endif -diffuseMap.rgb*=vDiffuseInfos.y; -#ifdef DIFFUSEHASALPHA -finalAlpha*=diffuseMap.a; -#endif -diffuseColor=diffuseMap.rgb; -#endif -#ifdef REFLECTIONFRESNEL -vec3 colorBase=diffuseColor; -#else -vec3 colorBase=reflectionColor.rgb*diffuseColor; -#endif -colorBase=max(colorBase,0.0); -#ifdef USERGBCOLOR -vec3 finalColor=colorBase; -#else -#ifdef USEHIGHLIGHTANDSHADOWCOLORS -vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); -#else -vec3 mainColor=vPrimaryColor.rgb; -#endif -vec3 finalColor=colorBase*mainColor; -#endif -#ifdef REFLECTIONFRESNEL -vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; -#ifdef REFLECTIONFALLOFF -float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; -#endif -finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); -#endif -#ifdef OPACITYFRESNEL -float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; -#endif -#ifdef SHADOWINUSE -finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); -#endif -vec4 color=vec4(finalColor,finalAlpha); -#else -vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); -#endif -#include -#ifdef IMAGEPROCESSINGPOSTPROCESS -#if !defined(SKIPFINALCOLORCLAMP) -color.rgb=clamp(color.rgb,0.,30.0); -#endif -#else -color=applyImageProcessing(color); -#endif -#ifdef PREMULTIPLYALPHA -color.rgb*=color.a; -#endif -#ifdef NOISE -color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); -#endif -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -} -`;s_.v.ShadersStore.backgroundPixelShader=ot;let oi=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; -#ifdef DIFFUSE -uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -`;s_.v.IncludesShadersStore.backgroundVertexDeclaration=oi;let or=`precision highp float; -#include<__decl__backgroundVertex> -#include -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include -#include -#include -varying vec3 vPositionW; -#ifdef NORMAL -varying vec3 vNormalW; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef MAINUV1 -varying vec2 vMainUV1; -#endif -#ifdef MAINUV2 -varying vec2 vMainUV2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 -varying vec2 vDiffuseUV; -#endif -#include -#include -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=position; -#endif -#include -#include -#include -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} -#else -gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#endif -vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normal); -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); -#ifdef EQUIRECTANGULAR_RELFECTION_FOV -mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} -#endif -#endif -#ifndef UV1 -vec2 uv=vec2(0.,0.); -#endif -#ifndef UV2 -vec2 uv2=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uv; -#endif -#ifdef MAINUV2 -vMainUV2=uv2; -#endif -#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 -if (vDiffuseInfos.x==0.) -{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} -else -{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} -#endif -#include -#include -#include[0..maxSimultaneousLights] -#ifdef VERTEXCOLOR -vColor=color; -#endif -#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -#define CUSTOM_VERTEX_MAIN_END -} -`;s_.v.ShadersStore.backgroundVertexShader=or;let BackgroundMaterialDefines=class BackgroundMaterialDefines extends sn.H{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.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.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!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.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}};let BackgroundMaterial=class BackgroundMaterial extends PushMaterial{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=BackgroundMaterial.StandardReflectance0*t,this.reflectionReflectance90=BackgroundMaterial.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=BackgroundMaterial.StandardReflectance0+(1-BackgroundMaterial.StandardReflectance0)*t,this.reflectionReflectance90=BackgroundMaterial.StandardReflectance90+(1-BackgroundMaterial.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}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){super(e,t),this.primaryColor=rg.Wo.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=rm.P.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new sp.t(16),this._reflectionControls=rm.Lt.Zero(),this._white=rg.Wo.White(),this._primaryShadowColor=rg.Wo.Black(),this._primaryHighlightColor=rg.Wo.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!!this._diffuseTexture&&!!this._diffuseTexture.isRenderTarget||!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new BackgroundMaterialDefines);let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(so.G.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,so.G.PrepareDefinesForMultiview(r,s),s._areTexturesDirty){if(s._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;so.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE"),s.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,s.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,s.OPACITYFRESNEL=this._opacityFresnel}else s.DIFFUSE=!1,s.DIFFUSEDIRECTUV=0,s.DIFFUSEHASALPHA=!1,s.GAMMADIFFUSE=!1,s.OPACITYFRESNEL=!1;let e=this._reflectionTexture;if(e&&MaterialFlags.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(s.REFLECTION=!0,s.GAMMAREFLECTION=e.gammaSpace,s.RGBDREFLECTION=e.isRGBD,s.REFLECTIONBLUR=this._reflectionBlur>0,s.LODINREFLECTIONALPHA=e.lodLevelInAlpha,s.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,s.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===texture_Texture.INVCUBIC_MODE&&(s.INVERTCUBICMAP=!0),s.REFLECTIONMAP_3D=e.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case texture_Texture.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case texture_Texture.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case texture_Texture.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case texture_Texture.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case texture_Texture.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case texture_Texture.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.CUBIC_MODE:case texture_Texture.INVCUBIC_MODE:default:s.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(s.REFLECTIONFRESNEL=!0,s.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1)}else s.REFLECTION=!1,s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1,s.REFLECTIONBLUR=!1,s.REFLECTIONMAP_3D=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.INVERTCUBICMAP=!1,s.REFLECTIONMAP_OPPOSITEZ=!1,s.LODINREFLECTIONALPHA=!1,s.GAMMAREFLECTION=!1,s.RGBDREFLECTION=!1}s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.USERGBCOLOR=this._useRGBColor,s.NOISE=this._enableNoise}if(s._areLightsDirty&&(s.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),s.BACKMAT_SHADOWONLY=this._shadowOnly),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(s._areMiscDirty&&(s.REFLECTIONMAP_3D&&this._enableGroundProjection?(s.PROJECTED_GROUND=!0,s.REFLECTIONMAP_SKYBOX=!0):s.PROJECTED_GROUND=!1),so.G.PrepareDefinesForMisc(e,r,!1,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),so.G.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),so.G.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(rz.o.NormalKind)&&(e.createNormals(!0),rT.Y.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();let i=new EffectFallbacks;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),so.G.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);let a=[rz.o.PositionKind];s.NORMAL&&a.push(rz.o.NormalKind),s.UV1&&a.push(rz.o.UVKind),s.UV2&&a.push(rz.o.UV2Kind),so.G.PrepareAttributesForBones(a,e,s,i),so.G.PrepareAttributesForInstances(a,s);let o=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos"];(0,nX.qx)(o);let l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];sv.$&&(sv.$.PrepareUniforms(o,s),sv.$.PrepareSamplers(l,s)),so.G.PrepareUniformsAndSamplersList({uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});let u=s.toString(),c=r.getEngine().createEffect("background",{attributes:a,uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:u,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n);t.setEffect(c,s,this._materialContext),this.buildUniformLayout()}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)&&(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.materialDefines;if(!s)return;let n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),so.G.BindBonesParameters(t,this._activeEffect);let a=this._mustRebind(r,n,t.visibility);if(a){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);let e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(r.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),so.G.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&MaterialFlags.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&MaterialFlags.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&MaterialFlags.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),(0,nX.an)(this._activeEffect,this,r),r.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(a||!this.isFrozen)&&(r.lightsEnabled&&so.G.BindLights(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(n),so.G.BindFogParameters(r,t,this._activeEffect,!0),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return rb.p4.Clone(()=>new BackgroundMaterial(e,this.getScene()),this)}serialize(){let e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return rb.p4.Parse(()=>new BackgroundMaterial(e.name,t),e,t,i)}};BackgroundMaterial.StandardReflectance0=.05,BackgroundMaterial.StandardReflectance90=.5,(0,rH.gn)([(0,rb.n9)()],BackgroundMaterial.prototype,"_primaryColor",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"primaryColor",void 0),(0,rH.gn)([(0,rb.n9)()],BackgroundMaterial.prototype,"__perceptualColor",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_primaryColorShadowLevel",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_primaryColorHighlightLevel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"primaryColorHighlightLevel",null),(0,rH.gn)([(0,rb.oU)()],BackgroundMaterial.prototype,"_reflectionTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionTexture",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionBlur",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionBlur",void 0),(0,rH.gn)([(0,rb.oU)()],BackgroundMaterial.prototype,"_diffuseTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"diffuseTexture",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"shadowLights",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_shadowLevel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"shadowLevel",void 0),(0,rH.gn)([(0,rb.hd)()],BackgroundMaterial.prototype,"_sceneCenter",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"sceneCenter",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_opacityFresnel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"opacityFresnel",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionFresnel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionFresnel",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionFalloffDistance",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionFalloffDistance",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionAmount",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionAmount",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionReflectance0",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionReflectance0",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_reflectionReflectance90",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"reflectionReflectance90",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_useRGBColor",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"useRGBColor",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_enableNoise",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"enableNoise",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],BackgroundMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"_shadowOnly",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],BackgroundMaterial.prototype,"shadowOnly",void 0),(0,rH.gn)([(0,rb.rX)()],BackgroundMaterial.prototype,"_imageProcessingConfiguration",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],BackgroundMaterial.prototype,"enableGroundProjection",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"projectedGroundRadius",void 0),(0,rH.gn)([(0,rb.qC)()],BackgroundMaterial.prototype,"projectedGroundHeight",void 0),(0,rv.H)("BABYLON.BackgroundMaterial",BackgroundMaterial);let EnvironmentHelper=class EnvironmentHelper{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new rg.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new rg.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:rm.P.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=Object.assign(Object.assign({},EnvironmentHelper._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new rf.y$,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){let t=Object.assign(Object.assign({},this._options),e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new rg.HE(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof baseTexture_BaseTexture){this._scene.environmentTexture=this._options.environmentTexture;return}let e=cubeTexture_CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new rV.Kj("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;let e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};let r=this._scene.getWorldExtends(e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof ArcRotateCamera&&this._scene.activeCamera.upperRadiusLimit&&(t=e=2*this._scene.activeCamera.upperRadiusLimit);let n=s.length();n>e&&(t=e=2*n),e*=1.1,t*=1.5,(i=r.min.add(s.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=planeBuilder_CreatePlane("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(()=>{this._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new BackgroundMaterial("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof baseTexture_BaseTexture){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new texture_Texture(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture}}_setupGroundMirrorTexture(e){let t=texture_Texture.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new MirrorTexture("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,texture_Texture.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new r2.J(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new BackgroundMaterial("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof baseTexture_BaseTexture){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new cubeTexture_CubeTexture(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=texture_Texture.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture}}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}};EnvironmentHelper._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",EnvironmentHelper._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",EnvironmentHelper._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";let TextureDome=class TextureDome extends rk.Y{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=TextureDome.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new rf.y$,this.onLoadObservable=new rf.y$,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=void 0===i.autoPlay||!!i.autoPlay,i.loop=void 0===i.loop||!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=sphereBuilder_CreateSphere(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:rV.Kj.BACKSIDE},r);let n=this._material=new BackgroundMaterial(e+"_material",r);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;let a=this._initTexture(t,r,i);if(this.texture=a,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=sphereBuilder_CreateSphere("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:rV.Kj.BACKSIDE},r),this._halfDomeMask.rotate(rL.RD.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce(()=>{this._setReady(!0)}),i.faceForward&&r.activeCamera){let e=r.activeCamera,t=rm.P.Forward(),i=rm.P.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(rm.P.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case TextureDome.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case TextureDome.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;let e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=e:this._texture.uOffset=t});break}case TextureDome.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0})}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}};TextureDome.MODE_MONOSCOPIC=0,TextureDome.MODE_TOPBOTTOM=1,TextureDome.MODE_SIDEBYSIDE=2;let PhotoDome=class PhotoDome extends TextureDome{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new texture_Texture(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)})}};PhotoDome.MODE_MONOSCOPIC=TextureDome.MODE_MONOSCOPIC,PhotoDome.MODE_TOPBOTTOM=TextureDome.MODE_TOPBOTTOM,PhotoDome.MODE_SIDEBYSIDE=TextureDome.MODE_SIDEBYSIDE;let os=0,GetEnvironmentBRDFTexture=e=>{if(!e.environmentBRDFTexture){let t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;let i=e._blockEntityCollection;e._blockEntityCollection=!1;let r=texture_Texture.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"+os++,e,!0,!1,texture_Texture.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;let s=e.getEngine().getLoadedTexturesCache(),n=s.indexOf(r.getInternalTexture());-1!==n&&s.splice(n,1),r.isRGBD=!0,r.wrapU=texture_Texture.CLAMP_ADDRESSMODE,r.wrapV=texture_Texture.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,RGBDTextureTools.ExpandRGBDTexture(r);let a=e.getEngine().onContextRestoredObservable.add(()=>{r.isRGBD=!0;let checkReady=()=>{r.isReady()?RGBDTextureTools.ExpandRGBDTexture(r):rW.w1.SetImmediate(checkReady)};checkReady()});e.onDisposeObservable.add(()=>{e.getEngine().onContextRestoredObservable.remove(a)})}return e.environmentBRDFTexture};let MaterialBRDFDefines=class MaterialBRDFDefines extends sn.H{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}};let pbrBRDFConfiguration_PBRBRDFConfiguration=class pbrBRDFConfiguration_PBRBRDFConfiguration extends MaterialPluginBase{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new MaterialBRDFDefines,t),this._useEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],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"}};pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS=!0,pbrBRDFConfiguration_PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useEnergyConservation",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSphericalHarmonics",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBRDFConfiguration_PBRBRDFConfiguration.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);let on=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; -#ifdef ALBEDO -uniform vec2 vAlbedoInfos; -#endif -#ifdef AMBIENT -uniform vec4 vAmbientInfos; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#ifdef OPACITY -uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos; -#endif -#ifdef REFLECTIVITY -uniform vec3 vReflectivityInfos; -#endif -#ifdef MICROSURFACEMAP -uniform vec2 vMicroSurfaceSamplerInfos; -#endif -#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) -uniform mat4 view; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos; -#ifdef REALTIME_FILTERING -uniform vec2 vReflectionFilteringInfo; -#endif -uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; -#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) -uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; -#endif -#ifdef CLEARCOAT -uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; -#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) -uniform vec4 vClearCoatInfos; -#endif -#ifdef CLEARCOAT_TEXTURE -uniform mat4 clearCoatMatrix; -#endif -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS -uniform mat4 clearCoatRoughnessMatrix; -#endif -#ifdef CLEARCOAT_BUMP -uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; -#endif -#ifdef CLEARCOAT_TINT -uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; -#ifdef CLEARCOAT_TINT_TEXTURE -uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; -#endif -#endif -#endif -#ifdef IRIDESCENCE -uniform vec4 vIridescenceParams; -#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) -uniform vec4 vIridescenceInfos; -#endif -#ifdef IRIDESCENCE_TEXTURE -uniform mat4 iridescenceMatrix; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -uniform mat4 iridescenceThicknessMatrix; -#endif -#endif -#ifdef ANISOTROPIC -uniform vec3 vAnisotropy; -#ifdef ANISOTROPIC_TEXTURE -uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; -#endif -#endif -#ifdef SHEEN -uniform vec4 vSheenColor; -#ifdef SHEEN_ROUGHNESS -uniform float vSheenRoughness; -#endif -#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) -uniform vec4 vSheenInfos; -#endif -#ifdef SHEEN_TEXTURE -uniform mat4 sheenMatrix; -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -uniform mat4 sheenRoughnessMatrix; -#endif -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; -#ifdef REALTIME_FILTERING -uniform vec2 vRefractionFilteringInfo; -#endif -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; -#endif -uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; -#endif -#ifdef PREPASS -#ifdef SS_SCATTERING -uniform float scatteringDiffusionProfile; -#endif -#endif -#if DEBUGMODE>0 -uniform vec2 vDebugMode; -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos; -#endif -#include -#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; -#else -uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; -#endif -#endif -#define ADDITIONAL_FRAGMENT_DECLARATION -`;s_.v.IncludesShadersStore.pbrFragmentDeclaration=on;let oa=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; -#define ADDITIONAL_UBO_DECLARATION -}; -#include -#include -`;s_.v.IncludesShadersStore.pbrUboDeclaration=oa;let oo=`varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#include[1..7] -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#endif -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -`;s_.v.IncludesShadersStore.pbrFragmentExtraDeclaration=oo;let ol=`#ifdef _DEFINENAME_ -#if _DEFINENAME_DIRECTUV==1 -#define v_VARYINGNAME_UV vMainUV1 -#elif _DEFINENAME_DIRECTUV==2 -#define v_VARYINGNAME_UV vMainUV2 -#elif _DEFINENAME_DIRECTUV==3 -#define v_VARYINGNAME_UV vMainUV3 -#elif _DEFINENAME_DIRECTUV==4 -#define v_VARYINGNAME_UV vMainUV4 -#elif _DEFINENAME_DIRECTUV==5 -#define v_VARYINGNAME_UV vMainUV5 -#elif _DEFINENAME_DIRECTUV==6 -#define v_VARYINGNAME_UV vMainUV6 -#else -varying vec2 v_VARYINGNAME_UV; -#endif -#endif -`;s_.v.IncludesShadersStore.samplerFragmentAlternateDeclaration=ol;let oh=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) -#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) -#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) -#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) -#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) -#ifdef CLEARCOAT -#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) -#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D clearCoatRoughnessSampler; -#endif -#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) -#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) -#endif -#ifdef IRIDESCENCE -#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) -#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) -#endif -#ifdef SHEEN -#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) -#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) -uniform sampler2D sheenRoughnessSampler; -#endif -#endif -#ifdef ANISOTROPIC -#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) -#endif -#ifdef REFLECTION -#ifdef REFLECTIONMAP_3D -#define sampleReflection(s,c) textureCube(s,c) -uniform samplerCube reflectionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; -#endif -#ifdef USEIRRADIANCEMAP -uniform samplerCube irradianceSampler; -#endif -#else -#define sampleReflection(s,c) texture2D(s,c) -uniform sampler2D reflectionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; -#endif -#ifdef USEIRRADIANCEMAP -uniform sampler2D irradianceSampler; -#endif -#endif -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#else -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#endif -#endif -#ifdef ENVIRONMENTBRDF -uniform sampler2D environmentBrdfSampler; -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -#ifdef SS_REFRACTIONMAP_3D -#define sampleRefraction(s,c) textureCube(s,c) -uniform samplerCube refractionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) -#else -uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; -#endif -#else -#define sampleRefraction(s,c) texture2D(s,c) -uniform sampler2D refractionSampler; -#ifdef LODBASEDMICROSFURACE -#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) -#else -uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; -#endif -#endif -#endif -#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) -#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) -#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) -#endif -`;s_.v.IncludesShadersStore.pbrFragmentSamplersDeclaration=oh;let ou=`bool testLightingForSSS(float diffusionProfile) -{return diffusionProfile<1.;}`;s_.v.IncludesShadersStore.subSurfaceScatteringFunctions=ou;let oc=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} -vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} -vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { -float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;s_.v.IncludesShadersStore.importanceSampling=oc;let od=`#define MINIMUMVARIANCE 0.0005 -float convertRoughnessToAverageSlope(float roughness) -{return square(roughness)+MINIMUMVARIANCE;} -float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} -vec2 getAARoughnessFactors(vec3 normalVector) { -#ifdef SPECULARAA -vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); -#else -return vec2(0.); -#endif -} -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_LEGACY -vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} -vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} -#else -vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} -vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} -#endif -#endif -#if defined(CLEARCOAT) || defined(SS_REFRACTION) -vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} -vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} -vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} -vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), -cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), -clearCoatIntensity);return clearCoatAbsorption;} -#endif -#ifdef MICROSURFACEAUTOMATIC -float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) -{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} -#endif -`;s_.v.IncludesShadersStore.pbrHelperFunctions=od;let op=`#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 -+ vSphericalL1_1*(normal.y) -+ vSphericalL10*(normal.z) -+ vSphericalL11*(normal.x) -+ vSphericalL2_2*(normal.y*normal.x) -+ vSphericalL2_1*(normal.y*normal.z) -+ vSphericalL20*((3.0*normal.z*normal.z)-1.0) -+ vSphericalL21*(normal.z*normal.x) -+ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} -#else -vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} -#endif -#endif -`;s_.v.IncludesShadersStore.harmonicsFunctions=op;let o_=`struct preLightingInfo -{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; -#ifdef IRIDESCENCE -float iridescenceIntensity; -#endif -};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} -preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} -preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; -#ifdef SPECULARTERM -result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); -#endif -return result;}`;s_.v.IncludesShadersStore.pbrDirectLightingSetupFunctions=o_;let of=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) -{return max(0.,1.0-length(lightOffset)/range);} -float computeDistanceLightFalloff_Physical(float lightDistanceSquared) -{return 1.0/maxEps(lightDistanceSquared);} -float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) -{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} -float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) -{ -#ifdef USEPHYSICALLIGHTFALLOFF -return computeDistanceLightFalloff_Physical(lightDistanceSquared); -#elif defined(USEGLTFLIGHTFALLOFF) -return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); -#else -return computeDistanceLightFalloff_Standard(lightOffset,range); -#endif -} -float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) -{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) -{falloff=max(0.,pow(cosAngle,exponent));} -return falloff;} -float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) -{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; -float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} -float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) -{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} -float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) -{ -#ifdef USEPHYSICALLIGHTFALLOFF -return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); -#elif defined(USEGLTFLIGHTFALLOFF) -return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); -#else -return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); -#endif -}`;s_.v.IncludesShadersStore.pbrDirectLightingFalloffFunctions=of;let om=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 -#ifdef MS_BRDF_ENERGY_CONSERVATION -vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} -#endif -#ifdef ENVIRONMENTBRDF -vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); -#ifdef ENVIRONMENTBRDF_RGBD -brdfLookup.rgb=fromRGBD(brdfLookup.rgba); -#endif -return brdfLookup.rgb;} -vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { -#ifdef BRDF_V_HEIGHT_CORRELATED -vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; -#else -vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; -#endif -return reflectance;} -vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { -#ifdef BRDF_V_HEIGHT_CORRELATED -vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); -#else -vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; -#endif -return reflectance;} -#endif -/* NOT USED -#if defined(SHEEN) && defined(SHEEN_SOFTER) -float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) -{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} -#endif -*/ -#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) -vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) -{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) -/** -* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. -* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table -*/ -vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} -#endif -vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) -{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} -float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) -{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} -#ifdef CLEARCOAT -vec3 getR0RemappedForClearCoat(vec3 f0) { -#ifdef CLEARCOAT_DEFAULTIOR -#ifdef MOBILE -return saturate(f0*(f0*0.526868+0.529324)-0.0482256); -#else -return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); -#endif -#else -vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); -#endif -} -#endif -#ifdef IRIDESCENCE -const mat3 XYZ_TO_REC709=mat3( -3.2404542,-0.9692660, 0.0556434, --1.5371385, 1.8760108,-0.2040259, --0.4985314, 0.0415560, 1.0572252 -);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} -vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} -float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} -vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} -vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} -float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0 -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -float radicalInverse_VdC(uint bits) -{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } -vec2 hammersley(uint i,uint N) -{return vec2(float(i)/float(N),radicalInverse_VdC(i));} -#else -float vanDerCorpus(int n,int base) -{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) -{if(n>0) -{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} -return result;} -vec2 hammersley(int i,int N) -{return vec2(float(i)/float(N),vanDerCorpus(i,2));} -#endif -float log4(float x) {return log2(x)/2.;} -const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; -#define inline -vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -for(uint i=0u; i0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c;}} -result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} -#define inline -vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) -{vec3 n=normalize(inputN);if (alphaG==0.) {vec3 c=textureCube(inputTexture,n).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; -#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -for(uint i=0u; i0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; -#ifdef GAMMA_INPUT -c=toLinearSpace(c); -#endif -result+=c*NoL;}} -result=result/weight;return result;}} -#endif -#endif -`;s_.v.IncludesShadersStore.hdrFilteringFunctions=og;let ov=`#define CLEARCOATREFLECTANCE90 1.0 -struct lightingInfo -{vec3 diffuse; -#ifdef SPECULARTERM -vec3 specular; -#endif -#ifdef CLEARCOAT -vec4 clearCoat; -#endif -#ifdef SHEEN -vec3 sheen; -#endif -};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { -#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) -float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; -#else -return roughness; -#endif -} -vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} -vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} -#define inline -vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} -#ifdef SS_TRANSLUCENCY -vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} -#endif -#ifdef SPECULARTERM -vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); -#ifdef IRIDESCENCE -fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); -#endif -float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); -#ifdef BRDF_V_HEIGHT_CORRELATED -float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); -#else -float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); -#endif -vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} -#endif -#ifdef ANISOTROPIC -vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); -#ifdef IRIDESCENCE -fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); -#endif -float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} -#endif -#ifdef CLEARCOAT -vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( -clearCoatTerm*info.attenuation*NccdotL*lightColor, -1.0-fresnel -);} -vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} -#endif -#ifdef SHEEN -vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER -float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); -#else */ -float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ -float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} -#endif -`;s_.v.IncludesShadersStore.pbrDirectLightingFunctions=ov;let ox=`#if defined(REFLECTION) || defined(SS_REFRACTION) -float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} -float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} -#endif -#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) -float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} -#endif -#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) -float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} -#endif -#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) -#define UNPACK_LOD(x) (1.0-x)*255.0 -float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} -#endif -`;s_.v.IncludesShadersStore.pbrIBLFunctions=ox;let oT=`struct albedoOpacityOutParams -{vec3 surfaceAlbedo;float alpha;}; -#define pbr_inline -void albedoOpacityBlock( -in vec4 vAlbedoColor, -#ifdef ALBEDO -in vec4 albedoTexture, -in vec2 albedoInfos, -#endif -#ifdef OPACITY -in vec4 opacityMap, -in vec2 vOpacityInfos, -#endif -#ifdef DETAIL -in vec4 detailColor, -in vec4 vDetailInfos, -#endif -#ifdef DECAL -in vec4 decalColor, -in vec4 vDecalInfos, -#endif -out albedoOpacityOutParams outParams -) -{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; -#ifdef ALBEDO -#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) -alpha*=albedoTexture.a; -#endif -#ifdef GAMMAALBEDO -surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); -#else -surfaceAlbedo*=albedoTexture.rgb; -#endif -surfaceAlbedo*=albedoInfos.y; -#endif -#ifndef DECAL_AFTER_DETAIL -#include -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -surfaceAlbedo*=vColor.rgb; -#endif -#ifdef DETAIL -float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; -#endif -#ifdef DECAL_AFTER_DETAIL -#include -#endif -#define CUSTOM_FRAGMENT_UPDATE_ALBEDO -#ifdef OPACITY -#ifdef OPACITYRGB -alpha=getLuminance(opacityMap.rgb); -#else -alpha*=opacityMap.a; -#endif -alpha*=vOpacityInfos.y; -#endif -#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) -alpha*=vColor.a; -#endif -#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) -#ifdef ALPHATEST -#if DEBUGMODE != 88 -if (alpha0 -#ifdef METALLICWORKFLOW -vec2 metallicRoughness; -#ifdef REFLECTIVITY -vec4 surfaceMetallicColorMap; -#endif -#ifndef FROSTBITE_REFLECTANCE -vec3 metallicF0; -#endif -#else -#ifdef REFLECTIVITY -vec4 surfaceReflectivityColorMap; -#endif -#endif -#endif -}; -#define pbr_inline -void reflectivityBlock( -in vec4 vReflectivityColor, -#ifdef METALLICWORKFLOW -in vec3 surfaceAlbedo, -in vec4 metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -in vec3 reflectivityInfos, -in vec4 surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -in vec3 ambientOcclusionColorIn, -#endif -#ifdef MICROSURFACEMAP -in vec4 microSurfaceTexel, -#endif -#ifdef DETAIL -in vec4 detailColor, -in vec4 vDetailInfos, -#endif -out reflectivityOutParams outParams -) -{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; -#ifdef METALLICWORKFLOW -vec2 metallicRoughness=surfaceReflectivityColor.rg; -#ifdef REFLECTIVITY -#if DEBUGMODE>0 -outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; -#endif -#ifdef AOSTOREINMETALMAPRED -vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); -#endif -#ifdef METALLNESSSTOREINMETALMAPBLUE -metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; -#else -metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; -#endif -#ifdef ROUGHNESSSTOREINMETALMAPALPHA -metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; -#else -#ifdef ROUGHNESSSTOREINMETALMAPGREEN -metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; -#endif -#endif -#endif -#ifdef DETAIL -float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); -#endif -#ifdef MICROSURFACEMAP -metallicRoughness.g*=microSurfaceTexel.r; -#endif -#if DEBUGMODE>0 -outParams.metallicRoughness=metallicRoughness; -#endif -#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS -microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; -#ifdef FROSTBITE_REFLECTANCE -outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); -#else -vec3 metallicF0=metallicReflectanceFactors.rgb; -#if DEBUGMODE>0 -outParams.metallicF0=metallicF0; -#endif -outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); -#endif -#else -#ifdef REFLECTIVITY -surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; -#if DEBUGMODE>0 -outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; -#endif -#ifdef MICROSURFACEFROMREFLECTIVITYMAP -microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; -#else -#ifdef MICROSURFACEAUTOMATIC -microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); -#endif -#ifdef MICROSURFACEMAP -microSurface*=microSurfaceTexel.r; -#endif -#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE -#endif -#endif -#endif -microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} -`;s_.v.IncludesShadersStore.pbrBlockReflectivity=oS;let oC=`struct ambientOcclusionOutParams -{vec3 ambientOcclusionColor; -#if DEBUGMODE>0 && defined(AMBIENT) -vec3 ambientOcclusionColorMap; -#endif -}; -#define pbr_inline -void ambientOcclusionBlock( -#ifdef AMBIENT -in vec3 ambientOcclusionColorMap_, -in vec4 vAmbientInfos, -#endif -out ambientOcclusionOutParams outParams -) -{vec3 ambientOcclusionColor=vec3(1.,1.,1.); -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; -#ifdef AMBIENTINGRAYSCALE -ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); -#endif -ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); -#if DEBUGMODE>0 -outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; -#endif -#endif -outParams.ambientOcclusionColor=ambientOcclusionColor;} -`;s_.v.IncludesShadersStore.pbrBlockAmbientOcclusion=oC;let oE=`#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -struct alphaFresnelOutParams -{float alpha;}; -#define pbr_inline -void alphaFresnelBlock( -in vec3 normalW, -in vec3 viewDirectionW, -in float alpha, -in float microSurface, -out alphaFresnelOutParams outParams -) -{float opacityPerceptual=alpha; -#ifdef LINEARALPHAFRESNEL -float opacity0=opacityPerceptual; -#else -float opacity0=opacityPerceptual*opacityPerceptual; -#endif -float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; -#ifdef ALPHATEST -if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) -vec3 anisotropyMapData; -#endif -}; -#define pbr_inline -void anisotropicBlock( -in vec3 vAnisotropy, -in float roughness, -#ifdef ANISOTROPIC_TEXTURE -in vec3 anisotropyMapData, -#endif -in mat3 TBN, -in vec3 normalW, -in vec3 viewDirectionW, -out anisotropicOutParams outParams -) -{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); -#ifdef ANISOTROPIC_TEXTURE -anisotropy*=anisotropyMapData.b; -#if DEBUGMODE>0 -outParams.anisotropyMapData=anisotropyMapData; -#endif -anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; -#ifdef ANISOTROPIC_LEGACY -anisotropyDirection.rg*=anisotropyMapData.rg; -#else -anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); -#endif -#endif -mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} -#endif -`;s_.v.IncludesShadersStore.pbrBlockAnisotropic=ob;let oy=`#ifdef REFLECTION -struct reflectionOutParams -{vec4 environmentRadiance;vec3 environmentIrradiance; -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords; -#else -vec2 reflectionCoords; -#endif -#ifdef SS_TRANSLUCENCY -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -vec3 irradianceVector; -#endif -#endif -#endif -}; -#define pbr_inline -void createReflectionCoords( -in vec3 vPositionW, -in vec3 normalW, -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#ifdef REFLECTIONMAP_3D -out vec3 reflectionCoords -#else -out vec2 reflectionCoords -#endif -) -{ -#ifdef ANISOTROPIC -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); -#else -vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -reflectionCoords=reflectionVector; -#else -reflectionCoords=reflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -reflectionCoords/=reflectionVector.z; -#endif -reflectionCoords.y=1.0-reflectionCoords.y; -#endif -} -#define pbr_inline -#define inline -void sampleReflectionTexture( -in float alphaG, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -const vec3 reflectionCoords, -#else -in sampler2D reflectionSampler, -const vec2 reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -out vec4 environmentRadiance -) -{ -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); -#elif defined(LINEARSPECULARREFLECTION) -float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); -#else -float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); -#endif -#ifdef LODBASEDMICROSFURACE -reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; -#ifdef LODINREFLECTIONALPHA -float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); -#else -float requestedReflectionLOD=reflectionLOD; -#endif -#ifdef REALTIME_FILTERING -environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); -#else -environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); -#endif -#else -float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( -sampleReflection(reflectionSamplerHigh,reflectionCoords), -environmentMid, -lodReflectionNormalizedDoubled -);} else {environmentRadiance=mix( -environmentMid, -sampleReflection(reflectionSamplerLow,reflectionCoords), -lodReflectionNormalizedDoubled-1.0 -);} -#endif -#ifdef RGBDREFLECTION -environmentRadiance.rgb=fromRGBD(environmentRadiance); -#endif -#ifdef GAMMAREFLECTION -environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); -#endif -environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} -#define pbr_inline -#define inline -void reflectionBlock( -in vec3 vPositionW, -in vec3 normalW, -in float alphaG, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -in float NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -in float roughness, -#endif -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -#else -in sampler2D reflectionSampler, -#endif -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -in vec3 vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -in mat4 reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -in samplerCube irradianceSampler, -#else -in sampler2D irradianceSampler, -#endif -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -out reflectionOutParams outParams -) -{vec4 environmentRadiance=vec4(0.,0.,0.,0.); -#ifdef REFLECTIONMAP_3D -vec3 reflectionCoords=vec3(0.); -#else -vec2 reflectionCoords=vec2(0.); -#endif -createReflectionCoords( -vPositionW, -normalW, -#ifdef ANISOTROPIC -anisotropicOut, -#endif -reflectionCoords -);sampleReflectionTexture( -alphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -roughness, -#endif -#ifdef REFLECTIONMAP_3D -reflectionSampler, -reflectionCoords, -#else -reflectionSampler, -reflectionCoords, -#endif -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentRadiance -);vec3 environmentIrradiance=vec3(0.,0.,0.); -#ifdef USESPHERICALFROMREFLECTIONMAP -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -environmentIrradiance=vEnvironmentIrradiance; -#else -#ifdef ANISOTROPIC -vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; -#else -vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; -#endif -#ifdef REFLECTIONMAP_OPPOSITEZ -irradianceVector.z*=-1.0; -#endif -#ifdef INVERTCUBICMAP -irradianceVector.y*=-1.0; -#endif -#if defined(REALTIME_FILTERING) -environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); -#else -environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); -#endif -#ifdef SS_TRANSLUCENCY -outParams.irradianceVector=irradianceVector; -#endif -#endif -#elif defined(USEIRRADIANCEMAP) -vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; -#ifdef RGBDREFLECTION -environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); -#endif -#ifdef GAMMAREFLECTION -environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); -#endif -#endif -environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} -#endif -`;s_.v.IncludesShadersStore.pbrBlockReflection=oy;let oP=`#ifdef SHEEN -struct sheenOutParams -{float sheenIntensity;vec3 sheenColor;float sheenRoughness; -#ifdef SHEEN_LINKWITHALBEDO -vec3 surfaceAlbedo; -#endif -#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -float sheenAlbedoScaling; -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -vec3 finalSheenRadianceScaled; -#endif -#if DEBUGMODE>0 -#ifdef SHEEN_TEXTURE -vec4 sheenMapData; -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -vec3 sheenEnvironmentReflectance; -#endif -#endif -}; -#define pbr_inline -#define inline -void sheenBlock( -in vec4 vSheenColor, -#ifdef SHEEN_ROUGHNESS -in float vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -in vec4 sheenMapRoughnessData, -#endif -#endif -in float roughness, -#ifdef SHEEN_TEXTURE -in vec4 sheenMapData, -in float sheenMapLevel, -#endif -in float reflectance, -#ifdef SHEEN_LINKWITHALBEDO -in vec3 baseColor, -in vec3 surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -in float NdotV, -in vec3 environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -in vec2 AARoughnessFactors, -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -in vec3 reflectionCoords, -#else -in sampler2D reflectionSampler, -in vec2 reflectionCoords, -#endif -in float NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -in float seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -in float eho, -#endif -#endif -out sheenOutParams outParams -) -{float sheenIntensity=vSheenColor.a; -#ifdef SHEEN_TEXTURE -#if DEBUGMODE>0 -outParams.sheenMapData=sheenMapData; -#endif -#endif -#ifdef SHEEN_LINKWITHALBEDO -float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; -#ifdef SHEEN_TEXTURE -sheenIntensity*=sheenMapData.a; -#endif -#else -vec3 sheenColor=vSheenColor.rgb; -#ifdef SHEEN_TEXTURE -#ifdef SHEEN_GAMMATEXTURE -sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); -#else -sheenColor.rgb*=sheenMapData.rgb; -#endif -sheenColor.rgb*=sheenMapLevel; -#endif -#ifdef SHEEN_ROUGHNESS -float sheenRoughness=vSheenRoughness; -#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE -#if defined(SHEEN_TEXTURE) -sheenRoughness*=sheenMapData.a; -#endif -#elif defined(SHEEN_TEXTURE_ROUGHNESS) -#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL -sheenRoughness*=sheenMapData.a; -#else -sheenRoughness*=sheenMapRoughnessData.a; -#endif -#endif -#else -float sheenRoughness=roughness; -#ifdef SHEEN_TEXTURE -sheenIntensity*=sheenMapData.a; -#endif -#endif -#if !defined(SHEEN_ALBEDOSCALING) -sheenIntensity*=(1.-reflectance); -#endif -sheenColor*=sheenIntensity; -#endif -#ifdef ENVIRONMENTBRDF -/*#ifdef SHEEN_SOFTER -vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); -#else*/ -#ifdef SHEEN_ROUGHNESS -vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); -#else -vec3 environmentSheenBrdf=environmentBrdf; -#endif -/*#endif*/ -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); -#ifdef SPECULARAA -sheenAlphaG+=AARoughnessFactors.y; -#endif -vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( -sheenAlphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -sheenRoughness, -#endif -reflectionSampler, -reflectionCoords, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentSheenRadiance -);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -sheenEnvironmentReflectance*=seo; -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -sheenEnvironmentReflectance*=eho; -#endif -#if DEBUGMODE>0 -outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; -#endif -outParams.finalSheenRadianceScaled= -environmentSheenRadiance.rgb * -sheenEnvironmentReflectance * -vLightingIntensity.z; -#endif -#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; -#endif -outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} -#endif -`;s_.v.IncludesShadersStore.pbrBlockSheen=oP;let oR=`struct clearcoatOutParams -{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; -#ifdef REFLECTION -vec3 finalClearCoatRadianceScaled; -#endif -#ifdef CLEARCOAT_TINT -vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; -#endif -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -vec3 energyConservationFactorClearCoat; -#endif -#if DEBUGMODE>0 -#ifdef CLEARCOAT_BUMP -mat3 TBNClearCoat; -#endif -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData; -#endif -#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -vec4 clearCoatTintMapData; -#endif -#ifdef REFLECTION -vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; -#endif -float clearCoatNdotV; -#endif -}; -#ifdef CLEARCOAT -#define pbr_inline -#define inline -void clearcoatBlock( -in vec3 vPositionW, -in vec3 geometricNormalW, -in vec3 viewDirectionW, -in vec2 vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -in vec4 clearCoatMapRoughnessData, -#endif -in vec3 specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -in vec2 clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -in vec4 vClearCoatTintParams, -in float clearCoatColorAtDistance, -in vec4 vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -in vec4 clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -in vec2 vClearCoatBumpInfos, -in vec4 clearCoatBumpMapData, -in vec2 vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -in mat3 vTBN, -#else -in vec2 vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -in mat4 normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -in vec3 faceNormal, -#endif -#ifdef REFLECTION -in vec3 vReflectionMicrosurfaceInfos, -in vec2 vReflectionInfos, -in vec3 vReflectionColor, -in vec4 vLightingIntensity, -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSampler, -#else -in sampler2D reflectionSampler, -#endif -#ifndef LODBASEDMICROSFURACE -#ifdef REFLECTIONMAP_3D -in samplerCube reflectionSamplerLow, -in samplerCube reflectionSamplerHigh, -#else -in sampler2D reflectionSamplerLow, -in sampler2D reflectionSamplerHigh, -#endif -#endif -#ifdef REALTIME_FILTERING -in vec2 vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -in float ambientMonochrome, -#endif -#endif -#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) -in float frontFacingMultiplier, -#endif -out clearcoatOutParams outParams -) -{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; -#ifdef CLEARCOAT_TEXTURE -clearCoatIntensity*=clearCoatMapData.x; -#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE -clearCoatRoughness*=clearCoatMapData.y; -#endif -#if DEBUGMODE>0 -outParams.clearCoatMapData=clearCoatMapData; -#endif -#endif -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL -clearCoatRoughness*=clearCoatMapData.y; -#else -clearCoatRoughness*=clearCoatMapRoughnessData.y; -#endif -#endif -outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; -#ifdef CLEARCOAT_TINT -vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; -#ifdef CLEARCOAT_TINT_TEXTURE -#ifdef CLEARCOAT_TINT_GAMMATEXTURE -clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); -#else -clearCoatColor*=clearCoatTintMapData.rgb; -#endif -clearCoatThickness*=clearCoatTintMapData.a; -#if DEBUGMODE>0 -outParams.clearCoatTintMapData=clearCoatTintMapData; -#endif -#endif -outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; -#endif -#ifdef CLEARCOAT_REMAP_F0 -vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); -#else -vec3 specularEnvironmentR0Updated=specularEnvironmentR0; -#endif -outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; -#ifdef CLEARCOAT_BUMP -#ifdef NORMALXYSCALE -float clearCoatNormalScale=1.0; -#else -float clearCoatNormalScale=vClearCoatBumpInfos.y; -#endif -#if defined(TANGENT) && defined(NORMAL) -mat3 TBNClearCoat=vTBN; -#else -vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); -#endif -#if DEBUGMODE>0 -outParams.TBNClearCoat=TBNClearCoat; -#endif -#ifdef OBJECTSPACE_NORMALMAP -clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); -#else -clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); -#endif -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; -#endif -outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); -#if DEBUGMODE>0 -outParams.clearCoatNdotV=clearCoatNdotV; -#endif -#ifdef CLEARCOAT_TINT -vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); -#endif -#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) -vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); -#endif -#if defined(REFLECTION) -float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); -#ifdef SPECULARAA -clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; -#endif -vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); -#ifdef REFLECTIONMAP_OPPOSITEZ -clearCoatReflectionVector.z*=-1.0; -#endif -#ifdef REFLECTIONMAP_3D -vec3 clearCoatReflectionCoords=clearCoatReflectionVector; -#else -vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -clearCoatReflectionCoords/=clearCoatReflectionVector.z; -#endif -clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; -#endif -sampleReflectionTexture( -clearCoatAlphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -clearCoatNdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -clearCoatRoughness, -#endif -reflectionSampler, -clearCoatReflectionCoords, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -environmentClearCoatRadiance -); -#if DEBUGMODE>0 -outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; -#endif -#endif -#endif -#else -vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); -#endif -clearCoatEnvironmentReflectance*=clearCoatIntensity; -#if DEBUGMODE>0 -outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; -#endif -outParams.finalClearCoatRadianceScaled= -environmentClearCoatRadiance.rgb * -clearCoatEnvironmentReflectance * -vLightingIntensity.z; -#endif -#if defined(CLEARCOAT_TINT) -outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); -#endif -float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); -#endif -} -#endif -`;s_.v.IncludesShadersStore.pbrBlockClearcoat=oR;let oA=`struct iridescenceOutParams -{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; -#ifdef IRIDESCENCE -#define pbr_inline -#define inline -void iridescenceBlock( -in vec4 vIridescenceParams, -in float viewAngle, -in vec3 specularEnvironmentR0, -#ifdef IRIDESCENCE_TEXTURE -in vec2 iridescenceMapData, -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -in vec2 iridescenceThicknessMapData, -#endif -#ifdef CLEARCOAT -in float NdotVUnclamped, -#ifdef CLEARCOAT_TEXTURE -in vec2 clearCoatMapData, -#endif -#endif -out iridescenceOutParams outParams -) -{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; -#ifdef IRIDESCENCE_TEXTURE -iridescenceIntensity*=iridescenceMapData.x; -#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE -iridescenceThicknessWeight=iridescenceMapData.g; -#endif -#endif -#if defined(IRIDESCENCE_THICKNESS_TEXTURE) -iridescenceThicknessWeight=iridescenceThicknessMapData.g; -#endif -float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; -#ifdef CLEARCOAT -float clearCoatIntensity=vClearCoatParams.x; -#ifdef CLEARCOAT_TEXTURE -clearCoatIntensity*=clearCoatMapData.x; -#endif -topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); -#endif -vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} -#endif -`;s_.v.IncludesShadersStore.pbrBlockIridescence=oA;let oI=`struct subSurfaceOutParams -{vec3 specularEnvironmentReflectance; -#ifdef SS_REFRACTION -vec3 finalRefraction;vec3 surfaceAlbedo; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -float alpha; -#endif -#ifdef REFLECTION -float refractionFactorForIrradiance; -#endif -#endif -#ifdef SS_TRANSLUCENCY -vec3 transmittance;float translucencyIntensity; -#ifdef REFLECTION -vec3 refractionIrradiance; -#endif -#endif -#if DEBUGMODE>0 -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap; -#endif -#ifdef SS_REFRACTION -vec4 environmentRefraction;vec3 refractionTransmittance; -#endif -#endif -}; -#ifdef SUBSURFACE -#define pbr_inline -#define inline -void subSurfaceBlock( -in vec3 vSubSurfaceIntensity, -in vec2 vThicknessParam, -in vec4 vTintColor, -in vec3 normalW, -in vec3 specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -in vec4 thicknessMap, -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -in vec4 refractionIntensityMap, -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -in vec4 translucencyIntensityMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -in mat4 reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -in vec3 irradianceVector_, -#endif -#if defined(REALTIME_FILTERING) -in samplerCube reflectionSampler, -in vec2 vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -#ifdef REFLECTIONMAP_3D -in samplerCube irradianceSampler, -#else -in sampler2D irradianceSampler, -#endif -#endif -#endif -#endif -#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) -in vec3 surfaceAlbedo, -#endif -#ifdef SS_REFRACTION -in vec3 vPositionW, -in vec3 viewDirectionW, -in mat4 view, -in vec4 vRefractionInfos, -in mat4 refractionMatrix, -in vec4 vRefractionMicrosurfaceInfos, -in vec4 vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -in float alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -in float NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -in float roughness, -#endif -in float alphaG, -#ifdef SS_REFRACTIONMAP_3D -in samplerCube refractionSampler, -#ifndef LODBASEDMICROSFURACE -in samplerCube refractionSamplerLow, -in samplerCube refractionSamplerHigh, -#endif -#else -in sampler2D refractionSampler, -#ifndef LODBASEDMICROSFURACE -in sampler2D refractionSamplerLow, -in sampler2D refractionSamplerHigh, -#endif -#endif -#ifdef ANISOTROPIC -in anisotropicOutParams anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -in vec2 vRefractionFilteringInfo, -#endif -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -in vec3 refractionPosition, -in vec3 refractionSize, -#endif -#endif -#ifdef SS_TRANSLUCENCY -in vec3 vDiffusionDistance, -#endif -out subSurfaceOutParams outParams -) -{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; -#ifdef SS_REFRACTION -float refractionIntensity=vSubSurfaceIntensity.x; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; -#endif -#endif -#ifdef SS_TRANSLUCENCY -float translucencyIntensity=vSubSurfaceIntensity.y; -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -#if defined(SS_USE_GLTF_TEXTURES) -float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; -#else -float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; -#endif -#if DEBUGMODE>0 -outParams.thicknessMap=thicknessMap; -#endif -#ifdef SS_MASK_FROM_THICKNESS_TEXTURE -#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) -#if defined(SS_USE_GLTF_TEXTURES) -refractionIntensity*=thicknessMap.r; -#else -refractionIntensity*=thicknessMap.g; -#endif -#endif -#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) -translucencyIntensity*=thicknessMap.b; -#endif -#endif -#else -float thickness=vThicknessParam.y; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -#ifdef SS_USE_GLTF_TEXTURES -refractionIntensity*=refractionIntensityMap.r; -#else -refractionIntensity*=refractionIntensityMap.g; -#endif -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -translucencyIntensity*=translucencyIntensityMap.b; -#endif -#ifdef SS_TRANSLUCENCY -thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; -#endif -#ifdef SS_REFRACTION -vec4 environmentRefraction=vec4(0.,0.,0.,0.); -#ifdef ANISOTROPIC -vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,vRefractionInfos.y); -#else -vec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y); -#endif -#ifdef SS_REFRACTIONMAP_OPPOSITEZ -refractionVector.z*=-1.0; -#endif -#ifdef SS_REFRACTIONMAP_3D -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); -#endif -refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); -#else -#ifdef SS_USE_THICKNESS_AS_DEPTH -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); -#else -vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); -#endif -vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; -#endif -#ifdef SS_HAS_THICKNESS -float ior=vRefractionInfos.y; -#else -float ior=vRefractionMicrosurfaceInfos.w; -#endif -#ifdef SS_LODINREFRACTIONALPHA -float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); -#elif defined(SS_LINEARSPECULARREFRACTION) -float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); -#else -float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); -#endif -#ifdef LODBASEDMICROSFURACE -refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; -#ifdef SS_LODINREFRACTIONALPHA -float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); -#else -float requestedRefractionLOD=refractionLOD; -#endif -#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) -environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); -#else -environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); -#endif -#else -float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( -sampleRefraction(refractionSamplerHigh,refractionCoords), -environmentRefractionMid, -lodRefractionNormalizedDoubled -);} else {environmentRefraction=mix( -environmentRefractionMid, -sampleRefraction(refractionSamplerLow,refractionCoords), -lodRefractionNormalizedDoubled-1.0 -);} -#endif -#ifdef SS_RGBDREFRACTION -environmentRefraction.rgb=fromRGBD(environmentRefraction); -#endif -#ifdef SS_GAMMAREFRACTION -environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); -#endif -environmentRefraction.rgb*=vRefractionInfos.x; -#endif -#ifdef SS_REFRACTION -vec3 refractionTransmittance=vec3(refractionIntensity); -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); -#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) -float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; -#else -vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); -#endif -#ifdef SS_ALBEDOFORREFRACTIONTINT -environmentRefraction.rgb*=surfaceAlbedo.rgb; -#endif -outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); -#ifdef REFLECTION -outParams.refractionFactorForIrradiance=(1.-refractionIntensity); -#endif -#ifdef UNUSED_MULTIPLEBOUNCES -vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); -#endif -refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; -#if DEBUGMODE>0 -outParams.refractionTransmittance=refractionTransmittance; -#endif -outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; -#if DEBUGMODE>0 -outParams.environmentRefraction=environmentRefraction; -#endif -#endif -#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) -vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -irradianceVector.z*=-1.0; -#endif -#ifdef INVERTCUBICMAP -irradianceVector.y*=-1.0; -#endif -#else -vec3 irradianceVector=irradianceVector_; -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) -#if defined(REALTIME_FILTERING) -vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); -#else -vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); -#endif -#elif defined(USEIRRADIANCEMAP) -#ifdef REFLECTIONMAP_3D -vec3 irradianceCoords=irradianceVector; -#else -vec2 irradianceCoords=irradianceVector.xy; -#ifdef REFLECTIONMAP_PROJECTION -irradianceCoords/=irradianceVector.z; -#endif -irradianceCoords.y=1.0-irradianceCoords.y; -#endif -vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); -#ifdef RGBDREFLECTION -refractionIrradiance.rgb=fromRGBD(refractionIrradiance); -#endif -#ifdef GAMMAREFLECTION -refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); -#endif -#else -vec4 refractionIrradiance=vec4(0.); -#endif -refractionIrradiance.rgb*=transmittance; -#ifdef SS_ALBEDOFORTRANSLUCENCYTINT -refractionIrradiance.rgb*=surfaceAlbedo.rgb; -#endif -outParams.refractionIrradiance=refractionIrradiance.rgb; -#endif -} -#endif -`;s_.v.IncludesShadersStore.pbrBlockSubSurface=oI;let oM=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); -#ifdef NORMAL -vec3 normalW=normalize(vNormalW); -#else -vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; -#endif -vec3 geometricNormalW=normalW; -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; -#endif -`;s_.v.IncludesShadersStore.pbrBlockNormalGeometric=oM;let oD=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) -vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; -#if defined(TWOSIDEDLIGHTING) -faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; -#endif -normalW*=sign(dot(normalW,faceNormal)); -#endif -#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) -normalW=gl_FrontFacing ? normalW : -normalW; -#endif -`;s_.v.IncludesShadersStore.pbrBlockNormalFinal=oD;let oO=`#ifdef LIGHTMAP -vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); -#ifdef RGBDLIGHTMAP -lightmapColor.rgb=fromRGBD(lightmapColor); -#endif -#ifdef GAMMALIGHTMAP -lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); -#endif -lightmapColor.rgb*=vLightmapInfos.y; -#endif -`;s_.v.IncludesShadersStore.pbrBlockLightmapInit=oO;let oN=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); -#ifdef SPECULARAA -alphaG+=AARoughnessFactors.y; -#endif -#if defined(ENVIRONMENTBRDF) -vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -#ifdef AMBIENTINGRAYSCALE -float ambientMonochrome=aoOut.ambientOcclusionColor.r; -#else -float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); -#endif -float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); -#endif -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); -#endif -#endif -#endif -#endif -`;s_.v.IncludesShadersStore.pbrBlockGeometryInfo=oN;let oF=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; -#ifdef METALLICWORKFLOW -vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); -#else -vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); -#endif -#ifdef ALPHAFRESNEL -float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; -#endif -`;s_.v.IncludesShadersStore.pbrBlockReflectance0=oF;let oB=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); -#ifdef RADIANCEOCCLUSION -specularEnvironmentReflectance*=seo; -#endif -#ifdef HORIZONOCCLUSION -#ifdef BUMP -#ifdef REFLECTIONMAP_3D -specularEnvironmentReflectance*=eho; -#endif -#endif -#endif -#else -vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); -#endif -#ifdef CLEARCOAT -specularEnvironmentReflectance*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -specularEnvironmentReflectance*=clearcoatOut.absorption; -#endif -#endif -`;s_.v.IncludesShadersStore.pbrBlockReflectance=oB;let oL=`vec3 diffuseBase=vec3(0.,0.,0.); -#ifdef SPECULARTERM -vec3 specularBase=vec3(0.,0.,0.); -#endif -#ifdef CLEARCOAT -vec3 clearCoatBase=vec3(0.,0.,0.); -#endif -#ifdef SHEEN -vec3 sheenBase=vec3(0.,0.,0.); -#endif -preLightingInfo preInfo;lightingInfo info;float shadow=1.; -float aggShadow=0.;float numLights=0.; -#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) -vec3 absorption=vec3(0.); -#endif -`;s_.v.IncludesShadersStore.pbrBlockDirectLighting=oL;let ow=`aggShadow=aggShadow/numLights; -#if defined(ENVIRONMENTBRDF) -#ifdef MS_BRDF_ENERGY_CONSERVATION -vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); -#endif -#endif -#ifndef METALLICWORKFLOW -#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION -surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; -#endif -#endif -#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) -surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; -#endif -#ifdef REFLECTION -vec3 finalIrradiance=reflectionOut.environmentIrradiance; -#if defined(CLEARCOAT) -finalIrradiance*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -finalIrradiance*=clearcoatOut.absorption; -#endif -#endif -#if defined(SS_REFRACTION) -finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; -#endif -#if defined(SS_TRANSLUCENCY) -finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; -#endif -finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; -#endif -#ifdef SPECULARTERM -vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalSpecularScaled*=energyConservationFactor; -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -finalSpecularScaled*=sheenOut.sheenAlbedoScaling; -#endif -#endif -#ifdef REFLECTION -vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalRadianceScaled*=energyConservationFactor; -#endif -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) -finalRadianceScaled*=sheenOut.sheenAlbedoScaling; -#endif -#endif -#ifdef SHEEN -vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; -#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) -sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; -#if defined(CLEARCOAT_TINT) -sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; -#endif -#endif -#endif -#ifdef CLEARCOAT -vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; -#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) -finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; -#endif -#ifdef SS_REFRACTION -subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; -#ifdef CLEARCOAT_TINT -subSurfaceOut.finalRefraction*=clearcoatOut.absorption; -#endif -#endif -#endif -#ifdef ALPHABLEND -float luminanceOverAlpha=0.0; -#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) -luminanceOverAlpha+=getLuminance(finalRadianceScaled); -#if defined(CLEARCOAT) -luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); -#endif -#endif -#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) -luminanceOverAlpha+=getLuminance(finalSpecularScaled); -#endif -#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) -luminanceOverAlpha+=getLuminance(finalClearCoatScaled); -#endif -#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) -alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); -#endif -#endif -`;s_.v.IncludesShadersStore.pbrBlockFinalLitComponents=ow;let oU=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; -#ifdef EMISSIVE -vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; -#ifdef GAMMAEMISSIVE -finalEmissive*=toLinearSpace(emissiveColorTex.rgb); -#else -finalEmissive*=emissiveColorTex.rgb; -#endif -finalEmissive*= vEmissiveInfos.y; -#endif -finalEmissive*=vLightingIntensity.y; -#ifdef AMBIENT -vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); -#else -vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; -#endif -finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; -`;s_.v.IncludesShadersStore.pbrBlockFinalUnlitComponents=oU;let oV=`vec4 finalColor=vec4( -#ifndef UNLIT -#ifdef REFLECTION -finalIrradiance + -#endif -#ifdef SPECULARTERM -finalSpecularScaled + -#endif -#ifdef SHEEN -finalSheenScaled + -#endif -#ifdef CLEARCOAT -finalClearCoatScaled + -#endif -#ifdef REFLECTION -finalRadianceScaled + -#if defined(SHEEN) && defined(ENVIRONMENTBRDF) -sheenOut.finalSheenRadianceScaled + -#endif -#ifdef CLEARCOAT -clearcoatOut.finalClearCoatRadianceScaled + -#endif -#endif -#ifdef SS_REFRACTION -subSurfaceOut.finalRefraction + -#endif -#endif -finalAmbient + -finalDiffuse, -alpha); -#ifdef LIGHTMAP -#ifndef LIGHTMAPEXCLUDED -#ifdef USELIGHTMAPASSHADOWMAP -finalColor.rgb*=lightmapColor.rgb; -#else -finalColor.rgb+=lightmapColor.rgb; -#endif -#endif -#endif -finalColor.rgb+=finalEmissive; -#define CUSTOM_FRAGMENT_BEFORE_FOG -finalColor=max(finalColor,0.0); -`;s_.v.IncludesShadersStore.pbrBlockFinalColorComposition=oV;let ok=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) -#if !defined(SKIPFINALCOLORCLAMP) -finalColor.rgb=clamp(finalColor.rgb,0.,30.0); -#endif -#else -finalColor=applyImageProcessing(finalColor); -#endif -finalColor.a*=visibility; -#ifdef PREMULTIPLYALPHA -finalColor.rgb*=finalColor.a; -#endif -`;s_.v.IncludesShadersStore.pbrBlockImageProcessing=ok;let oG=`#if DEBUGMODE>0 -if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { -#if DEBUGMODE==1 -gl_FragColor.rgb=vPositionW.rgb; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==2 && defined(NORMAL) -gl_FragColor.rgb=vNormalW.rgb; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) -gl_FragColor.rgb=TBN[0]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) -gl_FragColor.rgb=TBN[1]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==5 -gl_FragColor.rgb=normalW; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==6 && defined(MAINUV1) -gl_FragColor.rgb=vec3(vMainUV1,0.0); -#elif DEBUGMODE==7 && defined(MAINUV2) -gl_FragColor.rgb=vec3(vMainUV2,0.0); -#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) -gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) -gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==10 && defined(CLEARCOAT) -gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==11 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicNormal; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==12 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicTangent; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==13 && defined(ANISOTROPIC) -gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; -#define DEBUGMODE_NORMALIZE -#elif DEBUGMODE==20 && defined(ALBEDO) -gl_FragColor.rgb=albedoTexture.rgb; -#ifndef GAMMAALBEDO -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==21 && defined(AMBIENT) -gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; -#elif DEBUGMODE==22 && defined(OPACITY) -gl_FragColor.rgb=opacityMap.rgb; -#elif DEBUGMODE==23 && defined(EMISSIVE) -gl_FragColor.rgb=emissiveColorTex.rgb; -#ifndef GAMMAEMISSIVE -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==24 && defined(LIGHTMAP) -gl_FragColor.rgb=lightmapColor.rgb; -#ifndef GAMMALIGHTMAP -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; -#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); -#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; -#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) -gl_FragColor.rgb=sheenOut.sheenMapData.rgb; -#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) -gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; -#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) -gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; -#elif DEBUGMODE==32 && defined(BUMP) -gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; -#elif DEBUGMODE==40 && defined(SS_REFRACTION) -gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==41 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; -#ifndef GAMMAREFLECTION -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) -gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==50 -gl_FragColor.rgb=diffuseBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==51 && defined(SPECULARTERM) -gl_FragColor.rgb=specularBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==52 && defined(CLEARCOAT) -gl_FragColor.rgb=clearCoatBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==53 && defined(SHEEN) -gl_FragColor.rgb=sheenBase.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==54 && defined(REFLECTION) -gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; -#ifndef GAMMAREFLECTION -#define DEBUGMODE_GAMMA -#endif -#elif DEBUGMODE==60 -gl_FragColor.rgb=surfaceAlbedo.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==61 -gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) -gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); -#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) -gl_FragColor.rgb=reflectivityOut.metallicF0; -#elif DEBUGMODE==63 -gl_FragColor.rgb=vec3(roughness); -#elif DEBUGMODE==64 -gl_FragColor.rgb=vec3(alphaG); -#elif DEBUGMODE==65 -gl_FragColor.rgb=vec3(NdotV); -#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) -gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==67 && defined(CLEARCOAT) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); -#elif DEBUGMODE==68 && defined(CLEARCOAT) -gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); -#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) -gl_FragColor.rgb=subSurfaceOut.transmittance; -#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) -gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; -#elif DEBUGMODE==72 -gl_FragColor.rgb=vec3(microSurface); -#elif DEBUGMODE==73 -gl_FragColor.rgb=vAlbedoColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) -gl_FragColor.rgb=vReflectivityColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==75 -gl_FragColor.rgb=vEmissiveColor.rgb; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) -gl_FragColor.rgb=vec3(seo); -#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) -gl_FragColor.rgb=vec3(eho); -#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) -gl_FragColor.rgb=vec3(energyConservationFactor); -#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -gl_FragColor.rgb=specularEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) -gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; -#define DEBUGMODE_GAMMA -#elif DEBUGMODE==86 && defined(ALPHABLEND) -gl_FragColor.rgb=vec3(luminanceOverAlpha); -#elif DEBUGMODE==87 -gl_FragColor.rgb=vec3(alpha); -#elif DEBUGMODE==88 && defined(ALBEDO) -gl_FragColor.rgb=vec3(albedoTexture.a); -#else -float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); -#endif -gl_FragColor.rgb*=vDebugMode.y; -#ifdef DEBUGMODE_NORMALIZE -gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; -#endif -#ifdef DEBUGMODE_GAMMA -gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); -#endif -gl_FragColor.a=1.0; -#ifdef PREPASS -gl_FragData[0]=toLinearSpace(gl_FragColor); -gl_FragData[1]=vec4(0.,0.,0.,0.); -#endif -#ifdef DEBUGMODE_FORCERETURN -return; -#endif -} -#endif -`;s_.v.IncludesShadersStore.pbrDebug=oG;let oz=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) -#extension GL_OES_standard_derivatives : enable -#endif -#ifdef LODBASEDMICROSFURACE -#extension GL_EXT_shader_texture_lod : enable -#endif -#define CUSTOM_FRAGMENT_BEGIN -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -#include[SCENE_MRT_COUNT] -precision highp float; -#include -#ifndef FROMLINEARSPACE -#define FROMLINEARSPACE -#endif -#include<__decl__pbrFragment> -#include -#include<__decl__lightFragment>[0..maxSimultaneousLights] -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef REFLECTION -#include -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -#include -#include -#include -albedoOpacityOutParams albedoOpacityOut; -#ifdef ALBEDO -vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); -#endif -#ifdef DECAL -vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); -#endif -albedoOpacityBlock( -vAlbedoColor, -#ifdef ALBEDO -albedoTexture, -vAlbedoInfos, -#endif -#ifdef OPACITY -opacityMap, -vOpacityInfos, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -#ifdef DECAL -decalColor, -vDecalInfos, -#endif -albedoOpacityOut -);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; -#define CUSTOM_FRAGMENT_UPDATE_ALPHA -#include -#define CUSTOM_FRAGMENT_BEFORE_LIGHTS -ambientOcclusionOutParams aoOut; -#ifdef AMBIENT -vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; -#endif -ambientOcclusionBlock( -#ifdef AMBIENT -ambientOcclusionColorMap, -vAmbientInfos, -#endif -aoOut -); -#include -#ifdef UNLIT -vec3 diffuseBase=vec3(1.,1.,1.); -#else -vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; -#if defined(REFLECTIVITY) -vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; -#ifndef METALLICWORKFLOW -#ifdef REFLECTIVITY_GAMMA -surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); -#endif -surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; -#endif -#endif -#if defined(MICROSURFACEMAP) -vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; -#endif -#ifdef METALLICWORKFLOW -vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; -#ifdef REFLECTANCE -vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); -#ifdef REFLECTANCE_GAMMA -reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); -#endif -metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; -#endif -#ifdef METALLIC_REFLECTANCE -vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); -#ifdef METALLIC_REFLECTANCE_GAMMA -metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); -#endif -#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY -metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; -#endif -metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; -#endif -#endif -reflectivityBlock( -vReflectivityColor, -#ifdef METALLICWORKFLOW -surfaceAlbedo, -metallicReflectanceFactors, -#endif -#ifdef REFLECTIVITY -vReflectivityInfos, -surfaceMetallicOrReflectivityColorMap, -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor, -#endif -#ifdef MICROSURFACEMAP -microSurfaceTexel, -#endif -#ifdef DETAIL -detailColor, -vDetailInfos, -#endif -reflectivityOut -);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; -#ifdef METALLICWORKFLOW -surfaceAlbedo=reflectivityOut.surfaceAlbedo; -#endif -#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) -aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; -#endif -#ifdef ALPHAFRESNEL -#if defined(ALPHATEST) || defined(ALPHABLEND) -alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( -normalW, -viewDirectionW, -alpha, -microSurface, -alphaFresnelOut -);alpha=alphaFresnelOut.alpha; -#endif -#endif -#include -#ifdef ANISOTROPIC -anisotropicOutParams anisotropicOut; -#ifdef ANISOTROPIC_TEXTURE -vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; -#endif -anisotropicBlock( -vAnisotropy, -roughness, -#ifdef ANISOTROPIC_TEXTURE -anisotropyMapData, -#endif -TBN, -normalW, -viewDirectionW, -anisotropicOut -); -#endif -#ifdef REFLECTION -reflectionOutParams reflectionOut; -#ifndef USE_CUSTOM_REFLECTION -reflectionBlock( -vPositionW, -normalW, -alphaG, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) -NdotVUnclamped, -#endif -#ifdef LINEARSPECULARREFLECTION -roughness, -#endif -reflectionSampler, -#if defined(NORMAL) && defined(USESPHERICALINVERTEX) -vEnvironmentIrradiance, -#endif -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -reflectionMatrix, -#endif -#endif -#ifdef USEIRRADIANCEMAP -irradianceSampler, -#endif -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -reflectionOut -); -#else -#define CUSTOM_REFLECTION -#endif -#endif -#include -#ifdef SHEEN -sheenOutParams sheenOut; -#ifdef SHEEN_TEXTURE -vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); -#endif -#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; -#endif -sheenBlock( -vSheenColor, -#ifdef SHEEN_ROUGHNESS -vSheenRoughness, -#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) -sheenMapRoughnessData, -#endif -#endif -roughness, -#ifdef SHEEN_TEXTURE -sheenMapData, -vSheenInfos.y, -#endif -reflectance, -#ifdef SHEEN_LINKWITHALBEDO -baseColor, -surfaceAlbedo, -#endif -#ifdef ENVIRONMENTBRDF -NdotV, -environmentBrdf, -#endif -#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) -AARoughnessFactors, -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -vLightingIntensity, -reflectionSampler, -reflectionOut.reflectionCoords, -NdotVUnclamped, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) -seo, -#endif -#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) -eho, -#endif -#endif -sheenOut -); -#ifdef SHEEN_LINKWITHALBEDO -surfaceAlbedo=sheenOut.surfaceAlbedo; -#endif -#endif -#ifdef CLEARCOAT -#ifdef CLEARCOAT_TEXTURE -vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; -#endif -#endif -#ifdef IRIDESCENCE -iridescenceOutParams iridescenceOut; -#ifdef IRIDESCENCE_TEXTURE -vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; -#endif -iridescenceBlock( -vIridescenceParams, -NdotV, -specularEnvironmentR0, -#ifdef IRIDESCENCE_TEXTURE -iridescenceMapData, -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -iridescenceThicknessMapData, -#endif -#ifdef CLEARCOAT -NdotVUnclamped, -#ifdef CLEARCOAT_TEXTURE -clearCoatMapData, -#endif -#endif -iridescenceOut -);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; -#endif -clearcoatOutParams clearcoatOut; -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; -#endif -#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) -vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); -#endif -#ifdef CLEARCOAT_BUMP -vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); -#endif -clearcoatBlock( -vPositionW, -geometricNormalW, -viewDirectionW, -vClearCoatParams, -#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) -clearCoatMapRoughnessData, -#endif -specularEnvironmentR0, -#ifdef CLEARCOAT_TEXTURE -clearCoatMapData, -#endif -#ifdef CLEARCOAT_TINT -vClearCoatTintParams, -clearCoatColorAtDistance, -vClearCoatRefractionParams, -#ifdef CLEARCOAT_TINT_TEXTURE -clearCoatTintMapData, -#endif -#endif -#ifdef CLEARCOAT_BUMP -vClearCoatBumpInfos, -clearCoatBumpMapData, -vClearCoatBumpUV, -#if defined(TANGENT) && defined(NORMAL) -vTBN, -#else -vClearCoatTangentSpaceParams, -#endif -#ifdef OBJECTSPACE_NORMALMAP -normalMatrix, -#endif -#endif -#if defined(FORCENORMALFORWARD) && defined(NORMAL) -faceNormal, -#endif -#ifdef REFLECTION -vReflectionMicrosurfaceInfos, -vReflectionInfos, -vReflectionColor, -vLightingIntensity, -reflectionSampler, -#ifndef LODBASEDMICROSFURACE -reflectionSamplerLow, -reflectionSamplerHigh, -#endif -#ifdef REALTIME_FILTERING -vReflectionFilteringInfo, -#endif -#endif -#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) -#ifdef RADIANCEOCCLUSION -ambientMonochrome, -#endif -#endif -#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) -(gl_FrontFacing ? 1. : -1.), -#endif -clearcoatOut -); -#else -clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; -#endif -#include -subSurfaceOutParams subSurfaceOut; -#ifdef SUBSURFACE -#ifdef SS_THICKNESSANDMASK_TEXTURE -vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); -#endif -subSurfaceBlock( -vSubSurfaceIntensity, -vThicknessParam, -vTintColor, -normalW, -specularEnvironmentReflectance, -#ifdef SS_THICKNESSANDMASK_TEXTURE -thicknessMap, -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -refractionIntensityMap, -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -translucencyIntensityMap, -#endif -#ifdef REFLECTION -#ifdef SS_TRANSLUCENCY -reflectionMatrix, -#ifdef USESPHERICALFROMREFLECTIONMAP -#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) -reflectionOut.irradianceVector, -#endif -#if defined(REALTIME_FILTERING) -reflectionSampler, -vReflectionFilteringInfo, -#endif -#endif -#ifdef USEIRRADIANCEMAP -irradianceSampler, -#endif -#endif -#endif -#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) -surfaceAlbedo, -#endif -#ifdef SS_REFRACTION -vPositionW, -viewDirectionW, -view, -vRefractionInfos, -refractionMatrix, -vRefractionMicrosurfaceInfos, -vLightingIntensity, -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha, -#endif -#ifdef SS_LODINREFRACTIONALPHA -NdotVUnclamped, -#endif -#ifdef SS_LINEARSPECULARREFRACTION -roughness, -#endif -alphaG, -refractionSampler, -#ifndef LODBASEDMICROSFURACE -refractionSamplerLow, -refractionSamplerHigh, -#endif -#ifdef ANISOTROPIC -anisotropicOut, -#endif -#ifdef REALTIME_FILTERING -vRefractionFilteringInfo, -#endif -#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC -vRefractionPosition, -vRefractionSize, -#endif -#endif -#ifdef SS_TRANSLUCENCY -vDiffusionDistance, -#endif -subSurfaceOut -); -#ifdef SS_REFRACTION -surfaceAlbedo=subSurfaceOut.surfaceAlbedo; -#ifdef SS_LINKREFRACTIONTOTRANSPARENCY -alpha=subSurfaceOut.alpha; -#endif -#endif -#else -subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; -#endif -#include -#include[0..maxSimultaneousLights] -#include -#endif -#include -#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION -#include -#include -#include(color,finalColor) -#include -#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR -#ifdef PREPASS -float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; -#ifdef PREPASS_POSITION -gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); -#endif -#ifdef PREPASS_VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_ALBEDO_SQRT -vec3 sqAlbedo=sqrt(surfaceAlbedo); -#endif -#ifdef PREPASS_IRRADIANCE -vec3 irradiance=finalDiffuse; -#ifndef UNLIT -#ifdef REFLECTION -irradiance+=finalIrradiance; -#endif -#endif -#ifdef SS_SCATTERING -gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); -irradiance/=sqAlbedo; -#else -gl_FragData[0]=finalColor; -float scatteringDiffusionProfile=255.; -#endif -gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); -#else -gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); -#endif -#ifdef PREPASS_DEPTH -gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); -#endif -#ifdef PREPASS_NORMAL -#ifdef PREPASS_NORMAL_WORLDSPACE -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); -#else -gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); -#endif -#endif -#ifdef PREPASS_ALBEDO_SQRT -gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); -#endif -#ifdef PREPASS_REFLECTIVITY -#ifndef UNLIT -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; -#else -gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; -#endif -#endif -#endif -#if !defined(PREPASS) || defined(WEBGL2) -gl_FragColor=finalColor; -#endif -#include -#if ORDER_INDEPENDENT_TRANSPARENCY -if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} -#endif -#include -#define CUSTOM_FRAGMENT_MAIN_END -} -`;s_.v.ShadersStore.pbrPixelShader=oz;let oW=`uniform mat4 view;uniform mat4 viewProjection; -#ifdef ALBEDO -uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; -#endif -#ifdef AMBIENT -uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; -#endif -#ifdef OPACITY -uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; -#endif -#ifdef EMISSIVE -uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; -#endif -#ifdef LIGHTMAP -uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; -#endif -#ifdef REFLECTIVITY -uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; -#endif -#ifdef METALLIC_REFLECTANCE -uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; -#endif -#ifdef REFLECTANCE -uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; -#endif -#ifdef MICROSURFACEMAP -uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; -#endif -#ifdef POINTSIZE -uniform float pointSize; -#endif -#ifdef REFLECTION -uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; -#endif -#ifdef CLEARCOAT -#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) -uniform vec4 vClearCoatInfos; -#endif -#ifdef CLEARCOAT_TEXTURE -uniform mat4 clearCoatMatrix; -#endif -#ifdef CLEARCOAT_TEXTURE_ROUGHNESS -uniform mat4 clearCoatRoughnessMatrix; -#endif -#ifdef CLEARCOAT_BUMP -uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; -#endif -#ifdef CLEARCOAT_TINT_TEXTURE -uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; -#endif -#endif -#ifdef IRIDESCENCE -#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) -uniform vec4 vIridescenceInfos; -#endif -#ifdef IRIDESCENCE_TEXTURE -uniform mat4 iridescenceMatrix; -#endif -#ifdef IRIDESCENCE_THICKNESS_TEXTURE -uniform mat4 iridescenceThicknessMatrix; -#endif -#endif -#ifdef ANISOTROPIC -#ifdef ANISOTROPIC_TEXTURE -uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; -#endif -#endif -#ifdef SHEEN -#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) -uniform vec4 vSheenInfos; -#endif -#ifdef SHEEN_TEXTURE -uniform mat4 sheenMatrix; -#endif -#ifdef SHEEN_TEXTURE_ROUGHNESS -uniform mat4 sheenRoughnessMatrix; -#endif -#endif -#ifdef SUBSURFACE -#ifdef SS_REFRACTION -uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; -#endif -#ifdef SS_THICKNESSANDMASK_TEXTURE -uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; -#endif -#ifdef SS_REFRACTIONINTENSITY_TEXTURE -uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; -#endif -#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE -uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; -#endif -#endif -#ifdef NORMAL -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -#ifdef USESPHERICALFROMREFLECTIONMAP -#ifdef SPHERICAL_HARMONICS -uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; -#else -uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; -#endif -#endif -#endif -#endif -#ifdef DETAIL -uniform vec4 vDetailInfos;uniform mat4 detailMatrix; -#endif -#include -#define ADDITIONAL_VERTEX_DECLARATION -`;s_.v.IncludesShadersStore.pbrVertexDeclaration=oW;let oH=`precision highp float; -#include<__decl__pbrVertex> -#define CUSTOM_VERTEX_BEGIN -attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#ifdef TANGENT -attribute vec4 tangent; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#include[2..7] -#include[1..7] -#ifdef VERTEXCOLOR -attribute vec4 color; -#endif -#include -#include -#include -#include -#include -#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) -#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) -#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) -#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) -#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) -#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) -#ifdef CLEARCOAT -#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) -#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) -#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) -#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) -#endif -#ifdef IRIDESCENCE -#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) -#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) -#endif -#ifdef SHEEN -#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) -#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) -#endif -#ifdef ANISOTROPIC -#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) -#endif -#ifdef SUBSURFACE -#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) -#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) -#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) -#endif -varying vec3 vPositionW; -#if DEBUGMODE>0 -varying vec4 vClipSpacePosition; -#endif -#ifdef NORMAL -varying vec3 vNormalW; -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -varying vec3 vEnvironmentIrradiance; -#include -#endif -#endif -#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) -varying vec4 vColor; -#endif -#include -#include -#include -#include<__decl__lightVxFragment>[0..maxSimultaneousLights] -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -varying vec3 vPositionUVW; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -varying vec3 vDirectionW; -#endif -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#ifdef TANGENT -vec4 tangentUpdated=tangent; -#endif -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef REFLECTIONMAP_SKYBOX -vPositionUVW=positionUpdated; -#endif -#define CUSTOM_VERTEX_UPDATE_POSITION -#define CUSTOM_VERTEX_UPDATE_NORMAL -#include -#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); -#include -#ifdef NORMAL -mat3 normalWorld=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normalWorld=transposeMat3(inverseMat3(normalWorld)); -#endif -vNormalW=normalize(normalWorld*normalUpdated); -#endif -#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) -vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; -#ifdef REFLECTIONMAP_OPPOSITEZ -reflectionVector.z*=-1.0; -#endif -vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); -#endif -#endif -#define CUSTOM_VERTEX_UPDATE_WORLDPOS -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#if DEBUGMODE>0 -vClipSpacePosition=gl_Position; -#endif -#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) -vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); -#endif -#ifndef UV1 -vec2 uvUpdated=vec2(0.,0.); -#endif -#ifdef MAINUV1 -vMainUV1=uvUpdated; -#endif -#include[2..7] -#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) -#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) -#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) -#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) -#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) -#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) -#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) -#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) -#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) -#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) -#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) -#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) -#ifdef CLEARCOAT -#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) -#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) -#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) -#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) -#endif -#ifdef IRIDESCENCE -#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) -#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) -#endif -#ifdef SHEEN -#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) -#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) -#endif -#ifdef ANISOTROPIC -#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) -#endif -#ifdef SUBSURFACE -#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) -#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) -#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) -#endif -#include -#include -#include -#include[0..maxSimultaneousLights] -#include -#if defined(POINTSIZE) && !defined(WEBGPU) -gl_PointSize=pointSize; -#endif -#include -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.pbrVertexShader=oH;let MaterialClearCoatDefines=class MaterialClearCoatDefines extends sn.H{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_TEXTURE_ROUGHNESS_IDENTICAL=!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}};let pbrClearCoatConfiguration_PBRClearCoatConfiguration=class pbrClearCoatConfiguration_PBRClearCoatConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new MaterialClearCoatDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this.indexOfRefraction=pbrClearCoatConfiguration_PBRClearCoatConfiguration._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=rg.Wo.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.ClearCoatTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!MaterialFlags.ClearCoatTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())&&(!i.getCaps().standardDerivatives||!this._bumpTexture||!MaterialFlags.ClearCoatBumpTextureEnabled||!!r||!!this._bumpTexture.isReady())&&(!this._isTintEnabled||!this._tintTexture||!MaterialFlags.ClearCoatTintTextureEnabled||!!this._tintTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.ClearCoatTextureEnabled?so.G.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&MaterialFlags.ClearCoatTextureEnabled?so.G.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&MaterialFlags.ClearCoatBumpTextureEnabled?so.G.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled?(so.G.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!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,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=this._material._disableBumpMap,f=this._material._invertNormalMapX,m=this._material._invertNormalMapY,g=d.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!p||!e.isSync){g&&MaterialFlags.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),so.G.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&MaterialFlags.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&so.G.BindTextureMatrix(this._texture,e,"clearCoat"),!this._textureRoughness||g||d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE||so.G.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&MaterialFlags.ClearCoatTextureEnabled&&!_&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),so.G.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",f?1:-1,m?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",f?-1:1,m?-1:1)),this._tintTexture&&MaterialFlags.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),so.G.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let r=1-this._indexOfRefraction,p=1+this._indexOfRefraction,v=Math.pow(-r/p,2),x=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",v,x,r,p),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&&MaterialFlags.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!g&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&MaterialFlags.ClearCoatBumpTextureEnabled&&!_&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&MaterialFlags.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){var t,i,r,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(r=this._bumpTexture)||void 0===r||r.dispose(),null===(s=this._tintTexture)||void 0===s||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}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"}]}}};pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction=1.5,(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.qC)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"indexOfRefraction",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"useRoughnessFromMainTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"textureRoughness",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"remapF0OnInterfaceChange",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"bumpTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"isTintEnabled",void 0),(0,rH.gn)([(0,rb.n9)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintColor",void 0),(0,rH.gn)([(0,rb.qC)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintColorAtDistance",void 0),(0,rH.gn)([(0,rb.qC)()],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintThickness",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrClearCoatConfiguration_PBRClearCoatConfiguration.prototype,"tintTexture",void 0);let MaterialIridescenceDefines=class MaterialIridescenceDefines extends sn.H{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}};let pbrIridescenceConfiguration_PBRIridescenceConfiguration=class pbrIridescenceConfiguration_PBRIridescenceConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new MaterialIridescenceDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness,this.maximumThickness=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness,this.indexOfRefraction=pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.IridescenceTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._thicknessTexture||!MaterialFlags.IridescenceTextureEnabled||!!this._thicknessTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=null!==this._texture&&this._texture._texture===(null===(i=this._thicknessTexture)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.IridescenceTextureEnabled?so.G.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&MaterialFlags.IridescenceTextureEnabled?so.G.PrepareDefinesForMergedUV(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_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&p&&e.isSync||(_&&MaterialFlags.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),so.G.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&MaterialFlags.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._thicknessTexture)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&so.G.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||_||d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||so.G.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&MaterialFlags.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&MaterialFlags.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}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"}]}}};pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMinimumThickness=100,pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness=400,pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction=1.3,(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.qC)()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"minimumThickness",void 0),(0,rH.gn)([(0,rb.qC)()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"maximumThickness",void 0),(0,rH.gn)([(0,rb.qC)()],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"indexOfRefraction",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrIridescenceConfiguration_PBRIridescenceConfiguration.prototype,"thicknessTexture",void 0);let MaterialAnisotropicDefines=class MaterialAnisotropicDefines extends sn.H{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}};let pbrAnisotropicConfiguration_PBRAnisotropicConfiguration=class pbrAnisotropicConfiguration_PBRAnisotropicConfiguration extends MaterialPluginBase{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()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new MaterialAnisotropicDefines,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new rm.FM(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||!this._texture||!MaterialFlags.AnisotropicTextureEnabled||!!this._texture.isReadyOrNotBlocking()}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(rz.o.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.AnisotropicTextureEnabled?so.G.PrepareDefinesForMergedUV(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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&MaterialFlags.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),so.G.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&MaterialFlags.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,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}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,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}};(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.QC)()],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"direction",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrAnisotropicConfiguration_PBRAnisotropicConfiguration.prototype,"legacy",void 0);let MaterialSheenDefines=class MaterialSheenDefines extends sn.H{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,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}};let pbrSheenConfiguration_PBRSheenConfiguration=class pbrSheenConfiguration_PBRSheenConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new MaterialSheenDefines,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=rg.Wo.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[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!MaterialFlags.SheenTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!MaterialFlags.SheenTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;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.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&MaterialFlags.SheenTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&MaterialFlags.SheenTextureEnabled?so.G.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&p&&e.isSync||(_&&MaterialFlags.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),so.G.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&MaterialFlags.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&so.G.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||_||d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||so.G.BindTextureMatrix(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&&MaterialFlags.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&MaterialFlags.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}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"}]}}};(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"linkSheenWithAlbedo",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.n9)()],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"color",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"texture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"useRoughnessFromMainTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"textureRoughness",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSheenConfiguration_PBRSheenConfiguration.prototype,"albedoScaling",void 0);let MaterialSubSurfaceDefines=class MaterialSubSurfaceDefines extends sn.H{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_SCATTERING=!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_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_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}};let pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration=class pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration extends MaterialPluginBase{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){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new MaterialSubSurfaceDefines,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!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=rg.Wo.White(),this.tintColorAtDistance=1,this.diffusionDistance=rg.Wo.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;let e=this._getRefractionTexture(t);if(e&&MaterialFlags.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){e.SUBSURFACE=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1;return}if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!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;let i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,r=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(r||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&so.G.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&!s&&so.G.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&!s&&so.G.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){let i=this._getRefractionTexture(t);i&&MaterialFlags.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;r.getRenderingMesh().getWorldMatrix().decompose(rm.jp.Vector3[0]);let s=Math.max(Math.abs(rm.jp.Vector3[0].x),Math.abs(rm.jp.Vector3[0].y),Math.abs(rm.jp.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,n=this._material.isFrozen,a=this._material.realTimeFiltering,o=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),so.G.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),so.G.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),so.G.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&MaterialFlags.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;!l.isCube&&l.depth&&(t=l.depth);let i=l.getSize().width,r=this.volumeIndexOfRefraction;e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",i,rE.R.Log2(i)),l.boundingBoxSize&&(e.updateVector3("vRefractionPosition",l.boundingBoxPosition),e.updateVector3("vRefractionSize",l.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.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0)}t.texturesEnabled&&(this._thicknessTexture&&MaterialFlags.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&MaterialFlags.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&MaterialFlags.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&MaterialFlags.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){MaterialFlags.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!MaterialFlags.RefractionTextureEnabled&&!!this._refractionTexture&&!!this._refractionTexture.isRenderTarget}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}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)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")}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"}]}}};(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isRefractionEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isTranslucencyEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markScenePrePassDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"isScatteringEnabled",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionIntensity",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"translucencyIntensity",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useAlbedoToTintRefraction",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useAlbedoToTintTranslucency",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"thicknessTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"indexOfRefraction",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"_volumeIndexOfRefraction",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"volumeIndexOfRefraction",null),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"invertRefractionY",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"linkRefractionWithTransparency",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"minimumThickness",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"maximumThickness",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useThicknessAsDepth",void 0),(0,rH.gn)([(0,rb.n9)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"tintColor",void 0),(0,rH.gn)([(0,rb.qC)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"tintColorAtDistance",void 0),(0,rH.gn)([(0,rb.n9)()],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"diffusionDistance",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useMaskFromThicknessTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"refractionIntensityTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"translucencyIntensityTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration.prototype,"useGltfStyleTextures",void 0);let oX={effect:null,subMesh:null};let PBRMaterialDefines=class PBRMaterialDefines extends sn.H{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_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_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=!1,this.TONEMAPPING_ACES=!1,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}};let pbrBaseMaterial_PBRBaseMaterial=class pbrBaseMaterial_PBRBaseMaterial extends PushMaterial{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new rm.Lt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=pbrBaseMaterial_PBRBaseMaterial.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=rg.Wo.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new rg.Wo(0,0,0),this._albedoColor=new rg.Wo(1,1,1),this._reflectivityColor=new rg.Wo(1,1,1),this._reflectionColor=new rg.Wo(1,1,1),this._emissiveColor=new rg.Wo(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=pbrBaseMaterial_PBRBaseMaterial.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=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new sp.t(16),this._globalAmbientColor=new rg.Wo(0,0,0),this._useLogarithmicDepth=!1,this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new pbrBRDFConfiguration_PBRBRDFConfiguration(this),this.clearCoat=new pbrClearCoatConfiguration_PBRClearCoatConfiguration(this),this.iridescence=new pbrIridescenceConfiguration_PBRIridescenceConfiguration(this),this.anisotropy=new pbrAnisotropicConfiguration_PBRAnisotropicConfiguration(this),this.sheen=new pbrSheenConfiguration_PBRSheenConfiguration(this),this.subSurface=new pbrSubSurfaceConfiguration_PBRSubSurfaceConfiguration(this),this.detailMap=new material_detailMapConfiguration_DetailMapConfiguration(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),MaterialFlags.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this.getScene()),this.prePassConfiguration=new PrePassConfiguration}get hasRenderTargetTextures(){return!!MaterialFlags.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}get _disableAlphaBlending(){var e;return this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE||this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){var e;return!!this._forceAlphaTest||(null===(e=this.subSurface)||void 0===e||!e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var r;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(sG.S.GetDefineNames,this._eventInfo),t.materialDefines=new PBRMaterialDefines(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=this.getScene(),a=n.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let e=this._getReflectionTexture();if(e&&MaterialFlags.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(r=e.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(MaterialFlags.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()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(a.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;a.getCaps().standardDerivatives||e.isVerticesDataPresent(rz.o.NormalKind)||(e.createNormals(!0),rT.Y.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));let o=t.effect,l=s._areLightsDisposed,h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(h){if(this._onEffectCreatedObservable&&(oX.effect=h,oX.subMesh=t,this._onEffectCreatedObservable.notifyObservers(oX)),this.allowShaderHotSwapping&&o&&!h.isReady()){if(h=o,s.markAsUnprocessed(),u=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,s,this._materialContext)}return!!(t.effect&&t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!u,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return null!=this._metallic||null!=this._roughness||!!this._metallicTexture}_prepareEffect(e,t,i=null,r=null,s=null,n=null,a){if(this._prepareDefines(e,t,s,n,a),!t.isDirty)return null;t.markAsProcessed();let o=this.getScene(),l=o.getEngine(),h=new EffectFallbacks,u=0;t.USESPHERICALINVERTEX&&h.addFallback(u++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(u,"FOG"),t.SPECULARAA&&h.addFallback(u,"SPECULARAA"),t.POINTSIZE&&h.addFallback(u,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(u,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(u,"PARALLAX"),t.PARALLAX_RHS&&h.addFallback(u,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&h.addFallback(u++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(u++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(u++,"TANGENT"),t.BUMP&&h.addFallback(u++,"BUMP"),u=so.G.HandleFallbacksForShadows(t,h,this._maxSimultaneousLights,u++),t.SPECULARTERM&&h.addFallback(u++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(u++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(u++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(u++,"LIGHTMAP"),t.NORMAL&&h.addFallback(u++,"NORMAL"),t.AMBIENT&&h.addFallback(u++,"AMBIENT"),t.EMISSIVE&&h.addFallback(u++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(u++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(u++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");let c=[rz.o.PositionKind];t.NORMAL&&c.push(rz.o.NormalKind),t.TANGENT&&c.push(rz.o.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(rz.o.ColorKind),t.INSTANCESCOLOR&&c.push(rz.o.ColorInstanceKind),so.G.PrepareAttributesForBones(c,e,t,h),so.G.PrepareAttributesForInstances(c,t),so.G.PrepareAttributesForMorphTargets(c,e,t),so.G.PrepareAttributesForBakedVertexAnimation(c,e,t);let d="pbr",p=["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"],m={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=u,this._eventInfo.defines=t,this._eventInfo.uniforms=p,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=m,this._callbackPluginEventGeneric(sG.S.PrepareEffect,this._eventInfo),PrePassConfiguration.AddUniforms(p),PrePassConfiguration.AddSamplers(_),(0,nX.qx)(p),sv.$&&(sv.$.PrepareUniforms(p,t),sv.$.PrepareSamplers(_,t)),so.G.PrepareUniformsAndSamplersList({uniformsNames:p,uniformBuffersNames:f,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});let g={};this.customShaderNameResolve&&(d=this.customShaderNameResolve(d,p,f,_,t,c,g));let v=t.toString(),x=l.createEffect(d,{attributes:c,uniformsNames:p,uniformBuffersNames:f,samplers:_,defines:v,fallbacks:h,onCompiled:i,onError:r,indexParameters:m,processFinalCode:g.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},l);return this._eventInfo.customCode=void 0,x}_prepareDefines(e,t,i=null,r=null,s=!1){var n;let a=this.getScene(),o=a.getEngine();so.G.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,so.G.PrepareDefinesForMultiview(a,t);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(so.G.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!l),so.G.PrepareDefinesForOIT(a,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(a.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,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&MaterialFlags.AmbientTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&MaterialFlags.OpacityTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;let e=this._getReflectionTexture();if(e&&MaterialFlags.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,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===texture_Texture.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 texture_Texture.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case texture_Texture.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case texture_Texture.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case texture_Texture.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case texture_Texture.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case texture_Texture.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case texture_Texture.CUBIC_MODE:case texture_Texture.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==texture_Texture.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.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;if(this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled?(so.G.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,MaterialFlags.SpecularTextureEnabled){if(this._metallicTexture?(so.G.PrepareDefinesForMergedUV(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?(so.G.PrepareDefinesForMergedUV(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){let e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(n=this._reflectanceTexture)||void 0===n?void 0:n._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(so.G.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(so.G.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?so.G.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap?(so.G.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=a.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&&MaterialFlags.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===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===pbrBaseMaterial_PBRBaseMaterial.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=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,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&&(so.G.PrepareDefinesForMisc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(rz.o.NormalKind),t.DEBUGMODE=this._debugMode),so.G.PrepareDefinesForFrameBoundValues(a,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),so.G.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(sG.S.GetDefineNames,this._eventInfo);let s=new PBRMaterialDefines(this._eventInfo.defineNames),n=this._prepareEffect(e,s,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(oX.effect=n,oX.subMesh=null,this._onEffectCreatedObservable.notifyObservers(oX)),n.isReady()?t&&t(this):n.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){let 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,i){var r,s,n,a;let o=this.getScene(),l=i.materialDefines;if(!l)return;let h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);let u=o.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);so.G.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let d=null,p=this._uniformBuffer;if(c){if(this.bindViewProjection(h),d=this._getReflectionTexture(),!p.useUbo||!this.isFrozen||!p.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&(p.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),so.G.BindTextureMatrix(this._albedoTexture,p,"albedo")),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&(p.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),so.G.BindTextureMatrix(this._ambientTexture,p,"ambient")),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&(p.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),so.G.BindTextureMatrix(this._opacityTexture,p,"opacity")),d&&MaterialFlags.ReflectionTextureEnabled){if(p.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),p.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){let e=d;p.updateVector3("vReflectionPosition",e.boundingBoxPosition),p.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){let e=d.getSize().width;p.updateFloat2("vReflectionFilteringInfo",e,rE.R.Log2(e))}if(!l.USEIRRADIANCEMAP){let e=d.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&e){if(l.SPHERICAL_HARMONICS){let t=e.preScaledHarmonics;p.updateVector3("vSphericalL00",t.l00),p.updateVector3("vSphericalL1_1",t.l1_1),p.updateVector3("vSphericalL10",t.l10),p.updateVector3("vSphericalL11",t.l11),p.updateVector3("vSphericalL2_2",t.l2_2),p.updateVector3("vSphericalL2_1",t.l2_1),p.updateVector3("vSphericalL20",t.l20),p.updateVector3("vSphericalL21",t.l21),p.updateVector3("vSphericalL22",t.l22)}else p.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),p.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),p.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),p.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),p.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),p.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),p.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),p.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),p.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}}p.updateFloat3("vReflectionMicrosurfaceInfos",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&(p.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),so.G.BindTextureMatrix(this._emissiveTexture,p,"emissive")),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&(p.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),so.G.BindTextureMatrix(this._lightmapTexture,p,"lightmap")),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?(p.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),so.G.BindTextureMatrix(this._metallicTexture,p,"reflectivity")):this._reflectivityTexture&&(p.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),so.G.BindTextureMatrix(this._reflectivityTexture,p,"reflectivity")),this._metallicReflectanceTexture&&(p.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),so.G.BindTextureMatrix(this._metallicReflectanceTexture,p,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(p.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),so.G.BindTextureMatrix(this._reflectanceTexture,p,"reflectance")),this._microSurfaceTexture&&(p.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),so.G.BindTextureMatrix(this._microSurfaceTexture,p,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&(p.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),so.G.BindTextureMatrix(this._bumpTexture,p,"bump"),o._mirroredCameraPosition?p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&p.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){rg.zZ.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,rg.zZ.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,p.updateColor4("vReflectivityColor",rg.zZ.Color3[0],1);let e=null!==(s=null===(r=this.subSurface)||void 0===r?void 0:r._indexOfRefraction)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((e-1)/(e+1),2)*this._metallicF0Factor,rg.zZ.Color3[0]);let t=this._metallicF0Factor;p.updateColor4("vMetallicReflectanceFactors",rg.zZ.Color3[0],t)}else p.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);p.updateColor3("vEmissiveColor",MaterialFlags.EmissiveTextureEnabled?this._emissiveColor:rg.Wo.BlackReadOnly),p.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(n=this.subSurface)||void 0===n?void 0:n._linkRefractionWithTransparency)?p.updateColor4("vAlbedoColor",this._albedoColor,1):p.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*o.environmentIntensity,this._lightingInfos.w=this._specularIntensity,p.updateVector4("vLightingIntensity",this._lightingInfos),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),p.updateColor3("vAmbientColor",this._globalAmbientColor),p.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}o.texturesEnabled&&(this._albedoTexture&&MaterialFlags.DiffuseTextureEnabled&&p.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&MaterialFlags.AmbientTextureEnabled&&p.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&MaterialFlags.OpacityTextureEnabled&&p.setTexture("opacitySampler",this._opacityTexture),d&&MaterialFlags.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?p.setTexture("reflectionSampler",d):(p.setTexture("reflectionSampler",d._lodTextureMid||d),p.setTexture("reflectionSamplerLow",d._lodTextureLow||d),p.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&p.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&p.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&MaterialFlags.EmissiveTextureEnabled&&p.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&MaterialFlags.LightmapTextureEnabled&&p.setTexture("lightmapSampler",this._lightmapTexture),MaterialFlags.SpecularTextureEnabled&&(this._metallicTexture?p.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&p.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&p.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&p.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&p.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&!this._disableBumpMap&&p.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,nX.an)(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(o.lightsEnabled&&!this._disableLighting&&so.G.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==rN.x.FOGMODE_NONE||d||this.subSurface.refractionTexture||t.receiveShadows||l.PREPASS)&&this.bindView(h),so.G.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&so.G.BindMorphTargetParameters(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(a=t.bakedVertexAnimationManager)||void 0===a||a.bind(h,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),so.G.BindLogDepth(l,this._activeEffect,o)),this._afterBind(t,this._activeEffect),p.update()}getAnimatables(){let 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(){let 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(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;let t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,r,s,n,a,o,l,h,u,c,d,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._metallicTexture)||void 0===o||o.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(u=this._lightmapTexture)||void 0===u||u.dispose(),null===(c=this._metallicReflectanceTexture)||void 0===c||c.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.dispose(),null===(p=this._microSurfaceTexture)||void 0===p||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}};pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE=sr.F.MATERIAL_OPAQUE,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST=sr.F.MATERIAL_ALPHATEST,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND=sr.F.MATERIAL_ALPHABLEND,pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND=sr.F.MATERIAL_ALPHATESTANDBLEND,pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL=0,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF=1,pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD=2,(0,rH.gn)([(0,rb.rX)()],pbrBaseMaterial_PBRBaseMaterial.prototype,"_imageProcessingConfiguration",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrBaseMaterial_PBRBaseMaterial.prototype,"debugMode",void 0),(0,rH.gn)([(0,rb.qC)()],pbrBaseMaterial_PBRBaseMaterial.prototype,"useLogarithmicDepth",null);let pbrMaterial_PBRMaterial=class pbrMaterial_PBRMaterial extends pbrBaseMaterial_PBRBaseMaterial{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===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF:this._lightFalloff=pbrBaseMaterial_PBRBaseMaterial.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){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=rg.Wo.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new rg.Wo(0,0,0),this.albedoColor=new rg.Wo(1,1,1),this.reflectivityColor=new rg.Wo(1,1,1),this.reflectionColor=new rg.Wo(1,1,1),this.emissiveColor=new rg.Wo(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=GetEnvironmentBRDFTexture(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=rb.p4.Clone(()=>new pbrMaterial_PBRMaterial(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=rb.p4.Parse(()=>new pbrMaterial_PBRMaterial(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),sr.F._parsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};function FourCCToInt32(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}function Int32ToFourCC(e){return String.fromCharCode(255&e,e>>8&255,e>>16&255,e>>24&255)}pbrMaterial_PBRMaterial.PBRMATERIAL_OPAQUE=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_OPAQUE,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATEST=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATEST,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHABLEND=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHABLEND,pbrMaterial_PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND=pbrBaseMaterial_PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND,pbrMaterial_PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"directIntensity",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveIntensity",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"environmentIntensity",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"specularIntensity",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"disableBumpMap",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"albedoTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTextureStrength",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"opacityTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectionTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectivityTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallic",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicF0Factor",void 0),(0,rH.gn)([(0,rb.n9)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicReflectanceColor",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"metallicReflectanceTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectanceTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"microSurfaceTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"bumpTexture",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty",null)],pbrMaterial_PBRMaterial.prototype,"lightmapTexture",void 0),(0,rH.gn)([(0,rb.n9)("ambient"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"ambientColor",void 0),(0,rH.gn)([(0,rb.n9)("albedo"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"albedoColor",void 0),(0,rH.gn)([(0,rb.n9)("reflectivity"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectivityColor",void 0),(0,rH.gn)([(0,rb.n9)("reflection"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"reflectionColor",void 0),(0,rH.gn)([(0,rb.n9)("emissive"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"emissiveColor",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"microSurface",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useLightmapAsShadowmap",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"useAlphaFromAlbedoTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"forceAlphaTest",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pbrMaterial_PBRMaterial.prototype,"alphaCutOff",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useSpecularOverAlpha",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAmbientInGrayScale",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,rH.gn)([(0,rb.qC)()],pbrMaterial_PBRMaterial.prototype,"usePhysicalLightFalloff",null),(0,rH.gn)([(0,rb.qC)()],pbrMaterial_PBRMaterial.prototype,"useGLTFLightFalloff",null),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRadianceOverAlpha",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useObjectSpaceNormalMap",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useParallax",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useParallaxOcclusion",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"parallaxScaleBias",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],pbrMaterial_PBRMaterial.prototype,"disableLighting",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"forceIrradianceInFragment",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],pbrMaterial_PBRMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"invertNormalMapX",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"invertNormalMapY",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"twoSidedLighting",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useAlphaFresnel",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useLinearAlphaFresnel",void 0),(0,rH.gn)([(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"environmentBRDFTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"forceNormalForward",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"enableSpecularAntiAliasing",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useHorizonOcclusion",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],pbrMaterial_PBRMaterial.prototype,"useRadianceOcclusion",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrMaterial_PBRMaterial.prototype,"unlit",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsMiscDirty")],pbrMaterial_PBRMaterial.prototype,"applyDecalMapAfterDetailMap",void 0),(0,rv.H)("BABYLON.PBRMaterial",pbrMaterial_PBRMaterial);let oY=FourCCToInt32("DXT1"),oj=FourCCToInt32("DXT3"),oq=FourCCToInt32("DXT5"),oK=FourCCToInt32("DX10");let DDSTools=class DDSTools{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),r=1;131072&t[2]&&(r=Math.max(1,t[7]));let s=t[21],n=s===oK?i[32]:0,a=0;switch(s){case 113:a=2;break;case 116:a=1;break;case oK:if(10===n){a=2;break}2===n&&(a=1)}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:(4&t[20])==4,isRGB:(64&t[20])==64,isLuminance:(131072&t[20])==131072,isCube:(512&t[28])==512,isCompressed:s===oY||s===oj||s===oq,dxgiFormat:n,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,n){let a=new Float32Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,r,s,n,a,o){let l=new Uint8Array(r),h=new Uint8Array(s,i),u=0;for(let i=0;i0?r.sphericalPolynomial=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({size:_[4],right:d[0],left:d[1],up:d[2],down:d[3],front:d[4],back:d[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}};DDSTools.StoreLODInAlphaChannel=!1,r6.B.prototype.createPrefilteredCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,e=>{if(!e){s&&s(null);return}let n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new SphericalPolynomial,n._source=r5.S.CubePrefiltered,this.getCaps().textureLOD){s&&s(n);return}let a=this._gl,o=e.width;if(!o)return;let h=[];for(let s=0;s<3;s++){let l=s/2,u=1-l,c=rE.R.Log2(o)*i+r,d=r+(c-r)*u,p=Math.round(Math.min(Math.max(d,0),c)),_=new r5.l(this,r5.S.Temp);if(_.type=n.type,_.format=n.format,_.width=Math.pow(2,Math.max(rE.R.Log2(o)-p,0)),_.height=_.width,_.isCube=!0,_._cachedWrapU=0,_._cachedWrapV=0,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,_,!0),_.samplingMode=2,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){let t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),DDSTools.UploadDDSLevels(this,_,i,t,!0,6,p)}else rT.Y.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);let f=new baseTexture_BaseTexture(t);f._isCube=!0,f._texture=_,_.isReady=!0,h.push(f)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],s&&s(n)},n,a,o,l,i,r)};let _DDSTextureLoader=class _DDSTextureLoader{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,r){let s;let n=t.getEngine(),a=!1,o=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),DDSTools.UploadDDSLevels(n,t,r,s,a,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t)}else s=DDSTools.GetDDSInfo(e),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new SphericalPolynomial),a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),DDSTools.UploadDDSLevels(n,t,e,s,a,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t,!1);n._setCubeMapTextureParams(t,a,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){let r=DDSTools.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1==1;i(r.width,r.height,s,r.isFourCC,()=>{DDSTools.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}};rq.D._TextureLoaders.push(new _DDSTextureLoader);let _ENVTextureLoader=class _ENVTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=GetEnvInfo(e);if(n){t.width=n.width,t.height=n.width;try{UploadEnvSpherical(t,n),UploadEnvLevelsAsync(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},e=>{null==s||s("Can not upload environment levels",e)})}catch(e){null==s||s("Can not upload environment file",e)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}};rq.D._TextureLoaders.push(new _ENVTextureLoader);let KhronosTextureContainer=class KhronosTextureContainer{constructor(e,t){if(this.data=e,this.isInvalid=!1,!KhronosTextureContainer.IsValid(e)){this.isInvalid=!0,rT.Y.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=r.getUint32(0,!0),n=67305985===s;if(this.glType=r.getUint32(1*i,n),this.glTypeSize=r.getUint32(2*i,n),this.glFormat=r.getUint32(3*i,n),this.glInternalFormat=r.getUint32(4*i,n),this.glBaseInternalFormat=r.getUint32(5*i,n),this.pixelWidth=r.getUint32(6*i,n),this.pixelHeight=r.getUint32(7*i,n),this.pixelDepth=r.getUint32(8*i,n),this.numberOfArrayElements=r.getUint32(9*i,n),this.numberOfFaces=r.getUint32(10*i,n),this.numberOfMipmapLevels=r.getUint32(11*i,n),this.bytesOfKeyValueData=r.getUint32(12*i,n),0!==this.glType){rT.Y.Error("only compressed formats currently supported"),this.isInvalid=!0;return}if(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth){rT.Y.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(0!==this.numberOfArrayElements){rT.Y.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){rT.Y.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=KhronosTextureContainer.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case KhronosTextureContainer.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case KhronosTextureContainer.TEX_2D:case KhronosTextureContainer.COMPRESSED_3D:case KhronosTextureContainer.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=KhronosTextureContainer.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}};KhronosTextureContainer.HEADER_LEN=64,KhronosTextureContainer.COMPRESSED_2D=0,KhronosTextureContainer.COMPRESSED_3D=1,KhronosTextureContainer.TEX_2D=2,KhronosTextureContainer.TEX_3D=3;let WorkerPool=class WorkerPool{constructor(e){this._pendingActions=[],this._workerInfos=e.map(e=>({workerPromise:Promise.resolve(e),idle:!0}))}dispose(){for(let 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(let t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{let t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0})})}};let AutoReleaseWorkerPool=class AutoReleaseWorkerPool extends WorkerPool{constructor(e,t,i=AutoReleaseWorkerPool.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e)){if(this._workerInfos.length{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(e=>{e.terminate()});let t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)},this._options.idleTimeElapsedBeforeRelease))})})}};function applyConfig(e){e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}AutoReleaseWorkerPool.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},(eb=ib||(ib={}))[eb.ETC1S=0]="ETC1S",eb[eb.UASTC4x4=1]="UASTC4x4",(ey=iy||(iy={}))[ey.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",ey[ey.BC7_RGBA=1]="BC7_RGBA",ey[ey.BC3_RGBA=2]="BC3_RGBA",ey[ey.BC1_RGB=3]="BC1_RGB",ey[ey.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",ey[ey.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",ey[ey.ETC2_RGBA=6]="ETC2_RGBA",ey[ey.ETC1_RGB=7]="ETC1_RGB",ey[ey.RGBA32=8]="RGBA32",ey[ey.R8=9]="R8",ey[ey.RG8=10]="RG8",(eP=iP||(iP={}))[eP.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",eP[eP.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",eP[eP.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",eP[eP.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",eP[eP.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",eP[eP.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",eP[eP.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",eP[eP.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",eP[eP.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",eP[eP.RGBA8Format=32856]="RGBA8Format",eP[eP.R8Format=33321]="R8Format",eP[eP.RG8Format=33323]="RG8Format";let DefaultKTX2DecoderOptions=class DefaultKTX2DecoderOptions{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;let e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[iy.BC1_RGB,iy.BC3_RGBA],yes:{transcodeFormat:iy.RGBA32,engineFormat:iP.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}};let KhronosTextureContainer2=class KhronosTextureContainer2{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(KhronosTextureContainer2._WorkerPoolPromise||KhronosTextureContainer2._DecoderModulePromise)return;let t={jsDecoderModule:rW.w1.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:rW.w1.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:rW.w1.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?KhronosTextureContainer2._WorkerPoolPromise=new Promise(i=>{let r=`${applyConfig}(${workerFunc})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new AutoReleaseWorkerPool(e,()=>new Promise((e,i)=>{let r=new Worker(s),onError=e=>{r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),i(e)},onMessage=t=>{"init"===t.data.action&&(r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),e(r))};r.addEventListener("error",onError),r.addEventListener("message",onMessage),r.postMessage({action:"init",urls:t})})))}):"undefined"==typeof KTX2DECODER?KhronosTextureContainer2._DecoderModulePromise=rW.w1.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,applyConfig(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,KhronosTextureContainer2._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=KhronosTextureContainer2.DefaultNumWorkers){this._engine=e,KhronosTextureContainer2._Initialize(t)}uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(KhronosTextureContainer2._WorkerPoolPromise)return KhronosTextureContainer2._WorkerPoolPromise.then(r=>new Promise((n,a)=>{r.push((r,o)=>{let onError=e=>{r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),a(e),o()},onMessage=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",onError),r.removeEventListener("message",onMessage),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){a({message:e})}else a({message:e.data.msg});o()}};r.addEventListener("error",onError),r.addEventListener("message",onMessage),r.postMessage({action:"setDefaultDecoderOptions",options:KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions()});let l=new Uint8Array(e.byteLength);l.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:l,caps:s,options:i},[l.buffer])})}));if(KhronosTextureContainer2._DecoderModulePromise)return KhronosTextureContainer2._DecoderModulePromise.then(i=>(KhronosTextureContainer2.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((s,n)=>{i.decode(e,r).then(e=>{this._createTexture(e,t),s()}).catch(e=>{n({message:e})})})));throw Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let r=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,r=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}};function workerFunc(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;importScripts(i.jsDecoderModule),applyConfig(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=t.data.options;break;case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(e=>{let t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})})}}}function mapSRGBToLinear(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}KhronosTextureContainer2.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},KhronosTextureContainer2.DefaultNumWorkers=KhronosTextureContainer2.GetDefaultNumWorkers(),KhronosTextureContainer2.DefaultDecoderOptions=new DefaultKTX2DecoderOptions;let _KTXTextureLoader=class _KTXTextureLoader{constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),n=new KhronosTextureContainer(e,6),a=n.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,s._setCubeMapTextureParams(t,a,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(KhronosTextureContainer.IsValid(e)){t._invertVScale=!t.invertY;let r=new KhronosTextureContainer(e,1),s=mapSRGBToLinear(r.glInternalFormat);s?(t.format=s,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else if(KhronosTextureContainer2.IsValid(e)){let s=new KhronosTextureContainer2(t.getEngine());s.uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},e=>{rT.Y.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,()=>{},!0)})}else rT.Y.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0)}};rq.D._TextureLoaders.unshift(new _KTXTextureLoader);let WebXRCamera=class WebXRCamera extends FreeCamera{constructor(e,t,i){super(e,rm.P.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=rm._f.Identity(),this._referencedPosition=new rm.P,this._trackingState=tU.NOT_TRACKING,this.onXRCameraInitializedObservable=new rf.y$,this.onBeforeCameraTeleport=new rf.y$,this.onAfterCameraTeleport=new rf.y$,this.onTrackingStateChanged=new rf.y$,this.compensateOnFirstFrame=!0,this._rotate180=new rm._f(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new rm._f,this.cameraRigMode=rj.V.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new sh.l(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new sh.l(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){if(!e||e===this)return;let i=e.computeWorldMatrix();i.decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,rm._f.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace()}getClassName(){return"WebXRCamera"}setTarget(e){let t=rm.jp.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();let i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),rm._f.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(tU.NOT_TRACKING);return}let t=e.emulatedPosition?tU.TRACKING_LOST:tU.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){let e={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(e),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){let t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;let i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach((e,t)=>{var i;let r=this.rigCameras[t];r.isLeftCamera||r.isRightCamera||("right"===e.eye?r._isRightCamera=!0:"left"!==e.eye||(r._isLeftCamera=!0));let s=e.transform.position,n=e.transform.orientation;r.parent=this.parent,r.position.set(s.x,s.y,s.z),r.rotationQuaternion.set(n.x,n.y,n.z,n.w),this._scene.useRightHandedSystem?r.rotationQuaternion.multiplyInPlace(this._rotate180):(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1),rm.y3.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,r._projectionMatrix),this._scene.useRightHandedSystem||r._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(r._projectionMatrix);let a=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==a?void 0:a._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=a):(this._xrSessionManager.trySetViewportForView(r.viewport,e),r.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),r.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){let e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){let e=rm.jp.Matrix[0],t=rm.jp.Matrix[1],i=rm.jp.Matrix[2];rm.y3.ComposeToRef(WebXRCamera._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),rm.y3.ComposeToRef(WebXRCamera._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);let r=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(r)}}};WebXRCamera._ScaleReadOnly=rm.P.One();let WebXRExperienceHelper=class WebXRExperienceHelper{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new rf.y$,this.onStateChangedObservable=new rf.y$,this.state=tw.NOT_IN_XR,this.sessionManager=new WebXRSessionManager(e),this.camera=new WebXRCamera("webxr",e,this.sessionManager),this.featuresManager=new WebXRFeaturesManager(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){let t=new WebXRExperienceHelper(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(e=>{throw t._setState(tw.NOT_IN_XR),t.dispose(),e})}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),r={}){var s,n,a;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(tw.ENTERING_XR),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&rT.Y.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);let o=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(webXRFeaturesManager_WebXRFeatureName.LAYERS)||(l.baseLayer=o),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(n=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===n?void 0:n.attachedToElement),null===(a=this._nonVRCamera)||void 0===a||a.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce(()=>{this.state!==tw.EXITING_XR&&this._setState(tw.EXITING_XR),this.camera.rigCameras.forEach(e=>{e.outputRenderTarget=null}),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(tw.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(tw.IN_XR)}),this.sessionManager}catch(e){throw console.log(e),console.log(e.message),this._setState(tw.NOT_IN_XR),e}}exitXRAsync(){return this.state!==tw.IN_XR?Promise.resolve():(this._setState(tw.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){let t=(null==e?void 0:e.fps)?e.fps:1e3,i=1/t*1e3,r=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,updateSpectatorCamera=()=>{if(this._spectatorCamera){let e=this.sessionManager.currentTimestamp-this._lastTimestamp;e>=i&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[r].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[r].absoluteRotation))}};if(this._spectatorMode){if(r>=this.camera.rigCameras.length)throw Error("the preferred camera index is beyond the length of rig camera array.");let onStateChanged=()=>{this.state===tw.IN_XR?(this._spectatorCamera=new universalCamera_UniversalCamera("webxr-spectator",rm.P.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new rm._f,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(updateSpectatorCamera),this._scene.onAfterRenderCameraObservable.add(e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===tw.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera),this._scene.activeCameras=null)};this.onStateChangedObservable.add(onStateChanged),onStateChanged()}else this.sessionManager.onXRFrameObservable.removeCallback(updateSpectatorCamera),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}};let WebXRControllerComponent=class WebXRControllerComponent{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new rf.y$,this.onButtonStateChangedObservable=new rf.y$}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return -1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){let i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}};WebXRControllerComponent.BUTTON_TYPE="button",WebXRControllerComponent.SQUEEZE_TYPE="squeeze",WebXRControllerComponent.THUMBSTICK_TYPE="thumbstick",WebXRControllerComponent.TOUCHPAD_TYPE="touchpad",WebXRControllerComponent.TRIGGER_TYPE="trigger";let WebXRAbstractMotionController=class WebXRAbstractMotionController{constructor(e,t,i,r,s=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=n,this._initComponent=e=>{if(!e)return;let t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new WebXRControllerComponent(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new rf.y$,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach(e=>this.getComponent(e).dispose()),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach(e=>{e.setEnabled(!1)}),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map(e=>this.components[e]).filter(t=>t.type===e)}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){let e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath();return e?rT.Y.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{let meshesLoaded=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){let e=this._controllerCache.filter(e=>e.filename===t.filename&&e.path===t.path);if(e[0]){e[0].meshes.forEach(e=>e.setEnabled(!0)),meshesLoaded(e[0].meshes);return}}sceneLoader_SceneLoader.ImportMesh("",t.path,t.filename,this.scene,e=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:e})),meshesLoaded(e)},null,(e,i)=>{rT.Y.Log(i),rT.Y.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)})})}updateFromXRFrame(e){this.getComponentIds().forEach(e=>this.getComponent(e).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(e=>e.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(e=>e.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;let r=i?.5*t+.5:t;rm._f.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),rm.P.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=rm._f.FromEulerAngles(0,Math.PI,0)}};let WebXRGenericTriggerMotionController=class WebXRGenericTriggerMotionController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,o$[i],t,i),this.profileId=WebXRGenericTriggerMotionController.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=rm._f.FromEulerAngles(0,Math.PI,0)}_updateModel(){}};WebXRGenericTriggerMotionController.ProfileId="generic-trigger";let o$={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};let WebXRProfiledMotionController=class WebXRProfiledMotionController extends WebXRAbstractMotionController{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){let e=sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb");return e||rT.Y.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach(i=>{let r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{let s=t.type===WebXRControllerComponent.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===WebXRControllerComponent.TOUCHPAD_TYPE&&!this._touchDots[i]){let t=sphereBuilder_CreateSphere(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new standardMaterial_StandardMaterial(i+"mat",this.scene),t.material.diffuseColor=rg.Wo.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}})})}_setRootMesh(e){let t;this.rootMesh=new rV.Kj(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{let t=this.getComponent(e);if(!t.hasChanges)return;let i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach(e=>{let s=r.visualResponses[e],n=t.value;if("xAxis"===s.componentProperty?n=t.axes.x:"yAxis"===s.componentProperty&&(n=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==s.componentProperty);else{let r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}})})}};let oQ=[];let WebXRMotionControllerManager=class WebXRMotionControllerManager{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){let t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){let r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");let s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),!this.UseOnlineRepository)return this._LoadProfilesFromAvailableControllers(r,e,t);{let i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch(()=>s.call(this,r,e,t))}}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=rW.w1.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e.toString())),this._ProfilesList}static ClearControllerCache(){oQ.forEach(e=>{e.meshes.forEach(e=>{e.dispose(!1,!0)})}),oQ.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=rW.w1.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then(e=>JSON.parse(e))),this._ProfileLoadingPromises[e])).then(e=>new WebXRProfiledMotionController(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:oQ))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;rnew WebXRGenericTriggerMotionController(t,e.gamepad,e.handedness)),WebXRMotionControllerManager.DefaultFallbacks();let oZ=0;let WebXRInputSource=class WebXRInputSource{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new rm.P,this._disposed=!1,this.onDisposeObservable=new rf.y$,this.onMeshLoadedObservable=new rf.y$,this.onMotionControllerInitObservable=new rf.y$,this._uniqueId=`controller-${oZ++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new rG.x(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new rm._f,this.inputSource.gripSpace&&(this.grip=new rG.x(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new rm._f),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&WebXRMotionControllerManager.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then(e=>{var t;e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach(e=>e.renderingGroupId=this._options.renderingGroupId)),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&(null===(t=this.motionController)||void 0===t||t.dispose())})},()=>{rW.w1.Warn("Could not find a matching motion controller for the registered input source")})}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){let i=t&&this.grip?this.grip:this.pointer;rm.P.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){let r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){let e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z);let t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){let r=e.getPose(this.inputSource.gripSpace,t);if(r){let e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}};let WebXRInput=class WebXRInput{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new rf.y$,this.onControllerRemovedObservable=new rf.y$,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(e=>e.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(e=>{this.controllers.forEach(t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera)})}),this._options.customControllersRepositoryURL&&(WebXRMotionControllerManager.BaseRepositoryUrl=this._options.customControllersRepositoryURL),WebXRMotionControllerManager.UseOnlineRepository=!this._options.disableOnlineControllerRepository,WebXRMotionControllerManager.UseOnlineRepository)try{WebXRMotionControllerManager.UpdateProfilesList().catch(()=>{WebXRMotionControllerManager.UseOnlineRepository=!1})}catch(e){WebXRMotionControllerManager.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){let i=this.controllers.map(e=>e.inputSource);for(let t of e)if(-1===i.indexOf(t)){let e=new WebXRInputSource(this.xrSessionManager.scene,t,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}let r=[],s=[];this.controllers.forEach(e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)}),this.controllers=r,s.forEach(e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),WebXRMotionControllerManager.ClearControllerCache()}};let WebXRControllerPointerSelection=class WebXRControllerPointerSelection extends WebXRAbstractFeature{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new ray_Ray(new rm.P,new rm.P),disabledByNearInteraction:!1,id:WebXRControllerPointerSelection._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new rm.P,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new rg.Wo(.9,.9,.9),this.laserPointerDefaultColor=new rg.Wo(.7,.7,.7),this.selectionMeshDefaultColor=new rg.Wo(.8,.8,.8),this.selectionMeshPickedColor=new rg.Wo(.3,.3,1),this._identityMatrix=rm.y3.Identity(),this._screenCoordinatesRef=rm.P.Zero(),this._viewportRef=new sh.l(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){let e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new ray_Ray(new rm.P,new rm.P),disabledByNearInteraction:!1,id:WebXRControllerPointerSelection._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;i{let t;let i=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}if(i.laserPointer.isVisible=this.displayLaserPointer,i.xrController)t=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);else{if(!i.webXRCamera)return;t=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay)}if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&t){let e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;!r||(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),rm.P.ProjectToRef(t,this._identityMatrix,e.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));let s=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit){if(this._pickingMoved(s,t.pick))o&&!this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),o=!1,a=0;else if(a>i/10&&(n.isVisible=!0),(a+=this._scene.getEngine().getDeltaTime())>=i)this._scene.simulatePointerDown(t.pick,l),o=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{let e=1-a/i;n.scaling.set(e,e,e)}}else o=!1,a=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}}),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&o&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()})}_attachScreenRayMode(e){let t=this._controllers[e.uniqueId],i=!1,r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),t.pick&&(!this._options.disablePointerUpOnTouchOut||!i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){let t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);let i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))}),e.inputSource.gamepad){let init=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(r=>{if(r.changes.pressed){let s=r.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)):!s||this._options.enablePointerSelectionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)}})};e.motionController?init(e.motionController):e.onMotionControllerInitObservable.add(init)}else{let selectStartListener=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)},selectEndListener=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)};t.eventListeners={selectend:selectEndListener,selectstart:selectStartListener},this._xrSessionManager.session.addEventListener("selectstart",selectStartListener),this._xrSessionManager.session.addEventListener("selectend",selectEndListener)}}_convertNormalToDirectionOfRay(e,t){if(e){let i=Math.acos(rm.P.Dot(e,t.direction));i{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){let e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new r7.p,e),t.finalPointerUpTriggered=!0})}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){rW.w1.Warn("controller already detached.")}})}}_generateNewMeshPair(e){let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():cylinderBuilder_CreateCylinder("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;let r=new standardMaterial_StandardMaterial("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;let s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():CreateTorus("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;let n=new standardMaterial_StandardMaterial("targetMat",t);return n.specularColor=rg.Wo.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,s.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));let r=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance,s=this._tmpVectorForPickCompare.length();return s>r}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}};WebXRControllerPointerSelection._IdCounter=200,WebXRControllerPointerSelection.Name=webXRFeaturesManager_WebXRFeatureName.POINTER_SELECTION,WebXRControllerPointerSelection.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPointerSelection.Name,(e,t)=>()=>new WebXRControllerPointerSelection(e,t),WebXRControllerPointerSelection.Version,!0);var oJ=i(1091);oJ.P.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,n){let a=rm.jp.Vector3[0],o=rm.jp.Vector3[1],l=Infinity;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;let{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:iR.DEHYDRATED,grabRay:new ray_Ray(new rm.P,new rm.P),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:WebXRNearInteraction._IdCounter++,pickedPointVisualCue:s},this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new rg.Wo(.8,.8,.8),this.selectionMeshPickedColor=new rg.Wo(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=iA.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case iR.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===iR.HOVER)break;case iR.HOVER:e.touchCollisionMeshFunction(!0),iR.TOUCH}else switch(e.currentAnimationState){case iR.TOUCH:if(e.touchCollisionMeshFunction(!1),t===iR.HOVER)break;case iR.HOVER:e.hydrateCollisionMeshFunction(!1),iR.DEHYDRATED}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;let s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(rm.jp.Vector3[0]),s.grabRay.direction.copyFrom(rm.jp.Vector3[0]),this._options.nearInteractionControllerMode!==iA.CENTERED_IN_FRONT||(null===(r=s.xrController)||void 0===r?void 0:r.inputSource.hand)||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var i;let r=this._controllers[t],s=null===(i=r.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!r.xrController||!s&&(!this._options.nearInteractionControllerMode||!r.xrController.inputSource.gamepad)){r.pick=null;return}if(r.hoverInteraction=!1,r.nearInteraction=!1,!r.xrController)return;if(s){let i=s.get("index-finger-tip");if(i){let r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){let e=this._scene.useRightHandedSystem?1:-1;rm.jp.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),rm.jp.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,rm.jp.Vector3[0],rm.jp.Quaternion[0])}}}else if(r.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==iA.DISABLED){let e=r.xrController.pointer;r.xrController.grip&&this._options.nearInteractionControllerMode===iA.CENTERED_ON_CONTROLLER&&(e=r.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}let accuratePickInfo=(e,t)=>t&&t.hit?e&&e.hit?t.distance{let t=new r7.p,i=!1,r=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),r&&!i&&(t=e),t};if(!r.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,this._hoverRadius,this._utilityLayerScene,e=>this._nearInteractionPredicate(e)));let i=this._pickWithSphere(r,this._hoverRadius,this._scene,e=>this._nearInteractionPredicate(e)),n=accuratePickInfo(i,t);if(n&&n.hit&&(e=populateNearInteractionInfo(n)).hit&&(r.hoverInteraction=!0),r.hoverInteraction){let t=null,i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,i,this._utilityLayerScene,e=>this._nearPickPredicate(e)));let n=this._pickWithSphere(r,i,this._scene,e=>this._nearPickPredicate(e)),a=accuratePickInfo(n,t),o=populateNearInteractionInfo(a);o.hit&&(e=o,r.nearInteraction=!0)}r.stalePick=r.pick,r.pick=e,r.pick&&r.pick.pickedPoint&&r.pick.hit?(r.meshUnderPointer=r.pick.pickedMesh,r.pickedPointVisualCue.position.copyFrom(r.pick.pickedPoint),r.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!0)):(r.meshUnderPointer=null,r.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!1))}let n=iR.DEHYDRATED;r.grabInteraction||r.nearInteraction?n=iR.TOUCH:r.hoverInteraction&&(n=iR.HOVER),this._handleTransitionAnimation(r,n)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,t=sphereBuilder_CreateSphere("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=rm._f.Identity();let i=new standardMaterial_StandardMaterial("targetMat",e);return i.specularColor=rg.Wo.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){let t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))});let grabCheck=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!r||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){let init=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;grabCheck(t)}}):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(e=>{if(e.changes.pressed){let t=e.changes.pressed.current;grabCheck(t)}}))};e.motionController?init(e.motionController):e.onMotionControllerInitObservable.add(init)}else{let selectStartListener=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},selectEndListener=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:selectEndListener,selectstart:selectStartListener},this._xrSessionManager.session.addEventListener("selectstart",selectStartListener),this._xrSessionManager.session.addEventListener("selectend",selectEndListener)}}_detachController(e){let t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach(e=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{let e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new r7.p,e)}),delete this._controllers[e],this._attachedController===e)){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._scene,t=sphereBuilder_CreateSphere("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:NodeMaterial.ParseFromSnippetAsync("8RUNKL#3",e).then(e=>{t.material=e});let i=new QuadraticEase;i.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT);let r=new rm.P(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),n=new rm.P(s,s,s),a=this._controllerPickRadius*(7/6),o=new rm.P(a,a,a),l=.8*this._controllerPickRadius,h=new rm.P(l,l,l),u=1.5*this._controllerPickRadius,c=new rm.P(u,u,u),d=[{frame:0,value:r},{frame:10,value:c},{frame:18,value:n}],p=[{frame:0,value:n},{frame:10,value:h},{frame:18,value:r}],_=[{frame:0,value:rm.P.ZeroReadOnly},{frame:12,value:o},{frame:15,value:r}],f=[{frame:0,value:r},{frame:10,value:rm.P.ZeroReadOnly},{frame:15,value:rm.P.ZeroReadOnly}],m=new animation_Animation("touch","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),g=new animation_Animation("release","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),v=new animation_Animation("hydrate","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT),x=new animation_Animation("dehydrate","scaling",60,animation_Animation.ANIMATIONTYPE_VECTOR3,animation_Animation.ANIMATIONLOOPMODE_CONSTANT);return m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),x.setEasingFunction(i),m.setKeys(d),g.setKeys(p),v.setKeys(_),x.setKeys(f),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{let r=i?m:g;e.beginDirectAnimation(t,[r],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{let r=i?v:x;i&&(t.isVisible=!0),e.beginDirectAnimation(t,[r],0,15,!1,1,()=>{i||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){let s=new r7.p;if(s.distance=Infinity,e.touchCollisionMesh&&e.xrController){let n=e.touchCollisionMesh.position,a=nZ.K.CreateFromCenterAndRadius(n,t);for(let t=0;ts&&(r=0,u.copyFrom(t.center)),-1!==r&&r()=>new WebXRNearInteraction(e,t),WebXRNearInteraction.Version,!0);let WebXREnterExitUIButton=class WebXREnterExitUIButton{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}};let WebXREnterExitUI=class WebXREnterExitUI{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new rf.y$,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw rW.w1.Warn("WebXR can only be served over HTTPS"),Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";let e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor",r="undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A",s=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+r+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";s+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';let n=document.createElement("style");n.appendChild(document.createTextNode(s)),document.getElementsByTagName("head")[0].appendChild(n);let a=document.createElement("button");a.className="babylonVRicon",a.title=`${e} - ${i}`,this._buttons.push(new WebXREnterExitUIButton(a,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",a.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}let i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce(()=>{this.dispose()}))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;let i=this._buttons.map(t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode));e.onStateChangedObservable.add(e=>{e==tw.NOT_IN_XR&&this._updateButtons(null)});let r=await Promise.all(i);r.forEach((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):rW.w1.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){let r=new WebXREnterExitUI(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==tw.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==tw.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(r){this._updateButtons(null);let t=this._buttons[e].element,i=t.title;t.title="Error entering XR session : "+i,t.classList.add("xr-error"),this.options.onError&&this.options.onError(r)}}dispose(){let e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach(e=>{e.update(this._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}};function setAndStartTimer(e){var t;let i=0,r=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};let s=e.contextObservable.add(t=>{let n=Date.now();i=n-r;let a={startTime:r,currentTime:n,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(a),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(a)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(a))},e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}(eI=iI||(iI={}))[eI.INIT=0]="INIT",eI[eI.STARTED=1]="STARTED",eI[eI.ENDED=2]="ENDED";let AdvancedTimer=class AdvancedTimer{constructor(e){var t,i;this.onEachCountObservable=new rf.y$,this.onTimerAbortedObservable=new rf.y$,this.onTimerEndedObservable=new rf.y$,this.onStateChangedObservable=new rf.y$,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{let t=Date.now();this._timer=t-this._startTime;let i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},r=this._breakOnNextTick||this._breakCondition(i);r||this._timer>=this._timeToEnd?this._stop(i,r):this.onEachCountObservable.notifyObservers(i)},this._setState(iI.INIT),this._contextObservable=e.contextObservable,this._observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{},this._breakCondition=null!==(i=e.breakCondition)&&void 0!==i?i:()=>!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(this._state===iI.STARTED)throw 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(iI.STARTED)}stop(){this._state===iI.STARTED&&(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(iI.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}};let WebXRMotionControllerTeleportation=class WebXRMotionControllerTeleportation extends WebXRAbstractFeature{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){let t=this._options.teleportationTargetMesh.getChildMeshes(!1,e=>"rotationCone"===e.name);t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new rg.HE(1,1,1,1),this._tmpRay=new ray_Ray(new rm.P,new rm.P),this._tmpVector=new rm.P,this._tmpQuaternion=new rm._f,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new rf.y$,this.teleportationEnabled=!0,this._rotationEnabled=!0,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1}};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let initMotionController=()=>{if(e.motionController){let i=e.motionController.getComponentOfType(WebXRControllerComponent.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(WebXRControllerComponent.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){let i=e.motionController.getMainComponent();if(!i)return;t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add(()=>{if(this.teleportationEnabled&&i.changes.pressed){if(i.changes.pressed.current){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;let r=this._options.timeToTeleport||3e3;setAndStartTimer({timeout:r,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else t.teleportationState.forward=!1,this._currentTeleportationControllerId=""}})}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add(i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,rm._f.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);let e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,e=>-1!==this._floorMeshes.indexOf(e));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;let e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);rm._f.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))})}};e.motionController?initMotionController():e.onMotionControllerInitObservable.addOnce(()=>{initMotionController()})}else this._xrSessionManager.scene.onPointerObservable.add(i=>{if(i.type===r8.kD.POINTERDOWN){t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0;let i=this._options.timeToTeleport||3e3;setAndStartTimer({timeout:i,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})}else i.type===r8.kD.POINTERUP&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="")})},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new rg.HE(1,0,0,.75),this._setTargetMeshVisibility(!1)}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)}removeFloorMesh(e){let t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];let t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){let t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t){for(let i=0;i{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;let t=this._floorMeshes.indexOf(e);return -1!==t&&this._floorMeshes[t].absolutePosition.y!!this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e)||-1!==this._floorMeshes.indexOf(e));if(n&&n.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(n.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(n);return}n&&n.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(n),this._setTargetMeshVisibility(!0),this._showParabolicPath(n))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=CreateGround("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{let i=new DynamicTexture("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;let r=i.getContext();r.beginPath(),r.arc(256,256,200,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),i.update();let s=new standardMaterial_StandardMaterial("teleportationPlaneMaterial",e);s.diffuseTexture=i,t.material=s}let i=CreateTorus("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){let t=new animation_Animation("animationInnerCircle","position.y",30,animation_Animation.ANIMATIONTYPE_FLOAT,animation_Animation.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);let s=new SineEase;s.setEasingMode(EasingFunction.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}let r=cylinderBuilder_CreateCylinder("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(rL.RD.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{let t=new standardMaterial_StandardMaterial("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new rg.Wo(.3,.3,1):t.diffuseColor=new rg.Wo(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){let t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){let s=t*t;this._snapToPositions.forEach(t=>{let n=rm.P.DistanceSquared(t,e);n<=s&&n{t.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||utilityLayerRenderer_UtilityLayerRenderer.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=Curve3.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,n=Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=linesBuilder_CreateLines("teleportation path line",{points:r.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){let t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint)){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){let e=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,rm._f.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}};WebXRMotionControllerTeleportation.Name=webXRFeaturesManager_WebXRFeatureName.TELEPORTATION,WebXRMotionControllerTeleportation.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRMotionControllerTeleportation.Name,(e,t)=>()=>new WebXRMotionControllerTeleportation(e,t),WebXRMotionControllerTeleportation.Version,!0);let WebXRDefaultExperience=class WebXRDefaultExperience{constructor(){}static CreateAsync(e,t={}){let i=new WebXRDefaultExperience;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){let r=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new WebXREnterExitUI(e,r)}return WebXRExperienceHelper.CreateAsync(e).then(e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new WebXRInput(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){let e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(WebXRControllerPointerSelection.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(WebXRMotionControllerTeleportation.Name,t.useStablePlugins?"stable":"latest",Object.assign({floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId},t.teleportationOptions)),i.teleportation.setSelectionFeature(i.pointerSelection))}return(t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(WebXRNearInteraction.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI)?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(e=>(rT.Y.Error("Error initializing XR"),rT.Y.Error(e),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}};function removeSource(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}rN.x.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled()),s=r.max.subtract(r.min),n=r.min.add(s.scale(.5)),a=1.5*s.length();if(isFinite(a)||(a=1,n.copyFromFloats(0,0,0)),e){let e=new ArcRotateCamera("default camera",-(Math.PI/2),Math.PI/2,a,n,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,t=e}else{let e=new FreeCamera("default camera",new rm.P(n.x,n.y,-a),this);e.setTarget(n),t=e}t.minZ=.01*a,t.maxZ=1e3*a,t.speed=.2*a,this.activeCamera=t,i&&t.attachControl()}},rN.x.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},rN.x.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return rT.Y.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);let n=boxBuilder_CreateBox("hdrSkyBox",{size:i},this);if(t){let t=new pbrMaterial_PBRMaterial("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=texture_Texture.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{let t=new standardMaterial_StandardMaterial("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=texture_Texture.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},rN.x.prototype.createDefaultEnvironment=function(e){return EnvironmentHelper?new EnvironmentHelper(e,this):null},rN.x.prototype.createDefaultVRExperience=function(e={}){return new VRExperienceHelper(this,e)},rN.x.prototype.createDefaultXRExperienceAsync=function(e={}){return WebXRDefaultExperience.CreateAsync(this,e).then(e=>e)};let VideoTexture=class VideoTexture extends texture_Texture{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new rf.y$),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):rT.Y.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((null==e?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}if(!this.video.muted){rT.Y.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(e=>{this._processError(e)});return}}this._processError(e)})}constructor(e,t,i,r=!1,s=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,a={},o,l=5){var h,u;super(null,i,!r,s),this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||rW.w1.IsExponentOfTwo(this.video.videoWidth)&&rW.w1.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=texture_Texture.WRAP_ADDRESSMODE,this.wrapV=texture_Texture.WRAP_ADDRESSMODE):(this.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=null!==(e=this._format)&&void 0!==e?e:5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{let e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture||this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&c?c&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return rW.w1.SetCorsBehavior(e.currentSrc,e),e;let t=document.createElement("video");return"string"==typeof e?(rW.w1.SetCorsBehavior(e,t),t.src=e):(rW.w1.SetCorsBehavior(e[0],t),e.forEach(e=>{let i=document.createElement("source");i.src=e,t.appendChild(i)})),this.onDisposeObservable.addOnce(()=>{removeSource(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){!e||this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture())}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new VideoTexture(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),null===(e=this._externalTexture)||void 0===e||e.dispose()}static CreateFromStreamAsync(e,t,i,r=!0){let s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(void 0!==s.mozSrcObject?s.mozSrcObject=t:"object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise(t=>{let onPlaying=()=>{let i=new VideoTexture("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&i.onDisposeObservable.addOnce(()=>{s.remove()}),i.onDisposeObservable.addOnce(()=>{removeSource(s)}),t(i),s.removeEventListener("playing",onPlaying)};s.addEventListener("playing",onPlaying),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){let s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,s,t,r);return n.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(e=>{e.stop()})}),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then(function(e){t&&t(e)}).catch(function(e){rT.Y.Error(e.name)})}};(0,rH.gn)([(0,rb.qC)("settings")],VideoTexture.prototype,"_settings",void 0),(0,rH.gn)([(0,rb.qC)("src")],VideoTexture.prototype,"_currentSrc",void 0),(0,rH.gn)([(0,rb.qC)()],VideoTexture.prototype,"isVideo",void 0),texture_Texture._CreateVideoTexture=(e,t,i,r=!1,s=!1,n=texture_Texture.TRILINEAR_SAMPLINGMODE,a={},o,l=5)=>new VideoTexture(e,t,i,r,s,n,a,o,l),(0,rv.H)("BABYLON.VideoTexture",VideoTexture);let VideoDome=class VideoDome extends TextureDome{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){let r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new VideoTexture((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,texture_Texture.TRILINEAR_SAMPLINGMODE,r);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(e=>{var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===this.mesh&&this._texture.video.play()},r8.kD.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}};VideoDome.MODE_MONOSCOPIC=TextureDome.MODE_MONOSCOPIC,VideoDome.MODE_TOPBOTTOM=TextureDome.MODE_TOPBOTTOM,VideoDome.MODE_SIDEBYSIDE=TextureDome.MODE_SIDEBYSIDE;let o0=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) -#include -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; -#endif -#ifdef VERTEXALPHA -varying vec4 vColor; -#endif -uniform vec4 glowColor;uniform float glowIntensity; -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include -vec4 finalColor=glowColor; -#ifdef DIFFUSE -vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); -#ifdef DIFFUSE_ISLINEAR -albedoTexture=toGammaSpace(albedoTexture); -#endif -#ifdef GLOW -finalColor.a*=albedoTexture.a; -#endif -#ifdef HIGHLIGHT -finalColor.a=albedoTexture.a; -#endif -#endif -#ifdef OPACITY -vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); -#ifdef OPACITYRGB -finalColor.a*=getLuminance(opacityMap.rgb); -#else -finalColor.a*=opacityMap.a; -#endif -finalColor.a*=opacityIntensity; -#endif -#ifdef VERTEXALPHA -finalColor.a*=vColor.a; -#endif -#ifdef ALPHATEST -if (finalColor.a -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -uniform mat4 viewProjection;varying vec4 vPosition; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#ifdef DIFFUSE -varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; -#endif -#ifdef OPACITY -varying vec2 vUVOpacity;uniform mat4 opacityMatrix; -#endif -#ifdef EMISSIVE -varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; -#endif -#ifdef VERTEXALPHA -attribute vec4 color;varying vec4 vColor; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef CUBEMAP -vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); -#else -vPosition=viewProjection*worldPos;gl_Position=vPosition; -#endif -#ifdef DIFFUSE -#ifdef DIFFUSEUV1 -vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef DIFFUSEUV2 -vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef OPACITY -#ifdef OPACITYUV1 -vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef OPACITYUV2 -vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef EMISSIVE -#ifdef EMISSIVEUV1 -vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef EMISSIVEUV2 -vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#ifdef VERTEXALPHA -vColor=color; -#endif -#include -}`;s_.v.ShadersStore.glowMapGenerationVertexShader=o1;let EffectLayer=class EffectLayer{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);let n=this._scene.getEngine();if(r.length){for(n.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){let e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=e})}}_addCustomEffectDefines(e){}_isReady(e,t,i){var r;let s=this._scene.getEngine(),n=e.getMesh(),a=null===(r=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[s.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);let o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);let l=[],h=[rz.o.PositionKind],u=!1,c=!1;if(o){let e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),n.isVerticesDataPresent(rz.o.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),c=!0):n.isVerticesDataPresent(rz.o.UVKind)&&(l.push("#define DIFFUSEUV1"),u=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));let r=o.opacityTexture;r&&(l.push("#define OPACITY"),n.isVerticesDataPresent(rz.o.UV2Kind)&&1===r.coordinatesIndex?(l.push("#define OPACITYUV2"),c=!0):n.isVerticesDataPresent(rz.o.UVKind)&&(l.push("#define OPACITYUV1"),u=!0))}i&&(l.push("#define EMISSIVE"),n.isVerticesDataPresent(rz.o.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),c=!0):n.isVerticesDataPresent(rz.o.UVKind)&&(l.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(rz.o.ColorKind)&&n.hasVertexAlpha&&o.transparencyMode!==sr.F.MATERIAL_OPAQUE&&(h.push(rz.o.ColorKind),l.push("#define VERTEXALPHA")),u&&(h.push(rz.o.UVKind),l.push("#define UV1")),c&&(h.push(rz.o.UV2Kind),l.push("#define UV2"));let d=new EffectFallbacks;if(n.useBones&&n.computeBonesUsingShaders){h.push(rz.o.MatricesIndicesKind),h.push(rz.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(h.push(rz.o.MatricesIndicesExtraKind),h.push(rz.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);let e=n.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),n.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,n)}else l.push("#define NUM_BONE_INFLUENCERS 0");let p=n.morphTargetManager,_=0;p&&p.numInfluencers>0&&(l.push("#define MORPHTARGETS"),_=p.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+_),p.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(h,n,_)),t&&(l.push("#define INSTANCES"),so.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),(0,nX.lK)(o,this._scene,l),this._addCustomEffectDefines(l);let f=e._getDrawWrapper(void 0,!0),m=f.defines,g=l.join("\n");if(m!==g){let e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,nX.qx)(e),f.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:_}),g)}return f.effect.isReady()}render(){for(let e=0;ea.setMatrix("world",t))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[rz.o.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){let r=rW.w1.Instantiate(e.customType);return r.Parse(e,t,i)}};EffectLayer._SceneComponentInitialization=e=>{throw(0,r$.S)("EffectLayerSceneComponent")},(0,rH.gn)([(0,rb.qC)()],EffectLayer.prototype,"name",void 0),(0,rH.gn)([(0,rb.XX)()],EffectLayer.prototype,"neutralColor",void 0),(0,rH.gn)([(0,rb.qC)()],EffectLayer.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.VE)()],EffectLayer.prototype,"camera",null),(0,rH.gn)([(0,rb.qC)()],EffectLayer.prototype,"renderingGroupId",null),(0,rH.gn)([(0,rb.qC)()],EffectLayer.prototype,"disableBoundingBoxesFromEffectLayer",void 0),rp.p.AddParser(rQ.l.NAME_EFFECTLAYER,(e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(e)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.removeEffectLayer(e),t&&e.dispose()})}dispose(){let e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){let i=this._engine.currentRenderPassId,r=this.scene.effectLayers;for(let s of r){if(!s.hasMesh(e))continue;let r=s._mainTexture;for(let n of(this._engine.currentRenderPassId=r.renderPassId,e.subMeshes))if(!s.isReady(n,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1,i=this.scene.effectLayers;if(i&&i.length>0){for(let r of(this._previousStencilState=this._engine.getStencilBuffer(),i))if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===rj.V.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==rj.V.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(rQ.l.NAME_EFFECTLAYER);t||(t=new EffectLayerSceneComponent(e),e._addComponent(t))};let o2=`varying vec2 vUV;uniform sampler2D textureSampler; -#ifdef EMISSIVE -uniform sampler2D textureSampler2; -#endif -uniform float offset; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV); -#ifdef EMISSIVE -baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; -#else -baseColor.a=abs(offset-baseColor.a); -#ifdef STROKE -float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; -#endif -#endif -#if LDR -baseColor=clamp(baseColor,0.,1.0); -#endif -gl_FragColor=baseColor; -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.glowMapMergePixelShader=o2;let o3=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.glowMapMergeVertexShader=o3,rp.p.prototype.getGlowLayerByName=function(e){var t;for(let i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===GlowLayer.EffectName)return this.effectLayers[i];return null};let GlowLayer=class GlowLayer extends EffectLayer{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;let t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new rg.HE(0,0,0,1),this._options=Object.assign({mainTextureRatio:GlowLayer.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return GlowLayer.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[rz.o.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;let r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new renderTargetTexture_RenderTargetTexture("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];let n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new BlurPostProcess("GlowLayerHBP1",new rm.FM(1,0),n,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new BlurPostProcess("GlowLayerVBP1",new rm.FM(0,1),n,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new BlurPostProcess("GlowLayerHBP2",new rm.FM(1,0),n,{width:r,height:s},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new BlurPostProcess("GlowLayerVBP2",new rm.FM(0,1),n,{width:r,height:s},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(()=>{let e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);let t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(null!=t?t:e,!0)}}),this._postProcesses.map(e=>{e.autoClear=!1})}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;let s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);let t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(sr.F.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var r;let s=1;if(this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector)this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color);else if(i.emissiveColor){let e=null!==(r=i.emissiveIntensity)&&void 0!==r?r:1;s*=e,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)}else this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){let t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){let t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(()=>{this._disposeMesh(e)})}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){let e;let t=rb.p4.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;enew GlowLayer(e.name,t,e.options),e,t,i);for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)})}};let HighlightLayer=class HighlightLayer extends EffectLayer{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new rf.y$,this.onAfterBlurObservable=new rf.y$,this._instanceGlowingMeshStencilReference=HighlightLayer.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=HighlightLayer.NeutralColor,this._engine.isStencilEnable||rT.Y.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return HighlightLayer.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[rz.o.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?rq.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new renderTargetTexture_RenderTargetTexture("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(texture_Texture.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new PassPostProcess("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerHBP",new rm.FM(1,0),this._options.blurHorizontalSize,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new GlowBlurPostProcess("HighlightLayerVBP",new rm.FM(0,1),this._options.blurVerticalSize,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new BlurPostProcess("HighlightLayerHBP",new rm.FM(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new BlurPostProcess("HighlightLayerVBP",new rm.FM(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(e=>{e.autoClear=!1})}needStencil(){return!0}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,n=this._meshes[r.uniqueId];return n&&n.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);let i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(sr.F.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(sr.F.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return(!this._excludedMeshes||!this._excludedMeshes[e.uniqueId])&&!!super.hasMesh(e)}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];if(!t){let t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add(e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)}),t.afterRender=e.onAfterRenderObservable.add(e=>{e.getEngine().setStencilBuffer(t.stencilState)}),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!(this._meshes&&super.hasMesh(e))&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(e=>{this.isEnabled&&this._defaultStencilReference(e)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];for(let i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(let e in this._excludedMeshes){let t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){let e=rb.p4.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(let t in this._meshes){let i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(let t in this._excludedMeshes){let i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){let r;let s=rb.p4.Parse(()=>new HighlightLayer(e.name,t,e.options),e,t,i);for(r=0;r -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV); -#ifdef LINEAR -baseColor.rgb=toGammaSpace(baseColor.rgb); -#endif -#ifdef ALPHATEST -if (baseColor.a<0.4) -discard; -#endif -gl_FragColor=baseColor*color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.layerPixelShader=o5;let o6=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.layerVertexShader=o6;let LensFlare=class LensFlare{static AddFlare(e,t,i,r,s){return new LensFlare(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new rg.Wo(1,1,1),this.texture=r?new texture_Texture(r,s.getScene(),!0):null,this._system=s;let n=s.scene.getEngine();this._drawWrapper=new sm.q(n),this._drawWrapper.effect=n.createEffect("lensFlare",[rz.o.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();let e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}};let o8=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.lensFlarePixelShader=o8;let o7=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.lensFlareVertexShader=o7;let LensFlareSystem=class LensFlareSystem{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||rS.l.LastCreatedScene,LensFlareSystem._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&(e.layerMask&i.activeCamera.layerMask)!=0;let r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[rz.o.PositionKind]=new rz.o(r,s,rz.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){let 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)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=rm.P.Project(t,rm.y3.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=rm.P.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);let i=this._scene.useRightHandedSystem,r=t.z>0&&!i||t.z<0&&i;return!!r&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;let e=this.getEmitterPosition(),t=e.subtract(this._scene.activeCamera.globalPosition),i=t.length();t.normalize();let r=new ray_Ray(this._scene.activeCamera.globalPosition,t),s=this._scene.pickWithRay(r,this.meshesSelectionPredicate,!0);return!s||!s.hit||s.distance>i}render(){let e,t;if(!this._scene.activeCamera)return!1;let i=this._scene.getEngine(),r=this._scene.activeCamera.viewport,s=r.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(s)||!this._isVisible())return!1;let n=(e=this._positionXs.x+s.width-this.borderLimit?this._positionX-s.x-s.width+this.borderLimit:0)>(t=this._positionYs.y+s.height-this.borderLimit?this._positionY-s.y-s.height+this.borderLimit:0)?e:t;(n-=this.viewportBorder)>this.borderLimit&&(n=this.borderLimit);let a=1-rE.R.Clamp(n/this.borderLimit,0,1);if(a<0)return!1;a>1&&(a=1),this.viewportBorder>0&&(s.x+=this.viewportBorder,s.y+=this.viewportBorder,s.width-=2*this.viewportBorder,s.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);let o=s.x+s.width/2,l=s.y+s.height/2,h=o-this._positionX,u=l-this._positionY;i.setState(!1),i.setDepthBuffer(!1);for(let e=0;e{throw(0,r$.S)("LensFlareSystemSceneComponent")},rp.p.AddParser(rQ.l.NAME_LENSFLARESYSTEM,(e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,n=e.lensFlareSystems.length;s{this.scene.addLensFlareSystem(e)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()})}serialize(e){e.lensFlareSystems=[];let t=this.scene.lensFlareSystems;for(let i of t)e.lensFlareSystems.push(i.serialize())}dispose(){let e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){let t=this.scene.lensFlareSystems;for(let i of(rW.w1.StartPerformanceCounter("Lens flares",t.length>0),t))(e.layerMask&i.layerMask)!=0&&i.render();rW.w1.EndPerformanceCounter("Lens flares",t.length>0)}}};LensFlareSystem._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_LENSFLARESYSTEM);t||(t=new LensFlareSystemSceneComponent(e),e._addComponent(t))};let o9=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} -float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); -vec2 P2=floor(0.5*mod(_P,4.0)); -return 4.0*bayerDither2(P1)+bayerDither2(P2);} -float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); -vec2 P2=floor(0.5 *mod(_P,4.0)); -vec2 P4=floor(0.25*mod(_P,8.0)); -return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} -`;s_.v.IncludesShadersStore.bayerDitherFunctions=o9;let le=`#if SM_FLOAT==0 -#include -#endif -#if SM_SOFTTRANSPARENTSHADOW==1 -#include -uniform float softTransparentShadowSM; -#endif -varying float vDepthMetricSM; -#if SM_USEDISTANCE==1 -uniform vec3 lightDataSM;varying vec3 vPositionWSM; -#endif -uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -varying float zSM; -#endif -`;s_.v.IncludesShadersStore.shadowMapFragmentExtraDeclaration=le;let lt=`float depthSM=vDepthMetricSM; -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -#if SM_USEDISTANCE==1 -depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -#ifdef USE_REVERSE_DEPTHBUFFER -depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#endif -#ifdef USE_REVERSE_DEPTHBUFFER -gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); -#else -gl_FragDepth=clamp(depthSM,0.0,1.0); -#endif -#elif SM_USEDISTANCE==1 -depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#if SM_ESM==1 -depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); -#endif -#if SM_FLOAT==1 -gl_FragColor=vec4(depthSM,1.0,1.0,1.0); -#else -gl_FragColor=pack(depthSM); -#endif -return;`;s_.v.IncludesShadersStore.shadowMapFragment=lt;let li=`#include -#ifdef ALPHATEXTURE -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include -#ifdef ALPHATEXTURE -float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; -#ifdef ALPHATESTVALUE -if (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard; -#else -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; -#endif -#endif -#include -}`;s_.v.ShadersStore.shadowMapPixelShader=li;let lr=`uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; -`;s_.v.IncludesShadersStore.sceneVertexDeclaration=lr;let ls=`uniform mat4 world;uniform float visibility; -`;s_.v.IncludesShadersStore.meshVertexDeclaration=ls;let ln=`#include -#include -`;s_.v.IncludesShadersStore.shadowMapVertexDeclaration=ln;let la=`layout(std140,column_major) uniform; -#include -#include -`;s_.v.IncludesShadersStore.shadowMapUboDeclaration=la;let lo=`#if SM_NORMALBIAS==1 -uniform vec3 lightDataSM; -#endif -uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; -#if SM_USEDISTANCE==1 -varying vec3 vPositionWSM; -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -varying float zSM; -#endif -`;s_.v.IncludesShadersStore.shadowMapVertexExtraDeclaration=lo;let ll=`#if SM_NORMALBIAS==1 -#if SM_DIRECTIONINLIGHTDATA==1 -vec3 worldLightDirSM=normalize(-lightDataSM.xyz); -#else -vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); -#endif -float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; -#endif -`;s_.v.IncludesShadersStore.shadowMapVertexNormalBias=ll;let lh=`#if SM_USEDISTANCE==1 -vPositionWSM=worldPos.xyz; -#endif -#if SM_DEPTHTEXTURE==1 -#ifdef IS_NDC_HALF_ZRANGE -#define BIASFACTOR 0.5 -#else -#define BIASFACTOR 1.0 -#endif -#ifdef USE_REVERSE_DEPTHBUFFER -gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; -#else -gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; -#endif -#endif -#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 -zSM=gl_Position.z;gl_Position.z=0.0; -#elif SM_USEDISTANCE==0 -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#else -vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; -#endif -#endif -`;s_.v.IncludesShadersStore.shadowMapVertexMetric=lh;let lu=`attribute vec3 position; -#ifdef NORMAL -attribute vec3 normal; -#endif -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#ifdef INSTANCES -attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; -#endif -#include -#include<__decl__shadowMapVertex> -#ifdef ALPHATEXTURE -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#ifdef NORMAL -vec3 normalUpdated=normal; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#ifdef NORMAL -mat3 normWorldSM=mat3(finalWorld); -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vec3 vNormalW=normalize(normWorldSM*normalUpdated); -#endif -#endif -#include -gl_Position=viewProjection*worldPos; -#include -#ifdef ALPHATEXTURE -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#include -}`;s_.v.ShadersStore.shadowMapVertexShader=lu;let lc=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) -for (int y=-OFFSET; y<=OFFSET; y++) -colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;s_.v.ShadersStore.depthBoxBlurPixelShader=lc;let ld=`#if SM_SOFTTRANSPARENTSHADOW==1 -if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; -#endif -`;s_.v.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=ld;let shadowGenerator_ShadowGenerator=class shadowGenerator_ShadowGenerator{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}if(e===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}if(e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===shadowGenerator_ShadowGenerator.FILTER_PCF||e===shadowGenerator_ShadowGenerator.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_POISSONSAMPLING)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCF);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCF)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(shadowGenerator_ShadowGenerator.FILTER_PCSS);(e||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS)&&(this.filter=e?t:shadowGenerator_ShadowGenerator.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return shadowGenerator_ShadowGenerator.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(let t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(let t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,r,s){this.onBeforeShadowMapRenderObservable=new rf.y$,this.onAfterShadowMapRenderObservable=new rf.y$,this.onBeforeShadowMapRenderMeshObservable=new rf.y$,this.onAfterShadowMapRenderMeshObservable=new rf.y$,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=shadowGenerator_ShadowGenerator.FILTER_NONE,this._filteringQuality=shadowGenerator_ShadowGenerator.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=rm.P.Zero(),this._viewMatrix=rm.y3.Zero(),this._projectionMatrix=rm.y3.Zero(),this._transformMatrix=rm.y3.Zero(),this._cachedPosition=new rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new rm.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=rm.y3.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=r?r:null,this._useRedTextureType=!!s;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),shadowGenerator_ShadowGenerator._SceneComponentInitialization(this._scene);let a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){let e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new renderTargetTexture_RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new renderTargetTexture_RenderTargetTexture(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,r)=>this._renderForShadowMap(e,t,i,r),this._shadowMap.customIsReadyFunction=()=>!0;let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var t,i;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){null===(t=e._debugPopGroup)||void 0===t||t.call(e,1);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))});let t=new rg.HE(0,0,0,0),i=new rg.HE(1,1,1,1);this._shadowMap.onClearObservable.add(e=>{this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let e=sT.$.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new BlurPostProcess(this._light.name+"KernelBlurY",new rm.FM(0,1),this.blurKernel,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new postProcess_PostProcess(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;sn._getWorldMatrixDeterminant(),u=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;h&&(u=0===u?1:0);let c=0===u;o.setState(l.backFaceCulling,void 0,void 0,c,l.cullBackFaces);let d=s._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;let p=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||s.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e)){if(this.isReady(e,p,t)){e._renderId=a.getRenderId();let i=l.shadowDepthWrapper,h=null!==(r=null==i?void 0:i.getEffect(e,this,o.currentRenderPassId))&&void 0!==r?r:e._getDrawWrapper(),u=sm.q.GetEffect(h);o.enableEffect(h),p||s._bind(e,u,l.fillMode),this.getTransformMatrix(),u.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?u.setVector3("lightDataSM",this._cachedDirection):u.setVector3("lightDataSM",this._cachedPosition);let c=this._getCamera();if(c&&u.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(c),this.getLight().getDepthMinZ(c)+this.getLight().getDepthMaxZ(c)),t&&this.enableSoftTransparentShadow&&u.setFloat("softTransparentShadowSM",n.visibility*l.alpha),i)e._setMainDrawWrapperOverride(h),i.standalone?i.baseMaterial.bindForSubMesh(n.getWorldMatrix(),s,e):l.bindForSubMesh(n.getWorldMatrix(),s,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(u.setTexture("diffuseSampler",this._opacityTexture),u.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){let e=s.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(s);if(!t)return;u.setTexture("boneSampler",t),u.setFloat("boneTextureWidth",4*(e.bones.length+1))}else u.setMatrices("mBones",e.getTransformMatrices(s))}so.G.BindMorphTargetParameters(s,u),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(u),(0,nX.an)(u,l,a)}this._useUBO||i||this._bindCustomEffectForRenderSubMeshForShadowMap(e,u,n),so.G.BindSceneUniformBuffer(u,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();let _=n.getWorldMatrix();p&&(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(_)),this.forceBackFacesOnly&&o.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(s),this.onBeforeShadowMapRenderObservable.notifyObservers(u),s._processRendering(n,e,u,l.fillMode,d,p,(e,t)=>{n===s||e?(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(e?t:_)):(s.getMeshUniformBuffer().bindToEffect(u,"Mesh"),s.transferToEffect(t))}),this.forceBackFacesOnly&&o.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(u),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}_applyFilterValues(){this._shadowMap&&(this.filter===shadowGenerator_ShadowGenerator.FILTER_NONE||this.filter===shadowGenerator_ShadowGenerator.FILTER_PCSS?this._shadowMap.updateSamplingMode(texture_Texture.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(texture_Texture.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i=Object.assign({useInstances:!1},t),r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let n=[];for(let e of s)n.push(...e.subMeshes);if(0===n.length){e&&e(this);return}let a=0,checkReady=()=>{var t,r;if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[a],i.useInstances,null!==(r=null===(t=n[a].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(n[a].getMesh()))&&void 0!==r&&r);)if(++a>=n.length){e&&e(this);return}setTimeout(checkReady,16)}};checkReady()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(rz.o.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===light_Light.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var r;let s=e.getMaterial(),n=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;let a=[];if(this._prepareShadowDefines(e,t,a,i),n){if(!n.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let i=e._getDrawWrapper(void 0,!0),n=i.effect,o=i.defines,l=[rz.o.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(rz.o.NormalKind)&&(l.push(rz.o.NormalKind),a.push("#define NORMAL"),h.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));let u=s.needAlphaTesting();if((u||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let e=null!==(r=s.alphaCutOff)&&void 0!==r?r:shadowGenerator_ShadowGenerator.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),u&&a.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(rz.o.UVKind)&&(l.push(rz.o.UVKind),a.push("#define UV1")),h.isVerticesDataPresent(rz.o.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(rz.o.UV2Kind),a.push("#define UV2"))}let c=new EffectFallbacks;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(rz.o.MatricesIndicesKind),l.push(rz.o.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(rz.o.MatricesIndicesExtraKind),l.push(rz.o.MatricesWeightsExtraKind));let e=h.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");let d=h.morphTargetManager,p=0;if(d&&d.numInfluencers>0&&(a.push("#define MORPHTARGETS"),p=d.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(l,h,p)),(0,nX.lK)(s,this._scene,a),t&&(a.push("#define INSTANCES"),so.G.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let e of this.customShaderOptions.defines)-1===a.indexOf(e)&&a.push(e);let _=a.join("\n");if(o!==_){o=_;let e="shadowMap",t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],r=["diffuseSampler","boneSampler","morphTargets"];if((0,nX.qx)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(let e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(let e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}let s=this._scene.getEngine();n=s.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:["Scene","Mesh"],samplers:r,defines:_,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},s),i.setEffect(n,o)}if(!n.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),(!this._kernelBlurXPostprocess||!!this._kernelBlurXPostprocess.isReady())&&(!this._kernelBlurYPostprocess||!!this._kernelBlurYPostprocess.isReady())&&(!this._boxBlurPostprocess||!!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){let i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===shadowGenerator_ShadowGenerator.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let n=this.getShadowMap();n&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n.getSize().width,1/n.getSize().width,this.frustumEdgeFalloff,e)):this._filter===shadowGenerator_ShadowGenerator.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/n.getSize().width,this._contactHardeningLightSizeUVRatio*n.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/n.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(s),this.getLight().getDepthMinZ(s)+this.getLight().getDepthMaxZ(s),e))}getTransformMatrix(){let e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),rm.P.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(rm.P.Dot(this._lightDirection,rm.P.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),rm.y3.LookAtLHToRef(t,t.add(this._lightDirection),rm.P.Up(),this._viewMatrix);let e=this.getShadowMap();if(e){let t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t)for(let e of(this._shadowMap.renderList||(this._shadowMap.renderList=[]),t))this._shadowMap.renderList.push(e);else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){let[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var e;let t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=null===(e=this._camera)||void 0===e?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let e=0;e{throw(0,r$.S)("ShadowGeneratorSceneComponent")};let lp=`#ifdef ALPHATEST -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include -varying float vDepthMetric; -#ifdef PACKED -#include -#endif -#ifdef STORE_CAMERASPACE_Z -varying vec4 vViewPos; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#include -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#ifdef STORE_CAMERASPACE_Z -#ifdef PACKED -gl_FragColor=pack(vViewPos.z); -#else -gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); -#endif -#else -#ifdef NONLINEARDEPTH -#ifdef PACKED -gl_FragColor=pack(gl_FragCoord.z); -#else -gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); -#endif -#else -#ifdef PACKED -gl_FragColor=pack(vDepthMetric); -#else -gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); -#endif -#endif -#endif -}`;s_.v.ShadersStore.depthPixelShader=lp;let l_=`attribute vec3 position; -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -uniform mat4 viewProjection;uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#ifdef STORE_CAMERASPACE_Z -uniform mat4 view;varying vec4 vViewPos; -#endif -varying float vDepthMetric; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); -#include -gl_Position=viewProjection*worldPos; -#ifdef STORE_CAMERASPACE_Z -vViewPos=view*worldPos; -#else -#ifdef USE_REVERSE_DEPTHBUFFER -vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); -#else -vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); -#endif -#endif -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`;s_.v.ShadersStore.depthVertexShader=l_;let DepthRenderer=class DepthRenderer{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=texture_Texture.TRILINEAR_SAMPLINGMODE,n=!1,a){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new rg.HE(1,1,1,1):this.clearColor=new rg.HE(n?1e8:1,0,0,1),DepthRenderer._SceneComponentInitialization(this._scene);let o=e.getEngine();this._camera=i,s===texture_Texture.NEAREST_SAMPLINGMODE||(1!==t||o._caps.textureFloatLinearFiltering||(s=texture_Texture.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(s=texture_Texture.NEAREST_SAMPLINGMODE));let l=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new renderTargetTexture_RenderTargetTexture(null!=a?a:"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._depthMap.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(e=>{e.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{var e;null===(e=o._debugPushGroup)||void 0===e||e.call(o,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)}),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{var t,i;let r=e.getRenderingMesh(),s=e.getEffectiveMesh(),n=this._scene,a=n.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||s.infiniteDistance||o.disableDepthWrite||0===e.verticesCount||e._renderId===n.getRenderId())return;let l=0>s._getWorldMatrixDeterminant(),h=null!==(t=r.overrideMaterialSideOrientation)&&void 0!==t?t:o.sideOrientation;l&&(h=0===h?1:0);let u=0===h;a.setState(o.backFaceCulling,0,!1,u,this.reverseCulling?!o.cullBackFaces:o.cullBackFaces);let c=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(c.mustReturn)return;let d=a.getCaps().instancedArrays&&(null!==c.visibleInstances[e._id]&&void 0!==c.visibleInstances[e._id]||r.hasThinInstances),p=this._camera||n.activeCamera;if(this.isReady(e,d)&&p){let t,l;e._renderId=n.getRenderId();let h=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[a.currentRenderPassId],u=e._getDrawWrapper();!u&&h&&(u=h._getDrawWrapper());let _=p.mode===rj.V.ORTHOGRAPHIC_CAMERA;if(!u)return;let f=u.effect;if(a.enableEffect(u),d||r._bind(e,f,o.fillMode),h?h.bindForSubMesh(s.getWorldMatrix(),s,e):(f.setMatrix("viewProjection",n.getTransformMatrix()),f.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&f.setMatrix("view",n.getViewMatrix())),_?(t=!a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1):(t=a.useReverseDepthBuffer&&a.isNDCHalfZRange?p.minZ:a.isNDCHalfZRange?0:p.minZ,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:p.maxZ),f.setFloat2("depthValues",t,t+l),!h){if(o.needAlphaTesting()){let e=o.getAlphaTestTexture();e&&(f.setTexture("diffuseSampler",e),f.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){let e=r.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(r);if(!t)return;f.setTexture("boneSampler",t),f.setFloat("boneTextureWidth",4*(e.bones.length+1))}else f.setMatrices("mBones",e.getTransformMatrices(r))}(0,nX.an)(f,o,n),so.G.BindMorphTargetParameters(r,f),r.morphTargetManager&&r.morphTargetManager.isUsingTextureForTargets&&r.morphTargetManager._bind(f)}r._processRendering(s,e,f,o.fillMode,c,d,(e,t)=>f.setMatrix("world",t))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s4&&(h.push(rz.o.MatricesIndicesExtraKind),h.push(rz.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));let t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");let u=s.morphTargetManager,c=0;u&&u.numInfluencers>0&&(c=u.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+c),u.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(h,s,c)),t&&(l.push("#define INSTANCES"),so.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),(0,nX.lK)(o,n,l);let d=e._getDrawWrapper(void 0,!0),p=d.defines,_=l.join("\n");if(p!==_){let e=["world","mBones","boneTextureWidth","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,nX.qx)(e),d.setEffect(r.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer){let i=this._scene._depthRenderer[t];i===this&&e.push(t)}if(e.length>0)for(let t of(this._depthMap.dispose(),e))delete this._scene._depthRenderer[t]}};DepthRenderer._SceneComponentInitialization=e=>{throw(0,r$.S)("DepthRendererSceneComponent")};let lf=`varying vec2 vUV;uniform sampler2D textureSampler; -#if defined(INITIAL) -uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); -#ifdef DEPTH_REDUX -float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); -#else -float maxz=max(max(max(f1,f2),f3),f4); -#endif -glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(MAIN) -uniform vec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(ONEBEFORELAST) -uniform ivec2 texSize;void main(void) -{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} -#elif defined(LAST) -void main(void) -{glFragColor=vec4(0.);if (true) { -discard;}} -#endif -`;s_.v.ShadersStore.minmaxReduxPixelShader=lf;let MinMaxReducer=class MinMaxReducer{constructor(e){this.onAfterReductionPerformed=new rf.y$,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new sx.O(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){var s,n,a,o;if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;let l=this._camera.getScene(),h=new postProcess_PostProcess("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,l.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);h.autoClear=!1,h.forceFullscreenViewport=r;let u=this._sourceTexture.getRenderWidth(),c=this._sourceTexture.getRenderHeight();h.onApply=(s=u,n=c,e=>{e.setTexture("sourceTexture",this._sourceTexture),e.setFloat2("texSize",s,n)}),this._reductionSteps.push(h);let d=1;for(;u>1||c>1;){u=Math.max(Math.round(u/2),1),c=Math.max(Math.round(c/2),1);let e=new postProcess_PostProcess("Reduction phase "+d,"minmaxRedux",["texSize"],null,{width:u,height:c},null,1,l.getEngine(),!1,"#define "+(1==u&&1==c?"LAST":1==u||1==c?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=(a=u,o=c,e=>{1==a||1==o?e.setInt2("texSize",a,o):e.setFloat2("texSize",a,o)}),this._reductionSteps.push(e),d++,1==u&&1==c){let func=(e,t,i)=>{let r=new Float32Array(4*e*t),s={min:0,max:0};return()=>{l.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),s.min=r[0],s.max=r[1],this.onAfterReductionPerformed.notifyObservers(s)}};e.onAfterRenderObservable.add(func(u,c,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var e,t;let i=this._camera.getScene().getEngine();null===(e=i._debugPushGroup)||void 0===e||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),null===(t=i._debugPopGroup)||void 0===t||t.call(i,1)}),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return CascadedShadowGenerator.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),(t!=this._minDistance||i!=this._maxDistance)&&this.setMinMaxDistance(t,i)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return null!==(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)&&void 0!==i?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(null===(t=this._depthReducer)||void 0===t?void 0:t.depthRenderer)&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,n=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,a=t+s*r,o=t+n*r,l=o-a,h=o/a;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==shadowGenerator_ShadowGenerator.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light,r=this._scene;if(!r.shadowsEnabled||!i.shadowEnabled)return;let s=this._getCamera();if(!s)return;let n=this.getShadowMap();if(!n)return;let a=n.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===shadowGenerator_ShadowGenerator.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,n),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),a,1/a,this.frustumEdgeFalloff,e);else if(this._filter===shadowGenerator_ShadowGenerator.FILTER_PCSS){for(let e=0;enew CascadedShadowGenerator(e,t,void 0,i));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}};CascadedShadowGenerator._FrustumCornersNDCSpace=[new rm.P(-1,1,-1),new rm.P(1,1,-1),new rm.P(1,-1,-1),new rm.P(-1,-1,-1),new rm.P(-1,1,1),new rm.P(1,1,1),new rm.P(1,-1,1),new rm.P(-1,-1,1)],CascadedShadowGenerator.CLASSNAME="CascadedShadowGenerator",CascadedShadowGenerator.DEFAULT_CASCADES_COUNT=4,CascadedShadowGenerator.MIN_CASCADES_COUNT=2,CascadedShadowGenerator.MAX_CASCADES_COUNT=4,CascadedShadowGenerator._SceneComponentInitialization=e=>{throw(0,r$.S)("ShadowGeneratorSceneComponent")},rp.p.AddParser(rQ.l.NAME_SHADOWGENERATOR,(e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i{let t=e._getComponent(rQ.l.NAME_SHADOWGENERATOR);t||(t=new ShadowGeneratorSceneComponent(e),e._addComponent(t))},ry.N.AddNodeConstructor("Light_Type_0",(e,t)=>()=>new PointLight(e,rm.P.Zero(),t));let PointLight=class PointLight extends ShadowLight{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){let e=t.value;e.recreateShadowMap()}}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return light_Light.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new rm.P(1,0,0);case 1:return new rm.P(-1,0,0);case 2:return new rm.P(0,-1,0);case 3:return new rm.P(0,1,0);case 4:return new rm.P(0,0,1);case 5:return new rm.P(0,0,-1)}return rm.P.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;let s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;rm.y3.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:s,a?s: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}};(0,rH.gn)([(0,rb.qC)()],PointLight.prototype,"shadowAngle",null);let DefaultLoadingScreen=class DefaultLoadingScreen{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{let e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";let e=`@-webkit-keyframes spin1 {\ - 0% { -webkit-transform: rotate(0deg);} - 100% { -webkit-transform: rotate(360deg);} - }\ - @keyframes spin1 {\ - 0% { transform: rotate(0deg);} - 100% { transform: rotate(360deg);} - }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);let t=!!window.SVGSVGElement,i=new Image;DefaultLoadingScreen.DefaultLogoUrl?i.src=DefaultLoadingScreen.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";let r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";let s=new Image;if(DefaultLoadingScreen.DefaultSpinnerUrl?s.src=DefaultLoadingScreen.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!t){let e={w:16,h:18.5},t={w:30,h:30};i.style.width=`${e.w}vh`,i.style.height=`${e.h}vh`,i.style.left=`calc(50% - ${e.w/2}vh)`,i.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${t.w}vh`,s.style.height=`${t.h}vh`,s.style.left=`calc(50% - ${t.w/2}vh)`,s.style.top=`calc(50% - ${t.h/2}vh)`}r.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}};DefaultLoadingScreen.DefaultLogoUrl="",DefaultLoadingScreen.DefaultSpinnerUrl="",rq.D.DefaultLoadingScreenFactory=e=>new DefaultLoadingScreen(e);var lS=i(1687),lC=i(5461);let PanoramaToCubeMapTools=class PanoramaToCubeMapTools{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";let n=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),a=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),o=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s),l=this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),h=this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),u=this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s);return{front:n,back:a,left:o,right:l,up:h,down:u,size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,n=!1){let a=new ArrayBuffer(e*e*12),o=new Float32Array(a),l=n?Math.max(1,Math.round(r/4/e)):1,h=1/l,u=h*h,c=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),p=1/e,_=0;for(let n=0;nMath.PI;)s-=2*Math.PI;let a=s/Math.PI,o=Math.round((a=.5*a+.5)*i);o<0?o=0:o>=i&&(o=i-1);let l=Math.round(n/Math.PI*r);l<0?l=0:l>=r&&(l=r-1);let h=r-l-1,u=t[h*i*3+3*o+0],c=t[h*i*3+3*o+1],d=t[h*i*3+3*o+2];return{r:u,g:c,b:d}}};PanoramaToCubeMapTools.FACE_LEFT=[new rm.P(-1,-1,-1),new rm.P(1,-1,-1),new rm.P(-1,1,-1),new rm.P(1,1,-1)],PanoramaToCubeMapTools.FACE_RIGHT=[new rm.P(1,-1,1),new rm.P(-1,-1,1),new rm.P(1,1,1),new rm.P(-1,1,1)],PanoramaToCubeMapTools.FACE_FRONT=[new rm.P(1,-1,-1),new rm.P(1,-1,1),new rm.P(1,1,-1),new rm.P(1,1,1)],PanoramaToCubeMapTools.FACE_BACK=[new rm.P(-1,-1,1),new rm.P(-1,-1,-1),new rm.P(-1,1,1),new rm.P(-1,1,-1)],PanoramaToCubeMapTools.FACE_DOWN=[new rm.P(1,1,-1),new rm.P(1,1,1),new rm.P(-1,1,-1),new rm.P(-1,1,1)],PanoramaToCubeMapTools.FACE_UP=[new rm.P(-1,-1,-1),new rm.P(-1,-1,1),new rm.P(1,-1,-1),new rm.P(1,-1,1)];let HDRTools=class HDRTools{static _Ldexp(e,t){return t>1023?898846567431158e293*e*Math.pow(2,t-1023):t<-1074?5e-324*e*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,r,s,n){s>0?(s=this._Ldexp(1,s-136),e[n+0]=t*s,e[n+1]=i*s,e[n+2]=r*s):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",r="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:a+=r.length+1}}static GetCubeMapTextureData(e,t,i=!1){let r=new Uint8Array(e),s=this.RGBE_ReadHeader(r),n=this.RGBE_ReadPixels(r,s),a=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(n,s.width,s.height,t,i);return a}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i,r,s,n,a,o=t.height,l=t.width,h=t.dataPosition,u=0,c=0,d=0,p=new ArrayBuffer(4*l),_=new Uint8Array(p),f=new ArrayBuffer(t.width*t.height*12),m=new Float32Array(f);for(;o>0;){if(i=e[h++],r=e[h++],s=e[h++],n=e[h++],2!=i||2!=r||128&s||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((s<<8|n)!=l)throw"HDR Bad header format, wrong scan line width";for(d=0,u=0;d<4;d++)for(c=(d+1)*l;u128){if(0==(a=i-128)||a>c-u)throw"HDR Bad Format, bad scanline data (run)";for(;a-- >0;)_[u++]=r}else{if(0==(a=i)||a>c-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=r,--a>0)for(let t=0;t0;){for(a=0;a -#include -#include -#include -uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;s_.v.ShadersStore.hdrFilteringPixelShader=lb;let HDRFiltering=class HDRFiltering{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);let i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){let t=e.getSize().width,i=rE.R.ILog2(t)+1,r=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();let n=e.getInternalTexture();n&&this._engine.updateTextureSamplingMode(3,n,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let a=[[new rm.P(0,0,-1),new rm.P(0,-1,0),new rm.P(1,0,0)],[new rm.P(0,0,1),new rm.P(0,-1,0),new rm.P(-1,0,0)],[new rm.P(1,0,0),new rm.P(0,0,1),new rm.P(0,1,0)],[new rm.P(1,0,0),new rm.P(0,0,-1),new rm.P(0,-1,0)],[new rm.P(1,0,0),new rm.P(0,-1,0),new rm.P(0,0,1)],[new rm.P(-1,0,0),new rm.P(0,-1,0),new rm.P(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",a[e][0]),r.setVector3("right",a[e][1]),r.setVector3("front",a[e][2]);for(let n=0;n{this._effectRenderer=new EffectRenderer(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(rT.Y.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}};let hdrCubeTexture_HDRCubeTexture=class hdrCubeTexture_HDRCubeTexture extends baseTexture_BaseTexture{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(rm.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,n=!1,a=!1,o=null,l=null,h=!1){var u;if(super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=rm.P.Zero(),this.onLoadObservable=new rf.y$,!e)return;this._coordinatesMode=texture_Texture.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=rm.y3.Identity(),this._prefilterOnLoad=a,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),o&&o()},this._onError=l,this.gammaSpace=n,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?rW.w1.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(null===(u=this.getScene())||void 0===u?void 0:u.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture()}getClassName(){return"HDRCubeTexture"}_loadTexture(){let e=this._getEngine(),t=e.getCaps(),i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){let t=this._onLoad,i=new HDRFiltering(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;let t=HDRTools.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){let e=CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}let r=[],s=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));let a=t[hdrCubeTexture_HDRCubeTexture._FacesMapping[e]];if(this.gammaSpace||n||s){for(let e=0;e255){let e=255/n;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}}n?r.push(n):s?r.push(s):r.push(a)}return r},null,this._onLoad,this._onError)}clone(){let e=new hdrCubeTexture_HDRCubeTexture(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let r=null;return e.name&&!e.isRenderTarget&&((r=new hdrCubeTexture_HDRCubeTexture(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=rm.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=rm.P.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}};hdrCubeTexture_HDRCubeTexture._FacesMapping=["right","left","up","down","front","back"],(0,rv.H)("BABYLON.HDRCubeTexture",hdrCubeTexture_HDRCubeTexture);let MorphTarget=class MorphTarget{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let 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,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new rf.y$,this._onDataLayoutChanged=new rf.y$,this._animationPropertiesOverride=null,this._scene=i||rS.l.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){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){let e=rb.p4.Clone(()=>new MorphTarget(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(){let 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())),rb.p4.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){let i=new MorphTarget(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=[],this._targetInfluenceChangedObservers=[],this._targetDataLayoutChangedObservers=[],this._activeTargets=new sp.t(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=[],this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,e||(e=rS.l.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}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(){var e;return morphTargetManager_MorphTargetManager.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(null===(e=this._scene)||void 0===e?void 0:e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}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){let 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)}clone(){let e=new morphTargetManager_MorphTargetManager(this._scene);for(let t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){let e={};for(let t of(e.id=this.uniqueId,e.targets=[],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 i=-1;for(let e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;let r=e.getPositions();if(r){let e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e){rT.Y.Error("Incompatible target. Targets must all have the same vertices count.");return}}}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;ee&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){let 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();let e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4),i=0;for(let r=0;r-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new morphTargetManager_MorphTargetManager(t);for(let r of(i._uniqueId=e.id,e.targets))i.addTarget(MorphTarget.Parse(r,t));return i}};morphTargetManager_MorphTargetManager.EnableTextureStorage=!0,morphTargetManager_MorphTargetManager.MaxActiveMorphTargetsInVertexAttributeMode=8;let PhysicsRaycastResult=class PhysicsRaycastResult{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=rm.P.Zero(),this._hitPointWorld=rm.P.Zero(),this._rayFromWorld=rm.P.Zero(),this._rayToWorld=rm.P.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=null!=i?i:-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=rm.P.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=rm.P.Zero(),t=rm.P.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0}};let PhysicsEngine=class PhysicsEngine{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,r$.S)("CannonJSPlugin")}constructor(e,t=PhysicsEngine.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new rm.P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach(function(e){e.dispose()}),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){let t=this._impostors.indexOf(e);if(t>-1){let i=this._impostors.splice(t,1);i.length&&this.getPhysicsPlugin().removePhysicsBody(e)}}addJoint(e,t,i){let r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){let r=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach(e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)}),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e);if(!t){rT.Y.Warn("It was not possible to create a physics body for this object.");return}let i=e.physicsBody;i&&this.removePhysicsBody(e);let r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},n=e.getParam("nativeOptions");for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(s[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(t){let r=i[t];e.physicsBody[t].set(r.x,r.y,r.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){let processMesh=t=>{if(!t.rotationQuaternion)return;let i=t.getPhysicsImpostor();if(i){let r=i.parent;if(r!==e&&t.parent){let r=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);i.physicsBody&&(this.removePhysicsBody(i),i.physicsBody=null),i.parent=e,i.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(i),new this.BJSCANNON.Vec3(r.x,r.y,r.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=i.getParam("mass")}}t.getChildMeshes(!0).filter(e=>!!e.physicsImpostor).forEach(processMesh)};t.filter(e=>!!e.physicsImpostor).forEach(processMesh)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case PhysicsJoint.HingeJoint:case PhysicsJoint.Hinge2Joint:t=new this.BJSCANNON.HingeConstraint(i,r,n);break;case PhysicsJoint.DistanceJoint:t=new this.BJSCANNON.DistanceConstraint(i,r,s.maxDistance||2);break;case PhysicsJoint.SpringJoint:t=new this.BJSCANNON.Spring(i,r,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break;case PhysicsJoint.LockJoint:t=new this.BJSCANNON.LockConstraint(i,r,n);break;case PhysicsJoint.PointToPointJoint:case PhysicsJoint.BallAndSocketJoint:default:t=new this.BJSCANNON.PointToPointConstraint(i,n.pivotA,r,n.pivotB,n.maxForce)}t.collideConnected=!!s.collision,e.joint.physicsJoint=t,e.joint.type!==PhysicsJoint.SpringJoint?this.world.addConstraint(t):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){t.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==PhysicsJoint.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r1e3*i));e++);this.time+=r;let o=this.time%i,l=o/i,h=this.bodies;for(let i=0;i!==h.length;i++){let r=h[i];r.type!==t.Body.STATIC&&r.sleepState!==t.Body.SLEEPING?(r.position.vsub(r.previousPosition,e),e.scale(l,e),r.position.vadd(e,r.interpolatedPosition)):(r.interpolatedPosition.set(r.position.x,r.position.y,r.position.z),r.interpolatedQuaternion.set(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}};PhysicsEngine.DefaultPluginFactory=()=>new CannonJSPlugin;let OimoJSPlugin=class OimoJSPlugin{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=rm.P.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new PhysicsRaycastResult}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach(function(e){e.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e});let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}let e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];if(!e||!t){i=i.next;continue}e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){let r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){rT.Y.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){var t;let i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach(function(e){e.physicsImpostor&&r.push(e.physicsImpostor)});let checkWithEpsilon=e=>Math.max(e,rw.kn),s=new rm._f;r.forEach(t=>{if(!t.object.rotationQuaternion)return;let r=t.object.rotationQuaternion;s.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);let n=s.toEulerAngles(),a=t.getObjectExtents();if(t===e){let t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{let e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(57.29577951308232*n.x,57.29577951308232*n.y,57.29577951308232*n.z)}switch(t.object.rotationQuaternion.copyFrom(s),t.type){case physicsImpostor_PhysicsImpostor.ParticleImpostor:rT.Y.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case physicsImpostor_PhysicsImpostor.SphereImpostor:{let e=a.x,t=a.y,r=a.z,s=Math.max(checkWithEpsilon(e),checkWithEpsilon(t),checkWithEpsilon(r))/2;i.type.push("sphere"),i.size.push(s),i.size.push(s),i.size.push(s);break}case physicsImpostor_PhysicsImpostor.CylinderImpostor:{let e=checkWithEpsilon(a.x)/2,t=checkWithEpsilon(a.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case physicsImpostor_PhysicsImpostor.PlaneImpostor:case physicsImpostor_PhysicsImpostor.BoxImpostor:default:{let e=checkWithEpsilon(a.x),t=checkWithEpsilon(a.y),r=checkWithEpsilon(a.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r)}}t.object.rotationQuaternion=r}),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(s),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n=s.nativeParams||{},a={body1:i,body2:r,axe1:n.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:n.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:n.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:n.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:n.min,max:n.max,collision:n.collision||s.collision,spring:n.spring,world:this.world};switch(e.joint.type){case PhysicsJoint.BallAndSocketJoint:t="jointBall";break;case PhysicsJoint.SpringJoint:rT.Y.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"),a.min=s.length||a.min,a.max=Math.max(a.min,a.max);case PhysicsJoint.DistanceJoint:t="jointDistance",a.max=s.maxDistance;break;case PhysicsJoint.PrismaticJoint:t="jointPrisme";break;case PhysicsJoint.SliderJoint:t="jointSlide";break;case PhysicsJoint.WheelJoint:t="jointWheel";break;case PhysicsJoint.HingeJoint:default:t="jointHinge"}a.type=t,e.joint.physicsJoint=this.world.add(a)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){rT.Y.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{let t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){let t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.linearVelocity;return t?new rm.P(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new rm.P(t.x,t.y,t.z):null}setBodyMass(e,t){let i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?rT.Y.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){let i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){let i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return rT.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){rT.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}};let AmmoJSPlugin=class AmmoJSPlugin{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new rm._f,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new rm.P,this._tmpContactNormal=new rm.P,this._tmpVec3=new rm.P,this._tmpMatrix=new rm.y3,"function"==typeof t){rT.Y.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}if(this.bjsAMMO=t,!this.isSupported()){rT.Y.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint);let t=e.getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new PhysicsRaycastResult,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(i))for(let e of i._onPhysicsCollideCallbacks)for(let t of e.otherImpostors)(i.physicsBody.isActive()||t.physicsBody.isActive())&&this._isImpostorPairInContact(i,t)&&(i.onCollide({body:t.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),t.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===physicsImpostor_PhysicsImpostor.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){let t,i,r,s;let n=e.physicsBody.get_m_nodes(),a=n.size(),o=[];for(let e=0;e{this.bjsAMMO.destroy(e)}),e._pluginData.toDispose=[]))}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData;switch(s.mainPivot||(s.mainPivot=new rm.P(0,0,0)),s.connectedPivot||(s.connectedPivot=new rm.P(0,0,0)),e.joint.type){case PhysicsJoint.DistanceJoint:{let e=s.maxDistance;e&&(s.mainPivot=new rm.P(0,-e/2,0),s.connectedPivot=new rm.P(0,e/2,0)),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case PhysicsJoint.HingeJoint:{s.mainAxis||(s.mainAxis=new rm.P(0,0,0)),s.connectedAxis||(s.connectedAxis=new rm.P(0,0,0));let e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),n=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);t=new this.bjsAMMO.btHingeConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,n);break}case PhysicsJoint.BallAndSocketJoint:t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:rT.Y.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(t,!e.joint.jointData.collision),e.joint.physicsJoint=t}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s,n=i.getIndices();n||(n=[]);let a=i.getVerticesData(rz.o.PositionKind);if(a||(a=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?rm._f.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):rm._f.Identity();let r=rm.y3.Compose(rm.P.One(),e,t.position);r.invertToRef(this._tmpMatrix);let n=i.computeWorldMatrix(!1);s=n.multiply(this._tmpMatrix)}else rm.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),s=this._tmpMatrix;let o=n.length/3;for(let t=0;t{r+=this._addMeshVerts(e,t,i)})}return r}_softVertexData(e){let t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(rz.o.PositionKind);i||(i=[]);let r=t.getVerticesData(rz.o.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);let s=[],n=[];for(let e=0;ee*e),o=a.reduce((e,t)=>e+t);if(0===o)i=(t=s.length)/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;let r=e.getParam("path"),s=e.getParam("shape");if(null===s)return rT.Y.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;i=(t=r.length)-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let l=e.getParam("fixedPoints");l=l>3?3:l;let h=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,l);return h.get_m_cfg().set_collisions(17),h}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n=i.getVerticesData(rz.o.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);let a=s.length/3;for(let t=0;t{r+=this._addHullVerts(e,t,i)})}return r}_createShape(e,t=!1){let i;let r=e.object,s=e.getObjectExtents();if(!t){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];i=new this.bjsAMMO.btCompoundShape;let r=0;if(t.forEach(e=>{let t=e.getPhysicsImpostor();if(t){if(t.type==physicsImpostor_PhysicsImpostor.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";let s=this._createShape(t),n=e.parent.getWorldMatrix().clone(),a=new rm.P;n.decompose(a),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*a.x,e.position.y*a.y,e.position.z*a.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,s),t.dispose(),r++}}),r>0){if(e.type!=physicsImpostor_PhysicsImpostor.NoImpostor){let t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,t))}return i}this.bjsAMMO.destroy(i),i=null}switch(e.type){case physicsImpostor_PhysicsImpostor.SphereImpostor:if(rE.R.WithinEpsilon(s.x,s.y,1e-4)&&rE.R.WithinEpsilon(s.x,s.z,1e-4))i=new this.bjsAMMO.btSphereShape(s.x/2);else{let e=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(e,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case physicsImpostor_PhysicsImpostor.CapsuleImpostor:{let e=s.x/2;i=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case physicsImpostor_PhysicsImpostor.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case physicsImpostor_PhysicsImpostor.PlaneImpostor:case physicsImpostor_PhysicsImpostor.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case physicsImpostor_PhysicsImpostor.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)i=this.onCreateCustomMeshImpostor(e);else{let t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t);let s=this._addMeshVerts(t,r,r);i=0==s?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case physicsImpostor_PhysicsImpostor.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)i=this.onCreateCustomConvexHullImpostor(e);else{let t=new this.bjsAMMO.btConvexHullShape,s=this._addHullVerts(t,r,r);0==s?(e._pluginData.toDispose.push(t),i=new this.bjsAMMO.btCompoundShape):i=t}break;case physicsImpostor_PhysicsImpostor.NoImpostor:i=new this.bjsAMMO.btSphereShape(s.x/2);break;case physicsImpostor_PhysicsImpostor.CustomImpostor:i=this._createCustom(e);break;case physicsImpostor_PhysicsImpostor.SoftbodyImpostor:i=this._createSoftbody(e);break;case physicsImpostor_PhysicsImpostor.ClothImpostor:i=this._createCloth(e);break;case physicsImpostor_PhysicsImpostor.RopeImpostor:i=this._createRope(e);break;default:rT.Y.Warn("The impostor type is not currently supported by the ammo plugin.")}return i}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>rw.kn||Math.abs(r.getOrigin().y()-t.y)>rw.kn||Math.abs(r.getOrigin().z()-t.z)>rw.kn||Math.abs(r.getRotation().x()-i.x)>rw.kn||Math.abs(r.getRotation().y()-i.y)>rw.kn||Math.abs(r.getRotation().z()-i.z)>rw.kn||Math.abs(r.getRotation().w()-i.w)>rw.kn){if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){let t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(!(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity()))return null;let i=new rm.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(!(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity()))return null;let i=new rm.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(rT.Y.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===physicsImpostor_PhysicsImpostor.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):rT.Y.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(rT.Y.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):rT.Y.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(rT.Y.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):rT.Y.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(rT.Y.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):rT.Y.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,n=!1){let a=e.segments;e.physicsBody.appendAnchor(Math.round((a-1)*i)+a*(a-1-Math.round((a-1)*r)),t.physicsBody,n,s)}appendHook(e,t,i,r=1,s=!1){let n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){rT.Y.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){rT.Y.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){let i=t.physicsBody;i.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){let t=e.getObjectExtents();return t.x/2}getBoxSizeToRef(e,t){let i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);let r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}};AmmoJSPlugin._DISABLE_COLLISION_FLAG=4,AmmoJSPlugin._KINEMATIC_FLAG=2,AmmoJSPlugin._DISABLE_DEACTIVATION_FLAG=4,rp.p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return -1;let t=this.reflectionProbes.indexOf(e);return -1!==t&&this.reflectionProbes.splice(t,1),t},rp.p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};let reflectionProbe_ReflectionProbe=class reflectionProbe_ReflectionProbe{constructor(e,t,i,r=!0,s=!1,n=!1){let a;if(this.name=e,this._viewMatrix=rm.y3.Identity(),this._target=rm.P.Zero(),this._add=rm.P.Zero(),this._invertYAxis=!1,this.position=rm.P.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){let e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new renderTargetTexture_RenderTargetTexture(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;let l=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);let t=i.useRightHandedSystem?rm.y3.LookAtRHToRef:rm.y3.LookAtLHToRef,r=i.useRightHandedSystem?rm.y3.PerspectiveFovRH:rm.y3.PerspectiveFovLH;t(this.position,this._target,rm.P.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position}),this._renderTargetTexture.onBeforeBindObservable.add(()=>{var t,r;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(r=(t=i.getEngine())._debugPushGroup)||void 0===r||r.call(t,`reflection probe generation for ${e}`,1),a=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=a,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),null===(t=(e=i.getEngine())._debugPopGroup)||void 0===t||t.call(e,1)})}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){let e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){let e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){let e=rb.p4.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;ir||new reflectionProbe_ReflectionProbe(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i)).cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}};(0,rH.gn)([(0,rb.RR)()],reflectionProbe_ReflectionProbe.prototype,"_attachedMesh",void 0),(0,rH.gn)([(0,rb.hd)()],reflectionProbe_ReflectionProbe.prototype,"position",void 0);let BabylonFileLoaderConfiguration=class BabylonFileLoaderConfiguration{};BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine=void 0;let ly={},lP={},parseMaterialByPredicate=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,n=t.materials.length;s{for(let r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},logOperation=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),loadDetailLevels=(e,t)=>{if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){let i=t._waitingData.lods.ids,r=t.isEnabled(!1);if(t._waitingData.lods.distances){let s=t._waitingData.lods.distances;if(s.length>=i.length){let n=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let r=0;r0&&t.addLODLevel(n,null),!0===r&&t.setEnabled(!0)}else rW.w1.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},findParent=(e,t,i)=>{if("number"!=typeof e){let r=i.getLastEntryById(e);if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r}let r=ly[e];if(r&&null!=t){let e=r.instances[parseInt(t)];return e}return r},findMaterial=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):lP[e],loadAssetContainer=(e,t,i,r,s=!1)=>{let n=new AssetContainer(e),a="importScene has failed JSON parse";try{let r,s;var o=JSON.parse(t);a="";let l=sceneLoader_SceneLoader.loggingLevel===sceneLoader_SceneLoader.DETAILED_LOGGING;if(void 0!==o.environmentTexture&&null!==o.environmentTexture){let t=void 0===o.isPBR||o.isPBR;if(o.environmentTextureType&&"BABYLON.HDRCubeTexture"===o.environmentTextureType){let r=o.environmentTextureSize?o.environmentTextureSize:128,s=new hdrCubeTexture_HDRCubeTexture((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,r,!0,!t,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(s.rotationY=o.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof o.environmentTexture){let t=cubeTexture_CubeTexture.Parse(o.environmentTexture,e,i);e.environmentTexture=t}else if(o.environmentTexture.endsWith(".env")){let t=new cubeTexture_CubeTexture((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}else{let t=cubeTexture_CubeTexture.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}if(!0===o.createDefaultSkybox){let i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=o.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}n.environmentTexture=e.environmentTexture}if(void 0!==o.environmentIntensity&&null!==o.environmentIntensity&&(e.environmentIntensity=o.environmentIntensity),void 0!==o.lights&&null!==o.lights)for(r=0,s=o.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})}}if(void 0!==o.multiMaterials&&null!==o.multiMaterials)for(r=0,s=o.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})}if(void 0!==o.morphTargetManagers&&null!==o.morphTargetManagers)for(let t of o.morphTargetManagers){let i=morphTargetManager_MorphTargetManager.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==o.skeletons&&null!==o.skeletons)for(r=0,s=o.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)})}if(void 0!==o.transformNodes&&null!==o.transformNodes)for(r=0,s=o.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach(i=>{t.subMaterials.push(findMaterial(i,e))}),t._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(t=>{null!==t._waitingMaterialId&&(t.material=findMaterial(t._waitingMaterialId,e),t._waitingMaterialId=null)}),r=0,s=e.skeletons.length;r{if(t._waitingTransformNodeId){let i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}}),t._hasWaitingData=null)}for(r=0,s=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""}),rp.p.Parse(o,e,n,i),r=0,s=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,n,a,o)=>{var l;let h="importMesh has failed JSON parse";try{var u=JSON.parse(i);h="";let o=sceneLoader_SceneLoader.loggingLevel===sceneLoader_SceneLoader.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;let c=[],d=new Map,p=[];if(void 0!==u.transformNodes&&null!==u.transformNodes)for(let e=0,i=u.transformNodes.length;e{!0!==e&&u.geometries[i]&&Array.isArray(u.geometries[i])&&u.geometries[i].forEach(s=>{s.id===l.geometryId&&("vertexData"===i&&lS.Z.Parse(s,t,r),e=!0)})}),!1===e&&rT.Y.Warn("Geometry not found for mesh "+l.id)}if(l.materialUniqueId||l.materialId){let e=l.materialUniqueId?f:_,i=-1!==e.indexOf(l.materialUniqueId||l.materialId);if(!1===i&&void 0!==u.multiMaterials&&null!==u.multiMaterials){let loadSubMaterial=(i,s)=>{e.push(i);let n=parseMaterialByPredicate(s,u,t,r);n&&n.material&&(lP[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,h+="\n Material "+n.material.toString(o))};for(let r=0,s=u.multiMaterials.length;rloadSubMaterial(e,t=>t.uniqueId===e)):s.materials.forEach(e=>loadSubMaterial(e,t=>t.id===e)),e.push(s.uniqueId||s.id);let r=lC.G.ParseMultiMaterial(s,t);lP[s.uniqueId||s.id]=r,r&&(i=!0,h+="\n Multi-Material "+r.toString(o));break}}}if(!1===i){e.push(l.materialUniqueId||l.materialId);let i=parseMaterialByPredicate(e=>l.materialUniqueId&&e.uniqueId===l.materialUniqueId||e.id===l.materialId,u,t,r);i&&i.material?(lP[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,h+="\n Material "+i.material.toString(o)):rT.Y.Warn("Material not found for mesh "+l.id)}}if(null!==l.skeletonId&&void 0!==l.skeletonId&&-1!==u.skeletonId&&void 0!==u.skeletons&&null!==u.skeletons){let e=n.indexOf(l.skeletonId)>-1;if(!e)for(let e=0,i=u.skeletons.length;e-1&&void 0!==u.morphTargetManagers&&null!==u.morphTargetManagers){let e=m.indexOf(l.morphTargetManagerId)>-1;if(!e)for(let e=0,i=u.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach(i=>{e.subMaterials.push(findMaterial(i,t))}),e._waitingSubMaterialsUniqueIds=[]}),t.meshes.forEach(e=>{null!==e._waitingMaterialId&&(e.material=findMaterial(e._waitingMaterialId,t),e._waitingMaterialId=null)});for(let e=0,i=t.transformNodes.length;e-1&&p.splice(e,1)}i._waitingParentId=null}i._waitingData.lods&&loadDetailLevels(t,i)}for(let e of p)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){let i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}}),i._hasWaitingData=null)}for(let e=0,r=t.meshes.length;e{e._loadedUniqueId=""}),!0}catch(t){let e=logOperation("importMesh",u?u.producer:"Unknown")+h;if(o)o(e,t);else throw rT.Y.Log(e),t}finally{null!==h&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&rT.Y.Log(logOperation("importMesh",u?u.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?h:"")),lP={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var n=JSON.parse(t);if(s="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!sceneLoader_SceneLoader.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=rg.HE.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=rg.Wo.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=rm.P.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),n.fogMode&&0!==n.fogMode)switch(e.fogMode=n.fogMode,e.fogColor=rg.Wo.FromArray(n.fogColor),e.fogStart=n.fogStart,e.fogEnd=n.fogEnd,e.fogDensity=n.fogDensity,s+=" Fog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===CannonJSPlugin.name?t=new CannonJSPlugin(void 0,void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===OimoJSPlugin.name?t=new OimoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine):("ammo"===n.physicsEngine||n.physicsEngine===AmmoJSPlugin.name)&&(t=new AmmoJSPlugin(void 0,BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";let i=n.physicsGravity?rm.P.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled);let a=loadAssetContainer(e,t,i,r,!0);if(!a)return!1;return n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0}catch(t){let e=logOperation("importScene",n?n.producer:"Unknown")+s;if(r)r(e,t);else throw rT.Y.Log(e),t}finally{null!==s&&sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.NO_LOGGING&&rT.Y.Log(logOperation("importScene",n?n.producer:"Unknown")+(sceneLoader_SceneLoader.loggingLevel!==sceneLoader_SceneLoader.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>{let s=loadAssetContainer(e,t,i,r);return s}}),i(9087);let FresnelParameters=class FresnelParameters{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,rq.D.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||rg.Wo.White(),this.rightColor=e.rightColor||rg.Wo.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){let e=new FresnelParameters;return rC.j.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new FresnelParameters({isEnabled:e.isEnabled,leftColor:rg.Wo.FromArray(e.leftColor),rightColor:rg.Wo.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}};rb.p4._FresnelParametersParser=FresnelParameters.Parse;let PBRBaseSimpleMaterial=class PBRBaseSimpleMaterial extends pbrBaseMaterial_PBRBaseMaterial{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new rg.Wo(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}};(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],PBRBaseSimpleMaterial.prototype,"maxSimultaneousLights",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsLightsDirty")],PBRBaseSimpleMaterial.prototype,"disableLighting",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],PBRBaseSimpleMaterial.prototype,"environmentTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"invertNormalMapX",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"invertNormalMapY",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],PBRBaseSimpleMaterial.prototype,"normalTexture",void 0),(0,rH.gn)([(0,rb.n9)("emissive"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"emissiveColor",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"emissiveTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],PBRBaseSimpleMaterial.prototype,"occlusionStrength",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],PBRBaseSimpleMaterial.prototype,"occlusionTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],PBRBaseSimpleMaterial.prototype,"alphaCutOff",void 0),(0,rH.gn)([(0,rb.qC)()],PBRBaseSimpleMaterial.prototype,"doubleSided",null),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty",null)],PBRBaseSimpleMaterial.prototype,"lightmapTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRBaseSimpleMaterial.prototype,"useLightmapAsShadowmap",void 0);let PBRMetallicRoughnessMaterial=class PBRMetallicRoughnessMaterial extends PBRBaseSimpleMaterial{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){let t=rb.p4.Clone(()=>new PBRMetallicRoughnessMaterial(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){let e=rb.p4.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){let r=rb.p4.Parse(()=>new PBRMetallicRoughnessMaterial(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};(0,rH.gn)([(0,rb.n9)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],PBRMetallicRoughnessMaterial.prototype,"baseColor",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],PBRMetallicRoughnessMaterial.prototype,"baseTexture",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRMetallicRoughnessMaterial.prototype,"metallic",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],PBRMetallicRoughnessMaterial.prototype,"roughness",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],PBRMetallicRoughnessMaterial.prototype,"metallicRoughnessTexture",void 0),(0,rv.H)("BABYLON.PBRMetallicRoughnessMaterial",PBRMetallicRoughnessMaterial);let PBRSpecularGlossinessMaterial=class PBRSpecularGlossinessMaterial extends PBRBaseSimpleMaterial{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){let t=rb.p4.Clone(()=>new PBRSpecularGlossinessMaterial(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){let e=rb.p4.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){let r=rb.p4.Parse(()=>new PBRSpecularGlossinessMaterial(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}};(0,rH.gn)([(0,rb.n9)("diffuse"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],PBRSpecularGlossinessMaterial.prototype,"diffuseColor",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],PBRSpecularGlossinessMaterial.prototype,"diffuseTexture",void 0),(0,rH.gn)([(0,rb.n9)("specular"),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],PBRSpecularGlossinessMaterial.prototype,"specularColor",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_microSurface")],PBRSpecularGlossinessMaterial.prototype,"glossiness",void 0),(0,rH.gn)([(0,rb.oU)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],PBRSpecularGlossinessMaterial.prototype,"specularGlossinessTexture",void 0),(0,rv.H)("BABYLON.PBRSpecularGlossinessMaterial",PBRSpecularGlossinessMaterial);let ColorGradingTexture=class ColorGradingTexture extends baseTexture_BaseTexture{constructor(e,t,i=null){if(super(t),!e)return;if(this._textureMatrix=rm.y3.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{let e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){let e;let t=this._getEngine();e=t._features.support3DTextures?t.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=e,this._texture.isReady=!1,this.isCube=!1,this.is3D=t._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;let callback=i=>{let r;if("string"!=typeof i)return;let s=null,n=null,a=i.split("\n"),o=0,l=0,h=0,u=0,c=0;for(let e=0;e0&&(e+1)%4==0)s[e]=255;else{let t=n[e];s[e]=t/c*255}e.is3D?(e.updateSize(o,o,o),t.updateRawTexture3D(e,s,5,!1)):(e.updateSize(o*o,o),t.updateRawTexture(e,s,5,!1)),e.isReady=!0,this._triggerOnLoad()},i=this.getScene();return i?i._loadFile(this.url,callback):t._loadFile(this.url,callback),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){let e=new ColorGradingTexture(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&((i=new ColorGradingTexture(e.name,t)).name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}};ColorGradingTexture._NoneEmptyLineRegex=/\S+/,(0,rv.H)("BABYLON.ColorGradingTexture",ColorGradingTexture);let equiRectangularCubeTexture_EquiRectangularCubeTexture=class equiRectangularCubeTexture_EquiRectangularCubeTexture extends baseTexture_BaseTexture{constructor(e,t,i,r=!1,s=!0,n=null,a=null,o=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw Error("Image url is not set");this._coordinatesMode=texture_Texture.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=o,this._noMipmap=r,this.gammaSpace=s,this._onLoad=n,this._onError=a,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?rW.w1.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){let i=this.getScene();if(!i)return;let r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r;let s=document.createElement("canvas");(0,rJ.r6)(this.url,t=>{this._width=t.width,this._height=t.height,s.width=this._width,s.height=this._height;let i=s.getContext("2d");i.drawImage(t,0,0);let r=i.getImageData(0,0,t.width,t.height);this._buffer=r.data.buffer,s.remove(),e()},(e,s)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,s)},i?i.offlineProvider:null)}_loadTexture(){let e=this.getScene();if(!e)return;let t=(()=>{let e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=PanoramaToCubeMapTools.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){let r=t[equiRectangularCubeTexture_EquiRectangularCubeTexture._FacesMapping[e]];i.push(r)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){let t=new DataView(e),i=new Float32Array(3*e.byteLength/4),r=0;for(let s=0;st.length){rT.Y.Error("Unable to load TGA file - Not enough data");return}u+=c.id_length;let d=!1,p=!1,_=!1;switch(c.image_type){case 9:d=!0;case 1:p=!0;break;case 10:d=!0;case 2:break;case 11:d=!0;case 3:_=!0}let f=c.pixel_size>>3,m=c.width*c.height*f;if(p&&(r=t.subarray(u,u+=c.colormap_length*(c.colormap_size>>3))),d){let e,r,s;i=new Uint8Array(m);let n=0,a=new Uint8Array(f);for(;u>4){default:case 2:s=0,a=1,h=c.width,n=0,o=1,l=c.height;break;case 0:s=0,a=1,h=c.width,n=c.height-1,o=-1,l=-1;break;case 3:s=c.width-1,a=-1,h=-1,n=0,o=1,l=c.height;break;case 1:s=c.width-1,a=-1,h=-1,n=c.height-1,o=-1,l=-1}let g="_getImageData"+(_?"Grey":"")+c.pixel_size+"bits",v=lR[g](c,r,i,n,o,l,s,a,h),x=e.getEngine();x._uploadDataToTextureDirectly(e,v)}function _getImageData8bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+3]=255,f[(p+h*_)*4+2]=t[3*c+0],f[(p+h*_)*4+1]=t[3*c+1],f[(p+h*_)*4+0]=t[3*c+2];return f}function _getImageData16bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d+=2){c=i[d+0]+(i[d+1]<<8);let e=((31744&c)>>10)*255/31|0,t=((992&c)>>5)*255/31|0,r=(31&c)*255/31|0;f[(p+h*_)*4+0]=e,f[(p+h*_)*4+1]=t,f[(p+h*_)*4+2]=r,f[(p+h*_)*4+3]=32768&c?0:255}return f}function _getImageData24bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=3)_[(d+h*p)*4+3]=255,_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2];return _}function _getImageData32bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=4)_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2],_[(d+h*p)*4+3]=i[c+3];return _}function _getImageDataGrey8bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+0]=c,f[(p+h*_)*4+1]=c,f[(p+h*_)*4+2]=c,f[(p+h*_)*4+3]=255;return f}function _getImageDataGrey16bits(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=2)_[(d+h*p)*4+0]=i[c+0],_[(d+h*p)*4+1]=i[c+0],_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+3]=i[c+1];return _}HtmlElementTexture._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};let lR={GetTGAHeader,UploadContent,_getImageData8bits,_getImageData16bits,_getImageData24bits,_getImageData32bits,_getImageDataGrey8bits,_getImageDataGrey16bits};let _TGATextureLoader=class _TGATextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=GetTGAHeader(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{UploadContent(t,r)})}};rq.D._TextureLoaders.push(new _TGATextureLoader);let _HDRTextureLoader=class _HDRTextureLoader{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=HDRTools.RGBE_ReadHeader(r),n=HDRTools.RGBE_ReadPixels(r,s),a=s.width*s.height,o=new Float32Array(4*a);for(let e=0;e{let e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,o)})}};rq.D._TextureLoaders.push(new _HDRTextureLoader),(eM=iM||(iM={}))[eM.cTFETC1=0]="cTFETC1",eM[eM.cTFETC2=1]="cTFETC2",eM[eM.cTFBC1=2]="cTFBC1",eM[eM.cTFBC3=3]="cTFBC3",eM[eM.cTFBC4=4]="cTFBC4",eM[eM.cTFBC5=5]="cTFBC5",eM[eM.cTFBC7=6]="cTFBC7",eM[eM.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",eM[eM.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",eM[eM.cTFASTC_4x4=10]="cTFASTC_4x4",eM[eM.cTFATC_RGB=11]="cTFATC_RGB",eM[eM.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",eM[eM.cTFRGBA32=13]="cTFRGBA32",eM[eM.cTFRGB565=14]="cTFRGB565",eM[eM.cTFBGR565=15]="cTFBGR565",eM[eM.cTFRGBA4444=16]="cTFRGBA4444",eM[eM.cTFFXT1_RGB=17]="cTFFXT1_RGB",eM[eM.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",eM[eM.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",eM[eM.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",eM[eM.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11";let lA={JSModuleURL:`${rW.w1._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${rW.w1._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},lI=null,lM=null,lD=0,_CreateWorkerAsync=()=>(lI||(lI=new Promise((e,t)=>{lM?e(lM):rW.w1.LoadFileAsync(rW.w1.GetBabylonScriptURL(lA.WasmModuleURL)).then(i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");let r=URL.createObjectURL(new Blob([`(${basis_workerFunc})()`],{type:"application/javascript"}));lM=new Worker(r);let initHandler=i=>{"init"===i.data.action?(lM.removeEventListener("message",initHandler),e(lM)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};lM.addEventListener("message",initHandler),lM.postMessage({action:"init",url:rW.w1.GetBabylonScriptURL(lA.JSModuleURL),wasmBinary:i})}).catch(t)})),lI),TranscodeAsync=(e,t)=>{let i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise((e,r)=>{_CreateWorkerAsync().then(()=>{let s=lD++,messageHandler=t=>{"transcode"===t.data.action&&t.data.id===s&&(lM.removeEventListener("message",messageHandler),t.data.success?e(t.data):r("Transcode is not supported on this device"))};lM.addEventListener("message",messageHandler);let n=new Uint8Array(i.byteLength);n.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),lM.postMessage({action:"transcode",id:s,imageData:n,config:t,ignoreSupportedFormats:!1},[n.buffer])},e=>{r(e)})})},BindTexture=(e,t)=>{var i,r;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(r=t._gl)||void 0===r?void 0:r.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},LoadTextureFromTranscodeResult=(e,t)=>{let i=e.getEngine();for(let r=0;r{i._releaseTexture(t),BindTexture(e,i)})}else e._invertVScale=!e.invertY,e.width=s.width+3&-4,e.height=s.height+3&-4,e.samplingMode=2,BindTexture(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0)}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[r].levels.length>1;let n=lO.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,BindTexture(e,i),t.fileInfo.images[r].levels.forEach((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,r,s)}),i._features.basisNeedsPOT&&(rE.R.Log2(e.width)%1!=0||rE.R.Log2(e.height)%1!=0)&&(rW.w1.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=texture_Texture.CLAMP_ADDRESSMODE,e._cachedWrapV=texture_Texture.CLAMP_ADDRESSMODE)}}},lO={JSModuleURL:lA.JSModuleURL,WasmModuleURL:lA.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case iM.cTFETC1:i=36196;break;case iM.cTFBC1:i=33776;break;case iM.cTFBC4:i=33779;break;case iM.cTFASTC_4x4:i=37808;break;case iM.cTFETC2:i=37496;break;case iM.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync,LoadTextureFromTranscodeResult};function basis_workerFunc(){let e={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFRGB565:14},t=null;function GetSupportedTranscodeFormat(t,i){let r=null;return t.supportedCompressionFormats&&(r=t.supportedCompressionFormats.astc?e.cTFASTC_4x4:t.supportedCompressionFormats.bc7?e.cTFBC7:t.supportedCompressionFormats.s3tc?i.hasAlpha?e.cTFBC3:e.cTFBC1:t.supportedCompressionFormats.pvrtc?i.hasAlpha?e.cTFPVRTC1_4_RGBA:e.cTFPVRTC1_4_RGB:t.supportedCompressionFormats.etc2?e.cTFETC2:t.supportedCompressionFormats.etc1?e.cTFETC1:e.cTFRGB565),r}function GetFileInfo(e){let t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t>2&3],n[h++]=s[a>>4&3],n[h++]=s[a>>6&3]}}return n}onmessage=i=>{if("init"===i.data.action){if(!t){try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}t=BASIS({wasmBinary:i.data.wasmBinary})}null!==t&&t.then(e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})})}else if("transcode"===i.data.action){let t=i.data.config,r=i.data.imageData,s=new BASIS.BasisFile(r),n=GetFileInfo(s),a=i.data.ignoreSupportedFormats?null:GetSupportedTranscodeFormat(i.data.config,n),o=!1;null===a&&(o=!0,a=n.hasAlpha?e.cTFBC3:e.cTFBC1);let l=!0;s.startTranscoding()||(l=!1);let h=[];for(let e=0;e{let i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;LoadTextureFromTranscodeResult(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(e=>{rW.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(e)})}loadData(e,t,i){let r=t.getEngine().getCaps(),s={supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}};TranscodeAsync(e,s).then(e=>{let r=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(r.width,r.height,s,-1!==e.format,()=>{LoadTextureFromTranscodeResult(t,e)})}).catch(e=>{rW.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),rW.w1.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,()=>{},!0)})}};rq.D._TextureLoaders.push(new _BasisTextureLoader);let MultiRenderTarget=class MultiRenderTarget extends renderTargetTexture_RenderTargetTexture{get isSupported(){var e,t;return null!==(t=null===(e=this._engine)||void 0===e?void 0:e.getCaps().drawBuffersExtension)&&void 0!==t&&t}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,r,s,n,a,o,l,h){for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;let i=null===(e=this._renderTarget)||void 0===e?void 0:e.textures;if(i){for(let e=i.length-1;e>=0;e--)this._textures[e]._texture=null;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null}}};let TexturePackerFrame=class TexturePackerFrame{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}};let TexturePacker=class TexturePacker{constructor(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m;return this.name=e,this.meshes=t,this.scene=r,this.options=i,this.options.map=null!==(s=this.options.map)&&void 0!==s?s:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=null!==(n=this.options.uvsIn)&&void 0!==n?n:rz.o.UVKind,this.options.uvsOut=null!==(a=this.options.uvsOut)&&void 0!==a?a:rz.o.UVKind,this.options.layout=null!==(o=this.options.layout)&&void 0!==o?o:TexturePacker.LAYOUT_STRIP,this.options.layout===TexturePacker.LAYOUT_COLNUM&&(this.options.colnum=null!==(l=this.options.colnum)&&void 0!==l?l:8),this.options.updateInputMeshes=null===(h=this.options.updateInputMeshes)||void 0===h||h,this.options.disposeSources=null===(u=this.options.disposeSources)||void 0===u||u,this._expecting=0,this.options.fillBlanks=null===(c=this.options.fillBlanks)||void 0===c||c,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(d=this.options.customFillColor)&&void 0!==d?d:"black"),this.options.frameSize=null!==(p=this.options.frameSize)&&void 0!==p?p:256,this.options.paddingRatio=null!==(_=this.options.paddingRatio)&&void 0!==_?_:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(f=this.options.paddingMode)&&void 0!==f?f:TexturePacker.SUBUV_WRAP,this.options.paddingMode===TexturePacker.SUBUV_COLOR&&(this.options.paddingColor=null!==(m=this.options.paddingColor)&&void 0!==m?m:new rg.HE(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){let t=this._calculateSize(),i=new rm.FM(1,1).divide(t),r=0,s=this._expecting,n=this.meshes.length,a=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(o,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{r++,c.update(!1);let i=d.getImageData(0,0,h,h),n=this.sets[_],a=n.getContext();if(a.putImageData(i,t.x*p.x,t.y*p.y),c.dispose(),n.update(!1),r==s){done(),e();return}},_=a[n]||"_blank";if(u&&null!==u[_]){let e=u[_],t=new Image;e instanceof DynamicTexture?t.src=e.getContext().canvas.toDataURL("image/png"):t.src=e.url,rW.w1.SetCorsBehavior(t.src,t),t.onload=()=>{d.fillStyle="rgba(0,0,0,0)",d.fillRect(0,0,h,h),c.update(!1),d.setTransform(1,0,0,-1,0,0);let e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)d.drawImage(t,0,0,t.width,t.height,l+o*e[i],l+o*e[i+1]-h,o,o);break;case 1:for(let e=0;e{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length){e();return}let t=0,doneCheck=i=>{if(t++,this.options.map){for(let e=0;e{doneCheck(s)})}}catch(e){return t(e)}})}dispose(){let e=Object.keys(this.sets);for(let t=0;t{let i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesIndices"===e.name&&t(e));i||(i=new InputBlock("matricesIndices")).setAsAttribute("matricesIndices"),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesWeights"===e.name&&t(e));i||(i=new InputBlock("matricesWeights")).setAsAttribute("matricesWeights"),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(tC.World),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){so.G.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&so.G.PrepareDefinesForBones(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");let t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});let i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});let r=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 -`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName} * ${i}; -`,e.compilationString+=`#else -`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName}; -`,e.compilationString+=`#endif -`,this}};(0,rv.H)("BABYLON.BonesBlock",BonesBlock);let InstancesBlock=class InstancesBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Vertex),this.registerInput("world0",tm.Vector4),this.registerInput("world1",tm.Vector4),this.registerInput("world2",tm.Vector4),this.registerInput("world3",tm.Vector4),this.registerInput("world",tm.Matrix,!0),this.registerOutput("output",tm.Matrix),this.registerOutput("instanceID",tm.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world0"===e.name&&t(e));i||(i=new InputBlock("world0")).setAsAttribute("world0"),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world1"===e.name&&t(e));i||(i=new InputBlock("world1")).setAsAttribute("world1"),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world2"===e.name&&t(e));i||(i=new InputBlock("world2")).setAsAttribute("world2"),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world3"===e.name&&t(e));i||(i=new InputBlock("world3")).setAsAttribute("world3"),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world"===e.name&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(tC.World),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let n=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),n=!0),s&&!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)!==i.THIN_INSTANCES&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);let t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);let i=this._outputs[0],r=this._outputs[1],s=this.world0,n=this.world1,a=this.world2,o=this.world3;return e.compilationString+=`#ifdef INSTANCES -`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${n.associatedVariableName}, ${a.associatedVariableName}, ${o.associatedVariableName}); -`,e.compilationString+=`#ifdef THIN_INSTANCES -`,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; -`,e.compilationString+=`#endif -`,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(r,e)+` = float(gl_InstanceID); -`:e.compilationString+=this._declareOutput(r,e)+` = 0.0; -`,e.compilationString+=`#else -`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; -`,e.compilationString+=this._declareOutput(r,e)+` = 0.0; -`,e.compilationString+=`#endif -`,this}};(0,rv.H)("BABYLON.InstancesBlock",InstancesBlock);let MorphTargetsBlock=class MorphTargetsBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Vertex),this.registerInput("position",tm.Vector3),this.registerInput("normal",tm.Vector3),this.registerInput("tangent",tm.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(tm.Color4|tm.Vector4|tm.Vector3),this.registerInput("uv",tm.Vector2),this.registerOutput("positionOutput",tm.Vector3),this.registerOutput("normalOutput",tm.Vector3),this.registerOutput("tangentOutput",tm.Vector4),this.registerOutput("uvOutput",tm.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new InputBlock("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new InputBlock("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&t(e));i||(i=new InputBlock("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute("uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){let t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&so.G.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(so.G.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){let s=this.position,n=this.normal,a=this.tangent,o=this.uv,l=this.positionOutput,h=this.normalOutput,u=this.tangentOutput,c=this.uvOutput,d=r.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,_=p&&p.supportsNormals&&r.NORMAL,f=p&&p.supportsTangents&&r.TANGENT,m=p&&p.supportsUVs&&r.UV1,g="";(null==p?void 0:p.isUsingTextureForTargets)&&d>0&&(g+=`float vertexID; -`);for(let e=0;e0)for(let t=0;t!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.isSystemValue&&e.systemValue===tC.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(tC.World),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new InputBlock("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&e.type===tm.Vector4&&t(e));i||(i=new InputBlock("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var r,s,n,a;let o=this.normal,l=this.tangent,h=o.isConnected;(null===(r=o.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(s=o.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let u=l.isConnected;(null===(n=l.connectInputBlock)||void 0===n?void 0:n.isAttribute)&&!e.isVerticesDataPresent(null===(a=l.connectInputBlock)||void 0===a?void 0:a.name)&&(u=!1);let c=h&&u;i.setValue("TBNBLOCK",c,!0)}_buildBlock(e){super._buildBlock(e);let t=this.normal,i=this.tangent,r=this.world,s=this.TBN,n=this.row0,a=this.row1,o=this.row2;return e.target===tg.Fragment&&(e.compilationString+=` - // ${this.name} - vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; - vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); - vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; - mat3 ${s.associatedVariableName} = mat3(${r.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); - `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); -`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); -`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); -`),e.sharedData.blocksWithDefines.push(this)),this}};(0,rv.H)("BABYLON.TBNBlock",TBNBlock);let PerturbNormalBlock=class PerturbNormalBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",tm.Vector4,!1),this.registerInput("worldNormal",tm.Vector4,!1),this.registerInput("worldTangent",tm.Vector4,!0),this.registerInput("uv",tm.Vector2,!1),this.registerInput("normalMapColor",tm.Color3,!1),this.registerInput("strength",tm.Float,!1),this.registerInput("viewDirection",tm.Vector3,!0),this.registerInput("parallaxScale",tm.Float,!0),this.registerInput("parallaxHeight",tm.Float,!0),this.registerInput("TBN",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,tx.Input,TBNBlock,"TBNBlock")),this.registerInput("world",tm.Matrix,!0),this.registerOutput("output",tm.Vector4),this.registerOutput("uvOffset",tm.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){let r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new InputBlock("uv")).setAsAttribute(),i.output.connectTo(this.uv)}if(!this.strength.isConnected){let e=new InputBlock("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,n=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let a=null;this.normalMapColor.connectedPoint&&(a=this.normalMapColor.connectedPoint._ownerBlock.samplerName);let o=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&a||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?` -#if !defined(NORMALXYSCALE) -1.0/ -#endif -${e._emitFloat(this.strength.connectInputBlock.value)}`:` -#if !defined(NORMALXYSCALE) -1.0/ -#endif -${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let u={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},c=this.TBN;c.isConnected?e.compilationString+=` - #ifdef TBNBLOCK - mat3 vTBN = ${c.associatedVariableName}; - #endif - `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz); -`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); -`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; -`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); -`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[u,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});let d=o&&a?`texture2D(${a}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o&&this.useParallaxOcclusion?a:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${o?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:r.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:o?this.viewDirection.associatedVariableName:"vec3(0.)"},u]}),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; -`+`${this._codeVariableName}.invertY = ${this.invertY}; -${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; -${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; -`}serialize(){let e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}};(0,rH.gn)([editableInPropertyPage("Invert X axis",tT.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"invertX",void 0),(0,rH.gn)([editableInPropertyPage("Invert Y axis",tT.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"invertY",void 0),(0,rH.gn)([editableInPropertyPage("Use parallax occlusion",tT.Boolean)],PerturbNormalBlock.prototype,"useParallaxOcclusion",void 0),(0,rH.gn)([editableInPropertyPage("Object Space Mode",tT.Boolean,"PROPERTIES",{notifiers:{update:!1}})],PerturbNormalBlock.prototype,"useObjectSpaceNormalMap",void 0),(0,rv.H)("BABYLON.PerturbNormalBlock",PerturbNormalBlock);let DiscardBlock=class DiscardBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.registerInput("value",tm.Float,!0),this.registerInput("cutoff",tm.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard; -`,this}};(0,rv.H)("BABYLON.DiscardBlock",DiscardBlock);let FrontFacingBlock=class FrontFacingBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerOutput("output",tm.Float,tg.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===tg.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0; -`,this}};(0,rv.H)("BABYLON.FrontFacingBlock",FrontFacingBlock);let DerivativeBlock=class DerivativeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerInput("input",tm.AutoDetect,!1),this.registerOutput("dx",tm.BasedOnInput),this.registerOutput("dy",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName}); -`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName}); -`),this}};(0,rv.H)("BABYLON.DerivativeBlock",DerivativeBlock);let FragCoordBlock=class FragCoordBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerOutput("xy",tm.Vector2,tg.Fragment),this.registerOutput("xyz",tm.Vector3,tg.Fragment),this.registerOutput("xyzw",tm.Vector4,tg.Fragment),this.registerOutput("x",tm.Float,tg.Fragment),this.registerOutput("y",tm.Float,tg.Fragment),this.registerOutput("z",tm.Float,tg.Fragment),this.registerOutput("w",tm.Float,tg.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(let i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name}; -`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===tg.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}};(0,rv.H)("BABYLON.FragCoordBlock",FragCoordBlock);let ScreenSizeBlock=class ScreenSizeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerOutput("xy",tm.Vector2,tg.Fragment),this.registerOutput("x",tm.Float,tg.Fragment),this.registerOutput("y",tm.Float,tg.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){let t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; -`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===tg.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}};(0,rv.H)("BABYLON.ScreenSizeBlock",ScreenSizeBlock);let ScreenSpaceBlock=class ScreenSpaceBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerInput("vector",tm.AutoDetect),this.registerInput("worldViewProjection",tm.Matrix),this.registerOutput("output",tm.Vector2),this.registerOutput("x",tm.Float),this.registerOutput("y",tm.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.WorldViewProjection&&t(e));i||(i=new InputBlock("worldViewProjection")).setAsSystemValue(tC.WorldViewProjection),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;let r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case tm.Vector3:e.compilationString+=`vec4 ${s} = ${r} * vec4(${t.associatedVariableName}, 1.0); -`;break;case tm.Vector4:e.compilationString+=`vec4 ${s} = ${r} * ${t.associatedVariableName}; -`}return e.compilationString+=`${s}.xy /= ${s}.w;`,e.compilationString+=`${s}.xy = ${s}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${s}.xy; -`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x; -`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y; -`),this}};(0,rv.H)("BABYLON.ScreenSpaceBlock",ScreenSpaceBlock);let TwirlBlock=class TwirlBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerInput("input",tm.Vector2),this.registerInput("strength",tm.Float),this.registerInput("center",tm.Vector2),this.registerInput("offset",tm.Vector2),this.registerOutput("output",tm.Vector2),this.registerOutput("x",tm.Float),this.registerOutput("y",tm.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){let e=new InputBlock("center");e.value=new rm.FM(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){let e=new InputBlock("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){let e=new InputBlock("offset");e.value=new rm.FM(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);let t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` - vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; - float ${i} = ${this.strength.associatedVariableName} * length(${t}); - float ${r} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; - float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; - vec2 ${n} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); - `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n}; -`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x; -`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y; -`),this}};(0,rv.H)("BABYLON.TwirlBlock",TwirlBlock);let HeightToNormalBlock=class HeightToNormalBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",tm.Float),this.registerInput("worldPosition",tm.Vector3),this.registerInput("worldNormal",tm.Vector3),this.registerInput("worldTangent",tm.AutoDetect,!0),this.registerOutput("output",tm.Vector4),this.registerOutput("xyz",tm.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||console.error(`You must connect the 'worldTangent' input of the ${this.name} block!`);let i=this.generateInWorldSpace?"":` - vec3 biTangent = cross(normal, tangent); - mat3 TBN = mat3(tangent, biTangent, normal); - `,r=this.generateInWorldSpace?"":` - result = TBN * result; - result = result * vec3(0.5) + vec3(0.5); - `,s=` - vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { - ${i} - ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} - ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} - vec3 worlddX = dFdx(position); - vec3 worlddY = dFdy(position); - vec3 crossX = cross(normal, worlddX); - vec3 crossY = cross(normal, worlddY); - float d = abs(dot(crossY, worlddX)); - vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); - inToNormal.y *= -1.0; - vec3 result = normalize((d * normal) - inToNormal); - ${r} - return vec4(result, 0.); - }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",s,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName}); -`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; -`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; -${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; -${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; -`}serialize(){let e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}};(0,rH.gn)([editableInPropertyPage("Generate in world space instead of tangent space",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"generateInWorldSpace",void 0),(0,rH.gn)([editableInPropertyPage("Force normalization for the worldNormal input",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"automaticNormalizationNormal",void 0),(0,rH.gn)([editableInPropertyPage("Force normalization for the worldTangent input",tT.Boolean,"PROPERTIES",{notifiers:{update:!0}})],HeightToNormalBlock.prototype,"automaticNormalizationTangent",void 0),(0,rv.H)("BABYLON.HeightToNormalBlock",HeightToNormalBlock);let FragDepthBlock=class FragDepthBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.registerInput("depth",tm.Float,!0),this.registerInput("worldPos",tm.Vector4,!0),this.registerInput("viewProjection",tm.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; -`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` - vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; - float v = p.z / p.w; - #ifndef IS_NDC_HALF_ZRANGE - v = v * 0.5 + 0.5; - #endif - gl_FragDepth = v; - - `:console.warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}};(0,rv.H)("BABYLON.FragDepthBlock",FragDepthBlock);let ShadowMapBlock=class ShadowMapBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.registerInput("worldPosition",tm.Vector4,!1),this.registerInput("viewProjection",tm.Matrix,!1),this.registerInput("worldNormal",tm.AutoDetect,!0),this.registerOutput("depth",tm.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName}; -`,e.compilationString+=`vec3 vPositionWSM; -`,e.compilationString+=`float vDepthMetricSM = 0.0; -`,e.compilationString+=`float zSM; -`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; -`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` - #if SM_DEPTHTEXTURE == 1 - #ifdef IS_NDC_HALF_ZRANGE - gl_FragDepth = (clipPos.z / clipPos.w); - #else - gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; - #endif - #endif - `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); -`,this}};(0,rv.H)("BABYLON.ShadowMapBlock",ShadowMapBlock);let PrePassOutputBlock=class PrePassOutputBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment,!0),this.registerInput("viewDepth",tm.Float,!0),this.registerInput("worldPosition",tm.AutoDetect,!0),this.registerInput("viewNormal",tm.AutoDetect,!0),this.registerInput("reflectivity",tm.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(tm.Vector3|tm.Vector4|tm.Color3|tm.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);let t=this.worldPosition,i=this.viewNormal,r=this.viewDepth,s=this.reflectivity;e.sharedData.blocksWithDefines.push(this);let n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+=`#if defined(PREPASS)\r -`,e.compilationString+=`#ifdef PREPASS_DEPTH\r -`,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${r.associatedVariableName}, 0.0, 0.0, 1.0);\r -`:e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=`#ifdef PREPASS_POSITION\r -`,t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===tm.Vector4?t.associatedVariableName+".a":"1.0"});\r -`:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=`#ifdef PREPASS_NORMAL\r -`,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===tm.Vector4?i.associatedVariableName+".a":"1.0"});\r -`:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r -`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===tm.Vector4?s.associatedVariableName+".a":"1.0"});\r -`:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r -`,e.compilationString+=`#endif\r -`,e.compilationString+=`#endif\r -`,this}};(0,rv.H)("BABYLON.PrePassOutputBlock",PrePassOutputBlock);let FogBlock=class FogBlock extends NodeMaterialBlock{constructor(e){super(e,tg.VertexAndFragment,!1),this.registerInput("worldPosition",tm.Vector4,!1,tg.Vertex),this.registerInput("view",tm.Matrix,!1,tg.Vertex),this.registerInput("input",tm.AutoDetect,!1,tg.Fragment),this.registerInput("fogColor",tm.AutoDetect,!1,tg.Fragment),this.registerOutput("output",tm.Color3,tg.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(tC.View),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.FogColor&&t(e));i||(i=new InputBlock("fogColor",void 0,tm.Color3)).setAsSystemValue(tC.FogColor),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){let r=e.getScene();i.setValue("FOG",t.fogEnabled&&so.G.GetFogState(e,r))}bind(e,t,i){if(!i)return;let r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===tg.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});let t=e._getFreeVariableName("fog"),i=this.input,r=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");let s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG -`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); -`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${r.associatedVariableName}.rgb; -`,e.compilationString+=`#else -${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb; -`,e.compilationString+=`#endif -`}else{let t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz; -`}return this}};(0,rv.H)("BABYLON.FogBlock",FogBlock);let LightBlock=class LightBlock extends NodeMaterialBlock{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tg.Fragment:tg.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex}constructor(e){super(e,tg.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",tm.Vector4,!1,tg.Vertex),this.registerInput("worldNormal",tm.Vector4,!1,tg.Fragment),this.registerInput("cameraPosition",tm.Vector3,!1,tg.Fragment),this.registerInput("glossiness",tm.Float,!0,tg.Fragment),this.registerInput("glossPower",tm.Float,!0,tg.Fragment),this.registerInput("diffuseColor",tm.Color3,!0,tg.Fragment),this.registerInput("specularColor",tm.Color3,!0,tg.Fragment),this.registerInput("view",tm.Matrix,!0),this.registerOutput("diffuseOutput",tm.Color3,tg.Fragment),this.registerOutput("specularOutput",tm.Color3,tg.Fragment),this.registerOutput("shadow",tm.Float,tg.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(tC.CameraPosition),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;let r=e.getScene();if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};so.G.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else so.G.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;so.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;let r=i.getScene();this.light?so.G.BindLight(this.light,this._lightId,r,e,!0):so.G.BindLights(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){let t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));let r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; -`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; -`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; -`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==tg.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=`//${this.name}`,i=this.worldPosition,r=i.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${r}; -`,t),e.compilationString+=`${r} = ${i.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):r="v_"+r+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}); -`),e.compilationString+=`lightingInfo info; -`,e.compilationString+=`float shadow = 1.; -`,e.compilationString+=`float aggShadow = 0.; -`,e.compilationString+=`float numLights = 0.; -`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; -`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); -`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); -`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; -`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",replaceStrings:[{search:/vPositionW/g,replace:r+".xyz"}]}),0===this._lightId&&(e.compilationString+=`aggShadow = aggShadow / numLights; -`);let s=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; -`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; -`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = aggShadow; -`),this}serialize(){let e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}};(0,rH.gn)([editableInPropertyPage("Generate only fragment code",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:LightBlock._OnGenerateOnlyFragmentCodeChanged}})],LightBlock.prototype,"generateOnlyFragmentCode",void 0),(0,rv.H)("BABYLON.LightBlock",LightBlock);let ImageSourceBlock=class ImageSourceBlock extends NodeMaterialBlock{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,tg.VertexAndFragment),this.registerOutput("source",tm.Object,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,tx.Output,ImageSourceBlock,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===tg.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};(0,rv.H)("BABYLON.ImageSourceBlock",ImageSourceBlock);let TextureBlock=class TextureBlock extends NodeMaterialBlock{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _IsPrePassTextureBlock(e){return(null==e?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return TextureBlock._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!TextureBlock._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?tg.Fragment:tg.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",tm.AutoDetect,!1,tg.VertexAndFragment),this.registerInput("source",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,tx.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerInput("layer",tm.Float,!0),this.registerInput("lod",tm.Float,!0),this.registerOutput("rgba",tm.Color4,tg.Neutral),this.registerOutput("rgb",tm.Color3,tg.Neutral),this.registerOutput("r",tm.Float,tg.Neutral),this.registerOutput("g",tm.Float,tg.Neutral),this.registerOutput("b",tm.Float,tg.Neutral),this.registerOutput("a",tm.Float,tg.Neutral),this.registerOutput("level",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return tg.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return tg.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===tg.Fragment)return tg.Fragment;if(e.target===tg.Vertex)break;if(e.target===tg.Neutral||e.target===tg.VertexAndFragment){let t=e.ownerBlock;if(t.target===tg.Fragment)return tg.Fragment;for(let i of(e=null,t.inputs))if(i.connectedPoint){e=i.connectedPoint;break}}}return tg.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){if(e.mode===tb.PostProcess){let i=e.getBlockByPredicate(e=>"uv"===e.name&&t(e));i&&i.connectTo(this)}else{let i=e.mode===tb.Particle?"particle_uv":"uv",r=e.getInputBlockByPredicate(e=>e.isAttribute&&e.name===i&&t(e));r||(r=new InputBlock("uv")).setAsAttribute(i),r.output.connectTo(this.uv)}}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),void 0==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==tg.Fragment}_injectVertexCode(e){let t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName} -`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0)); -`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) -`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,e.compilationString+=`#endif -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}_getUVW(e){var t,i,r;let s=e,n=null!==(r=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==r&&r;if(n){let t=this.layer.isConnected?this.layer.associatedVariableName:"0";s=`vec3(${e}, ${t})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){let t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName} -`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix}); -`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) -`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix}); -`,e.compilationString+=`#endif -`}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tg.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix}); -`;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} - ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); - #endif - `),e.compilationString+=`#ifdef ${this._gammaDefineName} - ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); - #endif - `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tg.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; -`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,r,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===tg.Vertex||this._fragmentOnly||e.target===tg.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===tg.Fragment||this._isMixed&&e.target===tg.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==tg.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((null===(s=null===(r=this._texture)||void 0===r?void 0:r._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));let n=`//${this.name}`;for(let t of(e._emitFunctionFromInclude("helperFunctions",n),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; -`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};(0,rv.H)("BABYLON.TextureBlock",TextureBlock);let ReflectionTextureBaseBlock=class ReflectionTextureBaseBlock extends NodeMaterialBlock{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tg.Fragment:tg.VertexAndFragment)}constructor(e){super(e,tg.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new InputBlock("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.World&&t(e));i||(i=new InputBlock("world")).setAsSystemValue(tC.World),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(tC.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){let r=this._getTexture();i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize&&(e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)))}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===tg.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");let i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; -`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} -${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; -#endif -`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) -${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); -#endif -`),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} -`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; -`,e._samplerDeclaration+=`#else -`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; -`,e._samplerDeclaration+=`#endif -`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,r=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);let s=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,a=`${this._positionUVWName}`,o=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=` - #ifdef ${this._defineMirroredEquirectangularFixedName} - vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n}); - #endif - - #ifdef ${this._defineEquirectangularFixedName} - vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n}); - #endif - - #ifdef ${this._defineEquirectangularName} - vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - - #ifdef ${this._defineSphericalName} - vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s}); - #endif - - #ifdef ${this._definePlanarName} - vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - - #ifdef ${this._defineCubicName} - #ifdef ${this._defineLocalCubicName} - vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${o}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); - #else - vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${o}.xyz, ${s}); - #endif - #endif - - #ifdef ${this._defineProjectionName} - vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s}); - #endif - - #ifdef ${this._defineSkyboxName} - vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${a}, ${s}); - #endif - - #ifdef ${this._defineExplicitName} - vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); - #endif -`;return r||(h+=`#ifdef ${this._defineOppositeZ} - ${this._reflectionVectorName}.z *= -1.0; - #endif -`),i||(h+=` - #ifdef ${this._define3DName} - vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; - #else - vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; - #ifdef ${this._defineProjectionName} - ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; - #endif - ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; - #endif -`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i="vec"+(0===t.length?"4":t.length-1),r=`${i} ${this._reflectionColorName}; - #ifdef ${this._define3DName} -`;return e?r+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; -`:r+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; -`,r+=` - #else -`,e?r+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; -`:r+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; -`,r+=`#endif -`}writeOutputs(e,t){let i="";if(e.target===tg.Fragment)for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; -`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){let t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); -`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); -`;return e+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=cubeTexture_CubeTexture.Parse(e.texture,t,i):this.texture=texture_Texture.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}};(0,rH.gn)([editableInPropertyPage("Generate only fragment code",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ReflectionTextureBaseBlock._OnGenerateOnlyFragmentCodeChanged}})],ReflectionTextureBaseBlock.prototype,"generateOnlyFragmentCode",void 0),(0,rv.H)("BABYLON.ReflectionTextureBaseBlock",ReflectionTextureBaseBlock);let ReflectionTextureBlock=class ReflectionTextureBlock extends ReflectionTextureBaseBlock{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex}constructor(e){super(e),this.registerInput("position",tm.AutoDetect,!1,tg.Vertex),this.registerInput("worldPosition",tm.Vector4,!1,tg.Vertex),this.registerInput("worldNormal",tm.Vector4,!1,tg.Fragment),this.registerInput("world",tm.Matrix,!1,tg.Vertex),this.registerInput("cameraPosition",tm.Vector3,!1,tg.Fragment),this.registerInput("view",tm.Matrix,!1,tg.Fragment),this.registerOutput("rgb",tm.Color3,tg.Fragment),this.registerOutput("rgba",tm.Color4,tg.Fragment),this.registerOutput("r",tm.Float,tg.Fragment),this.registerOutput("g",tm.Float,tg.Fragment),this.registerOutput("b",tm.Float,tg.Fragment),this.registerOutput("a",tm.Float,tg.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(tC.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==tg.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);let t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); -`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}};(0,rv.H)("BABYLON.ReflectionTextureBlock",ReflectionTextureBlock);let SceneDepthBlock=class SceneDepthBlock extends NodeMaterialBlock{constructor(e){super(e,tg.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",tm.AutoDetect,!1,tg.VertexAndFragment),this.registerOutput("depth",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?tg.VertexAndFragment:tg.Fragment}_getTexture(e){let t=e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ);return t.getDepthMap()}bind(e,t){let i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput){let i=t.connectedPoint.ownerBlock;i.isAttribute||e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===tm.Vector3?"3":t.type===tm.Vector4?"4":"2"))}if(this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; -`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tg.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); -`;return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); -`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); -`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tg.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}if(this.uv.ownerBlock.target===tg.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; -`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.bindableBlocks.indexOf(this)&&e.sharedData.bindableBlocks.push(this),e.target!==tg.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(e=>e.isConnectedInFragmentShader)){for(let t of(e._emit2DSampler(this._samplerName),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){let e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}};(0,rH.gn)([editableInPropertyPage("Use non linear depth",tT.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],SceneDepthBlock.prototype,"useNonLinearDepth",void 0),(0,rH.gn)([editableInPropertyPage("Store Camera space Z",tT.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],SceneDepthBlock.prototype,"storeCameraSpaceZ",void 0),(0,rH.gn)([editableInPropertyPage("Force 32 bits float",tT.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>null==e?void 0:e.disableDepthRenderer()}})],SceneDepthBlock.prototype,"force32itsFloat",void 0),(0,rv.H)("BABYLON.SceneDepthBlock",SceneDepthBlock);let ClipPlanesBlock=class ClipPlanesBlock extends NodeMaterialBlock{constructor(e){super(e,tg.VertexAndFragment,!0),this.registerInput("worldPosition",tm.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return tg.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var r,s,n,a,o,l;let h=e.getScene(),u=null!==(r=t.clipPlane)&&void 0!==r?!!r:!!h.clipPlane,c=null!==(s=t.clipPlane2)&&void 0!==s?!!s:!!h.clipPlane2,d=null!==(n=t.clipPlane3)&&void 0!==n?!!n:!!h.clipPlane3,p=null!==(a=t.clipPlane4)&&void 0!==a?!!a:!!h.clipPlane4,_=null!==(o=t.clipPlane5)&&void 0!==o?!!o:!!h.clipPlane5,f=null!==(l=t.clipPlane6)&&void 0!==l?!!l:!!h.clipPlane6;i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",c,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",_,!0),i.setValue("CLIPPLANE6",f,!0)}bind(e,t,i){if(!i)return;let r=i.getScene();(0,nX.an)(e,t,r)}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;if(e.target!==tg.Fragment){let i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}};(0,rv.H)("BABYLON.ClipPlanesBlock",ClipPlanesBlock);let PrePassTextureBlock=class PrePassTextureBlock extends NodeMaterialBlock{get texture(){return null}set texture(e){}constructor(e,t=tg.VertexAndFragment){super(e,t,!1),this.registerOutput("position",tm.Object,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("position",this,tx.Output,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("depth",tm.Object,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("depth",this,tx.Output,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("normal",tm.Object,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("normal",this,tx.Output,ImageSourceBlock,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==tg.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){let i=t.getScene(),r=i.enablePrePassRenderer();if(!r)return;let s=r.defaultRT;s.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,s.textures[r.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,s.textures[r.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,s.textures[r.getIndex(6)]))}};(0,rv.H)("BABYLON.PrePassTextureBlock",PrePassTextureBlock);let NodeMaterialTeleportInBlock=class NodeMaterialTeleportInBlock extends NodeMaterialBlock{get endpoints(){return this._endpoints}constructor(e){super(e,tg.Neutral),this._endpoints=[],this.registerInput("input",tm.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){for(let e of(super.dispose(),this._endpoints))this.detachFromEndpoint(e);this._endpoints=[]}};(0,rv.H)("BABYLON.NodeMaterialTeleportInBlock",NodeMaterialTeleportInBlock);let NodeMaterialTeleportOutBlock=class NodeMaterialTeleportOutBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",tm.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){(this._target&e)==0&&(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName}; -`)}clone(e,t=""){let i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); -`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}};(0,rv.H)("BABYLON.NodeMaterialTeleportOutBlock",NodeMaterialTeleportOutBlock);let AddBlock=class AddBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(tm.Float),this._inputs[1].acceptedConnectionPointTypes.push(tm.Float)}getClassName(){return"AddBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; -`,this}};(0,rv.H)("BABYLON.AddBlock",AddBlock);let ScaleBlock=class ScaleBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.AutoDetect),this.registerInput("factor",tm.Float),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; -`,this}};(0,rv.H)("BABYLON.ScaleBlock",ScaleBlock);let ClampBlock=class ClampBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)}); -`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; -`+`${this._codeVariableName}.maximum = ${this.maximum}; -`}serialize(){let e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}};(0,rH.gn)([editableInPropertyPage("Minimum",tT.Float)],ClampBlock.prototype,"minimum",void 0),(0,rH.gn)([editableInPropertyPage("Maximum",tT.Float)],ClampBlock.prototype,"maximum",void 0),(0,rv.H)("BABYLON.ClampBlock",ClampBlock);let CrossBlock=class CrossBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tm.Vector2),this._inputs[1].excludedConnectionPointTypes.push(tm.Float),this._inputs[1].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); -`,this}};(0,rv.H)("BABYLON.CrossBlock",CrossBlock);let CustomBlock=class CustomBlock extends NodeMaterialBlock{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),this._outputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),e._emitFunction(i,t,""),this._outputs.forEach(t=>{e.compilationString+=this._declareOutput(t,e)+";\n"}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((t,i)=>{var s,n,a;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(a=null===(n=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===n?void 0:n.samplerName)&&void 0!==a?a:t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0}),this._outputs.forEach((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName}),e.compilationString+=");\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; -`}serialize(){let e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,r;this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=tg[e.target],null===(t=e.inParameters)||void 0===t||t.forEach((e,t)=>{let i=tm[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject(e.name,this,tx.Input,ImageSourceBlock,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})}),null===(i=e.outParameters)||void 0===i||i.forEach((e,t)=>{this.registerOutput(e.name,tm[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])}),null===(r=e.inLinkedConnectionTypes)||void 0===r||r.forEach(e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(tC.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); -`,this}};(0,rv.H)("BABYLON.ViewDirectionBlock",ViewDirectionBlock);let FresnelBlock=class FresnelBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("worldNormal",tm.Vector4),this.registerInput("viewDirection",tm.Vector3),this.registerInput("bias",tm.Float),this.registerInput("power",tm.Float),this.registerOutput("fresnel",tm.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){let t=new ViewDirectionBlock("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){let e=new InputBlock("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){let e=new InputBlock("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.FresnelBlock",FresnelBlock);let MaxBlock=class MaxBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.MaxBlock",MaxBlock);let MinBlock=class MinBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.MinBlock",MinBlock);let DistanceBlock=class DistanceBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.Float),this._inputs[1].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.DistanceBlock",DistanceBlock);let LengthBlock=class LengthBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerOutput("output",tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.LengthBlock",LengthBlock);let NegateBlock=class NegateBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName}; -`,this}};(0,rv.H)("BABYLON.NegateBlock",NegateBlock);let PowBlock=class PowBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerInput("power",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.PowBlock",PowBlock);let RandomNumberBlock=class RandomNumberBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("seed",tm.AutoDetect),this.registerOutput("output",tm.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Vector2|tm.Vector3|tm.Vector4|tm.Color3|tm.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy); -`,this}};(0,rv.H)("BABYLON.RandomNumberBlock",RandomNumberBlock);let ArcTan2Block=class ArcTan2Block extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("x",tm.Float),this.registerInput("y",tm.Float),this.registerOutput("output",tm.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.ArcTan2Block",ArcTan2Block);let SmoothStepBlock=class SmoothStepBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerInput("edge0",tm.Float),this.registerInput("edge1",tm.Float),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.SmoothStepBlock",SmoothStepBlock);let ReciprocalBlock=class ReciprocalBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return this.input.type===tm.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); -`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; -`,this}};(0,rv.H)("BABYLON.ReciprocalBlock",ReciprocalBlock);let ReplaceColorBlock=class ReplaceColorBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerInput("reference",tm.AutoDetect),this.registerInput("distance",tm.Float),this.registerInput("replacement",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(tm.Float),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.Float),this._inputs[1].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[3].excludedConnectionPointTypes.push(tm.Float),this._inputs[3].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`; -`,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { -`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; -`,e.compilationString+=`} else { -`,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; -`,e.compilationString+=`} -`,this}};(0,rv.H)("BABYLON.ReplaceColorBlock",ReplaceColorBlock);let PosterizeBlock=class PosterizeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("value",tm.AutoDetect),this.registerInput("steps",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.PosterizeBlock",PosterizeBlock),(eD=iD||(iD={}))[eD.SawTooth=0]="SawTooth",eD[eD.Square=1]="Square",eD[eD.Triangle=2]="Triangle";let WaveBlock=class WaveBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.kind=iD.SawTooth,this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];switch(this.kind){case iD.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); -`;break;case iD.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); -`;break;case iD.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; -`}return this}serialize(){let e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}};(0,rv.H)("BABYLON.WaveBlock",WaveBlock);let GradientBlockColorStep=class GradientBlockColorStep{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}};let GradientBlock=class GradientBlock extends NodeMaterialBlock{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,tg.Neutral),this.colorSteps=[new GradientBlockColorStep(0,rg.Wo.Black()),new GradientBlockColorStep(1,rg.Wo.White())],this.onValueChangedObservable=new rf.y$,this.registerInput("gradient",tm.AutoDetect),this.registerOutput("output",tm.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Float|tm.Vector2|tm.Vector3|tm.Vector4|tm.Color3|tm.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){let t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.); -`;return}let i=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; -`,e.compilationString+=`float ${r}; -`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==tm.Float&&(s+=".x");for(let t=1;ti.getWorldMatrix().determinant()?-1:1)}_buildBlock(e){return e.target===tg.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}};(0,rv.H)("BABYLON.AnisotropyBlock",AnisotropyBlock);let ReflectionBlock=class ReflectionBlock extends ReflectionTextureBaseBlock{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,console.error("The position input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",tm.AutoDetect,!1,tg.Vertex),this.registerInput("world",tm.Matrix,!1,tg.Vertex),this.registerInput("color",tm.Color3,!0,tg.Fragment),this.registerOutput("reflection",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",this,tx.Output,ReflectionBlock,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!r.invertZ:r.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",r.gammaSpace,!0),i.setValue("RGBDREFLECTION",r.isRGBD,!0),r&&r.coordinatesMode!==texture_Texture.SKYBOX_MODE&&r.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,r){super.bind(e,t,i);let s=this._getTexture();if(!s||!r)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);let n=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,n,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,n,rE.R.Log2(n));let a=r.materialDefines,o=s.sphericalPolynomial;if(a.USESPHERICALFROMREFLECTIONMAP&&o){if(a.SPHERICAL_HARMONICS){let t=o.preScaledHarmonics;e.setVector3("vSphericalL00",t.l00),e.setVector3("vSphericalL1_1",t.l1_1),e.setVector3("vSphericalL10",t.l10),e.setVector3("vSphericalL11",t.l11),e.setVector3("vSphericalL2_2",t.l2_2),e.setVector3("vSphericalL2_1",t.l2_1),e.setVector3("vSphericalL20",t.l20),e.setVector3("vSphericalL21",t.l21),e.setVector3("vSphericalL22",t.l22)}else e.setFloat3("vSphericalX",o.x.x,o.x.y,o.x.z),e.setFloat3("vSphericalY",o.y.x,o.y.y,o.y.z),e.setFloat3("vSphericalZ",o.z.x,o.z.y,o.z.z),e.setFloat3("vSphericalXX_ZZ",o.xx.x-o.zz.x,o.xx.y-o.zz.y,o.xx.z-o.zz.z),e.setFloat3("vSphericalYY_ZZ",o.yy.x-o.zz.x,o.yy.y-o.zz.y,o.yy.z-o.zz.z),e.setFloat3("vSphericalZZ",o.zz.x,o.zz.y,o.zz.z),e.setFloat3("vSphericalXY",o.xy.x,o.xy.y,o.xy.z),e.setFloat3("vSphericalYZ",o.yz.x,o.yz.y,o.yz.z),e.setFloat3("vSphericalZX",o.zx.x,o.zx.y,o.zx.z)}}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});let i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) - vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; - #ifdef ${this._defineOppositeZ} - ${i}.z *= -1.0; - #endif - ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i}); - #endif -`}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",` - #ifdef ${this._define3DName} - #define sampleReflection(s, c) textureCube(s, c) - #else - #define sampleReflection(s, c) texture2D(s, c) - #endif -`,`//${this.name}`),e._emitFunction("sampleReflectionLod",` - #ifdef ${this._define3DName} - #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) - #else - #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) - #endif -`,`//${this.name}`);let r=` - vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { - ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)} - return ${this._reflectionVectorName}; - } -`;return e._emitFunction("computeReflectionCoordsPBR",r,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION - vec2 ${this._vReflectionInfosName} = vec2(1., 0.); - - reflectionOutParams reflectionOut; - - reflectionBlock( - ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz, - ${t}, - alphaG, - ${this._vReflectionMicrosurfaceInfosName}, - ${this._vReflectionInfosName}, - ${this.reflectionColor}, - #ifdef ANISOTROPIC - anisotropicOut, - #endif - #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) - NdotVUnclamped, - #endif - #ifdef ${this._defineLinearSpecularReflection} - roughness, - #endif - #ifdef ${this._define3DName} - ${this._cubeSamplerName}, - #else - ${this._2DSamplerName}, - #endif - #if defined(NORMAL) && defined(USESPHERICALINVERTEX) - ${this._vEnvironmentIrradianceName}, - #endif - #ifdef USESPHERICALFROMREFLECTIONMAP - #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) - ${this._reflectionMatrixName}, - #endif - #endif - #ifdef USEIRRADIANCEMAP - irradianceSampler, // ** not handled ** - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${this._define3DName} - ${this._cubeSamplerName}, - ${this._cubeSamplerName}, - #else - ${this._2DSamplerName}, - ${this._2DSamplerName}, - #endif - #endif - #ifdef REALTIME_FILTERING - ${this._vReflectionFilteringInfoName}, - #endif - reflectionOut - ); - #endif -`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==tg.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace}; -`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics}; -${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment}; -`}serialize(){var e,t;let i=super.serialize();return i.useSphericalHarmonics=this.useSphericalHarmonics,i.forceIrradianceInFragment=this.forceIrradianceInFragment,i.gammaSpace=null===(t=null===(e=this.texture)||void 0===e?void 0:e.gammaSpace)||void 0===t||t,i}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}};(0,rH.gn)([editableInPropertyPage("Spherical Harmonics",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],ReflectionBlock.prototype,"useSphericalHarmonics",void 0),(0,rH.gn)([editableInPropertyPage("Force irradiance in fragment",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],ReflectionBlock.prototype,"forceIrradianceInFragment",void 0),(0,rv.H)("BABYLON.ReflectionBlock",ReflectionBlock);let ClearCoatBlock=class ClearCoatBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",tm.Float,!1,tg.Fragment),this.registerInput("roughness",tm.Float,!0,tg.Fragment),this.registerInput("indexOfRefraction",tm.Float,!0,tg.Fragment),this.registerInput("normalMapColor",tm.Color3,!0,tg.Fragment),this.registerInput("uv",tm.Vector2,!0,tg.Fragment),this.registerInput("tintColor",tm.Color3,!0,tg.Fragment),this.registerInput("tintAtDistance",tm.Float,!0,tg.Fragment),this.registerInput("tintThickness",tm.Float,!0,tg.Fragment),this.registerInput("worldTangent",tm.Vector4,!0),this.registerInput("worldNormal",tm.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(tm.Color4|tm.Vector4|tm.Vector3),this.registerInput("TBN",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("TBN",this,tx.Input,TBNBlock,"TBNBlock")),this.registerOutput("clearcoat",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",this,tx.Output,ClearCoatBlock,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new InputBlock("ClearCoat intensity",tg.Fragment,tm.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var r,s;super.bind(e,t,i);let n=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:pbrClearCoatConfiguration_PBRClearCoatConfiguration._DefaultIndexOfRefraction,a=1-n,o=1+n,l=Math.pow(-a/o,2);e.setFloat4("vClearCoatRefractionParams",l,1/n,a,o);let h=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,u=(null==h?void 0:h.perturbedNormal.isConnected)?h.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",(null==u?void 0:u.invertX)?1:-1,(null==u?void 0:u.invertY)?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",(null==u?void 0:u.invertX)?-1:1,(null==u?void 0:u.invertY)?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_generateTBNSpace(e,t,i){let r="",s=`//${this.name}`,n=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let a={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},o=this.TBN;return o.isConnected?e.compilationString+=` - #ifdef TBNBLOCK - mat3 vTBN = ${o.associatedVariableName}; - #endif - `:n.isConnected&&(r+=`vec3 tbnNormal = normalize(${i}.xyz); -vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); -vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; -mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); -`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[a]}),r}static GetCode(e,t,i,r,s,n,a){let o="",l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",h=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",u=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",c=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",p=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",_=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");let i=t.worldNormal;o+=`vec3 vGeometricNormaClearCoatW = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"}; -`}else o+=`vec3 vGeometricNormaClearCoatW = geometricNormalW; -`;return s&&t&&(o+=t._generateTBNSpace(e,r,a),n=t.worldTangent.isConnected),o+=`clearcoatOutParams clearcoatOut; - - #ifdef CLEARCOAT - vec2 vClearCoatParams = vec2(${l}, ${h}); - vec4 vClearCoatTintParams = vec4(${d}, ${p}); - - clearcoatBlock( - ${r}.xyz, - vGeometricNormaClearCoatW, - viewDirectionW, - vClearCoatParams, - specularEnvironmentR0, - #ifdef CLEARCOAT_TEXTURE - vec2(0.), - #endif - #ifdef CLEARCOAT_TINT - vClearCoatTintParams, - ${_}, - vClearCoatRefractionParams, - #ifdef CLEARCOAT_TINT_TEXTURE - vec4(0.), - #endif - #endif - #ifdef CLEARCOAT_BUMP - vec2(0., 1.), - vec4(${u}, 0.), - ${c}, - #if defined(${n?"TANGENT":"IGNORE"}) && defined(NORMAL) - vTBN, - #else - vClearCoatTangentSpaceParams, - #endif - #ifdef OBJECTSPACE_NORMALMAP - normalMatrix, - #endif - #endif - #if defined(FORCENORMALFORWARD) && defined(NORMAL) - faceNormal, - #endif - #ifdef REFLECTION - ${null==i?void 0:i._vReflectionMicrosurfaceInfosName}, - ${null==i?void 0:i._vReflectionInfosName}, - ${null==i?void 0:i.reflectionColor}, - vLightingIntensity, - #ifdef ${null==i?void 0:i._define3DName} - ${null==i?void 0:i._cubeSamplerName}, - #else - ${null==i?void 0:i._2DSamplerName}, - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${null==i?void 0:i._define3DName} - ${null==i?void 0:i._cubeSamplerName}, - ${null==i?void 0:i._cubeSamplerName}, - #else - ${null==i?void 0:i._2DSamplerName}, - ${null==i?void 0:i._2DSamplerName}, - #endif - #endif - #endif - #if defined(ENVIRONMENTBRDF) && !defined(${null==i?void 0:i._defineSkyboxName}) - #ifdef RADIANCEOCCLUSION - ambientMonochrome, - #endif - #endif - #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) - (gl_FrontFacing ? 1. : -1.), - #endif - clearcoatOut - ); - #else - clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; - #endif -`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===tg.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange}; -`}serialize(){let e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.remapF0OnInterfaceChange=null===(r=e.remapF0OnInterfaceChange)||void 0===r||r}};(0,rH.gn)([editableInPropertyPage("Remap F0 on interface change",tT.Boolean,"ADVANCED")],ClearCoatBlock.prototype,"remapF0OnInterfaceChange",void 0),(0,rv.H)("BABYLON.ClearCoatBlock",ClearCoatBlock);let IridescenceBlock=class IridescenceBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._isUnique=!0,this.registerInput("intensity",tm.Float,!0,tg.Fragment),this.registerInput("indexOfRefraction",tm.Float,!0,tg.Fragment),this.registerInput("thickness",tm.Float,!0,tg.Fragment),this.registerOutput("iridescence",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("iridescence",this,tx.Output,IridescenceBlock,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new InputBlock("Iridescence intensity",tg.Fragment,tm.Float);e.value=1,e.output.connectTo(this.intensity);let t=new InputBlock("Iridescence ior",tg.Fragment,tm.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);let i=new InputBlock("Iridescence thickness",tg.Fragment,tm.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t=(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1.",i=(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultIndexOfRefraction,r=(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:pbrIridescenceConfiguration_PBRIridescenceConfiguration._DefaultMaximumThickness;return`iridescenceOutParams iridescenceOut; - - #ifdef IRIDESCENCE - iridescenceBlock( - vec4(${t}, ${i}, 1., ${r}), - NdotV, - specularEnvironmentR0, - #ifdef CLEARCOAT - NdotVUnclamped, - #endif - iridescenceOut - ); - - float iridescenceIntensity = iridescenceOut.iridescenceIntensity; - specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; - #endif -`}_buildBlock(e){return e.target===tg.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){let e=super.serialize();return e}_deserialize(e,t,i){super._deserialize(e,t,i)}};(0,rv.H)("BABYLON.IridescenceBlock",IridescenceBlock);let RefractionBlock=class RefractionBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",tm.Float,!1,tg.Fragment),this.registerInput("tintAtDistance",tm.Float,!0,tg.Fragment),this.registerInput("volumeIndexOfRefraction",tm.Float,!0,tg.Fragment),this.registerOutput("refraction",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",this,tx.Output,RefractionBlock,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=()=>!0){if(!this.intensity.isConnected){let e=new InputBlock("Refraction intensity",tg.Fragment,tm.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(tC.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){var r,s,n,a;super.bind(e,t,i);let o=this._getTexture();if(!o)return;o.isCube?e.setTexture(this._cubeSamplerName,o):e.setTexture(this._2DSamplerName,o),e.setMatrix(this._refractionMatrixName,o.getRefractionTextureMatrix());let l=1;!o.isCube&&o.depth&&(l=o.depth);let h=null!==(a=null!==(s=null===(r=this.volumeIndexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:null===(n=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==a?a:1.5;e.setFloat4(this._vRefractionInfosName,o.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset,1/h);let u=o.getSize().width;e.setFloat2(this._vRefractionFilteringInfoName,u,rE.R.Log2(u)),o.boundingBoxSize&&(e.setVector3("vRefractionPosition",o.boundingBoxPosition),e.setVector3("vRefractionSize",o.boundingBoxSize))}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName} -`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; -`,e._samplerDeclaration+=`#else -`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; -`,e._samplerDeclaration+=`#endif -`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",` - #ifdef ${this._define3DName} - #define sampleRefraction(s, c) textureCube(s, c) - #else - #define sampleRefraction(s, c) texture2D(s, c) - #endif -`,`//${this.name}`),e._emitFunction("sampleRefractionLod",` - #ifdef ${this._define3DName} - #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) - #else - #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) - #endif -`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=(this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}"); -`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); -`)+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; -${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; -${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; -`}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=cubeTexture_CubeTexture.Parse(e.texture,t,i):this.texture=texture_Texture.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}};(0,rH.gn)([editableInPropertyPage("Link refraction to transparency",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"linkRefractionWithTransparency",void 0),(0,rH.gn)([editableInPropertyPage("Invert refraction Y",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"invertRefractionY",void 0),(0,rH.gn)([editableInPropertyPage("Use thickness as depth",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],RefractionBlock.prototype,"useThicknessAsDepth",void 0),(0,rv.H)("BABYLON.RefractionBlock",RefractionBlock);let SubSurfaceBlock=class SubSurfaceBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Fragment),this._isUnique=!0,this.registerInput("thickness",tm.Float,!1,tg.Fragment),this.registerInput("tintColor",tm.Color3,!0,tg.Fragment),this.registerInput("translucencyIntensity",tm.Float,!0,tg.Fragment),this.registerInput("translucencyDiffusionDist",tm.Color3,!0,tg.Fragment),this.registerInput("refraction",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("refraction",this,tx.Input,RefractionBlock,"RefractionBlock")),this.registerOutput("subsurface",tm.Object,tg.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",this,tx.Output,SubSurfaceBlock,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){let e=new InputBlock("SubSurface thickness",tg.Fragment,tm.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0)}static GetCode(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x;let T=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",S=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",C=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",E=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",b=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,y=(null==b?void 0:b.tintAtDistance.isConnected)?b.tintAtDistance.associatedVariableName:"1.",P=(null==b?void 0:b.intensity.isConnected)?b.intensity.associatedVariableName:"1.",R=(null==b?void 0:b.view.isConnected)?b.view.associatedVariableName:"";return""+(null!==(n=null==b?void 0:b.getCode(e))&&void 0!==n?n:"")+`subSurfaceOutParams subSurfaceOut; - - #ifdef SUBSURFACE - vec2 vThicknessParam = vec2(0., ${T}); - vec4 vTintColor = vec4(${S}, ${y}); - vec3 vSubSurfaceIntensity = vec3(${P}, ${C}, 0.); - - subSurfaceBlock( - vSubSurfaceIntensity, - vThicknessParam, - vTintColor, - normalW, - specularEnvironmentReflectance, - #ifdef SS_THICKNESSANDMASK_TEXTURE - vec4(0.), - #endif - #ifdef REFLECTION - #ifdef SS_TRANSLUCENCY - ${null==i?void 0:i._reflectionMatrixName}, - #ifdef USESPHERICALFROMREFLECTIONMAP - #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) - reflectionOut.irradianceVector, - #endif - #if defined(REALTIME_FILTERING) - ${null==i?void 0:i._cubeSamplerName}, - ${null==i?void 0:i._vReflectionFilteringInfoName}, - #endif - #endif - #ifdef USEIRRADIANCEMAP - irradianceSampler, - #endif - #endif - #endif - #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) - surfaceAlbedo, - #endif - #ifdef SS_REFRACTION - ${r}.xyz, - viewDirectionW, - ${R}, - ${null!==(a=null==b?void 0:b._vRefractionInfosName)&&void 0!==a?a:""}, - ${null!==(o=null==b?void 0:b._refractionMatrixName)&&void 0!==o?o:""}, - ${null!==(l=null==b?void 0:b._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""}, - vLightingIntensity, - #ifdef SS_LINKREFRACTIONTOTRANSPARENCY - alpha, - #endif - #ifdef ${null!==(h=null==b?void 0:b._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"} - NdotVUnclamped, - #endif - #ifdef ${null!==(u=null==b?void 0:b._defineLinearSpecularRefraction)&&void 0!==u?u:"IGNORE"} - roughness, - #endif - alphaG, - #ifdef ${null!==(c=null==b?void 0:b._define3DName)&&void 0!==c?c:"IGNORE"} - ${null!==(d=null==b?void 0:b._cubeSamplerName)&&void 0!==d?d:""}, - #else - ${null!==(p=null==b?void 0:b._2DSamplerName)&&void 0!==p?p:""}, - #endif - #ifndef LODBASEDMICROSFURACE - #ifdef ${null!==(_=null==b?void 0:b._define3DName)&&void 0!==_?_:"IGNORE"} - ${null!==(f=null==b?void 0:b._cubeSamplerName)&&void 0!==f?f:""}, - ${null!==(m=null==b?void 0:b._cubeSamplerName)&&void 0!==m?m:""}, - #else - ${null!==(g=null==b?void 0:b._2DSamplerName)&&void 0!==g?g:""}, - ${null!==(v=null==b?void 0:b._2DSamplerName)&&void 0!==v?v:""}, - #endif - #endif - #ifdef ANISOTROPIC - anisotropicOut, - #endif - #ifdef REALTIME_FILTERING - ${null!==(x=null==b?void 0:b._vRefractionFilteringInfoName)&&void 0!==x?x:""}, - #endif - #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC - vRefractionPosition, - vRefractionSize, - #endif - #endif - #ifdef SS_TRANSLUCENCY - ${E}, - #endif - subSurfaceOut - ); - - #ifdef SS_REFRACTION - surfaceAlbedo = subSurfaceOut.surfaceAlbedo; - #ifdef SS_LINKREFRACTIONTOTRANSPARENCY - alpha = subSurfaceOut.alpha; - #endif - #endif - #else - subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; - #endif -`}_buildBlock(e){return e.target===tg.Fragment&&e.sharedData.blocksWithDefines.push(this),this}};(0,rv.H)("BABYLON.SubSurfaceBlock",SubSurfaceBlock);let lF={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};let PBRMetallicRoughnessBlock=class PBRMetallicRoughnessBlock extends NodeMaterialBlock{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,console.error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tg.Fragment:tg.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tg.Fragment:tg.Vertex}constructor(e){super(e,tg.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=rg.Wo.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",tm.Vector4,!1,tg.Vertex),this.registerInput("worldNormal",tm.Vector4,!1,tg.Fragment),this.registerInput("view",tm.Matrix,!1),this.registerInput("cameraPosition",tm.Vector3,!1,tg.Fragment),this.registerInput("perturbedNormal",tm.Vector4,!0,tg.Fragment),this.registerInput("baseColor",tm.Color3,!0,tg.Fragment),this.registerInput("metallic",tm.Float,!1,tg.Fragment),this.registerInput("roughness",tm.Float,!1,tg.Fragment),this.registerInput("ambientOcc",tm.Float,!0,tg.Fragment),this.registerInput("opacity",tm.Float,!0,tg.Fragment),this.registerInput("indexOfRefraction",tm.Float,!0,tg.Fragment),this.registerInput("ambientColor",tm.Color3,!0,tg.Fragment),this.registerInput("reflection",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("reflection",this,tx.Input,ReflectionBlock,"ReflectionBlock")),this.registerInput("clearcoat",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("clearcoat",this,tx.Input,ClearCoatBlock,"ClearCoatBlock")),this.registerInput("sheen",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("sheen",this,tx.Input,SheenBlock,"SheenBlock")),this.registerInput("subsurface",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("subsurface",this,tx.Input,SubSurfaceBlock,"SubSurfaceBlock")),this.registerInput("anisotropy",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("anisotropy",this,tx.Input,AnisotropyBlock,"AnisotropyBlock")),this.registerInput("iridescence",tm.Object,!0,tg.Fragment,new NodeMaterialConnectionPointCustomObject("iridescence",this,tx.Input,IridescenceBlock,"IridescenceBlock")),this.registerOutput("ambientClr",tm.Color3,tg.Fragment),this.registerOutput("diffuseDir",tm.Color3,tg.Fragment),this.registerOutput("specularDir",tm.Color3,tg.Fragment),this.registerOutput("clearcoatDir",tm.Color3,tg.Fragment),this.registerOutput("sheenDir",tm.Color3,tg.Fragment),this.registerOutput("diffuseInd",tm.Color3,tg.Fragment),this.registerOutput("specularInd",tm.Color3,tg.Fragment),this.registerOutput("clearcoatInd",tm.Color3,tg.Fragment),this.registerOutput("sheenInd",tm.Color3,tg.Fragment),this.registerOutput("refraction",tm.Color3,tg.Fragment),this.registerOutput("lighting",tm.Color3,tg.Fragment),this.registerOutput("shadow",tm.Float,tg.Fragment),this.registerOutput("alpha",tm.Float,tg.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.CameraPosition&&t(e));i||(i=new InputBlock("cameraPosition")).setAsSystemValue(tC.CameraPosition),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tC.View&&t(e));i||(i=new InputBlock("view")).setAsSystemValue(tC.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));let r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",0>r.indexOf(".")?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);let s=e.getScene(),n=s.getEngine();if(n._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&MaterialFlags.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty){if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};so.G.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else so.G.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,so.G.PrepareDefinesForMultiview(s,i)}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;so.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return(!this._environmentBRDFTexture||!!this._environmentBRDFTexture.isReady())&&(!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var r,s;if(!i)return;let n=i.getScene();this.light?so.G.BindLight(this.light,this._lightId,n,e,!0):so.G.BindLights(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);let a=this._scene.ambientColor;a&&e.setColor3("ambientFromScene",a);let o=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);e.setFloat(this._invertNormalName,o?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);let l=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((l-1)/(l+1),2)*this._metallicF0Factor,rg.zZ.Color3[0]);let h=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,rg.zZ.Color3[0],h),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;let r=this.worldPosition,s=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));let n="v_"+r.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${r.associatedVariableName}; -`);let a=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==a?void 0:a.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 -`,e._injectAtEnd+=`vClipSpacePosition = gl_Position; -`,e._injectAtEnd+=`#endif -`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:r.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${r.associatedVariableName}; -`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; -`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; -`,t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+`albedoOpacityBlock( - vec4(${t}, 1.), - #ifdef ALBEDO - vec4(1.), - vec2(1., 1.), - #endif - #ifdef OPACITY - vec4(${i}), - vec2(1., 1.), - #endif - albedoOpacityOut - ); - - vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; - float alpha = albedoOpacityOut.alpha; -`}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; -`,t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+`ambientOcclusionBlock( - #ifdef AMBIENT - vec3(${t}), - vec4(0., 1.0, 1.0, 0.), - #endif - aoOut - ); -`}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; -`;return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo; - - reflectivityBlock( - vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), - #ifdef METALLICWORKFLOW - surfaceAlbedo, - ${this._vMetallicReflectanceFactorsName}, - #endif - #ifdef REFLECTIVITY - vec3(0., 0., 1.), - vec4(1.), - #endif - #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) - aoOut.ambientOcclusionColor, - #endif - #ifdef MICROSURFACEMAP - microSurfaceTexel, <== not handled! - #endif - reflectivityOut - ); - - float microSurface = reflectivityOut.microSurface; - float roughness = reflectivityOut.roughness; - - #ifdef METALLICWORKFLOW - surfaceAlbedo = reflectivityOut.surfaceAlbedo; - #endif - #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) - aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; - #endif -`}_buildBlock(e){var t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,C,E,b,y,P,R,A,I,M,D,O,N,F,B,L,w,U,V,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=GetEnvironmentBRDFTexture(this._scene));let z=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;if(z&&(z.worldPositionConnectionPoint=this.worldPosition,z.cameraPositionConnectionPoint=this.cameraPosition,z.worldNormalConnectionPoint=this.worldNormal,z.viewConnectionPoint=this.view),e.target!==tg.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);let W=`//${this.name}`,H=this.perturbedNormal,X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X}; -`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz; -`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 -`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); -`,e.compilationString+=`#endif -`):X="v_"+X,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",W),e._emitFunctionFromInclude("importanceSampling",W),e._emitFunctionFromInclude("pbrHelperFunctions",W),e._emitFunctionFromInclude("imageProcessingDeclaration",W),e._emitFunctionFromInclude("imageProcessingFunctions",W),e._emitFunctionFromInclude("shadowsFragmentFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",W),e._emitFunctionFromInclude("pbrBRDFFunctions",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(i=null==z?void 0:z._defineSkyboxName)&&void 0!==i?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",W),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",W),e._emitFunctionFromInclude("pbrBlockReflectivity",W),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",W),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",W),e._emitFunctionFromInclude("pbrBlockAnisotropic",W),e._emitUniformFromString("vLightingIntensity","vec4"),(null==z?void 0:z.generateOnlyFragmentCode)&&(e.compilationString+=z.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName}); -`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz); -`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; -`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"}; -`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",W),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",W),e.compilationString+=`#ifdef UNLIT - vec3 diffuseBase = vec3(1., 1., 1.); - #else -`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(r=null==z?void 0:z._defineSkyboxName)&&void 0!==r?r:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});let Y=this.anisotropy.isConnected?null===(n=this.anisotropy.connectedPoint)||void 0===n?void 0:n.ownerBlock:null;Y&&(Y.worldPositionConnectionPoint=this.worldPosition,Y.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=Y.getCode(e,!this.perturbedNormal.isConnected)),z&&z.hasTexture&&(e.compilationString+=z.getCode(e,Y?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(a=null==z?void 0:z._define3DName)&&void 0!==a?a:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(o=null==z?void 0:z._defineOppositeZ)&&void 0!==o?o:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(l=null==z?void 0:z._defineProjectionName)&&void 0!==l?l:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(h=null==z?void 0:z._defineSkyboxName)&&void 0!==h?h:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(u=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==u?u:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(c=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==c?c:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(d=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==d?d:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});let j=this.sheen.isConnected?null===(p=this.sheen.connectedPoint)||void 0===p?void 0:p.ownerBlock:null;j&&(e.compilationString+=j.getCode(z)),e._emitFunctionFromInclude("pbrBlockSheen",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(_=null==z?void 0:z._define3DName)&&void 0!==_?_:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(f=null==z?void 0:z._defineSkyboxName)&&void 0!==f?f:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(m=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==m?m:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(g=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==g?g:"LINEARSPECULARREFLECTION"}]});let K=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=IridescenceBlock.GetCode(K),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});let $=this.clearcoat.isConnected?null===(x=this.clearcoat.connectedPoint)||void 0===x?void 0:x.ownerBlock:null,Q=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Z=this.perturbedNormal.isConnected&&(null===(S=(null===(T=this.perturbedNormal.connectedPoint)||void 0===T?void 0:T.ownerBlock).worldTangent)||void 0===S?void 0:S.isConnected),J=this.anisotropy.isConnected&&(null===(C=this.anisotropy.connectedPoint)||void 0===C?void 0:C.ownerBlock).worldTangent.isConnected,ee=Z||!this.perturbedNormal.isConnected&&J;e.compilationString+=ClearCoatBlock.GetCode(e,$,z,X,Q,ee,this.worldNormal.associatedVariableName),Q&&(ee=null!==(E=null==$?void 0:$.worldTangent.isConnected)&&void 0!==E&&E),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(b=null==z?void 0:z._define3DName)&&void 0!==b?b:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(y=null==z?void 0:z._defineOppositeZ)&&void 0!==y?y:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(P=null==z?void 0:z._defineProjectionName)&&void 0!==P?P:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(R=null==z?void 0:z._defineSkyboxName)&&void 0!==R?R:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(A=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==A?A:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(I=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==I?I:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:ee?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(M=null==z?void 0:z._defineSkyboxName)&&void 0!==M?M:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(D=null==z?void 0:z._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});let et=this.subsurface.isConnected?null===(O=this.subsurface.connectedPoint)||void 0===O?void 0:O.ownerBlock:null,ei=this.subsurface.isConnected?null===(F=(null===(N=this.subsurface.connectedPoint)||void 0===N?void 0:N.ownerBlock).refraction.connectedPoint)||void 0===F?void 0:F.ownerBlock:null;ei&&(ei.viewConnectionPoint=this.view,ei.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=SubSurfaceBlock.GetCode(e,et,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(B=null==z?void 0:z._define3DName)&&void 0!==B?B:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(L=null==z?void 0:z._defineOppositeZ)&&void 0!==L?L:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(w=null==z?void 0:z._defineProjectionName)&&void 0!==w?w:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(U=null==ei?void 0:ei._define3DName)&&void 0!==U?U:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(V=null==ei?void 0:ei._defineLODRefractionAlpha)&&void 0!==V?V:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==ei?void 0:ei._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==ei?void 0:ei._defineOppositeZ)&&void 0!==G?G:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",W),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:X+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{repeatKey:"maxSimultaneousLights",replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",W),e.compilationString+=`#endif -`;let er=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",es=pbrBaseMaterial_PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();for(let t of(-1===es.indexOf(".")&&(es+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:er+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:es}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",W,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",W,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",W,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:X},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]}),this._outputs))if(t.hasEndpoints){let i=lF[t.name];if(i){let[r,s]=i;s&&(e.compilationString+=`#if ${s} -`),e.compilationString+=`${this._declareOutput(t,e)} = ${r}; -`,s&&(e.compilationString+=`#else -`,e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.); -`,e.compilationString+=`#endif -`)}else console.error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; -${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; -${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; -${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; -${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; -${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; -${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; -${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; -${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; -${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; -${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; -${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; -${this._codeVariableName}.unlit = ${this.unlit}; -${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; -${this._codeVariableName}.debugMode = ${this.debugMode}; -${this._codeVariableName}.debugLimit = ${this.debugLimit}; -${this._codeVariableName}.debugFactor = ${this.debugFactor}; -`}serialize(){let e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){var r,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(r=e.lightFalloff)&&void 0!==r?r:0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=null!==(s=e.realTimeFilteringQuality)&&void 0!==s?s:8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}};(0,rH.gn)([editableInPropertyPage("Direct lights",tT.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"directIntensity",void 0),(0,rH.gn)([editableInPropertyPage("Environment lights",tT.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"environmentIntensity",void 0),(0,rH.gn)([editableInPropertyPage("Specular highlights",tT.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"specularIntensity",void 0),(0,rH.gn)([editableInPropertyPage("Light falloff",tT.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_GLTF},{label:"Standard",value:pbrBaseMaterial_PBRBaseMaterial.LIGHTFALLOFF_STANDARD}]})],PBRMetallicRoughnessBlock.prototype,"lightFalloff",void 0),(0,rH.gn)([editableInPropertyPage("Alpha Testing",tT.Boolean,"OPACITY")],PBRMetallicRoughnessBlock.prototype,"useAlphaTest",void 0),(0,rH.gn)([editableInPropertyPage("Alpha CutOff",tT.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"alphaTestCutoff",void 0),(0,rH.gn)([editableInPropertyPage("Alpha blending",tT.Boolean,"OPACITY")],PBRMetallicRoughnessBlock.prototype,"useAlphaBlending",void 0),(0,rH.gn)([editableInPropertyPage("Radiance over alpha",tT.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useRadianceOverAlpha",void 0),(0,rH.gn)([editableInPropertyPage("Specular over alpha",tT.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useSpecularOverAlpha",void 0),(0,rH.gn)([editableInPropertyPage("Specular anti-aliasing",tT.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"enableSpecularAntiAliasing",void 0),(0,rH.gn)([editableInPropertyPage("Realtime filtering",tT.Boolean,"RENDERING",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"realTimeFiltering",void 0),(0,rH.gn)([editableInPropertyPage("Realtime filtering quality",tT.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],PBRMetallicRoughnessBlock.prototype,"realTimeFilteringQuality",void 0),(0,rH.gn)([editableInPropertyPage("Energy Conservation",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useEnergyConservation",void 0),(0,rH.gn)([editableInPropertyPage("Radiance occlusion",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useRadianceOcclusion",void 0),(0,rH.gn)([editableInPropertyPage("Horizon occlusion",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"useHorizonOcclusion",void 0),(0,rH.gn)([editableInPropertyPage("Unlit",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"unlit",void 0),(0,rH.gn)([editableInPropertyPage("Force normal forward",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"forceNormalForward",void 0),(0,rH.gn)([editableInPropertyPage("Generate only fragment code",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:PBRMetallicRoughnessBlock._OnGenerateOnlyFragmentCodeChanged}})],PBRMetallicRoughnessBlock.prototype,"generateOnlyFragmentCode",void 0),(0,rH.gn)([editableInPropertyPage("Debug mode",tT.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],PBRMetallicRoughnessBlock.prototype,"debugMode",void 0),(0,rH.gn)([editableInPropertyPage("Split position",tT.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"debugLimit",void 0),(0,rH.gn)([editableInPropertyPage("Output factor",tT.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],PBRMetallicRoughnessBlock.prototype,"debugFactor",void 0),(0,rv.H)("BABYLON.PBRMetallicRoughnessBlock",PBRMetallicRoughnessBlock);let ModBlock=class ModBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("left",tm.AutoDetect),this.registerInput("right",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.ModBlock",ModBlock);let MatrixBuilderBlock=class MatrixBuilderBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("row0",tm.Vector4),this.registerInput("row1",tm.Vector4),this.registerInput("row2",tm.Vector4),this.registerInput("row3",tm.Vector4),this.registerOutput("output",tm.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){let e=new InputBlock("row0");e.value=new rm.Lt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){let e=new InputBlock("row1");e.value=new rm.Lt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){let e=new InputBlock("row2");e.value=new rm.Lt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){let e=new InputBlock("row3");e.value=new rm.Lt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${n.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.MatrixBuilder",MatrixBuilderBlock),(eO=iO||(iO={}))[eO.Equal=0]="Equal",eO[eO.NotEqual=1]="NotEqual",eO[eO.LessThan=2]="LessThan",eO[eO.GreaterThan=3]="GreaterThan",eO[eO.LessOrEqual=4]="LessOrEqual",eO[eO.GreaterOrEqual=5]="GreaterOrEqual",eO[eO.Xor=6]="Xor",eO[eO.Or=7]="Or",eO[eO.And=8]="And";let ConditionalBlock=class ConditionalBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.condition=iO.LessThan,this.registerInput("a",tm.Float),this.registerInput("b",tm.Float),this.registerInput("true",tm.AutoDetect,!0),this.registerInput("false",tm.AutoDetect,!0),this.registerOutput("output",tm.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=tm.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case iO.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iO.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iO.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iO.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iO.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iO.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${r}; -`;break;case iO.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${r}; -`;break;case iO.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${r}; -`;break;case iO.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${r}; -`}return this}serialize(){let e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${iO[this.condition]}; -`;return e}};(0,rv.H)("BABYLON.ConditionalBlock",ConditionalBlock);let CloudBlock=class CloudBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.octaves=6,this.registerInput("seed",tm.AutoDetect),this.registerInput("chaos",tm.AutoDetect,!0),this.registerInput("offsetX",tm.Float,!0),this.registerInput("offsetY",tm.Float,!0),this.registerInput("offsetZ",tm.Float,!0),this.registerOutput("output",tm.Float),this._inputs[0].acceptedConnectionPointTypes.push(tm.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(tm.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var t,i;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let r=` - - float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } - - // Based on Morgan McGuire @morgan3d - // https://www.shadertoy.com/view/4dS3Wd - float cloudNoise(in vec2 x, in vec2 chaos) { - vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); - - vec2 i = floor(x); - vec2 f = fract(x); - - float n = dot(i, step); - - vec2 u = f * f * (3.0 - 2.0 * f); - return mix( - mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), - mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), - u.y - ); - } - - float cloudNoise(in vec3 x, in vec3 chaos) { - vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); - - vec3 i = floor(x); - vec3 f = fract(x); - - float n = dot(i, step); - - vec3 u = f * f * (3.0 - 2.0 * f); - return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), - mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), - mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), - mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); - }`,s=` - float fbm(in vec2 st, in vec2 chaos) { - // Initial values - float value = 0.0; - float amplitude = .5; - float frequency = 0.; - - // Loop of octaves - for (int i = 0; i < OCTAVES; i++) { - value += amplitude * cloudNoise(st, chaos); - st *= 2.0; - amplitude *= 0.5; - } - return value; - } - - float fbm(in vec3 x, in vec3 chaos) { - // Initial values - float value = 0.0; - float amplitude = 0.5; - for (int i = 0; i < OCTAVES; ++i) { - value += amplitude * cloudNoise(x, chaos); - x = x * 2.0; - amplitude *= 0.5; - } - return value; - }`,n=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",r,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,s.replace(/fbm/gi,n).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");let a=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===tm.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${a} = ${this.seed.associatedVariableName}; -`,this.offsetX.isConnected&&(e.compilationString+=`${a}.x += 0.1 * ${this.offsetX.associatedVariableName}; -`),this.offsetY.isConnected&&(e.compilationString+=`${a}.y += 0.1 * ${this.offsetY.associatedVariableName}; -`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${a}.z += 0.1 * ${this.offsetZ.associatedVariableName}; -`);let l="";return l=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===tm.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${n}(${a}, ${l}); -`,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; -`;return e}serialize(){let e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}};(0,rH.gn)([editableInPropertyPage("Octaves",tT.Int)],CloudBlock.prototype,"octaves",void 0),(0,rv.H)("BABYLON.CloudBlock",CloudBlock);let VoronoiNoiseBlock=class VoronoiNoiseBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("seed",tm.Vector2),this.registerInput("offset",tm.Float),this.registerInput("density",tm.Float),this.registerOutput("output",tm.Float),this.registerOutput("cells",tm.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){ - mat2 m = mat2(15.27, 47.63, 99.41, 89.98); - vec2 uv = fract(sin(m * seed) * 46839.32); - return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); - } - `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ - vec2 g = floor(seed * density); - vec2 f = fract(seed * density); - float t = 8.0; - vec3 res = vec3(8.0, 0.0, 0.0); - - for(int y=-1; y<=1; y++) - { - for(int x=-1; x<=1; x++) - { - vec2 lattice = vec2(x,y); - vec2 randomOffset = voronoiRandom(lattice + g, offset); - float d = distance(lattice + randomOffset, f); - if(d < res.x) - { - res = vec3(d, randomOffset.x, randomOffset.y); - outValue = res.x; - cells = res.y; - } - } - } - } - `,e._emitFunction("voronoi",t,"// Voronoi");let i=e._getFreeVariableName("tempOutput"),r=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; -`,e.compilationString+=`float ${r} = 0.0; -`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${r}); -`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; -`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${r}; -`),this}};(0,rv.H)("BABYLON.VoronoiNoiseBlock",VoronoiNoiseBlock);let ElbowBlock=class ElbowBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==tg.VertexAndFragment)return t.target;if(e.connectedPoint.target!==tg.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName}; -`,this}};(0,rv.H)("BABYLON.ElbowBlock",ElbowBlock);let TriPlanarBlock=class TriPlanarBlock extends NodeMaterialBlock{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?(null===(e=this.sourceY.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(null===(e=this.sourceZ)||void 0===e?void 0:e.isConnected)?(null===(t=this.sourceY.connectedPoint)||void 0===t?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return(null==e?void 0:e.isConnected)?e.connectedPoint.ownerBlock:null}get samplerName(){let e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceY))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get samplerZName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceZ))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rS.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,tg.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",tm.AutoDetect,!1),this.registerInput("normal",tm.AutoDetect,!1),this.registerInput("sharpness",tm.Float,!0),this.registerInput("source",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("source",this,tx.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerInput("sourceY",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("sourceY",this,tx.Input,ImageSourceBlock,"ImageSourceBlock")),t||this.registerInput("sourceZ",tm.Object,!0,tg.VertexAndFragment,new NodeMaterialConnectionPointCustomObject("sourceZ",this,tx.Input,ImageSourceBlock,"ImageSourceBlock")),this.registerOutput("rgba",tm.Color4,tg.Neutral),this.registerOutput("rgb",tm.Color3,tg.Neutral),this.registerOutput("r",tm.Float,tg.Neutral),this.registerOutput("g",tm.Float,tg.Neutral),this.registerOutput("b",tm.Float,tg.Neutral),this.registerOutput("a",tm.Float,tg.Neutral),this.registerOutput("level",tm.Float,tg.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(tm.Color3|tm.Vector3|tm.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;let r=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:r,n=null!==(i=this.samplerZName)&&void 0!==i?i:r,a=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",o=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),c=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),_=e._getFreeVariableName("uvz");e.compilationString+=` - vec3 ${c} = ${this.normal.associatedVariableName}.xyz; - - vec2 ${d} = ${this.position.associatedVariableName}.yz; - vec2 ${p} = ${this.position.associatedVariableName}.zx; - vec2 ${_} = ${this.position.associatedVariableName}.xy; - `,this.projectAsCube&&(e.compilationString+=` - ${d}.xy = ${d}.yx; - - if (${c}.x >= 0.0) { - ${d}.x = -${d}.x; - } - if (${c}.y < 0.0) { - ${p}.y = -${p}.y; - } - if (${c}.z < 0.0) { - ${_}.x = -${_}.x; - } - `),e.compilationString+=` - vec4 ${o} = texture2D(${r}, ${d}); - vec4 ${l} = texture2D(${s}, ${p}); - vec4 ${h} = texture2D(${n}, ${_}); - - // blend weights - vec3 ${u} = pow(abs(${c}), vec3(${a})); - - // blend and return - vec4 ${this._tempTextureRead} = (${o}*${u}.x + ${l}*${u}.y + ${h}*${u}.z) / (${u}.x + ${u}.y + ${u}.z); - `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} - ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); - #endif - `),e.compilationString+=`#ifdef ${this._gammaDefineName} - ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); - #endif - `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; -`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e),this._outputs))i.hasEndpoints&&"level"!==i.name&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; -${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; -${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; -${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; -`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); -${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; -${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; -${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; -${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; -${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; -${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; -${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; -${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; -${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; -${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; -`:e}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!NodeMaterial.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=texture_Texture.Parse(e.texture,t,i))}};(0,rH.gn)([editableInPropertyPage("Project as cube",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],TriPlanarBlock.prototype,"projectAsCube",void 0),(0,rv.H)("BABYLON.TriPlanarBlock",TriPlanarBlock);let BiPlanarBlock=class BiPlanarBlock extends TriPlanarBlock{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;let i=this.samplerName,r=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=` - // grab coord derivatives for texturing - vec3 ${n} = dFdx(${this.position.associatedVariableName}.xyz); - vec3 ${a} = dFdy(${this.position.associatedVariableName}.xyz); - vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); - - // determine major axis (in x; yz are following axis) - ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : - (${o}.y>${o}.z) ? ivec3(1,2,0) : - ivec3(2,0,1) ; - // determine minor axis (in x; yz are following axis) - ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : - (${o}.y<${o}.z) ? ivec3(1,2,0) : - ivec3(2,0,1) ; - // determine median axis (in x; yz are following axis) - ivec3 ${u} = ivec3(3) - ${h} - ${l}; - - // project+fetch - vec4 ${c} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), - vec2(${n}[${l}.y],${n}[${l}.z]), - vec2(${a}[${l}.y],${a}[${l}.z]) ); - vec4 ${d} = textureGrad( ${r}, vec2( ${this.position.associatedVariableName}[${u}.y], ${this.position.associatedVariableName}[${u}.z]), - vec2(${n}[${u}.y],${n}[${u}.z]), - vec2(${a}[${u}.y],${a}[${u}.z]) ); - - // blend factors - vec2 ${p} = vec2(${o}[${l}.x],${o}[${u}.x]); - // make local support - ${p} = clamp( (${p}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); - // shape transition - ${p} = pow( ${p}, vec2(${s}/8.0) ); - // blend and return - vec4 ${this._tempTextureRead} = (${c}*${p}.x + ${d}*${p}.y) / (${p}.x + ${p}.y); - `}};(0,rv.H)("BABYLON.BiPlanarBlock",BiPlanarBlock);let MatrixDeterminantBlock=class MatrixDeterminantBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.Matrix),this.registerOutput("output",tm.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.MatrixDeterminantBlock",MatrixDeterminantBlock);let MatrixTransposeBlock=class MatrixTransposeBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.registerInput("input",tm.Matrix),this.registerOutput("output",tm.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); -`,this}};(0,rv.H)("BABYLON.MatrixTransposeBlock",MatrixTransposeBlock),(eN=iN||(iN={}))[eN.None=0]="None",eN[eN.Normal=1]="Normal",eN[eN.Tangent=2]="Tangent",eN[eN.VertexColor=3]="VertexColor",eN[eN.UV1=4]="UV1",eN[eN.UV2=5]="UV2",eN[eN.UV3=6]="UV3",eN[eN.UV4=7]="UV4",eN[eN.UV5=8]="UV5",eN[eN.UV6=9]="UV6";let MeshAttributeExistsBlock=class MeshAttributeExistsBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.attributeType=iN.None,this.registerInput("input",tm.AutoDetect),this.registerInput("fallback",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(e=>{var t;if(this.attributeType)return;let i=e.ownerBlock;if(i instanceof InputBlock&&i.isAttribute)switch(i.name){case"color":this.attributeType=iN.VertexColor;break;case"normal":this.attributeType=iN.Normal;break;case"tangent":this.attributeType=iN.Tangent;break;case"uv":this.attributeType=iN.UV1;break;case"uv2":this.attributeType=iN.UV2;break;case"uv3":this.attributeType=iN.UV3;break;case"uv4":this.attributeType=iN.UV4;break;case"uv5":this.attributeType=iN.UV5;break;case"uv6":this.attributeType=iN.UV6}else if(i instanceof MorphTargetsBlock)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=iN.Normal;break;case"tangentOutput":this.attributeType=iN.Tangent;break;case"uvOutput":this.attributeType=iN.UV1}})}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case iN.VertexColor:t="VERTEXCOLOR_NME";break;case iN.Normal:t="NORMAL";break;case iN.Tangent:t="TANGENT";break;case iN.UV1:t="UV1";break;case iN.UV2:t="UV2";break;case iN.UV3:t="UV3";break;case iN.UV4:t="UV4";break;case iN.UV5:t="UV5";break;case iN.UV6:t="UV6"}let i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} -`),e.compilationString+=`${i} = ${this.input.associatedVariableName}; -`,t&&(e.compilationString+=`#else -`,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; -`,e.compilationString+=`#endif -`),this}serialize(){let e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.attributeType=null!==(r=e.attributeType)&&void 0!==r?r:iN.None}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.attributeType = ${this.attributeType}; -`}};(0,rH.gn)([editableInPropertyPage("Attribute lookup",tT.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:iN.None},{label:"Normal",value:iN.Normal},{label:"Tangent",value:iN.Tangent},{label:"Vertex Color",value:iN.VertexColor},{label:"UV1",value:iN.UV1},{label:"UV2",value:iN.UV2},{label:"UV3",value:iN.UV3},{label:"UV4",value:iN.UV4},{label:"UV5",value:iN.UV5},{label:"UV6",value:iN.UV6}]})],MeshAttributeExistsBlock.prototype,"attributeType",void 0),(0,rv.H)("BABYLON.MeshAttributeExistsBlock",MeshAttributeExistsBlock),(eF=iF||(iF={}))[eF.EaseInSine=0]="EaseInSine",eF[eF.EaseOutSine=1]="EaseOutSine",eF[eF.EaseInOutSine=2]="EaseInOutSine",eF[eF.EaseInQuad=3]="EaseInQuad",eF[eF.EaseOutQuad=4]="EaseOutQuad",eF[eF.EaseInOutQuad=5]="EaseInOutQuad",eF[eF.EaseInCubic=6]="EaseInCubic",eF[eF.EaseOutCubic=7]="EaseOutCubic",eF[eF.EaseInOutCubic=8]="EaseInOutCubic",eF[eF.EaseInQuart=9]="EaseInQuart",eF[eF.EaseOutQuart=10]="EaseOutQuart",eF[eF.EaseInOutQuart=11]="EaseInOutQuart",eF[eF.EaseInQuint=12]="EaseInQuint",eF[eF.EaseOutQuint=13]="EaseOutQuint",eF[eF.EaseInOutQuint=14]="EaseInOutQuint",eF[eF.EaseInExpo=15]="EaseInExpo",eF[eF.EaseOutExpo=16]="EaseOutExpo",eF[eF.EaseInOutExpo=17]="EaseInOutExpo",eF[eF.EaseInCirc=18]="EaseInCirc",eF[eF.EaseOutCirc=19]="EaseOutCirc",eF[eF.EaseInOutCirc=20]="EaseInOutCirc",eF[eF.EaseInBack=21]="EaseInBack",eF[eF.EaseOutBack=22]="EaseOutBack",eF[eF.EaseInOutBack=23]="EaseInOutBack",eF[eF.EaseInElastic=24]="EaseInElastic",eF[eF.EaseOutElastic=25]="EaseOutElastic",eF[eF.EaseInOutElastic=26]="EaseInOutElastic";let CurveBlock=class CurveBlock extends NodeMaterialBlock{constructor(e){super(e,tg.Neutral),this.type=iF.EaseInOutSine,this.registerInput("input",tm.AutoDetect),this.registerOutput("output",tm.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tm.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tm.Object),this._inputs[0].excludedConnectionPointTypes.push(tm.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if("float"===t)return this._duplicateEntryDirect(e);let i=parseInt(t.replace("vec","")),r=` - vec${i} ret = vec${i}(0.0); - `;for(let t=1;t<=i;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+"return ret;\n"}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="",r="",s="";switch(this.input.type){case tm.Float:s="float";break;case tm.Vector2:s="vec2";break;case tm.Vector3:case tm.Color3:s="vec3";break;case tm.Vector4:case tm.Color4:s="vec4"}switch(r=iF[this.type]+"_"+s,this.type){case iF.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case iF.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case iF.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case iF.EaseInQuad:i="return v * v";break;case iF.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case iF.EaseInOutQuad:i=this._duplicateVector("VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0",s);break;case iF.EaseInCubic:i="return v * v * v";break;case iF.EaseOutCubic:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s);break;case iF.EaseInOutCubic:i=this._duplicateVector("VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0",s);break;case iF.EaseInQuart:i="return v * v * v * v";break;case iF.EaseOutQuart:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s);break;case iF.EaseInOutQuart:i=this._duplicateVector("VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0",s);break;case iF.EaseInQuint:i="return v * v * v * v * v";break;case iF.EaseOutQuint:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s);break;case iF.EaseInOutQuint:i=this._duplicateVector("VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0",s);break;case iF.EaseInExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)",s);break;case iF.EaseOutExpo:i=this._duplicateVector("VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)",s);break;case iF.EaseInOutExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0",s);break;case iF.EaseInCirc:i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s);break;case iF.EaseOutCirc:i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s);break;case iF.EaseInOutCirc:i=this._duplicateVector("VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0",s);break;case iF.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case iF.EaseOutBack:i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s);break;case iF.EaseInOutBack:i=this._duplicateVector("VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0",s);break;case iF.EaseInElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))",s);break;case iF.EaseOutElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0",s);break;case iF.EaseInOutElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0",s)}return e._emitFunction(r,`${s} ${r}(${s} v) {${i};} -`,""),e.compilationString+=this._declareOutput(t,e)+` = ${r}(${this.input.associatedVariableName}); -`,this}serialize(){let e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${iF[this.type]}; -`;return e}};(0,rv.H)("BABYLON.CurveBlock",CurveBlock);let DecalMapDefines=class DecalMapDefines extends sn.H{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}};let DecalMapConfiguration=class DecalMapConfiguration extends MaterialPluginBase{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new DecalMapDefines,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;return!this._isEnabled||null==s||!s.texture||!MaterialFlags.DecalMapEnabled||!t.texturesEnabled||s.isReady()}prepareDefines(e,t,i){let r=i.decalMap;if(this._isEnabled&&(null==r?void 0:r.texture)&&MaterialFlags.DecalMapEnabled&&t.texturesEnabled){let t=!e.DECAL||e.GAMMADECAL!==r.texture.gammaSpace;t&&e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=r.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,so.G.PrepareDefinesForMergedUV(r.texture,e,"DECAL")}else{let t=e.DECAL;t&&e.markAsTexturesDirty(),e.DECAL=!1}}hardBindForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;if(!this._isEnabled||!(null==s?void 0:s.texture)||!MaterialFlags.DecalMapEnabled||!t.texturesEnabled)return;let n=this._material.isFrozen,a=s.texture;e.useUbo&&n&&e.isSync||(e.updateFloat4("vDecalInfos",a.coordinatesIndex,0,0,0),so.G.BindTextureMatrix(a,e,"decal")),e.setTexture("decalSampler",a)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}};(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],DecalMapConfiguration.prototype,"isEnabled",void 0),(0,rH.gn)([(0,rb.qC)(),(0,rb.wz)("_markAllSubMeshesAsTexturesDirty")],DecalMapConfiguration.prototype,"smoothAlpha",void 0),(0,rv.H)("BABYLON.DecalMapConfiguration",DecalMapConfiguration),(eB=iB||(iB={}))[eB.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",eB[eB.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",eB[eB.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE",(eL=iL||(iL={}))[eL.COLOR_MODE_SET=0]="COLOR_MODE_SET",eL[eL.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",eL[eL.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY",(ew=iw||(iw={}))[ew.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",ew[ew.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE";let greasedLineMaterialDefaults_GreasedLineMaterialDefaults=class greasedLineMaterialDefaults_GreasedLineMaterialDefaults{};greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR=rg.Wo.White(),greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED=1,greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH=.1;let greasedLineTools_GreasedLineTools=class greasedLineTools_GreasedLineTools{static ConvertPoints(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof rm.P){let t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof rm.P){let t=[];return e.forEach(e=>{t.push(e.flatMap(e=>[e.x,e.y,e.z]))}),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){let t=[];return e.forEach(e=>{t.push(Array.from(e))}),t}return[]}static OmitZeroLengthPredicate(e,t,i){let r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r}static OmitDuplicatesPredicate(e,t,i,r){let s=[];return greasedLineTools_GreasedLineTools._SearchInPoints(e,t,r)||s.push([e,t]),greasedLineTools_GreasedLineTools._SearchInPoints(t,i,r)||s.push([t,i]),greasedLineTools_GreasedLineTools._SearchInPoints(i,e,r)||s.push([i,e]),0===s.length?null:s}static _SearchInPoints(e,t,i){var r,s,n;for(let a of i)for(let i=0;i{let s=e.getVerticesData(rz.o.PositionKind),n=e.getIndices();if(s&&n)for(let a=0,o=0;a[e.x,e.y,e.z])}static GetPointsCountInfo(e){let t=Array(e.length),i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){let t;if(0===e.length)return 0;t="number"==typeof e[0]?greasedLineTools_GreasedLineTools.ToVector3Array(e):e;let i=rm.jp.Vector3[0],r=0;for(let e=0;e{if(e.length>t){let i=greasedLineTools_GreasedLineTools.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t));i.forEach(e=>{r.push(e)})}else r.push(e.point1),r.push(e.point2)}),r}static SegmentizeLineBySegmentCount(e,t){let i="number"==typeof e[0]?greasedLineTools_GreasedLineTools.ToVector3Array(e):e,r=greasedLineTools_GreasedLineTools.GetLineLength(i)/t;return greasedLineTools_GreasedLineTools.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){let t=[];for(let i=0;ie.length);return{min:i[0].length,max:i[i.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){let s=t*i,n=0,a=0,o=e.length;for(let t=0;t[e.x,e.y,e.z])}static GetArrowCap(e,t,i,r,s,n=0,a=0){let o=[e.clone(),e.add(t.multiplyByFloats(i,i,i))];return{points:o,widths:[r,s,n,a]}}static GetPointsFromText(e,t,i,r,s=0,n=!0){let a=[],o=CreateTextShapePaths(e,t,i,r);for(let e of o){for(let t of e.paths){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);a.push(e)}if(n)for(let t of e.holes){let e=[],i=t.getPoints();for(let t of i)e.push(t.x,t.y,s);a.push(e)}}return a}static Color3toRGBAUint8(e){let t=new Uint8Array(4*e.length);for(let i=0,r=0;i{greasedLineTools_GreasedLineTools.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){let e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?` - uniform vec4 grl_aspect_resolution_lineWidth; - uniform mat4 grl_projection; - `:"",fragment:` - uniform vec4 grl_dashOptions; - uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; - uniform vec3 grl_singleColor; - `}}get isEnabled(){return!0}bindForSubMesh(e){var t;if(this._cameraFacing){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}else throw Error("GreasedLinePluginMaterial requires an active camera.");let i=rm.jp.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}let i=rm.jp.Vector4[0];i.x=greasedLineTools_GreasedLineTools.BooleanToNumber(this.useDash),i.y=this._dashArray,i.z=this.dashOffset,i.w=this.dashRatio,e.updateVector4("grl_dashOptions",i);let r=rm.jp.Vector4[1];r.x=this.colorMode,r.y=this.visibility,r.z=this.colorsTexture?this.colorsTexture.getSize().width:0,r.w=greasedLineTools_GreasedLineTools.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",r),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",null!==(t=this.colorsTexture)&&void 0!==t?t:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===iw.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){let e={CUSTOM_VERTEX_DEFINITIONS:` - attribute float grl_widths; - attribute vec3 grl_offsets; - attribute float grl_colorPointers; - - varying float grlCounters; - varying float grlColorPointer; - - #ifdef GREASED_LINE_CAMERA_FACING - attribute vec4 grl_previousAndSide; - attribute vec4 grl_nextAndCounters; - - vec2 grlFix( vec4 i, float aspect ) { - vec2 res = i.xy / i.w; - res.x *= aspect; - return res; - } - #else - attribute vec3 grl_slopes; - attribute float grl_counters; - #endif - `,CUSTOM_VERTEX_UPDATE_POSITION:` - #ifdef GREASED_LINE_CAMERA_FACING - vec3 grlPositionOffset = grl_offsets; - positionUpdated += grlPositionOffset; - #else - positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); - #endif - `,CUSTOM_VERTEX_MAIN_END:` - grlColorPointer = grl_colorPointers; - - #ifdef GREASED_LINE_CAMERA_FACING - - float grlAspect = grl_aspect_resolution_lineWidth.x; - float grlBaseWidth = grl_aspect_resolution_lineWidth.w; - - - vec3 grlPrevious = grl_previousAndSide.xyz; - float grlSide = grl_previousAndSide.w; - - vec3 grlNext = grl_nextAndCounters.xyz; - grlCounters = grl_nextAndCounters.w; - - mat4 grlMatrix = viewProjection * finalWorld; - vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); - vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); - vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); - - vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); - vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); - vec2 grlNextP = grlFix( grlNextPos, grlAspect ); - - float grlWidth = grlBaseWidth * grl_widths; - - vec2 grlDir; - if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); - else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); - else { - vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); - vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); - grlDir = normalize( grlDir1 + grlDir2 ); - } - vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); - #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM - grlNormal.xy *= -.5 * grlWidth; - #else - grlNormal.xy *= .5 * grlWidth; - #endif - - grlNormal *= grl_projection; - - #ifdef GREASED_LINE_SIZE_ATTENUATION - grlNormal.xy *= grlFinalPosition.w; - grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; - #endif - - grlFinalPosition.xy += grlNormal.xy * grlSide; - gl_Position = grlFinalPosition; - - vPositionW = vec3(grlFinalPosition); - #else - grlCounters = grl_counters; - #endif - `};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:` - varying float grlCounters; - varying float grlColorPointer; - uniform sampler2D grl_colors; - `,CUSTOM_FRAGMENT_MAIN_END:` - float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; - float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; - float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; - float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; - - float grlUseDash = grl_dashOptions.x; - float grlDashArray = grl_dashOptions.y; - float grlDashOffset = grl_dashOptions.z; - float grlDashRatio = grl_dashOptions.w; - - gl_FragColor.a *= step(grlCounters, grlVisibility); - if( gl_FragColor.a == 0. ) discard; - - if(grlUseDash == 1.){ - gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); - if (gl_FragColor.a == 0.) discard; - } - - #ifdef GREASED_LINE_HAS_COLOR - if (grlColorMode == ${iL.COLOR_MODE_SET}.) { - gl_FragColor.rgb = grl_singleColor; - } else if (grlColorMode == ${iL.COLOR_MODE_ADD}.) { - gl_FragColor.rgb += grl_singleColor; - } else if (grlColorMode == ${iL.COLOR_MODE_MULTIPLY}.) { - gl_FragColor.rgb *= grl_singleColor; - } - #else - if (grlUseColors == 1.) { - #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE - vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); - #else - vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); - #endif - if (grlColorMode == ${iL.COLOR_MODE_SET}.) { - gl_FragColor = grlColor; - } else if (grlColorMode == ${iL.COLOR_MODE_ADD}.) { - gl_FragColor += grlColor; - } else if (grlColorMode == ${iL.COLOR_MODE_MULTIPLY}.) { - gl_FragColor *= grlColor; - } - } - #endif - - `}:null}dispose(){var e;null===(e=this.colorsTexture)||void 0===e||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this.colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this.colorsTexture&&o===e.length&&!i){let t=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else null===(a=this.colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,t||this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;super.parse(e,t,i);let s=e.greasedLineMaterialOptions;null===(r=this.colorsTexture)||void 0===r||r.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var t;null===(t=e.colorsTexture)||void 0===t||t.dispose(),this._colors&&(e.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${e._material.name}-colors-texture`,this._colors,e.colorsSampling,this._scene)),e.setColor(this.color,!0),e.colorsDistributionType=this.colorsDistributionType,e.colorsSampling=this.colorsSampling,e.colorMode=this.colorMode,e.useColors=this.useColors,e.visibility=this.visibility,e.useDash=this.useDash,e.dashCount=this.dashCount,e.dashRatio=this.dashRatio,e.dashOffset=this.dashOffset,e.width=this.width,e.sizeAttenuation=this.sizeAttenuation,e.resolution=this.resolution,e.markAllDefinesAsDirty()}};greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",(0,rv.H)(`BABYLON.${greasedLinePluginMaterial_GreasedLinePluginMaterial.GREASED_LINE_MATERIAL_NAME}`,greasedLinePluginMaterial_GreasedLinePluginMaterial);let lB=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} -if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { -textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} -if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} -`;s_.v.ShadersStore.greasedLinePixelShader=lB;let lL=`precision highp float; -#include -attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; -#ifdef GREASED_LINE_CAMERA_FACING -attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} -#else -attribute vec3 grl_slopes;attribute float grl_counters; -#endif -void main() { -#include -grlColorPointer=grl_colorPointers; -#ifdef GREASED_LINE_CAMERA_FACING -float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=viewProjection*finalWorld ;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} -vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); -#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM -grlNormal.xy*=-.5*grlWidth; -#else -grlNormal.xy*=.5*grlWidth; -#endif -grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} -grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; -#else -grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; -#endif -} -`;s_.v.ShadersStore.greasedLineVertexShader=lL;let greasedLineSimpleMaterial_GreasedLineSimpleMaterial=class greasedLineSimpleMaterial_GreasedLineSimpleMaterial extends shaderMaterial_ShaderMaterial{constructor(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f,m;let g=[`COLOR_DISTRIBUTION_TYPE_LINE ${iw.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${iw.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${iL.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${iL.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${iL.COLOR_MODE_MULTIPLY}.`],v=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&g.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(g.push("GREASED_LINE_CAMERA_FACING"),v.push("grl_previousAndSide","grl_nextAndCounters")):(v.push("grl_slopes"),v.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:v,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:g}),this._color=rg.Wo.White(),this._colorsDistributionType=iw.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR};let x=t.getEngine();this.visibility=null!==(r=i.visibility)&&void 0!==r?r:1,this.useDash=null!==(s=i.useDash)&&void 0!==s&&s,this.dashRatio=null!==(n=i.dashRatio)&&void 0!==n?n:.5,this.dashOffset=null!==(a=i.dashOffset)&&void 0!==a?a:0,this.dashCount=null!==(o=i.dashCount)&&void 0!==o?o:1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH_ATTENUATED:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_WIDTH,this.sizeAttenuation=null!==(l=i.sizeAttenuation)&&void 0!==l&&l,this.color=null!==(h=i.color)&&void 0!==h?h:rg.Wo.White(),this.useColors=null!==(u=i.useColors)&&void 0!==u&&u,this.colorsDistributionType=null!==(c=i.colorDistributionType)&&void 0!==c?c:iw.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(d=i.colorsSampling)&&void 0!==d?d:rawTexture_RawTexture.NEAREST_NEAREST,this.colorMode=null!==(p=i.colorMode)&&void 0!==p?p:iL.COLOR_MODE_SET,this._colors=null!==(_=i.colors)&&void 0!==_?_:null,this._cameraFacing=null===(f=i.cameraFacing)||void 0===f||f,this.resolution=null!==(m=i.resolution)&&void 0!==m?m:new rm.FM(x.getRenderWidth(),x.getRenderHeight()),i.colorsTexture&&(this.colorsTexture=i.colorsTexture),this._colors&&this.setColors(this._colors),x.onDisposeObservable.add(()=>{greasedLineTools_GreasedLineTools.DisposeEmptyColorsTexture()})}dispose(){var e;null===(e=this._colorsTexture)||void 0===e||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new rm.FM(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this._colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this._colorsTexture&&o===e.length&&!i){let t=greasedLineTools_GreasedLineTools.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else null===(a=this._colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}}get colorsTexture(){var e;return null!==(e=this._colorsTexture)&&void 0!==e?e:null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",greasedLineTools_GreasedLineTools.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=null!=e?e:greasedLineMaterialDefaults_GreasedLineMaterialDefaults.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r,s;let n=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),n.color&&(this.color=n.color),n.colorDistributionType&&(this.colorsDistributionType=n.colorDistributionType),n.colorsSampling&&(this.colorsSampling=n.colorsSampling),n.colorMode&&(this.colorMode=n.colorMode),n.useColors&&(this.useColors=n.useColors),n.visibility&&(this.visibility=n.visibility),n.useDash&&(this.useDash=n.useDash),n.dashCount&&(this.dashCount=n.dashCount),n.dashRatio&&(this.dashRatio=n.dashRatio),n.dashOffset&&(this.dashOffset=n.dashOffset),n.width&&(this.width=n.width),n.sizeAttenuation&&(this.sizeAttenuation=n.sizeAttenuation),n.resolution&&(this.resolution=n.resolution),n.colors?this.colorsTexture=greasedLineTools_GreasedLineTools.CreateColorsTexture(`${this.name}-colors-texture`,n.colors,this.colorsSampling,this.getScene()):greasedLineTools_GreasedLineTools.PrepareEmptyColorsTexture(t),this._cameraFacing=null===(s=n.cameraFacing)||void 0===s||s,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}};let lw=`#if defined(DBG_ENABLED) -attribute float dbg_initialPass; -varying vec3 dbg_vBarycentric; -flat varying vec3 dbg_vVertexWorldPos; -flat varying float dbg_vPass; -#endif`,lU=`#if defined(DBG_ENABLED) -float dbg_vertexIndex = mod(float(gl_VertexID), 3.); -if (dbg_vertexIndex == 0.0) { - dbg_vBarycentric = vec3(1.,0.,0.); -} -else if (dbg_vertexIndex == 1.0) { - dbg_vBarycentric = vec3(0.,1.,0.); -} -else { - dbg_vBarycentric = vec3(0.,0.,1.); -} - -dbg_vVertexWorldPos = vPositionW; -dbg_vPass = dbg_initialPass; -#endif`,lV=`#if defined(DBG_ENABLED) -uniform vec3 dbg_shadedDiffuseColor; -uniform vec4 dbg_shadedSpecularColorPower; -uniform vec3 dbg_thicknessRadiusScale; - -#if DBG_MODE == 2 || DBG_MODE == 3 - uniform vec3 dbg_vertexColor; -#endif - -#if DBG_MODE == 1 - uniform vec3 dbg_wireframeTrianglesColor; -#elif DBG_MODE == 3 - uniform vec3 dbg_wireframeVerticesColor; -#elif DBG_MODE == 4 || DBG_MODE == 5 - uniform vec3 dbg_uvPrimaryColor; - uniform vec3 dbg_uvSecondaryColor; -#elif DBG_MODE == 7 - uniform vec3 dbg_materialColor; -#endif -#endif`,lk=`#if defined(DBG_ENABLED) -varying vec3 dbg_vBarycentric; -flat varying vec3 dbg_vVertexWorldPos; -flat varying float dbg_vPass; - -#if !defined(DBG_MULTIPLY) - vec3 dbg_applyShading(vec3 color) { - vec3 N = vNormalW.xyz; - vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); - vec3 H = normalize(L + L); - float LdotN = clamp(dot(L,N), 0., 1.); - float HdotN = clamp(dot(H,N), 0., 1.); - float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); - color *= (LdotN / PI); - color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); - return color; - } -#endif - -#if DBG_MODE == 1 || DBG_MODE == 3 - float dbg_edgeFactor() { - vec3 d = fwidth(dbg_vBarycentric); - vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); - return min(min(a3.x, a3.y), a3.z); - } -#endif - -#if DBG_MODE == 2 || DBG_MODE == 3 - float dbg_cornerFactor() { - vec3 worldPos = vPositionW; - float dist = length(worldPos - dbg_vVertexWorldPos); - float camDist = length(worldPos - vEyePosition.xyz); - float d = sqrt(camDist) * .001; - return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); - } -#endif - -#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) - float dbg_checkerboardFactor(vec2 uv) { - vec2 f = fract(uv * dbg_thicknessRadiusScale.z); - f -= .5; - return (f.x * f.y) > 0. ? 1. : 0.; - } -#endif -#endif`,lG=`#if defined(DBG_ENABLED) -vec3 dbg_color = vec3(1.); -#if DBG_MODE == 1 - dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); -#elif DBG_MODE == 2 || DBG_MODE == 3 - float dbg_cornerFactor = dbg_cornerFactor(); - if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; - dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); - #if DBG_MODE == 3 - dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); - #endif -#elif DBG_MODE == 4 && defined(UV1) - dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); -#elif DBG_MODE == 5 && defined(UV2) - dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); -#elif DBG_MODE == 6 && defined(VERTEXCOLOR) - dbg_color = vColor.rgb; -#elif DBG_MODE == 7 - dbg_color = dbg_materialColor; -#endif - -#if defined(DBG_MULTIPLY) - gl_FragColor *= vec4(dbg_color, 1.); -#else - #if DBG_MODE != 6 - gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); - #else - gl_FragColor = vec4(dbg_color, 1.); - #endif -#endif -#endif`,lz=[new rg.Wo(.98,.26,.38),new rg.Wo(.47,.75,.3),new rg.Wo(0,.26,.77),new rg.Wo(.97,.6,.76),new rg.Wo(.19,.63,.78),new rg.Wo(.98,.8,.6),new rg.Wo(.65,.43,.15),new rg.Wo(.15,.47,.22),new rg.Wo(.67,.71,.86),new rg.Wo(.09,.46,.56),new rg.Wo(.8,.98,.02),new rg.Wo(.39,.29,.13),new rg.Wo(.53,.63,.06),new rg.Wo(.95,.96,.41),new rg.Wo(1,.72,.94),new rg.Wo(.63,.08,.31),new rg.Wo(.66,.96,.95),new rg.Wo(.22,.14,.19),new rg.Wo(.14,.65,.59),new rg.Wo(.93,1,.68),new rg.Wo(.93,.14,.44),new rg.Wo(.47,.86,.67),new rg.Wo(.85,.07,.78),new rg.Wo(.53,.64,.98),new rg.Wo(.43,.37,.56),new rg.Wo(.71,.65,.25),new rg.Wo(.66,.19,.01),new rg.Wo(.94,.53,.12),new rg.Wo(.41,.44,.44),new rg.Wo(.24,.71,.96),new rg.Wo(.57,.28,.56),new rg.Wo(.44,.98,.42)];(eU=iU||(iU={}))[eU.NONE=0]="NONE",eU[eU.TRIANGLES=1]="TRIANGLES",eU[eU.VERTICES=2]="VERTICES",eU[eU.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",eU[eU.UV0=4]="UV0",eU[eU.UV1=5]="UV1",eU[eU.VERTEXCOLORS=6]="VERTEXCOLORS",eU[eU.MATERIALIDS=7]="MATERIALIDS";let MeshDebugDefines=class MeshDebugDefines extends sn.H{constructor(){super(...arguments),this.DBG_MODE=iU.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}};let MeshDebugPluginMaterial=class MeshDebugPluginMaterial extends MaterialPluginBase{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,r,s,n,a,o,l,h,u,c,d,p,_;let f=new MeshDebugDefines;f.DBG_MODE=null!==(i=t.mode)&&void 0!==i?i:f.DBG_MODE,f.DBG_MULTIPLY=null!==(r=t.multiply)&&void 0!==r?r:f.DBG_MULTIPLY,super(e,"MeshDebug",200,f,!0,!0),this._mode=f.DBG_MODE,this._multiply=f.DBG_MULTIPLY,this.shadedDiffuseColor=null!==(s=t.shadedDiffuseColor)&&void 0!==s?s:new rg.Wo(1,1,1),this.shadedSpecularColor=null!==(n=t.shadedSpecularColor)&&void 0!==n?n:new rg.Wo(.8,.8,.8),this.shadedSpecularPower=null!==(a=t.shadedSpecularPower)&&void 0!==a?a:10,this.wireframeThickness=null!==(o=t.wireframeThickness)&&void 0!==o?o:.7,this.wireframeTrianglesColor=null!==(l=t.wireframeTrianglesColor)&&void 0!==l?l:new rg.Wo(0,0,0),this.wireframeVerticesColor=null!==(h=t.wireframeVerticesColor)&&void 0!==h?h:new rg.Wo(.8,.8,.8),this.vertexColor=null!==(u=t.vertexColor)&&void 0!==u?u:new rg.Wo(0,0,0),this.vertexRadius=null!==(c=t.vertexRadius)&&void 0!==c?c:1.2,this.uvScale=null!==(d=t.uvScale)&&void 0!==d?d:20,this.uvPrimaryColor=null!==(p=t.uvPrimaryColor)&&void 0!==p?p:new rg.Wo(1,1,1),this.uvSecondaryColor=null!==(_=t.uvSecondaryColor)&&void 0!==_?_:new rg.Wo(.5,.5,.5),this._materialColor=MeshDebugPluginMaterial.MaterialColors[MeshDebugPluginMaterial._PluginCount++%MeshDebugPluginMaterial.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().webGLVersion){rT.Y.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=iU.VERTICES&&this._mode!=iU.TRIANGLES&&this._mode!=iU.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||rT.Y.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:lV}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:lw,CUSTOM_VERTEX_MAIN_END:lU}:{CUSTOM_FRAGMENT_DEFINITIONS:lk,CUSTOM_FRAGMENT_MAIN_END:lG}}static Reset(){this._PluginCount=0,this.MaterialColors=lz}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let rollback=()=>{};if(0==e.getTotalIndices())return rollback;if(t){let t=e.getVerticesDataKinds(),i=e.getIndices(),r={};for(let i of t)r[i]=e.getVerticesData(i);rollback=function(){for(let s of(e.setIndices(i),t)){let t=e.getVertexBuffer(s).getStrideSize();e.setVerticesData(s,r[s],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let i=Array.from(e.getIndices()),r=[];for(let e=0;e{DracoDecoderModule({wasmBinary:e}).then(e=>{t({module:e})})})}function decodeMesh(e,t,i,r,s){let n=null,a=null,o=null;try{let l;n=new e.Decoder,(a=new e.DecoderBuffer).Init(t,t.byteLength);let h=n.GetEncodedGeometryType(a);switch(h){case e.TRIANGULAR_MESH:{let t=new e.Mesh;if(!(l=n.DecodeBufferToMesh(a,t)).ok()||0===t.ptr)throw Error(l.error_msg());let i=t.num_faces(),s=3*i,h=4*s,u=e._malloc(h);try{n.GetTrianglesUInt32Array(t,h,u);let i=new Uint32Array(s);i.set(new Uint32Array(e.HEAPF32.buffer,u,s)),r(i)}finally{e._free(u)}o=t;break}case e.POINT_CLOUD:{let t=new e.PointCloud;if(!(l=n.DecodeBufferToPointCloud(a,t)).ok()||!t.ptr)throw Error(l.error_msg());o=t;break}default:throw Error(`Invalid geometry type ${h}`)}let u=o.num_points(),processAttribute=(t,i,r,n)=>{let a=n.data_type(),o=n.num_components(),l=n.normalized(),h=n.byte_stride(),c=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}},p=d[a];if(!p)throw Error(`Invalid data type ${a}`);let _=u*o,f=_*p.typedArrayConstructor.BYTES_PER_ELEMENT,m=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(i,n,a,f,m);let e=new p.typedArrayConstructor(p.heap.buffer,m,_);s(r,e.slice(),o,c,h,l)}finally{e._free(m)}};if(i)for(let e in i){let t=i[e],r=n.GetAttributeByUniqueId(o,t);processAttribute(n,o,e,r)}else{let t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(let e in t){let i=n.GetAttributeId(o,t[e]);if(-1!==i){let t=n.GetAttribute(o,i);processAttribute(n,o,e,t)}}}return u}finally{o&&e.destroy(o),a&&e.destroy(a),n&&e.destroy(n)}}function worker(){let e;onmessage=t=>{let i=t.data;switch(i.id){case"init":{let t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw Error("Draco decoder module is not available");e.then(e=>{let t=decodeMesh(e,i.dataView,i.attributes,e=>{postMessage({id:"indices",data:e},[e.buffer])},(e,t,i,r,s,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:s,normalized:n},[t.buffer])});postMessage({id:"decodeMeshDone",totalVertices:t})})}}}let DracoCompression=class DracoCompression{static get DecoderAvailable(){let e=DracoCompression.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 DracoCompression._Default||(DracoCompression._Default=new DracoCompression),DracoCompression._Default}constructor(e=DracoCompression.DefaultNumWorkers){let t=DracoCompression.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:rW.w1.GetBabylonScriptURL(t.wasmUrl,!0),wasmBinaryPromise:rW.w1.LoadFileAsync(rW.w1.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:rW.w1.GetBabylonScriptURL(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then(t=>{let r=`${decodeMesh}(${worker})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));return new AutoReleaseWorkerPool(e,()=>new Promise((e,r)=>{let n=new Worker(s),onError=e=>{n.removeEventListener("error",onError),n.removeEventListener("message",onMessage),r(e)},onMessage=t=>{"initDone"===t.data.id&&(n.removeEventListener("error",onError),n.removeEventListener("message",onMessage),e(n))};n.addEventListener("error",onError),n.addEventListener("message",onMessage),n.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))}):this._decoderModulePromise=i.wasmBinaryPromise.then(e=>{if(!i.url)throw Error("Draco decoder module is not available");return rW.w1.LoadBabylonScriptAsync(i.url).then(()=>createDecoderAsync(e))})}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then(e=>{e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then(()=>{}):this._decoderModulePromise?this._decoderModulePromise.then(()=>{}):Promise.resolve()}_decodeMeshAsync(e,t,i){let r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),applyGltfNormalizedOverride=(e,t)=>i&&void 0!==i[e]?(t!==i[e]&&rT.Y.Warn(`Normalized flag from Draco data (${t}) does not match normalized flag from glTF accessor (${i[e]}). Using flag from glTF accessor.`),i[e]):t;if(this._workerPoolPromise)return this._workerPoolPromise.then(e=>new Promise((i,s)=>{e.push((e,n)=>{let a=null,o=[],onError=t=>{e.removeEventListener("error",onError),e.removeEventListener("message",onMessage),s(t),n()},onMessage=t=>{let r=t.data;switch(r.id){case"decodeMeshDone":e.removeEventListener("error",onError),e.removeEventListener("message",onMessage),i({indices:a,attributes:o,totalVertices:r.totalVertices}),n();break;case"indices":a=r.data;break;case"attribute":o.push({kind:r.kind,data:r.data,size:r.size,byteOffset:r.byteOffset,byteStride:r.byteStride,normalized:applyGltfNormalizedOverride(r.kind,r.normalized)})}};e.addEventListener("error",onError),e.addEventListener("message",onMessage);let l=r.slice();e.postMessage({id:"decodeMesh",dataView:l,attributes:t},[l.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(e=>{let i=null,s=[],n=decodeMesh(e.module,r,t,e=>{i=e},(e,t,i,r,n,a)=>{s.push({kind:e,data:t,size:i,byteOffset:r,byteStride:n,normalized:a})});return{indices:i,attributes:s,totalVertices:n}});throw Error("Draco decoder module is not available")}decodeMeshToGeometryAsync(e,t,i,r){return this._decodeMeshAsync(i,r).then(i=>{let r=new lS.Z(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new rz.o(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}_decodeMeshToGeometryForGltfAsync(e,t,i,r,s){return this._decodeMeshAsync(i,r,s).then(i=>{let r=new lS.Z(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new rz.o(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}decodeMeshAsync(e,t){return this._decodeMeshAsync(e,t).then(e=>{let t=new se.x;for(let i of(e.indices&&(t.indices=e.indices),e.attributes)){let r=rz.o.GetFloatData(i.data,i.size,rz.o.GetDataType(i.data),i.byteOffset,i.byteStride,i.normalized,e.totalVertices);t.set(r,i.kind)}return t})}};DracoCompression.Configuration={decoder:{wasmUrl:`${rW.w1._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${rW.w1._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${rW.w1._DefaultCdnUrl}/draco_decoder_gltf.js`}},DracoCompression.DefaultNumWorkers=DracoCompression.GetDefaultNumWorkers(),DracoCompression._Default=null;let MeshoptCompression=class MeshoptCompression{static get Default(){return MeshoptCompression._Default||(MeshoptCompression._Default=new MeshoptCompression),MeshoptCompression._Default}constructor(){let e=MeshoptCompression.Configuration.decoder;this._decoderModulePromise=rW.w1.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then(()=>{let n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,r,s),n})}};MeshoptCompression.Configuration={decoder:{url:`${rW.w1._DefaultCdnUrl}/meshopt_decoder.js`}},MeshoptCompression._Default=null;let lH=0;let Vertex=class Vertex{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){var e,t;return new Vertex(this.pos.clone(),this.normal.clone(),null===(e=this.uv)||void 0===e?void 0:e.clone(),null===(t=this.vertColor)||void 0===t?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new Vertex(rm.P.Lerp(this.pos,e.pos,t),rm.P.Lerp(this.normal,e.normal,t),this.uv&&e.uv?rm.FM.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?rg.HE.Lerp(this.vertColor,e.vertColor,t):void 0)}};let csg_Plane=class csg_Plane{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){let r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;let n=rm.P.Normalize(rm.P.Cross(r,s));return new csg_Plane(n,rm.P.Dot(n,e))}clone(){return new csg_Plane(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let n,a;let o=0,l=[];for(n=0;ncsg_Plane.EPSILON?1:0;o|=t,l.push(t)}switch(o){case 0:(rm.P.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{let t;let i=[],o=[];for(n=0;n=3&&(t=new csg_Polygon(i,e.shared)).plane&&r.push(t),o.length>=3&&(t=new csg_Polygon(o,e.shared)).plane&&s.push(t)}}}};csg_Plane.EPSILON=1e-5;let csg_Polygon=class csg_Polygon{constructor(e,t){this.vertices=e,this.shared=t,this.plane=csg_Plane.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){let e=this.vertices.map(e=>e.clone());return new csg_Polygon(e,this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}};let csg_Node=class csg_Node{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=[],e&&this.build(e)}clone(){let e=new csg_Node;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(e=>e.clone()),e}invert(){for(let e=0;ee.clone()),e.copyTransformAttributes(this),e}union(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){let t=new csg_Node(this.clone()._polygons),i=new csg_Node(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),CSG._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){let t=new csg_Node(this._polygons),i=new csg_Node(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){let e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){let i;let r=this.matrix.clone();r.invert();let s=this._polygons,n=[],a=[],o=[],l=null,h=null,u=rm.P.Zero(),c=rm.P.Zero(),d=rm.FM.Zero(),p=new rg.HE(0,0,0,0),_=[0,0,0],f={};for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId);let l=this.toVertexData(e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:Infinity,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),r=o[e.shared.meshId][e.shared.subMeshId]},()=>{r.indexStart=Math.min(a,r.indexStart),r.indexEnd=Math.max(a,r.indexEnd),a++});if(l.applyToMesh(s),i){let e=0,t;for(let i in s.subMeshes=[],o){for(let n in t=-1,o[i])r=o[i][n],oJ.P.CreateFromIndices(r.materialIndex+e,r.indexStart,r.indexEnd-r.indexStart+1,s),t=Math.max(r.materialIndex,t);e+=++t}}return s}toMesh(e,t=null,i,r){let s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}};let lX=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; -#if defined(INSTANCES) && defined(THIN_INSTANCES) -vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); -#else -#ifdef NONUNIFORMSCALING -normWorldSM=transposeMat3(inverseMat3(normWorldSM)); -#endif -vNormalW=normalize(normWorldSM*normalUpdated); -#endif -vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);} -`;s_.v.ShadersStore.meshUVSpaceRendererVertexShader=lX;let lY=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} -gl_FragColor=texture2D(textureSampler,vDecalTC);} -`;s_.v.ShadersStore.meshUVSpaceRendererPixelShader=lY,rV.Kj._TrailMeshParser=(e,t)=>TrailMesh.Parse(e,t);let TrailMesh=class TrailMesh extends rV.Kj{constructor(e,t,i,r=1,s=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=r,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){let e=this.getVerticesData(rz.o.PositionKind),t=this.getVerticesData(rz.o.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*this._sectionPolygonPointsCount;i{let i=this._getSimplifier(e);i.simplify(t,i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{let t=this._getSimplifier(e),runDecimation=(i,r)=>{t.simplify(i,t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()})};rW.$g.Run(e.settings.length,t=>{runDecimation(e.settings[t.index],()=>{t.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){return e.simplificationType,iV.QUADRATIC,new QuadraticErrorSimplification(e.mesh)}};(eV=iV||(iV={}))[eV.QUADRATIC=0]="QUADRATIC";let DecimationTriangle=class DecimationTriangle{constructor(e){this._vertices=e,this.error=[,,,,],this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}};let DecimationVertex=class DecimationVertex{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new QuadraticMatrix,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}};let QuadraticMatrix=class QuadraticMatrix{constructor(e){this.data=Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,n,a,o,l){let h=this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[o]+this.data[t]*this.data[n]*this.data[a]-this.data[i]*this.data[s]*this.data[a]-this.data[e]*this.data[n]*this.data[o]-this.data[t]*this.data[r]*this.data[l];return h}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){let t=new QuadraticMatrix;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}};let Reference=class Reference{constructor(e,t){this.vertexId=e,this.triangleId=t}};let QuadraticErrorSimplification=class QuadraticErrorSimplification{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=rw.kn}simplify(e,t){this._initDecimatedMesh(),rW.$g.Run(this._mesh.subMeshes.length,t=>{this._initWithMesh(t.index,()=>{this._runDecimation(e,t.index,()=>{t.executeNext()})},e.optimizeMesh)},()=>{setTimeout(()=>{t(this._reconstructedMesh)},0)})}_runDecimation(e,t,i){let r=~~(this._triangles.length*e.quality),s=0,n=this._triangles.length,iterationFunction=(e,t)=>{setTimeout(()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{let t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i)&&!r.deleted&&!r.isDirty){for(let e=0;e<3;++e)if(r.error[e]t.indexOf(!0)||0>i.indexOf(!0))continue;let h=[];if(l.forEach(e=>{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))}),h.length%2!=0)continue;n.q=a.q.add(n.q),n.updatePosition(o);let u=this._references.length;s=this._updateTriangles(n,n,t,s),s=this._updateTriangles(n,a,i,s);let c=this._references.length-u;if(c<=n.triangleCount){if(c)for(let e=0;en-s<=r)},0)};rW.$g.Run(this.decimationIterations,e=>{n-s<=r?e.breakLoop():iterationFunction(e.index,()=>{e.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];let r=this._mesh.getVerticesData(rz.o.PositionKind),s=this._mesh.getIndices(),n=this._mesh.subMeshes[e],findInVertices=e=>{if(i){for(let t=0;t>0,e=>{if(!r)return;let t=e+n.verticesStart,i=rm.P.FromArray(r,3*t),s=findInVertices(i)||new DecimationVertex(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),a.push(s.id)},()=>{rW.$g.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,e=>{if(!s)return;let t=n.indexStart/3+e,i=3*t,r=s[i+0],o=s[i+1],l=s[i+2],h=this._vertices[a[r-n.verticesStart]],u=this._vertices[a[o-n.verticesStart]],c=this._vertices[a[l-n.verticesStart]],d=new DecimationTriangle([h,u,c]);d.originalOffset=i,this._triangles.push(d)},()=>{this._init(t)})})}_init(e){rW.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];t.normal=rm.P.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-rm.P.Dot(t.normal,t._vertices[0].position)))},()=>{rW.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])},()=>{e()})})}_reconstructMesh(e){let t,i,r;let s=[];for(t=0;t{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(a.push(h[3*t]),a.push(h[3*t+1]),a.push(h[3*t+2])),u&&u.length&&(o.push(u[2*t]),o.push(u[2*t+1])),c&&c.length&&(l.push(c[4*t]),l.push(c[4*t+1]),l.push(c[4*t+2]),l.push(c[4*t+3])),++d})}let p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];let m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(t=0;t{let t=g[i.originalOffset+e],r=i._vertices[e].originalOffsets.indexOf(t);r<0&&(r=0),m.push(i._vertices[e].id+r+_)});this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(rz.o.PositionKind,n),a.length>0&&this._reconstructedMesh.setVerticesData(rz.o.NormalKind,a),o.length>0&&this._reconstructedMesh.setVerticesData(rz.o.UVKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(rz.o.ColorKind,l);let v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach(e=>{oJ.P.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),oJ.P.AddToMesh(v.materialIndex,_,d,p,3*s.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new rV.Kj(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,s){for(let n=0;n.999)return!0;let d=rm.P.Cross(u,c).normalize();if(r[n]=!1,.2>rm.P.Dot(d,a.normal))return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;rgreasedLineMesh_GreasedLineMesh.Parse(e,t);let greasedLineMesh_GreasedLineMesh=class greasedLineMesh_GreasedLineMesh extends GreasedLineBaseMesh{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(greasedLineTools_GreasedLineTools.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i{var i;let r=[],s=[],n=[],a=greasedLineTools_GreasedLineTools.GetLineLength(e);for(let i=0,o=0;o0&&(a=greasedLineMesh_GreasedLineMesh._CopyV3(o,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]));return a=greasedLineMesh_GreasedLineMesh._CompareV3(n-1,0,e)?greasedLineMesh_GreasedLineMesh._CopyV3(1,e):greasedLineMesh_GreasedLineMesh._CopyV3(n-1,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]),{previous:t,next:i,uvs:s,side:r}}_createVertexBuffers(){let e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new rz.l(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));let r=new rz.l(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_nextAndCounters",0,4));let s=new rz.l(t,this._widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;let n=new rz.l(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n,e}};greasedLineMesh_GreasedLineMesh._V_START=new rm.P,greasedLineMesh_GreasedLineMesh._V_END=new rm.P,greasedLineMesh_GreasedLineMesh._V_OFFSET_START=new rm.P,greasedLineMesh_GreasedLineMesh._V_OFFSET_END=new rm.P,rV.Kj._GreasedLineRibbonMeshParser=(e,t)=>greasedLineRibbonMesh_GreasedLineRibbonMesh.Parse(e,t);let greasedLineRibbonMesh_GreasedLineRibbonMesh=class greasedLineRibbonMesh_GreasedLineRibbonMesh extends GreasedLineBaseMesh{constructor(e,t,i,r){var s;if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=null!==(s=i.widths)&&void 0!==s?s:[],this._ribbonWidths=[],this._pathsOptions=null!=r?r:[],i.points&&this.addPoints(greasedLineTools_GreasedLineTools.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{let i=greasedLineRibbonMesh_GreasedLineRibbonMesh._ConvertToRibbonPath(e,o.ribbonOptions,this._scene.useRightHandedSystem,s?s[t]:s);n=this._preprocess(i,n,o)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var i,r,s;let n=e.length;if(n<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";let a=[],o=[],l=e[0];for(let t=0;t2)for(let e=0;e0&&(h[0]+=1,h[1]+=1),o.push(h[1]+(e%2!=0?n:0),h[0],h[2]),u&&o.push(h[0],h[1]+(e%2!=0?n:0),h[2])}else for(let e=0;ee.y&&e.x>e.z?i?greasedLineRibbonMesh_GreasedLineRibbonMesh._RightHandedForwardReadOnlyQuaternion:greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftHandedForwardReadOnlyQuaternion:greasedLineRibbonMesh_GreasedLineRibbonMesh._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(a,a,a),s.push(u.add(h)),n.push(u.subtract(h))}r||(s.push(o[o.length-1].add(h)),n.push(o[o.length-1].subtract(h)))}return[s,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&(null==i?void 0:i.x)!==1?e.y===t.y?greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ:e.z===t.z?greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XY:greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_XZ:greasedLineRibbonMesh_GreasedLineRibbonMesh.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={},s=[];rC.j.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),rC.j.DeepCopy(i,r,["instance"],void 0,!0);let n=new greasedLineRibbonMesh_GreasedLineRibbonMesh(e,this._scene,r,s);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){let i=e.lineOptions,r=e.name,s=e.pathOptions,n=new greasedLineRibbonMesh_GreasedLineRibbonMesh(r,t,i,s);return n}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){let t=e.length;this._vSegmentLengths=Array(t),this._vTotalLengths=Array(t);let i=0;for(let r=0;r=this._thinInstanceDataStorage.instancesCount)return!1;let r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},rV.Kj.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind),!!this._userThinInstanceBuffersStorage&&!!this._userThinInstanceBuffersStorage.data[e]&&!(t>=this._thinInstanceDataStorage.instancesCount)&&(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),r&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(rV.Kj.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;let r=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData,s=r?r.length/16:0;e<=s&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),rV.Kj.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind);let r=new rz.l(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},rV.Kj.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!1){var s,n,a;i=i||16,"matrix"===e?(null===(s=this._thinInstanceDataStorage.matrixBuffer)||void 0===s||s.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(n=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===n||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind),null===t?(null===(a=this._userThinInstanceBuffersStorage)||void 0===a?void 0:a.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]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new rz.o(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},rV.Kj.prototype.thinInstanceBufferUpdated=function(e){var t,i,r;"matrix"===e?null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):"previousMatrix"===e?null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},rV.Kj.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var r;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===rz.o.ColorKind&&(e=rz.o.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},rV.Kj.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];let e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}getConnectedValue(e){var t,i,r;return this.isConnected?(null===(t=this._connectedPoint)||void 0===t?void 0:t._storedFunction)?null===(i=this._connectedPoint)||void 0===i?void 0:i._storedFunction(e):null===(r=this._connectedPoint)||void 0===r?void 0:r._storedValue:this.value}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=[],this._type=iX.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new rf.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===iY.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==iX.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?iY.Compatible:iY.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return iY.TypeIncompatible;let r=i,s=t;return(this.direction===ij.Input&&(r=t,s=i),r.isAnAncestorOf(s))?iY.HierarchyIssue:iY.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t0&&!this._outputs.some(e=>e.hasEndpoints)&&!this.isDebug)return!1;for(let t of(this._buildId=e.buildId,this._inputs)){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}let i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&console.log(`Building ${this.name} [${this.getClassName()}]`);let t=rF.F.Now;for(let i of(this._buildBlock(e),this._buildExecutionTime=rF.F.Now-t,this._outputs))for(let t of i.endpoints){let i=t.ownerBlock;i&&i.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach(e=>{let t=this.inputs.find(t=>t.name===e.name);if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value)){if("number"===e.valueType)t.value=e.value;else{let i=(0,rv.q)(e.valueType);i&&(t.value=i.FromArray(e.value))}}}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame}; -`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); -`}return t}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` -// ${this.getClassName()} -`;for(let i of(this.comments&&(r+=`// ${this.comments} -`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); -`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint,n=s.ownerBlock;-1===t.indexOf(n)&&(r+=n._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){let e=this.serialize(),t=(0,rv.q)(e.customType);if(t){let i=new t;return i._deserialize(e),i}return null}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose();this.onBuildObservable.clear()}};(0,rH.gn)([(0,rb.qC)("comment")],NodeGeometryBlock.prototype,"comments",void 0);let GeometryOutputBlock=class GeometryOutputBlock extends NodeGeometryBlock{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",iX.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}};(0,rv.H)("BABYLON.GeometryOutputBlock",GeometryOutputBlock),(eq=iq||(iq={}))[eq.None=0]="None",eq[eq.Positions=1]="Positions",eq[eq.Normals=2]="Normals",eq[eq.Tangents=3]="Tangents",eq[eq.UV=4]="UV",eq[eq.UV2=5]="UV2",eq[eq.UV3=6]="UV3",eq[eq.UV4=7]="UV4",eq[eq.UV5=8]="UV5",eq[eq.UV6=9]="UV6",eq[eq.Colors=10]="Colors",eq[eq.VertexID=11]="VertexID",eq[eq.FaceID=12]="FaceID",eq[eq.GeometryID=13]="GeometryID",eq[eq.CollectionID=14]="CollectionID",eq[eq.LoopID=15]="LoopID",eq[eq.InstanceID=16]="InstanceID";let NodeGeometryBuildState=class NodeGeometryBuildState{constructor(){this._rotationMatrix=new rm.y3,this._scalingMatrix=new rm.y3,this._positionMatrix=new rm.y3,this._scalingRotationMatrix=new rm.y3,this._transformMatrix=new rm.y3,this._tempVector3=new rm.P,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;let i=this.executionContext.getExecutionIndex();switch(e){case iq.Positions:if(this.executionContext.getOverridePositionsContextualValue)return this.executionContext.getOverridePositionsContextualValue();if(!this.geometryContext||!this.geometryContext.positions)return rm.P.Zero();return rm.P.FromArray(this.geometryContext.positions,3*i);case iq.Normals:if(this.executionContext.getOverrideNormalsContextualValue)return this.executionContext.getOverrideNormalsContextualValue();if(!this.geometryContext||!this.geometryContext.normals)return rm.P.Zero();return rm.P.FromArray(this.geometryContext.normals,3*i);case iq.Colors:if(!this.geometryContext||!this.geometryContext.colors)return rm.Lt.Zero();return rm.Lt.FromArray(this.geometryContext.colors,4*i);case iq.Tangents:if(!this.geometryContext||!this.geometryContext.tangents)return rm.Lt.Zero();return rm.Lt.FromArray(this.geometryContext.tangents,4*i);case iq.UV:if(this.executionContext.getOverrideUVs1ContextualValue)return this.executionContext.getOverrideUVs1ContextualValue();if(!this.geometryContext||!this.geometryContext.uvs)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs,2*i);case iq.UV2:if(!this.geometryContext||!this.geometryContext.uvs2)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs2,2*i);case iq.UV3:if(!this.geometryContext||!this.geometryContext.uvs3)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs3,2*i);case iq.UV4:if(!this.geometryContext||!this.geometryContext.uvs4)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs4,2*i);case iq.UV5:if(!this.geometryContext||!this.geometryContext.uvs5)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs5,2*i);case iq.UV6:if(!this.geometryContext||!this.geometryContext.uvs6)return rm.FM.Zero();return rm.FM.FromArray(this.geometryContext.uvs6,2*i);case iq.VertexID:return i;case iq.FaceID:return this.executionContext.getExecutionFaceIndex();case iq.LoopID:return this.executionContext.getExecutionLoopIndex();case iq.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case iq.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case iq.CollectionID:if(!this.geometryContext||!this.geometryContext.metadata)return 0;return this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){let i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case iX.Vector2:return new rm.FM(i,i);case iX.Vector3:return new rm.P(i,i,i);case iX.Vector4:return new rm.Lt(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;let s=e.getConnectedValue(this);if((null===(r=e._connectedPoint)||void 0===r?void 0:r.type)===t)return s;switch(t){case iX.Vector2:return new rm.FM(s,s);case iX.Vector3:return new rm.P(s,s,s);case iX.Vector4:return new rm.Lt(s,s,s,s)}return null}emitErrors(){let e="";for(let t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. -`;for(let t of this.noContextualData)e+=`Contextual input ${iq[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block). -`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){rm.y3.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),rm.y3.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),rm.y3.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${iq[this._contextualSource]}; -`;let t=[],i="";switch(this.type){case iX.Float:case iX.Int:i=`${this.value}`;break;case iX.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case iX.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case iX.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),(this.type===iX.Float||this.type===iX.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){let e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=(0,rv.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}};(0,rv.H)("BABYLON.GeometryInputBlock",GeometryInputBlock);let BoxBlock=class BoxBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",iX.Float,!0,1),this.registerInput("width",iX.Float,!0,0),this.registerInput("height",iX.Float,!0,0),this.registerInput("depth",iX.Float,!0,0),this.registerInput("subdivisions",iX.Int,!0,1),this.registerInput("subdivisionsX",iX.Int,!0,0),this.registerInput("subdivisionsY",iX.Int,!0,0),this.registerInput("subdivisionsZ",iX.Int,!0,0),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){let e=new GeometryInputBlock("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){let e=new GeometryInputBlock("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){let t={},func=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);let i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),n&&(t.depthSegments=n),CreateSegmentedBoxVertexData(t)};if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BoxBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.BoxBlock",BoxBlock);let NodeGeometry=class NodeGeometry{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=NodeGeometry._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new rf.y$,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){rW.w1.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){let i=e&&e.editorURL?e.editorURL:NodeGeometry.EditorURL;rW.w1.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){let t=Object.assign({nodeGeometry:this},e);this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";let r=rF.F.Now;this._initializeBlock(this.outputBlock,i);let s=new NodeGeometryBuildState;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=NodeGeometry._BuildIdGenerator++),this._buildExecutionTime=rF.F.Now-r,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;let i=new rV.Kj(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){for(let i of(e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();let i={};for(let t of e.blocks){let e=(0,rv.q)(t.customType);if(e){let r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let r=i[t];r.attachToEndpoint(e)}}for(let r=0;re.targetConnectionName)&&!t||this._restoreConnections(n,e,i)}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){let r=e.locations||e.editorData.locations;for(let e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);let s=[];for(let e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}generateCode(){let e=[],t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); -`;for(let s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="// Connections\n"+this.outputBlock._dumpCodeForOutputConnections(e)+"// Output nodes\n"+`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; -`+`nodeGeometry.build(); -`),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}setToDefault(){this.clear(),this.editorData=null;let e=new BoxBlock("Box");e.autoConfigure();let t=new GeometryOutputBlock("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){let t=this.serialize(),i=rb.p4.Clone(()=>new NodeGeometry(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){let t=e?{}:rb.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];for(let r of(e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[],i))t.blocks.push(r.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){let t=new NodeGeometry(e);return t.setToDefault(),t.build(),t}static Parse(e){let t=rb.p4.Parse(()=>new NodeGeometry(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(NodeGeometry.CreateDefault("blank")):new Promise((r,s)=>{let n=new rP.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let a=JSON.parse(JSON.parse(n.responseText).jsonPayload),o=JSON.parse(a.nodeGeometry);t||(t=rb.p4.Parse(()=>new NodeGeometry(e),o,null)),t.parseSerializedObject(o),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}};NodeGeometry._BuildIdGenerator=0,NodeGeometry.EditorURL=`${rW.w1._DefaultCdnUrl}/v${rq.D.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,NodeGeometry.SnippetUrl="https://snippet.babylonjs.com",(0,rH.gn)([(0,rb.qC)()],NodeGeometry.prototype,"name",void 0),(0,rH.gn)([(0,rb.qC)("comment")],NodeGeometry.prototype,"comment",void 0);let GeometryOptimizeBlock=class GeometryOptimizeBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=rw.kn,this.registerInput("geometry",iX.Geometry),this.registerOutput("output",iX.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e),i=[],r={};for(let e=0;er[e]),s};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`+`${this._codeVariableName}.epsilon = ${this.epsilon}; -`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryOptimizeBlock.prototype,"evaluateContext",void 0),(0,rH.gn)([editableInPropertyPage("Epsilon",tT.Float,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryOptimizeBlock.prototype,"epsilon",void 0),(0,rv.H)("BABYLON.GeometryOptimizeBlock",GeometryOptimizeBlock);let PlaneBlock=class PlaneBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",iX.Float,!0,1),this.registerInput("width",iX.Float,!0,0),this.registerInput("height",iX.Float,!0,0),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){let e=new GeometryInputBlock("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){let t={},func=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),CreatePlaneVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],PlaneBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.PlaneBlock",PlaneBlock);let MeshBlock=class MeshBlock extends NodeGeometryBlock{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",iX.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}let e=se.x.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){let e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=se.x.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=se.x.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}};(0,rH.gn)([editableInPropertyPage("Serialize cached data",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],MeshBlock.prototype,"serializedCachedData",void 0),(0,rv.H)("BABYLON.MeshBlock",MeshBlock);let IcoSphereBlock=class IcoSphereBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",iX.Float,!0,1),this.registerInput("radiusX",iX.Float,!0,0),this.registerInput("radiusY",iX.Float,!0,0),this.registerInput("radiusZ",iX.Float,!0,0),this.registerInput("subdivisions",iX.Int,!0,4),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),CreateIcoSphereVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],IcoSphereBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.IcoSphereBlock",IcoSphereBlock);let SphereBlock=class SphereBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",iX.Int,!0,32),this.registerInput("diameter",iX.Float,!0,1),this.registerInput("diameterX",iX.Float,!0,0),this.registerInput("diameterY",iX.Float,!0,0),this.registerInput("diameterZ",iX.Float,!0,0),this.registerInput("arc",iX.Float,!0,1),this.registerInput("slice",iX.Float,!0,1),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},func=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),CreateSphereVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SphereBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.SphereBlock",SphereBlock);let GridBlock=class GridBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",iX.Float,!0,1),this.registerInput("height",iX.Float,!0,1),this.registerInput("subdivisions",iX.Int,!0,1),this.registerInput("subdivisionsX",iX.Int,!0,0),this.registerInput("subdivisionsY",iX.Int,!0,0),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){let e=new GeometryInputBlock("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},func=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),CreateGroundVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GridBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.GridBlock",GridBlock);let TorusBlock=class TorusBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",iX.Float,!0,1),this.registerInput("thickness",iX.Float,!0,.5),this.registerInput("tessellation",iX.Int,!0,16),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},func=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),CreateTorusVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],TorusBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.TorusBlock",TorusBlock);let CylinderBlock=class CylinderBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",iX.Float,!0,25),this.registerInput("diameter",iX.Float,!0,1),this.registerInput("diameterTop",iX.Float,!0,-1),this.registerInput("diameterBottom",iX.Float,!0,-1),this.registerInput("subdivisions",iX.Int,!0,1),this.registerInput("tessellation",iX.Int,!0,24),this.registerInput("arc",iX.Float,!0,1),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new GeometryInputBlock("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},func=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),CreateCylinderVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CylinderBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.CylinderBlock",CylinderBlock);let CapsuleBlock=class CapsuleBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",iX.Float,!0,1),this.registerInput("radius",iX.Float,!0,.25),this.registerInput("tessellation",iX.Int,!0,16),this.registerInput("subdivisions",iX.Int,!0,2),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){let e=new GeometryInputBlock("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),CreateCapsuleVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],CapsuleBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.CapsuleBlock",CapsuleBlock);let DiscBlock=class DiscBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",iX.Float,!0,.5),this.registerInput("tessellation",iX.Int,!0,64),this.registerInput("arc",iX.Float,!0,1),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new GeometryInputBlock("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},func=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),CreateDiscVertexData(t));if(this.evaluateContext)this.geometry._storedFunction=func;else{let t=func(e);this.geometry._storedFunction=()=>t.clone()}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],DiscBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.DiscBlock",DiscBlock);let NullBlock=class NullBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerOutput("geometry",iX.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}};(0,rv.H)("BABYLON.NullBlock",NullBlock);let SetPositionsBlock=class SetPositionsBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("positions",iX.Vector3),this.registerOutput("output",iX.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}let t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndext.getConnectedValue(e)+i.getConnectedValue(e):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case iK.Subtract:e=r?e=>t.getConnectedValue(e)-i.getConnectedValue(e):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case iK.Multiply:e=r?e=>t.getConnectedValue(e)*i.getConnectedValue(e):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case iK.Divide:e=r?e=>t.getConnectedValue(e)/i.getConnectedValue(e):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case iK.Min:if(r)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case iX.Vector2:e=e=>rm.FM.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iX.Vector3:e=e=>rm.P.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iX.Vector4:e=e=>rm.Lt.Minimize(t.getConnectedValue(e),e.adapt(i,t.type))}break;case iK.Max:if(r)e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case iX.Vector2:e=e=>rm.FM.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iX.Vector3:e=e=>rm.P.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iX.Vector4:e=e=>rm.Lt.Maximize(t.getConnectedValue(e),e.adapt(i,t.type))}}this.output._storedFunction=i=>t.type===iX.Int?0|e(i):e(i)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${iK[this.operation]}; -`;return e}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}};(0,rH.gn)([editableInPropertyPage("Operation",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:iK.Add},{label:"Subtract",value:iK.Subtract},{label:"Multiply",value:iK.Multiply},{label:"Divide",value:iK.Divide},{label:"Max",value:iK.Max},{label:"Min",value:iK.Min}]})],MathBlock.prototype,"operation",void 0),(0,rv.H)("BABYLON.MathBlock",MathBlock);let MapRangeBlock=class MapRangeBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("value",iX.AutoDetect),this.registerInput("fromMin",iX.Float,!0,0),this.registerInput("fromMax",iX.Float,!0,1),this.registerInput("toMin",iX.Float,!0,0),this.registerInput("toMax",iX.Float,!0,1),this.registerOutput("output",iX.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iX.Vector2),this._inputs[0].excludedConnectionPointTypes.push(iX.Vector3),this._inputs[0].excludedConnectionPointTypes.push(iX.Vector4),this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{let t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),n=this.toMax.getConnectedValue(e),a=(t-i)/(r-i)*(n-s)+s;return this.output.type===iX.Int?Math.floor(a):a}}};(0,rv.H)("BABYLON.MapRangeBlock",MapRangeBlock),(e$=i$||(i$={}))[e$.Equal=0]="Equal",e$[e$.NotEqual=1]="NotEqual",e$[e$.LessThan=2]="LessThan",e$[e$.GreaterThan=3]="GreaterThan",e$[e$.LessOrEqual=4]="LessOrEqual",e$[e$.GreaterOrEqual=5]="GreaterOrEqual",e$[e$.Xor=6]="Xor",e$[e$.Or=7]="Or",e$[e$.And=8]="And";let ConditionBlock=class ConditionBlock extends NodeGeometryBlock{constructor(e){super(e),this.test=i$.Equal,this.registerInput("left",iX.Float),this.registerInput("right",iX.Float,!0,0),this.registerInput("ifTrue",iX.AutoDetect,!0,1),this.registerInput("ifFalse",iX.AutoDetect,!0,0),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=iX.Float,this._inputs[0].acceptedConnectionPointTypes.push(iX.Int),this._inputs[1].acceptedConnectionPointTypes.push(iX.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e),r=!1;switch(this.test){case i$.Equal:r=rE.R.WithinEpsilon(t,i,rw.kn);break;case i$.NotEqual:r=t!==i;break;case i$.LessThan:r=ti;break;case i$.LessOrEqual:r=t<=i;break;case i$.GreaterOrEqual:r=t>=i;break;case i$.Xor:r=!!t&&!i||!t&&!!i;break;case i$.Or:r=!!t||!!i;break;case i$.And:r=!!t&&!!i}return r};this.output._storedFunction=e=>func(e)?this.ifTrue.getConnectedValue(e):this.ifFalse.getConnectedValue(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${i$[this.test]}; -`;return e}serialize(){let e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}};(0,rH.gn)([editableInPropertyPage("Test",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:i$.Equal},{label:"NotEqual",value:i$.NotEqual},{label:"LessThan",value:i$.LessThan},{label:"GreaterThan",value:i$.GreaterThan},{label:"LessOrEqual",value:i$.LessOrEqual},{label:"GreaterOrEqual",value:i$.GreaterOrEqual},{label:"Xor",value:i$.Xor},{label:"Or",value:i$.Or},{label:"And",value:i$.And}]})],ConditionBlock.prototype,"test",void 0),(0,rv.H)("BABYLON.ConditionBlock",ConditionBlock),(eQ=iQ||(iQ={}))[eQ.None=0]="None",eQ[eQ.LoopID=1]="LoopID",eQ[eQ.InstanceID=2]="InstanceID";let RandomBlock=class RandomBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentLockId=-1,this.lockMode=iQ.None,this.registerInput("min",iX.AutoDetect),this.registerInput("max",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture),this._inputs[1].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[1].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[1].excludedConnectionPointTypes.push(iX.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){let e=new GeometryInputBlock("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){let e=new GeometryInputBlock("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case iX.Int:case iX.Float:e=e=>{let t=this.min.getConnectedValue(e)||0,i=this.max.getConnectedValue(e)||0;return t+Math.random()*(i-t)};break;case iX.Vector2:e=e=>{let t=this.min.getConnectedValue(e)||rm.FM.Zero(),i=this.max.getConnectedValue(e)||rm.FM.Zero();return new rm.FM(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case iX.Vector3:e=e=>{let t=this.min.getConnectedValue(e)||rm.P.Zero(),i=this.max.getConnectedValue(e)||rm.P.Zero();return new rm.P(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case iX.Vector4:e=e=>{let t=this.min.getConnectedValue(e)||rm.Lt.Zero(),i=this.max.getConnectedValue(e)||rm.Lt.Zero();return new rm.Lt(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==iQ.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case iQ.InstanceID:i=t.getContextualValue(iq.InstanceID,!0)||0;break;case iQ.LoopID:i=t.getContextualValue(iq.LoopID,!0)||0}return this._currentLockId!==i&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${iQ[this.lockMode]}; -`;return e}serialize(){let e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}};(0,rH.gn)([editableInPropertyPage("LockMode",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:iQ.None},{label:"LoopID",value:iQ.LoopID},{label:"InstanceID",value:iQ.InstanceID}]})],RandomBlock.prototype,"lockMode",void 0),(0,rv.H)("BABYLON.RandomBlock",RandomBlock);let NoiseBlock=class NoiseBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("offset",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scale",iX.Float,!0,1),this.registerInput("octaves",iX.Float,!0,2,0,16),this.registerInput("roughness",iX.Float,!0,.5,0,1),this.registerOutput("output",iX.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,r){let s=15&e,n=s<8?t:i,a=12===s||14==s?t:r,o=s<4?i:a;return this._negateIf(n,s&n)+this._negateIf(o,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let r,s,n;return r=s=n=3735928584,n+=i,s+=t,r+=e,n^=s,n-=this._hashBitRotate(s,14),r^=n,r-=this._hashBitRotate(n,11),s^=r,s-=this._hashBitRotate(r,25),n^=s,n-=this._hashBitRotate(s,16),r^=n,r-=this._hashBitRotate(n,4),s^=r,s-=this._hashBitRotate(r,14),n^=s,n-=this._hashBitRotate(s,24)}_mix(e,t,i,r,s,n,a,o,l,h,u){let c=1-l,d=1-h;return(1-u)*(d*(e*c+t*l)+h*(i*c+r*l))+u*(d*(s*c+n*l)+h*(a*c+o*l))}_perlinNoise(e){let t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,n=e.y-i,a=e.z-r,o=this._fade(s),l=this._fade(n),h=this._fade(a);return this._mix(this._noiseGrad(this._hash(t,i,r),s,n,a),this._noiseGrad(this._hash(t+1,i,r),s-1,n,a),this._noiseGrad(this._hash(t,i+1,r),s,n-1,a),this._noiseGrad(this._hash(t+1,i+1,r),s-1,n-1,a),this._noiseGrad(this._hash(t,i,r+1),s,n,a-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,n,a-1),this._noiseGrad(this._hash(t,i+1,r+1),s,n-1,a-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,n-1,a-1),o,l,h)}_perlinSigned(e){return .982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){let n=new rm.P(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z),a=1,o=1,l=0,h=0;e=rE.R.Clamp(e,0,15);let u=0|e;for(let e=0;e<=u;e++){let e=this._perlin(n.scale(a));h+=e*o,l+=o,o*=rE.R.Clamp(t,0,1),a*=2}let c=e-Math.floor(e);if(0==c)return h/l;let d=this._perlin(n.scale(a)),p=h+d*o;return(1-c)*(h/=l)+c*(p/=l+o)}_buildBlock(){this.output._storedFunction=e=>{let t=e.getContextualValue(iq.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,n)}}};(0,rv.H)("BABYLON.NoiseBlock",NoiseBlock);let MergeGeometryBlock=class MergeGeometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",iX.Geometry),this.registerInput("geometry1",iX.Geometry,!0),this.registerInput("geometry2",iX.Geometry,!0),this.registerInput("geometry3",iX.Geometry,!0),this.registerInput("geometry4",iX.Geometry,!0),this.registerOutput("output",iX.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{let t=this.geometry0.getConnectedValue(e),i=[];if(this.geometry1.isConnected){let t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){let t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){let t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){let t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],MergeGeometryBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.MergeGeometryBlock",MergeGeometryBlock);let GeometryCollectionBlock=class GeometryCollectionBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",iX.Geometry,!0),this.registerInput("geometry1",iX.Geometry,!0),this.registerInput("geometry2",iX.Geometry,!0),this.registerInput("geometry3",iX.Geometry,!0),this.registerInput("geometry4",iX.Geometry,!0),this.registerInput("geometry5",iX.Geometry,!0),this.registerInput("geometry6",iX.Geometry,!0),this.registerInput("geometry7",iX.Geometry,!0),this.registerInput("geometry8",iX.Geometry,!0),this.registerInput("geometry9",iX.Geometry,!0),this.registerOutput("output",iX.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){let s=e.getConnectedValue(t);s&&(s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s))}}_buildBlock(e){let func=e=>{let t=[];return(this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length)?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryCollectionBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.GeometryCollectionBlock",GeometryCollectionBlock);let GeometryElbowBlock=class GeometryElbowBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("input",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}};(0,rv.H)("BABYLON.GeometryElbowBlock",GeometryElbowBlock);let ComputeNormalsBlock=class ComputeNormalsBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",iX.Geometry),this.registerOutput("output",iX.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),se.x.ComputeNormals(t.positions,t.indices,t.normals),t}}};(0,rv.H)("BABYLON.ComputeNormalsBlock",ComputeNormalsBlock);let VectorConverterBlock=class VectorConverterBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("xyzw ",iX.Vector4,!0),this.registerInput("xyz ",iX.Vector3,!0),this.registerInput("xy ",iX.Vector2,!0),this.registerInput("zw ",iX.Vector2,!0),this.registerInput("x ",iX.Float,!0),this.registerInput("y ",iX.Float,!0),this.registerInput("z ",iX.Float,!0),this.registerInput("w ",iX.Float,!0),this.registerOutput("xyzw",iX.Vector4),this.registerOutput("xyz",iX.Vector3),this.registerOutput("xy",iX.Vector2),this.registerOutput("zw",iX.Vector2),this.registerOutput("x",iX.Float),this.registerOutput("y",iX.Float),this.registerOutput("z",iX.Float),this.registerOutput("w",iX.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,u=this.xyzOut,c=this.xyOut,d=this.zwOut,p=this.xOut,_=this.yOut,f=this.zOut,m=this.wOut,getData=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,u=0,c=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(u=i.getConnectedValue(e)),r.isConnected&&(c=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),n.isConnected){let t=n.getConnectedValue(e);t&&(h=t.x,u=t.y)}if(a.isConnected){let t=a.getConnectedValue(e);t&&(c=t.x,d=t.y)}if(o.isConnected){let t=o.getConnectedValue(e);t&&(h=t.x,u=t.y,c=t.z)}return new rm.Lt(h,u,c,d)};h._storedFunction=e=>getData(e),u._storedFunction=e=>{let t=getData(e);return new rm.P(t.x,t.y,t.z)},c._storedFunction=e=>{let t=getData(e);return new rm.FM(t.x,t.y)},d._storedFunction=e=>{let t=getData(e);return new rm.FM(t.z,t.w)},p._storedFunction=e=>getData(e).x,_._storedFunction=e=>getData(e).y,f._storedFunction=e=>getData(e).z,m._storedFunction=e=>getData(e).w}};(0,rv.H)("BABYLON.VectorConverterBlock",VectorConverterBlock);let NormalizeVectorBlock=class NormalizeVectorBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("input",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iX.Float),this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize()}};(0,rv.H)("BABYLON.NormalizeVectorBlock",NormalizeVectorBlock);let SetMaterialIDBlock=class SetMaterialIDBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("id",iX.Int,!0,0),this.registerOutput("output",iX.Geometry),this.id.acceptedConnectionPointTypes.push(iX.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;let i=new se.D;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],SetMaterialIDBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.SetMaterialIDBlock",SetMaterialIDBlock),(eZ=iZ||(iZ={}))[eZ.Cos=0]="Cos",eZ[eZ.Sin=1]="Sin",eZ[eZ.Abs=2]="Abs",eZ[eZ.Exp=3]="Exp",eZ[eZ.Round=4]="Round",eZ[eZ.Floor=5]="Floor",eZ[eZ.Ceiling=6]="Ceiling",eZ[eZ.Sqrt=7]="Sqrt",eZ[eZ.Log=8]="Log",eZ[eZ.Tan=9]="Tan",eZ[eZ.ArcTan=10]="ArcTan",eZ[eZ.ArcCos=11]="ArcCos",eZ[eZ.ArcSin=12]="ArcSin",eZ[eZ.Sign=13]="Sign",eZ[eZ.Negate=14]="Negate",eZ[eZ.OneMinus=15]="OneMinus",eZ[eZ.Reciprocal=16]="Reciprocal",eZ[eZ.ToDegrees=17]="ToDegrees",eZ[eZ.ToRadians=18]="ToRadians";let GeometryTrigonometryBlock=class GeometryTrigonometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.operation=iZ.Cos,this.registerInput("input",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case iZ.Cos:t=e=>Math.cos(e);break;case iZ.Sin:t=e=>Math.sin(e);break;case iZ.Abs:t=e=>Math.abs(e);break;case iZ.Exp:t=e=>Math.exp(e);break;case iZ.Round:t=e=>Math.round(e);break;case iZ.Floor:t=e=>Math.floor(e);break;case iZ.Ceiling:t=e=>Math.ceil(e);break;case iZ.Sqrt:t=e=>Math.sqrt(e);break;case iZ.Log:t=e=>Math.log(e);break;case iZ.Tan:t=e=>Math.tan(e);break;case iZ.ArcTan:t=e=>Math.atan(e);break;case iZ.ArcCos:t=e=>Math.acos(e);break;case iZ.ArcSin:t=e=>Math.asin(e);break;case iZ.Sign:t=e=>Math.sign(e);break;case iZ.Negate:t=e=>-e;break;case iZ.OneMinus:t=e=>1-e;break;case iZ.Reciprocal:t=e=>1/e;break;case iZ.ToRadians:t=e=>e*Math.PI/180;break;case iZ.ToDegrees:t=e=>180*e/Math.PI}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case iX.Int:case iX.Float:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return t(i)};break;case iX.Vector2:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rm.FM(t(i.x),t(i.y))};break;case iX.Vector3:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rm.P(t(i.x),t(i.y),t(i.z))};break;case iX.Vector4:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rm.Lt(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${iZ[this.operation]}; -`;return e}};(0,rH.gn)([editableInPropertyPage("Operation",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:iZ.Cos},{label:"Sin",value:iZ.Sin},{label:"Abs",value:iZ.Abs},{label:"Exp",value:iZ.Exp},{label:"Round",value:iZ.Round},{label:"Floor",value:iZ.Floor},{label:"Ceiling",value:iZ.Ceiling},{label:"Sqrt",value:iZ.Sqrt},{label:"Log",value:iZ.Log},{label:"Tan",value:iZ.Tan},{label:"ArcTan",value:iZ.ArcTan},{label:"ArcCos",value:iZ.ArcCos},{label:"ArcSin",value:iZ.ArcSin},{label:"Sign",value:iZ.Sign},{label:"Negate",value:iZ.Negate},{label:"OneMinus",value:iZ.OneMinus},{label:"Reciprocal",value:iZ.Reciprocal},{label:"ToDegrees",value:iZ.ToDegrees},{label:"ToRadians",value:iZ.ToRadians}]})],GeometryTrigonometryBlock.prototype,"operation",void 0),(0,rv.H)("BABYLON.GeometryTrigonometryBlock",GeometryTrigonometryBlock);let GeometryTransformBlock=class GeometryTransformBlock extends NodeGeometryBlock{constructor(e){super(e),this._rotationMatrix=new rm.y3,this._scalingMatrix=new rm.y3,this._translationMatrix=new rm.y3,this._scalingRotationMatrix=new rm.y3,this._transformMatrix=new rm.y3,this.evaluateContext=!0,this.registerInput("value",iX.AutoDetect),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("translation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iX.Float),this._inputs[0].excludedConnectionPointTypes.push(iX.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let func=e=>{let t;let i=this.value.getConnectedValue(e);if(!i)return null;if(this.matrix.isConnected)t=this.matrix.getConnectedValue(e);else{let i=this.scaling.getConnectedValue(e),r=this.rotation.getConnectedValue(e),s=this.translation.getConnectedValue(e);rm.y3.ScalingToRef(i.x,i.y,i.z,this._scalingMatrix),rm.y3.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),rm.y3.TranslationToRef(s.x,s.y,s.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),t=this._transformMatrix}switch(this.value.type){case iX.Geometry:{let e=i.clone();return e.transform(t),e}case iX.Vector2:return rm.FM.Transform(i,t);case iX.Vector3:return rm.P.TransformCoordinates(i,t);case iX.Vector4:return rm.Lt.TransformCoordinates(i,t)}return null};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTransformBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.GeometryTransformBlock",GeometryTransformBlock);let RotationXBlock=class RotationXBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",iX.Float,!1,0),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rm.y3.RotationX(this.angle.getConnectedValue(e))}};(0,rv.H)("BABYLON.RotationXBlock",RotationXBlock);let RotationYBlock=class RotationYBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",iX.Float,!1,0),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rm.y3.RotationY(this.angle.getConnectedValue(e))}};(0,rv.H)("BABYLON.RotationYBlock",RotationYBlock);let RotationZBlock=class RotationZBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("angle",iX.Float,!1,0),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new GeometryInputBlock("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rm.y3.RotationZ(this.angle.getConnectedValue(e))}};(0,rv.H)("BABYLON.RotationZBlock",RotationZBlock);let ScalingBlock=class ScalingBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("scale",iX.Vector3,!1,rm.P.One()),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){let e=new GeometryInputBlock("Scale");e.value=new rm.P(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.scale.getConnectedValue(e);return rm.y3.Scaling(t.x,t.y,t.z)}}};(0,rv.H)("BABYLON.ScalingBlock",ScalingBlock);let AlignBlock=class AlignBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("source",iX.Vector3,!0,rm.P.Up()),this.registerInput("target",iX.Vector3,!0,rm.P.Left()),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new rm.y3;return t.normalize(),i.normalize(),rm.y3.RotationAlignToRef(t,i,r,!0),r}}};(0,rv.H)("BABYLON.AlignBlock",AlignBlock);let TranslationBlock=class TranslationBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("translation",iX.Vector3,!1,rm.P.Zero()),this.registerOutput("matrix",iX.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){let e=new GeometryInputBlock("Translation");e.value=new rm.P(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.translation.getConnectedValue(e);return rm.y3.Translation(t.x,t.y,t.z)}}};(0,rv.H)("BABYLON.TranslationBlock",TranslationBlock);let InstantiateOnVerticesBlock=class InstantiateOnVerticesBlock extends NodeGeometryBlock{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("instance",iX.Geometry,!0),this.registerInput("density",iX.Float,!0,1,0,1),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.scaling.acceptedConnectionPointTypes.push(iX.Float),this.registerOutput("output",iX.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3,i=[],r=new rm.P,s=[],n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexs)continue;r.fromArray(n,3*this._currentIndex);let a=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(a,r,t,i)}else{let t=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly),s=this.rotation.getConnectedValue(e)||rm.P.ZeroReadOnly;e._instantiate(a,r,s,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; -`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`}serialize(){let e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnVerticesBlock.prototype,"evaluateContext",void 0),(0,rH.gn)([editableInPropertyPage("Remove duplicated positions",tT.Boolean,"ADVANCED",{notifiers:{update:!0}})],InstantiateOnVerticesBlock.prototype,"removeDuplicatedPositions",void 0),(0,rv.H)("BABYLON.InstantiateOnVerticesBlock",InstantiateOnVerticesBlock);let InstantiateOnFacesBlock=class InstantiateOnFacesBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentPosition=new rm.P,this._currentUV=new rm.FM,this._vertex0=new rm.P,this._vertex1=new rm.P,this._vertex2=new rm.P,this._tempVector0=new rm.P,this._tempVector1=new rm.P,this._uv0=new rm.FM,this._uv1=new rm.FM,this._uv2=new rm.FM,this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("instance",iX.Geometry,!0),this.registerInput("count",iX.Int,!0,256),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.scaling.acceptedConnectionPointTypes.push(iX.Float),this.registerOutput("output",iX.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),rm.P.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r,n=0,a=[],o=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),r=Math.random();if(i>r){let e=i;i=r,r=e}let l=i,h=r-i,u=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+u*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+u*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+u*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+u*this._uv2.x,l*this._uv0.y+h*this._uv1.y+u*this._uv2.y),!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length){n-=s;continue}let c=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,a)}else{let t=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly),i=this.rotation.getConnectedValue(e)||rm.P.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,a)}o++,this._currentLoopIndex++}}if(a.length){if(1===a.length)this._vertexData=a[0];else{let e=a.splice(0,1)[0];this._vertexData=e.merge(a,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnFacesBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.InstantiateOnFacesBlock",InstantiateOnFacesBlock);let InstantiateOnVolumeBlock=class InstantiateOnVolumeBlock extends NodeGeometryBlock{constructor(e){super(e),this._currentPosition=new rm.P,this._vertex0=new rm.P,this._vertex1=new rm.P,this._vertex2=new rm.P,this.evaluateContext=!0,this.registerInput("geometry",iX.Geometry),this.registerInput("instance",iX.Geometry,!0),this.registerInput("count",iX.Int,!0,256),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.scaling.acceptedConnectionPointTypes.push(iX.Float),this.registerOutput("output",iX.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=[],s=(0,lW.k)(this._vertexData.positions,0,this._vertexData.positions.length/3),n=s.minimum,a=s.maximum,o=new rm.P(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let s=0;s0&&h++}if(h%2==0){s--;continue}if(!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length)continue;let u=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,r)}else{let t=e.adaptInput(this.scaling,iX.Vector3,rm.P.OneReadOnly),i=this.rotation.getConnectedValue(e)||rm.P.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,r)}this._currentLoopIndex++}if(r.length){if(1===r.length)this._vertexData=r[0];else{let e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateOnVolumeBlock.prototype,"evaluateContext",void 0),(0,rv.H)("BABYLON.InstantiateOnVolumeBlock",InstantiateOnVolumeBlock);let InstantiateBaseBlock=class InstantiateBaseBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",iX.Geometry,!0),this.registerInput("count",iX.Int,!0,1),this.registerOutput("output",iX.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`;return e}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],InstantiateBaseBlock.prototype,"evaluateContext",void 0);let InstantiateBlock=class InstantiateBlock extends InstantiateBaseBlock{constructor(e){super(e),this.registerInput("matrix",iX.Matrix,!0),this.registerInput("position",iX.Vector3,!0,rm.P.Zero()),this.registerInput("rotation",iX.Vector3,!0,rm.P.Zero()),this.registerInput("scaling",iX.Vector3,!0,rm.P.One()),this.scaling.acceptedConnectionPointTypes.push(iX.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){let func=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=rm.y3.Identity(),s=rm.P.Zero(),n=rm.P.Zero(),a=rm.P.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=rm.y3.Identity(),s=rm.y3.Identity(),n=rm.y3.Identity(),a=rm.P.Zero(),o=rm.P.Zero(),l=rm.P.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}};(0,rv.H)("BABYLON.IntFloatConverterBlock",IntFloatConverterBlock);let DebugBlock=class DebugBlock extends NodeGeometryBlock{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",iX.AutoDetect),this.registerOutput("output",iX.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iX.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iX.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];let func=e=>{let t=this.input.getConnectedValue(e);return null==t?this.log.push("null"):this.log.push(t.toString()),t};this.output.isConnected?this.output._storedFunction=func:this.output._storedValue=func(e)}};(0,rv.H)("BABYLON.DebugBlock",DebugBlock);let GeometryInfoBlock=class GeometryInfoBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",iX.Geometry),this.registerOutput("output",iX.Geometry),this.registerOutput("id",iX.Int),this.registerOutput("collectionId",iX.Int),this.registerOutput("verticesCount",iX.Int),this.registerOutput("facesCount",iX.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}};(0,rv.H)("BABYLON.GeometryInfoBlock",GeometryInfoBlock),(eJ=iJ||(iJ={}))[eJ.Spherical=0]="Spherical",eJ[eJ.Cylindrical=1]="Cylindrical",eJ[eJ.Cubic=2]="Cubic";let MappingBlock=class MappingBlock extends NodeGeometryBlock{constructor(e){super(e),this.mapping=iJ.Spherical,this.registerInput("position",iX.Vector3),this.registerInput("normal",iX.Vector3),this.registerInput("center",iX.Vector3,!0,rm.P.Zero()),this.registerOutput("uv",iX.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}let e=rm.P.Zero(),func=t=>{let i=this.position.getConnectedValue(t)||rm.P.Zero(),r=this.normal.getConnectedValue(t)||rm.P.Zero(),s=this.center.getConnectedValue(t),n=rm.FM.Zero();switch(this.mapping){case iJ.Spherical:{i.subtractToRef(s,e);let t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,(0!==e.x||0!==e.z)&&(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case iJ.Cylindrical:{i.subtractToRef(s,e);let t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case iJ.Cubic:{let e=Math.abs(r.x),t=Math.abs(r.y),a=Math.abs(r.z),o=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),l=0,h=0;e>=t&&e>=a?(l=i.y/o-s.y,h=i.z/o-s.z):t>=e&&t>=a?(l=i.x/o-s.x,h=i.z/o-s.z):(l=i.x/o-s.x,h=i.y/o-s.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>func(e)}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${iJ[this.mapping]}; -`;return e}serialize(){let e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}};(0,rH.gn)([editableInPropertyPage("Mapping",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:iJ.Spherical},{label:"Cylindrical",value:iJ.Cylindrical},{label:"Cubic",value:iJ.Cubic}]})],MappingBlock.prototype,"mapping",void 0),(0,rv.H)("BABYLON.MappingBlock",MappingBlock);let MatrixComposeBlock=class MatrixComposeBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("matrix0",iX.Matrix),this.registerInput("matrix1",iX.Matrix),this.registerOutput("output",iX.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;let t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}};(0,rv.H)("BABYLON.MatrixComposeBlock",MatrixComposeBlock);let TeleportInBlock=class TeleportInBlock extends NodeGeometryBlock{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",iX.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this.endpoints){let i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(let e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}};(0,rv.H)("BABYLON.TeleportInBlock",TeleportInBlock);let TeleportOutBlock=class TeleportOutBlock extends NodeGeometryBlock{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",iX.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){let e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); -`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}};(0,rv.H)("BABYLON.TeleportOutBlock",TeleportOutBlock);let GeometryTextureBlock=class GeometryTextureBlock extends NodeGeometryBlock{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",iX.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{let r=new Image,s=document.createElement("canvas"),n=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,n.drawImage(r,0,0);let e=n.getImageData(0,0,r.width,r.height),i=e.data,a=new Float32Array(i.length);for(let e=0;e{this._data=null,i()},r.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}let r=e.getSize();aa.GetTextureDataAsync(e,r.width,r.height).then(async e=>{let i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){let func=e=>{let t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;let i=this.coordinates.getConnectedValue(e);if(!i)return null;let r=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),s=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(r*(t.width-1)),a=Math.floor(s*(t.height-1)),o=n+t.width*a;return rm.Lt.FromArray(t.data,4*o)};this.rgba._storedFunction=e=>func(e),this.rgb._storedFunction=e=>{let t=func(e);return t?t.toVector3():null},this.r._storedFunction=e=>{let t=func(e);return t?t.x:null},this.g._storedFunction=e=>{let t=func(e);return t?t.y:null},this.b._storedFunction=e=>{let t=func(e);return t?t.z:null},this.a._storedFunction=e=>{let t=func(e);return t?t.w:null}}_dumpPropertiesCode(){let e=super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates}; -`;return e}serialize(){let e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}};(0,rH.gn)([editableInPropertyPage("Clamp Coordinates",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],GeometryTextureFetchBlock.prototype,"clampCoordinates",void 0),(0,rv.H)("BABYLON.GeometryTextureFetchBlock",GeometryTextureFetchBlock);let BoundingBlock=class BoundingBlock extends NodeGeometryBlock{constructor(e){super(e),this.registerInput("geometry",iX.Geometry),this.registerOutput("min",iX.Vector3),this.registerOutput("max",iX.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);if(!t)return null;let i=(0,lW.k)(t.positions,0,t.positions.length/3);return i.minimum},this.max._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);if(!t)return null;let i=(0,lW.k)(t.positions,0,t.positions.length/3);return i.maximum}}};(0,rv.H)("BABYLON.BoundingBlock",BoundingBlock),(e0=i0||(i0={}))[e0.Intersect=0]="Intersect",e0[e0.Subtract=1]="Subtract",e0[e0.Union=2]="Union";let BooleanGeometryBlock=class BooleanGeometryBlock extends NodeGeometryBlock{constructor(e){super(e),this.evaluateContext=!1,this.operation=i0.Intersect,this.registerInput("geometry0",iX.Geometry),this.registerInput("geometry1",iX.Geometry),this.registerOutput("output",iX.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let func=e=>{let t;let i=this.geometry0.getConnectedValue(e),r=this.geometry1.getConnectedValue(e);if(!i||!r)return null;let s=i.positions.length/3;!i.normals&&r.normals&&(i.normals=Array(i.positions.length)),!r.normals&&i.normals&&(r.normals=Array(r.positions.length)),!i.uvs&&r.uvs&&(i.uvs=Array(2*s)),!r.uvs&&i.uvs&&(r.uvs=Array(2*s)),!i.colors&&r.colors&&(i.colors=Array(4*s)),!r.colors&&i.colors&&(r.colors=Array(4*s));let n=CSG.FromVertexData(i),a=CSG.FromVertexData(r);switch(this.operation){case i0.Intersect:t=n.intersect(a);break;case i0.Subtract:t=n.subtract(a);break;case i0.Union:t=n.union(a)}return t.toVertexData()};this.evaluateContext?this.output._storedFunction=func:(this.output._storedFunction=null,this.output._storedValue=func(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; -`+`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${i0[this.operation]}; -`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}};(0,rH.gn)([editableInPropertyPage("Evaluate context",tT.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],BooleanGeometryBlock.prototype,"evaluateContext",void 0),(0,rH.gn)([editableInPropertyPage("Operation",tT.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:i0.Intersect},{label:"Subtract",value:i0.Subtract},{label:"Union",value:i0.Union}]})],BooleanGeometryBlock.prototype,"operation",void 0),(0,rv.H)("BABYLON.BooleanGeometryBlock",BooleanGeometryBlock),rq.D.OfflineProviderFactory=(e,t,i=!1)=>new Database(e,t,i);let Database=class Database{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=Database._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,Database.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,rW.w1.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){let noManifestFile=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},createManifestURL=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){let e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`},t=!1,i=createManifestURL(),r=new rP.g;navigator.onLine&&(t=!0,i=i+(null==i.match(/\?/)?"?":"&")+Date.now()),r.open("GET",i),r.addEventListener("load",()=>{if(200===r.status||Database._ValidateXHRData(r,1))try{let t=JSON.parse(r.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&Database._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){noManifestFile()}else noManifestFile()},!1),r.addEventListener("error",()=>{if(t){t=!1;let e=createManifestURL();r.open("GET",e),r.send()}else noManifestFile()},!1);try{r.send()}catch(t){rT.Y.Error("Error on XHR send request."),e(!1)}}open(e,t){let handleError=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline)){if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;let t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{handleError()},t.onblocked=()=>{rT.Y.Error("IDB request blocked. Please reload the page."),handleError()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){rT.Y.Error("Error while creating object stores. Exception: "+e.message),handleError()}}}}else this._isSupported=!1,t&&t()}loadImage(e,t){let i=Database._ReturnFullUrlLocation(e),saveAndLoadImage=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?saveAndLoadImage():this._loadImageFromDBAsync(i,t,saveAndLoadImage)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;let s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{rT.Y.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};let n=s.objectStore("textures").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{rT.Y.Error("Error loading texture "+e+" from DB."),t.src=e}}else rT.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){let generateBlobUrl=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(Database._IsUASupportingBlobStorage){let r=new rP.g;r.open("GET",e),r.responseType="blob",r.addEventListener("load",()=>{if(200===r.status&&this._db){i=r.response;let s=this._db.transaction(["textures"],"readwrite");s.onabort=e=>{try{let t=e.target,i=t.error;i&&"QuotaExceededError"===i.name&&(this._hasReachedQuota=!0)}catch(e){}generateBlobUrl()},s.oncomplete=()=>{generateBlobUrl()};let n={textureUrl:e,data:i};try{let e=s.objectStore("textures").put(n);e.onsuccess=()=>{},e.onerror=()=>{generateBlobUrl()}}catch(i){25===i.code&&(Database._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),r.addEventListener("error",()=>{rT.Y.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),r.send()}else t.src=e}else rT.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,()=>{this._saveVersionIntoDBAsync(e,t)})}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{let s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};let n=s.objectStore("versions").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{rT.Y.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){rT.Y.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else rT.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{let i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};let r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{rT.Y.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){rT.Y.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){let n=Database._ReturnFullUrlLocation(e),saveAndLoadFile=()=>{this._saveFileAsync(n,t,i,s,r)};this._checkVersionFromDB(n,e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,s,r):this._loadFileAsync(n,t,saveAndLoadFile):r&&r()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let r,s;r=-1!==e.indexOf(".babylon")?"scenes":"textures";let n=this._db.transaction([r]);n.oncomplete=()=>{s?t(s.data):i()},n.onabort=()=>{i()};let a=n.objectStore(r).get(e);a.onsuccess=e=>{s=e.target.result},a.onerror=()=>{rT.Y.Error("Error loading file "+e+" from DB."),i()}}else rT.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let n,a;n=-1!==e.indexOf(".babylon")?"scenes":"textures";let o=new rP.g;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(200===o.status||o.status<400&&Database._ValidateXHRData(o,r?6:1)){if(a=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){let i;let r=this._db.transaction([n],"readwrite");r.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},r.oncomplete=()=>{t(a)},i="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{let e=r.objectStore(n).put(i);e.onsuccess=()=>{},e.onerror=()=>{rT.Y.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a)}else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{rT.Y.Error("error on XHR request."),s&&s()},!1),o.send()}else rT.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){let i=GetTGAHeader(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){let t=new Uint8Array(e.response,0,3);if(68===t[0]&&68===t[1]&&83===t[2])return!0}}catch(e){}return!1}};Database._IsUASupportingBlobStorage=!0,Database.IDBStorageEnabled=!1,Database._ParseURL=e=>{let t=document.createElement("a");t.href=e;let i=e.substring(0,e.lastIndexOf("#")),r=e.substring(i.lastIndexOf("/")+1,e.length),s=e.substring(0,e.indexOf(r,0));return s},Database._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?Database._ParseURL(window.location.href)+e:e;let UniformBufferEffectCommonAccessor=class UniformBufferEffectCommonAccessor{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}};let lj=`#version 300 es -void main() {discard;} -`;s_.v.ShadersStore.gpuUpdateParticlesPixelShader=lj;let lq=`#version 300 es -#define PI 3.14159 -uniform float currentCount;uniform float timeDelta;uniform float stopFactor; -#ifndef LOCAL -uniform mat4 emitterWM; -#endif -uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; -#ifndef COLORGRADIENTS -uniform vec4 color1;uniform vec4 color2; -#endif -uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; -#ifdef BOXEMITTER -uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; -#endif -#ifdef POINTEMITTER -uniform vec3 direction1;uniform vec3 direction2; -#endif -#ifdef HEMISPHERICEMITTER -uniform float radius;uniform float radiusRange;uniform float directionRandomizer; -#endif -#ifdef SPHEREEMITTER -uniform float radius;uniform float radiusRange; -#ifdef DIRECTEDSPHEREEMITTER -uniform vec3 direction1;uniform vec3 direction2; -#else -uniform float directionRandomizer; -#endif -#endif -#ifdef CYLINDEREMITTER -uniform float radius;uniform float height;uniform float radiusRange; -#ifdef DIRECTEDCYLINDEREMITTER -uniform vec3 direction1;uniform vec3 direction2; -#else -uniform float directionRandomizer; -#endif -#endif -#ifdef CONEEMITTER -uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; -#endif -in vec3 position; -#ifdef CUSTOMEMITTER -in vec3 initialPosition; -#endif -in float age;in float life;in vec4 seed;in vec3 size; -#ifndef COLORGRADIENTS -in vec4 color; -#endif -in vec3 direction; -#ifndef BILLBOARD -in vec3 initialDirection; -#endif -#ifdef ANGULARSPEEDGRADIENTS -in float angle; -#else -in vec2 angle; -#endif -#ifdef ANIMATESHEET -in float cellIndex; -#ifdef ANIMATESHEETRANDOMSTART -in float cellStartOffset; -#endif -#endif -#ifdef NOISE -in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; -#endif -out vec3 outPosition; -#ifdef CUSTOMEMITTER -out vec3 outInitialPosition; -#endif -out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; -#ifndef COLORGRADIENTS -out vec4 outColor; -#endif -out vec3 outDirection; -#ifndef BILLBOARD -out vec3 outInitialDirection; -#endif -#ifdef ANGULARSPEEDGRADIENTS -out float outAngle; -#else -out vec2 outAngle; -#endif -#ifdef ANIMATESHEET -out float outCellIndex; -#ifdef ANIMATESHEETRANDOMSTART -out float outCellStartOffset; -#endif -#endif -#ifdef NOISE -out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; -#endif -#ifdef SIZEGRADIENTS -uniform sampler2D sizeGradientSampler; -#endif -#ifdef ANGULARSPEEDGRADIENTS -uniform sampler2D angularSpeedGradientSampler; -#endif -#ifdef VELOCITYGRADIENTS -uniform sampler2D velocityGradientSampler; -#endif -#ifdef LIMITVELOCITYGRADIENTS -uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; -#endif -#ifdef DRAGGRADIENTS -uniform sampler2D dragGradientSampler; -#endif -#ifdef NOISE -uniform vec3 noiseStrength;uniform sampler2D noiseSampler; -#endif -#ifdef ANIMATESHEET -uniform vec4 cellInfos; -#endif -vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} -vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} -void main() {float newAge=age+timeDelta; -if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; -#ifdef SIZEGRADIENTS -outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; -#else -outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; -#endif -outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; -#ifndef COLORGRADIENTS -outColor=color1+(color2-color1)*randoms.b; -#endif -#ifndef ANGULARSPEEDGRADIENTS -outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; -#else -outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; -#endif -#ifdef POINTEMITTER -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; -#elif defined(BOXEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; -#elif defined(HEMISPHERICEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; -#elif defined(SPHEREEMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); -#ifdef DIRECTEDSPHEREEMITTER -newDirection=normalize(direction1+(direction2-direction1)*randoms3); -#else -newDirection=normalize(newPosition+directionRandomizer*randoms3); -#endif -#elif defined(CYLINDEREMITTER) -vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); -#ifdef DIRECTEDCYLINDEREMITTER -newDirection=direction1+(direction2-direction1)*randoms3; -#else -angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); -#endif -#elif defined(CONEEMITTER) -vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; -#ifdef CONEEMITTERSPAWNPOINT -float h=0.0001; -#else -float h=randoms2.y*height.y;h=1.-h*h; -#endif -float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); -if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } -#elif defined(CUSTOMEMITTER) -newPosition=initialPosition;outInitialPosition=initialPosition; -#else -newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); -#endif -float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; -#ifdef LOCAL -outPosition=newPosition; -#else -outPosition=(emitterWM*vec4(newPosition,1.)).xyz; -#endif -#ifdef CUSTOMEMITTER -outDirection=direction; -#ifndef BILLBOARD -outInitialDirection=direction; -#endif -#else -#ifdef LOCAL -vec3 initial=newDirection; -#else -vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; -#endif -outDirection=initial*power; -#ifndef BILLBOARD -outInitialDirection=initial; -#endif -#endif -#ifdef ANIMATESHEET -outCellIndex=cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -outCellStartOffset=randoms.a*outLife; -#endif -#endif -#ifdef NOISE -outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; -#endif -} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; -#ifdef VELOCITYGRADIENTS -directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; -#endif -#ifdef DRAGGRADIENTS -directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; -#endif -#if defined(CUSTOMEMITTER) -outPosition=position+(direction-position)*ageGradient; -outInitialPosition=initialPosition; -#else -outPosition=position+direction*directionScale; -#endif -outLife=life;outSeed=seed; -#ifndef COLORGRADIENTS -outColor=color; -#endif -#ifdef SIZEGRADIENTS -outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; -#else -outSize=size; -#endif -#ifndef BILLBOARD -outInitialDirection=initialDirection; -#endif -#ifdef CUSTOMEMITTER -outDirection=direction; -#else -vec3 updatedDirection=direction+gravity*timeDelta; -#ifdef LIMITVELOCITYGRADIENTS -float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} -#endif -outDirection=updatedDirection; -#ifdef NOISE -float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; -#endif -#endif -#ifdef ANGULARSPEEDGRADIENTS -float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; -#else -outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); -#endif -#ifdef ANIMATESHEET -float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; -#else -float cellStartOffset=0.; -#endif -float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} -else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} -outCellIndex=float(int(cellInfos.x+ratio*dist)); -#endif -}}`;s_.v.ShadersStore.gpuUpdateParticlesVertexShader=lq;let WebGL2ParticleSystem=class WebGL2ParticleSystem{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateEffect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof CustomParticleEmitter&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new ss.Q("gpuUpdateParticles",this._updateEffectOptions,this._engine),new UniformBufferEffectCommonAccessor(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){let e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);let r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e, -age : f32, -size : vec3, -life : f32, -seed : vec4, -direction : vec3, -dummy0: f32, -#ifdef CUSTOMEMITTER -initialPosition : vec3, -dummy1: f32, -#endif -#ifndef COLORGRADIENTS -color : vec4, -#endif -#ifndef BILLBOARD -initialDirection : vec3, -dummy2: f32, -#endif -#ifdef NOISE -noiseCoordinates1 : vec3, -dummy3: f32, -noiseCoordinates2 : vec3, -dummy4: f32, -#endif -#ifdef ANGULARSPEEDGRADIENTS -angle : f32, -#else -angle : vec2, -#endif -#ifdef ANIMATESHEET -cellIndex : f32, -#ifdef ANIMATESHEETRANDOMSTART -cellStartOffset : f32, -#endif -#endif -};struct Particles {particles : array,};struct SimParams {currentCount : f32, -timeDelta : f32, -stopFactor : f32, -randomTextureSize: i32, -lifeTime : vec2, -emitPower : vec2, -#ifndef COLORGRADIENTS -color1 : vec4, -color2 : vec4, -#endif -sizeRange : vec2, -scaleRange : vec4, -angleRange : vec4, -gravity : vec3, -#ifdef LIMITVELOCITYGRADIENTS -limitVelocityDamping : f32, -#endif -#ifdef ANIMATESHEET -cellInfos : vec4, -#endif -#ifdef NOISE -noiseStrength : vec3, -#endif -#ifndef LOCAL -emitterWM : mat4x4, -#endif -#ifdef BOXEMITTER -direction1 : vec3, -direction2 : vec3, -minEmitBox : vec3, -maxEmitBox : vec3, -#endif -#ifdef CONEEMITTER -radius : vec2, -coneAngle : f32, -height : vec2, -directionRandomizer : f32, -#endif -#ifdef CYLINDEREMITTER -radius : f32, -height : f32, -radiusRange : f32, -#ifdef DIRECTEDCYLINDEREMITTER -direction1 : vec3, -direction2 : vec3, -#else -directionRandomizer : f32, -#endif -#endif -#ifdef HEMISPHERICEMITTER -radius : f32, -radiusRange : f32, -directionRandomizer : f32, -#endif -#ifdef POINTEMITTER -direction1 : vec3, -direction2 : vec3, -#endif -#ifdef SPHEREEMITTER -radius : f32, -radiusRange : f32, -#ifdef DIRECTEDSPHEREEMITTER -direction1 : vec3, -direction2 : vec3, -#else -directionRandomizer : f32, -#endif -#endif -};@binding(0) @group(0) var params : SimParams;@binding(1) @group(0) var particlesIn : Particles;@binding(2) @group(0) var particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d;@binding(4) @group(0) var randomTexture2 : texture_2d; -#ifdef SIZEGRADIENTS -@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d; -#endif -#ifdef ANGULARSPEEDGRADIENTS -@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d; -#endif -#ifdef VELOCITYGRADIENTS -@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d; -#endif -#ifdef LIMITVELOCITYGRADIENTS -@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d; -#endif -#ifdef DRAGGRADIENTS -@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d; -#endif -#ifdef NOISE -@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d; -#endif -fn getRandomVec3(offset : f32,vertexID : f32)->vec3 {return textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} -fn getRandomVec4(offset : f32,vertexID : f32)->vec4 {return textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} -@compute @workgroup_size(64) -fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} -let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4=particlesIn.particles[index].seed;let direction : vec3=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3;var newDirection : vec3;let randoms : vec4=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; -#ifdef SIZEGRADIENTS -sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r; -#else -sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; -#endif -particlesOut.particles[index].size=vec3( -sizex, -params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, -params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); -#ifndef COLORGRADIENTS -particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; -#endif -#ifndef ANGULARSPEEDGRADIENTS -particlesOut.particles[index].angle=vec2( -params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, -params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); -#else -particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; -#endif -#if defined(POINTEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=vec3(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#elif defined(BOXEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#elif defined(HEMISPHERICEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); -#elif defined(SPHEREEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ); -#ifdef DIRECTEDSPHEREEMITTER -newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); -#else -newDirection=normalize(newPosition+params.directionRandomizer*randoms3); -#endif -#elif defined(CYLINDEREMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); -#ifdef DIRECTEDCYLINDEREMITTER -newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; -#else -angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); -#endif -#elif defined(CONEEMITTER) -let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; -#ifdef CONEEMITTERSPAWNPOINT -let h : f32=0.0001; -#else -var h : f32=randoms2.y*params.height.y;h=1.-h*h; -#endif -var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3(randX,randY,randZ); -if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } -#elif defined(CUSTOMEMITTER) -newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; -#else -newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5)); -#endif -let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; -#ifdef LOCAL -particlesOut.particles[index].position=newPosition; -#else -particlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz; -#endif -#ifdef CUSTOMEMITTER -particlesOut.particles[index].direction=direction; -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=direction; -#endif -#else -#ifdef LOCAL -let initial : vec3=newDirection; -#else -let initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz; -#endif -particlesOut.particles[index].direction=initial*power; -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=initial; -#endif -#endif -#ifdef ANIMATESHEET -particlesOut.particles[index].cellIndex=params.cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -particlesOut.particles[index].cellStartOffset=randoms.a*outLife; -#endif -#endif -#ifdef NOISE -particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; -#endif -} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; -#ifdef VELOCITYGRADIENTS -directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r; -#endif -#ifdef DRAGGRADIENTS -directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r); -#endif -let position : vec3=particlesIn.particles[index].position; -#if defined(CUSTOMEMITTER) -particlesOut.particles[index].position=position+(direction-position)*ageGradient; -particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; -#else -particlesOut.particles[index].position=position+direction*directionScale; -#endif -particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; -#ifndef COLORGRADIENTS -particlesOut.particles[index].color=particlesIn.particles[index].color; -#endif -#ifdef SIZEGRADIENTS -particlesOut.particles[index].size=vec3( -textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r, -particlesIn.particles[index].size.yz); -#else -particlesOut.particles[index].size=particlesIn.particles[index].size; -#endif -#ifndef BILLBOARD -particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; -#endif -#ifdef CUSTOMEMITTER -particlesOut.particles[index].direction=direction; -#else -var updatedDirection : vec3=direction+params.gravity*timeDelta; -#ifdef LIMITVELOCITYGRADIENTS -let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} -#endif -particlesOut.particles[index].direction=updatedDirection; -#ifdef NOISE -let noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; -#endif -#endif -#ifdef ANGULARSPEEDGRADIENTS -let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; -#else -let angle : vec2=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y); -#endif -#ifdef ANIMATESHEET -var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; -#ifdef ANIMATESHEETRANDOMSTART -let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; -#else -let cellStartOffset : f32=0.; -#endif -var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} -else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} -particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); -#endif -}} -`;s_.v.ShadersStoreWGSL.gpuUpdateParticlesComputeShader=lK;let ComputeShaderParticleSystem=class ComputeShaderParticleSystem{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){var t;let i={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new ComputeShader("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new rX.M(this._engine),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new UniformBufferEffectCommonAccessor(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){let t=new StorageBuffer(this._engine,4*e.length,11);return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let e=0;ee){i(t[0],t[0],1);return}for(let r=0;r=s.gradient&&e<=n.gradient){let t=(e-s.gradient)/(n.gradient-s.gradient);i(s,n,t);return}}let r=t.length-1;i(t[r],t[r],1)}};let Particle=class Particle{constructor(e){if(this.particleSystem=e,this.position=rm.P.Zero(),this.direction=rm.P.Zero(),this.color=new rg.HE(0,0,0,0),this.colorStep=new rg.HE(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new rm.FM(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new rg.HE(0,0,0,0),this._currentColor2=new rg.HE(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=Particle._Count++,!this.particleSystem.isAnimationSheetEnabled)return;this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e,t=this.age,i=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===i?(i=1,t=this._randomCellOffset):t+=this._randomCellOffset);let r=this._initialEndSpriteCellID-this._initialStartSpriteCellID;e=this._initialSpriteCellLoop?rE.R.Clamp(t*i%this.lifeTime/this.lifeTime):rE.R.Clamp(t*i/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+e*r|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){let t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){let e=rm.jp.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else{let t=e.particleSystem.emitter;t.copyFrom(this.position)}this.direction.scaleToRef(e.inheritedVelocityAmount/2,rm.jp.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(rm.jp.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=Particle._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new rm.Lt(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}};Particle._Count=0,(e1=i1||(i1={}))[e1.ATTACHED=0]="ATTACHED",e1[e1.END=1]="END";let SubEmitter=class SubEmitter{constructor(e){if(this.particleSystem=e,this.type=i1.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){let t=(0,rv.q)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;if(e){if(e instanceof rm.P)e=e.clone();else if(-1!==e.getClassName().indexOf("Mesh")){let t=(0,rv.q)("BABYLON.Mesh");(e=new t("",e.getScene())).isVisible=!1}}else e=new rm.P;let t=new SubEmitter(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){let t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw(0,r$.S)("ParseParticle")}static Parse(e,t,i){let r=e.particleSystem,s=new SubEmitter(SubEmitter._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}};let l$=`#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; -#include -#include -#include -#include -#include -#ifdef RAMPGRADIENT -varying vec4 remapRanges;uniform sampler2D rampSampler; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; -#ifdef RAMPGRADIENT -float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); -#endif -#ifdef BLENDMULTIPLYMODE -float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); -#endif -#include -#ifdef IMAGEPROCESSINGPOSTPROCESS -baseColor.rgb=toLinearSpace(baseColor.rgb); -#else -#ifdef IMAGEPROCESSING -baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); -#endif -#endif -gl_FragColor=baseColor; -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.particlesPixelShader=l$;let lQ=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; -#ifdef ANIMATESHEET -attribute float cellIndex; -#endif -#ifndef BILLBOARD -attribute vec3 direction; -#endif -#ifdef BILLBOARDSTRETCHED -attribute vec3 direction; -#endif -#ifdef RAMPGRADIENT -attribute vec4 remapData; -#endif -attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; -#ifdef ANIMATESHEET -uniform vec3 particlesInfos; -#endif -varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; -#ifdef RAMPGRADIENT -varying vec4 remapRanges; -#endif -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include -#include -#ifdef BILLBOARD -uniform vec3 eyePosition; -#endif -vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} -#ifdef BILLBOARDSTRETCHED -vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); -#ifdef BILLBOARDSTRETCHED_LOCAL -vec3 row1=direction; -#else -vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); -#endif -mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; -#ifdef BILLBOARD -vec3 rotatedCorner; -#ifdef BILLBOARDY -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; -#elif defined(BILLBOARDSTRETCHED) -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; -#else -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; -#endif -#ifdef RAMPGRADIENT -remapRanges=remapData; -#endif -gl_Position=projection*vec4(viewPos,1.0); -#else -vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); -#endif -vColor=color; -#ifdef ANIMATESHEET -float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; -#else -vUV=offset; -#endif -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=vec4(vPositionW,1.0); -#endif -#include -#include -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.particlesVertexShader=lQ;let particleSystem_ParticleSystem=class particleSystem_ParticleSystem extends BaseParticleSystem{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new sm.q(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new rf.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,n=.01){super(e),this._emitterInverseWorldMatrix=rm.y3.Identity(),this._inheritedVelocityOffset=new rm.P,this.onDisposeObservable=new rf.y$,this.onStoppedObservable=new rf.y$,this._particles=[],this._stockParticles=[],this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new rg.HE(0,0,0,0),this._colorDiff=new rg.HE(0,0,0,0),this._scaledDirection=rm.P.Zero(),this._scaledGravity=rm.P.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=e=>{let t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;if(0!==this._stockParticles.length?(e=this._stockParticles.pop())._reset():e=new Particle(this),this._subEmitters&&this._subEmitters.length>0){let t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(t=>{if(t.type===i1.ATTACHED){let i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;let t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(t=>{if(t.type===i1.END){let i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=rm.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||rS.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new sm.q(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new BoxParticleEmitter;let a=null;this.updateFunction=e=>{var t;let i=null;this.noiseTexture&&(i=this.noiseTexture.getSize(),null===(t=this.noiseTexture.getContent())||void 0===t||t.then(e=>{a=e}));let r=e===this._particles;for(let t=0;ts.lifeTime){let e=s.age-o,t=s.lifeTime-o;n=t*n/e,s.age=s.lifeTime}let l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?GradientHelper.GetCurrentGradient(l,this._colorGradients,(e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),rg.HE.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)}):(s.colorStep.scaleToRef(n,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._angularSpeedGradients,(e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=rE.R.Lerp(s._currentAngularSpeed1,s._currentAngularSpeed2,i)}),s.angle+=s.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._velocityGradients,(e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=rE.R.Lerp(s._currentVelocity1,s._currentVelocity2,i)}),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._limitVelocityGradients,(e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);let r=rE.R.Lerp(s._currentLimitVelocity1,s._currentLimitVelocity2,i),n=s.direction.length();n>r&&s.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._dragGradients,(e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);let r=rE.R.Lerp(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)}),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),rm.P.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),a&&i&&s._randomNoiseCoordinates1){let e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,i.width,i.height,a),t=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,i.width,i.height,a),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,i.width,i.height,a),o=rm.jp.Vector3[0],l=rm.jp.Vector3[1];o.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),o.scaleToRef(n,l),s.direction.addInPlace(l)}if(this.gravity.scaleToRef(n,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._sizeGradients,(e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=rE.R.Lerp(s._currentSize1,s._currentSize2,i)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._colorRemapGradients,(e,t,i)=>{let r=rE.R.Lerp(e.factor1,t.factor1,i),n=rE.R.Lerp(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=n-r}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&GradientHelper.GetCurrentGradient(l,this._alphaRemapGradients,(e,t,i)=>{let r=rE.R.Lerp(e.factor1,t.factor1,i),n=rE.R.Lerp(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=n-r})),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime){this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach(e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),s._attachedSubEmitters=null),this.recycleParticle(s),r&&t--;continue}}}}_addFactorGradient(e,t,i,r){let s=new FactorGradient(t,i,r);e.push(s),e.sort((e,t)=>e.gradientt.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(let r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;let e=new Uint8Array(4*this._rawTextureWidth),t=rg.zZ.Color3[0];for(let i=0;i{rg.Wo.LerpToRef(r.color,s.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255})}this._rampGradientsTexture=rawTexture_RawTexture.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);let i=new Color3Gradient(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);let r=new ColorGradient(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((e,t)=>e.gradientt.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(let i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(let e of this._drawWrappers)if(e)for(let t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){e=.5*Math.abs(e)+.5,t=.5*Math.abs(t)+.5;let n=e*i%i|0,a=t*r%r|0;return s[(n+a*i)*4]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){let e;this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);let t=this._engine,i=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*i),this._vertexBuffer=new rz.l(t,this._vertexData,!0,i);let r=0,s=this._vertexBuffer.createVertexBuffer(rz.o.PositionKind,r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rz.o.PositionKind]=s,r+=3;let n=this._vertexBuffer.createVertexBuffer(rz.o.ColorKind,r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rz.o.ColorKind]=n,r+=4;let a=this._vertexBuffer.createVertexBuffer("angle",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=a,r+=1;let o=this._vertexBuffer.createVertexBuffer("size",r,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,r+=2,this._isAnimationSheetEnabled){let e=this._vertexBuffer.createVertexBuffer("cellIndex",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,r+=1}if(!this._isBillboardBased||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL){let e=this._vertexBuffer.createVertexBuffer("direction",r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,r+=3}if(this._useRampGradients){let e=this._vertexBuffer.createVertexBuffer("remapData",r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,r+=4}if(this._useInstancing){let i=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new rz.l(t,i,!1,2),e=this._spriteBuffer.createVertexBuffer("offset",0,2)}else e=this._vertexBuffer.createVertexBuffer("offset",r,2,this._vertexBufferSize,this._useInstancing),r+=2;this._vertexBuffers.offset=e,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}let e=[],t=[],i=0;for(let r=0;r{e instanceof particleSystem_ParticleSystem?this._subEmitters.push([new SubEmitter(e)]):e instanceof SubEmitter?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[]),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);let e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){!this._stopped&&(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED||this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL)&&(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(rm.P.TransformNormalToRef(e,this._emitterWorldMatrix,rm.jp.Vector3[0]),e=rm.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(rm.P.TransformNormalToRef(e,this._emitterWorldMatrix,rm.jp.Vector3[0]),e=rm.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;let e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){let t;if(this._alive=this._particles.length>0,this.emitter.position){let e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{let e=this.emitter;this._emitterWorldMatrix=rm.y3.Translation(e.x,e.y,e.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){let e=rE.R.Clamp(this._actualFrame/this.targetStopDuration);GradientHelper.GetCurrentGradient(e,this._lifeTimeGradients,(i,r)=>{let s=i.getFactor(),n=r.getFactor(),a=(e-i.gradient)/(r.gradient-i.gradient);t.lifeTime=rE.R.Lerp(s,n,a)})}else t.lifeTime=rE.R.RandomRange(this.minLifeTime,this.maxLifeTime);let e=rE.R.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),rm.P.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=rE.R.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(rE.R.RandomRange(this.minScaleX,this.maxScaleX),rE.R.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){let e=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(e,this._startSizeGradients,(e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);let s=rE.R.Lerp(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)})}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=rE.R.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=rE.R.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{let e=rE.R.RandomRange(0,1);rg.HE.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new rm.Lt(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new rm.P(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new rm.P(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){let r=[rz.o.PositionKind,rz.o.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1){let i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,nX.qx)(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&(0,nX.lK)(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===particleSystem_ParticleSystem.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case particleSystem_ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED:case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case particleSystem_ParticleSystem.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...particleSystem_ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED&&this.billboardMode!==particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...particleSystem_ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(sv.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),sv.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0,s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let n=s[e];n||((n=new sm.q(this._engine)).drawContext&&(n.drawContext.useInstancing=this._useInstancing),s[e]=n);let a=i.join("\n");if(n.defines!==a){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,a),a)}return n}animate(e=!1){var t;let i;if(this._started){if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){let t=this._actualFrame/this.targetStopDuration;GradientHelper.GetCurrentGradient(t,this._emitRateGradients,(t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=rE.R.Lerp(this._currentEmitRate1,this._currentEmitRate2,r)})}i=e*this._scaledUpdateSpeed>>0,this._newPartsExcess+=e*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&!this._alive&&(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this)),!e){let e=0;for(let t=0;t=0&&(d.invertToRef(rm.jp.Matrix[0]),u.setMatrix("invView",rm.jp.Matrix[0])),void 0!==this._vertexArrayObject?(null===(r=this._scene)||void 0===r?void 0:r.forceWireframe)?c.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,u):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,u)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?c.bindBuffers(this._vertexBuffers,(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._linesIndexBuffer:this._indexBuffer,u):c.bindBuffers(this._vertexBuffers,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBufferUseInstancing:null,u),this.useLogarithmicDepth&&this._scene&&so.G.BindLogDepth(p,u,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(u),e){case particleSystem_ParticleSystem.BLENDMODE_ADD:c.setAlphaMode(1);break;case particleSystem_ParticleSystem.BLENDMODE_ONEONE:c.setAlphaMode(6);break;case particleSystem_ParticleSystem.BLENDMODE_STANDARD:c.setAlphaMode(2);break;case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY:c.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(u),this._useInstancing?(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?c.drawElementsType(6,0,10,this._particles.length):c.drawArraysType(7,0,4,this._particles.length):(null===(l=this._scene)||void 0===l?void 0:l.forceWireframe)?c.drawElementsType(1,0,10*this._particles.length):c.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;let e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD?this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY)+this._render(particleSystem_ParticleSystem.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){s=this.customShader;let e=s.shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}let a=this.serialize(i),o=particleSystem_ParticleSystem.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,this.preventAutoStart||o.start(),o}serialize(e=!1){let t={};if(particleSystem_ParticleSystem._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters)for(let i of(t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray(),this._subEmitters)){let r=[];for(let t of i)r.push(t.serialize(e));t.subEmitters.push(r)}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){let i=t.emitter;e.emitterId=i.id}else{let i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,rb.p4.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;let r=t.getColorGradients();if(r)for(let t of(e.colorGradients=[],r)){let i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}let s=t.getRampGradients();if(s){for(let t of(e.rampGradients=[],s)){let i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}let n=t.getColorRemapGradients();if(n)for(let t of(e.colorRemapGradients=[],n)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}let a=t.getAlphaRemapGradients();if(a)for(let t of(e.alphaRemapGradients=[],a)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}let o=t.getSizeGradients();if(o)for(let t of(e.sizeGradients=[],o)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}let l=t.getAngularSpeedGradients();if(l)for(let t of(e.angularSpeedGradients=[],l)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}let h=t.getVelocityGradients();if(h)for(let t of(e.velocityGradients=[],h)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}let u=t.getDragGradients();if(u)for(let t of(e.dragGradients=[],u)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}let c=t.getEmitRateGradients();if(c)for(let t of(e.emitRateGradients=[],c)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}let d=t.getStartSizeGradients();if(d)for(let t of(e.startSizeGradients=[],d)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}let p=t.getLifeTimeGradients();if(p)for(let t of(e.lifeTimeGradients=[],p)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}let _=t.getLimitVelocityGradients();if(_){for(let t of(e.limitVelocityGradients=[],_)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,r){var s,n,a;let o,l;o=i instanceof r6.B?null:i;let h=(0,rv.q)("BABYLON.Texture");if(h&&o&&(e.texture?t.particleTexture=h.Parse(e.texture,o,r):e.textureName&&(t.particleTexture=new h(r+e.textureName,o,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&o?t.emitter=o.getLastMeshById(e.emitterId):t.emitter=rm.P.FromArray(e.emitter):t.emitter=rm.P.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let i=0;i0?l.shaderOptions.defines.join("\n"):"";o=n.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,t)}let h=new particleSystem_ParticleSystem(a,s||e.capacity,t,o,e.isAnimationSheetEnabled);if(h.customShader=l,h._rootUrl=i,e.id&&(h.id=e.id),e.subEmitters)for(let r of(h.subEmitters=[],e.subEmitters)){let e=[];for(let s of r)e.push(SubEmitter.Parse(s,t,i));h.subEmitters.push(e)}return particleSystem_ParticleSystem._Parse(e,h,t,i),e.textureMask&&(h.textureMask=rg.HE.FromArray(e.textureMask)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),r||h.preventAutoStart||h.start(),h}};particleSystem_ParticleSystem.BILLBOARDMODE_Y=2,particleSystem_ParticleSystem.BILLBOARDMODE_ALL=7,particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED=8,particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL=9,SubEmitter._ParseParticleSystem=particleSystem_ParticleSystem.Parse;let lZ=`#ifdef CLIPPLANE -in float fClipDistance; -#endif -#ifdef CLIPPLANE2 -in float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -in float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -in float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -in float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -in float fClipDistance6; -#endif -`;s_.v.IncludesShadersStore.clipPlaneFragmentDeclaration2=lZ;let lJ=`precision highp float; -#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; -#include -#include -#include -#include -#include -void main() { -#include -vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; -#ifdef BLENDMULTIPLYMODE -float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); -#endif -#include -#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); -#else -#ifdef IMAGEPROCESSING -gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); -#endif -#endif -} -`;s_.v.ShadersStore.gpuRenderParticlesPixelShader=lJ;let l0=`#ifdef CLIPPLANE -uniform vec4 vClipPlane;out float fClipDistance; -#endif -#ifdef CLIPPLANE2 -uniform vec4 vClipPlane2;out float fClipDistance2; -#endif -#ifdef CLIPPLANE3 -uniform vec4 vClipPlane3;out float fClipDistance3; -#endif -#ifdef CLIPPLANE4 -uniform vec4 vClipPlane4;out float fClipDistance4; -#endif -#ifdef CLIPPLANE5 -uniform vec4 vClipPlane5;out float fClipDistance5; -#endif -#ifdef CLIPPLANE6 -uniform vec4 vClipPlane6;out float fClipDistance6; -#endif -`;s_.v.IncludesShadersStore.clipPlaneVertexDeclaration2=l0;let l1=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; -#ifdef LOCAL -uniform mat4 emitterWM; -#endif -attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; -#ifndef BILLBOARD -attribute vec3 initialDirection; -#endif -#ifdef BILLBOARDSTRETCHED -attribute vec3 direction; -#endif -attribute float angle; -#ifdef ANIMATESHEET -attribute float cellIndex; -#endif -attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; -#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) -uniform mat4 invView; -#endif -#include -#include -#ifdef COLORGRADIENTS -uniform sampler2D colorGradientSampler; -#else -uniform vec4 colorDead;attribute vec4 color; -#endif -#ifdef ANIMATESHEET -uniform vec3 sheetInfos; -#endif -#ifdef BILLBOARD -uniform vec3 eyePosition; -#endif -vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; -#ifdef LOCAL -return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; -#else -return (position+worldOffset)+alignedCorner; -#endif -} -#ifdef BILLBOARDSTRETCHED -vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; -#ifdef LOCAL -return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; -#else -return (position+worldOffset)+alignedCorner; -#endif -} -#endif -void main() { -#ifdef ANIMATESHEET -float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; -#else -vUV=uv; -#endif -float ratio=age/life; -#ifdef COLORGRADIENTS -vColor=texture2D(colorGradientSampler,vec2(ratio,0)); -#else -vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); -#endif -vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; -#ifdef BILLBOARD -vec4 rotatedCorner;rotatedCorner.w=0.; -#ifdef BILLBOARDY -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); -#elif defined(BILLBOARDSTRETCHED) -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); -#else -rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; -#ifdef LOCAL -vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; -#else -vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; -#endif -vPositionW=(invView*viewPosition).xyz; -#endif -#else -vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); -#endif -gl_Position=projection*viewPosition; -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=vec4(vPositionW,1.0); -#endif -#include -#include -}`;s_.v.ShadersStore.gpuRenderParticlesVertexShader=l1;let GPUParticleSystem=class GPUParticleSystem extends BaseParticleSystem{static get IsSupported(){if(!rS.l.LastCreatedEngine)return!1;let e=rS.l.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]))}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(particleSystem_ParticleSystem.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new sm.q(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new rf.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);let i=new ColorGradient(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(let t in this._drawWrappers){let i=this._drawWrappers[t];null===(e=i.drawContext)||void 0===e||e.reset()}}_addFactorGradient(e,t,i){let r=new FactorGradient(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){e&&(i&&e.sort((e,t)=>e.gradientt.gradient?1:0),this[t]&&(this[t].dispose(),this[t]=null))}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new rf.y$,this.onStoppedObservable=new rf.y$,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=rm.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||rS.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,rv.q)("BABYLON.ComputeShaderParticleSystem"))throw Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,rv.q)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,rv.q)("BABYLON.WebGL2ParticleSystem"))throw Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,rv.q)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new sm.q(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new sm.q(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;let n=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),a=t;isFinite(a)&&(n.capacity=a),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new BoxParticleEmitter;let o=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize),l=[];for(let e=0;e0;)i.push(0)}let a=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),o=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new rz.l(t,o,!1,this._attributesStrideSize),this._buffer1=new rz.l(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new rz.l(t,a,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),!!this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||((r=new sm.q(this._engine)).drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);let s=i.join("\n");if(r.defines!==s){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){let s=[rz.o.PositionKind,"age","life","size","angle"];return e||s.push(rz.o.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",rz.o.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){let i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,nX.qx)(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&(0,nX.lK)(this,this._scene,e),t===particleSystem_ParticleSystem.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case particleSystem_ParticleSystem.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case particleSystem_ParticleSystem.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===particleSystem_ParticleSystem.BILLBOARDMODE_STRETCHED)),e.push(...GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(sv.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),sv.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,!this._stopped&&this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){let i=this[t];if(!e||!e.length||i)return;let r=new Float32Array(this._rawTextureWidth);for(let t=0;t{r[t]=rE.R.Lerp(e.factor1,i.factor1,s)})}this[t]=rawTexture_RawTexture.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;let e=new Uint8Array(4*this._rawTextureWidth),t=rg.zZ.Color4[0];for(let i=0;i{rg.HE.LerpToRef(r.color1,s.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a})}this._colorGradientsTexture=rawTexture_RawTexture.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,r,s,n,a;let o=this._getWrapper(e),l=o.effect;this._engine.enableEffect(o);let h=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||rm.y3.IdentityReadOnly;if(l.setMatrix("view",h),l.setMatrix("projection",null!==(r=this.defaultProjectionMatrix)&&void 0!==r?r:this._scene.getProjectionMatrix()),l.setTexture("diffuseSampler",this.particleTexture),l.setVector2("translationPivot",this.translationPivot),l.setVector3("worldOffset",this.worldOffset),this.isLocal&&l.setMatrix("emitterWM",t),this._colorGradientsTexture?l.setTexture("colorGradientSampler",this._colorGradientsTexture):l.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();l.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;l.setVector3("eyePosition",e.globalPosition)}let u=l.defines;if(this._scene&&(0,nX.an)(l,this,this._scene),u.indexOf("#define BILLBOARDMODE_ALL")>=0){let e=h.clone();e.invert(),l.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&so.G.BindLogDepth(u,l,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(l),e){case particleSystem_ParticleSystem.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case particleSystem_ParticleSystem.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case particleSystem_ParticleSystem.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case particleSystem_ParticleSystem.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,l,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(l),(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e){if(this.emitter.position){let t=this.emitter;e=t.getWorldMatrix()}else{let t=this.emitter;e=rm.jp.Matrix[0],rm.y3.TranslationToRef(t.x,t.y,t.z,e)}}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);let t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){let i;if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){let e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;if(this.emitter.position){let e=this.emitter;i=e.getWorldMatrix()}else{let e=this.emitter;i=rm.jp.Matrix[0],rm.y3.TranslationToRef(e.x,e.y,e.z,i)}let r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===particleSystem_ParticleSystem.BLENDMODE_MULTIPLYADD?this._render(particleSystem_ParticleSystem.BLENDMODE_MULTIPLY,i)+this._render(particleSystem_ParticleSystem.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){let checkUpdateEffect=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?this._initialize(!0):setTimeout(checkUpdateEffect,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),checkUpdateEffect()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(let e in this._drawWrappers){let t=this._drawWrappers[e];t.dispose()}if(this._drawWrappers={},this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?s.shaderOptions.defines.join("\n"):"";r[0]=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}let a=this.serialize(i),o=GPUParticleSystem.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,o}serialize(e=!1){let t={};return particleSystem_ParticleSystem._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){let n;let a=e.name;n=t instanceof r6.B?t:t.getEngine();let o=new GPUParticleSystem(a,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(o._rootUrl=i,e.customShader&&n.createEffectForParticles){let t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=n.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,o);o.setCustomEffect(r,0),o.customShader=t}return e.id&&(o.id=e.id),e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),particleSystem_ParticleSystem._Parse(e,o,t,i),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o}};let ParticleSystemSet=class ParticleSystemSet{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){for(let t of(this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1),this.systems))t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};let r=sphereBuilder_CreateSphere("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;let s=new standardMaterial_StandardMaterial("emitterSphereMaterial",i);for(let t of(s.emissiveColor=e.color,r.material=s,this.systems))t.emitter=r;this._emitterNode=r}start(e){for(let t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(let e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){let t={};for(let i of(t.systems=[],this.systems))t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){let s=new ParticleSystemSet,n=this.BaseAssetsUrl+"/textures/";for(let a of(t=t||rS.l.LastCreatedScene,e.systems))s.systems.push(i?GPUParticleSystem.Parse(a,t,n,!0,r):particleSystem_ParticleSystem.Parse(a,t,n,!0,r));if(e.emitter){let i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:rg.Wo.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}};ParticleSystemSet.BaseAssetsUrl="https://assets.babylonjs.com/particles";let ParticleHelper=class ParticleHelper{static CreateDefault(e,t=500,i,r=!1){let s;return(s=r?new GPUParticleSystem("default system",{capacity:t},i):new particleSystem_ParticleSystem("default system",t,i)).emitter=e,s.particleTexture=new texture_Texture("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new rg.HE(1,1,1,1),s.color2=new rg.HE(1,1,1,1),s.colorDead=new rg.HE(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,r){t||(t=rS.l.LastCreatedScene);let s={};return t.addPendingData(s),new Promise((n,a)=>{if(i&&!GPUParticleSystem.IsSupported)return t.removePendingData(s),a("Particle system with GPU is not supported.");rW.w1.LoadFile(`${ParticleHelper.BaseAssetsUrl}/systems/${e}.json`,e=>{t.removePendingData(s);let a=JSON.parse(e.toString());return n(ParticleSystemSet.Parse(a,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(s),a(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){let t=new ParticleSystemSet;for(let i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",n){return new Promise((a,o)=>{let l=new rP.g;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let t;let o=JSON.parse(l.responseText);t=r?GPUParticleSystem.Parse(o,i,s,!1,n):particleSystem_ParticleSystem.Parse(o,i,s,!1,n),e&&(t.name=e),a(t)}else o("Unable to load the particle system")}}),l.open("GET",t),l.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){let e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise((n,a)=>{let o=new rP.g;o.addEventListener("readystatechange",()=>{if(4==o.readyState){if(200==o.status){let a;let l=JSON.parse(JSON.parse(o.responseText).jsonPayload),h=JSON.parse(l.particleSystem);(a=i?GPUParticleSystem.Parse(h,t,r,!1,s):particleSystem_ParticleSystem.Parse(h,t,r,!1,s)).snippetId=e,n(a)}else a("Unable to load the snippet "+e)}}),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()})}};ParticleHelper.BaseAssetsUrl=ParticleSystemSet.BaseAssetsUrl,ParticleHelper.SnippetUrl="https://snippet.babylonjs.com",ParticleHelper.CreateFromSnippetAsync=ParticleHelper.ParseFromSnippetAsync,rp.p.AddParser(rQ.l.NAME_PARTICLESYSTEM,(e,t,i,r)=>{let s=rp.p.GetIndividualParser(rQ.l.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,a=e.particleSystems.length;n{if(e.activeParticleCount){let r=GPUParticleSystem.Parse(e,t,i);return r}{let r=particleSystem_ParticleSystem.Parse(e,t,i);return r}}),rq.D.prototype.createEffectForParticles=function(e,t=[],i=[],r="",s,n,a,o){var l;let h=[],u=[],c=[];return o?o.fillUniformsAttributesAndSamplerNames(u,h,c):(h=particleSystem_ParticleSystem._GetAttributeNamesOrOptions(),u=particleSystem_ParticleSystem._GetEffectCreationOptions()),-1===r.indexOf(" BILLBOARD")&&(r+="\n#define BILLBOARD\n"),(null==o?void 0:o.isAnimationSheetEnabled)&&-1===r.indexOf(" ANIMATESHEET")&&(r+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==o?void 0:o.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,u.concat(t),c.concat(i),r,s,n,a)},rV.Kj.prototype.getEmittedParticleSystems=function(){let e=[];for(let t=0;t{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),rG.x.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},rG.x.prototype.applyImpulse=function(e,t){return this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t),this},rG.x.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor&&this.physicsImpostor.createJoint(e.physicsImpostor,PhysicsJoint.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this};let physicsEngine_PhysicsEngine=class physicsEngine_PhysicsEngine{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,r$.S)("")}constructor(e,t=physicsEngine_PhysicsEngine.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new rm.P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){let t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){let r=new PhysicsRaycastResult;return this._physicsPlugin.raycast(e,t,r,i),r}};(e3=i3||(i3={}))[e3.FREE=0]="FREE",e3[e3.LIMITED=1]="LIMITED",e3[e3.LOCKED=2]="LOCKED",(e4=i4||(i4={}))[e4.LINEAR_X=0]="LINEAR_X",e4[e4.LINEAR_Y=1]="LINEAR_Y",e4[e4.LINEAR_Z=2]="LINEAR_Z",e4[e4.ANGULAR_X=3]="ANGULAR_X",e4[e4.ANGULAR_Y=4]="ANGULAR_Y",e4[e4.ANGULAR_Z=5]="ANGULAR_Z",e4[e4.LINEAR_DISTANCE=6]="LINEAR_DISTANCE",(e5=i5||(i5={}))[e5.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e5[e5.DISTANCE=2]="DISTANCE",e5[e5.HINGE=3]="HINGE",e5[e5.SLIDER=4]="SLIDER",e5[e5.LOCK=5]="LOCK",e5[e5.PRISMATIC=6]="PRISMATIC",e5[e5.SIX_DOF=7]="SIX_DOF",(e6=i6||(i6={}))[e6.SPHERE=0]="SPHERE",e6[e6.CAPSULE=1]="CAPSULE",e6[e6.CYLINDER=2]="CYLINDER",e6[e6.BOX=3]="BOX",e6[e6.CONVEX_HULL=4]="CONVEX_HULL",e6[e6.CONTAINER=5]="CONTAINER",e6[e6.MESH=6]="MESH",e6[e6.HEIGHTFIELD=7]="HEIGHTFIELD",(e8=i8||(i8={}))[e8.NONE=0]="NONE",e8[e8.VELOCITY=1]="VELOCITY",e8[e8.POSITION=2]="POSITION",(e7=i7||(i7={})).COLLISION_STARTED="COLLISION_STARTED",e7.COLLISION_CONTINUED="COLLISION_CONTINUED",e7.COLLISION_FINISHED="COLLISION_FINISHED",e7.TRIGGER_ENTERED="TRIGGER_ENTERED",e7.TRIGGER_EXITED="TRIGGER_EXITED",(e9=i9||(i9={}))[e9.STATIC=0]="STATIC",e9[e9.ANIMATED=1]="ANIMATED",e9[e9.DYNAMIC=2]="DYNAMIC",(te=re||(re={}))[te.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",te[te.MINIMUM=1]="MINIMUM",te[te.MAXIMUM=2]="MAXIMUM",te[te.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",te[te.MULTIPLY=4]="MULTIPLY",rN.x.prototype.getPhysicsEngine=function(){return this._physicsEngine},rN.x.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(rQ.l.NAME_PHYSICSENGINE);i||(i=new PhysicsEngineSceneComponent(this),this._addComponent(i));try{if(t&&(null==t?void 0:t.getPluginVersion())!==1){if((null==t?void 0:t.getPluginVersion())===2)this._physicsEngine=new physicsEngine_PhysicsEngine(e,t);else throw Error("Unsupported Physics plugin version.")}else this._physicsEngine=new PhysicsEngine(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return rT.Y.Error(e.message),!1}},rN.x.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},rN.x.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},rN.x.prototype.deleteCompoundImpostor=function(e){let t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},rN.x.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){let t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};let PhysicsEngineSceneComponent=class PhysicsEngineSceneComponent{constructor(e){this.name=rQ.l.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new rf.y$,this.scene.onAfterPhysicsObservable=new rf.y$,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}};Object.defineProperty(rk.Y.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0}),rk.Y.prototype.getPhysicsBody=function(){return this.physicsBody},rk.Y.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};let HelperTools=class HelperTools{static GetContactPointToRef(e,t,i,r,s){let n=e.getScene().getPhysicsEngine(),a=null==n?void 0:n.getPluginVersion();if(1===a){let s=new ray_Ray(t,i),n=s.intersectsMesh(e);if(n.hit&&n.pickedPoint)return r.copyFrom(n.pickedPoint),!0}else if(2===a)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){var i,r,s;return e.getMotionType(t)===i9.STATIC||(null!==(r=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==r?r:0)===0||(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){let s=rm.jp.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}};let PhysicsUpdraftEvent=class PhysicsUpdraftEvent{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=rm.P.Zero(),this._originDirection=rm.P.Zero(),this._cylinderPosition=rm.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new PhysicsUpdraftEventOptions),this._options),this._origin.addToRef(new rm.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new rm.P(0,this._options.height,0),this._originTop),this._options.updraftMode===ri.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout(()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)},0))}_getHitData(e,t){let i;i=this._options.updraftMode===ri.Perpendicular?this._originDirection:e.subtract(this._originTop);let r=rm.P.Distance(this._origin,e),s=-1*this._options.strength,n=i.multiplyByFloats(s,s,s);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(HelperTools.HasAppliedForces(e))return!1;let r=e.getObjectCenterWorld(i);return!!HelperTools.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){let e=PhysicsUpdraftEvent._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=cylinderBuilder_CreateCylinder("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}};PhysicsUpdraftEvent._HitData={force:new rm.P,contactPoint:new rm.P,distanceFromOrigin:0};let PhysicsVortexEvent=class PhysicsVortexEvent{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=rm.P.Zero(),this._cylinderPosition=rm.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new PhysicsVortexEventOptions),this._options),this._origin.addToRef(new rm.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new rm.P(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout(()=>{this._dataFetched||this._cylinder.dispose()},0))}_getHitData(e,t,i){let r,s,n;let a=PhysicsVortexEvent.originOnPlane;a.set(this._origin.x,t.y,this._origin.z);let o=rm.jp.Vector3[0];t.subtractToRef(a,o);let l=rm.jp.Vector3[1],h=HelperTools.GetContactPointToRef(e,a,o,l,i.instanceIndex);if(!h)return!1;let u=rm.P.Distance(l,a),c=u/this._options.radius,d=rm.jp.Vector3[2];if(l.normalizeToRef(d),c>this._options.centripetalForceThreshold&&d.negateInPlace(),c>this._options.centripetalForceThreshold)r=d.x*this._options.centripetalForceMultiplier,s=d.y*this._options.updraftForceMultiplier,n=d.z*this._options.centripetalForceMultiplier;else{let e=rm.P.Cross(a,t).normalize();r=(e.x+d.x)*this._options.centrifugalForceMultiplier,s=this._originTop.y*this._options.updraftForceMultiplier,n=(e.z+d.z)*this._options.centrifugalForceMultiplier}let p=rm.jp.Vector3[3];return p.set(r,s,n),p.scaleInPlace(this._options.strength),i.force.copyFrom(p),i.contactPoint.copyFrom(t),i.distanceFromOrigin=c,!0}_getBodyHitData(e,t,i){if(HelperTools.HasAppliedForces(e,i))return!1;let r=e.transformNode,s=e.getObjectCenterWorld(i);return!!HelperTools.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass||"Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){let e=PhysicsVortexEvent.hitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=cylinderBuilder_CreateCylinder("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}};PhysicsVortexEvent.originOnPlane=rm.P.Zero(),PhysicsVortexEvent.hitData={force:new rm.P,contactPoint:new rm.P,distanceFromOrigin:0};let PhysicsUpdraftEventOptions=class PhysicsUpdraftEventOptions{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=ri.Center}};let PhysicsVortexEventOptions=class PhysicsVortexEventOptions{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}};(tt=rt||(rt={}))[tt.Constant=0]="Constant",tt[tt.Linear=1]="Linear",(ti=ri||(ri={}))[ti.Center=0]="Center",ti[ti.Perpendicular=1]="Perpendicular";let l2=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); -vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;s_.v.ShadersStore.blackAndWhitePixelShader=l2;let BlackAndWhitePostProcess=class BlackAndWhitePostProcess extends postProcess_PostProcess{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,s,n){super(e,"blackAndWhite",["degree"],null,t,i,r,s,n),this.degree=1,this.onApplyObservable.add(e=>{e.setFloat("degree",this.degree)})}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new BlackAndWhitePostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],BlackAndWhitePostProcess.prototype,"degree",void 0),(0,rv.H)("BABYLON.BlackAndWhitePostProcess",BlackAndWhitePostProcess);let postProcessRenderEffect_PostProcessRenderEffect=class postProcessRenderEffect_PostProcessRenderEffect{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(let e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){let t=this._postProcesses[e];for(let e=0;e{let t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)}),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){let t=rW.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){let t=rW.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}};let l3=`#include -varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;s_.v.ShadersStore.extractHighlightsPixelShader=l3;let ExtractHighlightsPostProcess=class ExtractHighlightsPostProcess extends postProcess_PostProcess{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,s,n,null,a,void 0,null,o),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,rw.zp)),e.setFloat("exposure",this._exposure)})}};(0,rH.gn)([(0,rb.qC)()],ExtractHighlightsPostProcess.prototype,"threshold",void 0),(0,rv.H)("BABYLON.ExtractHighlightsPostProcess",ExtractHighlightsPostProcess);let l4=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } -`;s_.v.ShadersStore.bloomMergePixelShader=l4;let BloomMergePostProcess=class BloomMergePostProcess extends postProcess_PostProcess{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,n,a,o,l,null,h,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}};(0,rH.gn)([(0,rb.qC)()],BloomMergePostProcess.prototype,"weight",void 0),(0,rv.H)("BABYLON.BloomMergePostProcess",BloomMergePostProcess);let BloomEffect=class BloomEffect extends postProcessRenderEffect_PostProcessRenderEffect{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,r,s=0,n=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new ExtractHighlightsPostProcess("highlights",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._blurX=new BlurPostProcess("horizontal blur",new rm.FM(1,0),10,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new BlurPostProcess("vertical blur",new rm.FM(0,1),10,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new BloomMergePostProcess("bloomMerge",this._downscale,this._blurY,i,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)})}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new ChromaticAberrationPostProcess(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"aberrationAmount",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"radialIntensity",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"direction",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"centerPosition",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"screenWidth",void 0),(0,rH.gn)([(0,rb.qC)()],ChromaticAberrationPostProcess.prototype,"screenHeight",void 0),(0,rv.H)("BABYLON.ChromaticAberrationPostProcess",ChromaticAberrationPostProcess);let l6=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float depth=texture2D(depthSampler,vUV).r; -#define CUSTOM_COC_DEPTH -float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; -#define CUSTOM_COC_PIXELDISTANCE -float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} -`;s_.v.ShadersStore.circleOfConfusionPixelShader=l6;let CircleOfConfusionPostProcess=class CircleOfConfusionPostProcess extends postProcess_PostProcess{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,s,n,a,null,o,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(e=>{if(!this._depthTexture){rT.Y.Warn("No depth texture set on CircleOfConfusionPostProcess");return}e.setTexture("depthSampler",this._depthTexture);let t=this.lensSize/this.fStop,i=t*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",i);let r=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",r.minZ,r.maxZ-r.minZ)})}set depthTexture(e){this._depthTexture=e}};(0,rH.gn)([(0,rb.qC)()],CircleOfConfusionPostProcess.prototype,"lensSize",void 0),(0,rH.gn)([(0,rb.qC)()],CircleOfConfusionPostProcess.prototype,"fStop",void 0),(0,rH.gn)([(0,rb.qC)()],CircleOfConfusionPostProcess.prototype,"focusDistance",void 0),(0,rH.gn)([(0,rb.qC)()],CircleOfConfusionPostProcess.prototype,"focalLength",void 0),(0,rv.H)("BABYLON.CircleOfConfusionPostProcess",CircleOfConfusionPostProcess);let l8=`uniform sampler2D textureSampler; -uniform sampler2D colorTable; -varying vec2 vUV;const float SLICE_COUNT=16.0; -vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; -float slicePixelSize=sliceSize/width; -float sliceInnerSize=slicePixelSize*(width-1.0); -float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;s_.v.ShadersStore.colorCorrectionPixelShader=l8;let ColorCorrectionPostProcess=class ColorCorrectionPostProcess extends postProcess_PostProcess{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"colorCorrection",null,["colorTable"],i,r,s,n,a);let o=(null==r?void 0:r.getScene())||null;this._colorTableTexture=new texture_Texture(t,o,!0,!1,texture_Texture.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new ColorCorrectionPostProcess(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],ColorCorrectionPostProcess.prototype,"colorTableUrl",void 0),(0,rv.H)("BABYLON.ColorCorrectionPostProcess",ColorCorrectionPostProcess);let l7=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = -texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + -texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + -texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + -texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + -texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + -texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + -texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + -texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + -texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = -kernel[0] + -kernel[1] + -kernel[2] + -kernel[3] + -kernel[4] + -kernel[5] + -kernel[6] + -kernel[7] + -kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} -gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;s_.v.ShadersStore.convolutionPixelShader=l7;let ConvolutionPostProcess=class ConvolutionPostProcess extends postProcess_PostProcess{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,n,a,o=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,n,a,null,o),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new ConvolutionPostProcess(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}};ConvolutionPostProcess.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],ConvolutionPostProcess.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],ConvolutionPostProcess.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],ConvolutionPostProcess.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],ConvolutionPostProcess.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],ConvolutionPostProcess.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,rH.gn)([(0,rb.qC)()],ConvolutionPostProcess.prototype,"kernel",void 0),(0,rv.H)("BABYLON.ConvolutionPostProcess",ConvolutionPostProcess);let DepthOfFieldBlurPostProcess=class DepthOfFieldBlurPostProcess extends BlurPostProcess{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=null,l=texture_Texture.BILINEAR_SAMPLINGMODE,h,u,c=0,d=!1,p=5){super(e,i,r,s,n,2,h,u,c,`#define DOF 1 -`,d,p),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add(e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)})}};(0,rH.gn)([(0,rb.qC)()],DepthOfFieldBlurPostProcess.prototype,"direction",void 0),(0,rv.H)("BABYLON.DepthOfFieldBlurPostProcess",DepthOfFieldBlurPostProcess);let l9=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; -#if BLUR_LEVEL>0 -uniform sampler2D blurStep1; -#endif -#if BLUR_LEVEL>1 -uniform sampler2D blurStep2; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; -#if BLUR_LEVEL==0 -vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); -#endif -#if BLUR_LEVEL==1 -if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} -#endif -#if BLUR_LEVEL==2 -if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} -#endif -} -`;s_.v.ShadersStore.depthOfFieldMergePixelShader=l9;let DepthOfFieldMergePostProcess=class DepthOfFieldMergePostProcess extends postProcess_PostProcess{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,n,a,o,l,null,h,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,n){e||(e="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,n)}};(tr=rr||(rr={}))[tr.Low=0]="Low",tr[tr.Medium=1]="Medium",tr[tr.High=2]="High";let DepthOfFieldEffect=class DepthOfFieldEffect extends postProcessRenderEffect_PostProcessRenderEffect{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=rr.Low,r=0,s=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];let n=e.getEngine(),a=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new CircleOfConfusionPostProcess("circleOfConfusion",t,1,null,texture_Texture.BILINEAR_SAMPLINGMODE,n,!1,r,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,l=15;switch(i){case rr.High:o=3,l=51;break;case rr.Medium:o=2,l=31;break;default:l=15,o=1}let h=l/Math.pow(2,o-1),u=1;for(let t=0;tnew DisplayPassPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rv.H)("BABYLON.DisplayPassPostProcess",DisplayPassPostProcess);let ht=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;s_.v.ShadersStore.filterPixelShader=ht;let FilterPostProcess=class FilterPostProcess extends postProcess_PostProcess{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"filter",["kernelMatrix"],null,i,r,s,n,a),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new FilterPostProcess(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.oQ)()],FilterPostProcess.prototype,"kernelMatrix",void 0),(0,rv.H)("BABYLON.FilterPostProcess",FilterPostProcess);let hi=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); -#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) -void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); -#ifndef MALI -if(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) -{lumaN=lumaW;} -if (!horzSpan) -{lumaS=lumaE;} -if (horzSpan) -{lengthSign=texelSize.y;} -float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) -{lengthSign=-lengthSign;} -float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) -{posB.x+=lengthSign*0.5;} -if (horzSpan) -{posB.y+=lengthSign*0.5;} -vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) -{lumaNN=lumaSS;} -float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) -{posN.x-=offNP.x*3.0;} -if (!doneN) -{posN.y-=offNP.y*3.0;} -bool doneNP=(!doneN) || (!doneP);if (!doneP) -{posP.x+=offNP.x*3.0;} -if (!doneP) -{posP.y+=offNP.y*3.0;} -if (doneNP) -{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} -float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) -{dstN=posM.y-posN.y;} -if (!horzSpan) -{dstP=posP.y-posM.y;} -bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{let t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)})}_getDefines(){let e=this.getEngine();if(!e)return null;let t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new FxaaPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rv.H)("BABYLON.FxaaPostProcess",FxaaPostProcess);let hs=`#include -uniform sampler2D textureSampler; -uniform float intensity;uniform float animatedSeed;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;s_.v.ShadersStore.grainPixelShader=hs;let GrainPostProcess=class GrainPostProcess extends postProcess_PostProcess{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,n,null,a,void 0,null,o),this.intensity=30,this.animated=!1,this.onApplyObservable.add(e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new GrainPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],GrainPostProcess.prototype,"intensity",void 0),(0,rH.gn)([(0,rb.qC)()],GrainPostProcess.prototype,"animated",void 0),(0,rv.H)("BABYLON.GrainPostProcess",GrainPostProcess);let hn=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;s_.v.ShadersStore.highlightsPixelShader=hn;let ha=`varying vec2 vUV;uniform sampler2D textureSampler; -#include -#include -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 result=texture2D(textureSampler,vUV); -#ifdef IMAGEPROCESSING -#ifndef FROMLINEARSPACE -result.rgb=toLinearSpace(result.rgb); -#endif -result=applyImageProcessing(result); -#else -#ifdef FROMLINEARSPACE -result=applyImageProcessing(result); -#endif -#endif -gl_FragColor=result;}`;s_.v.ShadersStore.imageProcessingPixelShader=ha;let ImageProcessingPostProcess=class ImageProcessingPostProcess extends postProcess_PostProcess{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null,t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){let i=t.scenes;e=i[i.length-1]}else e=rS.l.LastCreatedScene;e?this._imageProcessingConfiguration=e.imageProcessingConfiguration:this._imageProcessingConfiguration=new sv.$}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){let e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,n,a=0,o){super(e,"imageProcessing",[],[],t,i,r,s,n,null,a,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(let t in this._defines)this._defines[t]&&(e+=`#define ${t}; -`);let t=["textureSampler"],i=["scale"];sv.$&&(sv.$.PrepareSamplers(t,this._defines),sv.$.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}};(0,rH.gn)([(0,rb.qC)()],ImageProcessingPostProcess.prototype,"_fromLinearSpace",void 0);let ho=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -layout(location=0) out vec4 glFragData[{X}]; -#endif -`;s_.v.IncludesShadersStore.mrtFragmentDeclaration=ho;let hl=`#extension GL_EXT_draw_buffers : require -#if defined(BUMP) || !defined(NORMAL) -#extension GL_OES_standard_derivatives : enable -#endif -precision highp float; -#ifdef BUMP -varying mat4 vWorldView;varying vec3 vNormalW; -#else -varying vec3 vNormalV; -#endif -varying vec4 vViewPos; -#if defined(POSITION) || defined(BUMP) -varying vec3 vPositionW; -#endif -#ifdef VELOCITY -varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#ifdef NEED_UV -varying vec2 vUV; -#endif -#ifdef BUMP -uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; -#endif -#if defined(REFLECTIVITY) -#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) -uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; -#endif -#ifdef ALBEDOTEXTURE -varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; -#endif -#ifdef REFLECTIVITYCOLOR -uniform vec3 reflectivityColor; -#endif -#ifdef ALBEDOCOLOR -uniform vec3 albedoColor; -#endif -#ifdef METALLIC -uniform float metallic; -#endif -#if defined(ROUGHNESS) || defined(GLOSSINESS) -uniform float glossiness; -#endif -#endif -#if defined(ALPHATEST) && defined(NEED_UV) -uniform sampler2D diffuseSampler; -#endif -#include -#include[RENDER_TARGET_COUNT] -#include -#include -#include -void main() { -#include -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -vec3 normalOutput; -#ifdef BUMP -vec3 normalW=normalize(vNormalW); -#include -#ifdef NORMAL_WORLDSPACE -normalOutput=normalW; -#else -normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); -#endif -#else -normalOutput=normalize(vNormalV); -#endif -#ifdef PREPASS -#ifdef PREPASS_DEPTH -gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); -#endif -#ifdef PREPASS_NORMAL -gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); -#endif -#else -gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); -#endif -#ifdef POSITION -gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); -#endif -#ifdef VELOCITY -vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); -#endif -#ifdef REFLECTIVITY -vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); -#ifdef METALLICWORKFLOW -float metal=1.0;float roughness=1.0; -#ifdef ORMTEXTURE -metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; -#endif -#ifdef METALLIC -metal*=metallic; -#endif -#ifdef ROUGHNESS -roughness*=(1.0-glossiness); -#endif -reflectivity.a-=roughness;vec3 color=vec3(1.0); -#ifdef ALBEDOTEXTURE -color=texture2D(albedoSampler,vAlbedoUV).rgb; -#ifdef GAMMAALBEDO -color=toLinearSpace(color); -#endif -#endif -#ifdef ALBEDOCOLOR -color*=albedoColor.xyz; -#endif -reflectivity.rgb=mix(vec3(0.04),color,metal); -#else -#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) -reflectivity=texture2D(reflectivitySampler,vReflectivityUV); -#ifdef GAMMAREFLECTIVITYTEXTURE -reflectivity.rgb=toLinearSpace(reflectivity.rgb); -#endif -#else -#ifdef REFLECTIVITYCOLOR -reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; -#endif -#endif -#ifdef GLOSSINESSS -reflectivity.a*=glossiness; -#endif -#endif -gl_FragData[REFLECTIVITY_INDEX]=reflectivity; -#endif -} -`;s_.v.ShadersStore.geometryPixelShader=hl,s_.v.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";let hh=`#include -`;s_.v.IncludesShadersStore.geometryUboDeclaration=hh;let hu=`precision highp float; -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include<__decl__geometryVertex> -#include -attribute vec3 position;attribute vec3 normal; -#ifdef NEED_UV -varying vec2 vUV; -#ifdef ALPHATEST -uniform mat4 diffuseMatrix; -#endif -#ifdef BUMP -uniform mat4 bumpMatrix;varying vec2 vBumpUV; -#endif -#ifdef REFLECTIVITY -uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; -#endif -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#ifdef BUMP -varying mat4 vWorldView; -#endif -#ifdef BUMP -varying vec3 vNormalW; -#else -varying vec3 vNormalV; -#endif -varying vec4 vViewPos; -#if defined(POSITION) || defined(BUMP) -varying vec3 vPositionW; -#endif -#ifdef VELOCITY -uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position;vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#include -#include -vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); -#ifdef BUMP -vWorldView=view*finalWorld;vNormalW=normalUpdated; -#else -#ifdef NORMAL_WORLDSPACE -vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); -#else -vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); -#endif -#endif -vViewPos=view*worldPos; -#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) -vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if NUM_BONE_INFLUENCERS>0 -mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; -#if NUM_BONE_INFLUENCERS>1 -previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; -#endif -#if NUM_BONE_INFLUENCERS>2 -previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; -#endif -#if NUM_BONE_INFLUENCERS>3 -previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; -#endif -#if NUM_BONE_INFLUENCERS>4 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; -#endif -#if NUM_BONE_INFLUENCERS>5 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; -#endif -#if NUM_BONE_INFLUENCERS>6 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; -#endif -#if NUM_BONE_INFLUENCERS>7 -previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; -#endif -vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); -#else -vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); -#endif -#endif -#if defined(POSITION) || defined(BUMP) -vPositionW=worldPos.xyz/worldPos.w; -#endif -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#include -#ifdef NEED_UV -#ifdef UV1 -#if defined(ALPHATEST) && defined(ALPHATEST_UV1) -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#else -vUV=uv; -#endif -#ifdef BUMP_UV1 -vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef REFLECTIVITY_UV1 -vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef ALBEDO_UV1 -vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#endif -#ifdef UV2 -#if defined(ALPHATEST) && defined(ALPHATEST_UV2) -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#else -vUV=uv2; -#endif -#ifdef BUMP_UV2 -vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef REFLECTIVITY_UV2 -vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); -#endif -#ifdef ALBEDO_UV2 -vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#endif -#include -} -`;s_.v.ShadersStore.geometryVertexShader=hu;let hc=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,nX.qx)(hc);let GeometryBufferRenderer=class GeometryBufferRenderer{_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===GeometryBufferRenderer.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===GeometryBufferRenderer.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===GeometryBufferRenderer.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case GeometryBufferRenderer.POSITION_TEXTURE_TYPE:return this._positionIndex;case GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case GeometryBufferRenderer.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case GeometryBufferRenderer.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return -1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return this._ratio}constructor(e,t=1,i=15){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new rg.HE(0,0,0,0),this._clearDepthColor=new rg.HE(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratio=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,GeometryBufferRenderer._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[rz.o.PositionKind,rz.o.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&MaterialFlags.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&r.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),n.isVerticesDataPresent(rz.o.UVKind)&&(s.push(rz.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(rz.o.UV2Kind)&&(s.push(rz.o.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),-1!==this._depthIndex&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),n.useBones&&n.computeBonesUsingShaders?(s.push(rz.o.MatricesIndicesKind),s.push(rz.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(rz.o.MatricesIndicesExtraKind),s.push(rz.o.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");let a=n.morphTargetManager,o=0;a&&a.numInfluencers>0&&(o=a.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+o),a.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(s,n,o)),t&&(r.push("#define INSTANCES"),so.G.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),(0,nX.lK)(i,this._scene,r);let l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),u=h.defines,c=r.join("\n");return u!==c&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:hc,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets"],defines:c,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:o}},l),c),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){if(this._resizeObserver){let e=this._scene.getEngine();e.onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null}this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],t=2;return e.push("gBuffer_Depth","gBuffer_Normal"),this._enablePosition&&(this._positionIndex=t,t++,e.push("gBuffer_Position")),this._enableVelocity&&(this._velocityIndex=t,t++,e.push("gBuffer_Velocity")),this._enableReflectivity&&(this._reflectivityIndex=t,t++,e.push("gBuffer_Reflectivity")),[t,e]}_createRenderTargets(){let e=this._scene.getEngine(),[t,i]=this._assignRenderTargetIndices(),r=0;if(e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?r=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(r=2),this._multiRenderTarget=new MultiRenderTarget("gBuffer",{width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio},t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,defaultType:r,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let s=[!0],n=[!1],a=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?l:o),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(h),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(o)}),this._resizeObserver=e.onResizeObservable.add(()=>{this._multiRenderTarget&&this._multiRenderTarget.resize({width:e.getRenderWidth()*this._ratio,height:e.getRenderHeight()*this._ratio})});let renderSubMesh=e=>{let t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:rm.y3.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){let e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}let a=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;let o=s.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,o)){let h;let u=e._getDrawWrapper();if(!u)return;let c=u.effect;s.enableEffect(u),o||t._bind(e,c,n.fillMode),this._useUbo?(so.G.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("view",r.getViewMatrix()));let d=t._instanceDataStorage;if(!d.isFrozen&&(n.backFaceCulling||null!==t.overrideMaterialSideOrientation)){let e=i._getWorldMatrixDeterminant();null===(h=t.overrideMaterialSideOrientation)&&(h=n.sideOrientation),e<0&&(h=h===sr.F.ClockWiseSideOrientation?sr.F.CounterClockWiseSideOrientation:sr.F.ClockWiseSideOrientation)}else h=d.sideOrientation;if(n._preBind(u,h),n.needAlphaTesting()){let e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}n.bumpTexture&&r.getEngine().getCaps().standardDerivatives&&MaterialFlags.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),(0,nX.an)(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton&&(c.setMatrices("mBones",t.skeleton.getTransformMatrices(t)),this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])),so.G.BindMorphTargetParameters(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),o&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,a,o,(e,t)=>{e||c.setMatrix("world",t)})}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),n=0;n{throw(0,r$.S)("GeometryBufferRendererSceneComponent")};let MotionBlurConfiguration=class MotionBlurConfiguration{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}};Object.defineProperty(rN.x.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),rN.x.prototype.enableGeometryBufferRenderer=function(e=1,t=15){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new GeometryBufferRenderer(this,e,t),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},rN.x.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};let GeometryBufferRendererSceneComponent=class GeometryBufferRendererSceneComponent{constructor(e){this.name=rQ.l.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(rQ.l.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}};GeometryBufferRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_GEOMETRYBUFFERRENDERER);t||(t=new GeometryBufferRendererSceneComponent(e),e._addComponent(t))};let hd=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; -#ifdef OBJECT_BASED -uniform sampler2D velocitySampler; -#else -uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#ifdef GEOMETRY_SUPPORTED -#ifdef OBJECT_BASED -vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount) -break;vec2 offset=vUV+velocity*(hlim+float(i)); -#if defined(WEBGPU) -result+=texture2DLodEXT(textureSampler,offset,0.0); -#else -result+=texture2D(textureSampler,offset); -#endif -} -gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; -#else -vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; -vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples) -break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); -#if defined(WEBGPU) -result+=texture2DLodEXT(textureSampler,offset1,0.0); -#else -result+=texture2D(textureSampler,offset1); -#endif -} -gl_FragColor=result/float(nSamples); -#endif -#else -gl_FragColor=texture2D(textureSampler,vUV); -#endif -} -`;s_.v.ShadersStore.motionBlurPixelShader=hd;let MotionBlurPostProcess=class MotionBlurPostProcess extends postProcess_PostProcess{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,n,a,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",o,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new MotionBlurConfiguration)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}let i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return rT.Y.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=rm.y3.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new rm.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){let t=rm.jp.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new rm.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){let e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new MotionBlurPostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],MotionBlurPostProcess.prototype,"motionStrength",void 0),(0,rH.gn)([(0,rb.qC)()],MotionBlurPostProcess.prototype,"motionBlurSamples",null),(0,rH.gn)([(0,rb.qC)()],MotionBlurPostProcess.prototype,"isObjectBased",null),(0,rv.H)("BABYLON.MotionBlurPostProcess",MotionBlurPostProcess),s_.v.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";let RefractionPostProcess=class RefractionPostProcess extends postProcess_PostProcess{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,n,a,o,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,a,o,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(e=>{this._refTexture=this._refTexture||new texture_Texture(t,e.getScene())}),this.onApplyObservable.add(e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new RefractionPostProcess(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],RefractionPostProcess.prototype,"color",void 0),(0,rH.gn)([(0,rb.qC)()],RefractionPostProcess.prototype,"depth",void 0),(0,rH.gn)([(0,rb.qC)()],RefractionPostProcess.prototype,"colorLevel",void 0),(0,rH.gn)([(0,rb.qC)()],RefractionPostProcess.prototype,"refractionTextureUrl",void 0),(0,rv.H)("BABYLON.RefractionPostProcess",RefractionPostProcess);let hp=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + -texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + -texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + -texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - -color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;s_.v.ShadersStore.sharpenPixelShader=hp;let SharpenPostProcess=class SharpenPostProcess extends postProcess_PostProcess{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,n,null,a,void 0,null,o),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new SharpenPostProcess(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],SharpenPostProcess.prototype,"colorAmount",void 0),(0,rH.gn)([(0,rb.qC)()],SharpenPostProcess.prototype,"edgeAmount",void 0),(0,rv.H)("BABYLON.SharpenPostProcess",SharpenPostProcess);let postProcessRenderPipeline_PostProcessRenderPipeline=class postProcessRenderPipeline_PostProcessRenderPipeline{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=[],this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(let e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){let i=this._renderEffects[e];i&&i._enable(rW.w1.MakeArray(t||this._cameras))}_disableEffect(e,t){let i=this._renderEffects[e];i&&i._disable(rW.w1.MakeArray(t||this._cameras))}_attachCameras(e,t){let i;let r=rW.w1.MakeArray(e||this._cameras);if(!r)return;let s=[];for(i=0;i0){let i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){let e=Object.keys(this._renderEffects);for(let t of e){let e=this._renderEffects[t].getPostProcesses();if(e)for(let t of e)t.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}};(0,rH.gn)([(0,rb.qC)()],postProcessRenderPipeline_PostProcessRenderPipeline.prototype,"_name",void 0);let PostProcessRenderPipelineManager=class PostProcessRenderPipelineManager{constructor(){this._renderPipelines={}}get supportedPipelines(){let e=[];for(let t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){let i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){let r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){let i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t._rebuild()}}dispose(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.dispose()}}};Object.defineProperty(rN.x.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(rQ.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new PostProcessRenderPipelineManagerSceneComponent(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new PostProcessRenderPipelineManager}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});let PostProcessRenderPipelineManagerSceneComponent=class PostProcessRenderPipelineManagerSceneComponent{constructor(e){this.name=rQ.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(rQ.l.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}};let DefaultRenderingPipeline=class DefaultRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){let e=this.bloom;this.bloom=new BloomEffect(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen,!0),this.depthOfField=new DepthOfFieldEffect(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add(()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new BloomEffect(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new ChromaticAberrationPostProcess("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new postProcessRenderEffect_PostProcessRenderEffect(a,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new GrainPostProcess("Grain",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new postProcessRenderEffect_PostProcessRenderEffect(a,this.GrainPostProcessId,()=>this.grain,!0);let o=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add(()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,o?rW.w1.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),o=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){let e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;let e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(let e of this._cameras){let t=this._scene.enableDepthRenderer(e);t.useOnlyInActiveCamera=!0}this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);let e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new ImageProcessingPostProcess("imageProcessing",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e,this.ImageProcessingPostProcessId,()=>this.imageProcessing,!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new FxaaPostProcess("fxaa",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&rT.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew DefaultRenderingPipeline(e._name,e._name._hdr,t),e,t,i)}};(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"sharpenEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomKernel",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"_bloomWeight",void 0),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"_bloomThreshold",void 0),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"_hdr",void 0),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomWeight",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomThreshold",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomScale",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"bloomEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"depthOfFieldEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"depthOfFieldBlurLevel",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"fxaaEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"samples",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"imageProcessingEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"glowLayerEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"chromaticAberrationEnabled",null),(0,rH.gn)([(0,rb.qC)()],DefaultRenderingPipeline.prototype,"grainEnabled",null),(0,rv.H)("BABYLON.DefaultRenderingPipeline",DefaultRenderingPipeline);let h_=`uniform sampler2D textureSampler; -uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } -else { lum_threshold=0.5+0.44*threshold; } -luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} -float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); -#ifdef PENTAGON -blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); -#else -blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); -#endif -blurred/=39.0;gl_FragColor=blurred;}`;s_.v.ShadersStore.lensHighlightsPixelShader=h_;let hf=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; -uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; -#define PI 3.14159265 -#define TWOPI 6.28318530 -#define inverse_focal_length 0.1 -vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) -{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} -vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } -vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} -float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} -float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} -vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} -if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} -col/=total_weight; -if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} -return col;} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); -vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); -float depth=texture2D(depthSampler,distorted_coords).r; -float distance=near+(far-near)*depth; -vec4 color=texture2D(textureSampler,vUV); -float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } -float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} -float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} -else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} -if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} -if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} -`;s_.v.ShadersStore.depthOfFieldPixelShader=hf;let SSAO2Configuration=class SSAO2Configuration{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}};let hm=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSAO -float scales[16]=float[16]( -0.1, -0.11406250000000001, -0.131640625, -0.15625, -0.187890625, -0.2265625, -0.272265625, -0.325, -0.384765625, -0.4515625, -0.525390625, -0.60625, -0.694140625, -0.7890625, -0.891015625, -1.0 -);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() -{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;} -float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} -occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} -#endif -#ifdef BLUR -uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; -#ifndef BLUR_BYPASS -uniform sampler2D depthSampler; -#ifdef BLUR_LEGACY -#define inline -float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} -#endif -#endif -void main() -{float result=0.0; -#ifdef BLUR_BYPASS -result=textureLod(textureSampler,vUV,0.0).r; -#else -#ifdef BLUR_H -vec2 step=vec2(1.0/outSize,0.0); -#else -vec2 step=vec2(0.0,1.0/outSize); -#endif -#ifdef BLUR_LEGACY -result=blur13Bilateral(textureSampler,vUV,step); -#else -float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;let t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},a.samples=this.textureSamples,a}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,23283064365386963e-26*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){let i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new rm.P(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){let e;let t=this.samples,i=[],r=0;for(;r{var t,i,r,s;if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===rj.V.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{let n=this._scene.getEngine().getRenderWidth()/2,a=this._scene.getEngine().getRenderHeight()/2,o=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-n,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:n,h=null!==(r=this._scene.activeCamera.orthoBottom)&&void 0!==r?r:-a,u=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:a;e.setMatrix3x3("depthProjection",SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",(l-o)*.5),e.setFloat("yViewport",(u-h)*.5)}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new SSAO2Configuration)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new postProcess_PostProcess("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{let t=this._scene.activeCamera.viewport;e.setVector4("viewport",rm.jp.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){let e=new Uint8Array(65536),t=rm.FM.Zero();for(let i=0;inew SSAO2RenderingPipeline(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}};SSAO2RenderingPipeline.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],SSAO2RenderingPipeline.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"totalStrength",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"maxZ",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"minZAspect",void 0),(0,rH.gn)([(0,rb.qC)("epsilon")],SSAO2RenderingPipeline.prototype,"_epsilon",void 0),(0,rH.gn)([(0,rb.qC)("samples")],SSAO2RenderingPipeline.prototype,"_samples",void 0),(0,rH.gn)([(0,rb.qC)("textureSamples")],SSAO2RenderingPipeline.prototype,"_textureSamples",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"_forceGeometryBuffer",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"_ratio",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"_textureType",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"radius",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"base",void 0),(0,rH.gn)([(0,rb.qC)("bypassBlur")],SSAO2RenderingPipeline.prototype,"_bypassBlur",void 0),(0,rH.gn)([(0,rb.qC)("expensiveBlur")],SSAO2RenderingPipeline.prototype,"_expensiveBlur",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"bilateralSamples",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"bilateralSoften",void 0),(0,rH.gn)([(0,rb.qC)()],SSAO2RenderingPipeline.prototype,"bilateralTolerance",void 0),(0,rv.H)("BABYLON.SSAO2RenderingPipeline",SSAO2RenderingPipeline);let hv=`uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSAO -uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) -{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} -void main() -{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){for(let i of(super._attachCameras(e,t),this._cameras))this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{let e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e}),this._blurVPostProcess.onActivateObservable.add(()=>{let e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){let t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new postProcess_PostProcess("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new postProcess_PostProcess("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",rm.jp.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){let e=new Uint8Array(1048576);for(let t=0;t0.0) -hitCoord-=dir;else -hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} -projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} -/** -* Tests the given world position (hitCoord) according to the given reflection vector (dir) -* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). -*/ -ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) -{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){let t=i.getTextureIndex(GeometryBufferRenderer.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){let t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}let s=t.activeCamera;if(!s)return;let n=s.getViewMatrix(!0),a=s.getProjectionMatrix(!0);e.setMatrix("projection",a),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){let e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new ScreenSpaceReflectionPostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"threshold",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"strength",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"reflectionSpecularFalloffExponent",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"step",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"roughnessFactor",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"enableSmoothReflections",null),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"reflectionSamples",null),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceReflectionPostProcess.prototype,"smoothSteps",null),(0,rv.H)("BABYLON.ScreenSpaceReflectionPostProcess",ScreenSpaceReflectionPostProcess);let hT=`uniform sampler2D textureSampler;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -#if defined(PASS_POST_PROCESS) -void main(void) -{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} -#endif -#if defined(DOWN_SAMPLE_X4) -uniform vec2 dsOffsets[16];void main(void) -{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} -#endif -#if defined(BRIGHT_PASS) -uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) -{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth) -accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} -accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} -#endif -#if defined(VLSMERGE) -uniform sampler2D originalSampler;void main(void) -{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} -#endif -#if defined(LUMINANCE) -uniform vec2 lumOffsets[4];void main() -{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) -{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); -#ifdef WEIGHTED_AVERAGE -float GreyValue=dot(color.rgb,weight); -#endif -#ifdef BRIGHTNESS -float GreyValue=max(color.r,max(color.g,color.b)); -#endif -#ifdef HSL_COMPONENT -float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); -#endif -#ifdef MAGNITUDE -float GreyValue=length(color.rgb); -#endif -maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} -average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} -#endif -#if defined(LUMINANCE_DOWN_SAMPLE) -uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; -#ifdef FINAL_DOWN_SAMPLER -#include -#endif -void main() -{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) -{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} -average/=9.0; -#ifdef FINAL_DOWN_SAMPLER -gl_FragColor=pack(average); -#else -gl_FragColor=vec4(average,average,0.0,1.0); -#endif -} -#endif -#if defined(HDR) -uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() -{vec4 color=texture2D(textureAdderSampler,vUV); -#ifndef AUTO_EXPOSURE -vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; -#endif -gl_FragColor=color;} -#endif -#if defined(LENS_FLARE) -#define GHOSTS 3 -uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) -{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} -float noise(in vec2 p) -{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), -hash(i+vec2(1.0,0.0)),u.x), -mix(hash(i+vec2(0.0,1.0)), -hash(i+vec2(1.0,1.0)),u.x),u.y);} -float fbm(vec2 p) -{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} -vec3 pattern(vec2 uv) -{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} -float luminance(vec3 color) -{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} -vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) -{return vec4( -texture2D(tex,texcoord+direction*distortion.r).r, -texture2D(tex,texcoord+direction*distortion.g).g, -texture2D(tex,texcoord+direction*distortion.b).b, -1.0 -);} -void main(void) -{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples) -break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} -gl_FragColor=result/float(nSamples);} -#endif -`;s_.v.ShadersStore.standardPixelShader=hT;let StandardRenderingPipeline=class StandardRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){let t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){let t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e){let e=this._scene.enableGeometryBufferRenderer();if(!e){rT.Y.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){let e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new ScreenSpaceReflectionPostProcess("HDRPass",t,e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new postProcess_PostProcess("HDRPass","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.originalPostProcess}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRPassPostProcess",()=>this.originalPostProcess,!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new postProcess_PostProcess("HDRDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new postProcess_PostProcess("HDRVLSFinal","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new postProcess_PostProcess("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new postProcess_PostProcess("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRPostHDReDepthOfFieldSource",()=>this.hdrFinalPostProcess,!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new FxaaPostProcess("fxaa",1,null,texture_Texture.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&rT.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){let i=Array(32);this.downSampleX4PostProcess=new postProcess_PostProcess("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0,r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=(e+.5)*(1/r),i[t+1]=(n+.5)*(1/s),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){let i=Array(8);this.brightPassPostProcess=new postProcess_PostProcess("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{let t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){let s=e.getEngine(),n=new BlurPostProcess("HDRBlurH_"+i,new rm.FM(1,0),this[r],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new BlurPostProcess("HDRBlurV_"+i,new rm.FM(0,1),this[r],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{let e=n.width/s.getRenderWidth();n.kernel=this[r]*e}),a.onActivateObservable.add(()=>{let e=a.height/s.getRenderHeight();a.kernel=this.horizontalBlur?64*e:this[r]*e}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRBlurV"+i,()=>a,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new postProcess_PostProcess("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){let i=e.enableGeometryBufferRenderer();i.enablePosition=!0;let r=i.getGBuffer();this.volumetricLightPostProcess=new postProcess_PostProcess("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));let s=rm.FM.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){let t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new postProcess_PostProcess("HDRVLSMerge","standard",[],["originalSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,StandardRenderingPipeline.LuminanceSteps);this.luminancePostProcess=new postProcess_PostProcess("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);let r=[];this.luminancePostProcess.onApply=e=>{let t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let r=StandardRenderingPipeline.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");let n=new postProcess_PostProcess("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(n)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((t,i)=>{let r=Array(18);t.onApply=e=>{if(!s)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[n]=e/s.width,r[n+1]=t/s.height,n+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{let t=e.getEngine().readPixels(0,0,1,1),i=new rm.Lt(6030862941101084e-23,1/65025,1/255,1);t.then(e=>{let t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100})}),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLuminanceDownSample"+i,()=>t,!0))})}_createHdrPostProcess(e,t){let i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new postProcess_PostProcess("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{let e=(n-s)/1e3;this._hdrCurrentLuminancer-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=rE.R.Clamp(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),n=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new postProcess_PostProcess("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new postProcess_PostProcess("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));let i=new rm.FM(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};let r=rm.y3.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=rm.y3.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);let t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2),n=rm.P.Dot(t.toVector3(),new rm.P(1,0,0))+rm.P.Dot(i.toVector3(),new rm.P(0,0,1));n*=4;let a=rm.y3.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),o=s.multiply(a).multiply(r);e.setMatrix("lensStarMatrix",o),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new postProcess_PostProcess("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){let i=new MotionBlurPostProcess("HDRMotionBlur",e,t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new postProcess_PostProcess("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,texture_Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=rm.y3.Identity(),s=rm.y3.Identity(),n=rm.y3.Identity(),a=rm.FM.Zero();this.motionBlurPostProcess.onApply=t=>{(n=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=n,a.x=this.motionBlurPostProcess.width,a.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",a),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){if(this._scene.getEngine().getCaps().drawBuffersExtension){let e=this._scene.enableGeometryBufferRenderer();return e.getGBuffer().textures[0]}return this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew StandardRenderingPipeline(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&rb.p4.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}};StandardRenderingPipeline.LuminanceSteps=6,(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"brightThreshold",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"blurWidth",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"horizontalBlur",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"exposure",null),(0,rH.gn)([(0,rb.oU)("lensTexture")],StandardRenderingPipeline.prototype,"lensTexture",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"volumetricLightCoefficient",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"volumetricLightPower",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"volumetricLightBlurScale",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"hdrMinimumLuminance",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"hdrDecreaseRate",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"hdrIncreaseRate",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"hdrAutoExposure",null),(0,rH.gn)([(0,rb.oU)("lensColorTexture")],StandardRenderingPipeline.prototype,"lensColorTexture",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareStrength",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareGhostDispersal",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareHaloWidth",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareDistortionStrength",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"lensFlareBlurWidth",void 0),(0,rH.gn)([(0,rb.oU)("lensStarTexture")],StandardRenderingPipeline.prototype,"lensStarTexture",void 0),(0,rH.gn)([(0,rb.oU)("lensFlareDirtTexture")],StandardRenderingPipeline.prototype,"lensFlareDirtTexture",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"depthOfFieldDistance",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"depthOfFieldBlurWidth",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"motionStrength",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"objectBasedMotionBlur",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"_ratio",void 0),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"BloomEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"DepthOfFieldEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"LensFlareEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"HDREnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"VLSEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"MotionBlurEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"fxaaEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"screenSpaceReflectionsEnabled",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"volumetricLightStepsCount",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"motionBlurSamples",null),(0,rH.gn)([(0,rb.qC)()],StandardRenderingPipeline.prototype,"samples",null),(0,rv.H)("BABYLON.StandardRenderingPipeline",StandardRenderingPipeline);let ScreenSpaceReflections2Configuration=class ScreenSpaceReflections2Configuration{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}};let hS=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } -/** -param csOrigin Camera-space ray origin,which must be -within the view volume and must have z>0.01 and project within the valid screen rectangle -param csDirection Unit length camera-space ray direction -param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates -(**not** [-1,+1] normalized device coordinates). -param csZBuffer The camera-space Z buffer -param csZBufferSize Dimensions of csZBuffer -param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer -param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value -for clipping rays headed towards the camera -param stride Step in horizontal or vertical pixels between samples. This is a float -because integer math is slow on GPUs,but should be set to an integer>=1 -param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units -to conceal banding artifacts,plus the stride ray offset. -param maxSteps Maximum number of iterations. Higher gives better images but may be slow -param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss -param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. -1 is a reasonable value,depending on the scene you may need to set this value to 2 -param hitPixel Pixel coordinates of the first intersection with the scene -param numIterations number of iterations performed -param csHitPoint Camera space location of the ray hit -*/ -#define inline -bool traceScreenSpaceRay1( -vec3 csOrigin, -vec3 csDirection, -mat4 projectToPixelMatrix, -sampler2D csZBuffer, -vec2 csZBufferSize, -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -sampler2D csZBackBuffer, -float csZBackSizeFactor, -#endif -float csZThickness, -float nearPlaneZ, -float stride, -float jitterFraction, -float maxSteps, -float maxRayTraceDistance, -float selfCollisionNumSkip, -out vec2 startPixel, -out vec2 hitPixel, -out vec3 csHitPoint, -out float numIterations -#ifdef SSRAYTRACE_DEBUG -,out vec3 debugColor -#endif -) -{ -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; -#else -float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);} -if ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));} -P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); -#endif -P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { -float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} -sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); -#else -hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); -#endif -#else -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); -#else -hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); -#endif -#endif -} -pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} -#ifdef SSRAYTRACE_ENABLE_REFINEMENT -if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || -(refinementStepCount<=stride*1.4) && -(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} -#endif -return hit;} -/** -texCoord: in the [0,1] range -depth: depth in view space (range [znear,zfar]]) -*/ -vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -ndc.z=-projection[2].z-projection[3].z/depth; -#else -ndc.z=projection[2].z+projection[3].z/depth; -#endif -ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} -`;s_.v.IncludesShadersStore.screenSpaceRayTrace=hS;let hC=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV; -#ifdef SSR_SUPPORTED -uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -uniform sampler2D backDepthSampler;uniform float backSizeFactor; -#endif -#ifdef SSR_USE_ENVIRONMENT_CUBE -uniform samplerCube envCubeSampler; -#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC -uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; -#endif -#endif -uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; -#include -#include -#include -vec3 hash(vec3 a) -{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} -float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; -#ifdef SSR_ATTENUATE_SCREEN_BORDERS -vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); -#endif -#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE -attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); -#endif -#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS -attenuation*=1.0-(numIterations/maxSteps); -#endif -#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION -vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; -#endif -return attenuation;} -#endif -void main() -{ -#ifdef SSR_SUPPORTED -vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); -#ifndef SSR_DISABLE_REFLECTIVITY_TEST -if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { -#ifdef SSR_USE_BLUR -gl_FragColor=vec4(0.); -#else -gl_FragColor=colorFull; -#endif -return;} -#endif -#ifdef SSR_INPUT_IS_GAMMA_SPACE -color=toLinearSpace(color); -#endif -vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; -float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); -#ifdef SSR_USE_ENVIRONMENT_CUBE -vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); -#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC -vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); -#endif -#ifdef SSR_INVERTCUBICMAP -wReflectedVector.y*=-1.0; -#endif -#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE -wReflectedVector.z*=-1.0; -#endif -vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; -#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE -envColor=toLinearSpace(envColor); -#endif -#else -vec3 envColor=color; -#endif -float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; -#ifdef SSRAYTRACE_DEBUG -vec3 debugColor; -#endif -#ifdef SSR_ATTENUATE_FACING_CAMERA -reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); -#endif -if (reflectionAttenuation>0.0) { -#ifdef SSR_USE_BLUR -vec3 jitt=vec3(0.); -#else -float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; -#endif -vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); -rayHasHit=traceScreenSpaceRay1( -csPosition, -normalize(csReflectedVector+jitt), -projectionPixel, -depthSampler, -texSize, -#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER -backDepthSampler, -backSizeFactor, -#endif -thickness, -nearPlaneZ, -stepSize, -jitter, -maxSteps, -maxDistance, -selfCollisionNumSkip, -startPixel, -hitPixel, -hitPoint, -numIterations -#ifdef SSRAYTRACE_DEBUG -,debugColor -#endif -);} -#ifdef SSRAYTRACE_DEBUG -gl_FragColor=vec4(debugColor,1.);return; -#endif -vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; -#ifdef SSR_INPUT_IS_GAMMA_SPACE -reflectedColor=toLinearSpace(reflectedColor); -#endif -reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} -#ifndef SSR_BLEND_WITH_FRESNEL -SSR*=fresnel; -#endif -#ifdef SSR_USE_BLUR -float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; -float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} -gl_FragColor=vec4(SSR,blur_radius/255.0); -#else -#ifdef SSR_BLEND_WITH_FRESNEL -vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#else -vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#endif -vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); -#ifdef SSR_OUTPUT_IS_GAMMA_SPACE -finalColor=toGammaSpace(finalColor); -#endif -gl_FragColor=vec4(finalColor,colorFull.a); -#endif -#else -gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); -#endif -} -`;s_.v.ShadersStore.screenSpaceReflection2PixelShader=hC;let hE=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) -#else -#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) -#endif -uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) -{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} -void main() -{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} -float blurRadius=colorFull.a*255.0; -vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} -`;s_.v.ShadersStore.screenSpaceReflection2BlurPixelShader=hE;let hb=`uniform sampler2D textureSampler; -uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; -#include -#ifdef SSR_BLEND_WITH_FRESNEL -#include -#include -uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; -#endif -void main() -{ -#ifdef SSRAYTRACE_DEBUG -gl_FragColor=texture2D(textureSampler,vUV); -#else -vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); -#ifndef SSR_DISABLE_REFLECTIVITY_TEST -if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} -#endif -#ifdef SSR_INPUT_IS_GAMMA_SPACE -color=toLinearSpace(color); -#endif -#ifdef SSR_BLEND_WITH_FRESNEL -vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#else -vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); -#endif -vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); -#ifdef SSR_OUTPUT_IS_GAMMA_SPACE -finalColor=toGammaSpace(finalColor); -#endif -gl_FragColor=vec4(finalColor,color.a); -#endif -} -`;s_.v.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader=hb;let hy=rm.y3.Compose(new rm.P(.5,.5,.5),rm._f.Identity(),new rm.P(.5,.5,.5)),hP=rm.y3.Compose(new rm.P(.5,.5,1),rm._f.Identity(),new rm.P(.5,.5,0));let SSRRenderingPipeline=class SSRRenderingPipeline extends postProcessRenderPipeline_PostProcessRenderPipeline{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;let t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){let e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!1,s=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0,e.generateNormalsInWorldSpace&&console.error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"))}else{let e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty(),e.generateNormalsInWorldSpace&&console.error("SSRRenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!"))}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var e,t;let i=this._scene.getEngine(),r=this._prePassRenderer,s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(r&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){let e=r.getRenderTarget();e&&e.textures&&(s=e.textures[r.getIndex(4)].getSize())}else(null===(t=this._ssrPostProcess)||void 0===t?void 0:t.inputTexture)&&(s.width=this._ssrPostProcess.inputTexture.width,s.height=this._ssrPostProcess.inputTexture.height);return s}_updateEffectDefines(){var e;let t=[];(this._geometryBufferRenderer||this._prePassRenderer)&&t.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&t.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&t.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(t.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&t.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&t.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&t.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&t.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&t.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&t.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&t.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&t.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&t.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&t.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&t.push("#define SSR_USE_BLUR"),this._debug&&t.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&t.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&t.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&t.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&t.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),null===(e=this._ssrPostProcess)||void 0===e||e.updateEffect(t.join("\n"))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;let t=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){let t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new DepthRenderer(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),t.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new postProcessRenderEffect_PostProcessRenderEffect(t,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;let e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){let t=null!==(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))&&void 0!==e?e:-1;-1!==t&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,r;for(let s=0;s{this._resizeDepthRenderer();let t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){let i=t.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){let t=i.getIndex(5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));let r=this._scene.activeCamera;if(!r)return;let s=r.getViewMatrix(!0),n=r.getProjectionMatrix(!0);n.invertToRef(rm.jp.Matrix[0]),s.invertToRef(rm.jp.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",s),e.setMatrix("invView",rm.jp.Matrix[1]),e.setMatrix("invProjectionMatrix",rm.jp.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);let a=this._getTextureSize();rm.y3.ScalingToRef(a.width,a.height,1,rm.jp.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?hP:hy,rm.jp.Matrix[3]),rm.jp.Matrix[3].multiplyToRef(rm.jp.Matrix[2],rm.jp.Matrix[4]),e.setMatrix("projectionPixel",rm.jp.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new ScreenSpaceReflections2Configuration)}_createBlurAndCombinerPostProcesses(){let e=this._scene.getEngine();this._blurPostProcessX=new postProcess_PostProcess("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(e=>{var t,i;let r=null!==(i=null===(t=this._blurPostProcessX)||void 0===t?void 0:t.inputTexture.width)&&void 0!==i?i:this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/r,0)}),this._blurPostProcessY=new postProcess_PostProcess("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(e=>{var t,i;let r=null!==(i=null===(t=this._blurPostProcessY)||void 0===t?void 0:t.inputTexture.height)&&void 0!==i?i:this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/r)});let t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"],r="";this._debug&&(r+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(r+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(r+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(r+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new postProcess_PostProcess("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(e=>{var t;let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(r||i){if(r&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){let t=r.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[r.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){let t=i.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",i.getGBuffer().textures[t]),this.useFresnel&&(e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("depthSampler",i.getGBuffer().textures[0]))}else if(r){let t=r.getIndex(3);if(e.setTexture("reflectivitySampler",r.getRenderTarget().textures[t]),this.useFresnel){let t=r.getIndex(5),i=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[i]),e.setTexture("depthSampler",r.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();i.invertToRef(rm.jp.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",rm.jp.Matrix[0])}}}})}serialize(){let e=rb.p4.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return rb.p4.Parse(()=>new SSRRenderingPipeline(e._name,t,e._ratio),e,t,i)}};(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"samples",null),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"maxDistance",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"step",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"thickness",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"strength",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"reflectionSpecularFalloffExponent",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"maxSteps",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"roughnessFactor",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"selfCollisionNumSkip",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"_reflectivityThreshold",void 0),(0,rH.gn)([(0,rb.qC)("_ssrDownsample")],SSRRenderingPipeline.prototype,"_ssrDownsample",void 0),(0,rH.gn)([(0,rb.qC)()],SSRRenderingPipeline.prototype,"ssrDownsample",null),(0,rH.gn)([(0,rb.qC)("blurDispersionStrength")],SSRRenderingPipeline.prototype,"_blurDispersionStrength",void 0),(0,rH.gn)([(0,rb.qC)("blurDownsample")],SSRRenderingPipeline.prototype,"_blurDownsample",void 0),(0,rH.gn)([(0,rb.qC)("enableSmoothReflections")],SSRRenderingPipeline.prototype,"_enableSmoothReflections",void 0),(0,rH.gn)([(0,rb.qC)("environmentTexture")],SSRRenderingPipeline.prototype,"_environmentTexture",void 0),(0,rH.gn)([(0,rb.qC)("environmentTextureIsProbe")],SSRRenderingPipeline.prototype,"_environmentTextureIsProbe",void 0),(0,rH.gn)([(0,rb.qC)("attenuateScreenBorders")],SSRRenderingPipeline.prototype,"_attenuateScreenBorders",void 0),(0,rH.gn)([(0,rb.qC)("attenuateIntersectionDistance")],SSRRenderingPipeline.prototype,"_attenuateIntersectionDistance",void 0),(0,rH.gn)([(0,rb.qC)("attenuateIntersectionIterations")],SSRRenderingPipeline.prototype,"_attenuateIntersectionIterations",void 0),(0,rH.gn)([(0,rb.qC)("attenuateFacingCamera")],SSRRenderingPipeline.prototype,"_attenuateFacingCamera",void 0),(0,rH.gn)([(0,rb.qC)("attenuateBackfaceReflection")],SSRRenderingPipeline.prototype,"_attenuateBackfaceReflection",void 0),(0,rH.gn)([(0,rb.qC)("clipToFrustum")],SSRRenderingPipeline.prototype,"_clipToFrustum",void 0),(0,rH.gn)([(0,rb.qC)("useFresnel")],SSRRenderingPipeline.prototype,"_useFresnel",void 0),(0,rH.gn)([(0,rb.qC)("enableAutomaticThicknessComputation")],SSRRenderingPipeline.prototype,"_enableAutomaticThicknessComputation",void 0),(0,rH.gn)([(0,rb.qC)("backfaceDepthTextureDownsample")],SSRRenderingPipeline.prototype,"_backfaceDepthTextureDownsample",void 0),(0,rH.gn)([(0,rb.qC)("backfaceForceDepthWriteTransparentMeshes")],SSRRenderingPipeline.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,rH.gn)([(0,rb.qC)("isEnabled")],SSRRenderingPipeline.prototype,"_isEnabled",void 0),(0,rH.gn)([(0,rb.qC)("inputTextureColorIsInGammaSpace")],SSRRenderingPipeline.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,rH.gn)([(0,rb.qC)("generateOutputInGammaSpace")],SSRRenderingPipeline.prototype,"_generateOutputInGammaSpace",void 0),(0,rH.gn)([(0,rb.qC)("debug")],SSRRenderingPipeline.prototype,"_debug",void 0),(0,rv.H)("BABYLON.SSRRenderingPipeline",SSRRenderingPipeline);let hR=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; -#if defined(HABLE_TONEMAPPING) -const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; -#endif -float Luminance(vec3 c) -{return dot(c,vec3(0.22,0.707,0.071));} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec3 colour=texture2D(textureSampler,vUV).rgb; -#if defined(REINHARD_TONEMAPPING) -float lum=Luminance(colour.rgb); -float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); -colour*=scale/lum; -#elif defined(HABLE_TONEMAPPING) -colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; -#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) -colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; -#elif defined(PHOTOGRAPHIC_TONEMAPPING) -colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); -#endif -gl_FragColor=vec4(colour.rgb,1.0);}`;s_.v.ShadersStore.tonemapPixelShader=hR,(ts=rs||(rs={}))[ts.Hable=0]="Hable",ts[ts.Reinhard=1]="Reinhard",ts[ts.HejiDawson=2]="HejiDawson",ts[ts.Photographic=3]="Photographic";let hA=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -uniform mat4 viewProjection;uniform vec2 depthValues; -#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position; -#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -#include -#include -#include -gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); -#if defined(ALPHATEST) || defined(BASIC_RENDER) -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -} -`;s_.v.ShadersStore.volumetricLightScatteringPassVertexShader=hI;let hM=`#if defined(ALPHATEST) || defined(NEED_UV) -varying vec2 vUV; -#endif -#if defined(ALPHATEST) -uniform sampler2D diffuseSampler; -#endif -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{ -#if defined(ALPHATEST) -vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) -discard; -#endif -gl_FragColor=vec4(0.0,0.0,0.0,1.0);} -`;s_.v.ShadersStore.volumetricLightScatteringPassPixelShader=hM;let VolumetricLightScatteringPostProcess=class VolumetricLightScatteringPostProcess extends postProcess_PostProcess{get useDiffuseColor(){return rT.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){rT.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,s=100,n=texture_Texture.BILINEAR_SAMPLINGMODE,a,o,l){var h,u;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,a,o,"#define NUM_SAMPLES "+s),this._screenCoordinates=rm.FM.Zero(),this.customMeshPosition=rm.P.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,a=(l=null!==(u=null!==(h=null==i?void 0:i.getScene())&&void 0!==h?h:l)&&void 0!==u?u:this._scene).getEngine(),this._viewPort=new sh.l(0,0,1,1).toGlobal(a.getRenderWidth(),a.getRenderHeight()),this.mesh=null!=r?r:VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh",l),this._createPass(l,t.passRatio||t),this.onActivate=e=>{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add(e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;let r=e.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);let s=null===(i=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(r,e,t);let n=[],a=[rz.o.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(rz.o.UVKind)&&(a.push(rz.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(rz.o.UV2Kind)&&(a.push(rz.o.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(a.push(rz.o.MatricesIndicesKind),a.push(rz.o.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),t&&(n.push("#define INSTANCES"),so.G.PushAttributesForInstances(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));let l=e._getDrawWrapper(void 0,!0),h=l.defines,u=n.join("\n");return h!==u&&l.setEffect(r.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:r.numBoneInfluencers}),u),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){let t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){let i;let r=e.getEngine();this._volumetricLightScatteringRTT=new renderTargetTexture_RenderTargetTexture("volumetricLightScatteringMap",{width:r.getRenderWidth()*t,height:r.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;let s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);let renderSubMesh=e=>{var t;let i=e.getRenderingMesh(),r=e.getEffectiveMesh();if(this._meshExcluded(i))return;r._internalAbstractMeshDataInfo._isActiveIntermediate=!1;let s=e.getMaterial();if(!s)return;let n=i.getScene(),a=n.getEngine();a.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);let o=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;let l=a.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){let h=null===(t=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[a.currentRenderPassId],u=e._getDrawWrapper();if(i!==this.mesh||u||(u=s._getDrawWrapper()),!u)return;let c=u.effect;if(a.enableEffect(u),l||i._bind(e,c,s.fillMode),i===this.mesh)s.bind(r.getWorldMatrix(),i);else if(h)h.bindForSubMesh(r.getWorldMatrix(),r,e);else{if(c.setMatrix("viewProjection",n.getTransformMatrix()),s&&s.needAlphaTesting()){let e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&c.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&c.setMatrix("world",r.getWorldMatrix()),i._processRendering(r,e,c,sr.F.TriangleFillMode,o,l,(e,t)=>{e||c.setMatrix("world",t)})}},n=new rg.HE(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{i=e.clearColor,e.clearColor=n}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=i}),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{let n;let a=e.getEngine();if(s.length){for(a.setColorWrite(!1),n=0;ne._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0),a.setAlphaMode(2),n=0;n{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));let t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):rT.Y.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){let e=rS.l.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return rb.p4.Parse(()=>new ScreenSpaceCurvaturePostProcess(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}};(0,rH.gn)([(0,rb.qC)()],ScreenSpaceCurvaturePostProcess.prototype,"ridge",void 0),(0,rH.gn)([(0,rb.qC)()],ScreenSpaceCurvaturePostProcess.prototype,"valley",void 0),(0,rv.H)("BABYLON.ScreenSpaceCurvaturePostProcess",ScreenSpaceCurvaturePostProcess);let hO=`uniform vec4 color; -`;s_.v.IncludesShadersStore.boundingBoxRendererFragmentDeclaration=hO;let hN=`#ifdef WEBGL2 -uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -#else -layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; -#endif -`;s_.v.IncludesShadersStore.boundingBoxRendererUboDeclaration=hN;let hF=`#include<__decl__boundingBoxRendererFragment> -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.boundingBoxRendererPixelShader=hF;let hB=`uniform mat4 world;uniform mat4 viewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR; -#endif -`;s_.v.IncludesShadersStore.boundingBoxRendererVertexDeclaration=hB;let hL=`attribute vec3 position; -#include<__decl__boundingBoxRendererVertex> -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec4 worldPos=world*vec4(position,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} -#else -gl_Position=viewProjection*worldPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -} -`;s_.v.ShadersStore.boundingBoxRendererVertexShader=hL,Object.defineProperty(rN.x.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),rN.x.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new BoundingBoxRenderer(this)),this._boundingBoxRenderer},Object.defineProperty(rG.x.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});let BoundingBoxRenderer=class BoundingBoxRenderer{constructor(e){this.name=rQ.l.NAME_BOUNDINGBOXRENDERER,this.frontColor=new rg.Wo(1,1,1),this.backColor=new rg.Wo(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new rf.y$,this.onAfterBoxRenderingObservable=new rf.y$,this.onResourcesReadyObservable=new rf.y$,this.enabled=!0,this.renderList=new sp.t(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new rX.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new rX.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(rQ.l.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(rQ.l.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(rQ.l.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(rQ.l.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new shaderMaterial_ShaderMaterial("colorShader",this.scene,"boundingBoxRenderer",{attributes:[rz.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new shaderMaterial_ShaderMaterial("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[rz.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=CreateBoxVertexData({size:1});this._vertexBuffers[rz.o.PositionKind]=new rz.o(e,t.positions,rz.o.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){let e=this._vertexBuffers[rz.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;let r=this.scene.getEngine();r.setDepthWrite(!1);let s=this.scene.getTransformMatrix();for(let n=0;n{let t=e._getComponent(rQ.l.NAME_DEPTHRENDERER);t||(t=new DepthRendererSceneComponent(e),e._addComponent(t))};let hw=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( -frontColor.rgb+alphaMultiplier*backColor.rgb, -frontColor.a+backColor.a -);}`;s_.v.ShadersStore.oitFinalPixelShader=hw;let hU=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { -discard;}}`;s_.v.ShadersStore.oitBackBlendPixelShader=hU;let DepthPeelingEffectConfiguration=class DepthPeelingEffectConfiguration{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}};let DepthPeelingRenderer=class DepthPeelingRenderer{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){let t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new sp.t(10),this._excludedSubMeshes=new sp.t(10),this._excludedMeshes=[],this._colorCache=[new rg.HE(DepthPeelingRenderer._DEPTH_CLEAR_VALUE,DepthPeelingRenderer._DEPTH_CLEAR_VALUE,0,0),new rg.HE(-DepthPeelingRenderer._MIN_DEPTH,DepthPeelingRenderer._MAX_DEPTH,0,0),new rg.HE(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){rT.Y.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let e=0;e -uniform vec4 color; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.linePixelShader=hV;let hk=`#include -#include -attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -#include -mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; -#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) -vec4 worldPos=finalWorld*vec4(position,1.0); -#include -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.lineVertexShader=hk,rG.x.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},rG.x.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new EdgesRenderer(this,e,t,!0,i),this},Object.defineProperty(rG.x.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),LinesMesh.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new LineEdgesRenderer(this,e,t),this},InstancedLinesMesh.prototype.enableEdgesRendering=function(e=.95,t=!1){return LinesMesh.prototype.enableEdgesRendering.apply(this,arguments),this};let FaceAdjacencies=class FaceAdjacencies{constructor(){this.edges=[],this.edgesConnectedCount=0}};let EdgesRenderer=class EdgesRenderer{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){let t=new shaderMaterial_ShaderMaterial("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,r=!0,s){var n;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=[],this._linesNormals=[],this._linesIndices=[],this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new sp.t(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=s?s:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new sm.q(e.getEngine())),this._prepareRessources(),r&&(null===(n=null==s?void 0:s.useAlternateEdgeFinder)||void 0===n||n?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=EdgesRenderer._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[rz.o.PositionKind];e&&e._rebuild(),(e=this._buffers[rz.o.NormalKind])&&e._rebuild();let t=this._source.getScene(),i=t.getEngine();this._ib=i.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[rz.o.PositionKind];t&&(t.dispose(),this._buffers[rz.o.PositionKind]=null),(t=this._buffers[rz.o.NormalKind])&&(t.dispose(),this._buffers[rz.o.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),null===(e=this._drawWrapper)||void 0===e||e.dispose()}_processEdgeForAdjacencies(e,t,i,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,r,s){let n;if(void 0===t)n=!0;else{let r=rm.P.Dot(i[e],i[t]);n=r{i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?s=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(s=2);for(let t=0;t<3;++t)t===s?e[t].sort((e,t)=>e[1]t[1]?1:0):e[t].sort((e,t)=>e[1]>t[1]?-1:e[1]=s+1;--n)makePointList(e[n%3],a,n!==s+2?r[i[t+(n+1)%3]]:-1);let l=a.length;i.push(r[i[t+s]],n[0],a[0]),i.push(r[i[t+(s+1)%3]],a[l-1],n[o-1]);let h=o<=l,u=h?o:l,c=h?l:o,d=h?o-1:l-1,p=h?0:1,_=o+l-2,f=0,m=0,g=h?n:a,v=h?a:n,x=0;for(;_-- >0;){let e;p?i.push(g[f],v[m]):i.push(v[m],g[f]),(x+=u)>=c&&fs){let e=r;r=s,s=e}let a=r+"_"+s,o=m[a];if(o){if(!o.done){let e=rm.P.Dot(t,o.normal);e0||this._source.hasThinInstances)}render(){let e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}let i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances,s=0;if(r){if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){let e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;enull!=e),this._scene.autoClear=!0;let r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;let s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0],a=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?a=n:this._needsCompositionForThisPass?a=e.imageProcessingPostProcess:s&&(a=s),this._bindFrameBuffer(),this._linkInternalTexture(e,a)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e))){for(let r=0;r=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw(0,r$.S)("PrePassRendererSceneComponent")},PrePassRenderer.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(rN.x.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),rN.x.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new PrePassRenderer(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,rT.Y.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},rN.x.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};let PrePassRendererSceneComponent=class PrePassRendererSceneComponent{constructor(e){this.name=rQ.l.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(rQ.l.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(rQ.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(rQ.l.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(rQ.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(rQ.l.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(rQ.l.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(rQ.l.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(rQ.l.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;let s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){let t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}};PrePassRenderer._SceneComponentInitialization=e=>{let t=e._getComponent(rQ.l.NAME_PREPASSRENDERER);t||(t=new PrePassRendererSceneComponent(e),e._addComponent(t))};let hG=`#define rcp(x) 1./x -#define GOLDEN_RATIO 1.618033988749895 -#define TWO_PI 6.2831855 -vec2 Golden2dSeq(int i,float n) -{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} -vec2 SampleDiskGolden(int i,int sampleCount) -{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;s_.v.IncludesShadersStore.fibonacci=hG,s_.v.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";let hz=`#include -#include -#include -#include -varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; -#define rcp(x) 1./x -#define Sq(x) x*x -#define SSS_BILATERAL_FILTER true -vec3 EvalBurleyDiffusionProfile(float r,vec3 S) -{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); -vec3 expSum=exp_13*(1.+exp_13*exp_13); -return (S*rcp(8.*PI))*expSum; } -vec2 SampleBurleyDiffusionProfile(float u,float rcpS) -{u=1.-u; -float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); -float p=(g*n)*n; -float c=1.+p+n; -float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); -float x=(3./LOG2_E)*log2(c)-d; -float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; -return vec2(r,rcpPdf);} -vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) -{ -#ifndef SSS_BILATERAL_FILTER -z=0.; -#endif -float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; -#if SSS_CLAMP_ARTIFACT -return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); -#else -return EvalBurleyDiffusionProfile(r,S)*area; -#endif -} -void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, -float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) -{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; -float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; -vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; -float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) -{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} -else -{}} -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) -{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) -{centerDepth=texture2D(depthSampler,vUV).r;} -if (!passedStencilTest) { -gl_FragColor=inputColor;return;} -float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; -vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; -float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) -{ -#ifdef DEBUG_SSS_SAMPLES -vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; -#endif -gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} -#ifdef DEBUG_SSS_SAMPLES -vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; -#endif -float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); -vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration){rT.Y.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}let i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}};let SubSurfaceConfiguration=class SubSurfaceConfiguration{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=rQ.l.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new rg.Wo(1,1,1)),this._scene=e,SubSurfaceConfiguration._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return rT.Y.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw(0,r$.S)("SubSurfaceSceneComponent")},rp.p.AddParser(rQ.l.NAME_SUBSURFACE,(e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(rQ.l.NAME_SUBSURFACE);t||(t=new SubSurfaceSceneComponent(e),e._addComponent(t))};let hW=`#ifdef LOGARITHMICDEPTH -#extension GL_EXT_frag_depth : enable -#endif -uniform vec4 color; -#ifdef ALPHATEST -varying vec2 vUV;uniform sampler2D diffuseSampler; -#endif -#include -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#include -#ifdef ALPHATEST -if (texture2D(diffuseSampler,vUV).a<0.4) -discard; -#endif -#include -gl_FragColor=color; -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.outlinePixelShader=hW;let hH=`attribute vec3 position;attribute vec3 normal; -#include -#include -#include -#include[0..maxSimultaneousMorphTargets] -#include -uniform float offset; -#include -uniform mat4 viewProjection; -#ifdef ALPHATEST -varying vec2 vUV;uniform mat4 diffuseMatrix; -#ifdef UV1 -attribute vec2 uv; -#endif -#ifdef UV2 -attribute vec2 uv2; -#endif -#endif -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) -{vec3 positionUpdated=position;vec3 normalUpdated=normal; -#ifdef UV1 -vec2 uvUpdated=uv; -#endif -#include -#include[0..maxSimultaneousMorphTargets] -vec3 offsetPosition=positionUpdated+(normalUpdated*offset); -#include -#include -#include -vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; -#ifdef ALPHATEST -#ifdef UV1 -vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); -#endif -#ifdef UV2 -vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); -#endif -#endif -#include -#include -} -`;s_.v.ShadersStore.outlineVertexShader=hH,rN.x.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new OutlineRenderer(this)),this._outlineRenderer},Object.defineProperty(rV.Kj.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(rV.Kj.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});let OutlineRenderer=class OutlineRenderer{constructor(e){this.name=rQ.l.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(rQ.l.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(rQ.l.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",t)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];let r=[],s=[rz.o.PositionKind,rz.o.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;let o=n.getScene();a.needAlphaTesting()&&(r.push("#define ALPHATEST"),n.isVerticesDataPresent(rz.o.UVKind)&&(s.push(rz.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(rz.o.UV2Kind)&&(s.push(rz.o.UV2Kind),r.push("#define UV2"))),a.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),(0,nX.lK)(a,o,r),n.useBones&&n.computeBonesUsingShaders?(s.push(rz.o.MatricesIndicesKind),s.push(rz.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(rz.o.MatricesIndicesExtraKind),s.push(rz.o.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");let l=n.morphTargetManager,h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),so.G.PrepareAttributesForMorphTargetsInfluencers(s,n,h)),t&&(r.push("#define INSTANCES"),so.G.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));let u=e._getDrawWrapper(i,!0),c=u.defines,d=r.join("\n");if(c!==d){let e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,nX.qx)(e),u.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){let r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(OutlineRenderer._StencilReference),this._engine.setStencilFunctionReference(OutlineRenderer._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){let e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}};OutlineRenderer._StencilReference=4,i(7254);let FluidRenderingObject=class FluidRenderingObject{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!(null===(e=this.vertexBuffers)||void 0===e?void 0:e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new rf.y$,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){let e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new EffectWrapper({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new EffectWrapper({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;let e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){let e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;let t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){let e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;let t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;null===(e=this._depthEffectWrapper)||void 0===e||e.dispose(),null===(t=this._thicknessEffectWrapper)||void 0===t||t.dispose()}};let FluidRenderingObjectParticleSystem=class FluidRenderingObjectParticleSystem extends FluidRenderingObject{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add(()=>{this._engine.setAlphaMode(2)})))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}};let FluidRenderingTextures=class FluidRenderingTextures{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){let e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,r,s,n,a=1,o=6,l=1,h=6,u=!1,c=null,d=!0,p=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new rf.y$,this._name=e,this._scene=t,this._camera=c,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=n,this._textureType=a,this._textureFormat=o,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=u,this._generateDepthBuffer=d,this._samples=p,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){let[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});let e=this._rt.texture;e.incrementReferences(),this._texture=new texture_Texture(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,this._texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,r,s,n=!1){let a=this._scene.getEngine(),o=new rm.FM(Math.floor(this._blurTextureSizeX/r),Math.floor(this._blurTextureSizeY/r)),l=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:o.x,height:o.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),u=h.texture;u.incrementReferences();let c=new texture_Texture(null,this._scene);if(c.name="rttBlurred"+s,c._texture=u,c.wrapU=texture_Texture.CLAMP_ADDRESSMODE,c.wrapV=texture_Texture.CLAMP_ADDRESSMODE,c.anisotropicFilteringLevel=1,n){let r=new postProcess_PostProcess("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),r.onSizeChangedObservable.add(()=>{r._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(r);let s=new postProcess_PostProcess("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.onApplyObservable.add(e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),s.onSizeChangedObservable.add(()=>{s._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s),r.autoClear=!1,s.autoClear=!1;let n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?s:r;return[h,c,n]}{let r=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new postProcess_PostProcess("BilateralBlurX","fluidRenderingBilateralBlur",r,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),s.onSizeChangedObservable.add(()=>{s._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s);let n=new postProcess_PostProcess("BilateralBlurY","fluidRenderingBilateralBlur",r,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add(e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),n.onSizeChangedObservable.add(()=>{n._textures.forEach(e=>{e.texture.wrapU=texture_Texture.CLAMP_ADDRESSMODE,e.texture.wrapV=texture_Texture.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(n),s.autoClear=!1,n.autoClear=!1;let o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?n:s;return[h,c,o]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((null!==(t=null===(e=this._camera)||void 0===e?void 0:e.fov)&&void 0!==t?t:45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,r;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),null===(e=this._rt)||void 0===e||e.dispose(),this._rt=null,null===(t=this._texture)||void 0===t||t.dispose(),this._texture=null,null===(i=this._rtBlur)||void 0===i||i.dispose(),this._rtBlur=null,null===(r=this._textureBlurred)||void 0===r||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}};(tn=rn||(rn={}))[tn.DepthTexture=0]="DepthTexture",tn[tn.DepthBlurredTexture=1]="DepthBlurredTexture",tn[tn.ThicknessTexture=2]="ThicknessTexture",tn[tn.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",tn[tn.DiffuseTexture=4]="DiffuseTexture",tn[tn.Normals=5]="Normals",tn[tn.DiffuseRendering=6]="DiffuseRendering";let FluidRenderingTargetRenderer=class FluidRenderingTargetRenderer{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new rg.Wo(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new rm.P(-2,-1,1).normalize(),this._debugFeature=rn.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new rf.y$,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=null!=t?t:e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new rm.y3,this._depthClearColor=new rg.HE(1e6,1e6,1e6,1),this._thicknessClearColor=new rg.HE(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;let r=null!==(e=this._depthMapSize)&&void 0!==e?e:this._engine.getRenderWidth(),s=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new FluidRenderingTextures("Depth",this._scene,r,s,r,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){let e=null!==(t=this._diffuseMapSize)&&void 0!==t?t:this._engine.getRenderWidth(),i=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new FluidRenderingTextures("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}let n=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),a=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new FluidRenderingTextures("Thickness",this._scene,n,a,n,a,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){(null===e||e===this._depthRenderTarget)&&this._setBlurDepthParameters(),(null===e||e===this._thicknessRenderTarget)&&this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){var e;let t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;let n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new rm.FM(1/n.getSize().width,1/n.getSize().height);if(this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap){let t=null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture;t&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT"))}this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),r.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===rn.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===rn.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),(this._debugFeature===rn.DepthTexture||this._debugFeature===rn.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new postProcess_PostProcess("FluidRendering","fluidRenderingRender",i,r,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(e=>{var i,r,s,n,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,C,E,b,y;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&e.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(n=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==n?n:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==r?r:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(u=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==u?u:null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(l=null===(o=this._diffuseRenderTarget.texture)||void 0===o?void 0:o.getInternalTexture())&&void 0!==l?l:null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&e.setTextureSampler("bgDepthSamplerSampler",null!==(c=this._bgDepthTexture)&&void 0!==c?c:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(f=null===(_=this._thicknessRenderTarget.textureBlur)||void 0===_?void 0:_.getInternalTexture())&&void 0!==f?f:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(p=null===(d=this._thicknessRenderTarget.texture)||void 0===d?void 0:d.getInternalTexture())&&void 0!==p?p:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){let i=null!==(m=this._environmentMap)&&void 0!==m?m:this._scene.environmentTexture;i&&(e.setTexture("reflectionSampler",i),t.isWebGPU&&e.setTextureSampler("reflectionSamplerSampler",null!==(g=null==i?void 0:i.getInternalTexture())&&void 0!==g?g:null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",a),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case rn.DepthTexture:i=this._depthRenderTarget.texture;break;case rn.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case rn.ThicknessTexture:i=null!==(x=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==x?x:null;break;case rn.ThicknessBlurredTexture:i=(null===(T=this._thicknessRenderTarget)||void 0===T?void 0:T.enableBlur)?null!==(C=null===(S=this._thicknessRenderTarget)||void 0===S?void 0:S.textureBlur)&&void 0!==C?C:null:null!==(b=null===(E=this._thicknessRenderTarget)||void 0===E?void 0:E.texture)&&void 0!==b?b:null;break;case rn.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==rn.Normals&&(e.setTexture("debugSampler",i),t.isWebGPU&&e.setTextureSampler("debugSamplerSampler",null!==(y=null==i?void 0:i.getInternalTexture())&&void 0!==y?y:null))}})}_clearTargets(){var e,t,i;(null===(e=this._depthRenderTarget)||void 0===e?void 0:e.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(t=this._diffuseRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(i=this._thicknessRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var t,i,r,s,n,a;if(this._needInitialization||!e.isReady())return;let o=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(null===(t=this._depthRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(i=this._diffuseRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(r=this._thicknessRenderTarget)||void 0===r?void 0:r.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),null===(s=this._depthRenderTarget)||void 0===s||s.applyBlurPostProcesses(),null===(n=this._diffuseRenderTarget)||void 0===n||n.applyBlurPostProcesses(),null===(a=this._thicknessRenderTarget)||void 0===a||a.applyBlurPostProcesses(),o&&this._engine.bindFramebuffer(o)}dispose(e=!1){var t,i,r,s;e||(null===(t=this._depthRenderTarget)||void 0===t||t.dispose(),this._depthRenderTarget=null,null===(i=this._diffuseRenderTarget)||void 0===i||i.dispose(),this._diffuseRenderTarget=null,null===(r=this._thicknessRenderTarget)||void 0===r||r.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),null===(s=this._renderPostProcess)||void 0===s||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}};let FluidRenderingObjectCustomParticles=class FluidRenderingObjectCustomParticles extends FluidRenderingObject{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(let t in e){let i;let r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new rz.o(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new EffectWrapper({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new rz.o(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&null!==(t=null===(e=this._diffuseEffectWrapper)||void 0===e?void 0:e.effect.isReady())&&void 0!==t&&t}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){let e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;let t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;for(let t in super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose(),this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}};let hX=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; -#include -void main(void) -{vec4 color=texture2D(textureSampler,vUV); -#ifdef DEPTH_TEXTURE -gl_FragDepth=color.r; -#else -if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} -gl_FragColor=color; -#endif -} -`;s_.v.ShadersStore.copyTextureToTexturePixelShader=hX,(ta=ra||(ra={}))[ta.None=0]="None",ta[ta.ToLinearSpace=1]="ToLinearSpace",ta[ta.ToGammaSpace=2]="ToGammaSpace";let CopyTextureToTexture=class CopyTextureToTexture{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new EffectRenderer(e),this._effectWrapper=new EffectWrapper({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add(()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)})}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=ra.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;let r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}};let FluidRenderingDepthTextureCopy=class FluidRenderingDepthTextureCopy{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new CopyTextureToTexture(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil")}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}};let hY=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; -#ifdef FLUIDRENDERING_VELOCITY -attribute vec3 velocity;varying float velocityNorm; -#endif -void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; -#ifdef FLUIDRENDERING_VELOCITY -velocityNorm=length(velocity); -#endif -} -`;s_.v.ShadersStore.fluidRenderingParticleDepthVertexShader=hY;let hj=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; -#ifdef FLUIDRENDERING_VELOCITY -varying float velocityNorm; -#endif -void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); -#ifndef FLUIDRENDERING_RHS -normal.z=-normal.z; -#endif -vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; -#ifdef WEBGPU -gl_FragDepth=clipSpacePos.z/clipSpacePos.w; -#else -gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; -#endif -#ifdef FLUIDRENDERING_RHS -realViewPos.z=-realViewPos.z; -#endif -#ifdef FLUIDRENDERING_VELOCITY -glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); -#else -glFragColor=vec4(realViewPos.z,0.,0.,1.); -#endif -} -`;s_.v.ShadersStore.fluidRenderingParticleDepthPixelShader=hj;let hq=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} -`;s_.v.ShadersStore.fluidRenderingParticleThicknessVertexShader=hq;let hK=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} -`;s_.v.ShadersStore.fluidRenderingParticleThicknessPixelShader=hK;let h$=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} -`;s_.v.ShadersStore.fluidRenderingParticleDiffuseVertexShader=h$;let hQ=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} -`;s_.v.ShadersStore.fluidRenderingParticleDiffusePixelShader=hQ;let hZ=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} -int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} -glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} -`;s_.v.ShadersStore.fluidRenderingBilateralBlurPixelShader=hZ;let hJ=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} -float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} -sum/=wsum;glFragColor=vec4(sum.rgb,1.);} -`;s_.v.ShadersStore.fluidRenderingStandardBlurPixelShader=hJ;let h0=`/* disable_uniformity_analysis */ -#define IOR 1.333 -#define ETA 1.0/IOR -#define F0 0.02 -uniform sampler2D textureSampler;uniform sampler2D depthSampler; -#ifdef FLUIDRENDERING_DIFFUSETEXTURE -uniform sampler2D diffuseSampler; -#else -uniform vec3 diffuseColor; -#endif -#ifdef FLUIDRENDERING_FIXED_THICKNESS -uniform float thickness;uniform sampler2D bgDepthSampler; -#else -uniform float minimumThickness;uniform sampler2D thicknessSampler; -#endif -#ifdef FLUIDRENDERING_ENVIRONMENT -uniform samplerCube reflectionSampler; -#endif -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) -uniform sampler2D debugSampler; -#endif -uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; -#ifdef FLUIDRENDERING_RHS -ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; -#else -ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; -#endif -ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} -vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} -void main(void) {vec2 texCoord=vUV; -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) -vec4 color=texture2D(debugSampler,texCoord); -#ifdef FLUIDRENDERING_DEBUG_DEPTH -glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} -#else -glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} -#endif -return; -#endif -vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; -#ifndef FLUIDRENDERING_FIXED_THICKNESS -float thickness=texture2D(thicknessSampler,texCoord).x; -#else -float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; -#endif -vec4 backColor=texture2D(textureSampler,texCoord); -#ifndef FLUIDRENDERING_FIXED_THICKNESS -if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { -#else -if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { -#endif -glFragColor=backColor;return;} -vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} -vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} -vec3 normal=normalize(cross(ddy,ddx)); -#ifdef FLUIDRENDERING_RHS -normal=-normal; -#endif -#ifndef WEBGPU -if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} -#endif -#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) -glFragColor=vec4(normal*0.5+0.5,1.0);return; -#endif -vec3 rayDir=normalize(viewPos); -#ifdef FLUIDRENDERING_DIFFUSETEXTURE -vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; -#endif -vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); -#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING -float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; -#endif -vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); -vec3 refractionColor=transmitted.rgb*transmittance; -#ifdef FLUIDRENDERING_ENVIRONMENT -vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; -#else -vec3 finalColor=refractionColor+specular; -#endif -#ifdef FLUIDRENDERING_VELOCITY -float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); -#endif -glFragColor=vec4(finalColor,transmitted.a);} -`;function IsParticleSystemObject(e){return!!e.particleSystem}s_.v.ShadersStore.fluidRenderingRenderPixelShader=h0,Object.defineProperty(rN.x.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),rN.x.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new FluidRenderer(this)),this._fluidRenderer},rN.x.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};let FluidRendererSceneComponent=class FluidRendererSceneComponent{constructor(e){this.name=rQ.l.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(rQ.l.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(rQ.l.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._prepareRendering()}_afterCameraDraw(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._render(e)}rebuild(){this.scene._fluidRenderer&&(this.scene.disableFluidRenderer(),this.scene.enableFluidRenderer())}dispose(){this.scene.disableFluidRenderer()}};let FluidRenderer=class FluidRenderer{static _SceneComponentInitialization(e){let t=e._getComponent(rQ.l.NAME_FLUIDRENDERER);t||(t=new FluidRendererSceneComponent(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,FluidRenderer._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){let t=this._getParticleSystemIndex(e);return -1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){let s=new FluidRenderingObjectParticleSystem(this._scene,e);s.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new FluidRenderingTargetRenderer(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==t&&(i.generateDiffuseTexture=t);let n={object:s,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,r,s){let n=new FluidRenderingObjectCustomParticles(this._scene,e,t);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),r||(r=new FluidRenderingTargetRenderer(this._scene,s),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==i&&(r.generateDiffuseTexture=i);let a={object:n,targetRenderer:r};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}removeRenderObject(e,t=!0){let i=this.renderObjects.indexOf(e);return -1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort((e,t)=>e.object.priorityt.object.priority?1:0)}_removeUnusedTargetRenderers(){let e={};for(let t=0;t{var e;for(let t of(s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`),n)){let i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,r=null==i?void 0:i.texture;if(i&&r){let e=r.width+"_"+r.height,t=a[e];t||(t=a[e]=new FluidRenderingDepthTextureCopy(this._engine,r.width,r.height)),t.depthRTWrapper._shareDepth(i)}}})}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=this._cameras.get(t),s=r[1],n=e.get(t);if(n)for(let e in s)n[1][e]||s[e].dispose();else for(let e in s)s[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){let e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)})}_setUseVelocityForRenderObject(){for(let e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(let e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var t;for(let t=0;t{let t=e[1];for(let e in t)t[e].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}};let ThinSprite=class ThinSprite{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}};let Sprite=class Sprite extends ThinSprite{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=[],this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new rf.y$,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new rg.HE(1,1,1,1),this.position=rm.P.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=s.distance))&&(s=o,i))break}return s||new r7.p},rN.x.prototype._internalMultiPickSprites=function(e,t,i){if(!r7.p)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(rQ.l.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(rQ.l.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(rQ.l.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();let e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){let n=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,r,s){let n=this.scene;return r?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&s&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){let s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,rx.V.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,rx.V.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,rx.V.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,rx.V.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){let n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){let i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)),s&&i.pickedSprite.actionManager.processTrigger(6,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,rx.V.CreateNewFromSprite(n._pickedDownSprite,n,r)))}return i}};let h1=`#ifdef IMAGEPROCESSINGPOSTPROCESS -gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); -#endif -`;s_.v.IncludesShadersStore.imageProcessingCompatibility=h1;let h2=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; -#include -#define CUSTOM_FRAGMENT_DEFINITIONS -#ifdef PIXEL_PERFECT -vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} -#endif -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -#ifdef PIXEL_PERFECT -vec2 uv=uvPixelPerfect(vUV); -#else -vec2 uv=vUV; -#endif -vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) -{if (color.a<0.95) -discard;} -color*=vColor; -#include -gl_FragColor=color; -#include -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.spritesPixelShader=h2;let h3=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; -#include -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; -vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); -vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; -#ifdef FOG -vFogDistance=viewPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.spritesVertexShader=h3;let SpriteRenderer=class SpriteRenderer{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,r=null){let s;this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new rz.l(e,this._vertexData,!0,this._vertexBufferSize);let n=this._buffer.createVertexBuffer(rz.o.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),a=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),o=6;if(this._useInstancing){let t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new rz.l(e,t,!1,2),s=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else s=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;let l=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(rz.o.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[rz.o.PositionKind]=n,this._vertexBuffers.options=a,this._vertexBuffers.offsets=s,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[rz.o.ColorKind]=u,this._createEffects()}_createEffects(){var e,t,i,r;null===(e=this._drawWrapperBase)||void 0===e||e.dispose(),null===(t=this._drawWrapperFog)||void 0===t||t.dispose(),null===(i=this._drawWrapperDepth)||void 0===i||i.dispose(),null===(r=this._drawWrapperFogDepth)||void 0===r||r.dispose(),this._drawWrapperBase=new sm.q(this._engine),this._drawWrapperFog=new sm.q(this._engine),this._drawWrapperDepth=new sm.q(this._engine,!1),this._drawWrapperFogDepth=new sm.q(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);let s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[rz.o.PositionKind,"options","offsets","inverts","cellInfo",rz.o.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],s),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[rz.o.PositionKind,"options","offsets","inverts","cellInfo",rz.o.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],s+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,r,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,a=this._drawWrapperDepth,o=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(n=this._drawWrapperFog,a=this._drawWrapperFogDepth,o=!0);let l=n.effect;if(!l.isReady())return;let h=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),c=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length),p=0,_=!0;for(let i=0;i>0;t._xOffset=(t.cellIndex-i*e)*this.cellWidth/s.width,t._yOffset=i*this.cellHeight/s.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._useInstancing?o-=2:(this._vertexData[o+6]=i,this._vertexData[o+7]=r),n?this._vertexData[o+8]=t.invertU?0:1:this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0,this._vertexData[o+10]=t._xOffset,this._vertexData[o+11]=t._yOffset,this._vertexData[o+12]=t._xSize/s.width,this._vertexData[o+13]=t._ySize/s.height,this._vertexData[o+14]=t.color.r,this._vertexData[o+15]=t.color.g,this._vertexData[o+16]=t.color.b,this._vertexData[o+17]=t.color.a}_buildIndexBuffer(){let e=[],t=0;for(let i=0;i{e.cellRef||(e.cellIndex=0);let i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=rS.l.LastCreatedScene),s._getComponent(rQ.l.NAME_SPRITE)||s._addComponent(new SpriteSceneComponent(s)),this._fromPacked=o,this._scene=s;let h=this._scene.getEngine();if(this._spriteRenderer=new SpriteRenderer(h,i,n,s),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(void 0!==r)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new texture_Texture(t,s,!0,!1,a)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if((e="string"==typeof t?JSON.parse(t):t).frames.length){let t={};for(let i=0;i0);let r=e.substring(0,t-1)+".json";rW.w1.LoadFile(r,e=>{try{let t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON format. Please check documentation for format specifications.")}},void 0,void 0,!1,()=>{rT.Y.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1})}}_checkTextureAlpha(e,t,i,r,s){if(!e.useAlphaForPicking||!this.texture)return!0;let n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));let a=rm.jp.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);let o=(a.x-r.x)/(s.x-r.x),l=1-(a.y-r.y)/(s.y-r.y),h=e._xOffset*n.width+o*e._xSize|0,u=e._yOffset*n.height+l*e._ySize|0,c=this._textureContent[(h+u*n.width)*4+3];return c>.5}intersects(e,t,i,r){let s=Math.min(this.capacity,this.sprites.length),n=rm.P.Zero(),a=rm.P.Zero(),o=Number.MAX_VALUE,l=null,h=rm.jp.Vector3[0],u=rm.jp.Vector3[1],c=t.getViewMatrix(),d=e,p=e;for(let t=0;te){if(!this._checkTextureAlpha(s,d,e,n,a))continue;if(p=d,o=e,l=s,r)break}}}}if(l){let e=new r7.p;c.invertToRef(rm.jp.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=o;let t=rm.jp.Vector3[2];return t.copyFrom(p.direction),t.normalize(),t.scaleInPlace(o),p.origin.addToRef(t,h),e.pickedPoint=rm.P.TransformCoordinates(h,rm.jp.Matrix[0]),e}return null}multiIntersects(e,t,i){let r;let s=Math.min(this.capacity,this.sprites.length),n=rm.P.Zero(),a=rm.P.Zero(),o=[],l=rm.jp.Vector3[0].copyFromFloats(0,0,0),h=rm.jp.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let t=0;t{let a=new rP.g;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=spriteManager_SpriteManager.Parse(t,i||rS.l.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the sprite manager")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new spriteManager_SpriteManager("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,s)=>{let n=new rP.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(n.responseText).jsonPayload),a=JSON.parse(s.spriteManager),o=spriteManager_SpriteManager.Parse(a,t||rS.l.LastCreatedScene,i);o.snippetId=e,r(o)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}};spriteManager_SpriteManager.SnippetUrl="https://snippet.babylonjs.com",spriteManager_SpriteManager.CreateFromSnippetAsync=spriteManager_SpriteManager.ParseFromSnippetAsync;let h4=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) -#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) -#else -#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) -#endif -precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( -texture2D(frameMap,vec2(fX,0.),0.), -texture2D(frameMap,vec2(fX,fdStep*1.),0.), -texture2D(frameMap,vec2(fX,fdStep*2.),0.), -vec4(0.) -);} -void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); -#ifdef FLIPU -tileUV.y=1.0-tileUV.y; -#endif -vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;} -animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} -mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} -vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} -color.xyz*=colorMul;gl_FragColor=color;}`;s_.v.ShadersStore.spriteMapPixelShader=h4;let h5=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; -gl_Position=worldViewProjection*p;}`;s_.v.ShadersStore.spriteMapVertexShader=h5,i(3609),i(6807),i(1146),(to=ro||(ro={}))[to.INIT=0]="INIT",to[to.RUNNING=1]="RUNNING",to[to.DONE=2]="DONE",to[to.ERROR=3]="ERROR",i(320),rf.y$.prototype.notifyObserversWithPromise=async function(e,t=-1,i,r,s){let n=Promise.resolve(e);if(!this.observers.length)return n;let a=this._eventState;return a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.userInfo=s,this.observers.forEach(i=>{!a.skipNextObservers&&!i._willBeUnregistered&&i.mask&t&&(n=i.scope?n.then(t=>(a.lastReturnValue=t,i.callback.apply(i.scope,[e,a]))):n.then(t=>(a.lastReturnValue=t,i.callback(e,a))),i.unregisterOnNextCall&&this._deferUnregister(i))}),await n,e},i(8786);let SceneOptimization=class SceneOptimization{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}};let MergeMeshesOptimization=class MergeMeshesOptimization extends SceneOptimization{constructor(){super(...arguments),this._canBeMerged=e=>e instanceof rV.Kj&&!e.isDisposed()&&!!e.isVisible&&!!e.isEnabled()&&!(e.instances.length>0)&&!e.skeleton&&!e.hasLODLevels&&0!==e.getTotalVertices()}static get UpdateSelectionTree(){return MergeMeshesOptimization._UpdateSelectionTree}static set UpdateSelectionTree(e){MergeMeshesOptimization._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){let r=e.meshes.slice(0),s=r.length;for(let e=0;e{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),h6[e.id]=!0)},SerializeMesh=(e,t)=>{let i={},r=e._geometry;return r&&!e.getScene().getGeometryById(r.id)&&SerializeGeometry(r,t.geometries),e.serialize&&e.serialize(i),i},FinalizeSingleNode=(e,t)=>{if(e._isMesh){if(1===e.delayLoadState||0===e.delayLoadState){let serializeMaterial=i=>{t.materials=t.materials||[],e.material&&!t.materials.some(t=>t.id===e.material.id)&&t.materials.push(i.serialize())};if(e.material&&!e.material.doNotSerialize){if(e.material instanceof lC.G){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some(t=>t.id===e.material.id))for(let i of(t.multiMaterials.push(e.material.serialize()),e.material.subMaterials))i&&serializeMaterial(i)}else serializeMaterial(e.material)}else e.material||serializeMaterial(e.getScene().defaultMaterial);let i=e._geometry;i&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),SerializeGeometry(i,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(SerializeMesh(e,t))}}else"TransformNode"===e.getClassName()?t.transformNodes.push(e.serialize()):-1!==e.getClassName().indexOf("Camera")?t.cameras.push(e.serialize()):-1!==e.getClassName().indexOf("Light")&&t.lights.push(e.serialize())};let sceneSerializer_SceneSerializer=class sceneSerializer_SceneSerializer{static ClearCache(){h6=[]}static Serialize(e){return sceneSerializer_SceneSerializer._Serialize(e)}static _Serialize(e,t=!0){let i,r,s;let n={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&texture_Texture.ForceSerializeBuffers&&console.warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),sceneSerializer_SceneSerializer.ClearCache(),n.useDelayedTextureLoading=e.useDelayedTextureLoading,n.autoClear=e.autoClear,n.clearColor=e.clearColor.asArray(),n.ambientColor=e.ambientColor.asArray(),n.gravity=e.gravity.asArray(),n.collisionsEnabled=e.collisionsEnabled,n.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(n.fogMode=e.fogMode,n.fogColor=e.fogColor.asArray(),n.fogStart=e.fogStart,n.fogEnd=e.fogEnd,n.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){let t=e.getPhysicsEngine();t&&(n.physicsEnabled=!0,n.physicsGravity=t.gravity.asArray(),n.physicsEngine=t.getPhysicsPluginName())}for(let t of(e.metadata&&(n.metadata=e.metadata),n.morphTargetManagers=[],e.meshes)){let e=t.morphTargetManager;e&&n.morphTargetManagers.push(e.serialize())}for(i=0,n.lights=[];i0){n.animationGroups=[];for(let t=0;t0)for(i=0,n.reflectionProbes=[];it)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){let r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],sceneSerializer_SceneSerializer.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r{0>e.indexOf(t)&&!t.doNotSerialize&&e.push(t)}),t&&e[r].parent&&0>e.indexOf(e[r].parent)&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach(e=>{FinalizeSingleNode(e,r)}),r}};let VideoRecorder=class VideoRecorder{static IsSupported(e){let t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!VideoRecorder.IsSupported(e))throw"Your browser does not support recording so far.";let i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options=Object.assign(Object.assign({},VideoRecorder._DefaultOptions),t);let r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(let e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout(()=>{this.stopRecording()},1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise((e,t)=>{this._resolve=e,this._reject=t})}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),this._reject)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();let e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&rW.w1.Download(e,this._fileName)}};VideoRecorder._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let h8=null;function CreateScreenshot(e,t,i,r,s="image/png",n=!1,a){let{height:o,width:l}=_GetScreenshotSize(e,t,i);if(!(o&&l)){rT.Y.Error("Invalid 'size' parameter !");return}h8||(h8=document.createElement("canvas")),h8.width=l,h8.height=o;let h=h8.getContext("2d"),u=e.getRenderWidth()/e.getRenderHeight(),c=l,d=c/u;d>o&&(c=(d=o)*u);let p=Math.max(0,l-c)/2,_=Math.max(0,o-d)/2,f=t.getScene();f.activeCamera!==t?CreateScreenshotUsingRenderTarget(e,t,i,e=>{if(n){let t=new Blob([e]);rW.w1.DownloadBlob(t),r&&r("")}else r&&r(e)},s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):e.onEndFrameObservable.addOnce(()=>{let t=e.getRenderingCanvas();h&&t&&h.drawImage(t,p,_,c,d),h8&&(n?(rW.w1.EncodeScreenshotCanvasData(h8,void 0,s,void 0,a),r&&r("")):rW.w1.EncodeScreenshotCanvasData(h8,r,s,void 0,a))})}function CreateScreenshotAsync(e,t,i,r="image/png",s){return new Promise((n,a)=>{CreateScreenshot(e,t,i,e=>{void 0!==e?n(e):a(Error("Data is undefined"))},r,void 0,s)})}function CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,a=!1,o,l=!1,h=!1,u=!0,c,d){let{height:p,width:_,finalWidth:f,finalHeight:m}=_GetScreenshotSize(e,t,i);if(!(p&&_)){rT.Y.Error("Invalid 'size' parameter !");return}let g={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(_,p);let v=t.getScene(),x=new renderTargetTexture_RenderTargetTexture("screenShot",{width:_,height:p},v,!1,!1,0,!1,texture_Texture.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);x.renderList=v.meshes.slice(),x.samples=n,x.renderSprites=l,x.activeCamera=t,x.forceLayerMaskCheck=u,null==d||d(x);let renderWhenReady=()=>{x.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce(()=>{f===_&&m===p?x.readPixels(void 0,void 0,void 0,!1).then(e=>{dumpTools_DumpTools.DumpData(_,p,e,r,s,o,!0,void 0,c),x.dispose()}):ApplyPostProcess("pass",x.getInternalTexture(),v,void 0,void 0,void 0,f,m).then(t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then(e=>{dumpTools_DumpTools.DumpData(f,m,e,r,s,o,!0,void 0,c),t.dispose()})})}),x.render(!0),v.incrementRenderId(),v.resetCachedMaterial(),e.setSize(g.width,g.height),t.getProjectionMatrix(!0),v.render()):setTimeout(renderWhenReady,16)},renderToTexture=()=>{v.incrementRenderId(),v.resetCachedMaterial(),renderWhenReady()};if(a){let e=new FxaaPostProcess("antialiasing",1,v.activeCamera);x.addPostProcess(e),e.getEffect().isReady()?renderToTexture():e.getEffect().onCompiled=()=>{renderToTexture()}}else renderToTexture()}function CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,a,o=!1,l=!1,h=!0,u){return new Promise((c,d)=>{CreateScreenshotUsingRenderTarget(e,t,i,e=>{void 0!==e?c(e):d(Error("Data is undefined"))},r,s,n,a,o,l,h,u)})}function _GetScreenshotSize(e,t,i){let r=0,s=0,n=0,a=0;if("object"==typeof i){let o=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*o,s=i.width*o):i.width&&!i.height?r=Math.round((s=i.width*o)/e.getAspectRatio(t)):i.height&&!i.width?s=Math.round((r=i.height*o)*e.getAspectRatio(t)):r=Math.round((s=Math.round(e.getRenderWidth()*o))/e.getAspectRatio(t)),i.finalWidth&&i.finalHeight?(a=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?a=Math.round((n=i.finalWidth)/e.getAspectRatio(t)):i.finalHeight&&!i.finalWidth?n=Math.round((a=i.finalHeight)*e.getAspectRatio(t)):(n=s,a=r)}else isNaN(i)||(r=i,s=i,n=i,a=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),a&&(a=Math.floor(a)),{height:0|r,width:0|s,finalWidth:0|n,finalHeight:0|a}}rW.w1.CreateScreenshot=CreateScreenshot,rW.w1.CreateScreenshotAsync=CreateScreenshotAsync,rW.w1.CreateScreenshotUsingRenderTarget=CreateScreenshotUsingRenderTarget,rW.w1.CreateScreenshotUsingRenderTargetAsync=CreateScreenshotUsingRenderTargetAsync,(tl=rl||(rl={}))[tl.Checkbox=0]="Checkbox",tl[tl.Slider=1]="Slider",tl[tl.Vector3=2]="Vector3",tl[tl.Quaternion=3]="Quaternion",tl[tl.Color3=4]="Color3",tl[tl.String=5]="String",tl[tl.Button=6]="Button",tl[tl.Options=7]="Options",tl[tl.Tab=8]="Tab",tl[tl.FileButton=9]="FileButton",tl[tl.Vector2=10]="Vector2",i(9983);let DataStorage=class DataStorage{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(t){let e={};return{getItem:t=>{let i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){let i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){let i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){let i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}};DataStorage._Storage=DataStorage._GetStorage(),function(e){let Alphabet=class Alphabet{serialize(){let e={},t=Array(this._characterToIdx.size);return this._characterToIdx.forEach((e,i)=>{t[e]=i}),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){let t=JSON.parse(e),i=new Alphabet(t.characters);return i._insertionCosts=t.insertionCosts,i._deletionCosts=t.deletionCosts,i._substitutionCosts=t.substitutionCosts,i}constructor(e,t=null,i=null,r=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,r=null!=r?r:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=Array(e.length),this._deletionCosts=Array(e.length),this._substitutionCosts=Array(e.length);for(let n=0;nSequence._MAX_SEQUENCE_LENGTH)throw Error("Sequences longer than "+Sequence._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map(e=>this._alphabet.getCharacterIdx(e))}distance(e){return Sequence._Distance(this,e)}static _Distance(e,t){let i=e._alphabet;if(i!==t._alphabet)throw Error("Cannot Levenshtein compare Sequences built from different alphabets.");let r=e._characters,s=t._characters,n=r.length,a=s.length,o=Sequence._CostMatrix;o[0][0]=0;for(let e=0;eArray(Sequence._MAX_SEQUENCE_LENGTH+1)),e.Sequence=Sequence}(rh||(rh={}));let Trajectory=class Trajectory{serialize(){return JSON.stringify(this)}static Deserialize(e){let t=JSON.parse(e),i=new Trajectory(t._segmentLength);return i._points=t._points.map(e=>new rm.P(e._x,e._y,e._z)),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{let getT=()=>this._segmentLength/rm.P.Distance(this._points[t-1],e);for(let i=getT();i<=1;i=getT()){let r=this._points[t-1].scale(1-i);e.scaleAndAddToRef(i,r),this._points.push(r),++t}}}resampleAtTargetResolution(e){let t=new Trajectory(this.getLength()/e);return this._points.forEach(e=>{t.add(e)}),t}tokenize(e){let t=[],i=new rm.P;for(let r=2;r.98)&&(rm.P.CrossToRef(Trajectory._ForwardDir,Trajectory._InverseFromVec,Trajectory._UpDir),Trajectory._UpDir.normalize(),rm.y3.LookAtLHToRef(e,t,Trajectory._UpDir,Trajectory._LookMatrix),i.subtractToRef(t,Trajectory._FromToVec),Trajectory._FromToVec.normalize(),rm.P.TransformNormalToRef(Trajectory._FromToVec,Trajectory._LookMatrix,r),!0)}static _TokenizeSegment(e,t){Trajectory._BestMatch=0,Trajectory._Score=rm.P.Dot(e,t[0]),Trajectory._BestScore=Trajectory._Score;for(let i=1;iTrajectory._BestScore&&(Trajectory._BestMatch=i,Trajectory._BestScore=Trajectory._Score);return Trajectory._BestMatch}};Trajectory._ForwardDir=new rm.P,Trajectory._InverseFromVec=new rm.P,Trajectory._UpDir=new rm.P,Trajectory._FromToVec=new rm.P,Trajectory._LookMatrix=new rm.y3;let TrajectoryDescriptor=class TrajectoryDescriptor{serialize(){return JSON.stringify(this._sequences.map(e=>e.serialize()))}static Deserialize(e,t){let i=new TrajectoryDescriptor;return i._sequences=JSON.parse(e).map(e=>rh.Sequence.Deserialize(e,t)),i}static CreateFromTrajectory(e,t,i){return TrajectoryDescriptor.CreateFromTokenizationPyramid(TrajectoryDescriptor._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){let i=new TrajectoryDescriptor;return i._sequences=e.map(e=>new rh.Sequence(e,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=TrajectoryDescriptor._FINEST_DESCRIPTOR_RESOLUTION){let r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t=0;for(let i=0;ie.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){let i=JSON.parse(e),r=new TrajectoryClass;return r._descriptors=i.descriptors.map(e=>TrajectoryDescriptor.Deserialize(e,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){let e;this._centroidIdx=-1;let t=this._descriptors.map(t=>(e=0,this._descriptors.forEach(i=>{e+=t.distance(i)}),e));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,TrajectoryClass._MIN_AVERAGE_DISTANCE))}};TrajectoryClass._MIN_AVERAGE_DISTANCE=1;let Reflector=class Reflector{constructor(e,t,i){this._scene=e,rT.Y.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{let t=e.data;if(t.startsWith(Reflector._SERVER_PREFIX)){let e=t.substr(Reflector._SERVER_PREFIX.length);rT.Y.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),this._handleServerMessage(e);return}rT.Y.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{rT.Y.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&sceneSerializer_SceneSerializer.SerializeAsync(this._scene).then(e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)})}_handleClientMessage(){}};Reflector._SERVER_PREFIX="$$";let DynamicFloat32Array=class DynamicFloat32Array{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){let e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}};let h7="timestamp",h9="numPoints",ue=/\r/g;let PerformanceViewerCollector=class PerformanceViewerCollector{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{let e=rF.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength,r=0;if(i>0){let e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+PerformanceViewerCollector.NumberOfPointsOffset)+PerformanceViewerCollector.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())}),this.datasetObservable.hasObservers()){let i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new rf.he(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var r;return this._strategies.has(e)&&!t?void 0:(this._strategies.has(e)&&t&&(null===(r=this._strategies.get(e))||void 0===r||r.dispose(),this._strategies.delete(e)),this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0,s=t.onAfterRenderObservable.add(()=>{r=i,i=0}),n=this._customEventObservable.add(t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)});return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(n)}}},category:i}),{name:e})}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){let e=t(this._scene);if(this._strategies.has(e.id)){e.dispose();continue}this.datasets.ids.push(e.id),i&&(i=i.replace(RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255;i+=("0"+r.toString(16)).substr(-2)}return i}getCurrentSlice(){let e=rF.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=[e,t];this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasetObservable.hasObservers()&&i.push(t.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(i)}updateMetadata(e,t,i){let r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new DynamicFloat32Array(1800),this.datasets.ids.length=0,this.datasets.startingIndices=new DynamicFloat32Array(1800),this._datasetMeta.clear(),this._strategies.forEach(e=>e.dispose()),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){let i=e.replace(ue,"").split("\n").map(e=>e.split(",").filter(e=>e.length>0)).filter(e=>e.length>0),r=PerformanceViewerCollector.NumberOfPointsOffset;if(i.length<2)return!1;let s={ids:[],data:new DynamicFloat32Array(1800),startingIndices:new DynamicFloat32Array(1800)},[n,...a]=i;if(n.length<2||n[0]!==h7||n[r]!==h9)return!1;let o=new Map;for(let e=PerformanceViewerCollector.SliceDataOffset;ee.dispose()),this._strategies.clear(),!t)for(let e of this.datasets.ids){let t=o.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${h7},${h9}`;for(let t=0;t{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}};rN.x.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new PerformanceViewerCollector(this)),this._perfCollector};var ut=i(7521);function CreateObservableScheduler(e){let t=[],i=[],r=[],s=e.add(()=>{let e=t.length;for(let s=0;s{t.push(e),i.push(s),r.push(n)},dispose:()=>{e.remove(s)}}}rf.y$.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){let e=CreateObservableScheduler(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return(0,ut.sM)(e,this._coroutineScheduler)},rf.y$.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};let ui=`#ifdef GL_ES -precision highp float; -#endif -#define M_PI 3.1415926535897932384626433832795 -varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( -- sin( longitude )*sin( latitude ), -cos( latitude ), -- cos( longitude )*sin( latitude ) -);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;s_.v.ShadersStore.equirectangularPanoramaPixelShader=ui;let WebXRHitTestLegacy=class WebXRHitTestLegacy extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this._direction=new rm.P(0,0,-1),this._mat=new rm.y3,this._onSelectEnabled=!1,this._origin=new rm.P(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new rf.y$,this._onHitTestResults=e=>{let t=e.map(e=>{let t=rm.y3.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}});this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&WebXRHitTestLegacy.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",rW.w1.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(e=>{let t=r||(e=>!!e.hitMatrix);return e.filter(t)})}static XRHitTestWithSelectEvent(e,t){let i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);let r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;rm.y3.FromArrayToRef(t.transform.matrix,0,this._mat),rm.P.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),rm.P.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();let i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});WebXRHitTestLegacy.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}};WebXRHitTestLegacy.Name=webXRFeaturesManager_WebXRFeatureName.HIT_TEST,WebXRHitTestLegacy.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRHitTestLegacy.Name,(e,t)=>()=>new WebXRHitTestLegacy(e,t),WebXRHitTestLegacy.Version,!1);let ur=0;let WebXRAnchorSystem=class WebXRAnchorSystem extends WebXRAbstractFeature{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new rf.y$,this.onAnchorRemovedObservable=new rf.y$,this.onAnchorUpdatedObservable=new rf.y$,this._tmpVector=new rm.P,this._tmpQuaternion=new rm._f,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new rm.P,i=new rm._f){this._populateTmpTransformation(t,i);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{let t=await e.xrHitResult.createAnchor(r);return new Promise((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})})}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new rm._f,i=!1){this._populateTmpTransformation(e,t);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){let e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;let t=e.trackedAnchors;if(t){let i=this._trackedAnchors.filter(e=>!t.has(e.xrAnchor)).map(e=>{let t=this._trackedAnchors.indexOf(e);return t}),r=0;i.forEach(e=>{let t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++}),t.forEach(t=>{if(this._lastFrameDetected.has(t)){let i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new rm._f,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){rW.w1.Warn("Anchor could not be updated")}}else{let i={id:ur++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);let s=this._futureAnchors.filter(e=>e.nativeAnchor===t),n=s[0];n&&(n.resolve(r),n.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then(e=>{t.nativeAnchor=e},e=>{t.resolved=!0,t.reject(e)}),t.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new WebXRAnchorSystem(e,t),WebXRAnchorSystem.Version);let us=0;let WebXRPlaneDetector=class WebXRPlaneDetector extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new rf.y$,this.onPlaneRemovedObservable=new rf.y$,this.onPlaneUpdatedObservable=new rf.y$,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){let e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;let i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{let i={id:us++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}}),this._lastFrameDetected=i}}_init(){let internalInit=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){internalInit();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),internalInit()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(e=>{let t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new rm.P(e.x,e.y,e.z*t)});let r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new rm.y3;rm.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new WebXRPlaneDetector(e,t),WebXRPlaneDetector.Version);let WebXRBackgroundRemover=class WebXRBackgroundRemover extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new rf.y$}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){let t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper){if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){let i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){let i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{let i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(t=>t.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}};WebXRBackgroundRemover.Name=webXRFeaturesManager_WebXRFeatureName.BACKGROUND_REMOVER,WebXRBackgroundRemover.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRBackgroundRemover.Name,(e,t)=>()=>new WebXRBackgroundRemover(e,t),WebXRBackgroundRemover.Version,!0);let WebXRControllerPhysics=class WebXRControllerPhysics extends WebXRAbstractFeature{_createPhysicsImpostor(e){let t=this._options.physicsProperties.impostorType||physicsImpostor_PhysicsImpostor.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=sphereBuilder_CreateSphere("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new rm._f;let s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);let n=new physicsImpostor_PhysicsImpostor(r,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||rT.Y.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce(t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce(()=>{let i=new physicsImpostor_PhysicsImpostor(t.rootMesh,physicsImpostor_PhysicsImpostor.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new rm._f,this._tmpVector=new rm.P,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{let t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)})}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._options.enableHeadsetImpostor){let e=this._options.headsetImpostorParams||{impostorType:physicsImpostor_PhysicsImpostor.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=sphereBuilder_CreateSphere("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new rm._f,this._headsetMesh.isVisible=!1,this._headsetImpostor=new physicsImpostor_PhysicsImpostor(this._headsetMesh,e.impostorType,Object.assign({mass:0},e))}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){let t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties=Object.assign(Object.assign({},this._options.physicsProperties),e)}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),null===(t=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===t?void 0:t.linearVelocity){let e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(null===(i=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===i?void 0:i.angularVelocity){let e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(e=>{var t,i;let r=this._controllers[e],s=r.xrController.grip||r.xrController.pointer,n=r.oldPos||r.impostorMesh.position;if(null===(t=r.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){let e=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(n,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);n.copyFrom(s.position),this._debugMode&&console.log(this._tmpVector,"linear");let a=r.oldRotation||r.impostorMesh.rotationQuaternion;if(null===(i=r.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){let e=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!a.equalsWithEpsilon(s.rotationQuaternion)){a.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);let e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{let t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(e*(this._delta/1e3)))}r.impostor.setAngularVelocity(this._tmpVector)}a.copyFrom(s.rotationQuaternion),this._debugMode&&console.log(this._tmpVector,this._tmpQuaternion,"angular")})}_detachController(e){let t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}};WebXRControllerPhysics.Name=webXRFeaturesManager_WebXRFeatureName.PHYSICS_CONTROLLERS,WebXRControllerPhysics.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerPhysics.Name,(e,t)=>()=>new WebXRControllerPhysics(e,t),WebXRControllerPhysics.Version,!0);let WebXRHitTest=class WebXRHitTest extends WebXRAbstractFeature{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new rm.y3,this._tmpPos=new rm.P,this._tmpQuat=new rm._f,this._initHitTestSource=e=>{if(!e)return;let t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};if(this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),!i.space){rW.w1.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(i).then(e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new rf.y$,this.paused=!1,this.xrNativeFeatureName="hit-test",rW.w1.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){let e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then(e=>{this._transientXrHitTestSource=e})}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){let t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}if(this._transientXrHitTestSource){let t=e.getHitTestResultsForTransientInput(this._transientXrHitTestSource);t.forEach(e=>{this._processWebXRHitTestResult(e.results,e.inputSource)})}}}_processWebXRHitTestResult(e,t){let i=[];e.forEach(e=>{let r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;let s=r.transform.position,n=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(n.x,n.y,n.z,n.w),rm.y3.FromFloat32ArrayToRefScaled(r.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());let a={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(a)}),this.onHitTestResultObservable.notifyObservers(i)}};WebXRHitTest.Name=webXRFeaturesManager_WebXRFeatureName.HIT_TEST,WebXRHitTest.Version=2,WebXRFeaturesManager.AddWebXRFeature(WebXRHitTest.Name,(e,t)=>()=>new WebXRHitTest(e,t),WebXRHitTest.Version,!1);let WebXRFeaturePointSystem=class WebXRFeaturePointSystem extends WebXRAbstractFeature{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new rf.y$,this.onFeaturePointsUpdatedObservable=new rf.y$,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;let t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw Error("Received malformed feature point cloud of length: "+t.length);let e=t.length/5,i=[],r=[];for(let s=0;s0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}};WebXRFeaturePointSystem.Name=webXRFeaturesManager_WebXRFeatureName.FEATURE_POINTS,WebXRFeaturePointSystem.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRFeaturePointSystem.Name,e=>()=>new WebXRFeaturePointSystem(e),WebXRFeaturePointSystem.Version);let un=0;let WebXRMeshDetector=class WebXRMeshDetector extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new rf.y$,this.onMeshRemovedObservable=new rf.y$,this.onMeshUpdatedObservable=new rf.y$,this.xrNativeFeatureName="mesh-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach(e=>{this.onMeshRemovedObservable.notifyObservers(e)}),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;let i=null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes;if(i){let t=new Set;this._detectedMeshes.forEach((e,r)=>{i.has(r)||t.add(r)}),t.forEach(e=>{let t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))}),i.forEach(t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{let i={id:un++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}})}}catch(e){console.log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){if(t.xrMesh=e,t.worldParentNode=this._options.worldParentNode,this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=e.positions,t.normals=e.normals;else{t.positions=new Float32Array(e.positions.length);for(let i=0;i()=>new WebXRMeshDetector(e,t),WebXRMeshDetector.Version,!1),(th=ru||(ru={}))[th.NotReceived=0]="NotReceived",th[th.Waiting=1]="Waiting",th[th.Received=2]="Received";let WebXRImageTracking=class WebXRImageTracking extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new rf.y$,this.onTrackableImageFoundObservable=new rf.y$,this.onTrackedImageUpdatedObservable=new rf.y$,this._trackableScoreStatus=ru.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach(e=>{e.originalBitmap.close()}),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};let e=this.options.images.map(e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src));try{let t=await Promise.all(e);return this._originalTrackingRequest=t.map((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch(e){return rW.w1.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(!e.getImageTrackingResults||this._trackableScoreStatus===ru.Waiting)return;if(this._trackableScoreStatus===ru.NotReceived){this._checkScoresAsync();return}let t=e.getImageTrackingResults();for(let i of t){let t=!1,r=i.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=i,s.realWorldWidth!==i.measuredWidthInMeters&&(s.realWorldWidth=i.measuredWidthInMeters,t=!0);let n=e.getPose(i.imageSpace,this._xrSessionManager.referenceSpace);if(n){let e=s.transformationMatrix;rm.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t=!0}let a=i.trackingState,o="emulated"===a;s.emulated!==o&&(s.emulated=o,t=!0),t&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==ru.NotReceived)return;this._trackableScoreStatus=ru.Waiting;let e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||0===e.length){this._trackableScoreStatus=ru.NotReceived;return}for(let t=0;t0?ru.Received:ru.NotReceived}};WebXRImageTracking.Name=webXRFeaturesManager_WebXRFeatureName.IMAGE_TRACKING,WebXRImageTracking.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRImageTracking.Name,(e,t)=>()=>new WebXRImageTracking(e,t),WebXRImageTracking.Version,!1);let WebXRDomOverlay=class WebXRDomOverlay extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",rW.w1.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!!super.attach()&&!!this._xrSessionManager.session.domOverlayState&&null!==this._xrSessionManager.session.domOverlayState.type&&(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0)}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return rW.w1.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){let e=document.querySelector(this.options.element);if(null===e)return rW.w1.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}};WebXRDomOverlay.Name=webXRFeaturesManager_WebXRFeatureName.DOM_OVERLAY,WebXRDomOverlay.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRDomOverlay.Name,(e,t)=>()=>new WebXRDomOverlay(e,t),WebXRDomOverlay.Version,!1);let WebXRControllerMovement=class WebXRControllerMovement extends WebXRAbstractFeature{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){var i,r,s,n,a,o;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new rm._f,this._tmpRotationMatrix=rm.y3.Identity(),this._tmpTranslationDirection=new rm.P,this._tmpMovementTranslation=new rm.P,this._tempCacheQuaternion=new rm._f,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let initController=()=>{if(e.motionController)for(let i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(let t of i.allowedComponentTypes){let i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){let t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness||null===r)continue;let s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add(e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add(()=>{r.changes.pressed&&i.buttonChangedhandler(r.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};e.motionController?initController():e.onMotionControllerInitObservable.addOnce(()=>{initController()})}},!t||void 0===t.xrInput){rW.w1.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=WebXRControllerMovement.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(r=t.movementSpeed)&&void 0!==r?r:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(n=t.rotationEnabled)||void 0===n||n,rotationSpeed:null!==(a=t.rotationSpeed)&&void 0!==a?a:1,rotationThreshold:null!==(o=t.rotationThreshold)&&void 0!==o?o:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){let e=this._xrSessionManager.scene.getEngine().getDeltaTime(),t=.001*e*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=t,rm._f.RotationYawPitchRollToRef(t,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(rm._f.RotationYawPitchRollToRef(3*t,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(rm.y3.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),rm.P.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){let t=this._controllers[e];if(t){for(let e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}};WebXRControllerMovement.Name=webXRFeaturesManager_WebXRFeatureName.MOVEMENT,WebXRControllerMovement.REGISTRATIONS={default:[{allowedComponentTypes:[WebXRControllerComponent.THUMBSTICK_TYPE,WebXRControllerComponent.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[WebXRControllerComponent.THUMBSTICK_TYPE,WebXRControllerComponent.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},WebXRControllerMovement.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRControllerMovement.Name,(e,t)=>()=>new WebXRControllerMovement(e,t),WebXRControllerMovement.Version,!0);let WebXRLightEstimation=class WebXRLightEstimation extends WebXRAbstractFeature{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=rm.P.Up().negateInPlace(),this._lightColor=rg.Wo.White(),this._intensity=1,this._sphericalHarmonics=new SphericalHarmonics,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new rf.y$,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){let e=Date.now();if(e-this._cubeMapPollTime{this._xrLightProbe=e,this.options.disableCubeMapReflection||(!this._reflectionCubeMap&&(this._reflectionCubeMap=new baseTexture_BaseTexture(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))}),!0}detach(){let e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){let e=Date.now();if(e-this._lightEstimationPollTime()=>new WebXRLightEstimation(e,t),WebXRLightEstimation.Version,!1);let WebXREyeTracking=class WebXREyeTracking extends WebXRAbstractFeature{constructor(e){super(e),this.onEyeTrackingStartedObservable=new rf.y$,this.onEyeTrackingEndedObservable=new rf.y$,this.onEyeTrackingFrameUpdateObservable=new rf.y$,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new ray_Ray(rm.P.Zero(),rm.P.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){let t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z);let e=t.transform.orientation;rm.jp.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?rm.P.RightHandedForwardReadOnly.rotateByQuaternionToRef(rm.jp.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,rm.jp.Quaternion[0].z*=-1,rm.jp.Quaternion[0].w*=-1,rm.P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(rm.jp.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}};WebXREyeTracking.Name=webXRFeaturesManager_WebXRFeatureName.EYE_TRACKING,WebXREyeTracking.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXREyeTracking.Name,e=>()=>new WebXREyeTracking(e),WebXREyeTracking.Version,!1);let CircleBuffer=class CircleBuffer{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}};let FirstStepDetector=class FirstStepDetector{constructor(){this._samples=new CircleBuffer(20),this._entropy=0,this.onFirstStepDetected=new rf.y$}update(e,t,i,r){let s,n;this._samples.push(e,t);let a=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=rm.FM.Distance(a,this._samples.at(1)),this._entropy>this._entropyThreshold)return;for(s=this._samePointCheckStartIdx;so&&(l=t,o=e);if(os*this._squaredProjectionDistanceThreshold)return;let p=rm.jp.Vector3[0];p.set(i,r,0);let _=rm.jp.Vector3[1];_.set(u.x,u.y,0);let f=rm.P.Cross(p,_).z>0,m=a.clone(),g=a.clone();h.subtractToRef(a,u),f?(u.scaleAndAddToRef(this._axisToApexShrinkFactor,m),u.scaleAndAddToRef(this._axisToApexExtendFactor,g)):(u.scaleAndAddToRef(this._axisToApexExtendFactor,m),u.scaleAndAddToRef(this._axisToApexShrinkFactor,g)),this.onFirstStepDetected.notifyObservers({leftApex:m,rightApex:g,currentPosition:a,currentStepDirection:f?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),!(this._axisLength<.03))}get _vitalityThreshold(){return .1}get forward(){return this._forward}};let Walker=class Walker{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new FirstStepDetector,this._walker=null,this._movement=new rm.FM,this._millisecondsSinceLastUpdate=Walker._MillisecondsPerUpdate,this.movementThisFrame=rm.P.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(e=>{this._walker||(this._walker=new WalkingTracker(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add(()=>{console.log("Footfall!")}),this._walker.onMovement.add(e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)}))})}update(e,t){if(t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=Walker._MillisecondsPerUpdate){if(this._millisecondsSinceLastUpdate-=Walker._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker){let t=this._walker.update(e.x,e.z);t||(this._walker=null)}this._movement.scaleInPlace(.85)}this.movementThisFrame.set(this._movement.x,0,this._movement.y)}};let WebXRWalkingLocomotion=class WebXRWalkingLocomotion extends WebXRAbstractFeature{static get Name(){return webXRFeaturesManager_WebXRFeatureName.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new rm.P,this._forward=new rm.P,this._position=new rm.P,this._movement=new rm.P,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&rT.Y.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!!(this.isCompatible&&super.attach())&&(this._walker=new Walker(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){let t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;let i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||rm.P.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}};WebXRFeaturesManager.AddWebXRFeature(WebXRWalkingLocomotion.Name,(e,t)=>()=>new WebXRWalkingLocomotion(e,t),WebXRWalkingLocomotion.Version,!1);let WebXRCompositionLayerWrapper=class WebXRCompositionLayerWrapper extends WebXRLayerWrapper{constructor(e,t,i,r,s,n){super(e,t,i,r,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=n}};let WebXRCompositionLayerRenderTargetTextureProvider=class WebXRCompositionLayerRenderTargetTextureProvider extends WebXRLayerRenderTargetTextureProvider{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,r,s,n;let a=this._lastSubImages.get(t),o="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(r=e.colorTextureHeight)&&void 0!==r?r:e.textureHeight;if(!this._renderTargetTextures[o]||(null==a?void 0:a.textureWidth)!==l||(null==a?void 0:a.textureHeight)!==h){let t;let i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,r=null!==(n=e.depthStencilTextureHeight)&&void 0!==n?n:h;(l===i||h===r)&&(t=e.depthStencilTexture),this._renderTargetTextures[o]=this._createRenderTargetTexture(l,h,null,e.colorTexture,t,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:l,framebufferHeight:h}}return this._lastSubImages.set(t,e),this._renderTargetTextures[o]}_getSubImageForEye(e){let t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){let t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,r;let s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,n=null!==(r=t.colorTextureWidth)&&void 0!==r?r:t.textureHeight,a=t.viewport;e.x=a.x/s,e.y=a.y/n,e.width=a.width/s,e.height=a.height/n}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}};let WebXRProjectionLayerWrapper=class WebXRProjectionLayerWrapper extends WebXRCompositionLayerWrapper{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,e=>new WebXRProjectionLayerRenderTargetTextureProvider(e,i,this)),this.layer=e}};let WebXRProjectionLayerRenderTargetTextureProvider=class WebXRProjectionLayerRenderTargetTextureProvider extends WebXRCompositionLayerRenderTargetTextureProvider{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){let t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}};let ua={},uo={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};let WebXRLayers=class WebXRLayers extends WebXRAbstractFeature{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;let t=Object.assign({},uo),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return!!super.detach()&&(this._existingLayers.length=0,!0)}createXRWebGLLayer(e=ua){let t=new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e);return new WebXRWebGLLayerWrapper(t)}createProjectionLayer(e=uo,t=!1){if(t&&"texture-array"!==e.textureType)throw Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");let i=this._xrWebGLBinding.createProjectionLayer(e);return new WebXRProjectionLayerWrapper(i,t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;let t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map(e=>e.layer),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}};WebXRLayers.Name=webXRFeaturesManager_WebXRFeatureName.LAYERS,WebXRLayers.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRLayers.Name,(e,t)=>()=>new WebXRLayers(e,t),WebXRLayers.Version,!1);let WebXRDepthSensing=class WebXRDepthSensing extends WebXRAbstractFeature{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){var e,t;if(!this._cachedWebGLTexture)return null;let i=this._xrSessionManager.scene.getEngine(),r=new r5.l(i,r5.S.Unknown);return r.isCube=!1,r.invertY=!1,r._useSRGBBuffer=!1,r.format="ushort"===this.depthDataFormat?2:5,r.generateMipMaps=!1,r.type="ushort"===this.depthDataFormat?5:1,r.samplingMode=7,r.width=null!==(e=this.width)&&void 0!==e?e:0,r.height=null!==(t=this.height)&&void 0!==t?t:0,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new nj.B(this._cachedWebGLTexture,i._gl),r}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new rf.y$,this.xrNativeFeatureName="depth-sensing",rW.w1.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){if(!super.attach(e))return!1;let t=null==this._xrSessionManager.session.depthDataFormat||null==this._xrSessionManager.session.depthUsage;return!t&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;null===(e=this._cachedDepthImageTexture)||void 0===e||e.dispose()}_onXRFrame(e){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(let t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:rW.w1.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{data:s,width:n,height:a,rawValueToMeters:o,getDepthInMeters:l}=r;switch(this._width=n,this._height=a,this._rawValueToMeters=o,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=rawTexture_RawTexture.CreateRTexture(null,n,a,this._xrSessionManager.scene,!1,!0,texture_Texture.NEAREST_SAMPLINGMODE,rq.D.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(e=>e*o));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(e=>e*o))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{texture:s,width:n,height:a}=r;this._width=n,this._height=a,this._cachedWebGLTexture=s;let o=this._xrSessionManager.scene,l=o.getEngine(),h=l.wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=rawTexture_RawTexture.CreateRTexture(null,n,a,o,!1,!0,texture_Texture.NEAREST_SAMPLINGMODE,"ushort"===i?rq.D.TEXTURETYPE_UNSIGNED_BYTE:rq.D.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=h}getXRSessionInitExtension(){let e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise(i=>{if(e&&t){let e=this.options.usagePreference.map(e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),t=this.options.dataFormatPreference.map(e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}});i({depthSensing:{usagePreference:e,dataFormatPreference:t}})}else i({})})}};WebXRDepthSensing.Name=webXRFeaturesManager_WebXRFeatureName.DEPTH_SENSING,WebXRDepthSensing.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRDepthSensing.Name,(e,t)=>()=>new WebXRDepthSensing(e,t),WebXRDepthSensing.Version,!1);let ul=`precision highp float; -#define CUSTOM_FRAGMENT_BEGIN -varying vec4 clipPos;varying vec4 previousClipPos; -#define CUSTOM_FRAGMENT_DEFINITIONS -void main(void) { -#define CUSTOM_FRAGMENT_MAIN_BEGIN -highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; -#define CUSTOM_FRAGMENT_MAIN_END -}`;s_.v.ShadersStore.velocityPixelShader=ul;let uh=`#define CUSTOM_VERTEX_BEGIN -#define VELOCITY -attribute vec3 position; -#include -uniform mat4 viewProjection;uniform mat4 previousViewProjection; -#ifdef MULTIVIEW -uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; -#endif -varying vec4 clipPos;varying vec4 previousClipPos; -#define CUSTOM_VERTEX_DEFINITIONS -void main(void) { -#define CUSTOM_VERTEX_MAIN_BEGIN -vec3 positionUpdated=position; -#include -vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); -#ifdef MULTIVIEW -if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} -#elif -clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; -#endif -#define CUSTOM_VERTEX_MAIN_END -}`;s_.v.ShadersStore.velocityVertexShader=uh;let XRSpaceWarpRenderTarget=class XRSpaceWarpRenderTarget extends renderTargetTexture_RenderTargetTexture{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[rm.y3.Identity(),rm.y3.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new shaderMaterial_ShaderMaterial("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)}),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;let i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach(e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(e=>{e[0].material=e[1]})}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}};let WebXRSpaceWarpRenderTargetTextureProvider=class WebXRSpaceWarpRenderTargetTextureProvider{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){let t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw Error('For Space Warp, the base layer type should "XRProjectionLayer".');let i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw Error("Engine is disposed");let n=new XRSpaceWarpRenderTarget(r,s,this._scene,{width:e,height:t}),a=n.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=r,a._depthStencilTextureArray=s,n.disableRescaling(),n.renderListPredicate=()=>!0,n}_getRenderTargetForSubImage(e,t){let i=this._lastSubImages.get(t),r=this._renderTargetTextures.get(t.eye),s=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return r&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==n||(r=this._createRenderTargetTexture(s,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){let i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){let t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){let t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}};let WebXRSpaceWarp=class WebXRSpaceWarp extends WebXRAbstractFeature{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[webXRFeaturesManager_WebXRFeatureName.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new WebXRSpaceWarpRenderTargetTextureProvider(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;let i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}};WebXRSpaceWarp.Name=webXRFeaturesManager_WebXRFeatureName.SPACE_WARP,WebXRSpaceWarp.Version=1,WebXRFeaturesManager.AddWebXRFeature(WebXRSpaceWarp.Name,e=>()=>new WebXRSpaceWarp(e),WebXRSpaceWarp.Version,!1);let WebXRGenericHandController=class WebXRGenericHandController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,uu[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}};WebXRMotionControllerManager.RegisterController("generic-hand-select-grasp",(e,t)=>new WebXRGenericHandController(t,e.gamepad,e.handedness));let uu={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};let WebXRMicrosoftMixedRealityController=class WebXRMicrosoftMixedRealityController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,uc["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";e="left"===this.handedness?WebXRMicrosoftMixedRealityController.MODEL_LEFT_FILENAME:WebXRMicrosoftMixedRealityController.MODEL_RIGHT_FILENAME;let t=WebXRMicrosoftMixedRealityController.MODEL_BASE_URL+"default/";return{filename:e,path:t}}_getModelLoadingConstraints(){let e=sceneLoader_SceneLoader.IsPluginForExtensionAvailable(".glb");return e||rT.Y.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){let i=this._mapping.buttons[e],r=i.rootNodeName;if(!r){rT.Y.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);return}let s=this._getChildByName(this.rootMesh,r);if(!s){rT.Y.Warn("Missing button mesh with name: "+r);return}if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){let t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add(e=>{this._lerpTransform(i,e.value)},void 0,!0)}else rT.Y.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(e=>{let t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach(i=>{if(!this.rootMesh)return;let r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);if(!s){rT.Y.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add(e=>{let t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)},void 0,!0):rT.Y.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){let t;this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew WebXRMicrosoftMixedRealityController(t,e.gamepad,e.handedness));let uc={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};let WebXROculusTouchMotionController=class WebXROculusTouchMotionController extends WebXRAbstractMotionController{constructor(e,t,i,r=!1,s=!1){super(e,ud[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";e="left"===this.handedness?WebXROculusTouchMotionController.MODEL_LEFT_FILENAME:WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME;let t=this._isQuest()?WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL:WebXROculusTouchMotionController.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){let t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach(e=>{let r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add(r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-(.2*r.value),this._modelRootNode.getChildren()[3].position.y=-(.005*r.value),this._modelRootNode.getChildren()[3].position.z=-(.005*r.value));return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=rm._f.FromEulerAngles(0,Math.PI,0)),e.forEach(e=>{e.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}};WebXROculusTouchMotionController.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",WebXROculusTouchMotionController.MODEL_LEFT_FILENAME="left.babylon",WebXROculusTouchMotionController.MODEL_RIGHT_FILENAME="right.babylon",WebXROculusTouchMotionController.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",WebXRMotionControllerManager.RegisterController("oculus-touch",(e,t)=>new WebXROculusTouchMotionController(t,e.gamepad,e.handedness)),WebXRMotionControllerManager.RegisterController("oculus-touch-legacy",(e,t)=>new WebXROculusTouchMotionController(t,e.gamepad,e.handedness,!0));let ud={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};let WebXRHTCViveMotionController=class WebXRHTCViveMotionController extends WebXRAbstractMotionController{constructor(e,t,i){super(e,up[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){let e=WebXRHTCViveMotionController.MODEL_FILENAME,t=WebXRHTCViveMotionController.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add(t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-(.15*t.value);return;case"xr-standard-touchpad":case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new rV.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=rm._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}};WebXRHTCViveMotionController.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",WebXRHTCViveMotionController.MODEL_FILENAME="wand.babylon",WebXRMotionControllerManager.RegisterController("htc-vive",(e,t)=>new WebXRHTCViveMotionController(t,e.gamepad,e.handedness));let up={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};let NativeXRFrame=class NativeXRFrame{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>{var e;return null!==(e=this._nativeImpl._imageTrackingResults)&&void 0!==e?e:[]}}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;let i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];let r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw Error("This function is not available in Babylon Native")}};RegisterNativeTypeAsync("NativeXRFrame",NativeXRFrame),(tu=rc||(rc={}))[tu.Input=0]="Input",tu[tu.Output=1]="Output";let FlowGraphConnection=class FlowGraphConnection{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=(0,rZ.f)(),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 Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName(),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){let i=rW.w1.Instantiate(e.className),r=new i(e.name,e._connectionType,t);return r.deserialize(e),r}};let RichType=class RichType{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new RichType(e.typeName,e.defaultValue)}};let u_=new RichType("any",void 0),uf=new RichType("string",""),um=new RichType("number",0),ug=new RichType("boolean",!1),uv=new RichType("Vector2",rm.FM.Zero()),ux=new RichType("Vector3",rm.P.Zero()),uT=new RichType("Vector4",rm.Lt.Zero()),uS=new RichType("Matrix",rm.y3.Identity()),uC=new RichType("Color3",rg.Wo.Black()),uE=new RichType("Color4",new rg.HE(0,0,0,0)),ub=new RichType("Quaternion",rm._f.Identity());function getRichTypeFromValue(e){switch(typeof e){case"string":return uf;case"number":return um;case"boolean":return ug;case"object":if(e instanceof rm.FM)return uv;if(e instanceof rm.P)return ux;if(e instanceof rm.Lt)return uT;if(e instanceof rg.Wo)return uC;else if(e instanceof rg.HE)return uE;else if(e instanceof rm._f)return ub;else return u_;default:return u_}}let FlowGraphDataConnection=class FlowGraphDataConnection extends FlowGraphConnection{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return this.connectionType===rc.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===rc.Output?(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){let i=FlowGraphConnection.Parse(e,t);return i.richType=RichType.Parse(e.richType),i}};(0,rv.H)("FGDataConnection",FlowGraphDataConnection);let FlowGraphBlock=class FlowGraphBlock{constructor(e){this.config=e,this.uniqueId=(0,rZ.f)(),this.configure()}configure(){var e,t;this.name=null!==(t=null===(e=this.config)||void 0===e?void 0:e.name)&&void 0!==t?t:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}_registerDataInput(e,t){let i=new FlowGraphDataConnection(e,rc.Input,this,t);return this.dataInputs.push(i),i}_registerDataOutput(e,t){let i=new FlowGraphDataConnection(e,rc.Output,this,t);return this.dataOutputs.push(i),i}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.config=this.config,e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName(),this.dataInputs)){let i={};t.serialize(i),e.dataInputs.push(i)}for(let t of this.dataOutputs){let i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e){let t=rW.w1.Instantiate(e.className),i=new t(e.config);i.uniqueId=e.uniqueId;for(let t=0;t{t(r,i,e._userVariables)}),e._connectionValues={},this._connectionValues.forEach((i,r)=>{t(r,i,e._connectionValues)})}getClassName(){return"FGContext"}static Parse(e={},t,i=defaultValueParseFunction){let r=t.createContext();for(let t in r.uniqueId=e.uniqueId,e._userVariables){let s=i(t,e._userVariables,r._configuration.scene);r._userVariables.set(t,s)}for(let t in e._connectionValues){let s=i(t,e._connectionValues,r._configuration.scene);r._connectionValues.set(t,s)}return r}};(0,rH.gn)([(0,rb.qC)()],FlowGraphContext.prototype,"uniqueId",void 0);let FlowGraphVariableDefinitions=class FlowGraphVariableDefinitions{constructor(){this._definitions=new Map}defineVariable(e,t){this._definitions.set(e,t)}generateContext(e){let t=new FlowGraphContext(e);return this._definitions.forEach((e,i)=>{t.setVariable(i,e)}),t}serialize(e){this._definitions.forEach((t,i)=>{e[i]=t})}deserialize(e){for(let t in this._definitions.clear(),e)this._definitions.set(t,e[t])}};(tc=rd||(rd={}))[tc.Stopped=0]="Stopped",tc[tc.Started=1]="Started";let FlowGraph=class FlowGraph{constructor(e){this.variableDefinitions=new FlowGraphVariableDefinitions,this._eventBlocks=[],this._executionContexts=[],this.state=rd.Stopped,this._scene=e.scene,this._eventCoordinator=e.eventCoordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){let e=this.variableDefinitions.generateContext({scene:this._scene,eventCoordinator:this._eventCoordinator});return this._executionContexts.push(e),e}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==rd.Started)for(let e of(this.state=rd.Started,0===this._executionContexts.length&&this.createContext(),this._executionContexts))for(let t of this._eventBlocks)t._startPendingTasks(e)}dispose(){if(this.state!==rd.Stopped){for(let e of(this.state=rd.Stopped,this._executionContexts))e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}visitAllBlocks(e){let t=[],i=new Set;for(let e of this._eventBlocks)t.push(e),i.add(e.uniqueId);for(;t.length>0;){let r=t.pop();for(let s of(e(r),r.dataInputs))for(let e of s._connectedPoint)i.has(e._ownerBlock.uniqueId)||(t.push(e._ownerBlock),i.add(e._ownerBlock.uniqueId));if(r instanceof FlowGraphExecutionBlock)for(let e of r.signalOutputs)for(let r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId))}}serialize(e={},t){for(let i of(e.variableDefinitions={},this.variableDefinitions.serialize(e.variableDefinitions),e.allBlocks=[],this.visitAllBlocks(t=>{let i={};t.serialize(i),e.allBlocks.push(i)}),e.executionContexts=[],this._executionContexts)){let r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(let i of e)for(let e of i.dataOutputs)if(e.uniqueId===t)return e;throw Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(let i of e)if(i instanceof FlowGraphExecutionBlock){for(let e of i.signalInputs)if(e.uniqueId===t)return e}throw Error("Could not find signal in connection with unique id "+t)}static Parse(e,t,i){let r=t.createGraph();r.variableDefinitions.deserialize(e.variableDefinitions);let s=[];for(let t of e.allBlocks){let e=FlowGraphBlock.Parse(t);s.push(e),e instanceof FlowGraphEventBlock&&r.addEventBlock(e)}for(let e of s){for(let t of e.dataInputs)for(let e of t.connectedPointIds){let i=FlowGraph.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof FlowGraphExecutionBlock)for(let t of e.signalOutputs)for(let e of t.connectedPointIds){let i=FlowGraph.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(let t of e.executionContexts)FlowGraphContext.Parse(t,r,i);return r}};let FlowGraphEventCoordinator=class FlowGraphEventCoordinator{constructor(){this._customEventsMap=new Map}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new rf.y$,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){let i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}};let FlowGraphCoordinator=class FlowGraphCoordinator{constructor(e){var t;this._config=e,this._flowGraphs=[],this.eventCoordinator=new FlowGraphEventCoordinator,this._config.scene.onDisposeObservable.add(()=>{this.dispose()});let i=null!==(t=FlowGraphCoordinator.SceneCoordinators.get(this._config.scene))&&void 0!==t?t:[];i.push(this)}createGraph(){let e=new FlowGraph({scene:this._config.scene,eventCoordinator:this.eventCoordinator});return this._flowGraphs.push(e),e}removeGraph(e){let t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){var e;this._flowGraphs.forEach(e=>e.dispose()),this._flowGraphs.length=0;let t=null!==(e=FlowGraphCoordinator.SceneCoordinators.get(this._config.scene))&&void 0!==e?e:[],i=t.indexOf(this);-1!==i&&t.splice(i,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{let r={};i.serialize(r,t),e._flowGraphs.push(r)})}static Parse(e,t,i){var r;let s=new FlowGraphCoordinator({scene:t});return null===(r=e._flowGraphs)||void 0===r||r.forEach(e=>{FlowGraph.Parse(e,s,i)}),s}};FlowGraphCoordinator.SceneCoordinators=new Map;let FlowGraphWithOnDoneExecutionBlock=class FlowGraphWithOnDoneExecutionBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onDone=this._registerSignalOutput("onDone")}};let FlowGraphLogBlock=class FlowGraphLogBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.message=this._registerDataInput("message",u_)}_execute(e){let t=this.message.getValue(e);console.log(t),this.onDone._activateSignal(e)}getClassName(){return"FGLogBlock"}};(0,rv.H)("FGLogBlock",FlowGraphLogBlock);let FlowGraphSetVariableBlock=class FlowGraphSetVariableBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.variableName=this._registerDataInput("variableName",uf),this.input=this._registerDataInput("input",u_)}_execute(e){let t=this.variableName.getValue(e),i=this.input.getValue(e);e.setVariable(t,i),this.onDone._activateSignal(e)}getClassName(){return"FGSetVariableBlock"}};(0,rv.H)("FGSetVariableBlock",FlowGraphSetVariableBlock);let FlowGraphSetPropertyBlock=class FlowGraphSetPropertyBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.target=this._registerDataInput("target",u_),this.property=this._registerDataInput("property",uf),this.value=this._registerDataInput("value",u_)}_setProperty(e,t,i){let r=t.split("."),s=e;for(let e=0;er)this.timeRemaining.setValue(0,e),this.onDone._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s);else{let t=r-(s-i);this.timeRemaining.setValue(t,e)}}getClassName(){return"FGThrottleBlock"}};(0,rv.H)("FGThrottleBlock",FlowGraphThrottleBlock);let FlowGraphTimerBlock=class FlowGraphTimerBlock extends FlowGraphAsyncExecutionBlock{constructor(e){super(e),this.timeout=this._registerDataInput("timeout",um),this.onTimerDone=this._registerSignalOutput("onTimerDone")}_preparePendingTasks(e){let t=this.timeout.getValue(e);if(void 0!==t&&t>=0){let i=e._getExecutionVariable(this,"runningTimers")||[],r=e.configuration.scene,s=new AdvancedTimer({timeout:t,contextObservable:r.onBeforeRenderObservable,onEnded:()=>this._onEnded(s,e)});s.start(),i.push(s),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onEnded(e,t){let i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):rW.w1.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.onTimerDone._activateSignal(t)}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"runningTimers")||[];for(let e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return"FGTimerBlock"}};(0,rv.H)("FGTimerBlock",FlowGraphTimerBlock);let FlowGraphMultiGateBlock=class FlowGraphMultiGateBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this._registerDataOutput("currentIndex",um)}configure(){super.configure(),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)n=0;else if(n>=this.config.numberOutputFlows&&!this.config.loop)return;if(0===(s=s.filter(e=>e!==n)).length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(e=>e)){this.onDone._activateSignal(e);for(let e=0;e=i&&(this.onDone._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}};(0,rv.H)("FGDebounceBlock",FlowGraphDebounceBlock);let FlowGraphFlipFlopBlock=class FlowGraphFlipFlopBlock extends FlowGraphExecutionBlock{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this._registerDataOutput("isOn",ug)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}};(0,rv.H)("FGFlipFlopBlock",FlowGraphFlipFlopBlock);let FlowGraphPlayAnimationBlock=class FlowGraphPlayAnimationBlock extends FlowGraphAsyncExecutionBlock{constructor(e){super(e),this.target=this._registerDataInput("target",u_),this.animation=this._registerDataInput("animation",u_),this.speed=this._registerDataInput("speed",um),this.loop=this._registerDataInput("loop",ug),this.from=this._registerDataInput("from",um),this.to=this._registerDataInput("to",um),this.onAnimationEnd=this._registerSignalOutput("onAnimationEnd"),this.runningAnimatable=this._registerDataOutput("runningAnimatable",u_)}_preparePendingTasks(e){var t;let i=this.target.getValue(e),r=this.animation.getValue(e);if(!i||!r)throw Error("Cannot play animation without target or animation");let s=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[],n=this.runningAnimatable.getValue(e);if(n&&n.paused)n.restart();else{let t=e.configuration.scene,n=t.beginDirectAnimation(i,[r],this.from.getValue(e),this.to.getValue(e),this.loop.getValue(e),this.speed.getValue(e),()=>this._onAnimationEnd(n,e));this.runningAnimatable.setValue(n,e),s.push(n)}e._setExecutionVariable(this,"runningAnimatables",s)}_execute(e){this._startPendingTasks(e),this.onDone._activateSignal(e)}_onAnimationEnd(e,t){var i;let r=null!==(i=t._getExecutionVariable(this,"runningAnimatables"))&&void 0!==i?i:[],s=r.indexOf(e);-1!==s&&r.splice(s,1),t._removePendingBlock(this),this.onAnimationEnd._activateSignal(t)}_cancelPendingTasks(e){var t;let i=null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[];for(let e of i)e.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return"FGPlayAnimationBlock"}};(0,rv.H)("FGPlayAnimationBlock",FlowGraphPlayAnimationBlock);let FlowGraphStopAnimationBlock=class FlowGraphStopAnimationBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.animationToStop=this._registerDataInput("animationToStop",u_)}_execute(e){let t=this.animationToStop.getValue(e);t.stop(),this.onDone._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}};(0,rv.H)("FGStopAnimationBlock",FlowGraphStopAnimationBlock);let FlowGraphPauseAnimationBlock=class FlowGraphPauseAnimationBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.animationToPause=this._registerDataInput("animationToPause",u_)}_execute(e){let t=this.animationToPause.getValue(e);t.pause(),this.onDone._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}};(0,rv.H)("FGPauseAnimationBlock",FlowGraphPauseAnimationBlock);let FlowGraphPlayAudioBlock=class FlowGraphPlayAudioBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.audio=this._registerDataInput("audio",u_)}_execute(e,t){let i=this.audio.getValue(e);i instanceof Sound&&i.play(),this.onDone._activateSignal(e)}getClassName(){return"FGPlayAudioBlock"}};(0,rv.H)("FGPlayAudioBlock",FlowGraphPlayAudioBlock);let FlowGraphStopAudioBlock=class FlowGraphStopAudioBlock extends FlowGraphWithOnDoneExecutionBlock{constructor(e){super(e),this.audio=this._registerDataInput("audio",u_)}_execute(e,t){let i=this.audio.getValue(e);i instanceof Sound&&i.stop()}getClassName(){return"FGStopAudioBlock"}};(0,rv.H)("FGStopAudioBlock",FlowGraphStopAudioBlock);let FlowGraphConditionalDataBlock=class FlowGraphConditionalDataBlock extends FlowGraphBlock{constructor(e){super(e),this.condition=this._registerDataInput("condition",ug),this.trueValue=this._registerDataInput("trueValue",u_),this.falseValue=this._registerDataInput("falseValue",u_),this.output=this._registerDataOutput("output",u_)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}};(0,rv.H)("FGConditionalDataBlock",FlowGraphConditionalDataBlock);let FlowGraphGetVariableBlock=class FlowGraphGetVariableBlock extends FlowGraphBlock{constructor(e){super(e),this.variableName=this._registerDataInput("variableName",uf),this.output=this._registerDataOutput("output",u_)}_updateOutputs(e){let t=this.variableName.getValue(e);e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return"FGGetVariableBlock"}};(0,rv.H)("FGGetVariableBlock",FlowGraphGetVariableBlock);let FlowGraphCoordinateTransformBlock=class FlowGraphCoordinateTransformBlock extends FlowGraphBlock{constructor(e){super(e),this.sourceSystem=this._registerDataInput("sourceSystem",u_),this.destinationSystem=this._registerDataInput("destinationSystem",u_),this.inputCoordinates=this._registerDataInput("inputCoordinates",ux),this.outputCoordinates=this._registerDataOutput("outputCoordinates",ux)}_updateOutputs(e){let t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),n=i.getWorldMatrix(),a=rm.jp.Matrix[0].copyFrom(n);a.invert();let o=rm.jp.Matrix[1];a.multiplyToRef(s,o);let l=this.outputCoordinates.getValue(e);rm.P.TransformCoordinatesToRef(r,o,l)}getClassName(){return"FGCoordinateTransformBlock"}};(0,rv.H)("FGCoordinateTransformBlock",FlowGraphCoordinateTransformBlock);let FlowGraphConstantBlock=class FlowGraphConstantBlock extends FlowGraphBlock{constructor(e){super(e),this.config=e,this.output=this._registerDataOutput("output",getRichTypeFromValue(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}};(0,rv.H)("FGConstantBlock",FlowGraphConstantBlock);let uy="cachedOperationValue",uP="cachedExecutionId";let FlowGraphCachedOperationBlock=class FlowGraphCachedOperationBlock extends FlowGraphBlock{constructor(e,t){super(t),this.output=this._registerDataOutput("output",e)}_updateOutputs(e){let t=e._getExecutionVariable(this,uP),i=e._getExecutionVariable(this,uy);if(void 0!==i&&t===e.executionId)this.output.setValue(i,e);else{let t=this._doOperation(e);e._setExecutionVariable(this,uy,t),e._setExecutionVariable(this,uP,e.executionId),this.output.setValue(t,e)}}};let FlowGraphBinaryOperationBlock=class FlowGraphBinaryOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r,s,n){super(i,n),this._operation=r,this._className=s,this.leftInput=this._registerDataInput("leftInput",e),this.rightInput=this._registerDataInput("rightInput",t)}_doOperation(e){return this._operation(this.leftInput.getValue(e),this.rightInput.getValue(e))}getClassName(){return this._className}};let FlowGraphUnaryOperationBlock=class FlowGraphUnaryOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.input=this._registerDataInput("input",e)}_doOperation(e){return this._operation(this.input.getValue(e))}getClassName(){return this._className}};let uR="FGBitwise",uA="AndBlock",uI="OrBlock",uM="XorBlock",uD="NotBlock",uO="LeftShiftBlock",uN="RightShiftBlock",uF="CountLeadingZerosBlock",uB="CountTrailingZerosBlock";let FlowGraphBitwiseAndBlock=class FlowGraphBitwiseAndBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e&t,`${uR}${uA}`,e)}};(0,rv.H)(`${uR}${uA}`,FlowGraphBitwiseAndBlock);let FlowGraphBitwiseOrBlock=class FlowGraphBitwiseOrBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e|t,`${uR}${uI}`,e)}};(0,rv.H)(`${uR}${uI}`,FlowGraphBitwiseOrBlock);let FlowGraphBitwiseXorBlock=class FlowGraphBitwiseXorBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e^t,`${uR}${uM}`,e)}};(0,rv.H)(`${uR}${uM}`,FlowGraphBitwiseXorBlock);let FlowGraphBitwiseNotBlock=class FlowGraphBitwiseNotBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>~e,`${uR}${uD}`,e)}};(0,rv.H)(`${uR}${uD}`,FlowGraphBitwiseNotBlock);let FlowGraphBitwiseLeftShiftBlock=class FlowGraphBitwiseLeftShiftBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e<e>>t,`${uR}${uN}`,e)}};(0,rv.H)(`${uR}${uN}`,FlowGraphBitwiseRightShiftBlock);let FlowGraphCountLeadingZerosBlock=class FlowGraphCountLeadingZerosBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.clz32(e),`${uR}${uF}`,e)}};(0,rv.H)(`${uR}${uF}`,FlowGraphCountLeadingZerosBlock);let FlowGraphCountTrailingZerosBlock=class FlowGraphCountTrailingZerosBlock extends FlowGraphUnaryOperationBlock{_ctrz(e){return 0==(e>>>=0)?32:31-Math.clz32(e&=-e)}constructor(e){super(um,um,e=>this._ctrz(e),`${uR}${uB}`,e)}};(0,rv.H)(`${uR}${uB}`,FlowGraphCountTrailingZerosBlock);let uL="FGLogic",uw="AndBlock",uU="OrBlock",uV="NotBlock";let FlowGraphLogicAndBlock=class FlowGraphLogicAndBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(ug,ug,ug,(e,t)=>e&&t,`${uL}${uw}`,e)}};(0,rv.H)(`${uL}${uw}`,FlowGraphLogicAndBlock);let FlowGraphLogicOrBlock=class FlowGraphLogicOrBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(ug,ug,ug,(e,t)=>e||t,`${uL}${uU}`,e)}};(0,rv.H)(`${uL}${uU}`,FlowGraphLogicOrBlock);let FlowGraphLogicNotBlock=class FlowGraphLogicNotBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(ug,ug,e=>!e,`${uL}${uV}`,e)}};(0,rv.H)(`${uL}${uV}`,FlowGraphLogicNotBlock);let FlowGraphConstantOperationBlock=class FlowGraphConstantOperationBlock extends FlowGraphCachedOperationBlock{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}};let uk="FGAddNumberBlock";let FlowGraphAddNumberBlock=class FlowGraphAddNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e+t,uk,e)}};(0,rv.H)(uk,FlowGraphAddNumberBlock);let uG="FGSubtractNumberBlock";let FlowGraphSubtractNumberBlock=class FlowGraphSubtractNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e-t,uG,e)}};(0,rv.H)(uG,FlowGraphSubtractNumberBlock);let uz="FGMultiplyNumberBlock";let FlowGraphMultiplyNumberBlock=class FlowGraphMultiplyNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e*t,uz,e)}};(0,rv.H)(uz,FlowGraphMultiplyNumberBlock);let uW="FGDivideNumberBlock";let FlowGraphDivideNumberBlock=class FlowGraphDivideNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e/t,uW,e)}};(0,rv.H)(uW,FlowGraphDivideNumberBlock);let uH="FGModNumberBlock";let FlowGraphModNumberBlock=class FlowGraphModNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e%t,uH,e)}};(0,rv.H)(uH,FlowGraphModNumberBlock);let uX="FGPowNumberBlock";let FlowGraphPowNumberBlock=class FlowGraphPowNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.pow(e,t),uX,e)}};(0,rv.H)(uX,FlowGraphPowNumberBlock);let uY="FGIsNaNNumberBlock";let FlowGraphIsNaNNumberBlock=class FlowGraphIsNaNNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,ug,e=>isNaN(e),uY,e)}};(0,rv.H)(uY,FlowGraphIsNaNNumberBlock);let uj="FGIsInfinityNumberBlock";let FlowGraphIsInfinityNumberBlock=class FlowGraphIsInfinityNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,ug,e=>!isFinite(e),uj,e)}};(0,rv.H)(uj,FlowGraphIsInfinityNumberBlock);let uq="FGSqrtNumberBlock";let FlowGraphSqrtNumberBlock=class FlowGraphSqrtNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.sqrt(e),uq,e)}};(0,rv.H)(uq,FlowGraphSqrtNumberBlock);let uK="FGAbsNumberBlock";let FlowGraphAbsNumberBlock=class FlowGraphAbsNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.abs(e),uK,e)}};(0,rv.H)(uK,FlowGraphAbsNumberBlock);let u$="FGNegateNumberBlock";let FlowGraphNegateNumberBlock=class FlowGraphNegateNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>-e,u$,e)}};(0,rv.H)(u$,FlowGraphNegateNumberBlock);let uQ="FGFloorNumberBlock";let FlowGraphFloorNumberBlock=class FlowGraphFloorNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.floor(e),uQ,e)}};(0,rv.H)(uQ,FlowGraphFloorNumberBlock);let uZ="FGCeilNumberBlock";let FlowGraphCeilNumberBlock=class FlowGraphCeilNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.ceil(e),uZ,e)}};(0,rv.H)(uZ,FlowGraphCeilNumberBlock);let uJ="FGRoundNumberBlock";let FlowGraphRoundNumberBlock=class FlowGraphRoundNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.round(e/Math.pow(10,t))/Math.pow(10,t),uJ,e)}};(0,rv.H)(uJ,FlowGraphRoundNumberBlock);let u0="FGTruncNumberBlock";let FlowGraphTruncNumberBlock=class FlowGraphTruncNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.trunc(e),u0,e)}};(0,rv.H)(u0,FlowGraphTruncNumberBlock);let u1="FGExpNumberBlock";let FlowGraphExpNumberBlock=class FlowGraphExpNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.exp(e),u1,e)}};(0,rv.H)(u1,FlowGraphExpNumberBlock);let u2="FGLog10NumberBlock";let FlowGraphLog10NumberBlock=class FlowGraphLog10NumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.log10(e),u2,e)}};(0,rv.H)(u2,FlowGraphLog10NumberBlock);let u3="FGLogNumberBlock";let FlowGraphLogNumberBlock=class FlowGraphLogNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.log(e),u3,e)}};(0,rv.H)(u3,FlowGraphLogNumberBlock);let u4="FGLnNumberBlock";let FlowGraphLnNumberBlock=class FlowGraphLnNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.log(e)/Math.LN2,u4,e)}};(0,rv.H)(u4,FlowGraphLnNumberBlock);let u5="FGSineNumberBlock";let FlowGraphSinNumberBlock=class FlowGraphSinNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.sin(e),u5,e)}};(0,rv.H)(u5,FlowGraphSinNumberBlock);let u6="FGCosNumberBlock";let FlowGraphCosNumberBlock=class FlowGraphCosNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.cos(e),u6,e)}};(0,rv.H)(u6,FlowGraphCosNumberBlock);let u8="FGTanNumberBlock";let FlowGraphTanNumberBlock=class FlowGraphTanNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.tan(e),u8,e)}};(0,rv.H)(u8,FlowGraphTanNumberBlock);let u7="FGASineNumberBlock";let FlowGraphASinNumberBlock=class FlowGraphASinNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.asin(e),u7,e)}};(0,rv.H)(u7,FlowGraphASinNumberBlock);let u9="FGACosNumberBlock";let FlowGraphACosNumberBlock=class FlowGraphACosNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.acos(e),u9,e)}};(0,rv.H)(u9,FlowGraphACosNumberBlock);let ce="FGATanNumberBlock";let FlowGraphATanNumberBlock=class FlowGraphATanNumberBlock extends FlowGraphUnaryOperationBlock{constructor(e){super(um,um,e=>Math.atan(e),ce,e)}};(0,rv.H)(ce,FlowGraphATanNumberBlock);let ct="FGENumberBlock";let FlowGraphENumberBlock=class FlowGraphENumberBlock extends FlowGraphConstantOperationBlock{constructor(e){super(um,()=>Math.E,ct,e)}};(0,rv.H)(ct,FlowGraphENumberBlock);let ci="FGPiNumberBlock";let FlowGraphPiNumberBlock=class FlowGraphPiNumberBlock extends FlowGraphConstantOperationBlock{constructor(e){super(um,()=>Math.PI,ci,e)}};(0,rv.H)(ci,FlowGraphPiNumberBlock);let cr="FGATan2NumberBlock";let FlowGraphATan2NumberBlock=class FlowGraphATan2NumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.atan2(e,t),cr,e)}};(0,rv.H)(cr,FlowGraphATan2NumberBlock);let cs="FGRandomNumberBlock";let FlowGraphRandomNumberBlock=class FlowGraphRandomNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>e+Math.random()*(t-e),cs,e)}};(0,rv.H)(cs,FlowGraphRandomNumberBlock);let cn="FGMinNumberBlock";let FlowGraphMinNumberBlock=class FlowGraphMinNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.min(e,t),cn,e)}};(0,rv.H)(cn,FlowGraphMinNumberBlock);let ca="FGMaxNumberBlock";let FlowGraphMaxNumberBlock=class FlowGraphMaxNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,um,(e,t)=>Math.max(e,t),ca,e)}};(0,rv.H)(ca,FlowGraphMaxNumberBlock);let co="FGEqualsNumberBlock";let FlowGraphEqualsNumberBlock=class FlowGraphEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>e===t,co,e)}};(0,rv.H)(co,FlowGraphEqualsNumberBlock);let cl="FGGreaterThanNumberBlock";let FlowGraphGreaterThanNumberBlock=class FlowGraphGreaterThanNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>e>t,cl,e)}};(0,rv.H)(cl,FlowGraphGreaterThanNumberBlock);let ch="FGGreaterThanOrEqualsNumberBlock";let FlowGraphGreaterThanOrEqualsNumberBlock=class FlowGraphGreaterThanOrEqualsNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>e>=t,ch,e)}};(0,rv.H)(ch,FlowGraphGreaterThanOrEqualsNumberBlock);let cu="FGLessThanNumberBlock";let FlowGraphLessThanNumberBlock=class FlowGraphLessThanNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(um,um,ug,(e,t)=>ee<=t,cc,e)}};(0,rv.H)(cc,FlowGraphLessThanOrEqualsNumberBlock);let cd="FGMixNumberBlock";let FlowGraphMixNumberBlock=class FlowGraphMixNumberBlock extends FlowGraphBlock{constructor(e){super(e),this.leftInput=this._registerDataInput("leftInput",um),this.rightInput=this._registerDataInput("rightInput",um),this.alphaInput=this._registerDataInput("alphaInput",um),this.resultOutput=this._registerDataOutput("resultOutput",um)}_updateOutputs(e){let t=this.leftInput.getValue(e),i=this.rightInput.getValue(e),r=this.alphaInput.getValue(e);this.resultOutput.setValue(t+(i-t)*r,e)}getClassName(){return cd}};(0,rv.H)(cd,FlowGraphMixNumberBlock);let cp="FGAddVector2Block";let FlowGraphAddVector2Block=class FlowGraphAddVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,uv,uv,(e,t)=>e.add(t),cp,e)}};(0,rv.H)(cp,FlowGraphAddVector2Block);let c_="FGSubtractVector2Block";let FlowGraphSubtractVector2Block=class FlowGraphSubtractVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,uv,uv,(e,t)=>e.subtract(t),c_,e)}};(0,rv.H)(c_,FlowGraphSubtractVector2Block);let cf="FGMultiplyVector2Block";let FlowGraphMultiplyVector2Block=class FlowGraphMultiplyVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,uv,uv,(e,t)=>e.multiply(t),cf,e)}};(0,rv.H)(cf,FlowGraphMultiplyVector2Block);let cm="FGDivideVector2Block";let FlowGraphDivideVector2Block=class FlowGraphDivideVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,uv,uv,(e,t)=>e.divide(t),cm,e)}};(0,rv.H)(cm,FlowGraphDivideVector2Block);let cg="FGScaleVector2Block";let FlowGraphScaleVector2Block=class FlowGraphScaleVector2Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uv,um,uv,(e,t)=>e.scale(t),cg,e)}};(0,rv.H)(cg,FlowGraphScaleVector2Block);let cv="FGLengthVector2Block";let FlowGraphLengthVector2Block=class FlowGraphLengthVector2Block extends FlowGraphUnaryOperationBlock{constructor(e){super(uv,um,e=>e.length(),cv,e)}};(0,rv.H)(cv,FlowGraphLengthVector2Block);let cx="FGNormalizeVector2Block";let FlowGraphNormalizeVector2Block=class FlowGraphNormalizeVector2Block extends FlowGraphUnaryOperationBlock{constructor(e){super(uv,uv,e=>{let t=e.clone();return t.normalize(),t},cx,e)}};(0,rv.H)(cx,FlowGraphNormalizeVector2Block);let FlowGraphCreateVector2Block=class FlowGraphCreateVector2Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=rm.FM.Zero(),this.x=this._registerDataInput("x",um),this.y=this._registerDataInput("y",um),this.vector=this._registerDataOutput("vector",uv)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this.vector.setValue(this._cachedVector,e)}};(0,rv.H)("FGCreateVector2Block",FlowGraphCreateVector2Block);let FlowGraphSplitVector2Block=class FlowGraphSplitVector2Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",uv),this.x=this._registerDataOutput("x",um),this.y=this._registerDataOutput("y",um)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e)}};(0,rv.H)("FGSplitVector2Block",FlowGraphSplitVector2Block);let FlowGraphRotate2dVector2Block=class FlowGraphRotate2dVector2Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=rm.FM.Zero(),this.input=this._registerDataInput("input",uv),this.angle=this._registerDataInput("angle",um),this.output=this._registerDataOutput("output",uv)}_updateOutputs(e){let t=this.input.getValue(e),i=this.angle.getValue(e);this._cachedVector.x=t.x*Math.cos(i)-t.y*Math.sin(i),this._cachedVector.y=t.x*Math.sin(i)+t.y*Math.cos(i),this.output.setValue(this._cachedVector,e)}};(0,rv.H)("FGRotate2dVector2Block",FlowGraphRotate2dVector2Block);let cT="FGAddVector3Block";let FlowGraphAddVector3Block=class FlowGraphAddVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>e.add(t),cT,e)}};(0,rv.H)(cT,FlowGraphAddVector3Block);let cS="FGSubtractVector3Block";let FlowGraphSubtractVector3Block=class FlowGraphSubtractVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>e.subtract(t),cS,e)}};(0,rv.H)(cS,FlowGraphSubtractVector3Block);let cC="FGMultiplyVector3Block";let FlowGraphMultiplyVector3Block=class FlowGraphMultiplyVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>e.multiply(t),cC,e)}};(0,rv.H)(cC,FlowGraphMultiplyVector3Block);let cE="FGDivideVector3Block";let FlowGraphDivideVector3Block=class FlowGraphDivideVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>e.divide(t),cE,e)}};(0,rv.H)(cE,FlowGraphDivideVector3Block);let cb="FGScaleVector3Block";let FlowGraphScaleVector3Block=class FlowGraphScaleVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,um,ux,(e,t)=>e.scale(t),cb,e)}};(0,rv.H)(cb,FlowGraphScaleVector3Block);let cy="FGLengthVector3Block";let FlowGraphLengthVector3Block=class FlowGraphLengthVector3Block extends FlowGraphUnaryOperationBlock{constructor(e){super(ux,um,e=>e.length(),cy,e)}};(0,rv.H)(cy,FlowGraphLengthVector3Block);let cP="FGNormalizeVector3Block";let FlowGraphNormalizeVector3Block=class FlowGraphNormalizeVector3Block extends FlowGraphUnaryOperationBlock{constructor(e){super(ux,ux,e=>e.normalizeToNew(),cP,e)}};(0,rv.H)(cP,FlowGraphNormalizeVector3Block);let cR="FGDotVector3Block";let FlowGraphDotVector3Block=class FlowGraphDotVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,um,(e,t)=>rm.P.Dot(e,t),cR,e)}};(0,rv.H)(cR,FlowGraphDotVector3Block);let cA="FGCrossVector3Block";let FlowGraphCrossVector3Block=class FlowGraphCrossVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(ux,ux,ux,(e,t)=>rm.P.Cross(e,t),cA,e)}};(0,rv.H)(cA,FlowGraphCrossVector3Block);let cI="FGCreateVector3Block";let FlowGraphCreateVector3Block=class FlowGraphCreateVector3Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=rm.P.Zero(),this.x=this._registerDataInput("x",um),this.y=this._registerDataInput("y",um),this.z=this._registerDataInput("y",um),this.vector=this._registerDataOutput("vector",ux)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this._cachedVector.z=this.z.getValue(e),this.vector.setValue(this._cachedVector,e)}getClassName(){return cI}};(0,rv.H)(cI,FlowGraphCreateVector3Block);let cM="FGSplitVector3Block";let FlowGraphSplitVector3Block=class FlowGraphSplitVector3Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",ux),this.x=this._registerDataOutput("x",um),this.y=this._registerDataOutput("y",um),this.z=this._registerDataOutput("z",um)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e),this.z.setValue(t.z,e)}getClassName(){return cM}};(0,rv.H)(cM,FlowGraphSplitVector3Block);let cD="FGRotateVector3Block";let FlowGraphRotate3dVector3Block=class FlowGraphRotate3dVector3Block extends FlowGraphBlock{constructor(e){super(e),this._cachedQuaternion=new rm._f,this.input=this._registerDataInput("input",ux),this.angle=this._registerDataInput("angle",um),this.output=this._registerDataOutput("output",ux)}_updateOutputs(e){let t=rm._f.RotationAxisToRef(this.axis.getValue(e),this.angle.getValue(e),this._cachedQuaternion),i=this.input.getValue(e),r=this.output.getValue(e);i.applyRotationQuaternionToRef(t,r)}getClassName(){return cD}};(0,rv.H)(cD,FlowGraphRotate3dVector3Block);let cO="FGTransformVector3Block";let FlowGraphTransformVector3Block=class FlowGraphTransformVector3Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,ux,ux,(e,t)=>rm.P.TransformCoordinatesToRef(t,e,this._cachedResult),cO,e),this._cachedResult=rm.P.Zero()}};(0,rv.H)(cO,FlowGraphTransformVector3Block);let cN="FGAddVector4Block";let FlowGraphAddVector4Block=class FlowGraphAddVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,uT,uT,(e,t)=>e.add(t),cN,e)}};(0,rv.H)(cN,FlowGraphAddVector4Block);let cF="FGSubtractVector4Block";let FlowGraphSubtractVector4Block=class FlowGraphSubtractVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,uT,uT,(e,t)=>e.subtract(t),cF,e)}};(0,rv.H)(cF,FlowGraphSubtractVector4Block);let cB="FGMultiplyVector4Block";let FlowGraphMultiplyVector4Block=class FlowGraphMultiplyVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,uT,uT,(e,t)=>e.multiply(t),cB,e)}};(0,rv.H)(cB,FlowGraphMultiplyVector4Block);let cL="FGDivideVector4Block";let FlowGraphDivideVector4Block=class FlowGraphDivideVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,uT,uT,(e,t)=>e.divide(t),cL,e)}};(0,rv.H)(cL,FlowGraphDivideVector4Block);let cw="FGScaleVector4Block";let FlowGraphScaleVector4Block=class FlowGraphScaleVector4Block extends FlowGraphBinaryOperationBlock{constructor(e){super(uT,um,uT,(e,t)=>e.scale(t),cw,e)}};(0,rv.H)(cw,FlowGraphScaleVector4Block);let cU="FGLengthVector4Block";let FlowGraphLengthVector4Block=class FlowGraphLengthVector4Block extends FlowGraphUnaryOperationBlock{constructor(e){super(uT,um,e=>e.length(),cU,e)}};(0,rv.H)(cU,FlowGraphLengthVector4Block);let cV="FGNormalizeVector4Block";let FlowGraphNormalizeVector4Block=class FlowGraphNormalizeVector4Block extends FlowGraphUnaryOperationBlock{constructor(e){super(uT,uT,e=>{let t=e.clone();return t.normalize(),t},cV,e)}getClassName(){return cV}};(0,rv.H)(cV,FlowGraphNormalizeVector4Block);let ck="FGCreateVector4Block";let FlowGraphCreateVector4Block=class FlowGraphCreateVector4Block extends FlowGraphBlock{constructor(e){super(e),this._cachedVector=rm.Lt.Zero(),this.x=this._registerDataInput("x",um),this.y=this._registerDataInput("y",um),this.z=this._registerDataInput("y",um),this.w=this._registerDataInput("w",um),this.vector=this._registerDataOutput("vector",uT)}_updateOutputs(e){this._cachedVector.x=this.x.getValue(e),this._cachedVector.y=this.y.getValue(e),this._cachedVector.z=this.z.getValue(e),this._cachedVector.w=this.w.getValue(e),this.vector.setValue(this._cachedVector,e)}getClassName(){return ck}};(0,rv.H)(ck,FlowGraphCreateVector4Block);let cG="FGSplitVector4Block";let FlowGraphSplitVector4Block=class FlowGraphSplitVector4Block extends FlowGraphBlock{constructor(e){super(e),this.vector=this._registerDataInput("vector",uT),this.x=this._registerDataOutput("x",um),this.y=this._registerDataOutput("y",um),this.z=this._registerDataOutput("z",um),this.w=this._registerDataOutput("w",um)}_updateOutputs(e){let t=this.vector.getValue(e);this.x.setValue(t.x,e),this.y.setValue(t.y,e),this.z.setValue(t.z,e),this.w.setValue(t.w,e)}getClassName(){return cG}};(0,rv.H)(cG,FlowGraphSplitVector4Block);let cz="FGAddMatrixBlock";let FlowGraphAddMatrixBlock=class FlowGraphAddMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,uS,uS,(e,t)=>e.addToRef(t,this._cachedMatrix),cz,e),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cz,FlowGraphAddMatrixBlock);let cW="FGAddMatrixAndNumberBlock";let FlowGraphAddMatrixAndNumberBlock=class FlowGraphAddMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,um,uS,(e,t)=>{for(let i=0;ie.addToRef(t.scaleToRef(-1,rm.jp.Matrix[0]),this._cachedMatrix),cH,e),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cH,FlowGraphSubtractMatrixBlock);let cX="FGSubtractMatrixAndNumberBlock";let FlowGraphSubtractMatrixAndNumberBlock=class FlowGraphSubtractMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,um,uS,(e,t)=>{for(let i=0;ie.multiplyToRef(t,this._cachedMatrix),cY,e),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cY,FlowGraphMultiplyMatrixBlock);let cj="FGDivideMatrixBlock";let FlowGraphDivideMatrixBlock=class FlowGraphDivideMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,uS,uS,(e,t)=>e.multiplyToRef(t.invertToRef(rm.jp.Matrix[0]),this._cachedResultMatrix),cj,e),this._cachedResultMatrix=rm.y3.Zero()}};(0,rv.H)(cj,FlowGraphDivideMatrixBlock);let cq="FGDivideMatrixAndNumberBlock";let FlowGraphDivideMatrixAndNumberBlock=class FlowGraphDivideMatrixAndNumberBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(uS,um,uS,(e,t)=>{for(let i=0;ie.scaleToRef(t,this._cachedMatrix),cK,e),this._cachedMatrix=rm.y3.Zero()}};(0,rv.H)(cK,FlowGraphScaleMatrixBlock);let c$="FGClampMatrixBlock";let FlowGraphClampMatrixBlock=class FlowGraphClampMatrixBlock extends FlowGraphBlock{constructor(e){super(e),this._cachedArray=new Float32Array(16),this._cachedMatrix=rm.y3.Identity(),this.input=this._registerDataInput("input",uS),this.min=this._registerDataInput("min",um),this.max=this._registerDataInput("max",um),this.output=this._registerDataOutput("output",uS)}_updateOutputs(e){let t=this.input.getValue(e),i=this.min.getValue(e),r=this.max.getValue(e);for(let e=0;erm.y3.FromQuaternionToRef(e,this._cachedMatrix),cJ,e),this._cachedMatrix=new rm.y3}};(0,rv.H)(cJ,FlowGraphQuaternionToRotationMatrixBlock);let c0="FGGetTransformationMatrixBlock";let FlowGraphGetTransformationMatrixBlock=class FlowGraphGetTransformationMatrixBlock extends FlowGraphBinaryOperationBlock{constructor(e){super(u_,u_,uS,(e,t)=>{let i=e.getWorldMatrix(),r=t.getWorldMatrix(),s=r.invertToRef(rm.jp.Matrix[0]),n=s.multiplyToRef(i,this._cachedResult);return n},c0,e),this._cachedResult=rm.y3.Zero()}};(0,rv.H)(c0,FlowGraphGetTransformationMatrixBlock);let FlowGraphMeshPickEventBlock=class FlowGraphMeshPickEventBlock extends FlowGraphEventBlock{constructor(e){super(e),this.config=e}configure(){super.configure(),this._meshVariableName=this.config.meshVariableName}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){let i=e.getVariable(this._meshVariableName);t=i.getScene().onPointerObservable.add(t=>{var r;t.type===r8.kD.POINTERPICK&&(null===(r=t.pickInfo)||void 0===r?void 0:r.pickedMesh)===i&&this._execute(e)});let r=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){let t=e.getVariable(this._meshVariableName),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return"FGMeshPickEventBlock"}};(0,rv.H)("FGMeshPickEventBlock",FlowGraphMeshPickEventBlock);let FlowGraphSceneReadyEventBlock=class FlowGraphSceneReadyEventBlock extends FlowGraphEventBlock{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){let t=e.configuration.scene,i=t.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneReadyObserver"),i=e.configuration.scene;i.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return"FGSceneReadyEventBlock"}};(0,rv.H)("FGSceneReadyEventBlock",FlowGraphSceneReadyEventBlock);let FlowGraphReceiveCustomEventBlock=class FlowGraphReceiveCustomEventBlock extends FlowGraphEventBlock{constructor(e){super(e),this.config=e,this.eventData=this._registerDataOutput("eventData",u_)}_preparePendingTasks(e){let t=e.configuration.eventCoordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=t.add(t=>{this.eventData.setValue(t,e),this._execute(e)})}_cancelPendingTasks(e){let t=e.configuration.eventCoordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):rW.w1.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`)}getClassName(){return"FGReceiveCustomEventBlock"}};(0,rv.H)("FGReceiveCustomEventBlock",FlowGraphReceiveCustomEventBlock);let FlowGraphSceneTickEventBlock=class FlowGraphSceneTickEventBlock extends FlowGraphEventBlock{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){let t=e.configuration.scene,i=t.onBeforeRenderObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneBeforeRender"),i=e.configuration.scene;i.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return"FGSceneTickEventBlock"}};(0,rv.H)("FGSceneTickEventBlock",FlowGraphSceneTickEventBlock)},208:function(e,t,i){i.d(t,{N:function(){return Node}});var r=i(9956),s=i(78),n=i(1760),a=i(4800),o=i(6030),l=i(6131);let _InternalNodeDataInfo=class _InternalNodeDataInfo{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new a.y$,this._onClonedObservable=new a.y$}};let Node=class Node{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):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;let t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){let t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&((void 0===this._parentNode._children||null===this._parentNode._children)&&(this._parentNode._children=[]),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){let 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){this._isDirty=!1,this._nodeDataStorage=new _InternalNodeDataInfo,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new a.y$,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=s.y3.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new a.y$,this._onDisposeObserver=null,this._behaviors=[],this.name=e,this.id=e,this._scene=t||o.l.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){let i=this._behaviors.indexOf(e);return -1!==i||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce(()=>{e.attach(this)}):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){let 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(let 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={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,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._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):(!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,i){if(this._children)for(let r=0;r(!t||t(e))&&void 0!==e.cullingStrategy),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew Node(e,this.getScene()),this);if(t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i{throw(0,l.S)("AnimationRange")},Node._NodeConstructors={},(0,r.gn)([(0,n.qC)()],Node.prototype,"name",void 0),(0,r.gn)([(0,n.qC)()],Node.prototype,"id",void 0),(0,r.gn)([(0,n.qC)()],Node.prototype,"uniqueId",void 0),(0,r.gn)([(0,n.qC)()],Node.prototype,"state",void 0),(0,r.gn)([(0,n.qC)()],Node.prototype,"metadata",void 0)},7609:function(e,t,i){i.d(t,{H:function(){return Stage},l:function(){return SceneComponentConstants}});let SceneComponentConstants=class SceneComponentConstants{};SceneComponentConstants.NAME_EFFECTLAYER="EffectLayer",SceneComponentConstants.NAME_LAYER="Layer",SceneComponentConstants.NAME_LENSFLARESYSTEM="LensFlareSystem",SceneComponentConstants.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",SceneComponentConstants.NAME_PARTICLESYSTEM="ParticleSystem",SceneComponentConstants.NAME_GAMEPAD="Gamepad",SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",SceneComponentConstants.NAME_PREPASSRENDERER="PrePassRenderer",SceneComponentConstants.NAME_DEPTHRENDERER="DepthRenderer",SceneComponentConstants.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",SceneComponentConstants.NAME_SPRITE="Sprite",SceneComponentConstants.NAME_SUBSURFACE="SubSurface",SceneComponentConstants.NAME_OUTLINERENDERER="Outline",SceneComponentConstants.NAME_PROCEDURALTEXTURE="ProceduralTexture",SceneComponentConstants.NAME_SHADOWGENERATOR="ShadowGenerator",SceneComponentConstants.NAME_OCTREE="Octree",SceneComponentConstants.NAME_PHYSICSENGINE="PhysicsEngine",SceneComponentConstants.NAME_AUDIO="Audio",SceneComponentConstants.NAME_FLUIDRENDERER="FluidRenderer",SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER=0,SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS=0,SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER=2,SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER=1,SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS=0,SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE=1,SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS=0,SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE=1,SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,SceneComponentConstants.STEP_BEFORECLEAR_PREPASS=1,SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER=1,SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS=0,SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER=4,SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,SceneComponentConstants.STEP_AFTERRENDER_AUDIO=0,SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,SceneComponentConstants.STEP_POINTERMOVE_SPRITE=0,SceneComponentConstants.STEP_POINTERDOWN_SPRITE=0,SceneComponentConstants.STEP_POINTERUP_SPRITE=0;let Stage=class Stage extends Array{constructor(e){super(...e)}static Create(){return Object.create(Stage.prototype)}registerStep(e,t,i){let r=0;for(;r=0;o--)(s=e[o])&&(a=(n<3?s(a):n>3?s(t,i,a):s(t,i))||a);return n>3&&a&&Object.defineProperty(t,i,a),a}}}]); \ No newline at end of file diff --git a/.next/static/chunks/1f3d3139-8a75094e9a213384.js b/.next/static/chunks/1f3d3139-8a75094e9a213384.js new file mode 100644 index 0000000..96481de --- /dev/null +++ b/.next/static/chunks/1f3d3139-8a75094e9a213384.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[105],{3249:function(e,t,s){s.d(t,{Kj:function(){return w},gW:function(){return P}});var i=s(4800),r=s(5132),a=s(3189),n=s(1803),o=s(7521),h=s(2421),l=s(6540),d=s(78),c=s(2983),u=s(208),f=s(1295),g=s(2696),_=s(1687),m=s(7042),I=s(1091),M=s(2515),p=s(5461),v=s(2697),D=s(1760),y=s(9626),b=s(3048),S=s(6131),x=s(7609),B=s(4926);class P{}class A{constructor(){this.visibleInstances={},this.batchCache=new O,this.batchCacheReplacementModeInFrozenMode=new O,this.instancesBufferSize=2048}}class O{constructor(){this.mustReturn=!1,this.visibleInstances=[],this.renderSelf=[],this.hardwareInstancedRendering=[]}}class C{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class F{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=[],this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class w extends m.x{static _GetDefaultSideOrientation(e){return e||w.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(f.o.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(f.o.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 i.y$),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new i.y$),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new i.y$),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new i.y$),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new i.y$),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 overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=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}constructor(e,t=null,s=null,r=null,o,h=!0){if(super(e,t),this._internalMeshDataInfo=new F,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new A,this._thinInstanceDataStorage=new C,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=w.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,s)=>{e&&s&&(this._uniformBuffer?this.transferToEffect(t):s.bindOnlyWorldMatrix(t))},r){if(r._geometry&&r._geometry.applyToMesh(this),a.j.DeepCopy(r,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=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){let e=r._ranges;for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,this._internalMetadata=r._internalMetadata,n.$&&n.$.HasTags(r)&&n.$.AddTagsTo(this,n.$.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix()),this.id=e+"."+r.id,this.material=r.material,!o){let t=r.getDescendants(!0);for(let s=0;s{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 i.y$(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,s){let 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));for(let r of(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),this.getChildTransformNodes(!0)))"InstancedMesh"===r.getClassName()&&"Mesh"===i.getClassName()&&r.sourceMesh===this?r.instantiateHierarchy(i,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:i},s):r.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()+", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let s=0;s0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,s)=>t.distanceOrScreenCoverages.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return y.Y.Warn("You cannot use a mesh as LOD level twice"),this;let s=new B.g(e,t);return this._internalMeshDataInfo._LODLevels.push(s),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let s=0;sn*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();let u=this.material||d.defaultMaterial;if(u){if(u._storeEffectOnSubMeshes)for(let e of this.subMeshes){let t=e.getMaterial();if(t){if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,c))return!1}else if(!t.isReady(this,c))return!1}}else if(!u.isReady(this,c))return!1}let f=l.currentRenderPassId;for(let e of this.lightSources){let t=e.getShadowGenerators();if(!t)continue;let d=t.values();for(let e=d.next();!0!==e.done;e=d.next()){let t=e.value;if(t&&(!(null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)&&(null===(a=null===(r=t.getShadowMap())||void 0===r?void 0:r.renderList)||void 0===a?void 0:a.indexOf(this))!==-1)){let e=null!==(n=t.getShadowMap().renderPassIds)&&void 0!==n?n:[l.currentRenderPassId];for(let s=0;s0){let s=this.getIndices();if(!s)return null;let i=s.length,r=!1;if(e)r=!0;else for(let e of this.subMeshes)if(e.indexStart+e.indexCount>i||e.verticesStart+e.verticesCount>t){r=!0;break}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new I.P(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),s=t/e|0,i=0;for(;s%3!=0;)s++;this.releaseSubMeshes();for(let r=0;r=t);r++)I.P.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{let i=new g.x;i.set(t,e);let r=this.getScene();new _.Z(_.Z.RandomId(),r,i,s,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let s=this.getVertexBuffer(e);s&&s.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=_.Z.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}updateMeshPositions(e,t=!0){let s=this.getVerticesData(f.o.PositionKind);if(!s)return this;if(e(s),this.updateVerticesData(f.o.PositionKind,s,!1,!1),t){let e=this.getIndices(),t=this.getVerticesData(f.o.NormalKind);if(!t)return this;g.x.ComputeNormals(s,e,t),this.updateVerticesData(f.o.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry||1===this._geometry.meshes.length)return this;let e=this._geometry,t=this._geometry.copy(_.Z.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,s){let i=this._geometry;i||(i=new _.Z(_.Z.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{let t=new g.x;t.indices=e;let i=this.getScene();new _.Z(_.Z.RandomId(),i,t,s,this)}return this}updateIndices(e,t,s=!1){return this._geometry&&this._geometry.updateIndices(e,t,s),this}toLeftHanded(){return this._geometry&&this._geometry.toLeftHanded(),this}_bind(e,t,s,i=!0){let r;if(!this._geometry)return this;let a=this.getScene().getEngine();if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)r=null;else switch(this._getRenderingFillMode(s)){case M.F.PointFillMode:r=null;break;case M.F.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),a);break;default:case M.F.TriangleFillMode:r=this._geometry.getIndexBuffer()}return i&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,r,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,r),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);let i=this.getScene().getEngine();return this._unIndexed||t==M.F.PointFillMode?i.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||s):t==M.F.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}let s=this.getScene(),i=s._isInIntermediateRendering(),r=i?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){let t=this._instanceDataStorage.visibleInstances,r=s.getRenderId(),n=i?t.intermediateDefaultRenderId:t.defaultRenderId;a.visibleInstances[e]=t[r],!a.visibleInstances[e]&&n&&(a.visibleInstances[e]=t[n])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==a.visibleInstances[e]&&void 0!==a.visibleInstances[e],this._instanceDataStorage.previousBatch=a,a}_renderWithInstances(e,t,s,i,r){var a;let n=s.visibleInstances[e._id],o=n?n.length:0,h=this._instanceDataStorage,l=h.instancesBufferSize,c=h.instancesBuffer,u=h.instancesPreviousBuffer,g=64*(o+1);for(;h.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&c.activeCamera===c.activeCameras[0]||u<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let f=this._getInstancesRenderList(e._id,!!s);if(f.mustReturn||!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let g=c.getEngine(),_=0,m=null;this.ignoreCameraMaxZ&&c.activeCamera&&!c._isInIntermediateRendering()&&(_=c.activeCamera.maxZ,m=c.activeCamera,c.activeCamera.maxZ=0,c.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let I=e.getRenderingMesh(),p=f.hardwareInstancedRendering[e._id]||I.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,v=this._instanceDataStorage,D=e.getMaterial();if(!D)return m&&(m.maxZ=_,c.updateTransformMatrix(!0)),this;if(v.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===D){if(D._storeEffectOnSubMeshes&&!(null===(a=e.effect)||void 0===a?void 0:a._wasPreviouslyReady)||!D._storeEffectOnSubMeshes&&!(null===(n=D.getEffect())||void 0===n?void 0:n._wasPreviouslyReady))return m&&(m.maxZ=_,c.updateTransformMatrix(!0)),this}else{if(D._storeEffectOnSubMeshes){if(!D.isReadyForSubMesh(this,e,p))return m&&(m.maxZ=_,c.updateTransformMatrix(!0)),this}else if(!D.isReady(this,p))return m&&(m.maxZ=_,c.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=D}t&&g.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode);let y=null!==(o=null==(h=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper())?void 0:h.effect)&&void 0!==o?o:null;for(let t of c._beforeRenderingMeshStage)t.action(this,e,f,y);if(!h||!y)return m&&(m.maxZ=_,c.updateTransformMatrix(!0)),this;let b=s||this;if(!v.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||null!==this.overrideMaterialSideOrientation||this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)){let e=b._getWorldMatrixDeterminant();null==(d=this.overrideMaterialSideOrientation)&&(d=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(d=d===M.F.ClockWiseSideOrientation?M.F.CounterClockWiseSideOrientation:M.F.ClockWiseSideOrientation),v.sideOrientation=d}else d=v.sideOrientation;let S=this._internalMeshDataInfo._effectiveMaterial._preBind(h,d);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&g.setDepthWrite(!0);let x=this._internalMeshDataInfo._effectiveMaterial,B=x.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),p||this._bind(e,y,B,!1);let P=b.getWorldMatrix();for(let t of(x._storeEffectOnSubMeshes?x.bindForSubMesh(P,this,e):x.bind(P,this),!x.backFaceCulling&&x.separateCullingPass&&(g.setState(!0,x.zOffset,!1,!S,x.cullBackFaces,x.stencil,x.zOffsetUnits),this._processRendering(this,e,y,B,f,p,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),g.setState(!0,x.zOffset,!1,S,x.cullBackFaces,x.stencil,x.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,y,B,f,p,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind(),c._afterRenderingMeshStage))t.action(this,e,f,y);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),m&&(m.maxZ=_,c.updateTransformMatrix(!0)),c.performancePriority!==l.a.Aggressive||v.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(f.o.MatricesWeightsKind)&&(this.isVerticesDataPresent(f.o.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){let e=this.getVerticesData(f.o.MatricesWeightsKind),t=e.length;for(let s=0;ss&&i++,0!==a&&c++,d+=a,s=a}if(h[c]++,c>a&&(a=c),0===d)r++;else{let s=1/d,i=0;for(let r=0;r.001&&n++}}let l=this.skeleton.bones.length,d=this.getVerticesData(f.o.MatricesIndicesKind),c=this.getVerticesData(f.o.MatricesIndicesExtraKind),u=0;for(let e=0;e=l||s<0)&&u++}let g="Number of Weights = "+s/4+"\nMaximum influences = "+a+"\nMissing Weights = "+r+"\nNot Sorted = "+i+"\nNot Normalized = "+n+"\nWeightCounts = ["+h+"]\nNumber of bones = "+l+"\nBad Bone Indices = "+u;return{skinned:!0,valid:0===r&&0===n&&0===u,report:g}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return r.w1.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=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return!!(2!==this.delayLoadState&&super.isInFrustum(e))&&(this._checkDelayState(),!0)}setMaterialById(e){let t;let s=this.getScene().materials;for(t=s.length-1;t>-1;t--)if(s[t].id===e)return this.material=s[t],this;let i=this.getScene().multiMaterials;for(t=i.length-1;t>-1;t--)if(i[t].id===e){this.material=i[t];break}return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){let t;if(!this.isVerticesDataPresent(f.o.PositionKind))return this;let s=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(f.o.PositionKind),r=d.P.Zero();for(t=0;te.determinant()&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=s,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?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 w(e,this.getScene(),t,this,s,i)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);let 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(let e in s.meshMap){let 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 for(let e of this.getScene().meshes)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,a,n,o=!1,h){let l=this.getScene();return r.w1.LoadImage(e,e=>{let r=e.width,h=e.height,l=this.getEngine().createCanvas(r,h).getContext("2d");l.drawImage(e,0,0);let d=l.getImageData(0,0,r,h).data;this.applyDisplacementMapFromBuffer(d,r,h,t,s,a,n,o),i&&i(this)},h||(()=>{}),l.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,s,i,r,a,n,o=!1){if(!this.isVerticesDataPresent(f.o.PositionKind)||!this.isVerticesDataPresent(f.o.NormalKind)||!this.isVerticesDataPresent(f.o.UVKind))return y.Y.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let h=this.getVerticesData(f.o.PositionKind,!0,!0),l=this.getVerticesData(f.o.NormalKind),c=this.getVerticesData(f.o.UVKind),u=d.P.Zero(),_=d.P.Zero(),m=d.FM.Zero();a=a||d.FM.Zero(),n=n||new d.FM(1,1);for(let o=0;o{let i=new Float32Array(s.length*t),r=0;for(let a=0;aMath.abs(i[3*d[e]+t])&&(i[3*d[e]+t]=0),D[e]+=i[3*d[e]+t]+"|"}if(!(D[0]==D[1]||D[0]==D[2]||D[1]==D[2]))for(let e=0;e<3;e++){if(void 0===(l=b[D[e]])){b[D[e]]=y,l=y++;for(let t=0;t<3;t++)c.push(i[3*d[e]+t]);if(null!=r)for(let t=0;t<4;t++)m.push(r[4*d[e]+t]);if(null!=t)for(let s=0;s<2;s++)_.push(t[2*d[e]+s]);if(null!=a)for(let t=0;t<4;t++)I.push(a[4*d[e]+t]);if(null!=n)for(let t=0;t<4;t++)M.push(n[4*d[e]+t]);if(null!=o)for(let t=0;t<4;t++)p.push(o[4*d[e]+t]);if(null!=h)for(let t=0;t<4;t++)v.push(h[4*d[e]+t])}u.push(l)}}let S=[];g.x.ComputeNormals(c,u,S),e.positions=c,e.indices=u,e.normals=S,null!=t&&(e.uvs=_),null!=r&&(e.colors=m),null!=a&&(e.matricesIndices=I),null!=n&&(e.matricesWeights=M),null!=o&&(e.matricesIndicesExtra=p),null!=n&&(e.matricesWeightsExtra=v),e.applyToMesh(this,this.isVertexBufferUpdatable(f.o.PositionKind))}}static _instancedMeshFactory(e,t){throw(0,S.S)("InstancedMesh")}static _PhysicsImpostorParser(e,t,s){throw(0,S.S)("PhysicsImpostor")}createInstance(e){return w._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e{let t=i.length-1-e,s=i[t];for(let e=0;e{for(let e=0;e-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;t4,l=h?this.getVerticesData(f.o.MatricesIndicesExtraKind):null,c=h?this.getVerticesData(f.o.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),g=d.P.Zero(),_=new d.y3,m=new d.y3,I=0;for(let e=0;e0&&(d.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*n[I+t]),f,m),_.addToSelf(m));if(h)for(t=0;t<4;t++)(f=c[I+t])>0&&(d.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*l[I+t]),f,m),_.addToSelf(m));d.P.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],_,g),g.toArray(r,e),s&&(d.P.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],_,g),g.toArray(a,e)),_.reset()}return this.updateVerticesData(f.o.PositionKind,r),s&&this.updateVerticesData(f.o.NormalKind,a),this}static MinMax(e){let t=null,s=null;return(e.forEach(function(e){let 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:d.P.Zero(),max:d.P.Zero()}}static Center(e){let t=e instanceof Array?w.MinMax(e):e;return d.P.Center(t.min,t.max)}static MergeMeshes(e,t=!0,s,i,r,a){return(0,o.s3)(w._MergeMeshesCoroutine(e,t,s,i,r,a,!1))}static MergeMeshesAsync(e,t=!0,s,i,r,a){return(0,o.sM)(w._MergeMeshesCoroutine(e,t,s,i,r,a,!0),(0,o.KO)())}static*_MergeMeshesCoroutine(e,t=!0,s,i,r,a,n){let o;if(0===(e=e.filter(Boolean)).length)return null;if(!s){let t=0;for(o=0;o=65536)return y.Y.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(r=!1);let h=[],l=[],d=[],c=e[0].overrideMaterialSideOrientation;for(o=0;oh.indexOf(e.subMaterials[t])&&h.push(e.subMaterials[t]);for(let s=0;sh.indexOf(e)&&h.push(e);for(let s=0;s{let t=e.computeWorldMatrix(!0);return{vertexData:g.x.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:_,transform:m}=f(u);n&&(yield);let M=Array(e.length-1);for(let t=1;t{throw(0,S.S)("GroundMesh")},w._GoldbergMeshParser=(e,t)=>{throw(0,S.S)("GoldbergMesh")},w._LinesMeshParser=(e,t)=>{throw(0,S.S)("LinesMesh")},w._GreasedLineMeshParser=(e,t)=>{throw(0,S.S)("GreasedLineMesh")},w._GreasedLineRibbonMeshParser=(e,t)=>{throw(0,S.S)("GreasedLineRibbonMesh")},w._TrailMeshParser=(e,t)=>{throw(0,S.S)("TrailMesh")},(0,b.H)("BABYLON.Mesh",w)}}]); \ No newline at end of file diff --git a/.next/static/chunks/1f3d3139-f107a678ff6361e9.js b/.next/static/chunks/1f3d3139-f107a678ff6361e9.js deleted file mode 100644 index bbda3dd..0000000 --- a/.next/static/chunks/1f3d3139-f107a678ff6361e9.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[105],{3249:function(e,t,s){s.d(t,{Kj:function(){return Mesh},gW:function(){return _CreationDataStorage}});var i=s(4800),r=s(5132),a=s(3189),n=s(1803),o=s(7521),h=s(555),l=s(6540),d=s(78),c=s(2983),u=s(208),f=s(1295),g=s(2696),_=s(1687),m=s(7042),M=s(1091),I=s(2515),p=s(5461),v=s(2697),D=s(1760),y=s(9626),b=s(3048),S=s(6131),x=s(7609),B=s(4926);let _CreationDataStorage=class _CreationDataStorage{};let _InstanceDataStorage=class _InstanceDataStorage{constructor(){this.visibleInstances={},this.batchCache=new _InstancesBatch,this.batchCacheReplacementModeInFrozenMode=new _InstancesBatch,this.instancesBufferSize=2048}};let _InstancesBatch=class _InstancesBatch{constructor(){this.mustReturn=!1,this.visibleInstances=[],this.renderSelf=[],this.hardwareInstancedRendering=[]}};let _ThinInstanceDataStorage=class _ThinInstanceDataStorage{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}};let _InternalMeshDataInfo=class _InternalMeshDataInfo{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=[],this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}};let Mesh=class Mesh extends m.x{static _GetDefaultSideOrientation(e){return e||Mesh.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(f.o.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(f.o.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 i.y$),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new i.y$),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new i.y$),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new i.y$),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new i.y$),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(){var e;return(null!==(e=this._thinInstanceDataStorage.instancesCount)&&void 0!==e?e:0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=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}constructor(e,t=null,s=null,r=null,o,h=!0){if(super(e,t),this._internalMeshDataInfo=new _InternalMeshDataInfo,this.delayLoadState=0,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new _InstanceDataStorage,this._thinInstanceDataStorage=new _ThinInstanceDataStorage,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=Mesh.DEFAULTSIDE,this.overrideMaterialSideOrientation=null,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._onBeforeDraw=(e,t,s)=>{e&&s&&(this._uniformBuffer?this.transferToEffect(t):s.bindOnlyWorldMatrix(t))},r){if(r._geometry&&r._geometry.applyToMesh(this),a.j.DeepCopy(r,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=r,t.useClonedMeshMap&&(r._internalMeshDataInfo.meshMap||(r._internalMeshDataInfo.meshMap={}),r._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=r._originalBuilderSideOrientation,this._creationDataStorage=r._creationDataStorage,r._ranges){let e=r._ranges;for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&e[t]&&this.createAnimationRange(t,e[t].from,e[t].to)}if(r.metadata&&r.metadata.clone?this.metadata=r.metadata.clone():this.metadata=r.metadata,this._internalMetadata=r._internalMetadata,n.$&&n.$.HasTags(r)&&n.$.AddTagsTo(this,n.$.GetTags(r,!0)),this.setEnabled(r.isEnabled(!1)),this.parent=r.parent,this.setPivotMatrix(r.getPivotMatrix()),this.id=e+"."+r.id,this.material=r.material,!o){let t=r.getDescendants(!0);for(let s=0;s{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 i.y$(this._internalMeshDataInfo._onMeshReadyObserverAdded),r&&r.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,s){let 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));for(let r of(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),this.getChildTransformNodes(!0)))"InstancedMesh"===r.getClassName()&&"Mesh"===i.getClassName()&&r.sourceMesh===this?r.instantiateHierarchy(i,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:i},s):r.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()+", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let s=0;s0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){let e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort((t,s)=>t.distanceOrScreenCoverages.distanceOrScreenCoverage?-e:0)}addLODLevel(e,t){if(t&&t._masterMesh)return y.Y.Warn("You cannot use a mesh as LOD level twice"),this;let s=new B.g(e,t);return this._internalMeshDataInfo._LODLevels.push(s),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){let t=this._internalMeshDataInfo;for(let s=0;sn*a)return this.onLODLevelSelection&&this.onLODLevelSelection(a,this,this),this;for(let e=0;e0||this.hasThinInstances);this.computeWorldMatrix();let u=this.material||d.defaultMaterial;if(u){if(u._storeEffectOnSubMeshes)for(let e of this.subMeshes){let t=e.getMaterial();if(t){if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,c))return!1}else if(!t.isReady(this,c))return!1}}else if(!u.isReady(this,c))return!1}let f=l.currentRenderPassId;for(let e of this.lightSources){let t=e.getShadowGenerators();if(!t)continue;let d=t.values();for(let e=d.next();!0!==e.done;e=d.next()){let t=e.value;if(t&&(!(null===(s=t.getShadowMap())||void 0===s?void 0:s.renderList)||(null===(i=t.getShadowMap())||void 0===i?void 0:i.renderList)&&(null===(a=null===(r=t.getShadowMap())||void 0===r?void 0:r.renderList)||void 0===a?void 0:a.indexOf(this))!==-1)){let e=t.getShadowMap(),s=null!==(n=e.renderPassIds)&&void 0!==n?n:[l.currentRenderPassId];for(let e=0;e0){let s=this.getIndices();if(!s)return null;let i=s.length,r=!1;if(e)r=!0;else for(let e of this.subMeshes)if(e.indexStart+e.indexCount>i||e.verticesStart+e.verticesCount>t){r=!0;break}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new M.P(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;let t=this.getTotalIndices(),s=t/e|0,i=0;for(;s%3!=0;)s++;this.releaseSubMeshes();for(let r=0;r=t);r++)M.P.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{let i=new g.x;i.set(t,e);let r=this.getScene();new _.Z(_.Z.RandomId(),r,i,s,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){let s=this.getVertexBuffer(e);s&&s.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=_.Z.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}updateMeshPositions(e,t=!0){let s=this.getVerticesData(f.o.PositionKind);if(!s)return this;if(e(s),this.updateVerticesData(f.o.PositionKind,s,!1,!1),t){let e=this.getIndices(),t=this.getVerticesData(f.o.NormalKind);if(!t)return this;g.x.ComputeNormals(s,e,t),this.updateVerticesData(f.o.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry||1===this._geometry.meshes.length)return this;let e=this._geometry,t=this._geometry.copy(_.Z.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndices(e,t=null,s=!1){if(this._geometry)this._geometry.setIndices(e,t,s);else{let t=new g.x;t.indices=e;let i=this.getScene();new _.Z(_.Z.RandomId(),i,t,s,this)}return this}updateIndices(e,t,s=!1){return this._geometry&&this._geometry.updateIndices(e,t,s),this}toLeftHanded(){return this._geometry&&this._geometry.toLeftHanded(),this}_bind(e,t,s,i=!0){let r;if(!this._geometry)return this;let a=this.getScene().getEngine();if(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(t),this._unIndexed)r=null;else switch(this._getRenderingFillMode(s)){case I.F.PointFillMode:r=null;break;case I.F.WireFrameFillMode:r=e._getLinesIndexBuffer(this.getIndices(),a);break;default:case I.F.TriangleFillMode:r=this._geometry.getIndexBuffer()}return i&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(t,r,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(t,r),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);let i=this.getScene(),r=i.getEngine();return this._unIndexed||t==I.F.PointFillMode?r.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||s):t==I.F.WireFrameFillMode?r.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||s):r.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}let s=this.getScene(),i=s._isInIntermediateRendering(),r=i?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,a=this._instanceDataStorage.batchCache;if(a.mustReturn=!1,a.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,a.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){let t=this._instanceDataStorage.visibleInstances,r=s.getRenderId(),n=i?t.intermediateDefaultRenderId:t.defaultRenderId;a.visibleInstances[e]=t[r],!a.visibleInstances[e]&&n&&(a.visibleInstances[e]=t[n])}return a.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==a.visibleInstances[e]&&void 0!==a.visibleInstances[e],this._instanceDataStorage.previousBatch=a,a}_renderWithInstances(e,t,s,i,r){var a;let n=s.visibleInstances[e._id],o=n?n.length:0,h=this._instanceDataStorage,l=h.instancesBufferSize,c=h.instancesBuffer,u=h.instancesPreviousBuffer,g=64*(o+1);for(;h.instancesBufferSizee._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera1&&c.activeCamera===c.activeCameras[0]||u<=1;if(f&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;let g=this._getInstancesRenderList(e._id,!!s);if(g.mustReturn||!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let _=c.getEngine(),m=0,M=null;this.ignoreCameraMaxZ&&c.activeCamera&&!c._isInIntermediateRendering()&&(m=c.activeCamera.maxZ,M=c.activeCamera,c.activeCamera.maxZ=0,c.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);let p=e.getRenderingMesh(),v=g.hardwareInstancedRendering[e._id]||p.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,D=this._instanceDataStorage,y=e.getMaterial();if(!y)return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this;if(D.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===y){if(y._storeEffectOnSubMeshes&&!(null===(a=e.effect)||void 0===a?void 0:a._wasPreviouslyReady)||!y._storeEffectOnSubMeshes&&!(null===(n=y.getEffect())||void 0===n?void 0:n._wasPreviouslyReady))return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this}else{if(y._storeEffectOnSubMeshes){if(!y.isReadyForSubMesh(this,e,v))return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this}else if(!y.isReady(this,v))return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=y}t&&_.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),h=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();let b=null!==(o=null==h?void 0:h.effect)&&void 0!==o?o:null;for(let t of c._beforeRenderingMeshStage)t.action(this,e,g,b);if(!h||!b)return M&&(M.maxZ=m,c.updateTransformMatrix(!0)),this;let S=s||this;if(!D.isFrozen&&(this._internalMeshDataInfo._effectiveMaterial.backFaceCulling||null!==this.overrideMaterialSideOrientation)){let e=S._getWorldMatrixDeterminant();null==(d=this.overrideMaterialSideOrientation)&&(d=this._internalMeshDataInfo._effectiveMaterial.sideOrientation),e<0&&(d=d===I.F.ClockWiseSideOrientation?I.F.CounterClockWiseSideOrientation:I.F.ClockWiseSideOrientation),D.sideOrientation=d}else d=D.sideOrientation;let x=this._internalMeshDataInfo._effectiveMaterial._preBind(h,d);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&_.setDepthWrite(!0);let B=this._internalMeshDataInfo._effectiveMaterial,P=B.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),v||this._bind(e,b,P,!1);let A=S.getWorldMatrix();for(let t of(B._storeEffectOnSubMeshes?B.bindForSubMesh(A,this,e):B.bind(A,this),!B.backFaceCulling&&B.separateCullingPass&&(_.setState(!0,B.zOffset,!1,!x,B.cullBackFaces,B.stencil,B.zOffsetUnits),this._processRendering(this,e,b,P,g,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),_.setState(!0,B.zOffset,!1,x,B.cullBackFaces,B.stencil,B.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,b,P,g,v,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind(),c._afterRenderingMeshStage))t.action(this,e,g,b);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),M&&(M.maxZ=m,c.updateTransformMatrix(!0)),c.performancePriority!==l.a.Aggressive||D.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(f.o.MatricesWeightsKind)&&(this.isVerticesDataPresent(f.o.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){let e=this.getVerticesData(f.o.MatricesWeightsKind),t=e.length;for(let s=0;ss&&i++,0!==a&&c++,d+=a,s=a}if(h[c]++,c>a&&(a=c),0===d)r++;else{let s=1/d,i=0;for(let r=0;r.001&&n++}}let l=this.skeleton.bones.length,d=this.getVerticesData(f.o.MatricesIndicesKind),c=this.getVerticesData(f.o.MatricesIndicesExtraKind),u=0;for(let e=0;e=l||s<0)&&u++}let g="Number of Weights = "+s/4+"\nMaximum influences = "+a+"\nMissing Weights = "+r+"\nNot Sorted = "+i+"\nNot Normalized = "+n+"\nWeightCounts = ["+h+"]\nNumber of bones = "+l+"\nBad Bone Indices = "+u;return{skinned:!0,valid:0===r&&0===n&&0===u,report:g}}_checkDelayState(){let e=this.getScene();return this._geometry?this._geometry.load(e):4===this.delayLoadState&&(this.delayLoadState=2,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);let t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return r.w1.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=1,e.removePendingData(this)},()=>{},e.offlineProvider,t),this}isInFrustum(e){return!!(2!==this.delayLoadState&&super.isInFrustum(e))&&(this._checkDelayState(),!0)}setMaterialById(e){let t;let s=this.getScene().materials;for(t=s.length-1;t>-1;t--)if(s[t].id===e)return this.material=s[t],this;let i=this.getScene().multiMaterials;for(t=i.length-1;t>-1;t--)if(i[t].id===e){this.material=i[t];break}return this}getAnimatables(){let e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){let t;if(!this.isVerticesDataPresent(f.o.PositionKind))return this;let s=this.subMeshes.splice(0);this._resetPointsArrayCache();let i=this.getVerticesData(f.o.PositionKind),r=d.P.Zero();for(t=0;te.determinant()&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=s,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions?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 Mesh(e,this.getScene(),t,this,s,i)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);let 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(let e in s.meshMap){let 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{let e=this.getScene().meshes;for(let t of e)t._internalMeshDataInfo&&t._internalMeshDataInfo._source&&t._internalMeshDataInfo._source===this&&(t._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,a,n,o=!1){let h=this.getScene();return r.w1.LoadImage(e,e=>{let r=e.width,h=e.height,l=this.getEngine().createCanvas(r,h),d=l.getContext("2d");d.drawImage(e,0,0);let c=d.getImageData(0,0,r,h).data;this.applyDisplacementMapFromBuffer(c,r,h,t,s,a,n,o),i&&i(this)},()=>{},h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,s,i,r,a,n,o=!1){if(!this.isVerticesDataPresent(f.o.PositionKind)||!this.isVerticesDataPresent(f.o.NormalKind)||!this.isVerticesDataPresent(f.o.UVKind))return y.Y.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;let h=this.getVerticesData(f.o.PositionKind,!0,!0),l=this.getVerticesData(f.o.NormalKind),c=this.getVerticesData(f.o.UVKind),u=d.P.Zero(),_=d.P.Zero(),m=d.FM.Zero();a=a||d.FM.Zero(),n=n||new d.FM(1,1);for(let o=0;o{let i=new Float32Array(s.length*t),r=0;for(let a=0;aMath.abs(i[3*d[e]+t])&&(i[3*d[e]+t]=0),D[e]+=i[3*d[e]+t]+"|"}if(!(D[0]==D[1]||D[0]==D[2]||D[1]==D[2]))for(let e=0;e<3;e++){if(void 0===(l=b[D[e]])){b[D[e]]=y,l=y++;for(let t=0;t<3;t++)c.push(i[3*d[e]+t]);if(null!=r)for(let t=0;t<4;t++)m.push(r[4*d[e]+t]);if(null!=t)for(let s=0;s<2;s++)_.push(t[2*d[e]+s]);if(null!=a)for(let t=0;t<4;t++)M.push(a[4*d[e]+t]);if(null!=n)for(let t=0;t<4;t++)I.push(n[4*d[e]+t]);if(null!=o)for(let t=0;t<4;t++)p.push(o[4*d[e]+t]);if(null!=h)for(let t=0;t<4;t++)v.push(h[4*d[e]+t])}u.push(l)}}let S=[];g.x.ComputeNormals(c,u,S),e.positions=c,e.indices=u,e.normals=S,null!=t&&(e.uvs=_),null!=r&&(e.colors=m),null!=a&&(e.matricesIndices=M),null!=n&&(e.matricesWeights=I),null!=o&&(e.matricesIndicesExtra=p),null!=n&&(e.matricesWeightsExtra=v),e.applyToMesh(this,this.isVertexBufferUpdatable(f.o.PositionKind))}}static _instancedMeshFactory(e,t){throw(0,S.S)("InstancedMesh")}static _PhysicsImpostorParser(e,t,s){throw(0,S.S)("PhysicsImpostor")}createInstance(e){return Mesh._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e{let t=i.length-1-e,s=i[t];for(let e=0;e{for(let e=0;e-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;t4,l=h?this.getVerticesData(f.o.MatricesIndicesExtraKind):null,c=h?this.getVerticesData(f.o.MatricesWeightsExtraKind):null,u=e.getTransformMatrices(this),g=d.P.Zero(),_=new d.y3,m=new d.y3,M=0;for(let e=0;e0&&(d.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*n[M+t]),f,m),_.addToSelf(m));if(h)for(t=0;t<4;t++)(f=c[M+t])>0&&(d.y3.FromFloat32ArrayToRefScaled(u,Math.floor(16*l[M+t]),f,m),_.addToSelf(m));d.P.TransformCoordinatesFromFloatsToRef(i._sourcePositions[e],i._sourcePositions[e+1],i._sourcePositions[e+2],_,g),g.toArray(r,e),s&&(d.P.TransformNormalFromFloatsToRef(i._sourceNormals[e],i._sourceNormals[e+1],i._sourceNormals[e+2],_,g),g.toArray(a,e)),_.reset()}return this.updateVerticesData(f.o.PositionKind,r),s&&this.updateVerticesData(f.o.NormalKind,a),this}static MinMax(e){let t=null,s=null;return(e.forEach(function(e){let i=e.getBoundingInfo(),r=i.boundingBox;t&&s?(t.minimizeInPlace(r.minimumWorld),s.maximizeInPlace(r.maximumWorld)):(t=r.minimumWorld,s=r.maximumWorld)}),t&&s)?{min:t,max:s}:{min:d.P.Zero(),max:d.P.Zero()}}static Center(e){let t=e instanceof Array?Mesh.MinMax(e):e;return d.P.Center(t.min,t.max)}static MergeMeshes(e,t=!0,s,i,r,a){return(0,o.s3)(Mesh._MergeMeshesCoroutine(e,t,s,i,r,a,!1))}static MergeMeshesAsync(e,t=!0,s,i,r,a){return(0,o.sM)(Mesh._MergeMeshesCoroutine(e,t,s,i,r,a,!0),(0,o.KO)())}static*_MergeMeshesCoroutine(e,t=!0,s,i,r,a,n){let o;if(0===(e=e.filter(Boolean)).length)return null;if(!s){let t=0;for(o=0;o=65536)return y.Y.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}a&&(r=!1);let h=[],l=[],d=[],c=e[0].overrideMaterialSideOrientation;for(o=0;oh.indexOf(e.subMaterials[t])&&h.push(e.subMaterials[t]);for(let s=0;sh.indexOf(e)&&h.push(e);for(let s=0;s{let t=e.computeWorldMatrix(!0),s=g.x.ExtractFromMesh(e,!1,!1);return{vertexData:s,transform:t}},{vertexData:f,transform:_}=getVertexDataFromMesh(u);n&&(yield);let m=Array(e.length-1);for(let t=1;t{throw(0,S.S)("GroundMesh")},Mesh._GoldbergMeshParser=(e,t)=>{throw(0,S.S)("GoldbergMesh")},Mesh._LinesMeshParser=(e,t)=>{throw(0,S.S)("LinesMesh")},Mesh._GreasedLineMeshParser=(e,t)=>{throw(0,S.S)("GreasedLineMesh")},Mesh._GreasedLineRibbonMeshParser=(e,t)=>{throw(0,S.S)("GreasedLineRibbonMesh")},Mesh._TrailMeshParser=(e,t)=>{throw(0,S.S)("TrailMesh")},(0,b.H)("BABYLON.Mesh",Mesh)}}]); \ No newline at end of file diff --git a/.next/static/chunks/255.f5115df174538d84.js b/.next/static/chunks/255.f5115df174538d84.js new file mode 100644 index 0000000..7cb6f0c --- /dev/null +++ b/.next/static/chunks/255.f5115df174538d84.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[255],{5619:function(n,e,r){r.r(e),r.d(e,{default:function(){return o}});var t=r(7437),i=r(2265),s=r(4672),a=r(3693);class o extends i.PureComponent{componentDidMount(){console.clear(),this.setup(this.canvas)}render(){return(0,t.jsx)(t.Fragment,{children:(0,t.jsx)("canvas",{id:this.id,ref:this.onMount,style:f})})}constructor(...n){super(...n),this.setup=async n=>{s.vGS.ShadersStoreWGSL.starsPixelShader="\n uniform seed : f32;\n uniform density : f32;\n uniform brightness : f32;\n\n fn rand(seed : vec2) -> f32 {\n return fract(sin(dot(seed, vec2(12.9898, 78.233))) * 43758.5453);\n }\n\n @fragment\n fn main(input : FragmentInputs) -> FragmentOutputs {\n\n let random = rand(input.vUV*uniforms.seed);\n var brightness = 0.0;\n if (random < uniforms.density){\n brightness = random/uniforms.density*uniforms.brightness;\n }\n //fragmentOutputs.color = vec4(1., 1., 1., brightness);\n fragmentOutputs.color = vec4(brightness, brightness, brightness, 1.);\n }\n ",s.vGS.ShadersStoreWGSL.nebulasPixelShader="\n var textureSampler: texture_2d;\n var textureSamplerSampler: sampler;\n\n uniform seed: f32;\n uniform color: vec4;\n uniform nebulascale: u32;\n uniform depth: u32;\n uniform intensity: f32;\n uniform falloff: f32;\n uniform persistence: f32;\n\n fn mod289(x: vec2) -> vec2 {\n return x - floor(x * (1. / 289.)) * 289.;\n }\n \n fn mod289_3(x: vec3) -> vec3 {\n return x - floor(x * (1. / 289.)) * 289.;\n }\n \n fn permute3(x: vec3) -> vec3 {\n return mod289_3(((x * 34.) + 1.) * x);\n }\n \n // MIT License. \xa9 Ian McEwan, Stefan Gustavson, Munrocket\n fn simplexNoise2(v: vec2) -> f32 {\n let C = vec4(\n 0.211324865405187, // (3.0-sqrt(3.0))/6.0\n 0.366025403784439, // 0.5*(sqrt(3.0)-1.0)\n -0.577350269189626, // -1.0 + 2.0 * C.x\n 0.024390243902439 // 1.0 / 41.0\n );\n \n // First corner\n var i = floor(v + dot(v, C.yy));\n let x0 = v - i + dot(i, C.xx);\n \n // Other corners\n var i1 = select(vec2(0., 1.), vec2(1., 0.), x0.x > x0.y);\n \n // x0 = x0 - 0.0 + 0.0 * C.xx ;\n // x1 = x0 - i1 + 1.0 * C.xx ;\n // x2 = x0 - 1.0 + 2.0 * C.xx ;\n var x12 = x0.xyxy + C.xxzz;\n x12.x = x12.x - i1.x;\n x12.y = x12.y - i1.y;\n \n // Permutations\n i = mod289(i); // Avoid truncation effects in permutation\n \n var p = permute3(permute3(i.y + vec3(0., i1.y, 1.)) + i.x + vec3(0., i1.x, 1.));\n var m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), vec3(0.));\n m *= m;\n m *= m;\n \n // Gradients: 41 points uniformly over a line, mapped onto a diamond.\n // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)\n let x = 2. * fract(p * C.www) - 1.;\n let h = abs(x) - 0.5;\n let ox = floor(x + 0.5);\n let a0 = x - ox;\n \n // Normalize gradients implicitly by scaling m\n // Approximation of: m *= inversesqrt( a0*a0 + h*h );\n m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\n \n // Compute final noise value at P\n let g = vec3(a0.x * x0.x + h.x * x0.y, a0.yz * x12.xz + h.yz * x12.yw);\n return 130. * dot(m, g);\n }\n\n fn normalNoise(v: vec2) -> f32 {\n return simplexNoise2(v)*0.5 + 0.5;\n }\n\n @fragment\n fn main(input : FragmentInputs) -> FragmentOutputs {\n let sampleColor = textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV);\n\n var offset = 0.;\n let scaledUV = (input.vUV+offset+uniforms.seed)*f32(uniforms.nebulascale)/uniforms.scale;\n\n var displace = 0.;\n var i=u32(0);\n for (i=0; i{let e;return await s.fWK.IsSupportedAsync?(e=new s.fWK(n),await e.initAsync()):(console.log("WebGPU is not supported (or turned on) for this browser!"),e=new s.fWK(n)),e},this.id="Babylon",this.onMount=n=>this.canvas=n}}let f={width:window.innerWidth,height:window.innerHeight,background:"transparent"}}}]); \ No newline at end of file diff --git a/.next/static/chunks/472-51fd3a56159f1e5b.js b/.next/static/chunks/472-51fd3a56159f1e5b.js deleted file mode 100644 index 66d69cd..0000000 --- a/.next/static/chunks/472-51fd3a56159f1e5b.js +++ /dev/null @@ -1,25 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[472],{5844:function(t,r){"use strict";function getDeploymentIdQueryOrEmptyString(){return""}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"getDeploymentIdQueryOrEmptyString",{enumerable:!0,get:function(){return getDeploymentIdQueryOrEmptyString}})},2335:function(){"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var t=/\((.*)\)/.exec(this.toString());return t?t[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(t,r){return r=this.concat.apply([],this),t>1&&r.some(Array.isArray)?r.flat(t-1):r},Array.prototype.flatMap=function(t,r){return this.map(t,r).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(t){if("function"!=typeof t)return this.then(t,t);var r=this.constructor||Promise;return this.then(function(n){return r.resolve(t()).then(function(){return n})},function(n){return r.resolve(t()).then(function(){throw n})})}),Object.fromEntries||(Object.fromEntries=function(t){return Array.from(t).reduce(function(t,r){return t[r[0]]=r[1],t},{})}),Array.prototype.at||(Array.prototype.at=function(t){var r=Math.trunc(t)||0;if(r<0&&(r+=this.length),!(r<0||r>=this.length))return this[r]})},9872:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"addBasePath",{enumerable:!0,get:function(){return addBasePath}});let o=n(8356),a=n(3997);function addBasePath(t,r){return(0,a.normalizePathTrailingSlash)((0,o.addPathPrefix)(t,""))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5354:function(t,r){"use strict";function loadScriptsInSequence(t,r){return t&&t.length?t.reduce((t,r)=>{let[n,o]=r;return t.then(()=>new Promise((t,r)=>{let a=document.createElement("script");if(o)for(let t in o)"children"!==t&&a.setAttribute(t,o[t]);n?(a.src=n,a.onload=()=>t(),a.onerror=r):o&&(a.innerHTML=o.children,setTimeout(t)),document.head.appendChild(a)}))},Promise.resolve()).catch(t=>{console.error(t)}).then(()=>{r()}):r()}function appBootstrap(t){loadScriptsInSequence(self.__next_s,()=>{t()})}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"appBootstrap",{enumerable:!0,get:function(){return appBootstrap}}),window.next={version:"14.0.1",appDir:!0},("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5231:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"callServer",{enumerable:!0,get:function(){return callServer}});let o=n(3728);async function callServer(t,r){let n=(0,o.getServerActionDispatcher)();if(!n)throw Error("Invariant: missing action dispatcher.");return new Promise((o,a)=>{n({actionId:t,actionArgs:r,resolve:o,reject:a})})}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},811:function(t,r,n){"use strict";let o,a;Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"hydrate",{enumerable:!0,get:function(){return hydrate}});let u=n(1024),i=n(8533);n(2335);let s=u._(n(4040)),d=i._(n(2265)),p=n(6671),_=n(1852);n(6313);let b=u._(n(2504)),m=n(5231),j=n(4119),C=window.console.error;window.console.error=function(){for(var t=arguments.length,r=Array(t),n=0;n{if((0,j.isNextRouterError)(t.error)){t.preventDefault();return}});let w=document,getCacheKey=()=>{let{pathname:t,search:r}=location;return t+r},D=new TextEncoder,U=!1,B=!1,$=null;function nextServerDataCallback(t){if(0===t[0])o=[];else if(1===t[0]){if(!o)throw Error("Unexpected server data: missing bootstrap script.");a?a.enqueue(D.encode(t[1])):o.push(t[1])}else 2===t[0]&&($=t[1])}function nextServerDataRegisterWriter(t){o&&(o.forEach(r=>{t.enqueue(D.encode(r))}),U&&!B&&(t.close(),B=!0,o=void 0)),a=t}let DOMContentLoaded=function(){a&&!B&&(a.close(),B=!0,o=void 0),U=!0};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",DOMContentLoaded,!1):DOMContentLoaded();let K=self.__next_f=self.__next_f||[];function createResponseCache(){return new Map}K.forEach(nextServerDataCallback),K.push=nextServerDataCallback;let q=createResponseCache();function useInitialServerResponse(t){let r=q.get(t);if(r)return r;let n=new ReadableStream({start(t){nextServerDataRegisterWriter(t)}}),o=(0,p.createFromReadableStream)(n,{callServer:m.callServer});return q.set(t,o),o}function ServerRoot(t){let{cacheKey:r}=t;d.default.useEffect(()=>{q.delete(r)});let n=useInitialServerResponse(r),o=(0,d.use)(n);return o}let ee=d.default.StrictMode;function Root(t){let{children:r}=t;return r}function RSCComponent(t){return d.default.createElement(ServerRoot,{...t,cacheKey:getCacheKey()})}function hydrate(){let t=d.default.createElement(ee,null,d.default.createElement(_.HeadManagerContext.Provider,{value:{appDir:!0}},d.default.createElement(Root,null,d.default.createElement(RSCComponent,null)))),r={onRecoverableError:b.default},n="__next_error__"===document.documentElement.id;n?s.default.createRoot(w,r).render(t):d.default.startTransition(()=>s.default.hydrateRoot(w,t,{...r,formState:$}))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2019:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0});let o=n(5354);(0,o.appBootstrap)(()=>{n(1055);let{hydrate:t}=n(811);n(3728),n(6954),t()}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1055:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),n(5844);{let t=n.u;n.u=function(){for(var r=arguments.length,n=Array(r),o=0;o{let t=getAnnouncerNode();return i(t),()=>{let t=document.getElementsByTagName(u)[0];(null==t?void 0:t.isConnected)&&document.body.removeChild(t)}},[]);let[s,d]=(0,o.useState)(""),p=(0,o.useRef)();return(0,o.useEffect)(()=>{let t="";if(document.title)t=document.title;else{let r=document.querySelector("h1");r&&(t=r.innerText||r.textContent||"")}void 0!==p.current&&p.current!==t&&d(t),p.current=t},[r]),n?(0,a.createPortal)(s,n):null}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8343:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{RSC:function(){return n},ACTION:function(){return o},NEXT_ROUTER_STATE_TREE:function(){return a},NEXT_ROUTER_PREFETCH:function(){return u},NEXT_URL:function(){return i},RSC_CONTENT_TYPE_HEADER:function(){return s},RSC_VARY_HEADER:function(){return d},FLIGHT_PARAMETERS:function(){return p},NEXT_RSC_UNION_QUERY:function(){return _}});let n="RSC",o="Next-Action",a="Next-Router-State-Tree",u="Next-Router-Prefetch",i="Next-Url",s="text/x-component",d=n+", "+a+", "+u+", "+i,p=[[n],[a],[u]],_="_rsc";("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3728:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{getServerActionDispatcher:function(){return getServerActionDispatcher},urlToUrlWithoutFlightMarker:function(){return urlToUrlWithoutFlightMarker},default:function(){return AppRouter}});let o=n(8533),a=o._(n(2265)),u=n(6313),i=n(7205),s=n(9706),d=n(2301),p=n(7407),_=n(2327),b=n(9928),m=n(5311),j=n(2169),C=n(9872),w=n(8325),D=n(5138),U=n(6700),B=n(3085),$=n(8343),K=n(3714),q=n(6746),ee=new Map,et=null;function getServerActionDispatcher(){return et}let er={refresh:()=>{}};function urlToUrlWithoutFlightMarker(t){let r=new URL(t,location.origin);return r.searchParams.delete($.NEXT_RSC_UNION_QUERY),r}function isExternalURL(t){return t.origin!==window.location.origin}function HistoryUpdater(t){let{tree:r,pushRef:n,canonicalUrl:o,sync:u}=t;return(0,a.useInsertionEffect)(()=>{let t={__NA:!0,tree:r};n.pendingPush&&(0,d.createHrefFromUrl)(new URL(window.location.href))!==o?(n.pendingPush=!1,window.history.pushState(t,"",o)):window.history.replaceState(t,"",o),u()},[r,n,o,u]),null}let createEmptyCacheNode=()=>({status:u.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map});function useServerActionDispatcher(t){let r=(0,a.useCallback)(r=>{(0,a.startTransition)(()=>{t({...r,type:s.ACTION_SERVER_ACTION,mutable:{globalMutable:er},cache:createEmptyCacheNode()})})},[t]);et=r}function useChangeByServerResponse(t){return(0,a.useCallback)((r,n,o)=>{(0,a.startTransition)(()=>{t({type:s.ACTION_SERVER_PATCH,flightData:n,previousTree:r,overrideCanonicalUrl:o,cache:createEmptyCacheNode(),mutable:{globalMutable:er}})})},[t])}function useNavigate(t){return(0,a.useCallback)((r,n,o,a)=>{let u=new URL((0,C.addBasePath)(r),location.href);return er.pendingNavigatePath=(0,d.createHrefFromUrl)(u),t({type:s.ACTION_NAVIGATE,url:u,isExternalUrl:isExternalURL(u),locationSearch:location.search,forceOptimisticNavigation:o,shouldScroll:null==a||a,navigateType:n,cache:createEmptyCacheNode(),mutable:{globalMutable:er}})},[t])}function Router(t){let{buildId:r,initialHead:n,initialTree:o,initialCanonicalUrl:d,children:b,assetPrefix:$}=t,et=(0,a.useMemo)(()=>(0,m.createInitialRouterState)({buildId:r,children:b,initialCanonicalUrl:d,initialTree:o,initialParallelRoutes:ee,isServer:!1,location:window.location,initialHead:n}),[r,b,d,o,n]),[{tree:en,cache:eo,prefetchCache:eu,pushRef:el,focusAndScrollRef:ei,canonicalUrl:ec,nextUrl:es},ef,ed]=(0,_.useReducerWithReduxDevtools)(i.reducer,et);(0,a.useEffect)(()=>{ee=null},[]);let{searchParams:ep,pathname:eh}=(0,a.useMemo)(()=>{let t=new URL(ec,window.location.href);return{searchParams:t.searchParams,pathname:(0,q.hasBasePath)(t.pathname)?(0,K.removeBasePath)(t.pathname):t.pathname}},[ec]),e_=useChangeByServerResponse(ef),ey=useNavigate(ef);useServerActionDispatcher(ef);let eg=(0,a.useMemo)(()=>{let t={back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(t,r)=>{if((0,j.isBot)(window.navigator.userAgent))return;let n=new URL((0,C.addBasePath)(t),location.href);isExternalURL(n)||(0,a.startTransition)(()=>{var t;ef({type:s.ACTION_PREFETCH,url:n,kind:null!=(t=null==r?void 0:r.kind)?t:s.PrefetchKind.FULL})})},replace:(t,r)=>{void 0===r&&(r={}),(0,a.startTransition)(()=>{var n;ey(t,"replace",!!r.forceOptimisticNavigation,null==(n=r.scroll)||n)})},push:(t,r)=>{void 0===r&&(r={}),(0,a.startTransition)(()=>{var n;ey(t,"push",!!r.forceOptimisticNavigation,null==(n=r.scroll)||n)})},refresh:()=>{(0,a.startTransition)(()=>{ef({type:s.ACTION_REFRESH,cache:createEmptyCacheNode(),mutable:{globalMutable:er},origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}};return t},[ef,ey]);if((0,a.useEffect)(()=>{window.next&&(window.next.router=eg)},[eg]),(0,a.useEffect)(()=>{er.refresh=eg.refresh},[eg.refresh]),(0,a.useEffect)(()=>{function handlePageShow(t){var r;t.persisted&&(null==(r=window.history.state)?void 0:r.tree)&&ef({type:s.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.tree})}return window.addEventListener("pageshow",handlePageShow),()=>{window.removeEventListener("pageshow",handlePageShow)}},[ef]),el.mpaNavigation){if(er.pendingMpaPath!==ec){let t=window.location;el.pendingPush?t.assign(ec):t.replace(ec),er.pendingMpaPath=ec}(0,a.use)((0,B.createInfinitePromise)())}let eb=(0,a.useCallback)(t=>{let{state:r}=t;if(r){if(!r.__NA){window.location.reload();return}(0,a.startTransition)(()=>{ef({type:s.ACTION_RESTORE,url:new URL(window.location.href),tree:r.tree})})}},[ef]);(0,a.useEffect)(()=>(window.addEventListener("popstate",eb),()=>{window.removeEventListener("popstate",eb)}),[eb]);let em=(0,a.useMemo)(()=>(0,U.findHeadInCache)(eo,en[1]),[eo,en]),ev=a.default.createElement(D.RedirectBoundary,null,em,eo.subTreeData,a.default.createElement(w.AppRouterAnnouncer,{tree:en}));return a.default.createElement(a.default.Fragment,null,a.default.createElement(HistoryUpdater,{tree:en,pushRef:el,canonicalUrl:ec,sync:ed}),a.default.createElement(p.PathnameContext.Provider,{value:eh},a.default.createElement(p.SearchParamsContext.Provider,{value:ep},a.default.createElement(u.GlobalLayoutRouterContext.Provider,{value:{buildId:r,changeByServerResponse:e_,tree:en,focusAndScrollRef:ei,nextUrl:es}},a.default.createElement(u.AppRouterContext.Provider,{value:eg},a.default.createElement(u.LayoutRouterContext.Provider,{value:{childNodes:eo.parallelRoutes,tree:en,url:ec}},ev))))))}function AppRouter(t){let{globalErrorComponent:r,...n}=t;return a.default.createElement(b.ErrorBoundary,{errorComponent:r},a.default.createElement(Router,n))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3940:function(t,r,n){"use strict";function clientHookInServerComponentError(t){}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"clientHookInServerComponentError",{enumerable:!0,get:function(){return clientHookInServerComponentError}}),n(1024),n(2265),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},9928:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{ErrorBoundaryHandler:function(){return ErrorBoundaryHandler},GlobalError:function(){return GlobalError},default:function(){return s},ErrorBoundary:function(){return ErrorBoundary}});let o=n(1024),a=o._(n(2265)),u=n(94),i={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function HandleISRError(t){let{error:r}=t;if("function"==typeof fetch.__nextGetStaticStore){var n;let t=null==(n=fetch.__nextGetStaticStore())?void 0:n.getStore();if((null==t?void 0:t.isRevalidate)||(null==t?void 0:t.isStaticGeneration))throw console.error(r),r}return null}let ErrorBoundaryHandler=class ErrorBoundaryHandler extends a.default.Component{static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,r){return t.pathname!==r.previousPathname&&r.error?{error:null,previousPathname:t.pathname}:{error:r.error,previousPathname:t.pathname}}render(){return this.state.error?a.default.createElement(a.default.Fragment,null,a.default.createElement(HandleISRError,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,a.default.createElement(this.props.errorComponent,{error:this.state.error,reset:this.reset})):this.props.children}constructor(t){super(t),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}};function GlobalError(t){let{error:r}=t,n=null==r?void 0:r.digest;return a.default.createElement("html",{id:"__next_error__"},a.default.createElement("head",null),a.default.createElement("body",null,a.default.createElement(HandleISRError,{error:r}),a.default.createElement("div",{style:i.error},a.default.createElement("div",null,a.default.createElement("h2",{style:i.text},"Application error: a "+(n?"server":"client")+"-side exception has occurred (see the "+(n?"server logs":"browser console")+" for more information)."),n?a.default.createElement("p",{style:i.text},"Digest: "+n):null))))}let s=GlobalError;function ErrorBoundary(t){let{errorComponent:r,errorStyles:n,errorScripts:o,children:i}=t,s=(0,u.usePathname)();return r?a.default.createElement(ErrorBoundaryHandler,{pathname:s,errorComponent:r,errorStyles:n,errorScripts:o},i):a.default.createElement(a.default.Fragment,null,i)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1351:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{DYNAMIC_ERROR_CODE:function(){return n},DynamicServerError:function(){return DynamicServerError}});let n="DYNAMIC_SERVER_USAGE";let DynamicServerError=class DynamicServerError extends Error{constructor(t){super("Dynamic server usage: "+t),this.digest=n}};("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3085:function(t,r){"use strict";let n;function createInfinitePromise(){return n||(n=new Promise(()=>{})),n}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createInfinitePromise",{enumerable:!0,get:function(){return createInfinitePromise}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},4119:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"isNextRouterError",{enumerable:!0,get:function(){return isNextRouterError}});let o=n(9273),a=n(8466);function isNextRouterError(t){return t&&t.digest&&((0,a.isRedirectError)(t)||(0,o.isNotFoundError)(t))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6954:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return OuterLayoutRouter}});let o=n(1024),a=n(8533),u=a._(n(2265)),i=o._(n(4887)),s=n(6313),d=n(8146),p=n(3085),_=n(9928),b=n(8163),m=n(280),j=n(5138),C=n(3170),w=n(1263),D=n(3322),U=n(3559);function walkAddRefetch(t,r){if(t){let[n,o]=t,a=2===t.length;if((0,b.matchSegment)(r[0],n)&&r[1].hasOwnProperty(o)){if(a){let t=walkAddRefetch(void 0,r[1][o]);return[r[0],{...r[1],[o]:[t[0],t[1],t[2],"refetch"]}]}return[r[0],{...r[1],[o]:walkAddRefetch(t.slice(2),r[1][o])}]}}return r}function findDOMNode(t){return i.default.findDOMNode(t)}let B=["bottom","height","left","right","top","width","x","y"];function shouldSkipElement(t){if(["sticky","fixed"].includes(getComputedStyle(t).position))return!0;let r=t.getBoundingClientRect();return B.every(t=>0===r[t])}function topOfElementInViewport(t,r){let n=t.getBoundingClientRect();return n.top>=0&&n.top<=r}function getHashFragmentDomNode(t){var r;return"top"===t?document.body:null!=(r=document.getElementById(t))?r:document.getElementsByName(t)[0]}let InnerScrollAndFocusHandler=class InnerScrollAndFocusHandler extends u.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...t){super(...t),this.handlePotentialScroll=()=>{let{focusAndScrollRef:t,segmentPath:r}=this.props;if(t.apply){if(0!==t.segmentPaths.length&&!t.segmentPaths.some(t=>r.every((r,n)=>(0,b.matchSegment)(r,t[n]))))return;let n=null,o=t.hashFragment;if(o&&(n=getHashFragmentDomNode(o)),n||(n=findDOMNode(this)),!(n instanceof Element))return;for(;!(n instanceof HTMLElement)||shouldSkipElement(n);){if(null===n.nextElementSibling)return;n=n.nextElementSibling}t.apply=!1,t.hashFragment=null,t.segmentPaths=[],(0,m.handleSmoothScroll)(()=>{if(o){n.scrollIntoView();return}let t=document.documentElement,r=t.clientHeight;!topOfElementInViewport(n,r)&&(t.scrollTop=0,topOfElementInViewport(n,r)||n.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:t.onlyHashChange}),t.onlyHashChange=!1,n.focus()}}}};function ScrollAndFocusHandler(t){let{segmentPath:r,children:n}=t,o=(0,u.useContext)(s.GlobalLayoutRouterContext);if(!o)throw Error("invariant global layout router not mounted");return u.default.createElement(InnerScrollAndFocusHandler,{segmentPath:r,focusAndScrollRef:o.focusAndScrollRef},n)}function InnerLayoutRouter(t){let{parallelRouterKey:r,url:n,childNodes:o,childProp:a,segmentPath:i,tree:_,cacheKey:b}=t,m=(0,u.useContext)(s.GlobalLayoutRouterContext);if(!m)throw Error("invariant global layout router not mounted");let{buildId:j,changeByServerResponse:C,tree:w}=m,D=o.get(b);if(a&&null!==a.current&&(D?D.status===s.CacheStates.LAZY_INITIALIZED&&(D.status=s.CacheStates.READY,D.subTreeData=a.current):(D={status:s.CacheStates.READY,data:null,subTreeData:a.current,parallelRoutes:new Map},o.set(b,D))),!D||D.status===s.CacheStates.LAZY_INITIALIZED){let t=walkAddRefetch(["",...i],w);D={status:s.CacheStates.DATA_FETCH,data:(0,U.createRecordFromThenable)((0,d.fetchServerResponse)(new URL(n,location.origin),t,m.nextUrl,j)),subTreeData:null,head:D&&D.status===s.CacheStates.LAZY_INITIALIZED?D.head:void 0,parallelRoutes:D&&D.status===s.CacheStates.LAZY_INITIALIZED?D.parallelRoutes:new Map},o.set(b,D)}if(!D)throw Error("Child node should always exist");if(D.subTreeData&&D.data)throw Error("Child node should not have both subTreeData and data");if(D.data){let[t,r]=(0,u.use)(D.data);D.data=null,setTimeout(()=>{(0,u.startTransition)(()=>{C(w,t,r)})}),(0,u.use)((0,p.createInfinitePromise)())}D.subTreeData||(0,u.use)((0,p.createInfinitePromise)());let B=u.default.createElement(s.LayoutRouterContext.Provider,{value:{tree:_[1][r],childNodes:D.parallelRoutes,url:n}},D.subTreeData);return B}function LoadingBoundary(t){let{children:r,loading:n,loadingStyles:o,loadingScripts:a,hasLoading:i}=t;return i?u.default.createElement(u.Suspense,{fallback:u.default.createElement(u.default.Fragment,null,o,a,n)},r):u.default.createElement(u.default.Fragment,null,r)}function OuterLayoutRouter(t){let{parallelRouterKey:r,segmentPath:n,childProp:o,error:a,errorStyles:i,errorScripts:d,templateStyles:p,templateScripts:m,loading:U,loadingStyles:B,loadingScripts:$,hasLoading:K,template:q,notFound:ee,notFoundStyles:et,styles:er}=t,en=(0,u.useContext)(s.LayoutRouterContext);if(!en)throw Error("invariant expected layout router to be mounted");let{childNodes:eo,tree:eu,url:el}=en,ei=eo.get(r);ei||(ei=new Map,eo.set(r,ei));let ec=eu[1][r][0],es=o.segment,ef=(0,w.getSegmentValue)(ec),ed=[ec];return u.default.createElement(u.default.Fragment,null,er,ed.map(t=>{let er=(0,b.matchSegment)(t,es),en=(0,w.getSegmentValue)(t),eo=(0,D.createRouterCacheKey)(t);return u.default.createElement(s.TemplateContext.Provider,{key:(0,D.createRouterCacheKey)(t,!0),value:u.default.createElement(ScrollAndFocusHandler,{segmentPath:n},u.default.createElement(_.ErrorBoundary,{errorComponent:a,errorStyles:i,errorScripts:d},u.default.createElement(LoadingBoundary,{hasLoading:K,loading:U,loadingStyles:B,loadingScripts:$},u.default.createElement(C.NotFoundBoundary,{notFound:ee,notFoundStyles:et},u.default.createElement(j.RedirectBoundary,null,u.default.createElement(InnerLayoutRouter,{parallelRouterKey:r,url:el,tree:eu,childNodes:ei,childProp:er?o:null,segmentPath:n,cacheKey:eo,isActive:ef===en}))))))},p,m,q)}))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8163:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{matchSegment:function(){return matchSegment},canSegmentBeOverridden:function(){return canSegmentBeOverridden}});let o=n(5682),matchSegment=(t,r)=>"string"==typeof t?"string"==typeof r&&t===r:"string"!=typeof r&&t[0]===r[0]&&t[1]===r[1],canSegmentBeOverridden=(t,r)=>{var n;return!Array.isArray(t)&&!!Array.isArray(r)&&(null==(n=(0,o.getSegmentParam)(t))?void 0:n.param)===r[0]};("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5437:function(t,r,n){"use strict";function maybePostpone(t,r){if(!t.isStaticGeneration||!t.experimental.ppr)return;let o=n(2265);"function"==typeof o.unstable_postpone&&o.unstable_postpone(r)}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"maybePostpone",{enumerable:!0,get:function(){return maybePostpone}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},94:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{ReadonlyURLSearchParams:function(){return ReadonlyURLSearchParams},useSearchParams:function(){return useSearchParams},usePathname:function(){return usePathname},ServerInsertedHTMLContext:function(){return d.ServerInsertedHTMLContext},useServerInsertedHTML:function(){return d.useServerInsertedHTML},useRouter:function(){return useRouter},useParams:function(){return useParams},useSelectedLayoutSegments:function(){return useSelectedLayoutSegments},useSelectedLayoutSegment:function(){return useSelectedLayoutSegment},redirect:function(){return p.redirect},permanentRedirect:function(){return p.permanentRedirect},RedirectType:function(){return p.RedirectType},notFound:function(){return _.notFound}});let o=n(2265),a=n(6313),u=n(7407),i=n(3940),s=n(1263),d=n(3972),p=n(8466),_=n(9273),b=Symbol("internal for urlsearchparams readonly");function readonlyURLSearchParamsError(){return Error("ReadonlyURLSearchParams cannot be modified")}let ReadonlyURLSearchParams=class ReadonlyURLSearchParams{[Symbol.iterator](){return this[b][Symbol.iterator]()}append(){throw readonlyURLSearchParamsError()}delete(){throw readonlyURLSearchParamsError()}set(){throw readonlyURLSearchParamsError()}sort(){throw readonlyURLSearchParamsError()}constructor(t){this[b]=t,this.entries=t.entries.bind(t),this.forEach=t.forEach.bind(t),this.get=t.get.bind(t),this.getAll=t.getAll.bind(t),this.has=t.has.bind(t),this.keys=t.keys.bind(t),this.values=t.values.bind(t),this.toString=t.toString.bind(t),this.size=t.size}};function useSearchParams(){(0,i.clientHookInServerComponentError)("useSearchParams");let t=(0,o.useContext)(u.SearchParamsContext),r=(0,o.useMemo)(()=>t?new ReadonlyURLSearchParams(t):null,[t]);return r}function usePathname(){return(0,i.clientHookInServerComponentError)("usePathname"),(0,o.useContext)(u.PathnameContext)}function useRouter(){(0,i.clientHookInServerComponentError)("useRouter");let t=(0,o.useContext)(a.AppRouterContext);if(null===t)throw Error("invariant expected app router to be mounted");return t}function getSelectedParams(t,r){void 0===r&&(r={});let n=t[1];for(let t of Object.values(n)){let n=t[0],o=Array.isArray(n),a=o?n[1]:n;if(!a||a.startsWith("__PAGE__"))continue;let u=o&&("c"===n[2]||"oc"===n[2]);u?r[n[0]]=n[1].split("/"):o&&(r[n[0]]=n[1]),r=getSelectedParams(t,r)}return r}function useParams(){(0,i.clientHookInServerComponentError)("useParams");let t=(0,o.useContext)(a.GlobalLayoutRouterContext),r=(0,o.useContext)(u.PathParamsContext);return(0,o.useMemo)(()=>(null==t?void 0:t.tree)?getSelectedParams(t.tree):r,[null==t?void 0:t.tree,r])}function getSelectedLayoutSegmentPath(t,r,n,o){let a;if(void 0===n&&(n=!0),void 0===o&&(o=[]),n)a=t[1][r];else{var u;let r=t[1];a=null!=(u=r.children)?u:Object.values(r)[0]}if(!a)return o;let i=a[0],d=(0,s.getSegmentValue)(i);return!d||d.startsWith("__PAGE__")?o:(o.push(d),getSelectedLayoutSegmentPath(a,r,!1,o))}function useSelectedLayoutSegments(t){void 0===t&&(t="children"),(0,i.clientHookInServerComponentError)("useSelectedLayoutSegments");let{tree:r}=(0,o.useContext)(a.LayoutRouterContext);return getSelectedLayoutSegmentPath(r,t)}function useSelectedLayoutSegment(t){void 0===t&&(t="children"),(0,i.clientHookInServerComponentError)("useSelectedLayoutSegment");let r=useSelectedLayoutSegments(t);return 0===r.length?null:r[0]}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3170:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"NotFoundBoundary",{enumerable:!0,get:function(){return NotFoundBoundary}});let o=n(1024),a=o._(n(2265)),u=n(94);let NotFoundErrorBoundary=class NotFoundErrorBoundary extends a.default.Component{static getDerivedStateFromError(t){if((null==t?void 0:t.digest)==="NEXT_NOT_FOUND")return{notFoundTriggered:!0};throw t}static getDerivedStateFromProps(t,r){return t.pathname!==r.previousPathname&&r.notFoundTriggered?{notFoundTriggered:!1,previousPathname:t.pathname}:{notFoundTriggered:r.notFoundTriggered,previousPathname:t.pathname}}render(){return this.state.notFoundTriggered?a.default.createElement(a.default.Fragment,null,a.default.createElement("meta",{name:"robots",content:"noindex"}),!1,this.props.notFoundStyles,this.props.notFound):this.props.children}constructor(t){super(t),this.state={notFoundTriggered:!!t.asNotFound,previousPathname:t.pathname}}};function NotFoundBoundary(t){let{notFound:r,notFoundStyles:n,asNotFound:o,children:i}=t,s=(0,u.usePathname)();return r?a.default.createElement(NotFoundErrorBoundary,{pathname:s,notFound:r,notFoundStyles:n,asNotFound:o},i):a.default.createElement(a.default.Fragment,null,i)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},9273:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{notFound:function(){return notFound},isNotFoundError:function(){return isNotFoundError}});let n="NEXT_NOT_FOUND";function notFound(){let t=Error(n);throw t.digest=n,t}function isNotFoundError(t){return(null==t?void 0:t.digest)===n}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},839:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"PromiseQueue",{enumerable:!0,get:function(){return PromiseQueue}});let o=n(4677),a=n(6249);var u=a._("_maxConcurrency"),i=a._("_runningCount"),s=a._("_queue"),d=a._("_processNext");let PromiseQueue=class PromiseQueue{enqueue(t){let r,n;let a=new Promise((t,o)=>{r=t,n=o}),task=async()=>{try{o._(this,i)[i]++;let n=await t();r(n)}catch(t){n(t)}finally{o._(this,i)[i]--,o._(this,d)[d]()}};return o._(this,s)[s].push({promiseFn:a,task}),o._(this,d)[d](),a}bump(t){let r=o._(this,s)[s].findIndex(r=>r.promiseFn===t);if(r>-1){let t=o._(this,s)[s].splice(r,1)[0];o._(this,s)[s].unshift(t),o._(this,d)[d](!0)}}constructor(t=5){Object.defineProperty(this,d,{value:processNext}),Object.defineProperty(this,u,{writable:!0,value:void 0}),Object.defineProperty(this,i,{writable:!0,value:void 0}),Object.defineProperty(this,s,{writable:!0,value:void 0}),o._(this,u)[u]=t,o._(this,i)[i]=0,o._(this,s)[s]=[]}};function processNext(t){if(void 0===t&&(t=!1),(o._(this,i)[i]0){var r;null==(r=o._(this,s)[s].shift())||r.task()}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5138:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{RedirectErrorBoundary:function(){return RedirectErrorBoundary},RedirectBoundary:function(){return RedirectBoundary}});let o=n(8533),a=o._(n(2265)),u=n(94),i=n(8466);function HandleRedirect(t){let{redirect:r,reset:n,redirectType:o}=t,s=(0,u.useRouter)();return(0,a.useEffect)(()=>{a.default.startTransition(()=>{o===i.RedirectType.push?s.push(r,{}):s.replace(r,{}),n()})},[r,o,n,s]),null}let RedirectErrorBoundary=class RedirectErrorBoundary extends a.default.Component{static getDerivedStateFromError(t){if((0,i.isRedirectError)(t)){let r=(0,i.getURLFromRedirectError)(t),n=(0,i.getRedirectTypeFromError)(t);return{redirect:r,redirectType:n}}throw t}render(){let{redirect:t,redirectType:r}=this.state;return null!==t&&null!==r?a.default.createElement(HandleRedirect,{redirect:t,redirectType:r,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(t){super(t),this.state={redirect:null,redirectType:null}}};function RedirectBoundary(t){let{children:r}=t,n=(0,u.useRouter)();return a.default.createElement(RedirectErrorBoundary,{router:n},r)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8466:function(t,r,n){"use strict";var o,a;Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{RedirectType:function(){return o},getRedirectError:function(){return getRedirectError},redirect:function(){return redirect},permanentRedirect:function(){return permanentRedirect},isRedirectError:function(){return isRedirectError},getURLFromRedirectError:function(){return getURLFromRedirectError},getRedirectTypeFromError:function(){return getRedirectTypeFromError}});let u=n(228),i="NEXT_REDIRECT";function getRedirectError(t,r,n){void 0===n&&(n=!1);let o=Error(i);o.digest=i+";"+r+";"+t+";"+n;let a=u.requestAsyncStorage.getStore();return a&&(o.mutableCookies=a.mutableCookies),o}function redirect(t,r){throw void 0===r&&(r="replace"),getRedirectError(t,r,!1)}function permanentRedirect(t,r){throw void 0===r&&(r="replace"),getRedirectError(t,r,!0)}function isRedirectError(t){if("string"!=typeof(null==t?void 0:t.digest))return!1;let[r,n,o,a]=t.digest.split(";",4);return r===i&&("replace"===n||"push"===n)&&"string"==typeof o&&("true"===a||"false"===a)}function getURLFromRedirectError(t){return isRedirectError(t)?t.digest.split(";",3)[2]:null}function getRedirectTypeFromError(t){if(!isRedirectError(t))throw Error("Not a redirect error");return t.digest.split(";",2)[1]}(a=o||(o={})).push="push",a.replace="replace",("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},7264:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return RenderFromTemplateContext}});let o=n(8533),a=o._(n(2265)),u=n(6313);function RenderFromTemplateContext(){let t=(0,a.useContext)(u.TemplateContext);return a.default.createElement(a.default.Fragment,null,t)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},228:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"requestAsyncStorage",{enumerable:!0,get:function(){return a}});let o=n(7346),a=(0,o.createAsyncLocalStorage)();("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2713:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"applyFlightData",{enumerable:!0,get:function(){return applyFlightData}});let o=n(6313),a=n(782),u=n(1956);function applyFlightData(t,r,n,i){void 0===i&&(i=!1);let[s,d,p]=n.slice(-3);return null!==d&&(3===n.length?(r.status=o.CacheStates.READY,r.subTreeData=d,(0,a.fillLazyItemsTillLeafWithHead)(r,t,s,p,i)):(r.status=o.CacheStates.READY,r.subTreeData=t.subTreeData,r.parallelRoutes=new Map(t.parallelRoutes),(0,u.fillCacheWithNewSubTreeData)(r,t,n,i)),!0)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8934:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return applyRouterStatePatchToTree}});let o=n(8163);function applyPatch(t,r){let[n,a]=t,[u,i]=r;if("__DEFAULT__"===u&&"__DEFAULT__"!==n)return t;if((0,o.matchSegment)(n,u)){let r={};for(let t in a){let n=void 0!==i[t];n?r[t]=applyPatch(a[t],i[t]):r[t]=a[t]}for(let t in i)r[t]||(r[t]=i[t]);let o=[n,r];return t[2]&&(o[2]=t[2]),t[3]&&(o[3]=t[3]),t[4]&&(o[4]=t[4]),o}return r}function applyRouterStatePatchToTree(t,r,n){let a;let[u,i,,,s]=r;if(1===t.length){let t=applyPatch(r,n);return t}let[d,p]=t;if(!(0,o.matchSegment)(d,u))return null;let _=2===t.length;if(_)a=applyPatch(i[p],n);else if(null===(a=applyRouterStatePatchToTree(t.slice(2),i[p],n)))return null;let b=[t[0],{...i,[p]:a}];return s&&(b[4]=!0),b}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2082:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{extractPathFromFlightRouterState:function(){return extractPathFromFlightRouterState},computeChangedPath:function(){return computeChangedPath}});let o=n(4507),a=n(1706),u=n(8163),removeLeadingSlash=t=>"/"===t[0]?t.slice(1):t,segmentToPathname=t=>"string"==typeof t?t:t[1];function normalizeSegments(t){return t.reduce((t,r)=>""===(r=removeLeadingSlash(r))||(0,a.isGroupSegment)(r)?t:t+"/"+r,"")||"/"}function extractPathFromFlightRouterState(t){var r;let n=Array.isArray(t[0])?t[0][1]:t[0];if("__DEFAULT__"===n||o.INTERCEPTION_ROUTE_MARKERS.some(t=>n.startsWith(t)))return;if(n.startsWith("__PAGE__"))return"";let a=[n],u=null!=(r=t[1])?r:{},i=u.children?extractPathFromFlightRouterState(u.children):void 0;if(void 0!==i)a.push(i);else for(let[t,r]of Object.entries(u)){if("children"===t)continue;let n=extractPathFromFlightRouterState(r);void 0!==n&&a.push(n)}return normalizeSegments(a)}function computeChangedPathImpl(t,r){let[n,a]=t,[i,s]=r,d=segmentToPathname(n),p=segmentToPathname(i);if(o.INTERCEPTION_ROUTE_MARKERS.some(t=>d.startsWith(t)||p.startsWith(t)))return"";if(!(0,u.matchSegment)(n,i)){var _;return null!=(_=extractPathFromFlightRouterState(r))?_:""}for(let t in a)if(s[t]){let r=computeChangedPathImpl(a[t],s[t]);if(null!==r)return segmentToPathname(i)+"/"+r}return null}function computeChangedPath(t,r){let n=computeChangedPathImpl(t,r);return null==n||"/"===n?n:normalizeSegments(n.split("/"))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2301:function(t,r){"use strict";function createHrefFromUrl(t,r){return void 0===r&&(r=!0),t.pathname+t.search+(r?t.hash:"")}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createHrefFromUrl",{enumerable:!0,get:function(){return createHrefFromUrl}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5311:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createInitialRouterState",{enumerable:!0,get:function(){return createInitialRouterState}});let o=n(6313),a=n(2301),u=n(782),i=n(2082);function createInitialRouterState(t){var r;let{buildId:n,initialTree:s,children:d,initialCanonicalUrl:p,initialParallelRoutes:_,isServer:b,location:m,initialHead:j}=t,C={status:o.CacheStates.READY,data:null,subTreeData:d,parallelRoutes:b?new Map:_};return(null===_||0===_.size)&&(0,u.fillLazyItemsTillLeafWithHead)(C,void 0,s,j),{buildId:n,tree:s,cache:C,prefetchCache:new Map,pushRef:{pendingPush:!1,mpaNavigation:!1},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:m?(0,a.createHrefFromUrl)(m):p,nextUrl:null!=(r=(0,i.extractPathFromFlightRouterState)(s)||(null==m?void 0:m.pathname))?r:null}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},180:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createOptimisticTree",{enumerable:!0,get:function(){return createOptimisticTree}});let o=n(8163);function createOptimisticTree(t,r,n){let a;let[u,i,s,d,p]=r||[null,{}],_=t[0],b=1===t.length,m=null!==u&&(0,o.matchSegment)(u,_),j=Object.keys(i).length>1,C=!r||!m||j,w={};if(null!==u&&m&&(w=i),!b&&!j){let r=createOptimisticTree(t.slice(1),w?w.children:null,n||C);a=r}let D=[_,{...w,...a?{children:a}:{}}];return s&&(D[2]=s),!n&&C?D[3]="refetch":m&&d&&(D[3]=d),m&&p&&(D[4]=p),D}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3559:function(t,r){"use strict";function createRecordFromThenable(t){return t.status="pending",t.then(r=>{"pending"===t.status&&(t.status="fulfilled",t.value=r)},r=>{"pending"===t.status&&(t.status="rejected",t.reason=r)}),t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createRecordFromThenable",{enumerable:!0,get:function(){return createRecordFromThenable}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3322:function(t,r){"use strict";function createRouterCacheKey(t,r){return void 0===r&&(r=!1),Array.isArray(t)?(t[0]+"|"+t[1]+"|"+t[2]).toLowerCase():r&&t.startsWith("__PAGE__")?"__PAGE__":t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createRouterCacheKey",{enumerable:!0,get:function(){return createRouterCacheKey}}),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8146:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fetchServerResponse",{enumerable:!0,get:function(){return fetchServerResponse}});let o=n(8343),a=n(3728),u=n(5231),i=n(9706),s=n(6360),d=n(1824),{createFromFetch:p}=n(6671);function doMpaNavigation(t){return[(0,a.urlToUrlWithoutFlightMarker)(t).toString(),void 0]}async function fetchServerResponse(t,r,n,_,b){let m={[o.RSC]:"1",[o.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(r))};b===i.PrefetchKind.AUTO&&(m[o.NEXT_ROUTER_PREFETCH]="1"),n&&(m[o.NEXT_URL]=n);let j=(0,s.hexHash)([m[o.NEXT_ROUTER_PREFETCH]||"0",m[o.NEXT_ROUTER_STATE_TREE],m[o.NEXT_URL]].join(","));try{let r=new URL(t);r.searchParams.set(o.NEXT_RSC_UNION_QUERY,j);let n=await fetch(r,{credentials:"same-origin",headers:m}),i=(0,a.urlToUrlWithoutFlightMarker)(n.url),s=n.redirected?i:void 0,b=n.headers.get("content-type")||"",C=!!n.headers.get(d.NEXT_DID_POSTPONE_HEADER);if(b!==o.RSC_CONTENT_TYPE_HEADER||!n.ok)return t.hash&&(i.hash=t.hash),doMpaNavigation(i.toString());let[w,D]=await p(Promise.resolve(n),{callServer:u.callServer});if(_!==w)return doMpaNavigation(n.url);return[D,s,C]}catch(r){return console.error("Failed to fetch RSC payload for "+t+". Falling back to browser navigation.",r),[t.toString(),void 0]}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6443:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fillCacheWithDataProperty",{enumerable:!0,get:function(){return fillCacheWithDataProperty}});let o=n(6313),a=n(3322);function fillCacheWithDataProperty(t,r,n,u,i){void 0===i&&(i=!1);let s=n.length<=2,[d,p]=n,_=(0,a.createRouterCacheKey)(p),b=r.parallelRoutes.get(d);if(!b||i&&r.parallelRoutes.size>1)return{bailOptimistic:!0};let m=t.parallelRoutes.get(d);m&&m!==b||(m=new Map(b),t.parallelRoutes.set(d,m));let j=b.get(_),C=m.get(_);if(s){C&&C.data&&C!==j||m.set(_,{status:o.CacheStates.DATA_FETCH,data:u(),subTreeData:null,parallelRoutes:new Map});return}if(!C||!j){C||m.set(_,{status:o.CacheStates.DATA_FETCH,data:u(),subTreeData:null,parallelRoutes:new Map});return}return C===j&&(C={status:C.status,data:C.data,subTreeData:C.subTreeData,parallelRoutes:new Map(C.parallelRoutes)},m.set(_,C)),fillCacheWithDataProperty(C,j,n.slice(2),u)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1956:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return fillCacheWithNewSubTreeData}});let o=n(6313),a=n(5303),u=n(782),i=n(3322);function fillCacheWithNewSubTreeData(t,r,n,s){let d=n.length<=5,[p,_]=n,b=(0,i.createRouterCacheKey)(_),m=r.parallelRoutes.get(p);if(!m)return;let j=t.parallelRoutes.get(p);j&&j!==m||(j=new Map(m),t.parallelRoutes.set(p,j));let C=m.get(b),w=j.get(b);if(d){w&&w.data&&w!==C||(w={status:o.CacheStates.READY,data:null,subTreeData:n[3],parallelRoutes:C?new Map(C.parallelRoutes):new Map},C&&(0,a.invalidateCacheByRouterState)(w,C,n[2]),(0,u.fillLazyItemsTillLeafWithHead)(w,C,n[2],n[4],s),j.set(b,w));return}w&&C&&(w===C&&(w={status:w.status,data:w.data,subTreeData:w.subTreeData,parallelRoutes:new Map(w.parallelRoutes)},j.set(b,w)),fillCacheWithNewSubTreeData(w,C,n.slice(2),s))}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},782:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return fillLazyItemsTillLeafWithHead}});let o=n(6313),a=n(3322);function fillLazyItemsTillLeafWithHead(t,r,n,u,i){let s=0===Object.keys(n[1]).length;if(s){t.head=u;return}for(let s in n[1]){let d=n[1][s],p=d[0],_=(0,a.createRouterCacheKey)(p);if(r){let n=r.parallelRoutes.get(s);if(n){let r=new Map(n),a=r.get(_),p=i&&a?{status:a.status,data:a.data,subTreeData:a.subTreeData,parallelRoutes:new Map(a.parallelRoutes)}:{status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map(null==a?void 0:a.parallelRoutes)};r.set(_,p),fillLazyItemsTillLeafWithHead(p,a,d,u,i),t.parallelRoutes.set(s,r);continue}}let b={status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map},m=t.parallelRoutes.get(s);m?m.set(_,b):t.parallelRoutes.set(s,new Map([[_,b]])),fillLazyItemsTillLeafWithHead(b,void 0,d,u,i)}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2800:function(t,r){"use strict";var n,o;function getPrefetchEntryCacheStatus(t){let{kind:r,prefetchTime:n,lastUsedTime:o}=t;return Date.now()<(null!=o?o:n)+3e4?o?"reusable":"fresh":"auto"===r&&Date.now()[...n,...t]);for(let n of s){let o=(0,p.fillCacheWithDataProperty)(t,r,n,u);(null==o?void 0:o.bailOptimistic)||(i=!0)}return i}function navigateReducer(t,r){let{url:n,isExternalUrl:K,navigateType:q,cache:ee,mutable:et,forceOptimisticNavigation:er,shouldScroll:en}=r,{pathname:eo,hash:eu}=n,el=(0,s.createHrefFromUrl)(n),ei="push"===q;(0,B.prunePrefetchCache)(t.prefetchCache);let ec=JSON.stringify(et.previousTree)===JSON.stringify(t.tree);if(ec)return(0,w.handleMutable)(t,et);if(K)return handleExternalUrl(t,et,n.toString(),ei);let es=t.prefetchCache.get((0,s.createHrefFromUrl)(n,!1));if(er&&(null==es?void 0:es.kind)!==C.PrefetchKind.TEMPORARY){let r=eo.split("/");r.push("__PAGE__");let i=(0,_.createOptimisticTree)(r,t.tree,!1),d={...ee};d.status=o.CacheStates.READY,d.subTreeData=t.cache.subTreeData,d.parallelRoutes=new Map(t.cache.parallelRoutes);let b=null,m=r.slice(1).map(t=>["children",t]).flat(),j=(0,p.fillCacheWithDataProperty)(d,t.cache,m,()=>(b||(b=(0,u.createRecordFromThenable)((0,a.fetchServerResponse)(n,i,t.nextUrl,t.buildId))),b),!0);if(!(null==j?void 0:j.bailOptimistic))return et.previousTree=t.tree,et.patchedTree=i,et.pendingPush=ei,et.hashFragment=eu,et.shouldScroll=en,et.scrollableSegments=[],et.cache=d,et.canonicalUrl=el,t.prefetchCache.set((0,s.createHrefFromUrl)(n,!1),{data:b?(0,u.createRecordFromThenable)(Promise.resolve(b)):null,kind:C.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:t.tree,lastUsedTime:Date.now()}),(0,w.handleMutable)(t,et)}if(!es){let r=(0,u.createRecordFromThenable)((0,a.fetchServerResponse)(n,t.tree,t.nextUrl,t.buildId,void 0)),o={data:(0,u.createRecordFromThenable)(Promise.resolve(r)),kind:C.PrefetchKind.TEMPORARY,prefetchTime:Date.now(),treeAtTimeOfPrefetch:t.tree,lastUsedTime:null};t.prefetchCache.set((0,s.createHrefFromUrl)(n,!1),o),es=o}let ef=(0,U.getPrefetchEntryCacheStatus)(es),{treeAtTimeOfPrefetch:ed,data:ep}=es;$.prefetchQueue.bump(ep);let[eh,e_,ey]=(0,i.readRecordValue)(ep);if(es.lastUsedTime||(es.lastUsedTime=Date.now()),"string"==typeof eh)return handleExternalUrl(t,et,eh,ei);let eg=t.tree,eb=t.cache,em=[];for(let r of eh){let i=r.slice(0,-4),s=r.slice(-3)[0],p=["",...i],_=(0,b.applyRouterStatePatchToTree)(p,eg,s);if(null===_&&(_=(0,b.applyRouterStatePatchToTree)(p,ed,s)),null!==_){if((0,j.isNavigatingToNewRootLayout)(eg,_))return handleExternalUrl(t,et,el,ei);let b=!ey&&(0,D.applyFlightData)(eb,ee,r,"auto"===es.kind&&ef===U.PrefetchCacheEntryStatus.reusable);b||ef!==U.PrefetchCacheEntryStatus.stale||(b=addRefetchToLeafSegments(ee,eb,i,s,()=>(0,u.createRecordFromThenable)((0,a.fetchServerResponse)(n,eg,t.nextUrl,t.buildId))));let C=(0,m.shouldHardNavigate)(p,eg);for(let t of(C?(ee.status=o.CacheStates.READY,ee.subTreeData=eb.subTreeData,(0,d.invalidateCacheBelowFlightSegmentPath)(ee,eb,i),et.cache=ee):b&&(et.cache=ee),eb=ee,eg=_,generateSegmentsFromPatch(s))){let r=[...i,...t];"__DEFAULT__"!==r[r.length-1]&&em.push(r)}}}return et.previousTree=t.tree,et.patchedTree=eg,et.canonicalUrl=e_?(0,s.createHrefFromUrl)(e_):el,et.pendingPush=ei,et.scrollableSegments=em,et.hashFragment=eu,et.shouldScroll=en,(0,w.handleMutable)(t,et)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3709:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{prefetchQueue:function(){return _},prefetchReducer:function(){return prefetchReducer}});let o=n(2301),a=n(8146),u=n(9706),i=n(3559),s=n(3627),d=n(8343),p=n(839),_=new p.PromiseQueue(5);function prefetchReducer(t,r){(0,s.prunePrefetchCache)(t.prefetchCache);let{url:n}=r;n.searchParams.delete(d.NEXT_RSC_UNION_QUERY);let p=(0,o.createHrefFromUrl)(n,!1),b=t.prefetchCache.get(p);if(b&&(b.kind===u.PrefetchKind.TEMPORARY&&t.prefetchCache.set(p,{...b,kind:r.kind}),!(b.kind===u.PrefetchKind.AUTO&&r.kind===u.PrefetchKind.FULL)))return t;let m=(0,i.createRecordFromThenable)(_.enqueue(()=>(0,a.fetchServerResponse)(n,t.tree,t.nextUrl,t.buildId,r.kind)));return t.prefetchCache.set(p,{treeAtTimeOfPrefetch:t.tree,data:m,kind:r.kind,prefetchTime:Date.now(),lastUsedTime:null}),t}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3627:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"prunePrefetchCache",{enumerable:!0,get:function(){return prunePrefetchCache}});let o=n(2800);function prunePrefetchCache(t){for(let[r,n]of t)(0,o.getPrefetchEntryCacheStatus)(n)===o.PrefetchCacheEntryStatus.expired&&t.delete(r)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2701:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"refreshReducer",{enumerable:!0,get:function(){return refreshReducer}});let o=n(8146),a=n(3559),u=n(929),i=n(2301),s=n(8934),d=n(2782),p=n(8640),_=n(8543),b=n(6313),m=n(782);function refreshReducer(t,r){let{cache:n,mutable:j,origin:C}=r,w=t.canonicalUrl,D=t.tree,U=JSON.stringify(j.previousTree)===JSON.stringify(D);if(U)return(0,_.handleMutable)(t,j);n.data||(n.data=(0,a.createRecordFromThenable)((0,o.fetchServerResponse)(new URL(w,C),[D[0],D[1],D[2],"refetch"],t.nextUrl,t.buildId)));let[B,$]=(0,u.readRecordValue)(n.data);if("string"==typeof B)return(0,p.handleExternalUrl)(t,j,B,t.pushRef.pendingPush);for(let r of(n.data=null,B)){if(3!==r.length)return console.log("REFRESH FAILED"),t;let[o]=r,a=(0,s.applyRouterStatePatchToTree)([""],D,o);if(null===a)throw Error("SEGMENT MISMATCH");if((0,d.isNavigatingToNewRootLayout)(D,a))return(0,p.handleExternalUrl)(t,j,w,t.pushRef.pendingPush);let u=$?(0,i.createHrefFromUrl)($):void 0;$&&(j.canonicalUrl=u);let[_,C]=r.slice(-2);null!==_&&(n.status=b.CacheStates.READY,n.subTreeData=_,(0,m.fillLazyItemsTillLeafWithHead)(n,void 0,o,C),j.cache=n,j.prefetchCache=new Map),j.previousTree=D,j.patchedTree=a,j.canonicalUrl=w,D=a}return(0,_.handleMutable)(t,j)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1705:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"restoreReducer",{enumerable:!0,get:function(){return restoreReducer}});let o=n(2301);function restoreReducer(t,r){let{url:n,tree:a}=r,u=(0,o.createHrefFromUrl)(n);return{buildId:t.buildId,canonicalUrl:u,pushRef:t.pushRef,focusAndScrollRef:t.focusAndScrollRef,cache:t.cache,prefetchCache:t.prefetchCache,tree:a,nextUrl:n.pathname}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},1383:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"serverActionReducer",{enumerable:!0,get:function(){return serverActionReducer}});let o=n(5231),a=n(8343),u=n(3559),i=n(929),s=n(9872),d=n(2301),p=n(8640),_=n(8934),b=n(2782),m=n(6313),j=n(8543),C=n(782),{createFromFetch:w,encodeReply:D}=n(6671);async function fetchServerAction(t,r){let n,{actionId:u,actionArgs:i}=r,d=await D(i),p=await fetch("",{method:"POST",headers:{Accept:a.RSC_CONTENT_TYPE_HEADER,[a.ACTION]:u,[a.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(t.tree)),...t.nextUrl?{[a.NEXT_URL]:t.nextUrl}:{}},body:d}),_=p.headers.get("x-action-redirect");try{let t=JSON.parse(p.headers.get("x-action-revalidated")||"[[],0,0]");n={paths:t[0]||[],tag:!!t[1],cookie:t[2]}}catch(t){n={paths:[],tag:!1,cookie:!1}}let b=_?new URL((0,s.addBasePath)(_),new URL(t.canonicalUrl,window.location.href)):void 0;if(p.headers.get("content-type")===a.RSC_CONTENT_TYPE_HEADER){let t=await w(Promise.resolve(p),{callServer:o.callServer});if(_){let[,r]=null!=t?t:[];return{actionFlightData:r,redirectLocation:b,revalidatedParts:n}}let[r,[,a]]=null!=t?t:[];return{actionResult:r,actionFlightData:a,redirectLocation:b,revalidatedParts:n}}return{redirectLocation:b,revalidatedParts:n}}function serverActionReducer(t,r){let{mutable:n,cache:o,resolve:a,reject:s}=r,w=t.canonicalUrl,D=t.tree,U=JSON.stringify(n.previousTree)===JSON.stringify(D);if(U)return(0,j.handleMutable)(t,n);if(n.inFlightServerAction){if("fulfilled"!==n.inFlightServerAction.status&&n.globalMutable.pendingNavigatePath&&n.globalMutable.pendingNavigatePath!==w)return n.inFlightServerAction.then(()=>{n.actionResultResolved||(n.inFlightServerAction=null,n.globalMutable.pendingNavigatePath=void 0,n.globalMutable.refresh(),n.actionResultResolved=!0)},()=>{}),t}else n.inFlightServerAction=(0,u.createRecordFromThenable)(fetchServerAction(t,r));try{let{actionResult:r,actionFlightData:u,redirectLocation:s}=(0,i.readRecordValue)(n.inFlightServerAction);if(s&&(t.pushRef.pendingPush=!0,n.pendingPush=!0),n.previousTree=t.tree,!u){if(n.actionResultResolved||(a(r),n.actionResultResolved=!0),s)return(0,p.handleExternalUrl)(t,n,s.href,t.pushRef.pendingPush);return t}if("string"==typeof u)return(0,p.handleExternalUrl)(t,n,u,t.pushRef.pendingPush);for(let r of(n.inFlightServerAction=null,u)){if(3!==r.length)return console.log("SERVER ACTION APPLY FAILED"),t;let[a]=r,u=(0,_.applyRouterStatePatchToTree)([""],D,a);if(null===u)throw Error("SEGMENT MISMATCH");if((0,b.isNavigatingToNewRootLayout)(D,u))return(0,p.handleExternalUrl)(t,n,w,t.pushRef.pendingPush);let[i,s]=r.slice(-2);null!==i&&(o.status=m.CacheStates.READY,o.subTreeData=i,(0,C.fillLazyItemsTillLeafWithHead)(o,void 0,a,s),n.cache=o,n.prefetchCache=new Map),n.previousTree=D,n.patchedTree=u,n.canonicalUrl=w,D=u}if(s){let t=(0,d.createHrefFromUrl)(s,!1);n.canonicalUrl=t}return n.actionResultResolved||(a(r),n.actionResultResolved=!0),(0,j.handleMutable)(t,n)}catch(r){if("rejected"===r.status)return n.actionResultResolved||(s(r.reason),n.actionResultResolved=!0),t;throw r}}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},5330:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"serverPatchReducer",{enumerable:!0,get:function(){return serverPatchReducer}});let o=n(2301),a=n(8934),u=n(2782),i=n(8640),s=n(2713),d=n(8543);function serverPatchReducer(t,r){let{flightData:n,previousTree:p,overrideCanonicalUrl:_,cache:b,mutable:m}=r,j=JSON.stringify(p)===JSON.stringify(t.tree);if(!j)return console.log("TREE MISMATCH"),t;if(m.previousTree)return(0,d.handleMutable)(t,m);if("string"==typeof n)return(0,i.handleExternalUrl)(t,m,n,t.pushRef.pendingPush);let C=t.tree,w=t.cache;for(let r of n){let n=r.slice(0,-4),[d]=r.slice(-3,-2),p=(0,a.applyRouterStatePatchToTree)(["",...n],C,d);if(null===p)throw Error("SEGMENT MISMATCH");if((0,u.isNavigatingToNewRootLayout)(C,p))return(0,i.handleExternalUrl)(t,m,t.canonicalUrl,t.pushRef.pendingPush);let j=_?(0,o.createHrefFromUrl)(_):void 0;j&&(m.canonicalUrl=j),(0,s.applyFlightData)(w,b,r),m.previousTree=C,m.patchedTree=p,m.cache=b,w=b,C=p}return(0,d.handleMutable)(t,m)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},9706:function(t,r){"use strict";var n,o;Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{PrefetchKind:function(){return n},ACTION_REFRESH:function(){return a},ACTION_NAVIGATE:function(){return u},ACTION_RESTORE:function(){return i},ACTION_SERVER_PATCH:function(){return s},ACTION_PREFETCH:function(){return d},ACTION_FAST_REFRESH:function(){return p},ACTION_SERVER_ACTION:function(){return _}});let a="refresh",u="navigate",i="restore",s="server-patch",d="prefetch",p="fast-refresh",_="server-action";(o=n||(n={})).AUTO="auto",o.FULL="full",o.TEMPORARY="temporary",("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},7205:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"reducer",{enumerable:!0,get:function(){return b}});let o=n(9706),a=n(8640),u=n(5330),i=n(1705),s=n(2701),d=n(3709),p=n(3682),_=n(1383);function clientReducer(t,r){switch(r.type){case o.ACTION_NAVIGATE:return(0,a.navigateReducer)(t,r);case o.ACTION_SERVER_PATCH:return(0,u.serverPatchReducer)(t,r);case o.ACTION_RESTORE:return(0,i.restoreReducer)(t,r);case o.ACTION_REFRESH:return(0,s.refreshReducer)(t,r);case o.ACTION_FAST_REFRESH:return(0,p.fastRefreshReducer)(t,r);case o.ACTION_PREFETCH:return(0,d.prefetchReducer)(t,r);case o.ACTION_SERVER_ACTION:return(0,_.serverActionReducer)(t,r);default:throw Error("Unknown action")}}let b=clientReducer;("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3006:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"shouldHardNavigate",{enumerable:!0,get:function(){return shouldHardNavigate}});let o=n(8163);function shouldHardNavigate(t,r){let[n,a]=r,[u,i]=t;if(!(0,o.matchSegment)(u,n))return!!Array.isArray(u);let s=t.length<=2;return!s&&shouldHardNavigate(t.slice(2),a[i])}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8519:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return createSearchParamsBailoutProxy}});let o=n(2004);function createSearchParamsBailoutProxy(){return new Proxy({},{get(t,r){"string"==typeof r&&(0,o.staticGenerationBailout)("searchParams."+r)}})}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8985:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"staticGenerationAsyncStorage",{enumerable:!0,get:function(){return a}});let o=n(7346),a=(0,o.createAsyncLocalStorage)();("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2004:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"staticGenerationBailout",{enumerable:!0,get:function(){return staticGenerationBailout}});let o=n(1351),a=n(5437),u=n(8985);let StaticGenBailoutError=class StaticGenBailoutError extends Error{constructor(...t){super(...t),this.code="NEXT_STATIC_GEN_BAILOUT"}};function formatErrorMessage(t,r){let{dynamic:n,link:o}=r||{};return"Page"+(n?' with `dynamic = "'+n+'"`':"")+" couldn't be rendered statically because it used `"+t+"`."+(o?" See more info here: "+o:"")}let staticGenerationBailout=(t,r)=>{let n=u.staticGenerationAsyncStorage.getStore();if(!n)return!1;if(n.forceStatic)return!0;if(n.dynamicShouldError){var i;throw new StaticGenBailoutError(formatErrorMessage(t,{...r,dynamic:null!=(i=null==r?void 0:r.dynamic)?i:"error"}))}let s=formatErrorMessage(t,{...r,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if((0,a.maybePostpone)(n,s),n.revalidate=0,(null==r?void 0:r.dynamic)||(n.staticPrefetchBailout=!0),n.isStaticGeneration){let r=new o.DynamicServerError(s);throw n.dynamicUsageDescription=t,n.dynamicUsageStack=r.stack,r}return!1};("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},8297:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return StaticGenerationSearchParamsBailoutProvider}});let o=n(1024),a=o._(n(2265)),u=n(8519);function StaticGenerationSearchParamsBailoutProvider(t){let{Component:r,propsForComponent:n,isStaticGeneration:o}=t;if(o){let t=(0,u.createSearchParamsBailoutProxy)();return a.default.createElement(r,{searchParams:t,...n})}return a.default.createElement(r,n)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2327:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"useReducerWithReduxDevtools",{enumerable:!0,get:function(){return a}});let o=n(2265);function normalizeRouterState(t){if(t instanceof Map){let r={};for(let[n,o]of t.entries()){if("function"==typeof o){r[n]="fn()";continue}if("object"==typeof o&&null!==o){if(o.$$typeof){r[n]=o.$$typeof.toString();continue}if(o._bundlerConfig){r[n]="FlightData";continue}}r[n]=normalizeRouterState(o)}return r}if("object"==typeof t&&null!==t){let r={};for(let n in t){let o=t[n];if("function"==typeof o){r[n]="fn()";continue}if("object"==typeof o&&null!==o){if(o.$$typeof){r[n]=o.$$typeof.toString();continue}if(o.hasOwnProperty("_bundlerConfig")){r[n]="FlightData";continue}}r[n]=normalizeRouterState(o)}return r}return Array.isArray(t)?t.map(normalizeRouterState):t}function devToolReducer(t,r){return(n,o)=>{let a=t(n,o);return r.current&&r.current.send(o,normalizeRouterState(a)),a}}function useReducerWithReduxDevtoolsImpl(t,r){let n=(0,o.useRef)(),a=(0,o.useRef)();(0,o.useEffect)(()=>{if(!n.current&&!1!==a.current){if(void 0===a.current&&void 0===window.__REDUX_DEVTOOLS_EXTENSION__){a.current=!1;return}return n.current=window.__REDUX_DEVTOOLS_EXTENSION__.connect({instanceId:8e3,name:"next-router"}),n.current&&n.current.init(normalizeRouterState(r)),()=>{n.current=void 0}}},[r]);let[u,i]=(0,o.useReducer)(devToolReducer(t,n),r),s=(0,o.useCallback)(()=>{n.current&&n.current.send({type:"RENDER_SYNC"},normalizeRouterState(u))},[u]);return[u,i,s]}let a=useReducerWithReduxDevtoolsImpl;("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6746:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"hasBasePath",{enumerable:!0,get:function(){return hasBasePath}});let o=n(1446);function hasBasePath(t){return(0,o.pathHasPrefix)(t,"")}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3997:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return normalizePathTrailingSlash}});let o=n(9006),a=n(9466),normalizePathTrailingSlash=t=>{if(!t.startsWith("/"))return t;let{pathname:r,query:n,hash:u}=(0,a.parsePath)(t);return""+(0,o.removeTrailingSlash)(r)+n+u};("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},2504:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"default",{enumerable:!0,get:function(){return onRecoverableError}});let o=n(1283);function onRecoverableError(t){let r="function"==typeof reportError?reportError:t=>{window.console.error(t)};t.digest!==o.NEXT_DYNAMIC_NO_SSR_CODE&&r(t)}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},3714:function(t,r,n){"use strict";function removeBasePath(t){return t}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"removeBasePath",{enumerable:!0,get:function(){return removeBasePath}}),n(6746),("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},6313:function(t,r,n){"use strict";var o,a;Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{CacheStates:function(){return o},AppRouterContext:function(){return s},LayoutRouterContext:function(){return d},GlobalLayoutRouterContext:function(){return p},TemplateContext:function(){return _}});let u=n(1024),i=u._(n(2265));(a=o||(o={})).LAZY_INITIALIZED="LAZYINITIALIZED",a.DATA_FETCH="DATAFETCH",a.READY="READY";let s=i.default.createContext(null),d=i.default.createContext(null),p=i.default.createContext(null),_=i.default.createContext(null)},6360:function(t,r){"use strict";function djb2Hash(t){let r=5381;for(let n=0;n!r||(0,a.isGroupSegment)(r)||"@"===r[0]||("page"===r||"route"===r)&&n===o.length-1?t:t+"/"+r,""))}function normalizeRscURL(t){return t.replace(/\.rsc($|\?)/,"$1")}function normalizePostponedURL(t){let r=new URL(t),{pathname:n}=r;return n&&n.startsWith("/_next/postponed")?(r.pathname=n.substring(16)||"/",r.toString()):t}},280:function(t,r){"use strict";function handleSmoothScroll(t,r){if(void 0===r&&(r={}),r.onlyHashChange){t();return}let n=document.documentElement,o=n.style.scrollBehavior;n.style.scrollBehavior="auto",r.dontForceLayout||n.getClientRects(),t(),n.style.scrollBehavior=o}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"handleSmoothScroll",{enumerable:!0,get:function(){return handleSmoothScroll}})},2169:function(t,r){"use strict";function isBot(t){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(t)}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"isBot",{enumerable:!0,get:function(){return isBot}})},9466:function(t,r){"use strict";function parsePath(t){let r=t.indexOf("#"),n=t.indexOf("?"),o=n>-1&&(r<0||n-1?{pathname:t.substring(0,o?n:r),query:o?t.substring(n,r>-1?r:void 0):"",hash:r>-1?t.slice(r):""}:{pathname:t,query:"",hash:""}}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"parsePath",{enumerable:!0,get:function(){return parsePath}})},1446:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"pathHasPrefix",{enumerable:!0,get:function(){return pathHasPrefix}});let o=n(9466);function pathHasPrefix(t,r){if("string"!=typeof t)return!1;let{pathname:n}=(0,o.parsePath)(t);return n===r||n.startsWith(r+"/")}},9006:function(t,r){"use strict";function removeTrailingSlash(t){return t.replace(/\/$/,"")||"/"}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"removeTrailingSlash",{enumerable:!0,get:function(){return removeTrailingSlash}})},1706:function(t,r){"use strict";function isGroupSegment(t){return"("===t[0]&&t.endsWith(")")}Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"isGroupSegment",{enumerable:!0,get:function(){return isGroupSegment}})},3972:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{ServerInsertedHTMLContext:function(){return u},useServerInsertedHTML:function(){return useServerInsertedHTML}});let o=n(8533),a=o._(n(2265)),u=a.default.createContext(null);function useServerInsertedHTML(t){let r=(0,a.useContext)(u);r&&r(t)}},7346:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"createAsyncLocalStorage",{enumerable:!0,get:function(){return createAsyncLocalStorage}});let n=Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available");let FakeAsyncLocalStorage=class FakeAsyncLocalStorage{disable(){throw n}getStore(){}run(){throw n}exit(){throw n}enterWith(){throw n}};let o=globalThis.AsyncLocalStorage;function createAsyncLocalStorage(){return o?new o:new FakeAsyncLocalStorage}("function"==typeof r.default||"object"==typeof r.default&&null!==r.default)&&void 0===r.default.__esModule&&(Object.defineProperty(r.default,"__esModule",{value:!0}),Object.assign(r.default,r),t.exports=r.default)},4040:function(t,r,n){"use strict";var o=n(4887);r.createRoot=o.createRoot,r.hydrateRoot=o.hydrateRoot},4887:function(t,r,n){"use strict";function checkDCE(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)}catch(t){console.error(t)}}checkDCE(),t.exports=n(4417)},7950:function(t,r,n){"use strict";/** - * @license React - * react-server-dom-webpack-client.browser.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var o=n(4887),a=n(2265),u={stream:!0};function v(t,r){if(t){var n=t[r[0]];if(t=n[r[2]])n=t.name;else{if(!(t=n["*"]))throw Error('Could not find the module "'+r[0]+'" in the React SSR Manifest. This is probably a bug in the React Server Components bundler.');n=r[2]}return 4===r.length?[t.id,t.chunks,n,1]:[t.id,t.chunks,n]}return r}var i=new Map;function x(t){var r=n(t);return"function"!=typeof r.then||"fulfilled"===r.status?null:(r.then(function(t){r.status="fulfilled",r.value=t},function(t){r.status="rejected",r.reason=t}),r)}function y(){}function z(t){for(var r=t[1],o=[],a=0;ai?(d=i,i=3,a++):(d=0,i=3);continue;case 2:44===(m=o[a++])?i=4:_=_<<4|(96o.length&&(m=-1)}var j=o.byteOffset+a;if(-1>>1,a=t[o];if(0>>1;og(s,n))dg(p,s)?(t[o]=p,t[d]=n,o=d):(t[o]=s,t[i]=n,o=i);else if(dg(p,n))t[o]=p,t[d]=n,o=d;else break}}return r}function g(t,r){var n=t.sortIndex-r.sortIndex;return 0!==n?n:t.id-r.id}if(r.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var n,o=performance;r.unstable_now=function(){return o.now()}}else{var a=Date,u=a.now();r.unstable_now=function(){return a.now()-u}}var i=[],s=[],d=1,p=null,_=3,b=!1,m=!1,j=!1,C="function"==typeof setTimeout?setTimeout:null,w="function"==typeof clearTimeout?clearTimeout:null,D="undefined"!=typeof setImmediate?setImmediate:null;function G(t){for(var r=h(s);null!==r;){if(null===r.callback)k(s);else if(r.startTime<=t)k(s),r.sortIndex=r.expirationTime,f(i,r);else break;r=h(s)}}function H(t){if(j=!1,G(t),!m){if(null!==h(i))m=!0,I();else{var r=h(s);null!==r&&J(H,r.startTime-t)}}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var U=!1,B=-1,$=5,K=-1;function O(){return!(r.unstable_now()-K<$)}function P(){if(U){var t=r.unstable_now();K=t;var o=!0;try{e:{m=!1,j&&(j=!1,w(B),B=-1),b=!0;var a=_;try{t:{for(G(t),p=h(i);null!==p&&!(p.expirationTime>t&&O());){var u=p.callback;if("function"==typeof u){p.callback=null,_=p.priorityLevel;var d=u(p.expirationTime<=t);if(t=r.unstable_now(),"function"==typeof d){p.callback=d,G(t),o=!0;break t}p===h(i)&&k(i),G(t)}else k(i);p=h(i)}if(null!==p)o=!0;else{var C=h(s);null!==C&&J(H,C.startTime-t),o=!1}}break e}finally{p=null,_=a,b=!1}o=void 0}}finally{o?n():U=!1}}}if("function"==typeof D)n=function(){D(P)};else if("undefined"!=typeof MessageChannel){var q=new MessageChannel,ee=q.port2;q.port1.onmessage=P,n=function(){ee.postMessage(null)}}else n=function(){C(P,0)};function I(){U||(U=!0,n())}function J(t,n){B=C(function(){t(r.unstable_now())},n)}r.unstable_IdlePriority=5,r.unstable_ImmediatePriority=1,r.unstable_LowPriority=4,r.unstable_NormalPriority=3,r.unstable_Profiling=null,r.unstable_UserBlockingPriority=2,r.unstable_cancelCallback=function(t){t.callback=null},r.unstable_continueExecution=function(){m||b||(m=!0,I())},r.unstable_forceFrameRate=function(t){0>t||125a?(t.sortIndex=o,f(s,t),null===h(i)&&t===h(s)&&(j?(w(B),B=-1):j=!0,J(H,o-a))):(t.sortIndex=u,f(i,t),m||b||(m=!0,I())),t},r.unstable_shouldYield=O,r.unstable_wrapCallback=function(t){var r=_;return function(){var n=_;_=r;try{return t.apply(this,arguments)}finally{_=n}}}},8261:function(t,r,n){"use strict";t.exports=n(1756)},1824:function(t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{NEXT_QUERY_PARAM_PREFIX:function(){return n},PRERENDER_REVALIDATE_HEADER:function(){return o},PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER:function(){return a},NEXT_DID_POSTPONE_HEADER:function(){return u},NEXT_CACHE_TAGS_HEADER:function(){return i},NEXT_CACHE_SOFT_TAGS_HEADER:function(){return s},NEXT_CACHE_REVALIDATED_TAGS_HEADER:function(){return d},NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER:function(){return p},NEXT_CACHE_TAG_MAX_LENGTH:function(){return _},NEXT_CACHE_SOFT_TAG_MAX_LENGTH:function(){return b},NEXT_CACHE_IMPLICIT_TAG_ID:function(){return m},CACHE_ONE_YEAR:function(){return j},MIDDLEWARE_FILENAME:function(){return C},MIDDLEWARE_LOCATION_REGEXP:function(){return w},INSTRUMENTATION_HOOK_FILENAME:function(){return D},PAGES_DIR_ALIAS:function(){return U},DOT_NEXT_ALIAS:function(){return B},ROOT_DIR_ALIAS:function(){return $},APP_DIR_ALIAS:function(){return K},RSC_MOD_REF_PROXY_ALIAS:function(){return q},RSC_ACTION_VALIDATE_ALIAS:function(){return ee},RSC_ACTION_PROXY_ALIAS:function(){return et},RSC_ACTION_ENCRYPTION_ALIAS:function(){return er},RSC_ACTION_CLIENT_WRAPPER_ALIAS:function(){return en},PUBLIC_DIR_MIDDLEWARE_CONFLICT:function(){return eo},SSG_GET_INITIAL_PROPS_CONFLICT:function(){return eu},SERVER_PROPS_GET_INIT_PROPS_CONFLICT:function(){return el},SERVER_PROPS_SSG_CONFLICT:function(){return ei},STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR:function(){return ec},SERVER_PROPS_EXPORT_ERROR:function(){return es},GSP_NO_RETURNED_VALUE:function(){return ef},GSSP_NO_RETURNED_VALUE:function(){return ed},UNSTABLE_REVALIDATE_RENAME_ERROR:function(){return ep},GSSP_COMPONENT_MEMBER_ERROR:function(){return eh},NON_STANDARD_NODE_ENV:function(){return e_},SSG_FALLBACK_EXPORT_ERROR:function(){return ey},ESLINT_DEFAULT_DIRS:function(){return eg},ESLINT_PROMPT_VALUES:function(){return eb},SERVER_RUNTIME:function(){return em},WEBPACK_LAYERS:function(){return eR},WEBPACK_RESOURCE_QUERIES:function(){return eS}});let n="nxtP",o="x-prerender-revalidate",a="x-prerender-revalidate-if-generated",u="x-nextjs-postponed",i="x-next-cache-tags",s="x-next-cache-soft-tags",d="x-next-revalidated-tags",p="x-next-revalidate-tag-token",_=256,b=1024,m="_N_T_",j=31536e3,C="middleware",w=`(?:src/)?${C}`,D="instrumentation",U="private-next-pages",B="private-dot-next",$="private-next-root-dir",K="private-next-app-dir",q="private-next-rsc-mod-ref-proxy",ee="private-next-rsc-action-validate",et="private-next-rsc-action-proxy",er="private-next-rsc-action-encryption",en="private-next-rsc-action-client-wrapper",eo="You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict",eu="You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps",el="You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.",ei="You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps",ec="can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props",es="pages with `getServerSideProps` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export",ef="Your `getStaticProps` function did not return an object. Did you forget to add a `return`?",ed="Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?",ep="The `unstable_revalidate` property is available for general use.\nPlease use `revalidate` instead.",eh="can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member",e_='You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env',ey="Pages with `fallback` enabled in `getStaticPaths` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export",eg=["app","pages","components","lib","src"],eb=[{title:"Strict",recommended:!0,config:{extends:"next/core-web-vitals"}},{title:"Base",config:{extends:"next"}},{title:"Cancel",config:null}],em={edge:"edge",experimentalEdge:"experimental-edge",nodejs:"nodejs"},ev={shared:"shared",reactServerComponents:"rsc",serverSideRendering:"ssr",actionBrowser:"action-browser",api:"api",middleware:"middleware",edgeAsset:"edge-asset",appPagesBrowser:"app-pages-browser",appMetadataRoute:"app-metadata-route",appRouteHandler:"app-route-handler"},eR={...ev,GROUP:{server:[ev.reactServerComponents,ev.actionBrowser,ev.appMetadataRoute,ev.appRouteHandler],nonClientServerTarget:[ev.middleware,ev.api],app:[ev.reactServerComponents,ev.actionBrowser,ev.appMetadataRoute,ev.appRouteHandler,ev.serverSideRendering,ev.appPagesBrowser]}},eS={edgeSSREntry:"__next_edge_ssr_entry__",metadata:"__next_metadata__",metadataRoute:"__next_metadata_route__",metadataImageMeta:"__next_metadata_image_meta__"}},5682:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),Object.defineProperty(r,"getSegmentParam",{enumerable:!0,get:function(){return getSegmentParam}});let o=n(4507);function getSegmentParam(t){let r=o.INTERCEPTION_ROUTE_MARKERS.find(r=>t.startsWith(r));return(r&&(t=t.slice(r.length)),t.startsWith("[[...")&&t.endsWith("]]"))?{type:"optional-catchall",param:t.slice(5,-2)}:t.startsWith("[...")&&t.endsWith("]")?{type:"catchall",param:t.slice(4,-1)}:t.startsWith("[")&&t.endsWith("]")?{type:"dynamic",param:t.slice(1,-1)}:null}},4507:function(t,r,n){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),function(t,r){for(var n in r)Object.defineProperty(t,n,{enumerable:!0,get:r[n]})}(r,{INTERCEPTION_ROUTE_MARKERS:function(){return a},isInterceptionRouteAppPath:function(){return isInterceptionRouteAppPath},extractInterceptionRouteInformation:function(){return extractInterceptionRouteInformation}});let o=n(3701),a=["(..)(..)","(.)","(..)","(...)"];function isInterceptionRouteAppPath(t){return void 0!==t.split("/").find(t=>a.find(r=>t.startsWith(r)))}function extractInterceptionRouteInformation(t){let r,n,u;for(let o of t.split("/"))if(n=a.find(t=>o.startsWith(t))){[r,u]=t.split(n,2);break}if(!r||!n||!u)throw Error(`Invalid interception route: ${t}. Must be in the format //(..|...|..)(..)/`);switch(r=(0,o.normalizeAppPath)(r),n){case"(.)":u="/"===r?`/${u}`:r+"/"+u;break;case"(..)":if("/"===r)throw Error(`Invalid interception route: ${t}. Cannot use (..) marker at the root level, use (.) instead.`);u=r.split("/").slice(0,-1).concat(u).join("/");break;case"(...)":u="/"+u;break;case"(..)(..)":let i=r.split("/");if(i.length<=2)throw Error(`Invalid interception route: ${t}. Cannot use (..)(..) marker at the root level or one level up.`);u=i.slice(0,-2).concat(u).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:r,interceptedRoute:u}}},4677:function(t,r,n){"use strict";function _class_private_field_loose_base(t,r){if(!Object.prototype.hasOwnProperty.call(t,r))throw TypeError("attempted to use private field on non-instance");return t}n.r(r),n.d(r,{_:function(){return _class_private_field_loose_base},_class_private_field_loose_base:function(){return _class_private_field_loose_base}})},6249:function(t,r,n){"use strict";n.r(r),n.d(r,{_:function(){return _class_private_field_loose_key},_class_private_field_loose_key:function(){return _class_private_field_loose_key}});var o=0;function _class_private_field_loose_key(t){return"__private_"+o+++"_"+t}},1024:function(t,r,n){"use strict";function _interop_require_default(t){return t&&t.__esModule?t:{default:t}}n.r(r),n.d(r,{_:function(){return _interop_require_default},_interop_require_default:function(){return _interop_require_default}})},8533:function(t,r,n){"use strict";function _getRequireWildcardCache(t){if("function"!=typeof WeakMap)return null;var r=new WeakMap,n=new WeakMap;return(_getRequireWildcardCache=function(t){return t?n:r})(t)}function _interop_require_wildcard(t,r){if(!r&&t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var n=_getRequireWildcardCache(r);if(n&&n.has(t))return n.get(t);var o={},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in t)if("default"!==u&&Object.prototype.hasOwnProperty.call(t,u)){var i=a?Object.getOwnPropertyDescriptor(t,u):null;i&&(i.get||i.set)?Object.defineProperty(o,u,i):o[u]=t[u]}return o.default=t,n&&n.set(t,o),o}n.r(r),n.d(r,{_:function(){return _interop_require_wildcard},_interop_require_wildcard:function(){return _interop_require_wildcard}})}}]); \ No newline at end of file diff --git a/.next/static/chunks/537cd76e-7aba1cf7a4752418.js b/.next/static/chunks/537cd76e-7aba1cf7a4752418.js index a1069f4..cf7ba3a 100644 --- a/.next/static/chunks/537cd76e-7aba1cf7a4752418.js +++ b/.next/static/chunks/537cd76e-7aba1cf7a4752418.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[116],{7089:function(e,t){/*! Tweakpane 3.1.10 (c) 2016 cocopon, licensed under the MIT license. */!function(e){"use strict";let Semver=class Semver{constructor(e){let[t,r]=e.split("-"),i=t.split(".");this.major=parseInt(i[0],10),this.minor=parseInt(i[1],10),this.patch=parseInt(i[2],10),this.prerelease=null!=r?r:null}toString(){let e=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[e,this.prerelease].join("-"):e}};let BladeApi=class BladeApi{constructor(e){this.controller_=e}get element(){return this.controller_.view.element}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(e){this.controller_.viewProps.set("disabled",e)}get hidden(){return this.controller_.viewProps.get("hidden")}set hidden(e){this.controller_.viewProps.set("hidden",e)}dispose(){this.controller_.viewProps.set("disposed",!0)}};let TpEvent=class TpEvent{constructor(e){this.target=e}};let TpChangeEvent=class TpChangeEvent extends TpEvent{constructor(e,t,r,i){super(e),this.value=t,this.presetKey=r,this.last=null==i||i}};let TpUpdateEvent=class TpUpdateEvent extends TpEvent{constructor(e,t,r){super(e),this.value=t,this.presetKey=r}};let TpFoldEvent=class TpFoldEvent extends TpEvent{constructor(e,t){super(e),this.expanded=t}};let TpTabSelectEvent=class TpTabSelectEvent extends TpEvent{constructor(e,t){super(e),this.index=t}};function isEmpty(e){return null==e}function deepEqualsArray(e,t){if(e.length!==t.length)return!1;for(let r=0;r"View has been already disposed",invalidparams:e=>`Invalid parameters for '${e.name}'`,nomatchingcontroller:e=>`No matching controller for '${e.key}'`,nomatchingview:e=>`No matching view for '${JSON.stringify(e.params)}'`,notbindable:()=>"Value is not bindable",propertynotfound:e=>`Property '${e.name}' not found`,shouldneverhappen:()=>"This error should never happen"};let TpError=class TpError{static alreadyDisposed(){return new TpError({type:"alreadydisposed"})}static notBindable(){return new TpError({type:"notbindable"})}static propertyNotFound(e){return new TpError({type:"propertynotfound",context:{name:e}})}static shouldNeverHappen(){return new TpError({type:"shouldneverhappen"})}constructor(e){var r;this.message=null!==(r=t[e.type](e.context))&&void 0!==r?r:"Unexpected error",this.name=this.constructor.name,this.stack=Error(this.message).stack,this.type=e.type}};let BindingTarget=class BindingTarget{constructor(e,t,r){this.obj_=e,this.key_=t,this.presetKey_=null!=r?r:t}static isBindable(e){return null!==e&&("object"==typeof e||"function"==typeof e)}get key(){return this.key_}get presetKey(){return this.presetKey_}read(){return this.obj_[this.key_]}write(e){this.obj_[this.key_]=e}writeProperty(e,t){let r=this.read();if(!BindingTarget.isBindable(r))throw TpError.notBindable();if(!(e in r))throw TpError.propertyNotFound(e);r[e]=t}};let ButtonApi=class ButtonApi extends BladeApi{get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get title(){var e;return null!==(e=this.controller_.valueController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.valueController.props.set("title",e)}on(e,t){let r=t.bind(this),i=this.controller_.valueController.emitter;return i.on(e,()=>{r(new TpEvent(this))}),this}};let Emitter=class Emitter{constructor(){this.observers_={}}on(e,t){let r=this.observers_[e];return r||(r=this.observers_[e]=[]),r.push({handler:t}),this}off(e,t){let r=this.observers_[e];return r&&(this.observers_[e]=r.filter(e=>e.handler!==t)),this}emit(e,t){let r=this.observers_[e];r&&r.forEach(e=>{e.handler(t)})}};function ClassName(e){return(t,r)=>["tp","-",e,"v",t?`_${t}`:"",r?`-${r}`:""].join("")}function compose(e,t){return r=>t(e(r))}function extractValue(e){return e.rawValue}function bindValue(e,t){e.emitter.on("change",compose(extractValue,t)),t(e.rawValue)}function bindValueMap(e,t,r){bindValue(e.value(t),r)}function applyClass(e,t,r){r?e.classList.add(t):e.classList.remove(t)}function valueToClassName(e,t){return r=>{applyClass(e,t,r)}}function bindValueToTextContent(e,t){bindValue(e,e=>{t.textContent=null!=e?e:""})}let r=ClassName("btn");let ButtonView=class ButtonView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(r()),t.viewProps.bindClassModifiers(this.element);let i=e.createElement("button");i.classList.add(r("b")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let n=e.createElement("div");n.classList.add(r("t")),bindValueToTextContent(t.props.value("title"),n),this.buttonElement.appendChild(n)}};let ButtonController=class ButtonController{constructor(e,t){this.emitter=new Emitter,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new ButtonView(e,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}};let BoundValue=class BoundValue{constructor(e,t){var r;this.constraint_=null==t?void 0:t.constraint,this.equals_=null!==(r=null==t?void 0:t.equals)&&void 0!==r?r:(e,t)=>e===t,this.emitter=new Emitter,this.rawValue_=e}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let r=null!=t?t:{forceEmit:!1,last:!0},i=this.constraint_?this.constraint_.constrain(e):e,n=this.rawValue_,o=!this.equals_(n,i);(o||r.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=i,this.emitter.emit("change",{options:r,previousRawValue:n,rawValue:i,sender:this}))}};let PrimitiveValue=class PrimitiveValue{constructor(e){this.emitter=new Emitter,this.value_=e}get rawValue(){return this.value_}set rawValue(e){this.setRawValue(e,{forceEmit:!1,last:!0})}setRawValue(e,t){let r=null!=t?t:{forceEmit:!1,last:!0},i=this.value_;(i!==e||r.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=e,this.emitter.emit("change",{options:r,previousRawValue:i,rawValue:this.value_,sender:this}))}};function createValue(e,t){let r=null==t?void 0:t.constraint,i=null==t?void 0:t.equals;return r||i?new BoundValue(e,t):new PrimitiveValue(e)}let ValueMap=class ValueMap{constructor(e){for(let t in this.emitter=new Emitter,this.valMap_=e,this.valMap_){let e=this.valMap_[t];e.emitter.on("change",()=>{this.emitter.emit("change",{key:t,sender:this})})}}static createCore(e){let t=Object.keys(e);return t.reduce((t,r)=>Object.assign(t,{[r]:createValue(e[r])}),{})}static fromObject(e){let t=this.createCore(e);return new ValueMap(t)}get(e){return this.valMap_[e].rawValue}set(e,t){this.valMap_[e].rawValue=t}value(e){return this.valMap_[e]}};function parseObject(e,t){let r=Object.keys(t),i=r.reduce((r,i)=>{if(void 0===r)return;let n=t[i],o=n(e[i]);return o.succeeded?Object.assign(Object.assign({},r),{[i]:o.value}):void 0},{});return i}function parseArray(e,t){return e.reduce((e,r)=>{if(void 0===e)return;let i=t(r);if(i.succeeded&&void 0!==i.value)return[...e,i.value]},[])}function isObject(e){return null!==e&&"object"==typeof e}function createParamsParserBuilder(e){return t=>r=>{if(!t&&void 0===r)return{succeeded:!1,value:void 0};if(t&&void 0===r)return{succeeded:!0,value:void 0};let i=e(r);return void 0!==i?{succeeded:!0,value:i}:{succeeded:!1,value:void 0}}}function createParamsParserBuilders(e){return{custom:t=>createParamsParserBuilder(t)(e),boolean:createParamsParserBuilder(e=>"boolean"==typeof e?e:void 0)(e),number:createParamsParserBuilder(e=>"number"==typeof e?e:void 0)(e),string:createParamsParserBuilder(e=>"string"==typeof e?e:void 0)(e),function:createParamsParserBuilder(e=>"function"==typeof e?e:void 0)(e),constant:t=>createParamsParserBuilder(e=>e===t?t:void 0)(e),raw:createParamsParserBuilder(e=>e)(e),object:t=>createParamsParserBuilder(e=>{if(isObject(e))return parseObject(e,t)})(e),array:t=>createParamsParserBuilder(e=>{if(Array.isArray(e))return parseArray(e,t)})(e)}}let i={optional:createParamsParserBuilders(!0),required:createParamsParserBuilders(!1)};function parseParams(e,t){let r=i.required.object(t)(e);return r.succeeded?r.value:void 0}function warnMissing(e){console.warn(`Missing '${e.key}' of ${e.target} in ${e.place}. Please rebuild plugins with the latest core package.`)}function disposeElement(e){return e&&e.parentElement&&e.parentElement.removeChild(e),null}let ReadonlyValue=class ReadonlyValue{constructor(e){this.value_=e}static create(e){return[new ReadonlyValue(e),(t,r)=>{e.setRawValue(t,r)}]}get emitter(){return this.value_.emitter}get rawValue(){return this.value_.rawValue}};let n=ClassName("");function valueToModifier(e,t){return valueToClassName(e,n(void 0,t))}let ViewProps=class ViewProps extends ValueMap{constructor(e){var t;super(e),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=ReadonlyValue.create(createValue(this.getGlobalDisabled_())),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(e){var t,r,i;let n=null!=e?e:{};return new ViewProps(ValueMap.createCore({disabled:null!==(t=n.disabled)&&void 0!==t&&t,disposed:!1,hidden:null!==(r=n.hidden)&&void 0!==r&&r,parent:null!==(i=n.parent)&&void 0!==i?i:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(e){bindValue(this.globalDisabled_,valueToModifier(e,"disabled")),bindValueMap(this,"hidden",valueToModifier(e,"hidden"))}bindDisabled(e){bindValue(this.globalDisabled_,t=>{e.disabled=t})}bindTabIndex(e){bindValue(this.globalDisabled_,t=>{e.tabIndex=t?-1:0})}handleDispose(e){this.value("disposed").emitter.on("change",t=>{t&&e()})}getGlobalDisabled_(){let e=this.get("parent"),t=!!e&&e.globalDisabled.rawValue;return t||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(e){var t;let r=e.previousRawValue;null==r||r.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(t=this.get("parent"))||void 0===t||t.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}};function getAllBladePositions(){return["veryfirst","first","last","verylast"]}let o=ClassName(""),a={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"};let BladeController=class BladeController{constructor(e){this.parent_=null,this.blade=e.blade,this.view=e.view,this.viewProps=e.viewProps;let t=this.view.element;this.blade.value("positions").emitter.on("change",()=>{getAllBladePositions().forEach(e=>{t.classList.remove(o(void 0,a[e]))}),this.blade.get("positions").forEach(e=>{t.classList.add(o(void 0,a[e]))})}),this.viewProps.handleDispose(()=>{disposeElement(t)})}get parent(){return this.parent_}set parent(e){if(this.parent_=e,!("parent"in this.viewProps.valMap_)){warnMissing({key:"parent",target:ViewProps.name,place:"BladeController.parent"});return}this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}};let l="http://www.w3.org/2000/svg";function forceReflow(e){e.offsetHeight}function disableTransitionTemporarily(e,t){let r=e.style.transition;e.style.transition="none",t(),e.style.transition=r}function supportsTouch(e){return void 0!==e.ontouchstart}function getGlobalObject(){return globalThis}function getWindowDocument(){let e=getGlobalObject();return e.document}function getCanvasContext(e){let t=e.ownerDocument.defaultView;return t&&"document"in t?e.getContext("2d",{willReadFrequently:!0}):null}let s={check:'',dropdown:'',p2dpad:''};function createSvgIconElement(e,t){let r=e.createElementNS(l,"svg");return r.innerHTML=s[t],r}function insertElementAt(e,t,r){e.insertBefore(t,e.children[r])}function removeElement(e){e.parentElement&&e.parentElement.removeChild(e)}function removeChildElements(e){for(;e.children.length>0;)e.removeChild(e.children[0])}function removeChildNodes(e){for(;e.childNodes.length>0;)e.removeChild(e.childNodes[0])}function findNextTarget(e){return e.relatedTarget?e.relatedTarget:"explicitOriginalTarget"in e?e.explicitOriginalTarget:null}let p=ClassName("lbl");function createLabelNode(e,t){let r=e.createDocumentFragment(),i=t.split("\n").map(t=>e.createTextNode(t));return i.forEach((t,i)=>{i>0&&r.appendChild(e.createElement("br")),r.appendChild(t)}),r}let LabelView=class LabelView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(p()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(p("l")),bindValueMap(t.props,"label",t=>{isEmpty(t)?this.element.classList.add(p(void 0,"nol")):(this.element.classList.remove(p(void 0,"nol")),removeChildNodes(r),r.appendChild(createLabelNode(e,t)))}),this.element.appendChild(r),this.labelElement=r;let i=e.createElement("div");i.classList.add(p("v")),this.element.appendChild(i),this.valueElement=i}};let LabelController=class LabelController extends BladeController{constructor(e,t){let r=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{view:new LabelView(e,{props:t.props,viewProps:r}),viewProps:r})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}};let d={id:"button",type:"blade",accept(e){let t=parseParams(e,{title:i.required.string,view:i.required.constant("button"),label:i.optional.string});return t?{params:t}:null},controller:e=>new LabelController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:new ButtonController(e.document,{props:ValueMap.fromObject({title:e.params.title}),viewProps:e.viewProps})}),api:e=>e.controller instanceof LabelController&&e.controller.valueController instanceof ButtonController?new ButtonApi(e.controller):null};let ValueBladeController=class ValueBladeController extends BladeController{constructor(e){super(e),this.value=e.value}};function createBlade(){return new ValueMap({positions:createValue([],{equals:deepEqualsArray})})}let Foldable=class Foldable extends ValueMap{constructor(e){super(e)}static create(e){let t=ValueMap.createCore({completed:!0,expanded:e,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null});return new Foldable(t)}get styleExpanded(){var e;return null!==(e=this.get("temporaryExpanded"))&&void 0!==e?e:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";let e=this.get("expandedHeight");return this.get("shouldFixHeight")&&!isEmpty(e)?`${e}px`:"auto"}bindExpandedClass(e,t){let onExpand=()=>{let r=this.styleExpanded;r?e.classList.add(t):e.classList.remove(t)};bindValueMap(this,"expanded",onExpand),bindValueMap(this,"temporaryExpanded",onExpand)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}};function computeExpandedFolderHeight(e,t){let r=0;return disableTransitionTemporarily(t,()=>{e.set("expandedHeight",null),e.set("temporaryExpanded",!0),forceReflow(t),r=t.clientHeight,e.set("temporaryExpanded",null),forceReflow(t)}),r}function applyHeight(e,t){t.style.height=e.styleHeight}function bindFoldable(e,t){e.value("expanded").emitter.on("beforechange",()=>{if(e.set("completed",!1),isEmpty(e.get("expandedHeight"))){let r=computeExpandedFolderHeight(e,t);r>0&&e.set("expandedHeight",r)}e.set("shouldFixHeight",!0),forceReflow(t)}),e.emitter.on("change",()=>{applyHeight(e,t)}),applyHeight(e,t),t.addEventListener("transitionend",t=>{"height"===t.propertyName&&e.cleanUpTransition()})}let RackLikeApi=class RackLikeApi extends BladeApi{constructor(e,t){super(e),this.rackApi_=t}};function addButtonAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"button"}))}function addFolderAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"folder"}))}function addSeparatorAsBlade(e,t){let r=null!=t?t:{};return e.addBlade(Object.assign(Object.assign({},r),{view:"separator"}))}function addTabAsBlade(e,t){return e.addBlade(Object.assign(Object.assign({},t),{view:"tab"}))}let NestedOrderedSet=class NestedOrderedSet{constructor(e){this.emitter=new Emitter,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=e}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(e){for(let t of this.allItems())if(e(t))return t;return null}includes(e){return this.cache_.has(e)}add(e,t){if(this.includes(e))throw TpError.shouldNeverHappen();let r=void 0!==t?t:this.items_.length;this.items_.splice(r,0,e),this.cache_.add(e);let i=this.extract_(e);i&&(i.emitter.on("add",this.onSubListAdd_),i.emitter.on("remove",this.onSubListRemove_),i.allItems().forEach(e=>{this.cache_.add(e)})),this.emitter.emit("add",{index:r,item:e,root:this,target:this})}remove(e){let t=this.items_.indexOf(e);if(t<0)return;this.items_.splice(t,1),this.cache_.delete(e);let r=this.extract_(e);r&&(r.emitter.off("add",this.onSubListAdd_),r.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:t,item:e,root:this,target:this})}onSubListAdd_(e){this.cache_.add(e.item),this.emitter.emit("add",{index:e.index,item:e.item,root:this,target:e.target})}onSubListRemove_(e){this.cache_.delete(e.item),this.emitter.emit("remove",{index:e.index,item:e.item,root:this,target:e.target})}};let InputBindingApi=class InputBindingApi extends BladeApi{constructor(e){super(e),this.onBindingChange_=this.onBindingChange_.bind(this),this.emitter_=new Emitter,this.controller_.binding.emitter.on("change",this.onBindingChange_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingChange_(e){let t=e.sender.target.read();this.emitter_.emit("change",{event:new TpChangeEvent(this,t,this.controller_.binding.target.presetKey,e.options.last)})}};let InputBindingController=class InputBindingController extends LabelController{constructor(e,t){super(e,t),this.binding=t.binding}};let MonitorBindingApi=class MonitorBindingApi extends BladeApi{constructor(e){super(e),this.onBindingUpdate_=this.onBindingUpdate_.bind(this),this.emitter_=new Emitter,this.controller_.binding.emitter.on("update",this.onBindingUpdate_)}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}refresh(){this.controller_.binding.read()}onBindingUpdate_(e){let t=e.sender.target.read();this.emitter_.emit("update",{event:new TpUpdateEvent(this,t,this.controller_.binding.target.presetKey)})}};let MonitorBindingController=class MonitorBindingController extends LabelController{constructor(e,t){super(e,t),this.binding=t.binding,this.viewProps.bindDisabled(this.binding.ticker),this.viewProps.handleDispose(()=>{this.binding.dispose()})}};function findSubBladeApiSet(e){return e instanceof RackApi?e.apiSet_:e instanceof RackLikeApi?e.rackApi_.apiSet_:null}function getApiByController(e,t){let r=e.find(e=>e.controller_===t);if(!r)throw TpError.shouldNeverHappen();return r}function createBindingTarget(e,t,r){if(!BindingTarget.isBindable(e))throw TpError.notBindable();return new BindingTarget(e,t,r)}let RackApi=class RackApi extends BladeApi{constructor(e,t){super(e),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this),this.onRackInputChange_=this.onRackInputChange_.bind(this),this.onRackMonitorUpdate_=this.onRackMonitorUpdate_.bind(this),this.emitter_=new Emitter,this.apiSet_=new NestedOrderedSet(findSubBladeApiSet),this.pool_=t;let r=this.controller_.rack;r.emitter.on("add",this.onRackAdd_),r.emitter.on("remove",this.onRackRemove_),r.emitter.on("inputchange",this.onRackInputChange_),r.emitter.on("monitorupdate",this.onRackMonitorUpdate_),r.children.forEach(e=>{this.setUpApi_(e)})}get children(){return this.controller_.rack.children.map(e=>getApiByController(this.apiSet_,e))}addInput(e,t,r){let i=null!=r?r:{},n=this.controller_.view.element.ownerDocument,o=this.pool_.createInput(n,createBindingTarget(e,t,i.presetKey),i),a=new InputBindingApi(o);return this.add(a,i.index)}addMonitor(e,t,r){let i=null!=r?r:{},n=this.controller_.view.element.ownerDocument,o=this.pool_.createMonitor(n,createBindingTarget(e,t),i),a=new MonitorBindingApi(o);return this.add(a,i.index)}addFolder(e){return addFolderAsBlade(this,e)}addButton(e){return addButtonAsBlade(this,e)}addSeparator(e){return addSeparatorAsBlade(this,e)}addTab(e){return addTabAsBlade(this,e)}add(e,t){this.controller_.rack.add(e.controller_,t);let r=this.apiSet_.find(t=>t.controller_===e.controller_);return r&&this.apiSet_.remove(r),this.apiSet_.add(e),e}remove(e){this.controller_.rack.remove(e.controller_)}addBlade(e){let t=this.controller_.view.element.ownerDocument,r=this.pool_.createBlade(t,e),i=this.pool_.createBladeApi(r);return this.add(i,e.index)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}setUpApi_(e){let t=this.apiSet_.find(t=>t.controller_===e);t||this.apiSet_.add(this.pool_.createBladeApi(e))}onRackAdd_(e){this.setUpApi_(e.bladeController)}onRackRemove_(e){if(e.isRoot){let t=getApiByController(this.apiSet_,e.bladeController);this.apiSet_.remove(t)}}onRackInputChange_(e){let t=e.bladeController;if(t instanceof InputBindingController){let r=getApiByController(this.apiSet_,t),i=t.binding;this.emitter_.emit("change",{event:new TpChangeEvent(r,i.target.read(),i.target.presetKey,e.options.last)})}else if(t instanceof ValueBladeController){let r=getApiByController(this.apiSet_,t);this.emitter_.emit("change",{event:new TpChangeEvent(r,t.value.rawValue,void 0,e.options.last)})}}onRackMonitorUpdate_(e){if(!(e.bladeController instanceof MonitorBindingController))throw TpError.shouldNeverHappen();let t=getApiByController(this.apiSet_,e.bladeController),r=e.bladeController.binding;this.emitter_.emit("update",{event:new TpUpdateEvent(t,r.target.read(),r.target.presetKey)})}};let FolderApi=class FolderApi extends RackLikeApi{constructor(e,t){super(e,new RackApi(e.rackController,t)),this.emitter_=new Emitter,this.controller_.foldable.value("expanded").emitter.on("change",e=>{this.emitter_.emit("fold",{event:new TpFoldEvent(this,e.sender.rawValue)})}),this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})})}get expanded(){return this.controller_.foldable.get("expanded")}set expanded(e){this.controller_.foldable.set("expanded",e)}get title(){return this.controller_.props.get("title")}set title(e){this.controller_.props.set("title",e)}get children(){return this.rackApi_.children}addInput(e,t,r){return this.rackApi_.addInput(e,t,r)}addMonitor(e,t,r){return this.rackApi_.addMonitor(e,t,r)}addFolder(e){return this.rackApi_.addFolder(e)}addButton(e){return this.rackApi_.addButton(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){return this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addBlade(e){return this.rackApi_.addBlade(e)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}};let RackLikeController=class RackLikeController extends BladeController{constructor(e){super({blade:e.blade,view:e.view,viewProps:e.rackController.viewProps}),this.rackController=e.rackController}};let PlainView=class PlainView{constructor(e,t){let r=ClassName(t.viewName);this.element=e.createElement("div"),this.element.classList.add(r()),t.viewProps.bindClassModifiers(this.element)}};function findInputBindingController(e,t){for(let r=0;rt instanceof e)}onSetAdd_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("add",{bladeController:e.item,index:e.index,isRoot:t,sender:this}),!t)return;let r=e.item;if(r.viewProps.emitter.on("change",this.onChildViewPropsChange_),r.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),r.viewProps.handleDispose(this.onChildDispose_),r instanceof InputBindingController)r.binding.emitter.on("change",this.onChildInputChange_);else if(r instanceof MonitorBindingController)r.binding.emitter.on("update",this.onChildMonitorUpdate_);else if(r instanceof ValueBladeController)r.value.emitter.on("change",this.onChildValueChange_);else{let e=findSubRack(r);if(e){let t=e.emitter;t.on("layout",this.onDescendantLayout_),t.on("inputchange",this.onDescendantInputChange_),t.on("monitorupdate",this.onDescendantMonitorUpdate_)}}}onSetRemove_(e){this.updatePositions_();let t=e.target===e.root;if(this.emitter.emit("remove",{bladeController:e.item,isRoot:t,sender:this}),!t)return;let r=e.item;if(r instanceof InputBindingController)r.binding.emitter.off("change",this.onChildInputChange_);else if(r instanceof MonitorBindingController)r.binding.emitter.off("update",this.onChildMonitorUpdate_);else if(r instanceof ValueBladeController)r.value.emitter.off("change",this.onChildValueChange_);else{let e=findSubRack(r);if(e){let t=e.emitter;t.off("layout",this.onDescendantLayout_),t.off("inputchange",this.onDescendantInputChange_),t.off("monitorupdate",this.onDescendantMonitorUpdate_)}}}updatePositions_(){let e=this.bcSet_.items.filter(e=>!e.viewProps.get("hidden")),t=e[0],r=e[e.length-1];this.bcSet_.items.forEach(e=>{let i=[];e===t&&(i.push("first"),(!this.blade_||this.blade_.get("positions").includes("veryfirst"))&&i.push("veryfirst")),e===r&&(i.push("last"),(!this.blade_||this.blade_.get("positions").includes("verylast"))&&i.push("verylast")),e.blade.set("positions",i)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){let e=this.bcSet_.items.filter(e=>e.viewProps.get("disposed"));e.forEach(e=>{this.bcSet_.remove(e)})}onChildInputChange_(e){let t=findInputBindingController(this.find(InputBindingController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:t,options:e.options,sender:this})}onChildMonitorUpdate_(e){let t=findMonitorBindingController(this.find(MonitorBindingController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("monitorupdate",{bladeController:t,sender:this})}onChildValueChange_(e){let t=findValueBladeController(this.find(ValueBladeController),e.sender);if(!t)throw TpError.alreadyDisposed();this.emitter.emit("inputchange",{bladeController:t,options:e.options,sender:this})}onDescendantLayout_(e){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onDescendantInputChange_(e){this.emitter.emit("inputchange",{bladeController:e.bladeController,options:e.options,sender:this})}onDescendantMonitorUpdate_(e){this.emitter.emit("monitorupdate",{bladeController:e.bladeController,sender:this})}onBladePositionsChange_(){this.updatePositions_()}};let RackController=class RackController extends BladeController{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new PlainView(e,{viewName:"brk",viewProps:t.viewProps})})),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this);let r=new BladeRack({blade:t.root?void 0:t.blade,viewProps:t.viewProps});r.emitter.on("add",this.onRackAdd_),r.emitter.on("remove",this.onRackRemove_),this.rack=r,this.viewProps.handleDispose(()=>{for(let e=this.rack.children.length-1;e>=0;e--){let t=this.rack.children[e];t.viewProps.set("disposed",!0)}})}onRackAdd_(e){e.isRoot&&insertElementAt(this.view.element,e.bladeController.view.element,e.index)}onRackRemove_(e){e.isRoot&&removeElement(e.bladeController.view.element)}};let u=ClassName("cnt");let FolderView=class FolderView{constructor(e,t){var r;this.className_=ClassName(null!==(r=t.viewName)&&void 0!==r?r:"fld"),this.element=e.createElement("div"),this.element.classList.add(this.className_(),u()),t.viewProps.bindClassModifiers(this.element),this.foldable_=t.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),bindValueMap(this.foldable_,"completed",valueToClassName(this.element,this.className_(void 0,"cpl")));let i=e.createElement("button");i.classList.add(this.className_("b")),bindValueMap(t.props,"title",e=>{isEmpty(e)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let n=e.createElement("div");n.classList.add(this.className_("i")),this.element.appendChild(n);let o=e.createElement("div");o.classList.add(this.className_("t")),bindValueToTextContent(t.props.value("title"),o),this.buttonElement.appendChild(o),this.titleElement=o;let a=e.createElement("div");a.classList.add(this.className_("m")),this.buttonElement.appendChild(a);let l=t.containerElement;l.classList.add(this.className_("c")),this.element.appendChild(l),this.containerElement=l}};let FolderController=class FolderController extends RackLikeController{constructor(e,t){var r;let i=Foldable.create(null===(r=t.expanded)||void 0===r||r),n=new RackController(e,{blade:t.blade,root:t.root,viewProps:t.viewProps});super(Object.assign(Object.assign({},t),{rackController:n,view:new FolderView(e,{containerElement:n.view.element,foldable:i,props:t.props,viewName:t.root?"rot":void 0,viewProps:t.viewProps})})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=t.props,this.foldable=i,bindFoldable(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}};let c={id:"folder",type:"blade",accept(e){let t=parseParams(e,{title:i.required.string,view:i.required.constant("folder"),expanded:i.optional.boolean});return t?{params:t}:null},controller:e=>new FolderController(e.document,{blade:e.blade,expanded:e.params.expanded,props:ValueMap.fromObject({title:e.params.title}),viewProps:e.viewProps}),api:e=>e.controller instanceof FolderController?new FolderApi(e.controller,e.pool):null};let LabeledValueController=class LabeledValueController extends ValueBladeController{constructor(e,t){let r=t.valueController.viewProps;super(Object.assign(Object.assign({},t),{value:t.valueController.value,view:new LabelView(e,{props:t.props,viewProps:r}),viewProps:r})),this.props=t.props,this.valueController=t.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}};let SeparatorApi=class SeparatorApi extends BladeApi{};let h=ClassName("spr");let SeparatorView=class SeparatorView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(h()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("hr");r.classList.add(h("r")),this.element.appendChild(r)}};let SeparatorController=class SeparatorController extends BladeController{constructor(e,t){super(Object.assign(Object.assign({},t),{view:new SeparatorView(e,{viewProps:t.viewProps})}))}};let v={id:"separator",type:"blade",accept(e){let t=parseParams(e,{view:i.required.constant("separator")});return t?{params:t}:null},controller:e=>new SeparatorController(e.document,{blade:e.blade,viewProps:e.viewProps}),api:e=>e.controller instanceof SeparatorController?new SeparatorApi(e.controller):null},m=ClassName("tbi");let TabItemView=class TabItemView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(m()),t.viewProps.bindClassModifiers(this.element),bindValueMap(t.props,"selected",e=>{e?this.element.classList.add(m(void 0,"sel")):this.element.classList.remove(m(void 0,"sel"))});let r=e.createElement("button");r.classList.add(m("b")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.buttonElement=r;let i=e.createElement("div");i.classList.add(m("t")),bindValueToTextContent(t.props.value("title"),i),this.buttonElement.appendChild(i),this.titleElement=i}};let TabItemController=class TabItemController{constructor(e,t){this.emitter=new Emitter,this.onClick_=this.onClick_.bind(this),this.props=t.props,this.viewProps=t.viewProps,this.view=new TabItemView(e,{props:t.props,viewProps:t.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}};let TabPageController=class TabPageController{constructor(e,t){this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new TabItemController(e,{props:t.itemProps,viewProps:ViewProps.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.cc_=new RackController(e,{blade:createBlade(),viewProps:ViewProps.create()}),this.props=t.props,bindValueMap(this.props,"selected",e=>{this.itemController.props.set("selected",e),this.contentController.viewProps.set("hidden",!e)})}get itemController(){return this.ic_}get contentController(){return this.cc_}onItemClick_(){this.props.set("selected",!0)}};let TabPageApi=class TabPageApi{constructor(e,t){this.controller_=e,this.rackApi_=t}get title(){var e;return null!==(e=this.controller_.itemController.props.get("title"))&&void 0!==e?e:""}set title(e){this.controller_.itemController.props.set("title",e)}get selected(){return this.controller_.props.get("selected")}set selected(e){this.controller_.props.set("selected",e)}get children(){return this.rackApi_.children}addButton(e){return this.rackApi_.addButton(e)}addFolder(e){return this.rackApi_.addFolder(e)}addSeparator(e){return this.rackApi_.addSeparator(e)}addTab(e){return this.rackApi_.addTab(e)}add(e,t){this.rackApi_.add(e,t)}remove(e){this.rackApi_.remove(e)}addInput(e,t,r){return this.rackApi_.addInput(e,t,r)}addMonitor(e,t,r){return this.rackApi_.addMonitor(e,t,r)}addBlade(e){return this.rackApi_.addBlade(e)}};let TabApi=class TabApi extends RackLikeApi{constructor(e,t){super(e,new RackApi(e.rackController,t)),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.onSelect_=this.onSelect_.bind(this),this.emitter_=new Emitter,this.pageApiMap_=new Map,this.rackApi_.on("change",e=>{this.emitter_.emit("change",{event:e})}),this.rackApi_.on("update",e=>{this.emitter_.emit("update",{event:e})}),this.controller_.tab.selectedIndex.emitter.on("change",this.onSelect_),this.controller_.pageSet.emitter.on("add",this.onPageAdd_),this.controller_.pageSet.emitter.on("remove",this.onPageRemove_),this.controller_.pageSet.items.forEach(e=>{this.setUpPageApi_(e)})}get pages(){return this.controller_.pageSet.items.map(e=>{let t=this.pageApiMap_.get(e);if(!t)throw TpError.shouldNeverHappen();return t})}addPage(e){let t=this.controller_.view.element.ownerDocument,r=new TabPageController(t,{itemProps:ValueMap.fromObject({selected:!1,title:e.title}),props:ValueMap.fromObject({selected:!1})});this.controller_.add(r,e.index);let i=this.pageApiMap_.get(r);if(!i)throw TpError.shouldNeverHappen();return i}removePage(e){this.controller_.remove(e)}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}setUpPageApi_(e){let t=this.rackApi_.apiSet_.find(t=>t.controller_===e.contentController);if(!t)throw TpError.shouldNeverHappen();let r=new TabPageApi(e,t);this.pageApiMap_.set(e,r)}onPageAdd_(e){this.setUpPageApi_(e.item)}onPageRemove_(e){let t=this.pageApiMap_.get(e.item);if(!t)throw TpError.shouldNeverHappen();this.pageApiMap_.delete(e.item)}onSelect_(e){this.emitter_.emit("select",{event:new TpTabSelectEvent(this,e.rawValue)})}};let Tab=class Tab{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=createValue(!0),this.selectedIndex=createValue(-1),this.items_=[]}add(e,t){let r=null!=t?t:this.items_.length;this.items_.splice(r,0,e),e.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(e){let t=this.items_.indexOf(e);t<0||(this.items_.splice(t,1),e.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length){this.selectedIndex.rawValue=-1,this.empty.rawValue=!0;return}let e=this.items_.findIndex(e=>e.rawValue);e<0?(this.items_.forEach((e,t)=>{e.rawValue=0===t}),this.selectedIndex.rawValue=0):(this.items_.forEach((t,r)=>{t.rawValue=r===e}),this.selectedIndex.rawValue=e),this.empty.rawValue=!1}onItemSelectedChange_(e){if(e.rawValue){let t=this.items_.findIndex(t=>t===e.sender);this.items_.forEach((e,r)=>{e.rawValue=r===t}),this.selectedIndex.rawValue=t}else this.keepSelection_()}};let b=ClassName("tab");let TabView=class TabView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(b(),u()),t.viewProps.bindClassModifiers(this.element),bindValue(t.empty,valueToClassName(this.element,b(void 0,"nop")));let r=e.createElement("div");r.classList.add(b("t")),this.element.appendChild(r),this.itemsElement=r;let i=e.createElement("div");i.classList.add(b("i")),this.element.appendChild(i);let n=t.contentsElement;n.classList.add(b("c")),this.element.appendChild(n),this.contentsElement=n}};let TabController=class TabController extends RackLikeController{constructor(e,t){let r=new RackController(e,{blade:t.blade,viewProps:t.viewProps}),i=new Tab;super({blade:t.blade,rackController:r,view:new TabView(e,{contentsElement:r.view.element,empty:i.empty,viewProps:t.viewProps})}),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.pageSet_=new NestedOrderedSet(()=>null),this.pageSet_.emitter.on("add",this.onPageAdd_),this.pageSet_.emitter.on("remove",this.onPageRemove_),this.tab=i}get pageSet(){return this.pageSet_}add(e,t){this.pageSet_.add(e,t)}remove(e){this.pageSet_.remove(this.pageSet_.items[e])}onPageAdd_(e){let t=e.item;insertElementAt(this.view.itemsElement,t.itemController.view.element,e.index),t.itemController.viewProps.set("parent",this.viewProps),this.rackController.rack.add(t.contentController,e.index),this.tab.add(t.props.value("selected"))}onPageRemove_(e){let t=e.item;removeElement(t.itemController.view.element),t.itemController.viewProps.set("parent",null),this.rackController.rack.remove(t.contentController),this.tab.remove(t.props.value("selected"))}};let g={id:"tab",type:"blade",accept(e){let t=parseParams(e,{pages:i.required.array(i.required.object({title:i.required.string})),view:i.required.constant("tab")});return t&&0!==t.pages.length?{params:t}:null},controller(e){let t=new TabController(e.document,{blade:e.blade,viewProps:e.viewProps});return e.params.pages.forEach(r=>{let i=new TabPageController(e.document,{itemProps:ValueMap.fromObject({selected:!1,title:r.title}),props:ValueMap.fromObject({selected:!1})});t.add(i)}),t},api:e=>e.controller instanceof TabController?new TabApi(e.controller,e.pool):null};function createBladeController(e,t){let r=e.accept(t.params);if(!r)return null;let n=i.optional.boolean(t.params.disabled).value,o=i.optional.boolean(t.params.hidden).value;return e.controller({blade:createBlade(),document:t.document,params:Object.assign(Object.assign({},r.params),{disabled:n,hidden:o}),viewProps:ViewProps.create({disabled:n,hidden:o})})}let ManualTicker=class ManualTicker{constructor(){this.disabled=!1,this.emitter=new Emitter}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}};let IntervalTicker=class IntervalTicker{constructor(e,t){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=e,this.emitter=new Emitter,this.interval_=t,this.setTimer_()}get disabled(){return this.disabled_}set disabled(e){this.disabled_=e,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;let e=this.doc_.defaultView;e&&e.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;let e=this.doc_.defaultView;e&&(this.timerId_=e.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}};let InputBinding=class InputBinding{constructor(e){this.onValueChange_=this.onValueChange_.bind(this),this.reader=e.reader,this.writer=e.writer,this.emitter=new Emitter,this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.target=e.target,this.read()}read(){let e=this.target.read();void 0!==e&&(this.value.rawValue=this.reader(e))}write_(e){this.writer(this.target,e)}onValueChange_(e){this.write_(e.rawValue),this.emitter.emit("change",{options:e.options,rawValue:e.rawValue,sender:this})}};function fillBuffer(e,t){for(;e.lengthe.length?r.splice(0,r.length-e.length):fillBuffer(r,e.length),r}let MonitorBinding=class MonitorBinding{constructor(e){this.onTick_=this.onTick_.bind(this),this.reader_=e.reader,this.target=e.target,this.emitter=new Emitter,this.value=e.value,this.ticker=e.ticker,this.ticker.emitter.on("tick",this.onTick_),this.read()}dispose(){this.ticker.dispose()}read(){let e=this.target.read();if(void 0===e)return;let t=this.value.rawValue,r=this.reader_(e);this.value.rawValue=createPushedBuffer(t,r),this.emitter.emit("update",{rawValue:r,sender:this})}onTick_(e){this.read()}};let CompositeConstraint=class CompositeConstraint{constructor(e){this.constraints=e}constrain(e){return this.constraints.reduce((e,t)=>t.constrain(e),e)}};function findConstraint(e,t){if(e instanceof t)return e;if(e instanceof CompositeConstraint){let r=e.constraints.reduce((e,r)=>e||(r instanceof t?r:null),null);if(r)return r}return null}let DefiniteRangeConstraint=class DefiniteRangeConstraint{constructor(e){this.values=ValueMap.fromObject({max:e.max,min:e.min})}constrain(e){let t=this.values.get("max"),r=this.values.get("min");return Math.min(Math.max(e,r),t)}};let ListConstraint=class ListConstraint{constructor(e){this.values=ValueMap.fromObject({options:e})}get options(){return this.values.get("options")}constrain(e){let t=this.values.get("options");if(0===t.length)return e;let r=t.filter(t=>t.value===e).length>0;return r?e:t[0].value}};let RangeConstraint=class RangeConstraint{constructor(e){this.values=ValueMap.fromObject({max:e.max,min:e.min})}get maxValue(){return this.values.get("max")}get minValue(){return this.values.get("min")}constrain(e){let t=this.values.get("max"),r=this.values.get("min"),i=e;return isEmpty(r)||(i=Math.max(i,r)),isEmpty(t)||(i=Math.min(i,t)),i}};let StepConstraint=class StepConstraint{constructor(e,t=0){this.step=e,this.origin=t}constrain(e){let t=this.origin%this.step,r=Math.round((e-t)/this.step);return t+r*this.step}};let _=ClassName("lst");let ListView=class ListView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.props_=t.props,this.element=e.createElement("div"),this.element.classList.add(_()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("select");r.classList.add(_("s")),t.viewProps.bindDisabled(r),this.element.appendChild(r),this.selectElement=r;let i=e.createElement("div");i.classList.add(_("m")),i.appendChild(createSvgIconElement(e,"dropdown")),this.element.appendChild(i),t.value.emitter.on("change",this.onValueChange_),this.value_=t.value,bindValueMap(this.props_,"options",t=>{removeChildElements(this.selectElement),t.forEach(t=>{let r=e.createElement("option");r.textContent=t.text,this.selectElement.appendChild(r)}),this.update_()})}update_(){let e=this.props_.get("options").map(e=>e.value);this.selectElement.selectedIndex=e.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}};let ListController=class ListController{constructor(e,t){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new ListView(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(e){let t=e.currentTarget;this.value.rawValue=this.props.get("options")[t.selectedIndex].value}};let f=ClassName("pop");let PopupView=class PopupView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(f()),t.viewProps.bindClassModifiers(this.element),bindValue(t.shows,valueToClassName(this.element,f(void 0,"v")))}};let PopupController=class PopupController{constructor(e,t){this.shows=createValue(!1),this.viewProps=t.viewProps,this.view=new PopupView(e,{shows:this.shows,viewProps:this.viewProps})}};let w=ClassName("txt");let TextView=class TextView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(w()),t.viewProps.bindClassModifiers(this.element),this.props_=t.props,this.props_.emitter.on("change",this.onChange_);let r=e.createElement("input");r.classList.add(w("i")),r.type="text",t.viewProps.bindDisabled(r),this.element.appendChild(r),this.inputElement=r,t.value.emitter.on("change",this.onChange_),this.value_=t.value,this.refresh()}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value_.rawValue)}onChange_(){this.refresh()}};let TextController=class TextController{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=t.parser,this.props=t.props,this.value=t.value,this.viewProps=t.viewProps,this.view=new TextView(e,{props:t.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget,r=t.value,i=this.parser_(r);isEmpty(i)||(this.value.rawValue=i),this.view.refresh()}};function boolToString(e){return String(e)}function boolFromUnknown(e){return"false"!==e&&!!e}function BooleanFormatter(e){return boolToString(e)}let NumberLiteralNode=class NumberLiteralNode{constructor(e){this.text=e}evaluate(){return Number(this.text)}toString(){return this.text}};let C={"**":(e,t)=>Math.pow(e,t),"*":(e,t)=>e*t,"/":(e,t)=>e/t,"%":(e,t)=>e%t,"+":(e,t)=>e+t,"-":(e,t)=>e-t,"<<":(e,t)=>e<>":(e,t)=>e>>t,">>>":(e,t)=>e>>>t,"&":(e,t)=>e&t,"^":(e,t)=>e^t,"|":(e,t)=>e|t};let BinaryOperationNode=class BinaryOperationNode{constructor(e,t,r){this.left=t,this.operator=e,this.right=r}evaluate(){let e=C[this.operator];if(!e)throw Error(`unexpected binary operator: '${this.operator}`);return e(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}};let x={"+":e=>e,"-":e=>-e,"~":e=>~e};let UnaryOperationNode=class UnaryOperationNode{constructor(e,t){this.operator=e,this.expression=t}evaluate(){let e=x[this.operator];if(!e)throw Error(`unexpected unary operator: '${this.operator}`);return e(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}};function combineReader(e){return(t,r)=>{for(let i=0;it.startsWith(e,r))[0];return i?(r+=i.length,{cursor:r+=readWhitespace(t,r).length,operator:i}):null}function createBinaryOperationExpressionParser(e,t){return(r,i)=>{let n=e(r,i);if(!n)return null;i=n.cursor;let o=n.evaluable;for(;;){let n=readBinaryOperator(t,r,i);if(!n)break;i=n.cursor;let a=e(r,i);if(!a)return null;i=a.cursor,o=new BinaryOperationNode(n.operator,o,a.evaluable)}return o?{cursor:i,evaluable:o}:null}}let V=[["**"],["*","/","%"],["+","-"],["<<",">>>",">>"],["&"],["^"],["|"]].reduce((e,t)=>createBinaryOperationExpressionParser(e,t),parseUnaryExpression);function parseExpression(e,t){return t+=readWhitespace(e,t).length,V(e,t)}function parseEcmaNumberExpression(e){let t=parseExpression(e,0);if(!t)return null;let r=t.cursor+readWhitespace(e,t.cursor).length;return r!==e.length?null:t.evaluable}function parseNumber(e){var t;let r=parseEcmaNumberExpression(e);return null!==(t=null==r?void 0:r.evaluate())&&void 0!==t?t:null}function numberFromUnknown(e){if("number"==typeof e)return e;if("string"==typeof e){let t=parseNumber(e);if(!isEmpty(t))return t}return 0}function numberToString(e){return String(e)}function createNumberFormatter(e){return t=>t.toFixed(Math.max(Math.min(e,20),0))}let k=createNumberFormatter(0);function formatPercentage(e){return k(e)+"%"}function stringFromUnknown(e){return String(e)}function formatString(e){return e}function connectValues({primary:e,secondary:t,forward:r,backward:i}){let n=!1;function preventFeedback(e){n||(n=!0,e(),n=!1)}e.emitter.on("change",i=>{preventFeedback(()=>{t.setRawValue(r(e,t),i.options)})}),t.emitter.on("change",n=>{preventFeedback(()=>{e.setRawValue(i(e,t),n.options)}),preventFeedback(()=>{t.setRawValue(r(e,t),n.options)})}),preventFeedback(()=>{t.setRawValue(r(e,t),{forceEmit:!1,last:!0})})}function getStepForKey(e,t){let r=e*(t.altKey?.1:1)*(t.shiftKey?10:1);return t.upKey?+r:t.downKey?-r:0}function getVerticalStepKeys(e){return{altKey:e.altKey,downKey:"ArrowDown"===e.key,shiftKey:e.shiftKey,upKey:"ArrowUp"===e.key}}function getHorizontalStepKeys(e){return{altKey:e.altKey,downKey:"ArrowLeft"===e.key,shiftKey:e.shiftKey,upKey:"ArrowRight"===e.key}}function isVerticalArrowKey(e){return"ArrowUp"===e||"ArrowDown"===e}function isArrowKey(e){return isVerticalArrowKey(e)||"ArrowLeft"===e||"ArrowRight"===e}function computeOffset$1(e,t){var r,i;let n=t.ownerDocument.defaultView,o=t.getBoundingClientRect();return{x:e.pageX-((null!==(r=n&&n.scrollX)&&void 0!==r?r:0)+o.left),y:e.pageY-((null!==(i=n&&n.scrollY)&&void 0!==i?i:0)+o.top)}}let PointerHandler=class PointerHandler{constructor(e){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=e,this.emitter=new Emitter,e.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),e.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),e.addEventListener("touchend",this.onTouchEnd_),e.addEventListener("mousedown",this.onMouseDown_)}computePosition_(e){let t=this.elem_.getBoundingClientRect();return{bounds:{width:t.width,height:t.height},point:e?{x:e.x,y:e.y}:null}}onMouseDown_(e){var t;e.preventDefault(),null===(t=e.currentTarget)||void 0===t||t.focus();let r=this.elem_.ownerDocument;r.addEventListener("mousemove",this.onDocumentMouseMove_),r.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseMove_(e){this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onDocumentMouseUp_(e){let t=this.elem_.ownerDocument;t.removeEventListener("mousemove",this.onDocumentMouseMove_),t.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(computeOffset$1(e,this.elem_)),sender:this,shiftKey:e.shiftKey})}onTouchStart_(e){e.preventDefault();let t=e.targetTouches.item(0),r=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-r.left,y:t.clientY-r.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchMove_(e){let t=e.targetTouches.item(0),r=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:e.altKey,data:this.computePosition_(t?{x:t.clientX-r.left,y:t.clientY-r.top}:void 0),sender:this,shiftKey:e.shiftKey}),this.lastTouch_=t}onTouchEnd_(e){var t;let r=null!==(t=e.targetTouches.item(0))&&void 0!==t?t:this.lastTouch_,i=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:e.altKey,data:this.computePosition_(r?{x:r.clientX-i.left,y:r.clientY-i.top}:void 0),sender:this,shiftKey:e.shiftKey})}};function mapRange(e,t,r,i,n){return i+(e-t)/(r-t)*(n-i)}function getDecimalDigits(e){let t=String(e.toFixed(10)),r=t.split(".")[1];return r.replace(/0+$/,"").length}function constrainRange(e,t,r){return Math.min(Math.max(e,t),r)}let S=ClassName("txt");let NumberTextView=class NumberTextView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(S(),S(void 0,"num")),t.arrayPosition&&this.element.classList.add(S(void 0,t.arrayPosition)),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("input");r.classList.add(S("i")),r.type="text",t.viewProps.bindDisabled(r),this.element.appendChild(r),this.inputElement=r,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=t.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(S()),this.inputElement.classList.add(S("i"));let i=e.createElement("div");i.classList.add(S("k")),this.element.appendChild(i),this.knobElement=i;let n=e.createElementNS(l,"svg");n.classList.add(S("g")),this.knobElement.appendChild(n);let o=e.createElementNS(l,"path");o.classList.add(S("gb")),n.appendChild(o),this.guideBodyElem_=o;let a=e.createElementNS(l,"path");a.classList.add(S("gh")),n.appendChild(a),this.guideHeadElem_=a;let s=e.createElement("div");s.classList.add(ClassName("tt")()),this.knobElement.appendChild(s),this.tooltipElem_=s,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.refresh()}onDraggingChange_(e){if(null===e.rawValue){this.element.classList.remove(S(void 0,"drg"));return}this.element.classList.add(S(void 0,"drg"));let t=e.rawValue/this.props_.get("draggingScale"),r=t+(t>0?-1:t<0?1:0),i=constrainRange(-r,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",`M ${r+i},0 L${r},4 L${r+i},8 M ${t},-1 L${t},9`),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${t},4`);let n=this.props_.get("formatter");this.tooltipElem_.textContent=n(this.value.rawValue),this.tooltipElem_.style.left=`${t}px`}refresh(){let e=this.props_.get("formatter");this.inputElement.value=e(this.value.rawValue)}onChange_(){this.refresh()}};let NumberTextController=class NumberTextController{constructor(e,t){var r;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.parser_=t.parser,this.props=t.props,this.sliderProps_=null!==(r=t.sliderProps)&&void 0!==r?r:null,this.value=t.value,this.viewProps=t.viewProps,this.dragging_=createValue(null),this.view=new NumberTextView(e,{arrayPosition:t.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);let i=new PointerHandler(this.view.knobElement);i.emitter.on("down",this.onPointerDown_),i.emitter.on("move",this.onPointerMove_),i.emitter.on("up",this.onPointerUp_)}constrainValue_(e){var t,r;let i=null===(t=this.sliderProps_)||void 0===t?void 0:t.get("minValue"),n=null===(r=this.sliderProps_)||void 0===r?void 0:r.get("maxValue"),o=e;return void 0!==i&&(o=Math.max(o,i)),void 0!==n&&(o=Math.min(o,n)),o}onInputChange_(e){let t=e.currentTarget,r=t.value,i=this.parser_(r);isEmpty(i)||(this.value.rawValue=this.constrainValue_(i)),this.view.refresh()}onInputKeyDown_(e){let t=getStepForKey(this.baseStep_,getVerticalStepKeys(e));0!==t&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+t),{forceEmit:!1,last:!1})}onInputKeyUp_(e){let t=getStepForKey(this.baseStep_,getVerticalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(e){if(!e.point)return null;let t=e.point.x-e.bounds.width/2;return this.constrainValue_(this.originRawValue_+t*this.props.get("draggingScale"))}onPointerMove_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(e){let t=this.computeDraggingValue_(e.data);null!==t&&(this.value.setRawValue(t,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}};let T=ClassName("sld");let SliderView=class SliderView{constructor(e,t){this.onChange_=this.onChange_.bind(this),this.props_=t.props,this.props_.emitter.on("change",this.onChange_),this.element=e.createElement("div"),this.element.classList.add(T()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(T("t")),t.viewProps.bindTabIndex(r),this.element.appendChild(r),this.trackElement=r;let i=e.createElement("div");i.classList.add(T("k")),this.trackElement.appendChild(i),this.knobElement=i,t.value.emitter.on("change",this.onChange_),this.value=t.value,this.update_()}update_(){let e=constrainRange(mapRange(this.value.rawValue,this.props_.get("minValue"),this.props_.get("maxValue"),0,100),0,100);this.knobElement.style.width=`${e}%`}onChange_(){this.update_()}};let SliderController=class SliderController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=t.baseStep,this.value=t.value,this.viewProps=t.viewProps,this.props=t.props,this.view=new SliderView(e,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){e.point&&this.value.setRawValue(mapRange(constrainRange(e.point.x,0,e.bounds.width),0,e.bounds.width,this.props.get("minValue"),this.props.get("maxValue")),t)}onPointerDownOrMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(this.baseStep_,getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue+t,{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(this.baseStep_,getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let R=ClassName("sldtxt");let SliderTextView=class SliderTextView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(R());let r=e.createElement("div");r.classList.add(R("s")),this.sliderView_=t.sliderView,r.appendChild(this.sliderView_.element),this.element.appendChild(r);let i=e.createElement("div");i.classList.add(R("t")),this.textView_=t.textView,i.appendChild(this.textView_.element),this.element.appendChild(i)}};let SliderTextController=class SliderTextController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.sliderC_=new SliderController(e,{baseStep:t.baseStep,props:t.sliderProps,value:t.value,viewProps:this.viewProps}),this.textC_=new NumberTextController(e,{baseStep:t.baseStep,parser:t.parser,props:t.textProps,sliderProps:t.sliderProps,value:t.value,viewProps:t.viewProps}),this.view=new SliderTextView(e,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}};function writePrimitive(e,t){e.write(t)}function parseListOptions(e){return Array.isArray(e)?i.required.array(i.required.object({text:i.required.string,value:i.required.raw}))(e).value:"object"==typeof e?i.required.raw(e).value:void 0}function parsePickerLayout(e){if("inline"===e||"popup"===e)return e}function parsePointDimensionParams(e){return i.required.object({max:i.optional.number,min:i.optional.number,step:i.optional.number})(e).value}function normalizeListOptions(e){if(Array.isArray(e))return e;let t=[];return Object.keys(e).forEach(r=>{t.push({text:r,value:e[r]})}),t}function createListConstraint(e){return isEmpty(e)?null:new ListConstraint(normalizeListOptions(e))}function findStep(e){let t=e?findConstraint(e,StepConstraint):null;return t?t.step:null}function getSuitableDecimalDigits(e,t){let r=e&&findConstraint(e,StepConstraint);return r?getDecimalDigits(r.step):Math.max(getDecimalDigits(t),2)}function getBaseStep(e){let t=findStep(e);return null!=t?t:1}function getSuitableDraggingScale(e,t){var r;let i=e&&findConstraint(e,StepConstraint),n=Math.abs(null!==(r=null==i?void 0:i.step)&&void 0!==r?r:t);return 0===n?.1:Math.pow(10,Math.floor(Math.log10(n))-1)}let M=ClassName("ckb");let CheckboxView=class CheckboxView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.element=e.createElement("div"),this.element.classList.add(M()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("label");r.classList.add(M("l")),this.element.appendChild(r);let i=e.createElement("input");i.classList.add(M("i")),i.type="checkbox",r.appendChild(i),this.inputElement=i,t.viewProps.bindDisabled(this.inputElement);let n=e.createElement("div");n.classList.add(M("w")),r.appendChild(n);let o=createSvgIconElement(e,"check");n.appendChild(o),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}};let CheckboxController=class CheckboxController{constructor(e,t){this.onInputChange_=this.onInputChange_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new CheckboxView(e,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(e){let t=e.currentTarget;this.value.rawValue=t.checked}};function createConstraint$6(e){let t=[],r=createListConstraint(e.options);return r&&t.push(r),new CompositeConstraint(t)}let L={id:"input-bool",type:"input",accept:(e,t)=>{if("boolean"!=typeof e)return null;let r=parseParams(t,{options:i.optional.custom(parseListOptions)});return r?{initialValue:e,params:r}:null},binding:{reader:e=>boolFromUnknown,constraint:e=>createConstraint$6(e.params),writer:e=>writePrimitive},controller:e=>{let t=e.document,r=e.value,i=e.constraint,n=i&&findConstraint(i,ListConstraint);return n?new ListController(t,{props:new ValueMap({options:n.values.value("options")}),value:r,viewProps:e.viewProps}):new CheckboxController(t,{value:r,viewProps:e.viewProps})}},A=ClassName("col");let ColorView=class ColorView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(A()),t.foldable.bindExpandedClass(this.element,A(void 0,"expanded")),bindValueMap(t.foldable,"completed",valueToClassName(this.element,A(void 0,"cpl")));let r=e.createElement("div");r.classList.add(A("h")),this.element.appendChild(r);let i=e.createElement("div");i.classList.add(A("s")),r.appendChild(i),this.swatchElement=i;let n=e.createElement("div");if(n.classList.add(A("t")),r.appendChild(n),this.textElement=n,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(A("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};function rgbToHslInt(e,t,r){let i=constrainRange(e/255,0,1),n=constrainRange(t/255,0,1),o=constrainRange(r/255,0,1),a=Math.max(i,n,o),l=Math.min(i,n,o),s=a-l,p=0,d=0;return 0!==s&&(d=s/(1-Math.abs(a+l-1)),p=(p=i===a?(n-o)/s:n===a?2+(o-i)/s:4+(i-n)/s)/6+(p<0?1:0)),[360*p,100*d,100*((l+a)/2)]}function hslToRgbInt(e,t,r){let i,n,o;let a=(e%360+360)%360,l=constrainRange(t/100,0,1),s=constrainRange(r/100,0,1),p=(1-Math.abs(2*s-1))*l,d=p*(1-Math.abs(a/60%2-1)),u=s-p/2;return a>=0&&a<60?[i,n,o]=[p,d,0]:a>=60&&a<120?[i,n,o]=[d,p,0]:a>=120&&a<180?[i,n,o]=[0,p,d]:a>=180&&a<240?[i,n,o]=[0,d,p]:a>=240&&a<300?[i,n,o]=[d,0,p]:[i,n,o]=[p,0,d],[(i+u)*255,(n+u)*255,(o+u)*255]}function rgbToHsvInt(e,t,r){let i=constrainRange(e/255,0,1),n=constrainRange(t/255,0,1),o=constrainRange(r/255,0,1),a=Math.max(i,n,o),l=a-Math.min(i,n,o);return[0===l?0:a===i?60*(((n-o)/l%6+6)%6):a===n?60*((o-i)/l+2):60*((i-n)/l+4),100*(0===a?0:l/a),100*a]}function hsvToRgbInt(e,t,r){let i,n,o;let a=(e%360+360)%360,l=constrainRange(t/100,0,1),s=constrainRange(r/100,0,1),p=s*l,d=p*(1-Math.abs(a/60%2-1)),u=s-p;return a>=0&&a<60?[i,n,o]=[p,d,0]:a>=60&&a<120?[i,n,o]=[d,p,0]:a>=120&&a<180?[i,n,o]=[0,p,d]:a>=180&&a<240?[i,n,o]=[0,d,p]:a>=240&&a<300?[i,n,o]=[d,0,p]:[i,n,o]=[p,0,d],[(i+u)*255,(n+u)*255,(o+u)*255]}function hslToHsvInt(e,t,r){let i=r+t*(100-Math.abs(2*r-100))/200;return[e,0!==i?t*(100-Math.abs(2*r-100))/i:0,r+t*(100-Math.abs(2*r-100))/200]}function hsvToHslInt(e,t,r){let i=100-Math.abs(r*(200-t)/100-100);return[e,0!==i?t*r/i:0,r*(200-t)/200]}function removeAlphaComponent(e){return[e[0],e[1],e[2]]}function appendAlphaComponent(e,t){return[e[0],e[1],e[2],t]}let B={hsl:{hsl:(e,t,r)=>[e,t,r],hsv:hslToHsvInt,rgb:hslToRgbInt},hsv:{hsl:hsvToHslInt,hsv:(e,t,r)=>[e,t,r],rgb:hsvToRgbInt},rgb:{hsl:rgbToHslInt,hsv:rgbToHsvInt,rgb:(e,t,r)=>[e,t,r]}};function getColorMaxComponents(e,t){return["float"===t?1:"rgb"===e?255:360,"float"===t?1:"rgb"===e?255:100,"float"===t?1:"rgb"===e?255:100]}function loopHueRange(e,t){return e===t?t:(e%t+t)%t}function constrainColorComponents(e,t,r){var i;let n=getColorMaxComponents(t,r);return["rgb"===t?constrainRange(e[0],0,n[0]):loopHueRange(e[0],n[0]),constrainRange(e[1],0,n[1]),constrainRange(e[2],0,n[2]),constrainRange(null!==(i=e[3])&&void 0!==i?i:1,0,1)]}function convertColorType(e,t,r,i){let n=getColorMaxComponents(t,r),o=getColorMaxComponents(t,i);return e.map((e,t)=>e/n[t]*o[t])}function convertColor(e,t,r){let i=convertColorType(e,t.mode,t.type,"int"),n=B[t.mode][r.mode](...i);return convertColorType(n,r.mode,"int",r.type)}function isRgbColorComponent(e,t){return!("object"!=typeof e||isEmpty(e))&&t in e&&"number"==typeof e[t]}let Color=class Color{static black(e="int"){return new Color([0,0,0],"rgb",e)}static fromObject(e,t="int"){let r="a"in e?[e.r,e.g,e.b,e.a]:[e.r,e.g,e.b];return new Color(r,"rgb",t)}static toRgbaObject(e,t="int"){return e.toRgbaObject(t)}static isRgbColorObject(e){return isRgbColorComponent(e,"r")&&isRgbColorComponent(e,"g")&&isRgbColorComponent(e,"b")}static isRgbaColorObject(e){return this.isRgbColorObject(e)&&isRgbColorComponent(e,"a")}static isColorObject(e){return this.isRgbColorObject(e)}static equals(e,t){if(e.mode!==t.mode)return!1;let r=e.comps_,i=t.comps_;for(let e=0;ee.inputElement)];return this.alphaViews_&&e.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),e}};function parseColorType(e){return"int"===e?"int":"float"===e?"float":void 0}function parseColorInputParams(e){return parseParams(e,{alpha:i.optional.boolean,color:i.optional.object({alpha:i.optional.boolean,type:i.optional.custom(parseColorType)}),expanded:i.optional.boolean,picker:i.optional.custom(parsePickerLayout)})}function getBaseStepForColor(e){return e?.1:1}function extractColorType(e){var t;return null===(t=e.color)||void 0===t?void 0:t.type}function equalsStringColorFormat(e,t){return e.alpha===t.alpha&&e.mode===t.mode&&e.notation===t.notation&&e.type===t.type}function parseCssNumberOrPercentage(e,t){let r=e.match(/^(.+)%$/);return r?Math.min(.01*parseFloat(r[1])*t,t):Math.min(parseFloat(e),t)}let N={deg:e=>e,grad:e=>360*e/400,rad:e=>360*e/(2*Math.PI),turn:e=>360*e};function parseCssNumberOrAngle(e){let t=e.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!t)return parseFloat(e);let r=parseFloat(t[1]),i=t[2];return N[i](r)}function parseFunctionalRgbColorComponents(e){let t=e.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let r=[parseCssNumberOrPercentage(t[1],255),parseCssNumberOrPercentage(t[2],255),parseCssNumberOrPercentage(t[3],255)];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])?null:r}function createFunctionalRgbColorParser(e){return t=>{let r=parseFunctionalRgbColorComponents(t);return r?new Color(r,"rgb",e):null}}function parseFunctionalRgbaColorComponents(e){let t=e.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let r=[parseCssNumberOrPercentage(t[1],255),parseCssNumberOrPercentage(t[2],255),parseCssNumberOrPercentage(t[3],255),parseCssNumberOrPercentage(t[4],1)];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])||isNaN(r[3])?null:r}function createFunctionalRgbaColorParser(e){return t=>{let r=parseFunctionalRgbaColorComponents(t);return r?new Color(r,"rgb",e):null}}function parseHslColorComponents(e){let t=e.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let r=[parseCssNumberOrAngle(t[1]),parseCssNumberOrPercentage(t[2],100),parseCssNumberOrPercentage(t[3],100)];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])?null:r}function createHslColorParser(e){return t=>{let r=parseHslColorComponents(t);return r?new Color(r,"hsl",e):null}}function parseHslaColorComponents(e){let t=e.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!t)return null;let r=[parseCssNumberOrAngle(t[1]),parseCssNumberOrPercentage(t[2],100),parseCssNumberOrPercentage(t[3],100),parseCssNumberOrPercentage(t[4],1)];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])||isNaN(r[3])?null:r}function createHslaColorParser(e){return t=>{let r=parseHslaColorComponents(t);return r?new Color(r,"hsl",e):null}}function parseHexRgbColorComponents(e){let t=e.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16)];let r=e.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return r?[parseInt(r[1],16),parseInt(r[2],16),parseInt(r[3],16)]:null}function parseHexRgbColor(e){let t=parseHexRgbColorComponents(e);return t?new Color(t,"rgb","int"):null}function parseHexRgbaColorComponents(e){let t=e.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(t)return[parseInt(t[1]+t[1],16),parseInt(t[2]+t[2],16),parseInt(t[3]+t[3],16),mapRange(parseInt(t[4]+t[4],16),0,255,0,1)];let r=e.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return r?[parseInt(r[1],16),parseInt(r[2],16),parseInt(r[3],16),mapRange(parseInt(r[4],16),0,255,0,1)]:null}function parseHexRgbaColor(e){let t=parseHexRgbaColorComponents(e);return t?new Color(t,"rgb","int"):null}function parseObjectRgbColorComponents(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let r=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])?null:r}function createObjectRgbColorParser(e){return t=>{let r=parseObjectRgbColorComponents(t);return r?new Color(r,"rgb",e):null}}function parseObjectRgbaColorComponents(e){let t=e.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!t)return null;let r=[parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3]),parseFloat(t[4])];return isNaN(r[0])||isNaN(r[1])||isNaN(r[2])||isNaN(r[3])?null:r}function createObjectRgbaColorParser(e){return t=>{let r=parseObjectRgbaColorComponents(t);return r?new Color(r,"rgb",e):null}}let F=[{parser:parseHexRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:parseHexRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:parseFunctionalRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:parseFunctionalRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:parseHslColorComponents,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:parseHslaColorComponents,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:parseObjectRgbColorComponents,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:parseObjectRgbaColorComponents,result:{alpha:!0,mode:"rgb",notation:"object"}}];function detectStringColor(e){return F.reduce((t,{parser:r,result:i})=>t||(r(e)?i:null),null)}function detectStringColorFormat(e,t="int"){let r=detectStringColor(e);return r?"hex"===r.notation&&"float"!==t?Object.assign(Object.assign({},r),{type:"int"}):"func"===r.notation?Object.assign(Object.assign({},r),{type:t}):null:null}let O={int:[parseHexRgbColor,parseHexRgbaColor,createFunctionalRgbColorParser("int"),createFunctionalRgbaColorParser("int"),createHslColorParser("int"),createHslaColorParser("int"),createObjectRgbColorParser("int"),createObjectRgbaColorParser("int")],float:[createFunctionalRgbColorParser("float"),createFunctionalRgbaColorParser("float"),createHslColorParser("float"),createHslaColorParser("float"),createObjectRgbColorParser("float"),createObjectRgbaColorParser("float")]};function createColorStringBindingReader(e){let t=O[e];return r=>{if("string"!=typeof r)return Color.black(e);let i=t.reduce((e,t)=>e||t(r),null);return null!=i?i:Color.black(e)}}function createColorStringParser(e){let t=O[e];return e=>t.reduce((t,r)=>t||r(e),null)}function zerofill(e){let t=constrainRange(Math.floor(e),0,255).toString(16);return 1===t.length?`0${t}`:t}function colorToHexRgbString(e,t="#"){let r=removeAlphaComponent(e.getComponents("rgb")).map(zerofill).join("");return`${t}${r}`}function colorToHexRgbaString(e,t="#"){let r=e.getComponents("rgb"),i=[r[0],r[1],r[2],255*r[3]].map(zerofill).join("");return`${t}${i}`}function colorToFunctionalRgbString(e,t){let r=createNumberFormatter("float"===t?2:0),i=removeAlphaComponent(e.getComponents("rgb",t)).map(e=>r(e));return`rgb(${i.join(", ")})`}function createFunctionalRgbColorFormatter(e){return t=>colorToFunctionalRgbString(t,e)}function colorToFunctionalRgbaString(e,t){let r=createNumberFormatter(2),i=createNumberFormatter("float"===t?2:0),n=e.getComponents("rgb",t).map((e,t)=>(3===t?r:i)(e));return`rgba(${n.join(", ")})`}function createFunctionalRgbaColorFormatter(e){return t=>colorToFunctionalRgbaString(t,e)}function colorToFunctionalHslString(e){let t=[createNumberFormatter(0),formatPercentage,formatPercentage],r=removeAlphaComponent(e.getComponents("hsl")).map((e,r)=>t[r](e));return`hsl(${r.join(", ")})`}function colorToFunctionalHslaString(e){let t=[createNumberFormatter(0),formatPercentage,formatPercentage,createNumberFormatter(2)],r=e.getComponents("hsl").map((e,r)=>t[r](e));return`hsla(${r.join(", ")})`}function colorToObjectRgbString(e,t){let r=createNumberFormatter("float"===t?2:0),i=["r","g","b"],n=removeAlphaComponent(e.getComponents("rgb",t)).map((e,t)=>`${i[t]}: ${r(e)}`);return`{${n.join(", ")}}`}function createObjectRgbColorFormatter(e){return t=>colorToObjectRgbString(t,e)}function colorToObjectRgbaString(e,t){let r=createNumberFormatter(2),i=createNumberFormatter("float"===t?2:0),n=["r","g","b","a"],o=e.getComponents("rgb",t).map((e,t)=>`${n[t]}: ${(3===t?r:i)(e)}`);return`{${o.join(", ")}}`}function createObjectRgbaColorFormatter(e){return t=>colorToObjectRgbaString(t,e)}let I=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:colorToHexRgbString},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:colorToHexRgbaString},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:colorToFunctionalHslString},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:colorToFunctionalHslaString},...["int","float"].reduce((e,t)=>[...e,{format:{alpha:!1,mode:"rgb",notation:"func",type:t},stringifier:createFunctionalRgbColorFormatter(t)},{format:{alpha:!0,mode:"rgb",notation:"func",type:t},stringifier:createFunctionalRgbaColorFormatter(t)},{format:{alpha:!1,mode:"rgb",notation:"object",type:t},stringifier:createObjectRgbColorFormatter(t)},{format:{alpha:!0,mode:"rgb",notation:"object",type:t},stringifier:createObjectRgbaColorFormatter(t)}],[])];function findColorStringifier(e){return I.reduce((t,r)=>t||(equalsStringColorFormat(r.format,e)?r.stringifier:null),null)}let j=ClassName("apl");let APaletteView=class APaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(j()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let r=e.createElement("div");r.classList.add(j("b")),this.element.appendChild(r);let i=e.createElement("div");i.classList.add(j("c")),r.appendChild(i),this.colorElem_=i;let n=e.createElement("div");n.classList.add(j("m")),this.element.appendChild(n),this.markerElem_=n;let o=e.createElement("div");o.classList.add(j("p")),this.markerElem_.appendChild(o),this.previewElem_=o,this.update_()}update_(){let e=this.value.rawValue,t=e.getComponents("rgb"),r=new Color([t[0],t[1],t[2],0],"rgb"),i=new Color([t[0],t[1],t[2],255],"rgb"),n=["to right",colorToFunctionalRgbaString(r),colorToFunctionalRgbaString(i)];this.colorElem_.style.background=`linear-gradient(${n.join(",")})`,this.previewElem_.style.backgroundColor=colorToFunctionalRgbaString(e);let o=mapRange(t[3],0,1,0,100);this.markerElem_.style.left=`${o}%`}onValueChange_(){this.update_()}};let APaletteController=class APaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new APaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let r=e.point.x/e.bounds.width,i=this.value.rawValue,[n,o,a]=i.getComponents("hsv");this.value.setRawValue(new Color([n,o,a,r],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(getBaseStepForColor(!0),getHorizontalStepKeys(e));if(0===t)return;let r=this.value.rawValue,[i,n,o,a]=r.getComponents("hsv");this.value.setRawValue(new Color([i,n,o,a+t],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(getBaseStepForColor(!0),getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let K=ClassName("coltxt");function createModeSelectElement(e){let t=e.createElement("select");return t.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"}].reduce((t,r)=>{let i=e.createElement("option");return i.textContent=r.text,i.value=r.value,t.appendChild(i),t},e.createDocumentFragment())),t}let ColorTextView=class ColorTextView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(K()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(K("m")),this.modeElem_=createModeSelectElement(e),this.modeElem_.classList.add(K("ms")),r.appendChild(this.modeSelectElement),t.viewProps.bindDisabled(this.modeElem_);let i=e.createElement("div");i.classList.add(K("mm")),i.appendChild(createSvgIconElement(e,"dropdown")),r.appendChild(i),this.element.appendChild(r);let n=e.createElement("div");n.classList.add(K("w")),this.element.appendChild(n),this.textsElem_=n,this.textViews_=t.textViews,this.applyTextViews_(),bindValue(t.colorMode,e=>{this.modeElem_.value=e})}get modeSelectElement(){return this.modeElem_}get textViews(){return this.textViews_}set textViews(e){this.textViews_=e,this.applyTextViews_()}applyTextViews_(){removeChildElements(this.textsElem_);let e=this.element.ownerDocument;this.textViews_.forEach(t=>{let r=e.createElement("div");r.classList.add(K("c")),r.appendChild(t.element),this.textsElem_.appendChild(r)})}};function createFormatter$2(e){return createNumberFormatter("float"===e?2:0)}function createConstraint$5(e,t,r){let i=getColorMaxComponents(e,t)[r];return new DefiniteRangeConstraint({min:0,max:i})}function createComponentController(e,t,r){return new NumberTextController(e,{arrayPosition:0===r?"fst":2===r?"lst":"mid",baseStep:getBaseStepForColor(!1),parser:t.parser,props:ValueMap.fromObject({draggingScale:"float"===t.colorType?.01:1,formatter:createFormatter$2(t.colorType)}),value:createValue(0,{constraint:createConstraint$5(t.colorMode,t.colorType,r)}),viewProps:t.viewProps})}let ColorTextController=class ColorTextController{constructor(e,t){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=t.colorType,this.parser_=t.parser,this.value=t.value,this.viewProps=t.viewProps,this.colorMode=createValue(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(e),this.view=new ColorTextView(e,{colorMode:this.colorMode,textViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(e){let t={colorMode:this.colorMode.rawValue,colorType:this.colorType_,parser:this.parser_,viewProps:this.viewProps},r=[createComponentController(e,t,0),createComponentController(e,t,1),createComponentController(e,t,2)];return r.forEach((e,t)=>{connectValues({primary:this.value,secondary:e.value,forward:e=>e.rawValue.getComponents(this.colorMode.rawValue,this.colorType_)[t],backward:(e,r)=>{let i=this.colorMode.rawValue,n=e.rawValue.getComponents(i,this.colorType_);return n[t]=r.rawValue,new Color(appendAlphaComponent(removeAlphaComponent(n),n[3]),i,this.colorType_)}})}),r}onModeSelectChange_(e){let t=e.currentTarget;this.colorMode.rawValue=t.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.textViews=[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view]}};let H=ClassName("hpl");let HPaletteView=class HPaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(H()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let r=e.createElement("div");r.classList.add(H("c")),this.element.appendChild(r);let i=e.createElement("div");i.classList.add(H("m")),this.element.appendChild(i),this.markerElem_=i,this.update_()}update_(){let e=this.value.rawValue,[t]=e.getComponents("hsv");this.markerElem_.style.backgroundColor=colorToFunctionalRgbString(new Color([t,100,100],"hsv"));let r=mapRange(t,0,360,0,100);this.markerElem_.style.left=`${r}%`}onValueChange_(){this.update_()}};let HPaletteController=class HPaletteController{constructor(e,t){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.view=new HPaletteView(e,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let r=mapRange(constrainRange(e.point.x,0,e.bounds.width),0,e.bounds.width,0,360),i=this.value.rawValue,[,n,o,a]=i.getComponents("hsv");this.value.setRawValue(new Color([r,n,o,a],"hsv"),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onKeyDown_(e){let t=getStepForKey(getBaseStepForColor(!1),getHorizontalStepKeys(e));if(0===t)return;let r=this.value.rawValue,[i,n,o,a]=r.getComponents("hsv");this.value.setRawValue(new Color([i+t,n,o,a],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(e){let t=getStepForKey(getBaseStepForColor(!1),getHorizontalStepKeys(e));0!==t&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let U=ClassName("svp");let SvPaletteView=class SvPaletteView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.element=e.createElement("div"),this.element.classList.add(U()),t.viewProps.bindClassModifiers(this.element),t.viewProps.bindTabIndex(this.element);let r=e.createElement("canvas");r.height=64,r.width=64,r.classList.add(U("c")),this.element.appendChild(r),this.canvasElement=r;let i=e.createElement("div");i.classList.add(U("m")),this.element.appendChild(i),this.markerElem_=i,this.update_()}update_(){let e=getCanvasContext(this.canvasElement);if(!e)return;let t=this.value.rawValue,r=t.getComponents("hsv"),i=this.canvasElement.width,n=this.canvasElement.height,o=e.getImageData(0,0,i,n),a=o.data;for(let e=0;ee.rawValue.getComponents()[3],backward:(e,t)=>{let r=e.rawValue.getComponents();return r[3]=t.rawValue,new Color(r,e.rawValue.mode)}}),this.textC_=new ColorTextController(e,{colorType:t.colorType,parser:parseNumber,value:this.value,viewProps:this.viewProps}),this.view=new ColorPickerView(e,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:t.supportsAlpha,svPaletteView:this.svPaletteC_.view,textView:this.textC_.view,viewProps:this.viewProps})}get textController(){return this.textC_}};let $=ClassName("colsw");let ColorSwatchView=class ColorSwatchView{constructor(e,t){this.onValueChange_=this.onValueChange_.bind(this),t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.element=e.createElement("div"),this.element.classList.add($()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add($("sw")),this.element.appendChild(r),this.swatchElem_=r;let i=e.createElement("button");i.classList.add($("b")),t.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i,this.update_()}update_(){let e=this.value.rawValue;this.swatchElem_.style.backgroundColor=colorToHexRgbaString(e)}onValueChange_(){this.update_()}};let ColorSwatchController=class ColorSwatchController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new ColorSwatchView(e,{value:this.value,viewProps:this.viewProps})}};let ColorController=class ColorController{constructor(e,t){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=Foldable.create(t.expanded),this.swatchC_=new ColorSwatchController(e,{value:this.value,viewProps:this.viewProps});let r=this.swatchC_.view.buttonElement;r.addEventListener("blur",this.onButtonBlur_),r.addEventListener("click",this.onButtonClick_),this.textC_=new TextController(e,{parser:t.parser,props:ValueMap.fromObject({formatter:t.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new ColorView(e,{foldable:this.foldable_,pickerLayout:t.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===t.pickerLayout?new PopupController(e,{viewProps:this.viewProps}):null;let i=new ColorPickerController(e,{colorType:t.colorType,supportsAlpha:t.supportsAlpha,value:this.value,viewProps:this.viewProps});i.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=i,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(i.view.element),connectValues({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),bindFoldable(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,r=e.relatedTarget;r&&t.contains(r)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,r=findNextTarget(e);!(r&&t.contains(r))&&(!r||r!==this.swatchC_.view.buttonElement||supportsTouch(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.swatchC_.view.buttonElement.focus()}};function colorFromObject(e,t){return Color.isColorObject(e)?Color.fromObject(e,t):Color.black(t)}function colorToRgbNumber(e){return removeAlphaComponent(e.getComponents("rgb")).reduce((e,t)=>e<<8|255&Math.floor(t),0)}function colorToRgbaNumber(e){return e.getComponents("rgb").reduce((e,t,r)=>e<<8|255&Math.floor(3===r?255*t:t),0)>>>0}function numberToRgbColor(e){return new Color([e>>16&255,e>>8&255,255&e],"rgb")}function numberToRgbaColor(e){return new Color([e>>24&255,e>>16&255,e>>8&255,mapRange(255&e,0,255,0,1)],"rgb")}function colorFromRgbNumber(e){return"number"!=typeof e?Color.black():numberToRgbColor(e)}function colorFromRgbaNumber(e){return"number"!=typeof e?Color.black():numberToRgbaColor(e)}function createColorStringWriter(e){let t=findColorStringifier(e);return t?(e,r)=>{writePrimitive(e,t(r))}:null}function createColorNumberWriter(e){let t=e?colorToRgbaNumber:colorToRgbNumber;return(e,r)=>{writePrimitive(e,t(r))}}function writeRgbaColorObject(e,t,r){let i=t.toRgbaObject(r);e.writeProperty("r",i.r),e.writeProperty("g",i.g),e.writeProperty("b",i.b),e.writeProperty("a",i.a)}function writeRgbColorObject(e,t,r){let i=t.toRgbaObject(r);e.writeProperty("r",i.r),e.writeProperty("g",i.g),e.writeProperty("b",i.b)}function createColorObjectWriter(e,t){return(r,i)=>{e?writeRgbaColorObject(r,i,t):writeRgbColorObject(r,i,t)}}function shouldSupportAlpha$1(e){var t;return null!=e&&!!e.alpha||null!==(t=null==e?void 0:e.color)&&void 0!==t&&!!t.alpha}function createFormatter$1(e){return e?e=>colorToHexRgbaString(e,"0x"):e=>colorToHexRgbString(e,"0x")}function isForColor(e){return"color"in e||"view"in e&&"color"===e.view}let z={id:"input-color-number",type:"input",accept:(e,t)=>{if("number"!=typeof e||!isForColor(t))return null;let r=parseColorInputParams(t);return r?{initialValue:e,params:r}:null},binding:{reader:e=>shouldSupportAlpha$1(e.params)?colorFromRgbaNumber:colorFromRgbNumber,equals:Color.equals,writer:e=>createColorNumberWriter(shouldSupportAlpha$1(e.params))},controller:e=>{let t=shouldSupportAlpha$1(e.params),r="expanded"in e.params?e.params.expanded:void 0,i="picker"in e.params?e.params.picker:void 0;return new ColorController(e.document,{colorType:"int",expanded:null!=r&&r,formatter:createFormatter$1(t),parser:createColorStringParser("int"),pickerLayout:null!=i?i:"popup",supportsAlpha:t,value:e.value,viewProps:e.viewProps})}};function shouldSupportAlpha(e){return Color.isRgbaColorObject(e)}function createColorObjectReader(e){return t=>colorFromObject(t,e)}function createColorObjectFormatter(e,t){return r=>e?colorToObjectRgbaString(r,t):colorToObjectRgbString(r,t)}let q={id:"input-color-object",type:"input",accept:(e,t)=>{if(!Color.isColorObject(e))return null;let r=parseColorInputParams(t);return r?{initialValue:e,params:r}:null},binding:{reader:e=>createColorObjectReader(extractColorType(e.params)),equals:Color.equals,writer:e=>createColorObjectWriter(shouldSupportAlpha(e.initialValue),extractColorType(e.params))},controller:e=>{var t;let r=Color.isRgbaColorObject(e.initialValue),i="expanded"in e.params?e.params.expanded:void 0,n="picker"in e.params?e.params.picker:void 0,o=null!==(t=extractColorType(e.params))&&void 0!==t?t:"int";return new ColorController(e.document,{colorType:o,expanded:null!=i&&i,formatter:createColorObjectFormatter(r,o),parser:createColorStringParser(o),pickerLayout:null!=n?n:"popup",supportsAlpha:r,value:e.value,viewProps:e.viewProps})}},G={id:"input-color-string",type:"input",accept:(e,t)=>{if("string"!=typeof e||"view"in t&&"text"===t.view)return null;let r=detectStringColorFormat(e,extractColorType(t));if(!r)return null;let i=findColorStringifier(r);if(!i)return null;let n=parseColorInputParams(t);return n?{initialValue:e,params:n}:null},binding:{reader:e=>{var t;return createColorStringBindingReader(null!==(t=extractColorType(e.params))&&void 0!==t?t:"int")},equals:Color.equals,writer:e=>{let t=detectStringColorFormat(e.initialValue,extractColorType(e.params));if(!t)throw TpError.shouldNeverHappen();let r=createColorStringWriter(t);if(!r)throw TpError.notBindable();return r}},controller:e=>{let t=detectStringColorFormat(e.initialValue,extractColorType(e.params));if(!t)throw TpError.shouldNeverHappen();let r=findColorStringifier(t);if(!r)throw TpError.shouldNeverHappen();let i="expanded"in e.params?e.params.expanded:void 0,n="picker"in e.params?e.params.picker:void 0;return new ColorController(e.document,{colorType:t.type,expanded:null!=i&&i,formatter:r,parser:createColorStringParser(t.type),pickerLayout:null!=n?n:"popup",supportsAlpha:t.alpha,value:e.value,viewProps:e.viewProps})}};let PointNdConstraint=class PointNdConstraint{constructor(e){this.components=e.components,this.asm_=e.assembly}constrain(e){let t=this.asm_.toComponents(e).map((e,t)=>{var r,i;return null!==(i=null===(r=this.components[t])||void 0===r?void 0:r.constrain(e))&&void 0!==i?i:e});return this.asm_.fromComponents(t)}};let Y=ClassName("pndtxt");let PointNdTextView=class PointNdTextView{constructor(e,t){this.textViews=t.textViews,this.element=e.createElement("div"),this.element.classList.add(Y()),this.textViews.forEach(t=>{let r=e.createElement("div");r.classList.add(Y("a")),r.appendChild(t.element),this.element.appendChild(r)})}};function createAxisController(e,t,r){return new NumberTextController(e,{arrayPosition:0===r?"fst":r===t.axes.length-1?"lst":"mid",baseStep:t.axes[r].baseStep,parser:t.parser,props:t.axes[r].textProps,value:createValue(0,{constraint:t.axes[r].constraint}),viewProps:t.viewProps})}let PointNdTextController=class PointNdTextController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.acs_=t.axes.map((r,i)=>createAxisController(e,t,i)),this.acs_.forEach((e,r)=>{connectValues({primary:this.value,secondary:e.value,forward:e=>t.assembly.toComponents(e.rawValue)[r],backward:(e,i)=>{let n=t.assembly.toComponents(e.rawValue);return n[r]=i.rawValue,t.assembly.fromComponents(n)}})}),this.view=new PointNdTextView(e,{textViews:this.acs_.map(e=>e.view)})}};function createStepConstraint(e,t){return"step"in e&&!isEmpty(e.step)?new StepConstraint(e.step,t):null}function createRangeConstraint(e){return isEmpty(e.max)||isEmpty(e.min)?isEmpty(e.max)&&isEmpty(e.min)?null:new RangeConstraint({max:e.max,min:e.min}):new DefiniteRangeConstraint({max:e.max,min:e.min})}function findNumberRange(e){let t=findConstraint(e,DefiniteRangeConstraint);if(t)return[t.values.get("min"),t.values.get("max")];let r=findConstraint(e,RangeConstraint);return r?[r.minValue,r.maxValue]:[void 0,void 0]}function createConstraint$4(e,t){let r=[],i=createStepConstraint(e,t);i&&r.push(i);let n=createRangeConstraint(e);n&&r.push(n);let o=createListConstraint(e.options);return o&&r.push(o),new CompositeConstraint(r)}let W={id:"input-number",type:"input",accept:(e,t)=>{if("number"!=typeof e)return null;let r=parseParams(t,{format:i.optional.function,max:i.optional.number,min:i.optional.number,options:i.optional.custom(parseListOptions),step:i.optional.number});return r?{initialValue:e,params:r}:null},binding:{reader:e=>numberFromUnknown,constraint:e=>createConstraint$4(e.params,e.initialValue),writer:e=>writePrimitive},controller:e=>{var t;let r=e.value,i=e.constraint,n=i&&findConstraint(i,ListConstraint);if(n)return new ListController(e.document,{props:new ValueMap({options:n.values.value("options")}),value:r,viewProps:e.viewProps});let o=null!==(t="format"in e.params?e.params.format:void 0)&&void 0!==t?t:createNumberFormatter(getSuitableDecimalDigits(i,r.rawValue)),a=i&&findConstraint(i,DefiniteRangeConstraint);return a?new SliderTextController(e.document,{baseStep:getBaseStep(i),parser:parseNumber,sliderProps:new ValueMap({maxValue:a.values.value("max"),minValue:a.values.value("min")}),textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(i,r.rawValue),formatter:o}),value:r,viewProps:e.viewProps}):new NumberTextController(e.document,{baseStep:getBaseStep(i),parser:parseNumber,props:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(i,r.rawValue),formatter:o}),value:r,viewProps:e.viewProps})}};let Point2d=class Point2d{constructor(e=0,t=0){this.x=e,this.y=t}getComponents(){return[this.x,this.y]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,r=e.y;return"number"==typeof t&&"number"==typeof r}static equals(e,t){return e.x===t.x&&e.y===t.y}toObject(){return{x:this.x,y:this.y}}};let X={toComponents:e=>e.getComponents(),fromComponents:e=>new Point2d(...e)},J=ClassName("p2d");let Point2dView=class Point2dView{constructor(e,t){this.element=e.createElement("div"),this.element.classList.add(J()),t.viewProps.bindClassModifiers(this.element),bindValue(t.expanded,valueToClassName(this.element,J(void 0,"expanded")));let r=e.createElement("div");r.classList.add(J("h")),this.element.appendChild(r);let i=e.createElement("button");i.classList.add(J("b")),i.appendChild(createSvgIconElement(e,"p2dpad")),t.viewProps.bindDisabled(i),r.appendChild(i),this.buttonElement=i;let n=e.createElement("div");if(n.classList.add(J("t")),r.appendChild(n),this.textElement=n,"inline"===t.pickerLayout){let t=e.createElement("div");t.classList.add(J("p")),this.element.appendChild(t),this.pickerElement=t}else this.pickerElement=null}};let Q=ClassName("p2dp");let Point2dPickerView=class Point2dPickerView{constructor(e,t){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.invertsY_=t.invertsY,this.maxValue_=t.maxValue,this.element=e.createElement("div"),this.element.classList.add(Q()),"popup"===t.layout&&this.element.classList.add(Q(void 0,"p")),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("div");r.classList.add(Q("p")),t.viewProps.bindTabIndex(r),this.element.appendChild(r),this.padElement=r;let i=e.createElementNS(l,"svg");i.classList.add(Q("g")),this.padElement.appendChild(i),this.svgElem_=i;let n=e.createElementNS(l,"line");n.classList.add(Q("ax")),n.setAttributeNS(null,"x1","0"),n.setAttributeNS(null,"y1","50%"),n.setAttributeNS(null,"x2","100%"),n.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(n);let o=e.createElementNS(l,"line");o.classList.add(Q("ax")),o.setAttributeNS(null,"x1","50%"),o.setAttributeNS(null,"y1","0"),o.setAttributeNS(null,"x2","50%"),o.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(o);let a=e.createElementNS(l,"line");a.classList.add(Q("l")),a.setAttributeNS(null,"x1","50%"),a.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(a),this.lineElem_=a;let s=e.createElement("div");s.classList.add(Q("m")),this.padElement.appendChild(s),this.markerElem_=s,t.value.emitter.on("change",this.onValueChange_),this.value=t.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){let[e,t]=this.value.rawValue.getComponents(),r=this.maxValue_,i=mapRange(e,-r,+r,0,100),n=mapRange(t,-r,+r,0,100),o=this.invertsY_?100-n:n;this.lineElem_.setAttributeNS(null,"x2",`${i}%`),this.lineElem_.setAttributeNS(null,"y2",`${o}%`),this.markerElem_.style.left=`${i}%`,this.markerElem_.style.top=`${o}%`}onValueChange_(){this.update_()}onFoldableChange_(){this.update_()}};function computeOffset(e,t,r){return[getStepForKey(t[0],getHorizontalStepKeys(e)),getStepForKey(t[1],getVerticalStepKeys(e))*(r?1:-1)]}let Point2dPickerController=class Point2dPickerController{constructor(e,t){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.baseSteps_=t.baseSteps,this.maxValue_=t.maxValue,this.invertsY_=t.invertsY,this.view=new Point2dPickerView(e,{invertsY:this.invertsY_,layout:t.layout,maxValue:this.maxValue_,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new PointerHandler(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(e,t){if(!e.point)return;let r=this.maxValue_,i=mapRange(e.point.x,0,e.bounds.width,-r,+r),n=mapRange(this.invertsY_?e.bounds.height-e.point.y:e.point.y,0,e.bounds.height,-r,+r);this.value.setRawValue(new Point2d(i,n),t)}onPointerDown_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerMove_(e){this.handlePointerEvent_(e.data,{forceEmit:!1,last:!1})}onPointerUp_(e){this.handlePointerEvent_(e.data,{forceEmit:!0,last:!0})}onPadKeyDown_(e){isArrowKey(e.key)&&e.preventDefault();let[t,r]=computeOffset(e,this.baseSteps_,this.invertsY_);(0!==t||0!==r)&&this.value.setRawValue(new Point2d(this.value.rawValue.x+t,this.value.rawValue.y+r),{forceEmit:!1,last:!1})}onPadKeyUp_(e){let[t,r]=computeOffset(e,this.baseSteps_,this.invertsY_);(0!==t||0!==r)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}};let Point2dController=class Point2dController{constructor(e,t){var r,i;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=t.value,this.viewProps=t.viewProps,this.foldable_=Foldable.create(t.expanded),this.popC_="popup"===t.pickerLayout?new PopupController(e,{viewProps:this.viewProps}):null;let n=new Point2dPickerController(e,{baseSteps:[t.axes[0].baseStep,t.axes[1].baseStep],invertsY:t.invertsY,layout:t.pickerLayout,maxValue:t.maxValue,value:this.value,viewProps:this.viewProps});n.view.allFocusableElements.forEach(e=>{e.addEventListener("blur",this.onPopupChildBlur_),e.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=n,this.textC_=new PointNdTextController(e,{assembly:X,axes:t.axes,parser:t.parser,value:this.value,viewProps:this.viewProps}),this.view=new Point2dView(e,{expanded:this.foldable_.value("expanded"),pickerLayout:t.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(r=this.view.buttonElement)||void 0===r||r.addEventListener("blur",this.onPadButtonBlur_),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),connectValues({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:e=>e.rawValue,backward:(e,t)=>t.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),bindFoldable(this.foldable_,this.view.pickerElement))}onPadButtonBlur_(e){if(!this.popC_)return;let t=this.view.element,r=e.relatedTarget;r&&t.contains(r)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(e){if(!this.popC_)return;let t=this.popC_.view.element,r=findNextTarget(e);!(r&&t.contains(r))&&(!r||r!==this.view.buttonElement||supportsTouch(t.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(e){this.popC_?"Escape"===e.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===e.key&&this.view.buttonElement.focus()}};let Point3d=class Point3d{constructor(e=0,t=0,r=0){this.x=e,this.y=t,this.z=r}getComponents(){return[this.x,this.y,this.z]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,r=e.y,i=e.z;return"number"==typeof t&&"number"==typeof r&&"number"==typeof i}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z}toObject(){return{x:this.x,y:this.y,z:this.z}}};let Z={toComponents:e=>e.getComponents(),fromComponents:e=>new Point3d(...e)};function point3dFromUnknown(e){return Point3d.isObject(e)?new Point3d(e.x,e.y,e.z):new Point3d}function writePoint3d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z)}function createConstraint$3(e,t){return new PointNdConstraint({assembly:Z,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y),createDimensionConstraint("z"in e?e.z:void 0,t.z)]})}function createAxis$2(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}let ee={id:"input-point3d",type:"input",accept:(e,t)=>{if(!Point3d.isObject(e))return null;let r=parseParams(t,{x:i.optional.custom(parsePointDimensionParams),y:i.optional.custom(parsePointDimensionParams),z:i.optional.custom(parsePointDimensionParams)});return r?{initialValue:e,params:r}:null},binding:{reader:e=>point3dFromUnknown,constraint:e=>createConstraint$3(e.params,e.initialValue),equals:Point3d.equals,writer:e=>writePoint3d},controller:e=>{let t=e.value,r=e.constraint;if(!(r instanceof PointNdConstraint))throw TpError.shouldNeverHappen();return new PointNdTextController(e.document,{assembly:Z,axes:[createAxis$2(t.rawValue.x,r.components[0]),createAxis$2(t.rawValue.y,r.components[1]),createAxis$2(t.rawValue.z,r.components[2])],parser:parseNumber,value:t,viewProps:e.viewProps})}};let Point4d=class Point4d{constructor(e=0,t=0,r=0,i=0){this.x=e,this.y=t,this.z=r,this.w=i}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(e){if(isEmpty(e))return!1;let t=e.x,r=e.y,i=e.z,n=e.w;return"number"==typeof t&&"number"==typeof r&&"number"==typeof i&&"number"==typeof n}static equals(e,t){return e.x===t.x&&e.y===t.y&&e.z===t.z&&e.w===t.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}};let et={toComponents:e=>e.getComponents(),fromComponents:e=>new Point4d(...e)};function point4dFromUnknown(e){return Point4d.isObject(e)?new Point4d(e.x,e.y,e.z,e.w):new Point4d}function writePoint4d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y),e.writeProperty("z",t.z),e.writeProperty("w",t.w)}function createConstraint$2(e,t){return new PointNdConstraint({assembly:et,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y),createDimensionConstraint("z"in e?e.z:void 0,t.z),createDimensionConstraint("w"in e?e.w:void 0,t.w)]})}function createAxis$1(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}let er={id:"input-point4d",type:"input",accept:(e,t)=>{if(!Point4d.isObject(e))return null;let r=parseParams(t,{x:i.optional.custom(parsePointDimensionParams),y:i.optional.custom(parsePointDimensionParams),z:i.optional.custom(parsePointDimensionParams),w:i.optional.custom(parsePointDimensionParams)});return r?{initialValue:e,params:r}:null},binding:{reader:e=>point4dFromUnknown,constraint:e=>createConstraint$2(e.params,e.initialValue),equals:Point4d.equals,writer:e=>writePoint4d},controller:e=>{let t=e.value,r=e.constraint;if(!(r instanceof PointNdConstraint))throw TpError.shouldNeverHappen();return new PointNdTextController(e.document,{assembly:et,axes:t.rawValue.getComponents().map((e,t)=>createAxis$1(e,r.components[t])),parser:parseNumber,value:t,viewProps:e.viewProps})}};function createConstraint$1(e){let t=[],r=createListConstraint(e.options);return r&&t.push(r),new CompositeConstraint(t)}let ei={id:"input-string",type:"input",accept:(e,t)=>{if("string"!=typeof e)return null;let r=parseParams(t,{options:i.optional.custom(parseListOptions)});return r?{initialValue:e,params:r}:null},binding:{reader:e=>stringFromUnknown,constraint:e=>createConstraint$1(e.params),writer:e=>writePrimitive},controller:e=>{let t=e.document,r=e.value,i=e.constraint,n=i&&findConstraint(i,ListConstraint);return n?new ListController(t,{props:new ValueMap({options:n.values.value("options")}),value:r,viewProps:e.viewProps}):new TextController(t,{parser:e=>e,props:ValueMap.fromObject({formatter:formatString}),value:r,viewProps:e.viewProps})}},en={monitor:{defaultInterval:200,defaultLineCount:3}},eo=ClassName("mll");let MultiLogView=class MultiLogView{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(eo()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("textarea");r.classList.add(eo("i")),r.style.height=`calc(var(--bld-us) * ${t.lineCount})`,r.readOnly=!0,t.viewProps.bindDisabled(r),this.element.appendChild(r),this.textareaElem_=r,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.textareaElem_,t=e.scrollTop===e.scrollHeight-e.clientHeight,r=[];this.value.rawValue.forEach(e=>{void 0!==e&&r.push(this.formatter_(e))}),e.textContent=r.join("\n"),t&&(e.scrollTop=e.scrollHeight)}onValueUpdate_(){this.update_()}};let MultiLogController=class MultiLogController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new MultiLogView(e,{formatter:t.formatter,lineCount:t.lineCount,value:this.value,viewProps:this.viewProps})}};let ea=ClassName("sgl");let SingleLogView=class SingleLogView{constructor(e,t){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=t.formatter,this.element=e.createElement("div"),this.element.classList.add(ea()),t.viewProps.bindClassModifiers(this.element);let r=e.createElement("input");r.classList.add(ea("i")),r.readOnly=!0,r.type="text",t.viewProps.bindDisabled(r),this.element.appendChild(r),this.inputElement=r,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}update_(){let e=this.value.rawValue,t=e[e.length-1];this.inputElement.value=void 0!==t?this.formatter_(t):""}onValueUpdate_(){this.update_()}};let SingleLogController=class SingleLogController{constructor(e,t){this.value=t.value,this.viewProps=t.viewProps,this.view=new SingleLogView(e,{formatter:t.formatter,value:this.value,viewProps:this.viewProps})}};let el={id:"monitor-bool",type:"monitor",accept:(e,t)=>{if("boolean"!=typeof e)return null;let r=parseParams(t,{lineCount:i.optional.number});return r?{initialValue:e,params:r}:null},binding:{reader:e=>boolFromUnknown},controller:e=>{var t;return 1===e.value.rawValue.length?new SingleLogController(e.document,{formatter:BooleanFormatter,value:e.value,viewProps:e.viewProps}):new MultiLogController(e.document,{formatter:BooleanFormatter,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:en.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}},es=ClassName("grl");let GraphLogView=class GraphLogView{constructor(e,t){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=e.createElement("div"),this.element.classList.add(es()),t.viewProps.bindClassModifiers(this.element),this.formatter_=t.formatter,this.props_=t.props,this.cursor_=t.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);let r=e.createElementNS(l,"svg");r.classList.add(es("g")),r.style.height=`calc(var(--bld-us) * ${t.lineCount})`,this.element.appendChild(r),this.svgElem_=r;let i=e.createElementNS(l,"polyline");this.svgElem_.appendChild(i),this.lineElem_=i;let n=e.createElement("div");n.classList.add(es("t"),ClassName("tt")()),this.element.appendChild(n),this.tooltipElem_=n,t.value.emitter.on("change",this.onValueUpdate_),this.value=t.value,this.update_()}get graphElement(){return this.svgElem_}update_(){let e=this.svgElem_.getBoundingClientRect(),t=this.value.rawValue.length-1,r=this.props_.get("minValue"),i=this.props_.get("maxValue"),n=[];this.value.rawValue.forEach((o,a)=>{if(void 0===o)return;let l=mapRange(a,0,t,0,e.width),s=mapRange(o,r,i,e.height,0);n.push([l,s].join(","))}),this.lineElem_.setAttributeNS(null,"points",n.join(" "));let o=this.tooltipElem_,a=this.value.rawValue[this.cursor_.rawValue];if(void 0===a){o.classList.remove(es("t","a"));return}let l=mapRange(this.cursor_.rawValue,0,t,0,e.width),s=mapRange(a,r,i,e.height,0);o.style.left=`${l}px`,o.style.top=`${s}px`,o.textContent=`${this.formatter_(a)}`,o.classList.contains(es("t","a"))||(o.classList.add(es("t","a"),es("t","in")),forceReflow(o),o.classList.remove(es("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}};let GraphLogController=class GraphLogController{constructor(e,t){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props_=t.props,this.value=t.value,this.viewProps=t.viewProps,this.cursor_=createValue(-1),this.view=new GraphLogView(e,{cursor:this.cursor_,formatter:t.formatter,lineCount:t.lineCount,props:this.props_,value:this.value,viewProps:this.viewProps}),supportsTouch(e)){let e=new PointerHandler(this.view.element);e.emitter.on("down",this.onGraphPointerDown_),e.emitter.on("move",this.onGraphPointerMove_),e.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(e){let t=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(mapRange(e.offsetX,0,t.width,0,this.value.rawValue.length))}onGraphPointerDown_(e){this.onGraphPointerMove_(e)}onGraphPointerMove_(e){if(!e.data.point){this.cursor_.rawValue=-1;return}this.cursor_.rawValue=Math.floor(mapRange(e.data.point.x,0,e.data.bounds.width,0,this.value.rawValue.length))}onGraphPointerUp_(){this.cursor_.rawValue=-1}};function createFormatter(e){return"format"in e&&!isEmpty(e.format)?e.format:createNumberFormatter(2)}function createTextMonitor(e){var t;return 1===e.value.rawValue.length?new SingleLogController(e.document,{formatter:createFormatter(e.params),value:e.value,viewProps:e.viewProps}):new MultiLogController(e.document,{formatter:createFormatter(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:en.monitor.defaultLineCount,value:e.value,viewProps:e.viewProps})}function createGraphMonitor(e){var t,r,i;return new GraphLogController(e.document,{formatter:createFormatter(e.params),lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:en.monitor.defaultLineCount,props:ValueMap.fromObject({maxValue:null!==(r="max"in e.params?e.params.max:null)&&void 0!==r?r:100,minValue:null!==(i="min"in e.params?e.params.min:null)&&void 0!==i?i:0}),value:e.value,viewProps:e.viewProps})}function shouldShowGraph(e){return"view"in e&&"graph"===e.view}let ep={id:"monitor-number",type:"monitor",accept:(e,t)=>{if("number"!=typeof e)return null;let r=parseParams(t,{format:i.optional.function,lineCount:i.optional.number,max:i.optional.number,min:i.optional.number,view:i.optional.string});return r?{initialValue:e,params:r}:null},binding:{defaultBufferSize:e=>shouldShowGraph(e)?64:1,reader:e=>numberFromUnknown},controller:e=>shouldShowGraph(e.params)?createGraphMonitor(e):createTextMonitor(e)},ed={id:"monitor-string",type:"monitor",accept:(e,t)=>{if("string"!=typeof e)return null;let r=parseParams(t,{lineCount:i.optional.number,multiline:i.optional.boolean});return r?{initialValue:e,params:r}:null},binding:{reader:e=>stringFromUnknown},controller:e=>{var t;let r=e.value,i=r.rawValue.length>1||"multiline"in e.params&&e.params.multiline;return i?new MultiLogController(e.document,{formatter:formatString,lineCount:null!==(t=e.params.lineCount)&&void 0!==t?t:en.monitor.defaultLineCount,value:r,viewProps:e.viewProps}):new SingleLogController(e.document,{formatter:formatString,value:r,viewProps:e.viewProps})}};function createInputBindingController(e,t){var r;let n=e.accept(t.target.read(),t.params);if(isEmpty(n))return null;let o={target:t.target,initialValue:n.initialValue,params:n.params},a=e.binding.reader(o),l=e.binding.constraint?e.binding.constraint(o):void 0,s=createValue(a(n.initialValue),{constraint:l,equals:e.binding.equals}),p=new InputBinding({reader:a,target:t.target,value:s,writer:e.binding.writer(o)}),d=i.optional.boolean(t.params.disabled).value,u=i.optional.boolean(t.params.hidden).value,c=e.controller({constraint:l,document:t.document,initialValue:n.initialValue,params:n.params,value:p.value,viewProps:ViewProps.create({disabled:d,hidden:u})});return new InputBindingController(t.document,{binding:p,blade:createBlade(),props:ValueMap.fromObject({label:"label"in t.params?null!==(r=i.optional.string(t.params.label).value)&&void 0!==r?r:null:t.target.key}),valueController:c})}function createTicker(e,t){return 0===t?new ManualTicker:new IntervalTicker(e,null!=t?t:en.monitor.defaultInterval)}function createMonitorBindingController(e,t){var r,n,o;let a=e.accept(t.target.read(),t.params);if(isEmpty(a))return null;let l={target:t.target,initialValue:a.initialValue,params:a.params},s=e.binding.reader(l),p=null!==(n=null!==(r=i.optional.number(t.params.bufferSize).value)&&void 0!==r?r:e.binding.defaultBufferSize&&e.binding.defaultBufferSize(a.params))&&void 0!==n?n:1,d=i.optional.number(t.params.interval).value,u=new MonitorBinding({reader:s,target:t.target,ticker:createTicker(t.document,d),value:initializeBuffer(p)}),c=i.optional.boolean(t.params.disabled).value,h=i.optional.boolean(t.params.hidden).value,v=e.controller({document:t.document,params:a.params,value:u.value,viewProps:ViewProps.create({disabled:c,hidden:h})});return new MonitorBindingController(t.document,{binding:u,blade:createBlade(),props:ValueMap.fromObject({label:"label"in t.params?null!==(o=i.optional.string(t.params.label).value)&&void 0!==o?o:null:t.target.key}),valueController:v})}let PluginPool=class PluginPool{constructor(){this.pluginsMap_={blades:[],inputs:[],monitors:[]}}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(e){"blade"===e.type?this.pluginsMap_.blades.unshift(e):"input"===e.type?this.pluginsMap_.inputs.unshift(e):"monitor"===e.type&&this.pluginsMap_.monitors.unshift(e)}createInput(e,t,r){let i=t.read();if(isEmpty(i))throw new TpError({context:{key:t.key},type:"nomatchingcontroller"});let n=this.pluginsMap_.inputs.reduce((i,n)=>null!=i?i:createInputBindingController(n,{document:e,target:t,params:r}),null);if(n)return n;throw new TpError({context:{key:t.key},type:"nomatchingcontroller"})}createMonitor(e,t,r){let i=this.pluginsMap_.monitors.reduce((i,n)=>null!=i?i:createMonitorBindingController(n,{document:e,params:r,target:t}),null);if(i)return i;throw new TpError({context:{key:t.key},type:"nomatchingcontroller"})}createBlade(e,t){let r=this.pluginsMap_.blades.reduce((r,i)=>null!=r?r:createBladeController(i,{document:e,params:t}),null);if(!r)throw new TpError({type:"nomatchingview",context:{params:t}});return r}createBladeApi(e){if(e instanceof InputBindingController)return new InputBindingApi(e);if(e instanceof MonitorBindingController)return new MonitorBindingApi(e);if(e instanceof RackController)return new RackApi(e,this);let t=this.pluginsMap_.blades.reduce((t,r)=>null!=t?t:r.api({controller:e,pool:this}),null);if(!t)throw TpError.shouldNeverHappen();return t}};function createDefaultPluginPool(){let e=new PluginPool;return[eu,ee,er,ei,W,G,q,z,L,el,ed,ep,d,c,v,g].forEach(t=>{e.register(t)}),e}function point2dFromUnknown(e){return Point2d.isObject(e)?new Point2d(e.x,e.y):new Point2d}function writePoint2d(e,t){e.writeProperty("x",t.x),e.writeProperty("y",t.y)}function createDimensionConstraint(e,t){if(!e)return;let r=[],i=createStepConstraint(e,t);i&&r.push(i);let n=createRangeConstraint(e);return n&&r.push(n),new CompositeConstraint(r)}function createConstraint(e,t){return new PointNdConstraint({assembly:X,components:[createDimensionConstraint("x"in e?e.x:void 0,t.x),createDimensionConstraint("y"in e?e.y:void 0,t.y)]})}function getSuitableMaxDimensionValue(e,t){let[r,i]=e?findNumberRange(e):[];if(!isEmpty(r)||!isEmpty(i))return Math.max(Math.abs(null!=r?r:0),Math.abs(null!=i?i:0));let n=getBaseStep(e);return Math.max(10*Math.abs(n),10*Math.abs(t))}function getSuitableMaxValue(e,t){let r=t instanceof PointNdConstraint?t.components[0]:void 0,i=t instanceof PointNdConstraint?t.components[1]:void 0,n=getSuitableMaxDimensionValue(r,e.x),o=getSuitableMaxDimensionValue(i,e.y);return Math.max(n,o)}function createAxis(e,t){return{baseStep:getBaseStep(t),constraint:t,textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(t,e),formatter:createNumberFormatter(getSuitableDecimalDigits(t,e))})}}function shouldInvertY(e){if(!("y"in e))return!1;let t=e.y;return!!t&&"inverted"in t&&!!t.inverted}let eu={id:"input-point2d",type:"input",accept:(e,t)=>{if(!Point2d.isObject(e))return null;let r=parseParams(t,{expanded:i.optional.boolean,picker:i.optional.custom(parsePickerLayout),x:i.optional.custom(parsePointDimensionParams),y:i.optional.object({inverted:i.optional.boolean,max:i.optional.number,min:i.optional.number,step:i.optional.number})});return r?{initialValue:e,params:r}:null},binding:{reader:e=>point2dFromUnknown,constraint:e=>createConstraint(e.params,e.initialValue),equals:Point2d.equals,writer:e=>writePoint2d},controller:e=>{let t=e.document,r=e.value,i=e.constraint;if(!(i instanceof PointNdConstraint))throw TpError.shouldNeverHappen();let n="expanded"in e.params?e.params.expanded:void 0,o="picker"in e.params?e.params.picker:void 0;return new Point2dController(t,{axes:[createAxis(r.rawValue.x,i.components[0]),createAxis(r.rawValue.y,i.components[1])],expanded:null!=n&&n,invertsY:shouldInvertY(e.params),maxValue:getSuitableMaxValue(r.rawValue,i),parser:parseNumber,pickerLayout:null!=o?o:"popup",value:r,viewProps:e.viewProps})}};let ListApi=class ListApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get options(){return this.controller_.valueController.props.get("options")}set options(e){this.controller_.valueController.props.set("options",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}};let SliderApi=class SliderApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get maxValue(){return this.controller_.valueController.sliderController.props.get("maxValue")}set maxValue(e){this.controller_.valueController.sliderController.props.set("maxValue",e)}get minValue(){return this.controller_.valueController.sliderController.props.get("minValue")}set minValue(e){this.controller_.valueController.sliderController.props.set("minValue",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}};let TextApi=class TextApi extends BladeApi{constructor(e){super(e),this.emitter_=new Emitter,this.controller_.valueController.value.emitter.on("change",e=>{this.emitter_.emit("change",{event:new TpChangeEvent(this,e.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(e){this.controller_.props.set("label",e)}get formatter(){return this.controller_.valueController.props.get("formatter")}set formatter(e){this.controller_.valueController.props.set("formatter",e)}get value(){return this.controller_.valueController.value.rawValue}set value(e){this.controller_.valueController.value.rawValue=e}on(e,t){let r=t.bind(this);return this.emitter_.on(e,e=>{r(e.event)}),this}};let ec={id:"list",type:"blade",accept(e){let t=parseParams(e,{options:i.required.custom(parseListOptions),value:i.required.raw,view:i.required.constant("list"),label:i.optional.string});return t?{params:t}:null},controller(e){let t=new ListConstraint(normalizeListOptions(e.params.options)),r=createValue(e.params.value,{constraint:t}),i=new ListController(e.document,{props:new ValueMap({options:t.values.value("options")}),value:r,viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:i})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof ListController?new ListApi(e.controller):null};function exportPresetJson(e){return e.reduce((e,t)=>Object.assign(e,{[t.presetKey]:t.read()}),{})}function importPresetJson(e,t){e.forEach(e=>{let r=t[e.target.presetKey];void 0!==r&&e.writer(e.target,e.reader(r))})}let RootApi=class RootApi extends FolderApi{constructor(e,t){super(e,t)}get element(){return this.controller_.view.element}importPreset(e){let t=this.controller_.rackController.rack.find(InputBindingController).map(e=>e.binding);importPresetJson(t,e),this.refresh()}exportPreset(){let e=this.controller_.rackController.rack.find(InputBindingController).map(e=>e.binding.target);return exportPresetJson(e)}refresh(){this.controller_.rackController.rack.find(InputBindingController).forEach(e=>{e.binding.read()}),this.controller_.rackController.rack.find(MonitorBindingController).forEach(e=>{e.binding.read()})}};let RootController=class RootController extends FolderController{constructor(e,t){super(e,{expanded:t.expanded,blade:t.blade,props:t.props,root:!0,viewProps:t.viewProps})}};let eh={id:"slider",type:"blade",accept(e){let t=parseParams(e,{max:i.required.number,min:i.required.number,view:i.required.constant("slider"),format:i.optional.function,label:i.optional.string,value:i.optional.number});return t?{params:t}:null},controller(e){var t,r;let i=null!==(t=e.params.value)&&void 0!==t?t:0,n=new DefiniteRangeConstraint({max:e.params.max,min:e.params.min}),o=new SliderTextController(e.document,{baseStep:1,parser:parseNumber,sliderProps:new ValueMap({maxValue:n.values.value("max"),minValue:n.values.value("min")}),textProps:ValueMap.fromObject({draggingScale:getSuitableDraggingScale(void 0,i),formatter:null!==(r=e.params.format)&&void 0!==r?r:numberToString}),value:createValue(i,{constraint:n}),viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:o})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof SliderTextController?new SliderApi(e.controller):null},ev={id:"text",type:"blade",accept(e){let t=parseParams(e,{parse:i.required.function,value:i.required.raw,view:i.required.constant("text"),format:i.optional.function,label:i.optional.string});return t?{params:t}:null},controller(e){var t;let r=new TextController(e.document,{parser:e.params.parse,props:ValueMap.fromObject({formatter:null!==(t=e.params.format)&&void 0!==t?t:e=>String(e)}),value:createValue(e.params.value),viewProps:e.viewProps});return new LabeledValueController(e.document,{blade:e.blade,props:ValueMap.fromObject({label:e.params.label}),valueController:r})},api:e=>e.controller instanceof LabeledValueController&&e.controller.valueController instanceof TextController?new TextApi(e.controller):null};function createDefaultWrapperElement(e){let t=e.createElement("div");return t.classList.add(ClassName("dfw")()),e.body&&e.body.appendChild(t),t}function embedStyle(e,t,r){if(e.querySelector(`style[data-tp-style=${t}]`))return;let i=e.createElement("style");i.dataset.tpStyle=t,i.textContent=r,e.head.appendChild(i)}let Pane=class Pane extends RootApi{constructor(e){var t,r;let i=null!=e?e:{},n=null!==(t=i.document)&&void 0!==t?t:getWindowDocument(),o=createDefaultPluginPool(),a=new RootController(n,{expanded:i.expanded,blade:createBlade(),props:ValueMap.fromObject({title:i.title}),viewProps:ViewProps.create()});super(a,o),this.pool_=o,this.containerElem_=null!==(r=i.container)&&void 0!==r?r:createDefaultWrapperElement(n),this.containerElem_.appendChild(this.element),this.doc_=n,this.usesDefaultWrapper_=!i.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw TpError.alreadyDisposed();return this.doc_}dispose(){let e=this.containerElem_;if(!e)throw TpError.alreadyDisposed();if(this.usesDefaultWrapper_){let t=e.parentElement;t&&t.removeChild(e)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(e){let t="plugin"in e?[e.plugin]:"plugins"in e?e.plugins:[];t.forEach(e=>{this.pool_.register(e),this.embedPluginStyle_(e)})}embedPluginStyle_(e){e.css&&embedStyle(this.document,`plugin-${e.id}`,e.css)}setUpDefaultPlugins_(){embedStyle(this.document,"default",'.tp-tbiv_b,.tp-coltxtv_ms,.tp-ckbv_i,.tp-rotv_b,.tp-fldv_b,.tp-mllv_i,.tp-sglv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--elm-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--bld-us);line-height:var(--bld-us);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--bld-us);line-height:var(--bld-us);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-mllv_i,.tp-sglv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--mo-fg);height:var(--bld-us);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-mllv_i::-webkit-scrollbar,.tp-sglv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-mllv_i::-webkit-scrollbar-corner,.tp-sglv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-mllv_i::-webkit-scrollbar-thumb,.tp-sglv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-rotv{--font-family: var(--tp-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-br: var(--tp-base-border-radius, 6px);--cnt-h-p: var(--tp-container-horizontal-padding, 4px);--cnt-v-p: var(--tp-container-vertical-padding, 4px);--elm-br: var(--tp-element-border-radius, 2px);--bld-s: var(--tp-blade-spacing, 4px);--bld-us: var(--tp-blade-unit-size, 20px);--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tabv_c .tp-brkv>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-v-p))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tabv_c .tp-brkv>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--bld-s)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tabv_c .tp-brkv>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tabv_c .tp-brkv>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--elm-br);border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tabv_c .tp-brkv .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--elm-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);overflow:hidden;padding-left:var(--cnt-h-p);padding-right:calc(4px + var(--bld-us) + var(--cnt-h-p));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-h-p) + (var(--bld-us) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-v-p);padding-top:var(--cnt-v-p);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--elm-br);cursor:pointer;display:block;height:var(--bld-us);position:relative;width:var(--bld-us)}.tp-ckbv_w svg{bottom:0;display:block;height:16px;left:0;margin:auto;opacity:0;position:absolute;right:0;top:0;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--bld-us)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--bld-s);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--bld-s)}.tp-colpv_rgb{display:flex;margin-top:var(--bld-s);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-v-p);padding-top:calc(var(--cnt-v-p) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-h-p));position:absolute;right:calc(-1*var(--cnt-h-p));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--elm-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--bld-us)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--elm-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;pointer-events:none;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--elm-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;cursor:pointer;display:block;height:var(--bld-us);left:0;margin:0;outline:none;padding:0;position:absolute;top:0;width:var(--bld-us)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--elm-br);bottom:0;content:"";display:block;left:0;position:absolute;right:0;top:0}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--elm-br);color:var(--lbl-fg);cursor:pointer;height:var(--bld-us);line-height:var(--bld-us);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv.tp-fldv-not .tp-fldv_b{display:none}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--bld-us)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-h-p);padding-right:var(--cnt-h-p)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:160px}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding:0 4px}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--bld-us)*3);line-height:var(--bld-us);padding:0 4px;resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--bld-us);margin-right:4px;position:relative;width:var(--bld-us)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--bld-s);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-p2dpv{padding-left:calc(var(--bld-us) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:6px;box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:168px;padding:var(--cnt-v-p) var(--cnt-h-p);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--bld-us);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin:auto;position:absolute;right:0;top:0}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin-bottom:auto;margin-top:auto;position:absolute;right:0;top:0}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--elm-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--bld-us) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_c{padding-bottom:var(--cnt-v-p);padding-left:4px;padding-top:var(--cnt-v-p)}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-h-p) + 4px);padding-right:calc(var(--cnt-h-p) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);bottom:2px;content:"";left:0;pointer-events:none;position:absolute;right:0;top:0}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);opacity:.5;overflow:hidden;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-txtv{position:relative}.tp-txtv_i{padding:0 4px}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:-3px;position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--bld-us) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--elm-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--font-family);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--bld-us) + var(--cnt-h-p));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0}.tp-rotv.tp-rotv-not .tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}'),this.pool_.getAll().forEach(e=>{this.embedPluginStyle_(e)}),this.registerPlugin({plugins:[eh,ec,g,ev]})}};let em=new Semver("3.1.10");e.BladeApi=BladeApi,e.ButtonApi=ButtonApi,e.FolderApi=FolderApi,e.InputBindingApi=InputBindingApi,e.ListApi=ListApi,e.MonitorBindingApi=MonitorBindingApi,e.Pane=Pane,e.SeparatorApi=SeparatorApi,e.SliderApi=SliderApi,e.TabApi=TabApi,e.TabPageApi=TabPageApi,e.TextApi=TextApi,e.TpChangeEvent=TpChangeEvent,e.VERSION=em,Object.defineProperty(e,"__esModule",{value:!0})}(t)}}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[116],{7089:function(t,e){/*! Tweakpane 3.1.10 (c) 2016 cocopon, licensed under the MIT license. */!function(t){"use strict";class e{constructor(t){let[e,i]=t.split("-"),n=e.split(".");this.major=parseInt(n[0],10),this.minor=parseInt(n[1],10),this.patch=parseInt(n[2],10),this.prerelease=null!=i?i:null}toString(){let t=[this.major,this.minor,this.patch].join(".");return null!==this.prerelease?[t,this.prerelease].join("-"):t}}class i{constructor(t){this.controller_=t}get element(){return this.controller_.view.element}get disabled(){return this.controller_.viewProps.get("disabled")}set disabled(t){this.controller_.viewProps.set("disabled",t)}get hidden(){return this.controller_.viewProps.get("hidden")}set hidden(t){this.controller_.viewProps.set("hidden",t)}dispose(){this.controller_.viewProps.set("disposed",!0)}}class n{constructor(t){this.target=t}}class r extends n{constructor(t,e,i,n){super(t),this.value=e,this.presetKey=i,this.last=null==n||n}}class s extends n{constructor(t,e,i){super(t),this.value=e,this.presetKey=i}}class o extends n{constructor(t,e){super(t),this.expanded=e}}class a extends n{constructor(t,e){super(t),this.index=e}}function l(t){return null==t}function p(t,e){if(t.length!==e.length)return!1;for(let i=0;i"View has been already disposed",invalidparams:t=>`Invalid parameters for '${t.name}'`,nomatchingcontroller:t=>`No matching controller for '${t.key}'`,nomatchingview:t=>`No matching view for '${JSON.stringify(t.params)}'`,notbindable:()=>"Value is not bindable",propertynotfound:t=>`Property '${t.name}' not found`,shouldneverhappen:()=>"This error should never happen"};class u{static alreadyDisposed(){return new u({type:"alreadydisposed"})}static notBindable(){return new u({type:"notbindable"})}static propertyNotFound(t){return new u({type:"propertynotfound",context:{name:t}})}static shouldNeverHappen(){return new u({type:"shouldneverhappen"})}constructor(t){var e;this.message=null!==(e=h[t.type](t.context))&&void 0!==e?e:"Unexpected error",this.name=this.constructor.name,this.stack=Error(this.message).stack,this.type=t.type}}class c{constructor(t,e,i){this.obj_=t,this.key_=e,this.presetKey_=null!=i?i:e}static isBindable(t){return null!==t&&("object"==typeof t||"function"==typeof t)}get key(){return this.key_}get presetKey(){return this.presetKey_}read(){return this.obj_[this.key_]}write(t){this.obj_[this.key_]=t}writeProperty(t,e){let i=this.read();if(!c.isBindable(i))throw u.notBindable();if(!(t in i))throw u.propertyNotFound(t);i[t]=e}}class v extends i{get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}get title(){var t;return null!==(t=this.controller_.valueController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller_.valueController.props.set("title",t)}on(t,e){let i=e.bind(this);return this.controller_.valueController.emitter.on(t,()=>{i(new n(this))}),this}}class m{constructor(){this.observers_={}}on(t,e){let i=this.observers_[t];return i||(i=this.observers_[t]=[]),i.push({handler:e}),this}off(t,e){let i=this.observers_[t];return i&&(this.observers_[t]=i.filter(t=>t.handler!==e)),this}emit(t,e){let i=this.observers_[t];i&&i.forEach(t=>{t.handler(e)})}}function b(t){return(e,i)=>["tp","-",t,"v",e?`_${e}`:"",i?`-${i}`:""].join("")}function _(t,e){t.emitter.on("change",t=>e(t.rawValue)),e(t.rawValue)}function g(t,e,i){_(t.value(e),i)}function f(t,e){return i=>{i?t.classList.add(e):t.classList.remove(e)}}function w(t,e){_(t,t=>{e.textContent=null!=t?t:""})}let x=b("btn");class C{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(x()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("button");i.classList.add(x("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let n=t.createElement("div");n.classList.add(x("t")),w(e.props.value("title"),n),this.buttonElement.appendChild(n)}}class y{constructor(t,e){this.emitter=new m,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new C(t,{props:this.props,viewProps:this.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}}class P{constructor(t,e){var i;this.constraint_=null==e?void 0:e.constraint,this.equals_=null!==(i=null==e?void 0:e.equals)&&void 0!==i?i:(t,e)=>t===e,this.emitter=new m,this.rawValue_=t}get constraint(){return this.constraint_}get rawValue(){return this.rawValue_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){let i=null!=e?e:{forceEmit:!1,last:!0},n=this.constraint_?this.constraint_.constrain(t):t,r=this.rawValue_;(!this.equals_(r,n)||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.rawValue_=n,this.emitter.emit("change",{options:i,previousRawValue:r,rawValue:n,sender:this}))}}class k{constructor(t){this.emitter=new m,this.value_=t}get rawValue(){return this.value_}set rawValue(t){this.setRawValue(t,{forceEmit:!1,last:!0})}setRawValue(t,e){let i=null!=e?e:{forceEmit:!1,last:!0},n=this.value_;(n!==t||i.forceEmit)&&(this.emitter.emit("beforechange",{sender:this}),this.value_=t,this.emitter.emit("change",{options:i,previousRawValue:n,rawValue:this.value_,sender:this}))}}function E(t,e){let i=null==e?void 0:e.constraint,n=null==e?void 0:e.equals;return i||n?new P(t,e):new k(t)}class V{constructor(t){for(let e in this.emitter=new m,this.valMap_=t,this.valMap_)this.valMap_[e].emitter.on("change",()=>{this.emitter.emit("change",{key:e,sender:this})})}static createCore(t){return Object.keys(t).reduce((e,i)=>Object.assign(e,{[i]:E(t[i])}),{})}static fromObject(t){return new V(this.createCore(t))}get(t){return this.valMap_[t].rawValue}set(t,e){this.valMap_[t].rawValue=e}value(t){return this.valMap_[t]}}function L(t){return e=>i=>{if(!e&&void 0===i)return{succeeded:!1,value:void 0};if(e&&void 0===i)return{succeeded:!0,value:void 0};let n=t(i);return void 0!==n?{succeeded:!0,value:n}:{succeeded:!1,value:void 0}}}function M(t){return{custom:e=>L(e)(t),boolean:L(t=>"boolean"==typeof t?t:void 0)(t),number:L(t=>"number"==typeof t?t:void 0)(t),string:L(t=>"string"==typeof t?t:void 0)(t),function:L(t=>"function"==typeof t?t:void 0)(t),constant:e=>L(t=>t===e?e:void 0)(t),raw:L(t=>t)(t),object:e=>L(t=>{if(null!==t&&"object"==typeof t)return Object.keys(e).reduce((i,n)=>{if(void 0===i)return;let r=(0,e[n])(t[n]);return r.succeeded?Object.assign(Object.assign({},i),{[n]:r.value}):void 0},{})})(t),array:e=>L(t=>{if(Array.isArray(t))return t.reduce((t,i)=>{if(void 0===t)return;let n=e(i);if(n.succeeded&&void 0!==n.value)return[...t,n.value]},[])})(t)}}let S={optional:M(!0),required:M(!1)};function A(t,e){let i=S.required.object(e)(t);return i.succeeded?i.value:void 0}function D(t){console.warn(`Missing '${t.key}' of ${t.target} in ${t.place}. Please rebuild plugins with the latest core package.`)}class j{constructor(t){this.value_=t}static create(t){return[new j(t),(e,i)=>{t.setRawValue(e,i)}]}get emitter(){return this.value_.emitter}get rawValue(){return this.value_.rawValue}}let R=b("");function O(t,e){return f(t,R(void 0,e))}class I extends V{constructor(t){var e;super(t),this.onDisabledChange_=this.onDisabledChange_.bind(this),this.onParentChange_=this.onParentChange_.bind(this),this.onParentGlobalDisabledChange_=this.onParentGlobalDisabledChange_.bind(this),[this.globalDisabled_,this.setGlobalDisabled_]=j.create(E(this.getGlobalDisabled_())),this.value("disabled").emitter.on("change",this.onDisabledChange_),this.value("parent").emitter.on("change",this.onParentChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_)}static create(t){var e,i,n;let r=null!=t?t:{};return new I(V.createCore({disabled:null!==(e=r.disabled)&&void 0!==e&&e,disposed:!1,hidden:null!==(i=r.hidden)&&void 0!==i&&i,parent:null!==(n=r.parent)&&void 0!==n?n:null}))}get globalDisabled(){return this.globalDisabled_}bindClassModifiers(t){_(this.globalDisabled_,O(t,"disabled")),g(this,"hidden",O(t,"hidden"))}bindDisabled(t){_(this.globalDisabled_,e=>{t.disabled=e})}bindTabIndex(t){_(this.globalDisabled_,e=>{t.tabIndex=e?-1:0})}handleDispose(t){this.value("disposed").emitter.on("change",e=>{e&&t()})}getGlobalDisabled_(){let t=this.get("parent");return!!t&&t.globalDisabled.rawValue||this.get("disabled")}updateGlobalDisabled_(){this.setGlobalDisabled_(this.getGlobalDisabled_())}onDisabledChange_(){this.updateGlobalDisabled_()}onParentGlobalDisabledChange_(){this.updateGlobalDisabled_()}onParentChange_(t){var e;let i=t.previousRawValue;null==i||i.globalDisabled.emitter.off("change",this.onParentGlobalDisabledChange_),null===(e=this.get("parent"))||void 0===e||e.globalDisabled.emitter.on("change",this.onParentGlobalDisabledChange_),this.updateGlobalDisabled_()}}let N=b(""),K={veryfirst:"vfst",first:"fst",last:"lst",verylast:"vlst"};class U{constructor(t){this.parent_=null,this.blade=t.blade,this.view=t.view,this.viewProps=t.viewProps;let e=this.view.element;this.blade.value("positions").emitter.on("change",()=>{["veryfirst","first","last","verylast"].forEach(t=>{e.classList.remove(N(void 0,K[t]))}),this.blade.get("positions").forEach(t=>{e.classList.add(N(void 0,K[t]))})}),this.viewProps.handleDispose(()=>{e&&e.parentElement&&e.parentElement.removeChild(e)})}get parent(){return this.parent_}set parent(t){if(this.parent_=t,!("parent"in this.viewProps.valMap_)){D({key:"parent",target:I.name,place:"BladeController.parent"});return}this.viewProps.set("parent",this.parent_?this.parent_.viewProps:null)}}let B="http://www.w3.org/2000/svg";function T(t){t.offsetHeight}function F(t){return void 0!==t.ontouchstart}let $={check:'',dropdown:'',p2dpad:''};function H(t,e){let i=t.createElementNS(B,"svg");return i.innerHTML=$[e],i}function z(t,e,i){t.insertBefore(e,t.children[i])}function q(t){t.parentElement&&t.parentElement.removeChild(t)}function G(t){for(;t.children.length>0;)t.removeChild(t.children[0])}function Y(t){return t.relatedTarget?t.relatedTarget:"explicitOriginalTarget"in t?t.explicitOriginalTarget:null}let X=b("lbl");class Q{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(X()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(X("l")),g(e.props,"label",e=>{l(e)?this.element.classList.add(X(void 0,"nol")):(this.element.classList.remove(X(void 0,"nol")),function(t){for(;t.childNodes.length>0;)t.removeChild(t.childNodes[0])}(i),i.appendChild(function(t,e){let i=t.createDocumentFragment();return e.split("\n").map(e=>t.createTextNode(e)).forEach((e,n)=>{n>0&&i.appendChild(t.createElement("br")),i.appendChild(e)}),i}(t,e)))}),this.element.appendChild(i),this.labelElement=i;let n=t.createElement("div");n.classList.add(X("v")),this.element.appendChild(n),this.valueElement=n}}class J extends U{constructor(t,e){let i=e.valueController.viewProps;super(Object.assign(Object.assign({},e),{view:new Q(t,{props:e.props,viewProps:i}),viewProps:i})),this.props=e.props,this.valueController=e.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}}let W={id:"button",type:"blade",accept(t){let e=A(t,{title:S.required.string,view:S.required.constant("button"),label:S.optional.string});return e?{params:e}:null},controller:t=>new J(t.document,{blade:t.blade,props:V.fromObject({label:t.params.label}),valueController:new y(t.document,{props:V.fromObject({title:t.params.title}),viewProps:t.viewProps})}),api:t=>t.controller instanceof J&&t.controller.valueController instanceof y?new v(t.controller):null};class Z extends U{constructor(t){super(t),this.value=t.value}}function tt(){return new V({positions:E([],{equals:p})})}class te extends V{constructor(t){super(t)}static create(t){return new te(V.createCore({completed:!0,expanded:t,expandedHeight:null,shouldFixHeight:!1,temporaryExpanded:null}))}get styleExpanded(){var t;return null!==(t=this.get("temporaryExpanded"))&&void 0!==t?t:this.get("expanded")}get styleHeight(){if(!this.styleExpanded)return"0";let t=this.get("expandedHeight");return this.get("shouldFixHeight")&&!l(t)?`${t}px`:"auto"}bindExpandedClass(t,e){let i=()=>{this.styleExpanded?t.classList.add(e):t.classList.remove(e)};g(this,"expanded",i),g(this,"temporaryExpanded",i)}cleanUpTransition(){this.set("shouldFixHeight",!1),this.set("expandedHeight",null),this.set("completed",!0)}}function ti(t,e){e.style.height=t.styleHeight}function tn(t,e){t.value("expanded").emitter.on("beforechange",()=>{if(t.set("completed",!1),l(t.get("expandedHeight"))){let i;let n=(i=0,function(t,e){let i=t.style.transition;t.style.transition="none",e(),t.style.transition=i}(e,()=>{t.set("expandedHeight",null),t.set("temporaryExpanded",!0),T(e),i=e.clientHeight,t.set("temporaryExpanded",null),T(e)}),i);n>0&&t.set("expandedHeight",n)}t.set("shouldFixHeight",!0),T(e)}),t.emitter.on("change",()=>{ti(t,e)}),ti(t,e),e.addEventListener("transitionend",e=>{"height"===e.propertyName&&t.cleanUpTransition()})}class tr extends i{constructor(t,e){super(t),this.rackApi_=e}}class ts{constructor(t){this.emitter=new m,this.items_=[],this.cache_=new Set,this.onSubListAdd_=this.onSubListAdd_.bind(this),this.onSubListRemove_=this.onSubListRemove_.bind(this),this.extract_=t}get items(){return this.items_}allItems(){return Array.from(this.cache_)}find(t){for(let e of this.allItems())if(t(e))return e;return null}includes(t){return this.cache_.has(t)}add(t,e){if(this.includes(t))throw u.shouldNeverHappen();let i=void 0!==e?e:this.items_.length;this.items_.splice(i,0,t),this.cache_.add(t);let n=this.extract_(t);n&&(n.emitter.on("add",this.onSubListAdd_),n.emitter.on("remove",this.onSubListRemove_),n.allItems().forEach(t=>{this.cache_.add(t)})),this.emitter.emit("add",{index:i,item:t,root:this,target:this})}remove(t){let e=this.items_.indexOf(t);if(e<0)return;this.items_.splice(e,1),this.cache_.delete(t);let i=this.extract_(t);i&&(i.emitter.off("add",this.onSubListAdd_),i.emitter.off("remove",this.onSubListRemove_)),this.emitter.emit("remove",{index:e,item:t,root:this,target:this})}onSubListAdd_(t){this.cache_.add(t.item),this.emitter.emit("add",{index:t.index,item:t.item,root:this,target:t.target})}onSubListRemove_(t){this.cache_.delete(t.item),this.emitter.emit("remove",{index:t.index,item:t.item,root:this,target:t.target})}}class to extends i{constructor(t){super(t),this.onBindingChange_=this.onBindingChange_.bind(this),this.emitter_=new m,this.controller_.binding.emitter.on("change",this.onBindingChange_)}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}refresh(){this.controller_.binding.read()}onBindingChange_(t){let e=t.sender.target.read();this.emitter_.emit("change",{event:new r(this,e,this.controller_.binding.target.presetKey,t.options.last)})}}class ta extends J{constructor(t,e){super(t,e),this.binding=e.binding}}class tl extends i{constructor(t){super(t),this.onBindingUpdate_=this.onBindingUpdate_.bind(this),this.emitter_=new m,this.controller_.binding.emitter.on("update",this.onBindingUpdate_)}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}refresh(){this.controller_.binding.read()}onBindingUpdate_(t){let e=t.sender.target.read();this.emitter_.emit("update",{event:new s(this,e,this.controller_.binding.target.presetKey)})}}class tp extends J{constructor(t,e){super(t,e),this.binding=e.binding,this.viewProps.bindDisabled(this.binding.ticker),this.viewProps.handleDispose(()=>{this.binding.dispose()})}}function td(t){return t instanceof tc?t.apiSet_:t instanceof tr?t.rackApi_.apiSet_:null}function th(t,e){let i=t.find(t=>t.controller_===e);if(!i)throw u.shouldNeverHappen();return i}function tu(t,e,i){if(!c.isBindable(t))throw u.notBindable();return new c(t,e,i)}class tc extends i{constructor(t,e){super(t),this.onRackAdd_=this.onRackAdd_.bind(this),this.onRackRemove_=this.onRackRemove_.bind(this),this.onRackInputChange_=this.onRackInputChange_.bind(this),this.onRackMonitorUpdate_=this.onRackMonitorUpdate_.bind(this),this.emitter_=new m,this.apiSet_=new ts(td),this.pool_=e;let i=this.controller_.rack;i.emitter.on("add",this.onRackAdd_),i.emitter.on("remove",this.onRackRemove_),i.emitter.on("inputchange",this.onRackInputChange_),i.emitter.on("monitorupdate",this.onRackMonitorUpdate_),i.children.forEach(t=>{this.setUpApi_(t)})}get children(){return this.controller_.rack.children.map(t=>th(this.apiSet_,t))}addInput(t,e,i){let n=null!=i?i:{},r=this.controller_.view.element.ownerDocument,s=new to(this.pool_.createInput(r,tu(t,e,n.presetKey),n));return this.add(s,n.index)}addMonitor(t,e,i){let n=null!=i?i:{},r=this.controller_.view.element.ownerDocument,s=new tl(this.pool_.createMonitor(r,tu(t,e),n));return this.add(s,n.index)}addFolder(t){return this.addBlade(Object.assign(Object.assign({},t),{view:"folder"}))}addButton(t){return this.addBlade(Object.assign(Object.assign({},t),{view:"button"}))}addSeparator(t){return this.addBlade(Object.assign(Object.assign({},null!=t?t:{}),{view:"separator"}))}addTab(t){return this.addBlade(Object.assign(Object.assign({},t),{view:"tab"}))}add(t,e){this.controller_.rack.add(t.controller_,e);let i=this.apiSet_.find(e=>e.controller_===t.controller_);return i&&this.apiSet_.remove(i),this.apiSet_.add(t),t}remove(t){this.controller_.rack.remove(t.controller_)}addBlade(t){let e=this.controller_.view.element.ownerDocument,i=this.pool_.createBlade(e,t),n=this.pool_.createBladeApi(i);return this.add(n,t.index)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}setUpApi_(t){this.apiSet_.find(e=>e.controller_===t)||this.apiSet_.add(this.pool_.createBladeApi(t))}onRackAdd_(t){this.setUpApi_(t.bladeController)}onRackRemove_(t){if(t.isRoot){let e=th(this.apiSet_,t.bladeController);this.apiSet_.remove(e)}}onRackInputChange_(t){let e=t.bladeController;if(e instanceof ta){let i=th(this.apiSet_,e),n=e.binding;this.emitter_.emit("change",{event:new r(i,n.target.read(),n.target.presetKey,t.options.last)})}else if(e instanceof Z){let i=th(this.apiSet_,e);this.emitter_.emit("change",{event:new r(i,e.value.rawValue,void 0,t.options.last)})}}onRackMonitorUpdate_(t){if(!(t.bladeController instanceof tp))throw u.shouldNeverHappen();let e=th(this.apiSet_,t.bladeController),i=t.bladeController.binding;this.emitter_.emit("update",{event:new s(e,i.target.read(),i.target.presetKey)})}}class tv extends tr{constructor(t,e){super(t,new tc(t.rackController,e)),this.emitter_=new m,this.controller_.foldable.value("expanded").emitter.on("change",t=>{this.emitter_.emit("fold",{event:new o(this,t.sender.rawValue)})}),this.rackApi_.on("change",t=>{this.emitter_.emit("change",{event:t})}),this.rackApi_.on("update",t=>{this.emitter_.emit("update",{event:t})})}get expanded(){return this.controller_.foldable.get("expanded")}set expanded(t){this.controller_.foldable.set("expanded",t)}get title(){return this.controller_.props.get("title")}set title(t){this.controller_.props.set("title",t)}get children(){return this.rackApi_.children}addInput(t,e,i){return this.rackApi_.addInput(t,e,i)}addMonitor(t,e,i){return this.rackApi_.addMonitor(t,e,i)}addFolder(t){return this.rackApi_.addFolder(t)}addButton(t){return this.rackApi_.addButton(t)}addSeparator(t){return this.rackApi_.addSeparator(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){return this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addBlade(t){return this.rackApi_.addBlade(t)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}}class tm extends U{constructor(t){super({blade:t.blade,view:t.view,viewProps:t.rackController.viewProps}),this.rackController=t.rackController}}class tb{constructor(t,e){let i=b(e.viewName);this.element=t.createElement("div"),this.element.classList.add(i()),e.viewProps.bindClassModifiers(this.element)}}function t_(t){return t instanceof tw?t.rack:t instanceof tm?t.rackController.rack:null}function tg(t){let e=t_(t);return e?e.bcSet_:null}class tf{constructor(t){var e,i;this.onBladePositionsChange_=this.onBladePositionsChange_.bind(this),this.onSetAdd_=this.onSetAdd_.bind(this),this.onSetRemove_=this.onSetRemove_.bind(this),this.onChildDispose_=this.onChildDispose_.bind(this),this.onChildPositionsChange_=this.onChildPositionsChange_.bind(this),this.onChildInputChange_=this.onChildInputChange_.bind(this),this.onChildMonitorUpdate_=this.onChildMonitorUpdate_.bind(this),this.onChildValueChange_=this.onChildValueChange_.bind(this),this.onChildViewPropsChange_=this.onChildViewPropsChange_.bind(this),this.onDescendantLayout_=this.onDescendantLayout_.bind(this),this.onDescendantInputChange_=this.onDescendantInputChange_.bind(this),this.onDescendantMonitorUpdate_=this.onDescendantMonitorUpdate_.bind(this),this.emitter=new m,this.blade_=null!==(e=t.blade)&&void 0!==e?e:null,null===(i=this.blade_)||void 0===i||i.value("positions").emitter.on("change",this.onBladePositionsChange_),this.viewProps=t.viewProps,this.bcSet_=new ts(tg),this.bcSet_.emitter.on("add",this.onSetAdd_),this.bcSet_.emitter.on("remove",this.onSetRemove_)}get children(){return this.bcSet_.items}add(t,e){var i;null===(i=t.parent)||void 0===i||i.remove(t),d(t,"parent")?t.parent=this:(t.parent_=this,D({key:"parent",target:"BladeController",place:"BladeRack.add"})),this.bcSet_.add(t,e)}remove(t){d(t,"parent")?t.parent=null:(t.parent_=null,D({key:"parent",target:"BladeController",place:"BladeRack.remove"})),this.bcSet_.remove(t)}find(t){return this.bcSet_.allItems().filter(e=>e instanceof t)}onSetAdd_(t){this.updatePositions_();let e=t.target===t.root;if(this.emitter.emit("add",{bladeController:t.item,index:t.index,isRoot:e,sender:this}),!e)return;let i=t.item;if(i.viewProps.emitter.on("change",this.onChildViewPropsChange_),i.blade.value("positions").emitter.on("change",this.onChildPositionsChange_),i.viewProps.handleDispose(this.onChildDispose_),i instanceof ta)i.binding.emitter.on("change",this.onChildInputChange_);else if(i instanceof tp)i.binding.emitter.on("update",this.onChildMonitorUpdate_);else if(i instanceof Z)i.value.emitter.on("change",this.onChildValueChange_);else{let t=t_(i);if(t){let e=t.emitter;e.on("layout",this.onDescendantLayout_),e.on("inputchange",this.onDescendantInputChange_),e.on("monitorupdate",this.onDescendantMonitorUpdate_)}}}onSetRemove_(t){this.updatePositions_();let e=t.target===t.root;if(this.emitter.emit("remove",{bladeController:t.item,isRoot:e,sender:this}),!e)return;let i=t.item;if(i instanceof ta)i.binding.emitter.off("change",this.onChildInputChange_);else if(i instanceof tp)i.binding.emitter.off("update",this.onChildMonitorUpdate_);else if(i instanceof Z)i.value.emitter.off("change",this.onChildValueChange_);else{let t=t_(i);if(t){let e=t.emitter;e.off("layout",this.onDescendantLayout_),e.off("inputchange",this.onDescendantInputChange_),e.off("monitorupdate",this.onDescendantMonitorUpdate_)}}}updatePositions_(){let t=this.bcSet_.items.filter(t=>!t.viewProps.get("hidden")),e=t[0],i=t[t.length-1];this.bcSet_.items.forEach(t=>{let n=[];t===e&&(n.push("first"),(!this.blade_||this.blade_.get("positions").includes("veryfirst"))&&n.push("veryfirst")),t===i&&(n.push("last"),(!this.blade_||this.blade_.get("positions").includes("verylast"))&&n.push("verylast")),t.blade.set("positions",n)})}onChildPositionsChange_(){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildViewPropsChange_(t){this.updatePositions_(),this.emitter.emit("layout",{sender:this})}onChildDispose_(){this.bcSet_.items.filter(t=>t.viewProps.get("disposed")).forEach(t=>{this.bcSet_.remove(t)})}onChildInputChange_(t){let e=function(t,e){for(let i=0;i{for(let t=this.rack.children.length-1;t>=0;t--)this.rack.children[t].viewProps.set("disposed",!0)})}onRackAdd_(t){t.isRoot&&z(this.view.element,t.bladeController.view.element,t.index)}onRackRemove_(t){t.isRoot&&q(t.bladeController.view.element)}}let tx=b("cnt");class tC{constructor(t,e){var i;this.className_=b(null!==(i=e.viewName)&&void 0!==i?i:"fld"),this.element=t.createElement("div"),this.element.classList.add(this.className_(),tx()),e.viewProps.bindClassModifiers(this.element),this.foldable_=e.foldable,this.foldable_.bindExpandedClass(this.element,this.className_(void 0,"expanded")),g(this.foldable_,"completed",f(this.element,this.className_(void 0,"cpl")));let n=t.createElement("button");n.classList.add(this.className_("b")),g(e.props,"title",t=>{l(t)?this.element.classList.add(this.className_(void 0,"not")):this.element.classList.remove(this.className_(void 0,"not"))}),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n;let r=t.createElement("div");r.classList.add(this.className_("i")),this.element.appendChild(r);let s=t.createElement("div");s.classList.add(this.className_("t")),w(e.props.value("title"),s),this.buttonElement.appendChild(s),this.titleElement=s;let o=t.createElement("div");o.classList.add(this.className_("m")),this.buttonElement.appendChild(o);let a=e.containerElement;a.classList.add(this.className_("c")),this.element.appendChild(a),this.containerElement=a}}class ty extends tm{constructor(t,e){var i;let n=te.create(null===(i=e.expanded)||void 0===i||i),r=new tw(t,{blade:e.blade,root:e.root,viewProps:e.viewProps});super(Object.assign(Object.assign({},e),{rackController:r,view:new tC(t,{containerElement:r.view.element,foldable:n,props:e.props,viewName:e.root?"rot":void 0,viewProps:e.viewProps})})),this.onTitleClick_=this.onTitleClick_.bind(this),this.props=e.props,this.foldable=n,tn(this.foldable,this.view.containerElement),this.rackController.rack.emitter.on("add",()=>{this.foldable.cleanUpTransition()}),this.rackController.rack.emitter.on("remove",()=>{this.foldable.cleanUpTransition()}),this.view.buttonElement.addEventListener("click",this.onTitleClick_)}get document(){return this.view.element.ownerDocument}onTitleClick_(){this.foldable.set("expanded",!this.foldable.get("expanded"))}}let tP={id:"folder",type:"blade",accept(t){let e=A(t,{title:S.required.string,view:S.required.constant("folder"),expanded:S.optional.boolean});return e?{params:e}:null},controller:t=>new ty(t.document,{blade:t.blade,expanded:t.params.expanded,props:V.fromObject({title:t.params.title}),viewProps:t.viewProps}),api:t=>t.controller instanceof ty?new tv(t.controller,t.pool):null};class tk extends Z{constructor(t,e){let i=e.valueController.viewProps;super(Object.assign(Object.assign({},e),{value:e.valueController.value,view:new Q(t,{props:e.props,viewProps:i}),viewProps:i})),this.props=e.props,this.valueController=e.valueController,this.view.valueElement.appendChild(this.valueController.view.element)}}class tE extends i{}let tV=b("spr");class tL{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(tV()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("hr");i.classList.add(tV("r")),this.element.appendChild(i)}}class tM extends U{constructor(t,e){super(Object.assign(Object.assign({},e),{view:new tL(t,{viewProps:e.viewProps})}))}}let tS={id:"separator",type:"blade",accept(t){let e=A(t,{view:S.required.constant("separator")});return e?{params:e}:null},controller:t=>new tM(t.document,{blade:t.blade,viewProps:t.viewProps}),api:t=>t.controller instanceof tM?new tE(t.controller):null},tA=b("tbi");class tD{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(tA()),e.viewProps.bindClassModifiers(this.element),g(e.props,"selected",t=>{t?this.element.classList.add(tA(void 0,"sel")):this.element.classList.remove(tA(void 0,"sel"))});let i=t.createElement("button");i.classList.add(tA("b")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.buttonElement=i;let n=t.createElement("div");n.classList.add(tA("t")),w(e.props.value("title"),n),this.buttonElement.appendChild(n),this.titleElement=n}}class tj{constructor(t,e){this.emitter=new m,this.onClick_=this.onClick_.bind(this),this.props=e.props,this.viewProps=e.viewProps,this.view=new tD(t,{props:e.props,viewProps:e.viewProps}),this.view.buttonElement.addEventListener("click",this.onClick_)}onClick_(){this.emitter.emit("click",{sender:this})}}class tR{constructor(t,e){this.onItemClick_=this.onItemClick_.bind(this),this.ic_=new tj(t,{props:e.itemProps,viewProps:I.create()}),this.ic_.emitter.on("click",this.onItemClick_),this.cc_=new tw(t,{blade:tt(),viewProps:I.create()}),this.props=e.props,g(this.props,"selected",t=>{this.itemController.props.set("selected",t),this.contentController.viewProps.set("hidden",!t)})}get itemController(){return this.ic_}get contentController(){return this.cc_}onItemClick_(){this.props.set("selected",!0)}}class tO{constructor(t,e){this.controller_=t,this.rackApi_=e}get title(){var t;return null!==(t=this.controller_.itemController.props.get("title"))&&void 0!==t?t:""}set title(t){this.controller_.itemController.props.set("title",t)}get selected(){return this.controller_.props.get("selected")}set selected(t){this.controller_.props.set("selected",t)}get children(){return this.rackApi_.children}addButton(t){return this.rackApi_.addButton(t)}addFolder(t){return this.rackApi_.addFolder(t)}addSeparator(t){return this.rackApi_.addSeparator(t)}addTab(t){return this.rackApi_.addTab(t)}add(t,e){this.rackApi_.add(t,e)}remove(t){this.rackApi_.remove(t)}addInput(t,e,i){return this.rackApi_.addInput(t,e,i)}addMonitor(t,e,i){return this.rackApi_.addMonitor(t,e,i)}addBlade(t){return this.rackApi_.addBlade(t)}}class tI extends tr{constructor(t,e){super(t,new tc(t.rackController,e)),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.onSelect_=this.onSelect_.bind(this),this.emitter_=new m,this.pageApiMap_=new Map,this.rackApi_.on("change",t=>{this.emitter_.emit("change",{event:t})}),this.rackApi_.on("update",t=>{this.emitter_.emit("update",{event:t})}),this.controller_.tab.selectedIndex.emitter.on("change",this.onSelect_),this.controller_.pageSet.emitter.on("add",this.onPageAdd_),this.controller_.pageSet.emitter.on("remove",this.onPageRemove_),this.controller_.pageSet.items.forEach(t=>{this.setUpPageApi_(t)})}get pages(){return this.controller_.pageSet.items.map(t=>{let e=this.pageApiMap_.get(t);if(!e)throw u.shouldNeverHappen();return e})}addPage(t){let e=new tR(this.controller_.view.element.ownerDocument,{itemProps:V.fromObject({selected:!1,title:t.title}),props:V.fromObject({selected:!1})});this.controller_.add(e,t.index);let i=this.pageApiMap_.get(e);if(!i)throw u.shouldNeverHappen();return i}removePage(t){this.controller_.remove(t)}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}setUpPageApi_(t){let e=this.rackApi_.apiSet_.find(e=>e.controller_===t.contentController);if(!e)throw u.shouldNeverHappen();let i=new tO(t,e);this.pageApiMap_.set(t,i)}onPageAdd_(t){this.setUpPageApi_(t.item)}onPageRemove_(t){if(!this.pageApiMap_.get(t.item))throw u.shouldNeverHappen();this.pageApiMap_.delete(t.item)}onSelect_(t){this.emitter_.emit("select",{event:new a(this,t.rawValue)})}}class tN{constructor(){this.onItemSelectedChange_=this.onItemSelectedChange_.bind(this),this.empty=E(!0),this.selectedIndex=E(-1),this.items_=[]}add(t,e){let i=null!=e?e:this.items_.length;this.items_.splice(i,0,t),t.emitter.on("change",this.onItemSelectedChange_),this.keepSelection_()}remove(t){let e=this.items_.indexOf(t);e<0||(this.items_.splice(e,1),t.emitter.off("change",this.onItemSelectedChange_),this.keepSelection_())}keepSelection_(){if(0===this.items_.length){this.selectedIndex.rawValue=-1,this.empty.rawValue=!0;return}let t=this.items_.findIndex(t=>t.rawValue);t<0?(this.items_.forEach((t,e)=>{t.rawValue=0===e}),this.selectedIndex.rawValue=0):(this.items_.forEach((e,i)=>{e.rawValue=i===t}),this.selectedIndex.rawValue=t),this.empty.rawValue=!1}onItemSelectedChange_(t){if(t.rawValue){let e=this.items_.findIndex(e=>e===t.sender);this.items_.forEach((t,i)=>{t.rawValue=i===e}),this.selectedIndex.rawValue=e}else this.keepSelection_()}}let tK=b("tab");class tU{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(tK(),tx()),e.viewProps.bindClassModifiers(this.element),_(e.empty,f(this.element,tK(void 0,"nop")));let i=t.createElement("div");i.classList.add(tK("t")),this.element.appendChild(i),this.itemsElement=i;let n=t.createElement("div");n.classList.add(tK("i")),this.element.appendChild(n);let r=e.contentsElement;r.classList.add(tK("c")),this.element.appendChild(r),this.contentsElement=r}}class tB extends tm{constructor(t,e){let i=new tw(t,{blade:e.blade,viewProps:e.viewProps}),n=new tN;super({blade:e.blade,rackController:i,view:new tU(t,{contentsElement:i.view.element,empty:n.empty,viewProps:e.viewProps})}),this.onPageAdd_=this.onPageAdd_.bind(this),this.onPageRemove_=this.onPageRemove_.bind(this),this.pageSet_=new ts(()=>null),this.pageSet_.emitter.on("add",this.onPageAdd_),this.pageSet_.emitter.on("remove",this.onPageRemove_),this.tab=n}get pageSet(){return this.pageSet_}add(t,e){this.pageSet_.add(t,e)}remove(t){this.pageSet_.remove(this.pageSet_.items[t])}onPageAdd_(t){let e=t.item;z(this.view.itemsElement,e.itemController.view.element,t.index),e.itemController.viewProps.set("parent",this.viewProps),this.rackController.rack.add(e.contentController,t.index),this.tab.add(e.props.value("selected"))}onPageRemove_(t){let e=t.item;q(e.itemController.view.element),e.itemController.viewProps.set("parent",null),this.rackController.rack.remove(e.contentController),this.tab.remove(e.props.value("selected"))}}let tT={id:"tab",type:"blade",accept(t){let e=A(t,{pages:S.required.array(S.required.object({title:S.required.string})),view:S.required.constant("tab")});return e&&0!==e.pages.length?{params:e}:null},controller(t){let e=new tB(t.document,{blade:t.blade,viewProps:t.viewProps});return t.params.pages.forEach(i=>{let n=new tR(t.document,{itemProps:V.fromObject({selected:!1,title:i.title}),props:V.fromObject({selected:!1})});e.add(n)}),e},api:t=>t.controller instanceof tB?new tI(t.controller,t.pool):null};class tF{constructor(){this.disabled=!1,this.emitter=new m}dispose(){}tick(){this.disabled||this.emitter.emit("tick",{sender:this})}}class t${constructor(t,e){this.disabled_=!1,this.timerId_=null,this.onTick_=this.onTick_.bind(this),this.doc_=t,this.emitter=new m,this.interval_=e,this.setTimer_()}get disabled(){return this.disabled_}set disabled(t){this.disabled_=t,this.disabled_?this.clearTimer_():this.setTimer_()}dispose(){this.clearTimer_()}clearTimer_(){if(null===this.timerId_)return;let t=this.doc_.defaultView;t&&t.clearInterval(this.timerId_),this.timerId_=null}setTimer_(){if(this.clearTimer_(),this.interval_<=0)return;let t=this.doc_.defaultView;t&&(this.timerId_=t.setInterval(this.onTick_,this.interval_))}onTick_(){this.disabled_||this.emitter.emit("tick",{sender:this})}}class tH{constructor(t){this.onValueChange_=this.onValueChange_.bind(this),this.reader=t.reader,this.writer=t.writer,this.emitter=new m,this.value=t.value,this.value.emitter.on("change",this.onValueChange_),this.target=t.target,this.read()}read(){let t=this.target.read();void 0!==t&&(this.value.rawValue=this.reader(t))}write_(t){this.writer(this.target,t)}onValueChange_(t){this.write_(t.rawValue),this.emitter.emit("change",{options:t.options,rawValue:t.rawValue,sender:this})}}function tz(t,e){for(;t.lengtht.length?i.splice(0,i.length-t.length):tz(i,t.length),i}(e,i),this.emitter.emit("update",{rawValue:i,sender:this})}onTick_(t){this.read()}}class tG{constructor(t){this.constraints=t}constrain(t){return this.constraints.reduce((t,e)=>e.constrain(t),t)}}function tY(t,e){if(t instanceof e)return t;if(t instanceof tG){let i=t.constraints.reduce((t,i)=>t||(i instanceof e?i:null),null);if(i)return i}return null}class tX{constructor(t){this.values=V.fromObject({max:t.max,min:t.min})}constrain(t){let e=this.values.get("max");return Math.min(Math.max(t,this.values.get("min")),e)}}class tQ{constructor(t){this.values=V.fromObject({options:t})}get options(){return this.values.get("options")}constrain(t){let e=this.values.get("options");return 0===e.length?t:e.filter(e=>e.value===t).length>0?t:e[0].value}}class tJ{constructor(t){this.values=V.fromObject({max:t.max,min:t.min})}get maxValue(){return this.values.get("max")}get minValue(){return this.values.get("min")}constrain(t){let e=this.values.get("max"),i=this.values.get("min"),n=t;return l(i)||(n=Math.max(n,i)),l(e)||(n=Math.min(n,e)),n}}class tW{constructor(t,e=0){this.step=t,this.origin=e}constrain(t){let e=this.origin%this.step,i=Math.round((t-e)/this.step);return e+i*this.step}}let tZ=b("lst");class t0{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.props_=e.props,this.element=t.createElement("div"),this.element.classList.add(tZ()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("select");i.classList.add(tZ("s")),e.viewProps.bindDisabled(i),this.element.appendChild(i),this.selectElement=i;let n=t.createElement("div");n.classList.add(tZ("m")),n.appendChild(H(t,"dropdown")),this.element.appendChild(n),e.value.emitter.on("change",this.onValueChange_),this.value_=e.value,g(this.props_,"options",e=>{G(this.selectElement),e.forEach(e=>{let i=t.createElement("option");i.textContent=e.text,this.selectElement.appendChild(i)}),this.update_()})}update_(){let t=this.props_.get("options").map(t=>t.value);this.selectElement.selectedIndex=t.indexOf(this.value_.rawValue)}onValueChange_(){this.update_()}}class t1{constructor(t,e){this.onSelectChange_=this.onSelectChange_.bind(this),this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new t0(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.view.selectElement.addEventListener("change",this.onSelectChange_)}onSelectChange_(t){let e=t.currentTarget;this.value.rawValue=this.props.get("options")[e.selectedIndex].value}}let t2=b("pop");class t5{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(t2()),e.viewProps.bindClassModifiers(this.element),_(e.shows,f(this.element,t2(void 0,"v")))}}class t6{constructor(t,e){this.shows=E(!1),this.viewProps=e.viewProps,this.view=new t5(t,{shows:this.shows,viewProps:this.viewProps})}}let t4=b("txt");class t8{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(t4()),e.viewProps.bindClassModifiers(this.element),this.props_=e.props,this.props_.emitter.on("change",this.onChange_);let i=t.createElement("input");i.classList.add(t4("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onChange_),this.value_=e.value,this.refresh()}refresh(){let t=this.props_.get("formatter");this.inputElement.value=t(this.value_.rawValue)}onChange_(){this.refresh()}}class t3{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.parser_=e.parser,this.props=e.props,this.value=e.value,this.viewProps=e.viewProps,this.view=new t8(t,{props:e.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){let e=t.currentTarget.value,i=this.parser_(e);l(i)||(this.value.rawValue=i),this.view.refresh()}}function t9(t){return"false"!==t&&!!t}function t7(t){return String(t)}class et{constructor(t){this.text=t}evaluate(){return Number(this.text)}toString(){return this.text}}let ee={"**":(t,e)=>Math.pow(t,e),"*":(t,e)=>t*e,"/":(t,e)=>t/e,"%":(t,e)=>t%e,"+":(t,e)=>t+e,"-":(t,e)=>t-e,"<<":(t,e)=>t<>":(t,e)=>t>>e,">>>":(t,e)=>t>>>e,"&":(t,e)=>t&e,"^":(t,e)=>t^e,"|":(t,e)=>t|e};class ei{constructor(t,e,i){this.left=e,this.operator=t,this.right=i}evaluate(){let t=ee[this.operator];if(!t)throw Error(`unexpected binary operator: '${this.operator}`);return t(this.left.evaluate(),this.right.evaluate())}toString(){return["b(",this.left.toString(),this.operator,this.right.toString(),")"].join(" ")}}let en={"+":t=>t,"-":t=>-t,"~":t=>~t};class er{constructor(t,e){this.operator=t,this.expression=e}evaluate(){let t=en[this.operator];if(!t)throw Error(`unexpected unary operator: '${this.operator}`);return t(this.expression.evaluate())}toString(){return["u(",this.operator,this.expression.toString(),")"].join(" ")}}function es(t){return(e,i)=>{for(let n=0;n>>",">>"],["&"],["^"],["|"]].reduce((t,e)=>(i,n)=>{let r=t(i,n);if(!r)return null;n=r.cursor;let s=r.evaluable;for(;;){let r=function(t,e,i){i+=eo(e,i).length;let n=t.filter(t=>e.startsWith(t,i))[0];return n?(i+=n.length,{cursor:i+=eo(e,i).length,operator:n}):null}(e,i,n);if(!r)break;let o=t(i,n=r.cursor);if(!o)return null;n=o.cursor,s=new ei(r.operator,s,o.evaluable)}return s?{cursor:n,evaluable:s}:null},function t(e,i){var n,r;let s=null!==(r=function(t,e){let i=eu(t,e);return(e+=i.length,""===i)?null:{evaluable:new et(i),cursor:e}}(e,n=i))&&void 0!==r?r:function(t,e){let i=t.substr(e,1);if(e+=i.length,"("!==i)return null;let n=ev(t,e);if(!n)return null;e=n.cursor,e+=eo(t,e).length;let r=t.substr(e,1);return(e+=r.length,")"!==r)?null:{evaluable:n.evaluable,cursor:e}}(e,n);if(s)return s;let o=e.substr(i,1);if(i+=o.length,"+"!==o&&"-"!==o&&"~"!==o)return null;let a=t(e,i);return a?{cursor:i=a.cursor,evaluable:new er(o,a.evaluable)}:null});function ev(t,e){return e+=eo(t,e).length,ec(t,e)}function em(t){var e;let i=function(t){let e=ev(t,0);return e&&e.cursor+eo(t,e.cursor).length===t.length?e.evaluable:null}(t);return null!==(e=null==i?void 0:i.evaluate())&&void 0!==e?e:null}function eb(t){if("number"==typeof t)return t;if("string"==typeof t){let e=em(t);if(!l(e))return e}return 0}function e_(t){return String(t)}function eg(t){return e=>e.toFixed(Math.max(Math.min(t,20),0))}let ef=eg(0);function ew(t){return ef(t)+"%"}function ex(t){return String(t)}function eC(t){return t}function ey({primary:t,secondary:e,forward:i,backward:n}){let r=!1;function s(t){r||(r=!0,t(),r=!1)}t.emitter.on("change",n=>{s(()=>{e.setRawValue(i(t,e),n.options)})}),e.emitter.on("change",r=>{s(()=>{t.setRawValue(n(t,e),r.options)}),s(()=>{e.setRawValue(i(t,e),r.options)})}),s(()=>{e.setRawValue(i(t,e),{forceEmit:!1,last:!0})})}function eP(t,e){let i=t*(e.altKey?.1:1)*(e.shiftKey?10:1);return e.upKey?+i:e.downKey?-i:0}function ek(t){return{altKey:t.altKey,downKey:"ArrowDown"===t.key,shiftKey:t.shiftKey,upKey:"ArrowUp"===t.key}}function eE(t){return{altKey:t.altKey,downKey:"ArrowLeft"===t.key,shiftKey:t.shiftKey,upKey:"ArrowRight"===t.key}}function eV(t){return"ArrowUp"===t||"ArrowDown"===t||"ArrowLeft"===t||"ArrowRight"===t}function eL(t,e){var i,n;let r=e.ownerDocument.defaultView,s=e.getBoundingClientRect();return{x:t.pageX-((null!==(i=r&&r.scrollX)&&void 0!==i?i:0)+s.left),y:t.pageY-((null!==(n=r&&r.scrollY)&&void 0!==n?n:0)+s.top)}}class eM{constructor(t){this.lastTouch_=null,this.onDocumentMouseMove_=this.onDocumentMouseMove_.bind(this),this.onDocumentMouseUp_=this.onDocumentMouseUp_.bind(this),this.onMouseDown_=this.onMouseDown_.bind(this),this.onTouchEnd_=this.onTouchEnd_.bind(this),this.onTouchMove_=this.onTouchMove_.bind(this),this.onTouchStart_=this.onTouchStart_.bind(this),this.elem_=t,this.emitter=new m,t.addEventListener("touchstart",this.onTouchStart_,{passive:!1}),t.addEventListener("touchmove",this.onTouchMove_,{passive:!0}),t.addEventListener("touchend",this.onTouchEnd_),t.addEventListener("mousedown",this.onMouseDown_)}computePosition_(t){let e=this.elem_.getBoundingClientRect();return{bounds:{width:e.width,height:e.height},point:t?{x:t.x,y:t.y}:null}}onMouseDown_(t){var e;t.preventDefault(),null===(e=t.currentTarget)||void 0===e||e.focus();let i=this.elem_.ownerDocument;i.addEventListener("mousemove",this.onDocumentMouseMove_),i.addEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(eL(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseMove_(t){this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(eL(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onDocumentMouseUp_(t){let e=this.elem_.ownerDocument;e.removeEventListener("mousemove",this.onDocumentMouseMove_),e.removeEventListener("mouseup",this.onDocumentMouseUp_),this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(eL(t,this.elem_)),sender:this,shiftKey:t.shiftKey})}onTouchStart_(t){t.preventDefault();let e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("down",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchMove_(t){let e=t.targetTouches.item(0),i=this.elem_.getBoundingClientRect();this.emitter.emit("move",{altKey:t.altKey,data:this.computePosition_(e?{x:e.clientX-i.left,y:e.clientY-i.top}:void 0),sender:this,shiftKey:t.shiftKey}),this.lastTouch_=e}onTouchEnd_(t){var e;let i=null!==(e=t.targetTouches.item(0))&&void 0!==e?e:this.lastTouch_,n=this.elem_.getBoundingClientRect();this.emitter.emit("up",{altKey:t.altKey,data:this.computePosition_(i?{x:i.clientX-n.left,y:i.clientY-n.top}:void 0),sender:this,shiftKey:t.shiftKey})}}function eS(t,e,i,n,r){return n+(t-e)/(i-e)*(r-n)}function eA(t){return String(t.toFixed(10)).split(".")[1].replace(/0+$/,"").length}function eD(t,e,i){return Math.min(Math.max(t,e),i)}let ej=b("txt");class eR{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(ej(),ej(void 0,"num")),e.arrayPosition&&this.element.classList.add(ej(void 0,e.arrayPosition)),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("input");i.classList.add(ej("i")),i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,this.onDraggingChange_=this.onDraggingChange_.bind(this),this.dragging_=e.dragging,this.dragging_.emitter.on("change",this.onDraggingChange_),this.element.classList.add(ej()),this.inputElement.classList.add(ej("i"));let n=t.createElement("div");n.classList.add(ej("k")),this.element.appendChild(n),this.knobElement=n;let r=t.createElementNS(B,"svg");r.classList.add(ej("g")),this.knobElement.appendChild(r);let s=t.createElementNS(B,"path");s.classList.add(ej("gb")),r.appendChild(s),this.guideBodyElem_=s;let o=t.createElementNS(B,"path");o.classList.add(ej("gh")),r.appendChild(o),this.guideHeadElem_=o;let a=t.createElement("div");a.classList.add(b("tt")()),this.knobElement.appendChild(a),this.tooltipElem_=a,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.refresh()}onDraggingChange_(t){if(null===t.rawValue){this.element.classList.remove(ej(void 0,"drg"));return}this.element.classList.add(ej(void 0,"drg"));let e=t.rawValue/this.props_.get("draggingScale"),i=e+(e>0?-1:e<0?1:0),n=eD(-i,-4,4);this.guideHeadElem_.setAttributeNS(null,"d",`M ${i+n},0 L${i},4 L${i+n},8 M ${e},-1 L${e},9`),this.guideBodyElem_.setAttributeNS(null,"d",`M 0,4 L${e},4`);let r=this.props_.get("formatter");this.tooltipElem_.textContent=r(this.value.rawValue),this.tooltipElem_.style.left=`${e}px`}refresh(){let t=this.props_.get("formatter");this.inputElement.value=t(this.value.rawValue)}onChange_(){this.refresh()}}class eO{constructor(t,e){var i;this.originRawValue_=0,this.onInputChange_=this.onInputChange_.bind(this),this.onInputKeyDown_=this.onInputKeyDown_.bind(this),this.onInputKeyUp_=this.onInputKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=e.baseStep,this.parser_=e.parser,this.props=e.props,this.sliderProps_=null!==(i=e.sliderProps)&&void 0!==i?i:null,this.value=e.value,this.viewProps=e.viewProps,this.dragging_=E(null),this.view=new eR(t,{arrayPosition:e.arrayPosition,dragging:this.dragging_,props:this.props,value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_),this.view.inputElement.addEventListener("keydown",this.onInputKeyDown_),this.view.inputElement.addEventListener("keyup",this.onInputKeyUp_);let n=new eM(this.view.knobElement);n.emitter.on("down",this.onPointerDown_),n.emitter.on("move",this.onPointerMove_),n.emitter.on("up",this.onPointerUp_)}constrainValue_(t){var e,i;let n=null===(e=this.sliderProps_)||void 0===e?void 0:e.get("minValue"),r=null===(i=this.sliderProps_)||void 0===i?void 0:i.get("maxValue"),s=t;return void 0!==n&&(s=Math.max(s,n)),void 0!==r&&(s=Math.min(s,r)),s}onInputChange_(t){let e=t.currentTarget.value,i=this.parser_(e);l(i)||(this.value.rawValue=this.constrainValue_(i)),this.view.refresh()}onInputKeyDown_(t){let e=eP(this.baseStep_,ek(t));0!==e&&this.value.setRawValue(this.constrainValue_(this.value.rawValue+e),{forceEmit:!1,last:!1})}onInputKeyUp_(t){0!==eP(this.baseStep_,ek(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}onPointerDown_(){this.originRawValue_=this.value.rawValue,this.dragging_.rawValue=0}computeDraggingValue_(t){if(!t.point)return null;let e=t.point.x-t.bounds.width/2;return this.constrainValue_(this.originRawValue_+e*this.props.get("draggingScale"))}onPointerMove_(t){let e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!1,last:!1}),this.dragging_.rawValue=this.value.rawValue-this.originRawValue_)}onPointerUp_(t){let e=this.computeDraggingValue_(t.data);null!==e&&(this.value.setRawValue(e,{forceEmit:!0,last:!0}),this.dragging_.rawValue=null)}}let eI=b("sld");class eN{constructor(t,e){this.onChange_=this.onChange_.bind(this),this.props_=e.props,this.props_.emitter.on("change",this.onChange_),this.element=t.createElement("div"),this.element.classList.add(eI()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(eI("t")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.trackElement=i;let n=t.createElement("div");n.classList.add(eI("k")),this.trackElement.appendChild(n),this.knobElement=n,e.value.emitter.on("change",this.onChange_),this.value=e.value,this.update_()}update_(){let t=eD(eS(this.value.rawValue,this.props_.get("minValue"),this.props_.get("maxValue"),0,100),0,100);this.knobElement.style.width=`${t}%`}onChange_(){this.update_()}}class eK{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDownOrMove_=this.onPointerDownOrMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.baseStep_=e.baseStep,this.value=e.value,this.viewProps=e.viewProps,this.props=e.props,this.view=new eN(t,{props:this.props,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eM(this.view.trackElement),this.ptHandler_.emitter.on("down",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("move",this.onPointerDownOrMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.trackElement.addEventListener("keydown",this.onKeyDown_),this.view.trackElement.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){t.point&&this.value.setRawValue(eS(eD(t.point.x,0,t.bounds.width),0,t.bounds.width,this.props.get("minValue"),this.props.get("maxValue")),e)}onPointerDownOrMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){let e=eP(this.baseStep_,eE(t));0!==e&&this.value.setRawValue(this.value.rawValue+e,{forceEmit:!1,last:!1})}onKeyUp_(t){0!==eP(this.baseStep_,eE(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let eU=b("sldtxt");class eB{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(eU());let i=t.createElement("div");i.classList.add(eU("s")),this.sliderView_=e.sliderView,i.appendChild(this.sliderView_.element),this.element.appendChild(i);let n=t.createElement("div");n.classList.add(eU("t")),this.textView_=e.textView,n.appendChild(this.textView_.element),this.element.appendChild(n)}}class eT{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.sliderC_=new eK(t,{baseStep:e.baseStep,props:e.sliderProps,value:e.value,viewProps:this.viewProps}),this.textC_=new eO(t,{baseStep:e.baseStep,parser:e.parser,props:e.textProps,sliderProps:e.sliderProps,value:e.value,viewProps:e.viewProps}),this.view=new eB(t,{sliderView:this.sliderC_.view,textView:this.textC_.view})}get sliderController(){return this.sliderC_}get textController(){return this.textC_}}function eF(t,e){t.write(e)}function e$(t){return Array.isArray(t)?S.required.array(S.required.object({text:S.required.string,value:S.required.raw}))(t).value:"object"==typeof t?S.required.raw(t).value:void 0}function eH(t){if("inline"===t||"popup"===t)return t}function ez(t){return S.required.object({max:S.optional.number,min:S.optional.number,step:S.optional.number})(t).value}function eq(t){if(Array.isArray(t))return t;let e=[];return Object.keys(t).forEach(i=>{e.push({text:i,value:t[i]})}),e}function eG(t){return l(t)?null:new tQ(eq(t))}function eY(t,e){let i=t&&tY(t,tW);return i?eA(i.step):Math.max(eA(e),2)}function eX(t){let e=function(t){let e=t?tY(t,tW):null;return e?e.step:null}(t);return null!=e?e:1}function eQ(t,e){var i;let n=t&&tY(t,tW),r=Math.abs(null!==(i=null==n?void 0:n.step)&&void 0!==i?i:e);return 0===r?.1:Math.pow(10,Math.floor(Math.log10(r))-1)}let eJ=b("ckb");class eW{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.element=t.createElement("div"),this.element.classList.add(eJ()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("label");i.classList.add(eJ("l")),this.element.appendChild(i);let n=t.createElement("input");n.classList.add(eJ("i")),n.type="checkbox",i.appendChild(n),this.inputElement=n,e.viewProps.bindDisabled(this.inputElement);let r=t.createElement("div");r.classList.add(eJ("w")),i.appendChild(r);let s=H(t,"check");r.appendChild(s),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}update_(){this.inputElement.checked=this.value.rawValue}onValueChange_(){this.update_()}}class eZ{constructor(t,e){this.onInputChange_=this.onInputChange_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new eW(t,{value:this.value,viewProps:this.viewProps}),this.view.inputElement.addEventListener("change",this.onInputChange_)}onInputChange_(t){let e=t.currentTarget;this.value.rawValue=e.checked}}let e0={id:"input-bool",type:"input",accept:(t,e)=>{if("boolean"!=typeof t)return null;let i=A(e,{options:S.optional.custom(e$)});return i?{initialValue:t,params:i}:null},binding:{reader:t=>t9,constraint:t=>(function(t){let e=[],i=eG(t.options);return i&&e.push(i),new tG(e)})(t.params),writer:t=>eF},controller:t=>{let e=t.document,i=t.value,n=t.constraint,r=n&&tY(n,tQ);return r?new t1(e,{props:new V({options:r.values.value("options")}),value:i,viewProps:t.viewProps}):new eZ(e,{value:i,viewProps:t.viewProps})}},e1=b("col");class e2{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(e1()),e.foldable.bindExpandedClass(this.element,e1(void 0,"expanded")),g(e.foldable,"completed",f(this.element,e1(void 0,"cpl")));let i=t.createElement("div");i.classList.add(e1("h")),this.element.appendChild(i);let n=t.createElement("div");n.classList.add(e1("s")),i.appendChild(n),this.swatchElement=n;let r=t.createElement("div");if(r.classList.add(e1("t")),i.appendChild(r),this.textElement=r,"inline"===e.pickerLayout){let e=t.createElement("div");e.classList.add(e1("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}}function e5(t,e,i){let n,r,s;let o=(t%360+360)%360,a=eD(e/100,0,1),l=eD(i/100,0,1),p=l*a,d=p*(1-Math.abs(o/60%2-1)),h=l-p;return o>=0&&o<60?[n,r,s]=[p,d,0]:o>=60&&o<120?[n,r,s]=[d,p,0]:o>=120&&o<180?[n,r,s]=[0,p,d]:o>=180&&o<240?[n,r,s]=[0,d,p]:o>=240&&o<300?[n,r,s]=[d,0,p]:[n,r,s]=[p,0,d],[(n+h)*255,(r+h)*255,(s+h)*255]}function e6(t){return[t[0],t[1],t[2]]}function e4(t,e){return[t[0],t[1],t[2],e]}let e8={hsl:{hsl:(t,e,i)=>[t,e,i],hsv:function(t,e,i){let n=i+e*(100-Math.abs(2*i-100))/200;return[t,0!==n?e*(100-Math.abs(2*i-100))/n:0,i+e*(100-Math.abs(2*i-100))/200]},rgb:function(t,e,i){let n,r,s;let o=(t%360+360)%360,a=eD(e/100,0,1),l=eD(i/100,0,1),p=(1-Math.abs(2*l-1))*a,d=p*(1-Math.abs(o/60%2-1)),h=l-p/2;return o>=0&&o<60?[n,r,s]=[p,d,0]:o>=60&&o<120?[n,r,s]=[d,p,0]:o>=120&&o<180?[n,r,s]=[0,p,d]:o>=180&&o<240?[n,r,s]=[0,d,p]:o>=240&&o<300?[n,r,s]=[d,0,p]:[n,r,s]=[p,0,d],[(n+h)*255,(r+h)*255,(s+h)*255]}},hsv:{hsl:function(t,e,i){let n=100-Math.abs(i*(200-e)/100-100);return[t,0!==n?e*i/n:0,i*(200-e)/200]},hsv:(t,e,i)=>[t,e,i],rgb:e5},rgb:{hsl:function(t,e,i){let n=eD(t/255,0,1),r=eD(e/255,0,1),s=eD(i/255,0,1),o=Math.max(n,r,s),a=Math.min(n,r,s),l=o-a,p=0,d=0;return 0!==l&&(d=l/(1-Math.abs(o+a-1)),p=(p=n===o?(r-s)/l:r===o?2+(s-n)/l:4+(n-r)/l)/6+(p<0?1:0)),[360*p,100*d,(a+o)/2*100]},hsv:function(t,e,i){let n=eD(t/255,0,1),r=eD(e/255,0,1),s=eD(i/255,0,1),o=Math.max(n,r,s),a=o-Math.min(n,r,s);return[0===a?0:o===n?((r-s)/a%6+6)%6*60:o===r?60*((s-n)/a+2):60*((n-r)/a+4),100*(0===o?0:a/o),100*o]},rgb:(t,e,i)=>[t,e,i]}};function e3(t,e){return["float"===e?1:"rgb"===t?255:360,"float"===e?1:"rgb"===t?255:100,"float"===e?1:"rgb"===t?255:100]}function e9(t,e,i,n){let r=e3(e,i),s=e3(e,n);return t.map((t,e)=>t/r[e]*s[e])}function e7(t,e){return!("object"!=typeof t||l(t))&&e in t&&"number"==typeof t[e]}class it{static black(t="int"){return new it([0,0,0],"rgb",t)}static fromObject(t,e="int"){return new it("a"in t?[t.r,t.g,t.b,t.a]:[t.r,t.g,t.b],"rgb",e)}static toRgbaObject(t,e="int"){return t.toRgbaObject(e)}static isRgbColorObject(t){return e7(t,"r")&&e7(t,"g")&&e7(t,"b")}static isRgbaColorObject(t){return this.isRgbColorObject(t)&&e7(t,"a")}static isColorObject(t){return this.isRgbColorObject(t)}static equals(t,e){if(t.mode!==e.mode)return!1;let i=t.comps_,n=e.comps_;for(let t=0;tt.inputElement)];return this.alphaViews_&&t.push(this.alphaViews_.palette.element,this.alphaViews_.text.inputElement),t}}function ir(t){return"int"===t?"int":"float"===t?"float":void 0}function is(t){return A(t,{alpha:S.optional.boolean,color:S.optional.object({alpha:S.optional.boolean,type:S.optional.custom(ir)}),expanded:S.optional.boolean,picker:S.optional.custom(eH)})}function io(t){return t?.1:1}function ia(t){var e;return null===(e=t.color)||void 0===e?void 0:e.type}function il(t,e){let i=t.match(/^(.+)%$/);return i?Math.min(.01*parseFloat(i[1])*e,e):Math.min(parseFloat(t),e)}let ip={deg:t=>t,grad:t=>360*t/400,rad:t=>360*t/(2*Math.PI),turn:t=>360*t};function id(t){let e=t.match(/^([0-9.]+?)(deg|grad|rad|turn)$/);if(!e)return parseFloat(t);let i=parseFloat(e[1]);return ip[e[2]](i)}function ih(t){let e=t.match(/^rgb\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;let i=[il(e[1],255),il(e[2],255),il(e[3],255)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function iu(t){return e=>{let i=ih(e);return i?new it(i,"rgb",t):null}}function ic(t){let e=t.match(/^rgba\(\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;let i=[il(e[1],255),il(e[2],255),il(e[3],255),il(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function iv(t){return e=>{let i=ic(e);return i?new it(i,"rgb",t):null}}function im(t){let e=t.match(/^hsl\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;let i=[id(e[1]),il(e[2],100),il(e[3],100)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function ib(t){return e=>{let i=im(e);return i?new it(i,"hsl",t):null}}function i_(t){let e=t.match(/^hsla\(\s*([0-9A-Fa-f.]+(?:deg|grad|rad|turn)?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*,\s*([0-9A-Fa-f.]+%?)\s*\)$/);if(!e)return null;let i=[id(e[1]),il(e[2],100),il(e[3],100),il(e[4],1)];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function ig(t){return e=>{let i=i_(e);return i?new it(i,"hsl",t):null}}function iw(t){let e=t.match(/^#([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)];let i=t.match(/^(?:#|0x)([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16)]:null}function ix(t){let e=t.match(/^#?([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])([0-9A-Fa-f])$/);if(e)return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16),eS(parseInt(e[4]+e[4],16),0,255,0,1)];let i=t.match(/^(?:#|0x)?([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})$/);return i?[parseInt(i[1],16),parseInt(i[2],16),parseInt(i[3],16),eS(parseInt(i[4],16),0,255,0,1)]:null}function iC(t){let e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;let i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])?null:i}function iy(t){return e=>{let i=iC(e);return i?new it(i,"rgb",t):null}}function iP(t){let e=t.match(/^\{\s*r\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*g\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*b\s*:\s*([0-9A-Fa-f.]+%?)\s*,\s*a\s*:\s*([0-9A-Fa-f.]+%?)\s*\}$/);if(!e)return null;let i=[parseFloat(e[1]),parseFloat(e[2]),parseFloat(e[3]),parseFloat(e[4])];return isNaN(i[0])||isNaN(i[1])||isNaN(i[2])||isNaN(i[3])?null:i}function ik(t){return e=>{let i=iP(e);return i?new it(i,"rgb",t):null}}let iE=[{parser:iw,result:{alpha:!1,mode:"rgb",notation:"hex"}},{parser:ix,result:{alpha:!0,mode:"rgb",notation:"hex"}},{parser:ih,result:{alpha:!1,mode:"rgb",notation:"func"}},{parser:ic,result:{alpha:!0,mode:"rgb",notation:"func"}},{parser:im,result:{alpha:!1,mode:"hsl",notation:"func"}},{parser:i_,result:{alpha:!0,mode:"hsl",notation:"func"}},{parser:iC,result:{alpha:!1,mode:"rgb",notation:"object"}},{parser:iP,result:{alpha:!0,mode:"rgb",notation:"object"}}];function iV(t,e="int"){let i=iE.reduce((e,{parser:i,result:n})=>e||(i(t)?n:null),null);return i?"hex"===i.notation&&"float"!==e?Object.assign(Object.assign({},i),{type:"int"}):"func"===i.notation?Object.assign(Object.assign({},i),{type:e}):null:null}let iL={int:[function(t){let e=iw(t);return e?new it(e,"rgb","int"):null},function(t){let e=ix(t);return e?new it(e,"rgb","int"):null},iu("int"),iv("int"),ib("int"),ig("int"),iy("int"),ik("int")],float:[iu("float"),iv("float"),ib("float"),ig("float"),iy("float"),ik("float")]};function iM(t){let e=iL[t];return t=>e.reduce((e,i)=>e||i(t),null)}function iS(t){let e=eD(Math.floor(t),0,255).toString(16);return 1===e.length?`0${e}`:e}function iA(t,e="#"){let i=e6(t.getComponents("rgb")).map(iS).join("");return`${e}${i}`}function iD(t,e="#"){let i=t.getComponents("rgb"),n=[i[0],i[1],i[2],255*i[3]].map(iS).join("");return`${e}${n}`}function ij(t,e){let i=eg("float"===e?2:0),n=e6(t.getComponents("rgb",e)).map(t=>i(t));return`rgb(${n.join(", ")})`}function iR(t,e){let i=eg(2),n=eg("float"===e?2:0),r=t.getComponents("rgb",e).map((t,e)=>(3===e?i:n)(t));return`rgba(${r.join(", ")})`}function iO(t,e){let i=eg("float"===e?2:0),n=["r","g","b"],r=e6(t.getComponents("rgb",e)).map((t,e)=>`${n[e]}: ${i(t)}`);return`{${r.join(", ")}}`}function iI(t,e){let i=eg(2),n=eg("float"===e?2:0),r=["r","g","b","a"],s=t.getComponents("rgb",e).map((t,e)=>`${r[e]}: ${(3===e?i:n)(t)}`);return`{${s.join(", ")}}`}let iN=[{format:{alpha:!1,mode:"rgb",notation:"hex",type:"int"},stringifier:iA},{format:{alpha:!0,mode:"rgb",notation:"hex",type:"int"},stringifier:iD},{format:{alpha:!1,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){let e=[eg(0),ew,ew],i=e6(t.getComponents("hsl")).map((t,i)=>e[i](t));return`hsl(${i.join(", ")})`}},{format:{alpha:!0,mode:"hsl",notation:"func",type:"int"},stringifier:function(t){let e=[eg(0),ew,ew,eg(2)],i=t.getComponents("hsl").map((t,i)=>e[i](t));return`hsla(${i.join(", ")})`}},...["int","float"].reduce((t,e)=>[...t,{format:{alpha:!1,mode:"rgb",notation:"func",type:e},stringifier:t=>ij(t,e)},{format:{alpha:!0,mode:"rgb",notation:"func",type:e},stringifier:t=>iR(t,e)},{format:{alpha:!1,mode:"rgb",notation:"object",type:e},stringifier:t=>iO(t,e)},{format:{alpha:!0,mode:"rgb",notation:"object",type:e},stringifier:t=>iI(t,e)}],[])];function iK(t){return iN.reduce((e,i)=>{var n;return e||((n=i.format).alpha===t.alpha&&n.mode===t.mode&&n.notation===t.notation&&n.type===t.type?i.stringifier:null)},null)}let iU=b("apl");class iB{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(iU()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);let i=t.createElement("div");i.classList.add(iU("b")),this.element.appendChild(i);let n=t.createElement("div");n.classList.add(iU("c")),i.appendChild(n),this.colorElem_=n;let r=t.createElement("div");r.classList.add(iU("m")),this.element.appendChild(r),this.markerElem_=r;let s=t.createElement("div");s.classList.add(iU("p")),this.markerElem_.appendChild(s),this.previewElem_=s,this.update_()}update_(){let t=this.value.rawValue,e=t.getComponents("rgb"),i=new it([e[0],e[1],e[2],0],"rgb"),n=new it([e[0],e[1],e[2],255],"rgb"),r=["to right",iR(i),iR(n)];this.colorElem_.style.background=`linear-gradient(${r.join(",")})`,this.previewElem_.style.backgroundColor=iR(t);let s=eS(e[3],0,1,0,100);this.markerElem_.style.left=`${s}%`}onValueChange_(){this.update_()}}class iT{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new iB(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eM(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;let i=t.point.x/t.bounds.width,[n,r,s]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new it([n,r,s,i],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){let e=eP(io(!0),eE(t));if(0===e)return;let[i,n,r,s]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new it([i,n,r,s+e],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==eP(io(!0),eE(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let iF=b("coltxt");class i${constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(iF()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(iF("m")),this.modeElem_=function(t){let e=t.createElement("select");return e.appendChild([{text:"RGB",value:"rgb"},{text:"HSL",value:"hsl"},{text:"HSV",value:"hsv"}].reduce((e,i)=>{let n=t.createElement("option");return n.textContent=i.text,n.value=i.value,e.appendChild(n),e},t.createDocumentFragment())),e}(t),this.modeElem_.classList.add(iF("ms")),i.appendChild(this.modeSelectElement),e.viewProps.bindDisabled(this.modeElem_);let n=t.createElement("div");n.classList.add(iF("mm")),n.appendChild(H(t,"dropdown")),i.appendChild(n),this.element.appendChild(i);let r=t.createElement("div");r.classList.add(iF("w")),this.element.appendChild(r),this.textsElem_=r,this.textViews_=e.textViews,this.applyTextViews_(),_(e.colorMode,t=>{this.modeElem_.value=t})}get modeSelectElement(){return this.modeElem_}get textViews(){return this.textViews_}set textViews(t){this.textViews_=t,this.applyTextViews_()}applyTextViews_(){G(this.textsElem_);let t=this.element.ownerDocument;this.textViews_.forEach(e=>{let i=t.createElement("div");i.classList.add(iF("c")),i.appendChild(e.element),this.textsElem_.appendChild(i)})}}function iH(t,e,i){return new eO(t,{arrayPosition:0===i?"fst":2===i?"lst":"mid",baseStep:io(!1),parser:e.parser,props:V.fromObject({draggingScale:"float"===e.colorType?.01:1,formatter:eg("float"===e.colorType?2:0)}),value:E(0,{constraint:new tX({min:0,max:e3(e.colorMode,e.colorType)[i]})}),viewProps:e.viewProps})}class iz{constructor(t,e){this.onModeSelectChange_=this.onModeSelectChange_.bind(this),this.colorType_=e.colorType,this.parser_=e.parser,this.value=e.value,this.viewProps=e.viewProps,this.colorMode=E(this.value.rawValue.mode),this.ccs_=this.createComponentControllers_(t),this.view=new i$(t,{colorMode:this.colorMode,textViews:[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view],viewProps:this.viewProps}),this.view.modeSelectElement.addEventListener("change",this.onModeSelectChange_)}createComponentControllers_(t){let e={colorMode:this.colorMode.rawValue,colorType:this.colorType_,parser:this.parser_,viewProps:this.viewProps},i=[iH(t,e,0),iH(t,e,1),iH(t,e,2)];return i.forEach((t,e)=>{ey({primary:this.value,secondary:t.value,forward:t=>t.rawValue.getComponents(this.colorMode.rawValue,this.colorType_)[e],backward:(t,i)=>{let n=this.colorMode.rawValue,r=t.rawValue.getComponents(n,this.colorType_);return r[e]=i.rawValue,new it(e4(e6(r),r[3]),n,this.colorType_)}})}),i}onModeSelectChange_(t){let e=t.currentTarget;this.colorMode.rawValue=e.value,this.ccs_=this.createComponentControllers_(this.view.element.ownerDocument),this.view.textViews=[this.ccs_[0].view,this.ccs_[1].view,this.ccs_[2].view]}}let iq=b("hpl");class iG{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(iq()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);let i=t.createElement("div");i.classList.add(iq("c")),this.element.appendChild(i);let n=t.createElement("div");n.classList.add(iq("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){let[t]=this.value.rawValue.getComponents("hsv");this.markerElem_.style.backgroundColor=ij(new it([t,100,100],"hsv"));let e=eS(t,0,360,0,100);this.markerElem_.style.left=`${e}%`}onValueChange_(){this.update_()}}class iY{constructor(t,e){this.onKeyDown_=this.onKeyDown_.bind(this),this.onKeyUp_=this.onKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.view=new iG(t,{value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eM(this.view.element),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.element.addEventListener("keydown",this.onKeyDown_),this.view.element.addEventListener("keyup",this.onKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;let i=eS(eD(t.point.x,0,t.bounds.width),0,t.bounds.width,0,360),[,n,r,s]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new it([i,n,r,s],"hsv"),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onKeyDown_(t){let e=eP(io(!1),eE(t));if(0===e)return;let[i,n,r,s]=this.value.rawValue.getComponents("hsv");this.value.setRawValue(new it([i+e,n,r,s],"hsv"),{forceEmit:!1,last:!1})}onKeyUp_(t){0!==eP(io(!1),eE(t))&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}let iX=b("svp");class iQ{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),this.value=e.value,this.value.emitter.on("change",this.onValueChange_),this.element=t.createElement("div"),this.element.classList.add(iX()),e.viewProps.bindClassModifiers(this.element),e.viewProps.bindTabIndex(this.element);let i=t.createElement("canvas");i.height=64,i.width=64,i.classList.add(iX("c")),this.element.appendChild(i),this.canvasElement=i;let n=t.createElement("div");n.classList.add(iX("m")),this.element.appendChild(n),this.markerElem_=n,this.update_()}update_(){let t=function(t){let e=t.ownerDocument.defaultView;return e&&"document"in e?t.getContext("2d",{willReadFrequently:!0}):null}(this.canvasElement);if(!t)return;let e=this.value.rawValue.getComponents("hsv"),i=this.canvasElement.width,n=this.canvasElement.height,r=t.getImageData(0,0,i,n),s=r.data;for(let t=0;tt.rawValue.getComponents()[3],backward:(t,e)=>{let i=t.rawValue.getComponents();return i[3]=e.rawValue,new it(i,t.rawValue.mode)}}),this.textC_=new iz(t,{colorType:e.colorType,parser:em,value:this.value,viewProps:this.viewProps}),this.view=new ii(t,{alphaViews:this.alphaIcs_?{palette:this.alphaIcs_.palette.view,text:this.alphaIcs_.text.view}:null,hPaletteView:this.hPaletteC_.view,supportsAlpha:e.supportsAlpha,svPaletteView:this.svPaletteC_.view,textView:this.textC_.view,viewProps:this.viewProps})}get textController(){return this.textC_}}let iZ=b("colsw");class i0{constructor(t,e){this.onValueChange_=this.onValueChange_.bind(this),e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.element=t.createElement("div"),this.element.classList.add(iZ()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(iZ("sw")),this.element.appendChild(i),this.swatchElem_=i;let n=t.createElement("button");n.classList.add(iZ("b")),e.viewProps.bindDisabled(n),this.element.appendChild(n),this.buttonElement=n,this.update_()}update_(){let t=this.value.rawValue;this.swatchElem_.style.backgroundColor=iD(t)}onValueChange_(){this.update_()}}class i1{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new i0(t,{value:this.value,viewProps:this.viewProps})}}class i2{constructor(t,e){this.onButtonBlur_=this.onButtonBlur_.bind(this),this.onButtonClick_=this.onButtonClick_.bind(this),this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=te.create(e.expanded),this.swatchC_=new i1(t,{value:this.value,viewProps:this.viewProps});let i=this.swatchC_.view.buttonElement;i.addEventListener("blur",this.onButtonBlur_),i.addEventListener("click",this.onButtonClick_),this.textC_=new t3(t,{parser:e.parser,props:V.fromObject({formatter:e.formatter}),value:this.value,viewProps:this.viewProps}),this.view=new e2(t,{foldable:this.foldable_,pickerLayout:e.pickerLayout}),this.view.swatchElement.appendChild(this.swatchC_.view.element),this.view.textElement.appendChild(this.textC_.view.element),this.popC_="popup"===e.pickerLayout?new t6(t,{viewProps:this.viewProps}):null;let n=new iW(t,{colorType:e.colorType,supportsAlpha:e.supportsAlpha,value:this.value,viewProps:this.viewProps});n.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=n,this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(n.view.element),ey({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t.rawValue,backward:(t,e)=>e.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),tn(this.foldable_,this.view.pickerElement))}get textController(){return this.textC_}onButtonBlur_(t){if(!this.popC_)return;let e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;let e=this.popC_.view.element,i=Y(t);!(i&&e.contains(i))&&(!i||i!==this.swatchC_.view.buttonElement||F(e.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.swatchC_.view.buttonElement.focus()}}function i5(t){return e6(t.getComponents("rgb")).reduce((t,e)=>t<<8|255&Math.floor(e),0)}function i6(t){return t.getComponents("rgb").reduce((t,e,i)=>t<<8|255&Math.floor(3===i?255*e:e),0)>>>0}function i4(t){return"number"!=typeof t?it.black():new it([t>>16&255,t>>8&255,255&t],"rgb")}function i8(t){return"number"!=typeof t?it.black():new it([t>>24&255,t>>16&255,t>>8&255,eS(255&t,0,255,0,1)],"rgb")}function i3(t){var e;return null!=t&&!!t.alpha||null!==(e=null==t?void 0:t.color)&&void 0!==e&&!!e.alpha}let i9={id:"input-color-number",type:"input",accept:(t,e)=>{if("number"!=typeof t||!("color"in e||"view"in e&&"color"===e.view))return null;let i=is(e);return i?{initialValue:t,params:i}:null},binding:{reader:t=>i3(t.params)?i8:i4,equals:it.equals,writer:t=>(function(t){let e=t?i6:i5;return(t,i)=>{eF(t,e(i))}})(i3(t.params))},controller:t=>{let e=i3(t.params),i="expanded"in t.params?t.params.expanded:void 0,n="picker"in t.params?t.params.picker:void 0;return new i2(t.document,{colorType:"int",expanded:null!=i&&i,formatter:e?t=>iD(t,"0x"):t=>iA(t,"0x"),parser:iM("int"),pickerLayout:null!=n?n:"popup",supportsAlpha:e,value:t.value,viewProps:t.viewProps})}},i7={id:"input-color-object",type:"input",accept:(t,e)=>{if(!it.isColorObject(t))return null;let i=is(e);return i?{initialValue:t,params:i}:null},binding:{reader:t=>{var e;return e=ia(t.params),t=>it.isColorObject(t)?it.fromObject(t,e):it.black(e)},equals:it.equals,writer:t=>{var e,i,n;return e=t.initialValue,i=it.isRgbaColorObject(e),n=ia(t.params),(t,e)=>{i?function(t,e,i){let n=e.toRgbaObject(i);t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b),t.writeProperty("a",n.a)}(t,e,n):function(t,e,i){let n=e.toRgbaObject(i);t.writeProperty("r",n.r),t.writeProperty("g",n.g),t.writeProperty("b",n.b)}(t,e,n)}}},controller:t=>{var e;let i=it.isRgbaColorObject(t.initialValue),n="expanded"in t.params?t.params.expanded:void 0,r="picker"in t.params?t.params.picker:void 0,s=null!==(e=ia(t.params))&&void 0!==e?e:"int";return new i2(t.document,{colorType:s,expanded:null!=n&&n,formatter:t=>i?iI(t,s):iO(t,s),parser:iM(s),pickerLayout:null!=r?r:"popup",supportsAlpha:i,value:t.value,viewProps:t.viewProps})}},nt={id:"input-color-string",type:"input",accept:(t,e)=>{if("string"!=typeof t||"view"in e&&"text"===e.view)return null;let i=iV(t,ia(e));if(!i||!iK(i))return null;let n=is(e);return n?{initialValue:t,params:n}:null},binding:{reader:t=>{var e;return function(t){let e=iL[t];return i=>{if("string"!=typeof i)return it.black(t);let n=e.reduce((t,e)=>t||e(i),null);return null!=n?n:it.black(t)}}(null!==(e=ia(t.params))&&void 0!==e?e:"int")},equals:it.equals,writer:t=>{let e=iV(t.initialValue,ia(t.params));if(!e)throw u.shouldNeverHappen();let i=function(t){let e=iK(t);return e?(t,i)=>{eF(t,e(i))}:null}(e);if(!i)throw u.notBindable();return i}},controller:t=>{let e=iV(t.initialValue,ia(t.params));if(!e)throw u.shouldNeverHappen();let i=iK(e);if(!i)throw u.shouldNeverHappen();let n="expanded"in t.params?t.params.expanded:void 0,r="picker"in t.params?t.params.picker:void 0;return new i2(t.document,{colorType:e.type,expanded:null!=n&&n,formatter:i,parser:iM(e.type),pickerLayout:null!=r?r:"popup",supportsAlpha:e.alpha,value:t.value,viewProps:t.viewProps})}};class ne{constructor(t){this.components=t.components,this.asm_=t.assembly}constrain(t){let e=this.asm_.toComponents(t).map((t,e)=>{var i,n;return null!==(n=null===(i=this.components[e])||void 0===i?void 0:i.constrain(t))&&void 0!==n?n:t});return this.asm_.fromComponents(e)}}let ni=b("pndtxt");class nn{constructor(t,e){this.textViews=e.textViews,this.element=t.createElement("div"),this.element.classList.add(ni()),this.textViews.forEach(e=>{let i=t.createElement("div");i.classList.add(ni("a")),i.appendChild(e.element),this.element.appendChild(i)})}}class nr{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.acs_=e.axes.map((i,n)=>new eO(t,{arrayPosition:0===n?"fst":n===e.axes.length-1?"lst":"mid",baseStep:e.axes[n].baseStep,parser:e.parser,props:e.axes[n].textProps,value:E(0,{constraint:e.axes[n].constraint}),viewProps:e.viewProps})),this.acs_.forEach((t,i)=>{ey({primary:this.value,secondary:t.value,forward:t=>e.assembly.toComponents(t.rawValue)[i],backward:(t,n)=>{let r=e.assembly.toComponents(t.rawValue);return r[i]=n.rawValue,e.assembly.fromComponents(r)}})}),this.view=new nn(t,{textViews:this.acs_.map(t=>t.view)})}}function ns(t,e){return"step"in t&&!l(t.step)?new tW(t.step,e):null}function no(t){return l(t.max)||l(t.min)?l(t.max)&&l(t.min)?null:new tJ({max:t.max,min:t.min}):new tX({max:t.max,min:t.min})}let na={id:"input-number",type:"input",accept:(t,e)=>{if("number"!=typeof t)return null;let i=A(e,{format:S.optional.function,max:S.optional.number,min:S.optional.number,options:S.optional.custom(e$),step:S.optional.number});return i?{initialValue:t,params:i}:null},binding:{reader:t=>eb,constraint:t=>(function(t,e){let i=[],n=ns(t,e);n&&i.push(n);let r=no(t);r&&i.push(r);let s=eG(t.options);return s&&i.push(s),new tG(i)})(t.params,t.initialValue),writer:t=>eF},controller:t=>{var e;let i=t.value,n=t.constraint,r=n&&tY(n,tQ);if(r)return new t1(t.document,{props:new V({options:r.values.value("options")}),value:i,viewProps:t.viewProps});let s=null!==(e="format"in t.params?t.params.format:void 0)&&void 0!==e?e:eg(eY(n,i.rawValue)),o=n&&tY(n,tX);return o?new eT(t.document,{baseStep:eX(n),parser:em,sliderProps:new V({maxValue:o.values.value("max"),minValue:o.values.value("min")}),textProps:V.fromObject({draggingScale:eQ(n,i.rawValue),formatter:s}),value:i,viewProps:t.viewProps}):new eO(t.document,{baseStep:eX(n),parser:em,props:V.fromObject({draggingScale:eQ(n,i.rawValue),formatter:s}),value:i,viewProps:t.viewProps})}};class nl{constructor(t=0,e=0){this.x=t,this.y=e}getComponents(){return[this.x,this.y]}static isObject(t){if(l(t))return!1;let e=t.x,i=t.y;return"number"==typeof e&&"number"==typeof i}static equals(t,e){return t.x===e.x&&t.y===e.y}toObject(){return{x:this.x,y:this.y}}}let np={toComponents:t=>t.getComponents(),fromComponents:t=>new nl(...t)},nd=b("p2d");class nh{constructor(t,e){this.element=t.createElement("div"),this.element.classList.add(nd()),e.viewProps.bindClassModifiers(this.element),_(e.expanded,f(this.element,nd(void 0,"expanded")));let i=t.createElement("div");i.classList.add(nd("h")),this.element.appendChild(i);let n=t.createElement("button");n.classList.add(nd("b")),n.appendChild(H(t,"p2dpad")),e.viewProps.bindDisabled(n),i.appendChild(n),this.buttonElement=n;let r=t.createElement("div");if(r.classList.add(nd("t")),i.appendChild(r),this.textElement=r,"inline"===e.pickerLayout){let e=t.createElement("div");e.classList.add(nd("p")),this.element.appendChild(e),this.pickerElement=e}else this.pickerElement=null}}let nu=b("p2dp");class nc{constructor(t,e){this.onFoldableChange_=this.onFoldableChange_.bind(this),this.onValueChange_=this.onValueChange_.bind(this),this.invertsY_=e.invertsY,this.maxValue_=e.maxValue,this.element=t.createElement("div"),this.element.classList.add(nu()),"popup"===e.layout&&this.element.classList.add(nu(void 0,"p")),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("div");i.classList.add(nu("p")),e.viewProps.bindTabIndex(i),this.element.appendChild(i),this.padElement=i;let n=t.createElementNS(B,"svg");n.classList.add(nu("g")),this.padElement.appendChild(n),this.svgElem_=n;let r=t.createElementNS(B,"line");r.classList.add(nu("ax")),r.setAttributeNS(null,"x1","0"),r.setAttributeNS(null,"y1","50%"),r.setAttributeNS(null,"x2","100%"),r.setAttributeNS(null,"y2","50%"),this.svgElem_.appendChild(r);let s=t.createElementNS(B,"line");s.classList.add(nu("ax")),s.setAttributeNS(null,"x1","50%"),s.setAttributeNS(null,"y1","0"),s.setAttributeNS(null,"x2","50%"),s.setAttributeNS(null,"y2","100%"),this.svgElem_.appendChild(s);let o=t.createElementNS(B,"line");o.classList.add(nu("l")),o.setAttributeNS(null,"x1","50%"),o.setAttributeNS(null,"y1","50%"),this.svgElem_.appendChild(o),this.lineElem_=o;let a=t.createElement("div");a.classList.add(nu("m")),this.padElement.appendChild(a),this.markerElem_=a,e.value.emitter.on("change",this.onValueChange_),this.value=e.value,this.update_()}get allFocusableElements(){return[this.padElement]}update_(){let[t,e]=this.value.rawValue.getComponents(),i=this.maxValue_,n=eS(t,-i,+i,0,100),r=eS(e,-i,+i,0,100),s=this.invertsY_?100-r:r;this.lineElem_.setAttributeNS(null,"x2",`${n}%`),this.lineElem_.setAttributeNS(null,"y2",`${s}%`),this.markerElem_.style.left=`${n}%`,this.markerElem_.style.top=`${s}%`}onValueChange_(){this.update_()}onFoldableChange_(){this.update_()}}function nv(t,e,i){return[eP(e[0],eE(t)),eP(e[1],ek(t))*(i?1:-1)]}class nm{constructor(t,e){this.onPadKeyDown_=this.onPadKeyDown_.bind(this),this.onPadKeyUp_=this.onPadKeyUp_.bind(this),this.onPointerDown_=this.onPointerDown_.bind(this),this.onPointerMove_=this.onPointerMove_.bind(this),this.onPointerUp_=this.onPointerUp_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.baseSteps_=e.baseSteps,this.maxValue_=e.maxValue,this.invertsY_=e.invertsY,this.view=new nc(t,{invertsY:this.invertsY_,layout:e.layout,maxValue:this.maxValue_,value:this.value,viewProps:this.viewProps}),this.ptHandler_=new eM(this.view.padElement),this.ptHandler_.emitter.on("down",this.onPointerDown_),this.ptHandler_.emitter.on("move",this.onPointerMove_),this.ptHandler_.emitter.on("up",this.onPointerUp_),this.view.padElement.addEventListener("keydown",this.onPadKeyDown_),this.view.padElement.addEventListener("keyup",this.onPadKeyUp_)}handlePointerEvent_(t,e){if(!t.point)return;let i=this.maxValue_,n=eS(t.point.x,0,t.bounds.width,-i,+i),r=eS(this.invertsY_?t.bounds.height-t.point.y:t.point.y,0,t.bounds.height,-i,+i);this.value.setRawValue(new nl(n,r),e)}onPointerDown_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerMove_(t){this.handlePointerEvent_(t.data,{forceEmit:!1,last:!1})}onPointerUp_(t){this.handlePointerEvent_(t.data,{forceEmit:!0,last:!0})}onPadKeyDown_(t){eV(t.key)&&t.preventDefault();let[e,i]=nv(t,this.baseSteps_,this.invertsY_);(0!==e||0!==i)&&this.value.setRawValue(new nl(this.value.rawValue.x+e,this.value.rawValue.y+i),{forceEmit:!1,last:!1})}onPadKeyUp_(t){let[e,i]=nv(t,this.baseSteps_,this.invertsY_);(0!==e||0!==i)&&this.value.setRawValue(this.value.rawValue,{forceEmit:!0,last:!0})}}class nb{constructor(t,e){var i,n;this.onPopupChildBlur_=this.onPopupChildBlur_.bind(this),this.onPopupChildKeydown_=this.onPopupChildKeydown_.bind(this),this.onPadButtonBlur_=this.onPadButtonBlur_.bind(this),this.onPadButtonClick_=this.onPadButtonClick_.bind(this),this.value=e.value,this.viewProps=e.viewProps,this.foldable_=te.create(e.expanded),this.popC_="popup"===e.pickerLayout?new t6(t,{viewProps:this.viewProps}):null;let r=new nm(t,{baseSteps:[e.axes[0].baseStep,e.axes[1].baseStep],invertsY:e.invertsY,layout:e.pickerLayout,maxValue:e.maxValue,value:this.value,viewProps:this.viewProps});r.view.allFocusableElements.forEach(t=>{t.addEventListener("blur",this.onPopupChildBlur_),t.addEventListener("keydown",this.onPopupChildKeydown_)}),this.pickerC_=r,this.textC_=new nr(t,{assembly:np,axes:e.axes,parser:e.parser,value:this.value,viewProps:this.viewProps}),this.view=new nh(t,{expanded:this.foldable_.value("expanded"),pickerLayout:e.pickerLayout,viewProps:this.viewProps}),this.view.textElement.appendChild(this.textC_.view.element),null===(i=this.view.buttonElement)||void 0===i||i.addEventListener("blur",this.onPadButtonBlur_),null===(n=this.view.buttonElement)||void 0===n||n.addEventListener("click",this.onPadButtonClick_),this.popC_?(this.view.element.appendChild(this.popC_.view.element),this.popC_.view.element.appendChild(this.pickerC_.view.element),ey({primary:this.foldable_.value("expanded"),secondary:this.popC_.shows,forward:t=>t.rawValue,backward:(t,e)=>e.rawValue})):this.view.pickerElement&&(this.view.pickerElement.appendChild(this.pickerC_.view.element),tn(this.foldable_,this.view.pickerElement))}onPadButtonBlur_(t){if(!this.popC_)return;let e=this.view.element,i=t.relatedTarget;i&&e.contains(i)||(this.popC_.shows.rawValue=!1)}onPadButtonClick_(){this.foldable_.set("expanded",!this.foldable_.get("expanded")),this.foldable_.get("expanded")&&this.pickerC_.view.allFocusableElements[0].focus()}onPopupChildBlur_(t){if(!this.popC_)return;let e=this.popC_.view.element,i=Y(t);!(i&&e.contains(i))&&(!i||i!==this.view.buttonElement||F(e.ownerDocument))&&(this.popC_.shows.rawValue=!1)}onPopupChildKeydown_(t){this.popC_?"Escape"===t.key&&(this.popC_.shows.rawValue=!1):this.view.pickerElement&&"Escape"===t.key&&this.view.buttonElement.focus()}}class n_{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}getComponents(){return[this.x,this.y,this.z]}static isObject(t){if(l(t))return!1;let e=t.x,i=t.y,n=t.z;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z}toObject(){return{x:this.x,y:this.y,z:this.z}}}let ng={toComponents:t=>t.getComponents(),fromComponents:t=>new n_(...t)};function nf(t){return n_.isObject(t)?new n_(t.x,t.y,t.z):new n_}function nw(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z)}function nx(t,e){return{baseStep:eX(e),constraint:e,textProps:V.fromObject({draggingScale:eQ(e,t),formatter:eg(eY(e,t))})}}let nC={id:"input-point3d",type:"input",accept:(t,e)=>{if(!n_.isObject(t))return null;let i=A(e,{x:S.optional.custom(ez),y:S.optional.custom(ez),z:S.optional.custom(ez)});return i?{initialValue:t,params:i}:null},binding:{reader:t=>nf,constraint:t=>{var e,i;return e=t.params,i=t.initialValue,new ne({assembly:ng,components:[nG("x"in e?e.x:void 0,i.x),nG("y"in e?e.y:void 0,i.y),nG("z"in e?e.z:void 0,i.z)]})},equals:n_.equals,writer:t=>nw},controller:t=>{let e=t.value,i=t.constraint;if(!(i instanceof ne))throw u.shouldNeverHappen();return new nr(t.document,{assembly:ng,axes:[nx(e.rawValue.x,i.components[0]),nx(e.rawValue.y,i.components[1]),nx(e.rawValue.z,i.components[2])],parser:em,value:e,viewProps:t.viewProps})}};class ny{constructor(t=0,e=0,i=0,n=0){this.x=t,this.y=e,this.z=i,this.w=n}getComponents(){return[this.x,this.y,this.z,this.w]}static isObject(t){if(l(t))return!1;let e=t.x,i=t.y,n=t.z,r=t.w;return"number"==typeof e&&"number"==typeof i&&"number"==typeof n&&"number"==typeof r}static equals(t,e){return t.x===e.x&&t.y===e.y&&t.z===e.z&&t.w===e.w}toObject(){return{x:this.x,y:this.y,z:this.z,w:this.w}}}let nP={toComponents:t=>t.getComponents(),fromComponents:t=>new ny(...t)};function nk(t){return ny.isObject(t)?new ny(t.x,t.y,t.z,t.w):new ny}function nE(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y),t.writeProperty("z",e.z),t.writeProperty("w",e.w)}let nV={id:"input-point4d",type:"input",accept:(t,e)=>{if(!ny.isObject(t))return null;let i=A(e,{x:S.optional.custom(ez),y:S.optional.custom(ez),z:S.optional.custom(ez),w:S.optional.custom(ez)});return i?{initialValue:t,params:i}:null},binding:{reader:t=>nk,constraint:t=>{var e,i;return e=t.params,i=t.initialValue,new ne({assembly:nP,components:[nG("x"in e?e.x:void 0,i.x),nG("y"in e?e.y:void 0,i.y),nG("z"in e?e.z:void 0,i.z),nG("w"in e?e.w:void 0,i.w)]})},equals:ny.equals,writer:t=>nE},controller:t=>{let e=t.value,i=t.constraint;if(!(i instanceof ne))throw u.shouldNeverHappen();return new nr(t.document,{assembly:nP,axes:e.rawValue.getComponents().map((t,e)=>{var n;return{baseStep:eX(n=i.components[e]),constraint:n,textProps:V.fromObject({draggingScale:eQ(n,t),formatter:eg(eY(n,t))})}}),parser:em,value:e,viewProps:t.viewProps})}},nL={id:"input-string",type:"input",accept:(t,e)=>{if("string"!=typeof t)return null;let i=A(e,{options:S.optional.custom(e$)});return i?{initialValue:t,params:i}:null},binding:{reader:t=>ex,constraint:t=>(function(t){let e=[],i=eG(t.options);return i&&e.push(i),new tG(e)})(t.params),writer:t=>eF},controller:t=>{let e=t.document,i=t.value,n=t.constraint,r=n&&tY(n,tQ);return r?new t1(e,{props:new V({options:r.values.value("options")}),value:i,viewProps:t.viewProps}):new t3(e,{parser:t=>t,props:V.fromObject({formatter:eC}),value:i,viewProps:t.viewProps})}},nM={monitor:{defaultInterval:200,defaultLineCount:3}},nS=b("mll");class nA{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(nS()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("textarea");i.classList.add(nS("i")),i.style.height=`calc(var(--bld-us) * ${e.lineCount})`,i.readOnly=!0,e.viewProps.bindDisabled(i),this.element.appendChild(i),this.textareaElem_=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){let t=this.textareaElem_,e=t.scrollTop===t.scrollHeight-t.clientHeight,i=[];this.value.rawValue.forEach(t=>{void 0!==t&&i.push(this.formatter_(t))}),t.textContent=i.join("\n"),e&&(t.scrollTop=t.scrollHeight)}onValueUpdate_(){this.update_()}}class nD{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new nA(t,{formatter:e.formatter,lineCount:e.lineCount,value:this.value,viewProps:this.viewProps})}}let nj=b("sgl");class nR{constructor(t,e){this.onValueUpdate_=this.onValueUpdate_.bind(this),this.formatter_=e.formatter,this.element=t.createElement("div"),this.element.classList.add(nj()),e.viewProps.bindClassModifiers(this.element);let i=t.createElement("input");i.classList.add(nj("i")),i.readOnly=!0,i.type="text",e.viewProps.bindDisabled(i),this.element.appendChild(i),this.inputElement=i,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}update_(){let t=this.value.rawValue,e=t[t.length-1];this.inputElement.value=void 0!==e?this.formatter_(e):""}onValueUpdate_(){this.update_()}}class nO{constructor(t,e){this.value=e.value,this.viewProps=e.viewProps,this.view=new nR(t,{formatter:e.formatter,value:this.value,viewProps:this.viewProps})}}let nI={id:"monitor-bool",type:"monitor",accept:(t,e)=>{if("boolean"!=typeof t)return null;let i=A(e,{lineCount:S.optional.number});return i?{initialValue:t,params:i}:null},binding:{reader:t=>t9},controller:t=>{var e;return 1===t.value.rawValue.length?new nO(t.document,{formatter:t7,value:t.value,viewProps:t.viewProps}):new nD(t.document,{formatter:t7,lineCount:null!==(e=t.params.lineCount)&&void 0!==e?e:nM.monitor.defaultLineCount,value:t.value,viewProps:t.viewProps})}},nN=b("grl");class nK{constructor(t,e){this.onCursorChange_=this.onCursorChange_.bind(this),this.onValueUpdate_=this.onValueUpdate_.bind(this),this.element=t.createElement("div"),this.element.classList.add(nN()),e.viewProps.bindClassModifiers(this.element),this.formatter_=e.formatter,this.props_=e.props,this.cursor_=e.cursor,this.cursor_.emitter.on("change",this.onCursorChange_);let i=t.createElementNS(B,"svg");i.classList.add(nN("g")),i.style.height=`calc(var(--bld-us) * ${e.lineCount})`,this.element.appendChild(i),this.svgElem_=i;let n=t.createElementNS(B,"polyline");this.svgElem_.appendChild(n),this.lineElem_=n;let r=t.createElement("div");r.classList.add(nN("t"),b("tt")()),this.element.appendChild(r),this.tooltipElem_=r,e.value.emitter.on("change",this.onValueUpdate_),this.value=e.value,this.update_()}get graphElement(){return this.svgElem_}update_(){let t=this.svgElem_.getBoundingClientRect(),e=this.value.rawValue.length-1,i=this.props_.get("minValue"),n=this.props_.get("maxValue"),r=[];this.value.rawValue.forEach((s,o)=>{if(void 0===s)return;let a=eS(o,0,e,0,t.width),l=eS(s,i,n,t.height,0);r.push([a,l].join(","))}),this.lineElem_.setAttributeNS(null,"points",r.join(" "));let s=this.tooltipElem_,o=this.value.rawValue[this.cursor_.rawValue];if(void 0===o){s.classList.remove(nN("t","a"));return}let a=eS(this.cursor_.rawValue,0,e,0,t.width),l=eS(o,i,n,t.height,0);s.style.left=`${a}px`,s.style.top=`${l}px`,s.textContent=`${this.formatter_(o)}`,s.classList.contains(nN("t","a"))||(s.classList.add(nN("t","a"),nN("t","in")),T(s),s.classList.remove(nN("t","in")))}onValueUpdate_(){this.update_()}onCursorChange_(){this.update_()}}class nU{constructor(t,e){if(this.onGraphMouseMove_=this.onGraphMouseMove_.bind(this),this.onGraphMouseLeave_=this.onGraphMouseLeave_.bind(this),this.onGraphPointerDown_=this.onGraphPointerDown_.bind(this),this.onGraphPointerMove_=this.onGraphPointerMove_.bind(this),this.onGraphPointerUp_=this.onGraphPointerUp_.bind(this),this.props_=e.props,this.value=e.value,this.viewProps=e.viewProps,this.cursor_=E(-1),this.view=new nK(t,{cursor:this.cursor_,formatter:e.formatter,lineCount:e.lineCount,props:this.props_,value:this.value,viewProps:this.viewProps}),F(t)){let t=new eM(this.view.element);t.emitter.on("down",this.onGraphPointerDown_),t.emitter.on("move",this.onGraphPointerMove_),t.emitter.on("up",this.onGraphPointerUp_)}else this.view.element.addEventListener("mousemove",this.onGraphMouseMove_),this.view.element.addEventListener("mouseleave",this.onGraphMouseLeave_)}onGraphMouseLeave_(){this.cursor_.rawValue=-1}onGraphMouseMove_(t){let e=this.view.element.getBoundingClientRect();this.cursor_.rawValue=Math.floor(eS(t.offsetX,0,e.width,0,this.value.rawValue.length))}onGraphPointerDown_(t){this.onGraphPointerMove_(t)}onGraphPointerMove_(t){if(!t.data.point){this.cursor_.rawValue=-1;return}this.cursor_.rawValue=Math.floor(eS(t.data.point.x,0,t.data.bounds.width,0,this.value.rawValue.length))}onGraphPointerUp_(){this.cursor_.rawValue=-1}}function nB(t){return"format"in t&&!l(t.format)?t.format:eg(2)}function nT(t){return"view"in t&&"graph"===t.view}let nF={id:"monitor-number",type:"monitor",accept:(t,e)=>{if("number"!=typeof t)return null;let i=A(e,{format:S.optional.function,lineCount:S.optional.number,max:S.optional.number,min:S.optional.number,view:S.optional.string});return i?{initialValue:t,params:i}:null},binding:{defaultBufferSize:t=>nT(t)?64:1,reader:t=>eb},controller:t=>{var e,i,n,r;return nT(t.params)?new nU(t.document,{formatter:nB(t.params),lineCount:null!==(e=t.params.lineCount)&&void 0!==e?e:nM.monitor.defaultLineCount,props:V.fromObject({maxValue:null!==(i="max"in t.params?t.params.max:null)&&void 0!==i?i:100,minValue:null!==(n="min"in t.params?t.params.min:null)&&void 0!==n?n:0}),value:t.value,viewProps:t.viewProps}):1===t.value.rawValue.length?new nO(t.document,{formatter:nB(t.params),value:t.value,viewProps:t.viewProps}):new nD(t.document,{formatter:nB(t.params),lineCount:null!==(r=t.params.lineCount)&&void 0!==r?r:nM.monitor.defaultLineCount,value:t.value,viewProps:t.viewProps})}},n$={id:"monitor-string",type:"monitor",accept:(t,e)=>{if("string"!=typeof t)return null;let i=A(e,{lineCount:S.optional.number,multiline:S.optional.boolean});return i?{initialValue:t,params:i}:null},binding:{reader:t=>ex},controller:t=>{var e;let i=t.value;return i.rawValue.length>1||"multiline"in t.params&&t.params.multiline?new nD(t.document,{formatter:eC,lineCount:null!==(e=t.params.lineCount)&&void 0!==e?e:nM.monitor.defaultLineCount,value:i,viewProps:t.viewProps}):new nO(t.document,{formatter:eC,value:i,viewProps:t.viewProps})}};class nH{constructor(){this.pluginsMap_={blades:[],inputs:[],monitors:[]}}getAll(){return[...this.pluginsMap_.blades,...this.pluginsMap_.inputs,...this.pluginsMap_.monitors]}register(t){"blade"===t.type?this.pluginsMap_.blades.unshift(t):"input"===t.type?this.pluginsMap_.inputs.unshift(t):"monitor"===t.type&&this.pluginsMap_.monitors.unshift(t)}createInput(t,e,i){if(l(e.read()))throw new u({context:{key:e.key},type:"nomatchingcontroller"});let n=this.pluginsMap_.inputs.reduce((n,r)=>null!=n?n:function(t,e){var i;let n=t.accept(e.target.read(),e.params);if(l(n))return null;let r={target:e.target,initialValue:n.initialValue,params:n.params},s=t.binding.reader(r),o=t.binding.constraint?t.binding.constraint(r):void 0,a=E(s(n.initialValue),{constraint:o,equals:t.binding.equals}),p=new tH({reader:s,target:e.target,value:a,writer:t.binding.writer(r)}),d=S.optional.boolean(e.params.disabled).value,h=S.optional.boolean(e.params.hidden).value,u=t.controller({constraint:o,document:e.document,initialValue:n.initialValue,params:n.params,value:p.value,viewProps:I.create({disabled:d,hidden:h})});return new ta(e.document,{binding:p,blade:tt(),props:V.fromObject({label:"label"in e.params?null!==(i=S.optional.string(e.params.label).value)&&void 0!==i?i:null:e.target.key}),valueController:u})}(r,{document:t,target:e,params:i}),null);if(n)return n;throw new u({context:{key:e.key},type:"nomatchingcontroller"})}createMonitor(t,e,i){let n=this.pluginsMap_.monitors.reduce((n,r)=>null!=n?n:function(t,e){var i,n,r,s;let o=t.accept(e.target.read(),e.params);if(l(o))return null;let a={target:e.target,initialValue:o.initialValue,params:o.params},p=t.binding.reader(a),d=null!==(n=null!==(i=S.optional.number(e.params.bufferSize).value)&&void 0!==i?i:t.binding.defaultBufferSize&&t.binding.defaultBufferSize(o.params))&&void 0!==n?n:1,h=S.optional.number(e.params.interval).value,u=new tq({reader:p,target:e.target,ticker:(s=e.document,0===h?new tF:new t$(s,null!=h?h:nM.monitor.defaultInterval)),value:function(t){let e=[];return tz(e,t),E(e)}(d)}),c=S.optional.boolean(e.params.disabled).value,v=S.optional.boolean(e.params.hidden).value,m=t.controller({document:e.document,params:o.params,value:u.value,viewProps:I.create({disabled:c,hidden:v})});return new tp(e.document,{binding:u,blade:tt(),props:V.fromObject({label:"label"in e.params?null!==(r=S.optional.string(e.params.label).value)&&void 0!==r?r:null:e.target.key}),valueController:m})}(r,{document:t,params:i,target:e}),null);if(n)return n;throw new u({context:{key:e.key},type:"nomatchingcontroller"})}createBlade(t,e){let i=this.pluginsMap_.blades.reduce((i,n)=>null!=i?i:function(t,e){let i=t.accept(e.params);if(!i)return null;let n=S.optional.boolean(e.params.disabled).value,r=S.optional.boolean(e.params.hidden).value;return t.controller({blade:tt(),document:e.document,params:Object.assign(Object.assign({},i.params),{disabled:n,hidden:r}),viewProps:I.create({disabled:n,hidden:r})})}(n,{document:t,params:e}),null);if(!i)throw new u({type:"nomatchingview",context:{params:e}});return i}createBladeApi(t){if(t instanceof ta)return new to(t);if(t instanceof tp)return new tl(t);if(t instanceof tw)return new tc(t,this);let e=this.pluginsMap_.blades.reduce((e,i)=>null!=e?e:i.api({controller:t,pool:this}),null);if(!e)throw u.shouldNeverHappen();return e}}function nz(t){return nl.isObject(t)?new nl(t.x,t.y):new nl}function nq(t,e){t.writeProperty("x",e.x),t.writeProperty("y",e.y)}function nG(t,e){if(!t)return;let i=[],n=ns(t,e);n&&i.push(n);let r=no(t);return r&&i.push(r),new tG(i)}function nY(t,e){let[i,n]=t?function(t){let e=tY(t,tX);if(e)return[e.values.get("min"),e.values.get("max")];let i=tY(t,tJ);return i?[i.minValue,i.maxValue]:[void 0,void 0]}(t):[];return l(i)&&l(n)?Math.max(10*Math.abs(eX(t)),10*Math.abs(e)):Math.max(Math.abs(null!=i?i:0),Math.abs(null!=n?n:0))}function nX(t,e){return{baseStep:eX(e),constraint:e,textProps:V.fromObject({draggingScale:eQ(e,t),formatter:eg(eY(e,t))})}}let nQ={id:"input-point2d",type:"input",accept:(t,e)=>{if(!nl.isObject(t))return null;let i=A(e,{expanded:S.optional.boolean,picker:S.optional.custom(eH),x:S.optional.custom(ez),y:S.optional.object({inverted:S.optional.boolean,max:S.optional.number,min:S.optional.number,step:S.optional.number})});return i?{initialValue:t,params:i}:null},binding:{reader:t=>nz,constraint:t=>{var e,i;return e=t.params,i=t.initialValue,new ne({assembly:np,components:[nG("x"in e?e.x:void 0,i.x),nG("y"in e?e.y:void 0,i.y)]})},equals:nl.equals,writer:t=>nq},controller:t=>{let e=t.document,i=t.value,n=t.constraint;if(!(n instanceof ne))throw u.shouldNeverHappen();let r="expanded"in t.params?t.params.expanded:void 0,s="picker"in t.params?t.params.picker:void 0;return new nb(e,{axes:[nX(i.rawValue.x,n.components[0]),nX(i.rawValue.y,n.components[1])],expanded:null!=r&&r,invertsY:function(t){if(!("y"in t))return!1;let e=t.y;return!!e&&"inverted"in e&&!!e.inverted}(t.params),maxValue:function(t,e){let i=e instanceof ne?e.components[0]:void 0,n=e instanceof ne?e.components[1]:void 0;return Math.max(nY(i,t.x),nY(n,t.y))}(i.rawValue,n),parser:em,pickerLayout:null!=s?s:"popup",value:i,viewProps:t.viewProps})}};class nJ extends i{constructor(t){super(t),this.emitter_=new m,this.controller_.valueController.value.emitter.on("change",t=>{this.emitter_.emit("change",{event:new r(this,t.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}get options(){return this.controller_.valueController.props.get("options")}set options(t){this.controller_.valueController.props.set("options",t)}get value(){return this.controller_.valueController.value.rawValue}set value(t){this.controller_.valueController.value.rawValue=t}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}}class nW extends i{constructor(t){super(t),this.emitter_=new m,this.controller_.valueController.value.emitter.on("change",t=>{this.emitter_.emit("change",{event:new r(this,t.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}get maxValue(){return this.controller_.valueController.sliderController.props.get("maxValue")}set maxValue(t){this.controller_.valueController.sliderController.props.set("maxValue",t)}get minValue(){return this.controller_.valueController.sliderController.props.get("minValue")}set minValue(t){this.controller_.valueController.sliderController.props.set("minValue",t)}get value(){return this.controller_.valueController.value.rawValue}set value(t){this.controller_.valueController.value.rawValue=t}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}}class nZ extends i{constructor(t){super(t),this.emitter_=new m,this.controller_.valueController.value.emitter.on("change",t=>{this.emitter_.emit("change",{event:new r(this,t.rawValue)})})}get label(){return this.controller_.props.get("label")}set label(t){this.controller_.props.set("label",t)}get formatter(){return this.controller_.valueController.props.get("formatter")}set formatter(t){this.controller_.valueController.props.set("formatter",t)}get value(){return this.controller_.valueController.value.rawValue}set value(t){this.controller_.valueController.value.rawValue=t}on(t,e){let i=e.bind(this);return this.emitter_.on(t,t=>{i(t.event)}),this}}let n0={id:"list",type:"blade",accept(t){let e=A(t,{options:S.required.custom(e$),value:S.required.raw,view:S.required.constant("list"),label:S.optional.string});return e?{params:e}:null},controller(t){let e=new tQ(eq(t.params.options)),i=E(t.params.value,{constraint:e}),n=new t1(t.document,{props:new V({options:e.values.value("options")}),value:i,viewProps:t.viewProps});return new tk(t.document,{blade:t.blade,props:V.fromObject({label:t.params.label}),valueController:n})},api:t=>t.controller instanceof tk&&t.controller.valueController instanceof t1?new nJ(t.controller):null};class n1 extends tv{constructor(t,e){super(t,e)}get element(){return this.controller_.view.element}importPreset(t){(function(t,e){t.forEach(t=>{let i=e[t.target.presetKey];void 0!==i&&t.writer(t.target,t.reader(i))})})(this.controller_.rackController.rack.find(ta).map(t=>t.binding),t),this.refresh()}exportPreset(){return this.controller_.rackController.rack.find(ta).map(t=>t.binding.target).reduce((t,e)=>Object.assign(t,{[e.presetKey]:e.read()}),{})}refresh(){this.controller_.rackController.rack.find(ta).forEach(t=>{t.binding.read()}),this.controller_.rackController.rack.find(tp).forEach(t=>{t.binding.read()})}}class n2 extends ty{constructor(t,e){super(t,{expanded:e.expanded,blade:e.blade,props:e.props,root:!0,viewProps:e.viewProps})}}let n5={id:"slider",type:"blade",accept(t){let e=A(t,{max:S.required.number,min:S.required.number,view:S.required.constant("slider"),format:S.optional.function,label:S.optional.string,value:S.optional.number});return e?{params:e}:null},controller(t){var e,i;let n=null!==(e=t.params.value)&&void 0!==e?e:0,r=new tX({max:t.params.max,min:t.params.min}),s=new eT(t.document,{baseStep:1,parser:em,sliderProps:new V({maxValue:r.values.value("max"),minValue:r.values.value("min")}),textProps:V.fromObject({draggingScale:eQ(void 0,n),formatter:null!==(i=t.params.format)&&void 0!==i?i:e_}),value:E(n,{constraint:r}),viewProps:t.viewProps});return new tk(t.document,{blade:t.blade,props:V.fromObject({label:t.params.label}),valueController:s})},api:t=>t.controller instanceof tk&&t.controller.valueController instanceof eT?new nW(t.controller):null},n6={id:"text",type:"blade",accept(t){let e=A(t,{parse:S.required.function,value:S.required.raw,view:S.required.constant("text"),format:S.optional.function,label:S.optional.string});return e?{params:e}:null},controller(t){var e;let i=new t3(t.document,{parser:t.params.parse,props:V.fromObject({formatter:null!==(e=t.params.format)&&void 0!==e?e:t=>String(t)}),value:E(t.params.value),viewProps:t.viewProps});return new tk(t.document,{blade:t.blade,props:V.fromObject({label:t.params.label}),valueController:i})},api:t=>t.controller instanceof tk&&t.controller.valueController instanceof t3?new nZ(t.controller):null};function n4(t,e,i){if(t.querySelector(`style[data-tp-style=${e}]`))return;let n=t.createElement("style");n.dataset.tpStyle=e,n.textContent=i,t.head.appendChild(n)}class n8 extends n1{constructor(t){var e,i;let n=null!=t?t:{},r=null!==(e=n.document)&&void 0!==e?e:globalThis.document,s=function(){let t=new nH;return[nQ,nC,nV,nL,na,nt,i7,i9,e0,nI,n$,nF,W,tP,tS,tT].forEach(e=>{t.register(e)}),t}();super(new n2(r,{expanded:n.expanded,blade:tt(),props:V.fromObject({title:n.title}),viewProps:I.create()}),s),this.pool_=s,this.containerElem_=null!==(i=n.container)&&void 0!==i?i:function(t){let e=t.createElement("div");return e.classList.add(b("dfw")()),t.body&&t.body.appendChild(e),e}(r),this.containerElem_.appendChild(this.element),this.doc_=r,this.usesDefaultWrapper_=!n.container,this.setUpDefaultPlugins_()}get document(){if(!this.doc_)throw u.alreadyDisposed();return this.doc_}dispose(){let t=this.containerElem_;if(!t)throw u.alreadyDisposed();if(this.usesDefaultWrapper_){let e=t.parentElement;e&&e.removeChild(t)}this.containerElem_=null,this.doc_=null,super.dispose()}registerPlugin(t){("plugin"in t?[t.plugin]:"plugins"in t?t.plugins:[]).forEach(t=>{this.pool_.register(t),this.embedPluginStyle_(t)})}embedPluginStyle_(t){t.css&&n4(this.document,`plugin-${t.id}`,t.css)}setUpDefaultPlugins_(){n4(this.document,"default",'.tp-tbiv_b,.tp-coltxtv_ms,.tp-ckbv_i,.tp-rotv_b,.tp-fldv_b,.tp-mllv_i,.tp-sglv_i,.tp-grlv_g,.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw,.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;font-family:inherit;font-size:inherit;font-weight:inherit;margin:0;outline:none;padding:0}.tp-p2dv_b,.tp-btnv_b,.tp-lstv_s{background-color:var(--btn-bg);border-radius:var(--elm-br);color:var(--btn-fg);cursor:pointer;display:block;font-weight:bold;height:var(--bld-us);line-height:var(--bld-us);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tp-p2dv_b:hover,.tp-btnv_b:hover,.tp-lstv_s:hover{background-color:var(--btn-bg-h)}.tp-p2dv_b:focus,.tp-btnv_b:focus,.tp-lstv_s:focus{background-color:var(--btn-bg-f)}.tp-p2dv_b:active,.tp-btnv_b:active,.tp-lstv_s:active{background-color:var(--btn-bg-a)}.tp-p2dv_b:disabled,.tp-btnv_b:disabled,.tp-lstv_s:disabled{opacity:.5}.tp-txtv_i,.tp-p2dpv_p,.tp-colswv_sw{background-color:var(--in-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--in-fg);font-family:inherit;height:var(--bld-us);line-height:var(--bld-us);min-width:0;width:100%}.tp-txtv_i:hover,.tp-p2dpv_p:hover,.tp-colswv_sw:hover{background-color:var(--in-bg-h)}.tp-txtv_i:focus,.tp-p2dpv_p:focus,.tp-colswv_sw:focus{background-color:var(--in-bg-f)}.tp-txtv_i:active,.tp-p2dpv_p:active,.tp-colswv_sw:active{background-color:var(--in-bg-a)}.tp-txtv_i:disabled,.tp-p2dpv_p:disabled,.tp-colswv_sw:disabled{opacity:.5}.tp-mllv_i,.tp-sglv_i,.tp-grlv_g{background-color:var(--mo-bg);border-radius:var(--elm-br);box-sizing:border-box;color:var(--mo-fg);height:var(--bld-us);scrollbar-color:currentColor rgba(0,0,0,0);scrollbar-width:thin;width:100%}.tp-mllv_i::-webkit-scrollbar,.tp-sglv_i::-webkit-scrollbar,.tp-grlv_g::-webkit-scrollbar{height:8px;width:8px}.tp-mllv_i::-webkit-scrollbar-corner,.tp-sglv_i::-webkit-scrollbar-corner,.tp-grlv_g::-webkit-scrollbar-corner{background-color:rgba(0,0,0,0)}.tp-mllv_i::-webkit-scrollbar-thumb,.tp-sglv_i::-webkit-scrollbar-thumb,.tp-grlv_g::-webkit-scrollbar-thumb{background-clip:padding-box;background-color:currentColor;border:rgba(0,0,0,0) solid 2px;border-radius:4px}.tp-rotv{--font-family: var(--tp-font-family, Roboto Mono, Source Code Pro, Menlo, Courier, monospace);--bs-br: var(--tp-base-border-radius, 6px);--cnt-h-p: var(--tp-container-horizontal-padding, 4px);--cnt-v-p: var(--tp-container-vertical-padding, 4px);--elm-br: var(--tp-element-border-radius, 2px);--bld-s: var(--tp-blade-spacing, 4px);--bld-us: var(--tp-blade-unit-size, 20px);--bs-bg: var(--tp-base-background-color, hsl(230, 7%, 17%));--bs-sh: var(--tp-base-shadow-color, rgba(0, 0, 0, 0.2));--btn-bg: var(--tp-button-background-color, hsl(230, 7%, 70%));--btn-bg-a: var(--tp-button-background-color-active, #d6d7db);--btn-bg-f: var(--tp-button-background-color-focus, #c8cad0);--btn-bg-h: var(--tp-button-background-color-hover, #bbbcc4);--btn-fg: var(--tp-button-foreground-color, hsl(230, 7%, 17%));--cnt-bg: var(--tp-container-background-color, rgba(187, 188, 196, 0.1));--cnt-bg-a: var(--tp-container-background-color-active, rgba(187, 188, 196, 0.25));--cnt-bg-f: var(--tp-container-background-color-focus, rgba(187, 188, 196, 0.2));--cnt-bg-h: var(--tp-container-background-color-hover, rgba(187, 188, 196, 0.15));--cnt-fg: var(--tp-container-foreground-color, hsl(230, 7%, 75%));--in-bg: var(--tp-input-background-color, rgba(187, 188, 196, 0.1));--in-bg-a: var(--tp-input-background-color-active, rgba(187, 188, 196, 0.25));--in-bg-f: var(--tp-input-background-color-focus, rgba(187, 188, 196, 0.2));--in-bg-h: var(--tp-input-background-color-hover, rgba(187, 188, 196, 0.15));--in-fg: var(--tp-input-foreground-color, hsl(230, 7%, 75%));--lbl-fg: var(--tp-label-foreground-color, rgba(187, 188, 196, 0.7));--mo-bg: var(--tp-monitor-background-color, rgba(0, 0, 0, 0.2));--mo-fg: var(--tp-monitor-foreground-color, rgba(187, 188, 196, 0.7));--grv-fg: var(--tp-groove-foreground-color, rgba(187, 188, 196, 0.1))}.tp-rotv_c>.tp-cntv.tp-v-lst,.tp-tabv_c .tp-brkv>.tp-cntv.tp-v-lst,.tp-fldv_c>.tp-cntv.tp-v-lst{margin-bottom:calc(-1*var(--cnt-v-p))}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_c,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_c{border-bottom-left-radius:0}.tp-rotv_c>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-tabv_c .tp-brkv>.tp-fldv.tp-v-lst .tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-v-lst .tp-fldv_b{border-bottom-left-radius:0}.tp-rotv_c>*:not(.tp-v-fst),.tp-tabv_c .tp-brkv>*:not(.tp-v-fst),.tp-fldv_c>*:not(.tp-v-fst){margin-top:var(--bld-s)}.tp-rotv_c>.tp-sprv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-fst),.tp-fldv_c>.tp-sprv:not(.tp-v-fst),.tp-rotv_c>.tp-cntv:not(.tp-v-fst),.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-fst),.tp-fldv_c>.tp-cntv:not(.tp-v-fst){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-sprv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-sprv+*:not(.tp-v-hidden),.tp-rotv_c>.tp-cntv+*:not(.tp-v-hidden),.tp-tabv_c .tp-brkv>.tp-cntv+*:not(.tp-v-hidden),.tp-fldv_c>.tp-cntv+*:not(.tp-v-hidden){margin-top:var(--cnt-v-p)}.tp-rotv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-tabv_c .tp-brkv>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-fldv_c>.tp-sprv:not(.tp-v-hidden)+.tp-sprv,.tp-rotv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-tabv_c .tp-brkv>.tp-cntv:not(.tp-v-hidden)+.tp-cntv,.tp-fldv_c>.tp-cntv:not(.tp-v-hidden)+.tp-cntv{margin-top:0}.tp-tabv_c .tp-brkv>.tp-cntv,.tp-fldv_c>.tp-cntv{margin-left:4px}.tp-tabv_c .tp-brkv>.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-fldv>.tp-fldv_b{border-top-left-radius:var(--elm-br);border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-fldv.tp-fldv-expanded>.tp-fldv_b,.tp-fldv_c>.tp-fldv.tp-fldv-expanded>.tp-fldv_b{border-bottom-left-radius:0}.tp-tabv_c .tp-brkv .tp-fldv>.tp-fldv_c,.tp-fldv_c .tp-fldv>.tp-fldv_c{border-bottom-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-fldv>.tp-fldv_b,.tp-fldv_c>.tp-cntv+.tp-fldv>.tp-fldv_b{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-cntv+.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-cntv+.tp-tabv>.tp-tabv_t{border-top-left-radius:0}.tp-tabv_c .tp-brkv>.tp-tabv>.tp-tabv_t,.tp-fldv_c>.tp-tabv>.tp-tabv_t{border-top-left-radius:var(--elm-br)}.tp-tabv_c .tp-brkv .tp-tabv>.tp-tabv_c,.tp-fldv_c .tp-tabv>.tp-tabv_c{border-bottom-left-radius:var(--elm-br)}.tp-rotv_b,.tp-fldv_b{background-color:var(--cnt-bg);color:var(--cnt-fg);cursor:pointer;display:block;height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);overflow:hidden;padding-left:var(--cnt-h-p);padding-right:calc(4px + var(--bld-us) + var(--cnt-h-p));position:relative;text-align:left;text-overflow:ellipsis;white-space:nowrap;width:100%;transition:border-radius .2s ease-in-out .2s}.tp-rotv_b:hover,.tp-fldv_b:hover{background-color:var(--cnt-bg-h)}.tp-rotv_b:focus,.tp-fldv_b:focus{background-color:var(--cnt-bg-f)}.tp-rotv_b:active,.tp-fldv_b:active{background-color:var(--cnt-bg-a)}.tp-rotv_b:disabled,.tp-fldv_b:disabled{opacity:.5}.tp-rotv_m,.tp-fldv_m{background:linear-gradient(to left, var(--cnt-fg), var(--cnt-fg) 2px, transparent 2px, transparent 4px, var(--cnt-fg) 4px);border-radius:2px;bottom:0;content:"";display:block;height:6px;right:calc(var(--cnt-h-p) + (var(--bld-us) + 4px - 6px)/2 - 2px);margin:auto;opacity:.5;position:absolute;top:0;transform:rotate(90deg);transition:transform .2s ease-in-out;width:6px}.tp-rotv.tp-rotv-expanded .tp-rotv_m,.tp-fldv.tp-fldv-expanded>.tp-fldv_b>.tp-fldv_m{transform:none}.tp-rotv_c,.tp-fldv_c{box-sizing:border-box;height:0;opacity:0;overflow:hidden;padding-bottom:0;padding-top:0;position:relative;transition:height .2s ease-in-out,opacity .2s linear,padding .2s ease-in-out}.tp-rotv.tp-rotv-cpl:not(.tp-rotv-expanded) .tp-rotv_c,.tp-fldv.tp-fldv-cpl:not(.tp-fldv-expanded)>.tp-fldv_c{display:none}.tp-rotv.tp-rotv-expanded .tp-rotv_c,.tp-fldv.tp-fldv-expanded>.tp-fldv_c{opacity:1;padding-bottom:var(--cnt-v-p);padding-top:var(--cnt-v-p);transform:none;overflow:visible;transition:height .2s ease-in-out,opacity .2s linear .2s,padding .2s ease-in-out}.tp-lstv,.tp-coltxtv_m{position:relative}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m,.tp-coltxtv_mm{bottom:0;margin:auto;pointer-events:none;position:absolute;right:2px;top:0}.tp-lstv_m svg,.tp-coltxtv_mm svg{bottom:0;height:16px;margin:auto;position:absolute;right:0;top:0;width:16px}.tp-lstv_m svg path,.tp-coltxtv_mm svg path{fill:currentColor}.tp-pndtxtv,.tp-coltxtv_w{display:flex}.tp-pndtxtv_a,.tp-coltxtv_c{width:100%}.tp-pndtxtv_a+.tp-pndtxtv_a,.tp-coltxtv_c+.tp-pndtxtv_a,.tp-pndtxtv_a+.tp-coltxtv_c,.tp-coltxtv_c+.tp-coltxtv_c{margin-left:2px}.tp-btnv_b{width:100%}.tp-btnv_t{text-align:center}.tp-ckbv_l{display:block;position:relative}.tp-ckbv_i{left:0;opacity:0;position:absolute;top:0}.tp-ckbv_w{background-color:var(--in-bg);border-radius:var(--elm-br);cursor:pointer;display:block;height:var(--bld-us);position:relative;width:var(--bld-us)}.tp-ckbv_w svg{bottom:0;display:block;height:16px;left:0;margin:auto;opacity:0;position:absolute;right:0;top:0;width:16px}.tp-ckbv_w svg path{fill:none;stroke:var(--in-fg);stroke-width:2}.tp-ckbv_i:hover+.tp-ckbv_w{background-color:var(--in-bg-h)}.tp-ckbv_i:focus+.tp-ckbv_w{background-color:var(--in-bg-f)}.tp-ckbv_i:active+.tp-ckbv_w{background-color:var(--in-bg-a)}.tp-ckbv_i:checked+.tp-ckbv_w svg{opacity:1}.tp-ckbv.tp-v-disabled .tp-ckbv_w{opacity:.5}.tp-colv{position:relative}.tp-colv_h{display:flex}.tp-colv_s{flex-grow:0;flex-shrink:0;width:var(--bld-us)}.tp-colv_t{flex:1;margin-left:4px}.tp-colv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-colv.tp-colv-expanded.tp-colv-cpl .tp-colv_p{overflow:visible}.tp-colv.tp-colv-expanded .tp-colv_p{margin-top:var(--bld-s);opacity:1}.tp-colv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-colpv_h,.tp-colpv_ap{margin-left:6px;margin-right:6px}.tp-colpv_h{margin-top:var(--bld-s)}.tp-colpv_rgb{display:flex;margin-top:var(--bld-s);width:100%}.tp-colpv_a{display:flex;margin-top:var(--cnt-v-p);padding-top:calc(var(--cnt-v-p) + 2px);position:relative}.tp-colpv_a::before{background-color:var(--grv-fg);content:"";height:2px;left:calc(-1*var(--cnt-h-p));position:absolute;right:calc(-1*var(--cnt-h-p));top:0}.tp-colpv.tp-v-disabled .tp-colpv_a::before{opacity:.5}.tp-colpv_ap{align-items:center;display:flex;flex:3}.tp-colpv_at{flex:1;margin-left:4px}.tp-svpv{border-radius:var(--elm-br);outline:none;overflow:hidden;position:relative}.tp-svpv.tp-v-disabled{opacity:.5}.tp-svpv_c{cursor:crosshair;display:block;height:calc(var(--bld-us)*4);width:100%}.tp-svpv_m{border-radius:100%;border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;filter:drop-shadow(0 0 1px rgba(0, 0, 0, 0.3));height:12px;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;width:12px}.tp-svpv:focus .tp-svpv_m{border-color:#fff}.tp-hplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative}.tp-hplv.tp-v-disabled{opacity:.5}.tp-hplv_c{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAAABCAYAAABubagXAAAAQ0lEQVQoU2P8z8Dwn0GCgQEDi2OK/RBgYHjBgIpfovFh8j8YBIgzFGQxuqEgPhaDOT5gOhPkdCxOZeBg+IDFZZiGAgCaSSMYtcRHLgAAAABJRU5ErkJggg==);background-position:left top;background-repeat:no-repeat;background-size:100% 100%;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;position:absolute;top:50%;width:100%}.tp-hplv_m{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-shadow:0 0 2px rgba(0,0,0,.1);box-sizing:border-box;height:12px;left:50%;margin-left:-6px;margin-top:-6px;pointer-events:none;position:absolute;top:50%;width:12px}.tp-hplv:focus .tp-hplv_m{border-color:#fff}.tp-aplv{cursor:pointer;height:var(--bld-us);outline:none;position:relative;width:100%}.tp-aplv.tp-v-disabled{opacity:.5}.tp-aplv_b{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:4px 4px;background-position:0 0,2px 2px;border-radius:2px;display:block;height:4px;left:0;margin-top:-2px;overflow:hidden;position:absolute;top:50%;width:100%}.tp-aplv_c{bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv_m{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:12px 12px;background-position:0 0,6px 6px;border-radius:var(--elm-br);box-shadow:0 0 2px rgba(0,0,0,.1);height:12px;left:50%;margin-left:-6px;margin-top:-6px;overflow:hidden;pointer-events:none;position:absolute;top:50%;width:12px}.tp-aplv_p{border-radius:var(--elm-br);border:rgba(255,255,255,.75) solid 2px;box-sizing:border-box;bottom:0;left:0;position:absolute;right:0;top:0}.tp-aplv:focus .tp-aplv_p{border-color:#fff}.tp-colswv{background-color:#fff;background-image:linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%),linear-gradient(to top right, #ddd 25%, transparent 25%, transparent 75%, #ddd 75%);background-size:10px 10px;background-position:0 0,5px 5px;border-radius:var(--elm-br);overflow:hidden}.tp-colswv.tp-v-disabled{opacity:.5}.tp-colswv_sw{border-radius:0}.tp-colswv_b{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:rgba(0,0,0,0);border-width:0;cursor:pointer;display:block;height:var(--bld-us);left:0;margin:0;outline:none;padding:0;position:absolute;top:0;width:var(--bld-us)}.tp-colswv_b:focus::after{border:rgba(255,255,255,.75) solid 2px;border-radius:var(--elm-br);bottom:0;content:"";display:block;left:0;position:absolute;right:0;top:0}.tp-coltxtv{display:flex;width:100%}.tp-coltxtv_m{margin-right:4px}.tp-coltxtv_ms{border-radius:var(--elm-br);color:var(--lbl-fg);cursor:pointer;height:var(--bld-us);line-height:var(--bld-us);padding:0 18px 0 4px}.tp-coltxtv_ms:hover{background-color:var(--in-bg-h)}.tp-coltxtv_ms:focus{background-color:var(--in-bg-f)}.tp-coltxtv_ms:active{background-color:var(--in-bg-a)}.tp-coltxtv_mm{color:var(--lbl-fg)}.tp-coltxtv.tp-v-disabled .tp-coltxtv_mm{opacity:.5}.tp-coltxtv_w{flex:1}.tp-dfwv{position:absolute;top:8px;right:8px;width:256px}.tp-fldv{position:relative}.tp-fldv.tp-fldv-not .tp-fldv_b{display:none}.tp-fldv_t{padding-left:4px}.tp-fldv_b:disabled .tp-fldv_m{display:none}.tp-fldv_c{padding-left:4px}.tp-fldv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-fldv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-fldv_b:hover+.tp-fldv_i{color:var(--cnt-bg-h)}.tp-fldv_b:focus+.tp-fldv_i{color:var(--cnt-bg-f)}.tp-fldv_b:active+.tp-fldv_i{color:var(--cnt-bg-a)}.tp-fldv.tp-v-disabled>.tp-fldv_i{opacity:.5}.tp-grlv{position:relative}.tp-grlv_g{display:block;height:calc(var(--bld-us)*3)}.tp-grlv_g polyline{fill:none;stroke:var(--mo-fg);stroke-linejoin:round}.tp-grlv_t{margin-top:-4px;transition:left .05s,top .05s;visibility:hidden}.tp-grlv_t.tp-grlv_t-a{visibility:visible}.tp-grlv_t.tp-grlv_t-in{transition:none}.tp-grlv.tp-v-disabled .tp-grlv_g{opacity:.5}.tp-grlv .tp-ttv{background-color:var(--mo-fg)}.tp-grlv .tp-ttv::before{border-top-color:var(--mo-fg)}.tp-lblv{align-items:center;display:flex;line-height:1.3;padding-left:var(--cnt-h-p);padding-right:var(--cnt-h-p)}.tp-lblv.tp-lblv-nol{display:block}.tp-lblv_l{color:var(--lbl-fg);flex:1;-webkit-hyphens:auto;hyphens:auto;overflow:hidden;padding-left:4px;padding-right:16px}.tp-lblv.tp-v-disabled .tp-lblv_l{opacity:.5}.tp-lblv.tp-lblv-nol .tp-lblv_l{display:none}.tp-lblv_v{align-self:flex-start;flex-grow:0;flex-shrink:0;width:160px}.tp-lblv.tp-lblv-nol .tp-lblv_v{width:100%}.tp-lstv_s{padding:0 20px 0 4px;width:100%}.tp-lstv_m{color:var(--btn-fg)}.tp-sglv_i{padding:0 4px}.tp-sglv.tp-v-disabled .tp-sglv_i{opacity:.5}.tp-mllv_i{display:block;height:calc(var(--bld-us)*3);line-height:var(--bld-us);padding:0 4px;resize:none;white-space:pre}.tp-mllv.tp-v-disabled .tp-mllv_i{opacity:.5}.tp-p2dv{position:relative}.tp-p2dv_h{display:flex}.tp-p2dv_b{height:var(--bld-us);margin-right:4px;position:relative;width:var(--bld-us)}.tp-p2dv_b svg{display:block;height:16px;left:50%;margin-left:-8px;margin-top:-8px;position:absolute;top:50%;width:16px}.tp-p2dv_b svg path{stroke:currentColor;stroke-width:2}.tp-p2dv_b svg circle{fill:currentColor}.tp-p2dv_t{flex:1}.tp-p2dv_p{height:0;margin-top:0;opacity:0;overflow:hidden;transition:height .2s ease-in-out,opacity .2s linear,margin .2s ease-in-out}.tp-p2dv.tp-p2dv-expanded .tp-p2dv_p{margin-top:var(--bld-s);opacity:1}.tp-p2dv .tp-popv{left:calc(-1*var(--cnt-h-p));right:calc(-1*var(--cnt-h-p));top:var(--bld-us)}.tp-p2dpv{padding-left:calc(var(--bld-us) + 4px)}.tp-p2dpv_p{cursor:crosshair;height:0;overflow:hidden;padding-bottom:100%;position:relative}.tp-p2dpv.tp-v-disabled .tp-p2dpv_p{opacity:.5}.tp-p2dpv_g{display:block;height:100%;left:0;pointer-events:none;position:absolute;top:0;width:100%}.tp-p2dpv_ax{opacity:.1;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_l{opacity:.5;stroke:var(--in-fg);stroke-dasharray:1}.tp-p2dpv_m{border:var(--in-fg) solid 1px;border-radius:50%;box-sizing:border-box;height:4px;margin-left:-2px;margin-top:-2px;position:absolute;width:4px}.tp-p2dpv_p:focus .tp-p2dpv_m{background-color:var(--in-fg);border-width:0}.tp-popv{background-color:var(--bs-bg);border-radius:6px;box-shadow:0 2px 4px var(--bs-sh);display:none;max-width:168px;padding:var(--cnt-v-p) var(--cnt-h-p);position:absolute;visibility:hidden;z-index:1000}.tp-popv.tp-popv-v{display:block;visibility:visible}.tp-sprv_r{background-color:var(--grv-fg);border-width:0;display:block;height:2px;margin:0;width:100%}.tp-sprv.tp-v-disabled .tp-sprv_r{opacity:.5}.tp-sldv.tp-v-disabled{opacity:.5}.tp-sldv_t{box-sizing:border-box;cursor:pointer;height:var(--bld-us);margin:0 6px;outline:none;position:relative}.tp-sldv_t::before{background-color:var(--in-bg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin:auto;position:absolute;right:0;top:0}.tp-sldv_k{height:100%;left:0;position:absolute;top:0}.tp-sldv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";display:block;height:2px;left:0;margin-bottom:auto;margin-top:auto;position:absolute;right:0;top:0}.tp-sldv_k::after{background-color:var(--btn-bg);border-radius:var(--elm-br);bottom:0;content:"";display:block;height:12px;margin-bottom:auto;margin-top:auto;position:absolute;right:-6px;top:0;width:12px}.tp-sldv_t:hover .tp-sldv_k::after{background-color:var(--btn-bg-h)}.tp-sldv_t:focus .tp-sldv_k::after{background-color:var(--btn-bg-f)}.tp-sldv_t:active .tp-sldv_k::after{background-color:var(--btn-bg-a)}.tp-sldtxtv{display:flex}.tp-sldtxtv_s{flex:2}.tp-sldtxtv_t{flex:1;margin-left:4px}.tp-tabv{position:relative}.tp-tabv_t{align-items:flex-end;color:var(--cnt-bg);display:flex;overflow:hidden;position:relative}.tp-tabv_t:hover{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus){color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active){color:var(--cnt-bg-a)}.tp-tabv_t::before{background-color:currentColor;bottom:0;content:"";height:2px;left:0;pointer-events:none;position:absolute;right:0}.tp-tabv.tp-v-disabled .tp-tabv_t::before{opacity:.5}.tp-tabv.tp-tabv-nop .tp-tabv_t{height:calc(var(--bld-us) + 4px);position:relative}.tp-tabv.tp-tabv-nop .tp-tabv_t::before{background-color:var(--cnt-bg);bottom:0;content:"";height:2px;left:0;position:absolute;right:0}.tp-tabv_c{padding-bottom:var(--cnt-v-p);padding-left:4px;padding-top:var(--cnt-v-p)}.tp-tabv_i{bottom:0;color:var(--cnt-bg);left:0;overflow:hidden;position:absolute;top:calc(var(--bld-us) + 4px);width:var(--bs-br)}.tp-tabv_i::before{background-color:currentColor;bottom:0;content:"";left:0;position:absolute;top:0;width:4px}.tp-tabv_t:hover+.tp-tabv_i{color:var(--cnt-bg-h)}.tp-tabv_t:has(*:focus)+.tp-tabv_i{color:var(--cnt-bg-f)}.tp-tabv_t:has(*:active)+.tp-tabv_i{color:var(--cnt-bg-a)}.tp-tabv.tp-v-disabled>.tp-tabv_i{opacity:.5}.tp-tbiv{flex:1;min-width:0;position:relative}.tp-tbiv+.tp-tbiv{margin-left:2px}.tp-tbiv+.tp-tbiv.tp-v-disabled::before{opacity:.5}.tp-tbiv_b{display:block;padding-left:calc(var(--cnt-h-p) + 4px);padding-right:calc(var(--cnt-h-p) + 4px);position:relative;width:100%}.tp-tbiv_b:disabled{opacity:.5}.tp-tbiv_b::before{background-color:var(--cnt-bg);bottom:2px;content:"";left:0;pointer-events:none;position:absolute;right:0;top:0}.tp-tbiv_b:hover::before{background-color:var(--cnt-bg-h)}.tp-tbiv_b:focus::before{background-color:var(--cnt-bg-f)}.tp-tbiv_b:active::before{background-color:var(--cnt-bg-a)}.tp-tbiv_t{color:var(--cnt-fg);height:calc(var(--bld-us) + 4px);line-height:calc(var(--bld-us) + 4px);opacity:.5;overflow:hidden;text-overflow:ellipsis}.tp-tbiv.tp-tbiv-sel .tp-tbiv_t{opacity:1}.tp-txtv{position:relative}.tp-txtv_i{padding:0 4px}.tp-txtv.tp-txtv-fst .tp-txtv_i{border-bottom-right-radius:0;border-top-right-radius:0}.tp-txtv.tp-txtv-mid .tp-txtv_i{border-radius:0}.tp-txtv.tp-txtv-lst .tp-txtv_i{border-bottom-left-radius:0;border-top-left-radius:0}.tp-txtv.tp-txtv-num .tp-txtv_i{text-align:right}.tp-txtv.tp-txtv-drg .tp-txtv_i{opacity:.3}.tp-txtv_k{cursor:pointer;height:100%;left:-3px;position:absolute;top:0;width:12px}.tp-txtv_k::before{background-color:var(--in-fg);border-radius:1px;bottom:0;content:"";height:calc(var(--bld-us) - 4px);left:50%;margin-bottom:auto;margin-left:-1px;margin-top:auto;opacity:.1;position:absolute;top:0;transition:border-radius .1s,height .1s,transform .1s,width .1s;width:2px}.tp-txtv_k:hover::before,.tp-txtv.tp-txtv-drg .tp-txtv_k::before{opacity:1}.tp-txtv.tp-txtv-drg .tp-txtv_k::before{border-radius:50%;height:4px;transform:translateX(-1px);width:4px}.tp-txtv_g{bottom:0;display:block;height:8px;left:50%;margin:auto;overflow:visible;pointer-events:none;position:absolute;top:0;visibility:hidden;width:100%}.tp-txtv.tp-txtv-drg .tp-txtv_g{visibility:visible}.tp-txtv_gb{fill:none;stroke:var(--in-fg);stroke-dasharray:1}.tp-txtv_gh{fill:none;stroke:var(--in-fg)}.tp-txtv .tp-ttv{margin-left:6px;visibility:hidden}.tp-txtv.tp-txtv-drg .tp-ttv{visibility:visible}.tp-ttv{background-color:var(--in-fg);border-radius:var(--elm-br);color:var(--bs-bg);padding:2px 4px;pointer-events:none;position:absolute;transform:translate(-50%, -100%)}.tp-ttv::before{border-color:var(--in-fg) rgba(0,0,0,0) rgba(0,0,0,0) rgba(0,0,0,0);border-style:solid;border-width:2px;box-sizing:border-box;content:"";font-size:.9em;height:4px;left:50%;margin-left:-2px;position:absolute;top:100%;width:4px}.tp-rotv{background-color:var(--bs-bg);border-radius:var(--bs-br);box-shadow:0 2px 4px var(--bs-sh);font-family:var(--font-family);font-size:11px;font-weight:500;line-height:1;text-align:left}.tp-rotv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br);border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br);padding-left:calc(4px + var(--bld-us) + var(--cnt-h-p));text-align:center}.tp-rotv.tp-rotv-expanded .tp-rotv_b{border-bottom-left-radius:0;border-bottom-right-radius:0}.tp-rotv.tp-rotv-not .tp-rotv_b{display:none}.tp-rotv_b:disabled .tp-rotv_m{display:none}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst>.tp-fldv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv_c>.tp-fldv.tp-v-lst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c .tp-fldv.tp-v-vlst:not(.tp-fldv-expanded)>.tp-fldv_b{border-bottom-right-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-fldv.tp-v-fst>.tp-fldv_b{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_c{border-bottom-left-radius:var(--bs-br);border-bottom-right-radius:var(--bs-br)}.tp-rotv_c>.tp-tabv.tp-v-lst>.tp-tabv_i{border-bottom-left-radius:var(--bs-br)}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst{margin-top:calc(-1*var(--cnt-v-p))}.tp-rotv.tp-rotv-not .tp-rotv_c>.tp-tabv.tp-v-fst>.tp-tabv_t{border-top-left-radius:var(--bs-br);border-top-right-radius:var(--bs-br)}.tp-rotv.tp-v-disabled,.tp-rotv .tp-v-disabled{pointer-events:none}.tp-rotv.tp-v-hidden,.tp-rotv .tp-v-hidden{display:none}'),this.pool_.getAll().forEach(t=>{this.embedPluginStyle_(t)}),this.registerPlugin({plugins:[n5,n0,tT,n6]})}}let n3=new e("3.1.10");t.BladeApi=i,t.ButtonApi=v,t.FolderApi=tv,t.InputBindingApi=to,t.ListApi=nJ,t.MonitorBindingApi=tl,t.Pane=n8,t.SeparatorApi=tE,t.SliderApi=nW,t.TabApi=tI,t.TabPageApi=tO,t.TextApi=nZ,t.TpChangeEvent=r,t.VERSION=n3,Object.defineProperty(t,"__esModule",{value:!0})}(e)}}]); \ No newline at end of file diff --git a/.next/static/chunks/604a08ec-59af37265fb99b3d.js b/.next/static/chunks/604a08ec-59af37265fb99b3d.js deleted file mode 100644 index 595c780..0000000 --- a/.next/static/chunks/604a08ec-59af37265fb99b3d.js +++ /dev/null @@ -1,4 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[735],{78:function(t,e,r){r.d(e,{FM:function(){return Vector2},Lt:function(){return Vector4},P:function(){return Vector3},_f:function(){return Quaternion},jp:function(){return TmpVectors},y3:function(){return Matrix}});var i=r(5762),s=r(9806),o=r(4254),a=r(3048),n=r(4548),h=r(6030);let _ExtractAsInt=t=>parseInt(t.toString().replace(/\W/g,""));let Vector2=class Vector2{constructor(t=0,e=0){this.x=t,this.y=e}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let t=_ExtractAsInt(this.x),e=_ExtractAsInt(this.y);return 397*t^e}toArray(t,e=0){return t[e]=this.x,t[e+1]=this.y,this}fromArray(t,e=0){return Vector2.FromArrayToRef(t,e,this),this}asArray(){let t=[];return this.toArray(t,0),t}copyFrom(t){return this.x=t.x,this.y=t.y,this}copyFromFloats(t,e){return this.x=t,this.y=e,this}set(t,e){return this.copyFromFloats(t,e)}add(t){return new this.constructor(this.x+t.x,this.y+t.y)}addToRef(t,e){return e.x=this.x+t.x,e.y=this.y+t.y,e}addInPlace(t){return this.x+=t.x,this.y+=t.y,this}addVector3(t){return new this.constructor(this.x+t.x,this.y+t.y)}subtract(t){return new this.constructor(this.x-t.x,this.y-t.y)}subtractToRef(t,e){return e.x=this.x-t.x,e.y=this.y-t.y,e}subtractInPlace(t){return this.x-=t.x,this.y-=t.y,this}multiplyInPlace(t){return this.x*=t.x,this.y*=t.y,this}multiply(t){return new this.constructor(this.x*t.x,this.y*t.y)}multiplyToRef(t,e){return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByFloats(t,e){return new this.constructor(this.x*t,this.y*e)}divide(t){return new this.constructor(this.x/t.x,this.y/t.y)}divideToRef(t,e){return e.x=this.x/t.x,e.y=this.y/t.y,e}divideInPlace(t){return this.divideToRef(t,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(t){return t.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(t){return this.x*=t,this.y*=t,this}scale(t){let e=new this.constructor(0,0);return this.scaleToRef(t,e),e}scaleToRef(t,e){return e.x=this.x*t,e.y=this.y*t,e}scaleAndAddToRef(t,e){return e.x+=this.x*t,e.y+=this.y*t,e}equals(t){return t&&this.x===t.x&&this.y===t.y}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this.x,t.x,e)&&i.R.WithinEpsilon(this.y,t.y,e)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(t,e){let r=Math.cos(t),i=Math.sin(t),s=r*this.x-i*this.y,o=i*this.x+r*this.y;return e.x=s,e.y=o,e}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return Vector2.NormalizeToRef(this,this),this}clone(){return new this.constructor(this.x,this.y)}static Zero(){return new Vector2(0,0)}static One(){return new Vector2(1,1)}static Random(t=0,e=1){return new Vector2(i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static get ZeroReadOnly(){return Vector2._ZeroReadOnly}static FromArray(t,e=0){return new Vector2(t[e],t[e+1])}static FromArrayToRef(t,e,r){return r.x=t[e],r.y=t[e+1],r}static CatmullRom(t,e,r,i,s){let o=s*s,a=s*o,n=.5*(2*e.x+(-t.x+r.x)*s+(2*t.x-5*e.x+4*r.x-i.x)*o+(-t.x+3*e.x-3*r.x+i.x)*a),h=.5*(2*e.y+(-t.y+r.y)*s+(2*t.y-5*e.y+4*r.y-i.y)*o+(-t.y+3*e.y-3*r.y+i.y)*a);return new t.constructor(n,h)}static Clamp(t,e,r){let i=t.x;i=(i=i>r.x?r.x:i)r.y?r.y:s)e.x?t.x:e.x,i=t.y>e.y?t.y:e.y;return new t.constructor(r,i)}static Transform(t,e){let r=new t.constructor;return Vector2.TransformToRef(t,e,r),r}static TransformToRef(t,e,r){let i=e.m,s=t.x*i[0]+t.y*i[4]+i[12],o=t.x*i[1]+t.y*i[5]+i[13];return r.x=s,r.y=o,r}static PointInTriangle(t,e,r,i){let s=.5*(-r.y*i.x+e.y*(-r.x+i.x)+e.x*(r.y-i.y)+r.x*i.y),o=s<0?-1:1,a=(e.y*i.x-e.x*i.y+(i.y-e.y)*t.x+(e.x-i.x)*t.y)*o,n=(e.x*r.y-e.y*r.x+(e.y-r.y)*t.x+(r.x-e.x)*t.y)*o;return a>0&&n>0&&a+n<2*s*o}static Distance(t,e){return Math.sqrt(Vector2.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t.x-e.x,i=t.y-e.y;return r*r+i*i}static Center(t,e){let r=new t.constructor;return Vector2.CenterToRef(t,e,r)}static CenterToRef(t,e,r){return r.copyFromFloats((t.x+e.x)/2,(t.y+e.y)/2)}static DistanceOfPointFromSegment(t,e,r){let i=Vector2.DistanceSquared(e,r);if(0===i)return Vector2.Distance(t,e);let s=r.subtract(e),o=Math.max(0,Math.min(1,Vector2.Dot(t.subtract(e),s)/i)),a=e.add(s.multiplyByFloats(o,o));return Vector2.Distance(t,a)}};Vector2._ZeroReadOnly=Vector2.Zero();let Vector3=class Vector3{get x(){return this._x}set x(t){this._x=t,this._isDirty=!0}get y(){return this._y}set y(t){this._y=t,this._isDirty=!0}get z(){return this._z}set z(t){this._z=t,this._isDirty=!0}constructor(t=0,e=0,r=0){this._isDirty=!0,this._x=t,this._y=e,this._z=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let t=_ExtractAsInt(this._x),e=_ExtractAsInt(this._y),r=_ExtractAsInt(this._z),i=t;return 397*(i=397*i^e)^r}asArray(){let t=[];return this.toArray(t,0),t}toArray(t,e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,this}fromArray(t,e=0){return Vector3.FromArrayToRef(t,e,this),this}toQuaternion(){return Quaternion.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(t){return this.addInPlaceFromFloats(t._x,t._y,t._z)}addInPlaceFromFloats(t,e,r){return this._x+=t,this._y+=e,this._z+=r,this._isDirty=!0,this}add(t){return new this.constructor(this._x+t._x,this._y+t._y,this._z+t._z)}addToRef(t,e){return e.copyFromFloats(this._x+t._x,this._y+t._y,this._z+t._z)}subtractInPlace(t){return this._x-=t._x,this._y-=t._y,this._z-=t._z,this._isDirty=!0,this}subtract(t){return new this.constructor(this._x-t._x,this._y-t._y,this._z-t._z)}subtractToRef(t,e){return this.subtractFromFloatsToRef(t._x,t._y,t._z,e)}subtractFromFloats(t,e,r){return new this.constructor(this._x-t,this._y-e,this._z-r)}subtractFromFloatsToRef(t,e,r,i){return i.copyFromFloats(this._x-t,this._y-e,this._z-r)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(t){return t.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(t){return this._x*=t,this._y*=t,this._z*=t,this._isDirty=!0,this}scale(t){return new this.constructor(this._x*t,this._y*t,this._z*t)}scaleToRef(t,e){return e.copyFromFloats(this._x*t,this._y*t,this._z*t)}getNormalToRef(t){let e=this.length(),r=Math.acos(this.y/e),i=Math.atan2(this.z,this.x);r>Math.PI/2?r-=Math.PI/2:r+=Math.PI/2;let s=e*Math.sin(r)*Math.cos(i),o=e*Math.cos(r),a=e*Math.sin(r)*Math.sin(i);return t.set(s,o,a),t}applyRotationQuaternionToRef(t,e){let r=this._x,i=this._y,s=this._z,o=t._x,a=t._y,n=t._z,h=t._w,c=2*(a*s-n*i),_=2*(n*r-o*s),l=2*(o*i-a*r);return e._x=r+h*c+a*l-n*_,e._y=i+h*_+n*c-o*l,e._z=s+h*l+o*_-a*c,e._isDirty=!0,e}applyRotationQuaternionInPlace(t){return this.applyRotationQuaternionToRef(t,this)}applyRotationQuaternion(t){return this.applyRotationQuaternionToRef(t,new this.constructor)}scaleAndAddToRef(t,e){return e.addInPlaceFromFloats(this._x*t,this._y*t,this._z*t)}projectOnPlane(t,e){let r=new this.constructor;return this.projectOnPlaneToRef(t,e,r),r}projectOnPlaneToRef(t,e,r){let i=t.normal,s=t.d,o=MathTmp.Vector3[0];this.subtractToRef(e,o),o.normalize();let a=Vector3.Dot(o,i);if(1e-10>Math.abs(a))r.setAll(1/0);else{let t=-(Vector3.Dot(e,i)+s)/a,n=o.scaleInPlace(t);e.addToRef(n,r)}return r}equals(t){return t&&this._x===t._x&&this._y===t._y&&this._z===t._z}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this._x,t._x,e)&&i.R.WithinEpsilon(this._y,t._y,e)&&i.R.WithinEpsilon(this._z,t._z,e)}equalsToFloats(t,e,r){return this._x===t&&this._y===e&&this._z===r}multiplyInPlace(t){return this._x*=t._x,this._y*=t._y,this._z*=t._z,this._isDirty=!0,this}multiply(t){return this.multiplyByFloats(t._x,t._y,t._z)}multiplyToRef(t,e){return e.copyFromFloats(this._x*t._x,this._y*t._y,this._z*t._z)}multiplyByFloats(t,e,r){return new this.constructor(this._x*t,this._y*e,this._z*r)}divide(t){return new this.constructor(this._x/t._x,this._y/t._y,this._z/t._z)}divideToRef(t,e){return e.copyFromFloats(this._x/t._x,this._y/t._y,this._z/t._z)}divideInPlace(t){return this.divideToRef(t,this)}minimizeInPlace(t){return this.minimizeInPlaceFromFloats(t._x,t._y,t._z)}maximizeInPlace(t){return this.maximizeInPlaceFromFloats(t._x,t._y,t._z)}minimizeInPlaceFromFloats(t,e,r){return tthis._x&&(this.x=t),e>this._y&&(this.y=e),r>this._z&&(this.z=r),this}isNonUniformWithinEpsilon(t){let e=Math.abs(this._x),r=Math.abs(this._y);if(!i.R.WithinEpsilon(e,r,t))return!0;let s=Math.abs(this._z);return!(i.R.WithinEpsilon(e,s,t)&&i.R.WithinEpsilon(r,s,t))}get isNonUniform(){let t=Math.abs(this._x),e=Math.abs(this._y);if(t!==e)return!0;let r=Math.abs(this._z);return t!==r}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}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(t){return"xyz"===(t=t.toLowerCase())||(MathTmp.Vector3[0].copyFrom(this),["x","y","z"].forEach((e,r)=>{this[e]=MathTmp.Vector3[0][t[r]]})),this}rotateByQuaternionToRef(t,e){return t.toRotationMatrix(MathTmp.Matrix[0]),Vector3.TransformCoordinatesToRef(this,MathTmp.Matrix[0],e),e}rotateByQuaternionAroundPointToRef(t,e,r){return this.subtractToRef(e,MathTmp.Vector3[0]),MathTmp.Vector3[0].rotateByQuaternionToRef(t,MathTmp.Vector3[0]),e.addToRef(MathTmp.Vector3[0],r),r}cross(t){let e=new this.constructor;return Vector3.CrossToRef(this,t,e)}normalizeFromLength(t){return 0===t||1===t?this:this.scaleInPlace(1/t)}normalizeToNew(){let t=new this.constructor(0,0,0);return this.normalizeToRef(t),t}normalizeToRef(t){let e=this.length();return 0===e||1===e?t.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/e,t)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(t){return this.copyFromFloats(t._x,t._y,t._z)}copyFromFloats(t,e,r){return this._x=t,this._y=e,this._z=r,this._isDirty=!0,this}set(t,e,r){return this.copyFromFloats(t,e,r)}setAll(t){return this._x=this._y=this._z=t,this._isDirty=!0,this}static GetClipFactor(t,e,r,i){let s=Vector3.Dot(t,r)-i,o=Vector3.Dot(e,r)-i;return s/(s-o)}static GetAngleBetweenVectors(t,e,r){let s=t.normalizeToRef(MathTmp.Vector3[1]),o=e.normalizeToRef(MathTmp.Vector3[2]),a=Vector3.Dot(s,o);a=i.R.Clamp(a,-1,1);let n=Math.acos(a),h=MathTmp.Vector3[3];return(Vector3.CrossToRef(s,o,h),Vector3.Dot(h,r)>0)?isNaN(n)?0:n:isNaN(n)?-Math.PI:-Math.acos(a)}static GetAngleBetweenVectorsOnPlane(t,e,r){MathTmp.Vector3[0].copyFrom(t);let s=MathTmp.Vector3[0];MathTmp.Vector3[1].copyFrom(e);let o=MathTmp.Vector3[1];MathTmp.Vector3[2].copyFrom(r);let a=MathTmp.Vector3[2],n=MathTmp.Vector3[3],h=MathTmp.Vector3[4];s.normalize(),o.normalize(),a.normalize(),Vector3.CrossToRef(a,s,n),Vector3.CrossToRef(n,a,h);let c=Math.atan2(Vector3.Dot(o,n),Vector3.Dot(o,h));return i.R.NormalizeRadians(c)}static PitchYawRollToMoveBetweenPointsToRef(t,e,r){let i=TmpVectors.Vector3[0];return e.subtractToRef(t,i),r._y=Math.atan2(i.x,i.z)||0,r._x=Math.atan2(Math.sqrt(i.x**2+i.z**2),i.y)||0,r._z=0,r._isDirty=!0,r}static PitchYawRollToMoveBetweenPoints(t,e){let r=Vector3.Zero();return Vector3.PitchYawRollToMoveBetweenPointsToRef(t,e,r)}static SlerpToRef(t,e,r,o){let a,n;r=i.R.Clamp(r,0,1);let h=MathTmp.Vector3[0],c=MathTmp.Vector3[1];h.copyFrom(t);let _=h.length();h.normalizeFromLength(_),c.copyFrom(e);let l=c.length();c.normalizeFromLength(l);let u=Vector3.Dot(h,c);if(u<1-s.kn){let t=Math.acos(u),e=1/Math.sin(t);a=Math.sin((1-r)*t)*e,n=Math.sin(r*t)*e}else a=1-r,n=r;return h.scaleInPlace(a),c.scaleInPlace(n),o.copyFrom(h).addInPlace(c),o.scaleInPlace(i.R.Lerp(_,l,r)),o}static SmoothToRef(t,e,r,i,s){return Vector3.SlerpToRef(t,e,0===i?1:r/i,s),s}static FromArray(t,e=0){return new Vector3(t[e],t[e+1],t[e+2])}static FromFloatArray(t,e){return Vector3.FromArray(t,e)}static FromArrayToRef(t,e,r){return r._x=t[e],r._y=t[e+1],r._z=t[e+2],r._isDirty=!0,r}static FromFloatArrayToRef(t,e,r){return Vector3.FromArrayToRef(t,e,r)}static FromFloatsToRef(t,e,r,i){return i.copyFromFloats(t,e,r),i}static Zero(){return new Vector3(0,0,0)}static One(){return new Vector3(1,1,1)}static Up(){return new Vector3(0,1,0)}static get UpReadOnly(){return Vector3._UpReadOnly}static get DownReadOnly(){return Vector3._DownReadOnly}static get RightReadOnly(){return Vector3._RightReadOnly}static get LeftReadOnly(){return Vector3._LeftReadOnly}static get LeftHandedForwardReadOnly(){return Vector3._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return Vector3._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return Vector3._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return Vector3._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return Vector3._ZeroReadOnly}static get OneReadOnly(){return Vector3._OneReadOnly}static Down(){return new Vector3(0,-1,0)}static Forward(t=!1){return new Vector3(0,0,t?-1:1)}static Backward(t=!1){return new Vector3(0,0,t?1:-1)}static Right(){return new Vector3(1,0,0)}static Left(){return new Vector3(-1,0,0)}static Random(t=0,e=1){return new Vector3(i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static TransformCoordinates(t,e){let r=Vector3.Zero();return Vector3.TransformCoordinatesToRef(t,e,r),r}static TransformCoordinatesToRef(t,e,r){return Vector3.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformCoordinatesFromFloatsToRef(t,e,r,i,s){let o=i.m,a=t*o[0]+e*o[4]+r*o[8]+o[12],n=t*o[1]+e*o[5]+r*o[9]+o[13],h=t*o[2]+e*o[6]+r*o[10]+o[14],c=1/(t*o[3]+e*o[7]+r*o[11]+o[15]);return s._x=a*c,s._y=n*c,s._z=h*c,s._isDirty=!0,s}static TransformNormal(t,e){let r=Vector3.Zero();return Vector3.TransformNormalToRef(t,e,r),r}static TransformNormalToRef(t,e,r){return this.TransformNormalFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformNormalFromFloatsToRef(t,e,r,i,s){let o=i.m;return s._x=t*o[0]+e*o[4]+r*o[8],s._y=t*o[1]+e*o[5]+r*o[9],s._z=t*o[2]+e*o[6]+r*o[10],s._isDirty=!0,s}static CatmullRom(t,e,r,i,s){let o=s*s,a=s*o,n=.5*(2*e._x+(-t._x+r._x)*s+(2*t._x-5*e._x+4*r._x-i._x)*o+(-t._x+3*e._x-3*r._x+i._x)*a),h=.5*(2*e._y+(-t._y+r._y)*s+(2*t._y-5*e._y+4*r._y-i._y)*o+(-t._y+3*e._y-3*r._y+i._y)*a),c=.5*(2*e._z+(-t._z+r._z)*s+(2*t._z-5*e._z+4*r._z-i._z)*o+(-t._z+3*e._z-3*r._z+i._z)*a);return new t.constructor(n,h,c)}static Clamp(t,e,r){let i=new t.constructor;return Vector3.ClampToRef(t,e,r,i),i}static ClampToRef(t,e,r,i){let s=t._x;s=(s=s>r._x?r._x:s)r._y?r._y:o)r._z?r._z:a)0&&D<0?(C.copyFrom(_),h=e,c=r):D>0&&P<0?(C.copyFrom(u),h=r,c=o):(C.copyFrom(l).scaleInPlace(-1),h=o,c=e);let L=MathTmp.Vector3[9],O=MathTmp.Vector3[4];h.subtractToRef(M,I),c.subtractToRef(M,L),Vector3.CrossToRef(I,L,O);let H=0>Vector3.Dot(O,y);if(!H)return a.copyFrom(M),Math.abs(d*p);let k=MathTmp.Vector3[5];Vector3.CrossToRef(C,O,k),k.normalize();let v=MathTmp.Vector3[9];v.copyFrom(h).subtractInPlace(M);let Q=v.length();if(Qthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(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(){let t=this.length();return 0===t?this:this.scaleInPlace(1/t)}toVector3(){return new Vector3(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}copyFromFloats(t,e,r,i){return this.x=t,this.y=e,this.z=r,this.w=i,this}set(t,e,r,i){return this.copyFromFloats(t,e,r,i)}setAll(t){return this.x=this.y=this.z=this.w=t,this}static FromArray(t,e){return e||(e=0),new Vector4(t[e],t[e+1],t[e+2],t[e+3])}static FromArrayToRef(t,e,r){return r.x=t[e],r.y=t[e+1],r.z=t[e+2],r.w=t[e+3],r}static FromFloatArrayToRef(t,e,r){return Vector4.FromArrayToRef(t,e,r),r}static FromFloatsToRef(t,e,r,i,s){return s.x=t,s.y=e,s.z=r,s.w=i,s}static Zero(){return new Vector4(0,0,0,0)}static One(){return new Vector4(1,1,1,1)}static Random(t=0,e=1){return new Vector4(i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static get ZeroReadOnly(){return Vector4._ZeroReadOnly}static Normalize(t){let e=Vector4.Zero();return Vector4.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){return e.copyFrom(t),e.normalize(),e}static Minimize(t,e){let r=new t.constructor;return r.copyFrom(t),r.minimizeInPlace(e),r}static Maximize(t,e){let r=new t.constructor;return r.copyFrom(t),r.maximizeInPlace(e),r}static Distance(t,e){return Math.sqrt(Vector4.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t.x-e.x,i=t.y-e.y,s=t.z-e.z,o=t.w-e.w;return r*r+i*i+s*s+o*o}static Center(t,e){return Vector4.CenterToRef(t,e,Vector4.Zero())}static CenterToRef(t,e,r){return r.copyFromFloats((t.x+e.x)/2,(t.y+e.y)/2,(t.z+e.z)/2,(t.w+e.w)/2)}static TransformCoordinates(t,e){let r=Vector4.Zero();return Vector4.TransformCoordinatesToRef(t,e,r),r}static TransformCoordinatesToRef(t,e,r){return Vector4.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformCoordinatesFromFloatsToRef(t,e,r,i,s){let o=i.m,a=t*o[0]+e*o[4]+r*o[8]+o[12],n=t*o[1]+e*o[5]+r*o[9]+o[13],h=t*o[2]+e*o[6]+r*o[10]+o[14],c=t*o[3]+e*o[7]+r*o[11]+o[15];return s.x=a,s.y=n,s.z=h,s.w=c,s}static TransformNormal(t,e){let r=new t.constructor;return Vector4.TransformNormalToRef(t,e,r),r}static TransformNormalToRef(t,e,r){let i=e.m,s=t.x*i[0]+t.y*i[4]+t.z*i[8],o=t.x*i[1]+t.y*i[5]+t.z*i[9],a=t.x*i[2]+t.y*i[6]+t.z*i[10];return r.x=s,r.y=o,r.z=a,r.w=t.w,r}static TransformNormalFromFloatsToRef(t,e,r,i,s,o){let a=s.m;return o.x=t*a[0]+e*a[4]+r*a[8],o.y=t*a[1]+e*a[5]+r*a[9],o.z=t*a[2]+e*a[6]+r*a[10],o.w=i,o}static FromVector3(t,e=0){return new Vector4(t._x,t._y,t._z,e)}};Vector4._ZeroReadOnly=Vector4.Zero();let Quaternion=class Quaternion{get x(){return this._x}set x(t){this._x=t,this._isDirty=!0}get y(){return this._y}set y(t){this._y=t,this._isDirty=!0}get z(){return this._z}set z(t){this._z=t,this._isDirty=!0}get w(){return this._w}set w(t){this._w=t,this._isDirty=!0}constructor(t=0,e=0,r=0,i=1){this._isDirty=!0,this._x=t,this._y=e,this._z=r,this._w=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let t=_ExtractAsInt(this._x),e=_ExtractAsInt(this._y),r=_ExtractAsInt(this._z),i=_ExtractAsInt(this._w),s=t;return 397*(s=397*(s=397*s^e)^r)^i}asArray(){return[this._x,this._y,this._z,this._w]}toArray(t,e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,this}equals(t){return t&&this._x===t._x&&this._y===t._y&&this._z===t._z&&this._w===t._w}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this._x,t._x,e)&&i.R.WithinEpsilon(this._y,t._y,e)&&i.R.WithinEpsilon(this._z,t._z,e)&&i.R.WithinEpsilon(this._w,t._w,e)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._w=t._w,this._isDirty=!0,this}copyFromFloats(t,e,r,i){return this._x=t,this._y=e,this._z=r,this._w=i,this._isDirty=!0,this}set(t,e,r,i){return this.copyFromFloats(t,e,r,i)}add(t){return new this.constructor(this._x+t._x,this._y+t._y,this._z+t._z,this._w+t._w)}addInPlace(t){return this._x+=t._x,this._y+=t._y,this._z+=t._z,this._w+=t._w,this._isDirty=!0,this}subtract(t){return new this.constructor(this._x-t._x,this._y-t._y,this._z-t._z,this._w-t._w)}subtractInPlace(t){return this._x-=t._x,this._y-=t._y,this._z-=t._z,this._w-=t._w,this._isDirty=!0,this}scale(t){return new this.constructor(this._x*t,this._y*t,this._z*t,this._w*t)}scaleToRef(t,e){return e._x=this._x*t,e._y=this._y*t,e._z=this._z*t,e._w=this._w*t,e._isDirty=!0,e}scaleInPlace(t){return this._x*=t,this._y*=t,this._z*=t,this._w*=t,this._isDirty=!0,this}scaleAndAddToRef(t,e){return e._x+=this._x*t,e._y+=this._y*t,e._z+=this._z*t,e._w+=this._w*t,e._isDirty=!0,e}multiply(t){let e=new this.constructor(0,0,0,1);return this.multiplyToRef(t,e),e}multiplyToRef(t,e){let r=this._x*t._w+this._y*t._z-this._z*t._y+this._w*t._x,i=-this._x*t._z+this._y*t._w+this._z*t._x+this._w*t._y,s=this._x*t._y-this._y*t._x+this._z*t._w+this._w*t._z,o=-this._x*t._x-this._y*t._y-this._z*t._z+this._w*t._w;return e.copyFromFloats(r,i,s,o),e}multiplyInPlace(t){return this.multiplyToRef(t,this),this}conjugateToRef(t){return t.copyFromFloats(-this._x,-this._y,-this._z,this._w),t}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){let t=this.conjugate(),e=this.lengthSquared();return 0==e||1==e||t.scaleInPlace(1/e),t}invertInPlace(){this.conjugateInPlace();let t=this.lengthSquared();return 0==t||1==t||this.scaleInPlace(1/t),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(){let t=this.length();return 0===t||this.scaleInPlace(1/t),this}normalizeToNew(){let t=this.length();return 0===t?this.clone():this.scale(1/t)}toEulerAngles(){let t=Vector3.Zero();return this.toEulerAnglesToRef(t),t}toEulerAnglesToRef(t){let e=this._z,r=this._x,i=this._y,s=this._w,o=i*e-r*s;if(o<-.4999999)t._y=2*Math.atan2(i,s),t._x=Math.PI/2,t._z=0,t._isDirty=!0;else if(o>.4999999)t._y=2*Math.atan2(i,s),t._x=-Math.PI/2,t._z=0,t._isDirty=!0;else{let a=s*s,n=e*e,h=r*r,c=i*i;t._z=Math.atan2(2*(r*i+e*s),-n-h+c+a),t._x=Math.asin(-2*o),t._y=Math.atan2(2*(e*r+i*s),n-h-c+a),t._isDirty=!0}return t}toRotationMatrix(t){return Matrix.FromQuaternionToRef(this,t),t}fromRotationMatrix(t){return Quaternion.FromRotationMatrixToRef(t,this),this}static FromRotationMatrix(t){let e=new Quaternion;return Quaternion.FromRotationMatrixToRef(t,e),e}static FromRotationMatrixToRef(t,e){let r;let i=t.m,s=i[0],o=i[4],a=i[8],n=i[1],h=i[5],c=i[9],_=i[2],l=i[6],u=i[10],y=s+h+u;return y>0?(r=.5/Math.sqrt(y+1),e._w=.25/r,e._x=(l-c)*r,e._y=(a-_)*r,e._z=(n-o)*r):s>h&&s>u?(r=2*Math.sqrt(1+s-h-u),e._w=(l-c)/r,e._x=.25*r,e._y=(o+n)/r,e._z=(a+_)/r):h>u?(r=2*Math.sqrt(1+h-s-u),e._w=(a-_)/r,e._x=(o+n)/r,e._y=.25*r,e._z=(c+l)/r):(r=2*Math.sqrt(1+u-s-h),e._w=(n-o)/r,e._x=(a+_)/r,e._y=(c+l)/r,e._z=.25*r),e._isDirty=!0,e}static Dot(t,e){return t._x*e._x+t._y*e._y+t._z*e._z+t._w*e._w}static AreClose(t,e,r=.1){let i=Quaternion.Dot(t,e);return 1-i*i<=r}static SmoothToRef(t,e,r,s,o){let a=0===s?1:r/s;return a=i.R.Clamp(a,0,1),Quaternion.SlerpToRef(t,e,a,o),o}static Zero(){return new Quaternion(0,0,0,0)}static Inverse(t){return new t.constructor(-t._x,-t._y,-t._z,t._w)}static InverseToRef(t,e){return e.set(-t._x,-t._y,-t._z,t._w),e}static Identity(){return new Quaternion(0,0,0,1)}static IsIdentity(t){return t&&0===t._x&&0===t._y&&0===t._z&&1===t._w}static RotationAxis(t,e){return Quaternion.RotationAxisToRef(t,e,new Quaternion)}static RotationAxisToRef(t,e,r){let i=Math.sin(e/2);return t.normalize(),r._w=Math.cos(e/2),r._x=t._x*i,r._y=t._y*i,r._z=t._z*i,r._isDirty=!0,r}static FromArray(t,e){return e||(e=0),new Quaternion(t[e],t[e+1],t[e+2],t[e+3])}static FromArrayToRef(t,e,r){return r._x=t[e],r._y=t[e+1],r._z=t[e+2],r._w=t[e+3],r._isDirty=!0,r}static FromEulerAngles(t,e,r){let i=new Quaternion;return Quaternion.RotationYawPitchRollToRef(e,t,r,i),i}static FromEulerAnglesToRef(t,e,r,i){return Quaternion.RotationYawPitchRollToRef(e,t,r,i),i}static FromEulerVector(t){let e=new Quaternion;return Quaternion.RotationYawPitchRollToRef(t._y,t._x,t._z,e),e}static FromEulerVectorToRef(t,e){return Quaternion.RotationYawPitchRollToRef(t._y,t._x,t._z,e),e}static FromUnitVectorsToRef(t,e,r,i=s.kn){let o=Vector3.Dot(t,e)+1;return oMath.abs(t.z)?r.set(-t.y,t.x,0,0):r.set(0,-t.z,t.y,0):(Vector3.CrossToRef(t,e,TmpVectors.Vector3[0]),r.set(TmpVectors.Vector3[0].x,TmpVectors.Vector3[0].y,TmpVectors.Vector3[0].z,o)),r.normalize()}static RotationYawPitchRoll(t,e,r){let i=new Quaternion;return Quaternion.RotationYawPitchRollToRef(t,e,r,i),i}static RotationYawPitchRollToRef(t,e,r,i){let s=.5*r,o=.5*e,a=.5*t,n=Math.sin(s),h=Math.cos(s),c=Math.sin(o),_=Math.cos(o),l=Math.sin(a),u=Math.cos(a);return i._x=u*c*h+l*_*n,i._y=l*_*h-u*c*n,i._z=u*_*n-l*c*h,i._w=u*_*h+l*c*n,i._isDirty=!0,i}static RotationAlphaBetaGamma(t,e,r){let i=new Quaternion;return Quaternion.RotationAlphaBetaGammaToRef(t,e,r,i),i}static RotationAlphaBetaGammaToRef(t,e,r,i){let s=(r+t)*.5,o=(r-t)*.5,a=.5*e;return i._x=Math.cos(o)*Math.sin(a),i._y=Math.sin(o)*Math.sin(a),i._z=Math.sin(s)*Math.cos(a),i._w=Math.cos(s)*Math.cos(a),i._isDirty=!0,i}static RotationQuaternionFromAxis(t,e,r){let i=new Quaternion(0,0,0,0);return Quaternion.RotationQuaternionFromAxisToRef(t,e,r,i),i}static RotationQuaternionFromAxisToRef(t,e,r,i){let s=MathTmp.Matrix[0];return Matrix.FromXYZAxesToRef(t.normalize(),e.normalize(),r.normalize(),s),Quaternion.FromRotationMatrixToRef(s,i),i}static FromLookDirectionLH(t,e){let r=new Quaternion;return Quaternion.FromLookDirectionLHToRef(t,e,r),r}static FromLookDirectionLHToRef(t,e,r){let i=MathTmp.Matrix[0];return Matrix.LookDirectionLHToRef(t,e,i),Quaternion.FromRotationMatrixToRef(i,r),r}static FromLookDirectionRH(t,e){let r=new Quaternion;return Quaternion.FromLookDirectionRHToRef(t,e,r),r}static FromLookDirectionRHToRef(t,e,r){let i=MathTmp.Matrix[0];return Matrix.LookDirectionRHToRef(t,e,i),Quaternion.FromRotationMatrixToRef(i,r)}static Slerp(t,e,r){let i=Quaternion.Identity();return Quaternion.SlerpToRef(t,e,r,i),i}static SlerpToRef(t,e,r,i){let s,o;let a=t._x*e._x+t._y*e._y+t._z*e._z+t._w*e._w,n=!1;if(a<0&&(n=!0,a=-a),a>.999999)o=1-r,s=n?-r:r;else{let t=Math.acos(a),e=1/Math.sin(t);o=Math.sin((1-r)*t)*e,s=n?-Math.sin(r*t)*e:Math.sin(r*t)*e}return i._x=o*t._x+s*e._x,i._y=o*t._y+s*e._y,i._z=o*t._z+s*e._z,i._w=o*t._w+s*e._w,i._isDirty=!0,i}static Hermite(t,e,r,i,s){let o=s*s,a=s*o,n=2*a-3*o+1,h=-2*a+3*o,c=a-2*o+s,_=a-o,l=t._x*n+r._x*h+e._x*c+i._x*_,u=t._y*n+r._y*h+e._y*c+i._y*_,y=t._z*n+r._z*h+e._z*c+i._z*_,m=t._w*n+r._w*h+e._w*c+i._w*_;return new t.constructor(l,u,y,m)}static Hermite1stDerivative(t,e,r,i,s){let o=new t.constructor;return this.Hermite1stDerivativeToRef(t,e,r,i,s,o),o}static Hermite1stDerivativeToRef(t,e,r,i,s,o){let a=s*s;return o._x=(a-s)*6*t._x+(3*a-4*s+1)*e._x+(-a+s)*6*r._x+(3*a-2*s)*i._x,o._y=(a-s)*6*t._y+(3*a-4*s+1)*e._y+(-a+s)*6*r._y+(3*a-2*s)*i._y,o._z=(a-s)*6*t._z+(3*a-4*s+1)*e._z+(-a+s)*6*r._z+(3*a-2*s)*i._z,o._w=(a-s)*6*t._w+(3*a-4*s+1)*e._w+(-a+s)*6*r._w+(3*a-2*s)*i._w,o._isDirty=!0,o}};let Matrix=class Matrix{static get Use64Bits(){return n.Z.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=Matrix._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(t,e=!1,r=!1,i=!0){this._isIdentity=t,this._isIdentity3x2=t||r,this._isIdentityDirty=!this._isIdentity&&e,this._isIdentity3x2Dirty=!this._isIdentity3x2&&i}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,n.Z.MatrixTrackPrecisionChange&&n.Z.MatrixTrackedMatrices.push(this),this._m=new n.Z.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let t=this._m;this._isIdentity=1===t[0]&&0===t[1]&&0===t[2]&&0===t[3]&&0===t[4]&&1===t[5]&&0===t[6]&&0===t[7]&&0===t[8]&&0===t[9]&&1===t[10]&&0===t[11]&&0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]?this._isIdentity3x2=!1: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;let t=this._m,e=t[0],r=t[1],i=t[2],s=t[3],o=t[4],a=t[5],n=t[6],h=t[7],c=t[8],_=t[9],l=t[10],u=t[11],y=t[12],m=t[13],x=t[14],R=t[15],T=l*R-x*u,f=_*R-m*u,d=_*x-m*l,p=c*R-y*u,z=c*x-l*y,M=c*m-y*_;return e*+(a*T-n*f+h*d)+-(r*(o*T-n*p+h*z))+i*+(o*f-a*p+h*M)+-(s*(o*d-a*z+n*M))}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} -${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} -${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} -${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return Matrix.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(t){let e=new this.constructor;return this.addToRef(t,e),e}addToRef(t,e){let r=this._m,i=e._m,s=t.m;for(let t=0;t<16;t++)i[t]=r[t]+s[t];return e.markAsUpdated(),e}addToSelf(t){let e=this._m,r=t.m;for(let t=0;t<16;t++)e[t]+=r[t];return this.markAsUpdated(),this}invertToRef(t){if(!0===this._isIdentity)return Matrix.IdentityToRef(t),t;let e=this._m,r=e[0],i=e[1],s=e[2],o=e[3],a=e[4],n=e[5],h=e[6],c=e[7],_=e[8],l=e[9],u=e[10],y=e[11],m=e[12],x=e[13],R=e[14],T=e[15],f=u*T-R*y,d=l*T-x*y,p=l*R-x*u,z=_*T-m*y,M=_*R-u*m,w=_*x-m*l,F=+(n*f-h*d+c*p),V=-(a*f-h*z+c*M),I=+(a*d-n*z+c*w),g=-(a*p-n*M+h*w),A=r*F+i*V+s*I+o*g;if(0===A)return t.copyFrom(this),t;let D=1/A,P=h*T-R*c,C=n*T-x*c,L=n*R-x*h,O=a*T-m*c,H=a*R-m*h,k=a*x-m*n,v=h*y-u*c,Q=n*y-l*c,S=n*u-l*h,B=a*y-_*c,b=a*u-_*h,E=a*l-_*n;return Matrix.FromValuesToRef(F*D,-(i*f-s*d+o*p)*D,+(i*P-s*C+o*L)*D,-(i*v-s*Q+o*S)*D,V*D,+(r*f-s*z+o*M)*D,-(r*P-s*O+o*H)*D,+(r*v-s*B+o*b)*D,I*D,-(r*d-i*z+o*w)*D,+(r*C-i*O+o*k)*D,-(r*Q-i*B+o*E)*D,g*D,+(r*p-i*M+s*w)*D,-(r*L-i*H+s*k)*D,+(r*S-i*b+s*E)*D,t),t}addAtIndex(t,e){return this._m[t]+=e,this.markAsUpdated(),this}multiplyAtIndex(t,e){return this._m[t]*=e,this.markAsUpdated(),this}setTranslationFromFloats(t,e,r){return this._m[12]=t,this._m[13]=e,this._m[14]=r,this.markAsUpdated(),this}addTranslationFromFloats(t,e,r){return this._m[12]+=t,this._m[13]+=e,this._m[14]+=r,this.markAsUpdated(),this}setTranslation(t){return this.setTranslationFromFloats(t._x,t._y,t._z)}getTranslation(){return new Vector3(this._m[12],this._m[13],this._m[14])}getTranslationToRef(t){return t.x=this._m[12],t.y=this._m[13],t.z=this._m[14],t}removeRotationAndScaling(){let t=this.m;return Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t[12],t[13],t[14],t[15],this),this._updateIdentityStatus(0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]),this}multiply(t){let e=new this.constructor;return this.multiplyToRef(t,e),e}copyFrom(t){return t.copyToArray(this._m),this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(t,e=0){let r=this._m;return t[e]=r[0],t[e+1]=r[1],t[e+2]=r[2],t[e+3]=r[3],t[e+4]=r[4],t[e+5]=r[5],t[e+6]=r[6],t[e+7]=r[7],t[e+8]=r[8],t[e+9]=r[9],t[e+10]=r[10],t[e+11]=r[11],t[e+12]=r[12],t[e+13]=r[13],t[e+14]=r[14],t[e+15]=r[15],this}multiplyToRef(t,e){return this._isIdentity?e.copyFrom(t):t._isIdentity?e.copyFrom(this):(this.multiplyToArray(t,e._m,0),e.markAsUpdated()),e}multiplyToArray(t,e,r){let i=this._m,s=t.m,o=i[0],a=i[1],n=i[2],h=i[3],c=i[4],_=i[5],l=i[6],u=i[7],y=i[8],m=i[9],x=i[10],R=i[11],T=i[12],f=i[13],d=i[14],p=i[15],z=s[0],M=s[1],w=s[2],F=s[3],V=s[4],I=s[5],g=s[6],A=s[7],D=s[8],P=s[9],C=s[10],L=s[11],O=s[12],H=s[13],k=s[14],v=s[15];return e[r]=o*z+a*V+n*D+h*O,e[r+1]=o*M+a*I+n*P+h*H,e[r+2]=o*w+a*g+n*C+h*k,e[r+3]=o*F+a*A+n*L+h*v,e[r+4]=c*z+_*V+l*D+u*O,e[r+5]=c*M+_*I+l*P+u*H,e[r+6]=c*w+_*g+l*C+u*k,e[r+7]=c*F+_*A+l*L+u*v,e[r+8]=y*z+m*V+x*D+R*O,e[r+9]=y*M+m*I+x*P+R*H,e[r+10]=y*w+m*g+x*C+R*k,e[r+11]=y*F+m*A+x*L+R*v,e[r+12]=T*z+f*V+d*D+p*O,e[r+13]=T*M+f*I+d*P+p*H,e[r+14]=T*w+f*g+d*C+p*k,e[r+15]=T*F+f*A+d*L+p*v,this}equals(t){if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;let e=this.m,r=t.m;return e[0]===r[0]&&e[1]===r[1]&&e[2]===r[2]&&e[3]===r[3]&&e[4]===r[4]&&e[5]===r[5]&&e[6]===r[6]&&e[7]===r[7]&&e[8]===r[8]&&e[9]===r[9]&&e[10]===r[10]&&e[11]===r[11]&&e[12]===r[12]&&e[13]===r[13]&&e[14]===r[14]&&e[15]===r[15]}clone(){let t=new this.constructor;return t.copyFrom(this),t}getClassName(){return"Matrix"}getHashCode(){let t=_ExtractAsInt(this._m[0]);for(let e=1;e<16;e++)t=397*t^_ExtractAsInt(this._m[e]);return t}decomposeToTransformNode(t){return t.rotationQuaternion=t.rotationQuaternion||new Quaternion,this.decompose(t.scaling,t.rotationQuaternion,t.position)}decompose(t,e,r,i){if(this._isIdentity)return r&&r.setAll(0),t&&t.setAll(1),e&&e.copyFromFloats(0,0,0,1),!0;let s=this._m;if(r&&r.copyFromFloats(s[12],s[13],s[14]),(t=t||MathTmp.Vector3[0]).x=Math.sqrt(s[0]*s[0]+s[1]*s[1]+s[2]*s[2]),t.y=Math.sqrt(s[4]*s[4]+s[5]*s[5]+s[6]*s[6]),t.z=Math.sqrt(s[8]*s[8]+s[9]*s[9]+s[10]*s[10]),i){let e=i.absoluteScaling.x<0?-1:1,r=i.absoluteScaling.y<0?-1:1,s=i.absoluteScaling.z<0?-1:1;t.x*=e,t.y*=r,t.z*=s}else 0>=this.determinant()&&(t.y*=-1);if(0===t._x||0===t._y||0===t._z)return e&&e.copyFromFloats(0,0,0,1),!1;if(e){let r=1/t._x,i=1/t._y,o=1/t._z;Matrix.FromValuesToRef(s[0]*r,s[1]*r,s[2]*r,0,s[4]*i,s[5]*i,s[6]*i,0,s[8]*o,s[9]*o,s[10]*o,0,0,0,0,1,MathTmp.Matrix[0]),Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0],e)}return!0}getRow(t){if(t<0||t>3)return null;let e=4*t;return new Vector4(this._m[e+0],this._m[e+1],this._m[e+2],this._m[e+3])}getRowToRef(t,e){if(t>=0&&t<3){let r=4*t;e.x=this._m[r+0],e.y=this._m[r+1],e.z=this._m[r+2],e.w=this._m[r+3]}return e}setRow(t,e){return this.setRowFromFloats(t,e.x,e.y,e.z,e.w)}transpose(){let t=new this.constructor;return Matrix.TransposeToRef(this,t),t}transposeToRef(t){return Matrix.TransposeToRef(this,t),t}setRowFromFloats(t,e,r,i,s){if(t<0||t>3)return this;let o=4*t;return this._m[o+0]=e,this._m[o+1]=r,this._m[o+2]=i,this._m[o+3]=s,this.markAsUpdated(),this}scale(t){let e=new this.constructor;return this.scaleToRef(t,e),e}scaleToRef(t,e){for(let r=0;r<16;r++)e._m[r]=this._m[r]*t;return e.markAsUpdated(),e}scaleAndAddToRef(t,e){for(let r=0;r<16;r++)e._m[r]+=this._m[r]*t;return e.markAsUpdated(),e}toNormalMatrix(t){let e=MathTmp.Matrix[0];this.invertToRef(e),e.transposeToRef(t);let r=t._m;return Matrix.FromValuesToRef(r[0],r[1],r[2],0,r[4],r[5],r[6],0,r[8],r[9],r[10],0,0,0,0,1,t),t}getRotationMatrix(){let t=new this.constructor;return this.getRotationMatrixToRef(t),t}getRotationMatrixToRef(t){let e=MathTmp.Vector3[0];if(!this.decompose(e))return Matrix.IdentityToRef(t),t;let r=this._m,i=1/e._x,s=1/e._y,o=1/e._z;return Matrix.FromValuesToRef(r[0]*i,r[1]*i,r[2]*i,0,r[4]*s,r[5]*s,r[6]*s,0,r[8]*o,r[9]*o,r[10]*o,0,0,0,0,1,t),t}toggleModelMatrixHandInPlace(){let t=this._m;return t[2]*=-1,t[6]*=-1,t[8]*=-1,t[9]*=-1,t[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let t=this._m;return t[8]*=-1,t[9]*=-1,t[10]*=-1,t[11]*=-1,this.markAsUpdated(),this}static FromArray(t,e=0){let r=new Matrix;return Matrix.FromArrayToRef(t,e,r),r}static FromArrayToRef(t,e,r){for(let i=0;i<16;i++)r._m[i]=t[i+e];return r.markAsUpdated(),r}static FromFloat32ArrayToRefScaled(t,e,r,i){for(let s=0;s<16;s++)i._m[s]=t[s+e]*r;return i.markAsUpdated(),i}static get IdentityReadOnly(){return Matrix._IdentityReadOnly}static FromValuesToRef(t,e,r,i,s,o,a,n,h,c,_,l,u,y,m,x,R){let T=R._m;T[0]=t,T[1]=e,T[2]=r,T[3]=i,T[4]=s,T[5]=o,T[6]=a,T[7]=n,T[8]=h,T[9]=c,T[10]=_,T[11]=l,T[12]=u,T[13]=y,T[14]=m,T[15]=x,R.markAsUpdated()}static FromValues(t,e,r,i,s,o,a,n,h,c,_,l,u,y,m,x){let R=new Matrix,T=R._m;return T[0]=t,T[1]=e,T[2]=r,T[3]=i,T[4]=s,T[5]=o,T[6]=a,T[7]=n,T[8]=h,T[9]=c,T[10]=_,T[11]=l,T[12]=u,T[13]=y,T[14]=m,T[15]=x,R.markAsUpdated(),R}static Compose(t,e,r){let i=new Matrix;return Matrix.ComposeToRef(t,e,r,i),i}static ComposeToRef(t,e,r,i){let s=i._m,o=e._x,a=e._y,n=e._z,h=e._w,c=o+o,_=a+a,l=n+n,u=o*c,y=o*_,m=o*l,x=a*_,R=a*l,T=n*l,f=h*c,d=h*_,p=h*l,z=t._x,M=t._y,w=t._z;return s[0]=(1-(x+T))*z,s[1]=(y+p)*z,s[2]=(m-d)*z,s[3]=0,s[4]=(y-p)*M,s[5]=(1-(u+T))*M,s[6]=(R+f)*M,s[7]=0,s[8]=(m+d)*w,s[9]=(R-f)*w,s[10]=(1-(u+x))*w,s[11]=0,s[12]=r._x,s[13]=r._y,s[14]=r._z,s[15]=1,i.markAsUpdated(),i}static Identity(){let t=Matrix.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return t._updateIdentityStatus(!0),t}static IdentityToRef(t){return Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(!0),t}static Zero(){let t=Matrix.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return t._updateIdentityStatus(!1),t}static RotationX(t){let e=new Matrix;return Matrix.RotationXToRef(t,e),e}static Invert(t){let e=new t.constructor;return t.invertToRef(e),e}static RotationXToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return Matrix.FromValuesToRef(1,0,0,0,0,i,r,0,0,-r,i,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationY(t){let e=new Matrix;return Matrix.RotationYToRef(t,e),e}static RotationYToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return Matrix.FromValuesToRef(i,0,-r,0,0,1,0,0,r,0,i,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationZ(t){let e=new Matrix;return Matrix.RotationZToRef(t,e),e}static RotationZToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return Matrix.FromValuesToRef(i,r,0,0,-r,i,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationAxis(t,e){let r=new Matrix;return Matrix.RotationAxisToRef(t,e,r),r}static RotationAxisToRef(t,e,r){let i=Math.sin(-e),s=Math.cos(-e),o=1-s;t.normalize();let a=r._m;return a[0]=t._x*t._x*o+s,a[1]=t._x*t._y*o-t._z*i,a[2]=t._x*t._z*o+t._y*i,a[3]=0,a[4]=t._y*t._x*o+t._z*i,a[5]=t._y*t._y*o+s,a[6]=t._y*t._z*o-t._x*i,a[7]=0,a[8]=t._z*t._x*o-t._y*i,a[9]=t._z*t._y*o+t._x*i,a[10]=t._z*t._z*o+s,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,r.markAsUpdated(),r}static RotationAlignToRef(t,e,r,i=!1){let o=Vector3.Dot(e,t),a=r._m;if(o<-1+s.kn)a[0]=-1,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=i?1:-1,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=i?-1:1,a[11]=0;else{let r=Vector3.Cross(e,t),i=1/(1+o);a[0]=r._x*r._x*i+o,a[1]=r._y*r._x*i-r._z,a[2]=r._z*r._x*i+r._y,a[3]=0,a[4]=r._x*r._y*i+r._z,a[5]=r._y*r._y*i+o,a[6]=r._z*r._y*i-r._x,a[7]=0,a[8]=r._x*r._z*i-r._y,a[9]=r._y*r._z*i+r._x,a[10]=r._z*r._z*i+o,a[11]=0}return a[12]=0,a[13]=0,a[14]=0,a[15]=1,r.markAsUpdated(),r}static RotationYawPitchRoll(t,e,r){let i=new Matrix;return Matrix.RotationYawPitchRollToRef(t,e,r,i),i}static RotationYawPitchRollToRef(t,e,r,i){return Quaternion.RotationYawPitchRollToRef(t,e,r,MathTmp.Quaternion[0]),MathTmp.Quaternion[0].toRotationMatrix(i),i}static Scaling(t,e,r){let i=new Matrix;return Matrix.ScalingToRef(t,e,r,i),i}static ScalingToRef(t,e,r,i){return Matrix.FromValuesToRef(t,0,0,0,0,e,0,0,0,0,r,0,0,0,0,1,i),i._updateIdentityStatus(1===t&&1===e&&1===r),i}static Translation(t,e,r){let i=new Matrix;return Matrix.TranslationToRef(t,e,r,i),i}static TranslationToRef(t,e,r,i){return Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,e,r,1,i),i._updateIdentityStatus(0===t&&0===e&&0===r),i}static Lerp(t,e,r){let i=new t.constructor;return Matrix.LerpToRef(t,e,r,i),i}static LerpToRef(t,e,r,i){let s=i._m,o=t.m,a=e.m;for(let t=0;t<16;t++)s[t]=o[t]*(1-r)+a[t]*r;return i.markAsUpdated(),i}static DecomposeLerp(t,e,r){let i=new t.constructor;return Matrix.DecomposeLerpToRef(t,e,r,i),i}static DecomposeLerpToRef(t,e,r,i){let s=MathTmp.Vector3[0],o=MathTmp.Quaternion[0],a=MathTmp.Vector3[1];t.decompose(s,o,a);let n=MathTmp.Vector3[2],h=MathTmp.Quaternion[1],c=MathTmp.Vector3[3];e.decompose(n,h,c);let _=MathTmp.Vector3[4];Vector3.LerpToRef(s,n,r,_);let l=MathTmp.Quaternion[2];Quaternion.SlerpToRef(o,h,r,l);let u=MathTmp.Vector3[5];return Vector3.LerpToRef(a,c,r,u),Matrix.ComposeToRef(_,l,u,i),i}static LookAtLH(t,e,r){let i=new Matrix;return Matrix.LookAtLHToRef(t,e,r,i),i}static LookAtLHToRef(t,e,r,i){let s=MathTmp.Vector3[0],o=MathTmp.Vector3[1],a=MathTmp.Vector3[2];e.subtractToRef(t,a),a.normalize(),Vector3.CrossToRef(r,a,s);let n=s.lengthSquared();0===n?s.x=1:s.normalizeFromLength(Math.sqrt(n)),Vector3.CrossToRef(a,s,o),o.normalize();let h=-Vector3.Dot(s,t),c=-Vector3.Dot(o,t),_=-Vector3.Dot(a,t);Matrix.FromValuesToRef(s._x,o._x,a._x,0,s._y,o._y,a._y,0,s._z,o._z,a._z,0,h,c,_,1,i)}static LookAtRH(t,e,r){let i=new Matrix;return Matrix.LookAtRHToRef(t,e,r,i),i}static LookAtRHToRef(t,e,r,i){let s=MathTmp.Vector3[0],o=MathTmp.Vector3[1],a=MathTmp.Vector3[2];t.subtractToRef(e,a),a.normalize(),Vector3.CrossToRef(r,a,s);let n=s.lengthSquared();0===n?s.x=1:s.normalizeFromLength(Math.sqrt(n)),Vector3.CrossToRef(a,s,o),o.normalize();let h=-Vector3.Dot(s,t),c=-Vector3.Dot(o,t),_=-Vector3.Dot(a,t);return Matrix.FromValuesToRef(s._x,o._x,a._x,0,s._y,o._y,a._y,0,s._z,o._z,a._z,0,h,c,_,1,i),i}static LookDirectionLH(t,e){let r=new Matrix;return Matrix.LookDirectionLHToRef(t,e,r),r}static LookDirectionLHToRef(t,e,r){let i=MathTmp.Vector3[0];i.copyFrom(t),i.scaleInPlace(-1);let s=MathTmp.Vector3[1];return Vector3.CrossToRef(e,i,s),Matrix.FromValuesToRef(s._x,s._y,s._z,0,e._x,e._y,e._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static LookDirectionRH(t,e){let r=new Matrix;return Matrix.LookDirectionRHToRef(t,e,r),r}static LookDirectionRHToRef(t,e,r){let i=MathTmp.Vector3[2];return Vector3.CrossToRef(e,t,i),Matrix.FromValuesToRef(i._x,i._y,i._z,0,e._x,e._y,e._z,0,t._x,t._y,t._z,0,0,0,0,1,r),r}static OrthoLH(t,e,r,i,s){let o=new Matrix;return Matrix.OrthoLHToRef(t,e,r,i,o,s),o}static OrthoLHToRef(t,e,r,i,s,o){let a=2/t,n=2/e,h=2/(i-r),_=-(i+r)/(i-r);return Matrix.FromValuesToRef(a,0,0,0,0,n,0,0,0,0,h,0,0,0,_,1,s),o&&s.multiplyToRef(c,s),s._updateIdentityStatus(1===a&&1===n&&1===h&&0===_),s}static OrthoOffCenterLH(t,e,r,i,s,o,a){let n=new Matrix;return Matrix.OrthoOffCenterLHToRef(t,e,r,i,s,o,n,a),n}static OrthoOffCenterLHToRef(t,e,r,i,s,o,a,n){return Matrix.FromValuesToRef(2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,2/(o-s),0,(t+e)/(t-e),(i+r)/(r-i),-(o+s)/(o-s),1,a),n&&a.multiplyToRef(c,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(t,e,r,i,s,o,a,n,h,c,_){let l=-a*Math.cos(n),u=-a*Math.sin(n);return Matrix.TranslationToRef(0,0,-h,MathTmp.Matrix[1]),Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,l,u,1,0,0,0,0,1,MathTmp.Matrix[0]),MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0],MathTmp.Matrix[0]),Matrix.TranslationToRef(0,0,h,MathTmp.Matrix[1]),MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1],MathTmp.Matrix[0]),Matrix.OrthoOffCenterLHToRef(t,e,r,i,s,o,c,_),MathTmp.Matrix[0].multiplyToRef(c,c),c}static OrthoOffCenterRH(t,e,r,i,s,o,a){let n=new Matrix;return Matrix.OrthoOffCenterRHToRef(t,e,r,i,s,o,n,a),n}static OrthoOffCenterRHToRef(t,e,r,i,s,o,a,n){return Matrix.OrthoOffCenterLHToRef(t,e,r,i,s,o,a,n),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(t,e,r,i,s,o,a,n,h,c,_){let l=a*Math.cos(n),u=a*Math.sin(n);return Matrix.TranslationToRef(0,0,h,MathTmp.Matrix[1]),Matrix.FromValuesToRef(1,0,0,0,0,1,0,0,l,u,1,0,0,0,0,1,MathTmp.Matrix[0]),MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0],MathTmp.Matrix[0]),Matrix.TranslationToRef(0,0,-h,MathTmp.Matrix[1]),MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1],MathTmp.Matrix[0]),Matrix.OrthoOffCenterRHToRef(t,e,r,i,s,o,c,_),MathTmp.Matrix[0].multiplyToRef(c,c),c}static PerspectiveLH(t,e,r,i,s,o=0){let a=new Matrix,n=Math.tan(o);return Matrix.FromValuesToRef(2*r/t,0,0,0,0,2*r/e,0,n,0,0,(i+r)/(i-r),1,0,0,-2*i*r/(i-r),0,a),s&&a.multiplyToRef(c,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(t,e,r,i,s,o=0,a=!1){let n=new Matrix;return Matrix.PerspectiveFovLHToRef(t,e,r,i,n,!0,s,o,a),n}static PerspectiveFovLHToRef(t,e,r,i,s,o=!0,a,n=0,h=!1){let _=1/Math.tan(.5*t),l=o?_/e:_,u=o?_:_*e,y=h&&0===r?-1:0!==i?(i+r)/(i-r):1,m=h&&0===r?2*i:0!==i?-2*i*r/(i-r):-2*r,x=Math.tan(n);return Matrix.FromValuesToRef(l,0,0,0,0,u,0,x,0,0,y,1,0,0,m,0,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(t,e,r,i,s,o=!0,a,n=0){let h=1/Math.tan(.5*t),_=o?h/e:h,l=o?h:h*e,u=Math.tan(n);return Matrix.FromValuesToRef(_,0,0,0,0,l,0,u,0,0,-r,1,0,0,1,0,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(t,e,r,i,s,o=0,a=!1){let n=new Matrix;return Matrix.PerspectiveFovRHToRef(t,e,r,i,n,!0,s,o,a),n}static PerspectiveFovRHToRef(t,e,r,i,s,o=!0,a,n=0,h=!1){let _=1/Math.tan(.5*t),l=o?_/e:_,u=o?_:_*e,y=h&&0===r?1:0!==i?-(i+r)/(i-r):-1,m=h&&0===r?2*i:0!==i?-2*i*r/(i-r):-2*r,x=Math.tan(n);return Matrix.FromValuesToRef(l,0,0,0,0,u,0,x,0,0,y,-1,0,0,m,0,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(t,e,r,i,s,o=!0,a,n=0){let h=1/Math.tan(.5*t),_=o?h/e:h,l=o?h:h*e,u=Math.tan(n);return Matrix.FromValuesToRef(_,0,0,0,0,l,0,u,0,0,-r,-1,0,0,-1,0,s),a&&s.multiplyToRef(c,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(t,e,r,i,s,o){let a=t.width,n=t.height,h=t.x,c=t.y,_=Matrix.FromValues(a/2,0,0,0,0,-n/2,0,0,0,0,o-s,0,h+a/2,n/2+c,s,1),l=new e.constructor;return e.multiplyToRef(r,l),l.multiplyToRef(i,l),l.multiplyToRef(_,l)}static GetAsMatrix2x2(t){let e=t.m,r=[e[0],e[1],e[4],e[5]];return n.Z.MatrixUse64Bits?r:new Float32Array(r)}static GetAsMatrix3x3(t){let e=t.m,r=[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]];return n.Z.MatrixUse64Bits?r:new Float32Array(r)}static Transpose(t){let e=new t.constructor;return Matrix.TransposeToRef(t,e),e}static TransposeToRef(t,e){let r=t.m,i=r[0],s=r[4],o=r[8],a=r[12],n=r[1],h=r[5],c=r[9],_=r[13],l=r[2],u=r[6],y=r[10],m=r[14],x=r[3],R=r[7],T=r[11],f=r[15],d=e._m;return d[0]=i,d[1]=s,d[2]=o,d[3]=a,d[4]=n,d[5]=h,d[6]=c,d[7]=_,d[8]=l,d[9]=u,d[10]=y,d[11]=m,d[12]=x,d[13]=R,d[14]=T,d[15]=f,e.markAsUpdated(),e._updateIdentityStatus(t._isIdentity,t._isIdentityDirty),e}static Reflection(t){let e=new Matrix;return Matrix.ReflectionToRef(t,e),e}static ReflectionToRef(t,e){t.normalize();let r=t.normal.x,i=t.normal.y,s=t.normal.z,o=-2*r,a=-2*i,n=-2*s;return Matrix.FromValuesToRef(o*r+1,a*r,n*r,0,o*i,a*i+1,n*i,0,o*s,a*s,n*s+1,0,o*t.d,a*t.d,n*t.d,1,e),e}static FromXYZAxesToRef(t,e,r,i){return Matrix.FromValuesToRef(t._x,t._y,t._z,0,e._x,e._y,e._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static FromQuaternionToRef(t,e){let r=t._x*t._x,i=t._y*t._y,s=t._z*t._z,o=t._x*t._y,a=t._z*t._w,n=t._z*t._x,h=t._y*t._w,c=t._y*t._z,_=t._x*t._w;return e._m[0]=1-2*(i+s),e._m[1]=2*(o+a),e._m[2]=2*(n-h),e._m[3]=0,e._m[4]=2*(o-a),e._m[5]=1-2*(s+r),e._m[6]=2*(c+_),e._m[7]=0,e._m[8]=2*(n+h),e._m[9]=2*(c-_),e._m[10]=1-2*(i+r),e._m[11]=0,e._m[12]=0,e._m[13]=0,e._m[14]=0,e._m[15]=1,e.markAsUpdated(),e}};Matrix._UpdateFlagSeed=0,Matrix._IdentityReadOnly=Matrix.Identity();let MathTmp=class MathTmp{};MathTmp.Vector3=o.B.BuildTuple(11,Vector3.Zero),MathTmp.Matrix=o.B.BuildTuple(2,Matrix.Identity),MathTmp.Quaternion=o.B.BuildTuple(3,Quaternion.Zero);let TmpVectors=class TmpVectors{};TmpVectors.Vector2=o.B.BuildTuple(3,Vector2.Zero),TmpVectors.Vector3=o.B.BuildTuple(13,Vector3.Zero),TmpVectors.Vector4=o.B.BuildTuple(3,Vector4.Zero),TmpVectors.Quaternion=o.B.BuildTuple(2,Quaternion.Zero),TmpVectors.Matrix=o.B.BuildTuple(8,Matrix.Identity),(0,a.H)("BABYLON.Vector2",Vector2),(0,a.H)("BABYLON.Vector3",Vector3),(0,a.H)("BABYLON.Vector4",Vector4),(0,a.H)("BABYLON.Matrix",Matrix);let c=Matrix.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)}}]); \ No newline at end of file diff --git a/.next/static/chunks/604a08ec-edbc4bb5c67ea975.js b/.next/static/chunks/604a08ec-edbc4bb5c67ea975.js new file mode 100644 index 0000000..1846d15 --- /dev/null +++ b/.next/static/chunks/604a08ec-edbc4bb5c67ea975.js @@ -0,0 +1,4 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[735],{78:function(t,e,r){r.d(e,{FM:function(){return l},Lt:function(){return u},P:function(){return c},_f:function(){return y},jp:function(){return R},y3:function(){return m}});var i=r(5762),s=r(9806),o=r(4254),n=r(3048),a=r(4548),h=r(6030);let _=t=>parseInt(t.toString().replace(/\W/g,""));class l{constructor(t=0,e=0){this.x=t,this.y=e}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let t=_(this.x),e=_(this.y);return 397*t^e}toArray(t,e=0){return t[e]=this.x,t[e+1]=this.y,this}fromArray(t,e=0){return l.FromArrayToRef(t,e,this),this}asArray(){let t=[];return this.toArray(t,0),t}copyFrom(t){return this.x=t.x,this.y=t.y,this}copyFromFloats(t,e){return this.x=t,this.y=e,this}set(t,e){return this.copyFromFloats(t,e)}add(t){return new this.constructor(this.x+t.x,this.y+t.y)}addToRef(t,e){return e.x=this.x+t.x,e.y=this.y+t.y,e}addInPlace(t){return this.x+=t.x,this.y+=t.y,this}addVector3(t){return new this.constructor(this.x+t.x,this.y+t.y)}subtract(t){return new this.constructor(this.x-t.x,this.y-t.y)}subtractToRef(t,e){return e.x=this.x-t.x,e.y=this.y-t.y,e}subtractInPlace(t){return this.x-=t.x,this.y-=t.y,this}multiplyInPlace(t){return this.x*=t.x,this.y*=t.y,this}multiply(t){return new this.constructor(this.x*t.x,this.y*t.y)}multiplyToRef(t,e){return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByFloats(t,e){return new this.constructor(this.x*t,this.y*e)}divide(t){return new this.constructor(this.x/t.x,this.y/t.y)}divideToRef(t,e){return e.x=this.x/t.x,e.y=this.y/t.y,e}divideInPlace(t){return this.divideToRef(t,this)}negate(){return new this.constructor(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(t){return t.copyFromFloats(-1*this.x,-1*this.y)}scaleInPlace(t){return this.x*=t,this.y*=t,this}scale(t){let e=new this.constructor(0,0);return this.scaleToRef(t,e),e}scaleToRef(t,e){return e.x=this.x*t,e.y=this.y*t,e}scaleAndAddToRef(t,e){return e.x+=this.x*t,e.y+=this.y*t,e}equals(t){return t&&this.x===t.x&&this.y===t.y}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this.x,t.x,e)&&i.R.WithinEpsilon(this.y,t.y,e)}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y))}fract(){return new this.constructor(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}rotateToRef(t,e){let r=Math.cos(t),i=Math.sin(t),s=r*this.x-i*this.y,o=i*this.x+r*this.y;return e.x=s,e.y=o,e}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(t){return 0===t||1===t?this:this.scaleInPlace(1/t)}normalizeToNew(){let t=new this.constructor(0,0);return this.normalizeToRef(t),t}normalizeToRef(t){let e=this.length();return 0===e||1===e?t.copyFromFloats(this.x,this.y):this.scaleToRef(1/e,t)}clone(){return new this.constructor(this.x,this.y)}dot(t){return this.x*t.x+this.y*t.y}static Zero(){return new l(0,0)}static One(){return new l(1,1)}static Random(t=0,e=1){return new l(i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static get ZeroReadOnly(){return l._ZeroReadOnly}static FromArray(t,e=0){return new l(t[e],t[e+1])}static FromArrayToRef(t,e,r){return r.x=t[e],r.y=t[e+1],r}static CatmullRom(t,e,r,i,s){let o=s*s,n=s*o,a=.5*(2*e.x+(-t.x+r.x)*s+(2*t.x-5*e.x+4*r.x-i.x)*o+(-t.x+3*e.x-3*r.x+i.x)*n),h=.5*(2*e.y+(-t.y+r.y)*s+(2*t.y-5*e.y+4*r.y-i.y)*o+(-t.y+3*e.y-3*r.y+i.y)*n);return new t.constructor(a,h)}static Clamp(t,e,r){let i=t.x;i=(i=i>r.x?r.x:i)r.y?r.y:s)e.x?t.x:e.x,i=t.y>e.y?t.y:e.y;return new t.constructor(r,i)}static Transform(t,e){let r=new t.constructor;return l.TransformToRef(t,e,r),r}static TransformToRef(t,e,r){let i=e.m,s=t.x*i[0]+t.y*i[4]+i[12],o=t.x*i[1]+t.y*i[5]+i[13];return r.x=s,r.y=o,r}static PointInTriangle(t,e,r,i){let s=.5*(-r.y*i.x+e.y*(-r.x+i.x)+e.x*(r.y-i.y)+r.x*i.y),o=s<0?-1:1,n=(e.y*i.x-e.x*i.y+(i.y-e.y)*t.x+(e.x-i.x)*t.y)*o,a=(e.x*r.y-e.y*r.x+(e.y-r.y)*t.x+(r.x-e.x)*t.y)*o;return n>0&&a>0&&n+a<2*s*o}static Distance(t,e){return Math.sqrt(l.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t.x-e.x,i=t.y-e.y;return r*r+i*i}static Center(t,e){let r=new t.constructor;return l.CenterToRef(t,e,r)}static CenterToRef(t,e,r){return r.copyFromFloats((t.x+e.x)/2,(t.y+e.y)/2)}static DistanceOfPointFromSegment(t,e,r){let i=l.DistanceSquared(e,r);if(0===i)return l.Distance(t,e);let s=r.subtract(e),o=Math.max(0,Math.min(1,l.Dot(t.subtract(e),s)/i)),n=e.add(s.multiplyByFloats(o,o));return l.Distance(t,n)}}l._ZeroReadOnly=l.Zero();class c{get x(){return this._x}set x(t){this._x=t,this._isDirty=!0}get y(){return this._y}set y(t){this._y=t,this._isDirty=!0}get z(){return this._z}set z(t){this._z=t,this._isDirty=!0}constructor(t=0,e=0,r=0){this._isDirty=!0,this._x=t,this._y=e,this._z=r}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let t=_(this._x),e=_(this._y),r=_(this._z),i=t;return 397*(i=397*i^e)^r}asArray(){let t=[];return this.toArray(t,0),t}toArray(t,e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,this}fromArray(t,e=0){return c.FromArrayToRef(t,e,this),this}toQuaternion(){return y.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(t){return this.addInPlaceFromFloats(t._x,t._y,t._z)}addInPlaceFromFloats(t,e,r){return this._x+=t,this._y+=e,this._z+=r,this._isDirty=!0,this}add(t){return new this.constructor(this._x+t._x,this._y+t._y,this._z+t._z)}addToRef(t,e){return e.copyFromFloats(this._x+t._x,this._y+t._y,this._z+t._z)}subtractInPlace(t){return this._x-=t._x,this._y-=t._y,this._z-=t._z,this._isDirty=!0,this}subtract(t){return new this.constructor(this._x-t._x,this._y-t._y,this._z-t._z)}subtractToRef(t,e){return this.subtractFromFloatsToRef(t._x,t._y,t._z,e)}subtractFromFloats(t,e,r){return new this.constructor(this._x-t,this._y-e,this._z-r)}subtractFromFloatsToRef(t,e,r,i){return i.copyFromFloats(this._x-t,this._y-e,this._z-r)}negate(){return new this.constructor(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(t){return t.copyFromFloats(-1*this._x,-1*this._y,-1*this._z)}scaleInPlace(t){return this._x*=t,this._y*=t,this._z*=t,this._isDirty=!0,this}scale(t){return new this.constructor(this._x*t,this._y*t,this._z*t)}scaleToRef(t,e){return e.copyFromFloats(this._x*t,this._y*t,this._z*t)}getNormalToRef(t){let e=this.length(),r=Math.acos(this.y/e),i=Math.atan2(this.z,this.x);r>Math.PI/2?r-=Math.PI/2:r+=Math.PI/2;let s=e*Math.sin(r)*Math.cos(i),o=e*Math.cos(r),n=e*Math.sin(r)*Math.sin(i);return t.set(s,o,n),t}applyRotationQuaternionToRef(t,e){let r=this._x,i=this._y,s=this._z,o=t._x,n=t._y,a=t._z,h=t._w,_=2*(n*s-a*i),l=2*(a*r-o*s),c=2*(o*i-n*r);return e._x=r+h*_+n*c-a*l,e._y=i+h*l+a*_-o*c,e._z=s+h*c+o*l-n*_,e._isDirty=!0,e}applyRotationQuaternionInPlace(t){return this.applyRotationQuaternionToRef(t,this)}applyRotationQuaternion(t){return this.applyRotationQuaternionToRef(t,new this.constructor)}scaleAndAddToRef(t,e){return e.addInPlaceFromFloats(this._x*t,this._y*t,this._z*t)}projectOnPlane(t,e){let r=new this.constructor;return this.projectOnPlaneToRef(t,e,r),r}projectOnPlaneToRef(t,e,r){let i=t.normal,s=t.d,o=x.Vector3[0];this.subtractToRef(e,o),o.normalize();let n=c.Dot(o,i);if(1e-10>Math.abs(n))r.setAll(1/0);else{let t=-(c.Dot(e,i)+s)/n,a=o.scaleInPlace(t);e.addToRef(a,r)}return r}equals(t){return t&&this._x===t._x&&this._y===t._y&&this._z===t._z}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this._x,t._x,e)&&i.R.WithinEpsilon(this._y,t._y,e)&&i.R.WithinEpsilon(this._z,t._z,e)}equalsToFloats(t,e,r){return this._x===t&&this._y===e&&this._z===r}multiplyInPlace(t){return this._x*=t._x,this._y*=t._y,this._z*=t._z,this._isDirty=!0,this}multiply(t){return this.multiplyByFloats(t._x,t._y,t._z)}multiplyToRef(t,e){return e.copyFromFloats(this._x*t._x,this._y*t._y,this._z*t._z)}multiplyByFloats(t,e,r){return new this.constructor(this._x*t,this._y*e,this._z*r)}divide(t){return new this.constructor(this._x/t._x,this._y/t._y,this._z/t._z)}divideToRef(t,e){return e.copyFromFloats(this._x/t._x,this._y/t._y,this._z/t._z)}divideInPlace(t){return this.divideToRef(t,this)}minimizeInPlace(t){return this.minimizeInPlaceFromFloats(t._x,t._y,t._z)}maximizeInPlace(t){return this.maximizeInPlaceFromFloats(t._x,t._y,t._z)}minimizeInPlaceFromFloats(t,e,r){return tthis._x&&(this.x=t),e>this._y&&(this.y=e),r>this._z&&(this.z=r),this}isNonUniformWithinEpsilon(t){let e=Math.abs(this._x),r=Math.abs(this._y);if(!i.R.WithinEpsilon(e,r,t))return!0;let s=Math.abs(this._z);return!(i.R.WithinEpsilon(e,s,t)&&i.R.WithinEpsilon(r,s,t))}get isNonUniform(){let t=Math.abs(this._x);return t!==Math.abs(this._y)||t!==Math.abs(this._z)}floor(){return new this.constructor(Math.floor(this._x),Math.floor(this._y),Math.floor(this._z))}fract(){return new this.constructor(this._x-Math.floor(this._x),this._y-Math.floor(this._y),this._z-Math.floor(this._z))}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z)}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(t){if("xyz"===(t=t.toLowerCase()))return this;let e=x.Vector3[0].copyFrom(this);return this.x=e[t[0]],this.y=e[t[1]],this.z=e[t[2]],this}rotateByQuaternionToRef(t,e){return t.toRotationMatrix(x.Matrix[0]),c.TransformCoordinatesToRef(this,x.Matrix[0],e),e}rotateByQuaternionAroundPointToRef(t,e,r){return this.subtractToRef(e,x.Vector3[0]),x.Vector3[0].rotateByQuaternionToRef(t,x.Vector3[0]),e.addToRef(x.Vector3[0],r),r}cross(t){let e=new this.constructor;return c.CrossToRef(this,t,e)}normalizeFromLength(t){return 0===t||1===t?this:this.scaleInPlace(1/t)}normalizeToNew(){let t=new this.constructor(0,0,0);return this.normalizeToRef(t),t}normalizeToRef(t){let e=this.length();return 0===e||1===e?t.copyFromFloats(this._x,this._y,this._z):this.scaleToRef(1/e,t)}clone(){return new this.constructor(this._x,this._y,this._z)}copyFrom(t){return this.copyFromFloats(t._x,t._y,t._z)}copyFromFloats(t,e,r){return this._x=t,this._y=e,this._z=r,this._isDirty=!0,this}set(t,e,r){return this.copyFromFloats(t,e,r)}setAll(t){return this._x=this._y=this._z=t,this._isDirty=!0,this}static GetClipFactor(t,e,r,i){let s=c.Dot(t,r);return(s-i)/(s-c.Dot(e,r))}static GetAngleBetweenVectors(t,e,r){let s=t.normalizeToRef(x.Vector3[1]),o=e.normalizeToRef(x.Vector3[2]),n=c.Dot(s,o),a=Math.acos(n=i.R.Clamp(n,-1,1)),h=x.Vector3[3];return(c.CrossToRef(s,o,h),c.Dot(h,r)>0)?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(t,e,r){x.Vector3[0].copyFrom(t);let s=x.Vector3[0];x.Vector3[1].copyFrom(e);let o=x.Vector3[1];x.Vector3[2].copyFrom(r);let n=x.Vector3[2],a=x.Vector3[3],h=x.Vector3[4];s.normalize(),o.normalize(),n.normalize(),c.CrossToRef(n,s,a),c.CrossToRef(a,n,h);let _=Math.atan2(c.Dot(o,a),c.Dot(o,h));return i.R.NormalizeRadians(_)}static PitchYawRollToMoveBetweenPointsToRef(t,e,r){let i=R.Vector3[0];return e.subtractToRef(t,i),r._y=Math.atan2(i.x,i.z)||0,r._x=Math.atan2(Math.sqrt(i.x**2+i.z**2),i.y)||0,r._z=0,r._isDirty=!0,r}static PitchYawRollToMoveBetweenPoints(t,e){let r=c.Zero();return c.PitchYawRollToMoveBetweenPointsToRef(t,e,r)}static SlerpToRef(t,e,r,o){let n,a;r=i.R.Clamp(r,0,1);let h=x.Vector3[0],_=x.Vector3[1];h.copyFrom(t);let l=h.length();h.normalizeFromLength(l),_.copyFrom(e);let u=_.length();_.normalizeFromLength(u);let y=c.Dot(h,_);if(y<1-s.kn){let t=Math.acos(y),e=1/Math.sin(t);n=Math.sin((1-r)*t)*e,a=Math.sin(r*t)*e}else n=1-r,a=r;return h.scaleInPlace(n),_.scaleInPlace(a),o.copyFrom(h).addInPlace(_),o.scaleInPlace(i.R.Lerp(l,u,r)),o}static SmoothToRef(t,e,r,i,s){return c.SlerpToRef(t,e,0===i?1:r/i,s),s}static FromArray(t,e=0){return new c(t[e],t[e+1],t[e+2])}static FromFloatArray(t,e){return c.FromArray(t,e)}static FromArrayToRef(t,e,r){return r._x=t[e],r._y=t[e+1],r._z=t[e+2],r._isDirty=!0,r}static FromFloatArrayToRef(t,e,r){return c.FromArrayToRef(t,e,r)}static FromFloatsToRef(t,e,r,i){return i.copyFromFloats(t,e,r),i}static Zero(){return new c(0,0,0)}static One(){return new c(1,1,1)}static Up(){return new c(0,1,0)}static get UpReadOnly(){return c._UpReadOnly}static get DownReadOnly(){return c._DownReadOnly}static get RightReadOnly(){return c._RightReadOnly}static get LeftReadOnly(){return c._LeftReadOnly}static get LeftHandedForwardReadOnly(){return c._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return c._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return c._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return c._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return c._ZeroReadOnly}static get OneReadOnly(){return c._OneReadOnly}static Down(){return new c(0,-1,0)}static Forward(t=!1){return new c(0,0,t?-1:1)}static Backward(t=!1){return new c(0,0,t?1:-1)}static Right(){return new c(1,0,0)}static Left(){return new c(-1,0,0)}static Random(t=0,e=1){return new c(i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static TransformCoordinates(t,e){let r=c.Zero();return c.TransformCoordinatesToRef(t,e,r),r}static TransformCoordinatesToRef(t,e,r){return c.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformCoordinatesFromFloatsToRef(t,e,r,i,s){let o=i.m,n=t*o[0]+e*o[4]+r*o[8]+o[12],a=t*o[1]+e*o[5]+r*o[9]+o[13],h=t*o[2]+e*o[6]+r*o[10]+o[14],_=1/(t*o[3]+e*o[7]+r*o[11]+o[15]);return s._x=n*_,s._y=a*_,s._z=h*_,s._isDirty=!0,s}static TransformNormal(t,e){let r=c.Zero();return c.TransformNormalToRef(t,e,r),r}static TransformNormalToRef(t,e,r){return this.TransformNormalFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformNormalFromFloatsToRef(t,e,r,i,s){let o=i.m;return s._x=t*o[0]+e*o[4]+r*o[8],s._y=t*o[1]+e*o[5]+r*o[9],s._z=t*o[2]+e*o[6]+r*o[10],s._isDirty=!0,s}static CatmullRom(t,e,r,i,s){let o=s*s,n=s*o,a=.5*(2*e._x+(-t._x+r._x)*s+(2*t._x-5*e._x+4*r._x-i._x)*o+(-t._x+3*e._x-3*r._x+i._x)*n),h=.5*(2*e._y+(-t._y+r._y)*s+(2*t._y-5*e._y+4*r._y-i._y)*o+(-t._y+3*e._y-3*r._y+i._y)*n),_=.5*(2*e._z+(-t._z+r._z)*s+(2*t._z-5*e._z+4*r._z-i._z)*o+(-t._z+3*e._z-3*r._z+i._z)*n);return new t.constructor(a,h,_)}static Clamp(t,e,r){let i=new t.constructor;return c.ClampToRef(t,e,r,i),i}static ClampToRef(t,e,r,i){let s=t._x;s=(s=s>r._x?r._x:s)r._y?r._y:o)r._z?r._z:n)0&&V<0?(C.copyFrom(_),a=e,h=r):V>0&&L<0?(C.copyFrom(u),a=r,h=o):(C.copyFrom(l).scaleInPlace(-1),a=o,h=e);let O=x.Vector3[9],H=x.Vector3[4];if(a.subtractToRef(p,D),h.subtractToRef(p,O),c.CrossToRef(D,O,H),!(0>c.Dot(H,y)))return n.copyFrom(p),Math.abs(T*w);let k=x.Vector3[5];c.CrossToRef(C,H,k),k.normalize();let v=x.Vector3[9];v.copyFrom(a).subtractInPlace(p);let S=v.length();if(Sthis.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this}floor(){return new this.constructor(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fract(){return new this.constructor(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(t){return 0===t||1===t?this:this.scaleInPlace(1/t)}normalizeToNew(){let t=new this.constructor(0,0,0,0);return this.normalizeToRef(t),t}normalizeToRef(t){let e=this.length();return 0===e||1===e?t.copyFromFloats(this.x,this.y,this.z,this.w):this.scaleToRef(1/e,t)}toVector3(){return new c(this.x,this.y,this.z)}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copyFrom(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this}copyFromFloats(t,e,r,i){return this.x=t,this.y=e,this.z=r,this.w=i,this}set(t,e,r,i){return this.copyFromFloats(t,e,r,i)}setAll(t){return this.x=this.y=this.z=this.w=t,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}static FromArray(t,e){return e||(e=0),new u(t[e],t[e+1],t[e+2],t[e+3])}static FromArrayToRef(t,e,r){return r.x=t[e],r.y=t[e+1],r.z=t[e+2],r.w=t[e+3],r}static FromFloatArrayToRef(t,e,r){return u.FromArrayToRef(t,e,r),r}static FromFloatsToRef(t,e,r,i,s){return s.x=t,s.y=e,s.z=r,s.w=i,s}static Zero(){return new u(0,0,0,0)}static One(){return new u(1,1,1,1)}static Random(t=0,e=1){return new u(i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e),i.R.RandomRange(t,e))}static get ZeroReadOnly(){return u._ZeroReadOnly}static Normalize(t){let e=u.Zero();return u.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){return t.normalizeToRef(e),e}static Minimize(t,e){let r=new t.constructor;return r.copyFrom(t),r.minimizeInPlace(e),r}static Maximize(t,e){let r=new t.constructor;return r.copyFrom(t),r.maximizeInPlace(e),r}static Distance(t,e){return Math.sqrt(u.DistanceSquared(t,e))}static DistanceSquared(t,e){let r=t.x-e.x,i=t.y-e.y,s=t.z-e.z,o=t.w-e.w;return r*r+i*i+s*s+o*o}static Center(t,e){return u.CenterToRef(t,e,u.Zero())}static CenterToRef(t,e,r){return r.copyFromFloats((t.x+e.x)/2,(t.y+e.y)/2,(t.z+e.z)/2,(t.w+e.w)/2)}static TransformCoordinates(t,e){let r=u.Zero();return u.TransformCoordinatesToRef(t,e,r),r}static TransformCoordinatesToRef(t,e,r){return u.TransformCoordinatesFromFloatsToRef(t._x,t._y,t._z,e,r),r}static TransformCoordinatesFromFloatsToRef(t,e,r,i,s){let o=i.m,n=t*o[0]+e*o[4]+r*o[8]+o[12],a=t*o[1]+e*o[5]+r*o[9]+o[13],h=t*o[2]+e*o[6]+r*o[10]+o[14],_=t*o[3]+e*o[7]+r*o[11]+o[15];return s.x=n,s.y=a,s.z=h,s.w=_,s}static TransformNormal(t,e){let r=new t.constructor;return u.TransformNormalToRef(t,e,r),r}static TransformNormalToRef(t,e,r){let i=e.m,s=t.x*i[0]+t.y*i[4]+t.z*i[8],o=t.x*i[1]+t.y*i[5]+t.z*i[9],n=t.x*i[2]+t.y*i[6]+t.z*i[10];return r.x=s,r.y=o,r.z=n,r.w=t.w,r}static TransformNormalFromFloatsToRef(t,e,r,i,s,o){let n=s.m;return o.x=t*n[0]+e*n[4]+r*n[8],o.y=t*n[1]+e*n[5]+r*n[9],o.z=t*n[2]+e*n[6]+r*n[10],o.w=i,o}static FromVector3(t,e=0){return new u(t._x,t._y,t._z,e)}static Dot(t,e){return t.dot(e)}}u._ZeroReadOnly=u.Zero();class y{get x(){return this._x}set x(t){this._x=t,this._isDirty=!0}get y(){return this._y}set y(t){this._y=t,this._isDirty=!0}get z(){return this._z}set z(t){this._z=t,this._isDirty=!0}get w(){return this._w}set w(t){this._w=t,this._isDirty=!0}constructor(t=0,e=0,r=0,i=1){this._isDirty=!0,this._x=t,this._y=e,this._z=r,this._w=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let t=_(this._x),e=_(this._y),r=_(this._z),i=_(this._w),s=t;return 397*(s=397*(s=397*s^e)^r)^i}asArray(){return[this._x,this._y,this._z,this._w]}toArray(t,e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,this}equals(t){return t&&this._x===t._x&&this._y===t._y&&this._z===t._z&&this._w===t._w}equalsWithEpsilon(t,e=s.kn){return t&&i.R.WithinEpsilon(this._x,t._x,e)&&i.R.WithinEpsilon(this._y,t._y,e)&&i.R.WithinEpsilon(this._z,t._z,e)&&i.R.WithinEpsilon(this._w,t._w,e)}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copyFrom(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._w=t._w,this._isDirty=!0,this}copyFromFloats(t,e,r,i){return this._x=t,this._y=e,this._z=r,this._w=i,this._isDirty=!0,this}set(t,e,r,i){return this.copyFromFloats(t,e,r,i)}add(t){return new this.constructor(this._x+t._x,this._y+t._y,this._z+t._z,this._w+t._w)}addInPlace(t){return this._x+=t._x,this._y+=t._y,this._z+=t._z,this._w+=t._w,this._isDirty=!0,this}subtract(t){return new this.constructor(this._x-t._x,this._y-t._y,this._z-t._z,this._w-t._w)}subtractInPlace(t){return this._x-=t._x,this._y-=t._y,this._z-=t._z,this._w-=t._w,this._isDirty=!0,this}scale(t){return new this.constructor(this._x*t,this._y*t,this._z*t,this._w*t)}scaleToRef(t,e){return e._x=this._x*t,e._y=this._y*t,e._z=this._z*t,e._w=this._w*t,e._isDirty=!0,e}scaleInPlace(t){return this._x*=t,this._y*=t,this._z*=t,this._w*=t,this._isDirty=!0,this}scaleAndAddToRef(t,e){return e._x+=this._x*t,e._y+=this._y*t,e._z+=this._z*t,e._w+=this._w*t,e._isDirty=!0,e}multiply(t){let e=new this.constructor(0,0,0,1);return this.multiplyToRef(t,e),e}multiplyToRef(t,e){let r=this._x*t._w+this._y*t._z-this._z*t._y+this._w*t._x,i=-this._x*t._z+this._y*t._w+this._z*t._x+this._w*t._y,s=this._x*t._y-this._y*t._x+this._z*t._w+this._w*t._z,o=-this._x*t._x-this._y*t._y-this._z*t._z+this._w*t._w;return e.copyFromFloats(r,i,s,o),e}multiplyInPlace(t){return this.multiplyToRef(t,this),this}conjugateToRef(t){return t.copyFromFloats(-this._x,-this._y,-this._z,this._w),t}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new this.constructor(-this._x,-this._y,-this._z,this._w)}invert(){let t=this.conjugate(),e=this.lengthSquared();return 0==e||1==e||t.scaleInPlace(1/e),t}invertInPlace(){this.conjugateInPlace();let t=this.lengthSquared();return 0==t||1==t||this.scaleInPlace(1/t),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(t){return 0===t||1===t?this:this.scaleInPlace(1/t)}normalizeToNew(){let t=new this.constructor(0,0,0,1);return this.normalizeToRef(t),t}normalizeToRef(t){let e=this.length();return 0===e||1===e?t.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/e,t)}toEulerAngles(){let t=c.Zero();return this.toEulerAnglesToRef(t),t}toEulerAnglesToRef(t){let e=this._z,r=this._x,i=this._y,s=this._w,o=i*e-r*s;if(o<-.4999999)t._y=2*Math.atan2(i,s),t._x=Math.PI/2,t._z=0,t._isDirty=!0;else if(o>.4999999)t._y=2*Math.atan2(i,s),t._x=-Math.PI/2,t._z=0,t._isDirty=!0;else{let n=s*s,a=e*e,h=r*r,_=i*i;t._z=Math.atan2(2*(r*i+e*s),-a-h+_+n),t._x=Math.asin(-2*o),t._y=Math.atan2(2*(e*r+i*s),a-h-_+n),t._isDirty=!0}return t}toRotationMatrix(t){return m.FromQuaternionToRef(this,t),t}fromRotationMatrix(t){return y.FromRotationMatrixToRef(t,this),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}static FromRotationMatrix(t){let e=new y;return y.FromRotationMatrixToRef(t,e),e}static FromRotationMatrixToRef(t,e){let r;let i=t.m,s=i[0],o=i[4],n=i[8],a=i[1],h=i[5],_=i[9],l=i[2],c=i[6],u=i[10],y=s+h+u;return y>0?(r=.5/Math.sqrt(y+1),e._w=.25/r,e._x=(c-_)*r,e._y=(n-l)*r,e._z=(a-o)*r):s>h&&s>u?(r=2*Math.sqrt(1+s-h-u),e._w=(c-_)/r,e._x=.25*r,e._y=(o+a)/r,e._z=(n+l)/r):h>u?(r=2*Math.sqrt(1+h-s-u),e._w=(n-l)/r,e._x=(o+a)/r,e._y=.25*r,e._z=(_+c)/r):(r=2*Math.sqrt(1+u-s-h),e._w=(a-o)/r,e._x=(n+l)/r,e._y=(_+c)/r,e._z=.25*r),e._isDirty=!0,e}static Dot(t,e){return t._x*e._x+t._y*e._y+t._z*e._z+t._w*e._w}static AreClose(t,e,r=.1){let i=y.Dot(t,e);return 1-i*i<=r}static SmoothToRef(t,e,r,s,o){let n=0===s?1:r/s;return n=i.R.Clamp(n,0,1),y.SlerpToRef(t,e,n,o),o}static Zero(){return new y(0,0,0,0)}static Inverse(t){return new t.constructor(-t._x,-t._y,-t._z,t._w)}static InverseToRef(t,e){return e.set(-t._x,-t._y,-t._z,t._w),e}static Identity(){return new y(0,0,0,1)}static IsIdentity(t){return t&&0===t._x&&0===t._y&&0===t._z&&1===t._w}static RotationAxis(t,e){return y.RotationAxisToRef(t,e,new y)}static RotationAxisToRef(t,e,r){let i=Math.sin(e/2);return t.normalize(),r._w=Math.cos(e/2),r._x=t._x*i,r._y=t._y*i,r._z=t._z*i,r._isDirty=!0,r}static FromArray(t,e){return e||(e=0),new y(t[e],t[e+1],t[e+2],t[e+3])}static FromArrayToRef(t,e,r){return r._x=t[e],r._y=t[e+1],r._z=t[e+2],r._w=t[e+3],r._isDirty=!0,r}static FromEulerAngles(t,e,r){let i=new y;return y.RotationYawPitchRollToRef(e,t,r,i),i}static FromEulerAnglesToRef(t,e,r,i){return y.RotationYawPitchRollToRef(e,t,r,i),i}static FromEulerVector(t){let e=new y;return y.RotationYawPitchRollToRef(t._y,t._x,t._z,e),e}static FromEulerVectorToRef(t,e){return y.RotationYawPitchRollToRef(t._y,t._x,t._z,e),e}static FromUnitVectorsToRef(t,e,r,i=s.kn){let o=c.Dot(t,e)+1;return oMath.abs(t.z)?r.set(-t.y,t.x,0,0):r.set(0,-t.z,t.y,0):(c.CrossToRef(t,e,R.Vector3[0]),r.set(R.Vector3[0].x,R.Vector3[0].y,R.Vector3[0].z,o)),r.normalize()}static RotationYawPitchRoll(t,e,r){let i=new y;return y.RotationYawPitchRollToRef(t,e,r,i),i}static RotationYawPitchRollToRef(t,e,r,i){let s=.5*r,o=.5*e,n=.5*t,a=Math.sin(s),h=Math.cos(s),_=Math.sin(o),l=Math.cos(o),c=Math.sin(n),u=Math.cos(n);return i._x=u*_*h+c*l*a,i._y=c*l*h-u*_*a,i._z=u*l*a-c*_*h,i._w=u*l*h+c*_*a,i._isDirty=!0,i}static RotationAlphaBetaGamma(t,e,r){let i=new y;return y.RotationAlphaBetaGammaToRef(t,e,r,i),i}static RotationAlphaBetaGammaToRef(t,e,r,i){let s=(r+t)*.5,o=(r-t)*.5,n=.5*e;return i._x=Math.cos(o)*Math.sin(n),i._y=Math.sin(o)*Math.sin(n),i._z=Math.sin(s)*Math.cos(n),i._w=Math.cos(s)*Math.cos(n),i._isDirty=!0,i}static RotationQuaternionFromAxis(t,e,r){let i=new y(0,0,0,0);return y.RotationQuaternionFromAxisToRef(t,e,r,i),i}static RotationQuaternionFromAxisToRef(t,e,r,i){let s=x.Matrix[0];return m.FromXYZAxesToRef(t.normalize(),e.normalize(),r.normalize(),s),y.FromRotationMatrixToRef(s,i),i}static FromLookDirectionLH(t,e){let r=new y;return y.FromLookDirectionLHToRef(t,e,r),r}static FromLookDirectionLHToRef(t,e,r){let i=x.Matrix[0];return m.LookDirectionLHToRef(t,e,i),y.FromRotationMatrixToRef(i,r),r}static FromLookDirectionRH(t,e){let r=new y;return y.FromLookDirectionRHToRef(t,e,r),r}static FromLookDirectionRHToRef(t,e,r){let i=x.Matrix[0];return m.LookDirectionRHToRef(t,e,i),y.FromRotationMatrixToRef(i,r)}static Slerp(t,e,r){let i=y.Identity();return y.SlerpToRef(t,e,r,i),i}static SlerpToRef(t,e,r,i){let s,o;let n=t._x*e._x+t._y*e._y+t._z*e._z+t._w*e._w,a=!1;if(n<0&&(a=!0,n=-n),n>.999999)o=1-r,s=a?-r:r;else{let t=Math.acos(n),e=1/Math.sin(t);o=Math.sin((1-r)*t)*e,s=a?-Math.sin(r*t)*e:Math.sin(r*t)*e}return i._x=o*t._x+s*e._x,i._y=o*t._y+s*e._y,i._z=o*t._z+s*e._z,i._w=o*t._w+s*e._w,i._isDirty=!0,i}static Hermite(t,e,r,i,s){let o=s*s,n=s*o,a=2*n-3*o+1,h=-2*n+3*o,_=n-2*o+s,l=n-o,c=t._x*a+r._x*h+e._x*_+i._x*l,u=t._y*a+r._y*h+e._y*_+i._y*l,y=t._z*a+r._z*h+e._z*_+i._z*l,m=t._w*a+r._w*h+e._w*_+i._w*l;return new t.constructor(c,u,y,m)}static Hermite1stDerivative(t,e,r,i,s){let o=new t.constructor;return this.Hermite1stDerivativeToRef(t,e,r,i,s,o),o}static Hermite1stDerivativeToRef(t,e,r,i,s,o){let n=s*s;return o._x=(n-s)*6*t._x+(3*n-4*s+1)*e._x+(-n+s)*6*r._x+(3*n-2*s)*i._x,o._y=(n-s)*6*t._y+(3*n-4*s+1)*e._y+(-n+s)*6*r._y+(3*n-2*s)*i._y,o._z=(n-s)*6*t._z+(3*n-4*s+1)*e._z+(-n+s)*6*r._z+(3*n-2*s)*i._z,o._w=(n-s)*6*t._w+(3*n-4*s+1)*e._w+(-n+s)*6*r._w+(3*n-2*s)*i._w,o._isDirty=!0,o}static Normalize(t){let e=y.Zero();return y.NormalizeToRef(t,e),e}static NormalizeToRef(t,e){return t.normalizeToRef(e),e}}class m{static get Use64Bits(){return a.Z.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=m._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(t,e=!1,r=!1,i=!0){this._isIdentity=t,this._isIdentity3x2=t||r,this._isIdentityDirty=!this._isIdentity&&e,this._isIdentity3x2Dirty=!this._isIdentity3x2&&i}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,a.Z.MatrixTrackPrecisionChange&&a.Z.MatrixTrackedMatrices.push(this),this._m=new a.Z.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;let t=this._m;this._isIdentity=1===t[0]&&0===t[1]&&0===t[2]&&0===t[3]&&0===t[4]&&1===t[5]&&0===t[6]&&0===t[7]&&0===t[8]&&0===t[9]&&1===t[10]&&0===t[11]&&0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]?this._isIdentity3x2=!1: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;let t=this._m,e=t[0],r=t[1],i=t[2],s=t[3],o=t[4],n=t[5],a=t[6],h=t[7],_=t[8],l=t[9],c=t[10],u=t[11],y=t[12],m=t[13],x=t[14],R=t[15],f=c*R-x*u,z=l*R-m*u,d=l*x-m*c,T=_*R-y*u,w=_*x-c*y,F=_*m-y*l;return e*+(n*f-a*z+h*d)+-(r*(o*f-a*T+h*w))+i*+(o*z-n*T+h*F)+-(s*(o*d-n*w+a*F))}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} +${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} +${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} +${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(){return this._m}asArray(){return this._m}invert(){return this.invertToRef(this),this}reset(){return m.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(t){let e=new this.constructor;return this.addToRef(t,e),e}addToRef(t,e){let r=this._m,i=e._m,s=t.m;for(let t=0;t<16;t++)i[t]=r[t]+s[t];return e.markAsUpdated(),e}addToSelf(t){let e=this._m,r=t.m;for(let t=0;t<16;t++)e[t]+=r[t];return this.markAsUpdated(),this}invertToRef(t){if(!0===this._isIdentity)return m.IdentityToRef(t),t;let e=this._m,r=e[0],i=e[1],s=e[2],o=e[3],n=e[4],a=e[5],h=e[6],_=e[7],l=e[8],c=e[9],u=e[10],y=e[11],x=e[12],R=e[13],f=e[14],z=e[15],d=u*z-f*y,T=c*z-R*y,w=c*f-R*u,F=l*z-x*y,p=l*f-u*x,M=l*R-x*c,I=+(a*d-h*T+_*w),g=-(n*d-h*F+_*p),D=+(n*T-a*F+_*M),P=-(n*w-a*p+h*M),A=r*I+i*g+s*D+o*P;if(0===A)return t.copyFrom(this),t;let V=1/A,L=h*z-f*_,C=a*z-R*_,O=a*f-R*h,H=n*z-x*_,k=n*f-x*h,v=n*R-x*a,S=h*y-u*_,B=a*y-c*_,b=a*u-c*h,Z=n*y-l*_,U=n*u-l*h,N=n*c-l*a;return m.FromValuesToRef(I*V,-(i*d-s*T+o*w)*V,+(i*L-s*C+o*O)*V,-(i*S-s*B+o*b)*V,g*V,+(r*d-s*F+o*p)*V,-(r*L-s*H+o*k)*V,+(r*S-s*Z+o*U)*V,D*V,-(r*T-i*F+o*M)*V,+(r*C-i*H+o*v)*V,-(r*B-i*Z+o*N)*V,P*V,+(r*w-i*p+s*M)*V,-(r*O-i*k+s*v)*V,+(r*b-i*U+s*N)*V,t),t}addAtIndex(t,e){return this._m[t]+=e,this.markAsUpdated(),this}multiplyAtIndex(t,e){return this._m[t]*=e,this.markAsUpdated(),this}setTranslationFromFloats(t,e,r){return this._m[12]=t,this._m[13]=e,this._m[14]=r,this.markAsUpdated(),this}addTranslationFromFloats(t,e,r){return this._m[12]+=t,this._m[13]+=e,this._m[14]+=r,this.markAsUpdated(),this}setTranslation(t){return this.setTranslationFromFloats(t._x,t._y,t._z)}getTranslation(){return new c(this._m[12],this._m[13],this._m[14])}getTranslationToRef(t){return t.x=this._m[12],t.y=this._m[13],t.z=this._m[14],t}removeRotationAndScaling(){let t=this.m;return m.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t[12],t[13],t[14],t[15],this),this._updateIdentityStatus(0===t[12]&&0===t[13]&&0===t[14]&&1===t[15]),this}multiply(t){let e=new this.constructor;return this.multiplyToRef(t,e),e}copyFrom(t){return t.copyToArray(this._m),this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(t,e=0){let r=this._m;return t[e]=r[0],t[e+1]=r[1],t[e+2]=r[2],t[e+3]=r[3],t[e+4]=r[4],t[e+5]=r[5],t[e+6]=r[6],t[e+7]=r[7],t[e+8]=r[8],t[e+9]=r[9],t[e+10]=r[10],t[e+11]=r[11],t[e+12]=r[12],t[e+13]=r[13],t[e+14]=r[14],t[e+15]=r[15],this}multiplyToRef(t,e){return this._isIdentity?e.copyFrom(t):t._isIdentity?e.copyFrom(this):(this.multiplyToArray(t,e._m,0),e.markAsUpdated()),e}multiplyToArray(t,e,r){let i=this._m,s=t.m,o=i[0],n=i[1],a=i[2],h=i[3],_=i[4],l=i[5],c=i[6],u=i[7],y=i[8],m=i[9],x=i[10],R=i[11],f=i[12],z=i[13],d=i[14],T=i[15],w=s[0],F=s[1],p=s[2],M=s[3],I=s[4],g=s[5],D=s[6],P=s[7],A=s[8],V=s[9],L=s[10],C=s[11],O=s[12],H=s[13],k=s[14],v=s[15];return e[r]=o*w+n*I+a*A+h*O,e[r+1]=o*F+n*g+a*V+h*H,e[r+2]=o*p+n*D+a*L+h*k,e[r+3]=o*M+n*P+a*C+h*v,e[r+4]=_*w+l*I+c*A+u*O,e[r+5]=_*F+l*g+c*V+u*H,e[r+6]=_*p+l*D+c*L+u*k,e[r+7]=_*M+l*P+c*C+u*v,e[r+8]=y*w+m*I+x*A+R*O,e[r+9]=y*F+m*g+x*V+R*H,e[r+10]=y*p+m*D+x*L+R*k,e[r+11]=y*M+m*P+x*C+R*v,e[r+12]=f*w+z*I+d*A+T*O,e[r+13]=f*F+z*g+d*V+T*H,e[r+14]=f*p+z*D+d*L+T*k,e[r+15]=f*M+z*P+d*C+T*v,this}equals(t){if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;let e=this.m,r=t.m;return e[0]===r[0]&&e[1]===r[1]&&e[2]===r[2]&&e[3]===r[3]&&e[4]===r[4]&&e[5]===r[5]&&e[6]===r[6]&&e[7]===r[7]&&e[8]===r[8]&&e[9]===r[9]&&e[10]===r[10]&&e[11]===r[11]&&e[12]===r[12]&&e[13]===r[13]&&e[14]===r[14]&&e[15]===r[15]}clone(){let t=new this.constructor;return t.copyFrom(this),t}getClassName(){return"Matrix"}getHashCode(){let t=_(this._m[0]);for(let e=1;e<16;e++)t=397*t^_(this._m[e]);return t}decomposeToTransformNode(t){return t.rotationQuaternion=t.rotationQuaternion||new y,this.decompose(t.scaling,t.rotationQuaternion,t.position)}decompose(t,e,r,i,s=!0){if(this._isIdentity)return r&&r.setAll(0),t&&t.setAll(1),e&&e.copyFromFloats(0,0,0,1),!0;let o=this._m;if(r&&r.copyFromFloats(o[12],o[13],o[14]),(t=t||x.Vector3[0]).x=Math.sqrt(o[0]*o[0]+o[1]*o[1]+o[2]*o[2]),t.y=Math.sqrt(o[4]*o[4]+o[5]*o[5]+o[6]*o[6]),t.z=Math.sqrt(o[8]*o[8]+o[9]*o[9]+o[10]*o[10]),i){let e=(s?i.absoluteScaling.x:i.scaling.x)<0?-1:1,r=(s?i.absoluteScaling.y:i.scaling.y)<0?-1:1,o=(s?i.absoluteScaling.z:i.scaling.z)<0?-1:1;t.x*=e,t.y*=r,t.z*=o}else 0>=this.determinant()&&(t.y*=-1);if(0===t._x||0===t._y||0===t._z)return e&&e.copyFromFloats(0,0,0,1),!1;if(e){let r=1/t._x,i=1/t._y,s=1/t._z;m.FromValuesToRef(o[0]*r,o[1]*r,o[2]*r,0,o[4]*i,o[5]*i,o[6]*i,0,o[8]*s,o[9]*s,o[10]*s,0,0,0,0,1,x.Matrix[0]),y.FromRotationMatrixToRef(x.Matrix[0],e)}return!0}getRow(t){if(t<0||t>3)return null;let e=4*t;return new u(this._m[e+0],this._m[e+1],this._m[e+2],this._m[e+3])}getRowToRef(t,e){if(t>=0&&t<=3){let r=4*t;e.x=this._m[r+0],e.y=this._m[r+1],e.z=this._m[r+2],e.w=this._m[r+3]}return e}setRow(t,e){return this.setRowFromFloats(t,e.x,e.y,e.z,e.w)}transpose(){let t=new this.constructor;return m.TransposeToRef(this,t),t}transposeToRef(t){return m.TransposeToRef(this,t),t}setRowFromFloats(t,e,r,i,s){if(t<0||t>3)return this;let o=4*t;return this._m[o+0]=e,this._m[o+1]=r,this._m[o+2]=i,this._m[o+3]=s,this.markAsUpdated(),this}scale(t){let e=new this.constructor;return this.scaleToRef(t,e),e}scaleToRef(t,e){for(let r=0;r<16;r++)e._m[r]=this._m[r]*t;return e.markAsUpdated(),e}scaleAndAddToRef(t,e){for(let r=0;r<16;r++)e._m[r]+=this._m[r]*t;return e.markAsUpdated(),e}toNormalMatrix(t){let e=x.Matrix[0];this.invertToRef(e),e.transposeToRef(t);let r=t._m;return m.FromValuesToRef(r[0],r[1],r[2],0,r[4],r[5],r[6],0,r[8],r[9],r[10],0,0,0,0,1,t),t}getRotationMatrix(){let t=new this.constructor;return this.getRotationMatrixToRef(t),t}getRotationMatrixToRef(t){let e=x.Vector3[0];if(!this.decompose(e))return m.IdentityToRef(t),t;let r=this._m,i=1/e._x,s=1/e._y,o=1/e._z;return m.FromValuesToRef(r[0]*i,r[1]*i,r[2]*i,0,r[4]*s,r[5]*s,r[6]*s,0,r[8]*o,r[9]*o,r[10]*o,0,0,0,0,1,t),t}toggleModelMatrixHandInPlace(){let t=this._m;return t[2]*=-1,t[6]*=-1,t[8]*=-1,t[9]*=-1,t[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){let t=this._m;return t[8]*=-1,t[9]*=-1,t[10]*=-1,t[11]*=-1,this.markAsUpdated(),this}static FromArray(t,e=0){let r=new m;return m.FromArrayToRef(t,e,r),r}static FromArrayToRef(t,e,r){for(let i=0;i<16;i++)r._m[i]=t[i+e];return r.markAsUpdated(),r}static FromFloat32ArrayToRefScaled(t,e,r,i){for(let s=0;s<16;s++)i._m[s]=t[s+e]*r;return i.markAsUpdated(),i}static get IdentityReadOnly(){return m._IdentityReadOnly}static FromValuesToRef(t,e,r,i,s,o,n,a,h,_,l,c,u,y,m,x,R){let f=R._m;f[0]=t,f[1]=e,f[2]=r,f[3]=i,f[4]=s,f[5]=o,f[6]=n,f[7]=a,f[8]=h,f[9]=_,f[10]=l,f[11]=c,f[12]=u,f[13]=y,f[14]=m,f[15]=x,R.markAsUpdated()}static FromValues(t,e,r,i,s,o,n,a,h,_,l,c,u,y,x,R){let f=new m,z=f._m;return z[0]=t,z[1]=e,z[2]=r,z[3]=i,z[4]=s,z[5]=o,z[6]=n,z[7]=a,z[8]=h,z[9]=_,z[10]=l,z[11]=c,z[12]=u,z[13]=y,z[14]=x,z[15]=R,f.markAsUpdated(),f}static Compose(t,e,r){let i=new m;return m.ComposeToRef(t,e,r,i),i}static ComposeToRef(t,e,r,i){let s=i._m,o=e._x,n=e._y,a=e._z,h=e._w,_=o+o,l=n+n,c=a+a,u=o*_,y=o*l,m=o*c,x=n*l,R=n*c,f=a*c,z=h*_,d=h*l,T=h*c,w=t._x,F=t._y,p=t._z;return s[0]=(1-(x+f))*w,s[1]=(y+T)*w,s[2]=(m-d)*w,s[3]=0,s[4]=(y-T)*F,s[5]=(1-(u+f))*F,s[6]=(R+z)*F,s[7]=0,s[8]=(m+d)*p,s[9]=(R-z)*p,s[10]=(1-(u+x))*p,s[11]=0,s[12]=r._x,s[13]=r._y,s[14]=r._z,s[15]=1,i.markAsUpdated(),i}static Identity(){let t=m.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return t._updateIdentityStatus(!0),t}static IdentityToRef(t){return m.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(!0),t}static Zero(){let t=m.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return t._updateIdentityStatus(!1),t}static RotationX(t){let e=new m;return m.RotationXToRef(t,e),e}static Invert(t){let e=new t.constructor;return t.invertToRef(e),e}static RotationXToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return m.FromValuesToRef(1,0,0,0,0,i,r,0,0,-r,i,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationY(t){let e=new m;return m.RotationYToRef(t,e),e}static RotationYToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return m.FromValuesToRef(i,0,-r,0,0,1,0,0,r,0,i,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationZ(t){let e=new m;return m.RotationZToRef(t,e),e}static RotationZToRef(t,e){let r=Math.sin(t),i=Math.cos(t);return m.FromValuesToRef(i,r,0,0,-r,i,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(1===i&&0===r),e}static RotationAxis(t,e){let r=new m;return m.RotationAxisToRef(t,e,r),r}static RotationAxisToRef(t,e,r){let i=Math.sin(-e),s=Math.cos(-e),o=1-s;t.normalize();let n=r._m;return n[0]=t._x*t._x*o+s,n[1]=t._x*t._y*o-t._z*i,n[2]=t._x*t._z*o+t._y*i,n[3]=0,n[4]=t._y*t._x*o+t._z*i,n[5]=t._y*t._y*o+s,n[6]=t._y*t._z*o-t._x*i,n[7]=0,n[8]=t._z*t._x*o-t._y*i,n[9]=t._z*t._y*o+t._x*i,n[10]=t._z*t._z*o+s,n[11]=0,n[12]=0,n[13]=0,n[14]=0,n[15]=1,r.markAsUpdated(),r}static RotationAlignToRef(t,e,r,i=!1){let o=c.Dot(e,t),n=r._m;if(o<-1+s.kn)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{let r=c.Cross(e,t),i=1/(1+o);n[0]=r._x*r._x*i+o,n[1]=r._y*r._x*i-r._z,n[2]=r._z*r._x*i+r._y,n[3]=0,n[4]=r._x*r._y*i+r._z,n[5]=r._y*r._y*i+o,n[6]=r._z*r._y*i-r._x,n[7]=0,n[8]=r._x*r._z*i-r._y,n[9]=r._y*r._z*i+r._x,n[10]=r._z*r._z*i+o,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,r.markAsUpdated(),r}static RotationYawPitchRoll(t,e,r){let i=new m;return m.RotationYawPitchRollToRef(t,e,r,i),i}static RotationYawPitchRollToRef(t,e,r,i){return y.RotationYawPitchRollToRef(t,e,r,x.Quaternion[0]),x.Quaternion[0].toRotationMatrix(i),i}static Scaling(t,e,r){let i=new m;return m.ScalingToRef(t,e,r,i),i}static ScalingToRef(t,e,r,i){return m.FromValuesToRef(t,0,0,0,0,e,0,0,0,0,r,0,0,0,0,1,i),i._updateIdentityStatus(1===t&&1===e&&1===r),i}static Translation(t,e,r){let i=new m;return m.TranslationToRef(t,e,r,i),i}static TranslationToRef(t,e,r,i){return m.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,e,r,1,i),i._updateIdentityStatus(0===t&&0===e&&0===r),i}static Lerp(t,e,r){let i=new t.constructor;return m.LerpToRef(t,e,r,i),i}static LerpToRef(t,e,r,i){let s=i._m,o=t.m,n=e.m;for(let t=0;t<16;t++)s[t]=o[t]*(1-r)+n[t]*r;return i.markAsUpdated(),i}static DecomposeLerp(t,e,r){let i=new t.constructor;return m.DecomposeLerpToRef(t,e,r,i),i}static DecomposeLerpToRef(t,e,r,i){let s=x.Vector3[0],o=x.Quaternion[0],n=x.Vector3[1];t.decompose(s,o,n);let a=x.Vector3[2],h=x.Quaternion[1],_=x.Vector3[3];e.decompose(a,h,_);let l=x.Vector3[4];c.LerpToRef(s,a,r,l);let u=x.Quaternion[2];y.SlerpToRef(o,h,r,u);let R=x.Vector3[5];return c.LerpToRef(n,_,r,R),m.ComposeToRef(l,u,R,i),i}static LookAtLH(t,e,r){let i=new m;return m.LookAtLHToRef(t,e,r,i),i}static LookAtLHToRef(t,e,r,i){let s=x.Vector3[0],o=x.Vector3[1],n=x.Vector3[2];e.subtractToRef(t,n),n.normalize(),c.CrossToRef(r,n,s);let a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),c.CrossToRef(n,s,o),o.normalize();let h=-c.Dot(s,t),_=-c.Dot(o,t),l=-c.Dot(n,t);return m.FromValuesToRef(s._x,o._x,n._x,0,s._y,o._y,n._y,0,s._z,o._z,n._z,0,h,_,l,1,i),i}static LookAtRH(t,e,r){let i=new m;return m.LookAtRHToRef(t,e,r,i),i}static LookAtRHToRef(t,e,r,i){let s=x.Vector3[0],o=x.Vector3[1],n=x.Vector3[2];t.subtractToRef(e,n),n.normalize(),c.CrossToRef(r,n,s);let a=s.lengthSquared();0===a?s.x=1:s.normalizeFromLength(Math.sqrt(a)),c.CrossToRef(n,s,o),o.normalize();let h=-c.Dot(s,t),_=-c.Dot(o,t),l=-c.Dot(n,t);return m.FromValuesToRef(s._x,o._x,n._x,0,s._y,o._y,n._y,0,s._z,o._z,n._z,0,h,_,l,1,i),i}static LookDirectionLH(t,e){let r=new m;return m.LookDirectionLHToRef(t,e,r),r}static LookDirectionLHToRef(t,e,r){let i=x.Vector3[0];i.copyFrom(t),i.scaleInPlace(-1);let s=x.Vector3[1];return c.CrossToRef(e,i,s),m.FromValuesToRef(s._x,s._y,s._z,0,e._x,e._y,e._z,0,i._x,i._y,i._z,0,0,0,0,1,r),r}static LookDirectionRH(t,e){let r=new m;return m.LookDirectionRHToRef(t,e,r),r}static LookDirectionRHToRef(t,e,r){let i=x.Vector3[2];return c.CrossToRef(e,t,i),m.FromValuesToRef(i._x,i._y,i._z,0,e._x,e._y,e._z,0,t._x,t._y,t._z,0,0,0,0,1,r),r}static OrthoLH(t,e,r,i,s){let o=new m;return m.OrthoLHToRef(t,e,r,i,o,s),o}static OrthoLHToRef(t,e,r,i,s,o){let n=2/t,a=2/e,h=2/(i-r),_=-(i+r)/(i-r);return m.FromValuesToRef(n,0,0,0,0,a,0,0,0,0,h,0,0,0,_,1,s),o&&s.multiplyToRef(f,s),s._updateIdentityStatus(1===n&&1===a&&1===h&&0===_),s}static OrthoOffCenterLH(t,e,r,i,s,o,n){let a=new m;return m.OrthoOffCenterLHToRef(t,e,r,i,s,o,a,n),a}static OrthoOffCenterLHToRef(t,e,r,i,s,o,n,a){return m.FromValuesToRef(2/(e-t),0,0,0,0,2/(i-r),0,0,0,0,2/(o-s),0,(t+e)/(t-e),(i+r)/(r-i),-(o+s)/(o-s),1,n),a&&n.multiplyToRef(f,n),n.markAsUpdated(),n}static ObliqueOffCenterLHToRef(t,e,r,i,s,o,n,a,h,_,l){let c=-n*Math.cos(a),u=-n*Math.sin(a);return m.TranslationToRef(0,0,-h,x.Matrix[1]),m.FromValuesToRef(1,0,0,0,0,1,0,0,c,u,1,0,0,0,0,1,x.Matrix[0]),x.Matrix[1].multiplyToRef(x.Matrix[0],x.Matrix[0]),m.TranslationToRef(0,0,h,x.Matrix[1]),x.Matrix[0].multiplyToRef(x.Matrix[1],x.Matrix[0]),m.OrthoOffCenterLHToRef(t,e,r,i,s,o,_,l),x.Matrix[0].multiplyToRef(_,_),_}static OrthoOffCenterRH(t,e,r,i,s,o,n){let a=new m;return m.OrthoOffCenterRHToRef(t,e,r,i,s,o,a,n),a}static OrthoOffCenterRHToRef(t,e,r,i,s,o,n,a){return m.OrthoOffCenterLHToRef(t,e,r,i,s,o,n,a),n._m[10]*=-1,n}static ObliqueOffCenterRHToRef(t,e,r,i,s,o,n,a,h,_,l){let c=n*Math.cos(a),u=n*Math.sin(a);return m.TranslationToRef(0,0,h,x.Matrix[1]),m.FromValuesToRef(1,0,0,0,0,1,0,0,c,u,1,0,0,0,0,1,x.Matrix[0]),x.Matrix[1].multiplyToRef(x.Matrix[0],x.Matrix[0]),m.TranslationToRef(0,0,-h,x.Matrix[1]),x.Matrix[0].multiplyToRef(x.Matrix[1],x.Matrix[0]),m.OrthoOffCenterRHToRef(t,e,r,i,s,o,_,l),x.Matrix[0].multiplyToRef(_,_),_}static PerspectiveLH(t,e,r,i,s,o=0){let n=new m;return m.FromValuesToRef(2*r/t,0,0,0,0,2*r/e,0,Math.tan(o),0,0,(i+r)/(i-r),1,0,0,-2*i*r/(i-r),0,n),s&&n.multiplyToRef(f,n),n._updateIdentityStatus(!1),n}static PerspectiveFovLH(t,e,r,i,s,o=0,n=!1){let a=new m;return m.PerspectiveFovLHToRef(t,e,r,i,a,!0,s,o,n),a}static PerspectiveFovLHToRef(t,e,r,i,s,o=!0,n,a=0,h=!1){let _=1/Math.tan(.5*t),l=o?_/e:_,c=o?_:_*e,u=h&&0===r?-1:0!==i?(i+r)/(i-r):1,y=h&&0===r?2*i:0!==i?-2*i*r/(i-r):-2*r;return m.FromValuesToRef(l,0,0,0,0,c,0,Math.tan(a),0,0,u,1,0,0,y,0,s),n&&s.multiplyToRef(f,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseLHToRef(t,e,r,i,s,o=!0,n,a=0){let h=1/Math.tan(.5*t),_=o?h/e:h,l=o?h:h*e;return m.FromValuesToRef(_,0,0,0,0,l,0,Math.tan(a),0,0,-r,1,0,0,1,0,s),n&&s.multiplyToRef(f,s),s._updateIdentityStatus(!1),s}static PerspectiveFovRH(t,e,r,i,s,o=0,n=!1){let a=new m;return m.PerspectiveFovRHToRef(t,e,r,i,a,!0,s,o,n),a}static PerspectiveFovRHToRef(t,e,r,i,s,o=!0,n,a=0,h=!1){let _=1/Math.tan(.5*t),l=o?_/e:_,c=o?_:_*e,u=h&&0===r?1:0!==i?-(i+r)/(i-r):-1,y=h&&0===r?2*i:0!==i?-2*i*r/(i-r):-2*r;return m.FromValuesToRef(l,0,0,0,0,c,0,Math.tan(a),0,0,u,-1,0,0,y,0,s),n&&s.multiplyToRef(f,s),s._updateIdentityStatus(!1),s}static PerspectiveFovReverseRHToRef(t,e,r,i,s,o=!0,n,a=0){let h=1/Math.tan(.5*t),_=o?h/e:h,l=o?h:h*e;return m.FromValuesToRef(_,0,0,0,0,l,0,Math.tan(a),0,0,-r,-1,0,0,-1,0,s),n&&s.multiplyToRef(f,s),s._updateIdentityStatus(!1),s}static GetFinalMatrix(t,e,r,i,s,o){let n=t.width,a=t.height,h=t.x,_=t.y,l=m.FromValues(n/2,0,0,0,0,-a/2,0,0,0,0,o-s,0,h+n/2,a/2+_,s,1),c=new e.constructor;return e.multiplyToRef(r,c),c.multiplyToRef(i,c),c.multiplyToRef(l,c)}static GetAsMatrix2x2(t){let e=t.m,r=[e[0],e[1],e[4],e[5]];return a.Z.MatrixUse64Bits?r:new Float32Array(r)}static GetAsMatrix3x3(t){let e=t.m,r=[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]];return a.Z.MatrixUse64Bits?r:new Float32Array(r)}static Transpose(t){let e=new t.constructor;return m.TransposeToRef(t,e),e}static TransposeToRef(t,e){let r=t.m,i=r[0],s=r[4],o=r[8],n=r[12],a=r[1],h=r[5],_=r[9],l=r[13],c=r[2],u=r[6],y=r[10],m=r[14],x=r[3],R=r[7],f=r[11],z=r[15],d=e._m;return d[0]=i,d[1]=s,d[2]=o,d[3]=n,d[4]=a,d[5]=h,d[6]=_,d[7]=l,d[8]=c,d[9]=u,d[10]=y,d[11]=m,d[12]=x,d[13]=R,d[14]=f,d[15]=z,e.markAsUpdated(),e._updateIdentityStatus(t._isIdentity,t._isIdentityDirty),e}static Reflection(t){let e=new m;return m.ReflectionToRef(t,e),e}static ReflectionToRef(t,e){t.normalize();let r=t.normal.x,i=t.normal.y,s=t.normal.z,o=-2*r,n=-2*i,a=-2*s;return m.FromValuesToRef(o*r+1,n*r,a*r,0,o*i,n*i+1,a*i,0,o*s,n*s,a*s+1,0,o*t.d,n*t.d,a*t.d,1,e),e}static FromXYZAxesToRef(t,e,r,i){return m.FromValuesToRef(t._x,t._y,t._z,0,e._x,e._y,e._z,0,r._x,r._y,r._z,0,0,0,0,1,i),i}static FromQuaternionToRef(t,e){let r=t._x*t._x,i=t._y*t._y,s=t._z*t._z,o=t._x*t._y,n=t._z*t._w,a=t._z*t._x,h=t._y*t._w,_=t._y*t._z,l=t._x*t._w;return e._m[0]=1-2*(i+s),e._m[1]=2*(o+n),e._m[2]=2*(a-h),e._m[3]=0,e._m[4]=2*(o-n),e._m[5]=1-2*(s+r),e._m[6]=2*(_+l),e._m[7]=0,e._m[8]=2*(a+h),e._m[9]=2*(_-l),e._m[10]=1-2*(i+r),e._m[11]=0,e._m[12]=0,e._m[13]=0,e._m[14]=0,e._m[15]=1,e.markAsUpdated(),e}}m._UpdateFlagSeed=0,m._IdentityReadOnly=m.Identity();class x{}x.Vector3=o.B.BuildTuple(11,c.Zero),x.Matrix=o.B.BuildTuple(2,m.Identity),x.Quaternion=o.B.BuildTuple(3,y.Zero);class R{}R.Vector2=o.B.BuildTuple(3,l.Zero),R.Vector3=o.B.BuildTuple(13,c.Zero),R.Vector4=o.B.BuildTuple(3,u.Zero),R.Quaternion=o.B.BuildTuple(2,y.Zero),R.Matrix=o.B.BuildTuple(8,m.Identity),(0,n.H)("BABYLON.Vector2",l),(0,n.H)("BABYLON.Vector3",c),(0,n.H)("BABYLON.Vector4",u),(0,n.H)("BABYLON.Matrix",m);let f=m.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1)}}]); \ No newline at end of file diff --git a/.next/static/chunks/751.591370f90aaa22a6.js b/.next/static/chunks/751.591370f90aaa22a6.js deleted file mode 100644 index ed21cd4..0000000 --- a/.next/static/chunks/751.591370f90aaa22a6.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[751],{2751:function(n,e,r){r.r(e),r.d(e,{default:function(){return BabylonScene}});var t=r(7437),i=r(2265),s=r(9111),a=r(1128);let BabylonScene=class BabylonScene extends i.PureComponent{componentDidMount(){console.clear(),this.setup(this.canvas)}render(){return(0,t.jsx)(t.Fragment,{children:(0,t.jsx)("canvas",{id:this.id,ref:this.onMount,style:o})})}constructor(...n){super(...n),this.setup=async n=>{s.vGS.ShadersStoreWGSL.starsPixelShader="\n uniform seed : f32;\n uniform density : f32;\n uniform brightness : f32;\n\n fn rand(seed : vec2) -> f32 {\n return fract(sin(dot(seed, vec2(12.9898, 78.233))) * 43758.5453);\n }\n\n @fragment\n fn main(input : FragmentInputs) -> FragmentOutputs {\n\n let random = rand(input.vUV*uniforms.seed);\n var brightness = 0.0;\n if (random < uniforms.density){\n brightness = random/uniforms.density*uniforms.brightness;\n }\n //fragmentOutputs.color = vec4(1., 1., 1., brightness);\n fragmentOutputs.color = vec4(brightness, brightness, brightness, 1.);\n }\n ",s.vGS.ShadersStoreWGSL.nebulasPixelShader="\n var textureSampler: texture_2d;\n var textureSamplerSampler: sampler;\n\n uniform seed: f32;\n uniform color: vec4;\n uniform nebulascale: u32;\n uniform depth: u32;\n uniform intensity: f32;\n uniform falloff: f32;\n uniform persistence: f32;\n\n fn mod289(x: vec2) -> vec2 {\n return x - floor(x * (1. / 289.)) * 289.;\n }\n \n fn mod289_3(x: vec3) -> vec3 {\n return x - floor(x * (1. / 289.)) * 289.;\n }\n \n fn permute3(x: vec3) -> vec3 {\n return mod289_3(((x * 34.) + 1.) * x);\n }\n \n // MIT License. \xa9 Ian McEwan, Stefan Gustavson, Munrocket\n fn simplexNoise2(v: vec2) -> f32 {\n let C = vec4(\n 0.211324865405187, // (3.0-sqrt(3.0))/6.0\n 0.366025403784439, // 0.5*(sqrt(3.0)-1.0)\n -0.577350269189626, // -1.0 + 2.0 * C.x\n 0.024390243902439 // 1.0 / 41.0\n );\n \n // First corner\n var i = floor(v + dot(v, C.yy));\n let x0 = v - i + dot(i, C.xx);\n \n // Other corners\n var i1 = select(vec2(0., 1.), vec2(1., 0.), x0.x > x0.y);\n \n // x0 = x0 - 0.0 + 0.0 * C.xx ;\n // x1 = x0 - i1 + 1.0 * C.xx ;\n // x2 = x0 - 1.0 + 2.0 * C.xx ;\n var x12 = x0.xyxy + C.xxzz;\n x12.x = x12.x - i1.x;\n x12.y = x12.y - i1.y;\n \n // Permutations\n i = mod289(i); // Avoid truncation effects in permutation\n \n var p = permute3(permute3(i.y + vec3(0., i1.y, 1.)) + i.x + vec3(0., i1.x, 1.));\n var m = max(0.5 - vec3(dot(x0, x0), dot(x12.xy, x12.xy), dot(x12.zw, x12.zw)), vec3(0.));\n m *= m;\n m *= m;\n \n // Gradients: 41 points uniformly over a line, mapped onto a diamond.\n // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)\n let x = 2. * fract(p * C.www) - 1.;\n let h = abs(x) - 0.5;\n let ox = floor(x + 0.5);\n let a0 = x - ox;\n \n // Normalize gradients implicitly by scaling m\n // Approximation of: m *= inversesqrt( a0*a0 + h*h );\n m *= 1.79284291400159 - 0.85373472095314 * (a0 * a0 + h * h);\n \n // Compute final noise value at P\n let g = vec3(a0.x * x0.x + h.x * x0.y, a0.yz * x12.xz + h.yz * x12.yw);\n return 130. * dot(m, g);\n }\n\n fn normalNoise(v: vec2) -> f32 {\n return simplexNoise2(v)*0.5 + 0.5;\n }\n\n @fragment\n fn main(input : FragmentInputs) -> FragmentOutputs {\n let sampleColor = textureSample(textureSampler,textureSamplerSampler,fragmentInputs.vUV);\n\n var offset = 0.;\n let scaledUV = (input.vUV+offset+uniforms.seed)*f32(uniforms.nebulascale)/uniforms.scale;\n\n var displace = 0.;\n var i=u32(0);\n for (i=0; i{let e;return await s.fWK.IsSupportedAsync?(e=new s.fWK(n),await e.initAsync()):(console.log("WebGPU is not supported (or turned on) for this browser!"),e=new s.fWK(n)),e},this.id="Babylon",this.onMount=n=>this.canvas=n}};let o={width:window.innerWidth,height:window.innerHeight,background:"transparent"}}}]); \ No newline at end of file diff --git a/.next/static/chunks/938-d733aaafb07bca99.js b/.next/static/chunks/938-d733aaafb07bca99.js new file mode 100644 index 0000000..80898b1 --- /dev/null +++ b/.next/static/chunks/938-d733aaafb07bca99.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[938],{5844:function(e,t){"use strict";function r(){return""}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getDeploymentIdQueryOrEmptyString",{enumerable:!0,get:function(){return r}})},2335:function(){"trimStart"in String.prototype||(String.prototype.trimStart=String.prototype.trimLeft),"trimEnd"in String.prototype||(String.prototype.trimEnd=String.prototype.trimRight),"description"in Symbol.prototype||Object.defineProperty(Symbol.prototype,"description",{configurable:!0,get:function(){var e=/\((.*)\)/.exec(this.toString());return e?e[1]:void 0}}),Array.prototype.flat||(Array.prototype.flat=function(e,t){return t=this.concat.apply([],this),e>1&&t.some(Array.isArray)?t.flat(e-1):t},Array.prototype.flatMap=function(e,t){return this.map(e,t).flat()}),Promise.prototype.finally||(Promise.prototype.finally=function(e){if("function"!=typeof e)return this.then(e,e);var t=this.constructor||Promise;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})}),Object.fromEntries||(Object.fromEntries=function(e){return Array.from(e).reduce(function(e,t){return e[t[0]]=t[1],e},{})}),Array.prototype.at||(Array.prototype.at=function(e){var t=Math.trunc(e)||0;if(t<0&&(t+=this.length),!(t<0||t>=this.length))return this[t]})},5786:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addBasePath",{enumerable:!0,get:function(){return u}});let n=r(1312),o=r(2139);function u(e,t){return(0,o.normalizePathTrailingSlash)((0,n.addPathPrefix)(e,""))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6159:function(e,t){"use strict";function r(e){var t,r;t=self.__next_s,r=()=>{e()},t&&t.length?t.reduce((e,t)=>{let[r,n]=t;return e.then(()=>new Promise((e,t)=>{let o=document.createElement("script");if(n)for(let e in n)"children"!==e&&o.setAttribute(e,n[e]);r?(o.src=r,o.onload=()=>e(),o.onerror=t):n&&(o.innerHTML=n.children,setTimeout(e)),document.head.appendChild(o)}))},Promise.resolve()).catch(e=>{console.error(e)}).then(()=>{r()}):r()}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"appBootstrap",{enumerable:!0,get:function(){return r}}),window.next={version:"14.0.4",appDir:!0},("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5355:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"callServer",{enumerable:!0,get:function(){return o}});let n=r(7690);async function o(e,t){let r=(0,n.getServerActionDispatcher)();if(!r)throw Error("Invariant: missing action dispatcher.");return new Promise((n,o)=>{r({actionId:e,actionArgs:t,resolve:n,reject:o})})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},945:function(e,t,r){"use strict";let n,o;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hydrate",{enumerable:!0,get:function(){return M}});let u=r(1024),a=r(8533);r(2335);let l=u._(r(4040)),i=a._(r(2265)),c=r(6671),s=r(3634);r(8599);let f=u._(r(4101)),d=r(5355),p=r(4950),h=r(5367),y=window.console.error;window.console.error=function(){for(var e=arguments.length,t=Array(e),r=0;r{if((0,p.isNextRouterError)(e.error)){e.preventDefault();return}});let _=document,b=()=>{let{pathname:e,search:t}=location;return e+t},v=new TextEncoder,g=!1,m=!1,O=null;function P(e){if(0===e[0])n=[];else if(1===e[0]){if(!n)throw Error("Unexpected server data: missing bootstrap script.");o?o.enqueue(v.encode(e[1])):n.push(e[1])}else 2===e[0]&&(O=e[1])}let E=function(){o&&!m&&(o.close(),m=!0,n=void 0),g=!0};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",E,!1):E();let R=self.__next_f=self.__next_f||[];R.forEach(P),R.push=P;let S=new Map;function j(e){let{cacheKey:t}=e;i.default.useEffect(()=>{S.delete(t)});let r=function(e){let t=S.get(e);if(t)return t;let r=new ReadableStream({start(e){n&&(n.forEach(t=>{e.enqueue(v.encode(t))}),g&&!m&&(e.close(),m=!0,n=void 0)),o=e}}),u=(0,c.createFromReadableStream)(r,{callServer:d.callServer});return S.set(e,u),u}(t);return(0,i.use)(r)}let T=i.default.StrictMode;function w(e){let{children:t}=e;return t}function C(e){return i.default.createElement(j,{...e,cacheKey:b()})}function M(){let e=(0,h.createMutableActionQueue)(),t=i.default.createElement(T,null,i.default.createElement(s.HeadManagerContext.Provider,{value:{appDir:!0}},i.default.createElement(h.ActionQueueContext.Provider,{value:e},i.default.createElement(w,null,i.default.createElement(C,null))))),r={onRecoverableError:f.default};"__next_error__"===document.documentElement.id?l.default.createRoot(_,r).render(t):i.default.startTransition(()=>l.default.hydrateRoot(_,t,{...r,formState:O}))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5317:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(9590),(0,r(6159).appBootstrap)(()=>{let{hydrate:e}=r(945);r(7690),r(5613),e()}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9590:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(5844);{let e=r.u;r.u=function(){for(var t=arguments.length,r=Array(t),n=0;n(a(function(){var e;let t=document.getElementsByName(u)[0];if(null==t?void 0:null==(e=t.shadowRoot)?void 0:e.childNodes[0])return t.shadowRoot.childNodes[0];{let e=document.createElement(u);e.style.cssText="position:absolute";let t=document.createElement("div");return t.ariaLive="assertive",t.id="__next-route-announcer__",t.role="alert",t.style.cssText="position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal",e.attachShadow({mode:"open"}).appendChild(t),document.body.appendChild(e),t}}()),()=>{let e=document.getElementsByTagName(u)[0];(null==e?void 0:e.isConnected)&&document.body.removeChild(e)}),[]);let[l,i]=(0,n.useState)(""),c=(0,n.useRef)();return(0,n.useEffect)(()=>{let e="";if(document.title)e=document.title;else{let t=document.querySelector("h1");t&&(e=t.innerText||t.textContent||"")}void 0!==c.current&&c.current!==e&&i(e),c.current=e},[t]),r?(0,o.createPortal)(l,r):null}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2275:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RSC_HEADER:function(){return r},ACTION:function(){return n},NEXT_ROUTER_STATE_TREE:function(){return o},NEXT_ROUTER_PREFETCH_HEADER:function(){return u},NEXT_URL:function(){return a},RSC_CONTENT_TYPE_HEADER:function(){return l},RSC_VARY_HEADER:function(){return i},FLIGHT_PARAMETERS:function(){return c},NEXT_RSC_UNION_QUERY:function(){return s},NEXT_DID_POSTPONE_HEADER:function(){return f}});let r="RSC",n="Next-Action",o="Next-Router-State-Tree",u="Next-Router-Prefetch",a="Next-Url",l="text/x-component",i=r+", "+o+", "+u+", "+a,c=[[r],[o],[u]],s="_rsc",f="x-nextjs-postponed";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7690:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{getServerActionDispatcher:function(){return P},urlToUrlWithoutFlightMarker:function(){return R},createEmptyCacheNode:function(){return T},default:function(){return C}});let n=r(8533)._(r(2265)),o=r(8599),u=r(1414),a=r(8419),l=r(4758),i=r(1276),c=r(8955),s=r(4492),f=r(6407),d=r(5786),p=r(2054),h=r(5737),y=r(671),_=r(4399),b=r(2275),v=r(8895),g=r(7379),m=new Map,O=null;function P(){return O}let E={};function R(e){let t=new URL(e,location.origin);return t.searchParams.delete(b.NEXT_RSC_UNION_QUERY),t}function S(e){return e.origin!==window.location.origin}function j(e){let{appRouterState:t,sync:r}=e;return(0,n.useInsertionEffect)(()=>{let{tree:e,pushRef:n,canonicalUrl:o}=t,u={__NA:!0,__PRIVATE_NEXTJS_INTERNALS_TREE:e};n.pendingPush&&(0,a.createHrefFromUrl)(new URL(window.location.href))!==o?(n.pendingPush=!1,window.history.pushState(u,"",o)):window.history.replaceState(u,"",o),r(t)},[t,r]),null}let T=()=>({status:o.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map});function w(e){let{buildId:t,initialHead:r,initialTree:a,initialCanonicalUrl:c,initialSeedData:b,assetPrefix:P}=e,R=(0,n.useMemo)(()=>(0,s.createInitialRouterState)({buildId:t,initialSeedData:b,initialCanonicalUrl:c,initialTree:a,initialParallelRoutes:m,isServer:!1,location:window.location,initialHead:r}),[t,b,c,a,r]),[T,w,C]=(0,i.useReducerWithReduxDevtools)(R);(0,n.useEffect)(()=>{m=null},[]);let{canonicalUrl:M}=(0,i.useUnwrapState)(T),{searchParams:x,pathname:A}=(0,n.useMemo)(()=>{let e=new URL(M,window.location.href);return{searchParams:e.searchParams,pathname:(0,g.hasBasePath)(e.pathname)?(0,v.removeBasePath)(e.pathname):e.pathname}},[M]),N=(0,n.useCallback)((e,t,r)=>{(0,n.startTransition)(()=>{w({type:u.ACTION_SERVER_PATCH,flightData:t,previousTree:e,overrideCanonicalUrl:r})})},[w]),I=(0,n.useCallback)((e,t,r)=>{let n=new URL((0,d.addBasePath)(e),location.href);return w({type:u.ACTION_NAVIGATE,url:n,isExternalUrl:S(n),locationSearch:location.search,shouldScroll:null==r||r,navigateType:t})},[w]);O=(0,n.useCallback)(e=>{(0,n.startTransition)(()=>{w({...e,type:u.ACTION_SERVER_ACTION})})},[w]);let D=(0,n.useMemo)(()=>({back:()=>window.history.back(),forward:()=>window.history.forward(),prefetch:(e,t)=>{if((0,f.isBot)(window.navigator.userAgent))return;let r=new URL((0,d.addBasePath)(e),window.location.href);S(r)||(0,n.startTransition)(()=>{var e;w({type:u.ACTION_PREFETCH,url:r,kind:null!=(e=null==t?void 0:t.kind)?e:u.PrefetchKind.FULL})})},replace:(e,t)=>{void 0===t&&(t={}),(0,n.startTransition)(()=>{var r;I(e,"replace",null==(r=t.scroll)||r)})},push:(e,t)=>{void 0===t&&(t={}),(0,n.startTransition)(()=>{var r;I(e,"push",null==(r=t.scroll)||r)})},refresh:()=>{(0,n.startTransition)(()=>{w({type:u.ACTION_REFRESH,origin:window.location.origin})})},fastRefresh:()=>{throw Error("fastRefresh can only be used in development mode. Please use refresh instead.")}}),[w,I]);(0,n.useEffect)(()=>{window.next&&(window.next.router=D)},[D]),(0,n.useEffect)(()=>{function e(e){var t;e.persisted&&(null==(t=window.history.state)?void 0:t.__PRIVATE_NEXTJS_INTERNALS_TREE)&&w({type:u.ACTION_RESTORE,url:new URL(window.location.href),tree:window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE})}return window.addEventListener("pageshow",e),()=>{window.removeEventListener("pageshow",e)}},[w]);let{pushRef:k}=(0,i.useUnwrapState)(T);if(k.mpaNavigation){if(E.pendingMpaPath!==M){let e=window.location;k.pendingPush?e.assign(M):e.replace(M),E.pendingMpaPath=M}(0,n.use)((0,_.createInfinitePromise)())}(0,n.useEffect)(()=>{window.history.pushState.bind(window.history),window.history.replaceState.bind(window.history);let e=e=>{let{state:t}=e;if(t){if(!t.__NA){window.location.reload();return}(0,n.startTransition)(()=>{w({type:u.ACTION_RESTORE,url:new URL(window.location.href),tree:t.__PRIVATE_NEXTJS_INTERNALS_TREE})})}};return window.addEventListener("popstate",e),()=>{window.removeEventListener("popstate",e)}},[w]);let{cache:F,tree:L,nextUrl:U,focusAndScrollRef:H}=(0,i.useUnwrapState)(T),$=(0,n.useMemo)(()=>(0,y.findHeadInCache)(F,L[1]),[F,L]),B=n.default.createElement(h.RedirectBoundary,null,$,F.subTreeData,n.default.createElement(p.AppRouterAnnouncer,{tree:L}));return n.default.createElement(n.default.Fragment,null,n.default.createElement(j,{appRouterState:(0,i.useUnwrapState)(T),sync:C}),n.default.createElement(l.PathnameContext.Provider,{value:A},n.default.createElement(l.SearchParamsContext.Provider,{value:x},n.default.createElement(o.GlobalLayoutRouterContext.Provider,{value:{buildId:t,changeByServerResponse:N,tree:L,focusAndScrollRef:H,nextUrl:U}},n.default.createElement(o.AppRouterContext.Provider,{value:D},n.default.createElement(o.LayoutRouterContext.Provider,{value:{childNodes:F.parallelRoutes,tree:L,url:M}},B))))))}function C(e){let{globalErrorComponent:t,...r}=e;return n.default.createElement(c.ErrorBoundary,{errorComponent:t},n.default.createElement(w,r))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3706:function(e,t,r){"use strict";function n(e){}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"clientHookInServerComponentError",{enumerable:!0,get:function(){return n}}),r(1024),r(2265),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8955:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ErrorBoundaryHandler:function(){return l},GlobalError:function(){return i},default:function(){return c},ErrorBoundary:function(){return s}});let n=r(1024)._(r(2265)),o=r(5313),u={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},text:{fontSize:"14px",fontWeight:400,lineHeight:"28px",margin:"0 8px"}};function a(e){let{error:t}=e;if("function"==typeof fetch.__nextGetStaticStore){var r;let e=null==(r=fetch.__nextGetStaticStore())?void 0:r.getStore();if((null==e?void 0:e.isRevalidate)||(null==e?void 0:e.isStaticGeneration))throw console.error(t),t}return null}class l extends n.default.Component{static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.error?{error:null,previousPathname:e.pathname}:{error:t.error,previousPathname:e.pathname}}render(){return this.state.error?n.default.createElement(n.default.Fragment,null,n.default.createElement(a,{error:this.state.error}),this.props.errorStyles,this.props.errorScripts,n.default.createElement(this.props.errorComponent,{error:this.state.error,reset:this.reset})):this.props.children}constructor(e){super(e),this.reset=()=>{this.setState({error:null})},this.state={error:null,previousPathname:this.props.pathname}}}function i(e){let{error:t}=e,r=null==t?void 0:t.digest;return n.default.createElement("html",{id:"__next_error__"},n.default.createElement("head",null),n.default.createElement("body",null,n.default.createElement(a,{error:t}),n.default.createElement("div",{style:u.error},n.default.createElement("div",null,n.default.createElement("h2",{style:u.text},"Application error: a "+(r?"server":"client")+"-side exception has occurred (see the "+(r?"server logs":"browser console")+" for more information)."),r?n.default.createElement("p",{style:u.text},"Digest: "+r):null))))}let c=i;function s(e){let{errorComponent:t,errorStyles:r,errorScripts:u,children:a}=e,i=(0,o.usePathname)();return t?n.default.createElement(l,{pathname:i,errorComponent:t,errorStyles:r,errorScripts:u},a):n.default.createElement(n.default.Fragment,null,a)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7127:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{DYNAMIC_ERROR_CODE:function(){return r},DynamicServerError:function(){return n}});let r="DYNAMIC_SERVER_USAGE";class n extends Error{constructor(e){super("Dynamic server usage: "+e),this.digest=r}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4399:function(e,t){"use strict";let r;function n(){return r||(r=new Promise(()=>{})),r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInfinitePromise",{enumerable:!0,get:function(){return n}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4950:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isNextRouterError",{enumerable:!0,get:function(){return u}});let n=r(2322),o=r(6155);function u(e){return e&&e.digest&&((0,o.isRedirectError)(e)||(0,n.isNotFoundError)(e))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5613:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return P}});let n=r(1024),o=r(8533)._(r(2265)),u=n._(r(4887)),a=r(8599),l=r(3546),i=r(4399),c=r(8955),s=r(2295),f=r(3011),d=r(5737),p=r(1902),h=r(6793),y=r(555),_=["bottom","height","left","right","top","width","x","y"];function b(e,t){let r=e.getBoundingClientRect();return r.top>=0&&r.top<=t}class v extends o.default.Component{componentDidMount(){this.handlePotentialScroll()}componentDidUpdate(){this.props.focusAndScrollRef.apply&&this.handlePotentialScroll()}render(){return this.props.children}constructor(...e){super(...e),this.handlePotentialScroll=()=>{let{focusAndScrollRef:e,segmentPath:t}=this.props;if(e.apply){var r;if(0!==e.segmentPaths.length&&!e.segmentPaths.some(e=>t.every((t,r)=>(0,s.matchSegment)(t,e[r]))))return;let n=null,o=e.hashFragment;if(o&&(n="top"===o?document.body:null!=(r=document.getElementById(o))?r:document.getElementsByName(o)[0]),n||(n=u.default.findDOMNode(this)),!(n instanceof Element))return;for(;!(n instanceof HTMLElement)||function(e){if(["sticky","fixed"].includes(getComputedStyle(e).position))return!0;let t=e.getBoundingClientRect();return _.every(e=>0===t[e])}(n);){if(null===n.nextElementSibling)return;n=n.nextElementSibling}e.apply=!1,e.hashFragment=null,e.segmentPaths=[],(0,f.handleSmoothScroll)(()=>{if(o){n.scrollIntoView();return}let e=document.documentElement,t=e.clientHeight;!b(n,t)&&(e.scrollTop=0,b(n,t)||n.scrollIntoView())},{dontForceLayout:!0,onlyHashChange:e.onlyHashChange}),e.onlyHashChange=!1,n.focus()}}}}function g(e){let{segmentPath:t,children:r}=e,n=(0,o.useContext)(a.GlobalLayoutRouterContext);if(!n)throw Error("invariant global layout router not mounted");return o.default.createElement(v,{segmentPath:t,focusAndScrollRef:n.focusAndScrollRef},r)}function m(e){let{parallelRouterKey:t,url:r,childNodes:n,segmentPath:u,tree:c,cacheKey:f}=e,d=(0,o.useContext)(a.GlobalLayoutRouterContext);if(!d)throw Error("invariant global layout router not mounted");let{buildId:p,changeByServerResponse:h,tree:y}=d,_=n.get(f);if(!_||_.status===a.CacheStates.LAZY_INITIALIZED){let e=function e(t,r){if(t){let[n,o]=t,u=2===t.length;if((0,s.matchSegment)(r[0],n)&&r[1].hasOwnProperty(o)){if(u){let t=e(void 0,r[1][o]);return[r[0],{...r[1],[o]:[t[0],t[1],t[2],"refetch"]}]}return[r[0],{...r[1],[o]:e(t.slice(2),r[1][o])}]}}return r}(["",...u],y);_={status:a.CacheStates.DATA_FETCH,data:(0,l.fetchServerResponse)(new URL(r,location.origin),e,d.nextUrl,p),subTreeData:null,head:_&&_.status===a.CacheStates.LAZY_INITIALIZED?_.head:void 0,parallelRoutes:_&&_.status===a.CacheStates.LAZY_INITIALIZED?_.parallelRoutes:new Map},n.set(f,_)}if(!_)throw Error("Child node should always exist");if(_.subTreeData&&_.data)throw Error("Child node should not have both subTreeData and data");if(_.data){let[e,t]=(0,o.use)(_.data);_.data=null,setTimeout(()=>{(0,o.startTransition)(()=>{h(y,e,t)})}),(0,o.use)((0,i.createInfinitePromise)())}return _.subTreeData||(0,o.use)((0,i.createInfinitePromise)()),o.default.createElement(a.LayoutRouterContext.Provider,{value:{tree:c[1][t],childNodes:_.parallelRoutes,url:r}},_.subTreeData)}function O(e){let{children:t,loading:r,loadingStyles:n,loadingScripts:u,hasLoading:a}=e;return a?o.default.createElement(o.Suspense,{fallback:o.default.createElement(o.default.Fragment,null,n,u,r)},t):o.default.createElement(o.default.Fragment,null,t)}function P(e){let{parallelRouterKey:t,segmentPath:r,error:n,errorStyles:u,errorScripts:l,templateStyles:i,templateScripts:s,loading:f,loadingStyles:_,loadingScripts:b,hasLoading:v,template:P,notFound:E,notFoundStyles:R,styles:S}=e,j=(0,o.useContext)(a.LayoutRouterContext);if(!j)throw Error("invariant expected layout router to be mounted");let{childNodes:T,tree:w,url:C}=j,M=T.get(t);M||(M=new Map,T.set(t,M));let x=w[1][t][0],A=(0,h.getSegmentValue)(x),N=[x];return o.default.createElement(o.default.Fragment,null,S,N.map(e=>{let S=(0,h.getSegmentValue)(e),j=(0,y.createRouterCacheKey)(e);return o.default.createElement(a.TemplateContext.Provider,{key:(0,y.createRouterCacheKey)(e,!0),value:o.default.createElement(g,{segmentPath:r},o.default.createElement(c.ErrorBoundary,{errorComponent:n,errorStyles:u,errorScripts:l},o.default.createElement(O,{hasLoading:v,loading:f,loadingStyles:_,loadingScripts:b},o.default.createElement(p.NotFoundBoundary,{notFound:E,notFoundStyles:R},o.default.createElement(d.RedirectBoundary,null,o.default.createElement(m,{parallelRouterKey:t,url:C,tree:w,childNodes:M,segmentPath:r,cacheKey:j,isActive:A===S}))))))},i,s,P)}))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2295:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{matchSegment:function(){return o},canSegmentBeOverridden:function(){return u}});let n=r(5682),o=(e,t)=>"string"==typeof e?"string"==typeof t&&e===t:"string"!=typeof t&&e[0]===t[0]&&e[1]===t[1],u=(e,t)=>{var r;return!Array.isArray(e)&&!!Array.isArray(t)&&(null==(r=(0,n.getSegmentParam)(e))?void 0:r.param)===t[0]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5313:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ReadonlyURLSearchParams:function(){return p},useSearchParams:function(){return h},usePathname:function(){return y},ServerInsertedHTMLContext:function(){return i.ServerInsertedHTMLContext},useServerInsertedHTML:function(){return i.useServerInsertedHTML},useRouter:function(){return _},useParams:function(){return b},useSelectedLayoutSegments:function(){return v},useSelectedLayoutSegment:function(){return g},redirect:function(){return c.redirect},permanentRedirect:function(){return c.permanentRedirect},RedirectType:function(){return c.RedirectType},notFound:function(){return s.notFound}});let n=r(2265),o=r(8599),u=r(4758),a=r(3706),l=r(6793),i=r(2472),c=r(6155),s=r(2322),f=Symbol("internal for urlsearchparams readonly");function d(){return Error("ReadonlyURLSearchParams cannot be modified")}class p{[Symbol.iterator](){return this[f][Symbol.iterator]()}append(){throw d()}delete(){throw d()}set(){throw d()}sort(){throw d()}constructor(e){this[f]=e,this.entries=e.entries.bind(e),this.forEach=e.forEach.bind(e),this.get=e.get.bind(e),this.getAll=e.getAll.bind(e),this.has=e.has.bind(e),this.keys=e.keys.bind(e),this.values=e.values.bind(e),this.toString=e.toString.bind(e),this.size=e.size}}function h(){(0,a.clientHookInServerComponentError)("useSearchParams");let e=(0,n.useContext)(u.SearchParamsContext);return(0,n.useMemo)(()=>e?new p(e):null,[e])}function y(){return(0,a.clientHookInServerComponentError)("usePathname"),(0,n.useContext)(u.PathnameContext)}function _(){(0,a.clientHookInServerComponentError)("useRouter");let e=(0,n.useContext)(o.AppRouterContext);if(null===e)throw Error("invariant expected app router to be mounted");return e}function b(){(0,a.clientHookInServerComponentError)("useParams");let e=(0,n.useContext)(o.GlobalLayoutRouterContext),t=(0,n.useContext)(u.PathParamsContext);return(0,n.useMemo)(()=>(null==e?void 0:e.tree)?function e(t,r){for(let n of(void 0===r&&(r={}),Object.values(t[1]))){let t=n[0],o=Array.isArray(t),u=o?t[1]:t;!u||u.startsWith("__PAGE__")||(o&&("c"===t[2]||"oc"===t[2])?r[t[0]]=t[1].split("/"):o&&(r[t[0]]=t[1]),r=e(n,r))}return r}(e.tree):t,[null==e?void 0:e.tree,t])}function v(e){void 0===e&&(e="children"),(0,a.clientHookInServerComponentError)("useSelectedLayoutSegments");let{tree:t}=(0,n.useContext)(o.LayoutRouterContext);return function e(t,r,n,o){let u;if(void 0===n&&(n=!0),void 0===o&&(o=[]),n)u=t[1][r];else{var a;let e=t[1];u=null!=(a=e.children)?a:Object.values(e)[0]}if(!u)return o;let i=u[0],c=(0,l.getSegmentValue)(i);return!c||c.startsWith("__PAGE__")?o:(o.push(c),e(u,r,!1,o))}(t,e)}function g(e){void 0===e&&(e="children"),(0,a.clientHookInServerComponentError)("useSelectedLayoutSegment");let t=v(e);return 0===t.length?null:t[0]}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1902:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NotFoundBoundary",{enumerable:!0,get:function(){return a}});let n=r(1024)._(r(2265)),o=r(5313);class u extends n.default.Component{static getDerivedStateFromError(e){if((null==e?void 0:e.digest)==="NEXT_NOT_FOUND")return{notFoundTriggered:!0};throw e}static getDerivedStateFromProps(e,t){return e.pathname!==t.previousPathname&&t.notFoundTriggered?{notFoundTriggered:!1,previousPathname:e.pathname}:{notFoundTriggered:t.notFoundTriggered,previousPathname:e.pathname}}render(){return this.state.notFoundTriggered?n.default.createElement(n.default.Fragment,null,n.default.createElement("meta",{name:"robots",content:"noindex"}),!1,this.props.notFoundStyles,this.props.notFound):this.props.children}constructor(e){super(e),this.state={notFoundTriggered:!!e.asNotFound,previousPathname:e.pathname}}}function a(e){let{notFound:t,notFoundStyles:r,asNotFound:a,children:l}=e,i=(0,o.usePathname)();return t?n.default.createElement(u,{pathname:i,notFound:t,notFoundStyles:r,asNotFound:a},l):n.default.createElement(n.default.Fragment,null,l)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2322:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{notFound:function(){return n},isNotFoundError:function(){return o}});let r="NEXT_NOT_FOUND";function n(){let e=Error(r);throw e.digest=r,e}function o(e){return(null==e?void 0:e.digest)===r}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2418:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PromiseQueue",{enumerable:!0,get:function(){return c}});let n=r(4677),o=r(6249);var u=o._("_maxConcurrency"),a=o._("_runningCount"),l=o._("_queue"),i=o._("_processNext");class c{enqueue(e){let t,r;let o=new Promise((e,n)=>{t=e,r=n}),u=async()=>{try{n._(this,a)[a]++;let r=await e();t(r)}catch(e){r(e)}finally{n._(this,a)[a]--,n._(this,i)[i]()}};return n._(this,l)[l].push({promiseFn:o,task:u}),n._(this,i)[i](),o}bump(e){let t=n._(this,l)[l].findIndex(t=>t.promiseFn===e);if(t>-1){let e=n._(this,l)[l].splice(t,1)[0];n._(this,l)[l].unshift(e),n._(this,i)[i](!0)}}constructor(e=5){Object.defineProperty(this,i,{value:s}),Object.defineProperty(this,u,{writable:!0,value:void 0}),Object.defineProperty(this,a,{writable:!0,value:void 0}),Object.defineProperty(this,l,{writable:!0,value:void 0}),n._(this,u)[u]=e,n._(this,a)[a]=0,n._(this,l)[l]=[]}}function s(e){if(void 0===e&&(e=!1),(n._(this,a)[a]0){var t;null==(t=n._(this,l)[l].shift())||t.task()}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5737:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectErrorBoundary:function(){return l},RedirectBoundary:function(){return i}});let n=r(8533)._(r(2265)),o=r(5313),u=r(6155);function a(e){let{redirect:t,reset:r,redirectType:a}=e,l=(0,o.useRouter)();return(0,n.useEffect)(()=>{n.default.startTransition(()=>{a===u.RedirectType.push?l.push(t,{}):l.replace(t,{}),r()})},[t,a,r,l]),null}class l extends n.default.Component{static getDerivedStateFromError(e){if((0,u.isRedirectError)(e))return{redirect:(0,u.getURLFromRedirectError)(e),redirectType:(0,u.getRedirectTypeFromError)(e)};throw e}render(){let{redirect:e,redirectType:t}=this.state;return null!==e&&null!==t?n.default.createElement(a,{redirect:e,redirectType:t,reset:()=>this.setState({redirect:null})}):this.props.children}constructor(e){super(e),this.state={redirect:null,redirectType:null}}}function i(e){let{children:t}=e,r=(0,o.useRouter)();return n.default.createElement(l,{router:r},t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9510:function(e,t){"use strict";var r,n;Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RedirectStatusCode",{enumerable:!0,get:function(){return r}}),(n=r||(r={}))[n.SeeOther=303]="SeeOther",n[n.TemporaryRedirect=307]="TemporaryRedirect",n[n.PermanentRedirect=308]="PermanentRedirect",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6155:function(e,t,r){"use strict";var n,o;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{RedirectType:function(){return n},getRedirectError:function(){return c},redirect:function(){return s},permanentRedirect:function(){return f},isRedirectError:function(){return d},getURLFromRedirectError:function(){return p},getRedirectTypeFromError:function(){return h},getRedirectStatusCodeFromError:function(){return y}});let u=r(6668),a=r(1264),l=r(9510),i="NEXT_REDIRECT";function c(e,t,r){void 0===r&&(r=l.RedirectStatusCode.TemporaryRedirect);let n=Error(i);n.digest=i+";"+t+";"+e+";"+r+";";let o=u.requestAsyncStorage.getStore();return o&&(n.mutableCookies=o.mutableCookies),n}function s(e,t){void 0===t&&(t="replace");let r=a.actionAsyncStorage.getStore();throw c(e,t,(null==r?void 0:r.isAction)?l.RedirectStatusCode.SeeOther:l.RedirectStatusCode.TemporaryRedirect)}function f(e,t){void 0===t&&(t="replace");let r=a.actionAsyncStorage.getStore();throw c(e,t,(null==r?void 0:r.isAction)?l.RedirectStatusCode.SeeOther:l.RedirectStatusCode.PermanentRedirect)}function d(e){if("string"!=typeof(null==e?void 0:e.digest))return!1;let[t,r,n,o]=e.digest.split(";",4),u=Number(o);return t===i&&("replace"===r||"push"===r)&&"string"==typeof n&&!isNaN(u)&&u in l.RedirectStatusCode}function p(e){return d(e)?e.digest.split(";",3)[2]:null}function h(e){if(!d(e))throw Error("Not a redirect error");return e.digest.split(";",2)[1]}function y(e){if(!d(e))throw Error("Not a redirect error");return Number(e.digest.split(";",4)[3])}(o=n||(n={})).push="push",o.replace="replace",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1778:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return u}});let n=r(8533)._(r(2265)),o=r(8599);function u(){let e=(0,n.useContext)(o.TemplateContext);return n.default.createElement(n.default.Fragment,null,e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6668:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"requestAsyncStorage",{enumerable:!0,get:function(){return n}});let n=(0,r(1704).createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},9671:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyFlightData",{enumerable:!0,get:function(){return a}});let n=r(8599),o=r(4765),u=r(0);function a(e,t,r,a){void 0===a&&(a=!1);let[l,i,c]=r.slice(-3);if(null===i)return!1;if(3===r.length){let r=i[2];t.status=n.CacheStates.READY,t.subTreeData=r,(0,o.fillLazyItemsTillLeafWithHead)(t,e,l,i,c,a)}else t.status=n.CacheStates.READY,t.subTreeData=e.subTreeData,t.parallelRoutes=new Map(e.parallelRoutes),(0,u.fillCacheWithNewSubTreeData)(t,e,r,a);return!0}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7098:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"applyRouterStatePatchToTree",{enumerable:!0,get:function(){return function e(t,r,u){let a;let[l,i,,,c]=r;if(1===t.length)return o(r,u);let[s,f]=t;if(!(0,n.matchSegment)(s,l))return null;if(2===t.length)a=o(i[f],u);else if(null===(a=e(t.slice(2),i[f],u)))return null;let d=[t[0],{...i,[f]:a}];return c&&(d[4]=!0),d}}});let n=r(2295);function o(e,t){let[r,u]=e,[a,l]=t;if("__DEFAULT__"===a&&"__DEFAULT__"!==r)return e;if((0,n.matchSegment)(r,a)){let t={};for(let e in u)void 0!==l[e]?t[e]=o(u[e],l[e]):t[e]=u[e];for(let e in l)t[e]||(t[e]=l[e]);let n=[r,t];return e[2]&&(n[2]=e[2]),e[3]&&(n[3]=e[3]),e[4]&&(n[4]=e[4]),n}return t}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4038:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{extractPathFromFlightRouterState:function(){return c},computeChangedPath:function(){return s}});let n=r(4507),o=r(3266),u=r(2295),a=e=>"/"===e[0]?e.slice(1):e,l=e=>"string"==typeof e?e:e[1];function i(e){return e.reduce((e,t)=>""===(t=a(t))||(0,o.isGroupSegment)(t)?e:e+"/"+t,"")||"/"}function c(e){var t;let r=Array.isArray(e[0])?e[0][1]:e[0];if("__DEFAULT__"===r||n.INTERCEPTION_ROUTE_MARKERS.some(e=>r.startsWith(e)))return;if(r.startsWith("__PAGE__"))return"";let o=[r],u=null!=(t=e[1])?t:{},a=u.children?c(u.children):void 0;if(void 0!==a)o.push(a);else for(let[e,t]of Object.entries(u)){if("children"===e)continue;let r=c(t);void 0!==r&&o.push(r)}return i(o)}function s(e,t){let r=function e(t,r){let[o,a]=t,[i,s]=r,f=l(o),d=l(i);if(n.INTERCEPTION_ROUTE_MARKERS.some(e=>f.startsWith(e)||d.startsWith(e)))return"";if(!(0,u.matchSegment)(o,i)){var p;return null!=(p=c(r))?p:""}for(let t in a)if(s[t]){let r=e(a[t],s[t]);if(null!==r)return l(i)+"/"+r}return null}(e,t);return null==r||"/"===r?r:i(r.split("/"))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8419:function(e,t){"use strict";function r(e,t){return void 0===t&&(t=!0),e.pathname+e.search+(t?e.hash:"")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createHrefFromUrl",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4492:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createInitialRouterState",{enumerable:!0,get:function(){return l}});let n=r(8599),o=r(8419),u=r(4765),a=r(4038);function l(e){var t;let{buildId:r,initialTree:l,initialSeedData:i,initialCanonicalUrl:c,initialParallelRoutes:s,isServer:f,location:d,initialHead:p}=e,h=i[2],y={status:n.CacheStates.READY,data:null,subTreeData:h,parallelRoutes:f?new Map:s};return(null===s||0===s.size)&&(0,u.fillLazyItemsTillLeafWithHead)(y,void 0,l,i,p),{buildId:r,tree:l,cache:y,prefetchCache:new Map,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:{apply:!1,onlyHashChange:!1,hashFragment:null,segmentPaths:[]},canonicalUrl:d?(0,o.createHrefFromUrl)(d):c,nextUrl:null!=(t=(0,a.extractPathFromFlightRouterState)(l)||(null==d?void 0:d.pathname))?t:null}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},555:function(e,t){"use strict";function r(e,t){return void 0===t&&(t=!1),Array.isArray(e)?(e[0]+"|"+e[1]+"|"+e[2]).toLowerCase():t&&e.startsWith("__PAGE__")?"__PAGE__":e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createRouterCacheKey",{enumerable:!0,get:function(){return r}}),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3546:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fetchServerResponse",{enumerable:!0,get:function(){return s}});let n=r(2275),o=r(7690),u=r(5355),a=r(1414),l=r(1),{createFromFetch:i}=r(6671);function c(e){return[(0,o.urlToUrlWithoutFlightMarker)(e).toString(),void 0]}async function s(e,t,r,s,f){let d={[n.RSC_HEADER]:"1",[n.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(t))};f===a.PrefetchKind.AUTO&&(d[n.NEXT_ROUTER_PREFETCH_HEADER]="1"),r&&(d[n.NEXT_URL]=r);let p=(0,l.hexHash)([d[n.NEXT_ROUTER_PREFETCH_HEADER]||"0",d[n.NEXT_ROUTER_STATE_TREE],d[n.NEXT_URL]].join(","));try{let t=new URL(e);t.searchParams.set(n.NEXT_RSC_UNION_QUERY,p);let r=await fetch(t,{credentials:"same-origin",headers:d}),a=(0,o.urlToUrlWithoutFlightMarker)(r.url),l=r.redirected?a:void 0,f=r.headers.get("content-type")||"",h=!!r.headers.get(n.NEXT_DID_POSTPONE_HEADER);if(f!==n.RSC_CONTENT_TYPE_HEADER||!r.ok)return e.hash&&(a.hash=e.hash),c(a.toString());let[y,_]=await i(Promise.resolve(r),{callServer:u.callServer});if(s!==y)return c(r.url);return[_,l,h]}catch(t){return console.error("Failed to fetch RSC payload for "+e+". Falling back to browser navigation.",t),[e.toString(),void 0]}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2950:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithDataProperty",{enumerable:!0,get:function(){return function e(t,r,u,a){let l=u.length<=2,[i,c]=u,s=(0,o.createRouterCacheKey)(c),f=r.parallelRoutes.get(i),d=t.parallelRoutes.get(i);d&&d!==f||(d=new Map(f),t.parallelRoutes.set(i,d));let p=null==f?void 0:f.get(s),h=d.get(s);if(l){h&&h.data&&h!==p||d.set(s,{status:n.CacheStates.DATA_FETCH,data:a(),subTreeData:null,parallelRoutes:new Map});return}if(!h||!p){h||d.set(s,{status:n.CacheStates.DATA_FETCH,data:a(),subTreeData:null,parallelRoutes:new Map});return}return h===p&&(h={status:h.status,data:h.data,subTreeData:h.subTreeData,parallelRoutes:new Map(h.parallelRoutes)},d.set(s,h)),e(h,p,u.slice(2),a)}}});let n=r(8599),o=r(555);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},0:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillCacheWithNewSubTreeData",{enumerable:!0,get:function(){return function e(t,r,l,i){let c=l.length<=5,[s,f]=l,d=(0,a.createRouterCacheKey)(f),p=r.parallelRoutes.get(s);if(!p)return;let h=t.parallelRoutes.get(s);h&&h!==p||(h=new Map(p),t.parallelRoutes.set(s,h));let y=p.get(d),_=h.get(d);if(c){if(!_||!_.data||_===y){let e=l[3],t=e[2];_={status:n.CacheStates.READY,data:null,subTreeData:t,parallelRoutes:y?new Map(y.parallelRoutes):new Map},y&&(0,o.invalidateCacheByRouterState)(_,y,l[2]),(0,u.fillLazyItemsTillLeafWithHead)(_,y,l[2],e,l[4],i),h.set(d,_)}return}_&&y&&(_===y&&(_={status:_.status,data:_.data,subTreeData:_.subTreeData,parallelRoutes:new Map(_.parallelRoutes)},h.set(d,_)),e(_,y,l.slice(2),i))}}});let n=r(8599),o=r(6152),u=r(4765),a=r(555);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4765:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"fillLazyItemsTillLeafWithHead",{enumerable:!0,get:function(){return function e(t,r,u,a,l,i){if(0===Object.keys(u[1]).length){t.head=l;return}for(let c in u[1]){let s;let f=u[1][c],d=f[0],p=(0,o.createRouterCacheKey)(d),h=null!==a&&null!==a[1]&&void 0!==a[1][c]?a[1][c]:null;if(r){let o=r.parallelRoutes.get(c);if(o){let r,u=new Map(o),a=u.get(p);if(null!==h){let e=h[2];r={status:n.CacheStates.READY,data:null,subTreeData:e,parallelRoutes:new Map(null==a?void 0:a.parallelRoutes)}}else r=i&&a?{status:a.status,data:a.data,subTreeData:a.subTreeData,parallelRoutes:new Map(a.parallelRoutes)}:{status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map(null==a?void 0:a.parallelRoutes)};u.set(p,r),e(r,a,f,h||null,l,i),t.parallelRoutes.set(c,u);continue}}if(null!==h){let e=h[2];s={status:n.CacheStates.READY,data:null,subTreeData:e,parallelRoutes:new Map}}else s={status:n.CacheStates.LAZY_INITIALIZED,data:null,subTreeData:null,parallelRoutes:new Map};let y=t.parallelRoutes.get(c);y?y.set(p,s):t.parallelRoutes.set(c,new Map([[p,s]])),e(s,void 0,f,h,l,i)}}}});let n=r(8599),o=r(555);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1486:function(e,t){"use strict";var r,n;function o(e){let{kind:t,prefetchTime:r,lastUsedTime:n}=e;return Date.now()<(null!=n?n:r)+3e4?n?"reusable":"fresh":"auto"===t&&Date.now(){let[f,y,_]=t;if(T&&!T.lastUsedTime&&(T.lastUsedTime=Date.now()),"string"==typeof f)return v(e,E,f,j);let m=e.tree,O=e.cache,M=[];for(let t of f){let u=t.slice(0,-4),f=t.slice(-3)[0],d=["",...u],y=(0,i.applyRouterStatePatchToTree)(d,m,f);if(null===y&&(y=(0,i.applyRouterStatePatchToTree)(d,C,f)),null!==y){if((0,s.isNavigatingToNewRootLayout)(m,y))return v(e,E,S,j);let i=(0,b.createEmptyCacheNode)(),P=(0,p.applyFlightData)(O,i,t,(null==T?void 0:T.kind)==="auto"&&w===h.PrefetchCacheEntryStatus.reusable);for(let t of((!P&&w===h.PrefetchCacheEntryStatus.stale||_)&&(P=function(e,t,r,o,u){let a=!1;for(let i of(e.status=n.CacheStates.READY,e.subTreeData=t.subTreeData,e.parallelRoutes=new Map(t.parallelRoutes),g(o).map(e=>[...r,...e])))(0,l.fillCacheWithDataProperty)(e,t,i,u),a=!0;return a}(i,O,u,f,()=>(0,o.fetchServerResponse)(r,m,e.nextUrl,e.buildId))),(0,c.shouldHardNavigate)(d,m)?(i.status=n.CacheStates.READY,i.subTreeData=O.subTreeData,(0,a.invalidateCacheBelowFlightSegmentPath)(i,O,u),E.cache=i):P&&(E.cache=i),O=i,m=y,g(f))){let e=[...u,...t];"__DEFAULT__"!==e[e.length-1]&&M.push(e)}}}return E.patchedTree=m,E.canonicalUrl=y?(0,u.createHrefFromUrl)(y):S,E.pendingPush=j,E.scrollableSegments=M,E.hashFragment=R,E.shouldScroll=P,(0,d.handleMutable)(e,E)},()=>e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5678:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{prefetchQueue:function(){return i},prefetchReducer:function(){return c}});let n=r(8419),o=r(3546),u=r(1414),a=r(7052),l=r(2275),i=new(r(2418)).PromiseQueue(5);function c(e,t){(0,a.prunePrefetchCache)(e.prefetchCache);let{url:r}=t;r.searchParams.delete(l.NEXT_RSC_UNION_QUERY);let c=(0,n.createHrefFromUrl)(r,!1),s=e.prefetchCache.get(c);if(s&&(s.kind===u.PrefetchKind.TEMPORARY&&e.prefetchCache.set(c,{...s,kind:t.kind}),!(s.kind===u.PrefetchKind.AUTO&&t.kind===u.PrefetchKind.FULL)))return e;let f=i.enqueue(()=>(0,o.fetchServerResponse)(r,e.tree,e.nextUrl,e.buildId,t.kind));return e.prefetchCache.set(c,{treeAtTimeOfPrefetch:e.tree,data:f,kind:t.kind,prefetchTime:Date.now(),lastUsedTime:null}),e}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7052:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"prunePrefetchCache",{enumerable:!0,get:function(){return o}});let n=r(1486);function o(e){for(let[t,r]of e)(0,n.getPrefetchEntryCacheStatus)(r)===n.PrefetchCacheEntryStatus.expired&&e.delete(t)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7491:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"refreshReducer",{enumerable:!0,get:function(){return d}});let n=r(3546),o=r(8419),u=r(7098),a=r(1956),l=r(5596),i=r(8875),c=r(8599),s=r(4765),f=r(7690);function d(e,t){let{origin:r}=t,d={},p=e.canonicalUrl,h=e.tree;d.preserveCustomHistoryState=!1;let y=(0,f.createEmptyCacheNode)();return y.data=(0,n.fetchServerResponse)(new URL(p,r),[h[0],h[1],h[2],"refetch"],e.nextUrl,e.buildId),y.data.then(t=>{let[r,n]=t;if("string"==typeof r)return(0,l.handleExternalUrl)(e,d,r,e.pushRef.pendingPush);for(let t of(y.data=null,r)){if(3!==t.length)return console.log("REFRESH FAILED"),e;let[r]=t,i=(0,u.applyRouterStatePatchToTree)([""],h,r);if(null===i)throw Error("SEGMENT MISMATCH");if((0,a.isNavigatingToNewRootLayout)(h,i))return(0,l.handleExternalUrl)(e,d,p,e.pushRef.pendingPush);let f=n?(0,o.createHrefFromUrl)(n):void 0;n&&(d.canonicalUrl=f);let[_,b]=t.slice(-2);if(null!==_){let e=_[2];y.status=c.CacheStates.READY,y.subTreeData=e,(0,s.fillLazyItemsTillLeafWithHead)(y,void 0,r,_,b),d.cache=y,d.prefetchCache=new Map}d.patchedTree=i,d.canonicalUrl=p,h=i}return(0,i.handleMutable)(e,d)},()=>e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7222:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"restoreReducer",{enumerable:!0,get:function(){return u}});let n=r(8419),o=r(4038);function u(e,t){var r;let{url:u,tree:a}=t,l=(0,n.createHrefFromUrl)(u);return{buildId:e.buildId,canonicalUrl:l,pushRef:{pendingPush:!1,mpaNavigation:!1,preserveCustomHistoryState:!0},focusAndScrollRef:e.focusAndScrollRef,cache:e.cache,prefetchCache:e.prefetchCache,tree:a,nextUrl:null!=(r=(0,o.extractPathFromFlightRouterState)(a))?r:u.pathname}}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},899:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverActionReducer",{enumerable:!0,get:function(){return v}});let n=r(5355),o=r(2275),u=r(5786),a=r(8419),l=r(5596),i=r(7098),c=r(1956),s=r(8599),f=r(8875),d=r(4765),p=r(7690),h=r(4038),{createFromFetch:y,encodeReply:_}=r(6671);async function b(e,t){let r,{actionId:a,actionArgs:l}=t,i=await _(l),c=(0,h.extractPathFromFlightRouterState)(e.tree),s=e.nextUrl&&e.nextUrl!==c,f=await fetch("",{method:"POST",headers:{Accept:o.RSC_CONTENT_TYPE_HEADER,[o.ACTION]:a,[o.NEXT_ROUTER_STATE_TREE]:encodeURIComponent(JSON.stringify(e.tree)),...s?{[o.NEXT_URL]:e.nextUrl}:{}},body:i}),d=f.headers.get("x-action-redirect");try{let e=JSON.parse(f.headers.get("x-action-revalidated")||"[[],0,0]");r={paths:e[0]||[],tag:!!e[1],cookie:e[2]}}catch(e){r={paths:[],tag:!1,cookie:!1}}let p=d?new URL((0,u.addBasePath)(d),new URL(e.canonicalUrl,window.location.href)):void 0;if(f.headers.get("content-type")===o.RSC_CONTENT_TYPE_HEADER){let e=await y(Promise.resolve(f),{callServer:n.callServer});if(d){let[,t]=null!=e?e:[];return{actionFlightData:t,redirectLocation:p,revalidatedParts:r}}let[t,[,o]]=null!=e?e:[];return{actionResult:t,actionFlightData:o,redirectLocation:p,revalidatedParts:r}}return{redirectLocation:p,revalidatedParts:r}}function v(e,t){let{resolve:r,reject:n}=t,o={},u=e.canonicalUrl,h=e.tree;return o.preserveCustomHistoryState=!1,o.inFlightServerAction=b(e,t),o.inFlightServerAction.then(t=>{let{actionResult:n,actionFlightData:y,redirectLocation:_}=t;if(_&&(e.pushRef.pendingPush=!0,o.pendingPush=!0),!y)return(o.actionResultResolved||(r(n),o.actionResultResolved=!0),_)?(0,l.handleExternalUrl)(e,o,_.href,e.pushRef.pendingPush):e;if("string"==typeof y)return(0,l.handleExternalUrl)(e,o,y,e.pushRef.pendingPush);for(let t of(o.inFlightServerAction=null,y)){if(3!==t.length)return console.log("SERVER ACTION APPLY FAILED"),e;let[r]=t,n=(0,i.applyRouterStatePatchToTree)([""],h,r);if(null===n)throw Error("SEGMENT MISMATCH");if((0,c.isNavigatingToNewRootLayout)(h,n))return(0,l.handleExternalUrl)(e,o,u,e.pushRef.pendingPush);let[a,f]=t.slice(-2),y=null!==a?a[2]:null;if(null!==y){let e=(0,p.createEmptyCacheNode)();e.status=s.CacheStates.READY,e.subTreeData=y,(0,d.fillLazyItemsTillLeafWithHead)(e,void 0,r,a,f),o.cache=e,o.prefetchCache=new Map}o.patchedTree=n,o.canonicalUrl=u,h=n}if(_){let e=(0,a.createHrefFromUrl)(_,!1);o.canonicalUrl=e}return o.actionResultResolved||(r(n),o.actionResultResolved=!0),(0,f.handleMutable)(e,o)},t=>{if("rejected"===t.status)return o.actionResultResolved||(n(t.reason),o.actionResultResolved=!0),e;throw t})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4173:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"serverPatchReducer",{enumerable:!0,get:function(){return s}});let n=r(8419),o=r(7098),u=r(1956),a=r(5596),l=r(9671),i=r(8875),c=r(7690);function s(e,t){let{flightData:r,overrideCanonicalUrl:s}=t,f={};if(f.preserveCustomHistoryState=!1,"string"==typeof r)return(0,a.handleExternalUrl)(e,f,r,e.pushRef.pendingPush);let d=e.tree,p=e.cache;for(let t of r){let r=t.slice(0,-4),[i]=t.slice(-3,-2),h=(0,o.applyRouterStatePatchToTree)(["",...r],d,i);if(null===h)throw Error("SEGMENT MISMATCH");if((0,u.isNavigatingToNewRootLayout)(d,h))return(0,a.handleExternalUrl)(e,f,e.canonicalUrl,e.pushRef.pendingPush);let y=s?(0,n.createHrefFromUrl)(s):void 0;y&&(f.canonicalUrl=y);let _=(0,c.createEmptyCacheNode)();(0,l.applyFlightData)(p,_,t),f.patchedTree=h,f.cache=_,p=_,d=h}return(0,i.handleMutable)(e,f)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1414:function(e,t){"use strict";var r,n;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{PrefetchKind:function(){return r},ACTION_REFRESH:function(){return o},ACTION_NAVIGATE:function(){return u},ACTION_RESTORE:function(){return a},ACTION_SERVER_PATCH:function(){return l},ACTION_PREFETCH:function(){return i},ACTION_FAST_REFRESH:function(){return c},ACTION_SERVER_ACTION:function(){return s},isThenable:function(){return f}});let o="refresh",u="navigate",a="restore",l="server-patch",i="prefetch",c="fast-refresh",s="server-action";function f(e){return e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(n=r||(r={})).AUTO="auto",n.FULL="full",n.TEMPORARY="temporary",("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6878:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return f}});let n=r(1414),o=r(5596),u=r(4173),a=r(7222),l=r(7491),i=r(5678),c=r(6503),s=r(899),f=function(e,t){switch(t.type){case n.ACTION_NAVIGATE:return(0,o.navigateReducer)(e,t);case n.ACTION_SERVER_PATCH:return(0,u.serverPatchReducer)(e,t);case n.ACTION_RESTORE:return(0,a.restoreReducer)(e,t);case n.ACTION_REFRESH:return(0,l.refreshReducer)(e,t);case n.ACTION_FAST_REFRESH:return(0,c.fastRefreshReducer)(e,t);case n.ACTION_PREFETCH:return(0,i.prefetchReducer)(e,t);case n.ACTION_SERVER_ACTION:return(0,s.serverActionReducer)(e,t);default:throw Error("Unknown action")}};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},3556:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"shouldHardNavigate",{enumerable:!0,get:function(){return function e(t,r){let[o,u]=r,[a,l]=t;return(0,n.matchSegment)(a,o)?!(t.length<=2)&&e(t.slice(2),u[l]):!!Array.isArray(a)}}});let n=r(2295);("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},5797:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createSearchParamsBailoutProxy",{enumerable:!0,get:function(){return o}});let n=r(8181);function o(){return new Proxy({},{get(e,t){"string"==typeof t&&(0,n.staticGenerationBailout)("searchParams."+t)}})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationAsyncStorage",{enumerable:!0,get:function(){return n}});let n=(0,r(1704).createAsyncLocalStorage)();("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8181:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"staticGenerationBailout",{enumerable:!0,get:function(){return l}});let n=r(7127),o=r(2);class u extends Error{constructor(...e){super(...e),this.code="NEXT_STATIC_GEN_BAILOUT"}}function a(e,t){let{dynamic:r,link:n}=t||{};return"Page"+(r?' with `dynamic = "'+r+'"`':"")+" couldn't be rendered statically because it used `"+e+"`."+(n?" See more info here: "+n:"")}let l=(e,t)=>{let{dynamic:r,link:l}=void 0===t?{}:t,i=o.staticGenerationAsyncStorage.getStore();if(!i)return!1;if(i.forceStatic)return!0;if(i.dynamicShouldError)throw new u(a(e,{link:l,dynamic:null!=r?r:"error"}));let c=a(e,{dynamic:r,link:"https://nextjs.org/docs/messages/dynamic-server-error"});if(null==i.postpone||i.postpone.call(i,e),i.revalidate=0,i.isStaticGeneration){let t=new n.DynamicServerError(c);throw i.dynamicUsageDescription=e,i.dynamicUsageStack=t.stack,t}return!1};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7831:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return u}});let n=r(1024)._(r(2265)),o=r(5797);function u(e){let{Component:t,propsForComponent:r,isStaticGeneration:u}=e;if(u){let e=(0,o.createSearchParamsBailoutProxy)();return n.default.createElement(t,{searchParams:e,...r})}return n.default.createElement(t,r)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1276:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{useUnwrapState:function(){return l},useReducerWithReduxDevtools:function(){return i}});let n=r(8533)._(r(2265)),o=r(1414),u=r(5367);function a(e){if(e instanceof Map){let t={};for(let[r,n]of e.entries()){if("function"==typeof n){t[r]="fn()";continue}if("object"==typeof n&&null!==n){if(n.$$typeof){t[r]=n.$$typeof.toString();continue}if(n._bundlerConfig){t[r]="FlightData";continue}}t[r]=a(n)}return t}if("object"==typeof e&&null!==e){let t={};for(let r in e){let n=e[r];if("function"==typeof n){t[r]="fn()";continue}if("object"==typeof n&&null!==n){if(n.$$typeof){t[r]=n.$$typeof.toString();continue}if(n.hasOwnProperty("_bundlerConfig")){t[r]="FlightData";continue}}t[r]=a(n)}return t}return Array.isArray(e)?e.map(a):e}function l(e){return(0,o.isThenable)(e)?(0,n.use)(e):e}let i=function(e){let[t,r]=n.default.useState(e),o=(0,n.useContext)(u.ActionQueueContext);if(!o)throw Error("Invariant: Missing ActionQueueContext");let l=(0,n.useRef)(),i=(0,n.useRef)();return(0,n.useEffect)(()=>{if(!l.current&&!1!==i.current){if(void 0===i.current&&void 0===window.__REDUX_DEVTOOLS_EXTENSION__){i.current=!1;return}return l.current=window.__REDUX_DEVTOOLS_EXTENSION__.connect({instanceId:8e3,name:"next-router"}),l.current&&(l.current.init(a(e)),o&&(o.devToolsInstance=l.current)),()=>{l.current=void 0}}},[e,o]),[t,(0,n.useCallback)(t=>{o.state||(o.state=e),o.dispatch(t,r)},[o,e]),(0,n.useCallback)(e=>{l.current&&l.current.send({type:"RENDER_SYNC"},a(e))},[])]};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7379:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"hasBasePath",{enumerable:!0,get:function(){return o}});let n=r(7027);function o(e){return(0,n.pathHasPrefix)(e,"")}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2139:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathTrailingSlash",{enumerable:!0,get:function(){return u}});let n=r(5868),o=r(6506),u=e=>{if(!e.startsWith("/"))return e;let{pathname:t,query:r,hash:u}=(0,o.parsePath)(e);return""+(0,n.removeTrailingSlash)(t)+r+u};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4101:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return o}});let n=r(6491);function o(e){let t="function"==typeof reportError?reportError:e=>{window.console.error(e)};e.digest!==n.NEXT_DYNAMIC_NO_SSR_CODE&&t(e)}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8895:function(e,t,r){"use strict";function n(e){return e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeBasePath",{enumerable:!0,get:function(){return n}}),r(7379),("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8599:function(e,t,r){"use strict";var n,o;Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{CacheStates:function(){return n},AppRouterContext:function(){return a},LayoutRouterContext:function(){return l},GlobalLayoutRouterContext:function(){return i},TemplateContext:function(){return c}});let u=r(1024)._(r(2265));(o=n||(n={})).LAZY_INITIALIZED="LAZYINITIALIZED",o.DATA_FETCH="DATAFETCH",o.READY="READY";let a=u.default.createContext(null),l=u.default.createContext(null),i=u.default.createContext(null),c=u.default.createContext(null)},1:function(e,t){"use strict";function r(e){let t=5381;for(let r=0;r>>0}function n(e){return r(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{djb2Hash:function(){return r},hexHash:function(){return n}})},3634:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"HeadManagerContext",{enumerable:!0,get:function(){return n}});let n=r(1024)._(r(2265)).default.createContext({})},4758:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{SearchParamsContext:function(){return o},PathnameContext:function(){return u},PathParamsContext:function(){return a}});let n=r(2265),o=(0,n.createContext)(null),u=(0,n.createContext)(null),a=(0,n.createContext)(null)},6491:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{NEXT_DYNAMIC_NO_SSR_CODE:function(){return r},throwWithNoSSR:function(){return n}});let r="NEXT_DYNAMIC_NO_SSR_CODE";function n(){let e=Error(r);throw e.digest=r,e}},9798:function(e,t){"use strict";function r(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return r}})},5367:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ActionQueueContext:function(){return l},createMutableActionQueue:function(){return s}});let n=r(8533),o=r(1414),u=r(6878),a=n._(r(2265)),l=a.default.createContext(null);function i(e,t){null!==e.pending&&(e.pending=e.pending.next,null!==e.pending&&c({actionQueue:e,action:e.pending,setState:t}))}async function c(e){let{actionQueue:t,action:r,setState:n}=e,u=t.state;if(!u)throw Error("Invariant: Router state not initialized");t.pending=r;let a=r.payload,l=t.action(u,a);function c(e){if(r.discarded){t.needsRefresh&&null===t.pending&&(t.needsRefresh=!1,t.dispatch({type:o.ACTION_REFRESH,origin:window.location.origin},n));return}t.state=e,t.devToolsInstance&&t.devToolsInstance.send(a,e),i(t,n),r.resolve(e)}(0,o.isThenable)(l)?l.then(c,e=>{i(t,n),r.reject(e)}):c(l)}function s(){let e={state:null,dispatch:(t,r)=>(function(e,t,r){let n={resolve:r,reject:()=>{}};if(t.type!==o.ACTION_RESTORE){let e=new Promise((e,t)=>{n={resolve:e,reject:t}});(0,a.startTransition)(()=>{r(e)})}let u={payload:t,next:null,resolve:n.resolve,reject:n.reject};null===e.pending?(e.last=u,c({actionQueue:e,action:u,setState:r})):t.type===o.ACTION_NAVIGATE?(e.pending.discarded=!0,e.last=u,e.pending.payload.type===o.ACTION_SERVER_ACTION&&(e.needsRefresh=!0),c({actionQueue:e,action:u,setState:r})):(null!==e.last&&(e.last.next=u),e.last=u)})(e,t,r),action:async(e,t)=>{if(null===e)throw Error("Invariant: Router state not initialized");return(0,u.reducer)(e,t)},pending:null,last:null};return e}},1312:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"addPathPrefix",{enumerable:!0,get:function(){return o}});let n=r(6506);function o(e,t){if(!e.startsWith("/")||!t)return e;let{pathname:r,query:o,hash:u}=(0,n.parsePath)(e);return""+t+r+o+u}},7178:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{normalizeAppPath:function(){return u},normalizeRscURL:function(){return a}});let n=r(9798),o=r(3266);function u(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,r,n)=>!t||(0,o.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&r===n.length-1?e:e+"/"+t,""))}function a(e){return e.replace(/\.rsc($|\?)/,"$1")}},3011:function(e,t){"use strict";function r(e,t){if(void 0===t&&(t={}),t.onlyHashChange){e();return}let r=document.documentElement,n=r.style.scrollBehavior;r.style.scrollBehavior="auto",t.dontForceLayout||r.getClientRects(),e(),r.style.scrollBehavior=n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"handleSmoothScroll",{enumerable:!0,get:function(){return r}})},6407:function(e,t){"use strict";function r(e){return/Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver/i.test(e)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isBot",{enumerable:!0,get:function(){return r}})},6506:function(e,t){"use strict";function r(e){let t=e.indexOf("#"),r=e.indexOf("?"),n=r>-1&&(t<0||r-1?{pathname:e.substring(0,n?r:t),query:n?e.substring(r,t>-1?t:void 0):"",hash:t>-1?e.slice(t):""}:{pathname:e,query:"",hash:""}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parsePath",{enumerable:!0,get:function(){return r}})},7027:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"pathHasPrefix",{enumerable:!0,get:function(){return o}});let n=r(6506);function o(e,t){if("string"!=typeof e)return!1;let{pathname:r}=(0,n.parsePath)(e);return r===t||r.startsWith(t+"/")}},5868:function(e,t){"use strict";function r(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return r}})},3266:function(e,t){"use strict";function r(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isGroupSegment",{enumerable:!0,get:function(){return r}})},2472:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{ServerInsertedHTMLContext:function(){return o},useServerInsertedHTML:function(){return u}});let n=r(8533)._(r(2265)),o=n.default.createContext(null);function u(e){let t=(0,n.useContext)(o);t&&t(e)}},1704:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"createAsyncLocalStorage",{enumerable:!0,get:function(){return u}});let r=Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available");class n{disable(){throw r}getStore(){}run(){throw r}exit(){throw r}enterWith(){throw r}}let o=globalThis.AsyncLocalStorage;function u(){return o?new o:new n}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},4040:function(e,t,r){"use strict";var n=r(4887);t.createRoot=n.createRoot,t.hydrateRoot=n.hydrateRoot},4887:function(e,t,r){"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}(),e.exports=r(4417)},7950:function(e,t,r){"use strict";var n=r(4887),o=r(2265),u={stream:!0},a=new Map;function l(e){var t=r(e);return"function"!=typeof t.then||"fulfilled"===t.status?null:(t.then(function(e){t.status="fulfilled",t.value=e},function(e){t.status="rejected",t.reason=e}),t)}function i(){}var c=new Map,s=r.u;r.u=function(e){var t=c.get(e);return void 0!==t?t:s(e)};var f=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Dispatcher,d=Symbol.for("react.element"),p=Symbol.for("react.provider"),h=Symbol.for("react.server_context"),y=Symbol.for("react.lazy"),_=Symbol.for("react.default_value"),b=Symbol.iterator,v=Array.isArray,g=Object.getPrototypeOf,m=Object.prototype,O=new WeakMap,P=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ContextRegistry;function E(e,t,r,n){this.status=e,this.value=t,this.reason=r,this._response=n}function R(e){switch(e.status){case"resolved_model":x(e);break;case"resolved_module":A(e)}switch(e.status){case"fulfilled":return e.value;case"pending":case"blocked":case"cyclic":throw e;default:throw e.reason}}function S(e,t){for(var r=0;rh?(_=h,h=3,p++):(_=0,h=3);continue;case 2:44===(g=d[p++])?h=4:b=b<<4|(96d.length&&(g=-1)}var m=d.byteOffset+p;if(-1>>1,o=e[n];if(0>>1;nu(i,r))cu(s,i)?(e[n]=s,e[c]=r,n=c):(e[n]=i,e[l]=r,n=l);else if(cu(s,r))e[n]=s,e[c]=r,n=c;else break}}return t}function u(e,t){var r=e.sortIndex-t.sortIndex;return 0!==r?r:e.id-t.id}if(t.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var a,l=performance;t.unstable_now=function(){return l.now()}}else{var i=Date,c=i.now();t.unstable_now=function(){return i.now()-c}}var s=[],f=[],d=1,p=null,h=3,y=!1,_=!1,b=!1,v="function"==typeof setTimeout?setTimeout:null,g="function"==typeof clearTimeout?clearTimeout:null,m="undefined"!=typeof setImmediate?setImmediate:null;function O(e){for(var t=n(f);null!==t;){if(null===t.callback)o(f);else if(t.startTime<=e)o(f),t.sortIndex=t.expirationTime,r(s,t);else break;t=n(f)}}function P(e){if(b=!1,O(e),!_){if(null!==n(s))_=!0,x();else{var t=n(f);null!==t&&A(P,t.startTime-e)}}}"undefined"!=typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);var E=!1,R=-1,S=5,j=-1;function T(){return!(t.unstable_now()-je&&T());){var l=p.callback;if("function"==typeof l){p.callback=null,h=p.priorityLevel;var i=l(p.expirationTime<=e);if(e=t.unstable_now(),"function"==typeof i){p.callback=i,O(e),r=!0;break t}p===n(s)&&o(s),O(e)}else o(s);p=n(s)}if(null!==p)r=!0;else{var c=n(f);null!==c&&A(P,c.startTime-e),r=!1}}break e}finally{p=null,h=u,y=!1}r=void 0}}finally{r?a():E=!1}}}if("function"==typeof m)a=function(){m(w)};else if("undefined"!=typeof MessageChannel){var C=new MessageChannel,M=C.port2;C.port1.onmessage=w,a=function(){M.postMessage(null)}}else a=function(){v(w,0)};function x(){E||(E=!0,a())}function A(e,r){R=v(function(){e(t.unstable_now())},r)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(e){e.callback=null},t.unstable_continueExecution=function(){_||y||(_=!0,x())},t.unstable_forceFrameRate=function(e){0>e||125a?(e.sortIndex=u,r(f,e),null===n(s)&&e===n(f)&&(b?(g(R),R=-1):b=!0,A(P,u-a))):(e.sortIndex=l,r(s,e),_||y||(_=!0,x())),e},t.unstable_shouldYield=T,t.unstable_wrapCallback=function(e){var t=h;return function(){var r=h;h=t;try{return e.apply(this,arguments)}finally{h=r}}}},8261:function(e,t,r){"use strict";e.exports=r(1756)},5682:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getSegmentParam",{enumerable:!0,get:function(){return o}});let n=r(4507);function o(e){let t=n.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t));return(t&&(e=e.slice(t.length)),e.startsWith("[[...")&&e.endsWith("]]"))?{type:"optional-catchall",param:e.slice(5,-2)}:e.startsWith("[...")&&e.endsWith("]")?{type:"catchall",param:e.slice(4,-1)}:e.startsWith("[")&&e.endsWith("]")?{type:"dynamic",param:e.slice(1,-1)}:null}},4507:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return o},isInterceptionRouteAppPath:function(){return u},extractInterceptionRouteInformation:function(){return a}});let n=r(7178),o=["(..)(..)","(.)","(..)","(...)"];function u(e){return void 0!==e.split("/").find(e=>o.find(t=>e.startsWith(t)))}function a(e){let t,r,u;for(let n of e.split("/"))if(r=o.find(e=>n.startsWith(e))){[t,u]=e.split(r,2);break}if(!t||!r||!u)throw Error(`Invalid interception route: ${e}. Must be in the format //(..|...|..)(..)/`);switch(t=(0,n.normalizeAppPath)(t),r){case"(.)":u="/"===t?`/${u}`:t+"/"+u;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);u=t.split("/").slice(0,-1).concat(u).join("/");break;case"(...)":u="/"+u;break;case"(..)(..)":let a=t.split("/");if(a.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);u=a.slice(0,-2).concat(u).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:u}}},4677:function(e,t,r){"use strict";function n(e,t){if(!Object.prototype.hasOwnProperty.call(e,t))throw TypeError("attempted to use private field on non-instance");return e}r.r(t),r.d(t,{_:function(){return n},_class_private_field_loose_base:function(){return n}})},6249:function(e,t,r){"use strict";r.r(t),r.d(t,{_:function(){return o},_class_private_field_loose_key:function(){return o}});var n=0;function o(e){return"__private_"+n+++"_"+e}},1024:function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}r.r(t),r.d(t,{_:function(){return n},_interop_require_default:function(){return n}})},8533:function(e,t,r){"use strict";function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function o(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var o={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in e)if("default"!==a&&Object.prototype.hasOwnProperty.call(e,a)){var l=u?Object.getOwnPropertyDescriptor(e,a):null;l&&(l.get||l.set)?Object.defineProperty(o,a,l):o[a]=e[a]}return o.default=e,r&&r.set(e,o),o}r.r(t),r.d(t,{_:function(){return o},_interop_require_wildcard:function(){return o}})}}]); \ No newline at end of file diff --git a/.next/static/chunks/973-5f61489a82d0bbab.js b/.next/static/chunks/973-5f61489a82d0bbab.js new file mode 100644 index 0000000..3c763d3 --- /dev/null +++ b/.next/static/chunks/973-5f61489a82d0bbab.js @@ -0,0 +1,11699 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[973],{4930:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let r=i(1024);i(2265);let s=r._(i(4795));function n(e){return{default:(null==e?void 0:e.default)||e}}function a(e,t){let i=s.default,r={loading:e=>{let{error:t,isLoading:i,pastDelay:r}=e;return null}};"function"==typeof e&&(r.loader=e),Object.assign(r,t);let a=r.loader;return i({...r,loader:()=>null!=a?a().then(n):Promise.resolve(n(()=>null))})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},6005:function(e,t,i){function r(e){let{children:t}=e;return t}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"NoSSR",{enumerable:!0,get:function(){return r}}),i(6491)},4795:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}});let r=i(1024)._(i(2265)),s=i(6005),n=function(e){let t=Object.assign({loader:null,loading:null,ssr:!0},e);function i(e){let i=t.loading,n=r.default.createElement(i,{isLoading:!0,pastDelay:!0,error:null}),a=t.ssr?r.default.Fragment:s.NoSSR,o=t.lazy;return r.default.createElement(r.default.Suspense,{fallback:n},r.default.createElement(a,null,r.default.createElement(o,e)))}return t.lazy=r.default.lazy(t.loader),i.displayName="LoadableComponent",i}},622:function(e,t,i){var r=i(2265),s=Symbol.for("react.element"),n=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,o=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function h(e,t,i){var r,n={},h=null,u=null;for(r in void 0!==i&&(h=""+i),void 0!==t.key&&(h=""+t.key),void 0!==t.ref&&(u=t.ref),t)a.call(t,r)&&!l.hasOwnProperty(r)&&(n[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===n[r]&&(n[r]=t[r]);return{$$typeof:s,type:e,key:h,ref:u,props:n,_owner:o.current}}t.Fragment=n,t.jsx=h,t.jsxs=h},7437:function(e,t,i){e.exports=i(622)},3621:function(e,t,i){i.d(t,{O:function(){return r}});class r{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1}static get HasTriggers(){for(let e in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(let e in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,e)){let t=parseInt(e);if(t>=1&&t<=7)return!0}return!1}static HasSpecificTrigger(e){for(let t in r.Triggers)if(Object.prototype.hasOwnProperty.call(r.Triggers,t)&&parseInt(t)===e)return!0;return!1}}r.Triggers={}},9528:function(e,t,i){i.d(t,{V:function(){return r}});class r{constructor(e,t,i,r,s,n){this.source=e,this.pointerX=t,this.pointerY=i,this.meshUnderPointer=r,this.sourceEvent=s,this.additionalData=n}static CreateNew(e,t,i){let s=e.getScene();return new r(e,s.pointerX,s.pointerY,s.meshUnderPointer||e,t,i)}static CreateNewFromSprite(e,t,i,s){return new r(e,t.pointerX,t.pointerY,t.meshUnderPointer,i,s)}static CreateNewFromScene(e,t){return new r(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,i,s){return new r(e,t.x,t.y,null,i,s)}}},1295:function(e,t,i){i.d(t,{l:function(){return s},o:function(){return n}});var r=i(9185);class s{get isDisposed(){return this._isDisposed}constructor(e,t,i,s=0,n=!1,a=!1,o=!1,l,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=i,this._instanced=a,this._divisor=l||1,this._label=h,t instanceof r.h?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=o?s:s*Float32Array.BYTES_PER_ELEMENT,n||this.create()}createVertexBuffer(e,t,i,r,s,a=!1,o){let l=a?t:t*Float32Array.BYTES_PER_ELEMENT,h=r?a?r:r*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new n(this._engine,this,e,this._updatable,!0,h,void 0===s?this._instanced:s,l,i,void 0,void 0,!0,this._divisor||o)}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(){this._buffer=null,this.create(this._data)}update(e){this.create(e)}updateDirectly(e,t,i,r=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,r?t:t*Float32Array.BYTES_PER_ELEMENT,i?i*this.byteStride:void 0),0===t&&void 0===i?this._data=e:this._data=null)}_increaseReferences(){if(this._buffer){if(!this._isAlreadyOwned){this._isAlreadyOwned=!0;return}this._buffer.references++}}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class n{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){let t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get totalVertices(){let 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,i,r,a,o,l,h,u,c,d=!1,p=!1,_=1,f=!1){var m,g,v,x,T;this._isDisposed=!1;let S=!1;if(this.engine=e,"object"==typeof r&&null!==r?(S=null!==(m=r.updatable)&&void 0!==m&&m,a=r.postponeInternalCreation,o=r.stride,l=r.instanced,h=r.offset,u=r.size,c=r.type,d=null!==(g=r.normalized)&&void 0!==g&&g,p=null!==(v=r.useBytes)&&void 0!==v&&v,_=null!==(x=r.divisor)&&void 0!==x?x:1,f=null!==(T=r.takeBufferOwnership)&&void 0!==T&&T,this._label=r.label):S=!!r,t instanceof s?(this._buffer=t,this._ownsBuffer=f):(this._buffer=new s(e,t,S,o,a,l,p,_,this._label),this._ownsBuffer=!0),this.uniqueId=n._Counter++,this._kind=i,void 0===c){let e=this.getData();this.type=e?n.GetDataType(e):n.FLOAT}else this.type=c;let E=n.GetTypeByteLength(this.type);p?(this._size=u||(o?o/E:n.DeduceStride(i)),this.byteStride=o||this._buffer.byteStride||this._size*E,this.byteOffset=h||0):(this._size=u||o||n.DeduceStride(i),this.byteStride=o?o*E:this._buffer.byteStride||this._size*E,this.byteOffset=(h||0)*E),this.normalized=d,this._instanced=void 0!==l&&l,this._instanceDivisor=l?_: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(){var e;null===(e=this._buffer)||void 0===e||e._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){let i=this.getData();return i?(e=null!=e?e:this.totalVertices,n.GetFloatData(i,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t)):null}getBuffer(){return this._buffer.getBuffer()}getStrideSize(){return this.byteStride/n.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/n.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*n.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,i=!1){this._buffer.updateDirectly(e,t,void 0,i),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){n.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case n.UVKind:case n.UV2Kind:case n.UV3Kind:case n.UV4Kind:case n.UV5Kind:case n.UV6Kind:return 2;case n.NormalKind:case n.PositionKind:return 3;case n.ColorKind:case n.ColorInstanceKind:case n.MatricesIndicesKind:case n.MatricesIndicesExtraKind:case n.MatricesWeightsKind:case n.MatricesWeightsExtraKind:case n.TangentKind:return 4;default:throw Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?n.BYTE:e instanceof Uint8Array?n.UNSIGNED_BYTE:e instanceof Int16Array?n.SHORT:e instanceof Uint16Array?n.UNSIGNED_SHORT:e instanceof Int32Array?n.INT:e instanceof Uint32Array?n.UNSIGNED_INT:n.FLOAT}static GetTypeByteLength(e){switch(e){case n.BYTE:case n.UNSIGNED_BYTE:return 1;case n.SHORT:case n.UNSIGNED_SHORT:return 2;case n.INT:case n.UNSIGNED_INT:case n.FLOAT:return 4;default:throw Error(`Invalid type '${e}'`)}}static ForEach(e,t,i,r,s,a,o,l){if(e instanceof Array){let s=t/4,n=i/4;for(let t=0;to[t]=e),o}if(!(e instanceof Array||e instanceof Float32Array)||0!==r||e.length!==u){if(e instanceof Array){let t=r/4;return e.slice(t,t+u)}if(e instanceof ArrayBuffer)return new Float32Array(e,r,u);{let t=e.byteOffset+r;if(l){let i=new Float32Array(u),r=new Float32Array(e.buffer,t,u);return i.set(r),i}let i=t%4;return i&&(t=Math.max(0,t-i)),new Float32Array(e.buffer,t,u)}}return l?e.slice():e}}n._Counter=0,n.BYTE=5120,n.UNSIGNED_BYTE=5121,n.SHORT=5122,n.UNSIGNED_SHORT=5123,n.INT=5124,n.UNSIGNED_INT=5125,n.FLOAT=5126,n.PositionKind="position",n.NormalKind="normal",n.TangentKind="tangent",n.UVKind="uv",n.UV2Kind="uv2",n.UV3Kind="uv3",n.UV4Kind="uv4",n.UV5Kind="uv5",n.UV6Kind="uv6",n.ColorKind="color",n.ColorInstanceKind="instanceColor",n.MatricesIndicesKind="matricesIndices",n.MatricesWeightsKind="matricesWeights",n.MatricesIndicesExtraKind="matricesIndicesExtra",n.MatricesWeightsExtraKind="matricesWeightsExtra"},9185:function(e,t,i){i.d(t,{h:function(){return r}});class r{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=r._Counter++}}r._Counter=0},2421:function(e,t,i){i.d(t,{V:function(){return f}});var r=i(9956),s=i(1760),n=i(8355),a=i(5132),o=i(4800),l=i(78),h=i(208),u=i(9626),c=i(3048),d=i(6131),p=i(6329),_=i(2975);class f extends h.N{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){var e,t,i,r;let s=0,n=0;if(this.mode===f.PERSPECTIVE_CAMERA)this.fovMode===f.FOVMODE_VERTICAL_FIXED?(n=2*this.minZ*Math.tan(this.fov/2),s=this.getEngine().getAspectRatio(this)*n):n=(s=2*this.minZ*Math.tan(this.fov/2))/this.getEngine().getAspectRatio(this);else{let a=this.getEngine().getRenderWidth()/2,o=this.getEngine().getRenderHeight()/2;s=(null!==(e=this.orthoRight)&&void 0!==e?e:a)-(null!==(t=this.orthoLeft)&&void 0!==t?t:-a),n=(null!==(i=this.orthoTop)&&void 0!==i?i:o)-(null!==(r=this.orthoBottom)&&void 0!==r?r:-o)}return s*n}set orthoLeft(e){for(let t of(this._orthoLeft=e,this._rigCameras))t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){for(let t of(this._orthoRight=e,this._rigCameras))t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){for(let t of(this._orthoBottom=e,this._rigCameras))t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){for(let t of(this._orthoTop=e,this._rigCameras))t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){for(let t of(this._mode=e,this._rigCameras))t.mode=e}get mode(){return this._mode}constructor(e,t,i,r=!0){super(e,i),this._position=l.P.Zero(),this._upVector=l.P.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=f.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new p.l(0,0,1,1),this.layerMask=268435455,this.fovMode=f.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=f.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new o.y$,this.onProjectionMatrixChangedObservable=new o.y$,this.onAfterCheckInputsObservable=new o.y$,this.onRestoreStateObservable=new o.y$,this.isRigCamera=!1,this._rigCameras=[],this._skipRendering=!1,this._projectionMatrix=new l.y3,this._postProcesses=[],this._activeMeshes=new n.t(256),this._globalPosition=l.P.Zero(),this._computedViewMatrix=l.y3.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=l.y3.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=l._f.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),r&&!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}_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 i=0;i-1?(u.Y.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){let 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 l.y3.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(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){var t,i,r,s,n,a,o,h,u,c,d,p,_,m,g,v,x,T,S;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;let E=this.getEngine(),C=this.getScene(),b=E.useReverseDepthBuffer;if(this.mode===f.PERSPECTIVE_CAMERA)this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=E.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),(C.useRightHandedSystem?l.y3.PerspectiveFovRHToRef:l.y3.PerspectiveFovLHToRef)(this.fov,E.getAspectRatio(this),b?this.maxZ:this.minZ,b?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===f.FOVMODE_VERTICAL_FIXED,E.isNDCHalfZRange,this.projectionPlaneTilt,b);else{let e=E.getRenderWidth()/2,f=E.getRenderHeight()/2;C.useRightHandedSystem?this.oblique?l.y3.ObliqueOffCenterRHToRef(null!==(t=this.orthoLeft)&&void 0!==t?t:-e,null!==(i=this.orthoRight)&&void 0!==i?i:e,null!==(r=this.orthoBottom)&&void 0!==r?r:-f,null!==(s=this.orthoTop)&&void 0!==s?s:f,b?this.maxZ:this.minZ,b?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,E.isNDCHalfZRange):l.y3.OrthoOffCenterRHToRef(null!==(n=this.orthoLeft)&&void 0!==n?n:-e,null!==(a=this.orthoRight)&&void 0!==a?a:e,null!==(o=this.orthoBottom)&&void 0!==o?o:-f,null!==(h=this.orthoTop)&&void 0!==h?h:f,b?this.maxZ:this.minZ,b?this.minZ:this.maxZ,this._projectionMatrix,E.isNDCHalfZRange):this.oblique?l.y3.ObliqueOffCenterLHToRef(null!==(u=this.orthoLeft)&&void 0!==u?u:-e,null!==(c=this.orthoRight)&&void 0!==c?c:e,null!==(d=this.orthoBottom)&&void 0!==d?d:-f,null!==(p=this.orthoTop)&&void 0!==p?p:f,b?this.maxZ:this.minZ,b?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,E.isNDCHalfZRange):l.y3.OrthoOffCenterLHToRef(null!==(_=this.orthoLeft)&&void 0!==_?_:-e,null!==(m=this.orthoRight)&&void 0!==m?m:e,null!==(g=this.orthoBottom)&&void 0!==g?g:-f,null!==(v=this.orthoTop)&&void 0!==v?v:f,b?this.maxZ:this.minZ,b?this.minZ:this.maxZ,this._projectionMatrix,E.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=null===(x=this.oblique)||void 0===x?void 0:x.angle,this._cache.obliqueLength=null===(T=this.oblique)||void 0===T?void 0:T.length,this._cache.obliqueOffset=null===(S=this.oblique)||void 0===S?void 0:S.offset,this._cache.renderWidth=E.getRenderWidth(),this._cache.renderHeight=E.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?l.P.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?_.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=_.i.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),!t||!(this.rigCameras.length>0))return e.isInFrustum(this._frustumPlanes);{let t=!1;return this.rigCameras.forEach(i=>{i._updateFrustumPlanes(),t=t||e.isInFrustum(i._frustumPlanes)}),t}}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,i){throw(0,d.S)("Ray")}getForwardRayToRef(e,t=100,i,r){throw(0,d.S)("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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){let 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!==f.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){let t=this._postProcesses[e];t&&t.dispose(this)}}let i=this.customRenderTargets.length;for(;--i>=0;)this.customRenderTargets[i].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;){let e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=a.w1.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==f.RIG_MODE_NONE){let e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);let 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 l.y3.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=a.w1.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;ef._CreateDefaultParsedCamera(t,i))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){let i=e.type,r=f.GetConstructorFromName(i,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),n=s.p4.Parse(r,e,t);if(void 0!==e.parentId&&(n._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(n._waitingParentInstanceIndex=e.parentInstanceIndex),n.inputs&&(n.inputs.parse(e),n._setupInputs()),e.upVector&&(n.upVector=l.P.FromArray(e.upVector)),n.setPosition&&(n.position.copyFromFloats(0,0,0),n.setPosition(l.P.FromArray(e.position))),e.target&&n.setTarget&&n.setTarget(l.P.FromArray(e.target)),e.cameraRigMode){let t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};n.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;tthis.parent._getWorldMatrixDeterminant()&&(e*=-1),e}}f._CreateDefaultParsedCamera=(e,t)=>{throw(0,d.S)("UniversalCamera")},f.PERSPECTIVE_CAMERA=0,f.ORTHOGRAPHIC_CAMERA=1,f.FOVMODE_VERTICAL_FIXED=0,f.FOVMODE_HORIZONTAL_FIXED=1,f.RIG_MODE_NONE=0,f.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,f.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,f.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,f.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,f.RIG_MODE_STEREOSCOPIC_INTERLACED=14,f.RIG_MODE_VR=20,f.RIG_MODE_CUSTOM=22,f.ForceAttachControlToAlwaysPreventDefault=!1,(0,r.gn)([(0,s.hd)("position")],f.prototype,"_position",void 0),(0,r.gn)([(0,s.hd)("upVector")],f.prototype,"_upVector",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"orthoLeft",null),(0,r.gn)([(0,s.qC)()],f.prototype,"orthoRight",null),(0,r.gn)([(0,s.qC)()],f.prototype,"orthoBottom",null),(0,r.gn)([(0,s.qC)()],f.prototype,"orthoTop",null),(0,r.gn)([(0,s.qC)()],f.prototype,"fov",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"projectionPlaneTilt",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"minZ",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"maxZ",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"inertia",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"mode",null),(0,r.gn)([(0,s.qC)()],f.prototype,"layerMask",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"fovMode",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"cameraRigMode",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"interaxialDistance",void 0),(0,r.gn)([(0,s.qC)()],f.prototype,"isStereoscopicSideBySide",void 0)},9372:function(e,t,i){i.d(t,{c:function(){return r}});class r{constructor(e,t,i){this.bu=e,this.bv=t,this.distance=i,this.faceId=0,this.subMeshId=0}}},5790:function(e,t,i){i.d(t,{a:function(){return s}});var r=i(78);class s{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new r.P(0,0,0),this._diffPositionForCollisions=new r.P(0,0,0),this._collisionResponse=!0}}},2248:function(e,t,i){i.d(t,{p:function(){return n}});var r=i(78),s=i(1295);class n{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){let i;if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(s.o.NormalKind))return null;let n=this.pickedMesh.getIndices();(null==n?void 0:n.length)===0&&(n=null);let a=r.jp.Vector3[0],o=r.jp.Vector3[1],l=r.jp.Vector3[2];if(t){let e=this.pickedMesh.getVerticesData(s.o.NormalKind),t=n?r.P.FromArrayToRef(e,3*n[3*this.faceId],a):a.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),h=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+1],o):o.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),u=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]);t=t.scale(this.bu),h=h.scale(this.bv),u=u.scale(1-this.bu-this.bv),i=new r.P(t.x+h.x+u.x,t.y+h.y+u.y,t.z+h.z+u.z)}else{let e=this.pickedMesh.getVerticesData(s.o.PositionKind),t=n?r.P.FromArrayToRef(e,3*n[3*this.faceId],a):a.copyFromFloats(e[9*this.faceId],e[9*this.faceId+1],e[9*this.faceId+2]),h=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+1],o):o.copyFromFloats(e[(3*this.faceId+1)*3],e[(3*this.faceId+1)*3+1],e[(3*this.faceId+1)*3+2]),u=n?r.P.FromArrayToRef(e,3*n[3*this.faceId+2],l):l.copyFromFloats(e[(3*this.faceId+2)*3],e[(3*this.faceId+2)*3+1],e[(3*this.faceId+2)*3+2]),c=t.subtract(h),d=u.subtract(h);i=r.P.Cross(c,d)}let h=(e,t)=>{let i=e.getWorldMatrix();e.nonUniformScaling&&(r.jp.Matrix[0].copyFrom(i),(i=r.jp.Matrix[0]).setTranslationFromFloats(0,0,0),i.invert(),i.transposeToRef(r.jp.Matrix[1]),i=r.jp.Matrix[1]),r.P.TransformNormalToRef(t,i,t)};if(e&&h(this.pickedMesh,i),this.ray){let t=r.jp.Vector3[0].copyFrom(i);e||h(this.pickedMesh,t),r.P.Dot(t,this.ray.direction)>0&&i.negateInPlace()}return i.normalize(),i}getTextureCoordinates(e=s.o.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;let t=this.pickedMesh.getIndices();if(!t)return null;let i=this.pickedMesh.getVerticesData(e);if(!i)return null;let n=r.FM.FromArray(i,2*t[3*this.faceId]),a=r.FM.FromArray(i,2*t[3*this.faceId+1]),o=r.FM.FromArray(i,2*t[3*this.faceId+2]);return n=n.scale(this.bu),a=a.scale(this.bv),o=o.scale(1-this.bu-this.bv),new r.FM(n.x+a.x+o.x,n.y+a.y+o.y)}}},6705:function(e,t,i){i.d(t,{e:function(){return r}});class r{}r.UseOpenGLOrientationForUV=!1},4347:function(e,t,i){i.d(t,{k:function(){return a}});var r=i(4254),s=i(78),n=i(9806);class a{constructor(e,t,i){this.vectors=r.B.BuildArray(8,s.P.Zero),this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.extendSize=s.P.Zero(),this.extendSizeWorld=s.P.Zero(),this.directions=r.B.BuildArray(3,s.P.Zero),this.vectorsWorld=r.B.BuildArray(8,s.P.Zero),this.minimumWorld=s.P.Zero(),this.maximumWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,i)}reConstruct(e,t,i){let r=e.x,n=e.y,a=e.z,o=t.x,l=t.y,h=t.z,u=this.vectors;this.minimum.copyFromFloats(r,n,a),this.maximum.copyFromFloats(o,l,h),u[0].copyFromFloats(r,n,a),u[1].copyFromFloats(o,l,h),u[2].copyFromFloats(o,n,a),u[3].copyFromFloats(r,l,a),u[4].copyFromFloats(r,n,h),u[5].copyFromFloats(o,l,a),u[6].copyFromFloats(r,l,h),u[7].copyFromFloats(o,n,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=i||s.y3.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){let t=a._TmpVector3,i=this.maximum.subtractToRef(this.minimum,t[0]),r=i.length();i.normalizeFromLength(r);let s=r*e,n=i.scaleInPlace(.5*s),o=this.center.subtractToRef(n,t[1]),l=this.center.addToRef(n,t[2]);return this.reConstruct(o,l,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){let t=this.minimumWorld,i=this.maximumWorld,r=this.directions,n=this.vectorsWorld,a=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),i.copyFrom(this.maximum);for(let e=0;e<8;++e)n[e].copyFrom(a[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),i.setAll(-Number.MAX_VALUE);for(let r=0;r<8;++r){let o=n[r];s.P.TransformCoordinatesToRef(a[r],e,o),t.minimizeInPlace(o),i.maximizeInPlace(o)}i.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),i.addToRef(t,this.centerWorld).scaleInPlace(.5)}s.P.FromArrayToRef(e.m,0,r[0]),s.P.FromArrayToRef(e.m,4,r[1]),s.P.FromArrayToRef(e.m,8,r[2]),this._worldMatrix=e}isInFrustum(e){return a.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return a.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){let t=this.minimumWorld,i=this.maximumWorld,r=t.x,s=t.y,a=t.z,o=i.x,l=i.y,h=i.z,u=e.x,c=e.y,d=e.z,p=-n.kn;return!(o-uu-r)&&!(l-cc-s)&&!(h-dd-a)}intersectsSphere(e){return a.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){let i=this.minimumWorld,r=this.maximumWorld,s=i.x,n=i.y,a=i.z,o=r.x,l=r.y,h=r.z,u=e.x,c=e.y,d=e.z,p=t.x,_=t.y,f=t.z;return!(op)&&!(l_)&&!(hf)}dispose(){var e,t;null===(e=this._drawWrapperFront)||void 0===e||e.dispose(),null===(t=this._drawWrapperBack)||void 0===t||t.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,i,r){let n=a._TmpVector3[0];return s.P.ClampToRef(i,e,t,n),s.P.DistanceSquared(i,n)<=r*r}static IsCompletelyInFrustum(e,t){for(let i=0;i<6;++i){let r=t[i];for(let t=0;t<8;++t)if(0>r.dotCoordinate(e[t]))return!1}return!0}static IsInFrustum(e,t){for(let i=0;i<6;++i){let r=!0,s=t[i];for(let t=0;t<8;++t)if(s.dotCoordinate(e[t])>=0){r=!1;break}if(r)return!1}return!0}}a._TmpVector3=r.B.BuildArray(3,s.P.Zero)},5681:function(e,t,i){i.d(t,{j:function(){return c}});var r=i(4254),s=i(78),n=i(4347),a=i(3592);let o={min:0,max:0},l={min:0,max:0},h=(e,t,i)=>{let r=s.P.Dot(t.centerWorld,e),n=Math.abs(s.P.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(s.P.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(s.P.Dot(t.directions[2],e))*t.extendSize.z;i.min=r-n,i.max=r+n},u=(e,t,i)=>(h(e,t,o),h(e,i,l),!(o.min>l.max||l.min>o.max));class c{constructor(e,t,i){this._isLocked=!1,this.boundingBox=new n.k(e,t,i),this.boundingSphere=new a.K(e,t,i)}reConstruct(e,t,i){this.boundingBox.reConstruct(e,t,i),this.boundingSphere.reConstruct(e,t,i)}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){let i=c._TmpVector3[0].copyFrom(e).subtractInPlace(t),r=c._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(i,r,this.boundingBox.getWorldMatrix()),this}encapsulate(e){let t=s.P.Minimize(this.minimum,e),i=s.P.Maximize(this.maximum,e);return this.reConstruct(t,i,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){let t=s.jp.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);let i=s.jp.Vector3[0];return s.P.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,i),this.encapsulate(i),s.P.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,i),this.encapsulate(i),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=0){return!!((2===t||3===t)&&this.boundingSphere.isCenterInFrustum(e))||!!this.boundingSphere.isInFrustum(e)&&(1===t||3===t||this.boundingBox.isInFrustum(e))}get diagonalLength(){let e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,c._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(!a.K.Intersects(this.boundingSphere,e.boundingSphere)||!n.k.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;let i=this.boundingBox,r=e.boundingBox;return!!(u(i.directions[0],i,r)&&u(i.directions[1],i,r)&&u(i.directions[2],i,r)&&u(r.directions[0],i,r)&&u(r.directions[1],i,r)&&u(r.directions[2],i,r)&&u(s.P.Cross(i.directions[0],r.directions[0]),i,r)&&u(s.P.Cross(i.directions[0],r.directions[1]),i,r)&&u(s.P.Cross(i.directions[0],r.directions[2]),i,r)&&u(s.P.Cross(i.directions[1],r.directions[0]),i,r)&&u(s.P.Cross(i.directions[1],r.directions[1]),i,r)&&u(s.P.Cross(i.directions[1],r.directions[2]),i,r)&&u(s.P.Cross(i.directions[2],r.directions[0]),i,r)&&u(s.P.Cross(i.directions[2],r.directions[1]),i,r)&&u(s.P.Cross(i.directions[2],r.directions[2]),i,r))}}c._TmpVector3=r.B.BuildArray(2,s.P.Zero)},3592:function(e,t,i){i.d(t,{K:function(){return n}});var r=i(4254),s=i(78);class n{constructor(e,t,i){this.center=s.P.Zero(),this.centerWorld=s.P.Zero(),this.minimum=s.P.Zero(),this.maximum=s.P.Zero(),this.reConstruct(e,t,i)}reConstruct(e,t,i){this.minimum.copyFrom(e),this.maximum.copyFrom(t);let r=s.P.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*r,this._update(i||s.y3.IdentityReadOnly)}scale(e){let t=this.radius*e,i=n._TmpVector3,r=i[0].setAll(t),s=this.center.subtractToRef(r,i[1]),a=this.center.addToRef(r,i[2]);return this.reConstruct(s,a,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{s.P.TransformCoordinatesToRef(this.center,e,this.centerWorld);let t=n._TmpVector3[0];s.P.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){let t=this.centerWorld,i=this.radiusWorld;for(let r=0;r<6;r++)if(e[r].dotCoordinate(t)<=-i)return!1;return!0}isCenterInFrustum(e){let t=this.centerWorld;for(let i=0;i<6;i++)if(0>e[i].dotCoordinate(t))return!1;return!0}intersectsPoint(e){let t=s.P.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld=r.Fz.LeftClick&&i<=r.Fz.RightClick&&(h.type=1===s?"pointerdown":"pointerup",h.button=i-2),h}static _CreateWheelEvent(e,t,i,s,a,o){let l=this._CreateMouseEvent(e,t,i,s,a,o);switch(l.pointerId=1,l.type="wheel",l.deltaMode=n.G.DOM_DELTA_PIXEL,l.deltaX=0,l.deltaY=0,l.deltaZ=0,i){case r.Fz.MouseWheelX:l.deltaX=s;break;case r.Fz.MouseWheelY:l.deltaY=s;break;case r.Fz.MouseWheelZ:l.deltaZ=s}return l}static _CreateMouseEvent(e,t,i,s,n,a){let o=this._CreateEvent(a),l=n.pollInput(e,t,r.Fz.Horizontal),h=n.pollInput(e,t,r.Fz.Vertical);return a?(o.movementX=0,o.movementY=0,o.offsetX=o.movementX-a.getBoundingClientRect().x,o.offsetY=o.movementY-a.getBoundingClientRect().y):(o.movementX=n.pollInput(e,t,r.FP.DeltaHorizontal),o.movementY=n.pollInput(e,t,r.FP.DeltaVertical),o.offsetX=0,o.offsetY=0),this._CheckNonCharacterKeys(o,n),o.clientX=l,o.clientY=h,o.x=l,o.y=h,o.deviceType=e,o.deviceSlot=t,o.inputIndex=i,o}static _CreateKeyboardEvent(e,t,i,s){let n=this._CreateEvent(s);return this._CheckNonCharacterKeys(n,i),n.deviceType=r.Yi.Keyboard,n.deviceSlot=0,n.inputIndex=e,n.type=1===t?"keydown":"keyup",n.key=String.fromCharCode(e),n.keyCode=e,n}static _CheckNonCharacterKeys(e,t){let i=t.isDeviceAvailable(r.Yi.Keyboard),s=i&&1===t.pollInput(r.Yi.Keyboard,0,18),n=i&&1===t.pollInput(r.Yi.Keyboard,0,17),a=i&&(1===t.pollInput(r.Yi.Keyboard,0,91)||1===t.pollInput(r.Yi.Keyboard,0,92)||1===t.pollInput(r.Yi.Keyboard,0,93)),o=i&&1===t.pollInput(r.Yi.Keyboard,0,16);e.altKey=s,e.ctrlKey=n,e.metaKey=a,e.shiftKey=o}static _CreateEvent(e){let t={};return t.preventDefault=()=>{},t.target=e,t}}class o{constructor(e,t,i){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,(e,t,r,s)=>{let n=a.CreateDeviceEvent(e,t,r,s,this);i(e,t,n)}):this._createDummyNativeInput()}pollInput(e,t,i){return this._nativeInput.pollInput(e,t,i)}isDeviceAvailable(e){return e===r.Yi.Mouse||e===r.Yi.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}var l=i(7209),h=i(5132);let u=Object.keys(r.Fz).length/2;class c{constructor(e,t,i,r){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=h.w1.IsSafari(),this._usingMacOS=(0,l.up)()&&/(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=(0,l.up)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=(0,l.up)()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=h.w1.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=i,this._onInputChanged=r,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,i){let s=this._inputs[e][t];if(!s)throw`Unable to find device ${r.Yi[e]}`;e>=r.Yi.DualShock&&e<=r.Yi.DualSense&&this._updateDevice(e,t,i);let n=s[i];if(void 0===n)throw`Unable to find input ${i} for device ${r.Yi[e]} in slot ${t}`;return i===r.Fz.Move&&h.w1.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),n}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){let e=this===null||void 0===this?void 0:this._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs){for(let e of this._inputs)if(e)for(let t in e){let i=e[+t];if(i)for(let e=0;e{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.Yi.Keyboard,0,255));let t=this._inputs[r.Yi.Keyboard][0];t&&(t[e.keyCode]=1,e.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&!this._metaKeys.includes(e.keyCode)&&this._metaKeys.push(e.keyCode),this._onInputChanged(r.Yi.Keyboard,0,e))},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(r.Yi.Keyboard,0,255));let t=this._inputs[r.Yi.Keyboard][0];if(t){if(t[e.keyCode]=0,e.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(let e of this._metaKeys){let i=a.CreateDeviceEvent(r.Yi.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(r.Yi.Keyboard,0,i)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(r.Yi.Keyboard,0,e)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){let e=this._inputs[r.Yi.Keyboard][0];for(let t=0;t{let t=this._getPointerType(e),i=t===r.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===r.Yi.Touch&&-1===i){let r=this._activeTouchIds.indexOf(-1);if(r>=0)i=r,this._activeTouchIds[r]=e.pointerId,this._onDeviceConnected(t,i);else{h.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]||this._addPointerDevice(t,i,e.clientX,e.clientY);let s=this._inputs[t][i];s&&(e.inputIndex=r.Fz.Move,s[r.Fz.Horizontal]=e.clientX,s[r.Fz.Vertical]=e.clientY,t===r.Yi.Touch&&0===s[r.Fz.LeftClick]&&(s[r.Fz.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,i,e),this._usingSafari||-1===e.button||(e.inputIndex=e.button+2,s[e.button+2]=s[e.button+2]?0:1,this._onInputChanged(t,i,e)))},this._pointerDownEvent=e=>{let t=this._getPointerType(e),i=t===r.Yi.Mouse?0:e.pointerId;if(t===r.Yi.Touch){let t=this._activeTouchIds.indexOf(-1);if(t>=0)i=t,this._activeTouchIds[t]=e.pointerId;else{h.w1.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);return}}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][i]?t===r.Yi.Touch&&this._onDeviceConnected(t,i):this._addPointerDevice(t,i,e.clientX,e.clientY);let s=this._inputs[t][i];if(s){let n=s[r.Fz.Horizontal],a=s[r.Fz.Vertical];if(t===r.Yi.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){}s[r.Fz.Horizontal]=e.clientX,s[r.Fz.Vertical]=e.clientY,s[e.button+2]=1,e.inputIndex=e.button+2,this._onInputChanged(t,i,e),(n!==e.clientX||a!==e.clientY)&&(e.inputIndex=r.Fz.Move,this._onInputChanged(t,i,e))}},this._pointerUpEvent=e=>{var t,i,s,n,a;let o=this._getPointerType(e),l=o===r.Yi.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(o===r.Yi.Touch){if(-1===l)return;this._activeTouchIds[l]=-1}let h=null===(t=this._inputs[o])||void 0===t?void 0:t[l];if(h&&0!==h[e.button+2]){let t=h[r.Fz.Horizontal],u=h[r.Fz.Vertical];h[r.Fz.Horizontal]=e.clientX,h[r.Fz.Vertical]=e.clientY,h[e.button+2]=0,void 0===e.pointerId&&(e.pointerId=this._mouseId),(t!==e.clientX||u!==e.clientY)&&(e.inputIndex=r.Fz.Move,this._onInputChanged(o,l,e)),e.inputIndex=e.button+2,o===r.Yi.Mouse&&this._mouseId>=0&&(null===(s=(i=this._elementToAttachTo).hasPointerCapture)||void 0===s?void 0:s.call(i,this._mouseId))?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&(null===(a=(n=this._elementToAttachTo).hasPointerCapture)||void 0===a?void 0:a.call(n,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(o,l,e),o===r.Yi.Touch&&this._onDeviceDisconnected(o,l)}},this._pointerCancelEvent=e=>{var t,i,s,n;if("mouse"===e.pointerType){let e=this._inputs[r.Yi.Mouse][0];this._mouseId>=0&&(null===(i=(t=this._elementToAttachTo).hasPointerCapture)||void 0===i?void 0:i.call(t,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=r.Fz.LeftClick;t<=r.Fz.BrowserForward;t++)if(1===e[t]){e[t]=0;let i=a.CreateDeviceEvent(r.Yi.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Mouse,0,i)}}else{let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;(null===(n=(s=this._elementToAttachTo).hasPointerCapture)||void 0===n?void 0:n.call(s,e.pointerId))&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[r.Yi.Touch][t][r.Fz.LeftClick]=0;let i=a.CreateDeviceEvent(r.Yi.Touch,t,r.Fz.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(r.Yi.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(r.Yi.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1,t=function(){};try{let i=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,i),this._elementToAttachTo.removeEventListener("test",t,i)}catch(e){}this._pointerBlurEvent=()=>{var e,t,i,s,n;if(this.isDeviceAvailable(r.Yi.Mouse)){let i=this._inputs[r.Yi.Mouse][0];this._mouseId>=0&&(null===(t=(e=this._elementToAttachTo).hasPointerCapture)||void 0===t?void 0:t.call(e,this._mouseId))&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let e=r.Fz.LeftClick;e<=r.Fz.BrowserForward;e++)if(1===i[e]){i[e]=0;let t=a.CreateDeviceEvent(r.Yi.Mouse,0,e,0,this,this._elementToAttachTo);this._onInputChanged(r.Yi.Mouse,0,t)}}if(this.isDeviceAvailable(r.Yi.Touch)){let e=this._inputs[r.Yi.Touch];for(let t=0;t{let t=r.Yi.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,u));let i=this._inputs[t][0];i&&(i[r.Fz.MouseWheelX]=e.deltaX||0,i[r.Fz.MouseWheelY]=e.deltaY||e.wheelDelta||0,i[r.Fz.MouseWheelZ]=e.deltaZ||0,void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==i[r.Fz.MouseWheelX]&&(e.inputIndex=r.Fz.MouseWheelX,this._onInputChanged(t,0,e)),0!==i[r.Fz.MouseWheelY]&&(e.inputIndex=r.Fz.MouseWheelY,this._onInputChanged(t,0,e)),0!==i[r.Fz.MouseWheelZ]&&(e.inputIndex=r.Fz.MouseWheelZ,this._onInputChanged(t,0,e)))},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(r.Yi.Mouse)){let e=this._inputs[r.Yi.Mouse][0];e[r.Fz.MouseWheelX]=0,e[r.Fz.MouseWheelY]=0,e[r.Fz.MouseWheelZ]=0}})}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){let t=this._getGamepadDeviceType(e.gamepad.id),i=e.gamepad.index;this._unregisterDevice(t,i),delete this._gamepads[i]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,i){let r=navigator.getGamepads()[t];if(r&&e===this._gamepads[t]){let s=this._inputs[e][t];i>=r.buttons.length?s[i]=r.axes[i-r.buttons.length].valueOf():s[i]=r.buttons[i].value}}_getGamepadDeviceType(e){return -1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?r.Yi.DualSense:r.Yi.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?r.Yi.Xbox:-1!==e.indexOf("057e")?r.Yi.Switch:r.Yi.Generic}_getPointerType(e){let t=r.Yi.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=r.Yi.Touch),t}}var d=i(6327);class p{constructor(e){this._registeredManagers=[],this._refCount=0,this.registerManager=e=>{for(let t=0;t{let t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};let t=Object.keys(r.Yi).length/2;this._devices=Array(t);let i=(e,t)=>{for(let i of(this._devices[e]||(this._devices[e]=[]),this._devices[e][t]||(this._devices[e][t]=t),this._registeredManagers)){let r=new d.p(this._deviceInputSystem,e,t);i._addDevice(r)}},s=(e,t)=>{var i;for(let r of((null===(i=this._devices[e])||void 0===i?void 0:i[t])&&delete this._devices[e][t],this._registeredManagers))r._removeDevice(e,t)},n=(e,t,i)=>{if(i)for(let r of this._registeredManagers)r._onInputChanged(e,t,i)};"undefined"!=typeof _native?this._deviceInputSystem=new o(i,s,n):this._deviceInputSystem=new c(e,i,s,n)}dispose(){this._deviceInputSystem.dispose()}}class _{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){let t=Object.keys(r.Yi).length/2;this._devices=Array(t),this._firstDevice=Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new p(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new s.y$(e=>{for(let t of this._devices)if(t)for(let i of t)i&&this.onDeviceConnectedObservable.notifyObserver(e,i)}),this.onDeviceDisconnectedObservable=new s.y$,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]=[]),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){var i,r;let s=null===(i=this._devices[e])||void 0===i?void 0:i[t];this.onDeviceDisconnectedObservable.notifyObservers(s),(null===(r=this._devices[e])||void 0===r?void 0:r[t])&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,i){var r,s;null===(s=null===(r=this._devices[e])||void 0===r?void 0:r[t])||void 0===s||s.onInputChangedObservable.notifyObservers(i)}_updateFirstDevices(e){switch(e){case r.Yi.Keyboard:case r.Yi.Mouse:this._firstDevice[e]=0;break;case r.Yi.Touch:case r.Yi.DualSense:case r.Yi.DualShock:case r.Yi.Xbox:case r.Yi.Switch:case r.Yi.Generic:{delete this._firstDevice[e];let t=this._devices[e];if(t){for(let i=0;i=s&&0===i?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,i,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(i,i+r)):(t=t instanceof ArrayBuffer?new Uint8Array(t,i,r):new Uint8Array(t.buffer,t.byteOffset+i,r),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()}},9255:function(e,t,i){i.d(t,{A:function(){return s}});var r=i(6465);function s(e,t,i=!1,r){switch(e){case 3:{let e=(ArrayBuffer,new Int8Array(t));return r&&e.set(new Int8Array(r)),e}case 0:{let e=(ArrayBuffer,new Uint8Array(t));return r&&e.set(new Uint8Array(r)),e}case 4:{let e=new Int16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Int16Array(r)),e}case 5:case 8:case 9:case 10:case 2:{let e=new Uint16Array(t instanceof ArrayBuffer?t:i?t/2:t);return r&&e.set(new Uint16Array(r)),e}case 6:{let e=new Int32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Int32Array(r)),e}case 7:case 11:case 12:case 13:case 14:case 15:{let e=new Uint32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Uint32Array(r)),e}case 1:{let e=new Float32Array(t instanceof ArrayBuffer?t:i?t/4:t);return r&&e.set(new Float32Array(r)),e}}let s=(ArrayBuffer,new Uint8Array(t));return r&&s.set(new Uint8Array(r)),s}r.B.prototype._readTexturePixelsSync=function(e,t,i,r=-1,n=0,a=null,o=!0,l=!1,h=0,u=0){var c,d;let p=this._gl;if(!p)throw Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){let e=p.createFramebuffer();if(!e)throw Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}p.bindFramebuffer(p.FRAMEBUFFER,this._dummyFramebuffer),r>-1?p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_CUBE_MAP_POSITIVE_X+r,null===(c=e._hardwareTexture)||void 0===c?void 0:c.underlyingResource,n):p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,null===(d=e._hardwareTexture)||void 0===d?void 0:d.underlyingResource,n);let _=void 0!==e.type?this._getWebGLTextureType(e.type):p.UNSIGNED_BYTE;return l?a||(a=s(e.type,4*t*i)):_===p.UNSIGNED_BYTE?(a||(a=new Uint8Array(4*t*i)),_=p.UNSIGNED_BYTE):(a||(a=new Float32Array(4*t*i)),_=p.FLOAT),o&&this.flushFramebuffer(),p.readPixels(h,u,t,i,p.RGBA,_,a),p.bindFramebuffer(p.FRAMEBUFFER,this._currentFramebuffer),a},r.B.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){return Promise.resolve(this._readTexturePixelsSync(e,t,i,r,s,n,a,o,l,h))}},68:function(e,t,i){var r=i(6465),s=i(998);r.B.prototype.createUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create uniform buffer");let r=new s.M(i);return this.bindUniformBuffer(r),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),r.references=1,r},r.B.prototype.createDynamicUniformBuffer=function(e,t){let i=this._gl.createBuffer();if(!i)throw Error("Unable to create dynamic uniform buffer");let r=new s.M(i);return this.bindUniformBuffer(r),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),r.references=1,r},r.B.prototype.updateUniformBuffer=function(e,t,i,r){this.bindUniformBuffer(e),void 0===i&&(i=0),void 0===r?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,i,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(i,i+r)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(i,i+r)),this.bindUniformBuffer(null)},r.B.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},r.B.prototype.bindUniformBufferBase=function(e,t,i){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},r.B.prototype.bindUniformBlock=function(e,t,i){let r=e.program,s=this._gl.getUniformBlockIndex(r,t);4294967295!==s&&this._gl.uniformBlockBinding(r,s,i)}},7790:function(e,t,i){i.d(t,{L:function(){return S}});class r{constructor(){this.children=[]}isValid(e){return!0}process(e,t){var i,r,s,n,a,o,l;let h="";if(this.line){let u=this.line,c=t.processor;if(c){c.lineProcessor&&(u=c.lineProcessor(u,t.isFragment,t.processingContext));let h=null!==(r=null===(i=t.processor)||void 0===i?void 0:i.attributeKeywordName)&&void 0!==r?r:"attribute",d=t.isFragment&&(null===(s=t.processor)||void 0===s?void 0:s.varyingFragmentKeywordName)?null===(n=t.processor)||void 0===n?void 0:n.varyingFragmentKeywordName:!t.isFragment&&(null===(a=t.processor)||void 0===a?void 0:a.varyingVertexKeywordName)?null===(o=t.processor)||void 0===o?void 0:o.varyingVertexKeywordName:"varying";!t.isFragment&&c.attributeProcessor&&this.line.startsWith(h)?u=c.attributeProcessor(this.line,e,t.processingContext):c.varyingProcessor&&((null===(l=c.varyingCheck)||void 0===l?void 0:l.call(c,this.line,t.isFragment))||!c.varyingCheck&&this.line.startsWith(d))?u=c.varyingProcessor(this.line,t.isFragment,e,t.processingContext):c.uniformProcessor&&c.uniformRegexp&&c.uniformRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&c.uniformBufferRegexp&&c.uniformBufferRegexp.test(this.line)?t.lookForClosingBracketForUniformBuffer||(u=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0):c.textureProcessor&&c.textureRegexp&&c.textureRegexp.test(this.line)?u=c.textureProcessor(this.line,t.isFragment,e,t.processingContext):(c.uniformProcessor||c.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer&&(/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?c.uniformProcessor&&(u=c.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):c.uniformBufferProcessor&&(u=c.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)),t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,c.endOfUniformBufferProcessor&&(u=c.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}h+=u+"\n"}return this.children.forEach(i=>{h+=i.process(e,t)}),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),h}}class s{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex1&&this._lines.push(e);else{let e=t.split(";");for(let t=0;t{""!==(u=u.trim())&&(i.push(u),u="")},n=e=>{ro._Stack[r],l=()=>-1===r?"!!INVALID EXPRESSION!!":o._Stack[r--],h=0,u="";for(;h1){for(s();-1!==r&&o._OperatorPriority[a()]>=o._OperatorPriority[c];)i.push(l());n(c),h++}else u+=t;h++}for(s();-1!==r;)"("===a()?l():i.push(l());return o._InfixToPostfixCache.size>=o.InfixToPostfixCacheLimitSize&&o.ClearCache(),o._InfixToPostfixCache.set(e,{result:i,accessTime:Date.now()}),i}static ClearCache(){let e=Array.from(o._InfixToPostfixCache.entries()).sort((e,t)=>e[1].accessTime-t[1].accessTime);for(let t=0;t":i=r>s;break;case"<":i=r=":i=r>=s;break;case"==":i=r===s;break;case"!=":i=r!==s}return i}}var d=i(6131),p=i(5550);let _=/defined\s*?\((.+?)\)/g,f=/defined\s*?\[(.+?)\]/g,m=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,g=/__decl__/,v=/light\{X\}.(\w*)/g,x=/\{X\}/g,T=[];class S{static Initialize(e){e.processor&&e.processor.initializeShaders&&e.processor.initializeShaders(e.processingContext)}static Process(e,t,i,r){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e)),i(this._ProcessShaderConversion(e,t,r),e)})}static PreProcess(e,t,i,r){var s;(null===(s=t.processor)||void 0===s?void 0:s.preProcessShaderCode)&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),this._ProcessIncludes(e,t,e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e)),i(this._ApplyPreProcessing(e,t,r),e)})}static Finalize(e,t,i){return i.processor&&i.processor.finalizeShaders?i.processor.finalizeShaders(e,t,i.processingContext):{vertexCode:e,fragmentCode:t}}static _ProcessPrecision(e,t){var i;if(null===(i=t.processor)||void 0===i?void 0:i.noPrecision)return e;let r=t.shouldUseHighPrecisionShader;return -1===e.indexOf("precision highp float")?e=r?"precision highp float;\n"+e:"precision mediump float;\n"+e:r||(e=e.replace("precision highp float","precision mediump float")),e}static _ExtractOperation(e){let t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new l(t[1].trim(),"!"===e[0]);let i="",r=0;for(i of["==","!=",">=","<=","<",">"])if((r=e.indexOf(i))>-1)break;if(-1===r)return new l(e);let s=e.substring(0,r).trim(),n=e.substring(r+i.length).trim();return new c(s,i,n)}static _BuildSubExpression(e){e=e.replace(_,"defined[$1]");let t=o.infixToPostfix(e),i=[];for(let e of t)if("||"!==e&&"&&"!==e)i.push(e);else if(i.length>=2){let t=i[i.length-1],r=i[i.length-2];i.length-=2;let s="&&"==e?new u:new h;"string"==typeof t&&(t=t.replace(f,"defined($1)")),"string"==typeof r&&(r=r.replace(f,"defined($1)")),s.leftOperand="string"==typeof r?this._ExtractOperation(r):r,s.rightOperand="string"==typeof t?this._ExtractOperation(t):t,i.push(s)}let r=i[i.length-1];return"string"==typeof r&&(r=r.replace(f,"defined($1)")),"string"==typeof r?this._ExtractOperation(r):r}static _BuildExpression(e,t){let i=new a,r=e.substring(0,t),s=e.substring(t);return s=s.substring(0,(s.indexOf("//")+1||s.length+1)-1).trim(),"#ifdef"===r?i.testExpression=new l(s):"#ifndef"===r?i.testExpression=new l(s,!0):i.testExpression=this._BuildSubExpression(s),i}static _MoveCursorWithinIf(e,t,i){let s=e.currentLine;for(;this._MoveCursor(e,i);){let n=(s=e.currentLine).substring(0,5).toLowerCase();if("#else"===n){let i=new r;t.children.push(i),this._MoveCursor(e,i);return}if("#elif"===n){let e=this._BuildExpression(s,5);t.children.push(e),i=e}}}static _MoveCursor(e,t){for(;e.canRead;){e.lineIndex++;let i=e.currentLine;if(i.indexOf("#")>=0){let r=S._MoveCursorRegex.exec(i);if(r&&r.length){switch(r[0]){case"#ifdef":{let r=new n;t.children.push(r);let s=this._BuildExpression(i,6);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{let r=new n;t.children.push(r);let s=this._BuildExpression(i,7);r.children.push(s),this._MoveCursorWithinIf(e,r,s);break}case"#if":{let r=new n,s=this._BuildExpression(i,3);t.children.push(r),r.children.push(s),this._MoveCursorWithinIf(e,r,s)}}continue}}let s=new r;if(s.line=i,t.children.push(s),"#"===i[0]&&"d"===i[1]){let e=i.replace(";","").split(" ");s.additionalDefineKey=e[1],3===e.length&&(s.additionalDefineValue=e[2])}}return!1}static _EvaluatePreProcessors(e,t,i){let n=new r,a=new s;return a.lineIndex=-1,a.lines=e.split("\n"),this._MoveCursor(a,n),n.process(t,i)}static _PreparePreProcessors(e,t){var i;let r=e.defines,s={};for(let e of r){let t=e.replace("#define","").replace(";","").trim().split(" ");s[t[0]]=t.length>1?t[1]:""}return(null===(i=e.processor)||void 0===i?void 0:i.shaderLanguage)===p.x.GLSL&&(s.GL_ES="true"),s.__VERSION__=e.version,s[e.platformName]="true",t._getGlobalDefines(s),s}static _ProcessShaderConversion(e,t,i){let r=this._ProcessPrecision(e,t);if(!t.processor||t.processor.shaderLanguage===p.x.GLSL&&-1!==r.indexOf("#version 3")&&(r=r.replace("#version 300 es",""),!t.processor.parseGLES3))return r;let s=t.defines,n=this._PreparePreProcessors(t,i);return t.processor.preProcessor&&(r=t.processor.preProcessor(r,s,t.isFragment,t.processingContext)),r=this._EvaluatePreProcessors(r,n,t),t.processor.postProcessor&&(r=t.processor.postProcessor(r,s,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(r=i.inlineShaderCode(r)),r}static _ApplyPreProcessing(e,t,i){var r,s;let n=e,a=t.defines,o=this._PreparePreProcessors(t,i);return(null===(r=t.processor)||void 0===r?void 0:r.preProcessor)&&(n=t.processor.preProcessor(n,a,t.isFragment,t.processingContext)),n=this._EvaluatePreProcessors(n,o,t),(null===(s=t.processor)||void 0===s?void 0:s.postProcessor)&&(n=t.processor.postProcessor(n,a,t.isFragment,t.processingContext,i)),i._features.needShaderCodeInlining&&(n=i.inlineShaderCode(n)),n}static _ProcessIncludes(e,t,i){let r;for(T.length=0;null!==(r=m.exec(e));)T.push(r);let s=String(e),n=[e],a=!1;for(let e of T){let r=e[1];if(-1!==r.indexOf("__decl__")&&(r=r.replace(g,""),t.supportsUniformBuffers&&(r=r.replace("Vertex","Ubo").replace("Fragment","Ubo")),r+="Declaration"),t.includesShadersStore[r]){let i=t.includesShadersStore[r];if(e[2]){let t=e[3].split(",");for(let e=0;et+"{X}")),i+=a.replace(x,e.toString())+"\n"}else t.supportsUniformBuffers||(i=i.replace(v,(e,t)=>t+"{X}")),i=i.replace(x,r)}let s=[];for(let t of n){let r=t.split(e[0]);for(let e=0;e=0||i.indexOf("#include <")>=0}else{let e=t.shadersRepository+"ShadersInclude/"+r+".fx";S._FileToolsLoadFile(e,e=>{t.includesShadersStore[r]=e,this._ProcessIncludes(n.join(""),t,i)});return}}T.length=0,s=n.join(""),a?this._ProcessIncludes(s.toString(),t,i):i(s)}static _FileToolsLoadFile(e,t,i,r,s,n){throw(0,d.S)("FileTools")}}S._MoveCursorRegex=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/},7666:function(e,t,i){i.d(t,{C:function(){return n}});var r=i(5550);let s=/(flat\s)?\s*varying\s*.*/;class n{constructor(){this.shaderLanguage=r.x.GLSL}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return s.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,i){let r=-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("),i){let 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,(r||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}}},5342:function(e,t,i){i.d(t,{B:function(){return r}});class r{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw 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(let e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){var t,i;return null!==(i=null===(t=this._MSAARenderBuffers)||void 0===t?void 0:t[e])&&void 0!==i?i:null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}},856:function(e,t,i){i.d(t,{y:function(){return r}});class r{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)}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this.engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);for(this.engine.getUniforms(this,i).forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l{n[e]=t}),h.getAttributes(this,a)))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r||2!==r.length)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s||3!==s.length)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setInt4(this._uniforms[e],t,i,r,s)&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this.engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setUInt4(this._uniforms[e],t,i,r,s)&&(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.toArray())&&(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){let i=this._valueCache[e];(void 0===i||i!==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,i){this._cacheFloat2(e,t,i)&&!this.engine.setFloat2(this._uniforms[e],t,i)&&(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,i,r){this._cacheFloat3(e,t,i,r)&&!this.engine.setFloat3(this._uniforms[e],t,i,r)&&(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,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this.engine.setFloat4(this._uniforms[e],t,i,r,s)&&(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(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}}},5410:function(e,t,i){i.d(t,{f:function(){return s}});var r=i(5550);class s{constructor(){this.shaderLanguage=r.x.GLSL}postProcessor(e,t,i,r,s){return s.getCaps().drawBuffersExtension||(e=e.replace(/#extension.+GL_EXT_draw_buffers.+(enable|require)/g,"")),e}}},8906:function(e,t,i){i.d(t,{D:function(){return _}});var r=i(4800),s=i(3912),n=i(7209),a=i(6030),o=i(6131),l=i(6465),h=i(8786),u=i(7263),c=i(998),d=i(9626),p=i(5342);i(6628),i(9255),i(6529);class _ extends l.B{static get NpmPackage(){return l.B.NpmPackage}static get Version(){return l.B.Version}static get Instances(){return a.l.Instances}static get LastCreatedEngine(){return a.l.LastCreatedEngine}static get LastCreatedScene(){return a.l.LastCreatedScene}_createImageBitmapFromSource(e,t){return new Promise((i,r)=>{let s=new Image;s.onload=()=>{s.decode().then(()=>{this.createImageBitmap(s,t).then(e=>{i(e)})})},s.onerror=()=>{r(`Error loading image ${s.src}`)},s.src=e})}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,i){let r=this.createCanvas(t,i).getContext("2d");if(!r)throw Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(e,0,0),r.getImageData(0,0,t,i).data}static MarkAllMaterialsAsDirty(e,t){for(let i=0;i<_.Instances.length;i++){let r=_.Instances[i];for(let i=0;i{this.onCanvasFocusObservable.notifyObservers(this)},this._onCanvasBlur=()=>{this.onCanvasBlurObservable.notifyObservers(this)},this._onCanvasContextMenu=e=>{this.disableContextMenu&&e.preventDefault()},e.addEventListener("focus",this._onCanvasFocus),e.addEventListener("blur",this._onCanvasBlur),e.addEventListener("contextmenu",this._onCanvasContextMenu),this._onBlur=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.disable(),this._windowIsBackground=!0},this._onFocus=()=>{this.disablePerformanceMonitorInBackground&&this._performanceMonitor.enable(),this._windowIsBackground=!1},this._onCanvasPointerOut=t=>{document.elementFromPoint(t.clientX,t.clientY)!==e&&this.onCanvasPointerOutObservable.notifyObservers(t)};let t=this.getHostWindow();t&&"function"==typeof t.addEventListener&&(t.addEventListener("blur",this._onBlur),t.addEventListener("focus",this._onFocus)),e.addEventListener("pointerout",this._onCanvasPointerOut),this._creationOptions.doNotHandleTouchAction||this._disableTouchAction(),!_.audioEngine&&this._creationOptions.audioEngine&&_.AudioEngineFactory&&(_.audioEngine=_.AudioEngineFactory(this.getRenderingCanvas(),this.getAudioContext(),this.getAudioDestination())),(0,n.n5)()&&(this._onFullscreenChange=()=>{this.isFullscreen=!!document.fullscreenElement,this.isFullscreen&&this._pointerLockRequested&&e&&_._RequestPointerlock(e)},document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",this._onFullscreenChange,!1),this._onPointerLockChange=()=>{this.isPointerLock=document.pointerLockElement===e},document.addEventListener("pointerlockchange",this._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",this._onPointerLockChange,!1)),this.enableOfflineSupport=void 0!==_.OfflineProviderFactory,this._deterministicLockstep=!!this._creationOptions.deterministicLockstep,this._lockstepMaxSteps=this._creationOptions.lockstepMaxSteps||0,this._timeStep=this._creationOptions.timeStep||1/60}_verifyPointerLock(){var e;null===(e=this._onPointerLockChange)||void 0===e||e.call(this)}getAspectRatio(e,t=!1){let i=e.viewport;return this.getRenderWidth(t)*i.width/(this.getRenderHeight(t)*i.height)}getScreenAspectRatio(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)}getRenderingCanvasClientRect(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null}getInputElementClientRect(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}generateMipMapsForCubemap(e,t=!0){if(e.generateMipMaps){let i=this._gl;this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,e,!0),i.generateMipmap(i.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)}}getDepthWrite(){return this._depthCullingState.depthMask}setDepthWrite(e){this._depthCullingState.depthMask=e}getStencilBuffer(){return this._stencilState.stencilTest}setStencilBuffer(e){this._stencilState.stencilTest=e}getStencilMask(){return this._stencilState.stencilMask}setStencilMask(e){this._stencilState.stencilMask=e}getStencilFunction(){return this._stencilState.stencilFunc}getStencilFunctionReference(){return this._stencilState.stencilFuncRef}getStencilFunctionMask(){return this._stencilState.stencilFuncMask}setStencilFunction(e){this._stencilState.stencilFunc=e}setStencilFunctionReference(e){this._stencilState.stencilFuncRef=e}setStencilFunctionMask(e){this._stencilState.stencilFuncMask=e}getStencilOperationFail(){return this._stencilState.stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilState.stencilOpDepthFail}getStencilOperationPass(){return this._stencilState.stencilOpStencilDepthPass}setStencilOperationFail(e){this._stencilState.stencilOpStencilFail=e}setStencilOperationDepthFail(e){this._stencilState.stencilOpDepthFail=e}setStencilOperationPass(e){this._stencilState.stencilOpStencilDepthPass=e}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)}getDepthFunction(){return this._depthCullingState.depthFunc}setDepthFunction(e){this._depthCullingState.depthFunc=e}setDepthFunctionToGreater(){this.setDepthFunction(516)}setDepthFunctionToGreaterOrEqual(){this.setDepthFunction(518)}setDepthFunctionToLess(){this.setDepthFunction(513)}setDepthFunctionToLessOrEqual(){this.setDepthFunction(515)}cacheStencilState(){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()}restoreStencilState(){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)}setDirectViewport(e,t,i,r){let s=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,i,r),s}scissorClear(e,t,i,r,s){this.enableScissor(e,t,i,r),this.clear(s,!0,!0,!0),this.disableScissor()}enableScissor(e,t,i,r){let s=this._gl;s.enable(s.SCISSOR_TEST),s.scissor(e,t,i,r)}disableScissor(){let e=this._gl;e.disable(e.SCISSOR_TEST)}_reportDrawCall(e=1){this._drawCalls.addCount(e,!1)}_loadFileAsync(e,t,i){return new Promise((r,s)=>{this._loadFile(e,e=>{r(e)},void 0,t,i,(e,t)=>{s(t)})})}getVertexShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){let t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}setDepthStencilTexture(e,t,i,r){void 0!==e&&(t&&(this._boundUniforms[e]=t),i&&i.depthStencilTexture?this._setTexture(e,i,!1,!0,r):this._setTexture(e,null,void 0,void 0,r))}setTextureFromPostProcess(e,t,i){var r;let s=null;t&&(t._forcedOutputTexture?s=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(s=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,null!==(r=null==s?void 0:s.texture)&&void 0!==r?r:null,i)}setTextureFromPostProcessOutput(e,t,i){var r,s;this._bindTexture(e,null!==(s=null===(r=null==t?void 0:t._outputTexture)||void 0===r?void 0:r.texture)&&void 0!==s?s:null,i)}_rebuildBuffers(){for(let e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(let e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}_rebuildTextures(){for(let e of this.scenes)e._rebuildTextures();for(let e of this._virtualScenes)e._rebuildTextures();super._rebuildTextures()}_renderFrame(){for(let e=0;e0?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()):this._renderingQueueLaunched=!1}_renderViews(){return!1}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){!this.isFullscreen&&(this._pointerLockRequested=e,this._renderingCanvas&&_._RequestFullscreen(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&_._ExitFullscreen()}enterPointerlock(){this._renderingCanvas&&_._RequestPointerlock(this._renderingCanvas)}exitPointerlock(){_._ExitPointerlock()}beginFrame(){this._measureFps(),this.onBeginFrameObservable.notifyObservers(this),super.beginFrame()}endFrame(){super.endFrame(),this.onEndFrameObservable.notifyObservers(this)}setSize(e,t,i=!1){if(!this._renderingCanvas||!super.setSize(e,t,i))return!1;if(this.scenes){for(let e=0;e1&&s){let t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,s),e.transformFeedback=t}return r.linkProgram(n),this.webGLVersion>1&&s&&this.bindTransformFeedback(null),e.context=r,e.vertexShader=t,e.fragmentShader=i,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)})})})}getRenderPassNames(){return this._renderPassNames}getCurrentRenderPassName(){return this._renderPassNames[this.currentRenderPassId]}createRenderPassId(e){let t=++_._RenderPassIdCounter;return this._renderPassNames[t]=null!=e?e:"NONAME",t}releaseRenderPassId(e){this._renderPassNames[e]=void 0;for(let t=0;t{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=i;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,r,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),s&&s()}))}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}wrapWebGLTexture(e,t=!1,i=3,r=0,n=0){let a=new p.B(e,this._gl),o=new s.l(this,s.S.Unknown,!0);return o._hardwareTexture=a,o.baseWidth=r,o.baseHeight=n,o.width=r,o.height=n,o.isReady=!0,o.useMipMaps=t,this.updateTextureSamplingMode(i,o),o}_uploadImageToTexture(e,t,i=0,r=0){let s=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),l=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(l,e,!0),this._unpackFlipY(e.invertY);let h=s.TEXTURE_2D;e.isCube&&(h=s.TEXTURE_CUBE_MAP_POSITIVE_X+i),s.texImage2D(h,r,o,a,n,t),this._bindTextureDirectly(l,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion){d.Y.Error("WebGL 1 does not support texture comparison.");return}let i=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,515),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.NONE)):(i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_FUNC,t),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){let t=this._gl.createBuffer();if(!t)throw Error("Unable to create instance buffer");let i=new c.M(t);return i.capacity=e,this.bindArrayBuffer(i),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),i.references=1,i}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,i=10){let r=this._gl;return new Promise((s,n)=>{let a=()=>{let o=r.clientWaitSync(e,t,0);if(o==r.WAIT_FAILED){n();return}if(o==r.TIMEOUT_EXPIRED){setTimeout(a,i);return}s()};a()})}_readPixelsAsync(e,t,i,r,s,n,a){if(this._webGLVersion<2)throw Error("_readPixelsAsync only work on WebGL2+");let o=this._gl,l=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,i,r,s,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);let h=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return h?(o.flush(),this._clientWaitAsync(h,0,10).then(()=>(o.deleteSync(h),o.bindBuffer(o.PIXEL_PACK_BUFFER,l),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(l),a))):null}dispose(){for(this.hideLoadingUI(),this.onNewSceneAddedObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(this._rescalePostProcess&&this._rescalePostProcess.dispose();this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();1===a.l.Instances.length&&_.audioEngine&&(_.audioEngine.dispose(),_.audioEngine=null);let e=this.getHostWindow();e&&"function"==typeof e.removeEventListener&&(e.removeEventListener("blur",this._onBlur),e.removeEventListener("focus",this._onFocus)),this._renderingCanvas&&(this._renderingCanvas.removeEventListener("focus",this._onCanvasFocus),this._renderingCanvas.removeEventListener("blur",this._onCanvasBlur),this._renderingCanvas.removeEventListener("pointerout",this._onCanvasPointerOut),this._renderingCanvas.removeEventListener("contextmenu",this._onCanvasContextMenu)),(0,n.n5)()&&(document.removeEventListener("fullscreenchange",this._onFullscreenChange),document.removeEventListener("mozfullscreenchange",this._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",this._onFullscreenChange),document.removeEventListener("msfullscreenchange",this._onFullscreenChange),document.removeEventListener("pointerlockchange",this._onPointerLockChange),document.removeEventListener("mspointerlockchange",this._onPointerLockChange),document.removeEventListener("mozpointerlockchange",this._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",this._onPointerLockChange)),super.dispose();let t=a.l.Instances.indexOf(this);t>=0&&a.l.Instances.splice(t,1),_.Instances.length||a.l.OnEnginesDisposedObservable.notifyObservers(this),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}_disableTouchAction(){this._renderingCanvas&&this._renderingCanvas.setAttribute&&(this._renderingCanvas.setAttribute("touch-action","none"),this._renderingCanvas.style.touchAction="none",this._renderingCanvas.style.webkitTapHighlightColor="transparent")}displayLoadingUI(){if(!(0,n.CG)())return;let e=this.loadingScreen;e&&e.displayLoadingUI()}hideLoadingUI(){if(!(0,n.CG)())return;let e=this._loadingScreen;e&&e.hideLoadingUI()}get loadingScreen(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=_.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen}set loadingScreen(e){this._loadingScreen=e}set loadingUIText(e){this.loadingScreen.loadingUIText=e}set loadingUIBackgroundColor(e){this.loadingScreen.loadingUIBackgroundColor=e}createVideoElement(e){return document.createElement("video")}static _RequestPointerlock(e){if(e.requestPointerLock){let t=e.requestPointerLock();t instanceof Promise?t.then(()=>{e.focus()}).catch(()=>{}):e.focus()}}static _ExitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}static _RequestFullscreen(e){let t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}static _ExitFullscreen(){let e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}getFontOffset(e){let t=document.createElement("span");t.innerHTML="Hg",t.setAttribute("style",`font: ${e} !important`);let i=document.createElement("div");i.style.display="inline-block",i.style.width="1px",i.style.height="0px",i.style.verticalAlign="bottom";let r=document.createElement("div");r.style.whiteSpace="nowrap",r.appendChild(t),r.appendChild(i),document.body.appendChild(r);let s=0,n=0;try{n=i.getBoundingClientRect().top-t.getBoundingClientRect().top,i.style.verticalAlign="baseline",s=i.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(r)}return{ascent:s,height:n,descent:n-s}}}_.ALPHA_DISABLE=0,_.ALPHA_ADD=1,_.ALPHA_COMBINE=2,_.ALPHA_SUBTRACT=3,_.ALPHA_MULTIPLY=4,_.ALPHA_MAXIMIZED=5,_.ALPHA_ONEONE=6,_.ALPHA_PREMULTIPLIED=7,_.ALPHA_PREMULTIPLIED_PORTERDUFF=8,_.ALPHA_INTERPOLATE=9,_.ALPHA_SCREENMODE=10,_.DELAYLOADSTATE_NONE=0,_.DELAYLOADSTATE_LOADED=1,_.DELAYLOADSTATE_LOADING=2,_.DELAYLOADSTATE_NOTLOADED=4,_.NEVER=512,_.ALWAYS=519,_.LESS=513,_.EQUAL=514,_.LEQUAL=515,_.GREATER=516,_.GEQUAL=518,_.NOTEQUAL=517,_.KEEP=7680,_.REPLACE=7681,_.INCR=7682,_.DECR=7683,_.INVERT=5386,_.INCR_WRAP=34055,_.DECR_WRAP=34056,_.TEXTURE_CLAMP_ADDRESSMODE=0,_.TEXTURE_WRAP_ADDRESSMODE=1,_.TEXTURE_MIRROR_ADDRESSMODE=2,_.TEXTUREFORMAT_ALPHA=0,_.TEXTUREFORMAT_LUMINANCE=1,_.TEXTUREFORMAT_LUMINANCE_ALPHA=2,_.TEXTUREFORMAT_RGB=4,_.TEXTUREFORMAT_RGBA=5,_.TEXTUREFORMAT_RED=6,_.TEXTUREFORMAT_R=6,_.TEXTUREFORMAT_RG=7,_.TEXTUREFORMAT_RED_INTEGER=8,_.TEXTUREFORMAT_R_INTEGER=8,_.TEXTUREFORMAT_RG_INTEGER=9,_.TEXTUREFORMAT_RGB_INTEGER=10,_.TEXTUREFORMAT_RGBA_INTEGER=11,_.TEXTURETYPE_UNSIGNED_BYTE=0,_.TEXTURETYPE_UNSIGNED_INT=0,_.TEXTURETYPE_FLOAT=1,_.TEXTURETYPE_HALF_FLOAT=2,_.TEXTURETYPE_BYTE=3,_.TEXTURETYPE_SHORT=4,_.TEXTURETYPE_UNSIGNED_SHORT=5,_.TEXTURETYPE_INT=6,_.TEXTURETYPE_UNSIGNED_INTEGER=7,_.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,_.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,_.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,_.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,_.TEXTURETYPE_UNSIGNED_INT_24_8=12,_.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,_.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,_.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,_.TEXTURE_NEAREST_SAMPLINGMODE=1,_.TEXTURE_BILINEAR_SAMPLINGMODE=2,_.TEXTURE_TRILINEAR_SAMPLINGMODE=3,_.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,_.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,_.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,_.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,_.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,_.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,_.TEXTURE_NEAREST_LINEAR=7,_.TEXTURE_NEAREST_NEAREST=1,_.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,_.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,_.TEXTURE_LINEAR_LINEAR=2,_.TEXTURE_LINEAR_NEAREST=12,_.TEXTURE_EXPLICIT_MODE=0,_.TEXTURE_SPHERICAL_MODE=1,_.TEXTURE_PLANAR_MODE=2,_.TEXTURE_CUBIC_MODE=3,_.TEXTURE_PROJECTION_MODE=4,_.TEXTURE_SKYBOX_MODE=5,_.TEXTURE_INVCUBIC_MODE=6,_.TEXTURE_EQUIRECTANGULAR_MODE=7,_.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,_.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,_.SCALEMODE_FLOOR=1,_.SCALEMODE_NEAREST=2,_.SCALEMODE_CEILING=3,_._RescalePostProcessFactory=null,_._RenderPassIdCounter=0},6030:function(e,t,i){i.d(t,{l:function(){return s}});var r=i(4800);class s{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}s.Instances=[],s.OnEnginesDisposedObservable=new r.y$,s._LastCreatedScene=null,s.UseFallbackTexture=!0,s.FallbackTexture=""},4548:function(e,t,i){i.d(t,{Z:function(){return r}});class r{static SetMatrixPrecision(e){if(r.MatrixTrackPrecisionChange=!1,e&&!r.MatrixUse64Bits&&r.MatrixTrackedMatrices)for(let e=0;e=h.Fz.MouseWheelX&&t.inputIndex<=h.Fz.MouseWheelZ?r.kD.POINTERWHEEL:r.kD.POINTERMOVE;s.onPointerMove&&(e=e||this._pickMove(t),s.onPointerMove(t,e,o)),e?(i=new r.R5(o,t,e),this._setRayOnPointerInfo(e,t)):(i=new r.R5(o,t,null,this),this._movePointerInfo=i),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,o)}_setRayOnPointerInfo(e,t){let i=this._scene;e&&i._pickingAvailable&&!e.ray&&(e.ray=i.createPickingRay(t.offsetX,t.offsetY,a.y3.Identity(),i.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,i){let s=this._scene,n=new r.FV(i,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(n.originalPickingInfo=e,n.ray=e.ray,e.originMesh&&(n.nearInteractionPickingInfo=e)),s.onPrePointerObservable.notifyObservers(n,i),!!n.skipOnPointerObservable}_pickMove(e){let t=this._scene,i=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(i,e,t),i}_setCursorAndPointerOverMesh(e,t,i){let r=i.getEngine().getInputElement();if(null==e?void 0:e.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!i.doNotHandleCursors&&r&&this._pointerOverMesh){let e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(r.style.cursor=e.hoverCursor||i.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){let i=new PointerEvent("pointermove",t);i.inputIndex=h.Fz.Move,this._checkPrePointerObservable(e,i,r.kD.POINTERMOVE)||this._processPointerMove(e,i)}simulatePointerDown(e,t){let i=new PointerEvent("pointerdown",t);i.inputIndex=i.button+2,this._checkPrePointerObservable(e,i,r.kD.POINTERDOWN)||this._processPointerDown(e,i)}_processPointerDown(e,t){let i;let s=this._scene;if(null==e?void 0:e.pickedMesh){this._pickedDownMesh=e.pickedMesh;let i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(5,o.V.CreateNew(e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(2,o.V.CreateNew(e.pickedMesh,t,e));break;case 1:i.processTrigger(4,o.V.CreateNew(e.pickedMesh,t,e));break;case 2:i.processTrigger(3,o.V.CreateNew(e.pickedMesh,t,e))}i.hasSpecificTrigger(8)&&window.setTimeout(()=>{let e=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(8)&&e===this._pickedDownMesh,!1,s.cameraToUseForPointers);(null==e?void 0:e.pickedMesh)&&i&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>p.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(8,o.V.CreateNew(e.pickedMesh,t)))},p.LongPressDelay)}}else for(let i of s._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let n=r.kD.POINTERDOWN;e?(s.onPointerDown&&s.onPointerDown(t,e,n),i=new r.R5(n,t,e),this._setRayOnPointerInfo(e,t)):i=new r.R5(n,t,null,this),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,n)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,i){let s=new PointerEvent("pointerup",t);s.inputIndex=h.Fz.Move;let n=new d;i?n.doubleClick=!0:n.singleClick=!0,this._checkPrePointerObservable(e,s,r.kD.POINTERUP)||this._processPointerUp(e,s,n)}_processPointerUp(e,t,i){let s=this._scene;if(null==e?void 0:e.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(s.onPointerPick&&s.onPointerPick(t,e),i.singleClick&&!i.ignore&&s.onPointerObservable.observers.length>this._cameraObserverCount)){let i=r.kD.POINTERPICK,n=new r.R5(i,t,e);this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,i)}let n=e.pickedMesh._getActionManagerForTrigger();if(n&&!i.ignore){n.processTrigger(7,o.V.CreateNew(e.pickedMesh,t,e)),!i.hasSwiped&&i.singleClick&&n.processTrigger(1,o.V.CreateNew(e.pickedMesh,t,e));let r=e.pickedMesh._getActionManagerForTrigger(6);i.doubleClick&&r&&r.processTrigger(6,o.V.CreateNew(e.pickedMesh,t,e))}}else if(!i.ignore)for(let r of s._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,i.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){let e=this._pickedDownMesh._getActionManagerForTrigger(16);e&&e.processTrigger(16,o.V.CreateNew(this._pickedDownMesh,t))}if(!i.ignore){let n=new r.R5(r.kD.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),s.onPointerObservable.notifyObservers(n,r.kD.POINTERUP),s.onPointerUp&&s.onPointerUp(t,e,r.kD.POINTERUP),!i.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let n=0;if(i.singleClick?n=r.kD.POINTERTAP:i.doubleClick&&(n=r.kD.POINTERDOUBLETAP),n){let i=new r.R5(n,t,e);s.onPointerObservable.hasObservers()&&s.onPointerObservable.hasSpecificMask(n)&&s.onPointerObservable.notifyObservers(i,n)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,i=!0,a=null){let c=this._scene,_=c.getEngine();a||(a=_.getInputElement()),this._alreadyAttached&&this.detachControl(),a&&(this._alreadyAttachedTo=a),this._deviceSourceManager=new u.U(_),this._initActionManager=e=>{if(!this._meshPickProceed){let t=!c.skipPointerUpPicking&&(0!==c._registeredActions||this._checkForPicking()||c.onPointerUp)?c.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c.pointerUpPredicate,c.pointerUpFastCheck,c.cameraToUseForPointers):null;this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,i)=>{if((Date.now()-this._previousStartingPointerTime>p.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){let t=this._delayedClicks[e].evt,i=r.kD.POINTERTAP,s=new r.R5(i,t,this._currentPickResult);c.onPointerObservable.hasObservers()&&c.onPointerObservable.hasSpecificMask(i)&&c.onPointerObservable.notifyObservers(s,i),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,i,n)=>{var a,o;let l=new d;this._currentPickResult=null;let h=null,u=e.hasSpecificMask(r.kD.POINTERPICK)||t.hasSpecificMask(r.kD.POINTERPICK)||e.hasSpecificMask(r.kD.POINTERTAP)||t.hasSpecificMask(r.kD.POINTERTAP)||e.hasSpecificMask(r.kD.POINTERDOUBLETAP)||t.hasSpecificMask(r.kD.POINTERDOUBLETAP);!u&&s.O&&(h=this._initActionManager(h,l))&&(u=h.hasPickTriggers);let c=!1;if(u){let u=i.button;if(l.hasSwiped=this._isPointerSwiping(),!l.hasSwiped){let d=!p.ExclusiveDoubleClickMode;if(!d&&(d=!e.hasSpecificMask(r.kD.POINTERDOUBLETAP)&&!t.hasSpecificMask(r.kD.POINTERDOUBLETAP))&&!s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l))&&(d=!h.hasSpecificTrigger(6)),d)(Date.now()-this._previousStartingPointerTime>p.DoubleClickDelay||u!==this._previousButtonPressed)&&(l.singleClick=!0,n(l,this._currentPickResult),c=!0);else{let e={evt:i,clickInfo:l,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,u,l,n),p.DoubleClickDelay)};this._delayedClicks[u]=e}let _=e.hasSpecificMask(r.kD.POINTERDOUBLETAP)||t.hasSpecificMask(r.kD.POINTERDOUBLETAP);!_&&s.O.HasSpecificTrigger(6)&&(h=this._initActionManager(h,l))&&(_=h.hasSpecificTrigger(6)),_&&(u===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>p.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>p.DragMovementThreshold),_.isPointerLock&&_._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=h.Fz.MouseWheelX&&e.inputIndex<=h.Fz.MouseWheelZ?r.kD.POINTERWHEEL:r.kD.POINTERMOVE)||!c.cameraToUseForPointers&&!c.activeCamera)return;if(c.skipPointerMovePicking){this._processPointerMove(new n.p,e);return}c.pointerMovePredicate||(c.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||c.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0));let t=c._registeredActions>0||c.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{var t;let i;if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,p.ExclusiveDoubleClickMode){for(let i=0;ie.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0)),this._pickedDownMesh=null,i=!c.skipPointerDownPicking&&(0!==c._registeredActions||this._checkForPicking()||c.onPointerDown)?c.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,c.pointerDownPredicate,c.pointerDownFastCheck,c.cameraToUseForPointers):new n.p,this._processPointerDown(i,e))},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),c.preventDefaultOnPointerUp&&a&&(e.preventDefault(),a.focus()),this._initClickEvent(c.onPrePointerObservable,c.onPointerObservable,e,(t,i)=>{if(c.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,r.kD.POINTERUP)){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1);return}!t.hasSwiped&&(t.singleClick&&c.onPrePointerObservable.hasSpecificMask(r.kD.POINTERTAP)&&this._checkPrePointerObservable(null,e,r.kD.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&c.onPrePointerObservable.hasSpecificMask(r.kD.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,r.kD.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}if(!this._pointerCaptures[e.pointerId]){this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1);return}0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(c.cameraToUseForPointers||c.activeCamera)&&(c.pointerUpPredicate||(c.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!c.cameraToUseForPointers||(c.cameraToUseForPointers.layerMask&e.layerMask)!=0)),!this._meshPickProceed&&(s.O&&s.O.HasTriggers||this._checkForPicking()||c.onPointerUp)&&this._initActionManager(null,t),i||(i=this._currentPickResult),this._processPointerUp(i,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))}))},this._onKeyDown=e=>{let t=l.OG.KEYDOWN;if(c.onPreKeyboardObservable.hasObservers()){let i=new l.WZ(t,e);if(c.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(c.onKeyboardObservable.hasObservers()){let i=new l.NG(t,e);c.onKeyboardObservable.notifyObservers(i,t)}c.actionManager&&c.actionManager.processTrigger(14,o.V.CreateNewFromScene(c,e))},this._onKeyUp=e=>{let t=l.OG.KEYUP;if(c.onPreKeyboardObservable.hasObservers()){let i=new l.WZ(t,e);if(c.onPreKeyboardObservable.notifyObservers(i,t),i.skipOnKeyboardObservable)return}if(c.onKeyboardObservable.hasObservers()){let i=new l.NG(t,e);c.onKeyboardObservable.notifyObservers(i,t)}c.actionManager&&c.actionManager.processTrigger(15,o.V.CreateNewFromScene(c,e))},this._deviceSourceManager.onDeviceConnectedObservable.add(r=>{r.deviceType===h.Yi.Mouse?r.onInputChangedObservable.add(s=>{s.inputIndex===h.Fz.LeftClick||s.inputIndex===h.Fz.MiddleClick||s.inputIndex===h.Fz.RightClick||s.inputIndex===h.Fz.BrowserBack||s.inputIndex===h.Fz.BrowserForward?t&&1===r.getInput(s.inputIndex)?this._onPointerDown(s):e&&0===r.getInput(s.inputIndex)&&this._onPointerUp(s):i&&(s.inputIndex===h.Fz.Move?this._onPointerMove(s):(s.inputIndex===h.Fz.MouseWheelX||s.inputIndex===h.Fz.MouseWheelY||s.inputIndex===h.Fz.MouseWheelZ)&&this._onPointerMove(s))}):r.deviceType===h.Yi.Touch?r.onInputChangedObservable.add(s=>{s.inputIndex===h.Fz.LeftClick&&(t&&1===r.getInput(s.inputIndex)?(this._onPointerDown(s),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===r.getInput(s.inputIndex)&&(this._onPointerUp(s),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),i&&s.inputIndex===h.Fz.Move&&this._onPointerMove(s)}):r.deviceType===h.Yi.Keyboard&&r.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,i,r){let s;if(this._meshUnderPointerId[t]===e&&(!e||!e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;let n=this._meshUnderPointerId[t];n&&(s=n._getActionManagerForTrigger(10))&&s.processTrigger(10,o.V.CreateNew(n,r,{pointerId:t})),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,(s=e._getActionManagerForTrigger(9))&&s.processTrigger(9,o.V.CreateNew(e,r,{pointerId:t,pickResult:i}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){for(let t in this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null),this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}p.DragMovementThreshold=10,p.LongPressDelay=500,p.DoubleClickDelay=300,p.ExclusiveDoubleClickMode=!1},6972:function(e,t,i){i.d(t,{m:function(){return r}});class r{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}r.FALLOFF_DEFAULT=0,r.FALLOFF_PHYSICAL=1,r.FALLOFF_GLTF=2,r.FALLOFF_STANDARD=3,r.LIGHTMAP_DEFAULT=0,r.LIGHTMAP_SPECULAR=1,r.LIGHTMAP_SHADOWSONLY=2,r.INTENSITYMODE_AUTOMATIC=0,r.INTENSITYMODE_LUMINOUSPOWER=1,r.INTENSITYMODE_LUMINOUSINTENSITY=2,r.INTENSITYMODE_ILLUMINANCE=3,r.INTENSITYMODE_LUMINANCE=4,r.LIGHTTYPEID_POINTLIGHT=0,r.LIGHTTYPEID_DIRECTIONALLIGHT=1,r.LIGHTTYPEID_SPOTLIGHT=2,r.LIGHTTYPEID_HEMISPHERICLIGHT=3},2697:function(e,t,i){i.d(t,{Z:function(){return r}});class r{static get ForceFullSceneLoadingForIncremental(){return r._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){r._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return r._ShowLoadingScreen}static set ShowLoadingScreen(e){r._ShowLoadingScreen=e}static get loggingLevel(){return r._LoggingLevel}static set loggingLevel(e){r._LoggingLevel=e}static get CleanBoneMatrixWeights(){return r._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){r._CleanBoneMatrixWeights=e}}r._ForceFullSceneLoadingForIncremental=!1,r._ShowLoadingScreen=!0,r._CleanBoneMatrixWeights=!1,r._LoggingLevel=0},3912:function(e,t,i){i.d(t,{S:function(){return s},l:function(){return o}});var r,s,n=i(4800),a=i(7584);(r=s||(s={}))[r.Unknown=0]="Unknown",r[r.Url=1]="Url",r[r.Temp=2]="Temp",r[r.Raw=3]="Raw",r[r.Dynamic=4]="Dynamic",r[r.RenderTarget=5]="RenderTarget",r[r.MultiRenderTarget=6]="MultiRenderTarget",r[r.Cube=7]="Cube",r[r.CubeRaw=8]="CubeRaw",r[r.CubePrefiltered=9]="CubePrefiltered",r[r.Raw3D=10]="Raw3D",r[r.Raw2DArray=11]="Raw2DArray",r[r.DepthStencil=12]="DepthStencil",r[r.CubeRawRGBD=13]="CubeRawRGBD",r[r.Depth=14]="Depth";class o extends a.a{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,i=!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 n.y$,this.onErrorObservable=new n.y$,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=s.Unknown,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=o._Counter++,i||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,i=1){this._engine.updateTextureDimensions(this,e,t,i),this.width=e,this.height=t,this.depth=i,this.baseWidth=e,this.baseHeight=t,this.baseDepth=i,this._size=e*t*i}_rebuild(){var e,t;let i;if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){let e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};e.isAsync?e.proxy.then(t):t(e.proxy);return}switch(this.source){case s.Temp:break;case s.Url:i=this._engine.createTexture(null!==(e=this._originalUrl)&&void 0!==e?e: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);return;case s.Raw:(i=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))._swapAndDie(this,!1),this.isReady=!0;break;case s.Raw3D:(i=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case s.Raw2DArray:(i=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type))._swapAndDie(this,!1),this.isReady=!0;break;case s.Dynamic:(i=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode))._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case s.Cube:i=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,()=>{i._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer);return;case s.CubeRaw:(i=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,null!==(t=this._originalFormat)&&void 0!==t?t:this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression))._swapAndDie(this,!1),this.isReady=!0;break;case s.CubeRawRGBD:return;case s.CubePrefiltered:(i=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,e=>{e&&e._swapAndDie(this,!1),this.isReady=!0},null,this.format,this._extension))._sphericalPolynomial=this._sphericalPolynomial;return}}_swapAndDie(e,t=!0){var i;null===(i=this._hardwareTexture)||void 0===i||i.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);let r=this._engine.getLoadedTexturesCache(),s=r.indexOf(this);-1!==s&&r.splice(s,1),-1===(s=r.indexOf(e))&&r.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}o._Counter=0},7584:function(e,t,i){i.d(t,{a:function(){return r}});class r{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=1,t=1,i=1,r=1,s=2,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=i,this._cachedAnisotropicFilteringLevel=r,this.samplingMode=s,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}}},6962:function(e,t,i){function r(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")}function s(e,t,i){var r,s,n,a,o,l;let h=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),u=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),c=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),d=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),p=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),_=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);h&&i.push("#define CLIPPLANE"),u&&i.push("#define CLIPPLANE2"),c&&i.push("#define CLIPPLANE3"),d&&i.push("#define CLIPPLANE4"),p&&i.push("#define CLIPPLANE5"),_&&i.push("#define CLIPPLANE6")}function n(e,t,i){var r,s,n,a,o,l;let h=!1,u=!!(null!==(r=e.clipPlane)&&void 0!==r?r:t.clipPlane),c=!!(null!==(s=e.clipPlane2)&&void 0!==s?s:t.clipPlane2),d=!!(null!==(n=e.clipPlane3)&&void 0!==n?n:t.clipPlane3),p=!!(null!==(a=e.clipPlane4)&&void 0!==a?a:t.clipPlane4),_=!!(null!==(o=e.clipPlane5)&&void 0!==o?o:t.clipPlane5),f=!!(null!==(l=e.clipPlane6)&&void 0!==l?l:t.clipPlane6);return i.CLIPPLANE!==u&&(i.CLIPPLANE=u,h=!0),i.CLIPPLANE2!==c&&(i.CLIPPLANE2=c,h=!0),i.CLIPPLANE3!==d&&(i.CLIPPLANE3=d,h=!0),i.CLIPPLANE4!==p&&(i.CLIPPLANE4=p,h=!0),i.CLIPPLANE5!==_&&(i.CLIPPLANE5=_,h=!0),i.CLIPPLANE6!==f&&(i.CLIPPLANE6=f,h=!0),h}function a(e,t,i){var r,s,n,a,l,h;let u=null!==(r=t.clipPlane)&&void 0!==r?r:i.clipPlane;o(e,"vClipPlane",u),o(e,"vClipPlane2",u=null!==(s=t.clipPlane2)&&void 0!==s?s:i.clipPlane2),o(e,"vClipPlane3",u=null!==(n=t.clipPlane3)&&void 0!==n?n:i.clipPlane3),o(e,"vClipPlane4",u=null!==(a=t.clipPlane4)&&void 0!==a?a:i.clipPlane4),o(e,"vClipPlane5",u=null!==(l=t.clipPlane5)&&void 0!==l?l:i.clipPlane5),o(e,"vClipPlane6",u=null!==(h=t.clipPlane6)&&void 0!==h?h:i.clipPlane6)}function o(e,t,i){i&&e.setFloat4(t,i.normal.x,i.normal.y,i.normal.z,i.d)}i.d(t,{AN:function(){return n},an:function(){return a},lK:function(){return s},qx:function(){return r}})},9087:function(e,t,i){i.d(t,{U:function(){return a}});var r=i(9956),s=i(1760),n=i(2983);class a{constructor(){this._dirty=!0,this._tempColor=new n.HE(0,0,0,0),this._globalCurve=new n.HE(0,0,0,0),this._highlightsCurve=new n.HE(0,0,0,0),this._midtonesCurve=new n.HE(0,0,0,0),this._shadowsCurve=new n.HE(0,0,0,0),this._positiveCurve=new n.HE(0,0,0,0),this._negativeCurve=new n.HE(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,i="vCameraColorCurvePositive",r="vCameraColorCurveNeutral",s="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(i,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(r,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(s,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}static PrepareUniforms(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}_getColorGradingDataToRef(e,t,i,r,s){null!=e&&(e=a._Clamp(e,0,360),t=a._Clamp(t,-100,100),i=a._Clamp(i,-100,100),r=a._Clamp(r,-100,100),t=.5*a._ApplyColorGradingSliderNonlinear(t),r=a._ApplyColorGradingSliderNonlinear(r),t<0&&(t*=-1,e=(e+180)%360),a._FromHSBToRef(e,t,50+.25*r,s),s.scaleToRef(2,s),s.a=1+.01*i)}static _ApplyColorGradingSliderNonlinear(e){let t=Math.abs(e/=100);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100}static _FromHSBToRef(e,t,i,r){let s=a._Clamp(e,0,360),n=a._Clamp(t/100,0,1),o=a._Clamp(i/100,0,1);if(0===n)r.r=o,r.g=o,r.b=o;else{let e=Math.floor(s/=60),t=s-e,i=o*(1-n),a=o*(1-n*t),l=o*(1-n*(1-t));switch(e){case 0:r.r=o,r.g=l,r.b=i;break;case 1:r.r=a,r.g=o,r.b=i;break;case 2:r.r=i,r.g=o,r.b=l;break;case 3:r.r=i,r.g=a,r.b=o;break;case 4:r.r=l,r.g=i,r.b=o;break;default:r.r=o,r.g=i,r.b=a}}r.a=1}static _Clamp(e,t,i){return Math.min(Math.max(e,t),i)}clone(){return s.p4.Clone(()=>new a,this)}serialize(){return s.p4.Serialize(this)}static Parse(e){return s.p4.Parse(()=>new a,e,null,null)}}(0,r.gn)([(0,s.qC)()],a.prototype,"_globalHue",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_globalDensity",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_globalSaturation",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_globalExposure",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_highlightsHue",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_highlightsDensity",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_highlightsSaturation",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_highlightsExposure",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_midtonesHue",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_midtonesDensity",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_midtonesSaturation",void 0),(0,r.gn)([(0,s.qC)()],a.prototype,"_midtonesExposure",void 0),s.p4._ColorCurvesParser=a.Parse},1606:function(e,t,i){i.d(t,{q:function(){return r}});class r{static IsWrapper(e){return void 0===e.getPipelineContext}static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,i=!0){var r;this.effect=e,void 0!==t&&(this.defines=t),i&&(null===(r=this.drawContext)||void 0===r||r.reset())}dispose(){var e;null===(e=this.drawContext)||void 0===e||e.dispose()}}},1088:function(e,t,i){i.d(t,{Q:function(){return h}});var r=i(4800),s=i(7209),n=i(9626),a=i(7790),o=i(513),l=i(5550);class h{static get ShadersRepository(){return o.v.ShadersRepository}static set ShadersRepository(e){o.v.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new r.y$),this._onBindObservable}constructor(e,t,i,s=null,n,a=null,o=null,u=null,c=null,d,p="",_=l.x.GLSL){var f,m,g;if(this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new r.y$,this.onErrorObservable=new r.y$,this._onBindObservable=null,this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!1,this._wasPreviouslyUsingInstances=null,this._isDisposed=!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=p,t.attributes){if(this._engine=i,this._attributesNames=t.attributes,this._uniformsNames=t.uniformsNames.concat(t.samplers),this._samplerList=t.samplers.slice(),this.defines=t.defines,this.onError=t.onError,this.onCompiled=t.onCompiled,this._fallbacks=t.fallbacks,this._indexParameters=t.indexParameters,this._transformFeedbackVaryings=t.transformFeedbackVaryings||null,this._multiTarget=!!t.multiTarget,this._shaderLanguage=null!==(f=t.shaderLanguage)&&void 0!==f?f:l.x.GLSL,t.uniformBuffersNames){this._uniformBuffersNamesList=t.uniformBuffersNames.slice();for(let e=0;e{if(u[0]&&u[1]){h.isFragment=!0;let[e,i]=u;a.L.Process(i,h,(i,r)=>{this._fragmentSourceCodeBeforeMigration=r,this._processFinalCode&&(i=this._processFinalCode("fragment",i));let s=a.L.Finalize(e,i,h);h=null,this._useFinalCode(s.vertexCode,s.fragmentCode,n,t)},this._engine)}};this._loadShader(i,"Vertex","",e=>{a.L.Initialize(h),a.L.Process(e,h,(t,i)=>{this._rawVertexSourceCode=e,this._vertexSourceCodeBeforeMigration=i,this._processFinalCode&&(t=this._processFinalCode("vertex",t)),u[0]=t,c()},this._engine)}),this._loadShader(r,"Fragment","Pixel",e=>{this._rawFragmentSourceCode=e,u[1]=e,c()})}_useFinalCode(e,t,i,r=!1){if(i){let r=i.vertexElement||i.vertex||i.spectorName||i,s=i.fragmentElement||i.fragment||i.spectorName||i;this._vertexSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME vertex:"+r+"\n"+e,this._fragmentSourceCode=(this._shaderLanguage===l.x.WGSL?"//":"")+"#define SHADER_NAME fragment:"+s+"\n"+t}else this._vertexSourceCode=e,this._fragmentSourceCode=t;this._prepareEffect(r)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){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){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}this._isDisposed||setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let n;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){r((0,s.v)(e));return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){r(window.atob(e.substr(7)));return}let a=o.v.GetShadersStore(this._shaderLanguage);if(a[e+t+"Shader"]){r(a[e+t+"Shader"]);return}if(i&&a[e+i+"Shader"]){r(a[e+i+"Shader"]);return}n="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:o.v.GetShadersRepository(this._shaderLanguage)+e,this._engine._loadFile(n+"."+t.toLowerCase()+".fx",r)}get vertexSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getVertexShaderCode())&&void 0!==t?t:this._vertexSourceCode}get fragmentSourceCode(){var e,t;return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getFragmentShaderCode())&&void 0!==t?t:this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}_rebuildProgram(e,t,i,r){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{r&&r(t)},this.onCompiled=()=>{let e=this.getEngine().scenes;if(e)for(let t=0;tthis._rebuildProgram(e,t,i,r);this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?n._preparePipelineContext(this._pipelineContext,this._vertexSourceCodeOverride,this._fragmentSourceCodeOverride,!0,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,null,this._transformFeedbackVaryings,this._key):n._preparePipelineContext(this._pipelineContext,this._vertexSourceCode,this._fragmentSourceCode,!1,this._rawVertexSourceCode,this._rawFragmentSourceCode,a,r,this._transformFeedbackVaryings,this._key),n._executeWhenRenderingStateIsCompiled(this._pipelineContext,()=>{if(this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,i,this._attributes),i)for(let e=0;e=t&&(r=`Offending line [${t}] in ${i?"fragment":"vertex"} code: ${n[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){var i,r,s;this._compilationError=e.message;let a=this._attributesNames,o=this._fallbacks;if(n.Y.Error("Unable to compile effect:"),n.Y.Error("Uniforms: "+this._uniformsNames.map(function(e){return" "+e})),n.Y.Error("Attributes: "+a.map(function(e){return" "+e})),n.Y.Error("Defines:\n"+this.defines),h.LogShaderCodeOnCompilationError){let e=null,t=null,a=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getVertexShaderCode())&&([a,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),a&&(n.Y.Error("Vertex code:"),n.Y.Error(a))),(null===(r=this._pipelineContext)||void 0===r?void 0:r._getFragmentShaderCode())&&([a,t]=this._getShaderCodeAndErrorLine(null===(s=this._pipelineContext)||void 0===s?void 0:s._getFragmentShaderCode(),this._compilationError,!0),a&&(n.Y.Error("Fragment code:"),n.Y.Error(a))),e&&n.Y.Error(e),t&&n.Y.Error(t)}n.Y.Error("Error: "+this._compilationError);let l=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,l()),o?(this._pipelineContext=null,o.hasMoreFallbacks?(this._allFallbacksProcessed=!1,n.Y.Error("Trying next fallback."),this.defines=o.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,l(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||l())}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)}setDepthStencilTexture(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){let i=e+"Ex";if(-1===this._samplerList.indexOf(i+"0")){let r=this._samplerList.indexOf(e);for(let e=1;enew c,this)}serialize(){return s.p4.Serialize(this)}static Parse(e){let t=s.p4.Parse(()=>new c,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}}c.TONEMAPPING_STANDARD=0,c.TONEMAPPING_ACES=1,c._VIGNETTEMODE_MULTIPLY=0,c._VIGNETTEMODE_OPAQUE=1,(0,r.gn)([(0,s.N$)()],c.prototype,"colorCurves",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_colorCurvesEnabled",void 0),(0,r.gn)([(0,s.oU)("colorGradingTexture")],c.prototype,"_colorGradingTexture",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_colorGradingEnabled",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_colorGradingWithGreenDepth",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_colorGradingBGR",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_exposure",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_toneMappingEnabled",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_toneMappingType",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_contrast",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteStretch",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteCenterX",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteCenterY",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteWeight",void 0),(0,r.gn)([(0,s.XX)()],c.prototype,"vignetteColor",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"vignetteCameraFov",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_vignetteBlendMode",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_vignetteEnabled",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_ditheringEnabled",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_ditheringIntensity",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_skipFinalColorClamp",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_applyByPostProcess",void 0),(0,r.gn)([(0,s.qC)()],c.prototype,"_isEnabled",void 0),s.p4._ImageProcessingConfigurationParser=c.Parse},2515:function(e,t,i){i.d(t,{F:function(){return g}});var r=i(9956),s=i(1760),n=i(5132),a=i(4800),o=i(6030),l=i(1091),h=i(9691),u=i(9626),c=i(1564),d=i(3385),p=i(1606);class _{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=519,this.funcRef=1,this.funcMask=255,this.opStencilFail=7680,this.opDepthFail=7680,this.opStencilDepthPass=7681}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){s.p4.Clone(()=>e,this)}serialize(){return s.p4.Serialize(this)}parse(e,t,i){s.p4.Parse(()=>this,e,t,i)}}(0,r.gn)([(0,s.qC)()],_.prototype,"func",null),(0,r.gn)([(0,s.qC)()],_.prototype,"funcRef",null),(0,r.gn)([(0,s.qC)()],_.prototype,"funcMask",null),(0,r.gn)([(0,s.qC)()],_.prototype,"opStencilFail",null),(0,r.gn)([(0,s.qC)()],_.prototype,"opDepthFail",null),(0,r.gn)([(0,s.qC)()],_.prototype,"opStencilDepthPass",null),(0,r.gn)([(0,s.qC)()],_.prototype,"mask",null),(0,r.gn)([(0,s.qC)()],_.prototype,"enabled",null);var f=i(6540),m=i(4885);class g{get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;let t=this._alpha;this._alpha=e,(1===t||1===e)&&this.markAsDirty(g.MiscDirtyFlag+g.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty(g.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty(g.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 a.y$),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 a.y$),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new a.y$),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty(g.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(g.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case g.WireFrameFillMode:case g.LineListDrawMode:case g.LineLoopDrawMode:case g.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?g.WireFrameFillMode:g.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case g.PointFillMode:case g.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?g.PointFillMode:g.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty(g.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){let t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&u.Y.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,i){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!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.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new a.y$,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=2,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 _,this._useUBO=!1,this._fillMode=g.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=()=>void 0,this._callbackPluginEventIsReadyForSubMesh=()=>void 0,this._callbackPluginEventPrepareDefines=()=>void 0,this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>void 0,this._callbackPluginEventHardBindForSubMesh=()=>void 0,this._callbackPluginEventBindForSubMesh=()=>void 0,this._callbackPluginEventHasRenderTargetTextures=()=>void 0,this._callbackPluginEventFillRenderTargetTextures=()=>void 0,this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;let r=t||o.l.LastCreatedScene;if(!r)return;this._scene=r,this._dirtyCallbacks={},this._dirtyCallbacks[1]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[2]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[4]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[8]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[16]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[32]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[63]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||n.w1.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new p.q(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._scene.useRightHandedSystem?this.sideOrientation=g.ClockWiseSideOrientation:this.sideOrientation=g.CounterClockWiseSideOrientation,this._uniformBuffer=new h.M(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,i||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),g.OnEventObservable.notifyObservers(this,m.S.Created)}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,i){let r=t.materialDefines;return!!r&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===g.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===g.MATERIAL_OPAQUE||this._transparencyMode===g.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){for(let t of this.getScene().meshes)if(t.subMeshes)for(let i of t.subMeshes)i.getMaterial()===this&&i.effect&&(i.effect._wasPreviouslyReady=!1,i.effect._wasPreviouslyUsingInstances=null,i.effect._forceRebindOnNextCall=e);e&&this.markAsDirty(g.AllDirtyFlag)}_preBind(e,t=null){let i=this._scene.getEngine(),r=(null==t?this.sideOrientation:t)===g.ClockWiseSideOrientation;return i.enableEffect(e||this._getDrawWrapper()),i.setState(this.backFaceCulling,this.zOffset,!1,r,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),r}bind(e,t){}buildUniformLayout(){let e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(m.S.PrepareUniformBuffer,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,i){let r=i.effect;r&&(this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),r._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){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,d.G.BindSceneUniformBuffer(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),e?this._scene._cachedVisibility=e.visibility:this._scene._cachedVisibility=1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){let e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){let e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){let e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction&&this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState),this.disableDepthWrite&&this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState),this.disableColorWrite&&this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(m.S.GetAnimatables,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(m.S.GetActiveTextures,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(m.S.HasTexture,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){let i={};if(this._serializePlugins(i),g._parsePlugins(i,e,this._scene,t),this.pluginManager)for(let t of this.pluginManager._plugins){let i=e.pluginManager.getPlugin(t.name);i&&t.copyTo(i)}}getBindedMeshes(){if(!this.meshMap)return this._scene.meshes.filter(e=>e.material===this);{let e=[];for(let t in this.meshMap){let i=this.meshMap[t];i&&e.push(i)}return e}}forceCompilation(e,t,i,r){let s=Object.assign({clipPlane:!1,useInstances:!1},i),n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;let o=()=>{if(!this._scene||!this._scene.getEngine())return;let i=n.clipPlane;if(s.clipPlane&&(n.clipPlane=new c.J(0,0,0,1)),this._storeEffectOnSubMeshes){let i=!0,n=null;if(e.subMeshes){let t=new l.P(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,s.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(i=!1,setTimeout(o,16)))}i&&(this.allowShaderHotSwapping=a,n&&r&&r(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);s.clipPlane&&(n.clipPlane=i)};o()}forceCompilationAsync(e,t){return new Promise((i,r)=>{this.forceCompilation(e,()=>{i()},t,e=>{r(e)})})}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||(g._DirtyCallbackArray.length=0,e&g.TextureDirtyFlag&&g._DirtyCallbackArray.push(g._TextureDirtyCallBack),e&g.LightDirtyFlag&&g._DirtyCallbackArray.push(g._LightsDirtyCallBack),e&g.FresnelDirtyFlag&&g._DirtyCallbackArray.push(g._FresnelDirtyCallBack),e&g.AttributesDirtyFlag&&g._DirtyCallbackArray.push(g._AttributeDirtyCallBack),e&g.MiscDirtyFlag&&g._DirtyCallbackArray.push(g._MiscDirtyCallBack),e&g.PrePassDirtyFlag&&g._DirtyCallbackArray.push(g._PrePassDirtyCallBack),g._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty(g._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){for(let e of this.getScene().meshes)if(e.subMeshes)for(let t of e.subMeshes)t.getMaterial()===this&&t.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(!this.getScene().blockMaterialDirtyMechanism&&!this._blockDirtyMechanism){for(let t of this.getScene().meshes)if(t.subMeshes){for(let i of t.subMeshes)if(i.getMaterial(!1)===this)for(let t of i._drawWrappers)t&&t.defines&&t.defines.markAllAsDirty&&this._materialContext===t.materialContext&&e(t.defines)}}}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;let e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty(g._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty(g._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty(g._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty(g._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty(g._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty(g._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty(g._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty(g._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty(g._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty(g._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(this._scene.performancePriority!==f.a.BackwardCompatible){this.checkReadyOnlyOnce=!0;let e=this._scene.onScenePerformancePriorityChangedObservable.addOnce(()=>{this.checkReadyOnlyOnce=!1});this.onDisposeObservable.add(()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)})}}setPrePassRenderer(e){return!1}dispose(e,t,i){let r=this.getScene();if(r.stopAnimation(this),r.freeProcessedMaterials(),r.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(m.S.Disposed,this._eventInfo),this._parentContainer){let e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==i){if(this.meshMap)for(let t in this.meshMap){let i=this.meshMap[t];i&&(i.material=null,this.releaseVertexArrayObject(i,e))}else for(let t of r.meshes)t.material!==this||t.sourceMesh||(t.material=null,this.releaseVertexArrayObject(t,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){let i=e.geometry;if(i){if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(let r of e.subMeshes)i._releaseVertexArrayObject(r.effect),t&&r.effect&&r.effect.dispose()}else i._releaseVertexArrayObject(this._drawWrapper.effect)}}serialize(){let e=s.p4.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(let t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,i){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return u.Y.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";let r=n.w1.Instantiate(e.customType).Parse(e,t,i);return r._loadedUniqueId=e.uniqueId,r}static _parsePlugins(e,t,i,r){var s;if(e.plugins)for(let a in e.plugins){let o=e.plugins[a],l=null===(s=t.pluginManager)||void 0===s?void 0:s.getPlugin(o.name);if(!l){let e=n.w1.Instantiate("BABYLON."+a);e&&(l=new e(t))}null==l||l.parse(o,i,r)}}}g.TriangleFillMode=0,g.WireFrameFillMode=1,g.PointFillMode=2,g.PointListDrawMode=3,g.LineListDrawMode=4,g.LineLoopDrawMode=5,g.LineStripDrawMode=6,g.TriangleStripDrawMode=7,g.TriangleFanDrawMode=8,g.ClockWiseSideOrientation=0,g.CounterClockWiseSideOrientation=1,g.TextureDirtyFlag=1,g.LightDirtyFlag=2,g.FresnelDirtyFlag=4,g.AttributesDirtyFlag=8,g.MiscDirtyFlag=16,g.PrePassDirtyFlag=32,g.AllDirtyFlag=63,g.MATERIAL_OPAQUE=0,g.MATERIAL_ALPHATEST=1,g.MATERIAL_ALPHABLEND=2,g.MATERIAL_ALPHATESTANDBLEND=3,g.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,g.MATERIAL_NORMALBLENDMETHOD_RNM=1,g.OnEventObservable=new a.y$,g._AllDirtyCallBack=e=>e.markAllAsDirty(),g._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),g._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),g._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),g._MiscDirtyCallBack=e=>e.markAsMiscDirty(),g._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),g._LightsDirtyCallBack=e=>e.markAsLightDirty(),g._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),g._FresnelAndMiscDirtyCallBack=e=>{g._FresnelDirtyCallBack(e),g._MiscDirtyCallBack(e)},g._TextureAndMiscDirtyCallBack=e=>{g._TextureDirtyCallBack(e),g._MiscDirtyCallBack(e)},g._DirtyCallbackArray=[],g._RunDirtyCallBacks=e=>{for(let t of g._DirtyCallbackArray)t(e)},(0,r.gn)([(0,s.qC)()],g.prototype,"id",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"uniqueId",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"name",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"metadata",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"checkReadyOnEveryCall",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"checkReadyOnlyOnce",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"state",void 0),(0,r.gn)([(0,s.qC)("alpha")],g.prototype,"_alpha",void 0),(0,r.gn)([(0,s.qC)("backFaceCulling")],g.prototype,"_backFaceCulling",void 0),(0,r.gn)([(0,s.qC)("cullBackFaces")],g.prototype,"_cullBackFaces",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"sideOrientation",void 0),(0,r.gn)([(0,s.qC)("alphaMode")],g.prototype,"_alphaMode",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"_needDepthPrePass",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"disableDepthWrite",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"disableColorWrite",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"forceDepthWrite",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"depthFunction",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"separateCullingPass",void 0),(0,r.gn)([(0,s.qC)("fogEnabled")],g.prototype,"_fogEnabled",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"pointSize",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"zOffset",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"zOffsetUnits",void 0),(0,r.gn)([(0,s.qC)()],g.prototype,"pointsCloud",null),(0,r.gn)([(0,s.qC)()],g.prototype,"fillMode",null),(0,r.gn)([(0,s.qC)()],g.prototype,"useLogarithmicDepth",null),(0,r.gn)([(0,s.qC)()],g.prototype,"transparencyMode",null)},5377:function(e,t,i){i.d(t,{H:function(){return r}});class r{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(let 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(){for(let e of(this._keys.length=0,Object.keys(this)))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(let 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;tthis._setDefaultValue(e))}_setDefaultValue(e){var t,i,r,s,n;let a=null!==(r=null===(i=null===(t=this._externalProperties)||void 0===t?void 0:t[e])||void 0===i?void 0:i.type)&&void 0!==r?r:typeof this[e],o=null===(n=null===(s=this._externalProperties)||void 0===s?void 0:s[e])||void 0===n?void 0:n.default;switch(a){case"number":this[e]=null!=o?o:0;break;case"string":this[e]=null!=o?o:"";break;default:this[e]=null!=o&&o}}toString(){let e="";for(let t=0;t0,t.NUM_MORPH_INFLUENCERS=i.numInfluencers,t.MORPHTARGETS_TEXTURE=i.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}static PrepareDefinesForBakedVertexAnimation(e,t){let i=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!!i&&!!i.isEnabled}static PrepareDefinesForAttributes(e,t,i,r,s=!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(o.o.NormalKind),t._needNormals&&e.isVerticesDataPresent(o.o.TangentKind)&&(t.TANGENT=!0);for(let i=1;i<=6;++i)t["UV"+i]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===i?"":i}`);if(i){let i=e.useVertexColors&&e.isVerticesDataPresent(o.o.ColorKind);t.VERTEXCOLOR=i,t.VERTEXALPHA=e.hasVertexAlpha&&i&&n}return e.isVerticesDataPresent(o.o.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),r&&this.PrepareDefinesForBones(e,t),s&&this.PrepareDefinesForMorphTargets(e,t),a&&this.PrepareDefinesForBakedVertexAnimation(e,t),!0}static PrepareDefinesForMultiview(e,t){if(e.activeCamera){let i=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=i&&t.markAsUnprocessed()}}static PrepareDefinesForOIT(e,t,i){let r=t.ORDER_INDEPENDENT_TRANSPARENCY,s=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&i,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,(r!==t.ORDER_INDEPENDENT_TRANSPARENCY||s!==t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS)&&t.markAsUnprocessed()}static PrepareDefinesForPrePass(e,t,i){let r=t.PREPASS;if(!t._arePrePassDirty)return;let s=[{type:1,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:2,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:3,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:0,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:7,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:5,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:6,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&i){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let i=0;i0&&(a.shadowEnabled=!0,t.prepareDefines(s,r))}}i.lightmapMode!=l.m.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,s["LIGHTMAPEXCLUDED"+r]=!0,s["LIGHTMAPNOSPECULAR"+r]=i.lightmapMode==l.m.LIGHTMAP_SHADOWSONLY):(s["LIGHTMAPEXCLUDED"+r]=!1,s["LIGHTMAPNOSPECULAR"+r]=!1)}static PrepareDefinesForLights(e,t,i,r,s=4,n=!1){if(!i._areLightsDirty)return i._needNormals;let a=0,o={needNormals:i._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n){for(let n of t.lightSources)if(this.PrepareDefinesForLight(e,t,n,a,i,r,o),++a===s)break}i.SPECULARTERM=o.specularEnabled,i.SHADOWS=o.shadowEnabled;for(let e=a;e0&&(s=r+n,t.addFallback(s,"LIGHT"+n)),!e.SHADOWS&&(e["SHADOW"+n]&&t.addFallback(r,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(r,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(r,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(r,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(r,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(r,"SHADOWCLOSEESM"+n));return s++}static PrepareAttributesForMorphTargetsInfluencers(e,t,i){this._TmpMorphInfluencers.NUM_MORPH_INFLUENCERS=i,this.PrepareAttributesForMorphTargets(e,t,this._TmpMorphInfluencers)}static PrepareAttributesForMorphTargets(e,t,i){let s=i.NUM_MORPH_INFLUENCERS;if(s>0&&a.l.LastCreatedEngine){let n=a.l.LastCreatedEngine.getCaps().maxVertexAttribs,l=t.morphTargetManager;if(null==l?void 0:l.isUsingTextureForTargets)return;let h=l&&l.supportsNormals&&i.NORMAL,u=l&&l.supportsTangents&&i.TANGENT,c=l&&l.supportsUVs&&i.UV1;for(let i=0;in&&r.Y.Error("Cannot add more vertex attributes for mesh "+t.name)}}static PrepareAttributesForBakedVertexAnimation(e,t,i){i.BAKED_VERTEX_ANIMATION_TEXTURE&&i.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}static PrepareAttributesForBones(e,t,i,r){i.NUM_BONE_INFLUENCERS>0&&(r.addCPUSkinningFallback(0,t),e.push(o.o.MatricesIndicesKind),e.push(o.o.MatricesWeightsKind),i.NUM_BONE_INFLUENCERS>4&&(e.push(o.o.MatricesIndicesExtraKind),e.push(o.o.MatricesWeightsExtraKind)))}static PrepareAttributesForInstances(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&this.PushAttributesForInstances(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(o.o.ColorInstanceKind)}static PushAttributesForInstances(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"))}static BindLightProperties(e,t,i){e.transferToEffect(t,i+"")}static BindLight(e,t,i,r,s,n=!0){e._bindLight(t,i,r,s,n)}static BindLights(e,t,i,r,s=4){let n=Math.min(t.lightSources.length,s);for(let s=0;s-1){let i=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",i),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{let s=r.getTransformMatrices(e);s&&(t.setMatrices("mBones",s),i&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(2)&&(i.previousBones[e.uniqueId]||(i.previousBones[e.uniqueId]=s.slice()),t.setMatrices("mPreviousBones",i.previousBones[e.uniqueId]),c._CopyBonesTransformationMatrices(s,i.previousBones[e.uniqueId])))}}}static _CopyBonesTransformationMatrices(e,t){return t.set(e),t}static BindMorphTargetParameters(e,t){let i=e.morphTargetManager;e&&i&&t.setFloatArray("morphTargetInfluences",i.influences)}static BindLogDepth(e,t,i){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){let e=i.activeCamera;e.mode===s.V.ORTHOGRAPHIC_CAMERA&&r.Y.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}}c._TmpMorphInfluencers={NUM_MORPH_INFLUENCERS:0},c._TempFogColor=h.Wo.Black()},4885:function(e,t,i){var r,s;i.d(t,{S:function(){return r}}),(s=r||(r={}))[s.Created=1]="Created",s[s.Disposed=2]="Disposed",s[s.GetDefineNames=4]="GetDefineNames",s[s.PrepareUniformBuffer=8]="PrepareUniformBuffer",s[s.IsReadyForSubMesh=16]="IsReadyForSubMesh",s[s.PrepareDefines=32]="PrepareDefines",s[s.BindForSubMesh=64]="BindForSubMesh",s[s.PrepareEffect=128]="PrepareEffect",s[s.GetAnimatables=256]="GetAnimatables",s[s.GetActiveTextures=512]="GetActiveTextures",s[s.HasTexture=1024]="HasTexture",s[s.FillRenderTargetTextures=2048]="FillRenderTargetTextures",s[s.HasRenderTargetTextures=4096]="HasRenderTargetTextures",s[s.HardBindForSubMesh=8192]="HardBindForSubMesh"},5461:function(e,t,i){i.d(t,{G:function(){return a}});var r=i(2515),s=i(1803),n=i(3048);class a extends r.F{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){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._markAllSubMeshesAsTexturesDirty(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._markAllSubMeshesAsTexturesDirty(),s}}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){var t;if(super.hasTexture(e))return!0;for(let i=0;i=0&&r.multiMaterials.splice(s,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){let i=new a(e.name,t);return i.id=e.id,i._loadedUniqueId=e.uniqueId,s.$&&s.$.AddTagsTo(i,e.tags),e.materialsUniqueIds?i._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach(e=>i.subMaterials.push(t.getLastMaterialById(e))),i}}(0,n.H)("BABYLON.MultiMaterial",a)},5550:function(e,t,i){var r,s;i.d(t,{x:function(){return r}}),(s=r||(r={}))[s.GLSL=0]="GLSL",s[s.WGSL=1]="WGSL"},9691:function(e,t,i){i.d(t,{M:function(){return n}});var r=i(9626),s=i(5132);i(68);class n{constructor(e,t,i,r,s=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||s,this._dynamic=i,this._name=null!=r?r:"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){let e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;let i=this._uniformLocationPointer-e;for(let e=0;e0){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:i},16==t)t*=i;else{let e=4-t;t=t*i+e*i}r=[];for(let e=0;e1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1])){this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame;return}this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(n._UpdatedUbosInFrame[this._name]||(n._UpdatedUbosInFrame[this._name]=0),n._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}}_createNewBuffer(){this._bufferIndex+10?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,i){this._checkNewFrame();let s=this._uniformLocations[e];if(void 0===s){if(this._buffer){r.Y.Error("Cannot add an uniform after UBO has been created.");return}this.addUniform(e,i),s=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e=0&&n<=1?(o=s,l=a):n>=1&&n<=2?(o=a,l=s):n>=2&&n<=3?(l=s,h=a):n>=3&&n<=4?(l=a,h=s):n>=4&&n<=5?(o=a,h=s):n>=5&&n<=6&&(o=s,h=a);let u=i-s;r.set(o+u,l+u,h+u)}static FromHSV(e,t,i){let r=new c(0,0,0);return c.HSVtoRGBToRef(e,t,i,r),r}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new c(0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16);return c.FromInts(t,i,r)}static FromArray(e,t=0){return new c(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2]}static FromInts(e,t,i){return new c(e/255,t/255,i/255)}static Lerp(e,t,i){let r=new c(0,0,0);return c.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n;return new c(e.r*o+i.r*l+t.r*h+r.r*u,e.g*o+i.g*l+t.g*h+r.g*u,e.b*o+i.b*l+t.b*h+r.b*u)}static Hermite1stDerivative(e,t,i,r,s){let n=c.Black();return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b}static Red(){return new c(1,0,0)}static Green(){return new c(0,1,0)}static Blue(){return new c(0,0,1)}static Black(){return new c(0,0,0)}static get BlackReadOnly(){return c._BlackReadOnly}static White(){return new c(1,1,1)}static Purple(){return new c(.5,0,.5)}static Magenta(){return new c(1,0,1)}static Yellow(){return new c(1,1,0)}static Gray(){return new c(.5,.5,.5)}static Teal(){return new c(0,1,1)}static Random(){return new c(Math.random(),Math.random(),Math.random())}}c._BlackReadOnly=c.Black();class d{constructor(e=0,t=0,i=0,r=1){this.r=e,this.g=t,this.b=i,this.a=r}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}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 d.FromArrayToRef(e,t,this),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 d(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}subtract(e){return new d(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,this}scale(e){return new d(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,this}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,this}clampToRef(e=0,t=1,i){return i.r=r.R.Clamp(this.r,e,t),i.g=r.R.Clamp(this.g,e,t),i.b=r.R.Clamp(this.b,e,t),i.a=r.R.Clamp(this.a,e,t),this}multiply(e){return new d(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}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 397*(e=397*(e=397*e^(255*this.g|0))^(255*this.b|0))^(255*this.a|0)}clone(){return new d(this.r,this.g,this.b,this.a)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,i,r){return this.r=e,this.g=t,this.b=i,this.a=r,this}set(e,t,i,r){return this.copyFromFloats(e,t,i,r)}toHexString(e=!1){let t=Math.round(255*this.r),i=Math.round(255*this.g),s=Math.round(255*this.b);if(e)return"#"+r.R.ToHex(t)+r.R.ToHex(i)+r.R.ToHex(s);let n=Math.round(255*this.a);return"#"+r.R.ToHex(t)+r.R.ToHex(i)+r.R.ToHex(s)+r.R.ToHex(n)}toLinearSpace(e=!1){let t=new d;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=l(this.r),e.g=l(this.g),e.b=l(this.b)):(e.r=o(this.r),e.g=o(this.g),e.b=o(this.b)),e.a=this.a,this}toGammaSpace(e=!1){let t=new d;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=u(this.r),e.g=u(this.g),e.b=u(this.b)):(e.r=h(this.r),e.g=h(this.g),e.b=h(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new d(0,0,0,0);let t=parseInt(e.substring(1,3),16),i=parseInt(e.substring(3,5),16),r=parseInt(e.substring(5,7),16),s=9===e.length?parseInt(e.substring(7,9),16):255;return d.FromInts(t,i,r,s)}static Lerp(e,t,i){let r=new d(0,0,0,0);return d.LerpToRef(e,t,i,r),r}static LerpToRef(e,t,i,r){r.r=e.r+(t.r-e.r)*i,r.g=e.g+(t.g-e.g)*i,r.b=e.b+(t.b-e.b)*i,r.a=e.a+(t.a-e.a)*i}static Hermite(e,t,i,r,s){let n=s*s,a=s*n,o=2*a-3*n+1,l=-2*a+3*n,h=a-2*n+s,u=a-n,c=e.r*o+i.r*l+t.r*h+r.r*u;return new d(c,e.g*o+i.g*l+t.g*h+r.g*u,e.b*o+i.b*l+t.b*h+r.b*u,e.a*o+i.a*l+t.a*h+r.a*u)}static Hermite1stDerivative(e,t,i,r,s){let n=new d;return this.Hermite1stDerivativeToRef(e,t,i,r,s,n),n}static Hermite1stDerivativeToRef(e,t,i,r,s,n){let a=s*s;n.r=(a-s)*6*e.r+(3*a-4*s+1)*t.r+(-a+s)*6*i.r+(3*a-2*s)*r.r,n.g=(a-s)*6*e.g+(3*a-4*s+1)*t.g+(-a+s)*6*i.g+(3*a-2*s)*r.g,n.b=(a-s)*6*e.b+(3*a-4*s+1)*t.b+(-a+s)*6*i.b+(3*a-2*s)*r.b,n.a=(a-s)*6*e.a+(3*a-4*s+1)*t.a+(-a+s)*6*i.a+(3*a-2*s)*r.a}static FromColor3(e,t=1){return new d(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new d(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,i){i.r=e[t],i.g=e[t+1],i.b=e[t+2],i.a=e[t+3]}static FromInts(e,t,i,r){return new d(e/255,t/255,i/255,r/255)}static CheckColors4(e,t){if(e.length===3*t){let t=[];for(let i=0;inew d(0,0,0,0)),(0,a.H)("BABYLON.Color3",c),(0,a.H)("BABYLON.Color4",d)},9806:function(e,t,i){i.d(t,{Nn:function(){return s},Q_:function(){return n},kn:function(){return a},zp:function(){return r}});let r=1/2.2,s=2.2,n=(1+Math.sqrt(5))/2,a=.001},2975:function(e,t,i){i.d(t,{i:function(){return s}});var r=i(1564);class s{static GetPlanes(e){let t=[];for(let e=0;e<6;e++)t.push(new r.J(0,0,0,0));return s.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[2],t.normal.y=i[7]+i[6],t.normal.z=i[11]+i[10],t.d=i[15]+i[14],t.normalize()}static GetFarPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[2],t.normal.y=i[7]-i[6],t.normal.z=i[11]-i[10],t.d=i[15]-i[14],t.normalize()}static GetLeftPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[0],t.normal.y=i[7]+i[4],t.normal.z=i[11]+i[8],t.d=i[15]+i[12],t.normalize()}static GetRightPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[0],t.normal.y=i[7]-i[4],t.normal.z=i[11]-i[8],t.d=i[15]-i[12],t.normalize()}static GetTopPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]-i[1],t.normal.y=i[7]-i[5],t.normal.z=i[11]-i[9],t.d=i[15]-i[13],t.normalize()}static GetBottomPlaneToRef(e,t){let i=e.m;t.normal.x=i[3]+i[1],t.normal.y=i[7]+i[5],t.normal.z=i[11]+i[9],t.d=i[15]+i[13],t.normalize()}static GetPlanesToRef(e,t){s.GetNearPlaneToRef(e,t[0]),s.GetFarPlaneToRef(e,t[1]),s.GetLeftPlaneToRef(e,t[2]),s.GetRightPlaneToRef(e,t[3]),s.GetTopPlaneToRef(e,t[4]),s.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let i=0;i<6;i++)if(0>t[i].dotCoordinate(e))return!1;return!0}}},7383:function(e,t,i){i.d(t,{k:function(){return l},y:function(){return o}});var r=i(9956),s=i(78),n=i(1760);class a{static extractMinAndMaxIndexed(e,t,i,r,s,n){for(let a=i;a!Array.isArray(e)&&!Array.isArray(t))],a,"extractMinAndMaxIndexed",null),(0,r.gn)([n.G6.filter((...[e])=>!Array.isArray(e))],a,"extractMinAndMax",null)},1564:function(e,t,i){i.d(t,{J:function(){return s}});var r=i(78);class s{constructor(e,t,i,s){this.normal=new r.P(e,t,i),this.d=s}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new s(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){return 397*this.normal.getHashCode()^(0|this.d)}normalize(){let e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),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){let t=s._TmpMatrix;e.invertToRef(t);let i=t.m,r=this.normal.x,n=this.normal.y,a=this.normal.z,o=this.d,l=r*i[0]+n*i[1]+a*i[2]+o*i[3];return new s(l,r*i[4]+n*i[5]+a*i[6]+o*i[7],r*i[8]+n*i[9]+a*i[10]+o*i[11],r*i[12]+n*i[13]+a*i[14]+o*i[15])}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,i){let r;let s=t.x-e.x,n=t.y-e.y,a=t.z-e.z,o=i.x-e.x,l=i.y-e.y,h=i.z-e.z,u=n*h-a*l,c=a*o-s*h,d=s*l-n*o,p=Math.sqrt(u*u+c*c+d*d);return r=0!==p?1/p:0,this.normal.x=u*r,this.normal.y=c*r,this.normal.z=d*r,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return r.P.Dot(this.normal,e)<=t}signedDistanceTo(e){return r.P.Dot(e,this.normal)+this.d}static FromArray(e){return new s(e[0],e[1],e[2],e[3])}static FromPoints(e,t,i){let r=new s(0,0,0,0);return r.copyFromPoints(e,t,i),r}static FromPositionAndNormal(e,t){let i=new s(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,i)}static FromPositionAndNormalToRef(e,t,i){return i.normal.copyFrom(t),i.normal.normalize(),i.d=-e.dot(i.normal),i}static SignedDistanceToPlaneFromPositionAndNormal(e,t,i){let s=-(t.x*e.x+t.y*e.y+t.z*e.z);return r.P.Dot(i,t)+s}}s._TmpMatrix=r.y3.Identity()},5762:function(e,t,i){i.d(t,{R:function(){return r}});class r{static WithinEpsilon(e,t,i=1401298e-51){return Math.abs(e-t)<=i}static ToHex(e){let t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}static Sign(e){return 0==(e=+e)||isNaN(e)?e:e>0?1:-1}static Clamp(e,t=0,i=1){return Math.min(i,Math.max(t,e))}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,i){return(e-t)/(i-t)}static Denormalize(e,t,i){return e*(i-t)+t}static DeltaAngle(e,t){let i=r.Repeat(t-e,360);return i>180&&(i-=360),i}static PingPong(e,t){let i=r.Repeat(e,2*t);return t-Math.abs(i-t)}static SmoothStep(e,t,i){let s=r.Clamp(i);return t*(s=-2*s*s*s+3*s*s)+e*(1-s)}static MoveTowards(e,t,i){return Math.abs(t-e)<=i?t:e+r.Sign(t-e)*i}static MoveTowardsAngle(e,t,i){let s=r.DeltaAngle(e,t),n=0;return-i180&&(s-=360),e+s*r.Clamp(i)}static InverseLerp(e,t,i){return e!=t?r.Clamp((i-e)/(t-e)):0}static Hermite(e,t,i,r,s){let n=s*s,a=s*n;return e*(2*a-3*n+1)+i*(-2*a+3*n)+t*(a-2*n+s)+r*(a-n)}static Hermite1stDerivative(e,t,i,r,s){let n=s*s;return(n-s)*6*e+(3*n-4*s+1)*t+(-n+s)*6*i+(3*n-2*s)*r}static RandomRange(e,t){return e===t?e:Math.random()*(t-e)+e}static RangeToPercent(e,t,i){return(e-t)/(i-t)}static PercentToRange(e,t,i){return(i-t)*e+t}static NormalizeRadians(e){return e-=r.TwoPi*Math.floor((e+Math.PI)/r.TwoPi)}static HCF(e,t){let i=e%t;return 0===i?t:r.HCF(t,i)}}r.TwoPi=2*Math.PI},6329:function(e,t,i){i.d(t,{l:function(){return r}});class r{constructor(e,t,i,r){this.x=e,this.y=t,this.width=i,this.height=r}toGlobal(e,t){return new r(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,i){return i.x=this.x*e,i.y=this.y*t,i.width=this.width*e,i.height=this.height*t,this}clone(){return new r(this.x,this.y,this.width,this.height)}}},998:function(e,t,i){i.d(t,{M:function(){return s}});var r=i(9185);class s extends r.h{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}},7042:function(e,t,i){i.d(t,{x:function(){return E}});var r=i(4800),s=i(6540),n=i(78),a=i(8906),o=i(1295),l=i(2696),h=i(8061),u=i(2248),c=i(5681),d=i(9691),p=i(5790),_=i(6131),f=i(7383),m=i(2983),g=i(9806),v=i(524),x=i(3048);class T{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=n.P.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class S{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new T,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 p.a,this._enableDistantPicking=!1,this._rawBoundingInfo=null}}class E extends h.Y{static get BILLBOARDMODE_NONE(){return h.Y.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return h.Y.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return h.Y.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return h.Y.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return h.Y.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return h.Y.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;let t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty(e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()})}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._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){var t;return null===(t=this._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[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}get _positions(){return null}set skeleton(e){let 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 S,this._waitingMaterialId=null,this.cullingStrategy=E.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new r.y$,this.onCollisionPositionChangeObservable=new r.y$,this.onMaterialChangedObservable=new r.y$,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=m.Wo.Red(),this.outlineWidth=.02,this.overlayColor=m.Wo.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 n.P(.5,1,.5),this.ellipsoidOffset=new n.P(0,0,0),this.edgesWidth=1,this.edgesColor=new m.HE(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=[],this._unIndexed=!1,this._lightSources=[],this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new r.y$,this._onCollisionPositionChange=(e,t,i=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>a.D.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),i&&this.onCollideObservable.notifyObservers(i),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new d.M(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case s.a.Aggressive:this.doNotSyncBoundingInfo=!0;case s.a.Intermediate:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){let 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);let i=this._internalAbstractMeshDataInfo._skeleton;return i&&(t+=", skeleton: "+i.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode]+", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==h.Y.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){return this.actionManager&&(t||this.actionManager.isRecursive)&&(!e||this.actionManager.hasSpecificTrigger(e))?this.actionManager: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(let e of this.subMeshes)e._rebuild()}_resyncLightSources(){for(let e of(this._lightSources.length=0,this.getScene().lights))e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){let t=e.isEnabled()&&e.canAffectMesh(this),i=this._lightSources.indexOf(e),r=!1;if(-1===i){if(!t)return;this._lightSources.push(e)}else{if(t)return;r=!0,this._lightSources.splice(i,1)}this._markSubMeshesAsLightDirty(r)}_unBindEffect(){for(let e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){let i=this._lightSources.indexOf(e);-1!==i&&(this._lightSources.splice(i,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(let t of this.subMeshes)for(let i=0;it.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(let 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,i,r){return this}updateVerticesData(e,t,i,r){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(){var e;return null!==(e=this.rawBoundingInfo)&&void 0!==e?e:this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,i){return this._boundingInfo=new c.j(e,t,i),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,i){return super.normalizeToUnitCube(e,t,i)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(o.o.MatricesIndicesKind)&&this.isVerticesDataPresent(o.o.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===h.Y.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,i){return this.position.addInPlace(this.calcMovePOV(e,t,i)),this}calcMovePOV(e,t,i){let r=new n.y3;(this.rotationQuaternion?this.rotationQuaternion:n._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(r);let s=n.P.Zero(),a=this.definedFacingForward?-1:1;return n.P.TransformCoordinatesFromFloatsToRef(e*a,t,i*a,r,s),s}rotatePOV(e,t,i){return this.rotation.addInPlace(this.calcRotatePOV(e,t,i)),this}calcRotatePOV(e,t,i){let r=this.definedFacingForward?1:-1;return new n.P(e*r,t,i*r)}refreshBoundingInfo(e=!1,t=!1){return this._boundingInfo&&this._boundingInfo.isLocked||this._refreshBoundingInfo(this._getPositionData(e,t),null),this}_refreshBoundingInfo(e,t){if(e){let i=(0,f.k)(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(i.minimum,i.maximum):this._boundingInfo=new c.j(i.minimum,i.maximum)}if(this.subMeshes)for(let t=0;t4,a=s?this.getVerticesData(o.o.MatricesIndicesExtraKind):null,l=s?this.getVerticesData(o.o.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this),u=n.jp.Vector3[0],c=n.jp.Matrix[0],d=n.jp.Matrix[1],p=0;for(let _=0;_0&&(n.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*e[p+f]),m,d),c.addToSelf(d));if(s)for(f=0;f<4;f++)(m=l[p+f])>0&&(n.y3.FromFloat32ArrayToRefScaled(h,Math.floor(16*a[p+f]),m,d),c.addToSelf(d));r===o.o.NormalKind?n.P.TransformNormalFromFloatsToRef(i[_],i[_+1],i[_+2],c,u):n.P.TransformCoordinatesFromFloatsToRef(i[_],i[_+1],i[_+2],c,u),u.toArray(i,_),r===o.o.PositionKind&&this._positions&&this._positions[_/3].copyFrom(u)}}}return i}getNormalsData(e=!1,t=!1){return this._getData(e,t,null,o.o.NormalKind)}getPositionData(e=!1,t=!1,i){return this._getData(e,t,i,o.o.PositionKind)}_getPositionData(e,t){var i;let r=this.getVerticesData(o.o.PositionKind);if(this._internalAbstractMeshDataInfo._positions&&(this._internalAbstractMeshDataInfo._positions=null),r&&(e&&this.skeleton||t&&this.morphTargetManager)){if(r=r.slice(),this._generatePointsArray(),this._positions){let e=this._positions;this._internalAbstractMeshDataInfo._positions=Array(e.length);for(let t=0;t1||!r.IsGlobal)&&r.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,i){let r=this.getBoundingInfo(),s=e.getBoundingInfo();if(r.intersects(s,t))return!0;if(i){for(let i of this.getChildMeshes())if(i.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);let 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,i){var r;if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];let i=e.verticesStart,r=e.verticesStart+e.verticesCount;for(let s=i;s1)||n._checkCollision(e))&&this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;let t=n.jp.Matrix[0],i=n.jp.Matrix[1];return n.y3.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,i),this._processCollisionsForSubMeshes(e,i),this}_generatePointsArray(){return!1}intersects(e,t,i,r=!1,s,a=!1){let o=new u.p,l=this.getClassName(),h="InstancedLinesMesh"===l||"LinesMesh"===l||"GreasedLineMesh"===l?this.intersectionThreshold:0,c=this.getBoundingInfo();if(!this.subMeshes||!a&&(!e.intersectsSphere(c.boundingSphere,h)||!e.intersectsBox(c.boundingBox,h)))return o;if(r)return o.hit=!a,o.pickedMesh=a?null:this,o.distance=a?0:n.P.Distance(e.origin,c.boundingSphere.center),o.subMeshId=0,o;if(!this._generatePointsArray())return o;let d=null,p=this._scene.getIntersectingSubMeshCandidates(this,e),_=p.length,f=!1;for(let e=0;e<_;e++){let t=p.data[e].getMaterial();if(t&&(7==t.fillMode||0==t.fillMode||1==t.fillMode||2==t.fillMode||4==t.fillMode)){f=!0;break}}if(!f)return o.hit=!0,o.pickedMesh=this,o.distance=n.P.Distance(e.origin,c.boundingSphere.center),o.subMeshId=-1,o;for(let r=0;r<_;r++){let s=p.data[r];if(_>1&&!a&&!s.canIntersects(e))continue;let n=s.intersects(e,this._positions,this.getIndices(),t,i);if(n&&(t||!d||n.distancee!==this&&e.actionManager===this.actionManager)||this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),i=0;i{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),-1!==(t=e.excludedMeshes.indexOf(this))&&e.excludedMeshes.splice(t,1);let i=e.getShadowGenerators();if(i){let e=i.values();for(let i=e.next();!0!==i.done;i=e.next()){let e=i.value.getShadowMap();e&&e.renderList&&-1!==(t=e.renderList.indexOf(this))&&e.renderList.splice(t,1)}}}),("InstancedMesh"!==this.getClassName()||"InstancedLinesMesh"!==this.getClassName())&&this.releaseSubMeshes();let s=r.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,s.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),s.wipeCaches(),r.removeMesh(this),this._parentContainer){let 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(i=0;i65535){t=!0;break}t?e.depthSortedIndices=new Uint32Array(i):e.depthSortedIndices=new Uint16Array(i)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){let t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:n.P.Zero()}e.depthSortedFacets=[];for(let t=0;tg.kn?s.maximum.x-s.minimum.x:g.kn,e.bbSize.y=s.maximum.y-s.minimum.y>g.kn?s.maximum.y-s.minimum.y:g.kn,e.bbSize.z=s.maximum.z-s.minimum.z>g.kn?s.maximum.z-s.minimum.z:g.kn;let a=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(a=a>e.bbSize.z?a:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/a),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/a),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/a),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=s,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),n.P.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,r&&l.x.ComputeNormals(t,i,r,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);let t=e.depthSortedIndices.length/3|0;for(let r=0;rs.subDiv.max||a<0||a>s.subDiv.max||o<0||o>s.subDiv.max?null:s.facetPartitioning[n+s.subDiv.max*a+s.subDiv.max*s.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,i,r,s=!1,a=!0){let o=this.getWorldMatrix(),l=n.jp.Matrix[5];o.invertToRef(l);let h=n.jp.Vector3[8];n.P.TransformCoordinatesFromFloatsToRef(e,t,i,l,h);let u=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,r,s,a);return r&&n.P.TransformCoordinatesFromFloatsToRef(r.x,r.y,r.z,o,r),u}getClosestFacetAtLocalCoordinates(e,t,i,r,s=!1,n=!0){let a,o,l,h=null,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=this.getFacetLocalPositions(),x=this.getFacetLocalNormals(),T=this.getFacetsAtLocalCoordinates(e,t,i);if(!T)return null;let S=Number.MAX_VALUE,E=S;for(let C=0;C=0||s&&!n&&p<=0)&&(p=o.x*l.x+o.y*l.y+o.z*l.z,_=-(o.x*e+o.y*t+o.z*i-p)/(o.x*o.x+o.y*o.y+o.z*o.z),f=e+o.x*_,m=t+o.y*_,g=i+o.z*_,(E=(u=f-e)*u+(c=m-t)*c+(d=g-i)*d)e.emitter===this)}}E.OCCLUSION_TYPE_NONE=0,E.OCCLUSION_TYPE_OPTIMISTIC=1,E.OCCLUSION_TYPE_STRICT=2,E.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,E.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,E.CULLINGSTRATEGY_STANDARD=0,E.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,E.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,E.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,(0,x.H)("BABYLON.AbstractMesh",E)},1687:function(e,t,i){i.d(t,{Z:function(){return f}});var r=i(78),s=i(2983),n=i(2696),a=i(1295),o=i(1091),l=i(2697),h=i(5681),u=i(5132),c=i(1803),d=i(7383),p=i(6030),_=i(6705);class f{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){let t=new f(f.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,i,r=!1,s=null){if(this.delayLoadState=0,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||p.l.LastCreatedScene,!this._scene)return;this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=r,i?this.setAllVerticesData(i,r):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),s&&(this.applyToMesh(s),s.computeWorldMatrix(!0))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return 1===this.delayLoadState||0===this.delayLoadState}get doNotSerialize(){for(let e=0;e65535),this._meshes))r._createGlobalSubMesh(!0),r.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,i=!1){for(let r of(this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=i,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,i,"Geometry_"+this.id+"_IndexBuffer")),void 0!=t&&(this._totalVertices=t),this._meshes))r._createGlobalSubMesh(!0),r.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;let i=this._indices;return t||e&&1!==this._meshes.length?i.slice():i}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){let i=this._meshes,r=i.indexOf(e);-1!==r&&(i.splice(r,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===i.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;let t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();let i=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),i.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(a.o.PositionKind)))return;this._extend=(0,d.k)(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){let t=this._meshes.length;for(let i in this._vertexBuffers)1===t&&this._vertexBuffers[i].create(),i===a.o.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){for(let t of(this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects(),this._meshes))t._markSubMeshesAsAttributesDirty()}load(e,t){if(2!==this.delayLoadState){if(this.isReady()){t&&t();return}this.delayLoadState=2,this._queueLoad(e,t)}}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,i=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(i),this),this.delayLoadState=1,this._delayInfo=[],e.removePendingData(this);let r=this._meshes,s=r.length;for(let e=0;e0){for(let t=0;t0){for(let e=0;e0){for(let e=0;e-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){let t;let i=new n.x;i.indices=[];let r=this.getIndices();if(r)for(let e=0;e0){let r=new Float32Array(e,i.positionsAttrDesc.offset,i.positionsAttrDesc.count);t.setVerticesData(a.o.PositionKind,r,!1)}if(i.normalsAttrDesc&&i.normalsAttrDesc.count>0){let r=new Float32Array(e,i.normalsAttrDesc.offset,i.normalsAttrDesc.count);t.setVerticesData(a.o.NormalKind,r,!1)}if(i.tangetsAttrDesc&&i.tangetsAttrDesc.count>0){let r=new Float32Array(e,i.tangetsAttrDesc.offset,i.tangetsAttrDesc.count);t.setVerticesData(a.o.TangentKind,r,!1)}if(i.uvsAttrDesc&&i.uvsAttrDesc.count>0){let r=new Float32Array(e,i.uvsAttrDesc.offset,i.uvsAttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs2AttrDesc.offset,i.uvs2AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs3AttrDesc.offset,i.uvs3AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs4AttrDesc.offset,i.uvs4AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs5AttrDesc.offset,i.uvs5AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.uvs6AttrDesc.offset,i.uvs6AttrDesc.count);if(_.e.UseOpenGLOrientationForUV)for(let e=1;e0){let r=new Float32Array(e,i.colorsAttrDesc.offset,i.colorsAttrDesc.count);t.setVerticesData(a.o.ColorKind,r,!1,i.colorsAttrDesc.stride)}if(i.matricesIndicesAttrDesc&&i.matricesIndicesAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesAttrDesc.offset,i.matricesIndicesAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(a.o.MatricesIndicesKind,s,!1)}if(i.matricesIndicesExtraAttrDesc&&i.matricesIndicesExtraAttrDesc.count>0){let r=new Int32Array(e,i.matricesIndicesExtraAttrDesc.offset,i.matricesIndicesExtraAttrDesc.count),s=[];for(let e=0;e>8),s.push((16711680&t)>>16),s.push(t>>24&255)}t.setVerticesData(a.o.MatricesIndicesExtraKind,s,!1)}if(i.matricesWeightsAttrDesc&&i.matricesWeightsAttrDesc.count>0){let r=new Float32Array(e,i.matricesWeightsAttrDesc.offset,i.matricesWeightsAttrDesc.count);t.setVerticesData(a.o.MatricesWeightsKind,r,!1)}if(i.indicesAttrDesc&&i.indicesAttrDesc.count>0){let r=new Int32Array(e,i.indicesAttrDesc.offset,i.indicesAttrDesc.count);t.setIndices(r,null)}if(i.subMeshesAttrDesc&&i.subMeshesAttrDesc.count>0){let r=new Int32Array(e,i.subMeshesAttrDesc.offset,5*i.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(a.o.MatricesIndicesKind,i,e.matricesIndices._updatable)}}if(e.matricesIndicesExtra){if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(a.o.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{let i=[];for(let t=0;t>8),i.push((16711680&r)>>16),i.push(r>>24&255)}t.setVerticesData(a.o.MatricesIndicesExtraKind,i,e.matricesIndicesExtra._updatable)}}e.matricesWeights&&(f._CleanMatricesWeights(e,t),t.setVerticesData(a.o.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(a.o.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let i=0;i-1))return;{let r=t.getScene().getLastSkeletonById(e.skeletonId);if(!r)return;i=r.bones.length}let r=t.getVerticesData(a.o.MatricesIndicesKind),s=t.getVerticesData(a.o.MatricesIndicesExtraKind),n=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,u=n.length;for(let e=0;eh-1)&&(a=h-1),t>.001){let i=1/t;for(let t=0;t<4;t++)n[e+t]*=i;if(o)for(let t=0;t<4;t++)o[e+t]*=i}else a>=4?(o[e+a-4]=1-t,s[e+a-4]=i):(n[e+a]=1-t,r[e+a]=i)}t.setVerticesData(a.o.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(a.o.MatricesIndicesExtraKind,s)}static Parse(e,t,i){let s=new f(e.id,t,void 0,e.updatable);return s._loadedUniqueId=e.uniqueId,c.$&&c.$.AddTagsTo(s,e.tags),e.delayLoadingFile?(s.delayLoadState=4,s.delayLoadingFile=i+e.delayLoadingFile,s._boundingInfo=new h.j(r.P.FromArray(e.boundingBoxMinimum),r.P.FromArray(e.boundingBoxMaximum)),s._delayInfo=[],e.hasUVs&&s._delayInfo.push(a.o.UVKind),e.hasUVs2&&s._delayInfo.push(a.o.UV2Kind),e.hasUVs3&&s._delayInfo.push(a.o.UV3Kind),e.hasUVs4&&s._delayInfo.push(a.o.UV4Kind),e.hasUVs5&&s._delayInfo.push(a.o.UV5Kind),e.hasUVs6&&s._delayInfo.push(a.o.UV6Kind),e.hasColors&&s._delayInfo.push(a.o.ColorKind),e.hasMatricesIndices&&s._delayInfo.push(a.o.MatricesIndicesKind),e.hasMatricesWeights&&s._delayInfo.push(a.o.MatricesWeightsKind),s._delayLoadingFunction=n.x.ImportVertexData):n.x.ImportVertexData(e,s),t.pushGeometry(s,!0),s}}},2696:function(e,t,i){i.d(t,{D:function(){return p},x:function(){return _}});var r=i(9956),s=i(78),n=i(1295),a=i(6131),o=i(2983),l=i(9626),h=i(1760),u=i(7521),c=i(3477),d=i(1091);class p{}class _{constructor(){this.uniqueId=0,this.metadata={},this._applyTo=(0,u.vp)(this._applyToCoroutine.bind(this)),this.uniqueId=_._UniqueIDGenerator,_._UniqueIDGenerator++}set(e,t){switch(e.length||l.Y.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case n.o.PositionKind:this.positions=e;break;case n.o.NormalKind:this.normals=e;break;case n.o.TangentKind:this.tangents=e;break;case n.o.UVKind:this.uvs=e;break;case n.o.UV2Kind:this.uvs2=e;break;case n.o.UV3Kind:this.uvs3=e;break;case n.o.UV4Kind:this.uvs4=e;break;case n.o.UV5Kind:this.uvs5=e;break;case n.o.UV6Kind:this.uvs6=e;break;case n.o.ColorKind:this.colors=e;break;case n.o.MatricesIndicesKind:this.matricesIndices=e;break;case n.o.MatricesWeightsKind:this.matricesWeights=e;break;case n.o.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case n.o.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,i){if(this.positions&&(e.setVerticesData(n.o.PositionKind,this.positions,t),i&&(yield)),this.normals&&(e.setVerticesData(n.o.NormalKind,this.normals,t),i&&(yield)),this.tangents&&(e.setVerticesData(n.o.TangentKind,this.tangents,t),i&&(yield)),this.uvs&&(e.setVerticesData(n.o.UVKind,this.uvs,t),i&&(yield)),this.uvs2&&(e.setVerticesData(n.o.UV2Kind,this.uvs2,t),i&&(yield)),this.uvs3&&(e.setVerticesData(n.o.UV3Kind,this.uvs3,t),i&&(yield)),this.uvs4&&(e.setVerticesData(n.o.UV4Kind,this.uvs4,t),i&&(yield)),this.uvs5&&(e.setVerticesData(n.o.UV5Kind,this.uvs5,t),i&&(yield)),this.uvs6&&(e.setVerticesData(n.o.UV6Kind,this.uvs6,t),i&&(yield)),this.colors&&(e.setVerticesData(n.o.ColorKind,this.colors,t),i&&(yield)),this.matricesIndices&&(e.setVerticesData(n.o.MatricesIndicesKind,this.matricesIndices,t),i&&(yield)),this.matricesWeights&&(e.setVerticesData(n.o.MatricesWeightsKind,this.matricesWeights,t),i&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),i&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),i&&(yield)),this.indices?(e.setIndices(this.indices,null,t),i&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1)for(let t of(e.subMeshes=[],this.materialInfos))new d.P(t.materialIndex,t.verticesStart,t.verticesCount,t.indexStart,t.indexCount,e);return this}_update(e,t,i){return this.positions&&e.updateVerticesData(n.o.PositionKind,this.positions,t,i),this.normals&&e.updateVerticesData(n.o.NormalKind,this.normals,t,i),this.tangents&&e.updateVerticesData(n.o.TangentKind,this.tangents,t,i),this.uvs&&e.updateVerticesData(n.o.UVKind,this.uvs,t,i),this.uvs2&&e.updateVerticesData(n.o.UV2Kind,this.uvs2,t,i),this.uvs3&&e.updateVerticesData(n.o.UV3Kind,this.uvs3,t,i),this.uvs4&&e.updateVerticesData(n.o.UV4Kind,this.uvs4,t,i),this.uvs5&&e.updateVerticesData(n.o.UV5Kind,this.uvs5,t,i),this.uvs6&&e.updateVerticesData(n.o.UV6Kind,this.uvs6,t,i),this.colors&&e.updateVerticesData(n.o.ColorKind,this.colors,t,i),this.matricesIndices&&e.updateVerticesData(n.o.MatricesIndicesKind,this.matricesIndices,t,i),this.matricesWeights&&e.updateVerticesData(n.o.MatricesWeightsKind,this.matricesWeights,t,i),this.matricesIndicesExtra&&e.updateVerticesData(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,i),this.matricesWeightsExtra&&e.updateVerticesData(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,i),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,i=0,r=e.length){let n=s.jp.Vector3[0],a=s.jp.Vector3[1];for(let o=i;oe.determinant();return this.positions&&_._TransformVector3Coordinates(this.positions,e),this.normals&&_._TransformVector3Normals(this.normals,e),this.tangents&&_._TransformVector4Normals(this.tangents,e),t&&this.indices&&_._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];let e=[];for(let t of this.materialInfos){let i=new _;if(this.positions&&(i.positions=this.positions.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.normals&&(i.normals=this.normals.slice(3*t.verticesStart,(t.verticesCount+t.verticesStart)*3)),this.tangents&&(i.tangents=this.tangents.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.colors&&(i.colors=this.colors.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.uvs&&(i.uvs=this.uvs.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs2&&(i.uvs2=this.uvs2.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs3&&(i.uvs3=this.uvs3.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs4&&(i.uvs4=this.uvs4.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs5&&(i.uvs5=this.uvs5.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.uvs6&&(i.uvs6=this.uvs6.slice(2*t.verticesStart,(t.verticesCount+t.verticesStart)*2)),this.matricesIndices&&(i.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesIndicesExtra&&(i.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeights&&(i.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.matricesWeightsExtra&&(i.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,(t.verticesCount+t.verticesStart)*4)),this.indices){i.indices=[];for(let e=t.indexStart;e({vertexData:e})):[{vertexData:e}];return(0,u.s3)(this._mergeCoroutine(void 0,n,t,!1,i,r,s))}*_mergeCoroutine(e,t,i=!1,r,s,a=!1,o=!1){var l,h,u,c;this._validate();let d=t.map(e=>e.vertexData),f=this;if(o)for(let e of d)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(let e of d)if(e){if(o)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 Error("Cannot merge vertex data that do not have the same set of attributes")}if(a){let i=0,r=0,s=0,n=[],a=null,o=[];for(let t of this.splitBasedOnMaterialID())o.push({vertexData:t,transform:e});for(let e of t)if(e.vertexData)for(let t of e.vertexData.splitBasedOnMaterialID())o.push({vertexData:t,transform:e.transform});for(let e of(o.sort((e,t)=>{let i=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,r=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return i>r?1:i===r?0:-1}),o)){let t=e.vertexData;if(i=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===i)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{let e=new p;e.materialIndex=i,e.indexStart=r,e.indexCount=t.indices.length,e.verticesStart=s,e.verticesCount=t.positions.length/3,n.push(e),a=e}r+=t.indices.length,s+=t.positions.length/3}let l=o.splice(0,1)[0];f=l.vertexData,e=l.transform,d=o.map(e=>e.vertexData),t=o,this.materialInfos=n}let m=d.reduce((e,t)=>{var i,r;return e+(null!==(r=null===(i=t.indices)||void 0===i?void 0:i.length)&&void 0!==r?r:0)},null!==(h=null===(l=f.indices)||void 0===l?void 0:l.length)&&void 0!==h?h:0),g=s||d.some(e=>e.indices===f.indices)?null===(u=f.indices)||void 0===u?void 0:u.slice():f.indices;if(m>0){let s=null!==(c=null==g?void 0:g.length)&&void 0!==c?c:0;if(g||(g=Array(m)),g.length!==m){if(Array.isArray(g))g.length=m;else{let e=i||g instanceof Uint32Array?new Uint32Array(m):new Uint16Array(m);e.set(g),g=e}e&&0>e.determinant()&&_._FlipFaces(g,0,s)}let n=f.positions?f.positions.length/3:0;for(let{vertexData:e,transform:i}of t)if(e.indices){for(let t=0;ti.determinant()&&_._FlipFaces(g,s,e.indices.length),n+=e.positions.length/3,s+=e.indices.length,r&&(yield)}}return this.indices=g,this.positions=_._MergeElement(n.o.PositionKind,f.positions,e,t.map(e=>[e.vertexData.positions,e.transform])),r&&(yield),f.normals&&(this.normals=_._MergeElement(n.o.NormalKind,f.normals,e,t.map(e=>[e.vertexData.normals,e.transform])),r&&(yield)),f.tangents&&(this.tangents=_._MergeElement(n.o.TangentKind,f.tangents,e,t.map(e=>[e.vertexData.tangents,e.transform])),r&&(yield)),f.uvs&&(this.uvs=_._MergeElement(n.o.UVKind,f.uvs,e,t.map(e=>[e.vertexData.uvs,e.transform])),r&&(yield)),f.uvs2&&(this.uvs2=_._MergeElement(n.o.UV2Kind,f.uvs2,e,t.map(e=>[e.vertexData.uvs2,e.transform])),r&&(yield)),f.uvs3&&(this.uvs3=_._MergeElement(n.o.UV3Kind,f.uvs3,e,t.map(e=>[e.vertexData.uvs3,e.transform])),r&&(yield)),f.uvs4&&(this.uvs4=_._MergeElement(n.o.UV4Kind,f.uvs4,e,t.map(e=>[e.vertexData.uvs4,e.transform])),r&&(yield)),f.uvs5&&(this.uvs5=_._MergeElement(n.o.UV5Kind,f.uvs5,e,t.map(e=>[e.vertexData.uvs5,e.transform])),r&&(yield)),f.uvs6&&(this.uvs6=_._MergeElement(n.o.UV6Kind,f.uvs6,e,t.map(e=>[e.vertexData.uvs6,e.transform])),r&&(yield)),f.colors&&(this.colors=_._MergeElement(n.o.ColorKind,f.colors,e,t.map(e=>[e.vertexData.colors,e.transform])),r&&(yield)),f.matricesIndices&&(this.matricesIndices=_._MergeElement(n.o.MatricesIndicesKind,f.matricesIndices,e,t.map(e=>[e.vertexData.matricesIndices,e.transform])),r&&(yield)),f.matricesWeights&&(this.matricesWeights=_._MergeElement(n.o.MatricesWeightsKind,f.matricesWeights,e,t.map(e=>[e.vertexData.matricesWeights,e.transform])),r&&(yield)),f.matricesIndicesExtra&&(this.matricesIndicesExtra=_._MergeElement(n.o.MatricesIndicesExtraKind,f.matricesIndicesExtra,e,t.map(e=>[e.vertexData.matricesIndicesExtra,e.transform])),r&&(yield)),f.matricesWeightsExtra&&(this.matricesWeightsExtra=_._MergeElement(n.o.MatricesWeightsExtraKind,f.matricesWeightsExtra,e,t.map(e=>[e.vertexData.matricesWeightsExtra,e.transform]))),this}static _MergeElement(e,t,i,r){let s=r.filter(e=>null!==e[0]&&void 0!==e[0]);if(!t&&0==s.length)return t;if(!t)return this._MergeElement(e,s[0][0],s[0][1],s.slice(1));let a=s.reduce((e,t)=>e+t[0].length,t.length),o=e===n.o.PositionKind?_._TransformVector3Coordinates:e===n.o.NormalKind?_._TransformVector3Normals:e===n.o.TangentKind?_._TransformVector4Normals:()=>{};if(t instanceof Float32Array){let e=new Float32Array(a);e.set(t),i&&o(e,i,0,t.length);let r=t.length;for(let[t,i]of s)e.set(t,r),i&&o(e,i,r,t.length),r+=t.length;return e}{let e=Array(a);for(let i=0;i{let i=n.o.DeduceStride(e);if(t.length%i!=0)throw Error("The "+e+"s array count must be a multiple of "+i);return t.length/i},t=e(n.o.PositionKind,this.positions),i=(i,r)=>{let s=e(i,r);if(s!==t)throw Error("The "+i+"s element count ("+s+") does not match the positions count ("+t+")")};this.normals&&i(n.o.NormalKind,this.normals),this.tangents&&i(n.o.TangentKind,this.tangents),this.uvs&&i(n.o.UVKind,this.uvs),this.uvs2&&i(n.o.UV2Kind,this.uvs2),this.uvs3&&i(n.o.UV3Kind,this.uvs3),this.uvs4&&i(n.o.UV4Kind,this.uvs4),this.uvs5&&i(n.o.UV5Kind,this.uvs5),this.uvs6&&i(n.o.UV6Kind,this.uvs6),this.colors&&i(n.o.ColorKind,this.colors),this.matricesIndices&&i(n.o.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&i(n.o.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&i(n.o.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&i(n.o.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){let e=this.serialize();return _.Parse(e)}serialize(){let 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)),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)for(let t of(e.materialInfos=[],this.materialInfos)){let i={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(i)}return e}static ExtractFromMesh(e,t,i){return _._ExtractFrom(e,t,i)}static ExtractFromGeometry(e,t,i){return _._ExtractFrom(e,t,i)}static _ExtractFrom(e,t,i){let r=new _;return e.isVerticesDataPresent(n.o.PositionKind)&&(r.positions=e.getVerticesData(n.o.PositionKind,t,i)),e.isVerticesDataPresent(n.o.NormalKind)&&(r.normals=e.getVerticesData(n.o.NormalKind,t,i)),e.isVerticesDataPresent(n.o.TangentKind)&&(r.tangents=e.getVerticesData(n.o.TangentKind,t,i)),e.isVerticesDataPresent(n.o.UVKind)&&(r.uvs=e.getVerticesData(n.o.UVKind,t,i)),e.isVerticesDataPresent(n.o.UV2Kind)&&(r.uvs2=e.getVerticesData(n.o.UV2Kind,t,i)),e.isVerticesDataPresent(n.o.UV3Kind)&&(r.uvs3=e.getVerticesData(n.o.UV3Kind,t,i)),e.isVerticesDataPresent(n.o.UV4Kind)&&(r.uvs4=e.getVerticesData(n.o.UV4Kind,t,i)),e.isVerticesDataPresent(n.o.UV5Kind)&&(r.uvs5=e.getVerticesData(n.o.UV5Kind,t,i)),e.isVerticesDataPresent(n.o.UV6Kind)&&(r.uvs6=e.getVerticesData(n.o.UV6Kind,t,i)),e.isVerticesDataPresent(n.o.ColorKind)&&(r.colors=e.getVerticesData(n.o.ColorKind,t,i)),e.isVerticesDataPresent(n.o.MatricesIndicesKind)&&(r.matricesIndices=e.getVerticesData(n.o.MatricesIndicesKind,t,i)),e.isVerticesDataPresent(n.o.MatricesWeightsKind)&&(r.matricesWeights=e.getVerticesData(n.o.MatricesWeightsKind,t,i)),e.isVerticesDataPresent(n.o.MatricesIndicesExtraKind)&&(r.matricesIndicesExtra=e.getVerticesData(n.o.MatricesIndicesExtraKind,t,i)),e.isVerticesDataPresent(n.o.MatricesWeightsExtraKind)&&(r.matricesWeightsExtra=e.getVerticesData(n.o.MatricesWeightsExtraKind,t,i)),r.indices=e.getIndices(t,i),r}static CreateRibbon(e){throw(0,a.S)("ribbonBuilder")}static CreateBox(e){throw(0,a.S)("boxBuilder")}static CreateTiledBox(e){throw(0,a.S)("tiledBoxBuilder")}static CreateTiledPlane(e){throw(0,a.S)("tiledPlaneBuilder")}static CreateSphere(e){throw(0,a.S)("sphereBuilder")}static CreateCylinder(e){throw(0,a.S)("cylinderBuilder")}static CreateTorus(e){throw(0,a.S)("torusBuilder")}static CreateLineSystem(e){throw(0,a.S)("linesBuilder")}static CreateDashedLines(e){throw(0,a.S)("linesBuilder")}static CreateGround(e){throw(0,a.S)("groundBuilder")}static CreateTiledGround(e){throw(0,a.S)("groundBuilder")}static CreateGroundFromHeightMap(e){throw(0,a.S)("groundBuilder")}static CreatePlane(e){throw(0,a.S)("planeBuilder")}static CreateDisc(e){throw(0,a.S)("discBuilder")}static CreatePolygon(e,t,i,r,s,n,o){throw(0,a.S)("polygonBuilder")}static CreateIcoSphere(e){throw(0,a.S)("icoSphereBuilder")}static CreatePolyhedron(e){throw(0,a.S)("polyhedronBuilder")}static CreateCapsule(e={orientation:s.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw(0,a.S)("capsuleBuilder")}static CreateTorusKnot(e){throw(0,a.S)("torusKnotBuilder")}static ComputeNormals(e,t,i,r){let n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0,p=0,_=0,f=0,m=0,g=0,v=0,x=0,T=0,S=0,E=0,C=0,b=0,y=!1,A=!1,R=!1,P=!1,I=1,M=0,D=null;r&&(y=!!r.facetNormals,A=!!r.facetPositions,R=!!r.facetPartitioning,I=!0===r.useRightHandedSystem?-1:1,M=r.ratio||0,P=!!r.depthSort,D=r.distanceTo,P&&void 0===D&&(D=s.P.Zero()));let O=0,N=0,F=0,L=0;for(R&&r&&r.bbSize&&(O=r.subDiv.X*M/r.bbSize.x,N=r.subDiv.Y*M/r.bbSize.y,F=r.subDiv.Z*M/r.bbSize.z,L=r.subDiv.max*r.subDiv.max,r.facetPartitioning.length=0),n=0;n!Array.isArray(e))],_,"_TransformVector3Coordinates",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],_,"_TransformVector3Normals",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],_,"_TransformVector4Normals",null),(0,r.gn)([h.G6.filter((...[e])=>!Array.isArray(e))],_,"_FlipFaces",null)},4926:function(e,t,i){i.d(t,{g:function(){return r}});class r{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}},1091:function(e,t,i){i.d(t,{P:function(){return l}});var r=i(1295),s=i(9372),n=i(5681),a=i(7383),o=i(1606);class l{get materialDefines(){var e;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:null===(e=this._getDrawWrapper())||void 0===e?void 0:e.defines}set materialDefines(e){var t;(null!==(t=this._mainDrawWrapperOverride)&&void 0!==t?t:this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=null!=e?e:this._engine.currentRenderPassId;let i=this._drawWrappers[e];return!i&&t&&(this._drawWrappers[e]=i=new o.q(this._mesh.getScene().getEngine())),i}_removeDrawWrapper(e,t=!0){var i;t&&(null===(i=this._drawWrappers[e])||void 0===i||i.dispose()),this._drawWrappers[e]=void 0}get effect(){var e,t;return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:null!==(t=null===(e=this._getDrawWrapper())||void 0===e?void 0:e.effect)&&void 0!==t?t:null}get _drawWrapper(){var e;return null!==(e=this._mainDrawWrapperOverride)&&void 0!==e?e:this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,i,r=!0){let s=this._drawWrapper;s.setEffect(e,t,r),void 0!==i&&(s.materialContext=i),e||(s.defines=null,s.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e){this._removeDrawWrapper(e);return}for(let e of this._drawWrappers)null==e||e.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,i,r,s,n,a,o=!0){return new l(e,t,i,r,s,n,a,o)}constructor(e,t,i,r,s,n,a,o=!0,l=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=i,this.indexStart=r,this.indexCount=s,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,l&&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(){return(this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null)||this._renderingMesh}getMaterial(e=!0){var t;let i=null!==(t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId))&&void 0!==t?t:this._renderingMesh.material;if(!i)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(i)){let e=i.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return i}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){let t;if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(r.o.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;let i=this._renderingMesh.getIndices();if(0===this.indexStart&&this.indexCount===i.length){let e=this._renderingMesh.getBoundingInfo();t={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else t=(0,a.y)(e,i,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(t.minimum,t.maximum):this._boundingInfo=new n.j(t.minimum,t.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){let t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){let 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){let i=[];for(let t=this.indexStart;to&&(o=t)}return new l(e,a,o-a+1,t,i,r,s,n)}}},8061:function(e,t,i){i.d(t,{Y:function(){return u}});var r=i(9956),s=i(1760),n=i(4800),a=i(78),o=i(208),l=i(524);let h=a.y3.Compose(a.P.One(),a._f.FromEulerAngles(0,Math.PI,0),a.P.Zero());class u extends o.N{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=(this._billboardMode&u.BILLBOARDMODE_USE_POSITION)!=0,this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==u.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,i=!0){super(e,t),this._forward=new a.P(0,0,1),this._up=new a.P(0,1,0),this._right=new a.P(1,0,0),this._position=a.P.Zero(),this._rotation=a.P.Zero(),this._rotationQuaternion=null,this._scaling=a.P.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=u.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=a.y3.Zero(),this._usePivotMatrix=!1,this._absolutePosition=a.P.Zero(),this._absoluteScaling=a.P.Zero(),this._absoluteRotationQuaternion=a._f.Identity(),this._pivotMatrix=a.y3.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new n.y$,this._nonUniformScaling=!1,i&&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 a.P.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return a.P.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return a.P.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._poseMatrix=e.clone(),this}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=a.y3.Identity()),this._poseMatrix}_isSynchronized(){let e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===u.BILLBOARDMODE_NONE&&!e.pivotMatrixUpdated&&!this._infiniteDistance&&!this._position._isDirty&&!this._scaling._isDirty&&(!this._rotationQuaternion||!this._rotationQuaternion._isDirty)&&!this._rotation._isDirty}_initCache(){super._initCache();let 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=a.y3.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,i){let r=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);for(let e of(r&&i&&i(this,r),this.getChildTransformNodes(!0)))e.instantiateHierarchy(r,t,i);return r}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||a._f.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){let t,i,r;if(!e)return this;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],i=arguments[1],r=arguments[2]}else t=e.x,i=e.y,r=e.z;if(this.parent){let e=a.jp.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),a.P.TransformCoordinatesFromFloatsToRef(t,i,r,e,this.position)}else this.position.x=t,this.position.y=i,this.position.z=r;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=a.P.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();let e=a.jp.Matrix[0];return this._localMatrix.invertToRef(e),a.P.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=a.P.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,i=0,r=0,s=l.T.LOCAL){let n=u._LookAtVectorCache,o=s===l.T.LOCAL?this.position:this.getAbsolutePosition();if(e.subtractToRef(o,n),this.setDirection(n,t,i,r),s===l.T.WORLD&&this.parent){if(this.rotationQuaternion){let e=a.jp.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);let t=a.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{let e=a.jp.Quaternion[0];a._f.FromEulerVectorToRef(this.rotation,e);let t=a.jp.Matrix[0];e.toRotationMatrix(t);let i=a.jp.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(i),i.invert(),t.multiplyToRef(i,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}}return this}getDirection(e){let t=a.P.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return a.P.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,i=0,r=0){let s=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),o=-Math.atan2(e.y,n);return this.rotationQuaternion?a._f.RotationYawPitchRollToRef(s+t,o+i,r,this.rotationQuaternion):(this.rotation.x=o+i,this.rotation.y=s+t,this.rotation.z=r),this}setPivotPoint(e,t=l.T.LOCAL){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);let i=this.getWorldMatrix();if(t==l.T.WORLD){let t=a.jp.Matrix[0];i.invertToRef(t),e=a.P.TransformCoordinates(e,t)}return this.setPivotMatrix(a.y3.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){let e=a.P.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(){let e=a.P.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),a.P.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(let t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,i=!1){if(!e&&!this.parent)return this;let r=a.jp.Quaternion[0],s=a.jp.Vector3[0],n=a.jp.Vector3[1],o=a.jp.Matrix[1];a.y3.IdentityToRef(o);let l=a.jp.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=u._TmpRotation,a._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),a.y3.ComposeToRef(this.scaling,h,this.position,l),this.parent&&l.multiplyToRef(this.parent.computeWorldMatrix(!0),l),e&&(e.computeWorldMatrix(!0).invertToRef(o),l.multiplyToRef(o,l)),l.decompose(n,r,s,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(r):r.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(s),this.parent=e,i&&this.setPivotMatrix(a.y3.Identity()),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),0>e.getFinalMatrix().determinant()&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(0>this.parent.getWorldMatrix().determinant()&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,e?this.parent=this._currentParentWhenAttachingToBone:this.parent=null):e&&(this.parent=this._currentParentWhenAttachingToBone),this}rotate(e,t,i){let r;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),i&&i!==l.T.LOCAL){if(this.parent){let i=this.parent.getWorldMatrix(),r=a.jp.Matrix[0];i.invertToRef(r),e=a.P.TransformNormal(e,r),0>i.determinant()&&(t*=-1)}(r=a._f.RotationAxisToRef(e,t,u._RotationAxisCache)).multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else r=a._f.RotationAxisToRef(e,t,u._RotationAxisCache),this.rotationQuaternion.multiplyToRef(r,this.rotationQuaternion);return this}rotateAround(e,t,i){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=a._f.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));let r=a.jp.Vector3[0],s=a.jp.Vector3[1],n=a.jp.Vector3[2],o=a.jp.Quaternion[0],l=a.jp.Matrix[0],h=a.jp.Matrix[1],u=a.jp.Matrix[2],c=a.jp.Matrix[3];return e.subtractToRef(this.position,r),a.y3.TranslationToRef(r.x,r.y,r.z,l),a.y3.TranslationToRef(-r.x,-r.y,-r.z,h),a.y3.RotationAxisToRef(t,i,u),h.multiplyToRef(u,c),c.multiplyToRef(l,c),c.decompose(s,o,n),this.position.addInPlace(n),o.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,i){let r=e.scale(t);if(i&&i!==l.T.LOCAL)this.setAbsolutePosition(this.getAbsolutePosition().add(r));else{let e=this.getPositionExpressedInLocalSpace().add(r);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,i){let r;this.rotationQuaternion?r=this.rotationQuaternion:(r=a.jp.Quaternion[1],a._f.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,r));let s=a.jp.Quaternion[0];return a._f.RotationYawPitchRollToRef(t,e,i,s),r.multiplyInPlace(s),this.rotationQuaternion||r.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==u.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){let i;if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;let r=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===r||this.isSynchronized()))return this._currentRenderId=r,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();let s=this._cache;s.pivotMatrixUpdated=!1,s.billboardMode=this.billboardMode,s.infiniteDistance=this.infiniteDistance,s.parent=this._parentNode,this._currentRenderId=r,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;let n=this._getEffectiveParent(),o=u._TmpScaling,l=this._position;if(this._infiniteDistance&&!this.parent&&t){let e=t.getWorldMatrix(),i=new a.P(e.m[12],e.m[13],e.m[14]);(l=u._TmpTranslation).copyFromFloats(this._position.x+i.x,this._position.y+i.y,this._position.z+i.z)}if(o.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion?(this._rotationQuaternion._isDirty=!1,i=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion&&this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(a._f.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))):(i=u._TmpRotation,a._f.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,i)),this._usePivotMatrix){let e=a.jp.Matrix[1];a.y3.ScalingToRef(o.x,o.y,o.z,e);let t=a.jp.Matrix[0];i.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,a.jp.Matrix[4]),a.jp.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(l.x,l.y,l.z)}else a.y3.ComposeToRef(o,i,l,this._localMatrix);if(n&&n.getWorldMatrix){if(e&&n.computeWorldMatrix(e),s.useBillboardPath){if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),a.jp.Matrix[7])}else a.jp.Matrix[7].copyFrom(n.getWorldMatrix());let e=a.jp.Vector3[5],t=a.jp.Vector3[6],i=a.jp.Quaternion[0];a.jp.Matrix[7].decompose(t,i,e),a.y3.ScalingToRef(t.x,t.y,t.z,a.jp.Matrix[7]),a.jp.Matrix[7].setTranslation(e),u.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(i,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(a.jp.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){let e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),a.jp.Matrix[6]),a.jp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(n.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(s.useBillboardPath&&t&&this.billboardMode&&!s.useBillboardPosition){let e=a.jp.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),a.jp.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&a.jp.Matrix[1].multiplyToRef(h,a.jp.Matrix[1]),a.jp.Matrix[1].setTranslationFromFloats(0,0,0),a.jp.Matrix[1].invertToRef(a.jp.Matrix[0]),(this.billboardMode&u.BILLBOARDMODE_ALL)!==u.BILLBOARDMODE_ALL){a.jp.Matrix[0].decompose(void 0,a.jp.Quaternion[0],void 0);let e=a.jp.Vector3[1];a.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&u.BILLBOARDMODE_X)!==u.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&u.BILLBOARDMODE_Y)!==u.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&u.BILLBOARDMODE_Z)!==u.BILLBOARDMODE_Z&&(e.z=0),a.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,a.jp.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.jp.Vector3[0])}else if(s.useBillboardPath&&t&&s.useBillboardPosition){let e=a.jp.Vector3[0];this._worldMatrix.getTranslationToRef(e);let i=t.globalPosition;this._worldMatrix.invertToRef(a.jp.Matrix[1]);let r=a.jp.Vector3[1];a.P.TransformCoordinatesToRef(i,a.jp.Matrix[1],r),r.normalize();let s=-Math.atan2(r.z,r.x)+Math.PI/2,n=Math.sqrt(r.x*r.x+r.z*r.z),o=-Math.atan2(r.y,n);if(a._f.RotationYawPitchRollToRef(s,o,0,a.jp.Quaternion[0]),(this.billboardMode&u.BILLBOARDMODE_ALL)!==u.BILLBOARDMODE_ALL){let e=a.jp.Vector3[1];a.jp.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&u.BILLBOARDMODE_X)!==u.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&u.BILLBOARDMODE_Y)!==u.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&u.BILLBOARDMODE_Z)!==u.BILLBOARDMODE_Z&&(e.z=0),a.y3.RotationYawPitchRollToRef(e.y,e.x,e.z,a.jp.Matrix[0])}else a.y3.FromQuaternionToRef(a.jp.Quaternion[0],a.jp.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(a.jp.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(a.jp.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):n&&n._nonUniformScaling?this._updateNonUniformScalingState(n._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=a.y3.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){let e=this.getChildren();for(let t=0;tnew u(e,this.getScene()),this);if(r.name=e,r.id=e,t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;inew u(e.name,t),e,t,i);return e.localMatrix?r.setPreTransformMatrix(a.y3.FromArray(e.localMatrix)):e.pivotMatrix&&r.setPivotMatrix(a.y3.FromArray(e.pivotMatrix)),r.setEnabled(e.isEnabled),r._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r}getChildTransformNodes(e,t){let i=[];return this._getDescendants(i,e,e=>(!t||t(e))&&e instanceof u),i}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){let e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e)for(let e of this.getChildTransformNodes(!0))e.parent=null,e.computeWorldMatrix(!0);super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,i){let r=null,s=null;t&&(this.rotationQuaternion?(s=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(r=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));let n=this.getHierarchyBoundingVectors(e,i),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);return 0===o||(this.scaling.scaleInPlace(1/o),t&&(this.rotationQuaternion&&s?this.rotationQuaternion.copyFrom(s):this.rotation&&r&&this.rotation.copyFrom(r))),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}u.BILLBOARDMODE_NONE=0,u.BILLBOARDMODE_X=1,u.BILLBOARDMODE_Y=2,u.BILLBOARDMODE_Z=4,u.BILLBOARDMODE_ALL=7,u.BILLBOARDMODE_USE_POSITION=128,u.BillboardUseParentOrientation=!1,u._TmpRotation=a._f.Zero(),u._TmpScaling=a.P.Zero(),u._TmpTranslation=a.P.Zero(),u._LookAtVectorCache=new a.P(0,0,0),u._RotationAxisCache=new a._f,(0,r.gn)([(0,s.hd)("position")],u.prototype,"_position",void 0),(0,r.gn)([(0,s.hd)("rotation")],u.prototype,"_rotation",void 0),(0,r.gn)([(0,s.mv)("rotationQuaternion")],u.prototype,"_rotationQuaternion",void 0),(0,r.gn)([(0,s.hd)("scaling")],u.prototype,"_scaling",void 0),(0,r.gn)([(0,s.qC)("billboardMode")],u.prototype,"_billboardMode",void 0),(0,r.gn)([(0,s.qC)()],u.prototype,"scalingDeterminant",void 0),(0,r.gn)([(0,s.qC)("infiniteDistance")],u.prototype,"_infiniteDistance",void 0),(0,r.gn)([(0,s.qC)()],u.prototype,"ignoreNonUniformScaling",void 0),(0,r.gn)([(0,s.qC)()],u.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0)},1146:function(e,t,i){i.d(t,{q:function(){return r}});class r{static Eval(e,t){return"true"===(e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,e=>(e=e.slice(1,e.length-1),r._HandleParenthesisContent(e,t))):r._HandleParenthesisContent(e,t))||"false"!==e&&r.Eval(e,t)}static _HandleParenthesisContent(e,t){let i;t=t||(e=>"true"===e);let s=e.split("||");for(let e in s)if(Object.prototype.hasOwnProperty.call(s,e)){let n=r._SimplifyNegation(s[e].trim()),a=n.split("&&");if(a.length>1)for(let e=0;e(e=e.replace(/[\s]/g,()=>"")).length%2?"!":"")).trim())?e="false":"!false"===e&&(e="true"),e}}},4254:function(e,t,i){i.d(t,{B:function(){return r},M:function(){return n}});class r{static BuildArray(e,t){let i=[];for(let r=0;r(function(e,t,i){let r=e[t];if("function"!=typeof r)return null;let s=function(){let r=e.length,n=s.previous.apply(e,arguments);return i(t,r),n};return r.next=s,s.previous=r,e[t]=s,()=>{let i=s.previous;if(!i)return;let r=s.next;r?(i.next=r,r.previous=i):(i.next=void 0,e[t]=i),s.next=void 0,s.previous=void 0}})(e,i,t));return()=>{i.forEach(e=>{null==e||e()})}}},7521:function(e,t,i){function r(e,t,i){try{let r=e.next();r.done?t(r):r.value?r.value.then(()=>{r.value=void 0,t(r)},i):t(r)}catch(e){i(e)}}function s(e=25){let t;return(i,s,n)=>{let a=performance.now();void 0===t||a-t>e?(t=a,setTimeout(()=>{r(i,s,n)},0)):r(i,s,n)}}function n(e,t,i,r,s){let n=()=>{let a;let o=e=>{e.done?i(e.value):void 0===a?a=!0:n()};do a=void 0,s&&s.aborted?r(Error("Aborted")):t(e,o,r),void 0===a&&(a=!1);while(a)};n()}function a(e,t){let i;return n(e,r,e=>i=e,e=>{throw e},t),i}function o(e,t,i){return new Promise((r,s)=>{n(e,t,r,s,i)})}function l(e,t){return(...i)=>a(e(...i),t)}i.d(t,{KO:function(){return s},WP:function(){return r},s3:function(){return a},sM:function(){return o},vp:function(){return l}})},1760:function(e,t,i){i.d(t,{G6:function(){return R},N$:function(){return T},QC:function(){return g},RR:function(){return x},VE:function(){return y},XX:function(){return S},hd:function(){return v},mv:function(){return C},n9:function(){return f},oQ:function(){return b},oU:function(){return _},p4:function(){return A},qC:function(){return p},qQ:function(){return m},rX:function(){return E},wz:function(){return d}});var r=i(1803),s=i(78),n=i(6131),a=i(2983);let o={},l={},h=function(e,t,i,s={}){let n=e();r.$&&r.$.HasTags(t)&&r.$.AddTagsTo(n,r.$.GetTags(t,!0));let a=u(n),o={};for(let e in a){let r=a[e],l=t[e],h=r.type;if(null!=l&&("uniqueId"!==e||A.AllowLoadingUniqueId))switch(h){case 0:case 6:case 11:n[e]=l;break;case 1:s.cloneTexturesOnlyOnce&&o[l.uniqueId]?n[e]=o[l.uniqueId]:(n[e]=i||l.isRenderTarget?l:l.clone(),o[l.uniqueId]=n[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[e]=i?l:l.clone()}}return n};function u(e){let t=e.getClassName();if(l[t])return l[t];l[t]={};let i=l[t],r=e,s=t;for(;s;){let e;let t=o[s];for(let e in t)i[e]=t[e];let n=!1;do{if(!(e=Object.getPrototypeOf(r)).getClassName){n=!0;break}if(e.getClassName()!==s)break;r=e}while(e);if(n)break;s=e.getClassName(),r=e}return i}function c(e,t){return(i,r)=>{let s=function(e){let t=e.getClassName();return o[t]||(o[t]={}),o[t]}(i);s[r]||(s[r]={type:e,sourceName:t})}}function d(e,t=null){return function(e,t=null){return(i,r)=>{let s=t||"_"+r;Object.defineProperty(i,r,{get:function(){return this[s]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[s]===t||(this[s]=t,i[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function p(e){return c(0,e)}function _(e){return c(1,e)}function f(e){return c(2,e)}function m(e){return c(3,e)}function g(e){return c(4,e)}function v(e){return c(5,e)}function x(e){return c(6,e)}function T(e){return c(7,e)}function S(e){return c(8,e)}function E(e){return c(9,e)}function C(e){return c(10,e)}function b(e){return c(12,e)}function y(e){return c(11,e)}class A{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let i=0;i{let n=s;if("undefined"!=typeof _native&&_native[t]){let e=_native[t];n=r?(...t)=>r(...t)?e(...t):s(...t):e}return e[t]=n,n(...i)}}A.AllowLoadingUniqueId=!1,A._ImageProcessingConfigurationParser=e=>{throw(0,n.S)("ImageProcessingConfiguration")},A._FresnelParametersParser=e=>{throw(0,n.S)("FresnelParameters")},A._ColorCurvesParser=e=>{throw(0,n.S)("ColorCurves")},A._TextureParser=(e,t,i)=>{throw(0,n.S)("Texture")},R.filter=function(e){return(t,i,r)=>R(t,i,r,e)}},3189:function(e,t,i){i.d(t,{j:function(){return n}});var r=i(9626);let s=(e,t,i)=>!e||e.getClassName&&"Mesh"===e.getClassName()?null:e.getClassName&&("SubMesh"===e.getClassName()||"PhysicsBody"===e.getClassName())?e.clone(t):e.clone?e.clone():Array.isArray(e)?e.slice():i&&"object"==typeof e?Object.assign({},e):null;class n{static DeepCopy(e,t,i,n,a=!1){for(let o of function(e){let t=[];do Object.getOwnPropertyNames(e).forEach(function(e){-1===t.indexOf(e)&&t.push(e)});while(e=Object.getPrototypeOf(e));return t}(e)){if("_"===o[0]&&(!n||-1===n.indexOf(o))||o.endsWith("Observable")||i&&-1!==i.indexOf(o))continue;let l=e[o],h=typeof l;if("function"!==h)try{if("object"===h){if(l instanceof Uint8Array)t[o]=Uint8Array.from(l);else if(l instanceof Array){if(t[o]=[],l.length>0){if("object"==typeof l[0])for(let e=0;e(e.__proto__=t,e));let s={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class n extends r{constructor(e,t,i){super(e),this.errorCode=t,this.innerError=i,this.name="RuntimeError",r._setPrototypeOf(this,n.prototype)}}},1166:function(e,t,i){let r;i.d(t,{$K:function(){return M},$M:function(){return E},FV:function(){return A},Ip:function(){return b},VL:function(){return P},r6:function(){return C},rN:function(){return T},vP:function(){return y}});var s=i(2962),n=i(7209),a=i(4800),o=i(320),l=i(9983),h=i(3477),u=i(9005),c=i(7790),d=i(6465),p=i(6030),_=i(9626),f=i(4490);let m=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class g extends h.LH{constructor(e,t){super(e,h.SM.LoadFileError),this.name="LoadFileError",h.GU._setPrototypeOf(this,g.prototype),t instanceof s.g?this.request=t:this.file=t}}class v extends h.LH{constructor(e,t){super(e,h.SM.RequestFileError),this.request=t,this.name="RequestFileError",h.GU._setPrototypeOf(this,v.prototype)}}class x extends h.LH{constructor(e,t){super(e,h.SM.ReadFileError),this.file=t,this.name="ReadFileError",h.GU._setPrototypeOf(this,x.prototype)}}let T={DefaultRetryStrategy:l.b.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e},S=e=>e=e.replace(/#/gm,"%23"),E=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&T.CorsBehavior){if("string"==typeof T.CorsBehavior||T.CorsBehavior instanceof String)t.crossOrigin=T.CorsBehavior;else{let i=T.CorsBehavior(e);i&&(t.crossOrigin=i)}}},C=(e,t,i,r,n="",a)=>{let l;let h=p.l.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!(null==h?void 0:h._features.forceBitmapOverHTMLImageElement))return i("LoadImage is only supported in web or BabylonNative environments."),null;let c=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(l=URL.createObjectURL(new Blob([e],{type:n})),c=!0):l=`data:${n};base64,`+(0,u.Gh)(e):e instanceof Blob?(l=URL.createObjectURL(e),c=!0):(l=S(e),l=T.PreprocessUrl(e));let d=t=>{if(i){let r=l||e.toString();i(`Error while trying to load image: ${0===r.indexOf("http")||r.length<=128?r:r.slice(0,128)+"..."}`,t)}};if(null==h?void 0:h._features.forceBitmapOverHTMLImageElement)return y(l,r=>{h.createImageBitmap(new Blob([r],{type:n}),Object.assign({premultiplyAlpha:"none"},a)).then(e=>{t(e),c&&URL.revokeObjectURL(l)}).catch(t=>{i&&i("Error while trying to load image: "+e,t)})},void 0,r||void 0,!0,(e,t)=>{d(t)}),null;let _=new Image;E(l,_);let f=[],m=()=>{f.forEach(e=>{e.target.removeEventListener(e.name,e.handler)}),f.length=0};f.push({target:_,name:"load",handler:()=>{m(),t(_),c&&_.src&&URL.revokeObjectURL(_.src)}}),f.push({target:_,name:"error",handler:e=>{m(),d(e),c&&_.src&&URL.revokeObjectURL(_.src)}}),f.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==_.src)return;m();let t=Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);p.l.UseFallbackTexture=!1,d(t),c&&_.src&&URL.revokeObjectURL(_.src),_.src=""}}),f.forEach(e=>{e.target.addEventListener(e.name,e.handler)});let g="blob:"===l.substring(0,5),v="data:"===l.substring(0,5),x=()=>{g||v||!s.g.IsCustomRequestAvailable?_.src=l:y(l,(e,t,i)=>{let r=!n&&i?i:n,s=new Blob([e],{type:r}),a=URL.createObjectURL(s);c=!0,_.src=a},void 0,r||void 0,!0,(e,t)=>{d(t)})};if(!g&&!v&&r&&r.enableTexturesOffline)r.open(()=>{r&&r.loadImage(l,_)},x);else{if(-1!==l.indexOf("file:")){let e=decodeURIComponent(l.substring(5).toLowerCase());if(o.X.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(o.X.FilesToLoad[e])}catch(i){t=URL.createObjectURL(o.X.FilesToLoad[e])}_.src=t,c=!0}catch(e){_.src=""}return _}}x()}return _},b=(e,t,i,r,s)=>{let n=new FileReader,o={onCompleteObservable:new a.y$,abort:()=>n.abort()};return n.onloadend=()=>o.onCompleteObservable.notifyObservers(o),s&&(n.onerror=()=>{s(new x(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},i&&(n.onprogress=i),r?n.readAsArrayBuffer(e):n.readAsText(e),o},y=(e,t,i,r,s,n,l)=>{if(e.name)return b(e,t,i,s,n?e=>{n(void 0,e)}:void 0);if(-1!==e.indexOf("file:")){let r=decodeURIComponent(e.substring(5).toLowerCase());0===r.indexOf("./")&&(r=r.substring(2));let a=o.X.FilesToLoad[r];if(a)return b(a,t,i,s,n?e=>n(void 0,new g(e.message,e.file)):void 0)}let{match:h,type:u}=I(e);if(h){let i={onCompleteObservable:new a.y$,abort:()=>()=>{}};try{let i=s?M(e):D(e);t(i,void 0,u)}catch(e){n?n(void 0,e):_.Y.Error(e.message||"Failed to parse the Data URL")}return f.Q.SetImmediate(()=>{i.onCompleteObservable.notifyObservers(i)}),i}return A(e,(e,i)=>{t(e,null==i?void 0:i.responseURL,null==i?void 0:i.getResponseHeader("content-type"))},i,r,s,n?e=>{n(e.request,new g(e.message,e.request))}:void 0,l)},A=(e,t,i,r,o,l,h)=>{e=S(e),e=T.PreprocessUrl(e);let u=T.BaseUrl+e,c=!1,d={onCompleteObservable:new a.y$,abort:()=>c=!0},p=()=>{let e,r=new s.g,a=null,p=()=>{r&&(i&&r.removeEventListener("progress",i),e&&r.removeEventListener("readystatechange",e),r.removeEventListener("loadend",f))},f=()=>{p(),d.onCompleteObservable.notifyObservers(d),d.onCompleteObservable.clear(),i=void 0,e=null,f=null,l=void 0,h=void 0,t=void 0};d.abort=()=>{c=!0,f&&f(),r&&r.readyState!==(XMLHttpRequest.DONE||4)&&r.abort(),null!==a&&(clearTimeout(a),a=null),r=null};let m=e=>{let t=e.message||"Unknown error";l&&r?l(new v(t,r)):_.Y.Error(t)},g=d=>{if(r){if(r.open("GET",u),h)try{h(r)}catch(e){m(e);return}o&&(r.responseType="arraybuffer"),i&&r.addEventListener("progress",i),f&&r.addEventListener("loadend",f),e=()=>{if(!c&&r&&r.readyState===(XMLHttpRequest.DONE||4)){if(e&&r.removeEventListener("readystatechange",e),r.status>=200&&r.status<300||0===r.status&&(!(0,n.CG)()||R())){try{t&&t(o?r.response:r.responseText,r)}catch(e){m(e)}return}let i=T.DefaultRetryStrategy;if(i){let e=i(u,r,d);if(-1!==e){p(),r=new s.g,a=setTimeout(()=>g(d+1),e);return}}let h=new v("Error status: "+r.status+" "+r.statusText+" - Unable to load "+u,r);l&&l(h)}},r.addEventListener("readystatechange",e),r.send()}};g(0)};if(r&&r.enableSceneOffline){let s=e=>{e&&e.status>400?l&&l(e):p()};r.open(()=>{r&&r.loadFile(T.BaseUrl+e,e=>{!c&&t&&t(e),d.onCompleteObservable.notifyObservers(d)},i?e=>{!c&&i&&i(e)}:void 0,s,o)},s)}else p();return d},R=()=>"undefined"!=typeof location&&"file:"===location.protocol,P=e=>m.test(e),I=e=>{let t=m.exec(e);return null===t||0===t.length?{match:!1,type:""}:{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function M(e){return(0,u.HQ)(e.split(",")[1])}let D=e=>(0,u.rP)(e.split(",")[1]);d.B._FileToolsLoadImage=C,d.B._FileToolsLoadFile=y,c.L._FileToolsLoadFile=y,Object.defineProperty(r={DecodeBase64UrlToBinary:M,DecodeBase64UrlToString:D,DefaultRetryStrategy:T.DefaultRetryStrategy,BaseUrl:T.BaseUrl,CorsBehavior:T.CorsBehavior,PreprocessUrl:T.PreprocessUrl,IsBase64DataUrl:P,IsFileURL:R,LoadFile:y,LoadImage:C,ReadFile:b,RequestFile:A,SetCorsBehavior:E},"DefaultRetryStrategy",{get:function(){return T.DefaultRetryStrategy},set:function(e){T.DefaultRetryStrategy=e}}),Object.defineProperty(r,"BaseUrl",{get:function(){return T.BaseUrl},set:function(e){T.BaseUrl=e}}),Object.defineProperty(r,"PreprocessUrl",{get:function(){return T.PreprocessUrl},set:function(e){T.PreprocessUrl=e}}),Object.defineProperty(r,"CorsBehavior",{get:function(){return T.CorsBehavior},set:function(e){T.CorsBehavior=e}})},320:function(e,t,i){i.d(t,{X:function(){return r}});class r{}r.FilesToLoad={}},1032:function(e,t,i){i.d(t,{f:function(){return r}});function r(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}},4406:function(e,t,i){i.d(t,{K:function(){return n}});var r=i(9626),s=i(3048);class n{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];let t=(0,s.q)(e);if(t)return t;r.Y.Warn(e+" not found, you may have missed an import.");let i=e.split("."),n=window||this;for(let e=0,t=i.length;ee<10?"0"+e:""+e,i=new Date;return"["+t(i.getHours())+":"+t(i.getMinutes())+":"+t(i.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,i){let s=Array.isArray(t)?t[0]:t;if(void 0!==i&&!r._CheckLimit(s,i))return;let n=r._FormatMessage(s),a=this._Levels[e],o=Array.isArray(t)?t.slice(1):[];a.logFunc&&a.logFunc("BJS - "+n,...o);let l=`
${n}

`;r._AddLogEntry(l),r._GenerateLimitMessage(s,e)}static get LogCache(){return r._LogCache}static ClearLogCache(){r._LogCache="",r._LogLimitOutputs={},r.errorsCount=0}static set LogLevels(e){r.Log=r._LogDisabled,r.Warn=r._LogDisabled,r.Error=r._LogDisabled,[r.MessageLogLevel,r.WarningLogLevel,r.ErrorLogLevel].forEach(t=>{(e&t)===t&&(r[this._Levels[t].name]=r._LogEnabled.bind(r,t))})}}r.NoneLogLevel=0,r.MessageLogLevel=1,r.WarningLogLevel=2,r.ErrorLogLevel=4,r.AllLogLevel=7,r.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",r._LogCache="",r._LogLimitOutputs={},r._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],r.errorsCount=0,r.Log=r._LogEnabled.bind(r,r.MessageLogLevel),r.Warn=r._LogEnabled.bind(r,r.WarningLogLevel),r.Error=r._LogEnabled.bind(r,r.ErrorLogLevel)},4800:function(e,t,i){i.d(t,{he:function(){return r},y$:function(){return n}});class r{constructor(e,t=!1,i,r){this.initialize(e,t,i,r)}initialize(e,t=!1,i,r){return this.mask=e,this.skipNextObservers=t,this.target=i,this.currentTarget=r,this}}class s{constructor(e,t,i=null){this.callback=e,this.mask=t,this.scope=i,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class n{static FromPromise(e,t){let i=new n;return e.then(e=>{i.notifyObservers(e)}).catch(e=>{if(t)t.notifyObservers(e);else throw e}),i}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=[],this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new r(0),e&&(this._onObserverAdded=e)}add(e,t=-1,i=!1,r=null,n=!1){if(!e)return null;let a=new s(e,t,r);return a.unregisterOnNextCall=n,i?this._observers.unshift(a):this._observers.push(a),this._onObserverAdded&&this._onObserverAdded(a),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(a,this._lastNotifiedValue),a._remove=()=>{this.remove(a)},a}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){return!!e&&(e._remove=null,-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0))}removeCallback(e,t){for(let i=0;i{this._remove(e)},0))}_remove(e,t=!0){if(!e)return!1;let i=this._observers.indexOf(e);return -1!==i&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(i,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,i,r,s){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;let n=this._eventState;for(let a of(n.mask=t,n.target=i,n.currentTarget=r,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=s,this._observers))if(!a._willBeUnregistered&&(a.mask&t&&(a.unregisterOnNextCall&&this._deferUnregister(a),a.scope?n.lastReturnValue=a.callback.apply(a.scope,[e,n]):n.lastReturnValue=a.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,i=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;let r=this._eventState;r.mask=i,r.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,r)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){let 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(){let e=new n;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(let t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}},7263:function(e,t,i){i.d(t,{z:function(){return s}});var r=i(7662);class s{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){s.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){s.Enabled&&(this._startMonitoringTime=r.F.Now)}endMonitoring(e=!0){if(!s.Enabled)return;e&&this.fetchNewFrame();let t=r.F.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;let e=r.F.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}s.Enabled=!0},8786:function(e,t,i){i.d(t,{A:function(){return s}});var r=i(7662);class s{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new n(e)}sampleFrame(e=r.F.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){let 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(){let 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 n{constructor(e){this._samples=Array(e),this.reset()}add(e){let t;if(this.isSaturated()){let 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;let 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){let t=this._samples.length;return(e%t+t)%t}}},7662:function(e,t,i){i.d(t,{F:function(){return s}});var r=i(7209);class s{static get Now(){return(0,r.CG)()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}},9983:function(e,t,i){i.d(t,{b:function(){return r}});class r{static ExponentialBackoff(e=3,t=500){return(i,r,s)=>0!==r.status||s>=e||-1!==i.indexOf("file:")?-1:Math.pow(2,s)*t}}},8355:function(e,t,i){i.d(t,{f:function(){return s},t:function(){return r}});class r{constructor(e){this.length=0,this.data=Array(e),this._id=r._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;tthis.data.length&&(this.data.length=(this.length+e.length)*2);for(let t=0;t=this.length?-1:t}contains(e){return -1!==this.indexOf(e)}}r._GlobalId=0;class s extends r{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=(this.length+e.length)*2);for(let t=0;tthis.add(e,t))}get(e){let t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let i=this.get(e);return void 0!==i||(i=t(e))&&this.add(e,i),i}getOrAdd(e,t){let i=this.get(e);return void 0!==i?i:(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){let 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(let t in this._data){let i=this._data[t];e(t,i)}}first(e){for(let t in this._data){let i=this._data[t],r=e(t,i);if(r)return r}return null}}},9005:function(e,t,i){i.d(t,{Gh:function(){return r},HQ:function(){return n},rP:function(){return s}});let r=e=>{let t,i,r,s,n,a,o;let l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h="",u=0,c=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;u>2,n=(3&t)<<4|i>>4,a=(15&i)<<2|r>>6,o=63&r,isNaN(i)?a=o=64:isNaN(r)&&(o=64),h+=l.charAt(s)+l.charAt(n)+l.charAt(a)+l.charAt(o);return h},s=e=>atob(e),n=e=>{let t=s(e),i=t.length,r=new Uint8Array(new ArrayBuffer(i));for(let e=0;es.HasTags(e),e.addTags=t=>s.AddTagsTo(e,t),e.removeTags=t=>s.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>s.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;let t=e._tags;for(let 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)return e._tags;{let t=[];for(let i in e._tags)Object.prototype.hasOwnProperty.call(e._tags,i)&&!0===e._tags[i]&&t.push(i);return t.join(" ")}}static AddTagsTo(e,t){t&&"string"==typeof t&&t.split(" ").forEach(function(t){s._AddTagTo(e,t)})}static _AddTagTo(e,t){""===(t=t.trim())||"true"===t||"false"===t||t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(s.EnableFor(e),e._tags[t]=!0)}static RemoveTagsFrom(e,t){if(!s.HasTags(e))return;let i=t.split(" ");for(let t in i)s._RemoveTagFrom(e,i[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?s.HasTags(e):r.q.Eval(t,t=>s.HasTags(e)&&e._tags[t]))}}},4490:function(e,t,i){i.d(t,{Q:function(){return s}});var r=i(7209);class s{static SetImmediate(e){(0,r.CG)()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}},5132:function(e,t,i){i.d(t,{$g:function(){return m},w1:function(){return f}});var r=i(4800),s=i(7209),n=i(9626),a=i(3189),o=i(7662),l=i(6131),h=i(2962),u=i(6030),c=i(1166),d=i(4490),p=i(4406),_=i(1032);class f{static get BaseUrl(){return c.rN.BaseUrl}static set BaseUrl(e){c.rN.BaseUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||!(-1===e.indexOf("://")||-1===e.indexOf(".")||-1===e.indexOf("/")||e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://"){(0,c.vP)(e,e=>{i(e)},void 0,void 0,t,(e,t)=>{r(t)})})}static GetBabylonScriptURL(e,t){if(!e)return"";if(f.ScriptBaseUrl&&e.startsWith(f._DefaultCdnUrl)){let t="/"===f.ScriptBaseUrl[f.ScriptBaseUrl.length-1]?f.ScriptBaseUrl.substring(0,f.ScriptBaseUrl.length-1):f.ScriptBaseUrl;e=e.replace(f._DefaultCdnUrl,t)}return e=f.ScriptPreprocessUrl(e),t&&(e=f.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,i,r){e=f.GetBabylonScriptURL(e),f.LoadScript(e,t,i)}static LoadBabylonScriptAsync(e){return e=f.GetBabylonScriptURL(e),f.LoadScriptAsync(e)}static LoadScript(e,t,i,r){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){null==i||i(`Unable to load script '${e}' in worker`,t)}return}if(!(0,s.CG)()){null==i||i(`Cannot load script '${e}' outside of a window or a worker`);return}let n=document.getElementsByTagName("head")[0],a=document.createElement("script");a.setAttribute("type","text/javascript"),a.setAttribute("src",e),r&&(a.id=r),a.onload=()=>{t&&t()},a.onerror=t=>{i&&i(`Unable to load script '${e}'`,t)},n.appendChild(a)}static LoadScriptAsync(e){return new Promise((t,i)=>{this.LoadScript(e,()=>{t()},(e,t)=>{i(t||Error(e))})})}static ReadFileAsDataURL(e,t,i){let s=new FileReader,n={onCompleteObservable:new r.y$,abort:()=>s.abort()};return s.onloadend=()=>{n.onCompleteObservable.notifyObservers(n)},s.onload=e=>{t(e.target.result)},s.onprogress=i,s.readAsDataURL(e),n}static ReadFile(e,t,i,r,s){return(0,c.Ip)(e,t,i,r,s)}static FileAsURL(e){let t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,i,r){a.j.DeepCopy(e,t,i,r)}static IsEmpty(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let i=0;i{let r=atob(this.toDataURL(t,i).split(",")[1]),s=r.length,n=new Uint8Array(s);for(let e=0;et(e)):e.toBlob(function(e){t(e)},i,r)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){let e=new Date;t="screenshot_"+((e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours())+"-"+("0"+e.getMinutes()).slice(-2)+".png"}f.Download(e,t)}else if(e&&"undefined"!=typeof URL){let t=URL.createObjectURL(e),i=window.open("");if(!i)return;let r=i.document.createElement("img");r.onload=function(){URL.revokeObjectURL(t)},r.src=t,i.document.body.appendChild(r)}}static EncodeScreenshotCanvasData(e,t,i="image/png",r,s){if("string"!=typeof r&&t){if(t){if(f._IsOffScreenCanvas(e)){e.convertToBlob({type:i,quality:s}).then(e=>{let i=new FileReader;i.readAsDataURL(e),i.onloadend=()=>{t(i.result)}});return}t(e.toDataURL(i,s))}}else this.ToBlob(e,function(e){e&&f.DownloadBlob(e,r),t&&t("")},i,s)}static Download(e,t){if("undefined"==typeof URL)return;let i=window.URL.createObjectURL(e),r=document.createElement("a");document.body.appendChild(r),r.style.display="none",r.href=i,r.download=t,r.addEventListener("click",()=>{r.parentElement&&r.parentElement.removeChild(r)}),r.click(),window.URL.revokeObjectURL(i)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,i,r,s="image/png",n=!1,a){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotAsync(e,t,i,r="image/png",s){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,i,r,s="image/png",n=1,a=!1,o,h=!1,u=!1,c=!0,d){throw(0,l.S)("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,i,r="image/png",s=1,n=!1,a,o=!1,h=!1,u=!0,c){throw(0,l.S)("ScreenshotTools")}static RandomId(){return(0,_.f)()}static IsBase64(e){return(0,c.VL)(e)}static DecodeBase64(e){return(0,c.$K)(e)}static get errorsCount(){return n.Y.errorsCount}static Log(e){n.Y.Log(e)}static Warn(e){n.Y.Warn(e)}static Error(e){n.Y.Error(e)}static get LogCache(){return n.Y.LogCache}static ClearLogCache(){n.Y.ClearLogCache()}static set LogLevels(e){n.Y.LogLevels=e}static set PerformanceLogLevel(e){if((e&f.PerformanceUserMarkLogLevel)===f.PerformanceUserMarkLogLevel){f.StartPerformanceCounter=f._StartUserMark,f.EndPerformanceCounter=f._EndUserMark;return}if((e&f.PerformanceConsoleLogLevel)===f.PerformanceConsoleLogLevel){f.StartPerformanceCounter=f._StartPerformanceConsole,f.EndPerformanceCounter=f._EndPerformanceConsole;return}f.StartPerformanceCounter=f._StartPerformanceCounterDisabled,f.EndPerformanceCounter=f._EndPerformanceCounterDisabled}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!f._Performance){if(!(0,s.CG)())return;f._Performance=window.performance}t&&f._Performance.mark&&f._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&f._Performance.mark&&(f._Performance.mark(e+"-End"),f._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(f._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(f._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return o.F.Now}static GetClassName(e,t=!1){let i=null;return!t&&e.getClassName?i=e.getClassName():(e instanceof Object&&(i=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__),i||(i=typeof e)),i}static First(e,t){for(let i of e)if(t(i))return i;return null}static getFullClassName(e,t=!1){let i=null,r=null;if(!t&&e.getClassName)i=e.getClassName();else{if(e instanceof Object){let s=t?e:Object.getPrototypeOf(e);i=s.constructor.__bjsclassName__,r=s.constructor.__bjsmoduleName__}i||(i=typeof e)}return i?(null!=r?r+".":"")+i:null}static DelayAsync(e){return new Promise(t=>{setTimeout(()=>{t()},e)})}static IsSafari(){return!!(0,s.up)()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}f.UseCustomRequestHeaders=!1,f.CustomRequestHeaders=h.g.CustomRequestHeaders,f.GetDOMTextContent=s.v,f._DefaultCdnUrl="https://cdn.babylonjs.com",f.GetAbsoluteUrl="object"==typeof document?e=>{let t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},f.NoneLogLevel=n.Y.NoneLogLevel,f.MessageLogLevel=n.Y.MessageLogLevel,f.WarningLogLevel=n.Y.WarningLogLevel,f.ErrorLogLevel=n.Y.ErrorLogLevel,f.AllLogLevel=n.Y.AllLogLevel,f.IsWindowObjectExist=s.CG,f.PerformanceNoneLogLevel=0,f.PerformanceUserMarkLogLevel=1,f.PerformanceConsoleLogLevel=2,f.StartPerformanceCounter=f._StartPerformanceCounterDisabled,f.EndPerformanceCounter=f._EndPerformanceCounterDisabled;class m{constructor(e,t,i,r=0){this.iterations=e,this.index=r-1,this._done=!1,this._fn=t,this._successCallback=i}executeNext(){this._done||(this.index+1{s&&s()?r.breakLoop():setTimeout(()=>{for(let n=0;n=e)break;if(i(a),s&&s()){r.breakLoop();break}}r.executeNext()},n)},r)}}u.l.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"},3048:function(e,t,i){i.d(t,{H:function(){return s},q:function(){return n}});let r={};function s(e,t){r[e]=t}function n(e){return r[e]}},7531:function(e,t,i){i.d(t,{K:function(){return r}});class r{static get UniqueId(){let e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}r._UniqueIdCounter=1},2962:function(e,t,i){i.d(t,{g:function(){return r}});class r{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(r.CustomRequestHeaders).length>0||r.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(let e in r.CustomRequestHeaders){let t=r.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return r.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,i){this._xhr.addEventListener(e,t,i)}removeEventListener(e,t,i){this._xhr.removeEventListener(e,t,i)}abort(){this._xhr.abort()}send(e){r.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(let e of r.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}return 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)}}r.CustomRequestHeaders={},r.CustomRequestModifiers=[],r.SkipRequestModificationForBabylonCDN=!0},5184:function(e,t,i){i.d(t,{O:function(){return s}});var r=i(1295);class s{constructor(e){this._vertexBuffers={},this._scene=e}_prepareBuffers(){if(this._vertexBuffers[r.o.PositionKind])return;let e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[r.o.PositionKind]=new r.o(this._scene.getEngine(),e,r.o.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){let 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(){let e=this._vertexBuffers[r.o.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){let i=this._scene.activeCamera;return!!(i&&(t=t||i._postProcesses.filter(e=>null!=e))&&0!==t.length&&this._scene.postProcessesEnabled)&&(t[0].activate(i,e,null!=t),!0)}directRender(e,t=null,i=!1,r=0,s=0,n=!1){var a;let o=this._scene.getEngine();for(let l=0;lnull!=e)).length||!this._scene.postProcessesEnabled)return;let o=this._scene.getEngine();for(let l=0,h=r.length;lt._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamerat._distanceToCamera?1:0}static PainterSortCompare(e,t){let i=e.getMesh(),r=t.getMesh();return i.material&&r.material?i.material.uniqueId-r.material.uniqueId:i.uniqueId-r.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,i){void 0===t&&(t=e.getMesh()),void 0===i&&(i=e.getMaterial()),null!=i&&(i.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):i.needAlphaTesting()?(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(i.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&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;let t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let i=0;ie=e.concat(t.bones)),e}}r._BabylonFileParsers={},r._IndividualBabylonFileParsers={}},4672:function(e,t,i){let r,s;i.d(t,{YfP:function(){return a2},HEv:function(){return rm.HE},Dso:function(){return nz},xsS:function(){return r2.x},xeF:function(){return nG.x},vGS:function(){return nw.v},w1W:function(){return sg.w1},Pa4:function(){return rf.P},fWK:function(){return da}});var n,a,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,E,C,b,y,A,R,P,I,M,D,O,N,F,L,w,B,U,V,k,G,z,W,H,X,Y,j,q,K,$,Q,Z,J,ee,et,ei,er,es,en,ea,eo,el,eh,eu,ec,ed,ep,e_,ef,em,eg,ev,ex,eT,eS,eE,eC,eb,ey,eA,eR,eP,eI,eM,eD,eO,eN,eF,eL,ew,eB,eU,eV,ek,eG,ez,eW,eH,eX,eY,ej,eq,eK,e$,eQ,eZ,eJ,e0,e1,e2,e3,e4,e5,e6,e8,e7,e9,te,tt,ti,tr,ts,tn,ta,to,tl,th,tu,tc,td,tp,t_,tf,tm,tg,tv,tx,tT,tS,tE,tC,tb,ty,tA,tR,tP,tI,tM,tD,tO,tN,tF,tL,tw,tB,tU,tV,tk,tG,tz,tW,tH,tX,tY,tj,tq,tK,t$,tQ,tZ,tJ,t0,t1,t2,t3,t4,t5,t6,t8,t7,t9,ie,it,ii,ir,is,ia,io,il,ih,iu,ic,id,ip,i_,im,ig,iv,ix,iT,iS,iE,iC,ib,iy,iA,iR,iP,iI,iM,iD,iO,iN,iF,iL,iw,iB,iU,iV,ik,iG,iz,iW,iH,iX,iY,ij,iq,iK,i$,iQ,iZ,iJ,i0,i1,i2,i3,i4,i5,i6,i8,i7,i9,re,rt,ri,rr,rs,rn,ra,ro,rl,rh,ru,rc,rd=i(800),rp=i(3621),r_=i(4800),rf=i(78),rm=i(2983),rg=i(3048);class rv{constructor(e,t){this.triggerOptions=e,this.onBeforeExecuteObservable=new r_.y$,e.parameter?(this.trigger=e.trigger,this._triggerParameter=e.parameter):e.trigger?this.trigger=e.trigger:this.trigger=e,this._nextActiveAction=this,this._condition=t}_prepare(){}getTriggerParameter(){return this._triggerParameter}setTriggerParameter(e){this._triggerParameter=e}_evaluateConditionForCurrentFrame(){let e=this._condition;if(!e)return!0;let t=this._actionManager.getScene().getRenderId();return e._evaluationId!==t&&(e._evaluationId=t,e._currentResult=e.isValid()),e._currentResult}_executeCurrent(e){this._evaluateConditionForCurrentFrame()&&(this.onBeforeExecuteObservable.notifyObservers(this),this._nextActiveAction.execute(e),this.skipToNextActiveAction())}execute(e){}skipToNextActiveAction(){this._nextActiveAction._child?(this._nextActiveAction._child._actionManager||(this._nextActiveAction._child._actionManager=this._actionManager),this._nextActiveAction=this._nextActiveAction._child):this._nextActiveAction=this}then(e){return this._child=e,e._actionManager=this._actionManager,e._prepare(),e}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(e){}_serialize(e,t){let i={type:1,children:[],name:e.name,properties:e.properties||[]};if(this._child&&this._child.serialize(i),this._condition){let e=this._condition.serialize();return e.children.push(i),t&&t.children.push(e),e}return t&&t.children.push(i),i}}rv._SerializeValueAsString=e=>"number"==typeof e?e.toString():"boolean"==typeof e?e?"true":"false":e instanceof rf.FM?e.x+", "+e.y:e instanceof rf.P?e.x+", "+e.y+", "+e.z:e instanceof rm.Wo?e.r+", "+e.g+", "+e.b:e instanceof rm.HE?e.r+", "+e.g+", "+e.b+", "+e.a:e,rv._GetTargetProperty=e=>({name:"target",targetType:e._isMesh?"MeshProperties":e._isLight?"LightProperties":e._isCamera?"CameraProperties":e._isMaterial?"MaterialProperties":"SceneProperties",value:e._isScene?"Scene":e.name}),(0,rg.H)("BABYLON.Action",rv);var rx=i(9528);class rT{constructor(e){this._actionManager=e}isValid(){return!0}_getProperty(e){return this._actionManager._getProperty(e)}_getEffectiveTarget(e,t){return this._actionManager._getEffectiveTarget(e,t)}serialize(){}_serialize(e){return{type:2,children:[],name:e.name,properties:e.properties}}}class rS extends rT{static get IsEqual(){return rS._IsEqual}static get IsDifferent(){return rS._IsDifferent}static get IsGreater(){return rS._IsGreater}static get IsLesser(){return rS._IsLesser}constructor(e,t,i,r,s=rS.IsEqual){super(e),this.propertyPath=i,this.value=r,this.operator=s,this._target=t,this._effectiveTarget=this._getEffectiveTarget(t,this.propertyPath),this._property=this._getProperty(this.propertyPath)}isValid(){switch(this.operator){case rS.IsGreater:return this._effectiveTarget[this._property]>this.value;case rS.IsLesser:return this._effectiveTarget[this._property]-1&&this._scene.actionManagers.splice(e,1),this._scene.meshes.filter(e=>e.actionManager===this)))t.actionManager=null}getScene(){return this._scene}hasSpecificTriggers(e){for(let t=0;t-1)return!0}return!1}hasSpecificTriggers2(e,t){for(let i=0;i=rB.OnPickTrigger&&t.trigger<=rB.OnPointerOutTrigger)return!0}return!1}get hasPickTriggers(){for(let e=0;e=rB.OnPickTrigger&&t.trigger<=rB.OnPickUpTrigger)return!0}return!1}registerAction(e){return e.trigger===rB.OnEveryFrameTrigger&&this.getScene().actionManager!==this?(rb.Y.Warn("OnEveryFrameTrigger can only be used with scene.actionManager"),null):(this.actions.push(e),this.getScene()._registeredActions++,rB.Triggers[e.trigger]?rB.Triggers[e.trigger]++:rB.Triggers[e.trigger]=1,e._actionManager=this,e._prepare(),e)}unregisterAction(e){let t=this.actions.indexOf(e);return -1!==t&&(this.actions.splice(t,1),rB.Triggers[e.trigger]-=1,0===rB.Triggers[e.trigger]&&delete rB.Triggers[e.trigger],e._actionManager=null,this.getScene()._registeredActions--,!0)}processTrigger(e,t){for(let i=0;i{let i=(0,rg.q)("BABYLON."+e);return i&&new i(...t)},n=(e,t,i,r)=>{if(null===r){let e=parseFloat(t);return"true"===t||"false"===t?"true"===t:isNaN(e)?t:e}let s=r.split("."),n=t.split(",");for(let e=0;e{if(e.detached)return;let u=[],c=null,d=null,p=e.combine&&e.combine.length>0;if(2===e.type?u.push(r):u.push(t),p){let t=[];for(let i=0;i0){let e=s.properties[0].value,t=null===s.properties[0].targetType?e:i.getMeshByName(e);t._meshId&&(t.mesh=i.getMeshById(t._meshId)),r={trigger:rB[s.name],parameter:t}}else r=rB[s.name];for(let e=0;e=0?o.referenceFrame:0,u=0,c=l._keys[0],d=l._keys.length-1,p=l._keys[d],_={referenceValue:c.value,referencePosition:rf.jp.Vector3[0],referenceQuaternion:rf.jp.Quaternion[0],referenceScaling:rf.jp.Vector3[1],keyPosition:rf.jp.Vector3[2],keyQuaternion:rf.jp.Quaternion[1],keyScaling:rf.jp.Vector3[3]},f=c.frame,m=p.frame;if(o.range){let e=l.getRange(o.range);e&&(f=e.from,m=e.to)}else f=null!==(n=o.fromFrame)&&void 0!==n?n:f,m=null!==(a=o.toFrame)&&void 0!==a?a:m;if(f!==c.frame&&(u=l.createKeyForFrame(f)),m!==p.frame&&(d=l.createKeyForFrame(m)),1===l._keys.length){let e=l._getKeyValue(l._keys[0]);_.referenceValue=e.clone?e.clone():e}else if(h<=c.frame){let e=l._getKeyValue(c.value);_.referenceValue=e.clone?e.clone():e}else if(h>=p.frame){let e=l._getKeyValue(p.value);_.referenceValue=e.clone?e.clone():e}else{rZ.key=0;let e=l._interpolate(h,rZ);_.referenceValue=e.clone?e.clone():e}l.dataType===rJ.ANIMATIONTYPE_QUATERNION?_.referenceValue.normalize().conjugateInPlace():l.dataType===rJ.ANIMATIONTYPE_MATRIX&&(_.referenceValue.decompose(_.referenceScaling,_.referenceQuaternion,_.referencePosition),_.referenceQuaternion.normalize().conjugateInPlace());let g=Number.MAX_VALUE,v=o.clipKeys?[]:null;for(let e=u;e<=d;e++){let t=l._keys[e];if(v&&(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},g===Number.MAX_VALUE&&(g=t.frame),t.frame-=g,v.push(t)),!e||l.dataType===rJ.ANIMATIONTYPE_FLOAT||t.value!==c.value)switch(l.dataType){case rJ.ANIMATIONTYPE_MATRIX:t.value.decompose(_.keyScaling,_.keyQuaternion,_.keyPosition),_.keyPosition.subtractInPlace(_.referencePosition),_.keyScaling.divideInPlace(_.referenceScaling),_.referenceQuaternion.multiplyToRef(_.keyQuaternion,_.keyQuaternion),rf.y3.ComposeToRef(_.keyScaling,_.keyQuaternion,_.keyPosition,t.value);break;case rJ.ANIMATIONTYPE_QUATERNION:_.referenceValue.multiplyToRef(t.value,t.value);break;case rJ.ANIMATIONTYPE_VECTOR2:case rJ.ANIMATIONTYPE_VECTOR3:case rJ.ANIMATIONTYPE_COLOR3:case rJ.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(_.referenceValue,t.value);break;case rJ.ANIMATIONTYPE_SIZE:t.value.width-=_.referenceValue.width,t.value.height-=_.referenceValue.height;break;default:t.value-=_.referenceValue}}return v&&l.setKeys(v,!0),l}static TransitionTo(e,t,i,r,s,n,a,o=null){if(a<=0)return i[e]=t,o&&o(),null;let l=a/1e3*s;n.setKeys([{frame:0,value:i[e].clone?i[e].clone():i[e]},{frame:l,value:t}]),i.animations||(i.animations=[]),i.animations.push(n);let h=r.beginAnimation(i,0,l,!1);return h.onAnimationEnd=o,h}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(let e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,i,r,s,n){this.name=e,this.targetProperty=t,this.framePerSecond=i,this.dataType=r,this.loopMode=s,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=[],this._events=[],this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=r,this.loopMode=void 0===s?rJ.ANIMATIONLOOPMODE_CYCLE:s,this.uniqueId=rJ._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType]+", nKeys: "+(this._keys?this._keys.length:"none")+", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;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=0;i--)this._keys[i].frame>=e&&this._keys[i].frame<=t&&this._keys.splice(i,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,i=this._keys.length;t0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;let s=this._keys,n=s.length,a=t.key;for(;a>=0&&e=s[a+1].frame;)++a;if(t.key=a,a<0)return i?void 0:this._getKeyValue(s[0].value);if(a+1>n-1)return i?void 0:this._getKeyValue(s[n-1].value);let o=s[a],l=s[a+1];if(i&&(e===o.frame||e===l.frame))return;let h=this._getKeyValue(o.value),u=this._getKeyValue(l.value);if(o.interpolation===tc.STEP)return l.frame>e?h:u;let c=void 0!==o.outTangent&&void 0!==l.inTangent,d=l.frame-o.frame,p=(e-o.frame)/d,_=o.easingFunction||this.getEasingFunction();switch(null!==_&&(p=_.ease(p)),this.dataType){case rJ.ANIMATIONTYPE_FLOAT:{let e=c?this.floatInterpolateFunctionWithTangents(h,o.outTangent*d,u,l.inTangent*d,p):this.floatInterpolateFunction(h,u,p);switch(t.loopMode){case rJ.ANIMATIONLOOPMODE_CYCLE:case rJ.ANIMATIONLOOPMODE_CONSTANT:case rJ.ANIMATIONLOOPMODE_YOYO:return e;case rJ.ANIMATIONLOOPMODE_RELATIVE:case rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(null!==(r=t.offsetValue)&&void 0!==r?r:0)*t.repeatCount+e}break}case rJ.ANIMATIONTYPE_QUATERNION:{let e=c?this.quaternionInterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.quaternionInterpolateFunction(h,u,p);switch(t.loopMode){case rJ.ANIMATIONLOOPMODE_CYCLE:case rJ.ANIMATIONLOOPMODE_CONSTANT:case rJ.ANIMATIONLOOPMODE_YOYO:break;case rJ.ANIMATIONLOOPMODE_RELATIVE:case rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||rY).scale(t.repeatCount))}return e}case rJ.ANIMATIONTYPE_VECTOR3:{let e=c?this.vector3InterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.vector3InterpolateFunction(h,u,p);switch(t.loopMode){case rJ.ANIMATIONLOOPMODE_CYCLE:case rJ.ANIMATIONLOOPMODE_CONSTANT:case rJ.ANIMATIONLOOPMODE_YOYO:return e;case rJ.ANIMATIONLOOPMODE_RELATIVE:case rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||rj).scale(t.repeatCount))}break}case rJ.ANIMATIONTYPE_VECTOR2:{let e=c?this.vector2InterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.vector2InterpolateFunction(h,u,p);switch(t.loopMode){case rJ.ANIMATIONLOOPMODE_CYCLE:case rJ.ANIMATIONLOOPMODE_CONSTANT:case rJ.ANIMATIONLOOPMODE_YOYO:return e;case rJ.ANIMATIONLOOPMODE_RELATIVE:case rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||rq).scale(t.repeatCount))}break}case rJ.ANIMATIONTYPE_SIZE:switch(t.loopMode){case rJ.ANIMATIONLOOPMODE_CYCLE:case rJ.ANIMATIONLOOPMODE_CONSTANT:case rJ.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(h,u,p);case rJ.ANIMATIONLOOPMODE_RELATIVE:case rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(h,u,p).add((t.offsetValue||rK).scale(t.repeatCount))}break;case rJ.ANIMATIONTYPE_COLOR3:{let e=c?this.color3InterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.color3InterpolateFunction(h,u,p);switch(t.loopMode){case rJ.ANIMATIONLOOPMODE_CYCLE:case rJ.ANIMATIONLOOPMODE_CONSTANT:case rJ.ANIMATIONLOOPMODE_YOYO:return e;case rJ.ANIMATIONLOOPMODE_RELATIVE:case rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||r$).scale(t.repeatCount))}break}case rJ.ANIMATIONTYPE_COLOR4:{let e=c?this.color4InterpolateFunctionWithTangents(h,o.outTangent.scale(d),u,l.inTangent.scale(d),p):this.color4InterpolateFunction(h,u,p);switch(t.loopMode){case rJ.ANIMATIONLOOPMODE_CYCLE:case rJ.ANIMATIONLOOPMODE_CONSTANT:case rJ.ANIMATIONLOOPMODE_YOYO:return e;case rJ.ANIMATIONLOOPMODE_RELATIVE:case rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||rQ).scale(t.repeatCount))}break}case rJ.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case rJ.ANIMATIONLOOPMODE_CYCLE:case rJ.ANIMATIONLOOPMODE_CONSTANT:case rJ.ANIMATIONLOOPMODE_YOYO:if(rJ.AllowMatricesInterpolation)return this.matrixInterpolateFunction(h,u,p,t.workValue);return h;case rJ.ANIMATIONLOOPMODE_RELATIVE:case rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return h}}return 0}matrixInterpolateFunction(e,t,i,r){return rJ.AllowMatrixDecomposeForInterpolation?r?(rf.y3.DecomposeLerpToRef(e,t,i,r),r):rf.y3.DecomposeLerp(e,t,i):r?(rf.y3.LerpToRef(e,t,i,r),r):rf.y3.Lerp(e,t,i)}clone(){let e=new rJ(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)for(let t in e._ranges={},this._ranges){let i=this._ranges[t];i&&(e._ranges[t]=i.clone())}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){rZ.key=0;let t=this._interpolate(e,rZ,!0);if(!t)return this._keys[rZ.key].frame===e?rZ.key:rZ.key+1;let i={frame:e,value:t.clone?t.clone():t};return this._keys.splice(rZ.key+1,0,i),rZ.key+1}serialize(){let 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;let t=this.dataType;e.keys=[];let i=this.getKeys();for(let r=0;r=2&&(r=l.values[1]),l.values.length>=3&&(a=l.values[2]),l.values.length>=4&&(o=l.values[3]);break;case rJ.ANIMATIONTYPE_QUATERNION:if(t=rf._f.FromArray(l.values),l.values.length>=8){let e=rf._f.FromArray(l.values.slice(4,8));e.equals(rf._f.Zero())||(r=e)}if(l.values.length>=12){let e=rf._f.FromArray(l.values.slice(8,12));e.equals(rf._f.Zero())||(a=e)}l.values.length>=13&&(o=l.values[12]);break;case rJ.ANIMATIONTYPE_MATRIX:t=rf.y3.FromArray(l.values),l.values.length>=17&&(o=l.values[16]);break;case rJ.ANIMATIONTYPE_COLOR3:t=rm.Wo.FromArray(l.values),l.values[3]&&(r=rm.Wo.FromArray(l.values[3])),l.values[4]&&(a=rm.Wo.FromArray(l.values[4])),l.values[5]&&(o=l.values[5]);break;case rJ.ANIMATIONTYPE_COLOR4:t=rm.HE.FromArray(l.values),l.values[4]&&(r=rm.HE.FromArray(l.values[4])),l.values[5]&&(a=rm.HE.FromArray(l.values[5])),l.values[6]&&(o=rm.HE.FromArray(l.values[6]));break;case rJ.ANIMATIONTYPE_VECTOR3:default:t=rf.P.FromArray(l.values),l.values[3]&&(r=rf.P.FromArray(l.values[3])),l.values[4]&&(a=rf.P.FromArray(l.values[4])),l.values[5]&&(o=l.values[5])}let h={};h.frame=l.frame,h.value=t,void 0!=r&&(h.inTangent=r),void 0!=a&&(h.outTangent=a),void 0!=o&&(h.interpolation=o),n.push(h)}if(r.setKeys(n),e.ranges)for(i=0;i{let s=new rX.g;s.addEventListener("readystatechange",()=>{if(4==s.readyState){if(200==s.status){let t=JSON.parse(s.responseText);if(t.animations&&(t=t.animations),t.length){let e=[];for(let i of t)e.push(this.Parse(i));i(e)}else{let r=this.Parse(t);e&&(r.name=e),i(r)}}else r("Unable to load the animation")}}),s.open("GET",t),s.send()})}static ParseFromSnippetAsync(e){return new Promise((t,i)=>{let r=new rX.g;r.addEventListener("readystatechange",()=>{if(4==r.readyState){if(200==r.status){let i=JSON.parse(JSON.parse(r.responseText).jsonPayload);if(i.animations){let r=JSON.parse(i.animations),s=[];for(let t of r.animations){let i=this.Parse(t);i.snippetId=e,s.push(i)}t(s)}else{let r=JSON.parse(i.animation),s=this.Parse(r);s.snippetId=e,t(s)}}else i("Unable to load the snippet "+e)}}),r.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),r.send()})}}rJ._UniqueIdGenerator=0,rJ.AllowMatricesInterpolation=!1,rJ.AllowMatrixDecomposeForInterpolation=!0,rJ.SnippetUrl="https://snippet.babylonjs.com",rJ.ANIMATIONTYPE_FLOAT=0,rJ.ANIMATIONTYPE_VECTOR3=1,rJ.ANIMATIONTYPE_QUATERNION=2,rJ.ANIMATIONTYPE_MATRIX=3,rJ.ANIMATIONTYPE_COLOR3=4,rJ.ANIMATIONTYPE_COLOR4=7,rJ.ANIMATIONTYPE_VECTOR2=5,rJ.ANIMATIONTYPE_SIZE=6,rJ.ANIMATIONLOOPMODE_RELATIVE=0,rJ.ANIMATIONLOOPMODE_CYCLE=1,rJ.ANIMATIONLOOPMODE_CONSTANT=2,rJ.ANIMATIONLOOPMODE_YOYO=4,rJ.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,rJ.CreateFromSnippetAsync=rJ.ParseFromSnippetAsync,(0,rg.H)("BABYLON.Animation",rJ),rW.N._AnimationRangeFactory=(e,t,i)=>new rz(e,t,i);class r0 extends rv{constructor(e,t,i,r,s=1e3,n,a,o){super(e,n),this.duration=1e3,this.onInterpolationDoneObservable=new r_.y$,this.propertyPath=i,this.value=r,this.duration=s,this.stopOtherAnimations=a,this.onInterpolationDone=o,this._target=this._effectiveTarget=t}_prepare(){this._effectiveTarget=this._getEffectiveTarget(this._effectiveTarget,this.propertyPath),this._property=this._getProperty(this.propertyPath)}execute(){let e;let t=this._actionManager.getScene(),i=[{frame:0,value:this._effectiveTarget[this._property]},{frame:100,value:this.value}];if("number"==typeof this.value)e=rJ.ANIMATIONTYPE_FLOAT;else if(this.value instanceof rm.Wo)e=rJ.ANIMATIONTYPE_COLOR3;else if(this.value instanceof rf.P)e=rJ.ANIMATIONTYPE_VECTOR3;else if(this.value instanceof rf.y3)e=rJ.ANIMATIONTYPE_MATRIX;else if(this.value instanceof rf._f)e=rJ.ANIMATIONTYPE_QUATERNION;else{rb.Y.Warn("InterpolateValueAction: Unsupported type ("+typeof this.value+")");return}let r=new rJ("InterpolateValueAction",this._property,1e3/this.duration*100,e,rJ.ANIMATIONLOOPMODE_CONSTANT);r.setKeys(i),this.stopOtherAnimations&&t.stopAnimation(this._effectiveTarget),t.beginDirectAnimation(this._effectiveTarget,[r],0,100,!1,1,()=>{this.onInterpolationDoneObservable.notifyObservers(this),this.onInterpolationDone&&this.onInterpolationDone()})}serialize(e){return super._serialize({name:"InterpolateValueAction",properties:[rv._GetTargetProperty(this._target),{name:"propertyPath",value:this.propertyPath},{name:"value",value:rv._SerializeValueAsString(this.value)},{name:"duration",value:rv._SerializeValueAsString(this.duration)},{name:"stopOtherAnimations",value:rv._SerializeValueAsString(this.stopOtherAnimations)||!1}]},e)}}(0,rg.H)("BABYLON.InterpolateValueAction",r0);class r1{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,i,r){if(this._events=[],this._currentFrame=0,this._originalValue=[],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._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=i,this._host=r,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===rJ.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=rf.y3.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){let e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(let 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];let s=t.getEvents();s&&s.length>0&&s.forEach(e=>{this._events.push(e._clone())}),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){let i=this._animation.targetPropertyPath;if(i.length>1){let r=e[i[0]];for(let e=1;e-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray){for(let i=0;it[t.length-1].frame&&(e=t[t.length-1].frame);let i=this._events;if(i.length)for(let t=0;tthis._maxFrame)&&(t=this._minFrame),(ithis._maxFrame)&&(i=this._maxFrame);let c=i-t,d=l.framePerSecond*s*e/1e3+this._absoluteFrameOffset,p=0;if(r&&this._animationState.loopMode===rJ.ANIMATIONLOOPMODE_YOYO&&(d=Math.abs(Math.sin((d-t)/c*Math.PI))*c+t),this._previousElapsedTime=e,this._previousAbsoluteFrame=d,!r&&i>=t&&d>=c)u=!1,p=l._getKeyValue(this._maxValue);else if(!r&&t>=i&&d<=c)u=!1,p=l._getKeyValue(this._minValue);else if(this._animationState.loopMode!==rJ.ANIMATIONLOOPMODE_CYCLE){let e=i.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=rJ.ANIMATIONLOOPMODE_CYCLE;let r=l._interpolate(t,this._animationState),s=l._interpolate(i,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),l.dataType){case rJ.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=s-r;break;case rJ.ANIMATIONTYPE_QUATERNION:case rJ.ANIMATIONTYPE_VECTOR3:case rJ.ANIMATIONTYPE_VECTOR2:case rJ.ANIMATIONTYPE_SIZE:case rJ.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=s.subtract(r)}this._highLimitsCache[e]=s}p=this._highLimitsCache[e],a=this._offsetsCache[e]}if(void 0===a)switch(l.dataType){case rJ.ANIMATIONTYPE_FLOAT:a=0;break;case rJ.ANIMATIONTYPE_QUATERNION:a=rY;break;case rJ.ANIMATIONTYPE_VECTOR3:a=rj;break;case rJ.ANIMATIONTYPE_VECTOR2:a=rq;break;case rJ.ANIMATIONTYPE_SIZE:a=rK;break;case rJ.ANIMATIONTYPE_COLOR3:a=r$;break;case rJ.ANIMATIONTYPE_COLOR4:a=rQ}if(this._host&&this._host.syncRoot){let e=this._host.syncRoot,i=(e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame);o=t+c*i}else o=d>0&&t>i||d<0&&t0&&this.currentFrame>o||s<0&&this.currentFrame0?0:l.getKeys().length-1}this._currentFrame=o,this._animationState.repeatCount=0===c?0:d/c>>0,this._animationState.highLimitValue=p,this._animationState.offsetValue=a;let f=l._interpolate(o,this._animationState);if(this.setValue(f,n),_.length){for(let e=0;e<_.length;e++)if(c>0&&o>=_[e].frame&&_[e].frame>=t||c<0&&o<=_[e].frame&&_[e].frame<=t){let t=_[e];t.isDone||(t.onlyOnce&&(_.splice(e,1),e--),t.isDone=!0,t.action(o))}}return u||(this._stopped=!0),u}}var r2=i(6540),r3=i(7662),r4=i(4254),r5=i(524);class r6 extends rW.N{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,i=null,r=null,s=null,n=null,a=null){var o;super(e,t.getScene()),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=null!==(o=null==r?void 0:r.clone())&&void 0!==o?o:rf.y3.Identity(),this._restMatrix=null!=s?s:this._localMatrix.clone(),this._bindMatrix=null!=n?n:this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new rf.y3,this._absoluteBindMatrix=new rf.y3,this._absoluteInverseBindMatrix=new rf.y3,this._finalMatrix=new rf.y3,t.bones.push(this),this.setParent(i,!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){let 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(){var e;if(this._linkedTransformNode){let t=rf.jp.Vector3[0],i=rf.jp.Quaternion[0],r=rf.jp.Vector3[1];this.getRestMatrix().decompose(t,i,r),this._linkedTransformNode.position.copyFrom(r),this._linkedTransformNode.rotationQuaternion=null!==(e=this._linkedTransformNode.rotationQuaternion)&&void 0!==e?e:rf._f.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(i),this._linkedTransformNode.scaling.copyFrom(t)}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=rf.P.Zero(),this._localRotation=rf._f.Zero(),this._localPosition=rf.P.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){if(this._needToCompose){if(!this._localScaling){this._needToCompose=!1;return}this._needToCompose=!1,rf.y3.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)}}updateMatrix(e,t=!0,i=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),i?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;ethis._absoluteBindMatrix.determinant()?-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=r5.T.LOCAL,i,r=!0){let s=this.getLocalMatrix();if(t==r5.T.LOCAL)r?(s.addAtIndex(12,e.x),s.addAtIndex(13,e.y),s.addAtIndex(14,e.z)):s.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;i&&(t=i.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let n=r6._TmpMats[0],a=r6._TmpVecs[0];this.parent?i&&t?(n.copyFrom(this.parent.getAbsoluteMatrix()),n.multiplyToRef(t,n)):n.copyFrom(this.parent.getAbsoluteMatrix()):rf.y3.IdentityToRef(n),r&&n.setTranslationFromFloats(0,0,0),n.invert(),rf.P.TransformCoordinatesToRef(e,n,a),r?(s.addAtIndex(12,a.x),s.addAtIndex(13,a.y),s.addAtIndex(14,a.z)):s.setTranslationFromFloats(a.x,a.y,a.z)}this._markAsDirtyAndDecompose()}translate(e,t=r5.T.LOCAL,i){this._updatePosition(e,t,i,!0)}setPosition(e,t=r5.T.LOCAL,i){this._updatePosition(e,t,i,!1)}setAbsolutePosition(e,t){this.setPosition(e,r5.T.WORLD,t)}scale(e,t,i,r=!1){let s=this.getLocalMatrix(),n=r6._TmpMats[0];for(let r of(rf.y3.ScalingToRef(e,t,i,n),n.multiplyToRef(s,s),n.invert(),this.children)){let s=r.getLocalMatrix();s.multiplyToRef(n,s),s.multiplyAtIndex(12,e),s.multiplyAtIndex(13,t),s.multiplyAtIndex(14,i),r._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),r)for(let s of this.children)s.scale(e,t,i,r)}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,i,r=r5.T.LOCAL,s){if(r===r5.T.LOCAL){let n=r6._TmpQuat;rf._f.RotationYawPitchRollToRef(e,t,i,n),this.setRotationQuaternion(n,r,s);return}let n=r6._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,s))return;let a=r6._TmpMats[1];rf.y3.RotationYawPitchRollToRef(e,t,i,a),n.multiplyToRef(a,a),this._rotateWithMatrix(a,r,s)}rotate(e,t,i=r5.T.LOCAL,r){let s=r6._TmpMats[0];s.setTranslationFromFloats(0,0,0),rf.y3.RotationAxisToRef(e,t,s),this._rotateWithMatrix(s,i,r)}setAxisAngle(e,t,i=r5.T.LOCAL,r){if(i===r5.T.LOCAL){let s=r6._TmpQuat;rf._f.RotationAxisToRef(e,t,s),this.setRotationQuaternion(s,i,r);return}let s=r6._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(s,r))return;let n=r6._TmpMats[1];rf.y3.RotationAxisToRef(e,t,n),s.multiplyToRef(n,n),this._rotateWithMatrix(n,i,r)}setRotation(e,t=r5.T.LOCAL,i){this.setYawPitchRoll(e.y,e.x,e.z,t,i)}setRotationQuaternion(e,t=r5.T.LOCAL,i){if(t===r5.T.LOCAL){this._decompose(),this._localRotation.copyFrom(e),this._markAsDirtyAndCompose();return}let r=r6._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=r6._TmpMats[1];rf.y3.FromQuaternionToRef(e,s),r.multiplyToRef(s,s),this._rotateWithMatrix(s,t,i)}setRotationMatrix(e,t=r5.T.LOCAL,i){if(t===r5.T.LOCAL){let r=r6._TmpQuat;rf._f.FromRotationMatrixToRef(e,r),this.setRotationQuaternion(r,t,i);return}let r=r6._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;let s=r6._TmpMats[1];s.copyFrom(e),r.multiplyToRef(e,s),this._rotateWithMatrix(s,t,i)}_rotateWithMatrix(e,t=r5.T.LOCAL,i){let r=this.getLocalMatrix(),s=r.m[12],n=r.m[13],a=r.m[14],o=this.getParent(),l=r6._TmpMats[3],h=r6._TmpMats[4];o&&t==r5.T.WORLD?(i?(l.copyFrom(i.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(l,l)):l.copyFrom(o.getAbsoluteMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):t==r5.T.WORLD&&i?(l.copyFrom(i.getWorldMatrix()),h.copyFrom(l),h.invert(),r.multiplyToRef(l,r),r.multiplyToRef(e,r),r.multiplyToRef(h,r)):r.multiplyToRef(e,r),r.setTranslationFromFloats(s,n,a),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){let i=r6._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),rf.y3.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,i)):rf.y3.IdentityToRef(i),e.invert(),!isNaN(e.m[0])&&(i.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(i,e),!0)}getPosition(e=r5.T.LOCAL,t=null){let i=rf.P.Zero();return this.getPositionToRef(e,t,i),i}getPositionToRef(e=r5.T.LOCAL,t,i){if(e==r5.T.LOCAL){let e=this.getLocalMatrix();i.x=e.m[12],i.y=e.m[13],i.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let r=r6._TmpMats[0];t&&e?(r.copyFrom(this.getAbsoluteMatrix()),r.multiplyToRef(e,r)):r=this.getAbsoluteMatrix(),i.x=r.m[12],i.y=r.m[13],i.z=r.m[14]}}getAbsolutePosition(e=null){let t=rf.P.Zero();return this.getPositionToRef(r5.T.WORLD,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(r5.T.WORLD,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);let e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}let e=this.children,t=e.length;for(let i=0;i-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let i=0;i{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){let t=this._runtimeAnimations;for(let i=0;i-1){let s=this._runtimeAnimations;for(let i=s.length-1;i>=0;i--){let r=s[i];(!e||r.animation.name==e)&&(!t||t(r.target))&&(r.dispose(),s.splice(i,1))}0==s.length&&(i||this._scene._activeAnimatables.splice(r,1),this._raiseOnAnimationEnd())}}else{let e=this._scene._activeAnimatables.indexOf(this);if(e>-1){i||this._scene._activeAnimatables.splice(e,1);let t=this._runtimeAnimations;for(let e=0;e{this.onAnimationEndObservable.add(()=>{e(this)},void 0,void 0,this,!0)})}_animate(e){let t;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 i=!1,r=this._runtimeAnimations;for(t=0;t0)return;this._animationTimeLast=e}this.deltaTime=this.useConstantAnimationDeltaTime?16:(e-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=e;let t=this._activeAnimatables;if(0===t.length)return;this._animationTime+=this.deltaTime;let i=this._animationTime;for(let e=0;ee.playOrder-t.playOrder)},r2.x.prototype.beginWeightedAnimation=function(e,t,i,r=1,s,n=1,a,o,l,h,u=!1){let c=this.beginAnimation(e,t,i,s,n,a,o,!1,l,h,u);return c.weight=r,c},r2.x.prototype.beginAnimation=function(e,t,i,r,s=1,n,a,o=!0,l,h,u=!1){t>i&&s>0&&(s*=-1),o&&this.stopAnimation(e,void 0,l),a||(a=new r8(this,e,t,i,r,s,n,void 0,h,u));let c=!l||l(e);if(e.animations&&c&&a.appendAnimations(e,e.animations),e.getAnimatables){let u=e.getAnimatables();for(let e=0;er&&n>0)n*=-1;else if(r>i&&n<0){let e=r;r=i,i=e}return new r8(this,e,i,r,s,n,a,t,o,l)},r2.x.prototype.beginDirectHierarchyAnimation=function(e,t,i,r,s,n,a,o,l,h=!1){let u=e.getDescendants(t),c=[];for(let t of(c.push(this.beginDirectAnimation(e,i,r,s,n,a,o,l,h)),u))c.push(this.beginDirectAnimation(t,i,r,s,n,a,o,l,h));return c},r2.x.prototype.getAnimatableByTarget=function(e){for(let t=0;t0?l:-l,s),o.scaleAndAddToRef(l,i)}s.normalize()}for(let t=0;t0)s.copyFrom(r);else if(1===e.animations.length){if(rf._f.SlerpToRef(r,i.currentValue,Math.min(1,e.totalWeight),s),0===e.totalAdditiveWeight)return s}else if(e.animations.length>1){let i,n,a=1;if(e.totalWeight<1){let t=1-e.totalWeight;n=[],(i=[]).push(r),n.push(t)}else{if(2===e.animations.length&&(rf._f.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;i=[],n=[],a=e.totalWeight}for(let t=0;t=h&&n.frame<=u&&(r?(o=n.value.clone(),f?(a=o.getTranslation(),o.setTranslation(a.scaleInPlace(m))):g&&s?(a=o.getTranslation(),o.setTranslation(a.multiplyInPlace(s))):o=n.value):o=n.value,v.push({frame:n.frame+i,value:o}));return this.animations[0].createRange(t,h+i,u+i),!0};var r7=i(9806);(a=td||(td={}))[a.CW=0]="CW",a[a.CCW=1]="CCW";class r9{constructor(e){this._radians=e,this._radians<0&&(this._radians+=2*Math.PI)}degrees(){return 180*this._radians/Math.PI}radians(){return this._radians}static BetweenTwoPoints(e,t){let i=t.subtract(e);return new r9(Math.atan2(i.y,i.x))}static BetweenTwoVectors(e,t){let i=e.lengthSquared()*t.lengthSquared();if(0===i)return new r9(Math.PI/2);i=Math.sqrt(i);let r=e.dot(t)/i;return new r9(Math.acos(r=rk.R.Clamp(r,-1,1)))}static FromRadians(e){return new r9(e)}static FromDegrees(e){return new r9(e*Math.PI/180)}}class se{constructor(e,t,i){this.startPoint=e,this.midPoint=t,this.endPoint=i;let r=Math.pow(t.x,2)+Math.pow(t.y,2),s=(Math.pow(e.x,2)+Math.pow(e.y,2)-r)/2,n=(r-Math.pow(i.x,2)-Math.pow(i.y,2))/2,a=(e.x-t.x)*(t.y-i.y)-(t.x-i.x)*(e.y-t.y);this.centerPoint=new rf.FM((s*(t.y-i.y)-n*(e.y-t.y))/a,((e.x-t.x)*n-(t.x-i.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=r9.BetweenTwoPoints(this.centerPoint,this.startPoint);let o=this.startAngle.degrees(),l=r9.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),h=r9.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();l-o>180&&(l-=360),l-o<-180&&(l+=360),h-l>180&&(h-=360),h-l<-180&&(h+=360),this.orientation=l-o<0?td.CW:td.CCW,this.angle=r9.FromDegrees(this.orientation===td.CW?o-h:h-o)}}class st{constructor(e,t){this._points=[],this._length=0,this.closed=!1,this._points.push(new rf.FM(e,t))}addLineTo(e,t){if(this.closed)return this;let i=new rf.FM(e,t),r=this._points[this._points.length-1];return this._points.push(i),this._length+=i.subtract(r).length(),this}addArcTo(e,t,i,r,s=36){if(this.closed)return this;let n=new se(this._points[this._points.length-1],new rf.FM(e,t),new rf.FM(i,r)),a=n.angle.radians()/s;n.orientation===td.CW&&(a*=-1);let o=n.startAngle.radians()+a;for(let e=0;e(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r,a=this._points[this._points.length-1];for(let o=0;o<=s;o++){let l=o/s,h=n(l,a.x,e,i),u=n(l,a.y,t,r);this.addLineTo(h,u)}return this}addBezierCurveTo(e,t,i,r,s,n,a=36){if(this.closed)return this;let o=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s,l=this._points[this._points.length-1];for(let h=0;h<=a;h++){let u=h/a,c=o(u,l.x,e,i,s),d=o(u,l.y,t,r,n);this.addLineTo(c,d)}return this}isPointInside(e){let t=!1,i=this._points.length;for(let r=i-1,s=0;sNumber.EPSILON){if(o<0&&(i=this._points[s],a=-a,n=this._points[r],o=-o),e.yn.y)continue;if(e.y===i.y&&e.x===i.x)return!0;{let r=o*(e.x-i.x)-a*(e.y-i.y);if(0===r)return!0;if(r<0)continue;t=!t}}else{if(e.y!==i.y)continue;if(n.x<=e.x&&e.x<=i.x||i.x<=e.x&&e.x<=n.x)return!0}}return t}close(){return this.closed=!0,this}length(){let e=this._length;if(this.closed){let t=this._points[this._points.length-1];e+=this._points[0].subtract(t).length()}return e}area(){let e=this._points.length,t=0;for(let i=e-1,r=0;r1)return rf.FM.Zero();let t=e*this.length(),i=0;for(let e=0;e=i&&t<=a){let e=n.normalize(),r=t-i;return new rf.FM(s.x+e.x*r,s.y+e.y*r)}i=a}return rf.FM.Zero()}static StartingAt(e,t){return new st(e,t)}}class si{constructor(e,t=null,i,r=!1){this.path=e,this._curve=[],this._distances=[],this._tangents=[],this._normals=[],this._binormals=[],this._pointAtData={id:0,point:rf.P.Zero(),previousPointArrayIndex:0,position:0,subPosition:0,interpolateReady:!1,interpolationMatrix:rf.y3.Identity()};for(let t=0;tt){let i=e;e=t,t=i}let i=this.getCurve(),r=this.getPointAt(e),s=this.getPreviousPointIndexAt(e),n=this.getPointAt(t),a=this.getPreviousPointIndexAt(t)+1,o=[];return 0!==e&&(s++,o.push(r)),o.push(...i.slice(s,a)),(1!==t||1===e)&&o.push(n),new si(o,this.getNormalAt(e),this._raw,this._alignTangentsWithPath)}update(e,t=null,i=!1){for(let t=0;tt+1;)t++,i=this._curve[e].subtract(this._curve[e-t]);return i}_normalVector(e,t){let i;let r=e.length();if(0===r&&(r=1),null==t){let t;t=rk.R.WithinEpsilon(Math.abs(e.y)/r,1,r7.kn)?rk.R.WithinEpsilon(Math.abs(e.x)/r,1,r7.kn)?rk.R.WithinEpsilon(Math.abs(e.z)/r,1,r7.kn)?rf.P.Zero():new rf.P(0,0,1):new rf.P(1,0,0):new rf.P(0,-1,0),i=rf.P.Cross(e,t)}else i=rf.P.Cross(e,t),rf.P.CrossToRef(i,e,i);return i.normalize(),i}_updatePointAtData(e,t=!1){let i;if(this._pointAtData.id===e)return this._pointAtData.interpolateReady||this._updateInterpolationMatrix(),this._pointAtData;this._pointAtData.id=e;let r=this.getPoints();if(e<=0)return this._setPointAtData(0,0,r[0],0,t);if(e>=1)return this._setPointAtData(1,1,r[r.length-1],r.length-1,t);let s=r[0],n=0,a=e*this.length();for(let o=1;oa){let r=(n-a)/l,h=s.subtract(i),u=i.add(h.scaleInPlace(r));return this._setPointAtData(e,1-r,u,o-1,t)}s=i}return this._pointAtData}_setPointAtData(e,t,i,r,s){return this._pointAtData.point=i,this._pointAtData.position=e,this._pointAtData.subPosition=t,this._pointAtData.previousPointArrayIndex=r,this._pointAtData.interpolateReady=s,s&&this._updateInterpolationMatrix(),this._pointAtData}_updateInterpolationMatrix(){this._pointAtData.interpolationMatrix=rf.y3.Identity();let e=this._pointAtData.previousPointArrayIndex;if(e!==this._tangents.length-1){let t=e+1,i=this._tangents[e].clone(),r=this._normals[e].clone(),s=this._binormals[e].clone(),n=this._tangents[t].clone(),a=this._normals[t].clone(),o=this._binormals[t].clone(),l=rf._f.RotationQuaternionFromAxis(r,s,i),h=rf._f.RotationQuaternionFromAxis(a,o,n);rf._f.Slerp(l,h,this._pointAtData.subPosition).toRotationMatrix(this._pointAtData.interpolationMatrix)}}}class sr{static CreateQuadraticBezier(e,t,i,r){r=r>2?r:3;let s=[],n=(e,t,i,r)=>(1-e)*(1-e)*t+2*e*(1-e)*i+e*e*r;for(let a=0;a<=r;a++)s.push(new rf.P(n(a/r,e.x,t.x,i.x),n(a/r,e.y,t.y,i.y),n(a/r,e.z,t.z,i.z)));return new sr(s)}static CreateCubicBezier(e,t,i,r,s){s=s>3?s:4;let n=[],a=(e,t,i,r,s)=>(1-e)*(1-e)*(1-e)*t+3*e*(1-e)*(1-e)*i+3*e*e*(1-e)*r+e*e*e*s;for(let o=0;o<=s;o++)n.push(new rf.P(a(o/s,e.x,t.x,i.x,r.x),a(o/s,e.y,t.y,i.y,r.y),a(o/s,e.z,t.z,i.z,r.z)));return new sr(n)}static CreateHermiteSpline(e,t,i,r,s){let n=[],a=1/s;for(let o=0;o<=s;o++)n.push(rf.P.Hermite(e,t,i,r,o*a));return new sr(n)}static CreateCatmullRomSpline(e,t,i){let r=[],s=1/t,n=0;if(i){let i=e.length;for(let a=0;a=.5?(1-this.easeInCore((1-e)*2))*.5+.5:.5*this.easeInCore(2*e)}}ss.EASINGMODE_EASEIN=0,ss.EASINGMODE_EASEOUT=1,ss.EASINGMODE_EASEINOUT=2;class sn extends ss{easeInCore(e){return 1-Math.sqrt(1-(e=Math.max(0,Math.min(1,e)))*e)}}class sa extends ss{constructor(e=1){super(),this.amplitude=e}easeInCore(e){return Math.pow(e,3)-e*Math.max(0,this.amplitude)*Math.sin(3.141592653589793*e)}}class so extends ss{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)}}class sl extends ss{easeInCore(e){return e*e}}class sh extends ss{easeInCore(e){return 1-Math.sin(1.5707963267948966*(1-e))}}var su=i(1803);class sc{getClassName(){return"TargetedAnimation"}serialize(){let e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class sd{syncWithMask(){if(!this.mask){this._numActiveAnimatables=this._targetedAnimations.length;return}this._numActiveAnimatables=0;for(let e=0;e0)){for(let e=0;en&&(n=t.to);let a=new sd(e[0].name+"_merged",e[0]._scene,r);for(let r of e){for(let e of(i&&r.normalize(s,n),r.targetedAnimations))a.addTargetedAnimation(e.animation,e.target);t&&r.dispose()}return a}constructor(e,t=null,i=-1,r=0){this.name=e,this._targetedAnimations=[],this._animatables=[],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._parentContainer=null,this.onAnimationEndObservable=new r_.y$,this.onAnimationLoopObservable=new r_.y$,this.onAnimationGroupLoopObservable=new r_.y$,this.onAnimationGroupEndObservable=new r_.y$,this.onAnimationGroupPauseObservable=new r_.y$,this.onAnimationGroupPlayObservable=new r_.y$,this.metadata=null,this._animationLoopFlags=[],this._scene=t||rL.l.LastCreatedScene,this._weight=i,this._playOrder=r,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){let i=new sc;i.animation=e,i.target=t;let r=e.getKeys();return this._from>r[0].frame&&(this._from=r[0].frame),this._to-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 i=0;ie){let t={frame:e,value:s.value,inTangent:s.inTangent,outTangent:s.outTangent,interpolation:s.interpolation};r.splice(0,0,t)}if(n.frame{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[i]||(this._animationLoopFlags[i]=!0,this._animationLoopCount++,this._animationLoopCount!==this._numActiveAnimatables||(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,i,r,s){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n{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;e0&&(this._scene._activeAnimatables[t++]=i)}return this._scene._activeAnimatables.length=t,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){let 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){let t=this._animatables.indexOf(e);t>-1&&this._animatables.splice(t,1),0===this._animatables.length&&(this._isStarted=!1,this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,i=!1){let r=new sd(e||this.name,this._scene,this._weight,this._playOrder);for(let e of(r._from=this.from,r._to=this.to,r._speedRatio=this.speedRatio,r._loopAnimation=this.loopAnimation,r._isAdditive=this.isAdditive,r._enableBlending=this.enableBlending,r._blendingSpeed=this.blendingSpeed,r.metadata=this.metadata,r.mask=this.mask,this._targetedAnimations))r.addTargetedAnimation(i?e.animation.clone():e.animation,t?t(e.target):e.target);return r}serialize(){let 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;ts[0].frame&&(e=s[0].frame),t=t&&e<=i||s&&r.frame>=t&&r.frame<=i){let e={frame:r.frame,value:r.value.clone?r.value.clone():r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation,lockedTangent:r.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,c.push(e)}}if(0===c.length){o.splice(e,1),e--;continue}n>c[0].frame&&(n=c[0].frame),a{let i=new sv(e,t);if(t.instancedBuffers)for(let e in i.instancedBuffers={},t.instancedBuffers)i.instancedBuffers[e]=t.instancedBuffers[e];return i};class sv extends sf.x{constructor(e,t){for(let i of(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(),t.getAnimationRanges()))null!=i&&this.createAnimationRange(i.name,i.from,i.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){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.receiveShadows)!==e&&sg.w1.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.material)!==e&&sg.w1.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.visibility)!==e&&sg.w1.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){var t;(null===(t=this._sourceMesh)||void 0===t?void 0:t.skeleton)!==e&&sg.w1.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&&rb.Y.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,i){return this._sourceMesh.getVerticesData(e,t,i)}setVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,i,r),this.sourceMesh}updateVerticesData(e,t,i,r){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,i,r),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 i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getPositionData(e,t),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||rb.Y.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!==s_.Y.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new rf.y3);let e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,rf.jp.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(rf.jp.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;let t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){let 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;e0)||-1!==this.includedOnlyMeshes.indexOf(e))&&(!this.excludedMeshes||!(this.excludedMeshes.length>0)||-1===this.excludedMeshes.indexOf(e))&&(0===this.includeOnlyWithLayerMask||(this.includeOnlyWithLayerMask&e.layerMask)!=0)&&(0===this.excludeWithLayerMask||!(this.excludeWithLayerMask&e.layerMask))}dispose(e,t=!1){if(this._shadowGenerators){let 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){let e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(let 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){let i=sE.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!i)return null;let r=rG.p4.Clone(i,this);return e&&(r.name=e),t&&(r.parent=t),r.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(r),r}serialize(){let e=rG.p4.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)})),rG.p4.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,i){return rW.N.Construct("Light_Type_"+e,t,i)||null}static Parse(e,t){let i=sE.GetConstructorFromName(e.type,e.name,t);if(!i)return null;let r=rG.p4.Parse(i,e,t);if(e.excludedMeshesIds&&(r._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(r._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(r.falloffType=e.falloffType),void 0!==e.lightmapMode&&(r.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t{let r=t.apply(e,i);for(let e of i)e._resyncLightSource(this);return r};let i=e.splice;for(let t of(e.splice=(t,r)=>{let s=i.apply(e,[t,r]);for(let e of s)e._resyncLightSource(this);return s},e))t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){let t=e.push;e.push=(...i)=>{let r=t.apply(e,i);return this._resyncMeshes(),r};let i=e.splice;e.splice=(t,r)=>{let s=i.apply(e,[t,r]);return this._resyncMeshes(),s},this._resyncMeshes()}_resyncMeshes(){for(let e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(let e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0,t=this.getTypeID(),i=this.intensityMode;switch(i===sE.INTENSITYMODE_AUTOMATIC&&(i=t===sE.LIGHTTYPEID_DIRECTIONALLIGHT?sE.INTENSITYMODE_ILLUMINANCE:sE.INTENSITYMODE_LUMINOUSINTENSITY),t){case sE.LIGHTTYPEID_POINTLIGHT:case sE.LIGHTTYPEID_SPOTLIGHT:switch(i){case sE.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case sE.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case sE.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case sE.LIGHTTYPEID_DIRECTIONALLIGHT:switch(i){case sE.INTENSITYMODE_ILLUMINANCE:e=1;break;case sE.INTENSITYMODE_LUMINANCE:{let t=this.radius;e=2*Math.PI*(1-Math.cos(t=Math.max(t,.001)))}}break;case sE.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){let e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}sE.FALLOFF_DEFAULT=sS.m.FALLOFF_DEFAULT,sE.FALLOFF_PHYSICAL=sS.m.FALLOFF_PHYSICAL,sE.FALLOFF_GLTF=sS.m.FALLOFF_GLTF,sE.FALLOFF_STANDARD=sS.m.FALLOFF_STANDARD,sE.LIGHTMAP_DEFAULT=sS.m.LIGHTMAP_DEFAULT,sE.LIGHTMAP_SPECULAR=sS.m.LIGHTMAP_SPECULAR,sE.LIGHTMAP_SHADOWSONLY=sS.m.LIGHTMAP_SHADOWSONLY,sE.INTENSITYMODE_AUTOMATIC=sS.m.INTENSITYMODE_AUTOMATIC,sE.INTENSITYMODE_LUMINOUSPOWER=sS.m.INTENSITYMODE_LUMINOUSPOWER,sE.INTENSITYMODE_LUMINOUSINTENSITY=sS.m.INTENSITYMODE_LUMINOUSINTENSITY,sE.INTENSITYMODE_ILLUMINANCE=sS.m.INTENSITYMODE_ILLUMINANCE,sE.INTENSITYMODE_LUMINANCE=sS.m.INTENSITYMODE_LUMINANCE,sE.LIGHTTYPEID_POINTLIGHT=sS.m.LIGHTTYPEID_POINTLIGHT,sE.LIGHTTYPEID_DIRECTIONALLIGHT=sS.m.LIGHTTYPEID_DIRECTIONALLIGHT,sE.LIGHTTYPEID_SPOTLIGHT=sS.m.LIGHTTYPEID_SPOTLIGHT,sE.LIGHTTYPEID_HEMISPHERICLIGHT=sS.m.LIGHTTYPEID_HEMISPHERICLIGHT,(0,sx.gn)([(0,rG.n9)()],sE.prototype,"diffuse",void 0),(0,sx.gn)([(0,rG.n9)()],sE.prototype,"specular",void 0),(0,sx.gn)([(0,rG.qC)()],sE.prototype,"falloffType",void 0),(0,sx.gn)([(0,rG.qC)()],sE.prototype,"intensity",void 0),(0,sx.gn)([(0,rG.qC)()],sE.prototype,"range",null),(0,sx.gn)([(0,rG.qC)()],sE.prototype,"intensityMode",null),(0,sx.gn)([(0,rG.qC)()],sE.prototype,"radius",null),(0,sx.gn)([(0,rG.qC)()],sE.prototype,"_renderPriority",void 0),(0,sx.gn)([(0,rG.wz)("_reorderLightsInScene")],sE.prototype,"renderPriority",void 0),(0,sx.gn)([(0,rG.qC)("shadowEnabled")],sE.prototype,"_shadowEnabled",void 0),(0,sx.gn)([(0,rG.qC)("excludeWithLayerMask")],sE.prototype,"_excludeWithLayerMask",void 0),(0,sx.gn)([(0,rG.qC)("includeOnlyWithLayerMask")],sE.prototype,"_includeOnlyWithLayerMask",void 0),(0,sx.gn)([(0,rG.qC)("lightmapMode")],sE.prototype,"_lightmapMode",void 0);var sC=i(2421);class sb extends rd.p{}class sy{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 sA extends rd.p{constructor(e){if(super(),this._wasAddedToScene=!1,!(e=e||rL.l.LastCreatedScene))return;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(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of this.particleSystems)e.rebuild();for(let e of this.textures)e._rebuild()})}_topologicalSort(e){let t=new Map;for(let i of e)t.set(i.uniqueId,i);let i={dependsOn:new Map,dependedBy:new Map};for(let t of e){let e=t.uniqueId;i.dependsOn.set(e,new Set),i.dependedBy.set(e,new Set)}for(let r of e){let e=r.uniqueId,s=i.dependsOn.get(e);if(r instanceof sv){let n=r.sourceMesh;t.has(n.uniqueId)&&(s.add(n.uniqueId),i.dependedBy.get(n.uniqueId).add(e))}let n=i.dependedBy.get(e);for(let s of r.getDescendants()){let r=s.uniqueId;t.has(r)&&(n.add(r),i.dependsOn.get(r).add(e))}}let r=[],s=[];for(let r of e){let e=r.uniqueId;0===i.dependsOn.get(e).size&&(s.push(r),t.delete(e))}for(;s.length>0;){let e=s.shift();for(let n of(r.push(e),Array.from(i.dependedBy.get(e.uniqueId).values()))){let r=i.dependsOn.get(n);r.delete(e.uniqueId),0===r.size&&t.get(n)&&(s.push(t.get(n)),t.delete(n))}}return t.size>0&&(rb.Y.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach(e=>rb.Y.Error(e.name))),r}_addNodeAndDescendantsToList(e,t,i,r){if(!(!i||r&&!r(i)||t.has(i.uniqueId)))for(let s of(e.push(i),t.add(i.uniqueId),i.getDescendants(!0)))this._addNodeAndDescendantsToList(e,t,s,r)}_isNodeInContainer(e){return e instanceof sp.Kj&&-1!==this.meshes.indexOf(e)||e instanceof s_.Y&&-1!==this.transformNodes.indexOf(e)||e instanceof sE&&-1!==this.lights.indexOf(e)||e instanceof sC.V&&-1!==this.cameras.indexOf(e)}_isValidHierarchy(){for(let e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return rb.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return rb.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return rb.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(let e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return rb.Y.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,i){this._isValidHierarchy()||sg.w1.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");let r={},s={},n=new sy,a=[],o=[],l=Object.assign({doNotInstantiate:!0},i),h=(t,i)=>{if(r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,e&&(i.name=e(t.name)),i instanceof sp.Kj&&i.morphTargetManager){let e=t.morphTargetManager;i.morphTargetManager=e.clone();for(let t=0;t{if(h(i,a),i.parent){let e=s[r[i.parent.uniqueId]];e?a.parent=e:a.parent=i.parent}if(a.position&&i.position&&a.position.copyFrom(i.position),a.rotationQuaternion&&i.rotationQuaternion&&a.rotationQuaternion.copyFrom(i.rotationQuaternion),a.rotation&&i.rotation&&a.rotation.copyFrom(i.rotation),a.scaling&&i.scaling&&a.scaling.copyFrom(i.scaling),a.material&&a.material){if(t){let t=i.material;if(-1===o.indexOf(t)){let i=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),r[t.uniqueId]=i.uniqueId,s[i.uniqueId]=i,"MultiMaterial"===t.getClassName()){for(let n of t.subMaterials)n&&(i=n.clone(e?e(n.name):"Clone of "+n.name),o.push(n),r[n.uniqueId]=i.uniqueId,s[i.uniqueId]=i);t.subMaterials=t.subMaterials.map(e=>e&&s[r[e.uniqueId]])}}"InstancedMesh"!==a.getClassName()&&(a.material=s[r[t.uniqueId]])}else"MultiMaterial"===a.material.getClassName()?-1===this.scene.multiMaterials.indexOf(a.material)&&this.scene.addMultiMaterial(a.material):-1===this.scene.materials.indexOf(a.material)&&this.scene.addMaterial(a.material)}null===a.parent&&n.rootNodes.push(a)};return d.forEach(e=>{if("InstancedMesh"===e.getClassName()){let t=e.sourceMesh,i=r[t.uniqueId],n=("number"==typeof i?s[i]:t).createInstance(e.name);p(e,n)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:l.doNotInstantiate&&(t="function"==typeof l.doNotInstantiate?!l.doNotInstantiate(e):!l.doNotInstantiate);let i=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!i)throw Error(`Could not clone or instantiate node on Asset Container ${e.name}`);p(e,i)}}),this.skeletons.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name);for(let e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){let t=s[r[e.uniqueId]];if(!t||t.isAnInstance||(t.skeleton=i,-1!==a.indexOf(i)))continue;for(let e of(a.push(i),i.bones))e._linkedTransformNode&&(e._linkedTransformNode=s[r[e._linkedTransformNode.uniqueId]])}n.skeletons.push(i)}),this.animationGroups.forEach(t=>{if(l.predicate&&!l.predicate(t))return;let i=t.clone(e?e(t.name):"Clone of "+t.name,e=>s[r[e.uniqueId]]||e);n.animationGroups.push(i)}),n}addAllToScene(){if(!this._wasAddedToScene){for(let e of(this._isValidHierarchy()||sg.w1.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture),this.scene._serializableComponents))e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){let t=[];for(let i of(this.cameras.forEach(i=>{(!e||e(i))&&(this.scene.addCamera(i),t.push(i))}),this.lights.forEach(i=>{(!e||e(i))&&(this.scene.addLight(i),t.push(i))}),this.meshes.forEach(i=>{(!e||e(i))&&(this.scene.addMesh(i),t.push(i))}),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(i=>{(!e||e(i))&&(this.scene.addTransformNode(i),t.push(i))}),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)}),t))i.parent&&-1===this.scene.getNodes().indexOf(i.parent)&&(i.setParent?i.setParent(null):i.parent=null)}removeAllFromScene(){for(let e of(this._isValidHierarchy()||sg.w1.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),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(){for(let e of(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),this.scene._serializableComponents))e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,i){if(e&&t)for(let r of e){let e=!0;if(i){for(let t of i)if(r===t){e=!1;break}}e&&(t.push(r),r._parentContainer=this)}}moveAllFromScene(e){for(let t in this._wasAddedToScene=!1,void 0===e&&(e=new sb),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(){let e=new sp.Kj("assetContainerRootMesh",this.scene);return this.meshes.forEach(t=>{t.parent||e.addChild(t)}),this.meshes.unshift(e),e}mergeAnimationsTo(e=rL.l.LastCreatedScene,t,i=null){if(!e)return rb.Y.Error("No scene available to merge animations to"),[];let r=i||(t=>{let i=null,r=t.animations.length?t.animations[0].targetProperty:"",s=t.name.split(".").join("").split("_primitive")[0];switch(r){case"position":case"rotationQuaternion":i=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(s);break;case"influence":i=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(s);break;default:i=e.getNodeByName(t.name)||e.getNodeByName(s)}return i});this.getNodes().forEach(e=>{let t=r(e);if(null!==t){for(let i of e.animations)for(let e of t.animations.filter(e=>e.targetProperty===i.targetProperty)){let i=t.animations.indexOf(e,0);i>-1&&t.animations.splice(i,1)}t.animations=t.animations.concat(e.animations)}});let s=[];return this.animationGroups.slice().forEach(e=>{s.push(e.clone(e.name,r)),e.animatables.forEach(e=>{e.stop()})}),t.forEach(t=>{let i=r(t.target);i&&(e.beginAnimation(i,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))}),s}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;let t=[],i=new Set;for(t.push(e);t.length>0;){let e=t.pop();if(e instanceof sp.Kj?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof s_.Y?this.transformNodes.push(e):e instanceof sE?this.lights.push(e):e instanceof sC.V&&this.cameras.push(e),e instanceof sf.x){if(e.material&&-1===this.materials.indexOf(e.material))for(let t of(this.materials.push(e.material),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(let r of e.getChildren())i.has(r)||t.push(r);i.add(e)}this.populateRootNodes()}}var sR=i(8906),sP=i(7209);sR.D.AudioEngineFactory=(e,t,i)=>new sI(e,t,i);class sI{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,i=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 r_.y$,this.onAudioLockedObservable=new r_.y$,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!(0,sP.CG)())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);let r=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=i;try{r&&r.canPlayType&&(r.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||r.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{r&&r.canPlayType&&r.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){var e,t;if((null===(e=this._audioContext)||void 0===e?void 0:e.state)==="running"){this._hideMuteButton();return}this._tryToRun?null===(t=this._audioContext)||void 0===t||t.suspend().then(()=>{this._tryToRun=!1,this._triggerRunningState()}):this._triggerRunningState()}_resumeAudioContext(){var e;return(null===(e=this._audioContext)||void 0===e?void 0:e.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,rb.Y.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";let e=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",t=document.createElement("style");t.appendChild(document.createTextNode(".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+e+"); 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) }")),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))}}var sM=i(6131);class sD{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){var e;if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if((null===(e=sR.D.audioEngine)||void 0===e?void 0:e.audioContext)&&(this.isPlaying||this.isPaused)){let e=this.isPaused?0:sR.D.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;let t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,i,r=null,s){var n,a,o,l,h;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 r_.y$,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=rf.P.Zero(),this._localDirection=new rf.P(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,!(i=i||rL.l.LastCreatedScene))return;if(this._scene=i,sD._SceneComponentInitialization(i),this._readyToPlayCallback=r,this._customAttenuationFunction=(e,t,i,r,s)=>t0&&(r=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":i.push(t);case"Array":0===i.length&&(i=t);for(let e=0;e{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&&rb.Y.Error("XHR "+e.status+" error on: "+t+"."),rb.Y.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)});break}}break;default:e=!1}e?!r&&(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)):rb.Y.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){rb.Y.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),sR.D.audioEngine&&!sR.D.audioEngine.WarnedWebAudioUnsupported&&(rb.Y.Error("Web Audio is not supported by your browser."),sR.D.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout(()=>{this._readyToPlayCallback&&this._readyToPlayCallback()},1e3)}dispose(){var e;(null===(e=sR.D.audioEngine)||void 0===e?void 0:e.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){var t;(null===(t=sR.D.audioEngine)||void 0===t?void 0:t.audioContext)&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){var t;(null===(t=sR.D.audioEngine)||void 0===t?void 0:t.audioContext)&&sR.D.audioEngine.audioContext.decodeAudioData(e,e=>{this._audioBufferLoaded(e)},e=>{rb.Y.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)})}setAudioBuffer(e){var t;(null===(t=sR.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){var t,i,r,s,n,a,o,l,h,u,c;e&&(this.loop=null!==(t=e.loop)&&void 0!==t?t:this.loop,this.maxDistance=null!==(i=e.maxDistance)&&void 0!==i?i:this.maxDistance,this.useCustomAttenuation=null!==(r=e.useCustomAttenuation)&&void 0!==r?r:this.useCustomAttenuation,this.rolloffFactor=null!==(s=e.rolloffFactor)&&void 0!==s?s:this.rolloffFactor,this.refDistance=null!==(n=e.refDistance)&&void 0!==n?n:this.refDistance,this.distanceModel=null!==(a=e.distanceModel)&&void 0!==a?a:this.distanceModel,this._playbackRate=null!==(o=e.playbackRate)&&void 0!==o?o:this._playbackRate,this._length=null!==(l=e.length)&&void 0!==l?l:void 0,this.spatialSound=null!==(h=e.spatialSound)&&void 0!==h?h:this._spatialSound,this._setOffset(null!==(u=e.offset)&&void 0!==u?u:void 0),this.setVolume(null!==(c=e.volume)&&void 0!==c?c: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(){var e,t;(null===(e=sR.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&sR.D.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=null!==(t=this._soundPanner)&&void 0!==t?t:sR.D.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){var e;this._spatialSound&&(this._inputAudioNode=this._soundGain,null===(e=this._soundPanner)||void 0===e||e.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.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(){var e;(null===(e=sR.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){var t;(null===(t=sR.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,i){if(t{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){let e=()=>{var t,i;if(null===(t=sR.D.audioEngine)||void 0===t?void 0:t.unlocked){let t=this._htmlAudioElement.play();void 0!==t&&t.catch(()=>{var t,i;null===(t=sR.D.audioEngine)||void 0===t||t.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(i=sR.D.audioEngine)||void 0===i?void 0:i.onAudioUnlockedObservable.addOnce(()=>{e()}))})}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=null===(i=sR.D.audioEngine)||void 0===i?void 0:i.onAudioUnlockedObservable.addOnce(()=>{e()}))};e()}}else{let s=()=>{var s,n,a,o;if(null===(s=sR.D.audioEngine)||void 0===s?void 0:s.audioContext){if(i=i||this._length,void 0!==t&&this._setOffset(t),this._soundSource){let e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=null===(n=sR.D.audioEngine)||void 0===n?void 0:n.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!==i&&(this._soundSource.loopEnd=(0|t)+i),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},r=e?(null===(a=sR.D.audioEngine)||void 0===a?void 0:a.audioContext.currentTime)+e:sR.D.audioEngine.audioContext.currentTime;let s=((this.isPaused?this.currentTime:0)+(null!==(o=this._offset)&&void 0!==o?o:0))%this._soundSource.buffer.duration;this._soundSource.start(r,s,this.loop?void 0:i)}}};(null===(a=sR.D.audioEngine)||void 0===a?void 0:a.audioContext.state)==="suspended"?this._tryToPlayTimeout=setTimeout(()=>{var e;(null===(e=sR.D.audioEngine)||void 0===e?void 0:e.audioContext.state)==="suspended"?(sR.D.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=sR.D.audioEngine.onAudioUnlockedObservable.addOnce(()=>{s()}))):s()},500):s()}this._startTime=r,this.isPlaying=!0,this.isPaused=!1}catch(e){rb.Y.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){var t;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((null===(t=sR.D.audioEngine)||void 0===t?void 0:t.audioContext)&&this._soundSource){let t=e?sR.D.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=()=>void 0),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1}else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){var e;this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):(null===(e=sR.D.audioEngine)||void 0===e?void 0:e.audioContext)&&this._soundSource&&(this._soundSource.onended=()=>void 0,this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=sR.D.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){var i;(null===(i=sR.D.audioEngine)||void 0===i?void 0:i.canUseWebAudio)&&this._soundGain&&(t&&sR.D.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(sR.D.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,sR.D.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,sR.D.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){var t;if(e.getBoundingInfo){let t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);(null===(t=sR.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{let e=()=>{this._isReadyToPlay?(i._audioBuffer=this.getAudioBuffer(),i._isReadyToPlay=!0,i.autoplay&&i.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},i=new sD(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&i.setAttenuationFunction(this._customAttenuationFunction),i.setPosition(this._position),i.setPlaybackRate(this._playbackRate),e(),i}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){let 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,i,r){let s,n;let a=e.name;s=e.url?i+e.url:i+a;let o={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};if(r){let e=()=>{r._isReadyToPlay?(n._audioBuffer=r.getAudioBuffer(),n._isReadyToPlay=!0,n.autoplay&&n.play(0,n._offset,n._length)):setTimeout(e,300)};n=new sD(a,new ArrayBuffer(0),t,null,o),e()}else n=new sD(a,s,t,()=>{t.removePendingData(n)},o),t.addPendingData(n);if(e.position){let t=rf.P.FromArray(e.position);n.setPosition(t)}if(e.isDirectional&&(n.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){let t=rf.P.FromArray(e.localDirectionToMesh);n.setLocalDirectionToMesh(t)}if(e.connectedMeshId){let i=t.getMeshById(e.connectedMeshId);i&&n.attachToMesh(i)}return e.metadata&&(n.metadata=e.metadata),n}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){var e;this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(null===(e=sR.D.audioEngine)||void 0===e||e.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}sD._SceneComponentInitialization=e=>{throw(0,sM.S)("AudioSceneComponent")};class sO{constructor(e,t={}){if(this.id=-1,this._isInitialized=!1,!(e=e||rL.l.LastCreatedScene))return;this._scene=e,this.soundCollection=[],this._options=t,!this._options.mainTrack&&this._scene.soundTracks&&(this._scene.soundTracks.push(this),this.id=this._scene.soundTracks.length-1)}_initializeSoundTrackAudioGraph(){var e;(null===(e=sR.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)&&sR.D.audioEngine.audioContext&&(this._outputAudioNode=sR.D.audioEngine.audioContext.createGain(),this._outputAudioNode.connect(sR.D.audioEngine.masterGain),this._options&&this._options.volume&&(this._outputAudioNode.gain.value=this._options.volume),this._isInitialized=!0)}dispose(){if(sR.D.audioEngine&&sR.D.audioEngine.canUseWebAudio){for(this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas();this.soundCollection.length;)this.soundCollection[0].dispose();this._outputAudioNode&&this._outputAudioNode.disconnect(),this._outputAudioNode=null}}addSound(e){var t;this._isInitialized||this._initializeSoundTrackAudioGraph(),(null===(t=sR.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&e.connectToSoundTrackAudioNode(this._outputAudioNode),void 0!==e.soundTrackId&&(-1===e.soundTrackId?this._scene.mainSoundTrack.removeSound(e):this._scene.soundTracks&&this._scene.soundTracks[e.soundTrackId].removeSound(e)),this.soundCollection.push(e),e.soundTrackId=this.id}removeSound(e){let t=this.soundCollection.indexOf(e);-1!==t&&this.soundCollection.splice(t,1)}setVolume(e){var t;(null===(t=sR.D.audioEngine)||void 0===t?void 0:t.canUseWebAudio)&&this._outputAudioNode&&(this._outputAudioNode.gain.value=e)}switchPanningModelToHRTF(){var e;if(null===(e=sR.D.audioEngine)||void 0===e?void 0:e.canUseWebAudio)for(let e=0;e{var s;let n;let a=[];if(i.sounds=i.sounds||[],void 0!==e.sounds&&null!==e.sounds)for(let o=0,l=e.sounds.length;o{e.play(),e.autoplay=!0,this.scene.mainSoundTrack.addSound(e)})}removeFromContainer(e,t=!1){e.sounds&&e.sounds.forEach(e=>{e.stop(),e.autoplay=!1,this.scene.mainSoundTrack.removeSound(e),t&&e.dispose()})}dispose(){let e=this.scene;if(e._mainSoundTrack&&e.mainSoundTrack.dispose(),e.soundTracks)for(let t=0;t0&&(r=t.activeCameras[0]),this.audioListenerPositionProvider){let e=this.audioListenerPositionProvider();i.audioContext.listener.setPosition(e.x||0,e.y||0,e.z||0)}else r?this._cachedCameraPosition.equals(r.globalPosition)||(this._cachedCameraPosition.copyFrom(r.globalPosition),i.audioContext.listener.setPosition(r.globalPosition.x,r.globalPosition.y,r.globalPosition.z)):i.audioContext.listener.setPosition(0,0,0);if(this.audioListenerRotationProvider){let e=this.audioListenerRotationProvider();i.audioContext.listener.setOrientation(e.x||0,e.y||0,e.z||0,0,1,0)}else r?(r.rigCameras&&r.rigCameras.length>0&&(r=r.rigCameras[0]),r.getViewMatrix().invertToRef(this._invertMatrixTemp),rf.P.TransformNormalToRef(sF._CameraDirection,this._invertMatrixTemp,this._cameraDirectionTemp),this._cameraDirectionTemp.normalize(),isNaN(this._cameraDirectionTemp.x)||isNaN(this._cameraDirectionTemp.y)||isNaN(this._cameraDirectionTemp.z)||this._cachedCameraDirection.equals(this._cameraDirectionTemp)||(this._cachedCameraDirection.copyFrom(this._cameraDirectionTemp),i.audioContext.listener.setOrientation(this._cameraDirectionTemp.x,this._cameraDirectionTemp.y,this._cameraDirectionTemp.z,0,1,0))):i.audioContext.listener.setOrientation(0,0,0,0,1,0);for(e=0;e{let t=e._getComponent(sN.l.NAME_AUDIO);t||(t=new sF(e),e._addComponent(t))};class sL{constructor(e){if(this._texture=null,this._isEnabled=!0,this.isEnabled=!0,this.time=0,!(e=e||rL.l.LastCreatedScene))return;this._scene=e,this.animationParameters=new rf.Lt(0,0,0,30)}_markSubMeshesAsAttributesDirty(){for(let e of this._scene.meshes)e.bakedVertexAnimationManager===this&&e._markSubMeshesAsAttributesDirty()}bind(e,t=!1){if(!this._texture||!this._isEnabled)return;let i=this._texture.getSize();e.setFloat2("bakedVertexAnimationTextureSizeInverted",1/i.width,1/i.height),e.setFloat("bakedVertexAnimationTime",this.time),t||e.setVector4("bakedVertexAnimationSettings",this.animationParameters),e.setTexture("bakedVertexAnimationTexture",this._texture)}clone(){let e=new sL(this._scene);return this.copyTo(e),e}setAnimationParameters(e,t,i=0,r=30){this.animationParameters=new rf.Lt(e,t,i,r)}dispose(e){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"BakedVertexAnimationManager"}copyTo(e){rG.p4.Clone(()=>e,this)}serialize(){return rG.p4.Serialize(this)}parse(e,t,i){rG.p4.Parse(()=>this,e,t,i)}}(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markSubMeshesAsAttributesDirty")],sL.prototype,"texture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markSubMeshesAsAttributesDirty")],sL.prototype,"isEnabled",void 0),(0,sx.gn)([(0,rG.qC)()],sL.prototype,"animationParameters",void 0),(0,sx.gn)([(0,rG.qC)()],sL.prototype,"time",void 0);var sw=i(1032),sB=i(1166);class sU{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(null==e?void 0:e._shareDepth)!==void 0}constructor(e){this._wrapU=1,this._wrapV=1,this.wrapR=1,this.anisotropicFilteringLevel=4,this.delayLoadState=0,this._texture=null,this._engine=null,this._cachedSize=rH.Zero(),this._cachedBaseSize=rH.Zero(),this._initialSamplingMode=2,this._texture=sU._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return 4===this.delayLoadState?(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;this._texture._size&&(this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size)}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.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight):(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)}}class sV extends sU{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(1,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){var t;if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){var t;e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,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=(0,sw.f)()),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=0,this.wrapR=1,this.anisotropicFilteringLevel=sV.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 r_.y$,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?sV._IsScene(e)?this._scene=e:this._engine=e:this._scene=rL.l.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}checkTransformsAreIdentical(e){return null!==e}getTextureMatrix(){return rf.y3.IdentityReadOnly}getReflectionTextureMatrix(){return rf.y3.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,i,r,s,n){let a=this._getEngine();if(!a)return null;let o=a._getUseSRGBBuffer(!!s,t),l=a.getLoadedTexturesCache();for(let a=0;a=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){let 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;let t=rG.p4.Serialize(this);return rG.p4.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let i=e.length;if(0===i){t();return}for(let r=0;r{0==--i&&t()}):0==--i&&t()}}}static _IsScene(e){return"Scene"===e.getClassName()}}sV.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,(0,sx.gn)([(0,rG.qC)()],sV.prototype,"uniqueId",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"name",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"metadata",void 0),(0,sx.gn)([(0,rG.qC)("hasAlpha")],sV.prototype,"_hasAlpha",void 0),(0,sx.gn)([(0,rG.qC)("getAlphaFromRGB")],sV.prototype,"_getAlphaFromRGB",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"level",void 0),(0,sx.gn)([(0,rG.qC)("coordinatesIndex")],sV.prototype,"_coordinatesIndex",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"optimizeUVAllocation",void 0),(0,sx.gn)([(0,rG.qC)("coordinatesMode")],sV.prototype,"_coordinatesMode",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"wrapU",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"wrapV",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"wrapR",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"anisotropicFilteringLevel",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"isCube",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"is3D",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"is2DArray",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"gammaSpace",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"invertZ",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"lodLevelInAlpha",void 0),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"lodGenerationOffset",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"lodGenerationScale",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"linearSpecularLOD",null),(0,sx.gn)([(0,rG.oU)()],sV.prototype,"irradianceTexture",null),(0,sx.gn)([(0,rG.qC)()],sV.prototype,"isRenderTarget",void 0);var sk=i(4490),sG=i(4406),sz=i(1564),sW=i(9005);function sH(e,t,i=!1){let r=t.width,s=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT,i=new Uint8Array(t);for(;--t>=0;){let r=e[t];r<0?r=0:r>1&&(r=1),i[t]=255*r}e=i}let n=document.createElement("canvas");n.width=r,n.height=s;let a=n.getContext("2d");if(!a)return null;let o=a.createImageData(r,s);if(o.data.set(e),a.putImageData(o,0,0),i){let e=document.createElement("canvas");e.width=r,e.height=s;let t=e.getContext("2d");return t?(t.translate(0,s),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}async function sX(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=await e.readPixels(t,i);return s?sH(s,e.getSize(),r.invertY):null}var sY=i(6705);class sj extends sV{static _CreateVideoTexture(e,t,i,r=!1,s=!1,n=sj.TRILINEAR_SAMPLINGMODE,a={},o,l=5){throw(0,sM.S)("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,i,r,s=sj.TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,l=!1,h,u,c,d,p){var _,f,m,g,v,x,T,S,E,C;let b;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._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 r_.y$,this._isBlocking=!0,this.name=e||"",this.url=e;let y=!1,A=null,R=!0;"object"==typeof i&&null!==i?(b=null!==(_=i.noMipmap)&&void 0!==_&&_,r=null!==(f=i.invertY)&&void 0!==f?f:!sY.e.UseOpenGLOrientationForUV,s=null!==(m=i.samplingMode)&&void 0!==m?m:sj.TRILINEAR_SAMPLINGMODE,n=null!==(g=i.onLoad)&&void 0!==g?g:null,a=null!==(v=i.onError)&&void 0!==v?v:null,o=null!==(x=i.buffer)&&void 0!==x?x:null,l=null!==(T=i.deleteBuffer)&&void 0!==T&&T,h=i.format,u=i.mimeType,c=i.loaderOptions,d=i.creationFlags,y=null!==(S=i.useSRGBBuffer)&&void 0!==S&&S,A=null!==(E=i.internalTexture)&&void 0!==E?E:null,R=null!==(C=i.gammaSpace)&&void 0!==C?C:R):b=!!i,this._gammaSpace=R,this._noMipmap=b,this._invertY=void 0===r?!sY.e.UseOpenGLOrientationForUV:r,this._initialSamplingMode=s,this._buffer=o,this._deleteBuffer=l,this._mimeType=u,this._loaderOptions=c,this._creationFlags=d,this._useSRGBBuffer=y,this._forcedExtension=p,h&&(this._format=h);let P=this.getScene(),I=this._getEngine();if(!I)return;I.onBeforeTextureInitObservable.notifyObservers(this);let M=()=>{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&&P&&P.resetCachedMaterial()},D=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),sj.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!A){this._delayedOnLoad=M,this._delayedOnError=D;return}if(this._texture=null!=A?A:this._getFromCache(this.url,b,s,this._invertY,y,this.isCube),this._texture){if(this._texture.isReady)sk.Q.SetImmediate(()=>M());else{let e=this._texture.onLoadedObservable.add(M);this._texture.onErrorObservable.add(t=>{var i;D(t.message,t.exception),null===(i=this._texture)||void 0===i||i.onLoadedObservable.remove(e)})}}else if(P&&P.useDelayedTextureLoading)this.delayLoadState=4,this._delayedOnLoad=M,this._delayedOnError=D;else{try{this._texture=I.createTexture(this.url,b,this._invertY,P,s,M,D,this._buffer,void 0,this._format,this._forcedExtension,u,c,d,y)}catch(e){throw D("error loading",e),e}l&&(this._buffer=null)}}updateURL(e,t=null,i,r){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(1,e=>e.hasTexture(this))),(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=r,this.delayLoadState=4,i&&(this._delayedOnLoad=i),this.delayLoad()}delayLoad(){if(4!==this.delayLoadState)return;let e=this.getScene();e&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?sk.Q.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,i,r){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,i-=this.wRotationCenter,rf.P.TransformCoordinatesFromFloatsToRef(e,t,i,this._rowGenerationMatrix,r),r.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,r.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,r.z+=this.wRotationCenter}checkTransformsAreIdentical(e){return null!==e&&this.uOffset===e.uOffset&&this.vOffset===e.vOffset&&this.uScale===e.uScale&&this.vScale===e.vScale&&this.uAng===e.uAng&&this.vAng===e.vAng&&this.wAng===e.wAng}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=rf.y3.Zero(),this._rowGenerationMatrix=new rf.y3,this._t0=rf.P.Zero(),this._t1=rf.P.Zero(),this._t2=rf.P.Zero()),rf.y3.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(rf.y3.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,rf.jp.Matrix[0]),rf.y3.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,rf.jp.Matrix[1]),rf.y3.ScalingToRef(this._cachedUScale,this._cachedVScale,0,rf.jp.Matrix[2]),rf.y3.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,rf.jp.Matrix[3]),rf.jp.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rf.jp.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rf.jp.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(rf.jp.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),rf.y3.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));let t=this.getScene();return t&&this.optimizeUVAllocation&&t.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedTextureMatrix}getReflectionTextureMatrix(){let e=this.getScene();if(!e||this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode&&(this.coordinatesMode!==sj.PROJECTION_MODE||this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag))return this._cachedReflectionTextureMatrix;this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=rf.y3.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=rf.y3.Zero());let 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 sj.PLANAR_MODE:rf.y3.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 sj.PROJECTION_MODE:{rf.y3.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);let t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:rf.y3.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this)),this._cachedReflectionTextureMatrix}clone(){let 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 rG.p4.Clone(()=>new sj(this._texture?this._texture.url:null,this.getScene(),e),this)}serialize(){var e,t;let i=this.name;!sj.SerializeBuffers&&this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");let r=super.serialize(sj._SerializeInternalTextureUniqueId);return r?((sj.SerializeBuffers||sj.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(r.base64String=this._buffer,r.name=r.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?r.base64String="data:image/png;base64,"+(0,sW.Gh)(this._buffer):(sj.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(r.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,i=0){let r=e.getInternalTexture();if(!r)return null;let s=e._readPixelsSync(t,i);return s?sH(s,e.getSize(),r.invertY):null}(this):sX(this))),r.invertY=this._invertY,r.samplingMode=this.samplingMode,r._creationFlags=this._creationFlags,r._useSRGBBuffer=this._useSRGBBuffer,sj._SerializeInternalTextureUniqueId&&(r.internalTextureUniqueId=null!==(t=null===(e=this._texture)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:void 0),r.noMipmap=this._noMipmap,this.name=i,r):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,i){let r;if(e.customType){let r=sG.K.Instantiate(e.customType).Parse(e,t,i);return e.samplingMode&&r.updateSamplingMode&&r._samplingMode&&r._samplingMode!==e.samplingMode&&r.updateSamplingMode(e.samplingMode),r}if(e.isCube&&!e.isRenderTarget)return sj._CubeTextureParser(e,t,i);let s=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!s)return null;if(s){for(let i of t.getEngine().getLoadedTexturesCache())if(i.uniqueId===e.internalTextureUniqueId){r=i;break}}let n=t=>{var i;if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){let i=e.samplingMode;t&&t.samplingMode!==i&&t.updateSamplingMode(i)}if(t&&e.animations)for(let i=0;i{var s,a,o;let l=!0;if(e.noMipmap&&(l=!1),e.mirrorPlane){let i=sj._CreateMirror(e.name,e.renderTargetSize,t,l);return i._waitingRenderList=e.renderList,i.mirrorPlane=sz.J.FromArray(e.mirrorPlane),n(i),i}if(e.isRenderTarget){let i=null;if(e.isCube){if(t.reflectionProbes)for(let i=0;i{n(s)},null!==(a=e._creationFlags)&&void 0!==a?a:0,null!==(o=e._useSRGBBuffer)&&void 0!==o&&o)).name=e.name;else{let a;a=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:i+e.name,e.url&&(e.url.startsWith("data:")||sj.UseSerializedUrlIfAny)&&(a=e.url),s=new sj(a,t,{noMipmap:!l,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(s)},internalTexture:r})}return s}},e,t)}static CreateFromBase64String(e,t,i,r,s,n=sj.TRILINEAR_SAMPLINGMODE,a=null,o=null,l=5,h){return new sj("data:"+t,i,r,s,n,a,o,e,!1,l,void 0,void 0,h)}static LoadFromDataString(e,t,i,r=!1,s,n=!0,a=sj.TRILINEAR_SAMPLINGMODE,o=null,l=null,h=5,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new sj(e,i,s,n,a,o,l,t,r,h,void 0,void 0,u)}}sj.SerializeBuffers=!0,sj.ForceSerializeBuffers=!1,sj.OnTextureLoadErrorObservable=new r_.y$,sj._SerializeInternalTextureUniqueId=!1,sj._CubeTextureParser=(e,t,i)=>{throw(0,sM.S)("CubeTexture")},sj._CreateMirror=(e,t,i,r)=>{throw(0,sM.S)("MirrorTexture")},sj._CreateRenderTargetTexture=(e,t,i,r,s)=>{throw(0,sM.S)("RenderTargetTexture")},sj.NEAREST_SAMPLINGMODE=1,sj.NEAREST_NEAREST_MIPLINEAR=8,sj.BILINEAR_SAMPLINGMODE=2,sj.LINEAR_LINEAR_MIPNEAREST=11,sj.TRILINEAR_SAMPLINGMODE=3,sj.LINEAR_LINEAR_MIPLINEAR=3,sj.NEAREST_NEAREST_MIPNEAREST=4,sj.NEAREST_LINEAR_MIPNEAREST=5,sj.NEAREST_LINEAR_MIPLINEAR=6,sj.NEAREST_LINEAR=7,sj.NEAREST_NEAREST=1,sj.LINEAR_NEAREST_MIPNEAREST=9,sj.LINEAR_NEAREST_MIPLINEAR=10,sj.LINEAR_LINEAR=2,sj.LINEAR_NEAREST=12,sj.EXPLICIT_MODE=0,sj.SPHERICAL_MODE=1,sj.PLANAR_MODE=2,sj.CUBIC_MODE=3,sj.PROJECTION_MODE=4,sj.SKYBOX_MODE=5,sj.INVCUBIC_MODE=6,sj.EQUIRECTANGULAR_MODE=7,sj.FIXED_EQUIRECTANGULAR_MODE=8,sj.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,sj.CLAMP_ADDRESSMODE=0,sj.WRAP_ADDRESSMODE=1,sj.MIRROR_ADDRESSMODE=2,sj.UseSerializedUrlIfAny=!1,(0,sx.gn)([(0,rG.qC)()],sj.prototype,"url",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"uOffset",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"vOffset",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"uScale",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"vScale",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"uAng",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"vAng",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"wAng",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"uRotationCenter",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"vRotationCenter",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"wRotationCenter",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"homogeneousRotationInUVTransform",void 0),(0,sx.gn)([(0,rG.qC)()],sj.prototype,"isBlocking",null),(0,rg.H)("BABYLON.Texture",sj),rG.p4._TextureParser=sj.Parse;var sq=i(3912),sK=i(6465);function s$(e,t,i,r){let s;let n=1;1===r?s=new Float32Array(t*i*4):2===r?(s=new Uint16Array(t*i*4),n=15360):s=7===r?new Uint32Array(t*i*4):new Uint8Array(t*i*4);for(let r=0;r{let i=p.width,n=a(e);if(n){if(o){let e=this._getWebGLTextureType(s),t=this._getInternalFormat(r),a=this._getRGBABufferInternalSizedFormat(s),l=!1;t===d.RGB&&(t=d.RGBA,l=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,p,!0),this._unpackFlipY(!1);let h=o(n);for(let r=0;r>r;for(let i=0;i<6;i++){let o=h[r][i];l&&(o=s$(o,n,n,s)),d.texImage2D(i,r,a,n,n,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(p,n,r,s,c);p.isReady=!0,null==t||t.removePendingData(p),p.onLoadedObservable.notifyObservers(p),p.onLoadedObservable.clear(),l&&l()}};return this._loadFile(e,e=>{_(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(p),h&&e&&h(e.status+" "+e.statusText,i)}),p},sK.B.prototype.createRawTexture2DArray=sQ(!1),sK.B.prototype.createRawTexture3D=sQ(!0),sK.B.prototype.updateRawTexture2DArray=sZ(!1),sK.B.prototype.updateRawTexture3D=sZ(!0);class sJ extends sj{constructor(e,t,i,r,s,n=!0,a=!1,o=3,l=0,h,u){if(super(null,s,!n,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,h),this.format=r,!this._engine)return;this._engine._caps.textureFloatLinearFiltering||1!==l||(o=1),this._engine._caps.textureHalfFloatLinearFiltering||2!==l||(o=1),this._texture=this._engine.createRawTexture(e,t,i,r,n,a,o,null,l,null!=h?h:0,null!=u&&u),this.wrapU=sj.CLAMP_ADDRESSMODE,this.wrapV=sj.CLAMP_ADDRESSMODE}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}static CreateLuminanceTexture(e,t,i,r,s=!0,n=!1,a=3){return new sJ(e,t,i,1,r,s,n,a)}static CreateLuminanceAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new sJ(e,t,i,2,r,s,n,a)}static CreateAlphaTexture(e,t,i,r,s=!0,n=!1,a=3){return new sJ(e,t,i,0,r,s,n,a)}static CreateRGBTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new sJ(e,t,i,4,r,s,n,a,o,l,h)}static CreateRGBATexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=0,h=!1){return new sJ(e,t,i,5,r,s,n,a,o,l,h)}static CreateRGBAStorageTexture(e,t,i,r,s=!0,n=!1,a=3,o=0,l=!1){return new sJ(e,t,i,5,r,s,n,a,o,1,l)}static CreateRTexture(e,t,i,r,s=!0,n=!1,a=sj.TRILINEAR_SAMPLINGMODE,o=1){return new sJ(e,t,i,6,r,s,n,a,o)}static CreateRStorageTexture(e,t,i,r,s=!0,n=!1,a=sj.TRILINEAR_SAMPLINGMODE,o=1){return new sJ(e,t,i,6,r,s,n,a,o,1)}}var s0=i(6114);class s1{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;let t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===s0.kD.POINTERDOWN){this._isPointerDown=!0;return}e.type===s0.kD.POINTERUP&&(this._isPointerDown=!1)}),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add(()=>{if(this._reachTargetAlpha())return;let e=r3.F.Now,t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();let i=Math.max(Math.min((e-this._lastInteractionTime-this._idleRotationWaitTime)/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*i,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))})}detach(){if(!this._attachedCamera)return;let e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=null!=e?e:r3.F.Now}_reachTargetAlpha(){return!!this._attachedCamera&&!!this.targetAlpha&&Math.abs(this._attachedCamera.alpha-this.targetAlpha){if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){let 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||(s2.EasingFunction.setEasingMode(s2.EasingMode),this._radiusBounceTransition=rJ.CreateAnimation("radius",rJ.ANIMATIONTYPE_FLOAT,60,s2.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;let t=rJ.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()}}s2.EasingFunction=new sa(.3),s2.EasingMode=ss.EASINGMODE_EASEOUT;class s3{constructor(){this.onTargetFramingAnimationEndObservable=new r_.y$,this._mode=s3.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=[],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;let t=this._attachedCamera.getScene();s3.EasingFunction.setEasingMode(s3.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add(e=>{if(e.type===s0.kD.POINTERDOWN){this._isPointerDown=!0;return}e.type===s0.kD.POINTERUP&&(this._isPointerDown=!1)}),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;let 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,i=null){e.computeWorldMatrix(!0);let r=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(r.minimumWorld,r.maximumWorld,t,i)}zoomOnMeshHierarchy(e,t=!1,i=null){e.computeWorldMatrix(!0);let r=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(r.min,r.max,t,i)}zoomOnMeshesHierarchy(e,t=!1,i=null){let r=new rf.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new rf.P(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t{this.stopAllAnimations(),r&&r(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()}))&&this._animatables.push(l),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){let i=this._attachedCamera;if(!i)return 0;let r=i._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return i.lowerRadiusLimit&&this._mode===s3.IgnoreBoundsSizeMode&&(r=ri.upperRadiusLimit?i.upperRadiusLimit:r),r}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;let e=r3.F.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>.5*Math.PI&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=rJ.CreateAnimation("beta",rJ.ANIMATIONTYPE_FLOAT,60,s3.EasingFunction));let e=rJ.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=r3.F.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)}}s3.EasingFunction=new so,s3.EasingMode=ss.EASINGMODE_EASEINOUT,s3.IgnoreBoundsSizeMode=0,s3.FitFrustumSidesMode=1;var s4=i(2248),s5=i(9372);class s6{constructor(e,t,i=Number.MAX_VALUE){this.origin=e,this.direction=t,this.length=i}clone(){return new s6(this.origin.clone(),this.direction.clone(),this.length)}intersectsBoxMinMax(e,t,i=0){let r,s,n,a;let o=s6._TmpVector3[0].copyFromFloats(e.x-i,e.y-i,e.z-i),l=s6._TmpVector3[1].copyFromFloats(t.x+i,t.y+i,t.z+i),h=0,u=Number.MAX_VALUE;if(1e-7>Math.abs(this.direction.x)){if(this.origin.xl.x)return!1}else if(r=1/this.direction.x,s=(o.x-this.origin.x)*r,(n=(l.x-this.origin.x)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.y)){if(this.origin.yl.y)return!1}else if(r=1/this.direction.y,s=(o.y-this.origin.y)*r,(n=(l.y-this.origin.y)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;if(1e-7>Math.abs(this.direction.z)){if(this.origin.zl.z)return!1}else if(r=1/this.direction.z,s=(o.z-this.origin.z)*r,(n=(l.z-this.origin.z)*r)==-1/0&&(n=1/0),s>n&&(a=s,s=n,n=a),(h=Math.max(s,h))>(u=Math.min(n,u)))return!1;return!0}intersectsBox(e,t=0){return this.intersectsBoxMinMax(e.minimum,e.maximum,t)}intersectsSphere(e,t=0){let i=e.center.x-this.origin.x,r=e.center.y-this.origin.y,s=e.center.z-this.origin.z,n=i*i+r*r+s*s,a=e.radius+t,o=a*a;if(n<=o)return!0;let l=i*this.direction.x+r*this.direction.y+s*this.direction.z;return!(l<0)&&n-l*l<=o}intersectsTriangle(e,t,i){let r=s6._TmpVector3[0],s=s6._TmpVector3[1],n=s6._TmpVector3[2],a=s6._TmpVector3[3],o=s6._TmpVector3[4];t.subtractToRef(e,r),i.subtractToRef(e,s),rf.P.CrossToRef(this.direction,s,n);let l=rf.P.Dot(r,n);if(0===l)return null;let h=1/l;this.origin.subtractToRef(e,a);let u=rf.P.Dot(a,n)*h;if(u<0||u>1)return null;rf.P.CrossToRef(a,r,o);let c=rf.P.Dot(this.direction,o)*h;if(c<0||u+c>1)return null;let d=rf.P.Dot(s,o)*h;return d>this.length?null:new s5.c(1-u-c,u,d)}intersectsPlane(e){let t;let i=rf.P.Dot(e.normal,this.direction);if(999999997475243e-21>Math.abs(i))return null;{let r=rf.P.Dot(e.normal,this.origin);return(t=(-e.d-r)/i)<0?t<-.000000999999997475243?null:0:t}}intersectsAxis(e,t=0){switch(e){case"y":{let e=(this.origin.y-t)/this.direction.y;if(e>0)return null;return new rf.P(this.origin.x+-(this.direction.x*e),t,this.origin.z+-(this.direction.z*e))}case"x":{let e=(this.origin.x-t)/this.direction.x;if(e>0)return null;return new rf.P(t,this.origin.y+-(this.direction.y*e),this.origin.z+-(this.direction.z*e))}case"z":{let e=(this.origin.z-t)/this.direction.z;if(e>0)return null;return new rf.P(this.origin.x+-(this.direction.x*e),this.origin.y+-(this.direction.y*e),t)}default:return null}}intersectsMesh(e,t,i,r=!1,s,n=!1){let a=rf.jp.Matrix[0];return e.getWorldMatrix().invertToRef(a),this._tmpRay?s6.TransformToRef(this,a,this._tmpRay):this._tmpRay=s6.Transform(this,a),e.intersects(this._tmpRay,t,i,r,s,n)}intersectsMeshes(e,t,i){i?i.length=0:i=[];for(let r=0;rt.distance?1:0}intersectionSegment(e,t,i){let r=this.origin,s=rf.jp.Vector3[0],n=rf.jp.Vector3[1],a=rf.jp.Vector3[2],o=rf.jp.Vector3[3];t.subtractToRef(e,s),this.direction.scaleToRef(s6._Rayl,a),r.addToRef(a,n),e.subtractToRef(r,o);let l=rf.P.Dot(s,s),h=rf.P.Dot(s,a),u=rf.P.Dot(a,a),c=rf.P.Dot(s,o),d=rf.P.Dot(a,o),p=l*u-h*h,_,f=p,m,g=p;pf&&(_=f,m=d+h,g=u)),m<0?(m=0,0>-c?_=0:-c>l?_=f:(_=-c,f=l)):m>g&&(m=g,-c+h<0?_=0:-c+h>l?_=f:(_=-c+h,f=l));let v=Math.abs(_)0&&x<=this.length&&E.lengthSquared()=e.distance))?h:null},r2.x.prototype._internalPick=function(e,t,i,r,s){let n=null,a=!!(this.activeCameras&&this.activeCameras.length>1&&this.cameraToUseForPointers!==this.activeCamera),o=this.cameraToUseForPointers||this.activeCamera;for(let l=0;l1&&this.cameraToUseForPointers!==this.activeCamera),n=this.cameraToUseForPointers||this.activeCamera;for(let a=0;a(this._tempPickingRay||(this._tempPickingRay=s6.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null),this._tempPickingRay),i,r,!0);return n&&(n.ray=this.createPickingRay(e,t,rf.y3.Identity(),s||null)),n},Object.defineProperty(r2.x.prototype,"_pickingAvailable",{get:()=>!0,enumerable:!1,configurable:!1}),r2.x.prototype.pick=function(e,t,i,r,s,n,a=!1){let o=this._internalPick((i,r)=>(this._tempPickingRay||(this._tempPickingRay=s6.Zero()),this.createPickingRayToRef(e,t,i,this._tempPickingRay,s||null,!1,r),this._tempPickingRay),i,r,!1,n);return o&&(o.ray=this.createPickingRay(e,t,rf.y3.Identity(),s||null)),o},r2.x.prototype.pickWithRay=function(e,t,i,r){let s=this._internalPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=rf.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=s6.Zero()),s6.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i,!1,r);return s&&(s.ray=e),s},r2.x.prototype.multiPick=function(e,t,i,r,s){return this._internalMultiPick(i=>this.createPickingRay(e,t,i,r||null),i,s)},r2.x.prototype.multiPickWithRay=function(e,t,i){return this._internalMultiPick(t=>(this._pickWithRayInverseMatrix||(this._pickWithRayInverseMatrix=rf.y3.Identity()),t.invertToRef(this._pickWithRayInverseMatrix),this._cachedRayForTransform||(this._cachedRayForTransform=s6.Zero()),s6.TransformToRef(e,this._pickWithRayInverseMatrix,this._cachedRayForTransform),this._cachedRayForTransform),t,i)},sC.V.prototype.getForwardRay=function(e=100,t,i){return this.getForwardRayToRef(new s6(rf.P.Zero(),rf.P.Zero(),e),e,t,i)},sC.V.prototype.getForwardRayToRef=function(e,t=100,i,r){i||(i=this.getWorldMatrix()),e.length=t,r?e.origin.copyFrom(r):e.origin.copyFrom(this.position);let s=rf.jp.Vector3[2];s.set(0,0,this._scene.useRightHandedSystem?-1:1);let n=rf.jp.Vector3[3];return rf.P.TransformNormalToRef(s,i,n),rf.P.NormalizeToRef(n,e.direction),e};class s8{static _RemoveAndStorePivotPoint(e){e&&0===s8._PivotCached&&(e.getPivotPointToRef(s8._OldPivotPoint),s8._PivotPostMultiplyPivotMatrix=e._postMultiplyPivotMatrix,s8._OldPivotPoint.equalsToFloats(0,0,0)||(e.setPivotMatrix(rf.y3.IdentityReadOnly),s8._OldPivotPoint.subtractToRef(e.getPivotPoint(),s8._PivotTranslation),s8._PivotTmpVector.copyFromFloats(1,1,1),s8._PivotTmpVector.subtractInPlace(e.scaling),s8._PivotTmpVector.multiplyInPlace(s8._PivotTranslation),e.position.addInPlace(s8._PivotTmpVector))),s8._PivotCached++}static _RestorePivotPoint(e){e&&!s8._OldPivotPoint.equalsToFloats(0,0,0)&&1===s8._PivotCached&&(e.setPivotPoint(s8._OldPivotPoint),e._postMultiplyPivotMatrix=s8._PivotPostMultiplyPivotMatrix,s8._PivotTmpVector.copyFromFloats(1,1,1),s8._PivotTmpVector.subtractInPlace(e.scaling),s8._PivotTmpVector.multiplyInPlace(s8._PivotTranslation),e.position.subtractInPlace(s8._PivotTmpVector)),this._PivotCached--}}s8._PivotCached=0,s8._OldPivotPoint=new rf.P,s8._PivotTranslation=new rf.P,s8._PivotTmpVector=new rf.P,s8._PivotPostMultiplyPivotMatrix=!1;var s7=i(2696);function s9(e){let t=[],i=[],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE,l=n/2,h=a/2;i.push(-l,-h,0),r.push(0,0,-1),s.push(0,sY.e.UseOpenGLOrientationForUV?1:0),i.push(l,-h,0),r.push(0,0,-1),s.push(1,sY.e.UseOpenGLOrientationForUV?1:0),i.push(l,h,0),r.push(0,0,-1),s.push(1,sY.e.UseOpenGLOrientationForUV?0:1),i.push(-l,h,0),r.push(0,0,-1),s.push(0,sY.e.UseOpenGLOrientationForUV?0:1),t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),s7.x._ComputeSides(o,i,t,r,s,e.frontUVs,e.backUVs);let u=new s7.x;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function ne(e,t={},i=null){let r=new sp.Kj(e,i);return t.sideOrientation=sp.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,s9(t).applyToMesh(r,t.updatable),t.sourcePlane&&(r.translate(t.sourcePlane.normal,-t.sourcePlane.d),r.setDirection(t.sourcePlane.normal.scale(-1))),r}s7.x.CreatePlane=s9,sp.Kj.CreatePlane=(e,t,i,r,s)=>ne(e,{size:t,width:t,height:t,sideOrientation:s,updatable:r},i);class nt{get currentDraggingPointerID(){return this.currentDraggingPointerId}set currentDraggingPointerID(e){this.currentDraggingPointerId=e}set enabled(e){e!=this._enabled&&this.onEnabledObservable.notifyObservers(e),this._enabled=e}get enabled(){return this._enabled}get options(){return this._options}set options(e){this._options=e}constructor(e){this._useAlternatePickedPointAboveMaxDragAngleDragSpeed=-1.1,this._activeDragButton=-1,this.maxDragAngle=0,this.dragButtons=[0,1,2],this._useAlternatePickedPointAboveMaxDragAngle=!1,this.currentDraggingPointerId=-1,this.dragging=!1,this.dragDeltaRatio=.2,this.updateDragPlane=!0,this._debugMode=!1,this._moving=!1,this.onDragObservable=new r_.y$,this.onDragStartObservable=new r_.y$,this.onDragEndObservable=new r_.y$,this.onEnabledObservable=new r_.y$,this.moveAttached=!0,this._enabled=!0,this.startAndReleaseDragOnPointerEvents=!0,this.detachCameraControls=!0,this.useObjectOrientationForDragging=!0,this.validateDrag=e=>!0,this._tmpVector=new rf.P(0,0,0),this._alternatePickedPoint=new rf.P(0,0,0),this._worldDragAxis=new rf.P(0,0,0),this._targetPosition=new rf.P(0,0,0),this._attachedToElement=!1,this._startDragRay=new s6(new rf.P,new rf.P),this._lastPointerRay={},this._dragDelta=new rf.P,this._pointA=new rf.P(0,0,0),this._pointC=new rf.P(0,0,0),this._localAxis=new rf.P(0,0,0),this._lookAt=new rf.P(0,0,0),this._options=e||{};let t=0;if(this._options.dragAxis&&t++,this._options.dragPlaneNormal&&t++,t>1)throw"Multiple drag modes specified in dragBehavior options. Only one expected"}get name(){return"PointerDrag"}init(){}attach(e,t){this._scene=e.getScene(),e.isNearGrabbable=!0,this.attachedNode=e,nt._PlaneScene||(this._debugMode?nt._PlaneScene=this._scene:(nt._PlaneScene=new r2.x(this._scene.getEngine(),{virtual:!0}),nt._PlaneScene.detachControl(),this._scene.onDisposeObservable.addOnce(()=>{nt._PlaneScene.dispose(),nt._PlaneScene=null}))),this._dragPlane=ne("pointerDragPlane",{size:this._debugMode?1:1e4,updatable:!1,sideOrientation:sp.Kj.DOUBLESIDE},nt._PlaneScene),this.lastDragPosition=new rf.P(0,0,0);let i=t||(e=>this.attachedNode==e||e.isDescendantOf(this.attachedNode));this._pointerObserver=this._scene.onPointerObservable.add(e=>{if(!this.enabled){this._attachedToElement&&this.releaseDrag();return}if(e.type==s0.kD.POINTERDOWN)this.startAndReleaseDragOnPointerEvents&&!this.dragging&&e.pickInfo&&e.pickInfo.hit&&e.pickInfo.pickedMesh&&e.pickInfo.pickedPoint&&e.pickInfo.ray&&i(e.pickInfo.pickedMesh)&&-1===this._activeDragButton&&-1!==this.dragButtons.indexOf(e.event.button)&&(this._activeDragButton=e.event.button,this._activePointerInfo=e,this._startDrag(e.event.pointerId,e.pickInfo.ray,e.pickInfo.pickedPoint));else if(e.type==s0.kD.POINTERUP)this.startAndReleaseDragOnPointerEvents&&this.currentDraggingPointerId==e.event.pointerId&&(this._activeDragButton===e.event.button||-1===this._activeDragButton)&&this.releaseDrag();else if(e.type==s0.kD.POINTERMOVE){let t=e.event.pointerId;if(this.currentDraggingPointerId===nt._AnyMouseId&&t!==nt._AnyMouseId){let i=e.event;("mouse"===i.pointerType||!this._scene.getEngine().hostInformation.isMobile&&i instanceof MouseEvent)&&(this._lastPointerRay[this.currentDraggingPointerId]&&(this._lastPointerRay[t]=this._lastPointerRay[this.currentDraggingPointerId],delete this._lastPointerRay[this.currentDraggingPointerId]),this.currentDraggingPointerId=t)}this._lastPointerRay[t]||(this._lastPointerRay[t]=new s6(new rf.P,new rf.P)),e.pickInfo&&e.pickInfo.ray&&(this._lastPointerRay[t].origin.copyFrom(e.pickInfo.ray.origin),this._lastPointerRay[t].direction.copyFrom(e.pickInfo.ray.direction),this.currentDraggingPointerId==t&&this.dragging&&this._moveDrag(e.pickInfo.ray))}}),this._beforeRenderObserver=this._scene.onBeforeRenderObservable.add(()=>{if(this._moving&&this.moveAttached){let e=!1;s8._RemoveAndStorePivotPoint(this.attachedNode),this._targetPosition.subtractToRef(this.attachedNode.absolutePosition,this._tmpVector),this._tmpVector.scaleInPlace(this.dragDeltaRatio),this.attachedNode.getAbsolutePosition().addToRef(this._tmpVector,this._tmpVector),this.validateDrag(this._tmpVector)&&(this.attachedNode.setAbsolutePosition(this._tmpVector),e=!0),s8._RestorePivotPoint(this.attachedNode),e&&this.attachedNode.computeWorldMatrix()}})}releaseDrag(){if(this.dragging&&(this.dragging=!1,this.onDragEndObservable.notifyObservers({dragPlanePoint:this.lastDragPosition,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo})),this.currentDraggingPointerId=-1,this._activeDragButton=-1,this._activePointerInfo=null,this._moving=!1,this.detachCameraControls&&this._attachedToElement&&this._scene.activeCamera&&!this._scene.activeCamera.leftCamera){if("ArcRotateCamera"===this._scene.activeCamera.getClassName()){let e=this._scene.activeCamera;e.attachControl(!e.inputs||e.inputs.noPreventDefault,e._useCtrlForPanning,e._panningMouseButton)}else this._scene.activeCamera.attachControl(!this._scene.activeCamera.inputs||this._scene.activeCamera.inputs.noPreventDefault);this._attachedToElement=!1}}startDrag(e=nt._AnyMouseId,t,i){this._startDrag(e,t,i);let r=this._lastPointerRay[e];e===nt._AnyMouseId&&(r=this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]),r&&this._moveDrag(r)}_startDrag(e,t,i){if(!this._scene.activeCamera||this.dragging||!this.attachedNode)return;s8._RemoveAndStorePivotPoint(this.attachedNode),t?(this._startDragRay.direction.copyFrom(t.direction),this._startDragRay.origin.copyFrom(t.origin)):(this._startDragRay.origin.copyFrom(this._scene.activeCamera.position),this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector),this._tmpVector.subtractToRef(this._scene.activeCamera.position,this._startDragRay.direction)),this._updateDragPlanePosition(this._startDragRay,i||this._tmpVector);let r=this._pickWithRayOnDragPlane(this._startDragRay);r?(this.dragging=!0,this.currentDraggingPointerId=e,this.lastDragPosition.copyFrom(r),this.onDragStartObservable.notifyObservers({dragPlanePoint:r,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this._targetPosition.copyFrom(this.attachedNode.getAbsolutePosition()),this.detachCameraControls&&this._scene.activeCamera&&this._scene.activeCamera.inputs&&!this._scene.activeCamera.leftCamera&&(this._scene.activeCamera.inputs.attachedToElement?(this._scene.activeCamera.detachControl(),this._attachedToElement=!0):this._attachedToElement=!1)):this.releaseDrag(),s8._RestorePivotPoint(this.attachedNode)}_moveDrag(e){this._moving=!0;let t=this._pickWithRayOnDragPlane(e);if(t){s8._RemoveAndStorePivotPoint(this.attachedNode),this.updateDragPlane&&this._updateDragPlanePosition(e,t);let i=0;this._options.dragAxis?(this.useObjectOrientationForDragging?rf.P.TransformCoordinatesToRef(this._options.dragAxis,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._worldDragAxis):this._worldDragAxis.copyFrom(this._options.dragAxis),t.subtractToRef(this.lastDragPosition,this._tmpVector),i=rf.P.Dot(this._tmpVector,this._worldDragAxis),this._worldDragAxis.scaleToRef(i,this._dragDelta)):(i=this._dragDelta.length(),t.subtractToRef(this.lastDragPosition,this._dragDelta)),this._targetPosition.addInPlace(this._dragDelta),this.onDragObservable.notifyObservers({dragDistance:i,delta:this._dragDelta,dragPlanePoint:t,dragPlaneNormal:this._dragPlane.forward,pointerId:this.currentDraggingPointerId,pointerInfo:this._activePointerInfo}),this.lastDragPosition.copyFrom(t),s8._RestorePivotPoint(this.attachedNode)}}_pickWithRayOnDragPlane(e){if(!e)return null;let t=Math.acos(rf.P.Dot(this._dragPlane.forward,e.direction));if(t>Math.PI/2&&(t=Math.PI-t),this.maxDragAngle>0&&t>this.maxDragAngle){if(!this._useAlternatePickedPointAboveMaxDragAngle)return null;{this._tmpVector.copyFrom(e.direction),this.attachedNode.absolutePosition.subtractToRef(e.origin,this._alternatePickedPoint),this._alternatePickedPoint.normalize(),this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed*rf.P.Dot(this._alternatePickedPoint,this._tmpVector)),this._tmpVector.addInPlace(this._alternatePickedPoint);let t=rf.P.Dot(this._dragPlane.forward,this._tmpVector);return this._dragPlane.forward.scaleToRef(-t,this._alternatePickedPoint),this._alternatePickedPoint.addInPlace(this._tmpVector),this._alternatePickedPoint.addInPlace(this.attachedNode.absolutePosition),this._alternatePickedPoint}}let i=this._dragPlane.forward,r=this._dragPlane.position,s=e.direction.dot(i);if(Math.abs(s).999?Math.abs(rf.P.Dot(rf.P.UpReadOnly,this._pointC))>.999?this._lookAt.copyFrom(rf.P.Right()):this._lookAt.copyFrom(rf.P.UpReadOnly):(rf.P.CrossToRef(this._localAxis,this._pointC,this._lookAt),rf.P.CrossToRef(this._localAxis,this._lookAt,this._lookAt),this._lookAt.normalize()),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._lookAt,this._lookAt),this._dragPlane.lookAt(this._lookAt)):this._options.dragPlaneNormal?(this.useObjectOrientationForDragging?rf.P.TransformCoordinatesToRef(this._options.dragPlaneNormal,this.attachedNode.getWorldMatrix().getRotationMatrix(),this._localAxis):this._localAxis.copyFrom(this._options.dragPlaneNormal),this._dragPlane.position.copyFrom(this._pointA),this._pointA.addToRef(this._localAxis,this._lookAt),this._dragPlane.lookAt(this._lookAt)):(this._dragPlane.position.copyFrom(this._pointA),this._dragPlane.lookAt(e.origin)),this._dragPlane.position.copyFrom(this.attachedNode.getAbsolutePosition()),this._dragPlane.computeWorldMatrix(!0)}detach(){this._lastPointerRay={},this.attachedNode&&(this.attachedNode.isNearGrabbable=!1),this._pointerObserver&&this._scene.onPointerObservable.remove(this._pointerObserver),this._beforeRenderObserver&&this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver),this._dragPlane&&this._dragPlane.dispose(),this.releaseDrag()}}nt._AnyMouseId=-2;class ni{}ni.ANCHOR_SYSTEM="xr-anchor-system",ni.BACKGROUND_REMOVER="xr-background-remover",ni.HIT_TEST="xr-hit-test",ni.MESH_DETECTION="xr-mesh-detection",ni.PHYSICS_CONTROLLERS="xr-physics-controller",ni.PLANE_DETECTION="xr-plane-detection",ni.POINTER_SELECTION="xr-controller-pointer-selection",ni.TELEPORTATION="xr-controller-teleportation",ni.FEATURE_POINTS="xr-feature-points",ni.HAND_TRACKING="xr-hand-tracking",ni.IMAGE_TRACKING="xr-image-tracking",ni.NEAR_INTERACTION="xr-near-interaction",ni.DOM_OVERLAY="xr-dom-overlay",ni.MOVEMENT="xr-controller-movement",ni.LIGHT_ESTIMATION="xr-light-estimation",ni.EYE_TRACKING="xr-eye-tracking",ni.WALKING_LOCOMOTION="xr-walking-locomotion",ni.LAYERS="xr-layers",ni.DEPTH_SENSING="xr-depth-sensing",ni.SPACE_WARP="xr-space-warp",ni.RAW_CAMERA_ACCESS="xr-raw-camera-access";class nr{constructor(e){this._xrSessionManager=e,this._features={},this._xrSessionManager.onXRSessionInit.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];!t.enabled||t.featureImplementation.attached||t.featureImplementation.disableAutoAttach||this.attachFeature(e)})}),this._xrSessionManager.onXRSessionEnded.add(()=>{this.getEnabledFeatures().forEach(e=>{let t=this._features[e];t.enabled&&t.featureImplementation.attached&&this.detachFeature(e)})})}static AddWebXRFeature(e,t,i=1,r=!1){this._AvailableFeatures[e]=this._AvailableFeatures[e]||{latest:i},i>this._AvailableFeatures[e].latest&&(this._AvailableFeatures[e].latest=i),r&&(this._AvailableFeatures[e].stable=i),this._AvailableFeatures[e][i]=t}static ConstructFeature(e,t=1,i,r){let s=this._AvailableFeatures[e][t];if(!s)throw Error("feature not found");return s(i,r)}static GetAvailableFeatures(){return Object.keys(this._AvailableFeatures)}static GetAvailableVersions(e){return Object.keys(this._AvailableFeatures[e])}static GetLatestVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].latest||-1}static GetStableVersionOfFeature(e){return this._AvailableFeatures[e]&&this._AvailableFeatures[e].stable||-1}attachFeature(e){let t=this._features[e];t&&t.enabled&&!t.featureImplementation.attached&&t.featureImplementation.attach()}detachFeature(e){let t=this._features[e];t&&t.featureImplementation.attached&&t.featureImplementation.detach()}disableFeature(e){let t="string"==typeof e?e:e.Name,i=this._features[t];return!!i&&!!i.enabled&&(i.enabled=!1,this.detachFeature(t),i.featureImplementation.dispose(),delete this._features[t],!0)}dispose(){this.getEnabledFeatures().forEach(e=>{this.disableFeature(e)})}enableFeature(e,t="latest",i={},r=!0,s=!0){let n="string"==typeof e?e:e.Name,a=0;if("string"==typeof t){if(!t)throw Error(`Error in provided version - ${n} (${t})`);if(-1===(a="stable"===t?nr.GetStableVersionOfFeature(n):"latest"===t?nr.GetLatestVersionOfFeature(n):+t)||isNaN(a))throw Error(`feature not found - ${n} (${t})`)}else a=t;let o=nr._ConflictingFeatures[n];if(void 0!==o&&-1!==this.getEnabledFeatures().indexOf(o))throw Error(`Feature ${n} cannot be enabled while ${o} is enabled.`);let l=this._features[n],h=nr.ConstructFeature(n,a,this._xrSessionManager,i);if(!h)throw Error(`feature not found - ${n}`);l&&this.disableFeature(n);let u=h();if(u.dependsOn&&!u.dependsOn.every(e=>!!this._features[e]))throw Error(`Dependant features missing. Make sure the following features are enabled - ${u.dependsOn.join(", ")}`);if(u.isCompatible())return this._features[n]={featureImplementation:u,enabled:!0,version:a,required:s},r?this._xrSessionManager.session&&!this._features[n].featureImplementation.attached&&this.attachFeature(n):this._features[n].featureImplementation.disableAutoAttach=!0,this._features[n].featureImplementation;if(!s)return sg.w1.Warn(`Feature ${n} not compatible with the current environment/browser and was not enabled.`),u;throw Error("required feature not compatible")}getEnabledFeature(e){return this._features[e]&&this._features[e].featureImplementation}getEnabledFeatures(){return Object.keys(this._features)}async _extendXRSessionInitObject(e){for(let t of this.getEnabledFeatures()){let i=this._features[t],r=i.featureImplementation.xrNativeFeatureName;if(r&&(i.required?(e.requiredFeatures=e.requiredFeatures||[],-1===e.requiredFeatures.indexOf(r)&&e.requiredFeatures.push(r)):(e.optionalFeatures=e.optionalFeatures||[],-1===e.optionalFeatures.indexOf(r)&&e.optionalFeatures.push(r))),i.featureImplementation.getXRSessionInitExtension){let t=await i.featureImplementation.getXRSessionInitExtension();e=Object.assign(Object.assign({},e),t)}}return e}}nr._AvailableFeatures={},nr._ConflictingFeatures={[ni.TELEPORTATION]:ni.MOVEMENT,[ni.MOVEMENT]:ni.TELEPORTATION};class ns{constructor(e){this._xrSessionManager=e,this._attached=!1,this._removeOnDetach=[],this.isDisposed=!1,this.disableAutoAttach=!1,this.xrNativeFeatureName="",this.onFeatureAttachObservable=new r_.y$,this.onFeatureDetachObservable=new r_.y$}get attached(){return this._attached}attach(e){if(this.isDisposed)return!1;if(e)this.attached&&this.detach();else if(this.attached)return!1;return this._attached=!0,this._addNewAttachObserver(this._xrSessionManager.onXRFrameObservable,e=>this._onXRFrame(e)),this.onFeatureAttachObservable.notifyObservers(this),!0}detach(){return this._attached?(this._attached=!1,this._removeOnDetach.forEach(e=>{e.observable.remove(e.observer)}),this.onFeatureDetachObservable.notifyObservers(this),!0):(this.disableAutoAttach=!0,!1)}dispose(){this.detach(),this.isDisposed=!0,this.onFeatureAttachObservable.clear(),this.onFeatureDetachObservable.clear()}isCompatible(){return!0}_addNewAttachObserver(e,t){this._removeOnDetach.push({observable:e,observer:e.add(t)})}}class nn{constructor(e,t){this.type=e,this.jointData=t,t.nativeParams=t.nativeParams||{}}get physicsJoint(){return this._physicsJoint}set physicsJoint(e){this._physicsJoint,this._physicsJoint=e}set physicsPlugin(e){this._physicsPlugin=e}executeNativeFunction(e){e(this._physicsPlugin.world,this._physicsJoint)}}nn.DistanceJoint=0,nn.HingeJoint=1,nn.BallAndSocketJoint=2,nn.WheelJoint=3,nn.SliderJoint=4,nn.PrismaticJoint=5,nn.UniversalJoint=6,nn.Hinge2Joint=nn.WheelJoint,nn.PointToPointJoint=8,nn.SpringJoint=9,nn.LockJoint=10,sp.Kj._PhysicsImpostorParser=function(e,t,i){return new na(t,i.physicsImpostor,{mass:i.physicsMass,friction:i.physicsFriction,restitution:i.physicsRestitution},e)};class na{get isDisposed(){return this._isDisposed}get mass(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyMass(this):0}set mass(e){this.setMass(e)}get friction(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyFriction(this):0}set friction(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyFriction(this,e)}get restitution(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this):0}set restitution(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this,e)}get pressure(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.setBodyPressure?e.getBodyPressure(this):0}set pressure(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPressure&&t.setBodyPressure(this,e)}get stiffness(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyStiffness?e.getBodyStiffness(this):0}set stiffness(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyStiffness&&t.setBodyStiffness(this,e)}get velocityIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyVelocityIterations?e.getBodyVelocityIterations(this):0}set velocityIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyVelocityIterations&&t.setBodyVelocityIterations(this,e)}get positionIterations(){if(!this._physicsEngine)return 0;let e=this._physicsEngine.getPhysicsPlugin();return e.getBodyPositionIterations?e.getBodyPositionIterations(this):0}set positionIterations(e){if(!this._physicsEngine)return;let t=this._physicsEngine.getPhysicsPlugin();t.setBodyPositionIterations&&t.setBodyPositionIterations(this,e)}constructor(e,t,i={mass:0},r){if(this.object=e,this.type=t,this._options=i,this._scene=r,this._pluginData={},this._bodyUpdateRequired=!1,this._onBeforePhysicsStepCallbacks=[],this._onAfterPhysicsStepCallbacks=[],this._onPhysicsCollideCallbacks=[],this._deltaPosition=rf.P.Zero(),this._isDisposed=!1,this.soft=!1,this.segments=0,this._tmpQuat=new rf._f,this._tmpQuat2=new rf._f,this.beforeStep=()=>{this._physicsEngine&&(this.object.translate(this._deltaPosition,-1),this._deltaRotationConjugated&&this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotationConjugated,this.object.rotationQuaternion),this.object.computeWorldMatrix(!1),this.object.parent&&this.object.rotationQuaternion?(this.getParentsRotation(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this._tmpQuat)):this._tmpQuat.copyFrom(this.object.rotationQuaternion||new rf._f),!this._options.disableBidirectionalTransformation&&this.object.rotationQuaternion&&this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(this,this.object.getAbsolutePosition(),this._tmpQuat),this._onBeforePhysicsStepCallbacks.forEach(e=>{e(this)}))},this.afterStep=()=>{this._physicsEngine&&(this._onAfterPhysicsStepCallbacks.forEach(e=>{e(this)}),this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(this),this.object.parent&&this.object.rotationQuaternion&&(this.getParentsRotation(),this._tmpQuat.conjugateInPlace(),this._tmpQuat.multiplyToRef(this.object.rotationQuaternion,this.object.rotationQuaternion)),this.object.setAbsolutePosition(this.object.position),this._deltaRotation?(this.object.rotationQuaternion&&this.object.rotationQuaternion.multiplyToRef(this._deltaRotation,this.object.rotationQuaternion),this._deltaPosition.applyRotationQuaternionToRef(this._deltaRotation,na._TmpVecs[0]),this.object.translate(na._TmpVecs[0],1)):this.object.translate(this._deltaPosition,1),this.object.computeWorldMatrix(!0))},this.onCollideEvent=null,this.onCollide=e=>{if(!this._onPhysicsCollideCallbacks.length&&!this.onCollideEvent||!this._physicsEngine)return;let t=this._physicsEngine.getImpostorWithPhysicsBody(e.body);t&&(this.onCollideEvent&&this.onCollideEvent(this,t),this._onPhysicsCollideCallbacks.filter(e=>-1!==e.otherImpostors.indexOf(t)).forEach(i=>{i.callback(this,t,e.point,e.distance,e.impulse,e.normal)}))},!this.object){rb.Y.Error("No object was provided. A physics object is obligatory");return}if(this.object.parent&&0!==i.mass&&rb.Y.Warn("A physics impostor has been created for an object which has a parent. Babylon physics currently works in local space so unexpected issues may occur."),!this._scene&&e.getScene&&(this._scene=e.getScene()),!this._scene)return;this.type>100&&(this.soft=!0),this._physicsEngine=this._scene.getPhysicsEngine(),this._physicsEngine?(this.object.rotationQuaternion||(this.object.rotation?this.object.rotationQuaternion=rf._f.RotationYawPitchRoll(this.object.rotation.y,this.object.rotation.x,this.object.rotation.z):this.object.rotationQuaternion=new rf._f),this._options.mass=void 0===i.mass?0:i.mass,this._options.friction=void 0===i.friction?.2:i.friction,this._options.restitution=void 0===i.restitution?.2:i.restitution,this.soft&&(this._options.mass=this._options.mass>0?this._options.mass:1,this._options.pressure=void 0===i.pressure?200:i.pressure,this._options.stiffness=void 0===i.stiffness?1:i.stiffness,this._options.velocityIterations=void 0===i.velocityIterations?20:i.velocityIterations,this._options.positionIterations=void 0===i.positionIterations?20:i.positionIterations,this._options.fixedPoints=void 0===i.fixedPoints?0:i.fixedPoints,this._options.margin=void 0===i.margin?0:i.margin,this._options.damping=void 0===i.damping?0:i.damping,this._options.path=void 0===i.path?null:i.path,this._options.shape=void 0===i.shape?null:i.shape),this._joints=[],!this.object.parent||this._options.ignoreParent?this._init():this.object.parent.physicsImpostor&&rb.Y.Warn("You must affect impostors to children before affecting impostor to parent.")):rb.Y.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.")}_init(){this._physicsEngine&&(this._physicsEngine.removeImpostor(this),this.physicsBody=null,this._parent=this._parent||this._getPhysicsParent(),this._isDisposed||this.parent&&!this._options.ignoreParent||this._physicsEngine.addImpostor(this))}_getPhysicsParent(){return this.object.parent instanceof sf.x?this.object.parent.physicsImpostor:null}isBodyInitRequired(){return this._bodyUpdateRequired||!this._physicsBody&&(!this._parent||!!this._options.ignoreParent)}setScalingUpdated(){this.forceUpdate()}forceUpdate(){this._init(),this.parent&&!this._options.ignoreParent&&this.parent.forceUpdate()}get physicsBody(){return this._parent&&!this._options.ignoreParent?this._parent.physicsBody:this._physicsBody}get parent(){return!this._options.ignoreParent&&this._parent?this._parent:null}set parent(e){this._parent=e}set physicsBody(e){this._physicsBody&&this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this),this._physicsBody=e,this.resetUpdateFlags()}resetUpdateFlags(){this._bodyUpdateRequired=!1}getObjectExtents(){if(!this.object.getBoundingInfo)return na.DEFAULT_OBJECT_SIZE;{let e=this.object.rotationQuaternion,t=this.object.scaling.clone();this.object.rotationQuaternion=na.IDENTITY_QUATERNION;let i=this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0);i&&i.decompose(t,void 0,void 0);let r=this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiplyInPlace(t);return r.x=Math.abs(r.x),r.y=Math.abs(r.y),r.z=Math.abs(r.z),this.object.rotationQuaternion=e,this.object.computeWorldMatrix&&this.object.computeWorldMatrix(!0),r}}getObjectCenter(){return this.object.getBoundingInfo?this.object.getBoundingInfo().boundingBox.centerWorld:this.object.position}getParam(e){return this._options[e]}setParam(e,t){this._options[e]=t,this._bodyUpdateRequired=!0}setMass(e){this.getParam("mass")!==e&&this.setParam("mass",e),this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setBodyMass(this,e)}getLinearVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this):rf.P.Zero()}setLinearVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this,e)}getAngularVelocity(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this):rf.P.Zero()}setAngularVelocity(e){this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this,e)}executeNativeFunction(e){this._physicsEngine&&e(this._physicsEngine.getPhysicsPlugin().world,this.physicsBody)}registerBeforePhysicsStep(e){this._onBeforePhysicsStepCallbacks.push(e)}unregisterBeforePhysicsStep(e){let t=this._onBeforePhysicsStepCallbacks.indexOf(e);t>-1?this._onBeforePhysicsStepCallbacks.splice(t,1):rb.Y.Warn("Function to remove was not found")}registerAfterPhysicsStep(e){this._onAfterPhysicsStepCallbacks.push(e)}unregisterAfterPhysicsStep(e){let t=this._onAfterPhysicsStepCallbacks.indexOf(e);t>-1?this._onAfterPhysicsStepCallbacks.splice(t,1):rb.Y.Warn("Function to remove was not found")}registerOnPhysicsCollide(e,t){this._onPhysicsCollideCallbacks.push({callback:t,otherImpostors:e instanceof Array?e:[e]})}unregisterOnPhysicsCollide(e,t){let i=e instanceof Array?e:[e],r=-1;this._onPhysicsCollideCallbacks.some((e,s)=>{if(e.callback===t&&e.otherImpostors.length===i.length){let t=e.otherImpostors.every(e=>i.indexOf(e)>-1);return t&&(r=s),t}return!1})?this._onPhysicsCollideCallbacks.splice(r,1):rb.Y.Warn("Function to remove was not found")}getParentsRotation(){let e=this.object.parent;for(this._tmpQuat.copyFromFloats(0,0,0,1);e;)e.rotationQuaternion?this._tmpQuat2.copyFrom(e.rotationQuaternion):rf._f.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,this._tmpQuat2),this._tmpQuat.multiplyToRef(this._tmpQuat2,this._tmpQuat),e=e.parent;return this._tmpQuat}applyForce(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyForce(this,e,t),this}applyImpulse(e,t){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().applyImpulse(this,e,t),this}createJoint(e,t,i){let r=new nn(t,i);return this.addJoint(e,r),this}addJoint(e,t){return this._joints.push({otherImpostor:e,joint:t}),this._physicsEngine&&this._physicsEngine.addJoint(this,e,t),this}addAnchor(e,t,i,r,s){if(!this._physicsEngine)return this;let n=this._physicsEngine.getPhysicsPlugin();return n.appendAnchor&&this._physicsEngine&&n.appendAnchor(this,e,t,i,r,s),this}addHook(e,t,i,r){if(!this._physicsEngine)return this;let s=this._physicsEngine.getPhysicsPlugin();return s.appendAnchor&&this._physicsEngine&&s.appendHook(this,e,t,i,r),this}sleep(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().sleepBody(this),this}wakeUp(){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().wakeUpBody(this),this}clone(e){return e?new na(e,this.type,this._options,this._scene):null}dispose(){this._physicsEngine&&(this._joints.forEach(e=>{this._physicsEngine&&this._physicsEngine.removeJoint(this,e.otherImpostor,e.joint)}),this._physicsEngine.removeImpostor(this),this.parent&&this.parent.forceUpdate(),this._isDisposed=!0)}setDeltaPosition(e){this._deltaPosition.copyFrom(e)}setDeltaRotation(e){this._deltaRotation||(this._deltaRotation=new rf._f),this._deltaRotation.copyFrom(e),this._deltaRotationConjugated=this._deltaRotation.conjugate()}getBoxSizeToRef(e){return this._physicsEngine&&this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this,e),this}getRadius(){return this._physicsEngine?this._physicsEngine.getPhysicsPlugin().getRadius(this):0}syncBoneWithImpostor(e,t,i,r,s){let n=na._TmpVecs[0],a=this.object;if(a.rotationQuaternion){if(s){let i=na._TmpQuat;a.rotationQuaternion.multiplyToRef(s,i),e.setRotationQuaternion(i,r5.T.WORLD,t)}else e.setRotationQuaternion(a.rotationQuaternion,r5.T.WORLD,t)}n.x=0,n.y=0,n.z=0,i&&(n.x=i.x,n.y=i.y,n.z=i.z,e.getDirectionToRef(n,t,n),null==r&&(r=i.length()),n.x*=r,n.y*=r,n.z*=r),e.getParent()?(n.addInPlace(a.getAbsolutePosition()),e.setAbsolutePosition(n,t)):(t.setAbsolutePosition(a.getAbsolutePosition()),t.position.x-=n.x,t.position.y-=n.y,t.position.z-=n.z)}syncImpostorWithBone(e,t,i,r,s,n){let a=this.object;if(a.rotationQuaternion){if(s){let i=na._TmpQuat;e.getRotationQuaternionToRef(r5.T.WORLD,t,i),i.multiplyToRef(s,a.rotationQuaternion)}else e.getRotationQuaternionToRef(r5.T.WORLD,t,a.rotationQuaternion)}let o=na._TmpVecs[0],l=na._TmpVecs[1];n||((n=na._TmpVecs[2]).x=0,n.y=1,n.z=0),e.getDirectionToRef(n,t,l),e.getAbsolutePositionToRef(t,o),null==r&&i&&(r=i.length()),null!=r&&(o.x+=l.x*r,o.y+=l.y*r,o.z+=l.z*r),a.setAbsolutePosition(o)}}na.DEFAULT_OBJECT_SIZE=new rf.P(1,1,1),na.IDENTITY_QUATERNION=rf._f.Identity(),na._TmpVecs=r4.B.BuildArray(3,rf.P.Zero),na._TmpQuat=rf._f.Identity(),na.NoImpostor=0,na.SphereImpostor=1,na.BoxImpostor=2,na.PlaneImpostor=3,na.MeshImpostor=4,na.CapsuleImpostor=6,na.CylinderImpostor=7,na.ParticleImpostor=8,na.HeightmapImpostor=9,na.ConvexHullImpostor=10,na.CustomImpostor=100,na.RopeImpostor=101,na.ClothImpostor=102,na.SoftbodyImpostor=103;var no=i(2697),nl=i(3477);(l=t_||(t_={}))[l.Clean=0]="Clean",l[l.Stop=1]="Stop",l[l.Sync=2]="Sync",l[l.NoSync=3]="NoSync";class nh{static get ForceFullSceneLoadingForIncremental(){return no.Z.ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){no.Z.ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return no.Z.ShowLoadingScreen}static set ShowLoadingScreen(e){no.Z.ShowLoadingScreen=e}static get loggingLevel(){return no.Z.loggingLevel}static set loggingLevel(e){no.Z.loggingLevel=e}static get CleanBoneMatrixWeights(){return no.Z.CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){no.Z.CleanBoneMatrixWeights=e}static GetDefaultPlugin(){return nh._RegisteredPlugins[".babylon"]}static _GetPluginForExtension(e){return nh._RegisteredPlugins[e]||(rb.Y.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"),nh.GetDefaultPlugin())}static _GetPluginForDirectLoad(e){for(let t in nh._RegisteredPlugins){let i=nh._RegisteredPlugins[t].plugin;if(i.canDirectLoad&&i.canDirectLoad(e))return nh._RegisteredPlugins[t]}return nh.GetDefaultPlugin()}static _GetPluginForFilename(e){let t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));let i=e.lastIndexOf("."),r=e.substring(i,e.length).toLowerCase();return nh._GetPluginForExtension(r)}static _GetDirectLoad(e){return"data:"===e.substr(0,5)?e.substr(5):null}static _FormatErrorMessage(e,t,i){let r="Unable to load from "+(e.rawData?"binary data":e.url);return t?r+=`: ${t}`:i&&(r+=`: ${i}`),r}static _LoadData(e,t,i,r,s,n,a,o){let l;let h=nh._GetDirectLoad(e.url);if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";let u=a?nh._GetPluginForExtension(a):h?nh._GetPluginForDirectLoad(e.url):nh._GetPluginForFilename(e.url);if(e.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";if(!(l=void 0!==u.plugin.createPlugin?u.plugin.createPlugin():u.plugin))throw"The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";if(nh.OnPluginActivatedObservable.notifyObservers(l),h&&(l.canDirectLoad&&l.canDirectLoad(e.url)||!(0,sB.VL)(e.url))){if(l.directLoad){let e=l.directLoad(t,h);e.then?e.then(e=>{i(l,e)}).catch(e=>{s("Error in directLoad of _loadData: "+e,e)}):i(l,e)}else i(l,h);return l}let c=u.isBinary,d=(e,r)=>{if(t.isDisposed){s("Scene has been disposed");return}i(l,e,r)},p=null,_=!1,f=l.onDisposeObservable;f&&f.add(()=>{_=!0,p&&(p.abort(),p=null),n()});let m=()=>{if(_)return;let i=(e,t)=>{s(null==e?void 0:e.statusText,t)};if(!l.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=l.loadFile?l.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,d,r,c,i,o):t._loadFile(e.file||e.url,d,r,!0,c,i)},g=t.getEngine(),v=g.enableOfflineSupport;if(v){let i=!1;for(let r of t.disableOfflineSupportExceptionRules)if(r.test(e.url)){i=!0;break}v=!i}return v&&sR.D.OfflineProviderFactory?t.offlineProvider=sR.D.OfflineProviderFactory(e.url,m,g.disableManifestCheck):m(),l}static _GetFileInfo(e,t){let i,r;let s=null,n=null;if(t){if(t.name)i=`file:${t.name}`,r=t.name,s=t;else if(ArrayBuffer.isView(t))i="",r="arrayBuffer",n=t;else if("string"==typeof t&&t.startsWith("data:"))i=t,r="";else{if("/"===t.substr(0,1))return sg.w1.Error("Wrong sceneFilename parameter"),null;i=e+t,r=t}}else i=e,r=sg.w1.GetFilename(e),e=sg.w1.GetFolderPath(e);return{url:i,rootUrl:e,name:r,file:s,rawData:n}}static GetPluginForExtension(e){return nh._GetPluginForExtension(e).plugin}static IsPluginForExtensionAvailable(e){return!!nh._RegisteredPlugins[e]}static RegisterPlugin(e){if("string"==typeof e.extensions){let t=e.extensions;nh._RegisteredPlugins[t.toLowerCase()]={plugin:e,isBinary:!1}}else{let t=e.extensions;Object.keys(t).forEach(i=>{nh._RegisteredPlugins[i.toLowerCase()]={plugin:e,isBinary:t[i].isBinary}})}}static ImportMesh(e,t,i="",r=rL.l.LastCreatedScene,s=null,n=null,a=null,o=null,l=""){if(!r)return rb.Y.Error("No scene available to import mesh to"),null;let h=nh._GetFileInfo(t,i);if(!h)return null;let u={};r.addPendingData(u);let c=()=>{r.removePendingData(u)},d=(e,t)=>{let i=nh._FormatErrorMessage(h,e,t);a?a(r,i,new nl.LH(i,nl.SM.SceneLoaderError,t)):rb.Y.Error(i),c()},p=n?e=>{try{n(e)}catch(e){d("Error in onProgress callback: "+e,e)}}:void 0,_=(e,t,i,n,a,o,l)=>{if(r.importedMeshesFiles.push(h.url),s)try{s(e,t,i,n,a,o,l)}catch(e){d("Error in onSuccess callback: "+e,e)}r.removePendingData(u)};return nh._LoadData(h,r,(t,i,s)=>{if(t.rewriteRootURL&&(h.rootUrl=t.rewriteRootURL(h.rootUrl,s)),t.importMesh){let s=[],n=[],a=[];t.importMesh(e,r,i,h.rootUrl,s,n,a,d)&&(r.loadingPluginName=t.name,_(s,n,a,[],[],[],[]))}else t.importMeshAsync(e,r,i,h.rootUrl,p,h.name).then(e=>{r.loadingPluginName=t.name,_(e.meshes,e.particleSystems,e.skeletons,e.animationGroups,e.transformNodes,e.geometries,e.lights)}).catch(e=>{d(e.message,e)})},p,d,c,o,l)}static ImportMeshAsync(e,t,i="",r=rL.l.LastCreatedScene,s=null,n=null,a=""){return new Promise((o,l)=>{nh.ImportMesh(e,t,i,r,(e,t,i,r,s,n,a)=>{o({meshes:e,particleSystems:t,skeletons:i,animationGroups:r,transformNodes:s,geometries:n,lights:a})},s,(e,t,i)=>{l(i||Error(t))},n,a)})}static Load(e,t="",i=rL.l.LastCreatedEngine,r=null,s=null,n=null,a=null,o=""){return i?nh.Append(e,t,new r2.x(i),r,s,n,a,o):(sg.w1.Error("No engine available"),null)}static LoadAsync(e,t="",i=rL.l.LastCreatedEngine,r=null,s=null,n=""){return new Promise((a,o)=>{nh.Load(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static Append(e,t="",i=rL.l.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return rb.Y.Error("No scene available to append to"),null;let l=nh._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let u=()=>{i.removePendingData(h)};nh.ShowLoadingScreen&&!this._ShowingLoadingScreen&&(this._ShowingLoadingScreen=!0,i.getEngine().displayLoadingUI(),i.executeWhenReady(()=>{i.getEngine().hideLoadingUI(),this._ShowingLoadingScreen=!1}));let c=(e,t)=>{let r=nh._FormatErrorMessage(l,e,t);n?n(i,r,new nl.LH(r,nl.SM.SceneLoaderError,t)):rb.Y.Error(r),u()},d=s?e=>{try{s(e)}catch(e){c("Error in onProgress callback",e)}}:void 0,p=()=>{if(r)try{r(i)}catch(e){c("Error in onSuccess callback",e)}i.removePendingData(h)};return nh._LoadData(l,i,(e,t)=>{e.load?!e.load(i,t,l.rootUrl,c)||(i.loadingPluginName=e.name,p()):e.loadAsync(i,t,l.rootUrl,d,l.name).then(()=>{i.loadingPluginName=e.name,p()}).catch(e=>{c(e.message,e)})},d,c,u,a,o)}static AppendAsync(e,t="",i=rL.l.LastCreatedScene,r=null,s=null,n=""){return new Promise((a,o)=>{nh.Append(e,t,i,e=>{a(e)},r,(e,t,i)=>{o(i||Error(t))},s,n)})}static LoadAssetContainer(e,t="",i=rL.l.LastCreatedScene,r=null,s=null,n=null,a=null,o=""){if(!i)return rb.Y.Error("No scene available to load asset container to"),null;let l=nh._GetFileInfo(e,t);if(!l)return null;let h={};i.addPendingData(h);let u=()=>{i.removePendingData(h)},c=(e,t)=>{let r=nh._FormatErrorMessage(l,e,t);n?n(i,r,new nl.LH(r,nl.SM.SceneLoaderError,t)):rb.Y.Error(r),u()},d=s?e=>{try{s(e)}catch(e){c("Error in onProgress callback",e)}}:void 0,p=e=>{if(r)try{r(e)}catch(e){c("Error in onSuccess callback",e)}i.removePendingData(h)};return nh._LoadData(l,i,(e,t)=>{if(e.loadAssetContainer){let r=e.loadAssetContainer(i,t,l.rootUrl,c);r&&(r.populateRootNodes(),i.loadingPluginName=e.name,p(r))}else e.loadAssetContainerAsync?e.loadAssetContainerAsync(i,t,l.rootUrl,d,l.name).then(t=>{t.populateRootNodes(),i.loadingPluginName=e.name,p(t)}).catch(e=>{c(e.message,e)}):c("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")},d,c,u,a,o)}static LoadAssetContainerAsync(e,t="",i=rL.l.LastCreatedScene,r=null,s=null){return new Promise((n,a)=>{nh.LoadAssetContainer(e,t,i,e=>{n(e)},r,(e,t,i)=>{a(i||Error(t))},s)})}static ImportAnimations(e,t="",i=rL.l.LastCreatedScene,r=!0,s=t_.Clean,n=null,a=null,o=null,l=null,h=null){if(!i){rb.Y.Error("No scene available to load animations to");return}if(r){for(let e of i.animatables)e.reset();i.stopAllAnimations(),i.animationGroups.slice().forEach(e=>{e.dispose()}),i.getNodes().forEach(e=>{e.animations&&(e.animations=[])})}else switch(s){case t_.Clean:i.animationGroups.slice().forEach(e=>{e.dispose()});break;case t_.Stop:i.animationGroups.forEach(e=>{e.stop()});break;case t_.Sync:i.animationGroups.forEach(e=>{e.reset(),e.restart()});break;case t_.NoSync:break;default:rb.Y.Error("Unknown animation group loading mode value '"+s+"'");return}let u=i.animatables.length;this.LoadAssetContainer(e,t,i,e=>{e.mergeAnimationsTo(i,i.animatables.slice(u),n),e.dispose(),i.onAnimationFileImportedObservable.notifyObservers(i),a&&a(i)},o,l,h)}static ImportAnimationsAsync(e,t="",i=rL.l.LastCreatedScene,r=!0,s=t_.Clean,n=null,a=null,o=null,l=null,h=null){return new Promise((a,l)=>{nh.ImportAnimations(e,t,i,r,s,n,e=>{a(e)},o,(e,t,i)=>{l(i||Error(t))},h)})}}nh.NO_LOGGING=0,nh.MINIMAL_LOGGING=1,nh.SUMMARY_LOGGING=2,nh.DETAILED_LOGGING=3,nh.OnPluginActivatedObservable=new r_.y$,nh._RegisteredPlugins={},nh._ShowingLoadingScreen=!1;var nu=i(2515);class nc extends nu.F{constructor(e,t,i=!0){super(e,t),this._normalMatrix=new rf.y3,this._storeEffectOnSubMeshes=i}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){let 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){super._afterBind(e,t),this.getScene()._cachedEffect=t,t&&(t._forceRebindOnNextCall=!1)}_mustRebind(e,t,i=1){return e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,i){this._activeEffect=void 0,super.dispose(e,t,i)}}(h=tf||(tf={}))[h.Float=1]="Float",h[h.Int=2]="Int",h[h.Vector2=4]="Vector2",h[h.Vector3=8]="Vector3",h[h.Vector4=16]="Vector4",h[h.Color3=32]="Color3",h[h.Color4=64]="Color4",h[h.Matrix=128]="Matrix",h[h.Object=256]="Object",h[h.AutoDetect=1024]="AutoDetect",h[h.BasedOnInput=2048]="BasedOnInput",h[h.All=4095]="All",(u=tm||(tm={}))[u.Vertex=1]="Vertex",u[u.Fragment=2]="Fragment",u[u.Neutral=4]="Neutral",u[u.VertexAndFragment=3]="VertexAndFragment";var nd=i(1088);class np{constructor(){this.supportUniformBuffers=!1,this.attributes=[],this.uniforms=[],this.constants=[],this.samplers=[],this.functions={},this.extensions={},this.prePassOutput={},this.counters={},this._attributeDeclaration="",this._uniformDeclaration="",this._constantDeclaration="",this._samplerDeclaration="",this._varyingTransfer="",this._injectAtEnd="",this._repeatableContentAnchorIndex=0,this._builtCompilationString="",this.compilationString=""}finalize(e){let t=e.sharedData.emitComments,i=this.target===tm.Fragment;this.compilationString=` +${t?"//Entry point\n":""}void main(void) { +${this.compilationString}`,this._constantDeclaration&&(this.compilationString=` +${t?"//Constants\n":""}${this._constantDeclaration} +${this.compilationString}`);let r="";for(let e in this.functions)r+=this.functions[e]+` +`;for(let e in this.compilationString=` +${r} +${this.compilationString}`,!i&&this._varyingTransfer&&(this.compilationString=`${this.compilationString} +${this._varyingTransfer}`),this._injectAtEnd&&(this.compilationString=`${this.compilationString} +${this._injectAtEnd}`),this.compilationString=`${this.compilationString} +}`,this.sharedData.varyingDeclaration&&(this.compilationString=` +${t?"//Varyings\n":""}${this.sharedData.varyingDeclaration} +${this.compilationString}`),this._samplerDeclaration&&(this.compilationString=` +${t?"//Samplers\n":""}${this._samplerDeclaration} +${this.compilationString}`),this._uniformDeclaration&&(this.compilationString=` +${t?"//Uniforms\n":""}${this._uniformDeclaration} +${this.compilationString}`),this._attributeDeclaration&&!i&&(this.compilationString=` +${t?"//Attributes\n":""}${this._attributeDeclaration} +${this.compilationString}`),this.compilationString="precision highp float;\n"+this.compilationString,this.compilationString="#if defined(WEBGL2) || defines(WEBGPU)\nprecision highp sampler2DArray;\n#endif\n"+this.compilationString,i&&(this.compilationString="#if defined(PREPASS)\r\n#extension GL_EXT_draw_buffers : require\r\nlayout(location = 0) out highp vec4 glFragData[SCENE_MRT_COUNT];\r\nhighp vec4 gl_FragColor;\r\n#endif\r\n"+this.compilationString),this.extensions){let t=this.extensions[e];this.compilationString=` +${t} +${this.compilationString}`}this._builtCompilationString=this.compilationString}get _repeatableContentAnchor(){return`###___ANCHOR${this._repeatableContentAnchorIndex++}___###`}_getFreeVariableName(e){return(e=e.replace(/[^a-zA-Z_]+/g,""),void 0===this.sharedData.variableNames[e])?(this.sharedData.variableNames[e]=0,"output"===e||"texture"===e)?e+this.sharedData.variableNames[e]:e:(this.sharedData.variableNames[e]++,e+this.sharedData.variableNames[e])}_getFreeDefineName(e){return void 0===this.sharedData.defineNames[e]?this.sharedData.defineNames[e]=0:this.sharedData.defineNames[e]++,e+this.sharedData.defineNames[e]}_excludeVariableName(e){this.sharedData.variableNames[e]=0}_emit2DSampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2D ${e}; +`,this.samplers.push(e))}_emit2DArraySampler(e){0>this.samplers.indexOf(e)&&(this._samplerDeclaration+=`uniform sampler2DArray ${e}; +`,this.samplers.push(e))}_getGLType(e){switch(e){case tf.Float:return"float";case tf.Int:return"int";case tf.Vector2:return"vec2";case tf.Color3:case tf.Vector3:return"vec3";case tf.Color4:case tf.Vector4:return"vec4";case tf.Matrix:return"mat4"}return""}_emitExtension(e,t,i=""){this.extensions[e]||(i&&(t=`#if ${i} +${t} +#endif`),this.extensions[e]=t)}_emitFunction(e,t,i){this.functions[e]||(this.sharedData.emitComments&&(t=i+` +`+t),this.functions[e]=t)}_emitCodeFromInclude(e,t,i){if(i&&i.repeatKey)return`#include<${e}>${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`;let r=nd.Q.IncludesShadersStore[e]+"\n";if(this.sharedData.emitComments&&(r=t+` +`+r),!i)return r;if(i.replaceStrings)for(let e=0;e${i.substitutionVars?"("+i.substitutionVars+")":""}[0..${i.repeatKey}] +`:this.functions[s]=`#include<${e}>${(null==i?void 0:i.substitutionVars)?"("+(null==i?void 0:i.substitutionVars)+")":""} +`,this.sharedData.emitComments&&(this.functions[s]=t+` +`+this.functions[s]);return}if(this.functions[s]=nd.Q.IncludesShadersStore[e],this.sharedData.emitComments&&(this.functions[s]=t+` +`+this.functions[s]),i.removeIfDef&&(this.functions[s]=this.functions[s].replace(/^\s*?#ifdef.+$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#endif.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#else.*$/gm,""),this.functions[s]=this.functions[s].replace(/^\s*?#elif.*$/gm,"")),i.removeAttributes&&(this.functions[s]=this.functions[s].replace(/\s*?attribute .+?;/g,"\n")),i.removeUniforms&&(this.functions[s]=this.functions[s].replace(/\s*?uniform .*?;/g,"\n")),i.removeVaryings&&(this.functions[s]=this.functions[s].replace(/\s*?(varying|in) .+?;/g,"\n")),i.replaceStrings)for(let e=0;ee.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get isDirectlyConnectedToVertexOutput(){if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tm.Vertex||(e.ownerBlock.target===tm.Neutral||e.ownerBlock.target===tm.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isDirectlyConnectedToVertexOutput))return!0;return!1}get isConnectedInVertexShader(){if(this.target===tm.Vertex)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tm.Vertex||e.target===tm.Vertex||(e.ownerBlock.target===tm.Neutral||e.ownerBlock.target===tm.VertexAndFragment)&&e.ownerBlock.outputs.some(e=>e.isConnectedInVertexShader))return!0;return!1}get isConnectedInFragmentShader(){if(this.target===tm.Fragment)return!0;if(!this.hasEndpoints)return!1;for(let e of this._endpoints)if(e.ownerBlock.target===tm.Fragment||(e.ownerBlock.target===tm.Neutral||e.ownerBlock.target===tm.VertexAndFragment)&&e.ownerBlock.isConnectedInFragmentShader())return!0;return!1}createCustomInputBlock(){return null}constructor(e,t,i){this._connectedPoint=null,this._endpoints=[],this._typeConnectionSource=null,this._defaultConnectionPointType=null,this._linkedConnectionSource=null,this._acceptedConnectionPointType=null,this._type=tf.Float,this._enforceAssociatedVariableName=!1,this.needDualDirectionValidation=!1,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new r_.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this._prioritizeVertex=!1,this._target=tm.VertexAndFragment,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeMaterialConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===tg.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(t.target===tm.Fragment){if(i.target===tm.Vertex)return tg.TargetIncompatible;for(let e of i.outputs)if(e.ownerBlock.target!=tm.Neutral&&e.isConnectedInVertexShader)return tg.TargetIncompatible}if(this.type!==e.type&&e.innerType!==tf.AutoDetect)return nm.AreEquivalentTypes(this.type,e.type)?tg.Compatible:e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)||e._acceptedConnectionPointType&&nm.AreEquivalentTypes(e._acceptedConnectionPointType.type,this.type)?tg.Compatible:tg.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return tg.TypeIncompatible;let r=i,s=t;return(this.direction===tv.Input&&(r=t,s=i),r.isAnAncestorOf(s))?tg.HierarchyIssue:tg.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this._enforceAssociatedVariableName=!1,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null,this._enforceAssociatedVariableName=!1,e._enforceAssociatedVariableName=!1),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t=0)&&(t.isExposedOnFrame=!0,t.exposedPortPosition=this.exposedPortPosition),t}dispose(){this.onConnectionObservable.clear()}}var ng=i(7531);class nv{get name(){return this._name}set name(e){this.validateBlockName(e)&&(this._name=e)}get isUnique(){return this._isUnique}get isFinalMerger(){return this._isFinalMerger}get isInput(){return this._isInput}get isTeleportOut(){return this._isTeleportOut}get isTeleportIn(){return this._isTeleportIn}get buildId(){return this._buildId}set buildId(e){this._buildId=e}get target(){return this._target}set target(e){(this._target&e)==0&&(this._target=e)}get inputs(){return this._inputs}get outputs(){return this._outputs}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}constructor(e,t=tm.Vertex,i=!1){this._isFinalMerger=!1,this._isInput=!1,this._isTeleportOut=!1,this._isTeleportIn=!1,this._name="",this._isUnique=!1,this.inputsAreExclusive=!1,this._codeVariableName="",this._inputs=[],this._outputs=[],this.comments="",this.visibleInInspector=!1,this.visibleOnFrame=!1,this._target=t,this._originalTargetIsNeutral=t===tm.Neutral,this._isFinalMerger=i,this._isInput="InputBlock"===this.getClassName(),this._isTeleportOut="NodeMaterialTeleportOutBlock"===this.getClassName(),this._isTeleportIn="NodeMaterialTeleportInBlock"===this.getClassName(),this._name=e,this.uniqueId=ng.K.UniqueId}_setInitialTarget(e){this._target=e,this._originalTargetIsNeutral=e===tm.Neutral}initialize(e){}bind(e,t,i,r){}_declareOutput(e,t){return`${t._getGLType(e.type)} ${e.associatedVariableName}`}_writeVariable(e){return e.connectedPoint?`${e.associatedVariableName}`:"0."}_writeFloat(e){let t=e.toString();return -1===t.indexOf(".")&&(t+=".0"),`${t}`}getClassName(){return"NodeMaterialBlock"}isConnectedInFragmentShader(){return this.outputs.some(e=>e.isConnectedInFragmentShader)}registerInput(e,t,i=!1,r,s){return(s=null!=s?s:new nm(e,this,tv.Input)).type=t,s.isOptional=i,r&&(s.target=r),this._inputs.push(s),this}registerOutput(e,t,i,r){return(r=null!=r?r:new nm(e,this,tv.Output)).type=t,i&&(r.target=i),this._outputs.push(r),this}getFirstAvailableInput(e=null){for(let t of this._inputs)if(!t.connectedPoint&&(!e||e.type===t.type||t.type===tf.AutoDetect))return t;return null}getFirstAvailableOutput(e=null){for(let t of this._outputs)if(!e||!e.target||e.target===tm.Neutral||(e.target&t.target)!=0)return t;return null}getSiblingOutput(e){let t=this._outputs.indexOf(e);return -1===t||t>=this._outputs.length?null:this._outputs[t+1]}isAnAncestorOf(e){for(let t of this._outputs)if(t.hasEndpoints){for(let i of t.endpoints)if(i.ownerBlock===e||i.ownerBlock.isAnAncestorOf(e))return!0}return!1}connectTo(e,t){if(0===this._outputs.length)return;let i=t&&t.output?this.getOutputByName(t.output):this.getFirstAvailableOutput(e),r=!0;for(;r;){let s=t&&t.input?e.getInputByName(t.input):e.getFirstAvailableInput(i);if(i&&s&&i.canConnectTo(s))i.connectTo(s),r=!1;else if(i)i=this.getSiblingOutput(i);else throw"Unable to find a compatible match"}return this}_buildBlock(e){}updateUniformsAndSamples(e,t,i,r){}provideFallbacks(e,t){}initializeDefines(e,t,i,r=!1){}prepareDefines(e,t,i,r=!1,s){}autoConfigure(e,t=()=>!0){}replaceRepeatableContent(e,t,i,r){}get willBeGeneratedIntoVertexShaderFromFragmentShader(){return!(this.isInput||this.isFinalMerger||this._outputs.some(e=>e.isDirectlyConnectedToVertexOutput))&&this.target!==tm.Vertex&&!!((this.target===tm.VertexAndFragment||this.target===tm.Neutral)&&this._outputs.some(e=>e.isConnectedInVertexShader))}isReady(e,t,i,r=!1){return!0}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}_processBuild(e,t,i,r){e.build(t,r);let s=null!=t._vertexState,n=e._buildTarget===tm.Vertex&&e.target!==tm.VertexAndFragment;if(s&&((e.target&e._buildTarget)==0||(e.target&i.target)==0||this.target!==tm.VertexAndFragment&&n)&&(!e.isInput&&t.target!==e._buildTarget||e.isInput&&e.isAttribute&&!e._noContextSwitch)){let e=i.connectedPoint;t._vertexState._emitVaryingFromString("v_"+e.associatedVariableName,t._getGLType(e.type))&&(t._vertexState.compilationString+=`${"v_"+e.associatedVariableName} = ${e.associatedVariableName}; +`),i.associatedVariableName="v_"+e.associatedVariableName,i._enforceAssociatedVariableName=!0}}validateBlockName(e){for(let t of["position","normal","tangent","particle_positionw","uv","uv2","uv3","uv4","uv5","uv6","position2d","particle_uv","matricesIndices","matricesWeights","world0","world1","world2","world3","particle_color","particle_texturemask"])if(e===t)return!1;return!0}_customBuildStep(e,t){}build(e,t){if(this._buildId===e.sharedData.buildId)return!0;if(!this.isInput)for(let t of this._outputs)t.associatedVariableName||(t.associatedVariableName=e._getFreeVariableName(t.name));for(let i of this._inputs){if(!i.connectedPoint){i.isOptional||e.sharedData.checks.notConnectedNonOptionalInputs.push(i);continue}if(this.target!==tm.Neutral&&((i.target&this.target)==0||(i.target&e.target)==0))continue;let r=i.connectedPoint.ownerBlock;r&&r!==this&&this._processBuild(r,e,i,t)}if(this._customBuildStep(e,t),this._buildId===e.sharedData.buildId)return!0;if(e.sharedData.verbose&&rb.Y.Log(`${e.target===tm.Vertex?"Vertex shader":"Fragment shader"}: Building ${this.name} [${this.getClassName()}]`),this.isFinalMerger)switch(e.target){case tm.Vertex:e.sharedData.checks.emitVertex=!0;break;case tm.Fragment:e.sharedData.checks.emitFragment=!0}for(let i of(!this.isInput&&e.sharedData.emitComments&&(e.compilationString+=` +//${this.name} +`),this._buildBlock(e),this._buildId=e.sharedData.buildId,this._buildTarget=e.target,this._outputs))if((i.target&e.target)!=0)for(let r of i.endpoints){let i=r.ownerBlock;i&&(i.target&e.target)!=0&&-1!==t.indexOf(i)&&this._processBuild(i,e,r,t)}return!1}_inputRename(e){return e}_outputRename(e){return e}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleInInspector = ${this.visibleInInspector}; +${e}.visibleOnFrame = ${this.visibleOnFrame}; +${e}.target = ${this.target}; +`}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` +// ${this.getClassName()} +`;for(let i of(this.comments&&(r+=`// ${this.comments} +`),r+=`var ${this._codeVariableName} = new BABYLON.${this.getClassName()}("${this.name}"); +`+this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}clone(e,t=""){let i=this.serialize(),r=(0,rg.q)(i.customType);if(r){let s=new r;return s._deserialize(i,e,t),s}return null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.comments=this.comments,e.visibleInInspector=this.visibleInInspector,e.visibleOnFrame=this.visibleOnFrame,e.target=this.target,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e,t,i){var r;this.name=e.name,this.comments=e.comments,this.visibleInInspector=!!e.visibleInInspector,this.visibleOnFrame=!!e.visibleOnFrame,this._target=null!==(r=e.target)&&void 0!==r?r:this.target,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach((e,t)=>{e.displayName&&(this.inputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.inputs[t].isExposedOnFrame=e.isExposedOnFrame,this.inputs[t].exposedPortPosition=e.exposedPortPosition)}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose()}}class nx extends nv{constructor(e){super(e,tm.Neutral),this.complementW=1,this.complementZ=0,this.target=tm.Vertex,this.registerInput("vector",tf.AutoDetect),this.registerInput("transform",tf.Matrix),this.registerOutput("output",tf.Vector4),this.registerOutput("xyz",tf.Vector3),this._inputs[0].onConnectionObservable.add(e=>{if(e.ownerBlock.isInput){let t=e.ownerBlock;("normal"===t.name||"tangent"===t.name)&&(this.complementW=0)}})}getClassName(){return"TransformBlock"}get vector(){return this._inputs[0]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}get transform(){return this._inputs[1]}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.transform;if(t.connectedPoint){if(0===this.complementW){let r=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",r),e.sharedData.blocksWithDefines.push(this);let s=e._getFreeVariableName(`${i.associatedVariableName}_NUS`);switch(e.compilationString+=`mat3 ${s} = mat3(${i.associatedVariableName}); +`,e.compilationString+=`#ifdef NONUNIFORMSCALING +`,e.compilationString+=`${s} = transposeMat3(inverseMat3(${s})); +`,e.compilationString+=`#endif +`,t.connectedPoint.type){case tf.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * vec3(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}), ${this._writeFloat(this.complementW)}); +`;break;case tf.Vector3:case tf.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = vec4(${s} * ${t.associatedVariableName}.xyz, ${this._writeFloat(this.complementW)}); +`}}else{let r=i.associatedVariableName;switch(t.connectedPoint.type){case tf.Vector2:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementZ)}, ${this._writeFloat(this.complementW)}); +`;break;case tf.Vector3:case tf.Color3:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * vec4(${t.associatedVariableName}, ${this._writeFloat(this.complementW)}); +`;break;default:e.compilationString+=this._declareOutput(this.output,e)+` = ${r} * ${t.associatedVariableName}; +`}}this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; +`)}return this}prepareDefines(e,t,i){e.nonUniformScaling&&i.setValue("NONUNIFORMSCALING",!0)}serialize(){let e=super.serialize();return e.complementZ=this.complementZ,e.complementW=this.complementW,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.complementZ=void 0!==e.complementZ?e.complementZ:0,this.complementW=void 0!==e.complementW?e.complementW:1}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.complementZ = ${this.complementZ}; +`+`${this._codeVariableName}.complementW = ${this.complementW}; +`}}(0,rg.H)("BABYLON.TransformBlock",nx);class nT extends nv{constructor(e){super(e,tm.Vertex,!0),this.registerInput("vector",tf.Vector4)}getClassName(){return"VertexOutputBlock"}get vector(){return this._inputs[0]}_isLogarithmicDepthEnabled(e,t){if(t)return!0;for(let t of e)if(t.useLogarithmicDepth)return!0;return!1}_buildBlock(e){super._buildBlock(e);let t=this.vector;return e.compilationString+=`gl_Position = ${t.associatedVariableName}; +`,this._isLogarithmicDepthEnabled(e.sharedData.fragmentOutputNodes,e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.compilationString+=`vFragmentDepth = 1.0 + gl_Position.w; +`,e.compilationString+=`gl_Position.z = log2(max(0.000001, vFragmentDepth)) * logarithmicDepthConstant; +`),this}}function nS(e,t=tx.Boolean,i="PROPERTIES",r){return(s,n)=>{let a=s._propStore;a||(a=[],s._propStore=a),a.push({propertyName:n,displayName:e,type:t,groupName:i,options:null!=r?r:{}})}}(0,rg.H)("BABYLON.VertexOutputBlock",nT),(p=tx||(tx={}))[p.Boolean=0]="Boolean",p[p.Float=1]="Float",p[p.Int=2]="Int",p[p.Vector2=3]="Vector2",p[p.List=4]="List";var nE=i(3385);class nC extends nv{constructor(e){super(e,tm.Fragment,!0),this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this.useLogarithmicDepth=!1,this.registerInput("rgba",tf.Color4,!0),this.registerInput("rgb",tf.AutoDetect,!0),this.registerInput("a",tf.Float,!0),this.rgb.addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Float)}getClassName(){return"FragmentOutputBlock"}initialize(e){e._excludeVariableName("logarithmicDepthConstant"),e._excludeVariableName("vFragmentDepth")}get rgba(){return this._inputs[0]}get rgb(){return this._inputs[1]}get a(){return this._inputs[2]}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToLinearSpace,!0),i.setValue(this._gammaDefineName,this.convertToGammaSpace,!0)}bind(e,t,i){(this.useLogarithmicDepth||t.useLogarithmicDepth)&&i&&nE.G.BindLogDepth(void 0,e,i.getScene())}_buildBlock(e){super._buildBlock(e);let t=this.rgba,i=this.rgb,r=this.a;e.sharedData.hints.needAlphaBlending=t.isConnected||r.isConnected,e.sharedData.blocksWithDefines.push(this),(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e._emitUniformFromString("logarithmicDepthConstant","float"),e._emitVaryingFromString("vFragmentDepth","float"),e.sharedData.bindableBlocks.push(this)),this._linearDefineName=e._getFreeDefineName("CONVERTTOLINEAR"),this._gammaDefineName=e._getFreeDefineName("CONVERTTOGAMMA");let s=`//${this.name}`;if(e._emitFunctionFromInclude("helperFunctions",s),t.connectedPoint)r.isConnected?e.compilationString+=`gl_FragColor = vec4(${t.associatedVariableName}.rgb, ${r.associatedVariableName}); +`:e.compilationString+=`gl_FragColor = ${t.associatedVariableName}; +`;else if(i.connectedPoint){let t="1.0";r.connectedPoint&&(t=r.associatedVariableName),i.connectedPoint.type===tf.Float?e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${i.associatedVariableName}, ${i.associatedVariableName}, ${t}); +`:e.compilationString+=`gl_FragColor = vec4(${i.associatedVariableName}, ${t}); +`}else e.sharedData.checks.notConnectedNonOptionalInputs.push(t);return e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`gl_FragColor = toLinearSpace(gl_FragColor); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`gl_FragColor = toGammaSpace(gl_FragColor); +`,e.compilationString+=`#endif +`,(this.useLogarithmicDepth||e.sharedData.nodeMaterial.useLogarithmicDepth)&&(e.compilationString+=`gl_FragDepthEXT = log2(vFragmentDepth) * logarithmicDepthConstant * 0.5; +`),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`gl_FragData[0] = gl_FragColor;\r +`,e.compilationString+=`#endif\r +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.useLogarithmicDepth = ${this.useLogarithmicDepth}; +`}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.useLogarithmicDepth=this.useLogarithmicDepth,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=e.convertToLinearSpace,this.useLogarithmicDepth=null!==(r=e.useLogarithmicDepth)&&void 0!==r&&r}}(0,sx.gn)([nS("Convert to gamma space",tx.Boolean,"PROPERTIES",{notifiers:{update:!0}})],nC.prototype,"convertToGammaSpace",void 0),(0,sx.gn)([nS("Convert to linear space",tx.Boolean,"PROPERTIES",{notifiers:{update:!0}})],nC.prototype,"convertToLinearSpace",void 0),(0,sx.gn)([nS("Use logarithmic depth",tx.Boolean,"PROPERTIES")],nC.prototype,"useLogarithmicDepth",void 0),(0,rg.H)("BABYLON.FragmentOutputBlock",nC),(_=tT||(tT={}))[_.Uniform=0]="Uniform",_[_.Attribute=1]="Attribute",_[_.Varying=2]="Varying",_[_.Undefined=3]="Undefined",(f=tS||(tS={}))[f.World=1]="World",f[f.View=2]="View",f[f.Projection=3]="Projection",f[f.ViewProjection=4]="ViewProjection",f[f.WorldView=5]="WorldView",f[f.WorldViewProjection=6]="WorldViewProjection",f[f.CameraPosition=7]="CameraPosition",f[f.FogColor=8]="FogColor",f[f.DeltaTime=9]="DeltaTime",f[f.CameraParameters=10]="CameraParameters",f[f.MaterialAlpha=11]="MaterialAlpha";var nb=i(2975),ny=i(6329);(m=tE||(tE={}))[m.None=0]="None",m[m.Time=1]="Time",m[m.RealTime=2]="RealTime";let nA={position2d:"position",particle_uv:"vUV",particle_color:"vColor",particle_texturemask:"textureMask",particle_positionw:"vPositionW"},nR={particle_uv:!0,particle_color:!0,particle_texturemask:!0,particle_positionw:!0},nP={particle_texturemask:!0};class nI extends nv{get type(){if(this._type===tf.AutoDetect){if(this.isUniform&&null!=this.value){if(!isNaN(this.value))return this._type=tf.Float,this._type;switch(this.value.getClassName()){case"Vector2":return this._type=tf.Vector2,this._type;case"Vector3":return this._type=tf.Vector3,this._type;case"Vector4":return this._type=tf.Vector4,this._type;case"Color3":return this._type=tf.Color3,this._type;case"Color4":return this._type=tf.Color4,this._type;case"Matrix":return this._type=tf.Matrix,this._type}}if(this.isAttribute)switch(this.name){case"position":case"normal":case"particle_positionw":return this._type=tf.Vector3,this._type;case"uv":case"uv2":case"uv3":case"uv4":case"uv5":case"uv6":case"position2d":case"particle_uv":return this._type=tf.Vector2,this._type;case"matricesIndices":case"matricesWeights":case"matricesIndicesExtra":case"matricesWeightsExtra":case"world0":case"world1":case"world2":case"world3":case"tangent":return this._type=tf.Vector4,this._type;case"color":case"instanceColor":case"particle_color":case"particle_texturemask":return this._type=tf.Color4,this._type}if(this.isSystemValue)switch(this._systemValue){case tS.World:case tS.WorldView:case tS.WorldViewProjection:case tS.View:case tS.ViewProjection:case tS.Projection:this._type=tf.Matrix;break;case tS.CameraPosition:this._type=tf.Vector3;break;case tS.FogColor:this._type=tf.Color3;break;case tS.DeltaTime:case tS.MaterialAlpha:this._type=tf.Float;break;case tS.CameraParameters:this._type=tf.Vector4}}return this._type}constructor(e,t=tm.Vertex,i=tf.AutoDetect){super(e,t,!1),this._mode=tT.Undefined,this._animationType=tE.None,this.min=0,this.max=0,this.isBoolean=!1,this.matrixMode=0,this._systemValue=null,this.isConstant=!1,this.groupInInspector="",this.onValueChangedObservable=new r_.y$,this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._type=i,this.setDefaultValue(),this.registerOutput("output",i)}validateBlockName(e){return!!this.isAttribute||super.validateBlockName(e)}get output(){return this._outputs[0]}setAsAttribute(e){return this._mode=tT.Attribute,e&&(this.name=e),this}setAsSystemValue(e){return this.systemValue=e,this}get value(){return this._storedValue}set value(e){this.type===tf.Float&&(this.isBoolean?e=e?1:0:this.min!==this.max&&(e=Math.max(this.min,e),e=Math.min(this.max,e))),this._storedValue=e,this._mode=tT.Uniform,this.onValueChangedObservable.notifyObservers(this)}get valueCallback(){return this._valueCallback}set valueCallback(e){this._valueCallback=e,this._mode=tT.Uniform}get associatedVariableName(){return this._associatedVariableName}set associatedVariableName(e){this._associatedVariableName=e}get animationType(){return this._animationType}set animationType(e){this._animationType=e}get isUndefined(){return this._mode===tT.Undefined}get isUniform(){return this._mode===tT.Uniform}set isUniform(e){this._mode=e?tT.Uniform:tT.Undefined,this.associatedVariableName=""}get isAttribute(){return this._mode===tT.Attribute}set isAttribute(e){this._mode=e?tT.Attribute:tT.Undefined,this.associatedVariableName=""}get isVarying(){return this._mode===tT.Varying}set isVarying(e){this._mode=e?tT.Varying:tT.Undefined,this.associatedVariableName=""}get isSystemValue(){return null!=this._systemValue}get systemValue(){return this._systemValue}set systemValue(e){this._mode=tT.Uniform,this.associatedVariableName="",this._systemValue=e}getClassName(){return"InputBlock"}animate(e){switch(this._animationType){case tE.Time:this.type===tf.Float&&(this.value+=.01*e.getAnimationRatio());break;case tE.RealTime:this.type===tf.Float&&(this.value=(r3.F.Now-e.getEngine().startTime)/1e3)}}_emitDefine(e){return"!"===e[0]?`#ifndef ${e.substring(1)} +`:`#ifdef ${e} +`}initialize(){this.associatedVariableName=""}setDefaultValue(){switch(this.type){case tf.Float:this.value=0;break;case tf.Vector2:this.value=rf.FM.Zero();break;case tf.Vector3:this.value=rf.P.Zero();break;case tf.Vector4:this.value=rf.Lt.Zero();break;case tf.Color3:this.value=rm.Wo.White();break;case tf.Color4:this.value=new rm.HE(1,1,1,1);break;case tf.Matrix:this.value=rf.y3.Identity()}}_emitConstant(e){switch(this.type){case tf.Float:return`${e._emitFloat(this.value)}`;case tf.Vector2:return`vec2(${this.value.x}, ${this.value.y})`;case tf.Vector3:return`vec3(${this.value.x}, ${this.value.y}, ${this.value.z})`;case tf.Vector4:return`vec4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;case tf.Color3:return rm.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&rm.zZ.Color3[0].toGammaSpaceToRef(rm.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rm.zZ.Color3[0].toLinearSpaceToRef(rm.zZ.Color3[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec3(${rm.zZ.Color3[0].r}, ${rm.zZ.Color3[0].g}, ${rm.zZ.Color3[0].b})`;case tf.Color4:return rm.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&rm.zZ.Color4[0].toGammaSpaceToRef(rm.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rm.zZ.Color4[0].toLinearSpaceToRef(rm.zZ.Color4[0],e.sharedData.scene.getEngine().useExactSrgbConversions),`vec4(${rm.zZ.Color4[0].r}, ${rm.zZ.Color4[0].g}, ${rm.zZ.Color4[0].b}, ${rm.zZ.Color4[0].a})`}return""}get _noContextSwitch(){return nR[this.name]}_emit(e,t){var i;if(this.isUniform){if(this.associatedVariableName||(this.associatedVariableName=e._getFreeVariableName("u_"+this.name)),this.isConstant){if(-1!==e.constants.indexOf(this.associatedVariableName))return;e.constants.push(this.associatedVariableName),e._constantDeclaration+=this._declareOutput(this.output,e)+` = ${this._emitConstant(e)}; +`;return}if(-1!==e.uniforms.indexOf(this.associatedVariableName))return;e.uniforms.push(this.associatedVariableName),t&&(e._uniformDeclaration+=this._emitDefine(t)),e._uniformDeclaration+=`uniform ${e._getGLType(this.type)} ${this.associatedVariableName}; +`,t&&(e._uniformDeclaration+=`#endif +`);let i=e.sharedData.hints;if(null!==this._systemValue&&void 0!==this._systemValue)switch(this._systemValue){case tS.WorldView:i.needWorldViewMatrix=!0;break;case tS.WorldViewProjection:i.needWorldViewProjectionMatrix=!0}else this._animationType!==tE.None&&e.sharedData.animatedInputs.push(this);return}if(this.isAttribute){if(this.associatedVariableName=null!==(i=nA[this.name])&&void 0!==i?i:this.name,this.target===tm.Vertex&&e._vertexState){nR[this.name]?nP[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):this._emit(e._vertexState,t);return}if(-1!==e.attributes.indexOf(this.associatedVariableName))return;e.attributes.push(this.associatedVariableName),nR[this.name]?nP[this.name]?e._emitUniformFromString(this.associatedVariableName,e._getGLType(this.type),t):e._emitVaryingFromString(this.associatedVariableName,e._getGLType(this.type),t):(t&&(e._attributeDeclaration+=this._emitDefine(t)),e._attributeDeclaration+=`attribute ${e._getGLType(this.type)} ${this.associatedVariableName}; +`,t&&(e._attributeDeclaration+=`#endif +`))}}_transmitWorld(e,t,i,r){if(!this._systemValue)return;let s=this.associatedVariableName;switch(this._systemValue){case tS.World:e.setMatrix(s,t);break;case tS.WorldView:e.setMatrix(s,i);break;case tS.WorldViewProjection:e.setMatrix(s,r)}}_transmit(e,t,i){if(this.isAttribute)return;let r=this.associatedVariableName;if(this._systemValue){switch(this._systemValue){case tS.World:case tS.WorldView:case tS.WorldViewProjection:break;case tS.View:e.setMatrix(r,t.getViewMatrix());break;case tS.Projection:e.setMatrix(r,t.getProjectionMatrix());break;case tS.ViewProjection:e.setMatrix(r,t.getTransformMatrix());break;case tS.CameraPosition:t.bindEyePosition(e,r,!0);break;case tS.FogColor:e.setColor3(r,t.fogColor);break;case tS.DeltaTime:e.setFloat(r,t.deltaTime/1e3);break;case tS.CameraParameters:t.activeCamera&&e.setFloat4(r,t.getEngine().hasOriginBottomLeft?-1:1,t.activeCamera.minZ,t.activeCamera.maxZ,1/t.activeCamera.maxZ);break;case tS.MaterialAlpha:e.setFloat(r,i.alpha)}return}let s=this._valueCallback?this._valueCallback():this._storedValue;if(null!==s)switch(this.type){case tf.Float:e.setFloat(r,s);break;case tf.Int:e.setInt(r,s);break;case tf.Color3:rm.zZ.Color3[0].set(this.value.r,this.value.g,this.value.b),this.convertToGammaSpace&&rm.zZ.Color3[0].toGammaSpaceToRef(rm.zZ.Color3[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rm.zZ.Color3[0].toLinearSpaceToRef(rm.zZ.Color3[0],t.getEngine().useExactSrgbConversions),e.setColor3(r,rm.zZ.Color3[0]);break;case tf.Color4:rm.zZ.Color4[0].set(this.value.r,this.value.g,this.value.b,this.value.a),this.convertToGammaSpace&&rm.zZ.Color4[0].toGammaSpaceToRef(rm.zZ.Color4[0],t.getEngine().useExactSrgbConversions),this.convertToLinearSpace&&rm.zZ.Color4[0].toLinearSpaceToRef(rm.zZ.Color4[0],t.getEngine().useExactSrgbConversions),e.setDirectColor4(r,rm.zZ.Color4[0]);break;case tf.Vector2:e.setVector2(r,s);break;case tf.Vector3:e.setVector3(r,s);break;case tf.Vector4:e.setVector4(r,s);break;case tf.Matrix:e.setMatrix(r,s)}}_buildBlock(e){super._buildBlock(e),(this.isUniform||this.isSystemValue)&&e.sharedData.inputBlocks.push(this),this._emit(e)}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isAttribute)return super._dumpPropertiesCode()+`${e}.setAsAttribute("${this.name}"); +`;if(this.isSystemValue)return super._dumpPropertiesCode()+`${e}.setAsSystemValue(BABYLON.NodeMaterialSystemValues.${tS[this._systemValue]}); +`;if(this.isUniform){let t=[],i="";switch(this.type){case tf.Float:i=`${this.value}`;break;case tf.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case tf.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case tf.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`;break;case tf.Color3:i=`new BABYLON.Color3(${this.value.r}, ${this.value.g}, ${this.value.b})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case tf.Color4:i=`new BABYLON.Color4(${this.value.r}, ${this.value.g}, ${this.value.b}, ${this.value.a})`,this.convertToGammaSpace&&(i+=".toGammaSpace()"),this.convertToLinearSpace&&(i+=".toLinearSpace()");break;case tf.Matrix:i=`BABYLON.Matrix.FromArray([${this.value.m}])`}return t.push(`${e}.value = ${i}`),this.type===tf.Float&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`,`${e}.isBoolean = ${this.isBoolean}`,`${e}.matrixMode = ${this.matrixMode}`,`${e}.animationType = BABYLON.AnimatedInputBlockTypes.${tE[this.animationType]}`),t.push(`${e}.isConstant = ${this.isConstant}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}return super._dumpPropertiesCode()}dispose(){this.onValueChangedObservable.clear(),super.dispose()}serialize(){let e=super.serialize();return e.type=this.type,e.mode=this._mode,e.systemValue=this._systemValue,e.animationType=this._animationType,e.min=this.min,e.max=this.max,e.isBoolean=this.isBoolean,e.matrixMode=this.matrixMode,e.isConstant=this.isConstant,e.groupInInspector=this.groupInInspector,e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,null!=this._storedValue&&this._mode===tT.Uniform&&(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e,t,i){if(this._mode=e.mode,super._deserialize(e,t,i),this._type=e.type,this._systemValue=e.systemValue||e.wellKnownValue,this._animationType=e.animationType,this.min=e.min||0,this.max=e.max||0,this.isBoolean=!!e.isBoolean,this.matrixMode=e.matrixMode||0,this.isConstant=!!e.isConstant,this.groupInInspector=e.groupInInspector||"",this.convertToGammaSpace=!!e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,"tangent"===e.name&&e.mode===tT.Attribute&&e.type===tf.Vector3&&(this._type=tf.Vector4),e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=(0,rg.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}}(0,rg.H)("BABYLON.InputBlock",nI);class nM extends nv{constructor(e){super(e,tm.VertexAndFragment),this._samplerName="textureSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",tf.AutoDetect,!1,tm.VertexAndFragment),this.registerOutput("rgba",tf.Color4,tm.Neutral),this.registerOutput("rgb",tf.Color3,tm.Neutral),this.registerOutput("r",tf.Float,tm.Neutral),this.registerOutput("g",tf.Float,tm.Neutral),this.registerOutput("b",tf.Float,tm.Neutral),this.registerOutput("a",tf.Float,tm.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Vector2|tf.Vector3|tf.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"CurrentScreenBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?tm.VertexAndFragment:tm.Fragment}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&!t.connectedPoint.ownerBlock.isAttribute&&e._emitUniformFromString(t.associatedVariableName,"vec2"),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,t.name,!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tm.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}if(this.uv.ownerBlock.target===tm.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tm.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===tm.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`}_buildBlock(e){if(super._buildBlock(e),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.blockingBlocks.indexOf(this)&&e.sharedData.blockingBlocks.push(this),0>e.sharedData.textureBlocks.indexOf(this)&&e.sharedData.textureBlocks.push(this),0>e.sharedData.blocksWithDefines.indexOf(this)&&e.sharedData.blocksWithDefines.push(this),e.target!==tm.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;e._emit2DSampler(this._samplerName),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),this._writeTextureRead(e),this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=sj.Parse(e.texture,t,i))}}(0,rg.H)("BABYLON.CurrentScreenBlock",nM);class nD extends nv{constructor(e){super(e,tm.Fragment),this._samplerName="diffuseSampler",this.convertToGammaSpace=!1,this.convertToLinearSpace=!1,this._isUnique=!1,this.registerInput("uv",tf.AutoDetect,!1,tm.VertexAndFragment),this.registerOutput("rgba",tf.Color4,tm.Neutral),this.registerOutput("rgb",tf.Color3,tm.Neutral),this.registerOutput("r",tf.Float,tm.Neutral),this.registerOutput("g",tf.Float,tm.Neutral),this.registerOutput("b",tf.Float,tm.Neutral),this.registerOutput("a",tf.Float,tm.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Vector2|tf.Vector3|tf.Vector4)}getClassName(){return"ParticleTextureBlock"}get uv(){return this._inputs[0]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}initialize(e){e._excludeVariableName("diffuseSampler")}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"particle_uv"===e.name&&t(e));i||(i=new nI("uv")).setAsAttribute("particle_uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){i.setValue(this._linearDefineName,this.convertToGammaSpace,!0),i.setValue(this._gammaDefineName,this.convertToLinearSpace,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}_writeOutput(e,t,i){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,e.compilationString+=`#ifdef ${this._linearDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`,e.compilationString+=`#ifdef ${this._gammaDefineName} +`,e.compilationString+=`${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); +`,e.compilationString+=`#endif +`}_buildBlock(e){if(super._buildBlock(e),e.target===tm.Vertex)return;this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),e._emit2DSampler(this._samplerName),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA");let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this.uv.associatedVariableName}); +`,this._outputs))i.hasEndpoints&&this._writeOutput(e,i,i.name);return this}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=sj.Parse(e.texture,t,i))}}(0,rg.H)("BABYLON.ParticleTextureBlock",nD);class nO extends nv{constructor(e){super(e,tm.Fragment),this._isUnique=!0,this.registerInput("color",tf.Color4,!1,tm.Fragment),this.registerOutput("rampColor",tf.Color4,tm.Fragment)}getClassName(){return"ParticleRampGradientBlock"}get color(){return this._inputs[0]}get rampColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("remapRanges"),e._excludeVariableName("rampSampler"),e._excludeVariableName("baseColor"),e._excludeVariableName("alpha"),e._excludeVariableName("remappedColorIndex"),e._excludeVariableName("rampColor"),e._excludeVariableName("finalAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==tm.Vertex)return e._emit2DSampler("rampSampler"),e._emitVaryingFromString("remapRanges","vec4","RAMPGRADIENT"),e.compilationString+=` + #ifdef RAMPGRADIENT + vec4 baseColor = ${this.color.associatedVariableName}; + float alpha = ${this.color.associatedVariableName}.a; + + float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0); + + vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.)); + baseColor.rgb *= rampColor.rgb; + + // Remapped alpha + float finalAlpha = baseColor.a; + baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0); + + ${this._declareOutput(this.rampColor,e)} = baseColor; + #else + ${this._declareOutput(this.rampColor,e)} = ${this.color.associatedVariableName}; + #endif + `,this}}(0,rg.H)("BABYLON.ParticleRampGradientBlock",nO);class nN extends nv{constructor(e){super(e,tm.Fragment),this._isUnique=!0,this.registerInput("color",tf.Color4,!1,tm.Fragment),this.registerInput("alphaTexture",tf.Float,!1,tm.Fragment),this.registerInput("alphaColor",tf.Float,!1,tm.Fragment),this.registerOutput("blendColor",tf.Color4,tm.Fragment)}getClassName(){return"ParticleBlendMultiplyBlock"}get color(){return this._inputs[0]}get alphaTexture(){return this._inputs[1]}get alphaColor(){return this._inputs[2]}get blendColor(){return this._outputs[0]}initialize(e){e._excludeVariableName("sourceAlpha")}_buildBlock(e){if(super._buildBlock(e),e.target!==tm.Vertex)return e.compilationString+=` + #ifdef BLENDMULTIPLYMODE + ${this._declareOutput(this.blendColor,e)}; + float sourceAlpha = ${this.alphaColor.associatedVariableName} * ${this.alphaTexture.associatedVariableName}; + ${this.blendColor.associatedVariableName}.rgb = ${this.color.associatedVariableName}.rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha); + ${this.blendColor.associatedVariableName}.a = ${this.color.associatedVariableName}.a; + #else + ${this._declareOutput(this.blendColor,e)} = ${this.color.associatedVariableName}; + #endif + `,this}}(0,rg.H)("BABYLON.ParticleBlendMultiplyBlock",nN);class nF{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(ethis._maxRank&&(this._maxRank=e),this._defines[e]=[]),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,ethis._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;let i=this._mesh.getScene();for(let e=0;e0&&(r.computeBonesUsingShaders=!1);continue}if(r.computeBonesUsingShaders&&0!==r.numBoneInfluencers){if(r.material.getEffect()===t)r.computeBonesUsingShaders=!1;else if(r.subMeshes){for(let e of r.subMeshes)if(e.effect===t){r.computeBonesUsingShaders=!1;break}}}}}else{let t=this._defines[this._currentRank];if(t)for(let i=0;i0}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 texture(){var e,t;return null!==(t=null===(e=this._textures)||void 0===e?void 0:e[0])&&void 0!==t?t: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,i=!1){if(this.samples===e&&!i)return e;let r=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,r}constructor(e,t,i,r,s){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=i,this._engine=r,this._depthStencilTexture=null,this.label=s}setTextures(e){Array.isArray(e)?this._textures=e:e?this._textures=[e]:this._textures=null}setTexture(e,t=0,i=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&i&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,i){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==i&&i>=0&&(this._faceIndices[e]=i)}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14,n){var a;return null===(a=this._depthStencilTexture)||void 0===a||a.dispose(),this._depthStencilTextureWithStencil=i,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:i,isCube:this._isCube,samples:r,depthTextureFormat:s,label:n},this),this._depthStencilTexture}_shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){var e,t,i,r,s,n,a,o;let l=null;if(this._isMulti){let i=this.textures;if(i&&i.length>0){let r=!1,s=i.length,n=i[i.length-1]._source;(n===sq.S.Depth||n===sq.S.DepthStencil)&&(r=!0,s--);let a=[],o=[],h=[],u=[],c=[],d=[],p=[],_={};for(let r=0;r1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){var e,t;if(this._textures)for(let t=0;t<(null===(e=this._textures)||void 0===e?void 0:e.length);++t)this._textures[t].dispose();this._textures=null}dispose(e=!1){var t;e||(null===(t=this._depthStencilTexture)||void 0===t||t.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class nV extends nU{constructor(e,t,i,r,s){super(e,t,i,r),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=s}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height)).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}_shareDepth(e){super._shareDepth(e);let t=this._context,i=this._depthStencilBuffer,r=e._MSAAFramebuffer||e._framebuffer;e._depthStencilBuffer&&e._depthStencilBuffer!==i&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=i;let s=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;this._engine._bindUnboundFramebuffer(r),t.framebufferRenderbuffer(t.FRAMEBUFFER,s,t.RENDERBUFFER,i),this._engine._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,i,r=0){var s,n,a,o;if(!e._hardwareTexture)return;let l=this._framebuffer,h=this._engine._currentFramebuffer;if(this._engine._bindUnboundFramebuffer(l),this._engine.webGLVersion>1){let l=this._context,h=l["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(i=null!==(n=null!=i?i:null===(s=this.layerIndices)||void 0===s?void 0:s[t])&&void 0!==n?n:0,l.framebufferTextureLayer(l.FRAMEBUFFER,h,e._hardwareTexture.underlyingResource,r,i)):e.isCube?(i=null!==(o=null!=i?i:null===(a=this.faceIndices)||void 0===a?void 0:a[t])&&void 0!==o?o:0,l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture.underlyingResource,r)):l.framebufferTexture2D(l.FRAMEBUFFER,h,l.TEXTURE_2D,e._hardwareTexture.underlyingResource,r)}else{let s=this._context,n=s["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==i?s.TEXTURE_CUBE_MAP_POSITIVE_X+i:s.TEXTURE_2D;s.framebufferTexture2D(s.FRAMEBUFFER,n,a,e._hardwareTexture.underlyingResource,r)}this._engine._bindUnboundFramebuffer(h)}setTexture(e,t=0,i=!0){super.setTexture(e,t,i),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){var i,r;if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;let s=null!==(r=null===(i=this._attachments)||void 0===i?void 0:i.length)&&void 0!==r?r:this.textures.length;for(let e=0;e1&&(15===a.format?c=r.DEPTH_COMPONENT16:16===a.format?c=r.DEPTH_COMPONENT24:17===a.format||13===a.format?c=r.DEPTH24_STENCIL8:14===a.format?c=r.DEPTH_COMPONENT32F:18===a.format&&(c=r.DEPTH32F_STENCIL8)),a.is2DArray?r.texImage3D(n,0,c,a.width,a.height,s,0,u,h,null):r.texImage2D(n,0,c,a.width,a.height,0,u,h,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),i._depthStencilBuffer){let e=this._currentFramebuffer;this._bindUnboundFramebuffer(i._framebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,null),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.STENCIL_ATTACHMENT,r.RENDERBUFFER,null),this._bindUnboundFramebuffer(e),r.deleteRenderbuffer(i._depthStencilBuffer),i._depthStencilBuffer=null}return a},sK.B.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let i=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(i.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(i.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);let r=e.texture._hardwareTexture;if(r.releaseMSAARenderBuffers(),t>1&&"function"==typeof i.renderbufferStorageMultisample){let s=i.createFramebuffer();if(!s)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=s,this._bindUnboundFramebuffer(e._MSAAFramebuffer);let n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),i.COLOR_ATTACHMENT0,!1);if(!n)throw Error("Unable to create multi sampled framebuffer");r.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};var nk=i(1606),nG=i(5550);class nz{static RegisterShaderCodeProcessing(e,t){if(!t){delete nz._CustomShaderCodeProcessing[null!=e?e:""];return}nz._CustomShaderCodeProcessing[null!=e?e:""]=t}static _GetShaderCodeProcessing(e){var t;return null!==(t=nz._CustomShaderCodeProcessing[e])&&void 0!==t?t:nz._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)})}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,i,r,s,n,a=1,o,l,h=null,u=0,c="postprocess",d,p=!1,_=5,f=nG.x.GLSL){var m,g,v,x,T,S,E,C,b,y,A,R;this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=0,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=1,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new nL.t(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new rf.FM(1,1),this._texelSize=rf.FM.Zero(),this.onActivateObservable=new r_.y$,this.onSizeChangedObservable=new r_.y$,this.onApplyObservable=new r_.y$,this.onBeforeRenderObservable=new r_.y$,this.onAfterRenderObservable=new r_.y$,this.name=e;let P=1,I=null;if(i&&!Array.isArray(i)){let e=i;i=null!==(m=e.uniforms)&&void 0!==m?m:null,r=null!==(g=e.samplers)&&void 0!==g?g:null,P=null!==(v=e.size)&&void 0!==v?v:1,n=null!==(x=e.camera)&&void 0!==x?x:null,a=null!==(T=e.samplingMode)&&void 0!==T?T:1,o=e.engine,l=e.reusable,h=null!==(S=e.defines)&&void 0!==S?S:null,u=null!==(E=e.textureType)&&void 0!==E?E:0,c=null!==(C=e.vertexUrl)&&void 0!==C?C:"postprocess",d=e.indexParameters,p=null!==(b=e.blockCompilation)&&void 0!==b&&b,_=null!==(y=e.textureFormat)&&void 0!==y?y:5,f=null!==(A=e.shaderLanguage)&&void 0!==A?A:nG.x.GLSL,I=null!==(R=e.uniformBuffers)&&void 0!==R?R:null}else s&&(P="number"==typeof s?s:{width:s.width,height:s.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=P,this.renderTargetSamplingMode=a||1,this._reusable=l||!1,this._textureType=u,this._textureFormat=_,this._shaderLanguage=f,this._samplers=r||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=c,this._parameters=i||[],this._parameters.push("scale"),this._uniformBuffers=I||[],this._indexParameters=d,this._drawWrapper=new nk.q(this._engine),p||this.updateEffect(h)}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 nL.t(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,i=null,r,s,n,a,o){var l,h;let u=nz._GetShaderCodeProcessing(this.name);if(null==u?void 0:u.defineCustomBindings){let r=null!==(l=null==t?void 0:t.slice())&&void 0!==l?l:[];r.push(...this._parameters);let s=null!==(h=null==i?void 0:i.slice())&&void 0!==h?h:[];s.push(...this._samplers),e=u.defineCustomBindings(this.name,e,r,s),t=r,i=s}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:null!=a?a:this._vertexUrl,fragment:null!=o?o:this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:i||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:null!=s?s:null,onError:null!=n?n:null,indexParameters:r||this._indexParameters,processCodeAfterIncludes:(null==u?void 0:u.processCodeAfterIncludes)?(e,t)=>u.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:(null==u?void 0:u.processFinalCode)?(e,t)=>u.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage},this._engine)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,i=0){for(let r=0;r=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let i=0;i0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(i){for(let e=0;e{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)}),this._flushTextureCache(),this._renderId++}return p||(p=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(l/u,h/c),this._engine.bindFramebuffer(p,0,l,h,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(p,0,void 0,void 0,this.forceFullscreenViewport)),null===(s=(r=this._engine)._debugInsertMarker)||void 0===s||s.call(r,`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(0===this.alphaMode||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:n.clearColor,n._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),p}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(){var e,t;return null!==(t=null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}apply(){var e,t,i;let r;return(null===(e=this._drawWrapper.effect)||void 0===e?void 0:e.isReady())?(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),r=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",null==r?void 0:r.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),null===(i=null===(t=nz._GetShaderCodeProcessing(this.name))||void 0===t?void 0:t.bindCustomBindings)||void 0===i||i.call(t,this.name,this._drawWrapper.effect),this._drawWrapper.effect):null}_disposeTextures(){if(this._shareOutputWithPostProcess||this._forcedOutputTexture){this._disposeTextureCache();return}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&&-1!==(t=this._scene.postProcesses.indexOf(this))&&this._scene.postProcesses.splice(t,1),this._parentContainer){let e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(-1!==(t=this._engine.postProcesses.indexOf(this))&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),0===(t=e._postProcesses.indexOf(this))&&e._postProcesses.length>0){let e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear()}}serialize(){let e=rG.p4.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(){let e=this.serialize();e._engine=this._engine,e.cameraId=null;let t=nz.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,i){let r=(0,rg.q)(e.customType);if(!r||!r._Parse)return null;let s=t?t.getCameraById(e.cameraId):null;return r._Parse(e,s,t,i)}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new nz(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,i,r)}}nz._CustomShaderCodeProcessing={},(0,sx.gn)([(0,rG.qC)()],nz.prototype,"uniqueId",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"name",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"width",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"height",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"renderTargetSamplingMode",void 0),(0,sx.gn)([(0,rG.XX)()],nz.prototype,"clearColor",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"autoClear",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"forceAutoClearInAlphaMode",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"alphaMode",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"alphaConstants",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"enablePixelPerfectMode",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"forceFullscreenViewport",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"scaleMode",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"alwaysForcePOT",void 0),(0,sx.gn)([(0,rG.qC)("samples")],nz.prototype,"_samples",void 0),(0,sx.gn)([(0,rG.qC)()],nz.prototype,"adaptScaleToCurrentViewport",void 0),(0,rg.H)("BABYLON.PostProcess",nz);class nW extends nv{constructor(e){super(e,tm.Neutral),this.xSwizzle="x",this.ySwizzle="y",this.zSwizzle="z",this.wSwizzle="w",this.registerInput("xyzw ",tf.Vector4,!0),this.registerInput("xyz ",tf.Vector3,!0),this.registerInput("xy ",tf.Vector2,!0),this.registerInput("zw ",tf.Vector2,!0),this.registerInput("x",tf.Float,!0),this.registerInput("y",tf.Float,!0),this.registerInput("z",tf.Float,!0),this.registerInput("w",tf.Float,!0),this.registerOutput("xyzw",tf.Vector4),this.registerOutput("xyz",tf.Vector3),this.registerOutput("xy",tf.Vector2),this.registerOutput("zw",tf.Vector2)}getClassName(){return"VectorMergerBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get x(){return this._inputs[4]}get y(){return this._inputs[5]}get z(){return this._inputs[6]}get w(){return this._inputs[7]}get xyzw(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xy(){return this.xyOut}get xyz(){return this.xyzOut}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":e}_buildSwizzle(e){return"."+(this.xSwizzle+this.ySwizzle+this.zSwizzle+this.wSwizzle).substr(0,e)}_buildBlock(e){super._buildBlock(e);let t=this.x,i=this.y,r=this.z,s=this.w,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this._outputs[0],u=this._outputs[1],c=this._outputs[2],d=this._outputs[3];return l.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = ${l.associatedVariableName}${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${l.associatedVariableName}${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${l.associatedVariableName}${this._buildSwizzle(2)}; +`)):o.isConnected?(h.hasEndpoints&&(e.compilationString+=this._declareOutput(h,e)+` = vec4(${o.associatedVariableName}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = ${o.associatedVariableName}${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${o.associatedVariableName}${this._buildSwizzle(2)}; +`)):(n.isConnected?(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${a.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${n.associatedVariableName}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = ${n.associatedVariableName}${this._buildSwizzle(2)}; +`)):(h.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${a.associatedVariableName})${this._buildSwizzle(4)}; +`:e.compilationString+=this._declareOutput(h,e)+` = vec4(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(4)}; +`),u.hasEndpoints&&(e.compilationString+=this._declareOutput(u,e)+` = vec3(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"}, ${r.isConnected?this._writeVariable(r):"0.0"})${this._buildSwizzle(3)}; +`),c.hasEndpoints&&(e.compilationString+=this._declareOutput(c,e)+` = vec2(${t.isConnected?this._writeVariable(t):"0.0"}, ${i.isConnected?this._writeVariable(i):"0.0"})${this._buildSwizzle(2)}; +`)),d.hasEndpoints&&(a.isConnected?e.compilationString+=this._declareOutput(d,e)+` = ${a.associatedVariableName}${this._buildSwizzle(2)}; +`:e.compilationString+=this._declareOutput(d,e)+` = vec2(${r.isConnected?this._writeVariable(r):"0.0"}, ${s.isConnected?this._writeVariable(s):"0.0"})${this._buildSwizzle(2)}; +`)),this}serialize(){let e=super.serialize();return e.xSwizzle=this.xSwizzle,e.ySwizzle=this.ySwizzle,e.zSwizzle=this.zSwizzle,e.wSwizzle=this.wSwizzle,e}_deserialize(e,t,i){var r,s,n,a;super._deserialize(e,t,i),this.xSwizzle=null!==(r=e.xSwizzle)&&void 0!==r?r:"x",this.ySwizzle=null!==(s=e.ySwizzle)&&void 0!==s?s:"y",this.zSwizzle=null!==(n=e.zSwizzle)&&void 0!==n?n:"z",this.wSwizzle=null!==(a=e.wSwizzle)&&void 0!==a?a:"w"}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.xSwizzle = "${this.xSwizzle}"; +${this._codeVariableName}.ySwizzle = "${this.ySwizzle}"; +${this._codeVariableName}.zSwizzle = "${this.zSwizzle}"; +${this._codeVariableName}.wSwizzle = "${this.wSwizzle}"; +`}}(0,rg.H)("BABYLON.VectorMergerBlock",nW);class nH extends nv{constructor(e){super(e,tm.Neutral),this.sourceRange=new rf.FM(-1,1),this.targetRange=new rf.FM(0,1),this.registerInput("input",tf.AutoDetect),this.registerInput("sourceMin",tf.Float,!0),this.registerInput("sourceMax",tf.Float,!0),this.registerInput("targetMin",tf.Float,!0),this.registerInput("targetMax",tf.Float,!0),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"RemapBlock"}get input(){return this._inputs[0]}get sourceMin(){return this._inputs[1]}get sourceMax(){return this._inputs[2]}get targetMin(){return this._inputs[3]}get targetMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.sourceMin.isConnected?this.sourceMin.associatedVariableName:this._writeFloat(this.sourceRange.x),r=this.sourceMax.isConnected?this.sourceMax.associatedVariableName:this._writeFloat(this.sourceRange.y),s=this.targetMin.isConnected?this.targetMin.associatedVariableName:this._writeFloat(this.targetRange.x),n=this.targetMax.isConnected?this.targetMax.associatedVariableName:this._writeFloat(this.targetRange.y);return e.compilationString+=this._declareOutput(t,e)+` = ${s} + (${this._inputs[0].associatedVariableName} - ${i}) * (${n} - ${s}) / (${r} - ${i}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.sourceRange = new BABYLON.Vector2(${this.sourceRange.x}, ${this.sourceRange.y}); +`+`${this._codeVariableName}.targetRange = new BABYLON.Vector2(${this.targetRange.x}, ${this.targetRange.y}); +`}serialize(){let e=super.serialize();return e.sourceRange=this.sourceRange.asArray(),e.targetRange=this.targetRange.asArray(),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.sourceRange=rf.FM.FromArray(e.sourceRange),this.targetRange=rf.FM.FromArray(e.targetRange)}}(0,sx.gn)([nS("From",tx.Vector2)],nH.prototype,"sourceRange",void 0),(0,sx.gn)([nS("To",tx.Vector2)],nH.prototype,"targetRange",void 0),(0,rg.H)("BABYLON.RemapBlock",nH);class nX extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("left",tf.AutoDetect),this.registerInput("right",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(tf.Float),this._inputs[1].acceptedConnectionPointTypes.push(tf.Float)}getClassName(){return"MultiplyBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} * ${this.right.associatedVariableName}; +`,this}}(0,rg.H)("BABYLON.MultiplyBlock",nX),(g=tC||(tC={}))[g.Material=0]="Material",g[g.PostProcess=1]="PostProcess",g[g.Particle=2]="Particle",g[g.ProceduralTexture=3]="ProceduralTexture";var nY=i(1974);class nj{constructor(){this.direction1=new rf.P(0,1,0),this.direction2=new rf.P(0,1,0),this.minEmitBox=new rf.P(-.5,-.5,-.5),this.maxEmitBox=new rf.P(.5,.5,.5)}startDirectionFunction(e,t,i,r){let s=rk.R.RandomRange(this.direction1.x,this.direction2.x),n=rk.R.RandomRange(this.direction1.y,this.direction2.y),a=rk.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.x=s,t.y=n,t.z=a;return}rf.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){let s=rk.R.RandomRange(this.minEmitBox.x,this.maxEmitBox.x),n=rk.R.RandomRange(this.minEmitBox.y,this.maxEmitBox.y),a=rk.R.RandomRange(this.minEmitBox.z,this.maxEmitBox.z);if(r){t.x=s,t.y=n,t.z=a;return}rf.P.TransformCoordinatesFromFloatsToRef(s,n,a,e,t)}clone(){let e=new nj;return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2),e.setVector3("minEmitBox",this.minEmitBox),e.setVector3("maxEmitBox",this.maxEmitBox)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3),e.addUniform("minEmitBox",3),e.addUniform("maxEmitBox",3)}getEffectDefines(){return"#define BOXEMITTER"}getClassName(){return"BoxParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e.minEmitBox=this.minEmitBox.asArray(),e.maxEmitBox=this.maxEmitBox.asArray(),e}parse(e){rf.P.FromArrayToRef(e.direction1,0,this.direction1),rf.P.FromArrayToRef(e.direction2,0,this.direction2),rf.P.FromArrayToRef(e.minEmitBox,0,this.minEmitBox),rf.P.FromArrayToRef(e.maxEmitBox,0,this.maxEmitBox)}}class nq{get radius(){return this._radius}set radius(e){this._radius=e,this._buildHeight()}get angle(){return this._angle}set angle(e){this._angle=e,this._buildHeight()}_buildHeight(){0!==this._angle?this._height=this._radius/Math.tan(this._angle/2):this._height=1}constructor(e=1,t=Math.PI,i=0){this.directionRandomizer=i,this.radiusRange=1,this.heightRange=1,this.emitFromSpawnPointOnly=!1,this.angle=t,this.radius=e}startDirectionFunction(e,t,i,r){r?rf.jp.Vector3[0].copyFrom(i._localPosition).normalize():i.position.subtractToRef(e.getTranslation(),rf.jp.Vector3[0]).normalize();let s=rk.R.RandomRange(0,this.directionRandomizer),n=rk.R.RandomRange(0,this.directionRandomizer),a=rk.R.RandomRange(0,this.directionRandomizer);t.x=rf.jp.Vector3[0].x+s,t.y=rf.jp.Vector3[0].y+n,t.z=rf.jp.Vector3[0].z+a,t.normalize()}startPositionFunction(e,t,i,r){let s;let n=rk.R.RandomRange(0,2*Math.PI);s=this.emitFromSpawnPointOnly?1e-4:1-(s=rk.R.RandomRange(0,this.heightRange))*s;let a=this._radius-rk.R.RandomRange(0,this._radius*this.radiusRange),o=(a*=s)*Math.sin(n),l=a*Math.cos(n),h=s*this._height;if(r){t.x=o,t.y=h,t.z=l;return}rf.P.TransformCoordinatesFromFloatsToRef(o,h,l,e,t)}clone(){let e=new nq(this._radius,this._angle,this.directionRandomizer);return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat2("radius",this._radius,this.radiusRange),e.setFloat("coneAngle",this._angle),e.setFloat2("height",this._height,this.heightRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",2),e.addUniform("coneAngle",1),e.addUniform("height",2),e.addUniform("directionRandomizer",1)}getEffectDefines(){let e="#define CONEEMITTER";return this.emitFromSpawnPointOnly&&(e+="\n#define CONEEMITTERSPAWNPOINT"),e}getClassName(){return"ConeParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this._radius,e.angle=this._angle,e.directionRandomizer=this.directionRandomizer,e.radiusRange=this.radiusRange,e.heightRange=this.heightRange,e.emitFromSpawnPointOnly=this.emitFromSpawnPointOnly,e}parse(e){this.radius=e.radius,this.angle=e.angle,this.directionRandomizer=e.directionRandomizer,this.radiusRange=void 0!==e.radiusRange?e.radiusRange:1,this.heightRange=void 0!==e.radiusRange?e.heightRange:1,this.emitFromSpawnPointOnly=void 0!==e.emitFromSpawnPointOnly&&e.emitFromSpawnPointOnly}}class nK{constructor(e=1,t=1,i=1,r=0){this.radius=e,this.height=t,this.radiusRange=i,this.directionRandomizer=r,this._tempVector=rf.P.Zero()}startDirectionFunction(e,t,i,r,s){i.position.subtractToRef(e.getTranslation(),this._tempVector),this._tempVector.normalize(),rf.P.TransformNormalToRef(this._tempVector,s,this._tempVector);let n=rk.R.RandomRange(-this.directionRandomizer/2,this.directionRandomizer/2),a=Math.atan2(this._tempVector.x,this._tempVector.z);if(a+=rk.R.RandomRange(-Math.PI/2,Math.PI/2)*this.directionRandomizer,this._tempVector.y=n,this._tempVector.x=Math.sin(a),this._tempVector.z=Math.cos(a),this._tempVector.normalize(),r){t.copyFrom(this._tempVector);return}rf.P.TransformNormalFromFloatsToRef(this._tempVector.x,this._tempVector.y,this._tempVector.z,e,t)}startPositionFunction(e,t,i,r){let s=rk.R.RandomRange(-this.height/2,this.height/2),n=rk.R.RandomRange(0,2*Math.PI),a=Math.sqrt(rk.R.RandomRange((1-this.radiusRange)*(1-this.radiusRange),1))*this.radius,o=a*Math.cos(n),l=a*Math.sin(n);if(r){t.copyFromFloats(o,s,l);return}rf.P.TransformCoordinatesFromFloatsToRef(o,s,l,e,t)}clone(){let e=new nK(this.radius,this.directionRandomizer);return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define CYLINDEREMITTER"}getClassName(){return"CylinderParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.height=this.height,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.height=e.height,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class n$ extends nK{constructor(e=1,t=1,i=1,r=new rf.P(0,1,0),s=new rf.P(0,1,0)){super(e,t,i),this.direction1=r,this.direction2=s}startDirectionFunction(e,t){let i=rk.R.RandomRange(this.direction1.x,this.direction2.x),r=rk.R.RandomRange(this.direction1.y,this.direction2.y),s=rk.R.RandomRange(this.direction1.z,this.direction2.z);rf.P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new n$(this.radius,this.height,this.radiusRange,this.direction1,this.direction2);return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("height",this.height),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("height",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"}getClassName(){return"CylinderDirectedParticleEmitter"}serialize(){let e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class nQ{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=rk.R.RandomRange(0,this.directionRandomizer),a=rk.R.RandomRange(0,this.directionRandomizer),o=rk.R.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}rf.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-rk.R.RandomRange(0,this.radius*this.radiusRange),n=rk.R.RandomRange(0,1),a=rk.R.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,Math.abs(h),u);return}rf.P.TransformCoordinatesFromFloatsToRef(l,Math.abs(h),u,e,t)}clone(){let e=new nQ(this.radius,this.directionRandomizer);return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define HEMISPHERICEMITTER"}getClassName(){return"HemisphericParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class nZ{constructor(){this.direction1=new rf.P(0,1,0),this.direction2=new rf.P(0,1,0)}startDirectionFunction(e,t,i,r){let s=rk.R.RandomRange(this.direction1.x,this.direction2.x),n=rk.R.RandomRange(this.direction1.y,this.direction2.y),a=rk.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}rf.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(r){t.copyFromFloats(0,0,0);return}rf.P.TransformCoordinatesFromFloatsToRef(0,0,0,e,t)}clone(){let e=new nZ;return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define POINTEMITTER"}getClassName(){return"PointParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){rf.P.FromArrayToRef(e.direction1,0,this.direction1),rf.P.FromArrayToRef(e.direction2,0,this.direction2)}}class nJ{constructor(e=1,t=1,i=0){this.radius=e,this.radiusRange=t,this.directionRandomizer=i}startDirectionFunction(e,t,i,r){let s=i.position.subtract(e.getTranslation()).normalize(),n=rk.R.RandomRange(0,this.directionRandomizer),a=rk.R.RandomRange(0,this.directionRandomizer),o=rk.R.RandomRange(0,this.directionRandomizer);if(s.x+=n,s.y+=a,s.z+=o,s.normalize(),r){t.copyFrom(s);return}rf.P.TransformNormalFromFloatsToRef(s.x,s.y,s.z,e,t)}startPositionFunction(e,t,i,r){let s=this.radius-rk.R.RandomRange(0,this.radius*this.radiusRange),n=rk.R.RandomRange(0,1),a=rk.R.RandomRange(0,2*Math.PI),o=Math.acos(2*n-1),l=s*Math.cos(a)*Math.sin(o),h=s*Math.cos(o),u=s*Math.sin(a)*Math.sin(o);if(r){t.copyFromFloats(l,h,u);return}rf.P.TransformCoordinatesFromFloatsToRef(l,h,u,e,t)}clone(){let e=new nJ(this.radius,this.directionRandomizer);return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setFloat("directionRandomizer",this.directionRandomizer)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("directionRandomizer",1)}getEffectDefines(){return"#define SPHEREEMITTER"}getClassName(){return"SphereParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e.radius=this.radius,e.radiusRange=this.radiusRange,e.directionRandomizer=this.directionRandomizer,e}parse(e){this.radius=e.radius,this.radiusRange=e.radiusRange,this.directionRandomizer=e.directionRandomizer}}class n0 extends nJ{constructor(e=1,t=new rf.P(0,1,0),i=new rf.P(0,1,0)){super(e),this.direction1=t,this.direction2=i}startDirectionFunction(e,t){let i=rk.R.RandomRange(this.direction1.x,this.direction2.x),r=rk.R.RandomRange(this.direction1.y,this.direction2.y),s=rk.R.RandomRange(this.direction1.z,this.direction2.z);rf.P.TransformNormalFromFloatsToRef(i,r,s,e,t)}clone(){let e=new n0(this.radius,this.direction1,this.direction2);return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setFloat("radius",this.radius),e.setFloat("radiusRange",this.radiusRange),e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("radius",1),e.addUniform("radiusRange",1),e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return"#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"}getClassName(){return"SphereDirectedParticleEmitter"}serialize(){let e=super.serialize();return e.direction1=this.direction1.asArray(),e.direction2=this.direction2.asArray(),e}parse(e){super.parse(e),this.direction1.copyFrom(e.direction1),this.direction2.copyFrom(e.direction2)}}class n1{constructor(){this.particlePositionGenerator=()=>{},this.particleDestinationGenerator=()=>{}}startDirectionFunction(e,t,i,r){let s=rf.jp.Vector3[0];if(this.particleDestinationGenerator){this.particleDestinationGenerator(-1,i,s);let e=rf.jp.Vector3[1];s.subtractToRef(i.position,e),e.scaleToRef(1/i.lifeTime,s)}else s.set(0,0,0);if(r){t.copyFrom(s);return}rf.P.TransformNormalToRef(s,e,t)}startPositionFunction(e,t,i,r){let s=rf.jp.Vector3[0];if(this.particlePositionGenerator?this.particlePositionGenerator(-1,i,s):s.set(0,0,0),r){t.copyFrom(s);return}rf.P.TransformCoordinatesToRef(s,e,t)}clone(){let e=new n1;return rw.j.DeepCopy(this,e),e}applyToShader(e){}buildUniformLayout(e){}getEffectDefines(){return"#define CUSTOMEMITTER"}getClassName(){return"CustomParticleEmitter"}serialize(){let e={};return e.type=this.getClassName(),e}parse(e){}}class n2{get mesh(){return this._mesh}set mesh(e){this._mesh!==e&&(this._mesh=e,e?(this._indices=e.getIndices(),this._positions=e.getVerticesData(sm.o.PositionKind),this._normals=e.getVerticesData(sm.o.NormalKind)):(this._indices=null,this._positions=null,this._normals=null))}constructor(e=null){this._indices=null,this._positions=null,this._normals=null,this._storedNormal=rf.P.Zero(),this._mesh=null,this.direction1=new rf.P(0,1,0),this.direction2=new rf.P(0,1,0),this.useMeshNormalsForDirection=!0,this.mesh=e}startDirectionFunction(e,t,i,r){if(this.useMeshNormalsForDirection&&this._normals){rf.P.TransformNormalToRef(this._storedNormal,e,t);return}let s=rk.R.RandomRange(this.direction1.x,this.direction2.x),n=rk.R.RandomRange(this.direction1.y,this.direction2.y),a=rk.R.RandomRange(this.direction1.z,this.direction2.z);if(r){t.copyFromFloats(s,n,a);return}rf.P.TransformNormalFromFloatsToRef(s,n,a,e,t)}startPositionFunction(e,t,i,r){if(!this._indices||!this._positions)return;let s=3*Math.random()*(this._indices.length/3)|0,n=Math.random(),a=Math.random()*(1-n),o=1-n-a,l=this._indices[s],h=this._indices[s+1],u=this._indices[s+2],c=rf.jp.Vector3[0],d=rf.jp.Vector3[1],p=rf.jp.Vector3[2],_=rf.jp.Vector3[3];rf.P.FromArrayToRef(this._positions,3*l,c),rf.P.FromArrayToRef(this._positions,3*h,d),rf.P.FromArrayToRef(this._positions,3*u,p),_.x=n*c.x+a*d.x+o*p.x,_.y=n*c.y+a*d.y+o*p.y,_.z=n*c.z+a*d.z+o*p.z,r?t.copyFromFloats(_.x,_.y,_.z):rf.P.TransformCoordinatesFromFloatsToRef(_.x,_.y,_.z,e,t),this.useMeshNormalsForDirection&&this._normals&&(rf.P.FromArrayToRef(this._normals,3*l,c),rf.P.FromArrayToRef(this._normals,3*h,d),rf.P.FromArrayToRef(this._normals,3*u,p),this._storedNormal.x=n*c.x+a*d.x+o*p.x,this._storedNormal.y=n*c.y+a*d.y+o*p.y,this._storedNormal.z=n*c.z+a*d.z+o*p.z)}clone(){let e=new n2(this.mesh);return rw.j.DeepCopy(this,e),e}applyToShader(e){e.setVector3("direction1",this.direction1),e.setVector3("direction2",this.direction2)}buildUniformLayout(e){e.addUniform("direction1",3),e.addUniform("direction2",3)}getEffectDefines(){return""}getClassName(){return"MeshParticleEmitter"}serialize(){var e;let t={};return t.type=this.getClassName(),t.direction1=this.direction1.asArray(),t.direction2=this.direction2.asArray(),t.meshId=null===(e=this.mesh)||void 0===e?void 0:e.id,t.useMeshNormalsForDirection=this.useMeshNormalsForDirection,t}parse(e,t){rf.P.FromArrayToRef(e.direction1,0,this.direction1),rf.P.FromArrayToRef(e.direction2,0,this.direction2),e.meshId&&t&&(this.mesh=t.getLastMeshById(e.meshId)),this.useMeshNormalsForDirection=e.useMeshNormalsForDirection}}i(6529);class n3{get noiseTexture(){return this._noiseTexture}set noiseTexture(e){this._noiseTexture!==e&&(this._noiseTexture=e,this._reset())}get isAnimationSheetEnabled(){return this._isAnimationSheetEnabled}set isAnimationSheetEnabled(e){this._isAnimationSheetEnabled!=e&&(this._isAnimationSheetEnabled=e,this._reset())}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){this._useLogarithmicDepth=e&&this.getScene().getEngine().getCaps().fragmentDepthSupported}getScene(){return this._scene}_hasTargetStopDurationDependantGradient(){return this._startSizeGradients&&this._startSizeGradients.length>0||this._emitRateGradients&&this._emitRateGradients.length>0||this._lifeTimeGradients&&this._lifeTimeGradients.length>0}getDragGradients(){return this._dragGradients}getLimitVelocityGradients(){return this._limitVelocityGradients}getColorGradients(){return this._colorGradients}getSizeGradients(){return this._sizeGradients}getColorRemapGradients(){return this._colorRemapGradients}getAlphaRemapGradients(){return this._alphaRemapGradients}getLifeTimeGradients(){return this._lifeTimeGradients}getAngularSpeedGradients(){return this._angularSpeedGradients}getVelocityGradients(){return this._velocityGradients}getStartSizeGradients(){return this._startSizeGradients}getEmitRateGradients(){return this._emitRateGradients}get direction1(){return this.particleEmitterType.direction1?this.particleEmitterType.direction1:rf.P.Zero()}set direction1(e){this.particleEmitterType.direction1&&(this.particleEmitterType.direction1=e)}get direction2(){return this.particleEmitterType.direction2?this.particleEmitterType.direction2:rf.P.Zero()}set direction2(e){this.particleEmitterType.direction2&&(this.particleEmitterType.direction2=e)}get minEmitBox(){return this.particleEmitterType.minEmitBox?this.particleEmitterType.minEmitBox:rf.P.Zero()}set minEmitBox(e){this.particleEmitterType.minEmitBox&&(this.particleEmitterType.minEmitBox=e)}get maxEmitBox(){return this.particleEmitterType.maxEmitBox?this.particleEmitterType.maxEmitBox:rf.P.Zero()}set maxEmitBox(e){this.particleEmitterType.maxEmitBox&&(this.particleEmitterType.maxEmitBox=e)}get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._reset())}get isBillboardBased(){return this._isBillboardBased}set isBillboardBased(e){this._isBillboardBased!==e&&(this._isBillboardBased=e,this._reset())}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(!e&&this._scene?this._imageProcessingConfiguration=this._scene.imageProcessingConfiguration:this._imageProcessingConfiguration=e)}_reset(){}_removeGradientAndTexture(e,t,i){if(!t)return this;let r=0;for(let i of t){if(i.gradient===e){t.splice(r,1);break}r++}return i&&i.dispose(),this}constructor(e){this.animations=[],this.renderingGroupId=0,this.emitter=rf.P.Zero(),this.emitRate=10,this.manualEmitCount=-1,this.updateSpeed=.01,this.targetStopDuration=0,this.disposeOnStop=!1,this.minEmitPower=1,this.maxEmitPower=1,this.minLifeTime=1,this.maxLifeTime=1,this.minSize=1,this.maxSize=1,this.minScaleX=1,this.maxScaleX=1,this.minScaleY=1,this.maxScaleY=1,this.minInitialRotation=0,this.maxInitialRotation=0,this.minAngularSpeed=0,this.maxAngularSpeed=0,this.layerMask=268435455,this.customShader=null,this.preventAutoStart=!1,this._wasDispatched=!1,this._rootUrl="",this.noiseStrength=new rf.P(10,10,10),this.onAnimationEnd=null,this.blendMode=n3.BLENDMODE_ONEONE,this.forceDepthWrite=!1,this.preWarmCycles=0,this.preWarmStepOffset=1,this.spriteCellChangeSpeed=1,this.startSpriteCellID=0,this.endSpriteCellID=0,this.spriteCellWidth=0,this.spriteCellHeight=0,this.spriteCellLoop=!0,this.spriteRandomStartCell=!1,this.translationPivot=new rf.FM(0,0),this.beginAnimationOnStart=!1,this.beginAnimationFrom=0,this.beginAnimationTo=60,this.beginAnimationLoop=!1,this.worldOffset=new rf.P(0,0,0),this._useLogarithmicDepth=!1,this.gravity=rf.P.Zero(),this._colorGradients=null,this._sizeGradients=null,this._lifeTimeGradients=null,this._angularSpeedGradients=null,this._velocityGradients=null,this._limitVelocityGradients=null,this._dragGradients=null,this._emitRateGradients=null,this._startSizeGradients=null,this._rampGradients=null,this._colorRemapGradients=null,this._alphaRemapGradients=null,this.startDelay=0,this.limitVelocityDamping=.4,this.color1=new rm.HE(1,1,1,1),this.color2=new rm.HE(1,1,1,1),this.colorDead=new rm.HE(0,0,0,1),this.textureMask=new rm.HE(1,1,1,1),this._isSubEmitter=!1,this._billboardMode=7,this._isBillboardBased=!0,this._imageProcessingConfigurationDefines=new nY.b,this.id=e,this.name=e}createPointEmitter(e,t){let i=new nZ;return i.direction1=e,i.direction2=t,this.particleEmitterType=i,i}createHemisphericEmitter(e=1,t=1){let i=new nQ(e,t);return this.particleEmitterType=i,i}createSphereEmitter(e=1,t=1){let i=new nJ(e,t);return this.particleEmitterType=i,i}createDirectedSphereEmitter(e=1,t=new rf.P(0,1,0),i=new rf.P(0,1,0)){let r=new n0(e,t,i);return this.particleEmitterType=r,r}createCylinderEmitter(e=1,t=1,i=1,r=0){let s=new nK(e,t,i,r);return this.particleEmitterType=s,s}createDirectedCylinderEmitter(e=1,t=1,i=1,r=new rf.P(0,1,0),s=new rf.P(0,1,0)){let n=new n$(e,t,i,r,s);return this.particleEmitterType=n,n}createConeEmitter(e=1,t=Math.PI/4){let i=new nq(e,t);return this.particleEmitterType=i,i}createBoxEmitter(e,t,i,r){let s=new nj;return this.particleEmitterType=s,this.direction1=e,this.direction2=t,this.minEmitBox=i,this.maxEmitBox=r,s}}n3.BLENDMODE_ONEONE=0,n3.BLENDMODE_STANDARD=1,n3.BLENDMODE_ADD=2,n3.BLENDMODE_MULTIPLY=3,n3.BLENDMODE_MULTIPLYADD=4;class n4 extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("rgba",tf.Color4,!0),this.registerInput("rgb ",tf.Color3,!0),this.registerOutput("rgb",tf.Color3),this.registerOutput("r",tf.Float),this.registerOutput("g",tf.Float),this.registerOutput("b",tf.Float),this.registerOutput("a",tf.Float),this.inputsAreExclusive=!0}getClassName(){return"ColorSplitterBlock"}get rgba(){return this._inputs[0]}get rgbIn(){return this._inputs[1]}get rgbOut(){return this._outputs[0]}get r(){return this._outputs[1]}get g(){return this._outputs[2]}get b(){return this._outputs[3]}get a(){return this._outputs[4]}_inputRename(e){return"rgb "===e?"rgbIn":e}_outputRename(e){return"rgb"===e?"rgbOut":e}_buildBlock(e){super._buildBlock(e);let t=this.rgba.isConnected?this.rgba:this.rgbIn;if(!t.isConnected)return;let i=this._outputs[0],r=this._outputs[1],s=this._outputs[2],n=this._outputs[3],a=this._outputs[4];return i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = ${t.associatedVariableName}.rgb; +`),r.hasEndpoints&&(e.compilationString+=this._declareOutput(r,e)+` = ${t.associatedVariableName}.r; +`),s.hasEndpoints&&(e.compilationString+=this._declareOutput(s,e)+` = ${t.associatedVariableName}.g; +`),n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = ${t.associatedVariableName}.b; +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = ${t.associatedVariableName}.a; +`),this}}(0,rg.H)("BABYLON.ColorSplitterBlock",n4);var n5=i(5184),n6=i(2195);sK.B.prototype.createRenderTargetCubeTexture=function(e,t){let i=this._createHardwareRenderTargetWrapper(!1,!0,e),r=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5},t);r.generateStencilBuffer=r.generateDepthBuffer&&r.generateStencilBuffer,(1!==r.type||this._caps.textureFloatLinearFiltering)&&(2!==r.type||this._caps.textureHalfFloatLinearFiltering)||(r.samplingMode=1);let s=this._gl,n=new sq.l(this,sq.S.RenderTarget);this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,n,!0);let a=this._getSamplingParameters(r.samplingMode,r.generateMipMaps);1!==r.type||this._caps.textureFloat||(r.type=0,rb.Y.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MAG_FILTER,a.mag),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_MIN_FILTER,a.min),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE);for(let t=0;t<6;t++)s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(r.type,r.format),e,e,0,this._getInternalFormat(r.format),this._getWebGLTextureType(r.type),null);let o=s.createFramebuffer();return this._bindUnboundFramebuffer(o),i._depthStencilBuffer=this._setupFramebufferDepthAttachments(r.generateStencilBuffer,r.generateDepthBuffer,e,e),r.generateMipMaps&&s.generateMipmap(s.TEXTURE_CUBE_MAP),this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),i._framebuffer=o,i._generateDepthBuffer=r.generateDepthBuffer,i._generateStencilBuffer=r.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=r.generateMipMaps,n.samplingMode=r.samplingMode,n.type=r.type,n.format=r.format,this._internalTexturesCache.push(n),i.setTextures(n),i};let n8={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class n7{constructor(e,t=n8){var i,r;this._fullscreenViewport=new ny.l(0,0,1,1);let s=null!==(i=t.positions)&&void 0!==i?i:n8.positions,n=null!==(r=t.indices)&&void 0!==r?r:n8.indices;this.engine=e,this._vertexBuffers={[sm.o.PositionKind]:new sm.o(e,s,sm.o.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(n),this._onContextRestoredObserver=e.onContextRestoredObservable.add(()=>{for(let t in this._indexBuffer=e.createIndexBuffer(n),this._vertexBuffers)this._vertexBuffers[t]._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(0,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();let i=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;i&&this.engine.bindFramebuffer(i),this.applyEffectWrapper(e),this.draw(),i&&this.engine.unBindFramebuffer(i),this.restoreStates()}dispose(){let e=this._vertexBuffers[sm.o.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[sm.o.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class n9{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new r_.y$;let i=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(i.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add(()=>{this.effect.setFloat2("scale",1,1)}));let r=e.defines?e.defines.join("\n"):"";this._drawWrapper=new nk.q(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"],i,e.samplerNames,r,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage)):(this.effect=new nd.Q(t,e.attributeNames||["position"],i,e.samplerNames,e.engine,r,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add(()=>{this.effect._pipelineContext=null,this.effect._wasPreviouslyReady=!1,this.effect._prepareEffect()}))}dispose(){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}let ae="passPixelShader",at=`varying vec2 vUV;uniform sampler2D textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);}`;nw.v.ShadersStore[ae]=at;let ai={name:ae,shader:at};class ar{static _CreateDumpRenderer(){if(!ar._DumpToolsEngine){let e;let t=null,i={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new sK.B(e,!1,i)}catch(r){e=document.createElement("canvas"),t=new sK.B(e,!1,i)}t.getCaps().parallelShaderCompile=void 0;let r=new n7(t),s=new n9({engine:t,name:ai.name,fragmentShader:ai.shader,samplerNames:["textureSampler"]});ar._DumpToolsEngine={canvas:e,engine:t,renderer:r,wrapper:s}}return ar._DumpToolsEngine}static async DumpFramebuffer(e,t,i,r,s="image/png",n,a){let o=await i.readPixels(0,0,e,t),l=new Uint8Array(o.buffer);ar.DumpData(e,t,l,r,s,n,!0,void 0,a)}static DumpDataAsync(e,t,i,r="image/png",s,n=!1,a=!1,o){return new Promise(l=>{ar.DumpData(e,t,i,e=>l(e),r,s,n,a,o)})}static DumpData(e,t,i,r,s="image/png",n,a=!1,o=!1,l){let h=ar._CreateDumpRenderer();if(h.engine.setSize(e,t,!0),i instanceof Float32Array){let e=new Uint8Array(i.length),t=i.length;for(;t--;){let r=i[t];e[t]=Math.round(255*rk.R.Clamp(r))}i=e}let u=h.engine.createRawTexture(i,e,t,5,!1,!a,1);h.renderer.setViewport(),h.renderer.applyEffectWrapper(h.wrapper),h.wrapper.effect._bindTexture("textureSampler",u),h.renderer.draw(),o?sg.w1.ToBlob(h.canvas,e=>{let t=new FileReader;t.onload=e=>{let t=e.target.result;r&&r(t)},t.readAsArrayBuffer(e)},s,l):sg.w1.EncodeScreenshotCanvasData(h.canvas,r,s,n,l),u.dispose()}static Dispose(){ar._DumpToolsEngine&&(ar._DumpToolsEngine.wrapper.dispose(),ar._DumpToolsEngine.renderer.dispose(),ar._DumpToolsEngine.engine.dispose()),ar._DumpToolsEngine=null}}sg.w1.DumpData=ar.DumpData,sg.w1.DumpDataAsync=ar.DumpDataAsync,sg.w1.DumpFramebuffer=ar.DumpFramebuffer;class as extends sj{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=(0,r4.M)(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 i;i=Array.isArray(e)?e:[e];for(let e=0;e{var i;let r=this._renderList?this._renderList.length:0;(0===t&&r>0||0===r)&&(null===(i=this.getScene())||void 0===i||i.meshes.forEach(e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new r_.y$,this.onAfterUnbindObservable=new r_.y$,this.onBeforeRenderObservable=new r_.y$,this.onAfterRenderObservable=new r_.y$,this.onClearObservable=new r_.y$,this.onResizeObservable=new r_.y$,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=rf.P.Zero(),!(i=this.getScene()))return;let A=this.getScene().getEngine();if(this._gammaSpace=y,this._coordinatesMode=sj.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=!!r,this._doNotChangeAspectRatio=s,this._renderingManager=new n6.$(i),this._renderingManager._useSceneAutoClearSetup=!0,u)return;this._renderTargetOptions={generateMipMaps:r,type:n,format:null!==(C=this._format)&&void 0!==C?C:void 0,samplingMode:this.samplingMode,generateDepthBuffer:l,generateStencilBuffer:h,samples:p,creationFlags:_,noColorAttachment:f,useSRGBBuffer:m,colorAttachment:b,label:this.name},this.samplingMode===sj.NEAREST_SAMPLINGMODE&&(this.wrapU=sj.CLAMP_ADDRESSMODE,this.wrapV=sj.CLAMP_ADDRESSMODE),d||(a?(this._renderTarget=i.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=sj.INVCUBIC_MODE,this._textureMatrix=rf.y3.Identity()):this._renderTarget=i.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0===p||(this.samples=p))}createDepthStencilTexture(e=0,t=!0,i=!1,r=1,s=14){var n;null===(n=this._renderTarget)||void 0===n||n.createDepthStencilTexture(e,t,i,r,s)}_releaseRenderPassId(){if(this._scene){let e=this._scene.getEngine();for(let t=0;t0&&(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(){return this._size.layers||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){let t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){var t;let i=this.isCube;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null;let r=this.getScene();r&&(this._processSizeParameter(e,!1),i?this._renderTarget=r.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):this._renderTarget=r.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,i=!1){var r;let s=this.getScene();if(!s)return i;let n=s.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e{this.onAfterRenderObservable.notifyObservers(t)})}_prepareFrame(e,t,i,r){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):r&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,i)}_renderToTarget(e,t,i,r=0,s=null){var n,a,o,l,h,u;let c=this.getScene();if(!c)return;let d=c.getEngine();if(null===(n=d._debugPushGroup)||void 0===n||n.call(d,`render to face #${e} layer #${r}`,1),this._prepareFrame(c,e,r,t),this.is2DArray?(d.currentRenderPassId=this._renderPassIds[r],this.onBeforeRenderObservable.notifyObservers(r)):(d.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e)),d.snapshotRendering&&1===d.snapshotRenderingMode)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0);else{let n=null,u=this.renderList?this.renderList:c.getActiveMeshes().data,p=this.renderList?this.renderList.length:c.getActiveMeshes().length;for(let t of(this.getCustomRenderList&&(n=this.getCustomRenderList(this.is2DArray?r:e,u,p)),n?this._prepareRenderingManager(n,n.length,s,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(u,p,s,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),n=u),c._beforeRenderTargetClearStage))t.action(this,e,r);for(let t of(this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(d):this.skipInitialClear||d.clear(this.clearColor||c.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),c._beforeRenderTargetDrawStage))t.action(this,e,r);for(let t of(this._renderingManager.render(this.customRenderFunction,n,this.renderParticles,this.renderSprites),c._afterRenderTargetDrawStage))t.action(this,e,r);let _=null!==(o=null===(a=this._texture)||void 0===a?void 0:a.generateMipMaps)&&void 0!==o&&o;for(let i of(this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,null!==(l=this._renderTarget)&&void 0!==l?l:void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&c.postProcessManager._finalizeFrame(!1,null!==(h=this._renderTarget)&&void 0!==h?h:void 0,e),c._afterRenderTargetPostProcessStage))i.action(this,e,r);this._texture&&(this._texture.generateMipMaps=_),this._doNotChangeAspectRatio||c.updateTransformMatrix(!0),i&&ar.DumpFramebuffer(this.getRenderWidth(),this.getRenderHeight(),d)}this._unbindFrameBuffer(d,e),this._texture&&this.isCube&&5===e&&d.generateMipMapsForCubemap(this._texture),null===(u=d._debugPopGroup)||void 0===u||u.call(d,1)}setRenderingOrder(e,t=null,i=null,r=null){this._renderingManager.setRenderingOrder(e,t,i,r)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){let e=this.getSize(),t=new as(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;let e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t=0&&t.customRenderTargets.splice(i,1),t.cameras))(i=e.customRenderTargets.indexOf(this))>=0&&e.customRenderTargets.splice(i,1);null===(e=this._renderTarget)||void 0===e||e.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===as.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=as.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}as.REFRESHRATE_RENDER_ONCE=0,as.REFRESHRATE_RENDER_ONEVERYFRAME=1,as.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,sj._CreateRenderTargetTexture=(e,t,i,r,s)=>new as(e,t,i,r);class an{constructor(e){this.name=sN.l.NAME_PROCEDURALTEXTURE,this.scene=e,this.scene.proceduralTextures=[]}register(){this.scene._beforeClearStage.registerStep(sN.l.STEP_BEFORECLEAR_PROCEDURALTEXTURE,this,this._beforeClear)}rebuild(){}dispose(){}_beforeClear(){if(this.scene.proceduralTexturesEnabled){sg.w1.StartPerformanceCounter("Procedural textures",this.scene.proceduralTextures.length>0);for(let e=0;e0)}}}let aa=`attribute vec2 position;varying vec2 vPosition;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vPosition=position;vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.proceduralVertexShader=aa;class ao extends sj{constructor(e,t,i,r,s=null,n=!0,a=!1,o=0){var l;super(null,r,!n),this.isEnabled=!0,this.autoClear=!0,this.onGeneratedObservable=new r_.y$,this.onBeforeGenerationObservable=new r_.y$,this.nodeMaterialSource=null,this._textures={},this._currentRefreshId=-1,this._frameId=-1,this._refreshRate=1,this._vertexBuffers={},this._uniforms=[],this._samplers=[],this._floats={},this._ints={},this._floatsArrays={},this._colors3={},this._colors4={},this._vectors2={},this._vectors3={},this._matrices={},this._fallbackTextureUsed=!1,this._cachedDefines=null,this._contentUpdateId=-1,this._rtWrapper=null,null===s||s instanceof sj?(this._options={},this._fallbackTexture=s):(this._options=s,this._fallbackTexture=null!==(l=s.fallbackTexture)&&void 0!==l?l:null);let h=(r=this.getScene()||rL.l.LastCreatedScene)._getComponent(sN.l.NAME_PROCEDURALTEXTURE);h||(h=new an(r),r._addComponent(h)),r.proceduralTextures.push(this),this._fullEngine=r.getEngine(),this.name=e,this.isRenderTarget=!0,this._size=t,this._textureType=o,this._generateMipMaps=n,this._drawWrapper=new nk.q(this._fullEngine),this.setFragment(i);let u=this._createRtWrapper(a,t,n,o);this._texture=u.texture;let c=[];c.push(1,1),c.push(-1,1),c.push(-1,-1),c.push(1,-1),this._vertexBuffers[sm.o.PositionKind]=new sm.o(this._fullEngine,c,sm.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createRtWrapper(e,t,i,r){return e?(this._rtWrapper=this._fullEngine.createRenderTargetCubeTexture(t,Object.assign({generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r},this._options)),this.setFloat("face",0)):this._rtWrapper=this._fullEngine.createRenderTargetTexture(t,Object.assign({generateMipMaps:i,generateDepthBuffer:!1,generateStencilBuffer:!1,type:r},this._options)),this._rtWrapper}getEffect(){return this._drawWrapper.effect}_setEffect(e){this._drawWrapper.effect=e}getContent(){return this._contentData&&this._frameId===this._contentUpdateId||(this._contentData?this._contentData.then(e=>{this._contentData=this.readPixels(0,0,e),this._contentUpdateId=this._frameId}):(this._contentData=this.readPixels(0,0),this._contentUpdateId=this._frameId)),this._contentData}_createIndexBuffer(){let e=this._fullEngine,t=[];t.push(0),t.push(1),t.push(2),t.push(0),t.push(2),t.push(3),this._indexBuffer=e.createIndexBuffer(t)}_rebuild(){let e=this._vertexBuffers[sm.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer(),this.refreshRate===as.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=as.REFRESHRATE_RENDER_ONCE)}reset(){var e;null===(e=this._drawWrapper.effect)||void 0===e||e.dispose(),this._drawWrapper.effect=null,this._cachedDefines=null}_getDefines(){return""}executeWhenReady(e){if(this.isReady()){e(this);return}let t=this.getEffect();t&&t.executeWhenCompiled(()=>{e(this)})}isReady(){let e=this._fullEngine;if(this.nodeMaterialSource)return this._drawWrapper.effect.isReady();if(!this._fragment)return!1;if(this._fallbackTextureUsed)return!0;if(!this._texture)return!1;let t=this._getDefines();if(this._drawWrapper.effect&&t===this._cachedDefines&&this._drawWrapper.effect.isReady())return!0;let i={vertex:"procedural",fragmentElement:this._fragment.fragmentElement,fragmentSource:this._fragment.fragmentSource,fragment:"string"==typeof this._fragment?this._fragment:void 0};return this._cachedDefines!==t&&(this._cachedDefines=t,this._drawWrapper.effect=e.createEffect(i,[sm.o.PositionKind],this._uniforms,this._samplers,t,void 0,void 0,()=>{var e;null===(e=this._rtWrapper)||void 0===e||e.dispose(),this._rtWrapper=this._texture=null,this._fallbackTexture&&(this._texture=this._fallbackTexture._texture,this._texture&&this._texture.incrementReferences()),this._fallbackTextureUsed=!0})),this._drawWrapper.effect.isReady()}resetRefreshCounter(){this._currentRefreshId=-1}setFragment(e){this._fragment=e}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}_shouldRender(){return this.isEnabled&&this.isReady()&&this._texture?!this._fallbackTextureUsed&&(-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,this._frameId++,!0):(this._currentRefreshId++,!1)):(this._texture&&(this._texture.isReady=!1),!1)}getRenderSize(){return this._size}resize(e,t){if(this._fallbackTextureUsed||!this._rtWrapper||!this._texture)return;let i=this._texture.isCube;this._rtWrapper.dispose();let r=this._createRtWrapper(i,e,t,this._textureType);this._texture=r.texture,this._size=e,this._generateMipMaps=t}_checkUniform(e){-1===this._uniforms.indexOf(e)&&this._uniforms.push(e)}setTexture(e,t){return -1===this._samplers.indexOf(e)&&this._samplers.push(e),this._textures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}render(e){var t,i;let r=this.getScene();if(!r)return;let s=this._fullEngine;if(s.enableEffect(this._drawWrapper),this.onBeforeGenerationObservable.notifyObservers(this),s.setState(!1),!this.nodeMaterialSource){for(let e in this._textures)this._drawWrapper.effect.setTexture(e,this._textures[e]);for(let e in this._ints)this._drawWrapper.effect.setInt(e,this._ints[e]);for(let e in this._floats)this._drawWrapper.effect.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)this._drawWrapper.effect.setArray(e,this._floatsArrays[e]);for(let e in this._colors3)this._drawWrapper.effect.setColor3(e,this._colors3[e]);for(let e in this._colors4){let t=this._colors4[e];this._drawWrapper.effect.setFloat4(e,t.r,t.g,t.b,t.a)}for(let e in this._vectors2)this._drawWrapper.effect.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)this._drawWrapper.effect.setVector3(e,this._vectors3[e]);for(let e in this._matrices)this._drawWrapper.effect.setMatrix(e,this._matrices[e])}if(!this._texture||!this._rtWrapper)return;null===(t=s._debugPushGroup)||void 0===t||t.call(s,`procedural texture generation for ${this.name}`,1);let n=s.currentViewport;if(this.isCube)for(let e=0;e<6;e++)s.bindFramebuffer(this._rtWrapper,e,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this._drawWrapper.effect.setFloat("face",e),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(nu.F.TriangleFillMode,0,6);else s.bindFramebuffer(this._rtWrapper,0,void 0,void 0,!0),s.bindBuffers(this._vertexBuffers,this._indexBuffer,this._drawWrapper.effect),this.autoClear&&s.clear(r.clearColor,!0,!1,!1),s.drawElementsType(nu.F.TriangleFillMode,0,6);s.unBindFramebuffer(this._rtWrapper,this.isCube),n&&s.setViewport(n),this.isCube&&s.generateMipMapsForCubemap(this._texture),null===(i=s._debugPopGroup)||void 0===i||i.call(s,1),this.onGenerated&&this.onGenerated(),this.onGeneratedObservable.notifyObservers(this)}clone(){let e=this.getSize(),t=new ao(this.name,e.width,this._fragment,this.getScene(),this._fallbackTexture,this._generateMipMaps);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,t}dispose(){let e=this.getScene();if(!e)return;let t=e.proceduralTextures.indexOf(this);t>=0&&e.proceduralTextures.splice(t,1);let i=this._vertexBuffers[sm.o.PositionKind];i&&(i.dispose(),this._vertexBuffers[sm.o.PositionKind]=null),this._indexBuffer&&this._fullEngine._releaseBuffer(this._indexBuffer)&&(this._indexBuffer=null),this.onGeneratedObservable.clear(),this.onBeforeGenerationObservable.clear(),super.dispose()}}(0,sx.gn)([(0,rG.qC)()],ao.prototype,"isEnabled",void 0),(0,sx.gn)([(0,rG.qC)()],ao.prototype,"autoClear",void 0),(0,sx.gn)([(0,rG.qC)()],ao.prototype,"_generateMipMaps",void 0),(0,sx.gn)([(0,rG.qC)()],ao.prototype,"_size",void 0),(0,sx.gn)([(0,rG.qC)()],ao.prototype,"refreshRate",null),(0,rg.H)("BABYLON.ProceduralTexture",ao),(v=tb||(tb={}))[v.Cos=0]="Cos",v[v.Sin=1]="Sin",v[v.Abs=2]="Abs",v[v.Exp=3]="Exp",v[v.Exp2=4]="Exp2",v[v.Round=5]="Round",v[v.Floor=6]="Floor",v[v.Ceiling=7]="Ceiling",v[v.Sqrt=8]="Sqrt",v[v.Log=9]="Log",v[v.Tan=10]="Tan",v[v.ArcTan=11]="ArcTan",v[v.ArcCos=12]="ArcCos",v[v.ArcSin=13]="ArcSin",v[v.Fract=14]="Fract",v[v.Sign=15]="Sign",v[v.Radians=16]="Radians",v[v.Degrees=17]="Degrees";class al extends nv{constructor(e){super(e,tm.Neutral),this.operation=tb.Cos,this.registerInput("input",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"TrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="";switch(this.operation){case tb.Cos:i="cos";break;case tb.Sin:i="sin";break;case tb.Abs:i="abs";break;case tb.Exp:i="exp";break;case tb.Exp2:i="exp2";break;case tb.Round:i="round";break;case tb.Floor:i="floor";break;case tb.Ceiling:i="ceil";break;case tb.Sqrt:i="sqrt";break;case tb.Log:i="log";break;case tb.Tan:i="tan";break;case tb.ArcTan:i="atan";break;case tb.ArcCos:i="acos";break;case tb.ArcSin:i="asin";break;case tb.Fract:i="fract";break;case tb.Sign:i="sign";break;case tb.Radians:i="radians";break;case tb.Degrees:i="degrees"}return e.compilationString+=this._declareOutput(t,e)+` = ${i}(${this.input.associatedVariableName}); +`,this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.TrigonometryBlockOperations.${tb[this.operation]}; +`}}(0,rg.H)("BABYLON.TrigonometryBlock",al);let ah={effect:null,subMesh:null};class au extends nf.H{constructor(){super(),this.NORMAL=!1,this.TANGENT=!1,this.VERTEXCOLOR_NME=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.PREPASS=!1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!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=!1,this.TONEMAPPING_ACES=!1,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.BUMPDIRECTUV=0,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.rebuild()}setValue(e,t,i=!1){void 0===this[e]&&this._keys.push(e),i&&this[e]!==t&&this.markAsUnprocessed(),this[e]=t}}class ac extends nc{static _BlockIsTextureBlock(e){return"TextureBlock"===e.getClassName()||"ReflectionTextureBaseBlock"===e.getClassName()||"RefractionBlock"===e.getClassName()||"CurrentScreenBlock"===e.getClassName()||"ParticleTextureBlock"===e.getClassName()||"ImageSourceBlock"===e.getClassName()||"TriPlanarBlock"===e.getClassName()||"BiPlanarBlock"===e.getClassName()||"PrePassTextureBlock"===e.getClassName()}_getGlobalNodeMaterialEditor(){return"undefined"!=typeof NODEEDITOR?NODEEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeEditor?BABYLON:void 0}get options(){return this._options}set options(e){this._options=e}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get mode(){return this._mode}set mode(e){this._mode=e}get buildId(){return this._buildId}set buildId(e){this._buildId=e}constructor(e,t,i={}){super(e,t||rL.l.LastCreatedScene),this._buildId=ac._BuildIdGenerator++,this._buildWasSuccessful=!1,this._cachedWorldViewMatrix=new rf.y3,this._cachedWorldViewProjectionMatrix=new rf.y3,this._optimizers=[],this._animationFrame=-1,this.BJSNODEMATERIALEDITOR=this._getGlobalNodeMaterialEditor(),this.editorData=null,this.ignoreAlpha=!1,this.maxSimultaneousLights=4,this.onBuildObservable=new r_.y$,this._vertexOutputNodes=[],this._fragmentOutputNodes=[],this.attachedBlocks=[],this._mode=tC.Material,this.forceAlphaBlending=!1,this._options=Object.assign({emitComments:!1},i),this._attachImageProcessingConfiguration(null)}getClassName(){return"NodeMaterial"}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){sg.w1.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlockByPredicate(e){for(let t of this.attachedBlocks)if(t.isInput&&e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}registerOptimizer(e){if(!(this._optimizers.indexOf(e)>-1))return this._optimizers.push(e),this}unregisterOptimizer(e){let t=this._optimizers.indexOf(e);if(-1!==t)return this._optimizers.splice(t,1),this}addOutputNode(e){if(null===e.target)throw"This node is not meant to be an output node. You may want to explicitly set its target value.";return(e.target&tm.Vertex)!=0&&this._addVertexOutputNode(e),(e.target&tm.Fragment)!=0&&this._addFragmentOutputNode(e),this}removeOutputNode(e){return null===e.target||((e.target&tm.Vertex)!=0&&this._removeVertexOutputNode(e),(e.target&tm.Fragment)!=0&&this._removeFragmentOutputNode(e)),this}_addVertexOutputNode(e){if(-1===this._vertexOutputNodes.indexOf(e))return e.target=tm.Vertex,this._vertexOutputNodes.push(e),this}_removeVertexOutputNode(e){let t=this._vertexOutputNodes.indexOf(e);if(-1!==t)return this._vertexOutputNodes.splice(t,1),this}_addFragmentOutputNode(e){if(-1===this._fragmentOutputNodes.indexOf(e))return e.target=tm.Fragment,this._fragmentOutputNodes.push(e),this}_removeFragmentOutputNode(e){let t=this._fragmentOutputNodes.indexOf(e);if(-1!==t)return this._fragmentOutputNodes.splice(t,1),this}needAlphaBlending(){return!this.ignoreAlpha&&(this.forceAlphaBlending||this.alpha<1||this._sharedData&&this._sharedData.hints.needAlphaBlending)}needAlphaTesting(){return this._sharedData&&this._sharedData.hints.needAlphaTesting}_processInitializeOnLink(e,t,i,r=!0){e.target===tm.VertexAndFragment?i.push(e):t.target===tm.Fragment&&e.target===tm.Vertex&&e._preparationId!==this._buildId&&i.push(e),this._initializeBlock(e,t,i,r)}_initializeBlock(e,t,i,r=!0){if(e.initialize(t),r&&e.autoConfigure(this),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)){if(e.isUnique){let t=e.getClassName();for(let e of this.attachedBlocks)if(e.getClassName()===t)throw`Cannot have multiple blocks of type ${t} in the same NodeMaterial`}this.attachedBlocks.push(e)}for(let s of e.inputs){s.associatedVariableName="";let n=s.connectedPoint;if(n){let s=n.ownerBlock;s!==e&&this._processInitializeOnLink(s,t,i,r)}}for(let s of(e.isTeleportOut&&e.entryPoint&&this._processInitializeOnLink(e.entryPoint,t,i,r),e.outputs))s.associatedVariableName=""}_resetDualBlocks(e,t){for(let i of(e.target===tm.VertexAndFragment&&(e.buildId=t),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._resetDualBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._resetDualBlocks(e.entryPoint,t)}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e.isFinalMerger&&this.removeOutputNode(e)}build(e=!1,t=!0,i=!1){this._vertexCompilationState||i||(i=!0),this._buildWasSuccessful=!1;let r=this.getScene().getEngine(),s=this._mode===tC.Particle;if(0===this._vertexOutputNodes.length&&!s)throw"You must define at least one vertexOutputNode";if(0===this._fragmentOutputNodes.length)throw"You must define at least one fragmentOutputNode";this._vertexCompilationState=new np,this._vertexCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._vertexCompilationState.target=tm.Vertex,this._fragmentCompilationState=new np,this._fragmentCompilationState.supportUniformBuffers=r.supportsUniformBuffers,this._fragmentCompilationState.target=tm.Fragment,this._sharedData=new n_,this._sharedData.nodeMaterial=this,this._sharedData.fragmentOutputNodes=this._fragmentOutputNodes,this._vertexCompilationState.sharedData=this._sharedData,this._fragmentCompilationState.sharedData=this._sharedData,this._sharedData.buildId=this._buildId,this._sharedData.emitComments=this._options.emitComments,this._sharedData.verbose=e,this._sharedData.scene=this.getScene(),this._sharedData.allowEmptyVertexProgram=s;let n=[],a=[];for(let e of this._vertexOutputNodes)n.push(e),this._initializeBlock(e,this._vertexCompilationState,a,i);for(let e of this._fragmentOutputNodes)a.push(e),this._initializeBlock(e,this._fragmentCompilationState,n,i);for(let e of(this.optimize(),n))e.build(this._vertexCompilationState,n);for(let e of(this._fragmentCompilationState.uniforms=this._vertexCompilationState.uniforms.slice(0),this._fragmentCompilationState._uniformDeclaration=this._vertexCompilationState._uniformDeclaration,this._fragmentCompilationState._constantDeclaration=this._vertexCompilationState._constantDeclaration,this._fragmentCompilationState._vertexState=this._vertexCompilationState,a))this._resetDualBlocks(e,this._buildId-1);for(let e of a)e.build(this._fragmentCompilationState,a);for(let i of(this._vertexCompilationState.finalize(this._vertexCompilationState),this._fragmentCompilationState.finalize(this._fragmentCompilationState),t&&(this._buildId=ac._BuildIdGenerator++),this._sharedData.emitErrors(),e&&(rb.Y.Log("Vertex shader:"),rb.Y.Log(this._vertexCompilationState.compilationString),rb.Y.Log("Fragment shader:"),rb.Y.Log(this._fragmentCompilationState.compilationString)),this._buildWasSuccessful=!0,this.onBuildObservable.notifyObservers(this),this.getScene().meshes))if(i.subMeshes)for(let e of i.subMeshes){if(e.getMaterial()!==this||!e.materialDefines)continue;let t=e.materialDefines;t.markAllAsDirty(),t.reset()}this.prePassTextureInputs.length&&this.getScene().enablePrePassRenderer();let o=this.getScene().prePassRenderer;o&&o.markAsDirty()}optimize(){for(let e of this._optimizers)e.optimize(this._vertexOutputNodes,this._fragmentOutputNodes)}_prepareDefinesForAttributes(e,t){let i=t.NORMAL,r=t.TANGENT,s=t.VERTEXCOLOR_NME;t.NORMAL=e.isVerticesDataPresent(sm.o.NormalKind),t.TANGENT=e.isVerticesDataPresent(sm.o.TangentKind);let n=e.useVertexColors&&e.isVerticesDataPresent(sm.o.ColorKind);t.VERTEXCOLOR_NME=n;let a=!1;for(let i=1;i<=6;++i){let r=t["UV"+i];t["UV"+i]=e.isVerticesDataPresent(`uv${1===i?"":i}`),a=a||t["UV"+i]!==r}let o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;nE.G.PrepareDefinesForPrePass(this.getScene(),t,!o),(i!==t.NORMAL||r!==t.TANGENT||s!==t.VERTEXCOLOR_NME||a)&&t.markAsAttributesDirty()}get isPrePassCapable(){return!0}get prePassTextureOutputs(){let e=this.getBlockByPredicate(e=>"PrePassOutputBlock"===e.getClassName()),t=[4];return!e||this.prePassTextureInputs.length||(e.viewDepth.isConnected&&t.push(5),e.viewNormal.isConnected&&t.push(6),e.worldPosition.isConnected&&t.push(1)),t}get prePassTextureInputs(){let e=this.getAllTextureBlocks().filter(e=>"PrePassTextureBlock"===e.getClassName()),t=[];for(let i of e)i.position.isConnected&&!t.includes(1)&&t.push(1),i.depth.isConnected&&!t.includes(5)&&t.push(5),i.normal.isConnected&&!t.includes(6)&&t.push(6);return t}setPrePassRenderer(e){let t=this.prePassTextureInputs.concat(this.prePassTextureOutputs);if(e&&t.length>1){let i=e.getEffectConfiguration("nodeMaterial");for(let r of(i||(i=e.addEffectConfiguration({enabled:!0,needsImageProcessing:!1,name:"nodeMaterial",texturesRequired:[]})),t))i.texturesRequired.includes(r)||i.texturesRequired.push(r);i.enabled=!0}return t.length>1}createPostProcess(e,t=1,i=1,r,s,n=0,a=5){return this.mode!==tC.PostProcess?(rb.Y.Log("Incompatible material mode"),null):this._createEffectForPostProcess(null,e,t,i,r,s,n,a)}createEffectForPostProcess(e){this._createEffectForPostProcess(e)}_createEffectForPostProcess(e,t,i=1,r=1,s,n,a=0,o=5){let l=this.name+this._buildId,h=new au,u=new sf.x(l+"PostProcess",this.getScene()),c=this._buildId;return this._processDefines(u,h),nd.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),e?e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l):e=new nz(this.name+"PostProcess",l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,i,t,r,s,n,h.toString(),a,l,{maxSimultaneousLights:this.maxSimultaneousLights},!1,o),e.nodeMaterialSource=this,e.onApplyObservable.add(t=>{c!==this._buildId&&(delete nd.Q.ShadersStore[l+"VertexShader"],delete nd.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId,h.markAllAsDirty(),c=this._buildId),this._processDefines(u,h)&&(nd.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),sk.Q.SetImmediate(()=>e.updateEffect(h.toString(),this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,{maxSimultaneousLights:this.maxSimultaneousLights},void 0,void 0,l,l))),this._checkInternals(t)}),e}createProceduralTexture(e,t){if(this.mode!==tC.ProceduralTexture)return rb.Y.Log("Incompatible material mode"),null;let i=this.name+this._buildId,r=new ao(i,e,null,t),s=new sf.x(i+"Procedural",this.getScene());s.reservedDataStore={hidden:!0};let n=new au,a=this._processDefines(s,n);nd.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString);let o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[sm.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==a?void 0:a.fallbacks,void 0);r.nodeMaterialSource=this,r._setEffect(o);let l=this._buildId;return r.onBeforeGenerationObservable.add(()=>{l!==this._buildId&&(delete nd.Q.ShadersStore[i+"VertexShader"],delete nd.Q.ShadersStore[i+"PixelShader"],i=this.name+this._buildId,n.markAllAsDirty(),l=this._buildId);let e=this._processDefines(s,n);e&&(nd.Q.RegisterShader(i,this._fragmentCompilationState._builtCompilationString,this._vertexCompilationState._builtCompilationString),sk.Q.SetImmediate(()=>{o=this.getScene().getEngine().createEffect({vertexElement:i,fragmentElement:i},[sm.o.PositionKind],this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString(),null==e?void 0:e.fallbacks,void 0),r._setEffect(o)})),this._checkInternals(o)}),r}_createEffectForParticles(e,t,i,r,s,n,a,o=""){let l=this.name+this._buildId+"_"+t;n||(n=new au),a||(a=this.getScene().getMeshByName(this.name+"Particle"))||((a=new sf.x(this.name+"Particle",this.getScene())).reservedDataStore={hidden:!0});let h=this._buildId,u=[],c=o;if(!s){let o=this._processDefines(a,n);nd.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),e.fillDefines(u,t),c=u.join("\n"),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==o?void 0:o.fallbacks,i,r,e),e.setCustomEffect(s,t)}s.onBindObservable.add(s=>{h!==this._buildId&&(delete nd.Q.ShadersStore[l+"PixelShader"],l=this.name+this._buildId+"_"+t,n.markAllAsDirty(),h=this._buildId),u.length=0,e.fillDefines(u,t);let d=u.join("\n");d!==c&&(n.markAllAsDirty(),c=d);let p=this._processDefines(a,n);if(p){nd.Q.RegisterShader(l,this._fragmentCompilationState._builtCompilationString),s=this.getScene().getEngine().createEffectForParticles(l,this._fragmentCompilationState.uniforms,this._fragmentCompilationState.samplers,n.toString()+"\n"+c,null==p?void 0:p.fallbacks,i,r,e),e.setCustomEffect(s,t),this._createEffectForParticles(e,t,i,r,s,n,a,o);return}this._checkInternals(s)})}_checkInternals(e){if(this._sharedData.animatedInputs){let e=this.getScene(),t=e.getFrameId();if(this._animationFrame!==t){for(let t of this._sharedData.animatedInputs)t.animate(e);this._animationFrame=t}}for(let t of this._sharedData.bindableBlocks)t.bind(e,this);for(let t of this._sharedData.inputBlocks)t._transmit(e,this.getScene(),this)}createEffectForParticles(e,t,i){if(this.mode!==tC.Particle){rb.Y.Log("Incompatible material mode");return}this._createEffectForParticles(e,n3.BLENDMODE_ONEONE,t,i),this._createEffectForParticles(e,n3.BLENDMODE_MULTIPLY,t,i)}createAsShadowDepthWrapper(e){if(this.mode!==tC.Material){rb.Y.Log("Incompatible material mode");return}e.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(this,this.getScene())}_processDefines(e,t,i=!1,r){let s=null,n=this.getScene();if(nE.G.PrepareDefinesForCamera(n,t)&&t.markAsMiscDirty(),this._sharedData.blocksWithDefines.forEach(r=>{r.initializeDefines(e,this,t,i)}),this._sharedData.blocksWithDefines.forEach(s=>{s.prepareDefines(e,this,t,i,r)}),t.isDirty){let i=t._areLightsDisposed;t.markAsProcessed(),this._vertexCompilationState.compilationString=this._vertexCompilationState._builtCompilationString,this._fragmentCompilationState.compilationString=this._fragmentCompilationState._builtCompilationString,this._sharedData.repeatableContentBlocks.forEach(i=>{i.replaceRepeatableContent(this._vertexCompilationState,this._fragmentCompilationState,e,t)});let r=[];this._sharedData.dynamicUniformBlocks.forEach(e=>{e.updateUniformsAndSamples(this._vertexCompilationState,this,t,r)});let n=this._vertexCompilationState.uniforms;this._fragmentCompilationState.uniforms.forEach(e=>{-1===n.indexOf(e)&&n.push(e)});let a=this._vertexCompilationState.samplers;this._fragmentCompilationState.samplers.forEach(e=>{-1===a.indexOf(e)&&a.push(e)});let o=new nF;this._sharedData.blocksWithFallbacks.forEach(t=>{t.provideFallbacks(e,o)}),s={lightDisposed:i,uniformBuffers:r,mergedUniforms:n,mergedSamplers:a,fallbacks:o}}return s}isReadyForSubMesh(e,t,i=!1){if(!this._buildWasSuccessful)return!1;let r=this.getScene();if(this._sharedData.animatedInputs){let e=r.getFrameId();if(this._animationFrame!==e){for(let e of this._sharedData.animatedInputs)e.animate(r);this._animationFrame=e}}if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new au);let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(this._prepareDefinesForAttributes(e,s),this._sharedData.blockingBlocks.some(t=>!t.isReady(e,this,s,i)))return!1;let a=this._processDefines(e,s,i,t);if(a){let e=t.effect,i=s.toString(),o=n.createEffect({vertex:"nodeMaterial"+this._buildId,fragment:"nodeMaterial"+this._buildId,vertexSource:this._vertexCompilationState.compilationString,fragmentSource:this._fragmentCompilationState.compilationString},{attributes:this._vertexCompilationState.attributes,uniformsNames:a.mergedUniforms,uniformBuffersNames:a.uniformBuffers,samplers:a.mergedSamplers,defines:i,fallbacks:a.fallbacks,onCompiled:this.onCompiled,onError:this.onError,multiTarget:s.PREPASS,indexParameters:{maxSimultaneousLights:this.maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS}},n);if(o){if(this._onEffectCreatedObservable&&(ah.effect=o,ah.subMesh=t,this._onEffectCreatedObservable.notifyObservers(ah)),this.allowShaderHotSwapping&&e&&!o.isReady()){if(o=e,s.markAsUnprocessed(),a.lightDisposed)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(o,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}get compiledShaders(){return`// Vertex shader +${this._vertexCompilationState.compilationString} + +// Fragment shader +${this._fragmentCompilationState.compilationString}`}bindOnlyWorldMatrix(e){let t=this.getScene();if(!this._activeEffect)return;let i=this._sharedData.hints;for(let r of(i.needWorldViewMatrix&&e.multiplyToRef(t.getViewMatrix(),this._cachedWorldViewMatrix),i.needWorldViewProjectionMatrix&&e.multiplyToRef(t.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),this._sharedData.inputBlocks))r._transmitWorld(this._activeEffect,e,this._cachedWorldViewMatrix,this._cachedWorldViewProjectionMatrix)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.effect;if(!s)return;this._activeEffect=s,this.bindOnlyWorldMatrix(e);let n=this._mustRebind(r,s,t.visibility),a=this._sharedData;if(n){for(let e of a.bindableBlocks)e.bind(s,this,t,i);for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);for(let e of a.inputBlocks)e._transmit(s,r,this)}else if(!this.isFrozen)for(let e of a.forcedBindableBlocks)e.bind(s,this,t,i);this._afterBind(t,this._activeEffect)}getActiveTextures(){let e=super.getActiveTextures();return this._sharedData&&e.push(...this._sharedData.textureBlocks.filter(e=>e.texture).map(e=>e.texture)),e}getTextureBlocks(){return this._sharedData?this._sharedData.textureBlocks:[]}getAllTextureBlocks(){let e=[];for(let t of this.attachedBlocks)ac._BlockIsTextureBlock(t)&&e.push(t);return e}hasTexture(e){if(super.hasTexture(e))return!0;if(!this._sharedData)return!1;for(let t of this._sharedData.textureBlocks)if(t.texture===e)return!0;return!1}dispose(e,t,i){if(t)for(let e of this.getTextureBlocks().filter(e=>e.texture).map(e=>e.texture))e.dispose();for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this._sharedData=null,this._vertexCompilationState=null,this._fragmentCompilationState=null,this.onBuildObservable.clear(),this._imageProcessingObserver&&(this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingObserver=null),super.dispose(e,t,i)}_createNodeEditor(e){let t=Object.assign({nodeMaterial:this},e);this.BJSNODEMATERIALEDITOR.NodeEditor.Show(t)}edit(e){return new Promise(t=>{if(this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),void 0===this.BJSNODEMATERIALEDITOR){let i=e&&e.editorURL?e.editorURL:ac.EditorURL;sg.w1.LoadBabylonScript(i,()=>{this.BJSNODEMATERIALEDITOR=this.BJSNODEMATERIALEDITOR||this._getGlobalNodeMaterialEditor(),this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeEditorConfig),t()})}clear(){this._vertexOutputNodes.length=0,this._fragmentOutputNodes.length=0,this.attachedBlocks.length=0}setToDefault(){this.clear(),this.editorData=null;let e=new nI("Position");e.setAsAttribute("position");let t=new nI("World");t.setAsSystemValue(tS.World);let i=new nx("WorldPos");e.connectTo(i),t.connectTo(i);let r=new nI("ViewProjection");r.setAsSystemValue(tS.ViewProjection);let s=new nx("WorldPos * ViewProjectionTransform");i.connectTo(s),r.connectTo(s);let n=new nT("VertexOutput");s.connectTo(n);let a=new nI("color");a.value=new rm.HE(.8,.8,.8,1);let o=new nC("FragmentOutput");a.connectTo(o),this.addOutputNode(n),this.addOutputNode(o),this._mode=tC.Material}setToDefaultPostProcess(){this.clear(),this.editorData=null;let e=new nI("Position");e.setAsAttribute("position2d");let t=new nI("Constant1");t.isConstant=!0,t.value=1;let i=new nW("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new nT("VertexOutput");i.connectTo(r);let s=new nI("Scale");s.visibleInInspector=!0,s.value=new rf.FM(1,1);let n=new nH("uv0");e.connectTo(n);let a=new nX("UV scale");n.connectTo(a),s.connectTo(a);let o=new nM("CurrentScreen");a.connectTo(o),o.texture=new sj("https://assets.babylonjs.com/nme/currentScreenPostProcess.png",this.getScene());let l=new nC("FragmentOutput");o.connectTo(l,{output:"rgba"}),this.addOutputNode(r),this.addOutputNode(l),this._mode=tC.PostProcess}setToDefaultProceduralTexture(){this.clear(),this.editorData=null;let e=new nI("Position");e.setAsAttribute("position2d");let t=new nI("Constant1");t.isConstant=!0,t.value=1;let i=new nW("Position3D");e.connectTo(i),t.connectTo(i,{input:"w"});let r=new nT("VertexOutput");i.connectTo(r);let s=new nI("Time");s.value=0,s.min=0,s.max=0,s.isBoolean=!1,s.matrixMode=0,s.animationType=tE.Time,s.isConstant=!1;let n=new nI("Color3");n.value=new rm.Wo(1,1,1),n.isConstant=!1;let a=new nC("FragmentOutput"),o=new nW("VectorMerger");o.visibleInInspector=!1;let l=new al("Cos");l.operation=tb.Cos,e.connectTo(o),s.output.connectTo(l.input),l.output.connectTo(o.z),o.xyzOut.connectTo(a.rgb),this.addOutputNode(r),this.addOutputNode(a),this._mode=tC.ProceduralTexture}setToDefaultParticle(){this.clear(),this.editorData=null;let e=new nI("uv");e.setAsAttribute("particle_uv");let t=new nD("ParticleTexture");e.connectTo(t);let i=new nI("Color");i.setAsAttribute("particle_color");let r=new nX("Texture * Color");t.connectTo(r),i.connectTo(r);let s=new nO("ParticleRampGradient");r.connectTo(s);let n=new n4("ColorSplitter");i.connectTo(n);let a=new nN("ParticleBlendMultiply");s.connectTo(a),t.connectTo(a,{output:"a"}),n.connectTo(a,{output:"a"});let o=new nC("FragmentOutput");a.connectTo(o),this.addOutputNode(o),this._mode=tC.Particle}async loadAsync(e,t=""){return ac.ParseFromFileAsync("",e,this.getScene(),t,!0,this)}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}generateCode(){let e=[],t=[],i=["const","var","let"];for(let e of this._vertexOutputNodes)this._gatherBlocks(e,t);let r=[];for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,r);let s=`var nodeMaterial = new BABYLON.NodeMaterial("${this.name||"node material"}"); +`;for(let r of(s+=`nodeMaterial.mode = BABYLON.NodeMaterialModes.${tC[this.mode]}; +`,t))r.isInput&&-1===e.indexOf(r)&&(s+=r._dumpCode(i,e));for(let t of r)t.isInput&&-1===e.indexOf(t)&&(s+=t._dumpCode(i,e));for(let t of(e=[],s+="\n// Connections\n",this._vertexOutputNodes))s+=t._dumpCodeForOutputConnections(e);for(let t of this._fragmentOutputNodes)s+=t._dumpCodeForOutputConnections(e);for(let e of(s+="\n// Output nodes\n",this._vertexOutputNodes))s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); +`;for(let e of this._fragmentOutputNodes)s+=`nodeMaterial.addOutputNode(${e._codeVariableName}); +`;return s+`nodeMaterial.build(); +`}serialize(e){let t=e?{}:rG.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];if(e)i=e;else{for(let e of(t.customType="BABYLON.NodeMaterial",t.outputNodes=[],this._vertexOutputNodes))this._gatherBlocks(e,i),t.outputNodes.push(e.uniqueId);for(let e of this._fragmentOutputNodes)this._gatherBlocks(e,i),-1===t.outputNodes.indexOf(e.uniqueId)&&t.outputNodes.push(e.uniqueId)}for(let e of(t.blocks=[],i))t.blocks.push(e.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}parseSerializedObject(e,t="",i=!1){var r;i||this.clear();let s={};for(let i of e.blocks){let e=(0,rg.q)(i.customType);if(e){let r=new e;r._deserialize(i,this.getScene(),t),s[i.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;t&&s[t].attachToEndpoint(e)}for(let t=0;tnew ac(e,this.getScene(),this.options),this);return r.id=e,r.name=e,r.parseSerializedObject(i),r._buildId=this._buildId,r.build(!1,!t),r}whenTexturesReadyAsync(){let e=[];return this.getActiveTextures().forEach(t=>{let i=t.getInternalTexture();i&&!i.isReady&&e.push(new Promise((e,t)=>{i.onLoadedObservable.addOnce(()=>{e()}),i.onErrorObservable.addOnce(e=>{t(e)})}))}),Promise.all(e)}static Parse(e,t,i=""){let r=rG.p4.Parse(()=>new ac(e.name,t),e,t,i);return r.parseSerializedObject(e,i),r.build(),r}static async ParseFromFileAsync(e,t,i,r="",s=!1,n){let a=null!=n?n:new ac(e,i),o=JSON.parse(await i._loadFileAsync(t));return a.parseSerializedObject(o,r),s||a.build(),a}static ParseFromSnippetAsync(e,t=rL.l.LastCreatedScene,i="",r,s=!1,n=!1){return"_BLANK"===e?Promise.resolve(ac.CreateDefault("blank",t)):new Promise((a,o)=>{let l=new rX.g;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let h=JSON.parse(JSON.parse(JSON.parse(l.responseText).jsonPayload).nodeMaterial);r||((r=rG.p4.Parse(()=>new ac(e,t),h,t,i)).uniqueId=t.getUniqueId()),r.parseSerializedObject(h),r.snippetId=e;try{s||r.build()}catch(e){o(e)}n?r.whenTexturesReadyAsync().then(()=>{a(r)}).catch(e=>{o(e)}):a(r)}else o("Unable to load the snippet "+e)}}),l.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),l.send()})}static CreateDefault(e,t){let i=new ac(e,t);return i.setToDefault(),i.build(),i}}function ad(e){let t;let i=e.sideOrientation||s7.x.DEFAULTSIDE,r=e.radius||1,s=void 0===e.flat||e.flat,n=0|(e.subdivisions||4),a=e.radiusX||r,o=e.radiusY||r,l=e.radiusZ||r,h=(1+Math.sqrt(5))/2,u=[-1,h,-0,1,h,0,-1,-h,0,1,-h,0,0,-1,-h,0,1,-h,0,-1,h,0,1,h,h,0,1,h,0,-1,-h,0,1,-h,0,-1],c=[0,11,5,0,5,1,0,1,7,0,7,10,12,22,23,1,5,20,5,11,4,23,22,13,22,18,6,7,1,8,14,21,4,14,4,2,16,13,6,15,6,19,3,8,9,4,21,5,13,17,23,6,13,22,19,6,18,9,8,1],d=[0,1,2,3,4,5,6,7,8,9,10,11,0,2,3,3,3,4,7,8,9,9,10,11],p=[5,1,3,1,6,4,0,0,5,3,4,2,2,2,4,0,2,0,1,1,6,0,6,2,0,4,3,3,4,4,3,1,4,2,4,4,0,2,1,1,2,2,3,3,1,3,2,4],_=138/1024,f=239/1024,m=60/1024,g=26/1024,v=-40/1024,x=20/1024,T=[0,0,0,0,1,0,0,1,1,0,0,0,1,1,0,0,1,1,1,0],S=[],E=[],C=[],b=[],y=0,A=[,,,],R=[,,,];for(t=0;t<3;t++)A[t]=rf.P.Zero(),R[t]=rf.FM.Zero();for(let e=0;e<20;e++){for(t=0;t<3;t++){let i=c[3*e+t];A[t].copyFromFloats(u[3*d[i]],u[3*d[i]+1],u[3*d[i]+2]),A[t].normalize(),R[t].copyFromFloats(p[2*i]*_+m+T[e]*v,p[2*i+1]*f+g+T[e]*x)}let i=(e,t,i,r)=>{let h;let u=rf.P.Lerp(A[0],A[2],t/n),c=rf.P.Lerp(A[1],A[2],t/n),d=n===t?A[2]:rf.P.Lerp(u,c,e/(n-t));if(d.normalize(),s){let e=rf.P.Lerp(A[0],A[2],r/n),t=rf.P.Lerp(A[1],A[2],r/n);h=rf.P.Lerp(e,t,i/(n-r))}else h=new rf.P(d.x,d.y,d.z);h.x/=a,h.y/=o,h.z/=l,h.normalize();let p=rf.FM.Lerp(R[0],R[2],t/n),_=rf.FM.Lerp(R[1],R[2],t/n),f=n===t?R[2]:rf.FM.Lerp(p,_,e/(n-t));E.push(d.x*a,d.y*o,d.z*l),C.push(h.x,h.y,h.z),b.push(f.x,sY.e.UseOpenGLOrientationForUV?1-f.y:f.y),S.push(y),y++};for(let e=0;eap(e,t,i),(x=ty||(ty={})).WRIST="wrist",x.THUMB="thumb",x.INDEX="index",x.MIDDLE="middle",x.RING="ring",x.LITTLE="little",(T=tA||(tA={})).WRIST="wrist",T.THUMB_METACARPAL="thumb-metacarpal",T.THUMB_PHALANX_PROXIMAL="thumb-phalanx-proximal",T.THUMB_PHALANX_DISTAL="thumb-phalanx-distal",T.THUMB_TIP="thumb-tip",T.INDEX_FINGER_METACARPAL="index-finger-metacarpal",T.INDEX_FINGER_PHALANX_PROXIMAL="index-finger-phalanx-proximal",T.INDEX_FINGER_PHALANX_INTERMEDIATE="index-finger-phalanx-intermediate",T.INDEX_FINGER_PHALANX_DISTAL="index-finger-phalanx-distal",T.INDEX_FINGER_TIP="index-finger-tip",T.MIDDLE_FINGER_METACARPAL="middle-finger-metacarpal",T.MIDDLE_FINGER_PHALANX_PROXIMAL="middle-finger-phalanx-proximal",T.MIDDLE_FINGER_PHALANX_INTERMEDIATE="middle-finger-phalanx-intermediate",T.MIDDLE_FINGER_PHALANX_DISTAL="middle-finger-phalanx-distal",T.MIDDLE_FINGER_TIP="middle-finger-tip",T.RING_FINGER_METACARPAL="ring-finger-metacarpal",T.RING_FINGER_PHALANX_PROXIMAL="ring-finger-phalanx-proximal",T.RING_FINGER_PHALANX_INTERMEDIATE="ring-finger-phalanx-intermediate",T.RING_FINGER_PHALANX_DISTAL="ring-finger-phalanx-distal",T.RING_FINGER_TIP="ring-finger-tip",T.PINKY_FINGER_METACARPAL="pinky-finger-metacarpal",T.PINKY_FINGER_PHALANX_PROXIMAL="pinky-finger-phalanx-proximal",T.PINKY_FINGER_PHALANX_INTERMEDIATE="pinky-finger-phalanx-intermediate",T.PINKY_FINGER_PHALANX_DISTAL="pinky-finger-phalanx-distal",T.PINKY_FINGER_TIP="pinky-finger-tip";let a_=[tA.WRIST,tA.THUMB_METACARPAL,tA.THUMB_PHALANX_PROXIMAL,tA.THUMB_PHALANX_DISTAL,tA.THUMB_TIP,tA.INDEX_FINGER_METACARPAL,tA.INDEX_FINGER_PHALANX_PROXIMAL,tA.INDEX_FINGER_PHALANX_INTERMEDIATE,tA.INDEX_FINGER_PHALANX_DISTAL,tA.INDEX_FINGER_TIP,tA.MIDDLE_FINGER_METACARPAL,tA.MIDDLE_FINGER_PHALANX_PROXIMAL,tA.MIDDLE_FINGER_PHALANX_INTERMEDIATE,tA.MIDDLE_FINGER_PHALANX_DISTAL,tA.MIDDLE_FINGER_TIP,tA.RING_FINGER_METACARPAL,tA.RING_FINGER_PHALANX_PROXIMAL,tA.RING_FINGER_PHALANX_INTERMEDIATE,tA.RING_FINGER_PHALANX_DISTAL,tA.RING_FINGER_TIP,tA.PINKY_FINGER_METACARPAL,tA.PINKY_FINGER_PHALANX_PROXIMAL,tA.PINKY_FINGER_PHALANX_INTERMEDIATE,tA.PINKY_FINGER_PHALANX_DISTAL,tA.PINKY_FINGER_TIP],af={[ty.WRIST]:[tA.WRIST],[ty.THUMB]:[tA.THUMB_METACARPAL,tA.THUMB_PHALANX_PROXIMAL,tA.THUMB_PHALANX_DISTAL,tA.THUMB_TIP],[ty.INDEX]:[tA.INDEX_FINGER_METACARPAL,tA.INDEX_FINGER_PHALANX_PROXIMAL,tA.INDEX_FINGER_PHALANX_INTERMEDIATE,tA.INDEX_FINGER_PHALANX_DISTAL,tA.INDEX_FINGER_TIP],[ty.MIDDLE]:[tA.MIDDLE_FINGER_METACARPAL,tA.MIDDLE_FINGER_PHALANX_PROXIMAL,tA.MIDDLE_FINGER_PHALANX_INTERMEDIATE,tA.MIDDLE_FINGER_PHALANX_DISTAL,tA.MIDDLE_FINGER_TIP],[ty.RING]:[tA.RING_FINGER_METACARPAL,tA.RING_FINGER_PHALANX_PROXIMAL,tA.RING_FINGER_PHALANX_INTERMEDIATE,tA.RING_FINGER_PHALANX_DISTAL,tA.RING_FINGER_TIP],[ty.LITTLE]:[tA.PINKY_FINGER_METACARPAL,tA.PINKY_FINGER_PHALANX_PROXIMAL,tA.PINKY_FINGER_PHALANX_INTERMEDIATE,tA.PINKY_FINGER_PHALANX_DISTAL,tA.PINKY_FINGER_TIP]};class am{get handMesh(){return this._handMesh}getHandPartMeshes(e){return af[e].map(e=>this._jointMeshes[a_.indexOf(e)])}getJointMesh(e){return this._jointMeshes[a_.indexOf(e)]}constructor(e,t,i,r,s=!1,n=!1,a=1){this.xrController=e,this._jointMeshes=t,this._handMesh=i,this.rigMapping=r,this._leftHandedMeshes=s,this._jointsInvisible=n,this._jointScaleFactor=a,this._jointTransforms=Array(a_.length),this._jointTransformMatrices=new Float32Array(16*a_.length),this._tempJointMatrix=new rf.y3,this._jointRadii=new Float32Array(a_.length),this._scene=t[0].getScene();for(let e=0;e{e.rootMesh&&e.rootMesh.setEnabled(!1)})),this.xrController.onMotionControllerInitObservable.add(e=>{e.onModelLoadedObservable.add(e=>{e.rootMesh&&e.rootMesh.setEnabled(!1)}),e.rootMesh&&e.rootMesh.setEnabled(!1)})}setHandMesh(e,t){if(this._handMesh=e,e.alwaysSelectAsActiveMesh=!0,e.getChildMeshes().forEach(e=>e.alwaysSelectAsActiveMesh=!0),this._handMesh.skeleton){let e=this._handMesh.skeleton;a_.forEach((i,r)=>{let s=e.getBoneIndexByName(t?t[i]:i);-1!==s&&e.bones[s].linkTransformNode(this._jointTransforms[r])})}}updateFromXRFrame(e,t){let i=this.xrController.inputSource.hand;if(!i)return;let r=a_.map(e=>i[e]||i.get(e)),s=!1;if(e.fillPoses&&e.fillJointRadii)s=e.fillPoses(r,t,this._jointTransformMatrices)&&e.fillJointRadii(r,this._jointRadii);else if(e.getJointPose){s=!0;for(let i=0;i{let i=this._jointTransforms[t];rf.y3.FromArrayToRef(this._jointTransformMatrices,16*t,this._tempJointMatrix),this._tempJointMatrix.decompose(void 0,i.rotationQuaternion,i.position);let r=this._jointRadii[t]*this._jointScaleFactor,s=this._jointMeshes[t];s.isVisible=!this._handMesh&&!this._jointsInvisible,s.position.copyFrom(i.position),s.rotationQuaternion.copyFrom(i.rotationQuaternion),s.scaling.setAll(r),!this._scene.useRightHandedSystem&&(s.position.z*=-1,s.rotationQuaternion.z*=-1,s.rotationQuaternion.w*=-1,this._leftHandedMeshes&&this._handMesh&&(i.position.z*=-1,i.rotationQuaternion.z*=-1,i.rotationQuaternion.w*=-1))}),this._handMesh&&(this._handMesh.isVisible=!0))}dispose(){this._handMesh&&(this._handMesh.isVisible=!1)}}class ag extends ns{static _GenerateTrackedJointMeshes(e){let t={};return["left","right"].map(i=>{var r,s,n,a,o;let l=[],h=(null===(r=e.jointMeshes)||void 0===r?void 0:r.sourceMesh)||ap("jointParent",ag._ICOSPHERE_PARAMS);h.isVisible=!!(null===(s=e.jointMeshes)||void 0===s?void 0:s.keepOriginalVisible);for(let t=0;t{var r,s,n,a,o;let l={};(null===(s=null===(r=ag._RightHandGLB)||void 0===r?void 0:r.meshes[1])||void 0===s?void 0:s.isDisposed())&&(ag._RightHandGLB=null),(null===(a=null===(n=ag._LeftHandGLB)||void 0===n?void 0:n.meshes[1])||void 0===a?void 0:a.isDisposed())&&(ag._LeftHandGLB=null);let h=!!(ag._RightHandGLB&&ag._LeftHandGLB),u=await Promise.all([ag._RightHandGLB||nh.ImportMeshAsync("",ag.DEFAULT_HAND_MODEL_BASE_URL,ag.DEFAULT_HAND_MODEL_RIGHT_FILENAME,e),ag._LeftHandGLB||nh.ImportMeshAsync("",ag.DEFAULT_HAND_MODEL_BASE_URL,ag.DEFAULT_HAND_MODEL_LEFT_FILENAME,e)]);ag._RightHandGLB=u[0],ag._LeftHandGLB=u[1];let c=new ac("handShader",e,{emitComments:!1});await c.loadAsync(ag.DEFAULT_HAND_MODEL_SHADER_URL),c.needDepthPrePass=!0,c.transparencyMode=nu.F.MATERIAL_ALPHABLEND,c.alphaMode=2,c.build(!1);let d=Object.assign({base:rm.Wo.FromInts(116,63,203),fresnel:rm.Wo.FromInts(149,102,229),fingerColor:rm.Wo.FromInts(177,130,255),tipFresnel:rm.Wo.FromInts(220,200,255)},null===(o=null==t?void 0:t.handMeshes)||void 0===o?void 0:o.customColors),p={base:c.getBlockByName("baseColor"),fresnel:c.getBlockByName("fresnelColor"),fingerColor:c.getBlockByName("fingerColor"),tipFresnel:c.getBlockByName("tipFresnelColor")};p.base.value=d.base,p.fresnel.value=d.fresnel,p.fingerColor.value=d.fingerColor,p.tipFresnel.value=d.tipFresnel,["left","right"].forEach(t=>{let i="left"==t?ag._LeftHandGLB:ag._RightHandGLB;if(!i)throw Error("Could not load hand model");let r=i.meshes[1];r._internalAbstractMeshDataInfo._computeBonesUsingShaders=!0,r.material=c.clone(`${t}HandShaderClone`,!0),r.isVisible=!1,l[t]=r,h||e.useRightHandedSystem||i.meshes[1].rotate(r5.RD.Y,Math.PI)}),c.dispose(),i({left:l.left,right:l.right})})}static _GenerateDefaultHandMeshRigMapping(e){let t="right"==e?"R":"L";return{[tA.WRIST]:`wrist_${t}`,[tA.THUMB_METACARPAL]:`thumb_metacarpal_${t}`,[tA.THUMB_PHALANX_PROXIMAL]:`thumb_proxPhalanx_${t}`,[tA.THUMB_PHALANX_DISTAL]:`thumb_distPhalanx_${t}`,[tA.THUMB_TIP]:`thumb_tip_${t}`,[tA.INDEX_FINGER_METACARPAL]:`index_metacarpal_${t}`,[tA.INDEX_FINGER_PHALANX_PROXIMAL]:`index_proxPhalanx_${t}`,[tA.INDEX_FINGER_PHALANX_INTERMEDIATE]:`index_intPhalanx_${t}`,[tA.INDEX_FINGER_PHALANX_DISTAL]:`index_distPhalanx_${t}`,[tA.INDEX_FINGER_TIP]:`index_tip_${t}`,[tA.MIDDLE_FINGER_METACARPAL]:`middle_metacarpal_${t}`,[tA.MIDDLE_FINGER_PHALANX_PROXIMAL]:`middle_proxPhalanx_${t}`,[tA.MIDDLE_FINGER_PHALANX_INTERMEDIATE]:`middle_intPhalanx_${t}`,[tA.MIDDLE_FINGER_PHALANX_DISTAL]:`middle_distPhalanx_${t}`,[tA.MIDDLE_FINGER_TIP]:`middle_tip_${t}`,[tA.RING_FINGER_METACARPAL]:`ring_metacarpal_${t}`,[tA.RING_FINGER_PHALANX_PROXIMAL]:`ring_proxPhalanx_${t}`,[tA.RING_FINGER_PHALANX_INTERMEDIATE]:`ring_intPhalanx_${t}`,[tA.RING_FINGER_PHALANX_DISTAL]:`ring_distPhalanx_${t}`,[tA.RING_FINGER_TIP]:`ring_tip_${t}`,[tA.PINKY_FINGER_METACARPAL]:`little_metacarpal_${t}`,[tA.PINKY_FINGER_PHALANX_PROXIMAL]:`little_proxPhalanx_${t}`,[tA.PINKY_FINGER_PHALANX_INTERMEDIATE]:`little_intPhalanx_${t}`,[tA.PINKY_FINGER_PHALANX_DISTAL]:`little_distPhalanx_${t}`,[tA.PINKY_FINGER_TIP]:`little_tip_${t}`}}isCompatible(){return"undefined"!=typeof XRHand}getHandByControllerId(e){return this._attachedHands[e]}getHandByHandedness(e){return"none"==e?null:this._trackingHands[e]}constructor(e,t){super(e),this.options=t,this._attachedHands={},this._trackingHands={left:null,right:null},this._handResources={jointMeshes:null,handMeshes:null,rigMappings:null},this.onHandAddedObservable=new r_.y$,this.onHandRemovedObservable=new r_.y$,this._attachHand=e=>{var t,i,r;if(!e.inputSource.hand||"none"==e.inputSource.handedness||!this._handResources.jointMeshes)return;let s=e.inputSource.handedness,n=new am(e,this._handResources.jointMeshes[s],this._handResources.handMeshes&&this._handResources.handMeshes[s],this._handResources.rigMappings&&this._handResources.rigMappings[s],null===(t=this.options.handMeshes)||void 0===t?void 0:t.meshesUseLeftHandedCoordinates,null===(i=this.options.jointMeshes)||void 0===i?void 0:i.invisible,null===(r=this.options.jointMeshes)||void 0===r?void 0:r.scaleFactor);this._attachedHands[e.uniqueId]=n,this._trackingHands[s]=n,this.onHandAddedObservable.notifyObservers(n)},this._detachHand=e=>{this._detachHandById(e.uniqueId)},this.xrNativeFeatureName="hand-tracking";let i=t.jointMeshes;if(i&&(void 0!==i.disableDefaultHandMesh&&(t.handMeshes=t.handMeshes||{},t.handMeshes.disableDefaultMeshes=i.disableDefaultHandMesh),void 0!==i.handMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.customMeshes=i.handMeshes),void 0!==i.leftHandedSystemMeshes&&(t.handMeshes=t.handMeshes||{},t.handMeshes.meshesUseLeftHandedCoordinates=i.leftHandedSystemMeshes),void 0!==i.rigMapping)){t.handMeshes=t.handMeshes||{};let e={},r={};[[i.rigMapping.left,e],[i.rigMapping.right,r]].forEach(e=>{let t=e[0],i=e[1];t.forEach((e,t)=>{i[a_[t]]=e})}),t.handMeshes.customRigMappings={left:e,right:r}}}attach(){var e,t,i,r;return!!super.attach()&&(this._handResources={jointMeshes:ag._GenerateTrackedJointMeshes(this.options),handMeshes:(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||null,rigMappings:(null===(t=this.options.handMeshes)||void 0===t?void 0:t.customRigMappings)||null},(null===(i=this.options.handMeshes)||void 0===i?void 0:i.customMeshes)||(null===(r=this.options.handMeshes)||void 0===r?void 0:r.disableDefaultMeshes)||ag._GenerateDefaultHandMeshesAsync(rL.l.LastCreatedScene,this.options).then(e=>{var t,i;this._handResources.handMeshes=e,this._handResources.rigMappings={left:ag._GenerateDefaultHandMeshRigMapping("left"),right:ag._GenerateDefaultHandMeshRigMapping("right")},null===(t=this._trackingHands.left)||void 0===t||t.setHandMesh(this._handResources.handMeshes.left,this._handResources.rigMappings.left),null===(i=this._trackingHands.right)||void 0===i||i.setHandMesh(this._handResources.handMeshes.right,this._handResources.rigMappings.right)}),this.options.xrInput.controllers.forEach(this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerAddedObservable,this._attachHand),this._addNewAttachObserver(this.options.xrInput.onControllerRemovedObservable,this._detachHand),!0)}_onXRFrame(e){var t,i;null===(t=this._trackingHands.left)||void 0===t||t.updateFromXRFrame(e,this._xrSessionManager.referenceSpace),null===(i=this._trackingHands.right)||void 0===i||i.updateFromXRFrame(e,this._xrSessionManager.referenceSpace)}_detachHandById(e){var t;let i=this.getHandByControllerId(e);if(i){let r="left"==i.xrController.inputSource.handedness?"left":"right";(null===(t=this._trackingHands[r])||void 0===t?void 0:t.xrController.uniqueId)===e&&(this._trackingHands[r]=null),this.onHandRemovedObservable.notifyObservers(i),i.dispose(),delete this._attachedHands[e]}}detach(){return!!super.detach()&&(Object.keys(this._attachedHands).forEach(e=>this._detachHandById(e)),!0)}dispose(){var e;super.dispose(),this.onHandAddedObservable.clear(),this.onHandRemovedObservable.clear(),!this._handResources.handMeshes||(null===(e=this.options.handMeshes)||void 0===e?void 0:e.customMeshes)||(this._handResources.handMeshes.left.dispose(),this._handResources.handMeshes.right.dispose(),ag._RightHandGLB=null,ag._LeftHandGLB=null),this._handResources.jointMeshes&&(this._handResources.jointMeshes.left.forEach(e=>e.dispose()),this._handResources.jointMeshes.right.forEach(e=>e.dispose()))}}ag.Name=ni.HAND_TRACKING,ag.Version=1,ag.DEFAULT_HAND_MODEL_BASE_URL="https://assets.babylonjs.com/meshes/HandMeshes/",ag.DEFAULT_HAND_MODEL_RIGHT_FILENAME="r_hand_rhs.glb",ag.DEFAULT_HAND_MODEL_LEFT_FILENAME="l_hand_rhs.glb",ag.DEFAULT_HAND_MODEL_SHADER_URL="https://assets.babylonjs.com/meshes/HandMeshes/handsShader.json",ag._ICOSPHERE_PARAMS={radius:.5,flat:!1,subdivisions:2},ag._RightHandGLB=null,ag._LeftHandGLB=null,nr.AddWebXRFeature(ag.Name,(e,t)=>()=>new ag(e,t),ag.Version,!1),(S=tR||(tR={}))[S.ABOVE_FINGER_TIPS=0]="ABOVE_FINGER_TIPS",S[S.RADIAL_SIDE=1]="RADIAL_SIDE",S[S.ULNAR_SIDE=2]="ULNAR_SIDE",S[S.BELOW_WRIST=3]="BELOW_WRIST",(E=tP||(tP={}))[E.LOOK_AT_CAMERA=0]="LOOK_AT_CAMERA",E[E.HAND_ROTATION=1]="HAND_ROTATION",(C=tI||(tI={}))[C.ALWAYS_VISIBLE=0]="ALWAYS_VISIBLE",C[C.PALM_UP=1]="PALM_UP",C[C.GAZE_FOCUS=2]="GAZE_FOCUS",C[C.PALM_AND_GAZE=3]="PALM_AND_GAZE";class av{get maxAngle(){return this._maxAngle}set maxAngle(e){this._setMaxAngle(e)}constructor(e,t,i){this.targetPosition=rf.P.Zero(),this.poleTargetPosition=rf.P.Zero(),this.poleTargetLocalOffset=rf.P.Zero(),this.poleAngle=0,this.slerpAmount=1,this._bone1Quat=rf._f.Identity(),this._bone1Mat=rf.y3.Identity(),this._bone2Ang=Math.PI,this._maxAngle=Math.PI,this._rightHandedSystem=!1,this._bendAxis=rf.P.Right(),this._slerping=!1,this._adjustRoll=0,this._notEnoughInformation=!1,this._bone2=t;let r=t.getParent();if(!r){this._notEnoughInformation=!0,rb.Y.Error("BoneIKController: bone must have a parent for IK to work.");return}if(this._bone1=r,0===this._bone2.children.length&&!this._bone2.length){this._notEnoughInformation=!0,rb.Y.Error("BoneIKController: bone must not be a leaf or it should have a length for IK to work.");return}this.mesh=e,t.getSkeleton().computeAbsoluteMatrices();let s=t.getPosition();if(t.getAbsoluteMatrix().determinant()>0&&(this._rightHandedSystem=!0,this._bendAxis.x=0,this._bendAxis.y=0,this._bendAxis.z=-1,s.x>s.y&&s.x>s.z&&(this._adjustRoll=.5*Math.PI,this._bendAxis.z=1)),this._bone1.length&&this._bone2.length){let e=this._bone1.getScale(),t=this._bone2.getScale();this._bone1Length=this._bone1.length*e.y*this.mesh.scaling.y,this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y}else if(this._bone2.children[0]){e.computeWorldMatrix(!0);let t=this._bone2.children[0].getAbsolutePosition(e),i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone2Length=rf.P.Distance(t,i),this._bone1Length=rf.P.Distance(i,r)}else{e.computeWorldMatrix(!0);let t=this._bone2.getScale();this._bone2Length=this._bone2.length*t.y*this.mesh.scaling.y;let i=this._bone2.getAbsolutePosition(e),r=this._bone1.getAbsolutePosition(e);this._bone1Length=rf.P.Distance(i,r)}this._bone1.getRotationMatrixToRef(r5.T.WORLD,e,this._bone1Mat),this.maxAngle=Math.PI,i&&(i.targetMesh&&(this.targetMesh=i.targetMesh,this.targetMesh.computeWorldMatrix(!0)),i.poleTargetMesh?(this.poleTargetMesh=i.poleTargetMesh,this.poleTargetMesh.computeWorldMatrix(!0)):i.poleTargetBone?this.poleTargetBone=i.poleTargetBone:this._bone1.getParent()&&(this.poleTargetBone=this._bone1.getParent()),i.poleTargetLocalOffset&&this.poleTargetLocalOffset.copyFrom(i.poleTargetLocalOffset),i.poleAngle&&(this.poleAngle=i.poleAngle),i.bendAxis&&this._bendAxis.copyFrom(i.bendAxis),i.maxAngle&&(this.maxAngle=i.maxAngle),i.slerpAmount&&(this.slerpAmount=i.slerpAmount))}_setMaxAngle(e){e<0&&(e=0),(e>Math.PI||void 0==e)&&(e=Math.PI),this._maxAngle=e;let t=this._bone1Length,i=this._bone2Length;this._maxReach=Math.sqrt(t*t+i*i-2*t*i*Math.cos(e))}update(){if(this._notEnoughInformation)return;let e=this.targetPosition,t=this.poleTargetPosition,i=av._TmpMats[0],r=av._TmpMats[1];this.targetMesh&&e.copyFrom(this.targetMesh.getAbsolutePosition()),this.poleTargetBone?this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset,this.mesh,t):this.poleTargetMesh&&rf.P.TransformCoordinatesToRef(this.poleTargetLocalOffset,this.poleTargetMesh.getWorldMatrix(),t);let s=av._TmpVecs[0],n=av._TmpVecs[1],a=av._TmpVecs[2],o=av._TmpVecs[3],l=av._TmpVecs[4],h=av._TmpQuat;this._bone1.getAbsolutePositionToRef(this.mesh,s),t.subtractToRef(s,l),0==l.x&&0==l.y&&0==l.z?l.y=1:l.normalize(),e.subtractToRef(s,o),o.normalize(),rf.P.CrossToRef(o,l,n),n.normalize(),rf.P.CrossToRef(o,n,a),a.normalize(),rf.y3.FromXYZAxesToRef(a,o,n,i);let u=this._bone1Length,c=this._bone2Length,d=rf.P.Distance(s,e);this._maxReach>0&&(d=Math.min(this._maxReach,d));let p=(c*c+d*d-u*u)/(2*c*d),_=(d*d+u*u-c*c)/(2*d*u);p>1&&(p=1),_>1&&(_=1),p<-1&&(p=-1),_<-1&&(_=-1);let f=Math.acos(_),m=-Math.acos(p)-f;if(this._rightHandedSystem)rf.y3.RotationYawPitchRollToRef(0,0,this._adjustRoll,r),r.multiplyToRef(i,i),rf.y3.RotationAxisToRef(this._bendAxis,f,r),r.multiplyToRef(i,i);else{let e=av._TmpVecs[5];e.copyFrom(this._bendAxis),e.x*=-1,rf.y3.RotationAxisToRef(e,-f,r),r.multiplyToRef(i,i)}this.poleAngle&&(rf.y3.RotationAxisToRef(o,this.poleAngle,r),i.multiplyToRef(r,i)),this._bone1&&(this.slerpAmount<1?(this._slerping||rf._f.FromRotationMatrixToRef(this._bone1Mat,this._bone1Quat),rf._f.FromRotationMatrixToRef(i,h),rf._f.SlerpToRef(this._bone1Quat,h,this.slerpAmount,this._bone1Quat),m=this._bone2Ang*(1-this.slerpAmount)+m*this.slerpAmount,this._bone1.setRotationQuaternion(this._bone1Quat,r5.T.WORLD,this.mesh),this._slerping=!0):(this._bone1.setRotationMatrix(i,r5.T.WORLD,this.mesh),this._bone1Mat.copyFrom(i),this._slerping=!1),this._updateLinkedTransformRotation(this._bone1)),this._bone2.setAxisAngle(this._bendAxis,m,r5.T.LOCAL),this._updateLinkedTransformRotation(this._bone2),this._bone2Ang=m}_updateLinkedTransformRotation(e){e._linkedTransformNode&&(e._linkedTransformNode.rotationQuaternion||(e._linkedTransformNode.rotationQuaternion=new rf._f),e.getRotationQuaternionToRef(r5.T.LOCAL,null,e._linkedTransformNode.rotationQuaternion))}}av._TmpVecs=[rf.P.Zero(),rf.P.Zero(),rf.P.Zero(),rf.P.Zero(),rf.P.Zero(),rf.P.Zero()],av._TmpQuat=rf._f.Identity(),av._TmpMats=[rf.y3.Identity(),rf.y3.Identity()];class ax{get minYaw(){return this._minYaw}set minYaw(e){this._minYaw=e,this._minYawSin=Math.sin(e),this._minYawCos=Math.cos(e),null!=this._maxYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get maxYaw(){return this._maxYaw}set maxYaw(e){this._maxYaw=e,this._maxYawSin=Math.sin(e),this._maxYawCos=Math.cos(e),null!=this._minYaw&&(this._midYawConstraint=.5*this._getAngleDiff(this._minYaw,this._maxYaw)+this._minYaw,this._yawRange=this._maxYaw-this._minYaw)}get minPitch(){return this._minPitch}set minPitch(e){this._minPitch=e,this._minPitchTan=Math.tan(e)}get maxPitch(){return this._maxPitch}set maxPitch(e){this._maxPitch=e,this._maxPitchTan=Math.tan(e)}constructor(e,t,i,r){if(this.upAxis=rf.P.Up(),this.upAxisSpace=r5.T.LOCAL,this.adjustYaw=0,this.adjustPitch=0,this.adjustRoll=0,this.slerpAmount=1,this._boneQuat=rf._f.Identity(),this._slerping=!1,this._firstFrameSkipped=!1,this._fowardAxis=rf.P.Forward(),this.useAbsoluteValueForYaw=!1,this.mesh=e,this.bone=t,this.target=i,r){if(r.adjustYaw&&(this.adjustYaw=r.adjustYaw),r.adjustPitch&&(this.adjustPitch=r.adjustPitch),r.adjustRoll&&(this.adjustRoll=r.adjustRoll),null!=r.maxYaw?this.maxYaw=r.maxYaw:this.maxYaw=Math.PI,null!=r.minYaw?this.minYaw=r.minYaw:this.minYaw=-Math.PI,null!=r.maxPitch?this.maxPitch=r.maxPitch:this.maxPitch=Math.PI,null!=r.minPitch?this.minPitch=r.minPitch:this.minPitch=-Math.PI,null!=r.slerpAmount&&(this.slerpAmount=r.slerpAmount),null!=r.upAxis&&(this.upAxis=r.upAxis),null!=r.upAxisSpace&&(this.upAxisSpace=r.upAxisSpace),null!=r.yawAxis||null!=r.pitchAxis){let e=r5.RD.Y,t=r5.RD.X;null!=r.yawAxis&&(e=r.yawAxis.clone()).normalize(),null!=r.pitchAxis&&(t=r.pitchAxis.clone()).normalize();let i=rf.P.Cross(t,e);this._transformYawPitch=rf.y3.Identity(),rf.y3.FromXYZAxesToRef(t,e,i,this._transformYawPitch),this._transformYawPitchInv=this._transformYawPitch.clone(),this._transformYawPitch.invert()}void 0!==r.useAbsoluteValueForYaw&&(this.useAbsoluteValueForYaw=r.useAbsoluteValueForYaw)}t.getParent()||this.upAxisSpace!=r5.T.BONE||(this.upAxisSpace=r5.T.LOCAL)}update(){if(this.slerpAmount<1&&!this._firstFrameSkipped){this._firstFrameSkipped=!0;return}let e=this.bone,t=ax._TmpVecs[0];e.getAbsolutePositionToRef(this.mesh,t);let i=this.target,r=ax._TmpMats[0],s=ax._TmpMats[1],n=this.mesh,a=e.getParent(),o=ax._TmpVecs[1];o.copyFrom(this.upAxis),this.upAxisSpace==r5.T.BONE&&a?(this._transformYawPitch&&rf.P.TransformCoordinatesToRef(o,this._transformYawPitchInv,o),a.getDirectionToRef(o,this.mesh,o)):this.upAxisSpace==r5.T.LOCAL&&(n.getDirectionToRef(o,o),(1!=n.scaling.x||1!=n.scaling.y||1!=n.scaling.z)&&o.normalize());let l=!1,h=!1;if((this._maxYaw!=Math.PI||this._minYaw!=-Math.PI)&&(l=!0),(this._maxPitch!=Math.PI||this._minPitch!=-Math.PI)&&(h=!0),l||h){let e=ax._TmpMats[2],r=ax._TmpMats[3];if(this.upAxisSpace==r5.T.BONE&&1==o.y&&a)a.getRotationMatrixToRef(r5.T.WORLD,this.mesh,e);else if(this.upAxisSpace!=r5.T.LOCAL||1!=o.y||a){let t=ax._TmpVecs[2];t.copyFrom(this._fowardAxis),this._transformYawPitch&&rf.P.TransformCoordinatesToRef(t,this._transformYawPitchInv,t),a?a.getDirectionToRef(t,this.mesh,t):n.getDirectionToRef(t,t);let i=rf.P.Cross(o,t);i.normalize(),t=rf.P.Cross(i,o),rf.y3.FromXYZAxesToRef(i,o,t,e)}else e.copyFrom(n.getWorldMatrix());e.invertToRef(r);let s=null;if(h){let n=ax._TmpVecs[3];i.subtractToRef(t,n),rf.P.TransformCoordinatesToRef(n,r,n),s=Math.sqrt(n.x*n.x+n.z*n.z);let a=Math.atan2(n.y,s),o=a;a>this._maxPitch?(n.y=this._maxPitchTan*s,o=this._maxPitch):athis._maxYaw||oMath.PI?this._isAngleBetween(a,this._maxYaw,this._midYawConstraint)?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,l=this._maxYaw):this._isAngleBetween(a,this._midYawConstraint,this._minYaw)&&(n.z=this._minYawCos*s,n.x=this._minYawSin*s,l=this._minYaw):o>this._maxYaw?(n.z=this._maxYawCos*s,n.x=this._maxYawSin*s,a<0&&this.useAbsoluteValueForYaw&&(n.x*=-1),l=this._maxYaw):oMath.PI){let e=ax._TmpVecs[8];e.copyFrom(r5.RD.Z),this._transformYawPitch&&rf.P.TransformCoordinatesToRef(e,this._transformYawPitchInv,e);let t=ax._TmpMats[4];this._boneQuat.toRotationMatrix(t),this.mesh.getWorldMatrix().multiplyToRef(t,t),rf.P.TransformCoordinatesToRef(e,t,e),rf.P.TransformCoordinatesToRef(e,r,e);let i=Math.atan2(e.x,e.z);if(this._getAngleBetween(i,a)>this._getAngleBetween(i,this._midYawConstraint)){null==s&&(s=Math.sqrt(n.x*n.x+n.z*n.z));let e=this._getAngleBetween(i,this._maxYaw);l=this._getAngleBetween(i,this._minYaw)Math.PI?i-=2*Math.PI:i<-Math.PI&&(i+=2*Math.PI),i}_getAngleBetween(e,t){e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI;let i=0;return(i=e<(t=t<0?t+2*Math.PI:t)?t-e:e-t)>Math.PI&&(i=2*Math.PI-i),i}_isAngleBetween(e,t,i){if(e%=2*Math.PI,e=e<0?e+2*Math.PI:e,t%=2*Math.PI,t=t<0?t+2*Math.PI:t,i%=2*Math.PI,t<(i=i<0?i+2*Math.PI:i)){if(e>t&&ei&&e0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter(e=>!e.getParent())}getTransformMatrices(e){return this.needInitialSkinMatrix?(e._bonesTransformMatrices||this.prepare(),e._bonesTransformMatrices):((!this._transformMatrices||this._isDirty)&&this.prepare(),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(let i in this._ranges)e&&(t+=", ",e=!1),t+=i;t+="}"}return t}getBoneIndexByName(e){for(let t=0,i=this.bones.length;t-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let i=0;i0){for(let e of this.bones)if(e._linkedTransformNode){let 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(let e of this._meshesWithPoseMatrix){let t=e.getPoseMatrix(),i=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),i=!0),i){if(this._synchronizedWithMesh!==e){for(let i of(this._synchronizedWithMesh=e,this.bones))i.getParent()||(i.getBindMatrix().multiplyToRef(t,rf.jp.Matrix[1]),i._updateAbsoluteBindMatrices(rf.jp.Matrix[1]));if(this.isUsingTextureForMatrices){let t=(this.bones.length+1)*4;e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=sJ.CreateRGBATexture(e._bonesTransformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))}}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=sJ.CreateRGBATexture(this._transformMatrices,(this.bones.length+1)*4,1,this._scene,!1,!1,1,1))),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{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){let 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(){var e;let t={};t.name=this.name,t.id=this.id,this.dimensionsAtRest&&(t.dimensionsAtRest=this.dimensionsAtRest.asArray()),t.bones=[],t.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let i=0;i0&&(n.animation=r.animations[0].serialize()),t.ranges=[],this._ranges){let i=this._ranges[e];if(!i)continue;let r={};r.name=e,r.from=i.from,r.to=i.to,t.ranges.push(r)}}return t}static Parse(e,t){let i;let r=new aT(e.name,e.id,t);for(e.dimensionsAtRest&&(r.dimensionsAtRest=rf.P.FromArray(e.dimensionsAtRest)),r.needInitialSkinMatrix=e.needInitialSkinMatrix,i=0;i-1&&(n=r.bones[t.parentBoneIndex]);let a=t.rest?rf.y3.FromArray(t.rest):null,o=new r6(t.name,r,n,rf.y3.FromArray(t.matrix),a,null,s);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(rJ.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(r._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(i=0;i0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){let e=[],t=Array(this.bones.length);for(let i=0;i{e.setCurrentPoseAsRest()})}}var aS=i(9185);class aE{constructor(e,t,i=3,r){this._engine=e,this._label=r,this._engine._storageBuffers.push(this),this._create(t,i)}_create(e,t){this._bufferSize=e,this._creationFlags=t,this._buffer=this._engine.createStorageBuffer(e,t,this._label)}_rebuild(){this._create(this._bufferSize,this._creationFlags)}getBuffer(){return this._buffer}update(e,t,i){this._buffer&&this._engine.updateStorageBuffer(this._buffer,e,t,i)}read(e,t,i,r){return this._engine.readFromStorageBuffer(this._buffer,e,t,i,r)}dispose(){let e=this._engine._storageBuffers,t=e.indexOf(this);-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._releaseBuffer(this._buffer),this._buffer=null}}let aC=(()=>{let e=new Uint8Array(4);return!!((new Uint32Array(e.buffer)[0]=1)&e[0])})();Object.defineProperty(sm.o.prototype,"effectiveByteStride",{get:function(){return this._alignedBuffer&&this._alignedBuffer.byteStride||this.byteStride},enumerable:!0,configurable:!0}),Object.defineProperty(sm.o.prototype,"effectiveByteOffset",{get:function(){return this._alignedBuffer?0:this.byteOffset},enumerable:!0,configurable:!0}),Object.defineProperty(sm.o.prototype,"effectiveBuffer",{get:function(){return this._alignedBuffer&&this._alignedBuffer.getBuffer()||this._buffer.getBuffer()},enumerable:!0,configurable:!0}),sm.o.prototype._rebuild=function(){var e,t;null===(e=this._buffer)||void 0===e||e._rebuild(),null===(t=this._alignedBuffer)||void 0===t||t._rebuild()},sm.o.prototype.dispose=function(){var e;this._ownsBuffer&&this._buffer.dispose(),null===(e=this._alignedBuffer)||void 0===e||e.dispose(),this._alignedBuffer=void 0,this._isDisposed=!0},sm.o.prototype._alignBuffer=function(){var e,t;let i,r;let s=this._buffer.getData();if(!this.engine._features.forceVertexBufferStrideMultiple4Bytes||this.byteStride%4==0||!s)return;let n=sm.o.GetTypeByteLength(this.type),a=this.byteStride+3&-4,o=a/n,l=this.totalVertices,h=l*a/n;if(Array.isArray(s)){let e=new Float32Array(s);i=new DataView(e.buffer,e.byteOffset,e.byteLength)}else i=s instanceof ArrayBuffer?new DataView(s,0,s.byteLength):new DataView(s.buffer,s.byteOffset,s.byteLength);r=this.type===sm.o.BYTE?new Int8Array(h):this.type===sm.o.UNSIGNED_BYTE?new Uint8Array(h):this.type===sm.o.SHORT?new Int16Array(h):this.type===sm.o.UNSIGNED_SHORT?new Uint16Array(h):this.type===sm.o.INT?new Int32Array(h):this.type===sm.o.UNSIGNED_INT?new Uint32Array(h):new Float32Array(h);let u=this.getSize(),c=this.byteOffset;for(let e=0;e{if(t.type!==s0.kD.POINTERWHEEL)return;let i=t.event,r=i.deltaMode===ab.G.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*r*i.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*r*i.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*r*i.deltaZ/this._normalize,i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,s0.kD.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"}}(0,sx.gn)([(0,rG.qC)()],ay.prototype,"wheelPrecisionX",void 0),(0,sx.gn)([(0,rG.qC)()],ay.prototype,"wheelPrecisionY",void 0),(0,sx.gn)([(0,rG.qC)()],ay.prototype,"wheelPrecisionZ",void 0);class aA{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=sg.w1.BackCompatCameraNoPreventDefault(arguments);let t=this.camera.getEngine(),i=t.getInputElement(),r=0,s=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=>{var a,o;let l=n.event,h="touch"===l.pointerType;if(n.type!==s0.kD.POINTERMOVE&&-1===this.buttons.indexOf(l.button))return;let u=l.target;if(this._altKey=l.altKey,this._ctrlKey=l.ctrlKey,this._metaKey=l.metaKey,this._shiftKey=l.shiftKey,this._buttonsPressed=l.buttons,t.isPointerLock){let e=l.movementX,t=l.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else if(n.type!==s0.kD.POINTERDOWN&&h&&(null===(a=this._pointA)||void 0===a?void 0:a.pointerId)!==l.pointerId&&(null===(o=this._pointB)||void 0===o?void 0:o.pointerId)!==l.pointerId)return;else if(n.type===s0.kD.POINTERDOWN&&(-1===this._currentActiveButton||h)){try{null==u||u.setPointerCapture(l.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType};else{if(null!==this._pointB)return;this._pointB={x:l.clientX,y:l.clientY,pointerId:l.pointerId,type:l.pointerType}}-1!==this._currentActiveButton||h||(this._currentActiveButton=l.button),this.onButtonDown(l),!e&&(l.preventDefault(),i&&i.focus())}else if(n.type===s0.kD.POINTERDOUBLETAP)this.onDoubleTap(l.pointerType);else if(n.type===s0.kD.POINTERUP&&(this._currentActiveButton===l.button||h)){try{null==u||u.releasePointerCapture(l.pointerId)}catch(e){}h||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==l.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==l.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==r||s)&&(this.onMultiTouch(this._pointA,this._pointB,r,0,s,null),r=0,s=null),this._currentActiveButton=-1,this.onButtonUp(l),e||l.preventDefault()}else if(n.type===s0.kD.POINTERMOVE){if(e||l.preventDefault(),this._pointA&&null===this._pointB){let e=l.clientX-this._pointA.x,t=l.clientY-this._pointA.y;this.onTouch(this._pointA,e,t),this._pointA.x=l.clientX,this._pointA.y=l.clientY}else if(this._pointA&&this._pointB){let e=this._pointA.pointerId===l.pointerId?this._pointA:this._pointB;e.x=l.clientX,e.y=l.clientY;let t=this._pointA.x-this._pointB.x,i=this._pointA.y-this._pointB.y,a=t*t+i*i,o={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:l.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,r,a,s,o),s=o,r=a}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,s0.kD.POINTERDOWN|s0.kD.POINTERUP|s0.kD.POINTERMOVE|s0.kD.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,r=0,s=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),i&&i.addEventListener("contextmenu",this._contextMenuBind,!1);let n=this.camera.getScene().getEngine().getHostWindow();n&&sg.w1.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){let e=this.camera.getScene().getEngine().getHostWindow();e&&sg.w1.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){let 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,i){}onMultiTouch(e,t,i,r,s,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}(0,sx.gn)([(0,rG.qC)()],aA.prototype,"buttons",void 0);var aR={};class aP{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){let t=e.getSimpleName();if(this.attached[t]){rb.Y.Warn("camera input of type "+t+" already exists on camera");return}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(let t in this.attached){let i=this.attached[t];if(i===e){i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck();return}}}removeByType(e){for(let t in this.attached){let i=this.attached[t];i.getClassName()===e&&(i.detachControl(),i.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){let t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement)for(let t in e=!sC.V.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e,this.attached)this.attached[t].attachControl(e)}detachElement(e=!1){for(let t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){for(let e in this.checkInputs=()=>{},this.attached){let 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){let t={};for(let e in this.attached){let i=this.attached[e],r=rG.p4.Serialize(i);t[i.getClassName()]=r}e.inputsmgr=t}parse(e){let t=e.inputsmgr;if(t)for(let e in this.clear(),t){let i=aR[e];if(i){let r=t[e],s=rG.p4.Parse(()=>new i,r,null);this.add(s)}}else for(let t in this.attached){let i=aR[this.attached[t].getClassName()];if(i){let r=rG.p4.Parse(()=>new i,e,null);this.remove(this.attached[t]),this.add(r)}}}}class aI{get isConnected(){return this._isConnected}constructor(e,t,i,r=0,s=1,n=2,a=3){this.id=e,this.index=t,this.browserGamepad=i,this._leftStick={x:0,y:0},this._rightStick={x:0,y:0},this._isConnected=!0,this._invertLeftStickY=!1,this.type=aI.GAMEPAD,this._leftStickAxisX=r,this._leftStickAxisY=s,this._rightStickAxisX=n,this._rightStickAxisY=a,this.browserGamepad.axes.length>=2&&(this._leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]}),this.browserGamepad.axes.length>=4&&(this._rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}onleftstickchanged(e){this._onleftstickchanged=e}onrightstickchanged(e){this._onrightstickchanged=e}get leftStick(){return this._leftStick}set leftStick(e){this._onleftstickchanged&&(this._leftStick.x!==e.x||this._leftStick.y!==e.y)&&this._onleftstickchanged(e),this._leftStick=e}get rightStick(){return this._rightStick}set rightStick(e){this._onrightstickchanged&&(this._rightStick.x!==e.x||this._rightStick.y!==e.y)&&this._onrightstickchanged(e),this._rightStick=e}update(){this._leftStick&&(this.leftStick={x:this.browserGamepad.axes[this._leftStickAxisX],y:this.browserGamepad.axes[this._leftStickAxisY]},this._invertLeftStickY&&(this.leftStick.y*=-1)),this._rightStick&&(this.rightStick={x:this.browserGamepad.axes[this._rightStickAxisX],y:this.browserGamepad.axes[this._rightStickAxisY]})}dispose(){}}aI.GAMEPAD=0,aI.GENERIC=1,aI.XBOX=2,aI.POSE_ENABLED=3,aI.DUALSHOCK=4;class aM extends aI{onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}constructor(e,t,i){super(e,t,i),this.onButtonDownObservable=new r_.y$,this.onButtonUpObservable=new r_.y$,this.type=aI.GENERIC,this._buttons=Array(i.buttons.length)}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}update(){super.update();for(let e=0;e{e.type===aI.POSE_ENABLED||this.gamepad&&e.type!==aI.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(aI.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad){let e=this.camera,t=this.gamepad.rightStick;if(t){if(0!=t.x){let i=t.x/this.gamepadRotationSensibility;0!=i&&Math.abs(i)>.005&&(e.inertialAlphaOffset+=i)}if(0!=t.y){let i=t.y/this.gamepadRotationSensibility*this._yAxisScale;0!=i&&Math.abs(i)>.005&&(e.inertialBetaOffset+=i)}}let i=this.gamepad.leftStick;if(i&&0!=i.y){let e=i.y/this.gamepadMoveSensibility;0!=e&&Math.abs(e)>.005&&(this.camera.inertialRadiusOffset-=e)}}}getClassName(){return"ArcRotateCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,sx.gn)([(0,rG.qC)()],aD.prototype,"gamepadRotationSensibility",void 0),(0,sx.gn)([(0,rG.qC)()],aD.prototype,"gamepadMoveSensibility",void 0),aR.ArcRotateCameraGamepadInput=aD;var aO=i(7534);class aN{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=[]}attachControl(e){e=sg.w1.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=>{let i=t.event;if(!i.metaKey){if(t.type===aO.OG.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&!e&&i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysReset.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&!e&&i.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){let e=this.camera;for(let t=0;t0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage)}attachControl(e){e=sg.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==s0.kD.POINTERWHEEL)return;let i=t.event,r=0,s=i.deltaMode===ab.G.DOM_DELTA_LINE?40:1,n=-(i.deltaY*s);if(this.customComputeDeltaFromMouseWheel)r=this.customComputeDeltaFromMouseWheel(n,this,i);else if(this.wheelDeltaPercentage){if((r=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius))>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+r;for(let i=0;i<20&&Math.abs(t)>.001;i++)e-=t,t*=this.camera.inertia;e=rk.R.Clamp(e,0,Number.MAX_VALUE),r=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else r=n/(40*this.wheelPrecision);r&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(r)):this.camera.inertialRadiusOffset+=r),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,s0.kD.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;let 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(){let e=this.camera,t=e.target.subtract(e.position);this._hitPlane=sz.J.FromPositionAndNormal(e.target,t)}_getPosition(){var e;let t=this.camera,i=t.getScene(),r=i.createPickingRay(i.pointerX,i.pointerY,rf.y3.Identity(),t,!1);(0!==t.targetScreenOffset.x||0!==t.targetScreenOffset.y)&&(this._viewOffset.set(t.targetScreenOffset.x,t.targetScreenOffset.y,0),t.getViewMatrix().invertToRef(t._cameraTransformMatrix),this._globalOffset=rf.P.TransformNormal(this._viewOffset,t._cameraTransformMatrix),r.origin.addInPlace(this._globalOffset));let s=0;return this._hitPlane&&(s=null!==(e=r.intersectsPlane(this._hitPlane))&&void 0!==e?e:0),r.origin.addInPlace(r.direction.scaleInPlace(s))}_zoomToMouse(e){var t,i;let r=this.camera,s=1-r.inertia;if(r.lowerRadiusLimit){let i=null!==(t=r.lowerRadiusLimit)&&void 0!==t?t:0;r.radius-(r.inertialRadiusOffset+e)/st&&(e=(r.radius-t)*s-r.inertialRadiusOffset)}let n=e/s/r.radius,a=this._getPosition(),o=rf.jp.Vector3[6];a.subtractToRef(r.target,o),o.scaleInPlace(n),o.scaleInPlace(s),this._inertialPanning.addInPlace(o),r.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)this.camera.pinchToPanMaxDistance?(this._computePinchZoom(i,r),this._isPinching=!0):this._computeMultiTouchPanning(s,n)):this.multiTouchPanning?this._computeMultiTouchPanning(s,n):this.pinchZoom&&this._computePinchZoom(i,r))}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}}aL.MinimumRadiusForPinch=.001,(0,sx.gn)([(0,rG.qC)()],aL.prototype,"buttons",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"angularSensibilityX",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"angularSensibilityY",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"pinchPrecision",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"pinchDeltaPercentage",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"useNaturalPinchZoom",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"pinchZoom",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"panningSensibility",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"multiTouchPanning",void 0),(0,sx.gn)([(0,rG.qC)()],aL.prototype,"multiTouchPanAndZoom",void 0),aR.ArcRotateCameraPointersInput=aL;class aw extends aP{constructor(e){super(e)}addMouseWheel(){return this.add(new aF),this}addPointers(){return this.add(new aL),this}addKeyboard(){return this.add(new aN),this}}aw.prototype.addVRDeviceOrientation=function(){return this.add(new aB),this};class aB{constructor(){this.alphaCorrection=1,this.gammaCorrection=1,this._alpha=0,this._gamma=0,this._dirty=!1,this._deviceOrientationHandler=e=>this._onOrientationEvent(e)}attachControl(e){e=sg.w1.BackCompatCameraNoPreventDefault(arguments),this.camera.attachControl(e);let t=this.camera.getScene().getEngine().getHostWindow();t&&("undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e?t.addEventListener("deviceorientation",this._deviceOrientationHandler):sg.w1.Warn("Permission not granted.")}).catch(e=>{sg.w1.Error(e)}):t.addEventListener("deviceorientation",this._deviceOrientationHandler))}_onOrientationEvent(e){null!==e.alpha&&(this._alpha=(0|+e.alpha)*this.alphaCorrection),null!==e.gamma&&(this._gamma=(0|+e.gamma)*this.gammaCorrection),this._dirty=!0}checkInputs(){this._dirty&&(this._dirty=!1,this._gamma<0&&(this._gamma=180+this._gamma),this.camera.alpha=-this._alpha/180*Math.PI%Math.PI*2,this.camera.beta=this._gamma/180*Math.PI)}detachControl(){window.removeEventListener("deviceorientation",this._deviceOrientationHandler)}getClassName(){return"ArcRotateCameraVRDeviceOrientationInput"}getSimpleName(){return"VRDeviceOrientation"}}aR.ArcRotateCameraVRDeviceOrientationInput=aB;class aU{constructor(){this.keysForward=[87],this.keysBackward=[83],this.keysUp=[69],this.keysDown=[81],this.keysRight=[68],this.keysLeft=[65],this._keys=[]}attachControl(e){e=sg.w1.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=>{let i=t.event;if(t.type===aO.OG.KEYDOWN)-1===this.keysForward.indexOf(i.keyCode)&&-1===this.keysBackward.indexOf(i.keyCode)&&-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysForward.indexOf(i.keyCode)||-1!==this.keysBackward.indexOf(i.keyCode)||-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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}getClassName(){return"FlyCameraKeyboardInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}checkInputs(){if(this._onKeyboardObserver){let e=this.camera;for(let t=0;t{this._pointerInput(e)},s0.kD.POINTERDOWN|s0.kD.POINTERUP|s0.kD.POINTERMOVE),this._rollObserver=this.camera.getScene().onBeforeRenderObservable.add(()=>{this.camera.rollCorrect&&this.camera.restoreRoll(this.camera.rollCorrect)})}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver),this._observer=null,this._rollObserver=null,this._previousPosition=null,this._noPreventDefault=void 0)}getClassName(){return"FlyCameraMouseInput"}getSimpleName(){return"mouse"}_pointerInput(e){let t=e.event,i=this.camera.getEngine();if(!this.touchEnabled&&"touch"===t.pointerType||e.type!==s0.kD.POINTERMOVE&&-1===this.buttons.indexOf(t.button))return;let r=t.target;if(e.type===s0.kD.POINTERDOWN){try{null==r||r.setPointerCapture(t.pointerId)}catch(e){}this._previousPosition={x:t.clientX,y:t.clientY},this.activeButton=t.button,this._noPreventDefault||(t.preventDefault(),this._element.focus()),i.isPointerLock&&this._onMouseMove(e.event)}else if(e.type===s0.kD.POINTERUP){try{null==r||r.releasePointerCapture(t.pointerId)}catch(e){}this.activeButton=-1,this._previousPosition=null,this._noPreventDefault||t.preventDefault()}else if(e.type===s0.kD.POINTERMOVE){if(!this._previousPosition){i.isPointerLock&&this._onMouseMove(e.event);return}let r=t.clientX-this._previousPosition.x,s=t.clientY-this._previousPosition.y;this._rotateCamera(r,s),this._previousPosition={x:t.clientX,y:t.clientY},this._noPreventDefault||t.preventDefault()}}_onMouseMove(e){if(!this.camera.getEngine().isPointerLock)return;let t=e.movementX,i=e.movementY;this._rotateCamera(t,i),this._previousPosition=null,this._noPreventDefault||e.preventDefault()}_rotateCamera(e,t){let i;let r=this.camera,s=r._calculateHandednessMultiplier(),n=(e*=s)/this.angularSensibility,a=t/this.angularSensibility,o=rf._f.RotationYawPitchRoll(r.rotation.y,r.rotation.x,r.rotation.z);if(this.buttonsPitch.some(e=>e===this.activeButton)&&(i=rf._f.RotationAxis(r5.RD.X,a),o.multiplyInPlace(i)),this.buttonsYaw.some(e=>e===this.activeButton)){i=rf._f.RotationAxis(r5.RD.Y,n),o.multiplyInPlace(i);let e=r.bankedTurnLimit+r._trackRoll;if(r.bankedTurn&&-ee===this.activeButton)&&(i=rf._f.RotationAxis(r5.RD.Z,-n),r._trackRoll-=n,o.multiplyInPlace(i)),o.toEulerAnglesToRef(r.rotation)}}(0,sx.gn)([(0,rG.qC)()],aV.prototype,"buttons",void 0),(0,sx.gn)([(0,rG.qC)()],aV.prototype,"angularSensibility",void 0),aR.FlyCameraMouseInput=aV;class ak{constructor(){this.keysHeightOffsetIncr=[38],this.keysHeightOffsetDecr=[40],this.keysHeightOffsetModifierAlt=!1,this.keysHeightOffsetModifierCtrl=!1,this.keysHeightOffsetModifierShift=!1,this.keysRotationOffsetIncr=[37],this.keysRotationOffsetDecr=[39],this.keysRotationOffsetModifierAlt=!1,this.keysRotationOffsetModifierCtrl=!1,this.keysRotationOffsetModifierShift=!1,this.keysRadiusIncr=[40],this.keysRadiusDecr=[38],this.keysRadiusModifierAlt=!0,this.keysRadiusModifierCtrl=!1,this.keysRadiusModifierShift=!1,this.heightSensibility=1,this.rotationSensibility=1,this.radiusSensibility=1,this._keys=[]}attachControl(e){e=sg.w1.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=>{let i=t.event;if(!i.metaKey){if(t.type===aO.OG.KEYDOWN)this._ctrlPressed=i.ctrlKey,this._altPressed=i.altKey,this._shiftPressed=i.shiftKey,(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode))&&(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),i.preventDefault&&!e&&i.preventDefault());else if(-1!==this.keysHeightOffsetIncr.indexOf(i.keyCode)||-1!==this.keysHeightOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetIncr.indexOf(i.keyCode)||-1!==this.keysRotationOffsetDecr.indexOf(i.keyCode)||-1!==this.keysRadiusIncr.indexOf(i.keyCode)||-1!==this.keysRadiusDecr.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),i.preventDefault&&!e&&i.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(){this._onKeyboardObserver&&this._keys.forEach(e=>{-1!==this.keysHeightOffsetIncr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset+=this.heightSensibility:-1!==this.keysHeightOffsetDecr.indexOf(e)&&this._modifierHeightOffset()?this.camera.heightOffset-=this.heightSensibility:-1!==this.keysRotationOffsetIncr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset+=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRotationOffsetDecr.indexOf(e)&&this._modifierRotationOffset()?(this.camera.rotationOffset-=this.rotationSensibility,this.camera.rotationOffset%=360):-1!==this.keysRadiusIncr.indexOf(e)&&this._modifierRadius()?this.camera.radius+=this.radiusSensibility:-1!==this.keysRadiusDecr.indexOf(e)&&this._modifierRadius()&&(this.camera.radius-=this.radiusSensibility)})}getClassName(){return"FollowCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}_modifierHeightOffset(){return this.keysHeightOffsetModifierAlt===this._altPressed&&this.keysHeightOffsetModifierCtrl===this._ctrlPressed&&this.keysHeightOffsetModifierShift===this._shiftPressed}_modifierRotationOffset(){return this.keysRotationOffsetModifierAlt===this._altPressed&&this.keysRotationOffsetModifierCtrl===this._ctrlPressed&&this.keysRotationOffsetModifierShift===this._shiftPressed}_modifierRadius(){return this.keysRadiusModifierAlt===this._altPressed&&this.keysRadiusModifierCtrl===this._ctrlPressed&&this.keysRadiusModifierShift===this._shiftPressed}}(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysHeightOffsetIncr",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysHeightOffsetDecr",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysHeightOffsetModifierAlt",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysHeightOffsetModifierCtrl",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysHeightOffsetModifierShift",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRotationOffsetIncr",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRotationOffsetDecr",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRotationOffsetModifierAlt",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRotationOffsetModifierCtrl",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRotationOffsetModifierShift",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRadiusIncr",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRadiusDecr",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRadiusModifierAlt",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRadiusModifierCtrl",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"keysRadiusModifierShift",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"heightSensibility",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"rotationSensibility",void 0),(0,sx.gn)([(0,rG.qC)()],ak.prototype,"radiusSensibility",void 0),aR.FollowCameraKeyboardMoveInput=ak;class aG{constructor(){this.axisControlRadius=!0,this.axisControlHeight=!1,this.axisControlRotation=!1,this.wheelPrecision=3,this.wheelDeltaPercentage=0}attachControl(e){e=sg.w1.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==s0.kD.POINTERWHEEL)return;let i=t.event,r=0,s=Math.max(-1,Math.min(1,i.deltaY));this.wheelDeltaPercentage?(+this.axisControlRadius+ +this.axisControlHeight+ +this.axisControlRotation&&rb.Y.Warn("wheelDeltaPercentage only usable when mouse wheel controls ONE axis. Currently enabled: axisControlRadius: "+this.axisControlRadius+", axisControlHeightOffset: "+this.axisControlHeight+", axisControlRotationOffset: "+this.axisControlRotation),this.axisControlRadius?r=.01*s*this.wheelDeltaPercentage*this.camera.radius:this.axisControlHeight?r=.01*s*this.wheelDeltaPercentage*this.camera.heightOffset:this.axisControlRotation&&(r=.01*s*this.wheelDeltaPercentage*this.camera.rotationOffset)):r=s*this.wheelPrecision,r&&(this.axisControlRadius?this.camera.radius+=r:this.axisControlHeight?this.camera.heightOffset-=r:this.axisControlRotation&&(this.camera.rotationOffset-=r)),i.preventDefault&&!e&&i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,s0.kD.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}(0,sx.gn)([(0,rG.qC)()],aG.prototype,"axisControlRadius",void 0),(0,sx.gn)([(0,rG.qC)()],aG.prototype,"axisControlHeight",void 0),(0,sx.gn)([(0,rG.qC)()],aG.prototype,"axisControlRotation",void 0),(0,sx.gn)([(0,rG.qC)()],aG.prototype,"wheelPrecision",void 0),(0,sx.gn)([(0,rG.qC)()],aG.prototype,"wheelDeltaPercentage",void 0),aR.FollowCameraMouseWheelInput=aG;class az extends aA{constructor(){super(...arguments),this.angularSensibilityX=1,this.angularSensibilityY=1,this.pinchPrecision=1e4,this.pinchDeltaPercentage=0,this.axisXControlRadius=!1,this.axisXControlHeight=!1,this.axisXControlRotation=!0,this.axisYControlRadius=!1,this.axisYControlHeight=!0,this.axisYControlRotation=!1,this.axisPinchControlRadius=!0,this.axisPinchControlHeight=!1,this.axisPinchControlRotation=!1,this.warningEnable=!0,this._warningCounter=0}getClassName(){return"FollowCameraPointersInput"}onTouch(e,t,i){this._warning(),this.axisXControlRotation?this.camera.rotationOffset+=t/this.angularSensibilityX:this.axisYControlRotation&&(this.camera.rotationOffset+=i/this.angularSensibilityX),this.axisXControlHeight?this.camera.heightOffset+=t/this.angularSensibilityY:this.axisYControlHeight&&(this.camera.heightOffset+=i/this.angularSensibilityY),this.axisXControlRadius?this.camera.radius-=t/this.angularSensibilityY:this.axisYControlRadius&&(this.camera.radius-=i/this.angularSensibilityY)}onMultiTouch(e,t,i,r,s,n){if(0===i&&null===s||0===r&&null===n)return;let a=(r-i)/(this.pinchPrecision*(this.angularSensibilityX+this.angularSensibilityY)/2);this.pinchDeltaPercentage?(a*=.01*this.pinchDeltaPercentage,this.axisPinchControlRotation&&(this.camera.rotationOffset+=a*this.camera.rotationOffset),this.axisPinchControlHeight&&(this.camera.heightOffset+=a*this.camera.heightOffset),this.axisPinchControlRadius&&(this.camera.radius-=a*this.camera.radius)):(this.axisPinchControlRotation&&(this.camera.rotationOffset+=a),this.axisPinchControlHeight&&(this.camera.heightOffset+=a),this.axisPinchControlRadius&&(this.camera.radius-=a))}_warning(){if(!this.warningEnable||this._warningCounter++%100!=0)return;let e="It probably only makes sense to control ONE camera property with each pointer axis. Set 'warningEnable = false' if you are sure. Currently enabled: ";+this.axisXControlRotation+ +this.axisXControlHeight+ +this.axisXControlRadius<=1&&rb.Y.Warn(e+"axisXControlRotation: "+this.axisXControlRotation+", axisXControlHeight: "+this.axisXControlHeight+", axisXControlRadius: "+this.axisXControlRadius),+this.axisYControlRotation+ +this.axisYControlHeight+ +this.axisYControlRadius<=1&&rb.Y.Warn(e+"axisYControlRotation: "+this.axisYControlRotation+", axisYControlHeight: "+this.axisYControlHeight+", axisYControlRadius: "+this.axisYControlRadius),+this.axisPinchControlRotation+ +this.axisPinchControlHeight+ +this.axisPinchControlRadius<=1&&rb.Y.Warn(e+"axisPinchControlRotation: "+this.axisPinchControlRotation+", axisPinchControlHeight: "+this.axisPinchControlHeight+", axisPinchControlRadius: "+this.axisPinchControlRadius)}}(0,sx.gn)([(0,rG.qC)()],az.prototype,"angularSensibilityX",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"angularSensibilityY",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"pinchPrecision",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"pinchDeltaPercentage",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisXControlRadius",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisXControlHeight",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisXControlRotation",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisYControlRadius",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisYControlHeight",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisYControlRotation",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisPinchControlRadius",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisPinchControlHeight",void 0),(0,sx.gn)([(0,rG.qC)()],az.prototype,"axisPinchControlRotation",void 0),aR.FollowCameraPointersInput=az;class aW{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=[]}attachControl(e){e=sg.w1.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=>{let i=t.event;if(!i.metaKey){if(t.type===aO.OG.KEYDOWN)-1===this.keysUp.indexOf(i.keyCode)&&-1===this.keysDown.indexOf(i.keyCode)&&-1===this.keysLeft.indexOf(i.keyCode)&&-1===this.keysRight.indexOf(i.keyCode)&&-1===this.keysUpward.indexOf(i.keyCode)&&-1===this.keysDownward.indexOf(i.keyCode)&&-1===this.keysRotateLeft.indexOf(i.keyCode)&&-1===this.keysRotateRight.indexOf(i.keyCode)&&-1===this.keysRotateUp.indexOf(i.keyCode)&&-1===this.keysRotateDown.indexOf(i.keyCode)||(-1===this._keys.indexOf(i.keyCode)&&this._keys.push(i.keyCode),e||i.preventDefault());else if(-1!==this.keysUp.indexOf(i.keyCode)||-1!==this.keysDown.indexOf(i.keyCode)||-1!==this.keysLeft.indexOf(i.keyCode)||-1!==this.keysRight.indexOf(i.keyCode)||-1!==this.keysUpward.indexOf(i.keyCode)||-1!==this.keysDownward.indexOf(i.keyCode)||-1!==this.keysRotateLeft.indexOf(i.keyCode)||-1!==this.keysRotateRight.indexOf(i.keyCode)||-1!==this.keysRotateUp.indexOf(i.keyCode)||-1!==this.keysRotateDown.indexOf(i.keyCode)){let t=this._keys.indexOf(i.keyCode);t>=0&&this._keys.splice(t,1),e||i.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){let e=this.camera;for(let t=0;t{let s=r.event,n="touch"===s.pointerType;if(!this.touchEnabled&&n||r.type!==s0.kD.POINTERMOVE&&-1===this.buttons.indexOf(s.button))return;let a=s.target;if(r.type===s0.kD.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=s.pointerId;try{null==a||a.setPointerCapture(s.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=s.button),this._previousPosition={x:s.clientX,y:s.clientY},!e&&(s.preventDefault(),i&&i.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(r.event)}else if(r.type===s0.kD.POINTERUP){if(n&&this._activePointerId!==s.pointerId||!n&&this._currentActiveButton!==s.button)return;try{null==a||a.releasePointerCapture(s.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||s.preventDefault(),this._activePointerId=-1}else if(r.type===s0.kD.POINTERMOVE&&(this._activePointerId===s.pointerId||!n)){if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(r.event);else if(this._previousPosition){let t=this.camera._calculateHandednessMultiplier(),i=(s.clientX-this._previousPosition.x)*t,r=s.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=i/this.angularSensibility,this.camera.cameraRotation.x+=r/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:i,offsetY:r}),this._previousPosition={x:s.clientX,y:s.clientY},e||s.preventDefault()}}}),this._onMouseMove=i=>{if(!t.isPointerLock)return;let r=this.camera._calculateHandednessMultiplier(),s=i.movementX*r;this.camera.cameraRotation.y+=s/this.angularSensibility;let n=i.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||i.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,s0.kD.POINTERDOWN|s0.kD.POINTERUP|s0.kD.POINTERMOVE),i&&(this._contextMenuBind=e=>this.onContextMenu(e),i.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){let 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"}}(0,sx.gn)([(0,rG.qC)()],aH.prototype,"buttons",void 0),(0,sx.gn)([(0,rG.qC)()],aH.prototype,"angularSensibility",void 0),aR.FreeCameraMouseInput=aH,(b=tM||(tM={}))[b.MoveRelative=0]="MoveRelative",b[b.RotateRelative=1]="RotateRelative",b[b.MoveScene=2]="MoveScene";class aX extends ay{constructor(){super(...arguments),this._moveRelative=rf.P.Zero(),this._rotateRelative=rf.P.Zero(),this._moveScene=rf.P.Zero(),this._wheelXAction=tM.MoveRelative,this._wheelXActionCoordinate=r5.c7.X,this._wheelYAction=tM.MoveRelative,this._wheelYActionCoordinate=r5.c7.Z,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){(null!==e||this._wheelXAction===tM.MoveRelative)&&(this._wheelXAction=tM.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==tM.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){(null!==e||this._wheelYAction===tM.MoveRelative)&&(this._wheelYAction=tM.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==tM.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){(null!==e||this._wheelZAction===tM.MoveRelative)&&(this._wheelZAction=tM.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==tM.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){(null!==e||this._wheelXAction===tM.RotateRelative)&&(this._wheelXAction=tM.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==tM.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){(null!==e||this._wheelYAction===tM.RotateRelative)&&(this._wheelYAction=tM.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==tM.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){(null!==e||this._wheelZAction===tM.RotateRelative)&&(this._wheelZAction=tM.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==tM.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){(null!==e||this._wheelXAction===tM.MoveScene)&&(this._wheelXAction=tM.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==tM.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){(null!==e||this._wheelYAction===tM.MoveScene)&&(this._wheelYAction=tM.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==tM.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){(null!==e||this._wheelZAction===tM.MoveScene)&&(this._wheelZAction=tM.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==tM.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);let e=rf.y3.Zero();this.camera.getViewMatrix().invertToRef(e);let t=rf.P.Zero();rf.P.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,i){if(0===e||null===t||null===i)return;let r=null;switch(t){case tM.MoveRelative:r=this._moveRelative;break;case tM.RotateRelative:r=this._rotateRelative;break;case tM.MoveScene:r=this._moveScene}switch(i){case r5.c7.X:r.set(e,0,0);break;case r5.c7.Y:r.set(0,e,0);break;case r5.c7.Z:r.set(0,0,e)}}}(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelXMoveRelative",null),(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelYMoveRelative",null),(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelZMoveRelative",null),(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelXRotateRelative",null),(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelYRotateRelative",null),(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelZRotateRelative",null),(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelXMoveScene",null),(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelYMoveScene",null),(0,sx.gn)([(0,rG.qC)()],aX.prototype,"wheelZMoveScene",null),aR.FreeCameraMouseWheelInput=aX;class aY{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=[],this._isSafari=sg.w1.IsSafari()}attachControl(e){e=sg.w1.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=i=>{let r=i.event,s="mouse"===r.pointerType||this._isSafari&&void 0===r.pointerType;if(this.allowMouse||!s){if(i.type===s0.kD.POINTERDOWN){if(e||r.preventDefault(),this._pointerPressed.push(r.pointerId),1!==this._pointerPressed.length)return;t={x:r.clientX,y:r.clientY}}else if(i.type===s0.kD.POINTERUP){e||r.preventDefault();let i=this._pointerPressed.indexOf(r.pointerId);if(-1===i||(this._pointerPressed.splice(i,1),0!=i))return;t=null,this._offsetX=null,this._offsetY=null}else if(i.type===s0.kD.POINTERMOVE){if(e||r.preventDefault(),!t||0!=this._pointerPressed.indexOf(r.pointerId))return;this._offsetX=r.clientX-t.x,this._offsetY=-(r.clientY-t.y)}}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,s0.kD.POINTERDOWN|s0.kD.POINTERUP|s0.kD.POINTERMOVE),this._onLostFocus){let 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){let 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||0===this._offsetX&&0===this._offsetY)return;let e=this.camera,t=e._calculateHandednessMultiplier();if(e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility,this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{let t=e._computeLocalCameraSpeed(),i=new rf.P(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);rf.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(rf.P.TransformCoordinates(i,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}(0,sx.gn)([(0,rG.qC)()],aY.prototype,"touchAngularSensibility",void 0),(0,sx.gn)([(0,rG.qC)()],aY.prototype,"touchMoveSensibility",void 0),aR.FreeCameraTouchInput=aY;class aj extends aP{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new aW),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new aH(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new aX,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new aY),this}clear(){super.clear(),this._mouseInput=null}}aj.prototype.addDeviceOrientation=function(e){return this._deviceOrientationInput||(this._deviceOrientationInput=new aq,e&&(this._deviceOrientationInput.smoothFactor=e),this.add(this._deviceOrientationInput)),this};class aq{static WaitForOrientationChangeAsync(e){return new Promise((t,i)=>{let r=!1,s=()=>{window.removeEventListener("deviceorientation",s),r=!0,t()};e&&setTimeout(()=>{r||(window.removeEventListener("deviceorientation",s),i("WaitForOrientationChangeAsync timed out"))},e),"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"==e?window.addEventListener("deviceorientation",s):sg.w1.Warn("Permission not granted.")}).catch(e=>{sg.w1.Error(e)}):window.addEventListener("deviceorientation",s)})}constructor(){this._screenOrientationAngle=0,this._screenQuaternion=new rf._f,this._alpha=0,this._beta=0,this._gamma=0,this.smoothFactor=0,this._onDeviceOrientationChangedObservable=new r_.y$,this._orientationChanged=()=>{this._screenOrientationAngle=void 0!==window.orientation?+window.orientation:window.screen.orientation&&window.screen.orientation.angle?window.screen.orientation.angle:0,this._screenOrientationAngle=-sg.w1.ToRadians(this._screenOrientationAngle/2),this._screenQuaternion.copyFromFloats(0,Math.sin(this._screenOrientationAngle),0,Math.cos(this._screenOrientationAngle))},this._deviceOrientation=e=>{this.smoothFactor?(this._alpha=null!==e.alpha?sg.w1.SmoothAngleChange(this._alpha,e.alpha,this.smoothFactor):0,this._beta=null!==e.beta?sg.w1.SmoothAngleChange(this._beta,e.beta,this.smoothFactor):0,this._gamma=null!==e.gamma?sg.w1.SmoothAngleChange(this._gamma,e.gamma,this.smoothFactor):0):(this._alpha=null!==e.alpha?e.alpha:0,this._beta=null!==e.beta?e.beta:0,this._gamma=null!==e.gamma?e.gamma:0),null!==e.alpha&&this._onDeviceOrientationChangedObservable.notifyObservers()},this._constantTranform=new rf._f(-Math.sqrt(.5),0,0,Math.sqrt(.5)),this._orientationChanged()}get camera(){return this._camera}set camera(e){this._camera=e,null==this._camera||this._camera.rotationQuaternion||(this._camera.rotationQuaternion=new rf._f),this._camera&&this._camera.onDisposeObservable.add(()=>{this._onDeviceOrientationChangedObservable.clear()})}attachControl(){let e=this.camera.getScene().getEngine().getHostWindow();if(e){let t=()=>{e.addEventListener("orientationchange",this._orientationChanged),e.addEventListener("deviceorientation",this._deviceOrientation),this._orientationChanged()};"undefined"!=typeof DeviceOrientationEvent&&"function"==typeof DeviceOrientationEvent.requestPermission?DeviceOrientationEvent.requestPermission().then(e=>{"granted"===e?t():sg.w1.Warn("Permission not granted.")}).catch(e=>{sg.w1.Error(e)}):t()}}detachControl(){window.removeEventListener("orientationchange",this._orientationChanged),window.removeEventListener("deviceorientation",this._deviceOrientation),this._alpha=0}checkInputs(){this._alpha&&(rf._f.RotationYawPitchRollToRef(sg.w1.ToRadians(this._alpha),sg.w1.ToRadians(this._beta),-sg.w1.ToRadians(this._gamma),this.camera.rotationQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion),this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform),this._camera.rotationQuaternion.z*=-1,this._camera.rotationQuaternion.w*=-1)}getClassName(){return"FreeCameraDeviceOrientationInput"}getSimpleName(){return"deviceOrientation"}}aR.FreeCameraDeviceOrientationInput=aq;class aK{constructor(){this.gamepadAngularSensibility=200,this.gamepadMoveSensibility=40,this.deadzoneDelta=.1,this._yAxisScale=1,this._cameraTransform=rf.y3.Identity(),this._deltaTransform=rf.P.Zero(),this._vector3=rf.P.Zero(),this._vector2=rf.FM.Zero()}get invertYAxis(){return 1!==this._yAxisScale}set invertYAxis(e){this._yAxisScale=e?-1:1}attachControl(){let e=this.camera.getScene().gamepadManager;this._onGamepadConnectedObserver=e.onGamepadConnectedObservable.add(e=>{e.type===aI.POSE_ENABLED||this.gamepad&&e.type!==aI.XBOX||(this.gamepad=e)}),this._onGamepadDisconnectedObserver=e.onGamepadDisconnectedObservable.add(e=>{this.gamepad===e&&(this.gamepad=null)}),this.gamepad=e.getGamepadByType(aI.XBOX),!this.gamepad&&e.gamepads.length&&(this.gamepad=e.gamepads[0])}detachControl(){this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver),this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver),this.gamepad=null}checkInputs(){if(this.gamepad&&this.gamepad.leftStick){let e=this.camera,t=this.gamepad.leftStick;0!==this.gamepadMoveSensibility&&(t.x=Math.abs(t.x)>this.deadzoneDelta?t.x/this.gamepadMoveSensibility:0,t.y=Math.abs(t.y)>this.deadzoneDelta?t.y/this.gamepadMoveSensibility:0);let i=this.gamepad.rightStick;i&&0!==this.gamepadAngularSensibility?(i.x=Math.abs(i.x)>this.deadzoneDelta?i.x/this.gamepadAngularSensibility:0,i.y=(Math.abs(i.y)>this.deadzoneDelta?i.y/this.gamepadAngularSensibility:0)*this._yAxisScale):i={x:0,y:0},e.rotationQuaternion?e.rotationQuaternion.toRotationMatrix(this._cameraTransform):rf.y3.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,this._cameraTransform);let r=50*e._computeLocalCameraSpeed();this._vector3.copyFromFloats(t.x*r,0,-t.y*r),rf.P.TransformCoordinatesToRef(this._vector3,this._cameraTransform,this._deltaTransform),e.cameraDirection.addInPlace(this._deltaTransform),this._vector2.copyFromFloats(i.y,i.x),e.cameraRotation.addInPlace(this._vector2)}}getClassName(){return"FreeCameraGamepadInput"}getSimpleName(){return"gamepad"}}(0,sx.gn)([(0,rG.qC)()],aK.prototype,"gamepadAngularSensibility",void 0),(0,sx.gn)([(0,rG.qC)()],aK.prototype,"gamepadMoveSensibility",void 0),aR.FreeCameraGamepadInput=aK;var a$=i(1186);(y=tD||(tD={}))[y.X=0]="X",y[y.Y=1]="Y",y[y.Z=2]="Z";class aQ{static _GetDefaultOptions(){return{puckSize:40,containerSize:60,color:"cyan",puckImage:void 0,containerImage:void 0,position:void 0,alwaysVisible:!1,limitToContainer:!1}}constructor(e,t){this._released=!1;let i=Object.assign(Object.assign({},aQ._GetDefaultOptions()),t);if(e?this._leftJoystick=!0:this._leftJoystick=!1,aQ._GlobalJoystickIndex++,this._axisTargetedByLeftAndRight=tD.X,this._axisTargetedByUpAndDown=tD.Y,this.reverseLeftRight=!1,this.reverseUpDown=!1,this._touches=new a$.x,this.deltaPosition=rf.P.Zero(),this._joystickSensibility=25,this._inversedSensibility=1/(this._joystickSensibility/1e3),this._onResize=()=>{aQ._VJCanvasWidth=window.innerWidth,aQ._VJCanvasHeight=window.innerHeight,aQ.Canvas&&(aQ.Canvas.width=aQ._VJCanvasWidth,aQ.Canvas.height=aQ._VJCanvasHeight),aQ._HalfWidth=aQ._VJCanvasWidth/2},!aQ.Canvas){window.addEventListener("resize",this._onResize,!1),aQ.Canvas=document.createElement("canvas"),aQ._VJCanvasWidth=window.innerWidth,aQ._VJCanvasHeight=window.innerHeight,aQ.Canvas.width=window.innerWidth,aQ.Canvas.height=window.innerHeight,aQ.Canvas.style.width="100%",aQ.Canvas.style.height="100%",aQ.Canvas.style.position="absolute",aQ.Canvas.style.backgroundColor="transparent",aQ.Canvas.style.top="0px",aQ.Canvas.style.left="0px",aQ.Canvas.style.zIndex="5",aQ.Canvas.style.touchAction="none",aQ.Canvas.setAttribute("touch-action","none");let e=aQ.Canvas.getContext("2d");if(!e)throw Error("Unable to create canvas for virtual joystick");aQ._VJCanvasContext=e,aQ._VJCanvasContext.strokeStyle="#ffffff",aQ._VJCanvasContext.lineWidth=2,document.body.appendChild(aQ.Canvas)}aQ._HalfWidth=aQ.Canvas.width/2,this.pressed=!1,this.limitToContainer=i.limitToContainer,this._joystickColor=i.color,this.containerSize=i.containerSize,this.puckSize=i.puckSize,i.position&&this.setPosition(i.position.x,i.position.y),i.puckImage&&this.setPuckImage(i.puckImage),i.containerImage&&this.setContainerImage(i.containerImage),i.alwaysVisible&&aQ._AlwaysVisibleSticks++,this.alwaysVisible=i.alwaysVisible,this._joystickPointerId=-1,this._joystickPointerPos=new rf.FM(0,0),this._joystickPreviousPointerPos=new rf.FM(0,0),this._joystickPointerStartPos=new rf.FM(0,0),this._deltaJoystickVector=new rf.FM(0,0),this._onPointerDownHandlerRef=e=>{this._onPointerDown(e)},this._onPointerMoveHandlerRef=e=>{this._onPointerMove(e)},this._onPointerUpHandlerRef=e=>{this._onPointerUp(e)},aQ.Canvas.addEventListener("pointerdown",this._onPointerDownHandlerRef,!1),aQ.Canvas.addEventListener("pointermove",this._onPointerMoveHandlerRef,!1),aQ.Canvas.addEventListener("pointerup",this._onPointerUpHandlerRef,!1),aQ.Canvas.addEventListener("pointerout",this._onPointerUpHandlerRef,!1),aQ.Canvas.addEventListener("contextmenu",e=>{e.preventDefault()},!1),requestAnimationFrame(()=>{this._drawVirtualJoystick()})}setJoystickSensibility(e){this._joystickSensibility=e,this._inversedSensibility=1/(this._joystickSensibility/1e3)}_onPointerDown(e){e.preventDefault(),(!0===this._leftJoystick?e.clientXaQ._HalfWidth)&&this._joystickPointerId<0?(this._joystickPointerId=e.pointerId,this._joystickPosition?(this._joystickPointerStartPos=this._joystickPosition.clone(),this._joystickPointerPos=this._joystickPosition.clone(),this._joystickPreviousPointerPos=this._joystickPosition.clone(),this._onPointerMove(e)):(this._joystickPointerStartPos.x=e.clientX,this._joystickPointerStartPos.y=e.clientY,this._joystickPointerPos=this._joystickPointerStartPos.clone(),this._joystickPreviousPointerPos=this._joystickPointerStartPos.clone()),this._deltaJoystickVector.x=0,this._deltaJoystickVector.y=0,this.pressed=!0,this._touches.add(e.pointerId.toString(),e)):aQ._GlobalJoystickIndex<2&&this._action&&(this._action(),this._touches.add(e.pointerId.toString(),{x:e.clientX,y:e.clientY,prevX:e.clientX,prevY:e.clientY}))}_onPointerMove(e){if(this._joystickPointerId==e.pointerId){if(this.limitToContainer){let t=new rf.FM(e.clientX-this._joystickPointerStartPos.x,e.clientY-this._joystickPointerStartPos.y),i=t.length();i>this.containerSize&&t.scaleInPlace(this.containerSize/i),this._joystickPointerPos.x=this._joystickPointerStartPos.x+t.x,this._joystickPointerPos.y=this._joystickPointerStartPos.y+t.y}else this._joystickPointerPos.x=e.clientX,this._joystickPointerPos.y=e.clientY;this._deltaJoystickVector=this._joystickPointerPos.clone(),this._deltaJoystickVector=this._deltaJoystickVector.subtract(this._joystickPointerStartPos),0this._containerImage=t}setPuckImage(e){let t=new Image;t.src=e,t.onload=()=>this._puckImage=t}_drawContainer(){let e=this._joystickPosition||this._joystickPointerStartPos;this._clearPreviousDraw(),this._containerImage?aQ._VJCanvasContext.drawImage(this._containerImage,e.x-this.containerSize,e.y-this.containerSize,2*this.containerSize,2*this.containerSize):(aQ._VJCanvasContext.beginPath(),aQ._VJCanvasContext.strokeStyle=this._joystickColor,aQ._VJCanvasContext.lineWidth=2,aQ._VJCanvasContext.arc(e.x,e.y,this.containerSize,0,2*Math.PI,!0),aQ._VJCanvasContext.stroke(),aQ._VJCanvasContext.closePath(),aQ._VJCanvasContext.beginPath(),aQ._VJCanvasContext.lineWidth=6,aQ._VJCanvasContext.strokeStyle=this._joystickColor,aQ._VJCanvasContext.arc(e.x,e.y,this.puckSize,0,2*Math.PI,!0),aQ._VJCanvasContext.stroke(),aQ._VJCanvasContext.closePath())}_drawPuck(){this._puckImage?aQ._VJCanvasContext.drawImage(this._puckImage,this._joystickPointerPos.x-this.puckSize,this._joystickPointerPos.y-this.puckSize,2*this.puckSize,2*this.puckSize):(aQ._VJCanvasContext.beginPath(),aQ._VJCanvasContext.strokeStyle=this._joystickColor,aQ._VJCanvasContext.lineWidth=2,aQ._VJCanvasContext.arc(this._joystickPointerPos.x,this._joystickPointerPos.y,this.puckSize,0,2*Math.PI,!0),aQ._VJCanvasContext.stroke(),aQ._VJCanvasContext.closePath())}_drawVirtualJoystick(){this._released||(this.alwaysVisible&&this._drawContainer(),this.pressed&&this._touches.forEach((e,t)=>{t.pointerId===this._joystickPointerId?(this.alwaysVisible||this._drawContainer(),this._drawPuck(),this._joystickPreviousPointerPos=this._joystickPointerPos.clone()):(aQ._VJCanvasContext.clearRect(t.prevX-44,t.prevY-44,88,88),aQ._VJCanvasContext.beginPath(),aQ._VJCanvasContext.fillStyle="white",aQ._VJCanvasContext.beginPath(),aQ._VJCanvasContext.strokeStyle="red",aQ._VJCanvasContext.lineWidth=6,aQ._VJCanvasContext.arc(t.x,t.y,40,0,2*Math.PI,!0),aQ._VJCanvasContext.stroke(),aQ._VJCanvasContext.closePath(),t.prevX=t.x,t.prevY=t.y)}),requestAnimationFrame(()=>{this._drawVirtualJoystick()}))}releaseCanvas(){aQ.Canvas&&(aQ.Canvas.removeEventListener("pointerdown",this._onPointerDownHandlerRef),aQ.Canvas.removeEventListener("pointermove",this._onPointerMoveHandlerRef),aQ.Canvas.removeEventListener("pointerup",this._onPointerUpHandlerRef),aQ.Canvas.removeEventListener("pointerout",this._onPointerUpHandlerRef),window.removeEventListener("resize",this._onResize),document.body.removeChild(aQ.Canvas),aQ.Canvas=null),this._released=!0}}aQ._GlobalJoystickIndex=0,aQ._AlwaysVisibleSticks=0,aj.prototype.addVirtualJoystick=function(){return this.add(new aZ),this};class aZ{getLeftJoystick(){return this._leftjoystick}getRightJoystick(){return this._rightjoystick}checkInputs(){if(this._leftjoystick){let e=this.camera,t=50*e._computeLocalCameraSpeed(),i=rf.y3.RotationYawPitchRoll(e.rotation.y,e.rotation.x,0),r=rf.P.TransformCoordinates(new rf.P(this._leftjoystick.deltaPosition.x*t,this._leftjoystick.deltaPosition.y*t,this._leftjoystick.deltaPosition.z*t),i);e.cameraDirection=e.cameraDirection.add(r),e.cameraRotation=e.cameraRotation.addVector3(this._rightjoystick.deltaPosition),this._leftjoystick.pressed||(this._leftjoystick.deltaPosition=this._leftjoystick.deltaPosition.scale(.9)),this._rightjoystick.pressed||(this._rightjoystick.deltaPosition=this._rightjoystick.deltaPosition.scale(.9))}}attachControl(){this._leftjoystick=new aQ(!0),this._leftjoystick.setAxisForUpDown(tD.Z),this._leftjoystick.setAxisForLeftRight(tD.X),this._leftjoystick.setJoystickSensibility(.15),this._rightjoystick=new aQ(!1),this._rightjoystick.setAxisForUpDown(tD.X),this._rightjoystick.setAxisForLeftRight(tD.Y),this._rightjoystick.reverseUpDown=!0,this._rightjoystick.setJoystickSensibility(.05),this._rightjoystick.setJoystickColor("yellow")}detachControl(){this._leftjoystick.releaseCanvas(),this._rightjoystick.releaseCanvas()}getClassName(){return"FreeCameraVirtualJoystickInput"}getSimpleName(){return"virtualJoystick"}}aR.FreeCameraVirtualJoystickInput=aZ;class aJ extends sC.V{constructor(e,t,i,r=!0){super(e,t,i,r),this._tmpUpVector=rf.P.Zero(),this._tmpTargetVector=rf.P.Zero(),this.cameraDirection=new rf.P(0,0,0),this.cameraRotation=new rf.FM(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new rf._f,this.rotation=new rf.P(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=rf.P.Zero(),this._initialFocalDistance=1,this._viewMatrix=rf.y3.Zero(),this._camMatrix=rf.y3.Zero(),this._cameraTransformMatrix=rf.y3.Zero(),this._cameraRotationMatrix=rf.y3.Zero(),this._referencePoint=new rf.P(0,0,1),this._transformedReferencePoint=rf.P.Zero(),this._deferredPositionUpdate=new rf.P,this._deferredRotationQuaternionUpdate=new rf._f,this._deferredRotationUpdate=new rf.P,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=rf.P.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();let 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){let 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 rf.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new rf.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new rf._f(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();let 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;let 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(){let 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+=r7.kn),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),rf.y3.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);let 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&&rf._f.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){this.parent.getWorldMatrix().invertToRef(rf.jp.Matrix[0]),rf.P.TransformNormalToRef(this.cameraDirection,rf.jp.Matrix[0],rf.jp.Vector3[0]),this._deferredPositionUpdate.addInPlace(rf.jp.Vector3[0]),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate);return}this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){let e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),i=this.cameraRotation.x||this.cameraRotation.y;this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),i&&(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint&&(this._deferredRotationUpdate.x>1.570796&&(this._deferredRotationUpdate.x=1.570796),this._deferredRotationUpdate.x<-1.570796&&(this._deferredRotationUpdate.x=-1.570796)),this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion&&this._deferredRotationUpdate.lengthSquared()&&(rf._f.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._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>sR.D.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&i&&this.onCollide(i))},this.inputs=new aj(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=sg.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new rf.P(0,0,0),this.cameraRotation=new rf.FM(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?rf.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=rf.P.Zero(),this._transformedDirection=rf.P.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"}}(0,sx.gn)([(0,rG.hd)()],a0.prototype,"ellipsoid",void 0),(0,sx.gn)([(0,rG.hd)()],a0.prototype,"ellipsoidOffset",void 0),(0,sx.gn)([(0,rG.qC)()],a0.prototype,"checkCollisions",void 0),(0,sx.gn)([(0,rG.qC)()],a0.prototype,"applyGravity",void 0),rW.N.AddNodeConstructor("TouchCamera",(e,t)=>()=>new a1(e,rf.P.Zero(),t));class a1 extends a0{get touchAngularSensibility(){let e=this.inputs.attached.touch;return e?e.touchAngularSensibility:0}set touchAngularSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchAngularSensibility=e)}get touchMoveSensibility(){let e=this.inputs.attached.touch;return e?e.touchMoveSensibility:0}set touchMoveSensibility(e){let t=this.inputs.attached.touch;t&&(t.touchMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addTouch(),this._setupInputs()}getClassName(){return"TouchCamera"}_setupInputs(){let e=this.inputs.attached.touch,t=this.inputs.attached.mouse;t?t.touchEnabled=!1:e.allowMouse=!0}}rW.N.AddNodeConstructor("ArcRotateCamera",(e,t)=>()=>new a2(e,0,0,1,rf.P.Zero(),t));class a2 extends aJ{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 rf.y3,this._upToYMatrix=new rf.y3,this._upVector=rf.P.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){rf.y3.RotationAlignToRef(rf.P.UpReadOnly,this._upVector,this._yToUpMatrix),rf.y3.RotationAlignToRef(this._upVector,rf.P.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){let e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){let t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){let e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){let t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){let e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){let t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){let e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){let t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){let e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){let t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){let e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){let t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){let e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){let t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){let e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){let 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 s2,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 s3,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 s1,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,i,r,s,n,a=!0){super(e,rf.P.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=rf.P.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=rf.FM.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this._viewMatrix=new rf.y3,this.panningAxis=new rf.P(1,1,0),this._transformedDirection=new rf.P,this.mapPanning=!1,this.onMeshTargetChangedObservable=new r_.y$,this.checkCollisions=!1,this.collisionRadius=new rf.P(.5,.5,.5),this._previousPosition=rf.P.Zero(),this._collisionVelocity=rf.P.Zero(),this._newPosition=rf.P.Zero(),this._computationVector=rf.P.Zero(),this._onCollisionPositionChange=(e,t,i=null)=>{i?(this.setPosition(t),this.onCollide&&this.onCollide(i)):this._previousPosition.copyFrom(this._position);let r=Math.cos(this.alpha),s=Math.sin(this.alpha),n=Math.cos(this.beta),a=Math.sin(this.beta);0===a&&(a=1e-4);let o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*r*a,this.radius*n,this.radius*s*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let l=this.upVector;this.allowUpsideDown&&this.beta<0&&(l=(l=l.clone()).negate()),this._computeViewMatrix(this._position,o,l),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=rf.P.Zero(),s&&this.setTarget(s),this.alpha=t,this.beta=i,this.radius=r,this.getViewMatrix(),this.inputs=new aw(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new rf.P(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=rf.FM.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){let e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}return this._getLockedTargetPosition()||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!!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,i=!0,r=2){let s=arguments;t=sg.w1.BackCompatCameraNoPreventDefault(s),this._useCtrlForPanning=i,this._panningMouseButton=r,"boolean"==typeof s[0]&&(s.length>1&&(this._useCtrlForPanning=s[1]),s.length>2&&(this._panningMouseButton=s[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(),0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){let e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier(),i=this.inertialAlphaOffset*t;this.beta<0&&(i*=-1),this.alpha+=i*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)Math.PI&&(this.beta=this.beta-2*Math.PI):this.betathis.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alphathis.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radiusthis.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)&&rf.P.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);let 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);let 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,i=!1,r=!1){var s;if(r=null!==(s=this.overrideCloneAlphaBetaRadius)&&void 0!==s?s:r,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{let t=this._getTargetPosition();if(t&&!i&&t.equals(e))return;this._targetHost=null,this._target=e,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}r||this.rebuildAnglesAndRadius()}_getViewMatrix(){let e=Math.cos(this.alpha),t=Math.sin(this.alpha),i=Math.cos(this.beta),r=Math.sin(this.beta);0===r&&(r=1e-4),0===this.radius&&(this.radius=1e-4);let s=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*r,this.radius*i,this.radius*t*r),(0!==this._upVector.x||1!==this._upVector.y||0!==this._upVector.z)&&rf.P.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),s.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){let 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&&r<0&&(e=e.negate()),this._computeViewMatrix(this._position,s,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=s,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;let i=sp.Kj.MinMax(e),r=this._calculateLowerRadiusFromModelBoundingSphere(i.min,i.max);r=Math.max(Math.min(r,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=r*this.zoomOnFactor,this.focusOn({min:i.min,max:i.max,distance:r},t)}focusOn(e,t=!1){let i,r;if(void 0===e.min){let t=e||this.getScene().meshes;i=sp.Kj.MinMax(t),r=rf.P.Distance(i.min,i.max)}else i=e,r=e.distance;this._target=sp.Kj.Center(i),t||(this.maxZ=2*r)}createRigCamera(e,t){let i=0;switch(this.cameraRigMode){case sC.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case sC.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case sC.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case sC.V.RIG_MODE_VR:i=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:i=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}let r=new a2(e,this.alpha+i,this.beta,this.radius,this._target,this.getScene());return r._cameraRigParams={},r.isRigCamera=!0,r.rigParent=this,r.upVector=this.upVector,r.mode=this.mode,r.orthoLeft=this.orthoLeft,r.orthoRight=this.orthoRight,r.orthoBottom=this.orthoBottom,r.orthoTop=this.orthoTop,r}_updateRigCameras(){let e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case sC.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case sC.V.RIG_MODE_STEREOSCOPIC_OVERUNDER:case sC.V.RIG_MODE_STEREOSCOPIC_INTERLACED:case sC.V.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,i=1){let r=rf.P.Distance(e,t),s=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),a=n*s,o=.5*r*i;return Math.max(o*Math.sqrt(1+1/(a*a)),o*Math.sqrt(1+1/(n*n)))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}(0,sx.gn)([(0,rG.qC)()],a2.prototype,"alpha",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"beta",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"radius",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"overrideCloneAlphaBetaRadius",void 0),(0,sx.gn)([(0,rG.hd)("target")],a2.prototype,"_target",void 0),(0,sx.gn)([(0,rG.RR)("targetHost")],a2.prototype,"_targetHost",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"inertialAlphaOffset",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"inertialBetaOffset",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"inertialRadiusOffset",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"lowerAlphaLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"upperAlphaLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"lowerBetaLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"upperBetaLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"lowerRadiusLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"upperRadiusLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"inertialPanningX",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"inertialPanningY",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"pinchToPanMaxDistance",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"panningDistanceLimit",void 0),(0,sx.gn)([(0,rG.hd)()],a2.prototype,"panningOriginTarget",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"panningInertia",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"zoomToMouseLocation",null),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"zoomOnFactor",void 0),(0,sx.gn)([(0,rG.QC)()],a2.prototype,"targetScreenOffset",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"allowUpsideDown",void 0),(0,sx.gn)([(0,rG.qC)()],a2.prototype,"useInputToRestoreState",void 0),rW.N.AddNodeConstructor("DeviceOrientationCamera",(e,t)=>()=>new a3(e,rf.P.Zero(),t));class a3 extends a0{constructor(e,t,i){super(e,t,i),this._tmpDragQuaternion=new rf._f,this._disablePointerInputWhenUsingDeviceOrientation=!0,this._dragFactor=0,this._quaternionCache=new rf._f,this.inputs.addDeviceOrientation(),this.inputs._deviceOrientationInput&&this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(()=>{this._disablePointerInputWhenUsingDeviceOrientation&&this.inputs._mouseInput&&(this.inputs._mouseInput._allowCameraRotation=!1,this.inputs._mouseInput.onPointerMovedObservable.add(e=>{0!=this._dragFactor&&(this._initialQuaternion||(this._initialQuaternion=new rf._f),rf._f.FromEulerAnglesToRef(0,e.offsetX*this._dragFactor,0,this._tmpDragQuaternion),this._initialQuaternion.multiplyToRef(this._tmpDragQuaternion,this._initialQuaternion))}))})}get disablePointerInputWhenUsingDeviceOrientation(){return this._disablePointerInputWhenUsingDeviceOrientation}set disablePointerInputWhenUsingDeviceOrientation(e){this._disablePointerInputWhenUsingDeviceOrientation=e}enableHorizontalDragging(e=1/300){this._dragFactor=e}getClassName(){return"DeviceOrientationCamera"}_checkInputs(){super._checkInputs(),this._quaternionCache.copyFrom(this.rotationQuaternion),this._initialQuaternion&&this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}resetToCurrentRotation(e=r5.RD.Y){this.rotationQuaternion&&(this._initialQuaternion||(this._initialQuaternion=new rf._f),this._initialQuaternion.copyFrom(this._quaternionCache||this.rotationQuaternion),["x","y","z"].forEach(t=>{e[t]?this._initialQuaternion[t]*=-1:this._initialQuaternion[t]=0}),this._initialQuaternion.normalize(),this._initialQuaternion.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion))}}class a4 extends aP{constructor(e){super(e)}addKeyboard(){return this.add(new aU),this}addMouse(){return this.add(new aV),this}}class a5 extends aJ{get angularSensibility(){let e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){let t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysForward(){let e=this.inputs.attached.keyboard;return e?e.keysForward:[]}set keysForward(e){let t=this.inputs.attached.keyboard;t&&(t.keysForward=e)}get keysBackward(){let e=this.inputs.attached.keyboard;return e?e.keysBackward:[]}set keysBackward(e){let t=this.inputs.attached.keyboard;t&&(t.keysBackward=e)}get keysUp(){let e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){let t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){let e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){let t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){let e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){let t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){let e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){let t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}constructor(e,t,i,r=!0){super(e,t,i,r),this.ellipsoid=new rf.P(1,1,1),this.ellipsoidOffset=new rf.P(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this.cameraDirection=rf.P.Zero(),this._trackRoll=0,this.rollCorrect=100,this.bankedTurn=!1,this.bankedTurnLimit=Math.PI/2,this.bankedTurnMultiplier=1,this._needMoveForGravity=!1,this._oldPosition=rf.P.Zero(),this._diffPosition=rf.P.Zero(),this._newPosition=rf.P.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,i=null)=>{(e=>{this._newPosition.copyFrom(e),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>sR.D.CollisionsEpsilon&&(this.position.addInPlace(this._diffPosition),this.onCollide&&i&&this.onCollide(i))})(t)},this.inputs=new a4(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=sg.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new rf.P(0,0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){(this.parent?rf.P.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position).subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);let t=this.getScene().collisionCoordinator;this._collider||(this._collider=t.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),t.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=rf.P.Zero(),this._transformedDirection=rf.P.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()}restoreRoll(e){let t=this._trackRoll,i=t-this.rotation.z;Math.abs(i)>=.001&&(this.rotation.z+=i/e,.001>=Math.abs(t-this.rotation.z)&&(this.rotation.z=t))}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FlyCamera"}}(0,sx.gn)([(0,rG.hd)()],a5.prototype,"ellipsoid",void 0),(0,sx.gn)([(0,rG.hd)()],a5.prototype,"ellipsoidOffset",void 0),(0,sx.gn)([(0,rG.qC)()],a5.prototype,"checkCollisions",void 0),(0,sx.gn)([(0,rG.qC)()],a5.prototype,"applyGravity",void 0);class a6 extends aP{constructor(e){super(e)}addKeyboard(){return this.add(new ak),this}addMouseWheel(){return this.add(new aG),this}addPointers(){return this.add(new az),this}addVRDeviceOrientation(){return rb.Y.Warn("DeviceOrientation support not yet implemented for FollowCamera."),this}}rW.N.AddNodeConstructor("FollowCamera",(e,t)=>()=>new a8(e,rf.P.Zero(),t)),rW.N.AddNodeConstructor("ArcFollowCamera",(e,t)=>()=>new a7(e,0,0,1,null,t));class a8 extends aJ{constructor(e,t,i,r=null){super(e,t,i),this.radius=12,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.rotationOffset=0,this.lowerRotationOffsetLimit=null,this.upperRotationOffsetLimit=null,this.heightOffset=4,this.lowerHeightOffsetLimit=null,this.upperHeightOffsetLimit=null,this.cameraAcceleration=.05,this.maxCameraSpeed=20,this.lockedTarget=r,this.inputs=new a6(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_follow(e){if(!e)return;let t=rf.jp.Matrix[0];e.absoluteRotationQuaternion.toRotationMatrix(t);let i=Math.atan2(t.m[8],t.m[10]),r=sg.w1.ToRadians(this.rotationOffset)+i,s=e.getAbsolutePosition(),n=s.x+Math.sin(r)*this.radius,a=s.z+Math.cos(r)*this.radius,o=n-this.position.x,l=s.y+this.heightOffset-this.position.y,h=a-this.position.z,u=o*this.cameraAcceleration*2,c=l*this.cameraAcceleration,d=h*this.cameraAcceleration*2;(u>this.maxCameraSpeed||u<-this.maxCameraSpeed)&&(u=u<1?-this.maxCameraSpeed:this.maxCameraSpeed),(c>this.maxCameraSpeed||c<-this.maxCameraSpeed)&&(c=c<1?-this.maxCameraSpeed:this.maxCameraSpeed),(d>this.maxCameraSpeed||d<-this.maxCameraSpeed)&&(d=d<1?-this.maxCameraSpeed:this.maxCameraSpeed),this.position=new rf.P(this.position.x+u,this.position.y+c,this.position.z+d),this.setTarget(s)}attachControl(e,t){t=sg.w1.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t),this._reset=()=>{}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){this.inputs.checkInputs(),this._checkLimits(),super._checkInputs(),this.lockedTarget&&this._follow(this.lockedTarget)}_checkLimits(){null!==this.lowerRadiusLimit&&this.radiusthis.upperRadiusLimit&&(this.radius=this.upperRadiusLimit),null!==this.lowerHeightOffsetLimit&&this.heightOffsetthis.upperHeightOffsetLimit&&(this.heightOffset=this.upperHeightOffsetLimit),null!==this.lowerRotationOffsetLimit&&this.rotationOffsetthis.upperRotationOffsetLimit&&(this.rotationOffset=this.upperRotationOffsetLimit)}getClassName(){return"FollowCamera"}}(0,sx.gn)([(0,rG.qC)()],a8.prototype,"radius",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"lowerRadiusLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"upperRadiusLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"rotationOffset",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"lowerRotationOffsetLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"upperRotationOffsetLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"heightOffset",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"lowerHeightOffsetLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"upperHeightOffsetLimit",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"cameraAcceleration",void 0),(0,sx.gn)([(0,rG.qC)()],a8.prototype,"maxCameraSpeed",void 0),(0,sx.gn)([(0,rG.RR)("lockedTargetId")],a8.prototype,"lockedTarget",void 0);class a7 extends aJ{constructor(e,t,i,r,s,n){super(e,rf.P.Zero(),n),this.alpha=t,this.beta=i,this.radius=r,this._cartesianCoordinates=rf.P.Zero(),this.setMeshTarget(s)}setMeshTarget(e){this._meshTarget=e,this._follow()}_follow(){if(!this._meshTarget)return;this._cartesianCoordinates.x=this.radius*Math.cos(this.alpha)*Math.cos(this.beta),this._cartesianCoordinates.y=this.radius*Math.sin(this.beta),this._cartesianCoordinates.z=this.radius*Math.sin(this.alpha)*Math.cos(this.beta);let e=this._meshTarget.getAbsolutePosition();this.position=e.add(this._cartesianCoordinates),this.setTarget(e)}_checkInputs(){super._checkInputs(),this._follow()}getClassName(){return"ArcFollowCamera"}}(A=tO||(tO={}))[A.A=0]="A",A[A.B=1]="B",A[A.X=2]="X",A[A.Y=3]="Y",A[A.LB=4]="LB",A[A.RB=5]="RB",A[A.Back=8]="Back",A[A.Start=9]="Start",A[A.LeftStick=10]="LeftStick",A[A.RightStick=11]="RightStick",(R=tN||(tN={}))[R.Up=12]="Up",R[R.Down=13]="Down",R[R.Left=14]="Left",R[R.Right=15]="Right";class a9 extends aI{constructor(e,t,i,r=!1){super(e,t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new r_.y$,this.onButtonUpObservable=new r_.y$,this.onPadDownObservable=new r_.y$,this.onPadUpObservable=new r_.y$,this._buttonA=0,this._buttonB=0,this._buttonX=0,this._buttonY=0,this._buttonBack=0,this._buttonStart=0,this._buttonLB=0,this._buttonRB=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this._isXboxOnePad=!1,this.type=aI.XBOX,this._isXboxOnePad=r}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonA(){return this._buttonA}set buttonA(e){this._buttonA=this._setButtonValue(e,this._buttonA,tO.A)}get buttonB(){return this._buttonB}set buttonB(e){this._buttonB=this._setButtonValue(e,this._buttonB,tO.B)}get buttonX(){return this._buttonX}set buttonX(e){this._buttonX=this._setButtonValue(e,this._buttonX,tO.X)}get buttonY(){return this._buttonY}set buttonY(e){this._buttonY=this._setButtonValue(e,this._buttonY,tO.Y)}get buttonStart(){return this._buttonStart}set buttonStart(e){this._buttonStart=this._setButtonValue(e,this._buttonStart,tO.Start)}get buttonBack(){return this._buttonBack}set buttonBack(e){this._buttonBack=this._setButtonValue(e,this._buttonBack,tO.Back)}get buttonLB(){return this._buttonLB}set buttonLB(e){this._buttonLB=this._setButtonValue(e,this._buttonLB,tO.LB)}get buttonRB(){return this._buttonRB}set buttonRB(e){this._buttonRB=this._setButtonValue(e,this._buttonRB,tO.RB)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,tO.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,tO.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,tN.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,tN.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,tN.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,tN.Right)}update(){super.update(),this._isXboxOnePad,this.buttonA=this.browserGamepad.buttons[0].value,this.buttonB=this.browserGamepad.buttons[1].value,this.buttonX=this.browserGamepad.buttons[2].value,this.buttonY=this.browserGamepad.buttons[3].value,this.buttonLB=this.browserGamepad.buttons[4].value,this.buttonRB=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonBack=this.browserGamepad.buttons[8].value,this.buttonStart=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}(P=tF||(tF={}))[P.Cross=0]="Cross",P[P.Circle=1]="Circle",P[P.Square=2]="Square",P[P.Triangle=3]="Triangle",P[P.L1=4]="L1",P[P.R1=5]="R1",P[P.Share=8]="Share",P[P.Options=9]="Options",P[P.LeftStick=10]="LeftStick",P[P.RightStick=11]="RightStick",(I=tL||(tL={}))[I.Up=12]="Up",I[I.Down=13]="Down",I[I.Left=14]="Left",I[I.Right=15]="Right";class oe extends aI{constructor(e,t,i){super(e.replace("STANDARD GAMEPAD","SONY PLAYSTATION DUALSHOCK"),t,i,0,1,2,3),this._leftTrigger=0,this._rightTrigger=0,this.onButtonDownObservable=new r_.y$,this.onButtonUpObservable=new r_.y$,this.onPadDownObservable=new r_.y$,this.onPadUpObservable=new r_.y$,this._buttonCross=0,this._buttonCircle=0,this._buttonSquare=0,this._buttonTriangle=0,this._buttonShare=0,this._buttonOptions=0,this._buttonL1=0,this._buttonR1=0,this._buttonLeftStick=0,this._buttonRightStick=0,this._dPadUp=0,this._dPadDown=0,this._dPadLeft=0,this._dPadRight=0,this.type=aI.DUALSHOCK}onlefttriggerchanged(e){this._onlefttriggerchanged=e}onrighttriggerchanged(e){this._onrighttriggerchanged=e}get leftTrigger(){return this._leftTrigger}set leftTrigger(e){this._onlefttriggerchanged&&this._leftTrigger!==e&&this._onlefttriggerchanged(e),this._leftTrigger=e}get rightTrigger(){return this._rightTrigger}set rightTrigger(e){this._onrighttriggerchanged&&this._rightTrigger!==e&&this._onrighttriggerchanged(e),this._rightTrigger=e}onbuttondown(e){this._onbuttondown=e}onbuttonup(e){this._onbuttonup=e}ondpaddown(e){this._ondpaddown=e}ondpadup(e){this._ondpadup=e}_setButtonValue(e,t,i){return e!==t&&(1===e&&(this._onbuttondown&&this._onbuttondown(i),this.onButtonDownObservable.notifyObservers(i)),0===e&&(this._onbuttonup&&this._onbuttonup(i),this.onButtonUpObservable.notifyObservers(i))),e}_setDPadValue(e,t,i){return e!==t&&(1===e&&(this._ondpaddown&&this._ondpaddown(i),this.onPadDownObservable.notifyObservers(i)),0===e&&(this._ondpadup&&this._ondpadup(i),this.onPadUpObservable.notifyObservers(i))),e}get buttonCross(){return this._buttonCross}set buttonCross(e){this._buttonCross=this._setButtonValue(e,this._buttonCross,tF.Cross)}get buttonCircle(){return this._buttonCircle}set buttonCircle(e){this._buttonCircle=this._setButtonValue(e,this._buttonCircle,tF.Circle)}get buttonSquare(){return this._buttonSquare}set buttonSquare(e){this._buttonSquare=this._setButtonValue(e,this._buttonSquare,tF.Square)}get buttonTriangle(){return this._buttonTriangle}set buttonTriangle(e){this._buttonTriangle=this._setButtonValue(e,this._buttonTriangle,tF.Triangle)}get buttonOptions(){return this._buttonOptions}set buttonOptions(e){this._buttonOptions=this._setButtonValue(e,this._buttonOptions,tF.Options)}get buttonShare(){return this._buttonShare}set buttonShare(e){this._buttonShare=this._setButtonValue(e,this._buttonShare,tF.Share)}get buttonL1(){return this._buttonL1}set buttonL1(e){this._buttonL1=this._setButtonValue(e,this._buttonL1,tF.L1)}get buttonR1(){return this._buttonR1}set buttonR1(e){this._buttonR1=this._setButtonValue(e,this._buttonR1,tF.R1)}get buttonLeftStick(){return this._buttonLeftStick}set buttonLeftStick(e){this._buttonLeftStick=this._setButtonValue(e,this._buttonLeftStick,tF.LeftStick)}get buttonRightStick(){return this._buttonRightStick}set buttonRightStick(e){this._buttonRightStick=this._setButtonValue(e,this._buttonRightStick,tF.RightStick)}get dPadUp(){return this._dPadUp}set dPadUp(e){this._dPadUp=this._setDPadValue(e,this._dPadUp,tL.Up)}get dPadDown(){return this._dPadDown}set dPadDown(e){this._dPadDown=this._setDPadValue(e,this._dPadDown,tL.Down)}get dPadLeft(){return this._dPadLeft}set dPadLeft(e){this._dPadLeft=this._setDPadValue(e,this._dPadLeft,tL.Left)}get dPadRight(){return this._dPadRight}set dPadRight(e){this._dPadRight=this._setDPadValue(e,this._dPadRight,tL.Right)}update(){super.update(),this.buttonCross=this.browserGamepad.buttons[0].value,this.buttonCircle=this.browserGamepad.buttons[1].value,this.buttonSquare=this.browserGamepad.buttons[2].value,this.buttonTriangle=this.browserGamepad.buttons[3].value,this.buttonL1=this.browserGamepad.buttons[4].value,this.buttonR1=this.browserGamepad.buttons[5].value,this.leftTrigger=this.browserGamepad.buttons[6].value,this.rightTrigger=this.browserGamepad.buttons[7].value,this.buttonShare=this.browserGamepad.buttons[8].value,this.buttonOptions=this.browserGamepad.buttons[9].value,this.buttonLeftStick=this.browserGamepad.buttons[10].value,this.buttonRightStick=this.browserGamepad.buttons[11].value,this.dPadUp=this.browserGamepad.buttons[12].value,this.dPadDown=this.browserGamepad.buttons[13].value,this.dPadLeft=this.browserGamepad.buttons[14].value,this.dPadRight=this.browserGamepad.buttons[15].value}dispose(){super.dispose(),this.onButtonDownObservable.clear(),this.onButtonUpObservable.clear(),this.onPadDownObservable.clear(),this.onPadUpObservable.clear()}}class ot{constructor(e){if(this._scene=e,this._babylonGamepads=[],this._oneGamepadConnected=!1,this._isMonitoring=!1,this.onGamepadDisconnectedObservable=new r_.y$,(0,sP.CG)()?(this._gamepadEventSupported="GamepadEvent"in window,this._gamepadSupport=navigator&&navigator.getGamepads):this._gamepadEventSupported=!1,this.onGamepadConnectedObservable=new r_.y$(e=>{for(let t in this._babylonGamepads){let i=this._babylonGamepads[t];i&&i._isConnected&&this.onGamepadConnectedObservable.notifyObserver(e,i)}}),this._onGamepadConnectedEvent=e=>{let t;let i=e.gamepad;i.index in this._babylonGamepads&&this._babylonGamepads[i.index].isConnected||(this._babylonGamepads[i.index]?((t=this._babylonGamepads[i.index]).browserGamepad=i,t._isConnected=!0):t=this._addNewGamepad(i),this.onGamepadConnectedObservable.notifyObservers(t),this._startMonitoringGamepads())},this._onGamepadDisconnectedEvent=e=>{let t=e.gamepad;for(let e in this._babylonGamepads)if(this._babylonGamepads[e].index===t.index){let t=this._babylonGamepads[e];t._isConnected=!1,this.onGamepadDisconnectedObservable.notifyObservers(t),t.dispose&&t.dispose();break}},this._gamepadSupport){if(this._updateGamepadObjects(),this._babylonGamepads.length&&this._startMonitoringGamepads(),this._gamepadEventSupported){let e=this._scene?this._scene.getEngine().getHostWindow():window;e&&(e.addEventListener("gamepadconnected",this._onGamepadConnectedEvent,!1),e.addEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent,!1))}else this._startMonitoringGamepads()}}get gamepads(){return this._babylonGamepads}getGamepadByType(e=aI.XBOX){for(let t of this._babylonGamepads)if(t&&t.type===e)return t;return null}dispose(){this._gamepadEventSupported&&(this._onGamepadConnectedEvent&&window.removeEventListener("gamepadconnected",this._onGamepadConnectedEvent),this._onGamepadDisconnectedEvent&&window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnectedEvent),this._onGamepadConnectedEvent=null,this._onGamepadDisconnectedEvent=null),this._babylonGamepads.forEach(e=>{e.dispose()}),this.onGamepadConnectedObservable.clear(),this.onGamepadDisconnectedObservable.clear(),this._oneGamepadConnected=!1,this._stopMonitoringGamepads(),this._babylonGamepads=[]}_addNewGamepad(e){let t;this._oneGamepadConnected||(this._oneGamepadConnected=!0);let i=-1!==e.id.search("054c")&&-1===e.id.search("0ce6"),r=-1!==e.id.search("Xbox One");return t=r||-1!==e.id.search("Xbox 360")||-1!==e.id.search("xinput")||-1!==e.id.search("045e")&&-1===e.id.search("Surface Dock")?new a9(e.id,e.index,e,r):i?new oe(e.id,e.index,e):new aM(e.id,e.index,e),this._babylonGamepads[t.index]=t,t}_startMonitoringGamepads(){this._isMonitoring||(this._isMonitoring=!0,this._checkGamepadsStatus())}_stopMonitoringGamepads(){this._isMonitoring=!1}_checkGamepadsStatus(){for(let e in this._updateGamepadObjects(),this._babylonGamepads){let t=this._babylonGamepads[e];if(t&&t.isConnected)try{t.update()}catch(e){-1===this._loggedErrors.indexOf(t.index)&&(sg.w1.Warn(`Error updating gamepad ${t.id}`),this._loggedErrors.push(t.index))}}this._isMonitoring&&sR.D.QueueNewFrame(()=>{this._checkGamepadsStatus()})}_updateGamepadObjects(){let e=navigator.getGamepads?navigator.getGamepads():[];for(let t=0;t()=>new or(e,rf.P.Zero(),t));class or extends a1{get gamepadAngularSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadAngularSensibility:0}set gamepadAngularSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadAngularSensibility=e)}get gamepadMoveSensibility(){let e=this.inputs.attached.gamepad;return e?e.gamepadMoveSensibility:0}set gamepadMoveSensibility(e){let t=this.inputs.attached.gamepad;t&&(t.gamepadMoveSensibility=e)}constructor(e,t,i){super(e,t,i),this.inputs.addGamepad()}getClassName(){return"UniversalCamera"}}sC.V._CreateDefaultParsedCamera=(e,t)=>new or(e,rf.P.Zero(),t),rW.N.AddNodeConstructor("GamepadCamera",(e,t)=>()=>new os(e,rf.P.Zero(),t));class os extends or{constructor(e,t,i){super(e,t,i)}getClassName(){return"GamepadCamera"}}let on=`varying vec2 vUV;uniform samplerCube textureSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 uv=vUV*2.0-1.0; +#ifdef POSITIVEX +gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); +#endif +#ifdef NEGATIVEX +gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); +#endif +#ifdef POSITIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); +#endif +#ifdef NEGATIVEY +gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); +#endif +#ifdef POSITIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); +#endif +#ifdef NEGATIVEZ +gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); +#endif +}`;nw.v.ShadersStore.passCubePixelShader=on;class oa extends nz{getClassName(){return"PassPostProcess"}constructor(e,t,i=null,r,s,n,a=0,o=!1){super(e,"pass",null,null,t,i,r,s,n,void 0,a,void 0,null,o)}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new oa(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable),e,i,r)}}(0,rg.H)("BABYLON.PassPostProcess",oa),sR.D._RescalePostProcessFactory=e=>new oa("rescale",1,null,2,e,!1,0);let oo=`varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D leftSampler; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 leftFrag=texture2D(leftSampler,vUV);leftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);vec4 rightFrag=texture2D(textureSampler,vUV);rightFrag=vec4(rightFrag.r,1.0,1.0,1.0);gl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);}`;nw.v.ShadersStore.anaglyphPixelShader=oo;class ol extends nz{getClassName(){return"AnaglyphPostProcess"}constructor(e,t,i,r,s,n){super(e,"anaglyph",null,["leftSampler"],t,i[1],r,s,n),this._passedProcess=i[0]._rigPostProcess,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("leftSampler",this._passedProcess)})}}function oh(e){e._rigCameras[0]._rigPostProcess=new oa(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new ol(e.name+"_anaglyph",1,e._rigCameras)}(0,rg.H)("BABYLON.AnaglyphPostProcess",ol),rW.N.AddNodeConstructor("AnaglyphArcRotateCamera",(e,t,i)=>()=>new ou(e,0,0,1,rf.P.Zero(),i.interaxial_distance,t));class ou extends a2{constructor(e,t,i,r,s,n,a){super(e,t,i,r,s,a),this._setRigMode=()=>oh(this),this.interaxialDistance=n,this.setCameraRigMode(sC.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:n})}getClassName(){return"AnaglyphArcRotateCamera"}}rW.N.AddNodeConstructor("AnaglyphFreeCamera",(e,t,i)=>()=>new oc(e,rf.P.Zero(),i.interaxial_distance,t));class oc extends a0{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>oh(this),this.interaxialDistance=i,this.setCameraRigMode(sC.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphFreeCamera"}}rW.N.AddNodeConstructor("AnaglyphGamepadCamera",(e,t,i)=>()=>new od(e,rf.P.Zero(),i.interaxial_distance,t));class od extends os{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>oh(this),this.interaxialDistance=i,this.setCameraRigMode(sC.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphGamepadCamera"}}rW.N.AddNodeConstructor("AnaglyphUniversalCamera",(e,t,i)=>()=>new op(e,rf.P.Zero(),i.interaxial_distance,t));class op extends or{constructor(e,t,i,r){super(e,t,r),this._setRigMode=()=>oh(this),this.interaxialDistance=i,this.setCameraRigMode(sC.V.RIG_MODE_STEREOSCOPIC_ANAGLYPH,{interaxialDistance:i})}getClassName(){return"AnaglyphUniversalCamera"}}let o_=`const vec3 TWO=vec3(2.0,2.0,2.0);varying vec2 vUV;uniform sampler2D camASampler;uniform sampler2D textureSampler;uniform vec2 stepSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{bool useCamA;bool useCamB;vec2 texCoord1;vec2 texCoord2;vec3 frag1;vec3 frag2; +#ifdef IS_STEREOSCOPIC_HORIZ +useCamB=vUV.x>0.5;useCamA=!useCamB;texCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);texCoord2=vec2(texCoord1.x+stepSize.x,vUV.y); +#else +#ifdef IS_STEREOSCOPIC_INTERLACED +float rowNum=floor(vUV.y/stepSize.y);useCamA=mod(rowNum,2.0)==1.0;useCamB=mod(rowNum,2.0)==0.0;texCoord1=vec2(vUV.x,vUV.y);texCoord2=vec2(vUV.x,vUV.y); +#else +useCamB=vUV.y>0.5;useCamA=!useCamB;texCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);texCoord2=vec2(vUV.x,texCoord1.y+stepSize.y); +#endif +#endif +if (useCamB){frag1=texture2D(textureSampler,texCoord1).rgb;frag2=texture2D(textureSampler,texCoord2).rgb;}else if (useCamA){frag1=texture2D(camASampler ,texCoord1).rgb;frag2=texture2D(camASampler ,texCoord2).rgb;}else {discard;} +gl_FragColor=vec4((frag1+frag2)/TWO,1.0);} +`;nw.v.ShadersStore.stereoscopicInterlacePixelShader=o_;class of extends nz{getClassName(){return"StereoscopicInterlacePostProcessI"}constructor(e,t,i,r,s,n,a){super(e,"stereoscopicInterlace",["stepSize"],["camASampler"],1,t[1],s,n,a,r?"#define IS_STEREOSCOPIC_INTERLACED 1":i?"#define IS_STEREOSCOPIC_HORIZ 1":void 0),this._passedProcess=t[0]._rigPostProcess,this._stepSize=new rf.FM(1/this.width,1/this.height),this.onSizeChangedObservable.add(()=>{this._stepSize=new rf.FM(1/this.width,1/this.height)}),this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("camASampler",this._passedProcess),e.setFloat2("stepSize",this._stepSize.x,this._stepSize.y)})}}function om(e){let t=e.cameraRigMode===sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL||e.cameraRigMode===sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,i=e.cameraRigMode===sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;e.cameraRigMode===sC.V.RIG_MODE_STEREOSCOPIC_INTERLACED?(e._rigCameras[0]._rigPostProcess=new oa(e.name+"_passthru",1,e._rigCameras[0]),e._rigCameras[1]._rigPostProcess=new of(e.name+"_stereoInterlace",e._rigCameras,!1,!0)):(e._rigCameras[i?1:0].viewport=new ny.l(0,0,t?.5:1,t?1:.5),e._rigCameras[i?0:1].viewport=new ny.l(t?.5:0,t?0:.5,t?.5:1,t?1:.5))}rW.N.AddNodeConstructor("StereoscopicArcRotateCamera",(e,t,i)=>()=>new og(e,0,0,1,rf.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class og extends a2{constructor(e,t,i,r,s,n,a,o){super(e,t,i,r,s,o),this._setRigMode=()=>om(this),this.interaxialDistance=n,this.isStereoscopicSideBySide=a,this.setCameraRigMode(a?sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:sC.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:n})}getClassName(){return"StereoscopicArcRotateCamera"}}rW.N.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new ov(e,rf.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class ov extends a0{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>om(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:sC.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicFreeCamera"}}rW.N.AddNodeConstructor("StereoscopicGamepadCamera",(e,t,i)=>()=>new ox(e,rf.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class ox extends os{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>om(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:sC.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicGamepadCamera"}}rW.N.AddNodeConstructor("StereoscopicFreeCamera",(e,t,i)=>()=>new oT(e,rf.P.Zero(),i.interaxial_distance,i.isStereoscopicSideBySide,t));class oT extends or{constructor(e,t,i,r,s){super(e,t,s),this._setRigMode=()=>om(this),this.interaxialDistance=i,this.isStereoscopicSideBySide=r,this.setCameraRigMode(r?sC.V.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:sC.V.RIG_MODE_STEREOSCOPIC_OVERUNDER,{interaxialDistance:i})}getClassName(){return"StereoscopicUniversalCamera"}}rW.N.AddNodeConstructor("VirtualJoysticksCamera",(e,t)=>()=>new oS(e,rf.P.Zero(),t));class oS extends a0{constructor(e,t,i){super(e,t,i),this.inputs.addVirtualJoystick()}getClassName(){return"VirtualJoysticksCamera"}}class oE{constructor(){this.compensateDistortion=!0,this.multiviewEnabled=!1}get aspectRatio(){return this.hResolution/(2*this.vResolution)}get aspectRatioFov(){return 2*Math.atan(this.postProcessScaleFactor*this.vScreenSize/(2*this.eyeToScreenDistance))}get leftHMatrix(){let e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return rf.y3.Translation(e,0,0)}get rightHMatrix(){let e=4*(this.hScreenSize/4-this.lensSeparationDistance/2)/this.hScreenSize;return rf.y3.Translation(-e,0,0)}get leftPreViewMatrix(){return rf.y3.Translation(.5*this.interpupillaryDistance,0,0)}get rightPreViewMatrix(){return rf.y3.Translation(-.5*this.interpupillaryDistance,0,0)}static GetDefault(){let e=new oE;return e.hResolution=1280,e.vResolution=800,e.hScreenSize=.149759993,e.vScreenSize=.0935999975,e.vScreenCenter=.0467999987,e.eyeToScreenDistance=.0410000011,e.lensSeparationDistance=.063500002,e.interpupillaryDistance=.064000003,e.distortionK=[1,.219999999,.239999995,0],e.chromaAbCorrection=[.995999992,-.00400000019,1.01400006,0],e.postProcessScaleFactor=1.714605507808412,e.lensCenterOffset=.151976421,e}}let oC=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 LensCenter;uniform vec2 Scale;uniform vec2 ScaleIn;uniform vec4 HmdWarpParam;vec2 HmdWarp(vec2 in01) {vec2 theta=(in01-LensCenter)*ScaleIn; +float rSq=theta.x*theta.x+theta.y*theta.y;vec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);return LensCenter+Scale*rvector;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 tc=HmdWarp(vUV);if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0) +gl_FragColor=vec4(0.0,0.0,0.0,0.0);else{gl_FragColor=texture2D(textureSampler,tc);}}`;nw.v.ShadersStore.vrDistortionCorrectionPixelShader=oC;class ob extends nz{getClassName(){return"VRDistortionCorrectionPostProcess"}constructor(e,t,i,r){super(e,"vrDistortionCorrection",["LensCenter","Scale","ScaleIn","HmdWarpParam"],null,r.postProcessScaleFactor,t,sj.BILINEAR_SAMPLINGMODE),this._isRightEye=i,this._distortionFactors=r.distortionK,this._postProcessScaleFactor=r.postProcessScaleFactor,this._lensCenterOffset=r.lensCenterOffset,this.adaptScaleToCurrentViewport=!0,this.onSizeChangedObservable.add(()=>{this._scaleIn=new rf.FM(2,2/this.aspectRatio),this._scaleFactor=new rf.FM(1/this._postProcessScaleFactor*.5,1/this._postProcessScaleFactor*.5*this.aspectRatio),this._lensCenter=new rf.FM(this._isRightEye?.5-.5*this._lensCenterOffset:.5+.5*this._lensCenterOffset,.5)}),this.onApplyObservable.add(e=>{e.setFloat2("LensCenter",this._lensCenter.x,this._lensCenter.y),e.setFloat2("Scale",this._scaleFactor.x,this._scaleFactor.y),e.setFloat2("ScaleIn",this._scaleIn.x,this._scaleIn.y),e.setFloat4("HmdWarpParam",this._distortionFactors[0],this._distortionFactors[1],this._distortionFactors[2],this._distortionFactors[3])})}}let oy=`precision mediump sampler2DArray;varying vec2 vUV;uniform sampler2DArray multiviewSampler;uniform int imageIndex; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(multiviewSampler,vec3(vUV,imageIndex));}`;nw.v.ShadersStore.vrMultiviewToSingleviewPixelShader=oy;class oA extends as{set samples(e){this._samples=e}get samples(){return this._samples}constructor(e,t=512){super("multiview rtt",t,e,!1,!0,0,!1,void 0,!1,!1,!0,void 0,!0),this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight()),this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,this.samples=this._getEngine().getCaps().maxSamples||this.samples,this._texture.samples=this._samples}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindMultiviewFramebuffer(this._renderTarget)}getViewCount(){return 2}}function oR(e,t){let i=new sT.M(e,void 0,!0,t);return i.addUniform("viewProjection",16),i.addUniform("viewProjectionR",16),i.addUniform("view",16),i.addUniform("projection",16),i.addUniform("vEyePosition",4),i}sR.D.prototype.createMultiviewRenderTargetTexture=function(e,t,i,r){let s=this._gl;if(!this.getCaps().multiview)throw"Multiview is not supported";let n=this._createHardwareRenderTargetWrapper(!1,!1,{width:e,height:t});n._framebuffer=s.createFramebuffer();let a=new sq.l(this,sq.S.Unknown,!0);return a.width=e,a.height=t,a.isMultiview=!0,i||(i=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,i),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.RGBA8,e,t,2)),n._colorTextureArray=i,r||(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D_ARRAY,r),s.texStorage3D(s.TEXTURE_2D_ARRAY,1,s.DEPTH24_STENCIL8,e,t,2)),n._depthStencilTextureArray=r,a.isReady=!0,n.setTextures(a),n._depthStencilTexture=a,n},sR.D.prototype.bindMultiviewFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)this.getCaps().oculusMultiview?(i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,e.samples,0,2),i.framebufferTextureMultisampleMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,e.samples,0,2)):(i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,e._depthStencilTextureArray,0,0,2));else throw"Invalid multiview frame buffer"},sR.D.prototype.bindSpaceWarpFramebuffer=function(e){let t=this._gl,i=this.getCaps().oculusMultiview||this.getCaps().multiview;if(this.bindFramebuffer(e,void 0,void 0,void 0,!0),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,e._framebuffer),e._colorTextureArray&&e._depthStencilTextureArray)i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,e._colorTextureArray,0,0,2),i.framebufferTextureMultiviewOVR(t.DRAW_FRAMEBUFFER,t.DEPTH_ATTACHMENT,e._depthStencilTextureArray,0,0,2);else throw Error("Invalid Space Warp framebuffer")},sC.V.prototype._useMultiviewToSingleView=!1,sC.V.prototype._multiviewTexture=null,sC.V.prototype._resizeOrCreateMultiviewTexture=function(e,t){this._multiviewTexture?(this._multiviewTexture.getRenderWidth()!=e||this._multiviewTexture.getRenderHeight()!=t)&&(this._multiviewTexture.dispose(),this._multiviewTexture=new oA(this.getScene(),{width:e,height:t})):this._multiviewTexture=new oA(this.getScene(),{width:e,height:t})};let oP=r2.x.prototype.createSceneUniformBuffer;r2.x.prototype._transformMatrixR=rf.y3.Zero(),r2.x.prototype._multiviewSceneUbo=null,r2.x.prototype._createMultiviewUbo=function(){this._multiviewSceneUbo=oR(this.getEngine(),"scene_multiview")},r2.x.prototype.createSceneUniformBuffer=function(e){return this._multiviewSceneUbo?oR(this.getEngine(),e):oP.bind(this)(e)},r2.x.prototype._updateMultiviewUbo=function(e,t){e&&t&&e.multiplyToRef(t,this._transformMatrixR),e&&t&&(e.multiplyToRef(t,rf.jp.Matrix[0]),nb.i.GetRightPlaneToRef(rf.jp.Matrix[0],this._frustumPlanes[3])),this._multiviewSceneUbo&&(this._multiviewSceneUbo.updateMatrix("viewProjection",this.getTransformMatrix()),this._multiviewSceneUbo.updateMatrix("viewProjectionR",this._transformMatrixR),this._multiviewSceneUbo.updateMatrix("view",this._viewMatrix),this._multiviewSceneUbo.updateMatrix("projection",this._projectionMatrix))},r2.x.prototype._renderMultiviewToSingleView=function(e){e._resizeOrCreateMultiviewTexture(e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.width>0?e._rigPostProcess.width:this.getEngine().getRenderWidth(!0),e._rigPostProcess&&e._rigPostProcess&&e._rigPostProcess.height>0?e._rigPostProcess.height:this.getEngine().getRenderHeight(!0)),this._multiviewSceneUbo||this._createMultiviewUbo(),e.outputRenderTarget=e._multiviewTexture,this._renderForCamera(e),e.outputRenderTarget=null;for(let t=0;t{}),this.onApplyObservable.add(e=>{r._scene.activeCamera&&r._scene.activeCamera.isLeftCamera?e.setInt("imageIndex",0):e.setInt("imageIndex",1),e.setTexture("multiviewSampler",r._multiviewTexture)})}}function oM(e,t){let i=t.vrCameraMetrics||oE.GetDefault();e._rigCameras[0]._cameraRigParams.vrMetrics=i,e._rigCameras[0].viewport=new ny.l(0,0,.5,1),e._rigCameras[0]._cameraRigParams.vrWorkMatrix=new rf.y3,e._rigCameras[0]._cameraRigParams.vrHMatrix=i.leftHMatrix,e._rigCameras[0]._cameraRigParams.vrPreViewMatrix=i.leftPreViewMatrix,e._rigCameras[0].getProjectionMatrix=e._rigCameras[0]._getVRProjectionMatrix,e._rigCameras[1]._cameraRigParams.vrMetrics=i,e._rigCameras[1].viewport=new ny.l(.5,0,.5,1),e._rigCameras[1]._cameraRigParams.vrWorkMatrix=new rf.y3,e._rigCameras[1]._cameraRigParams.vrHMatrix=i.rightHMatrix,e._rigCameras[1]._cameraRigParams.vrPreViewMatrix=i.rightPreViewMatrix,e._rigCameras[1].getProjectionMatrix=e._rigCameras[1]._getVRProjectionMatrix,i.multiviewEnabled&&(e.getScene().getEngine().getCaps().multiview?(e._useMultiviewToSingleView=!0,e._rigPostProcess=new oI("VRMultiviewToSingleview",e,i.postProcessScaleFactor)):(rb.Y.Warn("Multiview is not supported, falling back to standard rendering"),i.multiviewEnabled=!1)),i.compensateDistortion&&(e._rigCameras[0]._rigPostProcess=new ob("VR_Distort_Compensation_Left",e._rigCameras[0],!1,i),e._rigCameras[1]._rigPostProcess=new ob("VR_Distort_Compensation_Right",e._rigCameras[1],!0,i))}rW.N.AddNodeConstructor("VRDeviceOrientationArcRotateCamera",(e,t)=>()=>new oD(e,0,0,1,rf.P.Zero(),t));class oD extends a2{constructor(e,t,i,r,s,n,a=!0,o=oE.GetDefault()){super(e,t,i,r,s,n),this._setRigMode=e=>oM(this,e),o.compensateDistortion=a,this.setCameraRigMode(sC.V.RIG_MODE_VR,{vrCameraMetrics:o}),this.inputs.addVRDeviceOrientation()}getClassName(){return"VRDeviceOrientationArcRotateCamera"}}rW.N.AddNodeConstructor("VRDeviceOrientationFreeCamera",(e,t)=>()=>new oO(e,rf.P.Zero(),t));class oO extends a3{constructor(e,t,i,r=!0,s=oE.GetDefault()){super(e,t,i),this._setRigMode=e=>oM(this,e),s.compensateDistortion=r,this.setCameraRigMode(sC.V.RIG_MODE_VR,{vrCameraMetrics:s})}getClassName(){return"VRDeviceOrientationFreeCamera"}}rW.N.AddNodeConstructor("VRDeviceOrientationGamepadCamera",(e,t)=>()=>new oN(e,rf.P.Zero(),t));class oN extends oO{constructor(e,t,i,r=!0,s=oE.GetDefault()){super(e,t,i,r,s),this._setRigMode=e=>oM(this,e),this.inputs.addGamepad()}getClassName(){return"VRDeviceOrientationGamepadCamera"}}class oF{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,i,r,s){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&-1!==t.prePassRenderer.getIndex(2)){this.previousWorldMatrices[i.uniqueId]||(this.previousWorldMatrices[i.uniqueId]=r.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());let s=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==s.frameId&&(this._lastUpdateFrameId=s.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[i.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[i.uniqueId]=r.clone()}}}var oL=i(4885);class ow{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,sR.D.MarkAllMaterialsAsDirty(4))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get TranslucencyIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,sR.D.MarkAllMaterialsAsDirty(1))}}ow._DiffuseTextureEnabled=!0,ow._DetailTextureEnabled=!0,ow._DecalMapEnabled=!0,ow._AmbientTextureEnabled=!0,ow._OpacityTextureEnabled=!0,ow._ReflectionTextureEnabled=!0,ow._EmissiveTextureEnabled=!0,ow._SpecularTextureEnabled=!0,ow._BumpTextureEnabled=!0,ow._LightmapTextureEnabled=!0,ow._RefractionTextureEnabled=!0,ow._ColorGradingTextureEnabled=!0,ow._FresnelEnabled=!0,ow._ClearCoatTextureEnabled=!0,ow._ClearCoatBumpTextureEnabled=!0,ow._ClearCoatTintTextureEnabled=!0,ow._SheenTextureEnabled=!0,ow._AnisotropicTextureEnabled=!0,ow._ThicknessTextureEnabled=!0,ow._RefractionIntensityTextureEnabled=!0,ow._TranslucencyIntensityTextureEnabled=!0,ow._IridescenceTextureEnabled=!0;let oB=`#ifdef DECAL +uniform vec4 vDecalInfos; +#endif +`;nw.v.IncludesShadersStore.decalFragmentDeclaration=oB;let oU=`uniform vec4 vEyePosition;uniform vec4 vDiffuseColor; +#ifdef SPECULARTERM +uniform vec4 vSpecularColor; +#endif +uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef ALPHATEST +uniform float alphaCutOff; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFRACTION +uniform vec4 vRefractionInfos; +#ifndef REFRACTIONMAP_3D +uniform mat4 refractionMatrix; +#endif +#ifdef REFRACTIONFRESNEL +uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; +#endif +#if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos; +#endif +#ifdef DIFFUSEFRESNEL +uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; +#endif +#ifdef OPACITYFRESNEL +uniform vec4 opacityParts; +#endif +#ifdef EMISSIVEFRESNEL +uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) +uniform mat4 reflectionMatrix; +#endif +#ifndef REFLECTIONMAP_SKYBOX +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include +#define ADDITIONAL_FRAGMENT_DECLARATION +`;nw.v.IncludesShadersStore.defaultFragmentDeclaration=oU;let oV=`layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; +#ifdef MULTIVIEW +mat4 viewProjectionR; +#endif +mat4 view;mat4 projection;vec4 vEyePosition;}; +`;nw.v.IncludesShadersStore.sceneUboDeclaration=oV;let ok=`#ifdef WEBGL2 +uniform mat4 world;uniform float visibility; +#else +layout(std140,column_major) uniform;uniform Mesh +{mat4 world;float visibility;}; +#endif +#define WORLD_UBO +`;nw.v.IncludesShadersStore.meshUboDeclaration=ok;let oG=`layout(std140,column_major) uniform;uniform Material +{vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vReflectionInfos;vec3 vReflectionPosition;vec3 vReflectionSize;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 reflectionMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor; +#define ADDITIONAL_UBO_DECLARATION +}; +#include +#include +`;nw.v.IncludesShadersStore.defaultUboDeclaration=oG;let oz=`#ifdef PREPASS +#extension GL_EXT_draw_buffers : require +layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; +#ifdef PREPASS_DEPTH +varying highp vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; +#endif +#endif +`;nw.v.IncludesShadersStore.prePassDeclaration=oz;let oW=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +#extension GL_EXT_draw_buffers : require +layout(location=0) out vec2 depth; +layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; +#define MAX_DEPTH 99999.0 +highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; +#endif +`;nw.v.IncludesShadersStore.oitDeclaration=oW;let oH=`#ifdef MAINUV{X} +varying vec2 vMainUV{X}; +#endif +`;nw.v.IncludesShadersStore.mainUVVaryingDeclaration=oH;let oX=`const float PI=3.1415926535897932384626433832795;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float HALF_MIN=5.96046448e-08; +const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; +#define saturate(x) clamp(x,0.0,1.0) +#define absEps(x) abs(x)+Epsilon +#define maxEps(x) max(x,Epsilon) +#define saturateEps(x) clamp(x,Epsilon,1.0) +mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( +vec3(i0.x,i1.x,i2.x), +vec3(i0.y,i1.y,i2.y), +vec3(i0.z,i1.z,i2.z) +);return outMatrix;} +mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), +b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), +b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} +#if USE_EXACT_SRGB_CONVERSIONS +vec3 toLinearSpaceExact(vec3 color) +{vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); +#else +return +vec3( +color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, +color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, +color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); +#endif +} +vec3 toGammaSpaceExact(vec3 color) +{vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); +#else +return +vec3( +color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, +color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, +color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); +#endif +} +#endif +float toLinearSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; +#else +return pow(color,LinearEncodePowerApprox); +#endif +} +vec3 toLinearSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toLinearSpaceExact(color); +#else +return pow(color,vec3(LinearEncodePowerApprox)); +#endif +} +vec4 toLinearSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toLinearSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); +#endif +} +float toGammaSpace(float color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; +#else +return pow(color,GammaEncodePowerApprox); +#endif +} +vec3 toGammaSpace(vec3 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return toGammaSpaceExact(color); +#else +return pow(color,vec3(GammaEncodePowerApprox)); +#endif +} +vec4 toGammaSpace(vec4 color) +{ +#if USE_EXACT_SRGB_CONVERSIONS +return vec4(toGammaSpaceExact(color.rgb),color.a); +#else +return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); +#endif +} +float square(float value) +{return value*value;} +vec3 square(vec3 value) +{return value*value;} +float pow5(float value) {float sq=value*value;return sq*sq*value;} +float getLuminance(vec3 color) +{return clamp(dot(color,LuminanceEncodeApprox),0.,1.);} +float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} +float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} +const float rgbdMaxRange=255.0;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(clamp(rgb,0.,1.),D); } +vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} +vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} +`;nw.v.IncludesShadersStore.helperFunctions=oX;let oY=`#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; +#endif +#endif +`;nw.v.IncludesShadersStore.lightFragmentDeclaration=oY;let oj=`#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef PROJECTEDLIGHTTEXTURE{X} +uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightSampler{X}; +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DArrayShadow shadowSampler{X};uniform highp sampler2DArray depthSampler{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DArrayShadow shadowSampler{X}; +#else +uniform highp sampler2DArray shadowSampler{X}; +#endif +#ifdef SHADOWCSMDEBUG{X} +const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] +( +vec3 ( 1.5,0.0,0.0 ), +vec3 ( 0.0,1.5,0.0 ), +vec3 ( 0.0,0.0,5.5 ), +vec3 ( 1.5,0.0,5.5 ), +vec3 ( 1.5,1.5,0.0 ), +vec3 ( 1.0,1.0,1.0 ), +vec3 ( 0.0,1.0,5.5 ), +vec3 ( 0.5,3.5,0.75 ) +);vec3 shadowDebug{X}; +#endif +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +int index{X}=-1; +#else +int index{X}=SHADOWCSMNUM_CASCADES{X}-1; +#endif +float diff{X}=0.; +#elif defined(SHADOWCUBE{X}) +uniform samplerCube shadowSampler{X}; +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; +#if defined(SHADOWPCSS{X}) +uniform highp sampler2DShadow shadowSampler{X};uniform highp sampler2D depthSampler{X}; +#elif defined(SHADOWPCF{X}) +uniform highp sampler2DShadow shadowSampler{X}; +#else +uniform sampler2D shadowSampler{X}; +#endif +uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;nw.v.IncludesShadersStore.lightUboDeclaration=oj;let oq=`struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef NDOTL +float ndl; +#endif +};lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) +{vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} +else +{lightVectorW=normalize(-lightData.xyz);} +float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) +{cosAngle=max(0.,pow(cosAngle,lightData.w));attenuation*=cosAngle;float ndl=max(0.,dot(vNormal,lightVectorW)); +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=ndl*diffuseColor*attenuation; +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; +#endif +return result;} +result.diffuse=vec3(0.); +#ifdef SPECULARTERM +result.specular=vec3(0.); +#endif +#ifdef NDOTL +result.ndl=0.; +#endif +return result;} +lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; +#ifdef NDOTL +result.ndl=ndl; +#endif +result.diffuse=mix(groundColor,diffuseColor,ndl); +#ifdef SPECULARTERM +vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; +#endif +return result;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;}`;nw.v.IncludesShadersStore.lightsFragmentFunctions=oq;let oK=`#ifdef SHADOWS +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +#ifndef SHADOWFLOAT +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} +#endif +float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) +{float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} +#define inline +float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; +#ifndef SHADOWFLOAT +float shadow=unpack(textureCube(shadowSampler,directionToLight)); +#else +float shadow=textureCube(shadowSampler,directionToLight).x; +#endif +return depth>shadow ? darkness : 1.0;} +#define inline +float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) +{vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); +#ifndef SHADOWFLOAT +if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} +#endif +#define inline +float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} +#define inline +float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); +#ifndef SHADOWFLOAT +if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) +{return 1.0;} +else +{float shadowPixelDepth=clamp(depthMetric,0.,1.0); +#ifndef SHADOWFLOAT +float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); +#else +float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; +#endif +float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} +#ifdef IS_NDC_HALF_ZRANGE +#define ZINCLIP clipSpace.z +#else +#define ZINCLIP uvDepth.z +#endif +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define GREATEST_LESS_THAN_ONE 0.99999994 +/* disable_uniformity_analysis */ +#define inline +float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} +#define inline +float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +#define inline +float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) +{if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; +uv+=0.5; +vec2 st=fract(uv); +vec2 base_uv=floor(uv)-0.5; +base_uv*=shadowMapSizeAndInverse.y; +vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} +const vec3 PoissonSamplers32[64]=vec3[64]( +vec3(0.06407013,0.05409927,0.), +vec3(0.7366577,0.5789394,0.), +vec3(-0.6270542,-0.5320278,0.), +vec3(-0.4096107,0.8411095,0.), +vec3(0.6849564,-0.4990818,0.), +vec3(-0.874181,-0.04579735,0.), +vec3(0.9989998,0.0009880066,0.), +vec3(-0.004920578,-0.9151649,0.), +vec3(0.1805763,0.9747483,0.), +vec3(-0.2138451,0.2635818,0.), +vec3(0.109845,0.3884785,0.), +vec3(0.06876755,-0.3581074,0.), +vec3(0.374073,-0.7661266,0.), +vec3(0.3079132,-0.1216763,0.), +vec3(-0.3794335,-0.8271583,0.), +vec3(-0.203878,-0.07715034,0.), +vec3(0.5912697,0.1469799,0.), +vec3(-0.88069,0.3031784,0.), +vec3(0.5040108,0.8283722,0.), +vec3(-0.5844124,0.5494877,0.), +vec3(0.6017799,-0.1726654,0.), +vec3(-0.5554981,0.1559997,0.), +vec3(-0.3016369,-0.3900928,0.), +vec3(-0.5550632,-0.1723762,0.), +vec3(0.925029,0.2995041,0.), +vec3(-0.2473137,0.5538505,0.), +vec3(0.9183037,-0.2862392,0.), +vec3(0.2469421,0.6718712,0.), +vec3(0.3916397,-0.4328209,0.), +vec3(-0.03576927,-0.6220032,0.), +vec3(-0.04661255,0.7995201,0.), +vec3(0.4402924,0.3640312,0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.), +vec3(0.) +);const vec3 PoissonSamplers64[64]=vec3[64]( +vec3(-0.613392,0.617481,0.), +vec3(0.170019,-0.040254,0.), +vec3(-0.299417,0.791925,0.), +vec3(0.645680,0.493210,0.), +vec3(-0.651784,0.717887,0.), +vec3(0.421003,0.027070,0.), +vec3(-0.817194,-0.271096,0.), +vec3(-0.705374,-0.668203,0.), +vec3(0.977050,-0.108615,0.), +vec3(0.063326,0.142369,0.), +vec3(0.203528,0.214331,0.), +vec3(-0.667531,0.326090,0.), +vec3(-0.098422,-0.295755,0.), +vec3(-0.885922,0.215369,0.), +vec3(0.566637,0.605213,0.), +vec3(0.039766,-0.396100,0.), +vec3(0.751946,0.453352,0.), +vec3(0.078707,-0.715323,0.), +vec3(-0.075838,-0.529344,0.), +vec3(0.724479,-0.580798,0.), +vec3(0.222999,-0.215125,0.), +vec3(-0.467574,-0.405438,0.), +vec3(-0.248268,-0.814753,0.), +vec3(0.354411,-0.887570,0.), +vec3(0.175817,0.382366,0.), +vec3(0.487472,-0.063082,0.), +vec3(-0.084078,0.898312,0.), +vec3(0.488876,-0.783441,0.), +vec3(0.470016,0.217933,0.), +vec3(-0.696890,-0.549791,0.), +vec3(-0.149693,0.605762,0.), +vec3(0.034211,0.979980,0.), +vec3(0.503098,-0.308878,0.), +vec3(-0.016205,-0.872921,0.), +vec3(0.385784,-0.393902,0.), +vec3(-0.146886,-0.859249,0.), +vec3(0.643361,0.164098,0.), +vec3(0.634388,-0.049471,0.), +vec3(-0.688894,0.007843,0.), +vec3(0.464034,-0.188818,0.), +vec3(-0.440840,0.137486,0.), +vec3(0.364483,0.511704,0.), +vec3(0.034028,0.325968,0.), +vec3(0.099094,-0.308023,0.), +vec3(0.693960,-0.366253,0.), +vec3(0.678884,-0.204688,0.), +vec3(0.001801,0.780328,0.), +vec3(0.145177,-0.898984,0.), +vec3(0.062655,-0.611866,0.), +vec3(0.315226,-0.604297,0.), +vec3(-0.780145,0.486251,0.), +vec3(-0.371868,0.882138,0.), +vec3(0.200476,0.494430,0.), +vec3(-0.494552,-0.711051,0.), +vec3(0.612476,0.705252,0.), +vec3(-0.578845,-0.768792,0.), +vec3(-0.772454,-0.090976,0.), +vec3(0.504440,0.372295,0.), +vec3(0.155736,0.065157,0.), +vec3(0.391522,0.849605,0.), +vec3(-0.620106,-0.328104,0.), +vec3(0.789239,-0.419965,0.), +vec3(-0.545396,0.538133,0.), +vec3(-0.178564,-0.596057,0.) +); +#define inline +float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE);vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;} +else +{vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) +#endif +#if defined(DETAIL) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) +#endif +#if defined(BUMP) && defined(PARALLAX) +const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; icurrRayHeight) +{float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} +else +{currRayHeight-=stepSize;vLastOffset=vCurrOffset; +#ifdef PARALLAX_RHS +vCurrOffset-=stepSize*vMaxOffset; +#else +vCurrOffset+=stepSize*vMaxOffset; +#endif +lastSampledHeight=currSampledHeight;}} +return vCurrOffset;} +vec2 parallaxOffset(vec3 viewDir,float heightScale) +{float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; +#ifdef PARALLAX_RHS +return texCoordOffset; +#else +return -texCoordOffset; +#endif +} +#endif +`;nw.v.IncludesShadersStore.bumpFragmentFunctions=o2;let o3=`#ifdef CLIPPLANE +varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +varying float fClipDistance6; +#endif +`;nw.v.IncludesShadersStore.clipPlaneFragmentDeclaration=o3;let o4=`#ifdef LOGARITHMICDEPTH +uniform float logarithmicDepthConstant;varying float vFragmentDepth; +#endif +`;nw.v.IncludesShadersStore.logDepthDeclaration=o4;let o5=`#ifdef FOG +#define FOGMODE_NONE 0. +#define FOGMODE_EXP 1. +#define FOGMODE_EXP2 2. +#define FOGMODE_LINEAR 3. +#define E 2.71828 +uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() +{float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) +{fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} +else if (FOGMODE_EXP==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDensity);} +else if (FOGMODE_EXP2==vFogInfos.x) +{fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} +return clamp(fogCoeff,0.0,1.0);} +#endif +`;nw.v.IncludesShadersStore.fogFragmentDeclaration=o5;let o6=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fClipDistance6>0.0) +{discard;} +#endif +`;nw.v.IncludesShadersStore.clipPlaneFragment=o6;let o8=`vec2 uvOffset=vec2(0.0,0.0); +#if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) +#ifdef NORMALXYSCALE +float normalScale=1.0; +#elif defined(BUMP) +float normalScale=vBumpInfos.y; +#else +float normalScale=1.0; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#elif defined(BUMP) +vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); +#else +vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#elif defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +mat3 TBN=vTBN; +#else +vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); +#endif +#endif +#ifdef PARALLAX +mat3 invTBN=transposeMat3(TBN); +#ifdef PARALLAXOCCLUSION +uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); +#else +uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); +#endif +#endif +#ifdef DETAIL +vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); +#endif +#ifdef BUMP +#ifdef OBJECTSPACE_NORMALMAP +#define CUSTOM_FRAGMENT_BUMP_FRAGMENT +normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); +#elif !defined(DETAIL) +normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); +#else +vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; +#if DETAIL_NORMALBLENDMETHOD==0 +detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); +#elif DETAIL_NORMALBLENDMETHOD==1 +detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; +#endif +normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); +#endif +#elif defined(DETAIL) +detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); +#endif +`;nw.v.IncludesShadersStore.bumpFragment=o8;let o7=`#ifdef DECAL +#ifdef GAMMADECAL +decalColor.rgb=toLinearSpace(decalColor.rgb); +#endif +#ifdef DECAL_SMOOTHALPHA +decalColor.a*=decalColor.a; +#endif +surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); +#endif +`;nw.v.IncludesShadersStore.decalFragment=o7;let o9=`#ifdef DEPTHPREPASS +gl_FragColor=vec4(0.,0.,0.,1.0);return; +#endif +`;nw.v.IncludesShadersStore.depthPrePass=o9;let le=`#ifdef LIGHT{X} +#if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) +#else +#ifdef PBR +#ifdef SPOTLIGHT{X} +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(POINTLIGHT{X}) +preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(HEMILIGHT{X}) +preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#elif defined(DIRLIGHT{X}) +preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); +#endif +preInfo.NdotV=NdotV; +#ifdef SPOTLIGHT{X} +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared);preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x);preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); +#endif +#elif defined(POINTLIGHT{X}) +#ifdef LIGHT_FALLOFF_GLTF{X} +preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); +#elif defined(LIGHT_FALLOFF_PHYSICAL{X}) +preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); +#elif defined(LIGHT_FALLOFF_STANDARD{X}) +preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); +#else +preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); +#endif +#else +preInfo.attenuation=1.0; +#endif +#ifdef HEMILIGHT{X} +preInfo.roughness=roughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#ifdef IRIDESCENCE +preInfo.iridescenceIntensity=iridescenceIntensity; +#endif +#ifdef HEMILIGHT{X} +info.diffuse=computeHemisphericDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb,light{X}.vLightGround); +#elif defined(SS_TRANSLUCENCY) +info.diffuse=computeDiffuseAndTransmittedLighting(preInfo,light{X}.vLightDiffuse.rgb,subSurfaceOut.transmittance); +#else +info.diffuse=computeDiffuseLighting(preInfo,light{X}.vLightDiffuse.rgb); +#endif +#ifdef SPECULARTERM +#ifdef ANISOTROPIC +info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#else +info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#endif +#endif +#ifdef SHEEN +#ifdef SHEEN_LINKWITHALBEDO +preInfo.roughness=sheenOut.sheenIntensity; +#else +#ifdef HEMILIGHT{X} +preInfo.roughness=sheenOut.sheenRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +#endif +info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,light{X}.vLightDiffuse.rgb); +#endif +#ifdef CLEARCOAT +#ifdef HEMILIGHT{X} +preInfo.roughness=clearcoatOut.clearCoatRoughness; +#else +preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); +#endif +info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,light{X}.vLightDiffuse.rgb); +#ifdef CLEARCOAT_TINT +absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; +#ifdef SPECULARTERM +info.specular*=absorption; +#endif +#endif +info.diffuse*=info.clearCoat.w; +#ifdef SPECULARTERM +info.specular*=info.clearCoat.w; +#endif +#ifdef SHEEN +info.sheen*=info.clearCoat.w; +#endif +#endif +#else +#ifdef SPOTLIGHT{X} +info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); +#elif defined(HEMILIGHT{X}) +info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); +#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) +info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightDiffuse.a,glossiness); +#endif +#endif +#ifdef PROJECTEDLIGHTTEXTURE{X} +info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X}); +#endif +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +for (int i=0; i=0.) {index{X}=i;break;}} +#ifdef SHADOWCSMUSESHADOWMAXZ{X} +if (index{X}>=0) +#endif +{ +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; +#endif +#ifndef SHADOWCSMNOBLEND{X} +float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) +{index{X}+=1;float nextShadow=0.; +#if defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#elif defined(SHADOWMEDIUMQUALITY{X}) +nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#else +nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); +#endif +#else +nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +shadow=mix(nextShadow,shadow,diffRatio); +#ifdef SHADOWCSMDEBUG{X} +shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); +#endif +} +#endif +} +#elif defined(SHADOWCLOSEESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWESM{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); +#else +shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPOISSON{X}) +#if defined(SHADOWCUBE{X}) +shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCF{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#elif defined(SHADOWPCSS{X}) +#if defined(SHADOWLOWQUALITY{X}) +shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#elif defined(SHADOWMEDIUMQUALITY{X}) +shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#else +shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#else +#if defined(SHADOWCUBE{X}) +shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues); +#else +shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); +#endif +#endif +#ifdef SHADOWONLY +#ifndef SHADOWINUSE +#define SHADOWINUSE +#endif +globalShadow+=shadow;shadowLightCount+=1.0; +#endif +#else +shadow=1.; +#endif +aggShadow+=shadow;numLights+=1.0; +#ifndef SHADOWONLY +#ifdef CUSTOMUSERLIGHTING +diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); +#ifdef SPECULARTERM +specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); +#endif +#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) +diffuseBase+=lightmapColor.rgb*shadow; +#ifdef SPECULARTERM +#ifndef LIGHTMAPNOSPECULAR{X} +specularBase+=info.specular*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef CLEARCOAT +#ifndef LIGHTMAPNOSPECULAR{X} +clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; +#endif +#endif +#ifdef SHEEN +#ifndef LIGHTMAPNOSPECULAR{X} +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#else +#ifdef SHADOWCSMDEBUG{X} +diffuseBase+=info.diffuse*shadowDebug{X}; +#else +diffuseBase+=info.diffuse*shadow; +#endif +#ifdef SPECULARTERM +specularBase+=info.specular*shadow; +#endif +#ifdef CLEARCOAT +clearCoatBase+=info.clearCoat.rgb*shadow; +#endif +#ifdef SHEEN +sheenBase+=info.sheen.rgb*shadow; +#endif +#endif +#endif +#endif +`;nw.v.IncludesShadersStore.lightFragment=le;let lt=`#ifdef LOGARITHMICDEPTH +gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; +#endif +`;nw.v.IncludesShadersStore.logDepthFragment=lt;let li=`#ifdef FOG +float fog=CalcFogFactor(); +#ifdef PBR +fog=toLinearSpace(fog); +#endif +color.rgb=mix(vFogColor,color.rgb,fog); +#endif +`;nw.v.IncludesShadersStore.fogFragment=li;let lr=`#ifdef ORDER_INDEPENDENT_TRANSPARENCY +float fragDepth=gl_FragCoord.z; +#ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS +uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; +#endif +ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); +#ifdef USE_REVERSE_DEPTHBUFFER +float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; +#else +float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; +#endif +float alphaMultiplier=1.0-lastFrontColor.a; +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepth>nearestDepth || fragDepthfurthestDepth) { +#endif +return;} +#ifdef USE_REVERSE_DEPTHBUFFER +if (fragDepthfurthestDepth) { +#else +if (fragDepth>nearestDepth && fragDepth +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +#include[SCENE_MRT_COUNT] +#include +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include[1..7] +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef REFRACTION +#ifdef REFRACTIONMAP_3D +uniform samplerCube refractionCubeSampler; +#else +uniform sampler2D refraction2DSampler; +#endif +#endif +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) +#endif +#include +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +uniform samplerCube reflectionCubeSampler; +#else +uniform sampler2D reflection2DSampler; +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); +#endif +#include +#ifdef TWOSIDEDLIGHTING +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +#ifdef DIFFUSE +baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); +#if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) +if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +baseColor.rgb*=vColor.rgb; +#endif +#ifdef DETAIL +baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); +#endif +#if defined(DECAL) && defined(DECAL_AFTER_DETAIL) +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) +#endif +#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE +vec3 baseAmbientColor=vec3(1.,1.,1.); +#ifdef AMBIENT +baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; +#endif +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +#ifdef SPECULARTERM +float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; +#ifdef SPECULAR +vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; +#ifdef GLOSSINESS +glossiness=glossiness*specularMapColor.a; +#endif +#endif +#else +float glossiness=0.; +#endif +vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +float shadow=1.;float aggShadow=0.;float numLights=0.; +#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +#include[0..maxSimultaneousLights] +aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); +#ifdef REFRACTION +vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); +#ifdef REFRACTIONMAP_3D +#ifdef USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); +#endif +#ifdef RGBDREFRACTION +refractionColor.rgb=fromRGBD(refractionColor); +#endif +#ifdef IS_REFRACTION_LINEAR +refractionColor.rgb=toGammaSpace(refractionColor.rgb); +#endif +refractionColor.rgb*=vRefractionInfos.x; +#endif +vec4 reflectionColor=vec4(0.,0.,0.,1.); +#ifdef REFLECTION +vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +vReflectionUVW.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +#ifdef ROUGHNESS +float bias=vReflectionInfos.y; +#ifdef SPECULARTERM +#ifdef SPECULAR +#ifdef GLOSSINESS +bias*=(1.0-specularMapColor.a); +#endif +#endif +#endif +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); +#else +reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); +#endif +#else +vec2 coords=vReflectionUVW.xy; +#ifdef REFLECTIONMAP_PROJECTION +coords/=vReflectionUVW.z; +#endif +coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef IS_REFLECTION_LINEAR +reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#ifdef REFLECTIONFRESNEL +float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); +#ifdef REFLECTIONFRESNELFROMSPECULAR +#ifdef SPECULARTERM +reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#else +reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; +#endif +#endif +#endif +#ifdef REFRACTIONFRESNEL +float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#ifdef OPACITYRGB +opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; +#else +alpha*=opacityMap.a*vOpacityInfos.y; +#endif +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#ifdef OPACITYFRESNEL +float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; +#endif +#ifdef ALPHATEST +#ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS +if (alpha +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +color.rgb=toLinearSpace(color.rgb); +#else +#ifdef IMAGEPROCESSING +color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); +#endif +#endif +color.a*=visibility; +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0;gl_FragData[0]=color; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_IRRADIANCE +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#if defined(SPECULARTERM) +#if defined(SPECULAR) +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; +#endif +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(0.0,0.0,0.0,1.0)*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=color; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} +#endif +#define CUSTOM_FRAGMENT_MAIN_END +} +`;nw.v.ShadersStore.defaultPixelShader=ls;let ln=`#ifdef DECAL +uniform vec4 vDecalInfos;uniform mat4 decalMatrix; +#endif +`;nw.v.IncludesShadersStore.decalVertexDeclaration=ln;let la=`uniform mat4 viewProjection;uniform mat4 view; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#if defined(SPECULAR) && defined(SPECULARTERM) +uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef REFLECTION +uniform mat4 reflectionMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include +#define ADDITIONAL_VERTEX_DECLARATION +`;nw.v.IncludesShadersStore.defaultVertexDeclaration=la;let lo=`#ifdef UV{X} +attribute vec2 uv{X}; +#endif +`;nw.v.IncludesShadersStore.uvAttributeDeclaration=lo;let ll=`#if NUM_BONE_INFLUENCERS>0 +attribute vec4 matricesIndices;attribute vec4 matricesWeights; +#if NUM_BONE_INFLUENCERS>4 +attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +uniform highp sampler2D boneSampler;uniform float boneTextureWidth; +#else +uniform mat4 mBones[BonesPerMesh]; +#endif +#ifdef BONES_VELOCITY_ENABLED +uniform mat4 mPreviousBones[BonesPerMesh]; +#endif +#ifdef BONETEXTURE +#define inline +mat4 readMatrixFromRawSampler(sampler2D smp,float index) +{float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} +#endif +#endif +#endif +`;nw.v.IncludesShadersStore.bonesDeclaration=ll;let lh=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; +#ifdef INSTANCES +attribute vec4 bakedVertexAnimationSettingsInstanced; +#endif +#define inline +mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) +{float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} +#endif +`;nw.v.IncludesShadersStore.bakedVertexAnimationDeclaration=lh;let lu=`#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#ifdef INSTANCESCOLOR +attribute vec4 instanceColor; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; +#ifdef THIN_INSTANCES +uniform mat4 previousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform mat4 world; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform mat4 previousWorld; +#endif +#endif +`;nw.v.IncludesShadersStore.instancesDeclaration=lu;let lc=`#ifdef PREPASS +#ifdef PREPASS_DEPTH +varying vec3 vViewPos; +#endif +#ifdef PREPASS_VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#endif +`;nw.v.IncludesShadersStore.prePassVertexDeclaration=lc;let ld=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +varying vec2 v_VARYINGNAME_UV; +#endif +`;nw.v.IncludesShadersStore.samplerVertexDeclaration=ld;let lp=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +varying mat3 vTBN; +#endif +#endif +`;nw.v.IncludesShadersStore.bumpVertexDeclaration=lp;let l_=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;varying float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;varying float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;varying float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;varying float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;varying float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;varying float fClipDistance6; +#endif +`;nw.v.IncludesShadersStore.clipPlaneVertexDeclaration=l_;let lf=`#ifdef FOG +varying vec3 vFogDistance; +#endif +`;nw.v.IncludesShadersStore.fogVertexDeclaration=lf;let lm=`#ifdef LIGHT{X} +uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; +#ifdef SPECULARTERM +uniform vec4 vLightSpecular{X}; +#else +vec4 vLightSpecular{X}=vec4(0.); +#endif +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; +#endif +#ifdef SPOTLIGHT{X} +uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; +#elif defined(POINTLIGHT{X}) +uniform vec4 vLightFalloff{X}; +#elif defined(HEMILIGHT{X}) +uniform vec3 vLightGround{X}; +#endif +#endif +`;nw.v.IncludesShadersStore.lightVxFragmentDeclaration=lm;let lg=`#ifdef LIGHT{X} +uniform Light{X} +{vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; +#ifdef SPOTLIGHT{X} +vec4 vLightDirection;vec4 vLightFalloff; +#elif defined(POINTLIGHT{X}) +vec4 vLightFalloff; +#elif defined(HEMILIGHT{X}) +vec3 vLightGround; +#endif +vec4 shadowsInfo;vec2 depthValues;} light{X}; +#ifdef SHADOW{X} +#ifdef SHADOWCSM{X} +uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; +#elif defined(SHADOWCUBE{X}) +#else +varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; +#endif +#endif +#endif +`;nw.v.IncludesShadersStore.lightVxUboDeclaration=lg;let lv=`#ifdef MORPHTARGETS +uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; +#ifdef MORPHTARGETS_TEXTURE +uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) +{ +float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} +#endif +#endif +`;nw.v.IncludesShadersStore.morphTargetsVertexGlobalDeclaration=lv;let lx=`#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +attribute vec3 position{X}; +#ifdef MORPHTARGETS_NORMAL +attribute vec3 normal{X}; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute vec3 tangent{X}; +#endif +#ifdef MORPHTARGETS_UV +attribute vec2 uv_{X}; +#endif +#endif +#endif +`;nw.v.IncludesShadersStore.morphTargetsVertexDeclaration=lx;let lT=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +float vertexID; +#endif +#endif +`;nw.v.IncludesShadersStore.morphTargetsVertexGlobal=lT;let lS=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=float(gl_VertexID)*morphTargetTextureInfo.x;positionUpdated+=(readVector3FromRawSampler({X},vertexID)-position)*morphTargetInfluences[{X}];vertexID+=1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(readVector3FromRawSampler({X},vertexID) -normal)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(readVector3FromRawSampler({X},vertexID).xy-uv)*morphTargetInfluences[{X}];vertexID+=1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(readVector3FromRawSampler({X},vertexID) -tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#else +positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;nw.v.IncludesShadersStore.morphTargetsVertex=lS;let lE=`#ifdef INSTANCES +mat4 finalWorld=mat4(world0,world1,world2,world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +finalWorld=world*finalWorld; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +mat4 finalWorld=world; +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +mat4 finalPreviousWorld=previousWorld; +#endif +#endif +`;nw.v.IncludesShadersStore.instancesVertex=lE;let lC=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +mat4 influence; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; +#endif +#else +influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`;nw.v.IncludesShadersStore.bonesVertex=lC;let lb=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +#define BVASNAME bakedVertexAnimationSettingsInstanced +#else +#define BVASNAME bakedVertexAnimationSettings +#endif +float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`;nw.v.IncludesShadersStore.bakedVertexAnimation=lb;let ly=`#ifdef PREPASS_DEPTH +vViewPos=(view*worldPos).rgb; +#endif +#if defined(PREPASS_VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*worldPos; +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +`;nw.v.IncludesShadersStore.prePassVertex=ly;let lA=`#if !defined(UV{X}) && defined(MAINUV{X}) +vec2 uv{X}=vec2(0.,0.); +#endif +#ifdef MAINUV{X} +vMainUV{X}=uv{X}; +#endif +`;nw.v.IncludesShadersStore.uvVariableDeclaration=lA;let lR=`#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 +if (v_INFONAME_==0.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} +#ifdef UV2 +else if (v_INFONAME_==1.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2,1.0,0.0));} +#endif +#ifdef UV3 +else if (v_INFONAME_==2.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} +#endif +#ifdef UV4 +else if (v_INFONAME_==3.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} +#endif +#ifdef UV5 +else if (v_INFONAME_==4.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} +#endif +#ifdef UV6 +else if (v_INFONAME_==5.) +{v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} +#endif +#endif +`;nw.v.IncludesShadersStore.samplerVertexImplementation=lR;let lP=`#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#if defined(TANGENT) && defined(NORMAL) +vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); +#endif +#endif +`;nw.v.IncludesShadersStore.bumpVertex=lP;let lI=`#ifdef CLIPPLANE +fClipDistance=dot(worldPos,vClipPlane); +#endif +#ifdef CLIPPLANE2 +fClipDistance2=dot(worldPos,vClipPlane2); +#endif +#ifdef CLIPPLANE3 +fClipDistance3=dot(worldPos,vClipPlane3); +#endif +#ifdef CLIPPLANE4 +fClipDistance4=dot(worldPos,vClipPlane4); +#endif +#ifdef CLIPPLANE5 +fClipDistance5=dot(worldPos,vClipPlane5); +#endif +#ifdef CLIPPLANE6 +fClipDistance6=dot(worldPos,vClipPlane6); +#endif +`;nw.v.IncludesShadersStore.clipPlaneVertex=lI;let lM=`#ifdef FOG +vFogDistance=(view*worldPos).xyz; +#endif +`;nw.v.IncludesShadersStore.fogVertex=lM;let lD=`#ifdef SHADOWS +#if defined(SHADOWCSM{X}) +vPositionFromCamera{X}=view*worldPos;for (int i=0; i +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include[2..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#include +#include[1..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +vPositionW=vec3(worldPos); +#include +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include[2..7] +#include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#if defined(SPECULARTERM) +#include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) +#endif +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#include +#include +#define CUSTOM_VERTEX_MAIN_END +} +`;nw.v.ShadersStore.defaultVertexShader=lL;var lw=i(7790);let lB=RegExp("^([gimus]+)!");class lU{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;tthis._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort((e,t)=>e.priority-t.priority),this._codeInjectionPoints={};let i={};for(let e of(i[lU._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0},this._plugins))e.collectDefines(i),this._collectPointNames("vertex",e.getCustomCode("vertex")),this._collectPointNames("fragment",e.getCustomCode("fragment"));return this._defineNamesFromPlugins=i,!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;t0&&t.uniforms.push(...this._uniformList),this._samplerList.length>0&&t.samplers.push(...this._samplerList),this._uboList.length>0&&t.uniformBuffersNames.push(...this._uboList),t.customCode=this._injectCustomCode(t,t.customCode);break;case oL.S.PrepareUniformBuffer:for(let e of(this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[],this._plugins)){let r=e.getUniforms();if(r){if(r.ubo)for(let e of r.ubo){if(e.size&&e.type){let r=null!==(i=e.arraySize)&&void 0!==i?i:0;t.ubo.addUniform(e.name,e.size,r),this._uboDeclaration+=`${e.type} ${e.name}${r>0?`[${r}]`:""}; +`}this._uniformList.push(e.name)}r.vertex&&(this._vertexDeclaration+=r.vertex+"\n"),r.fragment&&(this._fragmentDeclaration+=r.fragment+"\n")}e.getSamplers(this._samplerList),e.getUniformBuffersNames(this._uboList)}}}_collectPointNames(e,t){if(t)for(let i in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][i]=!0}_injectCustomCode(e,t){return(i,r)=>{var s,n;t&&(r=t(i,r)),this._uboDeclaration&&(r=r.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(r=r.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(r=r.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));let a=null===(s=this._codeInjectionPoints)||void 0===s?void 0:s[i];if(!a)return r;let o=null;for(let t in a){let s="";for(let r of this._activePlugins){let a=null===(n=r.getCustomCode(i))||void 0===n?void 0:n[t];if(a){if(r.resolveIncludes){if(null===o){let t=nG.x.GLSL;o={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:nw.v.GetShadersRepository(t),includesShadersStore:nw.v.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}o.isFragment="fragment"===i,lw.L._ProcessIncludes(a,o,e=>a=e)}s+=a+"\n"}}if(s.length>0){if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{let i=lB.exec(t);i&&i.length>=2&&(e=i[1],t=t.substring(e.length+1))}0>e.indexOf("g")&&(e+="g");let i=r,n=new RegExp(t,e),a=n.exec(i);for(;null!==a;){let e=s;for(let t=0;t{lV.length=0,nu.F.OnEventObservable.remove(lk),lk=null});let lV=[],lk=null;class lG{_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,i,r,s=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=i,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new lU(e),e.onDisposeObservable.add(()=>{e.pluginManager=void 0})),this._pluginDefineNames=r,this._pluginManager=e.pluginManager,s&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[63]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,i,r){return!0}hardBindForSubMesh(e,t,i,r){}bindForSubMesh(e,t,i,r){}dispose(e){}getCustomCode(e){return null}collectDefines(e){if(this._pluginDefineNames)for(let t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;let i=typeof this._pluginDefineNames[t];e[t]={type:"number"===i?"number":"string"===i?"string":"boolean"===i?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,i){}prepareDefines(e,t,i){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,i){return i}getSamplers(e){}getAttributes(e,t,i){}getUniformBuffersNames(e){}getUniforms(){return{}}copyTo(e){rG.p4.Clone(()=>e,this)}serialize(){return rG.p4.Serialize(this)}parse(e,t,i){rG.p4.Parse(()=>this,e,t,i)}}(0,sx.gn)([(0,rG.qC)()],lG.prototype,"name",void 0),(0,sx.gn)([(0,rG.qC)()],lG.prototype,"priority",void 0),(0,sx.gn)([(0,rG.qC)()],lG.prototype,"resolveIncludes",void 0),(0,sx.gn)([(0,rG.qC)()],lG.prototype,"registerForExtraEvents",void 0);class lz extends nf.H{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class lW extends lG{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DetailMap",140,new lz,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=nu.F.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||!i.getCaps().standardDerivatives||!this._texture||!ow.DetailTextureEnabled||!!this._texture.isReady()}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;let i=t.getEngine();e._areTexturesDirty&&(i.getCaps().standardDerivatives&&this._texture&&ow.DetailTextureEnabled&&this._isEnabled?(nE.G.PrepareDefinesForMergedUV(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||!this._texture||!ow.DetailTextureEnabled||(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),nE.G.BindTextureMatrix(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&ow.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){var t;e&&(null===(t=this._texture)||void 0===t||t.dispose())}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}(0,sx.gn)([(0,rG.oU)("detailTexture"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lW.prototype,"texture",void 0),(0,sx.gn)([(0,rG.qC)()],lW.prototype,"diffuseBlendLevel",void 0),(0,sx.gn)([(0,rG.qC)()],lW.prototype,"roughnessBlendLevel",void 0),(0,sx.gn)([(0,rG.qC)()],lW.prototype,"bumpLevel",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lW.prototype,"normalBlendMethod",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lW.prototype,"isEnabled",void 0);var lH=i(6962);let lX={effect:null,subMesh:null};class lY extends nf.H{constructor(e){super(e),this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.OPACITY=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.REFLECTION=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.SPECULAR=!1,this.SPECULARDIRECTUV=0,this.BUMP=!1,this.BUMPDIRECTUV=0,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.SPECULAROVERALPHA=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHAFROMDIFFUSE=!1,this.POINTSIZE=!1,this.FOG=!1,this.SPECULARTERM=!1,this.DIFFUSEFRESNEL=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONFRESNEL=!1,this.REFRACTIONFRESNEL=!1,this.EMISSIVEFRESNEL=!1,this.FRESNEL=!1,this.NORMAL=!1,this.TANGENT=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.GLOSSINESS=!1,this.ROUGHNESS=!1,this.EMISSIVEASILLUMINATION=!1,this.LINKEMISSIVEWITHDIFFUSE=!1,this.REFLECTIONFRESNELFROMSPECULAR=!1,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.USELIGHTMAPASSHADOWMAP=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFRACTIONMAP_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.REFLECTIONMAP_OPPOSITEZ=!1,this.INVERTCUBICMAP=!1,this.LOGARITHMICDEPTH=!1,this.REFRACTION=!1,this.REFRACTIONMAP_3D=!1,this.REFLECTIONOVERALPHA=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!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.NONUNIFORMSCALING=!1,this.PREMULTIPLYALPHA=!1,this.ALPHATEST_AFTERALLALPHACOMPUTATIONS=!1,this.ALPHABLEND=!0,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_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.RGBDLIGHTMAP=!1,this.RGBDREFLECTION=!1,this.RGBDREFRACTION=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.IS_REFLECTION_LINEAR=!1,this.IS_REFRACTION_LINEAR=!1,this.EXPOSURE=!1,this.DECAL_AFTER_DETAIL=!1,this.rebuild()}setReflectionMode(e){for(let t of["REFLECTIONMAP_CUBIC","REFLECTIONMAP_EXPLICIT","REFLECTIONMAP_PLANAR","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_PROJECTION","REFLECTIONMAP_SKYBOX","REFLECTIONMAP_SPHERICAL","REFLECTIONMAP_EQUIRECTANGULAR","REFLECTIONMAP_EQUIRECTANGULAR_FIXED","REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"])this[t]=t===e}}class lj extends nc{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}get isPrePassCapable(){return!this.disableDepthWrite}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}get canRenderToMRT(){return!0}constructor(e,t){super(e,t),this._diffuseTexture=null,this._ambientTexture=null,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._specularTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._refractionTexture=null,this.ambientColor=new rm.Wo(0,0,0),this.diffuseColor=new rm.Wo(1,1,1),this.specularColor=new rm.Wo(1,1,1),this.emissiveColor=new rm.Wo(0,0,0),this.specularPower=64,this._useAlphaFromDiffuseTexture=!1,this._useEmissiveAsIllumination=!1,this._linkEmissiveWithDiffuse=!1,this._useSpecularOverAlpha=!1,this._useReflectionOverAlpha=!1,this._disableLighting=!1,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this._roughness=0,this.indexOfRefraction=.98,this.invertRefractionY=!0,this.alphaCutOff=.4,this._useLightmapAsShadowmap=!1,this._useReflectionFresnelFromSpecular=!1,this._useGlossinessFromSpecularMapAlpha=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._applyDecalMapAfterDetailMap=!1,this._renderTargets=new nL.t(16),this._worldViewProjectionMatrix=rf.y3.Zero(),this._globalAmbientColor=new rm.Wo(0,0,0),this._cacheHasRenderTargetTextures=!1,this.detailMap=new lW(this),this._attachImageProcessingConfiguration(null),this.prePassConfiguration=new oF,this.getRenderTargetTextures=()=>(this._renderTargets.reset(),lj.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),lj.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&this._renderTargets.push(this._refractionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets)}get hasRenderTargetTextures(){return!!lj.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||!!lj.RefractionTextureEnabled&&!!this._refractionTexture&&!!this._refractionTexture.isRenderTarget||this._cacheHasRenderTargetTextures}getClassName(){return"StandardMaterial"}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromDiffuseTexture()||this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled)}needAlphaTesting(){return!!this._forceAlphaTest||this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===nu.F.MATERIAL_ALPHATEST)}_shouldUseAlphaFromDiffuseTexture(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha&&this._useAlphaFromDiffuseTexture&&this._transparencyMode!==nu.F.MATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._diffuseTexture}isReadyForSubMesh(e,t,i=!1){if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(oL.S.GetDefineNames,this._eventInfo),t.materialDefines=new lY(this._eventInfo.defineNames));let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();s._needNormals=nE.G.PrepareDefinesForLights(r,e,s,!0,this._maxSimultaneousLights,this._disableLighting),nE.G.PrepareDefinesForMultiview(r,s);let a=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(nE.G.PrepareDefinesForPrePass(r,s,this.canRenderToMRT&&!a),nE.G.PrepareDefinesForOIT(r,s,a),s._areTexturesDirty){this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,s._needUVs=!1;for(let e=1;e<=6;++e)s["MAINUV"+e]=!1;if(r.texturesEnabled){if(s.DIFFUSEDIRECTUV=0,s.BUMPDIRECTUV=0,s.AMBIENTDIRECTUV=0,s.OPACITYDIRECTUV=0,s.EMISSIVEDIRECTUV=0,s.SPECULARDIRECTUV=0,s.LIGHTMAPDIRECTUV=0,this._diffuseTexture&&lj.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;nE.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE")}else s.DIFFUSE=!1;if(this._ambientTexture&&lj.AmbientTextureEnabled){if(!this._ambientTexture.isReadyOrNotBlocking())return!1;nE.G.PrepareDefinesForMergedUV(this._ambientTexture,s,"AMBIENT")}else s.AMBIENT=!1;if(this._opacityTexture&&lj.OpacityTextureEnabled){if(!this._opacityTexture.isReadyOrNotBlocking())return!1;nE.G.PrepareDefinesForMergedUV(this._opacityTexture,s,"OPACITY"),s.OPACITYRGB=this._opacityTexture.getAlphaFromRGB}else s.OPACITY=!1;if(this._reflectionTexture&&lj.ReflectionTextureEnabled){if(!this._reflectionTexture.isReadyOrNotBlocking())return!1;switch(s._needNormals=!0,s.REFLECTION=!0,s.ROUGHNESS=this._roughness>0,s.REFLECTIONOVERALPHA=this._useReflectionOverAlpha,s.INVERTCUBICMAP=this._reflectionTexture.coordinatesMode===sj.INVCUBIC_MODE,s.REFLECTIONMAP_3D=this._reflectionTexture.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!this._reflectionTexture.invertZ:this._reflectionTexture.invertZ,s.RGBDREFLECTION=this._reflectionTexture.isRGBD,this._reflectionTexture.coordinatesMode){case sj.EXPLICIT_MODE:s.setReflectionMode("REFLECTIONMAP_EXPLICIT");break;case sj.PLANAR_MODE:s.setReflectionMode("REFLECTIONMAP_PLANAR");break;case sj.PROJECTION_MODE:s.setReflectionMode("REFLECTIONMAP_PROJECTION");break;case sj.SKYBOX_MODE:s.setReflectionMode("REFLECTIONMAP_SKYBOX");break;case sj.SPHERICAL_MODE:s.setReflectionMode("REFLECTIONMAP_SPHERICAL");break;case sj.EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");break;case sj.FIXED_EQUIRECTANGULAR_MODE:s.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");break;case sj.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");break;case sj.CUBIC_MODE:case sj.INVCUBIC_MODE:default:s.setReflectionMode("REFLECTIONMAP_CUBIC")}s.USE_LOCAL_REFLECTIONMAP_CUBIC=!!this._reflectionTexture.boundingBoxSize}else s.REFLECTION=!1,s.REFLECTIONMAP_OPPOSITEZ=!1;if(this._emissiveTexture&&lj.EmissiveTextureEnabled){if(!this._emissiveTexture.isReadyOrNotBlocking())return!1;nE.G.PrepareDefinesForMergedUV(this._emissiveTexture,s,"EMISSIVE")}else s.EMISSIVE=!1;if(this._lightmapTexture&&lj.LightmapTextureEnabled){if(!this._lightmapTexture.isReadyOrNotBlocking())return!1;nE.G.PrepareDefinesForMergedUV(this._lightmapTexture,s,"LIGHTMAP"),s.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,s.RGBDLIGHTMAP=this._lightmapTexture.isRGBD}else s.LIGHTMAP=!1;if(this._specularTexture&&lj.SpecularTextureEnabled){if(!this._specularTexture.isReadyOrNotBlocking())return!1;nE.G.PrepareDefinesForMergedUV(this._specularTexture,s,"SPECULAR"),s.GLOSSINESS=this._useGlossinessFromSpecularMapAlpha}else s.SPECULAR=!1;if(r.getEngine().getCaps().standardDerivatives&&this._bumpTexture&&lj.BumpTextureEnabled){if(!this._bumpTexture.isReady())return!1;nE.G.PrepareDefinesForMergedUV(this._bumpTexture,s,"BUMP"),s.PARALLAX=this._useParallax,s.PARALLAX_RHS=r.useRightHandedSystem,s.PARALLAXOCCLUSION=this._useParallaxOcclusion,s.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap}else s.BUMP=!1,s.PARALLAX=!1,s.PARALLAX_RHS=!1,s.PARALLAXOCCLUSION=!1;if(this._refractionTexture&&lj.RefractionTextureEnabled){if(!this._refractionTexture.isReadyOrNotBlocking())return!1;s._needUVs=!0,s.REFRACTION=!0,s.REFRACTIONMAP_3D=this._refractionTexture.isCube,s.RGBDREFRACTION=this._refractionTexture.isRGBD,s.USE_LOCAL_REFRACTIONMAP_CUBIC=!!this._refractionTexture.boundingBoxSize}else s.REFRACTION=!1;s.TWOSIDEDLIGHTING=!this._backFaceCulling&&this._twoSidedLighting}else s.DIFFUSE=!1,s.AMBIENT=!1,s.OPACITY=!1,s.REFLECTION=!1,s.EMISSIVE=!1,s.LIGHTMAP=!1,s.BUMP=!1,s.REFRACTION=!1;s.ALPHAFROMDIFFUSE=this._shouldUseAlphaFromDiffuseTexture(),s.EMISSIVEASILLUMINATION=this._useEmissiveAsIllumination,s.LINKEMISSIVEWITHDIFFUSE=this._linkEmissiveWithDiffuse,s.SPECULAROVERALPHA=this._useSpecularOverAlpha,s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.ALPHATEST_AFTERALLALPHACOMPUTATIONS=null!==this.transparencyMode,s.ALPHABLEND=null===this.transparencyMode||this.needAlphaBlendingForMesh(e)}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s),s.IS_REFLECTION_LINEAR=null!=this.reflectionTexture&&!this.reflectionTexture.gammaSpace,s.IS_REFRACTION_LINEAR=null!=this.refractionTexture&&!this.refractionTexture.gammaSpace}s._areFresnelDirty&&(lj.FresnelEnabled?(this._diffuseFresnelParameters||this._opacityFresnelParameters||this._emissiveFresnelParameters||this._refractionFresnelParameters||this._reflectionFresnelParameters)&&(s.DIFFUSEFRESNEL=this._diffuseFresnelParameters&&this._diffuseFresnelParameters.isEnabled,s.OPACITYFRESNEL=this._opacityFresnelParameters&&this._opacityFresnelParameters.isEnabled,s.REFLECTIONFRESNEL=this._reflectionFresnelParameters&&this._reflectionFresnelParameters.isEnabled,s.REFLECTIONFRESNELFROMSPECULAR=this._useReflectionFresnelFromSpecular,s.REFRACTIONFRESNEL=this._refractionFresnelParameters&&this._refractionFresnelParameters.isEnabled,s.EMISSIVEFRESNEL=this._emissiveFresnelParameters&&this._emissiveFresnelParameters.isEnabled,s._needNormals=!0,s.FRESNEL=!0):s.FRESNEL=!1),nE.G.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,s,this._applyDecalMapAfterDetailMap),nE.G.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),this._eventInfo.defines=s,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),nE.G.PrepareDefinesForAttributes(e,s,!0,!0,!0),this._callbackPluginEventPrepareDefines(this._eventInfo);let o=!1;if(s.isDirty){let i=s._areLightsDisposed;s.markAsProcessed();let a=new nF;s.REFLECTION&&a.addFallback(0,"REFLECTION"),s.SPECULAR&&a.addFallback(0,"SPECULAR"),s.BUMP&&a.addFallback(0,"BUMP"),s.PARALLAX&&a.addFallback(1,"PARALLAX"),s.PARALLAX_RHS&&a.addFallback(1,"PARALLAX_RHS"),s.PARALLAXOCCLUSION&&a.addFallback(0,"PARALLAXOCCLUSION"),s.SPECULAROVERALPHA&&a.addFallback(0,"SPECULAROVERALPHA"),s.FOG&&a.addFallback(1,"FOG"),s.POINTSIZE&&a.addFallback(0,"POINTSIZE"),s.LOGARITHMICDEPTH&&a.addFallback(0,"LOGARITHMICDEPTH"),nE.G.HandleFallbacksForShadows(s,a,this._maxSimultaneousLights),s.SPECULARTERM&&a.addFallback(0,"SPECULARTERM"),s.DIFFUSEFRESNEL&&a.addFallback(1,"DIFFUSEFRESNEL"),s.OPACITYFRESNEL&&a.addFallback(2,"OPACITYFRESNEL"),s.REFLECTIONFRESNEL&&a.addFallback(3,"REFLECTIONFRESNEL"),s.EMISSIVEFRESNEL&&a.addFallback(4,"EMISSIVEFRESNEL"),s.FRESNEL&&a.addFallback(4,"FRESNEL"),s.MULTIVIEW&&a.addFallback(0,"MULTIVIEW");let l=[sm.o.PositionKind];s.NORMAL&&l.push(sm.o.NormalKind),s.TANGENT&&l.push(sm.o.TangentKind);for(let e=1;e<=6;++e)s["UV"+e]&&l.push(`uv${1===e?"":e}`);s.VERTEXCOLOR&&l.push(sm.o.ColorKind),nE.G.PrepareAttributesForBones(l,e,s,a),nE.G.PrepareAttributesForInstances(l,s),nE.G.PrepareAttributesForMorphTargets(l,e,s),nE.G.PrepareAttributesForBakedVertexAnimation(l,e,s);let h="default",u=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vDiffuseColor","vSpecularColor","vEmissiveColor","visibility","vFogInfos","vFogColor","pointSize","vDiffuseInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vEmissiveInfos","vSpecularInfos","vBumpInfos","vLightmapInfos","vRefractionInfos","mBones","diffuseMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","specularMatrix","bumpMatrix","normalMatrix","lightmapMatrix","refractionMatrix","diffuseLeftColor","diffuseRightColor","opacityParts","reflectionLeftColor","reflectionRightColor","emissiveLeftColor","emissiveRightColor","refractionLeftColor","refractionRightColor","vReflectionPosition","vReflectionSize","vRefractionPosition","vRefractionSize","logarithmicDepthConstant","vTangentSpaceParams","alphaCutOff","boneTextureWidth","morphTargetTextureInfo","morphTargetTextureIndices"],c=["diffuseSampler","ambientSampler","opacitySampler","reflectionCubeSampler","reflection2DSampler","emissiveSampler","specularSampler","bumpSampler","lightmapSampler","refractionCubeSampler","refraction2DSampler","boneSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],d=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:s.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=a,this._eventInfo.fallbackRank=0,this._eventInfo.defines=s,this._eventInfo.uniforms=u,this._eventInfo.attributes=l,this._eventInfo.samplers=c,this._eventInfo.uniformBuffersNames=d,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(oL.S.PrepareEffect,this._eventInfo),oF.AddUniforms(u),oF.AddSamplers(c),nY.$&&(nY.$.PrepareUniforms(u,s),nY.$.PrepareSamplers(c,s)),nE.G.PrepareUniformsAndSamplersList({uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:s,maxSimultaneousLights:this._maxSimultaneousLights}),(0,lH.qx)(u);let _={};this.customShaderNameResolve&&(h=this.customShaderNameResolve(h,u,d,c,s,l,_));let f=s.toString(),m=t.effect,g=r.getEngine().createEffect(h,{attributes:l,uniformsNames:u,uniformBuffersNames:d,samplers:c,defines:f,fallbacks:a,onCompiled:this.onCompiled,onError:this.onError,indexParameters:p,processFinalCode:_.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:s.PREPASS},n);if(this._eventInfo.customCode=void 0,g){if(this._onEffectCreatedObservable&&(lX.effect=g,lX.subMesh=t,this._onEffectCreatedObservable.notifyObservers(lX)),this.allowShaderHotSwapping&&m&&!g.isReady()){if(g=m,s.markAsUnprocessed(),o=this.isFrozen,i)return s._areLightsDisposed=!0,!1}else r.resetCachedMaterial(),t.setEffect(g,s,this._materialContext)}}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!o,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}buildUniformLayout(){let e=this._uniformBuffer;e.addUniform("diffuseLeftColor",4),e.addUniform("diffuseRightColor",4),e.addUniform("opacityParts",4),e.addUniform("reflectionLeftColor",4),e.addUniform("reflectionRightColor",4),e.addUniform("refractionLeftColor",4),e.addUniform("refractionRightColor",4),e.addUniform("emissiveLeftColor",4),e.addUniform("emissiveRightColor",4),e.addUniform("vDiffuseInfos",2),e.addUniform("vAmbientInfos",2),e.addUniform("vOpacityInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vSpecularInfos",2),e.addUniform("vBumpInfos",3),e.addUniform("diffuseMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("reflectionMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("specularMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("pointSize",1),e.addUniform("alphaCutOff",1),e.addUniform("refractionMatrix",16),e.addUniform("vRefractionInfos",4),e.addUniform("vRefractionPosition",3),e.addUniform("vRefractionSize",3),e.addUniform("vSpecularColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vDiffuseColor",4),e.addUniform("vAmbientColor",3),super.buildUniformLayout()}bindForSubMesh(e,t,i){var r;let s=this.getScene(),n=i.materialDefines;if(!n)return;let a=i.effect;if(!a)return;this._activeEffect=a,t.getMeshUniformBuffer().bindToEffect(a,"Mesh"),t.transferToEffect(e),this._uniformBuffer.bindToEffect(a,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,s,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),n.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let o=a._forceRebindOnNextCall||this._mustRebind(s,a,t.visibility);nE.G.BindBonesParameters(t,a);let l=this._uniformBuffer;if(o){if(this.bindViewProjection(a),!l.useUbo||!this.isFrozen||!l.isSync||a._forceRebindOnNextCall){if(lj.FresnelEnabled&&n.FRESNEL&&(this.diffuseFresnelParameters&&this.diffuseFresnelParameters.isEnabled&&(l.updateColor4("diffuseLeftColor",this.diffuseFresnelParameters.leftColor,this.diffuseFresnelParameters.power),l.updateColor4("diffuseRightColor",this.diffuseFresnelParameters.rightColor,this.diffuseFresnelParameters.bias)),this.opacityFresnelParameters&&this.opacityFresnelParameters.isEnabled&&l.updateColor4("opacityParts",new rm.Wo(this.opacityFresnelParameters.leftColor.toLuminance(),this.opacityFresnelParameters.rightColor.toLuminance(),this.opacityFresnelParameters.bias),this.opacityFresnelParameters.power),this.reflectionFresnelParameters&&this.reflectionFresnelParameters.isEnabled&&(l.updateColor4("reflectionLeftColor",this.reflectionFresnelParameters.leftColor,this.reflectionFresnelParameters.power),l.updateColor4("reflectionRightColor",this.reflectionFresnelParameters.rightColor,this.reflectionFresnelParameters.bias)),this.refractionFresnelParameters&&this.refractionFresnelParameters.isEnabled&&(l.updateColor4("refractionLeftColor",this.refractionFresnelParameters.leftColor,this.refractionFresnelParameters.power),l.updateColor4("refractionRightColor",this.refractionFresnelParameters.rightColor,this.refractionFresnelParameters.bias)),this.emissiveFresnelParameters&&this.emissiveFresnelParameters.isEnabled&&(l.updateColor4("emissiveLeftColor",this.emissiveFresnelParameters.leftColor,this.emissiveFresnelParameters.power),l.updateColor4("emissiveRightColor",this.emissiveFresnelParameters.rightColor,this.emissiveFresnelParameters.bias))),s.texturesEnabled){if(this._diffuseTexture&&lj.DiffuseTextureEnabled&&(l.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),nE.G.BindTextureMatrix(this._diffuseTexture,l,"diffuse")),this._ambientTexture&&lj.AmbientTextureEnabled&&(l.updateFloat2("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level),nE.G.BindTextureMatrix(this._ambientTexture,l,"ambient")),this._opacityTexture&&lj.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),nE.G.BindTextureMatrix(this._opacityTexture,l,"opacity")),this._hasAlphaChannel()&&l.updateFloat("alphaCutOff",this.alphaCutOff),this._reflectionTexture&&lj.ReflectionTextureEnabled&&(l.updateFloat2("vReflectionInfos",this._reflectionTexture.level,this.roughness),l.updateMatrix("reflectionMatrix",this._reflectionTexture.getReflectionTextureMatrix()),this._reflectionTexture.boundingBoxSize)){let e=this._reflectionTexture;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this._emissiveTexture&&lj.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),nE.G.BindTextureMatrix(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&lj.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),nE.G.BindTextureMatrix(this._lightmapTexture,l,"lightmap")),this._specularTexture&&lj.SpecularTextureEnabled&&(l.updateFloat2("vSpecularInfos",this._specularTexture.coordinatesIndex,this._specularTexture.level),nE.G.BindTextureMatrix(this._specularTexture,l,"specular")),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&lj.BumpTextureEnabled&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,1/this._bumpTexture.level,this.parallaxScaleBias),nE.G.BindTextureMatrix(this._bumpTexture,l,"bump"),s._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1)),this._refractionTexture&&lj.RefractionTextureEnabled){let e=1;if(!this._refractionTexture.isCube&&(l.updateMatrix("refractionMatrix",this._refractionTexture.getReflectionTextureMatrix()),this._refractionTexture.depth&&(e=this._refractionTexture.depth)),l.updateFloat4("vRefractionInfos",this._refractionTexture.level,this.indexOfRefraction,e,this.invertRefractionY?-1:1),this._refractionTexture.boundingBoxSize){let e=this._refractionTexture;l.updateVector3("vRefractionPosition",e.boundingBoxPosition),l.updateVector3("vRefractionSize",e.boundingBoxSize)}}}this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),n.SPECULARTERM&&l.updateColor4("vSpecularColor",this.specularColor,this.specularPower),l.updateColor3("vEmissiveColor",lj.EmissiveTextureEnabled?this.emissiveColor:rm.Wo.BlackReadOnly),l.updateColor4("vDiffuseColor",this.diffuseColor,this.alpha),s.ambientColor.multiplyToRef(this.ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor)}s.texturesEnabled&&(this._diffuseTexture&&lj.DiffuseTextureEnabled&&a.setTexture("diffuseSampler",this._diffuseTexture),this._ambientTexture&&lj.AmbientTextureEnabled&&a.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&lj.OpacityTextureEnabled&&a.setTexture("opacitySampler",this._opacityTexture),this._reflectionTexture&&lj.ReflectionTextureEnabled&&(this._reflectionTexture.isCube?a.setTexture("reflectionCubeSampler",this._reflectionTexture):a.setTexture("reflection2DSampler",this._reflectionTexture)),this._emissiveTexture&&lj.EmissiveTextureEnabled&&a.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&lj.LightmapTextureEnabled&&a.setTexture("lightmapSampler",this._lightmapTexture),this._specularTexture&&lj.SpecularTextureEnabled&&a.setTexture("specularSampler",this._specularTexture),this._bumpTexture&&s.getEngine().getCaps().standardDerivatives&&lj.BumpTextureEnabled&&a.setTexture("bumpSampler",this._bumpTexture),this._refractionTexture&&lj.RefractionTextureEnabled&&(this._refractionTexture.isCube?a.setTexture("refractionCubeSampler",this._refractionTexture):a.setTexture("refraction2DSampler",this._refractionTexture))),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(a),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,lH.an)(a,this,s),this.bindEyePosition(a)}else s.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(o||!this.isFrozen)&&(s.lightsEnabled&&!this._disableLighting&&nE.G.BindLights(s,t,a,n,this._maxSimultaneousLights),(s.fogEnabled&&t.applyFog&&s.fogMode!==r2.x.FOGMODE_NONE||this._reflectionTexture||this._refractionTexture||t.receiveShadows||n.PREPASS)&&this.bindView(a),nE.G.BindFogParameters(s,t,a),n.NUM_MORPH_INFLUENCERS&&nE.G.BindMorphTargetParameters(t,a),n.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(r=t.bakedVertexAnimationManager)||void 0===r||r.bind(a,n.INSTANCES)),this.useLogarithmicDepth&&nE.G.BindLogDepth(n,a,s),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),l.update()}getAnimatables(){let e=super.getAnimatables();return this._diffuseTexture&&this._diffuseTexture.animations&&this._diffuseTexture.animations.length>0&&e.push(this._diffuseTexture),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._specularTexture&&this._specularTexture.animations&&this._specularTexture.animations.length>0&&e.push(this._specularTexture),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._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),e}getActiveTextures(){let e=super.getActiveTextures();return this._diffuseTexture&&e.push(this._diffuseTexture),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._specularTexture&&e.push(this._specularTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),this._refractionTexture&&e.push(this._refractionTexture),e}hasTexture(e){return!!super.hasTexture(e)||this._diffuseTexture===e||this._ambientTexture===e||this._opacityTexture===e||this._reflectionTexture===e||this._emissiveTexture===e||this._specularTexture===e||this._bumpTexture===e||this._lightmapTexture===e||this._refractionTexture===e}dispose(e,t){var i,r,s,n,a,o,l,h,u;t&&(null===(i=this._diffuseTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._specularTexture)||void 0===o||o.dispose(),null===(l=this._bumpTexture)||void 0===l||l.dispose(),null===(h=this._lightmapTexture)||void 0===h||h.dispose(),null===(u=this._refractionTexture)||void 0===u||u.dispose()),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}clone(e,t=!0,i=""){let r=rG.p4.Clone(()=>new lj(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.name=e,r.id=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}static Parse(e,t,i){let r=rG.p4.Parse(()=>new lj(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),nu.F._parsePlugins(e,r,t,i),r}static get DiffuseTextureEnabled(){return ow.DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){ow.DiffuseTextureEnabled=e}static get DetailTextureEnabled(){return ow.DetailTextureEnabled}static set DetailTextureEnabled(e){ow.DetailTextureEnabled=e}static get AmbientTextureEnabled(){return ow.AmbientTextureEnabled}static set AmbientTextureEnabled(e){ow.AmbientTextureEnabled=e}static get OpacityTextureEnabled(){return ow.OpacityTextureEnabled}static set OpacityTextureEnabled(e){ow.OpacityTextureEnabled=e}static get ReflectionTextureEnabled(){return ow.ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){ow.ReflectionTextureEnabled=e}static get EmissiveTextureEnabled(){return ow.EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){ow.EmissiveTextureEnabled=e}static get SpecularTextureEnabled(){return ow.SpecularTextureEnabled}static set SpecularTextureEnabled(e){ow.SpecularTextureEnabled=e}static get BumpTextureEnabled(){return ow.BumpTextureEnabled}static set BumpTextureEnabled(e){ow.BumpTextureEnabled=e}static get LightmapTextureEnabled(){return ow.LightmapTextureEnabled}static set LightmapTextureEnabled(e){ow.LightmapTextureEnabled=e}static get RefractionTextureEnabled(){return ow.RefractionTextureEnabled}static set RefractionTextureEnabled(e){ow.RefractionTextureEnabled=e}static get ColorGradingTextureEnabled(){return ow.ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){ow.ColorGradingTextureEnabled=e}static get FresnelEnabled(){return ow.FresnelEnabled}static set FresnelEnabled(e){ow.FresnelEnabled=e}}(0,sx.gn)([(0,rG.oU)("diffuseTexture")],lj.prototype,"_diffuseTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],lj.prototype,"diffuseTexture",void 0),(0,sx.gn)([(0,rG.oU)("ambientTexture")],lj.prototype,"_ambientTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"ambientTexture",void 0),(0,sx.gn)([(0,rG.oU)("opacityTexture")],lj.prototype,"_opacityTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],lj.prototype,"opacityTexture",void 0),(0,sx.gn)([(0,rG.oU)("reflectionTexture")],lj.prototype,"_reflectionTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"reflectionTexture",void 0),(0,sx.gn)([(0,rG.oU)("emissiveTexture")],lj.prototype,"_emissiveTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"emissiveTexture",void 0),(0,sx.gn)([(0,rG.oU)("specularTexture")],lj.prototype,"_specularTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"specularTexture",void 0),(0,sx.gn)([(0,rG.oU)("bumpTexture")],lj.prototype,"_bumpTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"bumpTexture",void 0),(0,sx.gn)([(0,rG.oU)("lightmapTexture")],lj.prototype,"_lightmapTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"lightmapTexture",void 0),(0,sx.gn)([(0,rG.oU)("refractionTexture")],lj.prototype,"_refractionTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"refractionTexture",void 0),(0,sx.gn)([(0,rG.n9)("ambient")],lj.prototype,"ambientColor",void 0),(0,sx.gn)([(0,rG.n9)("diffuse")],lj.prototype,"diffuseColor",void 0),(0,sx.gn)([(0,rG.n9)("specular")],lj.prototype,"specularColor",void 0),(0,sx.gn)([(0,rG.n9)("emissive")],lj.prototype,"emissiveColor",void 0),(0,sx.gn)([(0,rG.qC)()],lj.prototype,"specularPower",void 0),(0,sx.gn)([(0,rG.qC)("useAlphaFromDiffuseTexture")],lj.prototype,"_useAlphaFromDiffuseTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],lj.prototype,"useAlphaFromDiffuseTexture",void 0),(0,sx.gn)([(0,rG.qC)("useEmissiveAsIllumination")],lj.prototype,"_useEmissiveAsIllumination",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"useEmissiveAsIllumination",void 0),(0,sx.gn)([(0,rG.qC)("linkEmissiveWithDiffuse")],lj.prototype,"_linkEmissiveWithDiffuse",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"linkEmissiveWithDiffuse",void 0),(0,sx.gn)([(0,rG.qC)("useSpecularOverAlpha")],lj.prototype,"_useSpecularOverAlpha",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"useSpecularOverAlpha",void 0),(0,sx.gn)([(0,rG.qC)("useReflectionOverAlpha")],lj.prototype,"_useReflectionOverAlpha",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"useReflectionOverAlpha",void 0),(0,sx.gn)([(0,rG.qC)("disableLighting")],lj.prototype,"_disableLighting",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],lj.prototype,"disableLighting",void 0),(0,sx.gn)([(0,rG.qC)("useObjectSpaceNormalMap")],lj.prototype,"_useObjectSpaceNormalMap",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"useObjectSpaceNormalMap",void 0),(0,sx.gn)([(0,rG.qC)("useParallax")],lj.prototype,"_useParallax",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"useParallax",void 0),(0,sx.gn)([(0,rG.qC)("useParallaxOcclusion")],lj.prototype,"_useParallaxOcclusion",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"useParallaxOcclusion",void 0),(0,sx.gn)([(0,rG.qC)()],lj.prototype,"parallaxScaleBias",void 0),(0,sx.gn)([(0,rG.qC)("roughness")],lj.prototype,"_roughness",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"roughness",void 0),(0,sx.gn)([(0,rG.qC)()],lj.prototype,"indexOfRefraction",void 0),(0,sx.gn)([(0,rG.qC)()],lj.prototype,"invertRefractionY",void 0),(0,sx.gn)([(0,rG.qC)()],lj.prototype,"alphaCutOff",void 0),(0,sx.gn)([(0,rG.qC)("useLightmapAsShadowmap")],lj.prototype,"_useLightmapAsShadowmap",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"useLightmapAsShadowmap",void 0),(0,sx.gn)([(0,rG.qQ)("diffuseFresnelParameters")],lj.prototype,"_diffuseFresnelParameters",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsFresnelDirty")],lj.prototype,"diffuseFresnelParameters",void 0),(0,sx.gn)([(0,rG.qQ)("opacityFresnelParameters")],lj.prototype,"_opacityFresnelParameters",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsFresnelAndMiscDirty")],lj.prototype,"opacityFresnelParameters",void 0),(0,sx.gn)([(0,rG.qQ)("reflectionFresnelParameters")],lj.prototype,"_reflectionFresnelParameters",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsFresnelDirty")],lj.prototype,"reflectionFresnelParameters",void 0),(0,sx.gn)([(0,rG.qQ)("refractionFresnelParameters")],lj.prototype,"_refractionFresnelParameters",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsFresnelDirty")],lj.prototype,"refractionFresnelParameters",void 0),(0,sx.gn)([(0,rG.qQ)("emissiveFresnelParameters")],lj.prototype,"_emissiveFresnelParameters",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsFresnelDirty")],lj.prototype,"emissiveFresnelParameters",void 0),(0,sx.gn)([(0,rG.qC)("useReflectionFresnelFromSpecular")],lj.prototype,"_useReflectionFresnelFromSpecular",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsFresnelDirty")],lj.prototype,"useReflectionFresnelFromSpecular",void 0),(0,sx.gn)([(0,rG.qC)("useGlossinessFromSpecularMapAlpha")],lj.prototype,"_useGlossinessFromSpecularMapAlpha",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"useGlossinessFromSpecularMapAlpha",void 0),(0,sx.gn)([(0,rG.qC)("maxSimultaneousLights")],lj.prototype,"_maxSimultaneousLights",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],lj.prototype,"maxSimultaneousLights",void 0),(0,sx.gn)([(0,rG.qC)("invertNormalMapX")],lj.prototype,"_invertNormalMapX",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"invertNormalMapX",void 0),(0,sx.gn)([(0,rG.qC)("invertNormalMapY")],lj.prototype,"_invertNormalMapY",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"invertNormalMapY",void 0),(0,sx.gn)([(0,rG.qC)("twoSidedLighting")],lj.prototype,"_twoSidedLighting",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],lj.prototype,"twoSidedLighting",void 0),(0,sx.gn)([(0,rG.qC)("applyDecalMapAfterDetailMap")],lj.prototype,"_applyDecalMapAfterDetailMap",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],lj.prototype,"applyDecalMapAfterDetailMap",void 0),(0,rg.H)("BABYLON.StandardMaterial",lj),r2.x.DefaultMaterialFactory=e=>new lj("default material",e),sK.B.prototype.createDynamicTexture=function(e,t,i,r){let s=new sq.l(this,sq.S.Dynamic);return s.baseWidth=e,s.baseHeight=t,i&&(e=this.needPOTTextures?sK.B.GetExponentOfTwo(e,this._caps.maxTextureSize):e,t=this.needPOTTextures?sK.B.GetExponentOfTwo(t,this._caps.maxTextureSize):t),s.width=e,s.height=t,s.isReady=!1,s.generateMipMaps=i,s.samplingMode=r,this.updateTextureSamplingMode(r,s),this._internalTexturesCache.push(s),s},sK.B.prototype.updateDynamicTexture=function(e,t,i,r=!1,s,n=!1,a=!1){if(!e)return;let o=this._gl,l=o.TEXTURE_2D,h=this._bindTextureDirectly(l,e,!0,n);this._unpackFlipY(void 0===i?e.invertY:i),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,1);let u=this._getWebGLTextureType(e.type),c=this._getInternalFormat(s||e.format),d=this._getRGBABufferInternalSizedFormat(e.type,c);o.texImage2D(l,0,d,c,u,t),e.generateMipMaps&&o.generateMipmap(l),h||this._bindTextureDirectly(l,null),r&&o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),s&&(e.format=s),e._dynamicTextureSource=t,e._premulAlpha=r,e.invertY=i||!1,e.isReady=!0};class lq extends sj{constructor(e,t,i=null,r=!1,s=3,n=5,a){super(null,i,!r,a,s,void 0,void 0,void 0,void 0,n),this.name=e,this.wrapU=sj.CLAMP_ADDRESSMODE,this.wrapV=sj.CLAMP_ADDRESSMODE,this._generateMipMaps=r;let o=this._getEngine();if(!o)return;t.getContext?(this._canvas=t,this._ownCanvas=!1,this._texture=o.createDynamicTexture(t.width,t.height,r,s)):(this._canvas=o.createCanvas(1,1),this._ownCanvas=!0,t.width||0===t.width?this._texture=o.createDynamicTexture(t.width,t.height,r,s):this._texture=o.createDynamicTexture(t,t,r,s));let l=this.getSize();this._canvas.width!==l.width&&(this._canvas.width=l.width),this._canvas.height!==l.height&&(this._canvas.height=l.height),this._context=this._canvas.getContext("2d")}getClassName(){return"DynamicTexture"}get canRescale(){return!0}_recreate(e){this._canvas.width=e.width,this._canvas.height=e.height,this.releaseInternalTexture(),this._texture=this._getEngine().createDynamicTexture(e.width,e.height,this._generateMipMaps,this.samplingMode)}scale(e){let t=this.getSize();t.width*=e,t.height*=e,this._recreate(t)}scaleTo(e,t){let i=this.getSize();i.width=e,i.height=t,this._recreate(i)}getContext(){return this._context}clear(e){let t=this.getSize();e&&(this._context.fillStyle=e),this._context.clearRect(0,0,t.width,t.height)}update(e,t=!1,i=!1){this._getEngine().updateDynamicTexture(this._texture,this._canvas,void 0===e||e,t,this._format||void 0,void 0,i)}drawText(e,t,i,r,s,n,a,o=!0){let l=this.getSize();if(n&&(this._context.fillStyle=n,this._context.fillRect(0,0,l.width,l.height)),this._context.font=r,null==t){let i=this._context.measureText(e);t=(l.width-i.width)/2}if(null==i){let e=parseInt(r.replace(/\D/g,""));i=l.height/2+e/3.65}this._context.fillStyle=s||"",this._context.fillText(e,t,i),o&&this.update(a)}dispose(){var e;super.dispose(),this._ownCanvas&&(null===(e=this._canvas)||void 0===e||e.remove()),this._canvas=null,this._context=null}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new lq(this.name,t,e,this._generateMipMaps);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.wrapU=this.wrapU,i.wrapV=this.wrapV,i}serialize(){let e=this.getScene();e&&!e.isReady()&&rb.Y.Warn("The scene must be ready before serializing the dynamic texture");let t=super.serialize();return lq._IsCanvasElement(this._canvas)&&(t.base64String=this._canvas.toDataURL()),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t}static _IsCanvasElement(e){return void 0!==e.toDataURL}_rebuild(){this.update()}}class lK{get isFixedFoveationSupported(){return"XRWebGLLayer"==this.layerType&&"number"==typeof this.layer.fixedFoveation}get fixedFoveation(){return this.isFixedFoveationSupported?this.layer.fixedFoveation:null}set fixedFoveation(e){this.isFixedFoveationSupported&&(this.layer.fixedFoveation=Math.max(0,Math.min(1,e||0)))}constructor(e,t,i,r,s){this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.createRenderTargetTextureProvider=s}}var l$=i(5342);class lQ{constructor(e,t){this._scene=e,this.layerWrapper=t,this._renderTargetTextures=[],this._engine=e.getEngine()}_createInternalTexture(e,t){let i=new sq.l(this._engine,sq.S.Unknown,!0);return i.width=e.width,i.height=e.height,i._hardwareTexture=new l$.B(t,this._engine._gl),i.isReady=!0,i}_createRenderTargetTexture(e,t,i,r,s,n){if(!this._engine)throw Error("Engine is disposed");let a={width:e,height:t},o=n?new oA(this._scene,a):new as("XR renderTargetTexture",a,this._scene),l=o.renderTarget;if(l._samples=o.samples,(i||!r)&&(l._framebuffer=i),r){if(n)l._colorTextureArray=r;else{let e=this._createInternalTexture(a,r);l.setTexture(e,0),o._texture=e}}return s&&(n?l._depthStencilTextureArray=s:l._depthStencilTexture=this._createInternalTexture(a,s)),o.disableRescaling(),"undefined"!=typeof XRWebGLBinding&&(o.skipInitialClear=!0),this._renderTargetTextures.push(o),o}_destroyRenderTargetTexture(e){this._renderTargetTextures.splice(this._renderTargetTextures.indexOf(e),1),e.dispose()}getFramebufferDimensions(){return this._framebufferDimensions}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.length=0}}class lZ extends lK{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new lJ(e.scene,this)),this.layer=e}}class lJ extends lQ{constructor(e,t){super(e,t),this.layerWrapper=t,this._layer=t.layer,this._framebufferDimensions={framebufferWidth:this._layer.framebufferWidth,framebufferHeight:this._layer.framebufferHeight}}trySetViewportForView(e,t){let i=this._layer.getViewport(t);if(!i)return!1;let r=this._framebufferDimensions.framebufferWidth,s=this._framebufferDimensions.framebufferHeight;return e.x=i.x/r,e.y=i.y/s,e.width=i.width/r,e.height=i.height/s,!0}getRenderTargetTextureForEye(e){let t=this._layer.framebufferWidth,i=this._layer.framebufferHeight,r=this._layer.framebuffer;return this._rtt&&t===this._framebufferDimensions.framebufferWidth&&i===this._framebufferDimensions.framebufferHeight&&r===this._framebuffer||(this._rtt=this._createRenderTargetTexture(t,i,r),this._framebufferDimensions.framebufferWidth=t,this._framebufferDimensions.framebufferHeight=i,this._framebuffer=r),this._rtt}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}}class l0{static GetDefaults(e){let t=new l0;return t.canvasOptions={antialias:!0,depth:!0,stencil:!e||e.isStencilEnable,alpha:!0,framebufferScaleFactor:1},t.newCanvasCssStyle="position:absolute; bottom:0px;right:0px;z-index:10;width:90%;height:100%;background-color: #000000;",t}}class l1{constructor(e,t=l0.GetDefaults()){if(this._options=t,this._canvas=null,this._engine=null,this.xrLayer=null,this._xrLayerWrapper=null,this.onXRLayerInitObservable=new r_.y$,this._engine=e.scene.getEngine(),this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),t.canvasElement)this._setManagedOutputCanvas(t.canvasElement);else{let e=document.createElement("canvas");e.style.cssText=this._options.newCanvasCssStyle||"position:absolute; bottom:0px;right:0px;",this._setManagedOutputCanvas(e)}e.onXRSessionInit.add(()=>{this._addCanvas()}),e.onXRSessionEnded.add(()=>{this._removeCanvas()})}dispose(){this._removeCanvas(),this._setManagedOutputCanvas(null)}async initializeXRLayerAsync(e){let t=()=>(this.xrLayer=new XRWebGLLayer(e,this.canvasContext,this._options.canvasOptions),this._xrLayerWrapper=new lZ(this.xrLayer),this.onXRLayerInitObservable.notifyObservers(this.xrLayer),this.xrLayer);return this.canvasContext.makeXRCompatible?this.canvasContext.makeXRCompatible().then(()=>{},()=>{sg.w1.Warn("Error executing makeXRCompatible. This does not mean that the session will work incorrectly.")}).then(()=>t()):Promise.resolve(t())}_addCanvas(){this._canvas&&this._engine&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.appendChild(this._canvas),this.xrLayer?this._setCanvasSize(!0):this.onXRLayerInitObservable.addOnce(()=>{this._setCanvasSize(!0)})}_removeCanvas(){this._canvas&&this._engine&&document.body.contains(this._canvas)&&this._canvas!==this._engine.getRenderingCanvas()&&document.body.removeChild(this._canvas),this._setCanvasSize(!1)}_setCanvasSize(e=!0,t=this._xrLayerWrapper){this._canvas&&this._engine&&(e?t&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=t.getWidth()+"px",this._canvas.style.height=t.getHeight()+"px"):this._engine.setSize(t.getWidth(),t.getHeight())):this._originalCanvasSize&&(this._canvas!==this._engine.getRenderingCanvas()?(this._canvas.style.width=this._originalCanvasSize.width+"px",this._canvas.style.height=this._originalCanvasSize.height+"px"):this._engine.setSize(this._originalCanvasSize.width,this._originalCanvasSize.height)))}_setManagedOutputCanvas(e){this._removeCanvas(),e?(this._originalCanvasSize={width:e.offsetWidth,height:e.offsetHeight},this._canvas=e,this.canvasContext=this._canvas.getContext("webgl2"),this.canvasContext||(this.canvasContext=this._canvas.getContext("webgl"))):(this._canvas=null,this.canvasContext=null)}}class l2 extends lK{constructor(e){super(()=>e.framebufferWidth,()=>e.framebufferHeight,e,"XRWebGLLayer",e=>new l3(e,this)),this.layer=e}}class l3 extends lQ{constructor(e,t){super(e.scene,t),this.layerWrapper=t,this._nativeRTTProvider=navigator.xr.getNativeRenderTargetProvider(e.session,this._createRenderTargetTexture.bind(this),this._destroyRenderTargetTexture.bind(this)),this._nativeLayer=t.layer}trySetViewportForView(e){return e.x=0,e.y=0,e.width=1,e.height=1,!0}getRenderTargetTextureForEye(e){return this._nativeRTTProvider.getRenderTargetForEye(e)}getRenderTargetTextureForView(e){return this._nativeRTTProvider.getRenderTargetForEye(e.eye)}getFramebufferDimensions(){return{framebufferWidth:this._nativeLayer.framebufferWidth,framebufferHeight:this._nativeLayer.framebufferHeight}}}class l4{constructor(e){this._nativeRenderTarget=navigator.xr.getWebXRRenderTarget(e.scene.getEngine())}async initializeXRLayerAsync(e){return await this._nativeRenderTarget.initializeXRLayerAsync(e),this.xrLayer=this._nativeRenderTarget.xrLayer,this.xrLayer}dispose(){}}class l5{constructor(e){this.scene=e,this.currentTimestamp=-1,this.defaultHeightCompensation=1.7,this.onXRFrameObservable=new r_.y$,this.onXRReferenceSpaceChanged=new r_.y$,this.onXRSessionEnded=new r_.y$,this.onXRSessionInit=new r_.y$,this.inXRFrameLoop=!1,this.inXRSession=!1,this._engine=e.getEngine(),this._onEngineDisposedObserver=this._engine.onDisposeObservable.addOnce(()=>{this._engine=null}),e.onDisposeObservable.addOnce(()=>{this.dispose()})}get referenceSpace(){return this._referenceSpace}set referenceSpace(e){this._referenceSpace=e,this.onXRReferenceSpaceChanged.notifyObservers(this._referenceSpace)}get sessionMode(){return this._sessionMode}dispose(){var e;this.inXRSession&&this.exitXRAsync(),this.onXRFrameObservable.clear(),this.onXRSessionEnded.clear(),this.onXRReferenceSpaceChanged.clear(),this.onXRSessionInit.clear(),null===(e=this._engine)||void 0===e||e.onDisposeObservable.remove(this._onEngineDisposedObserver),this._engine=null}exitXRAsync(){return this.session&&this.inXRSession?(this.inXRSession=!1,this.session.end().catch(()=>{rb.Y.Warn("Could not end XR session.")})):Promise.resolve()}trySetViewportForView(e,t){var i;return(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.trySetViewportForView(e,t))||!1}getRenderTargetTextureForEye(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForEye(e))||null}getRenderTargetTextureForView(e){var t;return(null===(t=this._baseLayerRTTProvider)||void 0===t?void 0:t.getRenderTargetTextureForView(e))||null}getWebXRRenderTarget(e){let t=this.scene.getEngine();return this._xrNavigator.xr.native?new l4(this):((e=e||l0.GetDefaults(t)).canvasElement=e.canvasElement||t.getRenderingCanvas()||void 0,new l1(this,e))}initializeAsync(){return(this._xrNavigator=navigator,this._xrNavigator.xr)?Promise.resolve():Promise.reject("WebXR not available")}initializeSessionAsync(e="immersive-vr",t={}){return this._xrNavigator.xr.requestSession(e,t).then(t=>(this.session=t,this._sessionMode=e,this.onXRSessionInit.notifyObservers(t),this.inXRSession=!0,this.session.addEventListener("end",()=>{var e;this.inXRSession=!1,this.onXRSessionEnded.notifyObservers(null),this._engine&&(this._engine.framebufferDimensionsObject=null,this._engine.restoreDefaultFramebuffer(),this._engine.customAnimationFrameRequester=null,this._engine._renderLoop()),this.isNative&&(null===(e=this._baseLayerRTTProvider)||void 0===e||e.dispose()),this._baseLayerRTTProvider=null,this._baseLayerWrapper=null},{once:!0}),this.session))}isSessionSupportedAsync(e){return l5.IsSessionSupportedAsync(e)}resetReferenceSpace(){this.referenceSpace=this.baseReferenceSpace}runXRRenderLoop(){var e;this.inXRSession&&this._engine&&(this._engine.customAnimationFrameRequester={requestAnimationFrame:e=>this.session.requestAnimationFrame(e),renderFunction:(e,t)=>{var i;this.inXRSession&&this._engine&&(this.currentFrame=t,this.currentTimestamp=e,t&&(this.inXRFrameLoop=!0,this._engine.framebufferDimensionsObject=(null===(i=this._baseLayerRTTProvider)||void 0===i?void 0:i.getFramebufferDimensions())||null,this.onXRFrameObservable.notifyObservers(t),this._engine._renderLoop(),this._engine.framebufferDimensionsObject=null,this.inXRFrameLoop=!1))}},this._engine.framebufferDimensionsObject=(null===(e=this._baseLayerRTTProvider)||void 0===e?void 0:e.getFramebufferDimensions())||null,"undefined"!=typeof window&&window.cancelAnimationFrame&&window.cancelAnimationFrame(this._engine._frameHandler),this._engine._renderLoop())}setReferenceSpaceTypeAsync(e="local-floor"){return this.session.requestReferenceSpace(e).then(e=>e,e=>(rb.Y.Error("XR.requestReferenceSpace failed for the following reason: "),rb.Y.Error(e),rb.Y.Log('Defaulting to universally-supported "viewer" reference space type.'),this.session.requestReferenceSpace("viewer").then(e=>{let t=new XRRigidTransform({x:0,y:-this.defaultHeightCompensation,z:0});return e.getOffsetReferenceSpace(t)},e=>{throw rb.Y.Error(e),'XR initialization failed: required "viewer" reference space type not supported.'}))).then(e=>this.session.requestReferenceSpace("viewer").then(t=>(this.viewerReferenceSpace=t,e))).then(e=>(this.referenceSpace=this.baseReferenceSpace=e,this.referenceSpace))}updateRenderStateAsync(e){return Promise.resolve(this.session.updateRenderState(e))}_setBaseLayerWrapper(e){var t,i;this.isNative&&(null===(t=this._baseLayerRTTProvider)||void 0===t||t.dispose()),this._baseLayerWrapper=e,this._baseLayerRTTProvider=(null===(i=this._baseLayerWrapper)||void 0===i?void 0:i.createRenderTargetTextureProvider(this))||null}_getBaseLayerWrapper(){return this._baseLayerWrapper}updateRenderState(e){e.baseLayer&&this._setBaseLayerWrapper(this.isNative?new l2(e.baseLayer):new lZ(e.baseLayer)),this.session.updateRenderState(e)}static IsSessionSupportedAsync(e){if(!navigator.xr)return Promise.resolve(!1);let t=navigator.xr.isSessionSupported||navigator.xr.supportsSession;return t?t.call(navigator.xr,e).then(e=>Promise.resolve(void 0===e||e)).catch(e=>(rb.Y.Warn(e),Promise.resolve(!1))):Promise.resolve(!1)}get isNative(){var e;return null!==(e=this._xrNavigator.xr.native)&&void 0!==e&&e}get currentFrameRate(){var e;return null===(e=this.session)||void 0===e?void 0:e.frameRate}get supportedFrameRates(){var e;return null===(e=this.session)||void 0===e?void 0:e.supportedFrameRates}updateTargetFrameRate(e){return this.session.updateTargetFrameRate(e)}runInXRFrame(e,t=!0){this.inXRFrameLoop?e():(this.inXRSession||!t)&&this.onXRFrameObservable.addOnce(e)}get isFixedFoveationSupported(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.isFixedFoveationSupported)||!1}get fixedFoveation(){var e;return(null===(e=this._baseLayerWrapper)||void 0===e?void 0:e.fixedFoveation)||null}set fixedFoveation(e){this._baseLayerWrapper&&(this._baseLayerWrapper.fixedFoveation=Math.max(0,Math.min(1,e||0)))}get enabledFeatures(){var e,t;return null!==(t=null===(e=this.session)||void 0===e?void 0:e.enabledFeatures)&&void 0!==t?t:null}}(M=tw||(tw={}))[M.ENTERING_XR=0]="ENTERING_XR",M[M.EXITING_XR=1]="EXITING_XR",M[M.IN_XR=2]="IN_XR",M[M.NOT_IN_XR=3]="NOT_IN_XR",(D=tB||(tB={}))[D.NOT_TRACKING=0]="NOT_TRACKING",D[D.TRACKING_LOST=1]="TRACKING_LOST",D[D.TRACKING=2]="TRACKING",sp.Kj._GroundMeshParser=(e,t)=>l6.Parse(e,t);class l6 extends sp.Kj{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),this.createOrUpdateSubmeshesOctree&&this.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){let i=this.getWorldMatrix(),r=rf.jp.Matrix[5];i.invertToRef(r);let s=rf.jp.Vector3[8];if(rf.P.TransformCoordinatesFromFloatsToRef(e,0,t,r,s),e=s.x,t=s.z,e=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return rf.P.TransformCoordinatesFromFloatsToRef(0,a,0,i,s),s.y}getNormalAtCoordinates(e,t){let i=new rf.P(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,i),i}getNormalAtCoordinatesToRef(e,t,i){let r=this.getWorldMatrix(),s=rf.jp.Matrix[5];r.invertToRef(s);let n=rf.jp.Vector3[8];if(rf.P.TransformCoordinatesFromFloatsToRef(e,0,t,s,n),e=n.x,t=n.z,ethis._maxX||tthis._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());let a=this._getFacetAt(e,t);return rf.P.TransformNormalFromFloatsToRef(a.x,a.y,a.z,r,i),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){let i=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),r=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),s=this._heightQuads[r*this._subdivisionsX+i];return te.maxHeight){h=!0;let t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(t=0;t<=e.subdivisions;t++)for(i=0;i<=e.subdivisions;i++){let r=new rf.P(i*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-t)*e.height/e.subdivisions-e.height/2),u=(((r.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(r.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth)*4,c=e.buffer[u]/255,d=e.buffer[u+1]/255,p=e.buffer[u+2]/255,_=e.buffer[u+3]/255;h&&(c=1-c,d=1-d,p=1-p);let f=c*o.r+d*o.g+p*o.b;_>=l?r.y=e.minHeight+(e.maxHeight-e.minHeight)*f:r.y=e.minHeight-r7.kn,s.push(r.x,r.y,r.z),n.push(0,0,0),a.push(i/e.subdivisions,1-t/e.subdivisions)}for(t=0;t=e.minHeight,u=s[3*a+1]>=e.minHeight,c=s[3*o+1]>=e.minHeight;h&&u&&c&&(r.push(n),r.push(a),r.push(o)),s[3*l+1]>=e.minHeight&&h&&c&&(r.push(l),r.push(n),r.push(o))}s7.x.ComputeNormals(s,r,n);let u=new s7.x;return u.indices=r,u.positions=s,u.normals=n,u.uvs=a,u}function he(e,t={},i){let r=new l6(e,i);return r._setReady(!1),r._subdivisionsX=t.subdivisionsX||t.subdivisions||1,r._subdivisionsY=t.subdivisionsY||t.subdivisions||1,r._width=t.width||1,r._height=t.height||1,r._maxX=r._width/2,r._maxZ=r._height/2,r._minX=-r._maxX,r._minZ=-r._maxZ,l8(t).applyToMesh(r,t.updatable),r._setReady(!0),r}function ht(e){let t=[],i=[],r=[],s=[],n=e.diameter||1,a=e.thickness||.5,o=0|(e.tessellation||16),l=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE,h=o+1;for(let e=0;e<=o;e++){let l=e/o,u=e*Math.PI*2/o-Math.PI/2,c=rf.y3.Translation(n/2,0,0).multiply(rf.y3.RotationY(u));for(let n=0;n<=o;n++){let u=1-n/o,d=n*Math.PI*2/o+Math.PI,p=Math.cos(d),_=Math.sin(d),f=new rf.P(p,_,0),m=f.scale(a/2),g=new rf.FM(l,u);m=rf.P.TransformCoordinates(m,c),f=rf.P.TransformNormal(f,c),i.push(m.x,m.y,m.z),r.push(f.x,f.y,f.z),s.push(g.x,sY.e.UseOpenGLOrientationForUV?1-g.y:g.y);let v=(e+1)%h,x=(n+1)%h;t.push(e*h+n),t.push(e*h+x),t.push(v*h+n),t.push(e*h+x),t.push(v*h+x),t.push(v*h+n)}}s7.x._ComputeSides(l,i,t,r,s,e.frontUVs,e.backUVs);let u=new s7.x;return u.indices=t,u.positions=i,u.normals=r,u.uvs=s,u}function hi(e,t={},i){let r=new sp.Kj(e,i);return t.sideOrientation=sp.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,ht(t).applyToMesh(r,t.updatable),r}s7.x.CreateGround=l8,s7.x.CreateTiledGround=l7,s7.x.CreateGroundFromHeightMap=l9,sp.Kj.CreateGround=(e,t,i,r,s,n)=>he(e,{width:t,height:i,subdivisions:r,updatable:n},s),sp.Kj.CreateTiledGround=(e,t,i,r,s,n,a,o,l)=>(function(e,t,i=null){let r=new sp.Kj(e,i);return l7(t).applyToMesh(r,t.updatable),r})(e,{xmin:t,zmin:i,xmax:r,zmax:s,subdivisions:n,precision:a,updatable:l},o),sp.Kj.CreateGroundFromHeightMap=(e,t,i,r,s,n,a,o,l,h,u)=>(function(e,t,i={},r=null){let s=i.width||10,n=i.height||10,a=i.subdivisions||1,o=i.minHeight||0,l=i.maxHeight||1,h=i.colorFilter||new rm.Wo(.3,.59,.11),u=i.alphaFilter||0,c=i.updatable,d=i.onReady,p=new l6(e,r=r||rL.l.LastCreatedScene);p._subdivisionsX=a,p._subdivisionsY=a,p._width=s,p._height=n,p._maxX=p._width/2,p._maxZ=p._height/2,p._minX=-p._maxX,p._minZ=-p._maxZ,p._setReady(!1);let _=(e,t,i)=>{l9({width:s,height:n,subdivisions:a,minHeight:o,maxHeight:l,colorFilter:h,buffer:e,bufferWidth:t,bufferHeight:i,alphaFilter:u}).applyToMesh(p,c),d&&d(p),p._setReady(!0)};return"string"==typeof t?sg.w1.LoadImage(t,e=>{let t=e.width,i=e.height;r.isDisposed||_(null==r?void 0:r.getEngine().resizeImageBitmap(e,t,i),t,i)},i.onError?i.onError:()=>{},r.offlineProvider):_(t.data,t.width,t.height),p})(e,t,{width:i,height:r,subdivisions:s,minHeight:n,maxHeight:a,updatable:l,onReady:h,alphaFilter:u},o),s7.x.CreateTorus=ht,sp.Kj.CreateTorus=(e,t,i,r,s,n,a)=>hi(e,{diameter:t,thickness:i,tessellation:r,sideOrientation:a,updatable:n},s);class hr{constructor(e,t=null){if(this.scene=e,this._pointerDownOnMeshAsked=!1,this._isActionableMesh=!1,this._teleportationRequestInitiated=!1,this._teleportationBackRequestInitiated=!1,this._rotationRightAsked=!1,this._rotationLeftAsked=!1,this._dpadPressed=!0,this._activePointer=!1,this._id=hr._IdCounter++,t)this._gazeTracker=t.clone("gazeTracker");else{this._gazeTracker=hi("gazeTracker",{diameter:.0035,thickness:.0025,tessellation:20,updatable:!1},e),this._gazeTracker.bakeCurrentTransformIntoVertices(),this._gazeTracker.isPickable=!1,this._gazeTracker.isVisible=!1;let t=new lj("targetMat",e);t.specularColor=rm.Wo.Black(),t.emissiveColor=new rm.Wo(.7,.7,.7),t.backFaceCulling=!1,this._gazeTracker.material=t}}_getForwardRay(e){return new s6(rf.P.Zero(),new rf.P(0,0,e))}_selectionPointerDown(){this._pointerDownOnMeshAsked=!0,this._currentHit&&this.scene.simulatePointerDown(this._currentHit,{pointerId:this._id})}_selectionPointerUp(){this._currentHit&&this.scene.simulatePointerUp(this._currentHit,{pointerId:this._id}),this._pointerDownOnMeshAsked=!1}_activatePointer(){this._activePointer=!0}_deactivatePointer(){this._activePointer=!1}_updatePointerDistance(e=100){}dispose(){this._interactionsEnabled=!1,this._teleportationEnabled=!1,this._gazeTracker&&this._gazeTracker.dispose()}}hr._IdCounter=0;class hs extends hr{constructor(e,t){super(t),this._getCamera=e}_getForwardRay(e){let t=this._getCamera();return t?t.getForwardRay(e):new s6(rf.P.Zero(),rf.P.Forward())}}class hn{get onEnteringVR(){return this.onEnteringVRObservable}get onExitingVR(){return this.onExitingVRObservable}get teleportationTarget(){return this._teleportationTarget}set teleportationTarget(e){e&&(e.name="teleportationTarget",this._isDefaultTeleportationTarget=!1,this._teleportationTarget=e)}get gazeTrackerMesh(){return this._cameraGazer._gazeTracker}set gazeTrackerMesh(e){e&&(this._cameraGazer._gazeTracker&&this._cameraGazer._gazeTracker.dispose(),this._cameraGazer._gazeTracker=e,this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(),this._cameraGazer._gazeTracker.isPickable=!1,this._cameraGazer._gazeTracker.isVisible=!1,this._cameraGazer._gazeTracker.name="gazeTracker")}get displayGaze(){return this._displayGaze}set displayGaze(e){this._displayGaze=e,e||(this._cameraGazer._gazeTracker.isVisible=!1)}get displayLaserPointer(){return this._displayLaserPointer}set displayLaserPointer(e){this._displayLaserPointer=e}get deviceOrientationCamera(){return this._deviceOrientationCamera}get currentVRCamera(){return this._scene.activeCamera}get vrDeviceOrientationCamera(){return this._vrDeviceOrientationCamera}get vrButton(){return this._btnVR}get _teleportationRequestInitiated(){return this._cameraGazer._teleportationRequestInitiated}constructor(e,t={}){if(this.webVROptions=t,this._fullscreenVRpresenting=!1,this.enableGazeEvenWhenNoPointerLock=!1,this.exitVROnDoubleTap=!0,this.onEnteringVRObservable=new r_.y$,this.onAfterEnteringVRObservable=new r_.y$,this.onExitingVRObservable=new r_.y$,this._useCustomVRButton=!1,this._teleportActive=!1,this._floorMeshesCollection=[],this._teleportationMode=hn.TELEPORTATIONMODE_CONSTANTTIME,this._teleportationTime=122,this._teleportationSpeed=20,this._rotationAllowed=!0,this._teleportBackwardsVector=new rf.P(0,-1,-1),this._isDefaultTeleportationTarget=!0,this._teleportationFillColor="#444444",this._teleportationBorderColor="#FFFFFF",this._rotationAngle=0,this._haloCenter=new rf.P(0,0,0),this._padSensibilityUp=.65,this._padSensibilityDown=.35,this._pickedLaserColor=new rm.Wo(.2,.2,1),this._pickedGazeColor=new rm.Wo(0,0,1),this.onNewMeshSelected=new r_.y$,this.onNewMeshPicked=new r_.y$,this.onBeforeCameraTeleport=new r_.y$,this.onAfterCameraTeleport=new r_.y$,this.onSelectedMeshUnselected=new r_.y$,this.teleportationEnabled=!0,this._teleportationInitialized=!1,this._interactionsEnabled=!1,this._displayGaze=!0,this._displayLaserPointer=!0,this.updateGazeTrackerScale=!0,this.updateGazeTrackerColor=!0,this.updateControllerLaserColor=!0,this.requestPointerLockOnFullScreen=!0,this.xrTestDone=!1,this._onResize=()=>{this._moveButtonToBottomRight()},this._onFullscreenChange=()=>{this._fullscreenVRpresenting=!!document.fullscreenElement,!this._fullscreenVRpresenting&&this._inputElement&&(this.exitVR(),!this._useCustomVRButton&&this._btnVR&&(this._btnVR.style.top=this._inputElement.offsetTop+this._inputElement.offsetHeight-70+"px",this._btnVR.style.left=this._inputElement.offsetLeft+this._inputElement.offsetWidth-100+"px",this._updateButtonVisibility()))},this._cachedAngularSensibility={angularSensibilityX:null,angularSensibilityY:null,angularSensibility:null},this._beforeRender=()=>{this._scene.getEngine().isPointerLock||this.enableGazeEvenWhenNoPointerLock||(this._cameraGazer._gazeTracker.isVisible=!1)},this._onNewGamepadConnected=e=>{e.type!==aI.POSE_ENABLED&&(e.leftStick&&e.onleftstickchanged(e=>{this._teleportationInitialized&&this.teleportationEnabled&&(this._checkTeleportWithRay(e,this._cameraGazer),this._checkTeleportBackwards(e,this._cameraGazer))}),e.rightStick&&e.onrightstickchanged(e=>{this._teleportationInitialized&&this._checkRotate(e,this._cameraGazer)}),e.type===aI.XBOX&&(e.onbuttondown(e=>{this._interactionsEnabled&&e===tO.A&&this._cameraGazer._selectionPointerDown()}),e.onbuttonup(e=>{this._interactionsEnabled&&e===tO.A&&this._cameraGazer._selectionPointerUp()})))},this._workingVector=rf.P.Zero(),this._workingQuaternion=rf._f.Identity(),this._workingMatrix=rf.y3.Identity(),rb.Y.Warn("WebVR is deprecated. Please avoid using this experience helper and use the WebXR experience helper instead"),this._scene=e,this._inputElement=e.getEngine().getInputElement(),"getVRDisplays"in navigator||void 0!==t.useXR||(t.useXR=!0),void 0===t.createFallbackVRDeviceOrientationFreeCamera&&(t.createFallbackVRDeviceOrientationFreeCamera=!0),void 0===t.createDeviceOrientationCamera&&(t.createDeviceOrientationCamera=!0),void 0===t.laserToggle&&(t.laserToggle=!0),this._hasEnteredVR=!1,this._scene.activeCamera?this._position=this._scene.activeCamera.position.clone():this._position=new rf.P(0,this._defaultHeight,0),t.createDeviceOrientationCamera||!this._scene.activeCamera){if(this._deviceOrientationCamera=new a3("deviceOrientationVRHelper",this._position.clone(),e),this._scene.activeCamera&&(this._deviceOrientationCamera.minZ=this._scene.activeCamera.minZ,this._deviceOrientationCamera.maxZ=this._scene.activeCamera.maxZ,this._scene.activeCamera instanceof aJ&&this._scene.activeCamera.rotation)){let e=this._scene.activeCamera;e.rotationQuaternion?this._deviceOrientationCamera.rotationQuaternion.copyFrom(e.rotationQuaternion):this._deviceOrientationCamera.rotationQuaternion.copyFrom(rf._f.RotationYawPitchRoll(e.rotation.y,e.rotation.x,e.rotation.z)),this._deviceOrientationCamera.rotation=e.rotation.clone()}this._scene.activeCamera=this._deviceOrientationCamera,this._inputElement&&this._scene.activeCamera.attachControl()}else this._existingCamera=this._scene.activeCamera;this.webVROptions.useXR&&navigator.xr?l5.IsSessionSupportedAsync("immersive-vr").then(i=>{i?(rb.Y.Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"),e.createDefaultXRExperienceAsync({floorMeshes:t.floorMeshes||[]}).then(t=>{this.xr=t,this.xrTestDone=!0,this._cameraGazer=new hs(()=>this.xr.baseExperience.camera,e),this.xr.baseExperience.onStateChangedObservable.add(e=>{switch(e){case tw.ENTERING_XR:this.onEnteringVRObservable.notifyObservers(this),this._interactionsEnabled||this.xr.pointerSelection.detach(),this.xr.pointerSelection.displayLaserPointer=this._displayLaserPointer;break;case tw.EXITING_XR:this.onExitingVRObservable.notifyObservers(this),this._scene.getEngine().resize();break;case tw.IN_XR:this._hasEnteredVR=!0;break;case tw.NOT_IN_XR:this._hasEnteredVR=!1}})})):this._completeVRInit(e,t)}):this._completeVRInit(e,t)}_completeVRInit(e,t){if(this.xrTestDone=!0,t.createFallbackVRDeviceOrientationFreeCamera&&(this._vrDeviceOrientationCamera=new oO("VRDeviceOrientationVRHelper",this._position,this._scene,!0,t.vrDeviceOrientationCameraMetrics),this._vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._cameraGazer=new hs(()=>this.currentVRCamera,e),!this._useCustomVRButton){this._btnVR=document.createElement("BUTTON"),this._btnVR.className="babylonVRicon",this._btnVR.id="babylonVRiconbtn",this._btnVR.title="Click to switch to VR";let e=".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A":"https://cdn.babylonjs.com/Assets/vrButton.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";e+=".babylonVRicon.vrdisplaypresenting { display: none; }";let t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),this._moveButtonToBottomRight()}this._btnVR&&this._btnVR.addEventListener("click",()=>{this.isInVRMode||this.enterVR()});let i=this._scene.getEngine().getHostWindow();i&&(i.addEventListener("resize",this._onResize),document.addEventListener("fullscreenchange",this._onFullscreenChange,!1),t.createFallbackVRDeviceOrientationFreeCamera&&this._displayVRButton(),this._onKeyDown=e=>{27===e.keyCode&&this.isInVRMode&&this.exitVR()},document.addEventListener("keydown",this._onKeyDown),this._scene.onPrePointerObservable.add(()=>{this._hasEnteredVR&&this.exitVROnDoubleTap&&(this.exitVR(),this._fullscreenVRpresenting&&this._scene.getEngine().exitFullscreen())},s0.kD.POINTERDOUBLETAP,!1),e.onDisposeObservable.add(()=>{this.dispose()}),this._updateButtonVisibility(),this._circleEase=new sn,this._circleEase.setEasingMode(ss.EASINGMODE_EASEINOUT),this._teleportationEasing=this._circleEase,e.onPointerObservable.add(t=>{this._interactionsEnabled&&e.activeCamera===this.vrDeviceOrientationCamera&&"mouse"===t.event.pointerType&&(t.type===s0.kD.POINTERDOWN?this._cameraGazer._selectionPointerDown():t.type===s0.kD.POINTERUP&&this._cameraGazer._selectionPointerUp())}),this.webVROptions.floorMeshes&&this.enableTeleportation({floorMeshes:this.webVROptions.floorMeshes}))}get isInVRMode(){return this.xr&&this.webVROptions.useXR&&this.xr.baseExperience.state===tw.IN_XR||this._fullscreenVRpresenting}_moveButtonToBottomRight(){if(this._inputElement&&!this._useCustomVRButton&&this._btnVR){let e=this._inputElement.getBoundingClientRect();this._btnVR.style.top=e.top+e.height-70+"px",this._btnVR.style.left=e.left+e.width-100+"px"}}_displayVRButton(){this._useCustomVRButton||this._btnVRDisplayed||!this._btnVR||(document.body.appendChild(this._btnVR),this._btnVRDisplayed=!0)}_updateButtonVisibility(){this._btnVR&&!this._useCustomVRButton&&(this._btnVR.className="babylonVRicon",this.isInVRMode&&(this._btnVR.className+=" vrdisplaypresenting"))}enterVR(){if(this.xr){this.xr.baseExperience.enterXRAsync("immersive-vr","local-floor",this.xr.renderTarget);return}if(this.onEnteringVRObservable)try{this.onEnteringVRObservable.notifyObservers(this)}catch(e){rb.Y.Warn("Error in your custom logic onEnteringVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone(),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.rotation=rf._f.FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(),this.vrDeviceOrientationCamera.angularSensibility=2e3),this._existingCamera=this._scene.activeCamera,this._existingCamera.angularSensibilityX&&(this._cachedAngularSensibility.angularSensibilityX=this._existingCamera.angularSensibilityX,this._existingCamera.angularSensibilityX=Number.MAX_VALUE),this._existingCamera.angularSensibilityY&&(this._cachedAngularSensibility.angularSensibilityY=this._existingCamera.angularSensibilityY,this._existingCamera.angularSensibilityY=Number.MAX_VALUE),this._existingCamera.angularSensibility&&(this._cachedAngularSensibility.angularSensibility=this._existingCamera.angularSensibility,this._existingCamera.angularSensibility=Number.MAX_VALUE)),this._vrDeviceOrientationCamera&&(this._vrDeviceOrientationCamera.position=this._position,this._scene.activeCamera&&(this._vrDeviceOrientationCamera.minZ=this._scene.activeCamera.minZ),this._scene.activeCamera=this._vrDeviceOrientationCamera,this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen),this._updateButtonVisibility(),this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(()=>{this.onAfterEnteringVRObservable.notifyObservers({success:!0})})),this._scene.activeCamera&&this._inputElement&&this._scene.activeCamera.attachControl(),this._interactionsEnabled&&this._scene.registerBeforeRender(this._beforeRender),this._hasEnteredVR=!0}exitVR(){if(this.xr){this.xr.baseExperience.exitXRAsync();return}if(this._hasEnteredVR){if(this.onExitingVRObservable)try{this.onExitingVRObservable.notifyObservers(this)}catch(e){rb.Y.Warn("Error in your custom logic onExitingVR: "+e)}this._scene.activeCamera&&(this._position=this._scene.activeCamera.position.clone()),this.vrDeviceOrientationCamera&&(this.vrDeviceOrientationCamera.angularSensibility=Number.MAX_VALUE),this._deviceOrientationCamera?(this._deviceOrientationCamera.position=this._position,this._scene.activeCamera=this._deviceOrientationCamera,this._cachedAngularSensibility.angularSensibilityX&&(this._deviceOrientationCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._deviceOrientationCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._deviceOrientationCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)):this._existingCamera&&(this._existingCamera.position=this._position,this._scene.activeCamera=this._existingCamera,this._inputElement&&this._scene.activeCamera.attachControl(),this._cachedAngularSensibility.angularSensibilityX&&(this._existingCamera.angularSensibilityX=this._cachedAngularSensibility.angularSensibilityX,this._cachedAngularSensibility.angularSensibilityX=null),this._cachedAngularSensibility.angularSensibilityY&&(this._existingCamera.angularSensibilityY=this._cachedAngularSensibility.angularSensibilityY,this._cachedAngularSensibility.angularSensibilityY=null),this._cachedAngularSensibility.angularSensibility&&(this._existingCamera.angularSensibility=this._cachedAngularSensibility.angularSensibility,this._cachedAngularSensibility.angularSensibility=null)),this._updateButtonVisibility(),this._interactionsEnabled&&(this._scene.unregisterBeforeRender(this._beforeRender),this._cameraGazer._gazeTracker.isVisible=!1),this._scene.getEngine().resize(),this._hasEnteredVR=!1}}get position(){return this._position}set position(e){this._position=e,this._scene.activeCamera&&(this._scene.activeCamera.position=e)}enableInteractions(){if(!this._interactionsEnabled){if(this.xr){this.xr.baseExperience.state===tw.IN_XR&&this.xr.pointerSelection.attach();return}this.raySelectionPredicate=e=>e.isVisible&&(e.isPickable||e.name===this._floorMeshName),this.meshSelectionPredicate=()=>!0,this._raySelectionPredicate=e=>(!!this._isTeleportationFloor(e)||-1===e.name.indexOf("gazeTracker")&&-1===e.name.indexOf("teleportationTarget")&&-1===e.name.indexOf("torusTeleportation"))&&this.raySelectionPredicate(e),this._interactionsEnabled=!0}}_isTeleportationFloor(e){for(let t=0;t-1||this._floorMeshesCollection.push(e)}removeFloorMesh(e){if(!this._floorMeshesCollection)return;let t=this._floorMeshesCollection.indexOf(e);-1!==t&&this._floorMeshesCollection.splice(t,1)}enableTeleportation(e={}){if(!this._teleportationInitialized){if(this.enableInteractions(),this.webVROptions.useXR&&(e.floorMeshes||e.floorMeshName)){let t=e.floorMeshes||[];if(!t.length){let i=this._scene.getMeshByName(e.floorMeshName);i&&t.push(i)}if(this.xr){t.forEach(e=>{this.xr.teleportation.addFloorMesh(e)}),this.xr.teleportation.attached||this.xr.teleportation.attach();return}if(!this.xrTestDone){let t=()=>{this.xrTestDone&&(this._scene.unregisterBeforeRender(t),this.xr?this.xr.teleportation.attached||this.xr.teleportation.attach():this.enableTeleportation(e))};this._scene.registerBeforeRender(t);return}}e.floorMeshName&&(this._floorMeshName=e.floorMeshName),e.floorMeshes&&(this._floorMeshesCollection=e.floorMeshes),e.teleportationMode&&(this._teleportationMode=e.teleportationMode),e.teleportationTime&&e.teleportationTime>0&&(this._teleportationTime=e.teleportationTime),e.teleportationSpeed&&e.teleportationSpeed>0&&(this._teleportationSpeed=e.teleportationSpeed),void 0!==e.easingFunction&&(this._teleportationEasing=e.easingFunction);let t=new nY.$;t.vignetteColor=new rm.HE(0,0,0,0),t.vignetteEnabled=!0,this._teleportationInitialized=!0,this._isDefaultTeleportationTarget&&this._createTeleportationCircles()}}_checkTeleportWithRay(e,t){(!this._teleportationRequestInitiated||t._teleportationRequestInitiated)&&(t._teleportationRequestInitiated?Math.sqrt(e.y*e.y+e.x*e.x)-this._padSensibilityDown&&(t._rotationLeftAsked=!1):e.x<-this._padSensibilityUp&&t._dpadPressed&&(t._rotationLeftAsked=!0,this._rotationAllowed&&this._rotateCamera(!1)),t._rotationRightAsked?e.xthis._padSensibilityUp&&t._dpadPressed&&(t._rotationRightAsked=!0,this._rotationAllowed&&this._rotateCamera(!0)))}_checkTeleportBackwards(e,t){if(!t._teleportationRequestInitiated){if(e.y>this._padSensibilityUp&&t._dpadPressed){if(!t._teleportationBackRequestInitiated){if(!this.currentVRCamera)return;let e=rf._f.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()),i=this.currentVRCamera.position;e.toEulerAnglesToRef(this._workingVector),this._workingVector.z=0,this._workingVector.x=0,rf._f.RotationYawPitchRollToRef(this._workingVector.y,this._workingVector.x,this._workingVector.z,this._workingQuaternion),this._workingQuaternion.toRotationMatrix(this._workingMatrix),rf.P.TransformCoordinatesToRef(this._teleportBackwardsVector,this._workingMatrix,this._workingVector);let r=new s6(i,this._workingVector),s=this._scene.pickWithRay(r,this._raySelectionPredicate);s&&s.pickedPoint&&s.pickedMesh&&this._isTeleportationFloor(s.pickedMesh)&&s.distance<5&&this.teleportCamera(s.pickedPoint),t._teleportationBackRequestInitiated=!0}}else t._teleportationBackRequestInitiated=!1}}_createTeleportationCircles(){this._teleportationTarget=he("teleportationTarget",{width:2,height:2,subdivisions:2},this._scene),this._teleportationTarget.isPickable=!1;let e=new lq("DynamicTexture",512,this._scene,!0);e.hasAlpha=!0;let t=e.getContext();t.beginPath(),t.arc(256,256,200,0,2*Math.PI,!1),t.fillStyle=this._teleportationFillColor,t.fill(),t.lineWidth=10,t.strokeStyle=this._teleportationBorderColor,t.stroke(),t.closePath(),e.update();let i=new lj("TextPlaneMaterial",this._scene);i.diffuseTexture=e,this._teleportationTarget.material=i;let r=hi("torusTeleportation",{diameter:.75,thickness:.1,tessellation:25,updatable:!1},this._scene);r.isPickable=!1,r.parent=this._teleportationTarget;let s=new rJ("animationInnerCircle","position.y",30,rJ.ANIMATIONTYPE_FLOAT,rJ.ANIMATIONLOOPMODE_CYCLE),n=[];n.push({frame:0,value:0}),n.push({frame:30,value:.4}),n.push({frame:60,value:0}),s.setKeys(n);let a=new sh;a.setEasingMode(ss.EASINGMODE_EASEINOUT),s.setEasingFunction(a),r.animations=[],r.animations.push(s),this._scene.beginAnimation(r,0,60,!0),this._hideTeleportationTarget()}_hideTeleportationTarget(){this._teleportActive=!1,this._teleportationInitialized&&(this._teleportationTarget.isVisible=!1,this._isDefaultTeleportationTarget&&(this._teleportationTarget.getChildren()[0].isVisible=!1))}_rotateCamera(e){if(!(this.currentVRCamera instanceof a0))return;e?this._rotationAngle++:this._rotationAngle--,this.currentVRCamera.animations=[];let t=rf._f.FromRotationMatrix(rf.y3.RotationY(Math.PI/4*this._rotationAngle)),i=new rJ("animationRotation","rotationQuaternion",90,rJ.ANIMATIONTYPE_QUATERNION,rJ.ANIMATIONLOOPMODE_CONSTANT),r=[];r.push({frame:0,value:this.currentVRCamera.rotationQuaternion}),r.push({frame:6,value:t}),i.setKeys(r),i.setEasingFunction(this._circleEase),this.currentVRCamera.animations.push(i),this._postProcessMove.animations=[];let s=new rJ("animationPP","vignetteWeight",90,rJ.ANIMATIONTYPE_FLOAT,rJ.ANIMATIONLOOPMODE_CONSTANT),n=[];n.push({frame:0,value:0}),n.push({frame:3,value:4}),n.push({frame:6,value:0}),s.setKeys(n),s.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(s);let a=new rJ("animationPP2","vignetteStretch",90,rJ.ANIMATIONTYPE_FLOAT,rJ.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:3,value:10}),o.push({frame:6,value:0}),a.setKeys(o),a.setEasingFunction(this._circleEase),this._postProcessMove.animations.push(a),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._postProcessMove.samples=4,this._scene.beginAnimation(this.currentVRCamera,0,6,!1,1)}teleportCamera(e){let t,i;if(!(this.currentVRCamera instanceof a0))return;if(this._workingVector.copyFrom(e),this.isInVRMode||(this._workingVector.y+=this._defaultHeight),this.onBeforeCameraTeleport.notifyObservers(this._workingVector),this._teleportationMode==hn.TELEPORTATIONMODE_CONSTANTSPEED){i=90;let e=rf.P.Distance(this.currentVRCamera.position,this._workingVector);t=this._teleportationSpeed/e}else i=Math.round(90*this._teleportationTime/1e3),t=1;this.currentVRCamera.animations=[];let r=new rJ("animationCameraTeleportation","position",90,rJ.ANIMATIONTYPE_VECTOR3,rJ.ANIMATIONLOOPMODE_CONSTANT),s=[{frame:0,value:this.currentVRCamera.position},{frame:i,value:this._workingVector}];r.setKeys(s),r.setEasingFunction(this._teleportationEasing),this.currentVRCamera.animations.push(r),this._postProcessMove.animations=[];let n=Math.round(i/2),a=new rJ("animationPP","vignetteWeight",90,rJ.ANIMATIONTYPE_FLOAT,rJ.ANIMATIONLOOPMODE_CONSTANT),o=[];o.push({frame:0,value:0}),o.push({frame:n,value:8}),o.push({frame:i,value:0}),a.setKeys(o),this._postProcessMove.animations.push(a);let l=new rJ("animationPP2","vignetteStretch",90,rJ.ANIMATIONTYPE_FLOAT,rJ.ANIMATIONLOOPMODE_CONSTANT),h=[];h.push({frame:0,value:0}),h.push({frame:n,value:10}),h.push({frame:i,value:0}),l.setKeys(h),this._postProcessMove.animations.push(l),this._postProcessMove.imageProcessingConfiguration.vignetteWeight=0,this._postProcessMove.imageProcessingConfiguration.vignetteStretch=0,this._scene.beginAnimation(this.currentVRCamera,0,i,!1,t,()=>{this.onAfterCameraTeleport.notifyObservers(this._workingVector)}),this._hideTeleportationTarget()}setLaserColor(e,t=this._pickedLaserColor){this._pickedLaserColor=t}setLaserLightingState(e=!0){}setGazeColor(e,t=this._pickedGazeColor){this._pickedGazeColor=t}changeLaserColor(e){if(!this.updateControllerLaserColor)return}changeGazeColor(e){this.updateGazeTrackerColor&&this._cameraGazer._gazeTracker.material&&(this._cameraGazer._gazeTracker.material.emissiveColor=e)}dispose(){this.isInVRMode&&this.exitVR(),this._postProcessMove&&this._postProcessMove.dispose(),this._vrDeviceOrientationCamera&&this._vrDeviceOrientationCamera.dispose(),!this._useCustomVRButton&&this._btnVR&&this._btnVR.parentNode&&document.body.removeChild(this._btnVR),this._deviceOrientationCamera&&this._scene.activeCamera!=this._deviceOrientationCamera&&this._deviceOrientationCamera.dispose(),this._cameraGazer&&this._cameraGazer.dispose(),this._teleportationTarget&&this._teleportationTarget.dispose(),this.xr&&this.xr.dispose(),this._floorMeshesCollection.length=0,document.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("vrdisplaypresentchange",this._onVrDisplayPresentChangeBind),window.removeEventListener("resize",this._onResize),document.removeEventListener("fullscreenchange",this._onFullscreenChange),this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected),this._scene.unregisterBeforeRender(this._beforeRender)}getClassName(){return"VRExperienceHelper"}}hn.TELEPORTATIONMODE_CONSTANTTIME=0,hn.TELEPORTATIONMODE_CONSTANTSPEED=1;let ha=(e,t,i,r)=>!(e.x>i.x+r)&&!(i.x-r>t.x)&&!(e.y>i.y+r)&&!(i.y-r>t.y)&&!(e.z>i.z+r)&&!(i.z-r>t.z),ho=function(){let e={root:0,found:!1};return function(t,i,r,s){e.root=0,e.found=!1;let n=i*i-4*t*r;if(n<0)return e;let a=Math.sqrt(n),o=(-i-a)/(2*t),l=(-i+a)/(2*t);if(o>l){let e=l;l=o,o=e}return o>0&&o0&&l=0))}_canDoCollision(e,t,i,r){let s=rf.P.Distance(this._basePointWorld,e),n=Math.max(this._radius.x,this._radius.y,this._radius.z);return!(s>this._velocityWorldLength+n+t)&&!!ha(i,r,this._basePointWorld,this._velocityWorldLength+n)}_testTriangle(e,t,i,r,s,n,a){let o;let l=!1;t||(t=[]),t[e]||(t[e]=new sz.J(0,0,0,0),t[e].copyFromPoints(i,r,s));let h=t[e];if(!n&&!h.isFrontFacingTo(this._normalizedVelocity,0))return;let u=h.signedDistanceTo(this._basePoint),c=rf.P.Dot(h.normal,this._velocity);if(hl.DoubleSidedCheck&&c>1e-4)return;if(0==c){if(Math.abs(u)>=1)return;l=!0,o=0}else{o=(-1-u)/c;let e=(1-u)/c;if(o>e){let t=e;e=o,o=t}if(o>1||e<0)return;o<0&&(o=0),o>1&&(o=1)}this._collisionPoint.copyFromFloats(0,0,0);let d=!1,p=1;if(!l&&(this._basePoint.subtractToRef(h.normal,this._planeIntersectionPoint),this._velocity.scaleToRef(o,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,i,r,s,h.normal)&&(d=!0,p=o,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!d){let e=this._velocitySquaredLength;this._basePoint.subtractToRef(i,this._tempVector);let t=2*rf.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,a=ho(e,t,n,p);a.found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(i)),this._basePoint.subtractToRef(r,this._tempVector),(a=ho(e,t=2*rf.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(r)),this._basePoint.subtractToRef(s,this._tempVector),(a=ho(e,t=2*rf.P.Dot(this._velocity,this._tempVector),n=this._tempVector.lengthSquared()-1,p)).found&&(p=a.root,d=!0,this._collisionPoint.copyFrom(s)),r.subtractToRef(i,this._edge),i.subtractToRef(this._basePoint,this._baseToVertex);let o=this._edge.lengthSquared(),l=rf.P.Dot(this._edge,this._velocity),h=rf.P.Dot(this._edge,this._baseToVertex);if((a=ho(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rf.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),i.addToRef(this._edge,this._collisionPoint))}if(s.subtractToRef(r,this._edge),r.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=rf.P.Dot(this._edge,this._velocity),h=rf.P.Dot(this._edge,this._baseToVertex),(a=ho(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rf.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),r.addToRef(this._edge,this._collisionPoint))}if(i.subtractToRef(s,this._edge),s.subtractToRef(this._basePoint,this._baseToVertex),o=this._edge.lengthSquared(),l=rf.P.Dot(this._edge,this._velocity),h=rf.P.Dot(this._edge,this._baseToVertex),(a=ho(e=-(o*this._velocitySquaredLength)+l*l,t=2*(o*rf.P.Dot(this._velocity,this._baseToVertex)-l*h),n=o*(1-this._baseToVertex.lengthSquared())+h*h,p)).found){let e=(l*a.root-h)/o;e>=0&&e<=1&&(p=a.root,d=!0,this._edge.scaleInPlace(e),s.addToRef(this._edge,this._collisionPoint))}}if(d){let e=p*p*this._velocitySquaredLength;(!this.collisionFound||e=r){s.copyFrom(e);return}let o=n?n.collisionMask:i.collisionMask;i._initialize(e,t,a);let l=n&&n.surroundingMeshes||this._scene.meshes;for(let e=0;enew hh,i(5790);class hu{constructor(e,t,i,r=""){var s,n;let a;this.name=null,this.defines="",this.onCompiled=null,this.onError=null,this.uniqueId=0,this.onCompileObservable=new r_.y$,this.onErrorObservable=new r_.y$,this.onBindObservable=new r_.y$,this._wasPreviouslyReady=!1,this._isReady=!1,this._compilationError="",this._key="",this._computeSourceCodeOverride="",this._pipelineContext=null,this._computeSourceCode="",this._rawComputeSourceCode="",this._shaderLanguage=nG.x.WGSL,this.name=e,this._key=r,this._engine=i,this.uniqueId=hu._UniqueIdSeed++,this.defines=null!==(s=t.defines)&&void 0!==s?s:"",this.onError=t.onError,this.onCompiled=t.onCompiled,this._entryPoint=null!==(n=t.entryPoint)&&void 0!==n?n:"main",this._shaderStore=nw.v.GetShadersStore(this._shaderLanguage),this._shaderRepository=nw.v.GetShadersRepository(this._shaderLanguage),this._includeShaderStore=nw.v.GetIncludesShadersStore(this._shaderLanguage);let o=(0,sP.CG)()?this._engine.getHostDocument():null;e.computeSource?a="source:"+e.computeSource:e.computeElement?(a=o?o.getElementById(e.computeElement):null)||(a=e.computeElement):a=e.compute||e;let l={defines:this.defines.split("\n"),indexParameters:void 0,isFragment:!1,shouldUseHighPrecisionShader:!1,processor:null,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:this._shaderRepository,includesShadersStore:this._includeShaderStore,version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:null,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer};this._loadShader(a,"Compute","",i=>{lw.L.Initialize(l),lw.L.PreProcess(i,l,r=>{this._rawComputeSourceCode=i,t.processFinalCode&&(r=t.processFinalCode(r));let s=lw.L.Finalize(r,"",l);this._useFinalCode(s.vertexCode,e)},this._engine)})}_useFinalCode(e,t){if(t){let i=t.computeElement||t.compute||t.spectorName||t;this._computeSourceCode="//#define SHADER_NAME compute:"+i+"\n"+e}else this._computeSourceCode=e;this._prepareEffect()}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch(e){return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getCompilationError(){return this._compilationError}executeWhenCompiled(e){if(this.isReady()){e(this);return}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){this._processCompilationErrors(t,e);return}setTimeout(()=>{this._checkIsReady(e)},16)}_loadShader(e,t,i,r){let s;if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){r((0,sP.v)(e));return}if("source:"===e.substr(0,7)){r(e.substr(7));return}if("base64:"===e.substr(0,7)){r(window.atob(e.substr(7)));return}if(this._shaderStore[e+t+"Shader"]){r(this._shaderStore[e+t+"Shader"]);return}if(i&&this._shaderStore[e+i+"Shader"]){r(this._shaderStore[e+i+"Shader"]);return}s="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:this._shaderRepository+e,this._engine._loadFile(s+"."+t.toLowerCase()+".fx",r)}get computeSourceCode(){var e,t;return this._computeSourceCodeOverride?this._computeSourceCodeOverride:null!==(t=null===(e=this._pipelineContext)||void 0===e?void 0:e._getComputeShaderCode())&&void 0!==t?t:this._computeSourceCode}get rawComputeSourceCode(){return this._rawComputeSourceCode}_prepareEffect(){let e=this.defines,t=this._pipelineContext;this._isReady=!1;try{let i=this._engine;this._pipelineContext=i.createComputePipelineContext(),this._pipelineContext._name=this._key,i._prepareComputePipelineContext(this._pipelineContext,this._computeSourceCodeOverride?this._computeSourceCodeOverride:this._computeSourceCode,this._rawComputeSourceCode,this._computeSourceCodeOverride?null:e,this._entryPoint),i._executeWhenComputeStateIsCompiled(this._pipelineContext,()=>{this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),t&&this.getEngine()._deleteComputePipelineContext(t)}),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t){let i=null;if(t&&e){let r=t.match(/COMPUTE SHADER ERROR: 0:(\d+?):/);if(r&&2===r.length){let t=parseInt(r[1]),s=e.split("\n",-1);s.length>=t&&(i=`Offending line [${t}] in compute code: ${s[t-1]}`)}}return[e,i]}_processCompilationErrors(e,t=null){var i;if(this._compilationError=e.message,rb.Y.Error("Unable to compile compute effect:"),rb.Y.Error("Defines:\n"+this.defines),hu.LogShaderCodeOnCompilationError){let e=null,t=null;(null===(i=this._pipelineContext)||void 0===i?void 0:i._getComputeShaderCode())&&([t,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getComputeShaderCode(),this._compilationError),t&&(rb.Y.Error("Compute code:"),rb.Y.Error(t))),e&&rb.Y.Error(e)}rb.Y.Error("Error: "+this._compilationError),t&&(this._pipelineContext=t,this._isReady=!0,this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this))}dispose(){this._pipelineContext&&this._pipelineContext.dispose(),this._engine._releaseComputeEffect(this)}static RegisterShader(e,t){nw.v.GetShadersStore(nG.x.WGSL)[`${e}ComputeShader`]=t}}hu._UniqueIdSeed=0,hu.LogShaderCodeOnCompilationError=!0,(O=tU||(tU={}))[O.Texture=0]="Texture",O[O.StorageTexture=1]="StorageTexture",O[O.UniformBuffer=2]="UniformBuffer",O[O.StorageBuffer=3]="StorageBuffer",O[O.TextureWithoutSampler=4]="TextureWithoutSampler",O[O.Sampler=5]="Sampler",O[O.ExternalTexture=6]="ExternalTexture",sK.B.prototype.createComputeEffect=function(e,t){throw Error("createComputeEffect: This engine does not support compute shaders!")},sK.B.prototype.createComputePipelineContext=function(){throw Error("createComputePipelineContext: This engine does not support compute shaders!")},sK.B.prototype.createComputeContext=function(){},sK.B.prototype.computeDispatch=function(e,t,i,r,s,n,a){throw Error("computeDispatch: This engine does not support compute shaders!")},sK.B.prototype.areAllComputeEffectsReady=function(){return!0},sK.B.prototype.releaseComputeEffects=function(){},sK.B.prototype._prepareComputePipelineContext=function(e,t,i,r,s){},sK.B.prototype._rebuildComputeEffects=function(){},sK.B.prototype._executeWhenComputeStateIsCompiled=function(e,t){t()},sK.B.prototype._releaseComputeEffect=function(e){},sK.B.prototype._deleteComputePipelineContext=function(e){};var hc=i(7584),hd=i(7263);class hp{constructor(){this._gpuTimeInFrameId=-1,this.counter=new hd.z}_addDuration(e,t){e{let n=()=>{this.dispatch(e,t,i)?s():setTimeout(n,r)};n()})}serialize(){let e=rG.p4.Serialize(this);for(let t in e.options=this._options,e.shaderPath=this._shaderPath,e.bindings={},e.textures={},this._bindings){let i=this._bindings[t],r=i.object;switch(i.type){case tU.Texture:case tU.TextureWithoutSampler:case tU.StorageTexture:{let s=r.serialize();s&&(e.textures[t]=s,e.bindings[t]={type:i.type})}case tU.UniformBuffer:}}return e}static Parse(e,t,i){let r=rG.p4.Parse(()=>new h_(e.name,t.getEngine(),e.shaderPath,e.options),e,t,i);for(let s in e.textures){let n=e.bindings[s],a=sj.Parse(e.textures[s],t,i);n.type===tU.Texture?r.setTexture(s,a):n.type===tU.TextureWithoutSampler?r.setTexture(s,a,!1):r.setStorageTexture(s,a)}return r}}(0,sx.gn)([(0,rG.qC)()],h_.prototype,"name",void 0),(0,sx.gn)([(0,rG.qC)()],h_.prototype,"fastMode",void 0),(0,rg.H)("BABYLON.ComputeShader",h_);var hf=i(4347),hm=i(5681),hg=i(3592);class hv{constructor(e,t,i,r,s,n){this.entries=[],this._boundingVectors=[],this._capacity=i,this._depth=r,this._maxDepth=s,this._creationFunc=n,this._minPoint=e,this._maxPoint=t,this._boundingVectors.push(e.clone()),this._boundingVectors.push(t.clone()),this._boundingVectors.push(e.clone()),this._boundingVectors[2].x=t.x,this._boundingVectors.push(e.clone()),this._boundingVectors[3].y=t.y,this._boundingVectors.push(e.clone()),this._boundingVectors[4].z=t.z,this._boundingVectors.push(t.clone()),this._boundingVectors[5].z=e.z,this._boundingVectors.push(t.clone()),this._boundingVectors[6].x=e.x,this._boundingVectors.push(t.clone()),this._boundingVectors[7].y=e.y}get capacity(){return this._capacity}get minPoint(){return this._minPoint}get maxPoint(){return this._maxPoint}addEntry(e){if(this.blocks){for(let t=0;tthis.capacity&&this._depth-1&&this.entries.splice(t,1)}addEntries(e){for(let t=0;t{let i=e.getBoundingInfo();!e.isBlocked&&i.boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},hx.CreationFuncForSubMeshes=(e,t)=>{e.getBoundingInfo().boundingBox.intersectsMinMax(t.minPoint,t.maxPoint)&&t.entries.push(e)},r2.x.prototype.createOrUpdateSelectionOctree=function(e=64,t=2){let i=this._getComponent(sN.l.NAME_OCTREE);i||(i=new hT(this),this._addComponent(i)),this._selectionOctree||(this._selectionOctree=new hx(hx.CreationFuncForMeshes,e,t));let r=this.getWorldExtends();return this._selectionOctree.update(r.min,r.max,this.meshes),this._selectionOctree},Object.defineProperty(r2.x.prototype,"selectionOctree",{get:function(){return this._selectionOctree},enumerable:!0,configurable:!0}),sf.x.prototype.createOrUpdateSubmeshesOctree=function(e=64,t=2){let i=this.getScene(),r=i._getComponent(sN.l.NAME_OCTREE);r||(r=new hT(i),i._addComponent(r)),this._submeshesOctree||(this._submeshesOctree=new hx(hx.CreationFuncForSubMeshes,e,t)),this.computeWorldMatrix(!0);let s=this.getBoundingInfo().boundingBox;return this._submeshesOctree.update(s.minimumWorld,s.maximumWorld,this.subMeshes),this._submeshesOctree};class hT{constructor(e){if(this.name=sN.l.NAME_OCTREE,this.checksIsEnabled=!0,this._tempRay=new s6(rf.P.Zero(),new rf.P(1,1,1)),!(e=e||rL.l.LastCreatedScene))return;this.scene=e,this.scene.getActiveMeshCandidates=()=>this.getActiveMeshCandidates(),this.scene.getActiveSubMeshCandidates=e=>this.getActiveSubMeshCandidates(e),this.scene.getCollidingSubMeshCandidates=(e,t)=>this.getCollidingSubMeshCandidates(e,t),this.scene.getIntersectingSubMeshCandidates=(e,t)=>this.getIntersectingSubMeshCandidates(e,t)}register(){this.scene.onMeshRemovedObservable.add(e=>{let t=this.scene.selectionOctree;if(null!=t){let i=t.dynamicContent.indexOf(e);-1!==i&&t.dynamicContent.splice(i,1)}}),this.scene.onMeshImportedObservable.add(e=>{let t=this.scene.selectionOctree;null!=t&&t.addMesh(e)})}getActiveMeshCandidates(){var e;return(null===(e=this.scene._selectionOctree)||void 0===e?void 0:e.select(this.scene.frustumPlanes))||this.scene._getDefaultMeshCandidates()}getActiveSubMeshCandidates(e){return e._submeshesOctree&&e.useOctreeForRenderingSelection?e._submeshesOctree.select(this.scene.frustumPlanes):this.scene._getDefaultSubMeshCandidates(e)}getIntersectingSubMeshCandidates(e,t){return e._submeshesOctree&&e.useOctreeForPicking?(s6.TransformToRef(t,e.getWorldMatrix(),this._tempRay),e._submeshesOctree.intersectsRay(this._tempRay)):this.scene._getDefaultSubMeshCandidates(e)}getCollidingSubMeshCandidates(e,t){if(e._submeshesOctree&&e.useOctreeForCollisions){let i=t._velocityWorldLength+Math.max(t._radius.x,t._radius.y,t._radius.z);return e._submeshesOctree.intersects(t._basePointWorld,i)}return this.scene._getDefaultSubMeshCandidates(e)}rebuild(){}dispose(){}}function hS(e){let t,i,r,s,n,a,o;let l=e.height||2,h=0===e.diameterTop?0:e.diameterTop||e.diameter||1,u=0===e.diameterBottom?0:e.diameterBottom||e.diameter||1;h=h||1e-5,u=u||1e-5;let c=0|(e.tessellation||24),d=0|(e.subdivisions||1),p=!!e.hasRings,_=!!e.enclose,f=0===e.cap?0:e.cap||sp.Kj.CAP_ALL,m=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,g=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE,v=e.faceUV||[,,,],x=e.faceColors,T=2+(1+(1!==m&&_?2:0))*(p?d:1);for(t=0;t{let t,i,r;let s=e?h/2:u/2;if(0===s)return;let n=e?v[T-1]:v[0],a=null;x&&(a=e?x[T-1]:x[0]);let o=E.length/3,d=e?l/2:-l/2,p=new rf.P(0,d,0);E.push(p.x,p.y,p.z),C.push(0,e?1:-1,0);let _=n.y+(n.w-n.y)*.5;b.push(n.x+(n.z-n.x)*.5,sY.e.UseOpenGLOrientationForUV?1-_:_),a&&y.push(a.r,a.g,a.b,a.a);let f=new rf.FM(.5,.5);for(r=0;r<=c;r++){let o=Math.cos(-(t=2*Math.PI*r*m/c)),l=Math.sin(-t);i=new rf.P(o*s,d,l*s);let h=new rf.FM(o*f.x+.5,l*f.y+.5);E.push(i.x,i.y,i.z),C.push(0,e?1:-1,0);let u=n.y+(n.w-n.y)*h.y;b.push(n.x+(n.z-n.x)*h.x,sY.e.UseOpenGLOrientationForUV?1-u:u),a&&y.push(a.r,a.g,a.b,a.a)}for(r=0;r(void 0!==a&&a instanceof r2.x||(void 0!==a&&(l=o||sp.Kj.DEFAULTSIDE,o=a),a=n,n=1),hE(e,{height:t,diameterTop:i,diameterBottom:r,tessellation:s,subdivisions:n,sideOrientation:l,updatable:o},a)),rW.N.AddNodeConstructor("Light_Type_3",(e,t)=>()=>new hC(e,rf.P.Zero(),t));class hC extends sE{constructor(e,t,i){super(e,i),this.groundColor=new rm.Wo(0,0,0),this.direction=t||rf.P.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=rf.P.Normalize(e.subtract(rf.P.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){let i=rf.P.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",i.x,i.y,i.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){let i=rf.P.Normalize(this.direction);return e.setFloat3(t,i.x,i.y,i.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=rf.y3.Identity()),this._worldMatrix}getTypeID(){return sE.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}(0,sx.gn)([(0,rG.n9)()],hC.prototype,"groundColor",void 0),(0,sx.gn)([(0,rG.hd)()],hC.prototype,"direction",void 0);class hb{getRenderCamera(e){if(this._renderCamera)return this._renderCamera;{let t;return(t=this.originalScene.activeCameras&&this.originalScene.activeCameras.length>1?this.originalScene.activeCameras[this.originalScene.activeCameras.length-1]:this.originalScene.activeCamera,e&&t&&t.isRigCamera)?t.rigParent:t}}setRenderCamera(e){this._renderCamera=e}_getSharedGizmoLight(){return this._sharedGizmoLight||(this._sharedGizmoLight=new hC("shared gizmo light",new rf.P(0,1,0),this.utilityLayerScene),this._sharedGizmoLight.intensity=2,this._sharedGizmoLight.groundColor=rm.Wo.Gray()),this._sharedGizmoLight}static get DefaultUtilityLayer(){return null==hb._DefaultUtilityLayer?hb._CreateDefaultUtilityLayerFromScene(rL.l.LastCreatedScene):hb._DefaultUtilityLayer}static _CreateDefaultUtilityLayerFromScene(e){return hb._DefaultUtilityLayer=new hb(e),hb._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{hb._DefaultUtilityLayer=null}),hb._DefaultUtilityLayer}static get DefaultKeepDepthUtilityLayer(){return null==hb._DefaultKeepDepthUtilityLayer&&(hb._DefaultKeepDepthUtilityLayer=new hb(rL.l.LastCreatedScene),hb._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil=!1,hb._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(()=>{hb._DefaultKeepDepthUtilityLayer=null})),hb._DefaultKeepDepthUtilityLayer}constructor(e,t=!0){this.originalScene=e,this._pointerCaptures={},this._lastPointerEvents={},this._sharedGizmoLight=null,this._renderCamera=null,this.pickUtilitySceneFirst=!0,this.shouldRender=!0,this.onlyCheckPointerDownEvents=!0,this.processAllEvents=!1,this.pickingEnabled=!0,this.onPointerOutObservable=new r_.y$,this.utilityLayerScene=new r2.x(e.getEngine(),{virtual:!0}),this.utilityLayerScene.useRightHandedSystem=e.useRightHandedSystem,this.utilityLayerScene._allowPostProcessClearColor=!1,this.utilityLayerScene.postProcessesEnabled=!1,this.utilityLayerScene.detachControl(),t&&(this._originalPointerObserver=e.onPrePointerObservable.add(t=>{if(!this.utilityLayerScene.activeCamera||!this.pickingEnabled||!this.processAllEvents&&t.type!==s0.kD.POINTERMOVE&&t.type!==s0.kD.POINTERUP&&t.type!==s0.kD.POINTERDOWN&&t.type!==s0.kD.POINTERDOUBLETAP)return;this.utilityLayerScene.pointerX=e.pointerX,this.utilityLayerScene.pointerY=e.pointerY;let i=t.event;if(e.isPointerCaptured(i.pointerId)){this._pointerCaptures[i.pointerId]=!1;return}let r=i=>{let r=null;if(t.nearInteractionPickingInfo)r=t.nearInteractionPickingInfo.pickedMesh.getScene()==i?t.nearInteractionPickingInfo:new s4.p;else if(i!==this.utilityLayerScene&&t.originalPickingInfo)r=t.originalPickingInfo;else{let s=null;this._renderCamera&&(s=i._activeCamera,i._activeCamera=this._renderCamera,t.ray=null),r=t.ray?i.pickWithRay(t.ray):i.pick(e.pointerX,e.pointerY),s&&(i._activeCamera=s)}return r},s=r(this.utilityLayerScene);if(!t.ray&&s&&(t.ray=s.ray),this.utilityLayerScene.onPrePointerObservable.notifyObservers(t),this.onlyCheckPointerDownEvents&&t.type!=s0.kD.POINTERDOWN){t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new s0.R5(t.type,t.event,s),t.type),t.type===s0.kD.POINTERUP&&this._pointerCaptures[i.pointerId]&&(this._pointerCaptures[i.pointerId]=!1);return}if(this.utilityLayerScene.autoClearDepthAndStencil||this.pickUtilitySceneFirst)s&&s.hit&&(t.skipOnPointerObservable||this.utilityLayerScene.onPointerObservable.notifyObservers(new s0.R5(t.type,t.event,s),t.type),t.skipOnPointerObservable=!0);else{let i=r(e),n=t.event;i&&s&&(0===s.distance&&i.pickedMesh?this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):t.type===s0.kD.POINTERDOWN?this._pointerCaptures[n.pointerId]=!0:(t.type===s0.kD.POINTERMOVE||t.type===s0.kD.POINTERUP)&&(this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,i,n)):!this._pointerCaptures[n.pointerId]&&(s.distance0)):!this._pointerCaptures[n.pointerId]&&s.distance>=i.distance&&(this.mainSceneTrackerPredicate&&this.mainSceneTrackerPredicate(i.pickedMesh)?(this._notifyObservers(t,i,n),t.skipOnPointerObservable=!0):((t.type===s0.kD.POINTERMOVE||t.type===s0.kD.POINTERUP)&&this._lastPointerEvents[n.pointerId]&&(this.onPointerOutObservable.notifyObservers(n.pointerId),delete this._lastPointerEvents[n.pointerId]),this._notifyObservers(t,s,n))),t.type===s0.kD.POINTERUP&&this._pointerCaptures[n.pointerId]&&(this._pointerCaptures[n.pointerId]=!1))}}),this._originalPointerObserver&&e.onPrePointerObservable.makeObserverTopPriority(this._originalPointerObserver)),this.utilityLayerScene.autoClear=!1,this._afterRenderObserver=this.originalScene.onAfterRenderCameraObservable.add(e=>{this.shouldRender&&e==this.getRenderCamera()&&this.render()}),this._sceneDisposeObserver=this.originalScene.onDisposeObservable.add(()=>{this.dispose()}),this._updateCamera()}_notifyObservers(e,t,i){e.skipOnPointerObservable||(this.utilityLayerScene.onPointerObservable.notifyObservers(new s0.R5(e.type,e.event,t),e.type),this._lastPointerEvents[i.pointerId]=!0)}render(){if(this._updateCamera(),this.utilityLayerScene.activeCamera){let e=this.utilityLayerScene.activeCamera.getScene(),t=this.utilityLayerScene.activeCamera;t._scene=this.utilityLayerScene,t.leftCamera&&(t.leftCamera._scene=this.utilityLayerScene),t.rightCamera&&(t.rightCamera._scene=this.utilityLayerScene),this.utilityLayerScene.render(!1),t._scene=e,t.leftCamera&&(t.leftCamera._scene=e),t.rightCamera&&(t.rightCamera._scene=e)}}dispose(){this.onPointerOutObservable.clear(),this._afterRenderObserver&&this.originalScene.onAfterCameraRenderObservable.remove(this._afterRenderObserver),this._sceneDisposeObserver&&this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver),this._originalPointerObserver&&this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver),this.utilityLayerScene.dispose()}_updateCamera(){this.utilityLayerScene.cameraToUseForPointers=this.getRenderCamera(),this.utilityLayerScene.activeCamera=this.getRenderCamera()}}hb._DefaultUtilityLayer=null,hb._DefaultKeepDepthUtilityLayer=null,(N=tV||(tV={}))[N.Origin=0]="Origin",N[N.Pivot=1]="Pivot",(F=tk||(tk={}))[F.World=0]="World",F[F.Local=1]="Local";class hy{set scaleRatio(e){this._scaleRatio=e}get scaleRatio(){return this._scaleRatio}get isHovered(){return this._isHovered}get attachedMesh(){return this._attachedMesh}set attachedMesh(e){this._attachedMesh=e,e&&(this._attachedNode=e),this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}get attachedNode(){return this._attachedNode}set attachedNode(e){this._attachedNode=e,this._attachedMesh=null,this._rootMesh.setEnabled(!!e),this._attachedNodeChanged(e)}setCustomMesh(e){if(e.getScene()!=this.gizmoLayer.utilityLayerScene)throw"When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";this._rootMesh.getChildMeshes().forEach(e=>{e.dispose()}),e.parent=this._rootMesh,this._customMeshSet=!0}set updateGizmoRotationToMatchAttachedMesh(e){this._updateGizmoRotationToMatchAttachedMesh=e}get updateGizmoRotationToMatchAttachedMesh(){return this._updateGizmoRotationToMatchAttachedMesh}set updateGizmoPositionToMatchAttachedMesh(e){this._updateGizmoPositionToMatchAttachedMesh=e}get updateGizmoPositionToMatchAttachedMesh(){return this._updateGizmoPositionToMatchAttachedMesh}set anchorPoint(e){this._anchorPoint=e}get anchorPoint(){return this._anchorPoint}set coordinatesMode(e){this._coordinatesMode=e;let t=e==tk.Local;this.updateGizmoRotationToMatchAttachedMesh=t,this.updateGizmoPositionToMatchAttachedMesh=!0}get coordinatesMode(){return this._coordinatesMode}set updateScale(e){this._updateScale=e}get updateScale(){return this._updateScale}_attachedNodeChanged(e){}constructor(e=hb.DefaultUtilityLayer){this.gizmoLayer=e,this._attachedMesh=null,this._attachedNode=null,this._customRotationQuaternion=null,this._scaleRatio=1,this._isHovered=!1,this._customMeshSet=!1,this._updateGizmoRotationToMatchAttachedMesh=!0,this._updateGizmoPositionToMatchAttachedMesh=!0,this._anchorPoint=tV.Origin,this._updateScale=!0,this._coordinatesMode=tk.Local,this._interactionsEnabled=!0,this._rightHandtoLeftHandMatrix=rf.y3.RotationY(Math.PI),this._rootMesh=new sp.Kj("gizmoRootNode",e.utilityLayerScene),this._rootMesh.rotationQuaternion=rf._f.Identity(),this._beforeRenderObserver=this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(()=>{this._update()})}get customRotationQuaternion(){return this._customRotationQuaternion}set customRotationQuaternion(e){this._customRotationQuaternion=e}_update(){if(this.attachedNode){let e=this.attachedNode;if(this.attachedMesh&&(e=this.attachedMesh||this.attachedNode),this.updateGizmoPositionToMatchAttachedMesh){if(this.anchorPoint==tV.Pivot&&e.getAbsolutePivotPoint){let t=e.getAbsolutePivotPoint();this._rootMesh.position.copyFrom(t)}else{let t=e.getWorldMatrix().getRow(3),i=t?t.toVector3():new rf.P(0,0,0);this._rootMesh.position.copyFrom(i)}}if(this.updateGizmoRotationToMatchAttachedMesh){let t=e._isMesh||"AbstractMesh"===e.getClassName()||"TransformNode"===e.getClassName()||"InstancedMesh"===e.getClassName()?e:void 0;e.getWorldMatrix().decompose(void 0,this._rootMesh.rotationQuaternion,void 0,hy.PreserveScaling?t:void 0),this._rootMesh.rotationQuaternion.normalize()}else this._customRotationQuaternion?this._rootMesh.rotationQuaternion.copyFrom(this._customRotationQuaternion):this._rootMesh.rotationQuaternion.set(0,0,0,1);if(this.updateScale){let t=this.gizmoLayer.utilityLayerScene.activeCamera,i=t.globalPosition;this._rootMesh.position.subtractToRef(i,rf.jp.Vector3[0]);let r=this.scaleRatio;if(t.mode==sC.V.ORTHOGRAPHIC_CAMERA)t.orthoTop&&t.orthoBottom&&(r*=t.orthoTop-t.orthoBottom);else{let e=t.getScene().useRightHandedSystem?rf.P.RightHandedForwardReadOnly:rf.P.LeftHandedForwardReadOnly,i=t.getDirection(e);r*=rf.P.Dot(rf.jp.Vector3[0],i)}this._rootMesh.scaling.setAll(r),0>e._getWorldMatrixDeterminant()&&!hy.PreserveScaling&&(this._rootMesh.scaling.y*=-1)}else this._rootMesh.scaling.setAll(this.scaleRatio)}}_handlePivotMatrixInverse(e,t,i){if(e.isUsingPivotMatrix()&&!e.isUsingPostMultiplyPivotMatrix()){e.getPivotMatrix().invertToRef(rf.jp.Matrix[5]),rf.jp.Matrix[5].multiplyToRef(t,i);return}i.copyFrom(t)}_matrixChanged(){if(this._attachedNode){if(this._attachedNode._isCamera){let e,t;let i=this._attachedNode;if(i.parent){let t=rf.jp.Matrix[1];i.parent._worldMatrix.invertToRef(t),this._attachedNode._worldMatrix.multiplyToRef(t,rf.jp.Matrix[0]),e=rf.jp.Matrix[0]}else e=this._attachedNode._worldMatrix;if(i.getScene().useRightHandedSystem?(this._rightHandtoLeftHandMatrix.multiplyToRef(e,rf.jp.Matrix[1]),t=rf.jp.Matrix[1]):t=e,t.decompose(rf.jp.Vector3[1],rf.jp.Quaternion[0],rf.jp.Vector3[0]),"FreeCamera"===this._attachedNode.getClassName()||"FlyCamera"===this._attachedNode.getClassName()||"ArcFollowCamera"===this._attachedNode.getClassName()||"TargetCamera"===this._attachedNode.getClassName()||"TouchCamera"===this._attachedNode.getClassName()||"UniversalCamera"===this._attachedNode.getClassName()){let e=this._attachedNode;e.rotation=rf.jp.Quaternion[0].toEulerAngles(),e.rotationQuaternion&&(e.rotationQuaternion.copyFrom(rf.jp.Quaternion[0]),e.rotationQuaternion.normalize())}i.position.copyFrom(rf.jp.Vector3[0])}else if(this._attachedNode._isMesh||"AbstractMesh"===this._attachedNode.getClassName()||"TransformNode"===this._attachedNode.getClassName()||"InstancedMesh"===this._attachedNode.getClassName()){let e=this._attachedNode;if(e.parent){let t=rf.jp.Matrix[0],i=rf.jp.Matrix[1];e.parent.getWorldMatrix().invertToRef(t),this._attachedNode.getWorldMatrix().multiplyToRef(t,i);let r=rf.jp.Matrix[4];if(this._handlePivotMatrixInverse(e,i,r),r.decompose(rf.jp.Vector3[0],rf.jp.Quaternion[0],e.position,hy.PreserveScaling?e:void 0,hy.UseAbsoluteScaling),rf.jp.Quaternion[0].normalize(),e.isUsingPivotMatrix()){let t=rf.jp.Quaternion[1];rf._f.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,e.rotation.z,t);let i=rf.jp.Matrix[2];rf.y3.ScalingToRef(e.scaling.x,e.scaling.y,e.scaling.z,i);let r=rf.jp.Matrix[2];t.toRotationMatrix(r);let s=e.getPivotMatrix(),n=rf.jp.Matrix[3];s.invertToRef(n),s.multiplyToRef(i,rf.jp.Matrix[4]),rf.jp.Matrix[4].multiplyToRef(r,rf.jp.Matrix[5]),rf.jp.Matrix[5].multiplyToRef(n,rf.jp.Matrix[6]),rf.jp.Matrix[6].getTranslationToRef(rf.jp.Vector3[1]),e.position.subtractInPlace(rf.jp.Vector3[1])}}else{let t=rf.jp.Matrix[4];this._handlePivotMatrixInverse(e,this._attachedNode._worldMatrix,t),t.decompose(rf.jp.Vector3[0],rf.jp.Quaternion[0],e.position,hy.PreserveScaling?e:void 0,hy.UseAbsoluteScaling)}rf.jp.Vector3[0].scaleInPlace(1/e.scalingDeterminant),e.scaling.copyFrom(rf.jp.Vector3[0]),e.billboardMode||(e.rotationQuaternion?(e.rotationQuaternion.copyFrom(rf.jp.Quaternion[0]),e.rotationQuaternion.normalize()):e.rotation=rf.jp.Quaternion[0].toEulerAngles())}else if("Bone"===this._attachedNode.getClassName()){let e=this._attachedNode,t=e.getParent();if(t){let i=rf.jp.Matrix[0],r=rf.jp.Matrix[1];t.getFinalMatrix().invertToRef(i),e.getFinalMatrix().multiplyToRef(i,r),e.getLocalMatrix().copyFrom(r)}else e.getLocalMatrix().copyFrom(e.getFinalMatrix());e.markAsDirty()}else{let e=this._attachedNode;if(e.getTypeID){let t=e.getTypeID();if(t===sE.LIGHTTYPEID_DIRECTIONALLIGHT||t===sE.LIGHTTYPEID_SPOTLIGHT||t===sE.LIGHTTYPEID_POINTLIGHT){let t=e.parent;if(t){let i=rf.jp.Matrix[0],r=rf.jp.Matrix[1];t.getWorldMatrix().invertToRef(i),e.getWorldMatrix().multiplyToRef(i,r),r.decompose(void 0,rf.jp.Quaternion[0],rf.jp.Vector3[0])}else this._attachedNode._worldMatrix.decompose(void 0,rf.jp.Quaternion[0],rf.jp.Vector3[0]);e.position=new rf.P(rf.jp.Vector3[0].x,rf.jp.Vector3[0].y,rf.jp.Vector3[0].z),e.direction&&(e.direction=new rf.P(e.direction.x,e.direction.y,e.direction.z))}}}}}_setGizmoMeshMaterial(e,t){e&&e.forEach(e=>{e.material=t,e.color&&(e.color=t.diffuseColor)})}static GizmoAxisPointerObserver(e,t){let i=!1;return e.utilityLayerScene.onPointerObservable.add(e=>{var r,s;if(e.pickInfo){if(e.type===s0.kD.POINTERMOVE){if(i)return;t.forEach(t=>{var i,r;if(t.colliderMeshes&&t.gizmoMeshes){let s=(null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1,n=t.dragBehavior.enabled?s||t.active?t.hoverMaterial:t.material:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=n,e.color&&(e.color=n.diffuseColor)})}})}e.type===s0.kD.POINTERDOWN&&t.has(null===(r=e.pickInfo.pickedMesh)||void 0===r?void 0:r.parent)&&(i=!0,t.get(null===(s=e.pickInfo.pickedMesh)||void 0===s?void 0:s.parent).active=!0,t.forEach(t=>{var i,r;let s=((null===(i=t.colliderMeshes)||void 0===i?void 0:i.indexOf(null===(r=null==e?void 0:e.pickInfo)||void 0===r?void 0:r.pickedMesh))!=-1||t.active)&&t.dragBehavior.enabled?t.hoverMaterial:t.disableMaterial;t.gizmoMeshes.forEach(e=>{e.material=s,e.color&&(e.color=s.diffuseColor)})})),e.type===s0.kD.POINTERUP&&t.forEach(e=>{e.active=!1,i=!1,e.gizmoMeshes.forEach(t=>{t.material=e.dragBehavior.enabled?e.material:e.disableMaterial,t.color&&(t.color=e.material.diffuseColor)})})}})}dispose(){this._rootMesh.dispose(),this._beforeRenderObserver&&this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver)}}hy.PreserveScaling=!1,hy.UseAbsoluteScaling=!0,Object.defineProperty(r2.x.prototype,"debugLayer",{get:function(){return this._debugLayer||(this._debugLayer=new hA(this)),this._debugLayer},enumerable:!0,configurable:!0}),(L=tG||(tG={}))[L.Properties=0]="Properties",L[L.Debug=1]="Debug",L[L.Statistics=2]="Statistics",L[L.Tools=3]="Tools",L[L.Settings=4]="Settings";class hA{get onPropertyChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable:(this._onPropertyChangedObservable||(this._onPropertyChangedObservable=new r_.y$),this._onPropertyChangedObservable)}get onSelectionChangedObservable(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector?this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable:(this._onSelectionChangedObservable||(this._onSelectionChangedObservable=new r_.y$),this._onSelectionChangedObservable)}constructor(e){if(this.BJSINSPECTOR=this._getGlobalInspector(),this._scene=e||rL.l.LastCreatedScene,!this._scene)return;this._scene.onDisposeObservable.add(()=>{this._scene._debugLayer&&this._scene._debugLayer.hide()})}_createInspector(e){if(this.isVisible())return;if(this._onPropertyChangedObservable){for(let e of this._onPropertyChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(e);this._onPropertyChangedObservable.clear(),this._onPropertyChangedObservable=void 0}if(this._onSelectionChangedObservable){for(let e of this._onSelectionChangedObservable.observers)this.BJSINSPECTOR.Inspector.OnSelectionChangedObservable.add(e);this._onSelectionChangedObservable.clear(),this._onSelectionChangedObservable=void 0}let t=Object.assign(Object.assign({},hA.Config),e);this.BJSINSPECTOR=this.BJSINSPECTOR||this._getGlobalInspector(),this.BJSINSPECTOR.Inspector.Show(this._scene,t)}select(e,t){this.BJSINSPECTOR&&(t&&("[object String]"==Object.prototype.toString.call(t)?this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(t):this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(t)),this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(e))}_getGlobalInspector(){return"undefined"!=typeof INSPECTOR?INSPECTOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.Inspector?BABYLON:void 0}isVisible(){return this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.IsVisible}hide(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector.Hide()}setAsActiveScene(){this.BJSINSPECTOR&&this.BJSINSPECTOR.Inspector._SetNewScene(this._scene)}show(e){return new Promise(t=>{if(void 0===this.BJSINSPECTOR){let i=e&&e.inspectorURL?e.inspectorURL:hA.InspectorURL;sg.w1.LoadBabylonScript(i,()=>{this._createInspector(e),t(this)})}else this._createInspector(e),t(this)})}}function hR(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],i=[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],r=[],s=[],n=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,l=e.wrap||!1,h=void 0===e.topBaseAt?1:e.topBaseAt,u=void 0===e.bottomBaseAt?0:e.bottomBaseAt;h=(h+4)%4,u=(u+4)%4;let c=[2,0,3,1][h],d=[2,0,1,3][u],p=[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(l){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],p=[-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]],i=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]],r=[17,18,19,16],s=[22,23,20,21];for(;c>0;)e.unshift(e.pop()),r.unshift(r.pop()),c--;for(;d>0;)i.unshift(i.pop()),s.unshift(s.pop()),d--;e=e.flat(),i=i.flat(),p=p.concat(e).concat(i),t.push(r[0],r[2],r[3],r[0],r[1],r[2]),t.push(s[0],s[2],s[3],s[0],s[1],s[2])}let _=[n/2,a/2,o/2];s=p.reduce((e,t,i)=>e.concat(t*_[i%3]),[]);let f=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE,m=e.faceUV||Array(6),g=e.faceColors,v=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new rf.Lt(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new rm.HE(1,1,1,1));for(let e=0;e<6;e++)if(r.push(m[e].z,sY.e.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,sY.e.UseOpenGLOrientationForUV?1-m[e].w:m[e].w),r.push(m[e].x,sY.e.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),r.push(m[e].z,sY.e.UseOpenGLOrientationForUV?1-m[e].y:m[e].y),g)for(let t=0;t<4;t++)v.push(g[e].r,g[e].g,g[e].b,g[e].a);s7.x._ComputeSides(f,s,t,i,r,e.frontUVs,e.backUVs);let x=new s7.x;if(x.indices=t,x.positions=s,x.normals=i,x.uvs=r,g){let e=f===s7.x.DOUBLESIDE?v.concat(v):v;x.colors=e}return x}function hP(e,t={},i=null){let r=new sp.Kj(e,i);return t.sideOrientation=sp.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,hR(t).applyToMesh(r,t.updatable),r}function hI(e){let t=0|(e.segments||32),i=e.diameterX||e.diameter||1,r=e.diameterY||e.diameter||1,s=e.diameterZ||e.diameter||1,n=e.arc&&(e.arc<=0||e.arc>1)?1:e.arc||1,a=e.slice&&e.slice<=0?1:e.slice||1,o=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE,l=!!e.dedupTopBottomIndices,h=new rf.P(i/2,r/2,s/2),u=2+t,c=2*u,d=[],p=[],_=[],f=[];for(let e=0;e<=u;e++){let t=e/u,i=t*Math.PI*a;for(let e=0;e<=c;e++){let r=e/c,s=r*Math.PI*2*n,a=rf.y3.RotationZ(-i),o=rf.y3.RotationY(s),l=rf.P.TransformCoordinates(rf.P.Up(),a),u=rf.P.TransformCoordinates(l,o),d=u.multiply(h),m=u.divide(h).normalize();p.push(d.x,d.y,d.z),_.push(m.x,m.y,m.z),f.push(r,sY.e.UseOpenGLOrientationForUV?1-t:t)}if(e>0){let t=p.length/3;for(let i=t-2*(c+1);i+c+21&&(d.push(i),d.push(i+1),d.push(i+c+1)),(em?m:Math.floor(g);let v=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE,x=e.uvs,T=e.colors,S=[],E=[],C=[],b=[],y=[],A=[],R=[],P=[],I=[],M=[];if(d.length<2){let e=[],t=[];for(r=0;r0&&(o=n[s].subtract(n[s-1]).length()+R[i],y[i].push(o),R[i]=o),s++;_&&(s--,S.push(n[0].x,n[0].y,n[0].z),o=n[s].subtract(n[0]).length()+R[i],y[i].push(o),R[i]=o),I[i]=a+O,M[i]=D,D+=a+O}let N=null,F=null;for(r=0;r{let s=r[0].length,n=0,a=o._originalBuilderSideOrientation===sp.Kj.DOUBLESIDE?2:1;for(let l=1;l<=a;++l)for(let a=0;a1)?1:e.arc||1,l=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE;t.push(0,0,0),s.push(.5,.5);let h=2*Math.PI*o,u=1===o?h/a:h/(a-1),c=0;for(let e=0;e0||c>0){switch(m=-d,g=-p,v=d,x=p,s){case sp.Kj.CENTER:l/=2,m-=l,v+=l;break;case sp.Kj.LEFT:v+=l,_=-l/2;break;case sp.Kj.RIGHT:m-=l,_=l/2}switch(n){case sp.Kj.CENTER:c/=2,g-=c,x+=c;break;case sp.Kj.BOTTOM:x+=c,f=-c/2;break;case sp.Kj.TOP:g-=c,f=c/2}}let T=[],S=[],E=[];E[0]=[0,0,1,0,1,1,0,1],E[1]=[0,0,1,0,1,1,0,1],(t===sp.Kj.ROTATE_TILE||t===sp.Kj.ROTATE_ROW)&&(E[1]=[1,1,0,1,0,0,1,0]),(t===sp.Kj.FLIP_TILE||t===sp.Kj.FLIP_ROW)&&(E[1]=[1,0,0,0,0,1,1,1]),(t===sp.Kj.FLIP_N_ROTATE_TILE||t===sp.Kj.FLIP_N_ROTATE_ROW)&&(E[1]=[0,1,1,1,1,0,0,0]);let C=[],b=[],y=[],A=0;for(let e=0;e0||c>0){let e,a,h,E;let R=c>0&&(n===sp.Kj.CENTER||n===sp.Kj.TOP),P=c>0&&(n===sp.Kj.CENTER||n===sp.Kj.BOTTOM),I=l>0&&(s===sp.Kj.CENTER||s===sp.Kj.RIGHT),M=l>0&&(s===sp.Kj.CENTER||s===sp.Kj.LEFT),D=[];if(R&&I&&(T.push(m+_,g+f,0),T.push(-d+_,g+f,0),T.push(-d+_,g+c+f,0),T.push(m+_,g+c+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,h=1,E=1,D=[e=1-l/i,a=1-c/r,h,a,h,E,e,E],t===sp.Kj.ROTATE_ROW&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),t===sp.Kj.FLIP_ROW&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),t===sp.Kj.FLIP_N_ROTATE_ROW&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),C=C.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R&&M&&(T.push(d+_,g+f,0),T.push(v+_,g+f,0),T.push(v+_,g+c+f,0),T.push(d+_,g+c+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,E=1,D=[e=0,a=1-c/r,h=l/i,a,h,E,e,E],(t===sp.Kj.ROTATE_ROW||t===sp.Kj.ROTATE_TILE&&o%2==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===sp.Kj.FLIP_ROW||t===sp.Kj.FLIP_TILE&&o%2==0)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===sp.Kj.FLIP_N_ROTATE_ROW||t===sp.Kj.FLIP_N_ROTATE_TILE&&o%2==0)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),C=C.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),P&&I&&(T.push(m+_,p+f,0),T.push(-d+_,p+f,0),T.push(-d+_,x+f,0),T.push(m+_,x+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,a=0,h=1,D=[e=1-l/i,a,h,a,h,E=c/r,e,E],(t===sp.Kj.ROTATE_ROW&&u%2==1||t===sp.Kj.ROTATE_TILE&&u%1==0)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===sp.Kj.FLIP_ROW&&u%2==1||t===sp.Kj.FLIP_TILE&&u%2==0)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===sp.Kj.FLIP_N_ROTATE_ROW&&u%2==1||t===sp.Kj.FLIP_N_ROTATE_TILE&&u%2==0)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),C=C.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),P&&M&&(T.push(d+_,p+f,0),T.push(v+_,p+f,0),T.push(v+_,x+f,0),T.push(d+_,x+f,0),y.push(A,A+1,A+3,A+1,A+2,A+3),A+=4,D=[e=0,a=0,h=l/i,a,h,E=c/r,e,E],(t===sp.Kj.ROTATE_ROW&&u%2==1||t===sp.Kj.ROTATE_TILE&&(u+o)%2==1)&&(D=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===sp.Kj.FLIP_ROW&&u%2==1||t===sp.Kj.FLIP_TILE&&(u+o)%2==1)&&(D=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===sp.Kj.FLIP_N_ROTATE_ROW&&u%2==1||t===sp.Kj.FLIP_N_ROTATE_TILE&&(u+o)%2==1)&&(D=[e,1-a,h,1-a,h,1-E,e,1-E]),C=C.concat(D),b.push(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1),S.push(0,0,-1,0,0,-1,0,0,-1,0,0,-1)),R){let s=[];e=0,a=1-c/r,h=1,E=1,s[0]=[e,a,h,a,h,E,e,E],s[1]=[e,a,h,a,h,E,e,E],(t===sp.Kj.ROTATE_TILE||t===sp.Kj.ROTATE_ROW)&&(s[1]=[1-e,1-a,1-h,1-a,1-h,1-E,1-e,1-E]),(t===sp.Kj.FLIP_TILE||t===sp.Kj.FLIP_ROW)&&(s[1]=[1-e,a,1-h,a,1-h,E,1-e,E]),(t===sp.Kj.FLIP_N_ROTATE_TILE||t===sp.Kj.FLIP_N_ROTATE_ROW)&&(s[1]=[e,1-a,h,1-a,h,1-E,e,1-E]);for(let e=0;e{let t=d/c*e,i=Math.cos(t);return new rf.P(o*(2+i)*.5*Math.cos(e),o*(2+i)*Math.sin(e)*.5,o*Math.sin(t)*.5)};for(t=0;t<=h;t++){let e=t%h/h*2*c*Math.PI,r=_(e),n=_(e+.01),o=n.subtract(r),d=n.add(r),p=rf.P.Cross(o,d);for(d=rf.P.Cross(p,o),p.normalize(),d.normalize(),i=0;ihP(e,{size:t,sideOrientation:s,updatable:r},i),s7.x.CreateSphere=hI,sp.Kj.CreateSphere=(e,t,i,r,s,n)=>hM(e,{segments:t,diameterX:i,diameterY:i,diameterZ:i,sideOrientation:n,updatable:s},r),sp.Kj.CreateCapsule=(e,t,i)=>(function(e,t={orientation:rf.P.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6,updatable:!1},i=null){let r=new sp.Kj(e,i);return hD(t).applyToMesh(r,t.updatable),r})(e,t,i),s7.x.CreateCapsule=hD,s7.x.CreateRibbon=hO,sp.Kj.CreateRibbon=(e,t,i=!1,r,s,n,a=!1,o,l)=>hN(e,{pathArray:t,closeArray:i,closePath:r,offset:s,updatable:a,sideOrientation:o,instance:l},n),s7.x.CreateDisc=hF,sp.Kj.CreateDisc=(e,t,i,r=null,s,n)=>hL(e,{radius:t,tessellation:i,sideOrientation:n,updatable:s},r),s7.x.CreateTiledPlane=hw,s7.x.CreateTiledBox=function(e){let t=e.faceUV||Array(6),i=e.faceColors,r=e.pattern||sp.Kj.NO_FLIP,s=e.width||e.size||1,n=e.height||e.size||1,a=e.depth||e.size||1,o=e.tileWidth||e.tileSize||1,l=e.tileHeight||e.tileSize||1,h=e.alignHorizontal||0,u=e.alignVertical||0,c=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE;for(let e=0;e<6;e++)void 0===t[e]&&(t[e]=new rf.Lt(0,0,1,1)),i&&void 0===i[e]&&(i[e]=new rm.HE(1,1,1,1));let d=[];for(let e=0;e<2;e++)d[e]=hw({pattern:r,tileWidth:o,tileHeight:l,width:s,height:n,alignVertical:u,alignHorizontal:h,sideOrientation:c});for(let e=2;e<4;e++)d[e]=hw({pattern:r,tileWidth:o,tileHeight:l,width:a,height:n,alignVertical:u,alignHorizontal:h,sideOrientation:c});let p=u;u===sp.Kj.BOTTOM?p=sp.Kj.TOP:u===sp.Kj.TOP&&(p=sp.Kj.BOTTOM);for(let e=4;e<6;e++)d[e]=hw({pattern:r,tileWidth:o,tileHeight:l,width:s,height:a,alignVertical:p,alignHorizontal:h,sideOrientation:c});let _=[],f=[],m=[],g=[],v=[],x=[],T=[],S=[],E=0,C=0;for(let e=0;e<6;e++){let r=d[e].positions.length;x[e]=[],T[e]=[];for(let t=0;te+C)),C+=x[e].length,i)for(let t=0;t<4;t++)v.push(i[e].r,i[e].g,i[e].b,i[e].a)}let b=new rf.P(0,0,a/2),y=rf.y3.RotationY(Math.PI);_=x[0].map(e=>rf.P.TransformNormal(e,y).add(b)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),f=T[0].map(e=>rf.P.TransformNormal(e,y)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]),_=_.concat(x[1].map(e=>e.subtract(b)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[1].map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let A=new rf.P(s/2,0,0),R=rf.y3.RotationY(-Math.PI/2);_=_.concat(x[2].map(e=>rf.P.TransformNormal(e,R).add(A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[2].map(e=>rf.P.TransformNormal(e,R)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let P=rf.y3.RotationY(Math.PI/2);_=_.concat(x[3].map(e=>rf.P.TransformNormal(e,P).subtract(A)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[3].map(e=>rf.P.TransformNormal(e,P)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let I=new rf.P(0,n/2,0),M=rf.y3.RotationX(Math.PI/2);_=_.concat(x[4].map(e=>rf.P.TransformNormal(e,M).add(I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[4].map(e=>rf.P.TransformNormal(e,M)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[]));let D=rf.y3.RotationX(-Math.PI/2);_=_.concat(x[5].map(e=>rf.P.TransformNormal(e,D).subtract(I)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),f=f.concat(T[5].map(e=>rf.P.TransformNormal(e,D)).map(e=>[e.x,e.y,e.z]).reduce((e,t)=>e.concat(t),[])),s7.x._ComputeSides(c,_,g,f,m);let O=new s7.x;if(O.indices=g,O.positions=_,O.normals=f,O.uvs=m,i){let e=c===s7.x.DOUBLESIDE?v.concat(v):v;O.colors=e}return O},s7.x.CreateTorusKnot=hB,sp.Kj.CreateTorusKnot=(e,t,i,r,s,n,a,o,l,h)=>(function(e,t={},i){let r=new sp.Kj(e,i);return t.sideOrientation=sp.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,hB(t).applyToMesh(r,t.updatable),r})(e,{radius:t,tube:i,radialSegments:r,tubularSegments:s,p:n,q:a,sideOrientation:h,updatable:l},o);let hU={effect:null,subMesh:null};class hV extends nc{constructor(e,t,i,r={},s=!0){super(e,t,s),this._textures={},this._textureArrays={},this._externalTextures={},this._floats={},this._ints={},this._uints={},this._floatsArrays={},this._colors3={},this._colors3Arrays={},this._colors4={},this._colors4Arrays={},this._vectors2={},this._vectors3={},this._vectors4={},this._quaternions={},this._quaternionsArrays={},this._matrices={},this._matrixArrays={},this._matrices3x3={},this._matrices2x2={},this._vectors2Arrays={},this._vectors3Arrays={},this._vectors4Arrays={},this._uniformBuffers={},this._textureSamplers={},this._storageBuffers={},this._cachedWorldViewMatrix=new rf.y3,this._cachedWorldViewProjectionMatrix=new rf.y3,this._multiview=!1,this._materialHelperNeedsPreviousMatrices=!1,this._shaderPath=i,this._options=Object.assign({needAlphaBlending:!1,needAlphaTesting:!1,attributes:["position","normal","uv"],uniforms:["worldViewProjection"],uniformBuffers:[],samplers:[],externalTextures:[],samplerObjects:[],storageBuffers:[],defines:[],useClipPlane:!1},r)}get shaderPath(){return this._shaderPath}set shaderPath(e){this._shaderPath=e}get options(){return this._options}get isMultiview(){return this._multiview}getClassName(){return"ShaderMaterial"}needAlphaBlending(){return this.alpha<1||this._options.needAlphaBlending}needAlphaTesting(){return this._options.needAlphaTesting}_checkUniform(e){-1===this._options.uniforms.indexOf(e)&&this._options.uniforms.push(e)}setTexture(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._textures[e]=t,this}setTextureArray(e,t){return -1===this._options.samplers.indexOf(e)&&this._options.samplers.push(e),this._checkUniform(e),this._textureArrays[e]=t,this}setExternalTexture(e,t){return -1===this._options.externalTextures.indexOf(e)&&this._options.externalTextures.push(e),this._externalTextures[e]=t,this}setFloat(e,t){return this._checkUniform(e),this._floats[e]=t,this}setInt(e,t){return this._checkUniform(e),this._ints[e]=t,this}setUInt(e,t){return this._checkUniform(e),this._uints[e]=t,this}setFloats(e,t){return this._checkUniform(e),this._floatsArrays[e]=t,this}setColor3(e,t){return this._checkUniform(e),this._colors3[e]=t,this}setColor3Array(e,t){return this._checkUniform(e),this._colors3Arrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setColor4(e,t){return this._checkUniform(e),this._colors4[e]=t,this}setColor4Array(e,t){return this._checkUniform(e),this._colors4Arrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setVector2(e,t){return this._checkUniform(e),this._vectors2[e]=t,this}setVector3(e,t){return this._checkUniform(e),this._vectors3[e]=t,this}setVector4(e,t){return this._checkUniform(e),this._vectors4[e]=t,this}setQuaternion(e,t){return this._checkUniform(e),this._quaternions[e]=t,this}setQuaternionArray(e,t){return this._checkUniform(e),this._quaternionsArrays[e]=t.reduce((e,t)=>(t.toArray(e,e.length),e),[]),this}setMatrix(e,t){return this._checkUniform(e),this._matrices[e]=t,this}setMatrices(e,t){this._checkUniform(e);let i=new Float32Array(16*t.length);for(let e=0;et===e||t.startsWith(i));return r>=0&&this.options.defines.splice(r,1),("boolean"!=typeof t||t)&&this.options.defines.push(i+t),this}isReadyForSubMesh(e,t,i){return this.isReady(e,i,t)}isReady(e,t,i){var r,s,n;let a=i&&this._storeEffectOnSubMeshes;if(this.isFrozen){if(a){if(i.effect&&i.effect._wasPreviouslyReady)return!0}else{let e=this._drawWrapper.effect;if(e&&e._wasPreviouslyReady&&e._wasPreviouslyUsingInstances===t)return!0}}let o=this.getScene(),l=o.getEngine(),h=[],u=[],c=new nF,d=this._shaderPath,p=this._options.uniforms,_=this._options.uniformBuffers,f=this._options.samplers;l.getCaps().multiview&&o.activeCamera&&o.activeCamera.outputRenderTarget&&o.activeCamera.outputRenderTarget.getViewCount()>1&&(this._multiview=!0,h.push("#define MULTIVIEW"),-1!==this._options.uniforms.indexOf("viewProjection")&&-1===this._options.uniforms.indexOf("viewProjectionR")&&this._options.uniforms.push("viewProjectionR"));for(let e=0;e4&&(u.push(sm.o.MatricesIndicesExtraKind),u.push(sm.o.MatricesWeightsExtraKind));let t=e.skeleton;h.push("#define NUM_BONE_INFLUENCERS "+e.numBoneInfluencers),c.addCPUSkinningFallback(0,e),t.isUsingTextureForMatrices?(h.push("#define BONETEXTURE"),-1===this._options.uniforms.indexOf("boneTextureWidth")&&this._options.uniforms.push("boneTextureWidth"),-1===this._options.samplers.indexOf("boneSampler")&&this._options.samplers.push("boneSampler")):(h.push("#define BonesPerMesh "+(t.bones.length+1)),-1===this._options.uniforms.indexOf("mBones")&&this._options.uniforms.push("mBones"))}else h.push("#define NUM_BONE_INFLUENCERS 0");let m=0,g=e?e.morphTargetManager:null;if(g){let e=g.supportsUVs&&-1!==h.indexOf("#define UV1"),t=g.supportsTangents&&-1!==h.indexOf("#define TANGENT"),i=g.supportsNormals&&-1!==h.indexOf("#define NORMAL");m=g.numInfluencers,e&&h.push("#define MORPHTARGETS_UV"),t&&h.push("#define MORPHTARGETS_TANGENT"),i&&h.push("#define MORPHTARGETS_NORMAL"),m>0&&h.push("#define MORPHTARGETS"),g.isUsingTextureForTargets&&(h.push("#define MORPHTARGETS_TEXTURE"),-1===this._options.uniforms.indexOf("morphTargetTextureIndices")&&this._options.uniforms.push("morphTargetTextureIndices"),-1===this._options.samplers.indexOf("morphTargets")&&this._options.samplers.push("morphTargets")),h.push("#define NUM_MORPH_INFLUENCERS "+m);for(let r=0;r0&&((p=p.slice()).push("morphTargetInfluences"),p.push("morphTargetTextureInfo"),p.push("morphTargetTextureIndices"))}else h.push("#define NUM_MORPH_INFLUENCERS 0");if(e){let t=e.bakedVertexAnimationManager;t&&t.isEnabled&&(h.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"),-1===this._options.uniforms.indexOf("bakedVertexAnimationSettings")&&this._options.uniforms.push("bakedVertexAnimationSettings"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTextureSizeInverted")&&this._options.uniforms.push("bakedVertexAnimationTextureSizeInverted"),-1===this._options.uniforms.indexOf("bakedVertexAnimationTime")&&this._options.uniforms.push("bakedVertexAnimationTime"),-1===this._options.samplers.indexOf("bakedVertexAnimationTexture")&&this._options.samplers.push("bakedVertexAnimationTexture")),nE.G.PrepareAttributesForBakedVertexAnimation(u,e,h)}for(let e in this._textures)if(!this._textures[e].isReady())return!1;e&&this._shouldTurnAlphaTestOn(e)&&h.push("#define ALPHATEST"),!1!==this._options.useClipPlane&&((0,lH.qx)(p),(0,lH.lK)(this,o,h)),this._useLogarithmicDepth&&(h.push("#define LOGARITHMICDEPTH"),-1===this._options.uniforms.indexOf("logarithmicDepthConstant")&&this._options.uniforms.push("logarithmicDepthConstant")),this.customShaderNameResolve&&(p=p.slice(),_=_.slice(),f=f.slice(),d=this.customShaderNameResolve(d,p,_,f,h,u));let v=a?i._getDrawWrapper():this._drawWrapper,x=null!==(r=null==v?void 0:v.effect)&&void 0!==r?r:null,T=null!==(s=null==v?void 0:v.defines)&&void 0!==s?s:null,S=h.join("\n"),E=x;return T!==S&&(E=l.createEffect(d,{attributes:u,uniformsNames:p,uniformBuffersNames:_,samplers:f,defines:S,fallbacks:c,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousMorphTargets:m},shaderLanguage:this._options.shaderLanguage},l),a?i.setEffect(E,S,this._materialContext):v&&v.setEffect(E,S),this._onEffectCreatedObservable&&(hU.effect=E,hU.subMesh=null!==(n=null!=i?i:null==e?void 0:e.subMeshes[0])&&void 0!==n?n:null,this._onEffectCreatedObservable.notifyObservers(hU))),E._wasPreviouslyUsingInstances=!!t,!!(null==E?void 0:E.isReady())&&(x!==E&&o.resetCachedMaterial(),E._wasPreviouslyReady=!0,!0)}bindOnlyWorldMatrix(e,t){let i=this.getScene(),r=null!=t?t:this.getEffect();r&&(-1!==this._options.uniforms.indexOf("world")&&r.setMatrix("world",e),-1!==this._options.uniforms.indexOf("worldView")&&(e.multiplyToRef(i.getViewMatrix(),this._cachedWorldViewMatrix),r.setMatrix("worldView",this._cachedWorldViewMatrix)),-1!==this._options.uniforms.indexOf("worldViewProjection")&&(e.multiplyToRef(i.getTransformMatrix(),this._cachedWorldViewProjectionMatrix),r.setMatrix("worldViewProjection",this._cachedWorldViewProjectionMatrix)))}bindForSubMesh(e,t,i){var r;this.bind(e,t,null===(r=i._drawWrapperOverride)||void 0===r?void 0:r.effect,i)}bind(e,t,i,r){var s;let n=r&&this._storeEffectOnSubMeshes,a=null!=i?i:n?r.effect:this.getEffect();if(!a)return;let o=this.getScene();this._activeEffect=a,this.bindOnlyWorldMatrix(e,i);let l=this._options.uniformBuffers,h=!1;if(a&&l&&l.length>0&&o.getEngine().supportsUniformBuffers)for(let i=0;i0&&nE.G.BindMorphTargetParameters(t,a);let i=t.bakedVertexAnimationManager;i&&i.isEnabled&&(null===(s=t.bakedVertexAnimationManager)||void 0===s||s.bind(a,!!a._wasPreviouslyUsingInstances))}this._afterBind(t,a)}getActiveTextures(){let e=super.getActiveTextures();for(let t in this._textures)e.push(this._textures[t]);for(let t in this._textureArrays){let i=this._textureArrays[t];for(let t=0;tnew hV(e,this.getScene(),this._shaderPath,this._options,this._storeEffectOnSubMeshes),this);for(let i in t.name=e,t.id=e,"object"==typeof t._shaderPath&&(t._shaderPath=Object.assign({},t._shaderPath)),this._options=Object.assign({},this._options),Object.keys(this._options).forEach(e=>{let t=this._options[e];Array.isArray(t)&&(this._options[e]=t.slice(0))}),this.stencil.copyTo(t.stencil),this._textures)t.setTexture(i,this._textures[i]);for(let e in this._textureArrays)t.setTextureArray(e,this._textureArrays[e]);for(let e in this._externalTextures)t.setExternalTexture(e,this._externalTextures[e]);for(let e in this._ints)t.setInt(e,this._ints[e]);for(let e in this._uints)t.setUInt(e,this._uints[e]);for(let e in this._floats)t.setFloat(e,this._floats[e]);for(let e in this._floatsArrays)t.setFloats(e,this._floatsArrays[e]);for(let e in this._colors3)t.setColor3(e,this._colors3[e]);for(let e in this._colors3Arrays)t._colors3Arrays[e]=this._colors3Arrays[e];for(let e in this._colors4)t.setColor4(e,this._colors4[e]);for(let e in this._colors4Arrays)t._colors4Arrays[e]=this._colors4Arrays[e];for(let e in this._vectors2)t.setVector2(e,this._vectors2[e]);for(let e in this._vectors3)t.setVector3(e,this._vectors3[e]);for(let e in this._vectors4)t.setVector4(e,this._vectors4[e]);for(let e in this._quaternions)t.setQuaternion(e,this._quaternions[e]);for(let e in this._quaternionsArrays)t._quaternionsArrays[e]=this._quaternionsArrays[e];for(let e in this._matrices)t.setMatrix(e,this._matrices[e]);for(let e in this._matrixArrays)t._matrixArrays[e]=this._matrixArrays[e].slice();for(let e in this._matrices3x3)t.setMatrix3x3(e,this._matrices3x3[e]);for(let e in this._matrices2x2)t.setMatrix2x2(e,this._matrices2x2[e]);for(let e in this._vectors2Arrays)t.setArray2(e,this._vectors2Arrays[e]);for(let e in this._vectors3Arrays)t.setArray3(e,this._vectors3Arrays[e]);for(let e in this._vectors4Arrays)t.setArray4(e,this._vectors4Arrays[e]);for(let e in this._uniformBuffers)t.setUniformBuffer(e,this._uniformBuffers[e]);for(let e in this._textureSamplers)t.setTextureSampler(e,this._textureSamplers[e]);for(let e in this._storageBuffers)t.setStorageBuffer(e,this._storageBuffers[e]);return t}dispose(e,t,i){if(t){let e;for(e in this._textures)this._textures[e].dispose();for(e in this._textureArrays){let t=this._textureArrays[e];for(let e=0;enew hV(e.name,t,e.shaderPath,e.options,e.storeEffectOnSubMeshes),e,t,i);for(r in e.stencil&&s.stencil.parse(e.stencil,t,i),e.textures)s.setTexture(r,sj.Parse(e.textures[r],t,i));for(r in e.textureArrays){let n=e.textureArrays[r],a=[];for(let e=0;e(i%3==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>rm.Wo.FromArray(e));s.setColor3Array(r,t)}for(r in e.colors4)s.setColor4(r,rm.HE.FromArray(e.colors4[r]));for(r in e.colors4Arrays){let t=e.colors4Arrays[r].reduce((e,t,i)=>(i%4==0?e.push([t]):e[e.length-1].push(t),e),[]).map(e=>rm.HE.FromArray(e));s.setColor4Array(r,t)}for(r in e.vectors2)s.setVector2(r,rf.FM.FromArray(e.vectors2[r]));for(r in e.vectors3)s.setVector3(r,rf.P.FromArray(e.vectors3[r]));for(r in e.vectors4)s.setVector4(r,rf.Lt.FromArray(e.vectors4[r]));for(r in e.quaternions)s.setQuaternion(r,rf._f.FromArray(e.quaternions[r]));for(r in e.matrices)s.setMatrix(r,rf.y3.FromArray(e.matrices[r]));for(r in e.matrixArray)s._matrixArrays[r]=new Float32Array(e.matrixArray[r]);for(r in e.matrices3x3)s.setMatrix3x3(r,e.matrices3x3[r]);for(r in e.matrices2x2)s.setMatrix2x2(r,e.matrices2x2[r]);for(r in e.vectors2Arrays)s.setArray2(r,e.vectors2Arrays[r]);for(r in e.vectors3Arrays)s.setArray3(r,e.vectors3Arrays[r]);for(r in e.vectors4Arrays)s.setArray4(r,e.vectors4Arrays[r]);for(r in e.quaternionsArrays)s.setArray4(r,e.quaternionsArrays[r]);return s}static ParseFromFileAsync(e,t,i,r=""){return new Promise((s,n)=>{let a=new rX.g;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=this.Parse(t,i||rL.l.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the ShaderMaterial")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return new Promise((r,s)=>{let n=new rX.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(JSON.parse(n.responseText).jsonPayload).shaderMaterial),a=this.Parse(s,t||rL.l.LastCreatedScene,i);a.snippetId=e,r(a)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}hV.SnippetUrl="https://snippet.babylonjs.com",hV.CreateFromSnippetAsync=hV.ParseFromSnippetAsync,(0,rg.H)("BABYLON.ShaderMaterial",hV);let hk=`#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +#define VERTEXCOLOR +varying vec4 vColor; +#else +uniform vec4 color; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +gl_FragColor=vColor; +#else +gl_FragColor=color; +#endif +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.colorPixelShader=hk;let hG=`attribute vec3 position; +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +#include +#include +vec4 worldPos=finalWorld*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.colorVertexShader=hG,sp.Kj._LinesMeshParser=(e,t)=>hz.Parse(e,t);class hz extends sp.Kj{_isShaderMaterial(e){return"ShaderMaterial"===e.getClassName()}constructor(e,t=null,i=null,r=null,s,n,a,o){super(e,t,i,r,s),this.useVertexColor=n,this.useVertexAlpha=a,this.color=new rm.Wo(1,1,1),this.alpha=1,r&&(this.color=r.color.clone(),this.alpha=r.alpha,this.useVertexColor=r.useVertexColor,this.useVertexAlpha=r.useVertexAlpha),this.intersectionThreshold=.1;let l={attributes:[sm.o.PositionKind],uniforms:["world","viewProjection"],needAlphaBlending:!0,defines:[],useClipPlane:null};!1===a?l.needAlphaBlending=!1:l.defines.push("#define VERTEXALPHA"),n?(l.defines.push("#define VERTEXCOLOR"),l.attributes.push(sm.o.ColorKind)):(l.uniforms.push("color"),this._color4=new rm.HE),o?this.material=o:(this.material=new hV("colorShader",this.getScene(),"color",l,!1),this.material.doNotSerialize=!0)}isReady(){return!!this._lineMaterial.isReady(this,!!this._userInstancedBuffersStorage||this.hasThinInstances)&&super.isReady()}getClassName(){return"LinesMesh"}get material(){return this._lineMaterial}set material(e){this._lineMaterial=e,this._lineMaterial.fillMode=nu.F.LineListDrawMode}get checkCollisions(){return!1}set checkCollisions(e){}_bind(e,t){if(!this._geometry)return this;let i=this.isUnIndexed?null:this._geometry.getIndexBuffer();if(!this._userInstancedBuffersStorage||this.hasThinInstances?this._geometry._bind(t,i):this._geometry._bind(t,i,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects),!this.useVertexColor&&this._isShaderMaterial(this._lineMaterial)){let{r:e,g:t,b:i}=this.color;this._color4.set(e,t,i,this.alpha),this._lineMaterial.setColor4("color",this._color4)}return this}_draw(e,t,i){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;let r=this.getScene().getEngine();return this._unIndexed?r.drawArraysType(nu.F.LineListDrawMode,e.verticesStart,e.verticesCount,i):r.drawElementsType(nu.F.LineListDrawMode,e.indexStart,e.indexCount,i),this}dispose(e,t=!1,i){i||this._lineMaterial.dispose(!1,!1,!0),super.dispose(e)}clone(e,t=null,i){return new hz(e,this.getScene(),t,this,i)}createInstance(e){let t=new hW(e,this);if(this.instancedBuffers)for(let e in t.instancedBuffers={},this.instancedBuffers)t.instancedBuffers[e]=this.instancedBuffers[e];return t}serialize(e){super.serialize(e),e.color=this.color.asArray(),e.alpha=this.alpha}static Parse(e,t){let i=new hz(e.name,t);return i.color=rm.Wo.FromArray(e.color),i.alpha=e.alpha,i}}class hW extends sv{constructor(e,t){super(e,t),this.intersectionThreshold=t.intersectionThreshold}getClassName(){return"InstancedLinesMesh"}}function hH(e){let t=[],i=[],r=e.lines,s=e.colors,n=[],a=0;for(let e=0;e0&&(t.push(a-1),t.push(a)),a++}}let o=new s7.x;return o.indices=t,o.positions=i,s&&(o.colors=n),o}function hX(e){let t=e.dashSize||3,i=e.gapSize||1,r=e.dashNb||200,s=e.points,n=[],a=[],o=rf.P.Zero(),l=0,h=0,u=0,c=0,d=0,p=0,_=0;for(_=0;_hj(e,{points:t,updatable:r,instance:s},i),sp.Kj.CreateDashedLines=(e,t,i,r,s,n=null,a,o)=>(function(e,t,i=null){let r=t.points,s=t.instance,n=t.gapSize||1,a=t.dashSize||3;if(s)return(t.dashNb||t.dashSize||t.gapSize||t.useVertexAlpha||t.material)&&rb.Y.Warn("You have used an option other than points with the instance option. Please be aware that these other options will be ignored."),s.updateMeshPositions(e=>{let t=rf.P.Zero(),i=e.length/6,n=0,a=0,o=0,l=0,h=0,u=0,c=0,d=0;for(c=0;c{let i=new hq(e,this.elements.length);t.push(i),this.elements.push(i)}),t}computeBounds(){let e=new rf.FM(this.elements[0].x,this.elements[0].y),t=new rf.FM(this.elements[0].x,this.elements[0].y);return this.elements.forEach(i=>{i.xt.x&&(t.x=i.x),i.yt.y&&(t.y=i.y)}),{min:e,max:t,width:t.x-e.x,height:t.y-e.y}}}class h${_addToepoint(e){for(let t of e)this._epoints.push(t.x,t.y)}constructor(e,t,i,r=earcut){let s;this._points=new hK,this._outlinepoints=new hK,this._holes=[],this._epoints=[],this._eholes=[],this.bjsEarcut=r,this._name=e,this._scene=i||rL.l.LastCreatedScene,s=t instanceof st?t.getPoints():t,this._addToepoint(s),this._points.add(s),this._outlinepoints.add(s),void 0===this.bjsEarcut&&rb.Y.Warn("Earcut was not found, the polygon will not be built.")}addHole(e){this._points.add(e);let t=new hK;return t.add(e),this._holes.push(t),this._eholes.push(this._epoints.length/2),this._addToepoint(e),this}build(e=!1,t=0,i=2){let r=new sp.Kj(this._name,this._scene),s=this.buildVertexData(t,i);return r.setVerticesData(sm.o.PositionKind,s.positions,e),r.setVerticesData(sm.o.NormalKind,s.normals,e),r.setVerticesData(sm.o.UVKind,s.uvs,e),r.setIndices(s.indices),r}buildVertexData(e=0,t=2){let i=new s7.x,r=[],s=[],n=[],a=this._points.computeBounds();this._points.elements.forEach(e=>{r.push(0,1,0),s.push(e.x,0,e.y),n.push((e.x-a.min.x)/a.width,(e.y-a.min.y)/a.height)});let o=[],l=this.bjsEarcut(this._epoints,this._eholes,2);for(let e=0;e0){let i=s.length/3;this._points.elements.forEach(t=>{r.push(0,-1,0),s.push(t.x,-e,t.y),n.push(1-(t.x-a.min.x)/a.width,1-(t.y-a.min.y)/a.height)});let l=o.length;for(let e=0;e{this._addSide(s,r,n,o,a,i,e,!0,t)})}return i.indices=o,i.positions=s,i.normals=r,i.uvs=n,i}_addSide(e,t,i,r,s,n,a,o,l){let h=e.length/3,u=0;for(let c=0;cl?El?CMath.abs(c[e+1])&&(S=1),.001>Math.abs(c[e+1]-1)&&(S=0),.001>Math.abs(c[e+1]+1)&&(S=2),T=e/3,1===S?((f=T-_)%4<1.5?h?d[2*T]=o[S].x+(o[S].z-o[S].x)*x[Math.floor(f/4)]/v:d[2*T]=o[S].x:h?d[2*T]=o[S].x+(o[S].z-o[S].x)*x[Math.floor(f/4)+1]/v:d[2*T]=o[S].z,f%2==0?d[2*T+1]=sY.e.UseOpenGLOrientationForUV?1-o[S].w:o[S].w:d[2*T+1]=sY.e.UseOpenGLOrientationForUV?1-o[S].y:o[S].y):(d[2*T]=(1-d[2*T])*o[S].x+d[2*T]*o[S].z,d[2*T+1]=(1-d[2*T+1])*o[S].y+d[2*T+1]*o[S].w,sY.e.UseOpenGLOrientationForUV&&(d[2*T+1]=1-d[2*T+1])),r&&l.push(r[S].r,r[S].g,r[S].b,r[S].a);s7.x._ComputeSides(t,u,p,c,d,s,n);let E=new s7.x;if(E.indices=p,E.positions=u,E.normals=c,E.uvs=d,r){let e=t===s7.x.DOUBLESIDE?l.concat(l):l;E.colors=e}return E}function hZ(e,t,i=null,r=earcut){t.sideOrientation=sp.Kj._GetDefaultSideOrientation(t.sideOrientation);let s=t.shape,n=t.holes||[],a=t.depth||0,o=t.smoothingThreshold||2,l=[],h=[];for(let e=0;e1),a=t.rotationFunction||(()=>0),o=t.closePath||t.ribbonCloseArray||!1,l=t.closeShape||t.ribbonClosePath||!1,h=0===t.cap?0:t.cap||sp.Kj.NO_CAP,u=t.updatable,c=t.firstNormal||null,d=t.adjustFrame||!1;return h1(e,s,r,null,null,n,a,o,l,h,!0,i,!!u,sp.Kj._GetDefaultSideOrientation(t.sideOrientation),t.instance||null,t.invertUV||!1,t.frontUVs||null,t.backUVs||null,c,d)}function h1(e,t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x){let T,S;let E=(e,t,i,r,s,n,a,o,l,h,u)=>{let c=i.getTangents(),d=i.getNormals(),p=i.getBinormals(),_=i.getDistances();if(u){for(let e=0;e0){let t=c[e-1];0>rf.P.Dot(t,c[e])&&c[e].scaleInPlace(-1),t=d[e-1],0>rf.P.Dot(t,d[e])&&d[e].scaleInPlace(-1),t=p[e-1],0>rf.P.Dot(t,p[e])&&p[e].scaleInPlace(-1)}}let f=0,m=h&&o?o:()=>null!==n?n:0,g=h&&a?a:()=>null!==s?s:1,v=l===sp.Kj.NO_CAP||l===sp.Kj.CAP_END?0:2,x=rf.jp.Matrix[0];for(let i=0;i{let t;let i=[],r=rf.P.Zero();for(t=0;t3?0:h,u,x),closeArray:o,closePath:l,updatable:d,sideOrientation:p,invertUV:f,frontUVs:m||void 0,backUVs:g||void 0},c);return C._creationDataStorage.pathArray=S,C._creationDataStorage.path3D=T,C._creationDataStorage.cap=h,C}function h2(e){let t,i,r,s,n,a;let o=[];o[0]={vertex:[[0,0,1.732051],[1.632993,0,-.5773503],[-.8164966,1.414214,-.5773503],[-.8164966,-1.414214,-.5773503]],face:[[0,1,2],[0,2,3],[0,3,1],[1,3,2]]},o[1]={vertex:[[0,0,1.414214],[1.414214,0,0],[0,1.414214,0],[-1.414214,0,0],[0,-1.414214,0],[0,0,-1.414214]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,1],[1,4,5],[1,5,2],[2,5,3],[3,5,4]]},o[2]={vertex:[[0,0,1.070466],[.7136442,0,.7978784],[-.3568221,.618034,.7978784],[-.3568221,-.618034,.7978784],[.7978784,.618034,.3568221],[.7978784,-.618034,.3568221],[-.9341724,.381966,.3568221],[.1362939,1,.3568221],[.1362939,-1,.3568221],[-.9341724,-.381966,.3568221],[.9341724,.381966,-.3568221],[.9341724,-.381966,-.3568221],[-.7978784,.618034,-.3568221],[-.1362939,1,-.3568221],[-.1362939,-1,-.3568221],[-.7978784,-.618034,-.3568221],[.3568221,.618034,-.7978784],[.3568221,-.618034,-.7978784],[-.7136442,0,-.7978784],[0,0,-1.070466]],face:[[0,1,4,7,2],[0,2,6,9,3],[0,3,8,5,1],[1,5,11,10,4],[2,7,13,12,6],[3,9,15,14,8],[4,10,16,13,7],[5,8,14,17,11],[6,12,18,15,9],[10,11,17,19,16],[12,13,16,19,18],[14,15,18,19,17]]},o[3]={vertex:[[0,0,1.175571],[1.051462,0,.5257311],[.3249197,1,.5257311],[-.8506508,.618034,.5257311],[-.8506508,-.618034,.5257311],[.3249197,-1,.5257311],[.8506508,.618034,-.5257311],[.8506508,-.618034,-.5257311],[-.3249197,1,-.5257311],[-1.051462,0,-.5257311],[-.3249197,-1,-.5257311],[0,0,-1.175571]],face:[[0,1,2],[0,2,3],[0,3,4],[0,4,5],[0,5,1],[1,5,7],[1,7,6],[1,6,2],[2,6,8],[2,8,3],[3,8,9],[3,9,4],[4,9,10],[4,10,5],[5,10,7],[6,7,11],[6,11,8],[7,10,11],[8,11,9],[9,11,10]]},o[4]={vertex:[[0,0,1.070722],[.7148135,0,.7971752],[-.104682,.7071068,.7971752],[-.6841528,.2071068,.7971752],[-.104682,-.7071068,.7971752],[.6101315,.7071068,.5236279],[1.04156,.2071068,.1367736],[.6101315,-.7071068,.5236279],[-.3574067,1,.1367736],[-.7888348,-.5,.5236279],[-.9368776,.5,.1367736],[-.3574067,-1,.1367736],[.3574067,1,-.1367736],[.9368776,-.5,-.1367736],[.7888348,.5,-.5236279],[.3574067,-1,-.1367736],[-.6101315,.7071068,-.5236279],[-1.04156,-.2071068,-.1367736],[-.6101315,-.7071068,-.5236279],[.104682,.7071068,-.7971752],[.6841528,-.2071068,-.7971752],[.104682,-.7071068,-.7971752],[-.7148135,0,-.7971752],[0,0,-1.070722]],face:[[0,2,3],[1,6,5],[4,9,11],[7,15,13],[8,16,10],[12,14,19],[17,22,18],[20,21,23],[0,1,5,2],[0,3,9,4],[0,4,7,1],[1,7,13,6],[2,5,12,8],[2,8,10,3],[3,10,17,9],[4,11,15,7],[5,6,14,12],[6,13,20,14],[8,12,19,16],[9,17,18,11],[10,16,22,17],[11,18,21,15],[13,15,21,20],[14,20,23,19],[16,19,23,22],[18,22,23,21]]},o[5]={vertex:[[0,0,1.322876],[1.309307,0,.1889822],[-.9819805,.8660254,.1889822],[.1636634,-1.299038,.1889822],[.3273268,.8660254,-.9449112],[-.8183171,-.4330127,-.9449112]],face:[[0,3,1],[2,4,5],[0,1,4,2],[0,2,5,3],[1,3,5,4]]},o[6]={vertex:[[0,0,1.159953],[1.013464,0,.5642542],[-.3501431,.9510565,.5642542],[-.7715208,-.6571639,.5642542],[.6633206,.9510565,-.03144481],[.8682979,-.6571639,-.3996071],[-1.121664,.2938926,-.03144481],[-.2348831,-1.063314,-.3996071],[.5181548,.2938926,-.9953061],[-.5850262,-.112257,-.9953061]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,9,7],[5,7,9,8],[0,3,7,5,1],[2,4,8,9,6]]},o[7]={vertex:[[0,0,1.118034],[.8944272,0,.6708204],[-.2236068,.8660254,.6708204],[-.7826238,-.4330127,.6708204],[.6708204,.8660254,.2236068],[1.006231,-.4330127,-.2236068],[-1.006231,.4330127,.2236068],[-.6708204,-.8660254,-.2236068],[.7826238,.4330127,-.6708204],[.2236068,-.8660254,-.6708204],[-.8944272,0,-.6708204],[0,0,-1.118034]],face:[[0,1,4,2],[0,2,6,3],[1,5,8,4],[3,6,10,7],[5,9,11,8],[7,10,11,9],[0,3,7,9,5,1],[2,4,8,11,10,6]]},o[8]={vertex:[[-.729665,.670121,.319155],[-.655235,-.29213,-.754096],[-.093922,-.607123,.537818],[.702196,.595691,.485187],[.776626,-.36656,-.588064]],face:[[1,4,2],[0,1,2],[3,0,2],[4,3,2],[4,1,0,3]]},o[9]={vertex:[[-.868849,-.100041,.61257],[-.329458,.976099,.28078],[-.26629,-.013796,-.477654],[-.13392,-1.034115,.229829],[.738834,.707117,-.307018],[.859683,-.535264,-.338508]],face:[[3,0,2],[5,3,2],[4,5,2],[1,4,2],[0,1,2],[0,3,5,4,1]]},o[10]={vertex:[[-.610389,.243975,.531213],[-.187812,-.48795,-.664016],[-.187812,.9759,-.664016],[.187812,-.9759,.664016],[.798201,.243975,.132803]],face:[[1,3,0],[3,4,0],[3,1,4],[0,2,1],[0,4,2],[2,4,1]]},o[11]={vertex:[[-1.028778,.392027,-.048786],[-.640503,-.646161,.621837],[-.125162,-.395663,-.540059],[.004683,.888447,-.651988],[.125161,.395663,.540059],[.632925,-.791376,.433102],[1.031672,.157063,-.354165]],face:[[3,2,0],[2,1,0],[2,5,1],[0,4,3],[0,1,4],[4,1,5],[2,3,6],[3,4,6],[5,2,6],[4,5,6]]},o[12]={vertex:[[-.669867,.334933,-.529576],[-.669867,.334933,.529577],[-.4043,1.212901,0],[-.334933,-.669867,-.529576],[-.334933,-.669867,.529577],[.334933,.669867,-.529576],[.334933,.669867,.529577],[.4043,-1.212901,0],[.669867,-.334933,-.529576],[.669867,-.334933,.529577]],face:[[8,9,7],[6,5,2],[3,8,7],[5,0,2],[4,3,7],[0,1,2],[9,4,7],[1,6,2],[9,8,5,6],[8,3,0,5],[3,4,1,0],[4,9,6,1]]},o[13]={vertex:[[-.931836,.219976,-.264632],[-.636706,.318353,.692816],[-.613483,-.735083,-.264632],[-.326545,.979634,0],[-.318353,-.636706,.692816],[-.159176,.477529,-.856368],[.159176,-.477529,-.856368],[.318353,.636706,.692816],[.326545,-.979634,0],[.613482,.735082,-.264632],[.636706,-.318353,.692816],[.931835,-.219977,-.264632]],face:[[11,10,8],[7,9,3],[6,11,8],[9,5,3],[2,6,8],[5,0,3],[4,2,8],[0,1,3],[10,4,8],[1,7,3],[10,11,9,7],[11,6,5,9],[6,2,0,5],[2,4,1,0],[4,10,7,1]]},o[14]={vertex:[[-.93465,.300459,-.271185],[-.838689,-.260219,-.516017],[-.711319,.717591,.128359],[-.710334,-.156922,.080946],[-.599799,.556003,-.725148],[-.503838,-.004675,-.969981],[-.487004,.26021,.48049],[-.460089,-.750282,-.512622],[-.376468,.973135,-.325605],[-.331735,-.646985,.084342],[-.254001,.831847,.530001],[-.125239,-.494738,-.966586],[.029622,.027949,.730817],[.056536,-.982543,-.262295],[.08085,1.087391,.076037],[.125583,-.532729,.485984],[.262625,.599586,.780328],[.391387,-.726999,-.716259],[.513854,-.868287,.139347],[.597475,.85513,.326364],[.641224,.109523,.783723],[.737185,-.451155,.538891],[.848705,-.612742,-.314616],[.976075,.365067,.32976],[1.072036,-.19561,.084927]],face:[[15,18,21],[12,20,16],[6,10,2],[3,0,1],[9,7,13],[2,8,4,0],[0,4,5,1],[1,5,11,7],[7,11,17,13],[13,17,22,18],[18,22,24,21],[21,24,23,20],[20,23,19,16],[16,19,14,10],[10,14,8,2],[15,9,13,18],[12,15,21,20],[6,12,16,10],[3,6,2,0],[9,3,1,7],[9,15,12,6,3],[22,17,11,5,4,8,14,19,23,24]]};let l=e.type&&(e.type<0||e.type>=o.length)?0:e.type||0,h=e.size,u=e.sizeX||h||1,c=e.sizeY||h||1,d=e.sizeZ||h||1,p=e.custom||o[l],_=p.face.length,f=e.faceUV||Array(_),m=e.faceColors,g=void 0===e.flat||e.flat,v=0===e.sideOrientation?0:e.sideOrientation||s7.x.DEFAULTSIDE,x=[],T=[],S=[],E=[],C=[],b=0,y=0,A=[],R=0,P=0;if(g)for(P=0;P<_;P++)m&&void 0===m[P]&&(m[P]=new rm.HE(1,1,1,1)),f&&void 0===f[P]&&(f[P]=new rf.Lt(0,0,1,1));if(g)for(P=0;P<_;P++){let e=p.face[P].length;for(R=0,s=.5*Math.tan((r=2*Math.PI/e)/2),n=.5;RhZ(e,{shape:t,holes:r,updatable:s,sideOrientation:n},i,a),sp.Kj.ExtrudePolygon=(e,t,i,r,s,n,a,o=earcut)=>(function(e,t,i=null,r=earcut){return hZ(e,t,i,r)})(e,{shape:t,holes:s,depth:i,updatable:n,sideOrientation:a},r,o),sp.Kj.ExtrudeShape=(e,t,i,r,s,n,a=null,o,l,h)=>hJ(e,{shape:t,path:i,scale:r,rotation:s,cap:0===n?0:n||sp.Kj.NO_CAP,sideOrientation:l,instance:h,updatable:o},a),sp.Kj.ExtrudeShapeCustom=(e,t,i,r,s,n,a,o,l,h,u,c)=>h0(e,{shape:t,path:i,scaleFunction:r,rotationFunction:s,ribbonCloseArray:n,ribbonClosePath:a,cap:0===o?0:o||sp.Kj.NO_CAP,sideOrientation:u,instance:c,updatable:h},l),sp.Kj.CreateLathe=(e,t,i,r,s,n,a)=>(function(e,t,i=null){let r,s;let n=t.arc?t.arc<=0||t.arc>1?1:t.arc:1,a=void 0===t.closed||t.closed,o=t.shape,l=t.radius||1,h=t.tessellation||64,u=t.clip||0,c=t.updatable,d=sp.Kj._GetDefaultSideOrientation(t.sideOrientation),p=t.cap||sp.Kj.NO_CAP,_=[],f=t.invertUV||!1,m=0,g=0,v=2*Math.PI/h*n;for(m=0;m<=h-u;m++){for(s=[],(p==sp.Kj.CAP_START||p==sp.Kj.CAP_ALL)&&(s.push(new rf.P(0,o[0].y,0)),s.push(new rf.P(Math.cos(m*v)*o[0].x*l,o[0].y,Math.sin(m*v)*o[0].x*l))),g=0;g(function(e,t,i=null){let r,s;let n=t.path,a=t.instance,o=1;void 0!==t.radius?o=t.radius:a&&(o=a._creationDataStorage.radius);let l=t.tessellation||64,h=t.radiusFunction||null,u=t.cap||sp.Kj.NO_CAP,c=t.invertUV||!1,d=t.updatable,p=sp.Kj._GetDefaultSideOrientation(t.sideOrientation);t.arc=t.arc&&(t.arc<=0||t.arc>1)?1:t.arc||1;let _=(e,t,i,r,s,n,a,o)=>{let l,h,u,c;let d=t.getTangents(),p=t.getNormals(),_=t.getDistances(),f=2*Math.PI/s*o,m=n||(()=>r),g=rf.jp.Matrix[0],v=a===sp.Kj.NO_CAP||a===sp.Kj.CAP_END?0:2;for(let t=0;t{let r=[];for(let s=0;s3?0:u,t.arc),closePath:!0,closeArray:!1,updatable:d,sideOrientation:p,invertUV:c,frontUVs:t.frontUVs,backUVs:t.backUVs},i);return f._creationDataStorage.pathArray=s,f._creationDataStorage.path3D=r,f._creationDataStorage.tessellation=l,f._creationDataStorage.cap=u,f._creationDataStorage.arc=t.arc,f._creationDataStorage.radius=o,f})(e,{path:t,radius:i,tessellation:r,radiusFunction:s,arc:1,cap:n,updatable:o,sideOrientation:l,instance:h},a),s7.x.CreatePolyhedron=h2,sp.Kj.CreatePolyhedron=(e,t,i)=>(function(e,t={},i=null){let r=new sp.Kj(e,i);return t.sideOrientation=sp.Kj._GetDefaultSideOrientation(t.sideOrientation),r._originalBuilderSideOrientation=t.sideOrientation,h2(t).applyToMesh(r,t.updatable),r})(e,t,i);let h3=new rf.P(1,0,0),h4=new rf.P(-1,0,0),h5=new rf.P(0,1,0),h6=new rf.P(0,-1,0),h8=new rf.P(0,0,1),h7=new rf.P(0,0,-1);class h9{constructor(e=rf.P.Zero(),t=rf.P.Up(),i=rf.FM.Zero(),r=0,s=0,n=null,a=null,o=null,l=null){this.position=e,this.normal=t,this.uv=i,this.vertexIdx=r,this.vertexIdxForBones=s,this.localPositionOverride=n,this.localNormalOverride=a,this.matrixIndicesOverride=o,this.matrixWeightsOverride=l}clone(){var e,t,i,r;return new h9(this.position.clone(),this.normal.clone(),this.uv.clone(),this.vertexIdx,this.vertexIdxForBones,null===(e=this.localPositionOverride)||void 0===e?void 0:e.slice(),null===(t=this.localNormalOverride)||void 0===t?void 0:t.slice(),null===(i=this.matrixIndicesOverride)||void 0===i?void 0:i.slice(),null===(r=this.matrixWeightsOverride)||void 0===r?void 0:r.slice())}}sp.Kj.CreateDecal=(e,t,i,r,s,n)=>(function(e,t,i){var r,s,n,a;let o=!!t.skeleton,l=i.localMode||o,h=null!==t.overrideMaterialSideOrientation&&void 0!==t.overrideMaterialSideOrientation,u=t.getIndices(),c=o?t.getPositionData(!0,!0):t.getVerticesData(sm.o.PositionKind),d=o?t.getNormalsData(!0,!0):t.getVerticesData(sm.o.NormalKind),p=l?o?t.getVerticesData(sm.o.PositionKind):c:null,_=l?o?t.getVerticesData(sm.o.NormalKind):d:null,f=t.getVerticesData(sm.o.UVKind),m=o?t.getVerticesData(sm.o.MatricesIndicesKind):null,g=o?t.getVerticesData(sm.o.MatricesWeightsKind):null,v=o?t.getVerticesData(sm.o.MatricesIndicesExtraKind):null,x=o?t.getVerticesData(sm.o.MatricesWeightsExtraKind):null,T=i.position||rf.P.Zero(),S=i.normal||rf.P.Up(),E=i.size||rf.P.One(),C=i.angle||0;if(!S){let e=new rf.P(0,0,1),i=t.getScene().activeCamera,r=rf.P.TransformCoordinates(e,i.getWorldMatrix());S=i.globalPosition.subtract(r)}let b=-Math.atan2(S.z,S.x)-Math.PI/2,y=Math.sqrt(S.x*S.x+S.z*S.z),A=Math.atan2(S.y,y),R=new s7.x;R.indices=[],R.positions=[],R.normals=[],R.uvs=[],R.matricesIndices=o?[]:null,R.matricesWeights=o?[]:null,R.matricesIndicesExtra=v?[]:null,R.matricesWeightsExtra=x?[]:null;let P=0,I=(e,t)=>{let r=new h9;if(!u||!c||!d)return r;let s=u[e];if(r.vertexIdx=3*s,r.vertexIdxForBones=4*s,r.position=new rf.P(c[3*s],c[3*s+1],c[3*s+2]),rf.P.TransformCoordinatesToRef(r.position,t,r.position),r.normal=new rf.P(d[3*s],d[3*s+1],d[3*s+2]),rf.P.TransformNormalToRef(r.normal,t,r.normal),i.captureUVS&&f){let e=f[2*s+1];r.uv=new rf.FM(f[2*s],sY.e.UseOpenGLOrientationForUV?1-e:e)}return r},M=[0,0,0,0],D=(e,t)=>{if(0===e.length)return e;let i=.5*Math.abs(rf.P.Dot(E,t)),r=(e,t,i,r)=>{for(let s=0;s{var n,a,o,l,h,u,c,d,f,v,x,T,S,E,C,b;let y=rf.P.GetClipFactor(e.position,s.position,t,i),A=M,R=M;if(m&&g){let t=e.matrixIndicesOverride?0:e.vertexIdxForBones,i=null!==(n=e.matrixIndicesOverride)&&void 0!==n?n:m,h=null!==(a=e.matrixWeightsOverride)&&void 0!==a?a:g,u=s.matrixIndicesOverride?0:s.vertexIdxForBones,c=null!==(o=s.matrixIndicesOverride)&&void 0!==o?o:m,d=null!==(l=s.matrixWeightsOverride)&&void 0!==l?l:g;A=[0,0,0,0],R=[0,0,0,0];let p=0;for(let e=0;e<4;++e)if(h[t+e]>0){let s=r(c,i[t+e],u,4);A[p]=i[t+e],R[p]=rk.R.Lerp(h[t+e],s>=0?d[s]:0,y),p++}for(let e=0;e<4&&p<4;++e){let s=c[u+e];-1===r(i,s,t,4)&&(A[p]=s,R[p]=rk.R.Lerp(0,d[u+e],y),p++)}let _=R[0]+R[1]+R[2]+R[3];R[0]/=_,R[1]/=_,R[2]/=_,R[3]/=_}let P=e.localPositionOverride?e.localPositionOverride[0]:null!==(h=null==p?void 0:p[e.vertexIdx])&&void 0!==h?h:0,I=e.localPositionOverride?e.localPositionOverride[1]:null!==(u=null==p?void 0:p[e.vertexIdx+1])&&void 0!==u?u:0,D=e.localPositionOverride?e.localPositionOverride[2]:null!==(c=null==p?void 0:p[e.vertexIdx+2])&&void 0!==c?c:0,O=s.localPositionOverride?s.localPositionOverride[0]:null!==(d=null==p?void 0:p[s.vertexIdx])&&void 0!==d?d:0,N=s.localPositionOverride?s.localPositionOverride[1]:null!==(f=null==p?void 0:p[s.vertexIdx+1])&&void 0!==f?f:0,F=s.localPositionOverride?s.localPositionOverride[2]:null!==(v=null==p?void 0:p[s.vertexIdx+2])&&void 0!==v?v:0,L=e.localNormalOverride?e.localNormalOverride[0]:null!==(x=null==_?void 0:_[e.vertexIdx])&&void 0!==x?x:0,w=e.localNormalOverride?e.localNormalOverride[1]:null!==(T=null==_?void 0:_[e.vertexIdx+1])&&void 0!==T?T:0,B=e.localNormalOverride?e.localNormalOverride[2]:null!==(S=null==_?void 0:_[e.vertexIdx+2])&&void 0!==S?S:0,U=s.localNormalOverride?s.localNormalOverride[0]:null!==(E=null==_?void 0:_[s.vertexIdx])&&void 0!==E?E:0,V=s.localNormalOverride?s.localNormalOverride[1]:null!==(C=null==_?void 0:_[s.vertexIdx+1])&&void 0!==C?C:0,k=s.localNormalOverride?s.localNormalOverride[2]:null!==(b=null==_?void 0:_[s.vertexIdx+2])&&void 0!==b?b:0,G=L+(U-L)*y,z=w+(V-w)*y,W=B+(k-B)*y,H=Math.sqrt(G*G+z*z+W*W);return new h9(rf.P.Lerp(e.position,s.position,y),rf.P.Lerp(e.normal,s.normal,y).normalize(),rf.FM.Lerp(e.uv,s.uv,y),-1,-1,p?[P+(O-P)*y,I+(N-I)*y,D+(F-D)*y]:null,_?[G/H,z/H,W/H]:null,A,R)},n=null;e.length>3&&(n=[]);for(let r=0;r0,_=c>0,f=d>0;switch((p?1:0)+(_?1:0)+(f?1:0)){case 0:e.length>3?(n.push(e[r]),n.push(e[r+1]),n.push(e[r+2])):n=e;break;case 1:if(n=null!=n?n:[],p&&(a=e[r+1],o=e[r+2],l=s(e[r],a),h=s(e[r],o)),_){a=e[r],o=e[r+2],l=s(e[r+1],a),h=s(e[r+1],o),n.push(l),n.push(o.clone()),n.push(a.clone()),n.push(o.clone()),n.push(l.clone()),n.push(h);break}f&&(a=e[r],o=e[r+1],l=s(e[r+2],a),h=s(e[r+2],o)),a&&o&&l&&h&&(n.push(a.clone()),n.push(o.clone()),n.push(l),n.push(h),n.push(l.clone()),n.push(o.clone()));break;case 2:n=null!=n?n:[],p||(o=s(a=e[r].clone(),e[r+1]),l=s(a,e[r+2]),n.push(a),n.push(o),n.push(l)),_||(o=s(a=e[r+1].clone(),e[r+2]),l=s(a,e[r]),n.push(a),n.push(o),n.push(l)),f||(o=s(a=e[r+2].clone(),e[r]),l=s(a,e[r+1]),n.push(a),n.push(o),n.push(l))}}return n},O=t instanceof sp.Kj?t:null,N=null==O?void 0:O._thinInstanceDataStorage.matrixData,F=(null==O?void 0:O.thinInstanceCount)||1,L=rf.jp.Matrix[0];L.copyFrom(rf.y3.IdentityReadOnly);for(let e=0;e=-t[0].normal.z&&0>=-t[1].normal.z&&0>=-t[2].normal.z)&&(t=D(t,h3))&&(t=D(t,h4))&&(t=D(t,h5))&&(t=D(t,h6))&&(t=D(t,h8))&&(t=D(t,h7)))for(let e=0;eue.Parse(e,t);class ue extends sp.Kj{constructor(){super(...arguments),this.goldbergData={faceColors:[],faceCenters:[],faceZaxis:[],faceXaxis:[],faceYaxis:[],nbSharedFaces:0,nbUnsharedFaces:0,nbFaces:0,nbFacesAtPole:0,adjacentFaces:[]}}relatedGoldbergFace(e,t){return void 0===t?(e>this.goldbergData.nbUnsharedFaces-1&&(rb.Y.Warn("Maximum number of unshared faces used"),e=this.goldbergData.nbUnsharedFaces-1),this.goldbergData.nbUnsharedFaces+e):(e>11&&(rb.Y.Warn("Last pole used"),e=11),t>this.goldbergData.nbFacesAtPole-1&&(rb.Y.Warn("Maximum number of faces at a pole used"),t=this.goldbergData.nbFacesAtPole-1),12+e*this.goldbergData.nbFacesAtPole+t)}_changeGoldbergFaceColors(e){for(let t=0;t1&&(r=1),u.push(r,s);for(let e=0;e<6;e++)r=o.x+l*Math.cos(h+e*Math.PI/3),s=o.y+l*Math.sin(h+e*Math.PI/3),r<0&&(r=0),r>1&&(r=1),c.push(r,s);for(let e=n;erm.HE.FromArray(e)),i.faceCenters=i.faceCenters.map(e=>rf.P.FromArray(e)),i.faceZaxis=i.faceZaxis.map(e=>rf.P.FromArray(e)),i.faceXaxis=i.faceXaxis.map(e=>rf.P.FromArray(e)),i.faceYaxis=i.faceYaxis.map(e=>rf.P.FromArray(e));let r=new ue(e.name,t);return r.goldbergData=i,r}}class ut{constructor(e){this._paths=[],this._tempPaths=[],this._holes=[],this._resolution=e}moveTo(e,t){this._currentPath=new st(e,t),this._tempPaths.push(this._currentPath)}lineTo(e,t){this._currentPath.addLineTo(e,t)}quadraticCurveTo(e,t,i,r){this._currentPath.addQuadraticCurveTo(e,t,i,r,this._resolution)}bezierCurveTo(e,t,i,r,s,n){this._currentPath.addBezierCurveTo(e,t,i,r,s,n,this._resolution)}extractHoles(){for(let e of this._tempPaths)e.area()>0?this._holes.push(e):this._paths.push(e);if(!this._paths.length&&this._holes.length){let e=this._holes;this._holes=this._paths,this._paths=e}this._tempPaths.length=0}get paths(){return this._paths}get holes(){return this._holes}}class ui{static CreateBoneWeightShader(e,t){var i,r,s,n,a,o;let l=e.skeleton,h=null!==(i=e.colorBase)&&void 0!==i?i:rm.Wo.Black(),u=null!==(r=e.colorZero)&&void 0!==r?r:rm.Wo.Blue(),c=null!==(s=e.colorQuarter)&&void 0!==s?s:rm.Wo.Green(),d=null!==(n=e.colorHalf)&&void 0!==n?n:rm.Wo.Yellow(),p=null!==(a=e.colorFull)&&void 0!==a?a:rm.Wo.Red(),_=null!==(o=e.targetBoneIndex)&&void 0!==o?o:0;nd.Q.ShadersStore["boneWeights:"+l.name+"VertexShader"]=`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + + #include + #if NUM_BONE_INFLUENCERS == 0 + attribute vec4 matricesIndices; + attribute vec4 matricesWeights; + #endif + #include + + #include + + varying vec3 vColor; + + uniform vec3 colorBase; + uniform vec3 colorZero; + uniform vec3 colorQuarter; + uniform vec3 colorHalf; + uniform vec3 colorFull; + + uniform float targetBoneIndex; + + void main() { + vec3 positionUpdated = position; + + #include + #include + #include + + vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); + + vec3 color = colorBase; + float totalWeight = 0.; + if(matricesIndices[0] == targetBoneIndex && matricesWeights[0] > 0.){ + totalWeight += matricesWeights[0]; + } + if(matricesIndices[1] == targetBoneIndex && matricesWeights[1] > 0.){ + totalWeight += matricesWeights[1]; + } + if(matricesIndices[2] == targetBoneIndex && matricesWeights[2] > 0.){ + totalWeight += matricesWeights[2]; + } + if(matricesIndices[3] == targetBoneIndex && matricesWeights[3] > 0.){ + totalWeight += matricesWeights[3]; + } + + color = mix(color, colorZero, smoothstep(0., 0.25, totalWeight)); + color = mix(color, colorQuarter, smoothstep(0.25, 0.5, totalWeight)); + color = mix(color, colorHalf, smoothstep(0.5, 0.75, totalWeight)); + color = mix(color, colorFull, smoothstep(0.75, 1.0, totalWeight)); + vColor = color; + + gl_Position = projection * view * worldPos; + }`,nd.Q.ShadersStore["boneWeights:"+l.name+"FragmentShader"]=` + precision highp float; + varying vec3 vPosition; + + varying vec3 vColor; + + void main() { + vec4 color = vec4(vColor, 1.0); + gl_FragColor = color; + } + `;let f=new hV("boneWeight:"+l.name,t,{vertex:"boneWeights:"+l.name,fragment:"boneWeights:"+l.name},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorBase","colorZero","colorQuarter","colorHalf","colorFull","targetBoneIndex"]});return f.setColor3("colorBase",h),f.setColor3("colorZero",u),f.setColor3("colorQuarter",c),f.setColor3("colorHalf",d),f.setColor3("colorFull",p),f.setFloat("targetBoneIndex",_),f.getClassName=()=>"BoneWeightShader",f.transparencyMode=nu.F.MATERIAL_OPAQUE,f}static CreateSkeletonMapShader(e,t){var i;let r=e.skeleton,s=null!==(i=e.colorMap)&&void 0!==i?i:[{color:new rm.Wo(1,.38,.18),location:0},{color:new rm.Wo(.59,.18,1),location:.2},{color:new rm.Wo(.59,1,.18),location:.4},{color:new rm.Wo(1,.87,.17),location:.6},{color:new rm.Wo(1,.17,.42),location:.8},{color:new rm.Wo(.17,.68,1),location:1}],n=r.bones.length+1,a=ui._CreateBoneMapColorBuffer(n,s,t),o=new hV("boneWeights:"+r.name,t,{vertexSource:`precision highp float; + + attribute vec3 position; + attribute vec2 uv; + + uniform mat4 view; + uniform mat4 projection; + uniform mat4 worldViewProjection; + uniform float colorMap[`+4*r.bones.length+`]; + + #include + #if NUM_BONE_INFLUENCERS == 0 + attribute vec4 matricesIndices; + attribute vec4 matricesWeights; + #endif + #include + #include + + varying vec3 vColor; + + void main() { + vec3 positionUpdated = position; + + #include + #include + #include + + vec3 color = vec3(0.); + bool first = true; + + for (int i = 0; i < 4; i++) { + int boneIdx = int(matricesIndices[i]); + float boneWgt = matricesWeights[i]; + + vec3 c = vec3(colorMap[boneIdx * 4 + 0], colorMap[boneIdx * 4 + 1], colorMap[boneIdx * 4 + 2]); + + if (boneWgt > 0.) { + if (first) { + first = false; + color = c; + } else { + color = mix(color, c, boneWgt); + } + } + } + + vColor = color; + + vec4 worldPos = finalWorld * vec4(positionUpdated, 1.0); + + gl_Position = projection * view * worldPos; + }`,fragmentSource:` + precision highp float; + varying vec3 vColor; + + void main() { + vec4 color = vec4( vColor, 1.0 ); + gl_FragColor = color; + } + `},{attributes:["position","normal","matricesIndices","matricesWeights"],uniforms:["world","worldView","worldViewProjection","view","projection","viewProjection","colorMap"]});return o.setFloats("colorMap",a),o.getClassName=()=>"SkeletonMapShader",o.transparencyMode=nu.F.MATERIAL_OPAQUE,o}static _CreateBoneMapColorBuffer(e,t,i){let r=new lq("temp",{width:e,height:1},i,!1),s=r.getContext(),n=s.createLinearGradient(0,0,e,0);t.forEach(e=>{n.addColorStop(e.location,e.color.toHexString())}),s.fillStyle=n,s.fillRect(0,0,e,1),r.update();let a=[],o=s.getImageData(0,0,e,1).data,l=1/255;for(let e=0;eui.DISPLAY_SPHERE_AND_SPURS&&(e=ui.DISPLAY_LINES),this.options.displayMode=e}constructor(e,t,i,r=!0,s=3,n={}){var a,o,l,h,u,c,d,p,_,f,m,g,v,x;if(this.skeleton=e,this.mesh=t,this.autoUpdateBonesMatrices=r,this.renderingGroupId=s,this.options=n,this.color=rm.Wo.White(),this._debugLines=[],this._localAxes=null,this._isEnabled=!0,this._obs=null,this._scene=i,this._ready=!1,n.pauseAnimations=null===(a=n.pauseAnimations)||void 0===a||a,n.returnToRest=null!==(o=n.returnToRest)&&void 0!==o&&o,n.displayMode=null!==(l=n.displayMode)&&void 0!==l?l:ui.DISPLAY_LINES,n.displayOptions=null!==(h=n.displayOptions)&&void 0!==h?h:{},n.displayOptions.midStep=null!==(u=n.displayOptions.midStep)&&void 0!==u?u:.235,n.displayOptions.midStepFactor=null!==(c=n.displayOptions.midStepFactor)&&void 0!==c?c:.155,n.displayOptions.sphereBaseSize=null!==(d=n.displayOptions.sphereBaseSize)&&void 0!==d?d:.15,n.displayOptions.sphereScaleUnit=null!==(p=n.displayOptions.sphereScaleUnit)&&void 0!==p?p:2,n.displayOptions.sphereFactor=null!==(_=n.displayOptions.sphereFactor)&&void 0!==_?_:.865,n.displayOptions.spurFollowsChild=null!==(f=n.displayOptions.spurFollowsChild)&&void 0!==f&&f,n.displayOptions.showLocalAxes=null!==(m=n.displayOptions.showLocalAxes)&&void 0!==m&&m,n.displayOptions.localAxesSize=null!==(g=n.displayOptions.localAxesSize)&&void 0!==g?g:.075,n.computeBonesUsingShaders=null===(v=n.computeBonesUsingShaders)||void 0===v||v,n.useAllBones=null===(x=n.useAllBones)||void 0===x||x,this._boneIndices=new Set,!n.useAllBones){let e=null==t?void 0:t.getVerticesData(sm.o.MatricesIndicesKind),i=null==t?void 0:t.getVerticesData(sm.o.MatricesWeightsKind);if(e&&i)for(let t=0;tui.DISPLAY_SPHERE_AND_SPURS&&(T=ui.DISPLAY_LINES),this.displayMode=T,this.update(),this._bindObs()}_bindObs(){this.displayMode===ui.DISPLAY_LINES&&(this._obs=this.scene.onBeforeRenderObservable.add(()=>{this._displayLinesUpdate()}))}update(){switch(this.displayMode){case ui.DISPLAY_LINES:this._displayLinesUpdate();break;case ui.DISPLAY_SPHERES:this._buildSpheresAndSpurs(!0);break;case ui.DISPLAY_SPHERE_AND_SPURS:this._buildSpheresAndSpurs(!1)}this._buildLocalAxes()}set isEnabled(e){this.isEnabled!==e&&(this._isEnabled=e,this.debugMesh&&this.debugMesh.setEnabled(e),e&&!this._obs?this._bindObs():!e&&this._obs&&(this.scene.onBeforeRenderObservable.remove(this._obs),this._obs=null))}get isEnabled(){return this._isEnabled}_getBonePosition(e,t,i,r=0,s=0,n=0){let a=rf.jp.Matrix[0],o=t.getParent();if(a.copyFrom(t.getLocalMatrix()),0!==r||0!==s||0!==n){let e=rf.jp.Matrix[1];rf.y3.IdentityToRef(e),e.setTranslationFromFloats(r,s,n),e.multiplyToRef(a,a)}o&&a.multiplyToRef(o.getAbsoluteMatrix(),a),a.multiplyToRef(i,a),e.x=a.m[12],e.y=a.m[13],e.z=a.m[14]}_getLinesForBonesWithLength(e,t){let i,r;let s=e.length;t?(i=t.getWorldMatrix(),r=t.position):(i=new rf.y3,r=e[0].position);let n=0;for(let t=0;t=0;n--){let r=e[n],a=r.getParent();if(!a||!this._boneIndices.has(r.getIndex())&&!this.options.useAllBones)continue;let o=this._debugLines[s];o||(o=[rf.P.Zero(),rf.P.Zero()],this._debugLines[s]=o),r.getAbsolutePositionToRef(t,o[0]),a.getAbsolutePositionToRef(t,o[1]),o[0].subtractInPlace(i),o[1].subtractInPlace(i),s++}n||t.dispose()}_revert(e){this.options.pauseAnimations&&(this.scene.animationsEnabled=e,this.utilityLayer.utilityLayerScene.animationsEnabled=e)}_getAbsoluteBindPoseToRef(e,t){if(null===e||-1===e._index){t.copyFrom(rf.y3.Identity());return}this._getAbsoluteBindPoseToRef(e.getParent(),t),e.getBindMatrix().multiplyToRef(t,t)}_buildSpheresAndSpurs(e=!0){var t,i;this._debugMesh&&(this._debugMesh.dispose(),this._debugMesh=null,this.ready=!1),this._ready=!1;let r=null===(t=this.utilityLayer)||void 0===t?void 0:t.utilityLayerScene,s=this.skeleton.bones,n=[],a=[],o=this.scene.animationsEnabled;try{this.options.pauseAnimations&&(this.scene.animationsEnabled=!1,r.animationsEnabled=!1),this.options.returnToRest&&this.skeleton.returnToRest(),this.autoUpdateBonesMatrices&&this.skeleton.computeAbsoluteMatrices();let t=Number.NEGATIVE_INFINITY,l=this.options.displayOptions||{};for(let i=0;i{let s=new rf.y3;i.getLocalMatrix().multiplyToRef(h,s);let n=new rf.P;s.decompose(void 0,void 0,n);let c=rf.P.Distance(u,n);if(c>t&&(t=c),e)return;let d=n.clone().subtract(u.clone()),p=d.length(),_=d.normalize().scale(p),f=l.midStep||.165,m=l.midStepFactor||.215,g=_.scale(f),v=h0("skeletonViewer",{shape:[new rf.P(1,-1,0),new rf.P(1,1,0),new rf.P(-1,1,0),new rf.P(-1,-1,0),new rf.P(1,-1,0)],path:[rf.P.Zero(),g,_],scaleFunction:e=>{switch(e){case 0:case 2:break;case 1:return p*m}return 0},sideOrientation:sp.Kj.DEFAULTSIDE,updatable:!1},r),x=v.getTotalVertices(),T=[],S=[];for(let e=0;e9?S.push(i.getIndex(),0,0,0):S.push(o.getIndex(),0,0,0);v.position=u.clone(),v.setVerticesData(sm.o.MatricesWeightsKind,T,!1),v.setVerticesData(sm.o.MatricesIndicesKind,S,!1),v.convertToFlatShadedMesh(),a.push(v)});let c=l.sphereBaseSize||.2,d=hM("skeletonViewer",{segments:6,diameter:c,updatable:!0},r),p=d.getTotalVertices(),_=[],f=[];for(let e=0;e{this._gpuFrameTimeToken||(this._gpuFrameTimeToken=this.startTimeQuery())}),this._onEndFrameObserver=this.onEndFrameObservable.add(()=>{if(!this._gpuFrameTimeToken)return;let e=this.endTimeQuery(this._gpuFrameTimeToken);e>-1&&(this._gpuFrameTimeToken=null,this._gpuFrameTime.fetchNewFrame(),this._gpuFrameTime.addCount(e,!0))})):(this.onBeginFrameObservable.remove(this._onBeginFrameObserver),this._onBeginFrameObserver=null,this.onEndFrameObservable.remove(this._onEndFrameObserver),this._onEndFrameObserver=null))},sR.D.prototype._getGlAlgorithmType=function(e){return e===sf.x.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE?this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE:this._gl.ANY_SAMPLES_PASSED},Object.defineProperty(sf.x.prototype,"isOcclusionQueryInProgress",{get:function(){return this._occlusionDataStorage.isOcclusionQueryInProgress},set:function(e){this._occlusionDataStorage.isOcclusionQueryInProgress=e},enumerable:!1,configurable:!0}),Object.defineProperty(sf.x.prototype,"_occlusionDataStorage",{get:function(){return this.__occlusionDataStorage||(this.__occlusionDataStorage=new un),this.__occlusionDataStorage},enumerable:!1,configurable:!0}),Object.defineProperty(sf.x.prototype,"isOccluded",{get:function(){return this._occlusionDataStorage.isOccluded},set:function(e){this._occlusionDataStorage.isOccluded=e},enumerable:!0,configurable:!0}),Object.defineProperty(sf.x.prototype,"occlusionQueryAlgorithmType",{get:function(){return this._occlusionDataStorage.occlusionQueryAlgorithmType},set:function(e){this._occlusionDataStorage.occlusionQueryAlgorithmType=e},enumerable:!0,configurable:!0}),Object.defineProperty(sf.x.prototype,"occlusionType",{get:function(){return this._occlusionDataStorage.occlusionType},set:function(e){this._occlusionDataStorage.occlusionType=e},enumerable:!0,configurable:!0}),Object.defineProperty(sf.x.prototype,"occlusionRetryCount",{get:function(){return this._occlusionDataStorage.occlusionRetryCount},set:function(e){this._occlusionDataStorage.occlusionRetryCount=e},enumerable:!0,configurable:!0}),Object.defineProperty(sf.x.prototype,"forceRenderingWhenOccluded",{get:function(){return this._occlusionDataStorage.forceRenderingWhenOccluded},set:function(e){this._occlusionDataStorage.forceRenderingWhenOccluded=e},enumerable:!0,configurable:!0}),sf.x.prototype._checkOcclusionQuery=function(){let e=this._occlusionDataStorage;if(e.occlusionType===sf.x.OCCLUSION_TYPE_NONE)return e.isOccluded=!1,!1;let t=this.getEngine();if(!t.getCaps().supportOcclusionQuery||!t.isQueryResultAvailable)return e.isOccluded=!1,!1;if(this.isOcclusionQueryInProgress&&null!==this._occlusionQuery&&void 0!==this._occlusionQuery){if(t.isQueryResultAvailable(this._occlusionQuery)){let i=t.getQueryResult(this._occlusionQuery);e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=!(i>0)}else{if(e.occlusionInternalRetryCounter++,-1===e.occlusionRetryCount||!(e.occlusionInternalRetryCounter>e.occlusionRetryCount))return e.occlusionType!==sf.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded;e.isOcclusionQueryInProgress=!1,e.occlusionInternalRetryCounter=0,e.isOccluded=e.occlusionType!==sf.x.OCCLUSION_TYPE_OPTIMISTIC&&e.isOccluded}}let i=this.getScene();if(i.getBoundingBoxRenderer){let r=i.getBoundingBoxRenderer();null===this._occlusionQuery&&(this._occlusionQuery=t.createQuery()),t.beginOcclusionQuery(e.occlusionQueryAlgorithmType,this._occlusionQuery)&&(r.renderOcclusionBoundingBox(this),t.endOcclusionQuery(e.occlusionQueryAlgorithmType),this._occlusionDataStorage.isOcclusionQueryInProgress=!0)}return e.isOccluded},sR.D.prototype.createTransformFeedback=function(){let e=this._gl.createTransformFeedback();if(!e)throw Error("Unable to create Transform Feedback");return e},sR.D.prototype.deleteTransformFeedback=function(e){this._gl.deleteTransformFeedback(e)},sR.D.prototype.bindTransformFeedback=function(e){this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK,e)},sR.D.prototype.beginTransformFeedback=function(e=!0){this._gl.beginTransformFeedback(e?this._gl.POINTS:this._gl.TRIANGLES)},sR.D.prototype.endTransformFeedback=function(){this._gl.endTransformFeedback()},sR.D.prototype.setTranformFeedbackVaryings=function(e,t){this._gl.transformFeedbackVaryings(e,t,this._gl.INTERLEAVED_ATTRIBS)},sR.D.prototype.bindTransformFeedbackBuffer=function(e){this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER,0,e?e.underlyingResource:null)},sK.B.prototype.createExternalTexture=function(e){return null},sK.B.prototype.setExternalTexture=function(e,t){throw Error("setExternalTexture: This engine does not support external textures!")},sK.B.prototype.updateVideoTexture=function(e,t,i){if(!e||e._isDisabled)return;let r=this._getInternalFormat(e.format),s=this._getRGBABufferInternalSizedFormat(0,e.format),n=this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0);this._unpackFlipY(!i);try{if(void 0===this._videoTextureSupported&&(this._gl.getError(),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t),0!==this._gl.getError()?this._videoTextureSupported=!1:this._videoTextureSupported=!0),this._videoTextureSupported)this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,t);else{if(!e._workingCanvas){e._workingCanvas=this.createCanvas(e.width,e.height);let t=e._workingCanvas.getContext("2d");if(!t)throw Error("Unable to get 2d context");e._workingContext=t,e._workingCanvas.width=e.width,e._workingCanvas.height=e.height}e._workingContext.clearRect(0,0,e.width,e.height),e._workingContext.drawImage(t,0,0,t.videoWidth,t.videoHeight,0,0,e.width,e.height),this._gl.texImage2D(this._gl.TEXTURE_2D,0,s,r,this._gl.UNSIGNED_BYTE,e._workingCanvas)}e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),n||this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0}catch(t){e._isDisabled=!0}},sK.B.prototype.restoreSingleAttachment=function(){let e=this._gl;this.bindAttachments([e.BACK])},sK.B.prototype.restoreSingleAttachmentForRenderTarget=function(){let e=this._gl;this.bindAttachments([e.COLOR_ATTACHMENT0])},sK.B.prototype.buildTextureLayout=function(e){let t=this._gl,i=[];for(let r=0;r1?"COLOR_ATTACHMENT"+t:"COLOR_ATTACHMENT"+t+"_WEBGL"],r.readBuffer(s[t]),r.drawBuffers(s),r.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r.COLOR_BUFFER_BIT,r.NEAREST)}for(let e=0;e1?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];r.drawBuffers(s)}for(let i=0;i1&&(13===t.depthTextureFormat||17===t.depthTextureFormat||16===t.depthTextureFormat||14===t.depthTextureFormat||18===t.depthTextureFormat)&&(h=t.depthTextureFormat)),x.label=null!==(r=null==t?void 0:t.label)&&void 0!==r?r:"MultiRenderTargetWrapper";let T=this._gl,S=T.createFramebuffer();this._bindUnboundFramebuffer(S);let E=e.width||e,C=e.height||e,b=[],y=[],A=this.webGLVersion>1&&l&&(13===t.depthTextureFormat||17===t.depthTextureFormat||18===t.depthTextureFormat),R=this._setupFramebufferDepthAttachments(!A&&o,!l&&a,E,C);x._framebuffer=S,x._depthStencilBuffer=R,x._generateDepthBuffer=!l&&a,x._generateStencilBuffer=!A&&o,x._attachments=y;for(let e=0;e1||this.isWebGPU);let u=this.webGLVersion>1,m=T[u?"COLOR_ATTACHMENT"+e:"COLOR_ATTACHMENT"+e+"_WEBGL"];if(y.push(m),-1===o)continue;let g=new sq.l(this,sq.S.MultiRenderTarget);b[e]=g,T.activeTexture(T["TEXTURE"+e]),T.bindTexture(o,g._hardwareTexture.underlyingResource),T.texParameteri(o,T.TEXTURE_MAG_FILTER,h.mag),T.texParameteri(o,T.TEXTURE_MIN_FILTER,h.min),T.texParameteri(o,T.TEXTURE_WRAP_S,T.CLAMP_TO_EDGE),T.texParameteri(o,T.TEXTURE_WRAP_T,T.CLAMP_TO_EDGE);let x=this._getRGBABufferInternalSizedFormat(i,a,r),S=this._getInternalFormat(a),A=this._getWebGLTextureType(i);if(u&&(35866===o||32879===o))35866===o?g.is2DArray=!0:g.is3D=!0,g.baseDepth=g.depth=l,T.texImage3D(o,0,x,E,C,l,0,S,A,null);else if(34067===o){for(let e=0;e<6;e++)T.texImage2D(T.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,x,E,C,0,S,A,null);g.isCube=!0}else T.texImage2D(T.TEXTURE_2D,0,x,E,C,0,S,A,null);n&&T.generateMipmap(o),this._bindTextureDirectly(o,null),g.baseWidth=E,g.baseHeight=C,g.width=E,g.height=C,g.isReady=!0,g.samples=1,g.generateMipMaps=n,g.samplingMode=t,g.type=i,g._useSRGBBuffer=r,g.format=a,this._internalTexturesCache.push(g)}if(l&&this._caps.depthTextureExtension){let e=new sq.l(this,sq.S.Depth),t=5,i=T.DEPTH_COMPONENT16,r=T.DEPTH_COMPONENT,s=T.UNSIGNED_SHORT,a=T.DEPTH_ATTACHMENT;this.webGLVersion<2?i=T.DEPTH_COMPONENT:14===h?(t=1,s=T.FLOAT,i=T.DEPTH_COMPONENT32F):18===h?(t=0,s=T.FLOAT_32_UNSIGNED_INT_24_8_REV,i=T.DEPTH32F_STENCIL8,r=T.DEPTH_STENCIL,a=T.DEPTH_STENCIL_ATTACHMENT):16===h?(t=0,s=T.UNSIGNED_INT,i=T.DEPTH_COMPONENT24,a=T.DEPTH_ATTACHMENT):(13===h||17===h)&&(t=12,s=T.UNSIGNED_INT_24_8,i=T.DEPTH24_STENCIL8,r=T.DEPTH_STENCIL,a=T.DEPTH_STENCIL_ATTACHMENT),T.activeTexture(T.TEXTURE0),T.bindTexture(T.TEXTURE_2D,e._hardwareTexture.underlyingResource),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MAG_FILTER,T.NEAREST),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MIN_FILTER,T.NEAREST),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_S,T.CLAMP_TO_EDGE),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_T,T.CLAMP_TO_EDGE),T.texImage2D(T.TEXTURE_2D,0,i,E,C,0,r,s,null),T.framebufferTexture2D(T.FRAMEBUFFER,a,T.TEXTURE_2D,e._hardwareTexture.underlyingResource,0),e.baseWidth=E,e.baseHeight=C,e.width=E,e.height=C,e.isReady=!0,e.samples=1,e.generateMipMaps=n,e.samplingMode=1,e.format=h,e.type=t,b[u]=e,this._internalTexturesCache.push(e)}return x.setTextures(b),i&&T.drawBuffers(y),this._bindUnboundFramebuffer(null),x.setLayerAndFaceIndices(g,m),this.resetTextureCache(),x},sK.B.prototype.updateMultipleRenderTargetTextureSampleCount=function(e,t,i=!0){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;let r=e._attachments.length;if(0===r)return 1;let s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples);let n=!!e._depthStencilBuffer;if(n&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null),t>1&&"function"==typeof s.renderbufferStorageMultisample){let n=s.createFramebuffer();if(!n)throw Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=n,this._bindUnboundFramebuffer(n);let a=[];for(let t=0;t1?"COLOR_ATTACHMENT"+i:"COLOR_ATTACHMENT"+i+"_WEBGL"],l=this._createRenderBuffer(r.width,r.height,t,-1,this._getRGBABufferInternalSizedFormat(r.type,r.format,r._useSRGBBuffer),o);if(!l)throw Error("Unable to create multi sampled framebuffer");n.addMSAARenderBuffer(l),r.samples=t,a.push(o)}i&&s.drawBuffers(a)}else this._bindUnboundFramebuffer(e._framebuffer);return n&&(e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t)),this._bindUnboundFramebuffer(null),t},sK.B.prototype._createDepthStencilCubeTexture=function(e,t,i){let r=new sq.l(this,sq.S.DepthStencil);if(r.isCube=!0,1===this.webGLVersion)return rb.Y.Error("Depth cube texture is not supported by WebGL 1."),r;let s=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1},t),n=this._gl;this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,r,!0),this._setupDepthStencilTexture(r,e,s.generateStencil,s.bilinearFiltering,s.comparisonFunction),i._depthStencilTexture=r,i._depthStencilTextureWithStencil=s.generateStencil;for(let t=0;t<6;t++)s.generateStencil?n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH24_STENCIL8,e,e,0,n.DEPTH_STENCIL,n.UNSIGNED_INT_24_8,null):n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,n.DEPTH_COMPONENT24,e,e,0,n.DEPTH_COMPONENT,n.UNSIGNED_INT,null);return this._bindTextureDirectly(n.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(r),r},sK.B.prototype._partialLoadFile=function(e,t,i,r,s=null){this._loadFile(e,e=>{i[t]=e,i._internalCount++,6===i._internalCount&&r(i)},void 0,void 0,!0,(e,t)=>{s&&e&&s(e.status+" "+e.statusText,t)})},sK.B.prototype._cascadeLoadFiles=function(e,t,i,r=null){let s=[];s._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(i[e],e,s,t,r)},sK.B.prototype._cascadeLoadImgs=function(e,t,i,r,s=null,n){let a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(r[o],o,a,e,t,i,s,n)},sK.B.prototype._partialLoadImg=function(e,t,i,r,s,n,a=null,o){let l=(0,sw.f)();(0,sB.r6)(e,e=>{i[t]=e,i._internalCount++,r&&r.removePendingData(l),6===i._internalCount&&n&&n(s,i)},(e,t)=>{r&&r.removePendingData(l),a&&a(e,t)},r?r.offlineProvider:null,o),r&&r.addPendingData(l)},sK.B.prototype._setCubeMapTextureParams=function(e,t,i){let r=this._gl;r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,t?r.LINEAR_MIPMAP_LINEAR:r.LINEAR),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),e.samplingMode=t?3:2,t&&this.getCaps().textureMaxLevel&&void 0!==i&&i>0&&(r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAX_LEVEL,i),e._maxLodLevel=i),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null)},sK.B.prototype.createCubeTextureBase=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=null,p=null,_=!1){let f=c||new sq.l(this,sq.S.Cube);f.isCube=!0,f.url=e,f.generateMipMaps=!r,f._lodGenerationScale=h,f._lodGenerationOffset=u,f._useSRGBBuffer=!!_&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||!!r),f!==c&&(f.label=e.substring(0,60)),this._doNotHandleContextLost||(f._extension=o,f._files=i);let m=e;this._transformTextureUrl&&!c&&(e=this._transformTextureUrl(e));let g=e.split("?")[0],v=g.lastIndexOf("."),x=o||(v>-1?g.substring(v).toLowerCase():""),T=null;for(let e of sK.B._TextureLoaders)if(e.canLoad(x)){T=e;break}if(T){let c=e=>{d&&d(f,e),T.loadCubeData(e,f,l,s,n)};i&&6===i.length?T.supportCascades?this._cascadeLoadFiles(t,e=>c(e.map(e=>new Uint8Array(e))),i,n):n?n("Textures type does not support cascades."):rb.Y.Warn("Texture loader does not support cascades."):this._loadFile(e,e=>c(new Uint8Array(e)),void 0,void 0,!0,(c,g)=>{e===m?n&&c&&n(c.status+" "+c.statusText,g):(rb.Y.Warn(`Failed to load ${e}, falling back to the ${m}`),this.createCubeTextureBase(m,t,i,!!r,s,n,a,o,l,h,u,f,d,p,_))})}else{if(!i||0===i.length)throw Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,f,(e,t)=>{p&&p(e,t)},i,n)}return this._internalTexturesCache.push(f),f},sK.B.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=this._gl;return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,e=>this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),(e,t)=>{let i=this.needPOTTextures?sK.B.GetExponentOfTwo(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=[_.TEXTURE_CUBE_MAP_POSITIVE_X,_.TEXTURE_CUBE_MAP_POSITIVE_Y,_.TEXTURE_CUBE_MAP_POSITIVE_Z,_.TEXTURE_CUBE_MAP_NEGATIVE_X,_.TEXTURE_CUBE_MAP_NEGATIVE_Y,_.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(_.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);let o=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:_.RGBA,l=a?this._getInternalFormat(a):_.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(l=o);for(let e=0;e{this.unRegisterView(e)}),s},sR.D.prototype.unRegisterView=function(e){if(!this.views||0===this.views.length)return this;for(let t of this.views)if(t.target===e){let e=this.views.indexOf(t);-1!==e&&this.views.splice(e,1);break}return this},sR.D.prototype._renderViewStep=function(e){let t=e.target,i=t.getContext("2d");if(!i)return!0;let r=this.getRenderingCanvas();ua.notifyObservers(e);let s=e.camera,n=null,a=null,o=null;if(s&&(n=(o=Array.isArray(s)?s[0].getScene():s.getScene()).activeCamera,a=o.activeCameras,this.activeView=e,Array.isArray(s)?o.activeCameras=s:(o.activeCamera=s,o.activeCameras=null)),e.customResize)e.customResize(t);else{let e=Math.floor(t.clientWidth/this._hardwareScalingLevel),i=Math.floor(t.clientHeight/this._hardwareScalingLevel),s=e!==t.width||r.width!==t.width||i!==t.height||r.height!==t.height;t.clientWidth&&t.clientHeight&&s&&(t.width=e,t.height=i,this.setSize(e,i))}return!!r.width&&!!r.height&&(this._renderFrame(),this.flushFramebuffer(),e.clearBeforeCopy&&i.clearRect(0,0,r.width,r.height),i.drawImage(r,0,0),o&&(o.activeCameras=a,o.activeCamera=n),uo.notifyObservers(e),!0)},sR.D.prototype._renderViews=function(){let e;if(!this.views||0===this.views.length||!this.getRenderingCanvas())return!1;for(let t of this.views)if(t.enabled){if(t.target===this.inputElement){e=t;continue}if(!this._renderViewStep(t))return!1}return(!e||!!this._renderViewStep(e))&&(this.activeView=null,!0)};var ul=i(9255);function uh(e){if(this._excludedCompressedTextures&&this._excludedCompressedTextures.some(t=>e&&(e===t||e.match(RegExp("\\b"+t+"\\b","g")))))return e;let t=e.lastIndexOf("."),i=e.lastIndexOf("?"),r=i>-1?e.substring(i,e.length):"";return(t>-1?e.substring(0,t):e)+this._textureFormatInUse+r}sK.B.prototype.createStorageBuffer=function(e,t){throw Error("createStorageBuffer: Unsupported method in this engine!")},sK.B.prototype.updateStorageBuffer=function(e,t,i,r){},sK.B.prototype.readFromStorageBuffer=function(e,t,i,r){throw Error("readFromStorageBuffer: Unsupported method in this engine!")},sK.B.prototype.setStorageBuffer=function(e,t){throw Error("setStorageBuffer: Unsupported method in this engine!")},Object.defineProperty(sR.D.prototype,"texturesSupported",{get:function(){let e=[];return this._caps.astc&&e.push("-astc.ktx"),this._caps.s3tc&&e.push("-dxt.ktx"),this._caps.pvrtc&&e.push("-pvrtc.ktx"),this._caps.etc2&&e.push("-etc2.ktx"),this._caps.etc1&&e.push("-etc1.ktx"),e},enumerable:!0,configurable:!0}),Object.defineProperty(sR.D.prototype,"textureFormatInUse",{get:function(){return this._textureFormatInUse||null},enumerable:!0,configurable:!0}),sR.D.prototype.setCompressedTextureExclusions=function(e){this._excludedCompressedTextures=e},sR.D.prototype.setTextureFormatToUse=function(e){let t=this.texturesSupported;for(let i=0,r=t.length;i{this._flush()})}writeUint32(e){this._flushIfNecessary(1),this._uint32s[this._position++]=e}writeInt32(e){this._flushIfNecessary(1),this._int32s[this._position++]=e}writeFloat32(e){this._flushIfNecessary(1),this._float32s[this._position++]=e}writeUint32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._uint32s.set(e,this._position),this._position+=e.length}writeInt32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._int32s.set(e,this._position),this._position+=e.length}writeFloat32Array(e){this._flushIfNecessary(1+e.length),this._uint32s[this._position++]=e.length,this._float32s.set(e,this._position),this._position+=e.length}writeNativeData(e){this._flushIfNecessary(e.length),this._uint32s.set(e,this._position),this._position+=e.length}writeBoolean(e){this.writeUint32(e?1:0)}_flushIfNecessary(e){this._position+e>this._length&&this._flush()}_flush(){this._nativeDataStream.writeBuffer(this._uint32s.buffer,this._position),this._position=0}}uu.DEFAULT_BUFFER_SIZE=65536;let uc=[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))],ud=[()=>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],up=(e,t)=>uc[e]*ud[e](t),u_=[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 uf{constructor(){this.preScaled=!1,this.l00=rf.P.Zero(),this.l1_1=rf.P.Zero(),this.l10=rf.P.Zero(),this.l11=rf.P.Zero(),this.l2_2=rf.P.Zero(),this.l2_1=rf.P.Zero(),this.l20=rf.P.Zero(),this.l21=rf.P.Zero(),this.l22=rf.P.Zero()}addLight(e,t,i){rf.jp.Vector3[0].set(t.r,t.g,t.b);let r=rf.jp.Vector3[0],s=rf.jp.Vector3[1];r.scaleToRef(i,s),s.scaleToRef(up(0,e),rf.jp.Vector3[2]),this.l00.addInPlace(rf.jp.Vector3[2]),s.scaleToRef(up(1,e),rf.jp.Vector3[2]),this.l1_1.addInPlace(rf.jp.Vector3[2]),s.scaleToRef(up(2,e),rf.jp.Vector3[2]),this.l10.addInPlace(rf.jp.Vector3[2]),s.scaleToRef(up(3,e),rf.jp.Vector3[2]),this.l11.addInPlace(rf.jp.Vector3[2]),s.scaleToRef(up(4,e),rf.jp.Vector3[2]),this.l2_2.addInPlace(rf.jp.Vector3[2]),s.scaleToRef(up(5,e),rf.jp.Vector3[2]),this.l2_1.addInPlace(rf.jp.Vector3[2]),s.scaleToRef(up(6,e),rf.jp.Vector3[2]),this.l20.addInPlace(rf.jp.Vector3[2]),s.scaleToRef(up(7,e),rf.jp.Vector3[2]),this.l21.addInPlace(rf.jp.Vector3[2]),s.scaleToRef(up(8,e),rf.jp.Vector3[2]),this.l22.addInPlace(rf.jp.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(u_[0]),this.l1_1.scaleInPlace(u_[1]),this.l10.scaleInPlace(u_[2]),this.l11.scaleInPlace(u_[3]),this.l2_2.scaleInPlace(u_[4]),this.l2_1.scaleInPlace(u_[5]),this.l20.scaleInPlace(u_[6]),this.l21.scaleInPlace(u_[7]),this.l22.scaleInPlace(u_[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(uc[0]),this.l1_1.scaleInPlace(uc[1]),this.l10.scaleInPlace(uc[2]),this.l11.scaleInPlace(uc[3]),this.l2_2.scaleInPlace(uc[4]),this.l2_1.scaleInPlace(uc[5]),this.l20.scaleInPlace(uc[6]),this.l21.scaleInPlace(uc[7]),this.l22.scaleInPlace(uc[8])}updateFromArray(e){return rf.P.FromArrayToRef(e[0],0,this.l00),rf.P.FromArrayToRef(e[1],0,this.l1_1),rf.P.FromArrayToRef(e[2],0,this.l10),rf.P.FromArrayToRef(e[3],0,this.l11),rf.P.FromArrayToRef(e[4],0,this.l2_2),rf.P.FromArrayToRef(e[5],0,this.l2_1),rf.P.FromArrayToRef(e[6],0,this.l20),rf.P.FromArrayToRef(e[7],0,this.l21),rf.P.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return rf.P.FromFloatsToRef(e[0],e[1],e[2],this.l00),rf.P.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),rf.P.FromFloatsToRef(e[6],e[7],e[8],this.l10),rf.P.FromFloatsToRef(e[9],e[10],e[11],this.l11),rf.P.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),rf.P.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),rf.P.FromFloatsToRef(e[18],e[19],e[20],this.l20),rf.P.FromFloatsToRef(e[21],e[22],e[23],this.l21),rf.P.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return new uf().updateFromArray(e)}static FromPolynomial(e){let t=new uf;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 um{constructor(){this.x=rf.P.Zero(),this.y=rf.P.Zero(),this.z=rf.P.Zero(),this.xx=rf.P.Zero(),this.yy=rf.P.Zero(),this.zz=rf.P.Zero(),this.xy=rf.P.Zero(),this.yz=rf.P.Zero(),this.zx=rf.P.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=uf.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){rf.jp.Vector3[0].copyFromFloats(e.r,e.g,e.b);let t=rf.jp.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),rf.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),rf.jp.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(rf.jp.Vector3[0]).addInPlace(rf.jp.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(rf.jp.Vector3[0]).subtractInPlace(rf.jp.Vector3[1]),this.zz.copyFrom(e.l00),rf.jp.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(rf.jp.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 um().updateFromHarmonics(e)}static FromArray(e){let t=new um;return rf.P.FromArrayToRef(e[0],0,t.x),rf.P.FromArrayToRef(e[1],0,t.y),rf.P.FromArrayToRef(e[2],0,t.z),rf.P.FromArrayToRef(e[3],0,t.xx),rf.P.FromArrayToRef(e[4],0,t.yy),rf.P.FromArrayToRef(e[5],0,t.zz),rf.P.FromArrayToRef(e[6],0,t.yz),rf.P.FromArrayToRef(e[7],0,t.zx),rf.P.FromArrayToRef(e[8],0,t.xy),t}}let ug=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`;function uv(e,t,i,r,s,n,a,o){let l=t.getEngine();return t.isReady=!1,s=null!=s?s:t.samplingMode,r=null!=r?r:t.type,n=null!=n?n:t.format,a=null!=a?a:t.width,o=null!=o?o:t.height,-1===r&&(r=0),new Promise(h=>{let u=new nz("postprocess",e,null,null,1,null,s,l,!1,void 0,r,void 0,null,!1,n);u.externalTextureSamplerBinding=!0;let c=l.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:s,type:r,format:n});u.getEffect().executeWhenCompiled(()=>{u.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},i.postProcessManager.directRender([u],c,!0),l.restoreDefaultFramebuffer(),l._releaseTexture(t),u&&u.dispose(),c._swapAndDie(t),t.type=r,t.format=5,t.isReady=!0,h(t)})})}function ux(e){r||(r=new Float32Array(1),s=new Int32Array(r.buffer)),r[0]=e;let t=s[0],i=t>>16&32768,n=t>>12&2047,a=t>>23&255;return a<103?i:a>142?(i|=31744,i|=(255==a?0:1)&&8388607&t):a<113?(n|=2048,i|=(n>>114-a)+(n>>113-a&1)):(i|=a-112<<10|n>>1,i+=1&n)}function uT(e){let t=(32768&e)>>15,i=(31744&e)>>10,r=1023&e;return 0===i?(t?-1:1)*6103515625e-14*(r/1024):31==i?r?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,i-15)*(1+r/1024)}nw.v.ShadersStore.rgbdDecodePixelShader=ug;let uS=async(e,t,i,r,s)=>{let n;let a=e.getScene(),o=a.getEngine();n=e.isCube?new nz("lodCube","lodCube",["lod","gamma"],null,1,null,sj.NEAREST_NEAREST_MIPNEAREST,o,!1,["#define POSITIVEX","#define NEGATIVEX","#define POSITIVEY","#define NEGATIVEY","#define POSITIVEZ","#define NEGATIVEZ"][r]):new nz("lod","lod",["lod","gamma"],null,1,null,sj.NEAREST_NEAREST_MIPNEAREST,o),await new Promise(e=>{n.getEffect().executeWhenCompiled(()=>{e(0)})});let l=new as("temp",{width:t,height:i},a,!1);n.onApply=function(t){t.setTexture("textureSampler",e),t.setFloat("lod",s),t.setBool("gamma",e.gammaSpace)};let h=e.getInternalTexture();try{if(l.renderTarget&&h){let r=h.samplingMode;0!==s?e.updateSamplingMode(sj.NEAREST_NEAREST_MIPNEAREST):e.updateSamplingMode(sj.NEAREST_NEAREST),a.postProcessManager.directRender([n],l.renderTarget,!0),e.updateSamplingMode(r);let u=await o.readPixels(0,0,t,i),c=new Uint8Array(u.buffer,0,u.byteLength);return o.unBindFramebuffer(l.renderTarget),c}throw Error("Render to texture failed.")}finally{l.dispose(),n.dispose()}},uE={CreateResizedCopy:function(e,t,i,r=!0){let s=e.getScene(),n=s.getEngine(),a=new as("resized"+e.name,{width:t,height:i},s,!e.noMipmap,!0,e._texture.type,!1,e.samplingMode,!1);a.wrapU=e.wrapU,a.wrapV=e.wrapV,a.uOffset=e.uOffset,a.vOffset=e.vOffset,a.uScale=e.uScale,a.vScale=e.vScale,a.uAng=e.uAng,a.vAng=e.vAng,a.wAng=e.wAng,a.coordinatesIndex=e.coordinatesIndex,a.level=e.level,a.anisotropicFilteringLevel=e.anisotropicFilteringLevel,a._texture.isReady=!1,e.wrapU=sj.CLAMP_ADDRESSMODE,e.wrapV=sj.CLAMP_ADDRESSMODE;let o=new oa("pass",1,null,r?sj.BILINEAR_SAMPLINGMODE:sj.NEAREST_SAMPLINGMODE,n,!1,0);return o.externalTextureSamplerBinding=!0,o.getEffect().executeWhenCompiled(()=>{o.onApply=function(t){t.setTexture("textureSampler",e)};let t=a.renderTarget;t&&(s.postProcessManager.directRender([o],t),n.unBindFramebuffer(t),a.disposeFramebufferObjects(),o.dispose(),a.getInternalTexture().isReady=!0)}),a},ApplyPostProcess:uv,ToHalfFloat:ux,FromHalfFloat:uT,GetTextureDataAsync:async function(e,t,i,r=0,s=0){return!e.isReady()&&e._texture&&await new Promise((t,i)=>{if(null===e._texture){i(0);return}e._texture.onLoadedObservable.addOnce(()=>{t(0)})}),await uS(e,t,i,r,s)}};class uC{static ExpandRGBDTexture(e){let t=e._texture;if(!t||!e.isRGBD)return;let i=t.getEngine(),r=i.getCaps(),s=t.isReady,n=!1;r.textureHalfFloatRender&&r.textureHalfFloatLinearFiltering?(n=!0,t.type=2):r.textureFloatRender&&r.textureFloatLinearFiltering&&(n=!0,t.type=1),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);let a=()=>{let r=new nz("rgbdDecode","rgbdDecode",null,null,1,null,3,i,!1,void 0,t.type,void 0,null,!1);r.externalTextureSamplerBinding=!0;let s=i.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:5});r.getEffect().executeWhenCompiled(()=>{r.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([r],s,!0),i.restoreDefaultFramebuffer(),i._releaseTexture(t),r&&r.dispose(),s._swapAndDie(t),t.isReady=!0})};n&&(s?a():e.onLoadObservable.addOnce(a))}static EncodeTextureToRGBD(e,t,i=0){return uv("rgbdEncode",e,t,i,1,5)}}class ub{constructor(e,t,i,r){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=i,this.worldAxisForFileY=r}}class uy{static ConvertCubeMapTextureToSphericalPolynomial(e){var t;let i,r;if(!e.isCube)return null;null===(t=e.getScene())||void 0===t||t.getEngine().flushFramebuffer();let s=e.getSize().width,n=e.readPixels(0,void 0,void 0,!1),a=e.readPixels(1,void 0,void 0,!1);e.isRenderTarget?(i=e.readPixels(3,void 0,void 0,!1),r=e.readPixels(2,void 0,void 0,!1)):(i=e.readPixels(2,void 0,void 0,!1),r=e.readPixels(3,void 0,void 0,!1));let o=e.readPixels(4,void 0,void 0,!1),l=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,u=0;return(1==e.textureType||2==e.textureType)&&(u=1),new Promise(e=>{Promise.all([a,n,i,r,o,l]).then(([t,i,r,n,a,o])=>{let l={size:s,right:i,left:t,up:r,down:n,front:a,back:o,format:5,type:u,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(l))})})}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){let t=new uf,i=0,r=2/e.size,s=.5*r,n=s-1;for(let a=0;a<6;a++){let o=this._FileFaces[a],l=e[o.name],h=n,u=5===e.format?4:3;for(let a=0;ag){let t=g/e;_*=t,f*=t,m*=t}}else _=rk.R.Clamp(_,0,g),f=rk.R.Clamp(f,0,g),m=rk.R.Clamp(m,0,g);let v=new rm.Wo(_,f,m);t.addLight(d,v,p),i+=p,c+=r}h+=r}}let a=4*Math.PI*6/6/i;return t.scaleInPlace(a),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),um.FromHarmonics(t)}}uy._FileFaces=[new ub("right",new rf.P(1,0,0),new rf.P(0,0,-1),new rf.P(0,-1,0)),new ub("left",new rf.P(-1,0,0),new rf.P(0,0,1),new rf.P(0,-1,0)),new ub("up",new rf.P(0,1,0),new rf.P(1,0,0),new rf.P(0,0,1)),new ub("down",new rf.P(0,-1,0),new rf.P(1,0,0),new rf.P(0,0,-1)),new ub("front",new rf.P(0,0,1),new rf.P(1,0,0),new rf.P(0,-1,0)),new ub("back",new rf.P(0,0,-1),new rf.P(-1,0,0),new rf.P(0,-1,0))],uy.MAX_HDRI_VALUE=4096,uy.PRESERVE_CLAMPED_COLORS=!1,sV.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(sV.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;this._texture.isReady&&!this._texture._sphericalPolynomialPromise&&(this._texture._sphericalPolynomialPromise=uy.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then(e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});let uA=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`;nw.v.ShadersStore.rgbdEncodePixelShader=uA;let uR="image/png",uP=[134,22,135,150,246,214,150,54];function uI(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),i=0;for(let e=0;e2)throw Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "2".`);return 2===e.version?e:e=Object.assign(Object.assign({},e),{version:2,imageType:uR})}function uD(e,t){let i=(t=uM(t)).specular,r=rk.R.Log2(t.width);if(r=Math.round(r)+1,i.mipmaps.length!==6*r)throw Error(`Unsupported specular mipmaps number "${i.mipmaps.length}"`);let s=Array(r);for(let t=0;t{if(i){let i=t.createTexture(null,!0,!0,null,1,null,e=>{d(e)},e);r.getEffect().executeWhenCompiled(()=>{r.externalTextureSamplerBinding=!0,r.onApply=r=>{r._bindTexture("textureSampler",i),r.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([r],h,!0,n,a),t.restoreDefaultFramebuffer(),i.dispose(),URL.revokeObjectURL(s),c())})}else{if(t._uploadImageToTexture(u,e,n,a),o){let i=l[a];i&&t._uploadImageToTexture(i._texture,e,n,0)}c()}})}function uN(e,t){let i=(t=uM(t)).irradiance;if(!i)return;let r=new um;rf.P.FromArrayToRef(i.x,0,r.x),rf.P.FromArrayToRef(i.y,0,r.y),rf.P.FromArrayToRef(i.z,0,r.z),rf.P.FromArrayToRef(i.xx,0,r.xx),rf.P.FromArrayToRef(i.yy,0,r.yy),rf.P.FromArrayToRef(i.zz,0,r.zz),rf.P.FromArrayToRef(i.yz,0,r.yz),rf.P.FromArrayToRef(i.zx,0,r.zx),rf.P.FromArrayToRef(i.xy,0,r.xy),e._sphericalPolynomial=r}function uF(e,t,i,r){let s=r,n=0,a="";for(;s=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||95==t}function uB(e){let t=0,i="",r=!1,s=[];for(;t=0&&d.push(t.substring(i+1))}"void"!==s&&d.push("return"),this._functionDescr.push({name:n,type:s,parameters:d,body:u,callIndex:0}),e=h+1;let p=t>0?this._sourceCode.substring(0,t):"",_=h+1=0&&this._replaceFunctionCallsByCode(););return this.debug&&rb.Y.Log(`numMaxIterations is ${e} after inlining process`),e>=0}_replaceFunctionCallsByCode(){let e=!1;for(let t of this._functionDescr){let{name:i,type:r,parameters:s,body:n}=t,a=0;for(;a{let t=[],i=0,r=0;for(;i0?this._sourceCode.substring(0,o):"",m=h+1=0&&"\n"!==e.charAt(t)&&(!r||e.charAt(t)!==r);)t--;return t}(this._sourceCode,o-1,0,"{");f=this._sourceCode.substring(0,e+1);let t=this._sourceCode.substring(e+1,o);this._sourceCode=f+r+" "+p+";\n"+_+"\n"+t+p+m,this.debug&&rb.Y.Log(`Replace function call by code. Function '${i}' (type=${r}). injectDeclarationIndex=${e}, call parameters=${d}`)}else this._sourceCode=f+_+m,a+=_.length-(h+1-o),this.debug&&rb.Y.Log(`Replace function call by code. Function '${i}' (type=${r}). functionCallIndex=${o}, call parameters=${d}`);e=!0}}return e}_replaceNames(e,t,i){for(let r=0;r{let o=s[0];return uw(e.charAt(o-1))||uw(e.charAt(o+n))?t[r]:a})}return e}}uU._RegexpFindFunctionNameAndType=/((\s+?)(\w+)\s+(\w+)\s*?)$/;var uV=i(7666);class uk{get isAsync(){return this.isParallelCompiled}get isReady(){if(this.compilationError){let e=this.compilationError.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}return this.isCompiled}_getVertexShaderCode(){return null}_getFragmentShaderCode(){return null}_handlesSpectorRebuildCallback(e){throw Error("Not implemented")}constructor(e){this.isParallelCompiled=!0,this.isCompiled=!1,this._valueCache={},this._engine=e}_fillEffectInformation(e,t,i,r,s,n,a,o){let l;let h=this._engine;if(h.supportsUniformBuffers)for(let i in t)e.bindUniformBlock(i,t[i]);for(this._engine.getUniforms(this,i).forEach((e,t)=>{r[i[t]]=e}),this._uniforms=r,l=0;l{n[e]=t}),o.push(...h.getAttributes(this,a))}dispose(){this._uniforms={}}_cacheMatrix(e,t){let i=this._valueCache[e],r=t.updateFlag;return(void 0===i||i!==r)&&(this._valueCache[e]=r,!0)}_cacheFloat2(e,t,i){let r=this._valueCache[e];if(!r)return r=[t,i],this._valueCache[e]=r,!0;let s=!1;return r[0]!==t&&(r[0]=t,s=!0),r[1]!==i&&(r[1]=i,s=!0),s}_cacheFloat3(e,t,i,r){let s=this._valueCache[e];if(!s)return s=[t,i,r],this._valueCache[e]=s,!0;let n=!1;return s[0]!==t&&(s[0]=t,n=!0),s[1]!==i&&(s[1]=i,n=!0),s[2]!==r&&(s[2]=r,n=!0),n}_cacheFloat4(e,t,i,r,s){let n=this._valueCache[e];if(!n)return n=[t,i,r,s],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==i&&(n[1]=i,a=!0),n[2]!==r&&(n[2]=r,a=!0),n[3]!==s&&(n[3]=s,a=!0),a}setInt(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setInt4(this._uniforms[e],t,i,r,s)&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,i){this._cacheFloat2(e,t,i)&&!this._engine.setUInt2(this._uniforms[e],t,i)&&(this._valueCache[e]=null)}setUInt3(e,t,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setUInt3(this._uniforms[e],t,i,r)&&(this._valueCache[e]=null)}setUInt4(e,t,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setUInt4(this._uniforms[e],t,i,r,s)&&(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)}setFloatArray(e,t){this._valueCache[e]=null,this._engine.setFloatArray(this._uniforms[e],t)}setFloatArray2(e,t){this._valueCache[e]=null,this._engine.setFloatArray2(this._uniforms[e],t)}setFloatArray3(e,t){this._valueCache[e]=null,this._engine.setFloatArray3(this._uniforms[e],t)}setFloatArray4(e,t){this._valueCache[e]=null,this._engine.setFloatArray4(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.toArray())&&(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){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setBool(e,t){let i=this._valueCache[e];(void 0===i||i!==t)&&this._engine.setInt(this._uniforms[e],t?1:0)&&(this._valueCache[e]=t?1:0)}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,i){this._cacheFloat2(e,t,i)&&!this._engine.setFloat2(this._uniforms[e],t,i)&&(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,i,r){this._cacheFloat3(e,t,i,r)&&!this._engine.setFloat3(this._uniforms[e],t,i,r)&&(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,i,r,s){this._cacheFloat4(e,t,i,r,s)&&!this._engine.setFloat4(this._uniforms[e],t,i,r,s)&&(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,i){this._cacheFloat4(e,t.r,t.g,t.b,i)&&!this._engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,i)&&(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)}}class uG extends nU{get _framebuffer(){return this.__framebuffer}set _framebuffer(e){this.__framebuffer&&this._engine._releaseFramebufferObjects(this.__framebuffer),this.__framebuffer=e}get _framebufferDepthStencil(){return this.__framebufferDepthStencil}set _framebufferDepthStencil(e){this.__framebufferDepthStencil&&this._engine._releaseFramebufferObjects(this.__framebufferDepthStencil),this.__framebufferDepthStencil=e}constructor(e,t,i,r){super(e,t,i,r),this.__framebuffer=null,this.__framebufferDepthStencil=null,this._engine=r}dispose(e=!1){this._framebuffer=null,this._framebufferDepthStencil=null,super.dispose(e)}}class uz{get underlyingResource(){return this._nativeTexture}constructor(e,t){this._engine=t,this.set(e)}setUsage(){}set(e){this._nativeTexture=e}reset(){this._nativeTexture=null}release(){this._nativeTexture&&this._engine.deleteTexture(this._nativeTexture),this.reset()}}function uW(e,t){switch(e){case 15:return _native.Engine.TEXTURE_FORMAT_D16;case 16:return _native.Engine.TEXTURE_FORMAT_D24;case 13:return _native.Engine.TEXTURE_FORMAT_D24S8;case 14:return _native.Engine.TEXTURE_FORMAT_D32F;case 36492:return _native.Engine.TEXTURE_FORMAT_BC7;case 36494:return _native.Engine.TEXTURE_FORMAT_BC6H;case 33779:return _native.Engine.TEXTURE_FORMAT_BC3;case 33778:return _native.Engine.TEXTURE_FORMAT_BC2;case 33777:case 33776:return _native.Engine.TEXTURE_FORMAT_BC1;case 37808:return _native.Engine.TEXTURE_FORMAT_ASTC4x4;case 36196:return _native.Engine.TEXTURE_FORMAT_ETC1;case 37492:return _native.Engine.TEXTURE_FORMAT_ETC2;case 37496:return _native.Engine.TEXTURE_FORMAT_ETC2A;case 4:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGB8;case 3:return _native.Engine.TEXTURE_FORMAT_RGB8S;case 6:return _native.Engine.TEXTURE_FORMAT_RGB8I;case 7:return _native.Engine.TEXTURE_FORMAT_RGB8U}break;case 5:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RGBA8;case 1:return _native.Engine.TEXTURE_FORMAT_RGBA32F;case 2:return _native.Engine.TEXTURE_FORMAT_RGBA16F;case 3:return _native.Engine.TEXTURE_FORMAT_RGBA8S;case 4:return _native.Engine.TEXTURE_FORMAT_RGBA16I;case 5:return _native.Engine.TEXTURE_FORMAT_RGBA16U;case 6:return _native.Engine.TEXTURE_FORMAT_RGBA32I;case 7:return _native.Engine.TEXTURE_FORMAT_RGBA32U}break;case 6:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_R8;case 1:return _native.Engine.TEXTURE_FORMAT_R32F;case 2:return _native.Engine.TEXTURE_FORMAT_R16F;case 3:return _native.Engine.TEXTURE_FORMAT_R8S;case 4:return _native.Engine.TEXTURE_FORMAT_R16S;case 5:return _native.Engine.TEXTURE_FORMAT_R16U;case 6:return _native.Engine.TEXTURE_FORMAT_R32I;case 7:return _native.Engine.TEXTURE_FORMAT_R32U}break;case 7:switch(t){case 0:return _native.Engine.TEXTURE_FORMAT_RG8;case 1:return _native.Engine.TEXTURE_FORMAT_RG32F;case 2:return _native.Engine.TEXTURE_FORMAT_RG16F;case 3:return _native.Engine.TEXTURE_FORMAT_RG8S;case 4:return _native.Engine.TEXTURE_FORMAT_RG16S;case 5:return _native.Engine.TEXTURE_FORMAT_RG16U;case 6:return _native.Engine.TEXTURE_FORMAT_RG32I;case 7:return _native.Engine.TEXTURE_FORMAT_RG32U}break;case 12:if(0===t)return _native.Engine.TEXTURE_FORMAT_BGRA8}throw new nl.LH(`Unsupported texture format or type: format ${e}, type ${t}.`,nl.SM.UnsupportedTextureError)}function uH(e){switch(e){case 1:return _native.Engine.TEXTURE_NEAREST_NEAREST;case 2:return _native.Engine.TEXTURE_LINEAR_LINEAR;case 3:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR;case 4:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;case 5:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;case 6:return _native.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;case 7:return _native.Engine.TEXTURE_NEAREST_LINEAR;case 8:return _native.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR;case 9:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;case 10:return _native.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;case 11:return _native.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST;case 12:return _native.Engine.TEXTURE_LINEAR_NEAREST;default:throw Error(`Unsupported sampling mode: ${e}.`)}}function uX(e){switch(e){case 1:return _native.Engine.ADDRESS_MODE_WRAP;case 0:return _native.Engine.ADDRESS_MODE_CLAMP;case 2:return _native.Engine.ADDRESS_MODE_MIRROR;default:throw Error("Unexpected wrap mode: "+e+".")}}let uY=new r_.y$;if("undefined"!=typeof self&&!Object.prototype.hasOwnProperty.call(self,"_native")){let e;Object.defineProperty(self,"_native",{get:()=>e,set:t=>{(e=t)&&uY.notifyObservers(e)}})}async function uj(e,t){(await new Promise(e=>{"undefined"==typeof _native?uY.addOnce(t=>e(t)):e(_native)}))[e]=t}class uq extends aS.h{}class uK{constructor(e){this._engine=e,this._pending=[],this._isCommandBufferScopeActive=!1,this._commandStream=u$._createNativeDataStream(),this._engine.setCommandDataStream(this._commandStream)}beginCommandScope(){if(this._isCommandBufferScopeActive)throw Error("Command scope already active.");this._isCommandBufferScopeActive=!0}endCommandScope(){if(!this._isCommandBufferScopeActive)throw Error("Command scope is not active.");this._isCommandBufferScopeActive=!1,this._submit()}startEncodingCommand(e){this._commandStream.writeNativeData(e)}encodeCommandArgAsUInt32(e){this._commandStream.writeUint32(e)}encodeCommandArgAsUInt32s(e){this._commandStream.writeUint32Array(e)}encodeCommandArgAsInt32(e){this._commandStream.writeInt32(e)}encodeCommandArgAsInt32s(e){this._commandStream.writeInt32Array(e)}encodeCommandArgAsFloat32(e){this._commandStream.writeFloat32(e)}encodeCommandArgAsFloat32s(e){this._commandStream.writeFloat32Array(e)}encodeCommandArgAsNativeData(e){this._commandStream.writeNativeData(e),this._pending.push(e)}finishEncodingCommand(){this._isCommandBufferScopeActive||this._submit()}_submit(){this._engine.submitCommands(),this._pending.length=0}}class u$ extends sR.D{setHardwareScalingLevel(e){super.setHardwareScalingLevel(e),this._engine.setHardwareScalingLevel(e)}constructor(e={}){if(super(null,!1,void 0,e.adaptToDeviceRatio),this._engine=new _native.Engine,this._camera=_native.Camera?new _native.Camera:null,this._commandBufferEncoder=new uK(this._engine),this._boundBuffersVertexArray=null,this._currentDepthTest=_native.Engine.DEPTH_TEST_LEQUAL,this._stencilTest=!1,this._stencilMask=255,this._stencilFunc=519,this._stencilFuncRef=0,this._stencilFuncMask=255,this._stencilOpStencilFail=7680,this._stencilOpDepthFail=7680,this._stencilOpStencilDepthPass=7681,this._zOffset=0,this._zOffsetUnits=0,this._depthWrite=!0,_native.Engine.PROTOCOL_VERSION!==u$.PROTOCOL_VERSION)throw Error(`Protocol version mismatch: ${_native.Engine.PROTOCOL_VERSION} (Native) !== ${u$.PROTOCOL_VERSION} (JS)`);this._webGLVersion=2,this.disableUniformBuffers=!0,this._shaderPlatformName="NATIVE",this._caps={maxTexturesImageUnits:16,maxVertexTextureImageUnits:16,maxCombinedTexturesImageUnits:32,maxTextureSize:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_SIZE,maxCubemapTextureSize:512,maxRenderTextureSize:512,maxVertexAttribs:16,maxVaryingVectors:16,maxFragmentUniformVectors:16,maxVertexUniformVectors:16,standardDerivatives:!0,astc:null,pvrtc:null,etc1:null,etc2:null,bptc:null,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!1,highPrecisionShaderSupported:!0,colorBufferFloat:!1,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,textureFloat:!0,textureFloatLinearFiltering:!1,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!1,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!1,drawBuffersExtension:!1,depthTextureExtension:!1,vertexArrayObject:!0,instancedArrays:!0,supportOcclusionQuery:!1,canUseTimestampForTimerQuery:!1,blendMinMax:!1,maxMSAASamples:16,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!1,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!1,texture2DArrayMaxLayerCount:_native.Engine.CAPS_LIMITS_MAX_TEXTURE_LAYERS,disableMorphTargetTexture:!1},this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!1,supportDepthStencilTexture:!1,supportShadowSamplers:!1,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!1,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:!1,basisNeedsPOT:!1,support3DTextures:!1,needTypeSuffixInShaderConstants:!1,supportMSAA:!0,supportSSAO2:!1,supportExtendedTextureFormats:!1,supportSwitchCaseInShader:!1,supportSyncTextureRead:!1,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!0,supportSpriteInstancing:!1,forceVertexBufferStrideMultiple4Bytes:!1,_collectUbosUpdatedInFrame:!1},sg.w1.Log("Babylon Native (v"+sR.D.Version+") launched"),sg.w1.LoadScript=function(e,t,i,r){sg.w1.LoadFile(e,e=>{Function(e).apply(null),t&&t()},void 0,void 0,!1,(e,t)=>{i&&i("LoadScript Error",t)})},"undefined"==typeof URL&&(window.URL={createObjectURL:function(){},revokeObjectURL:function(){}}),"undefined"==typeof Blob&&(window.Blob=function(e){return e}),Array.prototype.flat||Object.defineProperty(Array.prototype,"flat",{configurable:!0,value:function e(){let t=isNaN(arguments[0])?1:Number(arguments[0]);return t?Array.prototype.reduce.call(this,function(i,r){return Array.isArray(r)?i.push.apply(i,e.call(r,t-1)):i.push(r),i},[]):Array.prototype.slice.call(this)},writable:!0});let t=window&&window.devicePixelRatio||1;this._hardwareScalingLevel=e.adaptToDeviceRatio?1/t:1,this._engine.setHardwareScalingLevel(this._hardwareScalingLevel),this._lastDevicePixelRatio=t,this.resize();let i=this.getDepthFunction();i&&this.setDepthFunction(i),this._shaderProcessor=new uV.C,this.onNewSceneAddedObservable.add(e=>{let t=e.render;e.render=(...i)=>{this._commandBufferEncoder.beginCommandScope(),t.apply(e,i),this._commandBufferEncoder.endCommandScope()}})}dispose(){super.dispose(),this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._engine.dispose()}static _createNativeDataStream(){return new uu}_queueNewFrame(e,t){return t.requestAnimationFrame&&t!==window?t.requestAnimationFrame(e):this._engine.requestAnimationFrame(e),0}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._currentFramebuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_UNBINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(this._currentFramebuffer),this._commandBufferEncoder.finishEncodingCommand()),e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()),this._currentFramebuffer=e)}getHostDocument(){return null}clear(e,t,i,r=!1){if(this.useReverseDepthBuffer)throw Error("reverse depth buffer is not currently implemented");this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_CLEAR),this._commandBufferEncoder.encodeCommandArgAsUInt32(t&&e?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.r:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.g:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.b:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(e?e.a:1),this._commandBufferEncoder.encodeCommandArgAsUInt32(i?1:0),this._commandBufferEncoder.encodeCommandArgAsFloat32(1),this._commandBufferEncoder.encodeCommandArgAsUInt32(r?1:0),this._commandBufferEncoder.encodeCommandArgAsUInt32(0),this._commandBufferEncoder.finishEncodingCommand()}createIndexBuffer(e,t,i){let r=this._normalizeIndexData(e),s=new uq;return s.references=1,s.is32Bits=4===r.BYTES_PER_ELEMENT,r.byteLength&&(s.nativeIndexBuffer=this._engine.createIndexBuffer(r.buffer,r.byteOffset,r.byteLength,s.is32Bits,null!=t&&t)),s}createVertexBuffer(e,t,i){let r=ArrayBuffer.isView(e)?e:new Float32Array(e),s=new uq;return s.references=1,r.byteLength&&(s.nativeVertexBuffer=this._engine.createVertexBuffer(r.buffer,r.byteOffset,r.byteLength,null!=t&&t)),s}_recordVertexArrayObject(e,t,i,r,s){i&&this._engine.recordIndexBuffer(e,i.nativeIndexBuffer);let n=r.getAttributesNames();for(let i=0;i=0){let r=n[i],o=null;if(s&&(o=s[r]),o||(o=t[r]),o){let t=o.getBuffer();t&&t.nativeVertexBuffer&&this._engine.recordVertexBuffer(e,t.nativeVertexBuffer,a,o.byteOffset,o.byteStride,o.getSize(),function(e){switch(e){case sm.o.BYTE:return _native.Engine.ATTRIB_TYPE_INT8;case sm.o.UNSIGNED_BYTE:return _native.Engine.ATTRIB_TYPE_UINT8;case sm.o.SHORT:return _native.Engine.ATTRIB_TYPE_INT16;case sm.o.UNSIGNED_SHORT:return _native.Engine.ATTRIB_TYPE_UINT16;case sm.o.FLOAT:return _native.Engine.ATTRIB_TYPE_FLOAT;default:throw Error(`Unsupported attribute type: ${e}.`)}}(o.type),o.normalized,o.getInstanceDivisor())}}}}bindBuffers(e,t,i){this._boundBuffersVertexArray&&this._deleteVertexArray(this._boundBuffersVertexArray),this._boundBuffersVertexArray=this._engine.createVertexArray(),this._recordVertexArrayObject(this._boundBuffersVertexArray,e,t,i),this.bindVertexArrayObject(this._boundBuffersVertexArray)}recordVertexArrayObject(e,t,i,r){let s=this._engine.createVertexArray();return this._recordVertexArrayObject(s,e,t,i,r),s}_deleteVertexArray(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}bindVertexArrayObject(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_BINDVERTEXARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand()}releaseVertexArrayObject(e){this._deleteVertexArray(e)}getAttributes(e,t){return this._engine.getAttributes(e.nativeProgram,t)}drawElementsType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINDEXEDINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXEDINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINDEXED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}drawArraysType(e,t,i,r){this._drawCalls.addCount(1,!1),r&&_native.Engine.COMMAND_DRAWINSTANCED?(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAWINSTANCED),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r)):(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DRAW),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i)),this._commandBufferEncoder.finishEncodingCommand()}createPipelineContext(){return new uk(this)}createMaterialContext(){}createDrawContext(){}_preparePipelineContext(e,t,i,r,s,n,a,o){r?e.nativeProgram=this.createRawShaderProgram():e.nativeProgram=this.createShaderProgram(e,t,i,o)}isAsync(e){return!!(e.isAsync&&this._engine.createProgramAsync)}_executeWhenRenderingStateIsCompiled(e,t){if(!this.isAsync(e)){t();return}let i=e.onCompiled;i?e.onCompiled=()=>{i(),t()}:e.onCompiled=t}createRawShaderProgram(){throw Error("Not Supported")}createShaderProgram(e,t,i,r){if(e.nativeProgram)throw Error("Tried to create a second program in the same NativePipelineContext");this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=new uU(t);s.processCode(),t=s.code;let n=new uU(i);n.processCode(),i=n.code,t=sK.B._ConcatenateShader(t,r),i=sK.B._ConcatenateShader(i,r);let a=()=>{var t;e.isCompiled=!0,null===(t=e.onCompiled)||void 0===t||t.call(e),this.onAfterShaderCompilationObservable.notifyObservers(this)};if(this.isAsync(e))return this._engine.createProgramAsync(t,i,a,t=>{e.compilationError=t});try{let r=e.nativeProgram=this._engine.createProgram(t,i);return a(),r}catch(t){let e=null==t?void 0:t.message;throw Error("SHADER ERROR"+("string"==typeof e?"\n"+e:""))}}inlineShaderCode(e){let t=new uU(e);return t.debug=!1,t.processCode(),t.code}_setProgram(e){this._currentProgram!==e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand(),this._currentProgram=e)}_deletePipelineContext(e){e&&e.nativeProgram&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEPROGRAM),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeProgram),this._commandBufferEncoder.finishEncodingCommand())}getUniforms(e,t){return this._engine.getUniforms(e.nativeProgram,t)}bindUniformBlock(e,t,i){throw Error("Not Implemented")}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.nativeProgram);let i=e.getSamplers();for(let t=0;t{}}}setZOffset(e){e!==this._zOffset&&(this._zOffset=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSET),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffset(){return this._zOffset}setZOffsetUnits(e){e!==this._zOffsetUnits&&(this._zOffsetUnits=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETZOFFSETUNITS),this._commandBufferEncoder.encodeCommandArgAsFloat32(this.useReverseDepthBuffer?-e:e),this._commandBufferEncoder.finishEncodingCommand())}getZOffsetUnits(){return this._zOffsetUnits}setDepthBuffer(e){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(e?this._currentDepthTest:_native.Engine.DEPTH_TEST_ALWAYS),this._commandBufferEncoder.finishEncodingCommand()}getDepthWrite(){return this._depthWrite}getDepthFunction(){switch(this._currentDepthTest){case _native.Engine.DEPTH_TEST_NEVER:return 512;case _native.Engine.DEPTH_TEST_ALWAYS:return 519;case _native.Engine.DEPTH_TEST_GREATER:return 516;case _native.Engine.DEPTH_TEST_GEQUAL:return 518;case _native.Engine.DEPTH_TEST_NOTEQUAL:return 517;case _native.Engine.DEPTH_TEST_EQUAL:return 514;case _native.Engine.DEPTH_TEST_LESS:return 513;case _native.Engine.DEPTH_TEST_LEQUAL:return 515}return null}setDepthFunction(e){let t=0;switch(e){case 512:t=_native.Engine.DEPTH_TEST_NEVER;break;case 519:t=_native.Engine.DEPTH_TEST_ALWAYS;break;case 516:t=_native.Engine.DEPTH_TEST_GREATER;break;case 518:t=_native.Engine.DEPTH_TEST_GEQUAL;break;case 517:t=_native.Engine.DEPTH_TEST_NOTEQUAL;break;case 514:t=_native.Engine.DEPTH_TEST_EQUAL;break;case 513:t=_native.Engine.DEPTH_TEST_LESS;break;case 515:t=_native.Engine.DEPTH_TEST_LEQUAL}this._currentDepthTest=t,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHTEST),this._commandBufferEncoder.encodeCommandArgAsUInt32(this._currentDepthTest),this._commandBufferEncoder.finishEncodingCommand()}setDepthWrite(e){this._depthWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETDEPTHWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}setColorWrite(e){this._colorWrite=e,this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETCOLORWRITE),this._commandBufferEncoder.encodeCommandArgAsUInt32(Number(e)),this._commandBufferEncoder.finishEncodingCommand()}getColorWrite(){return this._colorWrite}applyStencil(){this._setStencil(this._stencilMask,function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_S_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_S_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_S_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_S_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_S_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_S_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_S_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_S_DECRSAT;default:throw Error(`Unsupported stencil OpFail mode: ${e}.`)}}(this._stencilOpStencilFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_FAIL_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_FAIL_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_FAIL_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_FAIL_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_FAIL_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_FAIL_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_FAIL_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_FAIL_Z_DECRSAT;default:throw Error(`Unsupported stencil depthFail mode: ${e}.`)}}(this._stencilOpDepthFail),function(e){switch(e){case 7680:return _native.Engine.STENCIL_OP_PASS_Z_KEEP;case 0:return _native.Engine.STENCIL_OP_PASS_Z_ZERO;case 7681:return _native.Engine.STENCIL_OP_PASS_Z_REPLACE;case 7682:return _native.Engine.STENCIL_OP_PASS_Z_INCR;case 7683:return _native.Engine.STENCIL_OP_PASS_Z_DECR;case 5386:return _native.Engine.STENCIL_OP_PASS_Z_INVERT;case 34055:return _native.Engine.STENCIL_OP_PASS_Z_INCRSAT;case 34056:return _native.Engine.STENCIL_OP_PASS_Z_DECRSAT;default:throw Error(`Unsupported stencil opPass mode: ${e}.`)}}(this._stencilOpStencilDepthPass),function(e){switch(e){case 513:return _native.Engine.STENCIL_TEST_LESS;case 515:return _native.Engine.STENCIL_TEST_LEQUAL;case 514:return _native.Engine.STENCIL_TEST_EQUAL;case 518:return _native.Engine.STENCIL_TEST_GEQUAL;case 516:return _native.Engine.STENCIL_TEST_GREATER;case 517:return _native.Engine.STENCIL_TEST_NOTEQUAL;case 512:return _native.Engine.STENCIL_TEST_NEVER;case 519:return _native.Engine.STENCIL_TEST_ALWAYS;default:throw Error(`Unsupported stencil func mode: ${e}.`)}}(this._stencilFunc),this._stencilFuncRef)}_setStencil(e,t,i,r,s,n){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETSTENCIL),this._commandBufferEncoder.encodeCommandArgAsUInt32(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.encodeCommandArgAsUInt32(s),this._commandBufferEncoder.encodeCommandArgAsUInt32(n),this._commandBufferEncoder.finishEncodingCommand()}setStencilBuffer(e){this._stencilTest=e,e?this.applyStencil():this._setStencil(255,_native.Engine.STENCIL_OP_FAIL_S_KEEP,_native.Engine.STENCIL_OP_FAIL_Z_KEEP,_native.Engine.STENCIL_OP_PASS_Z_KEEP,_native.Engine.STENCIL_TEST_ALWAYS,0)}getStencilBuffer(){return this._stencilTest}getStencilOperationPass(){return this._stencilOpStencilDepthPass}setStencilOperationPass(e){this._stencilOpStencilDepthPass=e,this.applyStencil()}setStencilMask(e){this._stencilMask=e,this.applyStencil()}setStencilFunction(e){this._stencilFunc=e,this.applyStencil()}setStencilFunctionReference(e){this._stencilFuncRef=e,this.applyStencil()}setStencilFunctionMask(e){this._stencilFuncMask=e}setStencilOperationFail(e){this._stencilOpStencilFail=e,this.applyStencil()}setStencilOperationDepthFail(e){this._stencilOpDepthFail=e,this.applyStencil()}getStencilMask(){return this._stencilMask}getStencilFunction(){return this._stencilFunc}getStencilFunctionReference(){return this._stencilFuncRef}getStencilFunctionMask(){return this._stencilFuncMask}getStencilOperationFail(){return this._stencilOpStencilFail}getStencilOperationDepthFail(){return this._stencilOpDepthFail}setAlphaConstants(e,t,i,r){throw Error("Setting alpha blend constant color not yet implemented.")}setAlphaMode(e,t=!1){if(this._alphaMode===e)return;let i=function(e){switch(e){case 0:return _native.Engine.ALPHA_DISABLE;case 1:return _native.Engine.ALPHA_ADD;case 2:return _native.Engine.ALPHA_COMBINE;case 3:return _native.Engine.ALPHA_SUBTRACT;case 4:return _native.Engine.ALPHA_MULTIPLY;case 5:return _native.Engine.ALPHA_MAXIMIZED;case 6:return _native.Engine.ALPHA_ONEONE;case 7:return _native.Engine.ALPHA_PREMULTIPLIED;case 8:return _native.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;case 9:return _native.Engine.ALPHA_INTERPOLATE;case 10:return _native.Engine.ALPHA_SCREENMODE;default:throw Error(`Unsupported alpha mode: ${e}.`)}}(e);this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETBLENDMODE),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t||this.setDepthWrite(0===e),this._alphaMode=e}getAlphaMode(){return this._alphaMode}setInt(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setIntArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETINTARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsInt32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloatArray4(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOATARRAY4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setArray(e,t){return!!e&&this.setFloatArray(e,new Float32Array(t))}setArray2(e,t){return!!e&&this.setFloatArray2(e,new Float32Array(t))}setArray3(e,t){return!!e&&this.setFloatArray3(e,new Float32Array(t))}setArray4(e,t){return!!e&&this.setFloatArray4(e,new Float32Array(t))}setMatrices(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRICES),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix3x3(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX3X3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setMatrix2x2(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETMATRIX2X2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32s(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat(e,t){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat2(e,t,i){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT2),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat3(e,t,i,r){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT3),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.finishEncodingCommand(),!0)}setFloat4(e,t,i,r,s){return!!e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETFLOAT4),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsFloat32(t),this._commandBufferEncoder.encodeCommandArgAsFloat32(i),this._commandBufferEncoder.encodeCommandArgAsFloat32(r),this._commandBufferEncoder.encodeCommandArgAsFloat32(s),this._commandBufferEncoder.finishEncodingCommand(),!0)}setColor3(e,t){return!!e&&(this.setFloat3(e,t.r,t.g,t.b),!0)}setColor4(e,t,i){return!!e&&(this.setFloat4(e,t.r,t.g,t.b,i),!0)}wipeCaches(e){this.preventCacheWipeBetweenFrames||(this.resetTextureCache(),this._currentEffect=null,e&&(this._currentProgram=null,this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._alphaState.reset()),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null)}_createTexture(){return this._engine.createTexture()}_deleteTexture(e){e&&this._engine.deleteTexture(e)}updateDynamicTexture(e,t,i,r=!1,s){if(void 0===r&&(r=!1),e&&e._hardwareTexture){let i=t.getCanvasTexture(),r=e._hardwareTexture.underlyingResource;this._engine.copyTexture(r,i),e.isReady=!0}}createDynamicTexture(e,t,i,r){return e=Math.max(e,1),t=Math.max(t,1),this.createRawTexture(new Uint8Array(e*t*4),e,t,5,!1,!1,r)}createVideoElement(e){return this._camera?this._camera.createVideo(e):null}updateVideoTexture(e,t,i){if(e&&e._hardwareTexture&&this._camera){let r=e._hardwareTexture.underlyingResource;this._camera.updateVideoTexture(r,t,i)}}createRawTexture(e,t,i,r,s,n,a,o=null,l=0,h=0,u=!1){let c=new sq.l(this,sq.S.Raw);if(c.format=r,c.generateMipMaps=s,c.samplingMode=a,c.invertY=n,c.baseWidth=t,c.baseHeight=i,c.width=c.baseWidth,c.height=c.baseHeight,c._compression=o,c.type=l,c._useSRGBBuffer=this._getUseSRGBBuffer(u,!s),this.updateRawTexture(c,e,r,n,o,l,c._useSRGBBuffer),c._hardwareTexture){let e=c._hardwareTexture.underlyingResource,t=uH(a);this._setTextureSampling(e,t)}return this._internalTexturesCache.push(c),c}createRawTexture2DArray(e,t,i,r,s,n,a,o,l=null,h=0){let u=new sq.l(this,sq.S.Raw2DArray);if(u.baseWidth=t,u.baseHeight=i,u.baseDepth=r,u.width=t,u.height=i,u.depth=r,u.format=s,u.type=h,u.generateMipMaps=n,u.samplingMode=o,u.is2DArray=!0,u._hardwareTexture){let l=u._hardwareTexture.underlyingResource;this._engine.loadRawTexture2DArray(l,e,t,i,r,uW(s,h),n,a);let c=uH(o);this._setTextureSampling(l,c)}return u.isReady=!0,this._internalTexturesCache.push(u),u}updateRawTexture(e,t,i,r,s=null,n=0,a=!1){if(e){if(t&&e._hardwareTexture){let r=e._hardwareTexture.underlyingResource;this._engine.loadRawTexture(r,t,e.width,e.height,uW(i,n),e.generateMipMaps,e.invertY)}e.isReady=!0}}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_=!1){let f="data:"===(e=e||"").substr(0,5),m=f&&-1!==e.indexOf(";base64,"),g=l||new sq.l(this,sq.S.Url),v=e;!this._transformTextureUrl||m||l||o||(e=this._transformTextureUrl(e));let x=e.lastIndexOf("."),T=u||(x>-1?e.substring(x).toLowerCase():""),S=null;for(let e of sR.D._TextureLoaders)if(e.canLoad(T)){S=e;break}r&&r.addPendingData(g),g.url=e,g.generateMipMaps=!t,g.samplingMode=s,g.invertY=i,g._useSRGBBuffer=this._getUseSRGBBuffer(_,t),this.doNotHandleContextLost||(g._buffer=o);let E=null;n&&!l&&(E=g.onLoadedObservable.add(n)),l||this._internalTexturesCache.push(g);let C=(i,l)=>{r&&r.removePendingData(g),e===v?(E&&g.onLoadedObservable.remove(E),rL.l.UseFallbackTexture&&this.createTexture(rL.l.FallbackTexture,t,g.invertY,r,s,null,a,o,g),a&&a((i||"Unknown error")+(rL.l.UseFallbackTexture?" - Fallback texture was used":""),l)):(rb.Y.Warn(`Failed to load ${e}, falling back to ${v}`),this.createTexture(v,t,g.invertY,r,s,n,a,o,g,h,u,c,d))};if(S)throw Error("Loading textures from IInternalTextureLoader not yet implemented.");{let n=e=>{if(!g._hardwareTexture){r&&r.removePendingData(g);return}let n=g._hardwareTexture.underlyingResource;this._engine.loadTexture(n,e,!t,i,g._useSRGBBuffer,()=>{g.baseWidth=this._engine.getTextureWidth(n),g.baseHeight=this._engine.getTextureHeight(n),g.width=g.baseWidth,g.height=g.baseHeight,g.isReady=!0;let e=uH(s);this._setTextureSampling(n,e),r&&r.removePendingData(g),g.onLoadedObservable.notifyObservers(g),g.onLoadedObservable.clear()},()=>{throw Error("Could not load a native texture.")})};if(f&&o){if(o instanceof ArrayBuffer)n(new Uint8Array(o));else if(ArrayBuffer.isView(o))n(o);else if("string"==typeof o)n(new Uint8Array(sg.w1.DecodeBase64(o)));else throw Error("Unsupported buffer type")}else m?n(new Uint8Array(sg.w1.DecodeBase64(e))):this._loadFile(e,e=>n(new Uint8Array(e)),void 0,void 0,!0,(e,t)=>{C("Unable to load "+(e&&e.responseURL,t))})}return g}wrapNativeTexture(e,t=!1,i=3){let r=new uz(e,this._engine),s=new sq.l(this,sq.S.Unknown,!0);return s._hardwareTexture=r,s.baseWidth=this._engine.getTextureWidth(e),s.baseHeight=this._engine.getTextureHeight(e),s.width=s.baseWidth,s.height=s.baseHeight,s.isReady=!0,s.useMipMaps=t,this.updateTextureSamplingMode(i,s),s}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapNativeTexture instead.")}_createDepthStencilTexture(e,t,i){var r,s;let n=t.generateStencil||!1,a=t.samples||1,o=new sq.l(this,sq.S.DepthStencil),l=null!==(r=e.width)&&void 0!==r?r:e,h=null!==(s=e.height)&&void 0!==s?s:e,u=this._engine.createFrameBuffer(o._hardwareTexture.underlyingResource,l,h,n,!0,a);return i._framebufferDepthStencil=u,o}_releaseFramebufferObjects(e){e&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEFRAMEBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.finishEncodingCommand())}_createImageBitmapFromSource(e,t){return new Promise((t,i)=>{let r=this.createCanvasImage();r.onload=()=>{try{let e=this._engine.createImageBitmap(r);t(e)}catch(e){i(`Error loading image ${r.src} with exception: ${e}`)}},r.onerror=e=>{i(`Error loading image ${r.src} with exception: ${e}`)},r.src=e})}createImageBitmap(e,t){return new Promise((t,i)=>{if(Array.isArray(e)&&e.length){let i=this._engine.createImageBitmap(e[0]);if(i){t(i);return}}i("Unsupported data for createImageBitmap.")})}resizeImageBitmap(e,t,i){return this._engine.resizeImageBitmap(e,t,i)}createCubeTexture(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d,p=!1){let _=c||new sq.l(this,sq.S.Cube);_.isCube=!0,_.url=e,_.generateMipMaps=!r,_._lodGenerationScale=h,_._lodGenerationOffset=u,_._useSRGBBuffer=this._getUseSRGBBuffer(p,!!r),this._doNotHandleContextLost||(_._extension=o,_._files=i);let f=e.lastIndexOf(".");if(".env"===(o||(f>-1?e.substring(f).toLowerCase():""))){let t=e=>{let t=uI(e);_.width=t.width,_.height=t.width,uN(_,t);let i=t.specular;if(!i)throw Error("Nothing else parsed so far");_._lodGenerationScale=i.lodGenerationScale;let r=uD(e,t);_.format=5,_.type=0,_.generateMipMaps=!0,_.getEngine().updateTextureSamplingMode(sj.TRILINEAR_SAMPLINGMODE,_),_._isRGBD=!0,_.invertY=!0,this._engine.loadCubeTextureWithMips(_._hardwareTexture.underlyingResource,r,!1,_._useSRGBBuffer,()=>{_.isReady=!0,s&&s()},()=>{throw Error("Could not load a native cube texture.")})};if(i&&6===i.length)throw Error("Multi-file loading not allowed on env files.");this._loadFile(e,e=>{t(new Uint8Array(e,0,e.byteLength))},void 0,void 0,!0,(e,t)=>{n&&e&&n(e.status+" "+e.statusText,t)})}else{if(!i||6!==i.length)throw Error("Cannot load cubemap because 6 files were not defined");Promise.all([i[0],i[3],i[1],i[4],i[2],i[5]].map(e=>this._loadFileAsync(e,void 0,!0).then(e=>new Uint8Array(e,0,e.byteLength)))).then(e=>new Promise((t,i)=>{this._engine.loadCubeTexture(_._hardwareTexture.underlyingResource,e,!r,!0,_._useSRGBBuffer,t,i)})).then(()=>{_.isReady=!0,s&&s()},e=>{n&&n(`Failed to load cubemap: ${e.message}`,e)})}return this._internalTexturesCache.push(_),_}_createHardwareTexture(){return new uz(this._createTexture(),this._engine)}_createHardwareRenderTargetWrapper(e,t,i){let r=new uG(e,t,i,this);return this._renderTargetWrapperCache.push(r),r}_createInternalTexture(e,t,i=!0,r=sq.S.Unknown){var s,n,a;let o;let l=!1,h=0,u=3,c=5,d=!1,p=1;void 0!==t&&"object"==typeof t?(l=!!t.generateMipMaps,h=void 0===t.type?0:t.type,u=void 0===t.samplingMode?3:t.samplingMode,c=void 0===t.format?5:t.format,d=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,p=null!==(s=t.samples)&&void 0!==s?s:1,o=t.label):l=!!t,d=this._getUseSRGBBuffer(d,!l),(1!==h||this._caps.textureFloatLinearFiltering)&&(2!==h||this._caps.textureHalfFloatLinearFiltering)||(u=1),1!==h||this._caps.textureFloat||(h=0,rb.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let _=new sq.l(this,r),f=null!==(n=e.width)&&void 0!==n?n:e,m=null!==(a=e.height)&&void 0!==a?a:e,g=e.layers||0;if(0!==g)throw Error("Texture layers are not supported in Babylon Native");let v=_._hardwareTexture.underlyingResource,x=uW(c,h);return this._engine.initializeTexture(v,f,m,l,x,!0,d,p),this._setTextureSampling(v,uH(u)),_._useSRGBBuffer=d,_.baseWidth=f,_.baseHeight=m,_.width=f,_.height=m,_.depth=g,_.isReady=!0,_.samples=p,_.generateMipMaps=l,_.samplingMode=u,_.type=h,_.format=c,_.label=o,this._internalTexturesCache.push(_),_}createRenderTargetTexture(e,t){var i,r,s,n;let a;let o=this._createHardwareRenderTargetWrapper(!1,!1,e),l=!0,h=!1,u=!1,c=1;void 0!==t&&"object"==typeof t&&(l=null===(i=t.generateDepthBuffer)||void 0===i||i,h=!!t.generateStencilBuffer,u=!!t.noColorAttachment,a=t.colorAttachment,c=null!==(r=t.samples)&&void 0!==r?r:1);let d=a||(u?null:this._createInternalTexture(e,t,!0,sq.S.RenderTarget)),p=null!==(s=e.width)&&void 0!==s?s:e,_=null!==(n=e.height)&&void 0!==n?n:e,f=this._engine.createFrameBuffer(d?d._hardwareTexture.underlyingResource:null,p,_,h,l,c);return o._framebuffer=f,o._generateDepthBuffer=l,o._generateStencilBuffer=h,o._samples=c,o.setTextures(d),o}updateRenderTargetTextureSampleCount(e,t){return rb.Y.Warn("Updating render target sample count is not currently supported"),e.samples}updateTextureSamplingMode(e,t){if(t._hardwareTexture){let i=uH(e);this._setTextureSampling(t._hardwareTexture.underlyingResource,i)}t.samplingMode=e}bindFramebuffer(e,t,i,r,s){if(this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,t)throw Error("Cuboid frame buffers are not yet supported in NativeEngine.");if(i||r)throw Error("Required width/height for frame buffers not yet supported in NativeEngine.");e._framebufferDepthStencil?this._bindUnboundFramebuffer(e._framebufferDepthStencil):this._bindUnboundFramebuffer(e._framebuffer)}unBindFramebuffer(e,t=!1,i){this._currentRenderTarget=null,i&&i(),this._bindUnboundFramebuffer(null)}createDynamicVertexBuffer(e){return this.createVertexBuffer(e,!0)}updateDynamicIndexBuffer(e,t,i=0){let r=this._normalizeIndexData(t);e.is32Bits=4===r.BYTES_PER_ELEMENT,this._engine.updateDynamicIndexBuffer(e.nativeIndexBuffer,r.buffer,r.byteOffset,r.byteLength,i)}updateDynamicVertexBuffer(e,t,i,r){let s=ArrayBuffer.isView(t)?t:new Float32Array(t);this._engine.updateDynamicVertexBuffer(e.nativeVertexBuffer,s.buffer,s.byteOffset+(null!=i?i:0),null!=r?r:s.byteLength)}_setTexture(e,t,i=!1,r=!1){let s;let n=this._boundUniforms[e];if(!n)return!1;if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._boundTexturesCache[e]=null),!1;if(t.video)this._activeChannel=e,t.update();else if(4===t.delayLoadState)return t.delayLoad(),!1;return s=r?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,this._activeChannel=e,!!s&&!!s._hardwareTexture&&(this._setTextureWrapMode(s._hardwareTexture.underlyingResource,uX(t.wrapU),uX(t.wrapV),uX(t.wrapR)),this._updateAnisotropicLevel(t),this._setTextureCore(n,s._hardwareTexture.underlyingResource),!0)}_setTextureSampling(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURESAMPLING),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.finishEncodingCommand()}_setTextureWrapMode(e,t,i,r){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREWRAPMODE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsUInt32(t),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.encodeCommandArgAsUInt32(r),this._commandBufferEncoder.finishEncodingCommand()}_setTextureCore(e,t){this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTURE),this._commandBufferEncoder.encodeCommandArgAsNativeData(e),this._commandBufferEncoder.encodeCommandArgAsNativeData(t),this._commandBufferEncoder.finishEncodingCommand()}_updateAnisotropicLevel(e){let t=e.getInternalTexture(),i=e.anisotropicFilteringLevel;t&&t._hardwareTexture&&t._cachedAnisotropicFilteringLevel!==i&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_SETTEXTUREANISOTROPICLEVEL),this._commandBufferEncoder.encodeCommandArgAsNativeData(t._hardwareTexture.underlyingResource),this._commandBufferEncoder.encodeCommandArgAsUInt32(i),this._commandBufferEncoder.finishEncodingCommand(),t._cachedAnisotropicFilteringLevel=i)}_bindTexture(e,t){let i=this._boundUniforms[e];if(i&&t&&t._hardwareTexture){let e=t._hardwareTexture.underlyingResource;this._setTextureCore(i,e)}}_deleteBuffer(e){e.nativeIndexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEINDEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeIndexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeIndexBuffer),e.nativeVertexBuffer&&(this._commandBufferEncoder.startEncodingCommand(_native.Engine.COMMAND_DELETEVERTEXBUFFER),this._commandBufferEncoder.encodeCommandArgAsNativeData(e.nativeVertexBuffer),this._commandBufferEncoder.finishEncodingCommand(),delete e.nativeVertexBuffer)}createCanvas(e,t){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");let i=new _native.Canvas;return i.width=e,i.height=t,i}createCanvasImage(){if(!_native.Canvas)throw Error("Native Canvas plugin not available.");return new _native.Image}updateTextureData(e,t,i,r,s,n,a=0,o=0,l=!1){throw Error("updateTextureData not implemented.")}_uploadCompressedDataToTextureDirectly(e,t,i,r,s,n=0,a=0){throw Error("_uploadCompressedDataToTextureDirectly not implemented.")}_uploadDataToTextureDirectly(e,t,i=0,r=0){throw Error("_uploadDataToTextureDirectly not implemented.")}_uploadArrayBufferViewToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}_uploadImageToTexture(e,t,i=0,r=0){throw Error("_uploadArrayBufferViewToTexture not implemented.")}getFontOffset(e){return{ascent:0,height:0,descent:0}}_readTexturePixels(e,t,i,r,s,n,a,o,l,h){var u,c,d,p;if(void 0!==r&&-1!==r)throw Error(`Reading cubemap faces is not supported, but faceIndex is ${r}.`);return this._engine.readTexture(null===(u=e._hardwareTexture)||void 0===u?void 0:u.underlyingResource,null!=s?s:0,null!=l?l:0,null!=h?h:0,t,i,null!==(c=null==n?void 0:n.buffer)&&void 0!==c?c:null,null!==(d=null==n?void 0:n.byteOffset)&&void 0!==d?d:0,null!==(p=null==n?void 0:n.byteLength)&&void 0!==p?p:0).then(e=>(n||(n=new Uint8Array(e)),n))}}u$.PROTOCOL_VERSION=8,u$._createNativeDataStream=function(){return _native.NativeDataStream.VALIDATION_ENABLED?new uQ:new uu};class uQ extends uu{constructor(){super()}writeUint32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32),super.writeUint32(e)}writeInt32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32),super.writeInt32(e)}writeFloat32(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32),super.writeFloat32(e)}writeUint32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_UINT_32_ARRAY),super.writeUint32Array(e)}writeInt32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_INT_32_ARRAY),super.writeInt32Array(e)}writeFloat32Array(e){super.writeUint32(_native.NativeDataStream.VALIDATION_FLOAT_32_ARRAY),super.writeFloat32Array(e)}writeNativeData(e){super.writeUint32(_native.NativeDataStream.VALIDATION_NATIVE_DATA),super.writeNativeData(e)}writeBoolean(e){super.writeUint32(_native.NativeDataStream.VALIDATION_BOOLEAN),super.writeBoolean(e)}}(w=tz||(tz={})).LowPower="low-power",w.HighPerformance="high-performance",(B=tW||(tW={})).DepthClipControl="depth-clip-control",B.Depth32FloatStencil8="depth32float-stencil8",B.TextureCompressionBC="texture-compression-bc",B.TextureCompressionETC2="texture-compression-etc2",B.TextureCompressionASTC="texture-compression-astc",B.TimestampQuery="timestamp-query",B.IndirectFirstInstance="indirect-first-instance",B.ShaderF16="shader-f16",B.RG11B10UFloatRenderable="rg11b10ufloat-renderable",B.BGRA8UnormStorage="bgra8unorm-storage",B.Float32Filterable="float32-filterable",(U=tH||(tH={})).Unmapped="unmapped",U.Pending="pending",U.Mapped="mapped",(V=tX||(tX={}))[V.MapRead=1]="MapRead",V[V.MapWrite=2]="MapWrite",V[V.CopySrc=4]="CopySrc",V[V.CopyDst=8]="CopyDst",V[V.Index=16]="Index",V[V.Vertex=32]="Vertex",V[V.Uniform=64]="Uniform",V[V.Storage=128]="Storage",V[V.Indirect=256]="Indirect",V[V.QueryResolve=512]="QueryResolve",(k=tY||(tY={}))[k.Read=1]="Read",k[k.Write=2]="Write",(G=tj||(tj={})).E1d="1d",G.E2d="2d",G.E3d="3d",(z=tq||(tq={}))[z.CopySrc=1]="CopySrc",z[z.CopyDst=2]="CopyDst",z[z.TextureBinding=4]="TextureBinding",z[z.StorageBinding=8]="StorageBinding",z[z.RenderAttachment=16]="RenderAttachment",(W=tK||(tK={})).E1d="1d",W.E2d="2d",W.E2dArray="2d-array",W.Cube="cube",W.CubeArray="cube-array",W.E3d="3d",(H=t$||(t$={})).All="all",H.StencilOnly="stencil-only",H.DepthOnly="depth-only",(X=tQ||(tQ={})).R8Unorm="r8unorm",X.R8Snorm="r8snorm",X.R8Uint="r8uint",X.R8Sint="r8sint",X.R16Uint="r16uint",X.R16Sint="r16sint",X.R16Float="r16float",X.RG8Unorm="rg8unorm",X.RG8Snorm="rg8snorm",X.RG8Uint="rg8uint",X.RG8Sint="rg8sint",X.R32Uint="r32uint",X.R32Sint="r32sint",X.R32Float="r32float",X.RG16Uint="rg16uint",X.RG16Sint="rg16sint",X.RG16Float="rg16float",X.RGBA8Unorm="rgba8unorm",X.RGBA8UnormSRGB="rgba8unorm-srgb",X.RGBA8Snorm="rgba8snorm",X.RGBA8Uint="rgba8uint",X.RGBA8Sint="rgba8sint",X.BGRA8Unorm="bgra8unorm",X.BGRA8UnormSRGB="bgra8unorm-srgb",X.RGB9E5UFloat="rgb9e5ufloat",X.RGB10A2UINT="rgb10a2uint",X.RGB10A2Unorm="rgb10a2unorm",X.RG11B10UFloat="rg11b10ufloat",X.RG32Uint="rg32uint",X.RG32Sint="rg32sint",X.RG32Float="rg32float",X.RGBA16Uint="rgba16uint",X.RGBA16Sint="rgba16sint",X.RGBA16Float="rgba16float",X.RGBA32Uint="rgba32uint",X.RGBA32Sint="rgba32sint",X.RGBA32Float="rgba32float",X.Stencil8="stencil8",X.Depth16Unorm="depth16unorm",X.Depth24Plus="depth24plus",X.Depth24PlusStencil8="depth24plus-stencil8",X.Depth32Float="depth32float",X.BC1RGBAUnorm="bc1-rgba-unorm",X.BC1RGBAUnormSRGB="bc1-rgba-unorm-srgb",X.BC2RGBAUnorm="bc2-rgba-unorm",X.BC2RGBAUnormSRGB="bc2-rgba-unorm-srgb",X.BC3RGBAUnorm="bc3-rgba-unorm",X.BC3RGBAUnormSRGB="bc3-rgba-unorm-srgb",X.BC4RUnorm="bc4-r-unorm",X.BC4RSnorm="bc4-r-snorm",X.BC5RGUnorm="bc5-rg-unorm",X.BC5RGSnorm="bc5-rg-snorm",X.BC6HRGBUFloat="bc6h-rgb-ufloat",X.BC6HRGBFloat="bc6h-rgb-float",X.BC7RGBAUnorm="bc7-rgba-unorm",X.BC7RGBAUnormSRGB="bc7-rgba-unorm-srgb",X.ETC2RGB8Unorm="etc2-rgb8unorm",X.ETC2RGB8UnormSRGB="etc2-rgb8unorm-srgb",X.ETC2RGB8A1Unorm="etc2-rgb8a1unorm",X.ETC2RGB8A1UnormSRGB="etc2-rgb8a1unorm-srgb",X.ETC2RGBA8Unorm="etc2-rgba8unorm",X.ETC2RGBA8UnormSRGB="etc2-rgba8unorm-srgb",X.EACR11Unorm="eac-r11unorm",X.EACR11Snorm="eac-r11snorm",X.EACRG11Unorm="eac-rg11unorm",X.EACRG11Snorm="eac-rg11snorm",X.ASTC4x4Unorm="astc-4x4-unorm",X.ASTC4x4UnormSRGB="astc-4x4-unorm-srgb",X.ASTC5x4Unorm="astc-5x4-unorm",X.ASTC5x4UnormSRGB="astc-5x4-unorm-srgb",X.ASTC5x5Unorm="astc-5x5-unorm",X.ASTC5x5UnormSRGB="astc-5x5-unorm-srgb",X.ASTC6x5Unorm="astc-6x5-unorm",X.ASTC6x5UnormSRGB="astc-6x5-unorm-srgb",X.ASTC6x6Unorm="astc-6x6-unorm",X.ASTC6x6UnormSRGB="astc-6x6-unorm-srgb",X.ASTC8x5Unorm="astc-8x5-unorm",X.ASTC8x5UnormSRGB="astc-8x5-unorm-srgb",X.ASTC8x6Unorm="astc-8x6-unorm",X.ASTC8x6UnormSRGB="astc-8x6-unorm-srgb",X.ASTC8x8Unorm="astc-8x8-unorm",X.ASTC8x8UnormSRGB="astc-8x8-unorm-srgb",X.ASTC10x5Unorm="astc-10x5-unorm",X.ASTC10x5UnormSRGB="astc-10x5-unorm-srgb",X.ASTC10x6Unorm="astc-10x6-unorm",X.ASTC10x6UnormSRGB="astc-10x6-unorm-srgb",X.ASTC10x8Unorm="astc-10x8-unorm",X.ASTC10x8UnormSRGB="astc-10x8-unorm-srgb",X.ASTC10x10Unorm="astc-10x10-unorm",X.ASTC10x10UnormSRGB="astc-10x10-unorm-srgb",X.ASTC12x10Unorm="astc-12x10-unorm",X.ASTC12x10UnormSRGB="astc-12x10-unorm-srgb",X.ASTC12x12Unorm="astc-12x12-unorm",X.ASTC12x12UnormSRGB="astc-12x12-unorm-srgb",X.Depth32FloatStencil8="depth32float-stencil8",(Y=tZ||(tZ={})).ClampToEdge="clamp-to-edge",Y.Repeat="repeat",Y.MirrorRepeat="mirror-repeat",(j=tJ||(tJ={})).Nearest="nearest",j.Linear="linear",(q=t0||(t0={})).Nearest="nearest",q.Linear="linear",(K=t1||(t1={})).Never="never",K.Less="less",K.Equal="equal",K.LessEqual="less-equal",K.Greater="greater",K.NotEqual="not-equal",K.GreaterEqual="greater-equal",K.Always="always",($=t2||(t2={}))[$.Vertex=1]="Vertex",$[$.Fragment=2]="Fragment",$[$.Compute=4]="Compute",(Q=t3||(t3={})).Uniform="uniform",Q.Storage="storage",Q.ReadOnlyStorage="read-only-storage",(Z=t4||(t4={})).Filtering="filtering",Z.NonFiltering="non-filtering",Z.Comparison="comparison",(J=t5||(t5={})).Float="float",J.UnfilterableFloat="unfilterable-float",J.Depth="depth",J.Sint="sint",J.Uint="uint",(t6||(t6={})).WriteOnly="write-only",(ee=t8||(t8={})).Error="error",ee.Warning="warning",ee.Info="info",(et=t7||(t7={})).Validation="validation",et.Internal="internal",(t9||(t9={})).Auto="auto",(ei=ie||(ie={})).PointList="point-list",ei.LineList="line-list",ei.LineStrip="line-strip",ei.TriangleList="triangle-list",ei.TriangleStrip="triangle-strip",(er=it||(it={})).CCW="ccw",er.CW="cw",(es=ii||(ii={})).None="none",es.Front="front",es.Back="back",(en=ir||(ir={}))[en.Red=1]="Red",en[en.Green=2]="Green",en[en.Blue=4]="Blue",en[en.Alpha=8]="Alpha",en[en.All=15]="All",(ea=is||(is={})).Zero="zero",ea.One="one",ea.Src="src",ea.OneMinusSrc="one-minus-src",ea.SrcAlpha="src-alpha",ea.OneMinusSrcAlpha="one-minus-src-alpha",ea.Dst="dst",ea.OneMinusDst="one-minus-dst",ea.DstAlpha="dst-alpha",ea.OneMinusDstAlpha="one-minus-dst-alpha",ea.SrcAlphaSaturated="src-alpha-saturated",ea.Constant="constant",ea.OneMinusConstant="one-minus-constant",(eo=ia||(ia={})).Add="add",eo.Subtract="subtract",eo.ReverseSubtract="reverse-subtract",eo.Min="min",eo.Max="max",(el=io||(io={})).Keep="keep",el.Zero="zero",el.Replace="replace",el.Invert="invert",el.IncrementClamp="increment-clamp",el.DecrementClamp="decrement-clamp",el.IncrementWrap="increment-wrap",el.DecrementWrap="decrement-wrap",(eh=il||(il={})).Uint16="uint16",eh.Uint32="uint32",(eu=ih||(ih={})).Uint8x2="uint8x2",eu.Uint8x4="uint8x4",eu.Sint8x2="sint8x2",eu.Sint8x4="sint8x4",eu.Unorm8x2="unorm8x2",eu.Unorm8x4="unorm8x4",eu.Snorm8x2="snorm8x2",eu.Snorm8x4="snorm8x4",eu.Uint16x2="uint16x2",eu.Uint16x4="uint16x4",eu.Sint16x2="sint16x2",eu.Sint16x4="sint16x4",eu.Unorm16x2="unorm16x2",eu.Unorm16x4="unorm16x4",eu.Snorm16x2="snorm16x2",eu.Snorm16x4="snorm16x4",eu.Float16x2="float16x2",eu.Float16x4="float16x4",eu.Float32="float32",eu.Float32x2="float32x2",eu.Float32x3="float32x3",eu.Float32x4="float32x4",eu.Uint32="uint32",eu.Uint32x2="uint32x2",eu.Uint32x3="uint32x3",eu.Uint32x4="uint32x4",eu.Sint32="sint32",eu.Sint32x2="sint32x2",eu.Sint32x3="sint32x3",eu.Sint32x4="sint32x4",eu.UNORM10x10x10x2="unorm10-10-10-2",(ec=iu||(iu={})).Vertex="vertex",ec.Instance="instance",(ed=ic||(ic={})).Beginning="beginning",ed.End="end",(ep=id||(id={})).Beginning="beginning",ep.End="end",(e_=ip||(ip={})).Load="load",e_.Clear="clear",(ef=i_||(i_={})).Store="store",ef.Discard="discard",(em=im||(im={})).Occlusion="occlusion",em.Timestamp="timestamp",(eg=ig||(ig={})).Opaque="opaque",eg.Premultiplied="premultiplied",(ev=iv||(iv={})).Unknown="unknown",ev.Destroyed="destroyed",(ex=ix||(ix={})).Validation="validation",ex.OutOfMemory="out-of-memory",ex.Internal="internal";class uZ{constructor(){this.shaderLanguage=nG.x.GLSL,this.vertexBufferKindToNumberOfComponents={}}_addUniformToLeftOverUBO(e,t,i){let r=0;[e,t,r]=this._getArraySize(e,t,i);for(let t=0;t=0&&(c.push(a[l]),d.push(e))}this.shaderProcessingContext.attributeNamesFromEffect=c,this.shaderProcessingContext.attributeLocationsFromEffect=d}buildUniformLayout(){if(this.shaderProcessingContext.leftOverUniforms.length){for(let e of(this.uniformBuffer=new sT.M(this.engine,void 0,void 0,"leftOver-"+this._name),this.shaderProcessingContext.leftOverUniforms)){let t=e.type.replace(/^(.*?)(<.*>)?$/,"$1"),i=uZ.UniformSizes[t];this.uniformBuffer.addUniform(e.name,i,e.length),this._leftOverUniformsByName[e.name]=e.type}this.uniformBuffer.create()}}dispose(){this.uniformBuffer&&this.uniformBuffer.dispose()}setInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt(e,t)}setInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt2(e,t,i)}setInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt3(e,t,i,r)}setInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateInt4(e,t,i,r,s)}setIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateIntArray(e,t)}setIntArray2(e,t){this.setIntArray(e,t)}setIntArray3(e,t){this.setIntArray(e,t)}setIntArray4(e,t){this.setIntArray(e,t)}setUInt(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt(e,t)}setUInt2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt2(e,t,i)}setUInt3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt3(e,t,i,r)}setUInt4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUInt4(e,t,i,r,s)}setUIntArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateUIntArray(e,t)}setUIntArray2(e,t){this.setUIntArray(e,t)}setUIntArray3(e,t){this.setUIntArray(e,t)}setUIntArray4(e,t){this.setUIntArray(e,t)}setArray(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateArray(e,t)}setArray2(e,t){this.setArray(e,t)}setArray3(e,t){this.setArray(e,t)}setArray4(e,t){this.setArray(e,t)}setMatrices(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrices(e,t)}setMatrix(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix(e,t)}setMatrix3x3(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix3x3(e,t)}setMatrix2x2(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateMatrix2x2(e,t)}setFloat(e,t){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat(e,t)}setVector2(e,t){this.setFloat2(e,t.x,t.y)}setFloat2(e,t,i){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat2(e,t,i)}setVector3(e,t){this.setFloat3(e,t.x,t.y,t.z)}setFloat3(e,t,i,r){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat3(e,t,i,r)}setVector4(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setQuaternion(e,t){this.setFloat4(e,t.x,t.y,t.z,t.w)}setFloat4(e,t,i,r,s){this.uniformBuffer&&this._leftOverUniformsByName[e]&&this.uniformBuffer.updateFloat4(e,t,i,r,s)}setColor3(e,t){this.setFloat3(e,t.r,t.g,t.b)}setColor4(e,t,i){this.setFloat4(e,t.r,t.g,t.b,i)}setDirectColor4(e,t){this.setFloat4(e,t.r,t.g,t.b,t.a)}_getVertexShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.vertex}_getFragmentShaderCode(){var e;return null===(e=this.sources)||void 0===e?void 0:e.fragment}}let u0={mat2:2,mat3:3,mat4:4,mat2x2:2,mat3x3:3,mat4x4:4};class u1{static get KnownUBOs(){return u1._SimplifiedKnownBindings?u1._SimplifiedKnownUBOs:u1._KnownUBOs}constructor(e){this.shaderLanguage=e,this._attributeNextLocation=0,this._varyingNextLocation=0,this.freeGroupIndex=0,this.freeBindingIndex=0,this.availableVaryings={},this.availableAttributes={},this.availableBuffers={},this.availableTextures={},this.availableSamplers={},this.orderedAttributes=[],this.bindGroupLayoutEntries=[],this.bindGroupLayoutEntryInfo=[],this.bindGroupEntries=[],this.bufferNames=[],this.textureNames=[],this.samplerNames=[],this.leftOverUniforms=[],this._findStartingGroupBinding()}_findStartingGroupBinding(){let e=u1.KnownUBOs,t=[];for(let i in e){let r=e[i].binding;-1!==r.groupIndex&&(void 0===t[r.groupIndex]?t[r.groupIndex]=r.bindingIndex:t[r.groupIndex]=Math.max(t[r.groupIndex],r.bindingIndex))}this.freeGroupIndex=t.length-1,0===this.freeGroupIndex?(this.freeGroupIndex++,this.freeBindingIndex=0):this.freeBindingIndex=t[t.length-1]+1}getAttributeNextLocation(e,t=0){var i;let r=this._attributeNextLocation;return this._attributeNextLocation+=(null!==(i=u0[e])&&void 0!==i?i:1)*(t||1),r}getVaryingNextLocation(e,t=0){var i;let r=this._varyingNextLocation;return this._varyingNextLocation+=(null!==(i=u0[e])&&void 0!==i?i:1)*(t||1),r}getNextFreeUBOBinding(){return this._getNextFreeBinding(1)}_getNextFreeBinding(e){if(this.freeBindingIndex>65536-e&&(this.freeGroupIndex++,this.freeBindingIndex=0),4===this.freeGroupIndex)throw"Too many textures or UBOs have been declared and it is not supported in WebGPU.";let t={groupIndex:this.freeGroupIndex,bindingIndex:this.freeBindingIndex};return this.freeBindingIndex+=e,t}}u1._SimplifiedKnownBindings=!0,u1._SimplifiedKnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:-1,bindingIndex:-1}},Light1:{binding:{groupIndex:-1,bindingIndex:-1}},Light2:{binding:{groupIndex:-1,bindingIndex:-1}},Light3:{binding:{groupIndex:-1,bindingIndex:-1}},Light4:{binding:{groupIndex:-1,bindingIndex:-1}},Light5:{binding:{groupIndex:-1,bindingIndex:-1}},Light6:{binding:{groupIndex:-1,bindingIndex:-1}},Light7:{binding:{groupIndex:-1,bindingIndex:-1}},Light8:{binding:{groupIndex:-1,bindingIndex:-1}},Light9:{binding:{groupIndex:-1,bindingIndex:-1}},Light10:{binding:{groupIndex:-1,bindingIndex:-1}},Light11:{binding:{groupIndex:-1,bindingIndex:-1}},Light12:{binding:{groupIndex:-1,bindingIndex:-1}},Light13:{binding:{groupIndex:-1,bindingIndex:-1}},Light14:{binding:{groupIndex:-1,bindingIndex:-1}},Light15:{binding:{groupIndex:-1,bindingIndex:-1}},Light16:{binding:{groupIndex:-1,bindingIndex:-1}},Light17:{binding:{groupIndex:-1,bindingIndex:-1}},Light18:{binding:{groupIndex:-1,bindingIndex:-1}},Light19:{binding:{groupIndex:-1,bindingIndex:-1}},Light20:{binding:{groupIndex:-1,bindingIndex:-1}},Light21:{binding:{groupIndex:-1,bindingIndex:-1}},Light22:{binding:{groupIndex:-1,bindingIndex:-1}},Light23:{binding:{groupIndex:-1,bindingIndex:-1}},Light24:{binding:{groupIndex:-1,bindingIndex:-1}},Light25:{binding:{groupIndex:-1,bindingIndex:-1}},Light26:{binding:{groupIndex:-1,bindingIndex:-1}},Light27:{binding:{groupIndex:-1,bindingIndex:-1}},Light28:{binding:{groupIndex:-1,bindingIndex:-1}},Light29:{binding:{groupIndex:-1,bindingIndex:-1}},Light30:{binding:{groupIndex:-1,bindingIndex:-1}},Light31:{binding:{groupIndex:-1,bindingIndex:-1}},Material:{binding:{groupIndex:-1,bindingIndex:-1}},Mesh:{binding:{groupIndex:-1,bindingIndex:-1}},Internals:{binding:{groupIndex:-1,bindingIndex:-1}}},u1._KnownUBOs={Scene:{binding:{groupIndex:0,bindingIndex:0}},Light0:{binding:{groupIndex:1,bindingIndex:0}},Light1:{binding:{groupIndex:1,bindingIndex:1}},Light2:{binding:{groupIndex:1,bindingIndex:2}},Light3:{binding:{groupIndex:1,bindingIndex:3}},Light4:{binding:{groupIndex:1,bindingIndex:4}},Light5:{binding:{groupIndex:1,bindingIndex:5}},Light6:{binding:{groupIndex:1,bindingIndex:6}},Light7:{binding:{groupIndex:1,bindingIndex:7}},Light8:{binding:{groupIndex:1,bindingIndex:8}},Light9:{binding:{groupIndex:1,bindingIndex:9}},Light10:{binding:{groupIndex:1,bindingIndex:10}},Light11:{binding:{groupIndex:1,bindingIndex:11}},Light12:{binding:{groupIndex:1,bindingIndex:12}},Light13:{binding:{groupIndex:1,bindingIndex:13}},Light14:{binding:{groupIndex:1,bindingIndex:14}},Light15:{binding:{groupIndex:1,bindingIndex:15}},Light16:{binding:{groupIndex:1,bindingIndex:16}},Light17:{binding:{groupIndex:1,bindingIndex:17}},Light18:{binding:{groupIndex:1,bindingIndex:18}},Light19:{binding:{groupIndex:1,bindingIndex:19}},Light20:{binding:{groupIndex:1,bindingIndex:20}},Light21:{binding:{groupIndex:1,bindingIndex:21}},Light22:{binding:{groupIndex:1,bindingIndex:22}},Light23:{binding:{groupIndex:1,bindingIndex:23}},Light24:{binding:{groupIndex:1,bindingIndex:24}},Light25:{binding:{groupIndex:1,bindingIndex:25}},Light26:{binding:{groupIndex:1,bindingIndex:26}},Light27:{binding:{groupIndex:1,bindingIndex:27}},Light28:{binding:{groupIndex:1,bindingIndex:28}},Light29:{binding:{groupIndex:1,bindingIndex:29}},Light30:{binding:{groupIndex:1,bindingIndex:30}},Light31:{binding:{groupIndex:1,bindingIndex:31}},Material:{binding:{groupIndex:2,bindingIndex:0}},Mesh:{binding:{groupIndex:2,bindingIndex:1}},Internals:{binding:{groupIndex:2,bindingIndex:2}}};class u2 extends uZ{constructor(){super(...arguments),this._missingVaryings=[],this._textureArrayProcessing=[],this._vertexIsGLES3=!1,this._fragmentIsGLES3=!1,this.shaderLanguage=nG.x.GLSL,this.parseGLES3=!0}_getArraySize(e,t,i){let r=0,s=e.indexOf("["),n=e.indexOf("]");if(s>0&&n>0){let t=e.substring(s+1,n);isNaN(r=+t)&&(r=+i[t.trim()]),e=e.substr(0,s)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._missingVaryings.length=0,this._textureArrayProcessing.length=0,this.attributeKeywordName=void 0,this.varyingVertexKeywordName=void 0,this.varyingFragmentKeywordName=void 0}preProcessShaderCode(e,t){let i=`// Internals UBO +uniform ${uZ.InternalsUBOName} { +float yFactor_; +float textureOutputHeight_; +}; +`,r=-1!==e.indexOf("// Internals UBO");return t?(this._fragmentIsGLES3=-1!==e.indexOf("#version 3"),this._fragmentIsGLES3&&(this.varyingFragmentKeywordName="in"),r?e:i+"##INJECTCODE##\n"+e):(this._vertexIsGLES3=-1!==e.indexOf("#version 3"),this._vertexIsGLES3&&(this.attributeKeywordName="in",this.varyingVertexKeywordName="out"),r?e:i+e)}varyingCheck(e,t){return(t&&this._fragmentIsGLES3?/(flat\s)?\s*\bin\b/:!t&&this._vertexIsGLES3?/(flat\s)?\s*\bout\b/:/(flat\s)?\s*\bvarying\b/).test(e)}varyingProcessor(e,t,i){var r;this._preProcessors=i;let s=(t&&this._fragmentIsGLES3?/\s*(flat)?\s*in\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:!t&&this._vertexIsGLES3?/\s*(flat)?\s*out\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm:/\s*(flat)?\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==s){let n;let a=null!==(r=s[1])&&void 0!==r?r:"",o=s[2],l=s[3];t?(n=this._webgpuProcessingContext.availableVaryings[l],this._missingVaryings[n]="",void 0===n&&rb.Y.Warn(`Invalid fragment shader: The varying named "${l}" is not declared in the vertex shader! This declaration will be ignored.`)):(n=this._webgpuProcessingContext.getVaryingNextLocation(o,this._getArraySize(l,o,i)[2]),this._webgpuProcessingContext.availableVaryings[l]=n,this._missingVaryings[n]=`layout(location = ${n}) ${a} in ${o} ${l};`),e=e.replace(s[0],void 0===n?"":`layout(location = ${n}) ${a} ${t?"in":"out"} ${o} ${l};`)}return e}attributeProcessor(e,t){this._preProcessors=t;let i=(this._vertexIsGLES3?/\s*in\s+(\S+)\s+(\S+)\s*;/gm:/\s*attribute\s+(\S+)\s+(\S+)\s*;/gm).exec(e);if(null!==i){let r=i[1],s=i[2],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;let a=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==a){let t=`_int_${s}_`;e=e.replace(i[0],`layout(location = ${n}) in ${a<0?-1===a?"int":"ivec"+-a:1===a?"uint":"uvec"+a} ${t}; ${r} ${s} = ${r}(${t});`)}else e=e.replace(i[0],`layout(location = ${n}) in ${r} ${s};`)}return e}uniformProcessor(e,t,i){var r;this._preProcessors=i;let s=/\s*uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/gm.exec(e);if(null!==s){let n=s[1],a=s[2];if(0===n.indexOf("sampler")||1===n.indexOf("sampler")){let s=0;[a,n,s]=this._getArraySize(a,n,i);let o=this._webgpuProcessingContext.availableTextures[a];if(!o){o={autoBindSampler:!0,isTextureArray:s>0,isStorageTexture:!1,textures:[],sampleType:t5.Float};for(let e=0;e<(s||1);++e)o.textures.push(this._webgpuProcessingContext.getNextFreeUBOBinding())}let l=null!==(r=uZ._SamplerTypeByWebGLSamplerType[n])&&void 0!==r?r:"sampler",h=!!uZ._IsComparisonSamplerByWebGPUSamplerType[l],u=h?t4.Comparison:t4.Filtering,c=a+uZ.AutoSamplerSuffix,d=this._webgpuProcessingContext.availableSamplers[c];d||(d={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:u});let p="u"===n.charAt(0)?"u":"i"===n.charAt(0)?"i":"";p&&(n=n.substr(1));let _=h?t5.Depth:"u"===p?t5.Uint:"i"===p?t5.Sint:t5.Float;o.sampleType=_;let f=s>0,m=d.binding.groupIndex,g=d.binding.bindingIndex,v=uZ._SamplerFunctionByWebGLSamplerType[n],x=uZ._TextureTypeByWebGLSamplerType[n],T=uZ._GpuTextureViewDimensionByWebGPUTextureType[x];if(f){let t=[];t.push(`layout(set = ${m}, binding = ${g}) uniform ${p}${l} ${c};`),e=` +`;for(let i=0;i0?"\n":""}#define ${a}${i} ${p}${v}(${a}Texture${i}, ${c})`}e=t.join("\n")+e,this._textureArrayProcessing.push(a)}else s=1,e=`layout(set = ${m}, binding = ${g}) uniform ${l} ${c}; + layout(set = ${o.textures[0].groupIndex}, binding = ${o.textures[0].bindingIndex}) uniform ${p}${x} ${a}Texture; + #define ${a} ${p}${v}(${a}Texture, ${c})`;this._webgpuProcessingContext.availableTextures[a]=o,this._webgpuProcessingContext.availableSamplers[c]=d,this._addSamplerBindingDescription(c,d,!t);for(let e=0;e=0,i=` + glFragCoord_ = gl_FragCoord; + if (yFactor_ == 1.) { + glFragCoord_.y = textureOutputHeight_ - glFragCoord_.y; + } + `,r=-1!==e.search(/layout *\(location *= *0\) *out/g);if(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(/gl_FragCoord/g,"glFragCoord_"),this._fragmentIsGLES3){let t=/^\s*out\s+\S+\s+\S+\s*;/gm.exec(e);null!==t&&(e=e.substring(0,t.index)+"layout(location = 0) "+e.substring(t.index))}else e=e.replace(/void\s+?main\s*\(/g,(n||r?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(");e=(e=e.replace(/dFdy/g,"(-yFactor_)*dFdy")).replace("##INJECTCODE##",t?"vec4 glFragCoord_;\n":""),t&&(e=this._injectStartingAndEndingCode(e,"void main",i))}else if(e=(e=e.replace(/gl_InstanceID/g,"gl_InstanceIndex")).replace(/gl_VertexID/g,"gl_VertexIndex"),-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e;if(!i){let t=e.lastIndexOf("}");e=e.substring(0,t)+"gl_Position.y *= yFactor_;\n",s.isNDCHalfZRange||(e+="gl_Position.z = (gl_Position.z + gl_Position.w) / 2.0;\n"),e+="}"}return e}_applyTextureArrayProcessing(e,t){let i=RegExp(t+"\\s*\\[(.+)?\\]","gm"),r=i.exec(e);for(;null!==r;){let s=r[1],n=+s;this._preProcessors&&isNaN(n)&&(n=+this._preProcessors[s.trim()]),e=e.replace(r[0],t+n),r=i.exec(e)}return e}_generateLeftOverUBOCode(e,t){let i=`layout(set = ${t.binding.groupIndex}, binding = ${t.binding.bindingIndex}) uniform ${e} { + `;for(let e of this._webgpuProcessingContext.leftOverUniforms)e.length>0?i+=` ${e.type} ${e.name}[${e.length}]; +`:i+=` ${e.type} ${e.name}; +`;return i+"};\n\n"}finalizeShaders(e,t){for(let i=0;i0&&(t=i+"\n"+t)}let i=this._buildLeftOverUBO();return e=i+e,t=i+t,this._collectBindingNames(),this._preCreateBindGroupEntries(),this._preProcessors=null,this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}}let u3=`#if NUM_BONE_INFLUENCERS>0 +attribute matricesIndices : vec4;attribute matricesWeights : vec4; +#if NUM_BONE_INFLUENCERS>4 +attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; +#endif +#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#ifdef BONETEXTURE +var boneSampler : texture_2d;uniform boneTextureWidth : f32; +#else +uniform mBones : array; +#ifdef BONES_VELOCITY_ENABLED +uniform mPreviousBones : array; +#endif +#endif +#ifdef BONETEXTURE +fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4 +{let offset=i32(index) *4; +let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4(m0,m1,m2,m3);} +#endif +#endif +#endif +`;nw.v.IncludesShadersStoreWGSL.bonesDeclaration=u3;let u4=`#ifndef BAKED_VERTEX_ANIMATION_TEXTURE +#if NUM_BONE_INFLUENCERS>0 +var influence : mat4x4; +#ifdef BONETEXTURE +influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; +#endif +#else +influence=uniforms.mBones[int(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +influence=influence+uniforms.mBones[int(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; +#endif +#endif +finalWorld=finalWorld*influence; +#endif +#endif +`;nw.v.IncludesShadersStoreWGSL.bonesVertex=u4;let u5=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; +#ifdef INSTANCES +attribute bakedVertexAnimationSettingsInstanced : vec4; +#endif +fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 +{let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} +#endif +`;nw.v.IncludesShadersStoreWGSL.bakedVertexAnimationDeclaration=u5;let u6=`#ifdef BAKED_VERTEX_ANIMATION_TEXTURE +{ +#ifdef INSTANCES +let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; +#else +let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; +#endif +let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; +#endif +finalWorld=finalWorld*VATInfluence;} +#endif +`;nw.v.IncludesShadersStoreWGSL.bakedVertexAnimation=u6;let u8=`#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +if (false) {} +#endif +#ifdef CLIPPLANE +else if (fragmentInputs.fClipDistance>0.0) +{discard;} +#endif +#ifdef CLIPPLANE2 +else if (fragmentInputs.fClipDistance2>0.0) +{discard;} +#endif +#ifdef CLIPPLANE3 +else if (fragmentInputs.fClipDistance3>0.0) +{discard;} +#endif +#ifdef CLIPPLANE4 +else if (fragmentInputs.fClipDistance4>0.0) +{discard;} +#endif +#ifdef CLIPPLANE5 +else if (fragmentInputs.fClipDistance5>0.0) +{discard;} +#endif +#ifdef CLIPPLANE6 +else if (fragmentInputs.fClipDistance6>0.0) +{discard;} +#endif +`;nw.v.IncludesShadersStoreWGSL.clipPlaneFragment=u8;let u7=`#ifdef CLIPPLANE +varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +varying fClipDistance6: f32; +#endif +`;nw.v.IncludesShadersStoreWGSL.clipPlaneFragmentDeclaration=u7;let u9=`#ifdef CLIPPLANE +vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); +#endif +#ifdef CLIPPLANE2 +vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); +#endif +#ifdef CLIPPLANE3 +vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); +#endif +#ifdef CLIPPLANE4 +vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); +#endif +#ifdef CLIPPLANE5 +vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); +#endif +#ifdef CLIPPLANE6 +vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); +#endif +`;nw.v.IncludesShadersStoreWGSL.clipPlaneVertex=u9;let ce=`#ifdef CLIPPLANE +uniform vClipPlane: vec4;varying fClipDistance: f32; +#endif +#ifdef CLIPPLANE2 +uniform vClipPlane2: vec4;varying fClipDistance2: f32; +#endif +#ifdef CLIPPLANE3 +uniform vClipPlane3: vec4;varying fClipDistance3: f32; +#endif +#ifdef CLIPPLANE4 +uniform vClipPlane4: vec4;varying fClipDistance4: f32; +#endif +#ifdef CLIPPLANE5 +uniform vClipPlane5: vec4;varying fClipDistance5: f32; +#endif +#ifdef CLIPPLANE6 +uniform vClipPlane6: vec4;varying fClipDistance6: f32; +#endif +`;nw.v.IncludesShadersStoreWGSL.clipPlaneVertexDeclaration=ce;let ct=`#ifdef INSTANCES +attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; +#ifdef INSTANCESCOLOR +attribute instanceColor : vec4; +#endif +#if defined(THIN_INSTANCES) && !defined(WORLD_UBO) +uniform world : mat4x4; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; +#ifdef THIN_INSTANCES +uniform previousWorld : mat4x4; +#endif +#endif +#else +#if !defined(WORLD_UBO) +uniform world : mat4x4; +#endif +#if defined(VELOCITY) || defined(PREPASS_VELOCITY) +uniform previousWorld : mat4x4; +#endif +#endif +`;nw.v.IncludesShadersStoreWGSL.instancesDeclaration=ct;let ci=`#ifdef INSTANCES +var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=mat4x4(previousWorld0,previousWorld1,previousWorld2,previousWorld3); +#endif +#ifdef THIN_INSTANCES +#if !defined(WORLD_UBO) +finalWorld=uniforms.world*finalWorld; +#else +finalWorld=mesh.world*finalWorld; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +finalPreviousWorld=previousWorld*finalPreviousWorld; +#endif +#endif +#else +#if !defined(WORLD_UBO) +var finalWorld=uniforms.world; +#else +var finalWorld=mesh.world; +#endif +#if defined(PREPASS_VELOCITY) || defined(VELOCITY) +var finalPreviousWorld=previousWorld; +#endif +#endif +`;nw.v.IncludesShadersStoreWGSL.instancesVertex=ci;let cr=`struct Mesh {world : mat4x4, +visibility : f32,};var mesh : Mesh; +#define WORLD_UBO +`;nw.v.IncludesShadersStoreWGSL.meshUboDeclaration=cr;let cs=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x;positionUpdated=positionUpdated+(readVector3FromRawSampler({X},vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#ifdef MORPHTARGETS_NORMAL +normalUpdated=normalUpdated+(readVector3FromRawSampler({X},vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(readVector3FromRawSampler({X},vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}];vertexID=vertexID+1.0; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(readVector3FromRawSampler({X},vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#else +positionUpdated=positionUpdated+(position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; +#ifdef MORPHTARGETS_NORMAL +normalUpdated+=(normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_TANGENT +tangentUpdated.xyz=tangentUpdated.xyz+(tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}]; +#endif +#ifdef MORPHTARGETS_UV +uvUpdated=uvUpdated+(uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; +#endif +#endif +#endif +`;nw.v.IncludesShadersStoreWGSL.morphTargetsVertex=cs;let cn=`#ifdef MORPHTARGETS +#ifndef MORPHTARGETS_TEXTURE +attribute position{X} : vec3; +#ifdef MORPHTARGETS_NORMAL +attribute normal{X} : vec3; +#endif +#ifdef MORPHTARGETS_TANGENT +attribute tangent{X} : vec3; +#endif +#ifdef MORPHTARGETS_UV +attribute uv_{X} : vec2; +#endif +#endif +#endif +`;nw.v.IncludesShadersStoreWGSL.morphTargetsVertexDeclaration=cn;let ca=`#ifdef MORPHTARGETS +#ifdef MORPHTARGETS_TEXTURE +var vertexID : f32; +#endif +#endif +`;nw.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobal=ca;let co=`#ifdef MORPHTARGETS +uniform morphTargetInfluences : array; +#ifdef MORPHTARGETS_TEXTURE +uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 +{ +let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} +#endif +#endif +`;nw.v.IncludesShadersStoreWGSL.morphTargetsVertexGlobalDeclaration=co;let cl=`struct Scene {viewProjection : mat4x4, +#ifdef MULTIVIEW +viewProjectionR : mat4x4, +#endif +view : mat4x4, +projection : mat4x4, +vEyePosition : vec4,};var scene : Scene; +`;nw.v.IncludesShadersStoreWGSL.sceneUboDeclaration=cl;let ch="fragmentOutputs.fragDepth",cu={texture_1d:tK.E1d,texture_2d:tK.E2d,texture_2d_array:tK.E2dArray,texture_3d:tK.E3d,texture_cube:tK.Cube,texture_cube_array:tK.CubeArray,texture_multisampled_2d:tK.E2d,texture_depth_2d:tK.E2d,texture_depth_2d_array:tK.E2dArray,texture_depth_cube:tK.Cube,texture_depth_cube_array:tK.CubeArray,texture_depth_multisampled_2d:tK.E2d,texture_storage_1d:tK.E1d,texture_storage_2d:tK.E2d,texture_storage_2d_array:tK.E2dArray,texture_storage_3d:tK.E3d,texture_external:null};class cc extends uZ{constructor(){super(...arguments),this.shaderLanguage=nG.x.WGSL,this.uniformRegexp=/uniform\s+(\w+)\s*:\s*(.+)\s*;/,this.textureRegexp=/var\s+(\w+)\s*:\s*((array<\s*)?(texture_\w+)\s*(<\s*(.+)\s*>)?\s*(,\s*\w+\s*>\s*)?);/,this.noPrecision=!0}_getArraySize(e,t,i){let r=0,s=t.lastIndexOf(">");if(t.indexOf("array")>=0&&s>0){let e=s;for(;e>0&&" "!==t.charAt(e)&&","!==t.charAt(e);)e--;let n=t.substring(e+1,s);for(isNaN(r=+n)&&(r=+i[n.trim()]);e>0&&(" "===t.charAt(e)||","===t.charAt(e));)e--;t=t.substring(t.indexOf("<")+1,e+1)}return[e,t,r]}initializeShaders(e){this._webgpuProcessingContext=e,this._attributesInputWGSL=[],this._attributesWGSL=[],this._attributesConversionCodeWGSL=[],this._hasNonFloatAttribute=!1,this._varyingsWGSL=[],this._varyingNamesWGSL=[],this._stridedUniformArrays=[]}preProcessShaderCode(e){return`struct ${uZ.InternalsUBOName} { + yFactor_: f32, + textureOutputHeight_: f32, +}; +var internals : ${uZ.InternalsUBOName}; +`+uB(e)}varyingProcessor(e,t,i){let r=/\s*varying\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==r){let s;let n=r[2],a=r[1];t?void 0===(s=this._webgpuProcessingContext.availableVaryings[a])&&rb.Y.Warn(`Invalid fragment shader: The varying named "${a}" is not declared in the vertex shader! This declaration will be ignored.`):(s=this._webgpuProcessingContext.getVaryingNextLocation(n,this._getArraySize(a,n,i)[2]),this._webgpuProcessingContext.availableVaryings[a]=s,this._varyingsWGSL.push(` @location(${s}) ${a} : ${n},`),this._varyingNamesWGSL.push(a)),e=""}return e}attributeProcessor(e,t){let i=/\s*attribute\s+(\S+)\s*:\s*(.+)\s*;/gm.exec(e);if(null!==i){let r=i[2],s=i[1],n=this._webgpuProcessingContext.getAttributeNextLocation(r,this._getArraySize(s,r,t)[2]);this._webgpuProcessingContext.availableAttributes[s]=n,this._webgpuProcessingContext.orderedAttributes[n]=s;let a=this.vertexBufferKindToNumberOfComponents[s];if(void 0!==a){let e=`_int_${s}_`;this._attributesInputWGSL.push(`@location(${n}) ${e} : ${a<0?-1===a?"i32":"vec"+-a+"":1===a?"u32":"vec"+a+""},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = ${r}(vertexInputs_.${e});`),this._hasNonFloatAttribute=!0}else this._attributesInputWGSL.push(`@location(${n}) ${s} : ${r},`),this._attributesWGSL.push(`${s} : ${r},`),this._attributesConversionCodeWGSL.push(`vertexInputs.${s} = vertexInputs_.${s};`);e=""}return e}uniformProcessor(e,t,i){let r=this.uniformRegexp.exec(e);if(null!==r){let t=r[2],s=r[1];this._addUniformToLeftOverUBO(s,t,i),e=""}return e}textureProcessor(e,t,i){let r=this.textureRegexp.exec(e);if(null!==r){let s=r[1],n=r[2],a=!!r[3],o=r[4],l=o.indexOf("storage")>0,h=r[6],u=l?h.substring(0,h.indexOf(",")).trim():null,c=a?this._getArraySize(s,n,i)[2]:0,d=this._webgpuProcessingContext.availableTextures[s];if(d)c=d.textures.length;else{d={isTextureArray:c>0,isStorageTexture:l,textures:[],sampleType:t5.Float},c=c||1;for(let e=0;e0,_=cu[o],f=p?t5.Depth:"u32"===h?t5.Uint:"i32"===h?t5.Sint:t5.Float;if(d.sampleType=f,void 0===_)throw`Can't get the texture dimension corresponding to the texture function "${o}"!`;for(let i=0;i=0?` + if (internals.yFactor_ == 1.) { + fragmentInputs.position.y = internals.textureOutputHeight_ - fragmentInputs.position.y; + } + `:"";e=this._processSamplers(e,!0),t=this._processSamplers(t,!1),e=this._processCustomBuffers(e,!0),t=this._processCustomBuffers(t,!1);let r=this._buildLeftOverUBO();e=r+e,t=r+t,e=e.replace(/#define /g,"//#define "),e=this._processStridedUniformArrays(e);let s="struct VertexInputs {\n @builtin(vertex_index) vertexIndex : u32,\n @builtin(instance_index) instanceIndex : u32,\n";this._attributesInputWGSL.length>0&&(s+=this._attributesInputWGSL.join("\n")),s+="\n};\nvar vertexInputs"+(this._hasNonFloatAttribute?"_":"")+" : VertexInputs;\n",this._hasNonFloatAttribute&&(s+="struct VertexInputs_ {\n vertexIndex : u32, instanceIndex : u32,\n"+this._attributesWGSL.join("\n")+"\n};\nvar vertexInputs : VertexInputs_;\n");let n="struct FragmentInputs {\n @builtin(position) position : vec4,\n";this._varyingsWGSL.length>0&&(n+=this._varyingsWGSL.join("\n")),n+="\n};\nvar vertexOutputs : FragmentInputs;\n",e=s+n+e;let a=` + vertexInputs${this._hasNonFloatAttribute?"_":""} = input; +`;this._hasNonFloatAttribute&&(a+="vertexInputs.vertexIndex = vertexInputs_.vertexIndex;\nvertexInputs.instanceIndex = vertexInputs_.instanceIndex;\n"+this._attributesConversionCodeWGSL.join("\n")+"\n");let o=` vertexOutputs.position.y = vertexOutputs.position.y * internals.yFactor_; + return vertexOutputs;`;e=this._injectStartingAndEndingCode(e,"fn main",a,o),t=t.replace(/#define /g,"//#define "),t=(t=this._processStridedUniformArrays(t)).replace(/dpdy/g,"(-internals.yFactor_)*dpdy");let l="struct FragmentInputs {\n @builtin(position) position : vec4,\n @builtin(front_facing) frontFacing : bool,\n";this._varyingsWGSL.length>0&&(l+=this._varyingsWGSL.join("\n")),l+="\n};\nvar fragmentInputs : FragmentInputs;\n";let h="struct FragmentOutputs {\n @location(0) color : vec4,\n",u=!1,c=0;for(;!u&&!((c=t.indexOf(ch,c))<0);){let e=c;for(u=!0;c>1&&"\n"!==t.charAt(c);){if("/"===t.charAt(c)&&"/"===t.charAt(c-1)){u=!1;break}c--}c=e+ch.length}return u&&(h+=" @builtin(frag_depth) fragDepth: f32,\n"),h+="};\nvar fragmentOutputs : FragmentOutputs;\n",t=l+h+t,t=this._injectStartingAndEndingCode(t,"fn main"," fragmentInputs = input;\n "+i," return fragmentOutputs;"),this._collectBindingNames(),this._preCreateBindGroupEntries(),this.vertexBufferKindToNumberOfComponents={},{vertexCode:e,fragmentCode:t}}_generateLeftOverUBOCode(e,t){let i="",r=`struct ${e} { +`;for(let t of this._webgpuProcessingContext.leftOverUniforms){let s=t.type.replace(/^(.*?)(<.*>)?$/,"$1"),n=uZ.UniformSizes[s];if(t.length>0){if(n<=2){let n=`${e}_${this._stridedUniformArrays.length}_strided_arr`;i+=`struct ${n} { + @size(16) + el: ${s}, + }`,this._stridedUniformArrays.push(t.name),r+=` @align(16) ${t.name} : array<${n}, ${t.length}>, +`}else r+=` ${t.name} : array<${t.type}, ${t.length}>, +`}else r+=` ${t.name} : ${t.type}, +`}return r+="};\n",r=`${i} +${r}@group(${t.binding.groupIndex}) @binding(${t.binding.bindingIndex}) var uniforms : ${e}; +`}_processSamplers(e,t){let i=/var\s+(\w+Sampler)\s*:\s*(sampler|sampler_comparison)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[2],a=s.indexOf(uZ.AutoSamplerSuffix)===s.length-uZ.AutoSamplerSuffix.length?s.substring(0,s.indexOf(uZ.AutoSamplerSuffix)):null,o="sampler_comparison"===n?t4.Comparison:t4.Filtering;if(a){let e=this._webgpuProcessingContext.availableTextures[a];e&&(e.autoBindSampler=!0)}let l=this._webgpuProcessingContext.availableSamplers[s];l||(l={binding:this._webgpuProcessingContext.getNextFreeUBOBinding(),type:o},this._webgpuProcessingContext.availableSamplers[s]=l),this._addSamplerBindingDescription(s,l,t);let h=e.substring(0,r.index),u=`@group(${l.binding.groupIndex}) @binding(${l.binding.bindingIndex}) `;e=h+u+e.substring(r.index),i.lastIndex+=u.length}return e}_processCustomBuffers(e,t){let i=/var<\s*(uniform|storage)\s*(,\s*(read|read_write)\s*)?>\s+(\S+)\s*:\s*(\S+)\s*;/gm;for(;;){let r=i.exec(e);if(null===r)break;let s=r[1],n=r[3],a=r[4],o=r[5],l=this._webgpuProcessingContext.availableBuffers[a];if(!l){let e;let t="uniform"===s?u1.KnownUBOs[o]:null;t?(a=o,-1===(e=t.binding).groupIndex&&(e=this._webgpuProcessingContext.getNextFreeUBOBinding())):e=this._webgpuProcessingContext.getNextFreeUBOBinding(),l={binding:e},this._webgpuProcessingContext.availableBuffers[a]=l}this._addBufferBindingDescription(a,this._webgpuProcessingContext.availableBuffers[a],"read_write"===n?t3.Storage:"storage"===s?t3.ReadOnlyStorage:t3.Uniform,t);let h=l.binding.groupIndex,u=l.binding.bindingIndex,c=e.substring(0,r.index),d=`@group(${h}) @binding(${u}) `;e=c+d+e.substring(r.index),i.lastIndex+=d.length}return e}_processStridedUniformArrays(e){for(let t of this._stridedUniformArrays)e=e.replace(RegExp(`${t}\\s*\\[(.*)\\]`,"g"),`${t}[$1].el`);return e}}class cd{static ComputeNumMipmapLevels(e,t){return rk.R.ILog2(Math.max(e,t))+1}static GetTextureTypeFromFormat(e){switch(e){case tQ.R8Unorm:case tQ.R8Snorm:case tQ.R8Uint:case tQ.R8Sint:case tQ.RG8Unorm:case tQ.RG8Snorm:case tQ.RG8Uint:case tQ.RG8Sint:case tQ.RGBA8Unorm:case tQ.RGBA8UnormSRGB:case tQ.RGBA8Snorm:case tQ.RGBA8Uint:case tQ.RGBA8Sint:case tQ.BGRA8Unorm:case tQ.BGRA8UnormSRGB:case tQ.RGB10A2UINT:case tQ.RGB10A2Unorm:case tQ.RGB9E5UFloat:case tQ.RG11B10UFloat:case tQ.BC7RGBAUnorm:case tQ.BC7RGBAUnormSRGB:case tQ.BC6HRGBUFloat:case tQ.BC6HRGBFloat:case tQ.BC5RGUnorm:case tQ.BC5RGSnorm:case tQ.BC3RGBAUnorm:case tQ.BC3RGBAUnormSRGB:case tQ.BC2RGBAUnorm:case tQ.BC2RGBAUnormSRGB:case tQ.BC4RUnorm:case tQ.BC4RSnorm:case tQ.BC1RGBAUnorm:case tQ.BC1RGBAUnormSRGB:case tQ.ETC2RGB8Unorm:case tQ.ETC2RGB8UnormSRGB:case tQ.ETC2RGB8A1Unorm:case tQ.ETC2RGB8A1UnormSRGB:case tQ.ETC2RGBA8Unorm:case tQ.ETC2RGBA8UnormSRGB:case tQ.EACR11Unorm:case tQ.EACR11Snorm:case tQ.EACRG11Unorm:case tQ.EACRG11Snorm:case tQ.ASTC4x4Unorm:case tQ.ASTC4x4UnormSRGB:case tQ.ASTC5x4Unorm:case tQ.ASTC5x4UnormSRGB:case tQ.ASTC5x5Unorm:case tQ.ASTC5x5UnormSRGB:case tQ.ASTC6x5Unorm:case tQ.ASTC6x5UnormSRGB:case tQ.ASTC6x6Unorm:case tQ.ASTC6x6UnormSRGB:case tQ.ASTC8x5Unorm:case tQ.ASTC8x5UnormSRGB:case tQ.ASTC8x6Unorm:case tQ.ASTC8x6UnormSRGB:case tQ.ASTC8x8Unorm:case tQ.ASTC8x8UnormSRGB:case tQ.ASTC10x5Unorm:case tQ.ASTC10x5UnormSRGB:case tQ.ASTC10x6Unorm:case tQ.ASTC10x6UnormSRGB:case tQ.ASTC10x8Unorm:case tQ.ASTC10x8UnormSRGB:case tQ.ASTC10x10Unorm:case tQ.ASTC10x10UnormSRGB:case tQ.ASTC12x10Unorm:case tQ.ASTC12x10UnormSRGB:case tQ.ASTC12x12Unorm:case tQ.ASTC12x12UnormSRGB:case tQ.Stencil8:break;case tQ.R16Uint:case tQ.R16Sint:case tQ.RG16Uint:case tQ.RG16Sint:case tQ.RGBA16Uint:case tQ.RGBA16Sint:case tQ.Depth16Unorm:return 5;case tQ.R16Float:case tQ.RG16Float:case tQ.RGBA16Float:return 2;case tQ.R32Uint:case tQ.R32Sint:case tQ.RG32Uint:case tQ.RG32Sint:case tQ.RGBA32Uint:case tQ.RGBA32Sint:return 7;case tQ.R32Float:case tQ.RG32Float:case tQ.RGBA32Float:case tQ.Depth32Float:case tQ.Depth32FloatStencil8:case tQ.Depth24Plus:case tQ.Depth24PlusStencil8:return 1}return 0}static GetBlockInformationFromFormat(e){switch(e){case tQ.R8Unorm:case tQ.R8Snorm:case tQ.R8Uint:case tQ.R8Sint:return{width:1,height:1,length:1};case tQ.R16Uint:case tQ.R16Sint:case tQ.R16Float:case tQ.RG8Unorm:case tQ.RG8Snorm:case tQ.RG8Uint:case tQ.RG8Sint:return{width:1,height:1,length:2};case tQ.R32Uint:case tQ.R32Sint:case tQ.R32Float:case tQ.RG16Uint:case tQ.RG16Sint:case tQ.RG16Float:case tQ.RGBA8Unorm:case tQ.RGBA8UnormSRGB:case tQ.RGBA8Snorm:case tQ.RGBA8Uint:case tQ.RGBA8Sint:case tQ.BGRA8Unorm:case tQ.BGRA8UnormSRGB:case tQ.RGB9E5UFloat:case tQ.RGB10A2UINT:case tQ.RGB10A2Unorm:case tQ.RG11B10UFloat:break;case tQ.RG32Uint:case tQ.RG32Sint:case tQ.RG32Float:case tQ.RGBA16Uint:case tQ.RGBA16Sint:case tQ.RGBA16Float:return{width:1,height:1,length:8};case tQ.RGBA32Uint:case tQ.RGBA32Sint:case tQ.RGBA32Float:return{width:1,height:1,length:16};case tQ.Stencil8:throw"No fixed size for Stencil8 format!";case tQ.Depth16Unorm:return{width:1,height:1,length:2};case tQ.Depth24Plus:throw"No fixed size for Depth24Plus format!";case tQ.Depth24PlusStencil8:throw"No fixed size for Depth24PlusStencil8 format!";case tQ.Depth32Float:break;case tQ.Depth32FloatStencil8:return{width:1,height:1,length:5};case tQ.BC7RGBAUnorm:case tQ.BC7RGBAUnormSRGB:case tQ.BC6HRGBUFloat:case tQ.BC6HRGBFloat:case tQ.BC5RGUnorm:case tQ.BC5RGSnorm:case tQ.BC3RGBAUnorm:case tQ.BC3RGBAUnormSRGB:case tQ.BC2RGBAUnorm:case tQ.BC2RGBAUnormSRGB:return{width:4,height:4,length:16};case tQ.BC4RUnorm:case tQ.BC4RSnorm:case tQ.BC1RGBAUnorm:case tQ.BC1RGBAUnormSRGB:case tQ.ETC2RGB8Unorm:case tQ.ETC2RGB8UnormSRGB:case tQ.ETC2RGB8A1Unorm:case tQ.ETC2RGB8A1UnormSRGB:case tQ.EACR11Unorm:case tQ.EACR11Snorm:return{width:4,height:4,length:8};case tQ.ETC2RGBA8Unorm:case tQ.ETC2RGBA8UnormSRGB:case tQ.EACRG11Unorm:case tQ.EACRG11Snorm:case tQ.ASTC4x4Unorm:case tQ.ASTC4x4UnormSRGB:return{width:4,height:4,length:16};case tQ.ASTC5x4Unorm:case tQ.ASTC5x4UnormSRGB:return{width:5,height:4,length:16};case tQ.ASTC5x5Unorm:case tQ.ASTC5x5UnormSRGB:return{width:5,height:5,length:16};case tQ.ASTC6x5Unorm:case tQ.ASTC6x5UnormSRGB:return{width:6,height:5,length:16};case tQ.ASTC6x6Unorm:case tQ.ASTC6x6UnormSRGB:return{width:6,height:6,length:16};case tQ.ASTC8x5Unorm:case tQ.ASTC8x5UnormSRGB:return{width:8,height:5,length:16};case tQ.ASTC8x6Unorm:case tQ.ASTC8x6UnormSRGB:return{width:8,height:6,length:16};case tQ.ASTC8x8Unorm:case tQ.ASTC8x8UnormSRGB:return{width:8,height:8,length:16};case tQ.ASTC10x5Unorm:case tQ.ASTC10x5UnormSRGB:return{width:10,height:5,length:16};case tQ.ASTC10x6Unorm:case tQ.ASTC10x6UnormSRGB:return{width:10,height:6,length:16};case tQ.ASTC10x8Unorm:case tQ.ASTC10x8UnormSRGB:return{width:10,height:8,length:16};case tQ.ASTC10x10Unorm:case tQ.ASTC10x10UnormSRGB:return{width:10,height:10,length:16};case tQ.ASTC12x10Unorm:case tQ.ASTC12x10UnormSRGB:return{width:12,height:10,length:16};case tQ.ASTC12x12Unorm:case tQ.ASTC12x12UnormSRGB:return{width:12,height:12,length:16}}return{width:1,height:1,length:4}}static IsHardwareTexture(e){return!!e.release}static IsInternalTexture(e){return!!e.dispose}static IsImageBitmap(e){return void 0!==e.close}static IsImageBitmapArray(e){return Array.isArray(e)&&void 0!==e[0].close}static IsCompressedFormat(e){switch(e){case tQ.BC7RGBAUnormSRGB:case tQ.BC7RGBAUnorm:case tQ.BC6HRGBFloat:case tQ.BC6HRGBUFloat:case tQ.BC5RGSnorm:case tQ.BC5RGUnorm:case tQ.BC4RSnorm:case tQ.BC4RUnorm:case tQ.BC3RGBAUnormSRGB:case tQ.BC3RGBAUnorm:case tQ.BC2RGBAUnormSRGB:case tQ.BC2RGBAUnorm:case tQ.BC1RGBAUnormSRGB:case tQ.BC1RGBAUnorm:case tQ.ETC2RGB8Unorm:case tQ.ETC2RGB8UnormSRGB:case tQ.ETC2RGB8A1Unorm:case tQ.ETC2RGB8A1UnormSRGB:case tQ.ETC2RGBA8Unorm:case tQ.ETC2RGBA8UnormSRGB:case tQ.EACR11Unorm:case tQ.EACR11Snorm:case tQ.EACRG11Unorm:case tQ.EACRG11Snorm:case tQ.ASTC4x4Unorm:case tQ.ASTC4x4UnormSRGB:case tQ.ASTC5x4Unorm:case tQ.ASTC5x4UnormSRGB:case tQ.ASTC5x5Unorm:case tQ.ASTC5x5UnormSRGB:case tQ.ASTC6x5Unorm:case tQ.ASTC6x5UnormSRGB:case tQ.ASTC6x6Unorm:case tQ.ASTC6x6UnormSRGB:case tQ.ASTC8x5Unorm:case tQ.ASTC8x5UnormSRGB:case tQ.ASTC8x6Unorm:case tQ.ASTC8x6UnormSRGB:case tQ.ASTC8x8Unorm:case tQ.ASTC8x8UnormSRGB:case tQ.ASTC10x5Unorm:case tQ.ASTC10x5UnormSRGB:case tQ.ASTC10x6Unorm:case tQ.ASTC10x6UnormSRGB:case tQ.ASTC10x8Unorm:case tQ.ASTC10x8UnormSRGB:case tQ.ASTC10x10Unorm:case tQ.ASTC10x10UnormSRGB:case tQ.ASTC12x10Unorm:case tQ.ASTC12x10UnormSRGB:case tQ.ASTC12x12Unorm:case tQ.ASTC12x12UnormSRGB:return!0}return!1}static GetWebGPUTextureFormat(e,t,i=!1){switch(t){case 15:return tQ.Depth16Unorm;case 16:return tQ.Depth24Plus;case 13:return tQ.Depth24PlusStencil8;case 14:return tQ.Depth32Float;case 18:return tQ.Depth32FloatStencil8;case 19:return tQ.Stencil8;case 36492:return i?tQ.BC7RGBAUnormSRGB:tQ.BC7RGBAUnorm;case 36495:return tQ.BC6HRGBUFloat;case 36494:return tQ.BC6HRGBFloat;case 33779:return i?tQ.BC3RGBAUnormSRGB:tQ.BC3RGBAUnorm;case 33778:return i?tQ.BC2RGBAUnormSRGB:tQ.BC2RGBAUnorm;case 33777:case 33776:return i?tQ.BC1RGBAUnormSRGB:tQ.BC1RGBAUnorm;case 37808:return i?tQ.ASTC4x4UnormSRGB:tQ.ASTC4x4Unorm;case 36196:case 37492:return i?tQ.ETC2RGB8UnormSRGB:tQ.ETC2RGB8Unorm;case 37496:return i?tQ.ETC2RGBA8UnormSRGB:tQ.ETC2RGBA8Unorm}switch(e){case 3:switch(t){case 6:return tQ.R8Snorm;case 7:return tQ.RG8Snorm;case 4:throw"RGB format not supported in WebGPU";case 8:return tQ.R8Sint;case 9:return tQ.RG8Sint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return tQ.RGBA8Sint;default:return tQ.RGBA8Snorm}case 0:switch(t){case 6:return tQ.R8Unorm;case 7:return tQ.RG8Unorm;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";case 5:return i?tQ.RGBA8UnormSRGB:tQ.RGBA8Unorm;case 12:return i?tQ.BGRA8UnormSRGB:tQ.BGRA8Unorm;case 8:return tQ.R8Uint;case 9:return tQ.RG8Uint;case 10:throw"RGB_INTEGER format not supported in WebGPU";case 11:return tQ.RGBA8Uint;case 0:throw"TEXTUREFORMAT_ALPHA format not supported in WebGPU";case 1:throw"TEXTUREFORMAT_LUMINANCE format not supported in WebGPU";case 2:throw"TEXTUREFORMAT_LUMINANCE_ALPHA format not supported in WebGPU";default:return tQ.RGBA8Unorm}case 4:switch(t){case 8:return tQ.R16Sint;case 9:return tQ.RG16Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tQ.RGBA16Sint}case 5:switch(t){case 8:return tQ.R16Uint;case 9:return tQ.RG16Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tQ.RGBA16Uint}case 6:switch(t){case 8:return tQ.R32Sint;case 9:return tQ.RG32Sint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tQ.RGBA32Sint}case 7:switch(t){case 8:return tQ.R32Uint;case 9:return tQ.RG32Uint;case 10:throw"TEXTUREFORMAT_RGB_INTEGER format not supported in WebGPU";default:return tQ.RGBA32Uint}case 1:switch(t){case 6:return tQ.R32Float;case 7:return tQ.RG32Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return tQ.RGBA32Float}case 2:switch(t){case 6:return tQ.R16Float;case 7:return tQ.RG16Float;case 4:throw"TEXTUREFORMAT_RGB format not supported in WebGPU";default:return tQ.RGBA16Float}case 10:throw"TEXTURETYPE_UNSIGNED_SHORT_5_6_5 format not supported in WebGPU";case 13:switch(t){case 5:default:return tQ.RG11B10UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV"}case 14:switch(t){case 5:default:return tQ.RGB9E5UFloat;case 11:throw"TEXTUREFORMAT_RGBA_INTEGER format not supported in WebGPU when type is TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV"}case 8:throw"TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 format not supported in WebGPU";case 9:throw"TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 format not supported in WebGPU";case 11:switch(t){case 5:default:return tQ.RGB10A2Unorm;case 11:return tQ.RGB10A2UINT}}return i?tQ.RGBA8UnormSRGB:tQ.RGBA8Unorm}static GetNumChannelsFromWebGPUTextureFormat(e){switch(e){case tQ.R8Unorm:case tQ.R8Snorm:case tQ.R8Uint:case tQ.R8Sint:case tQ.BC4RUnorm:case tQ.BC4RSnorm:case tQ.R16Uint:case tQ.R16Sint:case tQ.Depth16Unorm:case tQ.R16Float:case tQ.R32Uint:case tQ.R32Sint:case tQ.R32Float:case tQ.Depth32Float:case tQ.Stencil8:case tQ.Depth24Plus:case tQ.EACR11Unorm:case tQ.EACR11Snorm:return 1;case tQ.RG8Unorm:case tQ.RG8Snorm:case tQ.RG8Uint:case tQ.RG8Sint:case tQ.Depth32FloatStencil8:case tQ.BC5RGUnorm:case tQ.BC5RGSnorm:case tQ.RG16Uint:case tQ.RG16Sint:case tQ.RG16Float:case tQ.RG32Uint:case tQ.RG32Sint:case tQ.RG32Float:case tQ.Depth24PlusStencil8:case tQ.EACRG11Unorm:case tQ.EACRG11Snorm:return 2;case tQ.RGB9E5UFloat:case tQ.RG11B10UFloat:case tQ.BC6HRGBUFloat:case tQ.BC6HRGBFloat:case tQ.ETC2RGB8Unorm:case tQ.ETC2RGB8UnormSRGB:return 3;case tQ.RGBA8Unorm:case tQ.RGBA8UnormSRGB:case tQ.RGBA8Snorm:case tQ.RGBA8Uint:case tQ.RGBA8Sint:case tQ.BGRA8Unorm:case tQ.BGRA8UnormSRGB:case tQ.RGB10A2UINT:case tQ.RGB10A2Unorm:case tQ.BC7RGBAUnorm:case tQ.BC7RGBAUnormSRGB:case tQ.BC3RGBAUnorm:case tQ.BC3RGBAUnormSRGB:case tQ.BC2RGBAUnorm:case tQ.BC2RGBAUnormSRGB:case tQ.BC1RGBAUnorm:case tQ.BC1RGBAUnormSRGB:case tQ.RGBA16Uint:case tQ.RGBA16Sint:case tQ.RGBA16Float:case tQ.RGBA32Uint:case tQ.RGBA32Sint:case tQ.RGBA32Float:case tQ.ETC2RGB8A1Unorm:case tQ.ETC2RGB8A1UnormSRGB:case tQ.ETC2RGBA8Unorm:case tQ.ETC2RGBA8UnormSRGB:case tQ.ASTC4x4Unorm:case tQ.ASTC4x4UnormSRGB:case tQ.ASTC5x4Unorm:case tQ.ASTC5x4UnormSRGB:case tQ.ASTC5x5Unorm:case tQ.ASTC5x5UnormSRGB:case tQ.ASTC6x5Unorm:case tQ.ASTC6x5UnormSRGB:case tQ.ASTC6x6Unorm:case tQ.ASTC6x6UnormSRGB:case tQ.ASTC8x5Unorm:case tQ.ASTC8x5UnormSRGB:case tQ.ASTC8x6Unorm:case tQ.ASTC8x6UnormSRGB:case tQ.ASTC8x8Unorm:case tQ.ASTC8x8UnormSRGB:case tQ.ASTC10x5Unorm:case tQ.ASTC10x5UnormSRGB:case tQ.ASTC10x6Unorm:case tQ.ASTC10x6UnormSRGB:case tQ.ASTC10x8Unorm:case tQ.ASTC10x8UnormSRGB:case tQ.ASTC10x10Unorm:case tQ.ASTC10x10UnormSRGB:case tQ.ASTC12x10Unorm:case tQ.ASTC12x10UnormSRGB:case tQ.ASTC12x12Unorm:case tQ.ASTC12x12UnormSRGB:return 4}throw`Unknown format ${e}!`}static HasStencilAspect(e){switch(e){case tQ.Stencil8:case tQ.Depth32FloatStencil8:case tQ.Depth24PlusStencil8:return!0}return!1}static HasDepthAndStencilAspects(e){switch(e){case tQ.Depth32FloatStencil8:case tQ.Depth24PlusStencil8:return!0}return!1}static GetDepthFormatOnly(e){switch(e){case tQ.Depth16Unorm:return tQ.Depth16Unorm;case tQ.Depth24Plus:case tQ.Depth24PlusStencil8:return tQ.Depth24Plus;case tQ.Depth32Float:case tQ.Depth32FloatStencil8:return tQ.Depth32Float}return e}static GetSample(e){return e>1?4:1}}class cp{get underlyingResource(){return this._webgpuTexture}getMSAATexture(e=0){var t,i;return null!==(i=null===(t=this._webgpuMSAATexture)||void 0===t?void 0:t[e])&&void 0!==i?i:null}setMSAATexture(e,t=-1){this._webgpuMSAATexture||(this._webgpuMSAATexture=[]),-1===t&&(t=this._webgpuMSAATexture.length),this._webgpuMSAATexture[t]=e}releaseMSAATexture(){if(this._webgpuMSAATexture){for(let e of this._webgpuMSAATexture)null==e||e.destroy();this._webgpuMSAATexture=null}}constructor(e=null){this.format=tQ.RGBA8Unorm,this.textureUsages=0,this.textureAdditionalUsages=0,this._webgpuTexture=e,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}set(e){this._webgpuTexture=e}setUsage(e,t,i,r,s,n,a,o){let l=tK.E2d,h=1;r?(l=i?tK.CubeArray:tK.Cube,h=6*(o||1)):s?l=tK.E3d:i&&(l=tK.E2dArray,h=o);let u=cd.GetDepthFormatOnly(this.format),c=cd.HasDepthAndStencilAspects(this.format)?t$.DepthOnly:t$.All;this.createView({label:`TextureView${s?"3D":r?"Cube":"2D"}${i?"_Array"+h:""}_${n}x${a}_${t?"wmips":"womips"}_${this.format}_${l}`,format:u,dimension:l,mipLevelCount:t?rk.R.ILog2(Math.max(n,a))+1:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:h,aspect:c})}createView(e,t=!1){if(this.view=this._webgpuTexture.createView(e),t&&e){let t=e.mipLevelCount;e.mipLevelCount=1,this.viewForWriting=this._webgpuTexture.createView(e),e.mipLevelCount=t}}reset(){this._webgpuTexture=null,this._webgpuMSAATexture=null,this.view=null,this.viewForWriting=null}release(){var e,t;null===(e=this._webgpuTexture)||void 0===e||e.destroy(),this.releaseMSAATexture(),null===(t=this._copyInvertYTempTexture)||void 0===t||t.destroy(),this.reset()}}let c_=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(location = 0) out vec2 vTex; + + void main() { + vTex = tex[gl_VertexIndex]; + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,cf=` + layout(set = 0, binding = 0) uniform sampler imgSampler; + layout(set = 0, binding = 1) uniform texture2D img; + + layout(location = 0) in vec2 vTex; + layout(location = 0) out vec4 outColor; + + void main() { + outColor = texture(sampler2D(img, imgSampler), vTex); + } + `,cm=` + #extension GL_EXT_samplerless_texture_functions : enable + + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + const vec2 tex[4] = vec2[4](vec2(0.0f, 0.0f), vec2(1.0f, 0.0f), vec2(0.0f, 1.0f), vec2(1.0f, 1.0f)); + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) out flat ivec2 vTextureSize; + #endif + + void main() { + #ifdef INVERTY + vTextureSize = textureSize(img, 0); + #endif + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,cg=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, vTextureSize.y - gl_FragCoord.y), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,cv=` + #extension GL_EXT_samplerless_texture_functions : enable + + layout(set = 0, binding = 0) uniform texture2D img; + layout(set = 0, binding = 1) uniform Params { + float ofstX; + float ofstY; + float width; + float height; + }; + + #ifdef INVERTY + layout(location = 0) in flat ivec2 vTextureSize; + #endif + layout(location = 0) out vec4 outColor; + + void main() { + if (gl_FragCoord.x < ofstX || gl_FragCoord.x >= ofstX + width) { + discard; + } + if (gl_FragCoord.y < ofstY || gl_FragCoord.y >= ofstY + height) { + discard; + } + #ifdef INVERTY + vec4 color = texelFetch(img, ivec2(gl_FragCoord.x, ofstY + height - (gl_FragCoord.y - ofstY)), 0); + #else + vec4 color = texelFetch(img, ivec2(gl_FragCoord.xy), 0); + #endif + #ifdef PREMULTIPLYALPHA + color.rgb *= color.a; + #endif + outColor = color; + } + `,cx=` + const vec2 pos[4] = vec2[4](vec2(-1.0f, 1.0f), vec2(1.0f, 1.0f), vec2(-1.0f, -1.0f), vec2(1.0f, -1.0f)); + + void main() { + gl_Position = vec4(pos[gl_VertexIndex], 0.0, 1.0); + } + `,cT=` + layout(set = 0, binding = 0) uniform Uniforms { + uniform vec4 color; + }; + + layout(location = 0) out vec4 outColor; + + void main() { + outColor = color; + } + `,cS=` + struct VertexOutput { + @builtin(position) Position : vec4, + @location(0) fragUV : vec2 + } + + @vertex + fn main( + @builtin(vertex_index) VertexIndex : u32 + ) -> VertexOutput { + var pos = array, 4>( + vec2(-1.0, 1.0), + vec2( 1.0, 1.0), + vec2(-1.0, -1.0), + vec2( 1.0, -1.0) + ); + var tex = array, 4>( + vec2(0.0, 0.0), + vec2(1.0, 0.0), + vec2(0.0, 1.0), + vec2(1.0, 1.0) + ); + + var output: VertexOutput; + + output.Position = vec4(pos[VertexIndex], 0.0, 1.0); + output.fragUV = tex[VertexIndex]; + + return output; + } + `,cE=` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2 + ) -> @location(0) vec4 { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, fragUV); + } + `,cC=` + @group(0) @binding(0) var videoSampler: sampler; + @group(0) @binding(1) var videoTexture: texture_external; + + @fragment + fn main( + @location(0) fragUV: vec2 + ) -> @location(0) vec4 { + return textureSampleBaseClampToEdge(videoTexture, videoSampler, vec2(fragUV.x, 1.0 - fragUV.y)); + } + `;(eT=iT||(iT={}))[eT.MipMap=0]="MipMap",eT[eT.InvertYPremultiplyAlpha=1]="InvertYPremultiplyAlpha",eT[eT.Clear=2]="Clear",eT[eT.InvertYPremultiplyAlphaWithOfst=3]="InvertYPremultiplyAlphaWithOfst",(eS=iS||(iS={}))[eS.DontInvertY=0]="DontInvertY",eS[eS.InvertY=1]="InvertY";let cb=[{vertex:c_,fragment:cf},{vertex:cm,fragment:cg},{vertex:cx,fragment:cT},{vertex:cm,fragment:cv}],cy={"":0,r8unorm:1,r8uint:2,r8sint:3,r16uint:4,r16sint:5,r16float:6,rg8unorm:7,rg8uint:8,rg8sint:9,r32uint:10,r32sint:11,r32float:12,rg16uint:13,rg16sint:14,rg16float:15,rgba8unorm:16,"rgba8unorm-srgb":17,rgba8uint:18,rgba8sint:19,bgra8unorm:20,"bgra8unorm-srgb":21,rgb10a2uint:22,rgb10a2unorm:23,rg32uint:24,rg32sint:25,rg32float:26,rgba16uint:27,rgba16sint:28,rgba16float:29,rgba32uint:30,rgba32sint:31,rgba32float:32,stencil8:33,depth16unorm:34,depth24plus:35,"depth24plus-stencil8":36,depth32float:37,"depth32float-stencil8":38};class cA{constructor(e,t,i,r,s,n){if(this._pipelines={},this._compiledShaders=[],this._videoPipelines={},this._videoCompiledShaders=[],this._deferredReleaseTextures=[],this._engine=e,this._device=t,this._glslang=i,this._tintWASM=r,this._bufferManager=s,-1!==n.indexOf(tW.RG11B10UFloatRenderable)){let e=Object.keys(cy);cy[tQ.RG11B10UFloat]=cy[e[e.length-1]]+1}this._mipmapSampler=t.createSampler({minFilter:tJ.Linear}),this._videoSampler=t.createSampler({minFilter:tJ.Linear}),this._ubCopyWithOfst=this._bufferManager.createBuffer(16,tX.Uniform|tX.CopyDst,"UBCopyWithOffset").underlyingResource,this._getPipeline(tQ.RGBA8Unorm),this._getVideoPipeline(tQ.RGBA8Unorm)}_getPipeline(e,t=iT.MipMap,i){let r=t===iT.MipMap?1:t===iT.InvertYPremultiplyAlpha?((i.invertY?1:0)<<1)+((i.premultiplyAlpha?1:0)<<2):t===iT.Clear?8:t===iT.InvertYPremultiplyAlphaWithOfst?((i.invertY?1:0)<<4)+((i.premultiplyAlpha?1:0)<<5):0;this._pipelines[e]||(this._pipelines[e]=[]);let s=this._pipelines[e][r];if(!s){let n="#version 450\n";(t===iT.InvertYPremultiplyAlpha||t===iT.InvertYPremultiplyAlphaWithOfst)&&(i.invertY&&(n+="#define INVERTY\n"),i.premultiplyAlpha&&(n+="#define PREMULTIPLYALPHA\n"));let a=this._compiledShaders[r];if(!a){let e=this._glslang.compileGLSL(n+cb[t].vertex,"vertex"),i=this._glslang.compileGLSL(n+cb[t].fragment,"fragment");this._tintWASM&&(e=this._tintWASM.convertSpirV2WGSL(e),i=this._tintWASM.convertSpirV2WGSL(i));let s=this._device.createShaderModule({code:e}),o=this._device.createShaderModule({code:i});a=this._compiledShaders[r]=[s,o]}let o=this._device.createRenderPipeline({layout:t9.Auto,vertex:{module:a[0],entryPoint:"main"},fragment:{module:a[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:ie.TriangleStrip,stripIndexFormat:il.Uint16}});s=this._pipelines[e][r]=[o,o.getBindGroupLayout(0)]}return s}_getVideoPipeline(e,t=iS.DontInvertY){let i=t===iS.InvertY?1:0;this._videoPipelines[e]||(this._videoPipelines[e]=[]);let r=this._videoPipelines[e][i];if(!r){let t=this._videoCompiledShaders[i];if(!t){let e=this._device.createShaderModule({code:cS}),r=this._device.createShaderModule({code:0===i?cE:cC});t=this._videoCompiledShaders[i]=[e,r]}let s=this._device.createRenderPipeline({label:`BabylonWebGPUDevice${this._engine.uniqueId}_CopyVideoToTexture_${e}_${0===i?"DontInvertY":"InvertY"}`,layout:t9.Auto,vertex:{module:t[0],entryPoint:"main"},fragment:{module:t[1],entryPoint:"main",targets:[{format:e}]},primitive:{topology:ie.TriangleStrip,stripIndexFormat:il.Uint16}});r=this._videoPipelines[e][i]=[s,s.getBindGroupLayout(0)]}return r}setCommandEncoder(e){this._commandEncoderForCreation=e}copyVideoToTexture(e,t,i,r=!1,s){var n,a,o,l;let h=void 0===s,[u,c]=this._getVideoPipeline(i,r?iS.InvertY:iS.DontInvertY);h&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`copy video to texture - invertY=${r}`);let d={colorAttachments:[{view:t._hardwareTexture.underlyingResource.createView({format:i,dimension:tK.E2d,mipLevelCount:1,baseArrayLayer:0,baseMipLevel:0,arrayLayerCount:1,aspect:t$.All}),loadOp:ip.Load,storeOp:i_.Store}]},p=s.beginRenderPass(d),_={layout:c,entries:[{binding:0,resource:this._videoSampler},{binding:1,resource:this._device.importExternalTexture({source:e.underlyingResource})}]},f=this._device.createBindGroup(_);p.setPipeline(u),p.setBindGroup(0,f),p.draw(4,1,0,0),p.end(),null===(l=(o=s).popDebugGroup)||void 0===l||l.call(o),h&&(this._device.queue.submit([s.finish()]),s=null)}invertYPreMultiplyAlpha(e,t,i,r,s=!1,n=!1,a=0,o=0,l=1,h=0,u=0,c=0,d=0,p,_){var f,m,g,v,x,T;let S;let E=0!==c,C=void 0===p,[b,y]=this._getPipeline(r,E?iT.InvertYPremultiplyAlphaWithOfst:iT.InvertYPremultiplyAlpha,{invertY:s,premultiplyAlpha:n});if(a=Math.max(a,0),C&&(p=this._device.createCommandEncoder({})),null===(m=(f=p).pushDebugGroup)||void 0===m||m.call(f,`internal process texture - invertY=${s} premultiplyAlpha=${n}`),cd.IsHardwareTexture(e)?(S=e.underlyingResource,s&&!n&&1===l&&0===a||(e=void 0)):(S=e,e=void 0),!S)return;E&&this._bufferManager.setRawData(this._ubCopyWithOfst,0,new Float32Array([h,u,c,d]),0,16);let A=e,R=null!==(g=null==A?void 0:A._copyInvertYTempTexture)&&void 0!==g?g:this.createTexture({width:t,height:i,layers:1},!1,!1,!1,!1,!1,r,1,p,tq.CopySrc|tq.RenderAttachment|tq.TextureBinding,void 0,"TempTextureForCopyWithInvertY"),P=null!==(v=null==A?void 0:A._copyInvertYRenderPassDescr)&&void 0!==v?v:{colorAttachments:[{view:R.createView({format:r,dimension:tK.E2d,baseMipLevel:0,mipLevelCount:1,arrayLayerCount:1,baseArrayLayer:0}),loadOp:ip.Load,storeOp:i_.Store}]},I=p.beginRenderPass(P),M=E?null==A?void 0:A._copyInvertYBindGroupWithOfst:null==A?void 0:A._copyInvertYBindGroup;if(!M){let e={layout:y,entries:[{binding:0,resource:S.createView({format:r,dimension:tK.E2d,baseMipLevel:o,mipLevelCount:1,arrayLayerCount:l,baseArrayLayer:a})}]};E&&e.entries.push({binding:1,resource:{buffer:this._ubCopyWithOfst}}),M=this._device.createBindGroup(e)}I.setPipeline(b),I.setBindGroup(0,M),I.draw(4,1,0,0),I.end(),p.copyTextureToTexture({texture:R},{texture:S,mipLevel:o,origin:{x:0,y:0,z:a}},{width:t,height:i,depthOrArrayLayers:1}),A?(A._copyInvertYTempTexture=R,A._copyInvertYRenderPassDescr=P,E?A._copyInvertYBindGroupWithOfst=M:A._copyInvertYBindGroup=M):this._deferredReleaseTextures.push([R,null]),null===(T=(x=p).popDebugGroup)||void 0===T||T.call(x),C&&(this._device.queue.submit([p.finish()]),p=null)}copyWithInvertY(e,t,i,r){var s,n,a,o;let l=void 0===r,[h,u]=this._getPipeline(t,iT.InvertYPremultiplyAlpha,{invertY:!0,premultiplyAlpha:!1});l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,"internal copy texture with invertY");let c=r.beginRenderPass(i),d=this._device.createBindGroup({layout:u,entries:[{binding:0,resource:e}]});c.setPipeline(h),c.setBindGroup(0,d),c.draw(4,1,0,0),c.end(),null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}createTexture(e,t=!1,i=!1,r=!1,s=!1,n=!1,a=tQ.RGBA8Unorm,o=1,l,h=-1,u=0,c){o=cd.GetSample(o);let d=e.layers||1,p={width:e.width,height:e.height,depthOrArrayLayers:d},_=cy[a]?tq.RenderAttachment:0,f=cd.IsCompressedFormat(a),m=t?cd.ComputeNumMipmapLevels(e.width,e.height):1,g=h>=0?h:tq.CopySrc|tq.CopyDst|tq.TextureBinding;u|=t&&!f?tq.CopySrc|_:0,f||n||(u|=_|tq.CopyDst);let v=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_Texture${n?"3D":"2D"}_${c?c+"_":""}${p.width}x${p.height}x${p.depthOrArrayLayers}_${t?"wmips":"womips"}_${a}_samples${o}`,size:p,dimension:n?tj.E3d:tj.E2d,format:a,usage:g|u,sampleCount:o,mipLevelCount:m});return cd.IsImageBitmap(e)&&(this.updateTexture(e,v,e.width,e.height,d,a,0,0,r,s,0,0),t&&i&&this.generateMipmaps(v,a,m,0,l)),v}createCubeTexture(e,t=!1,i=!1,r=!1,s=!1,n=tQ.RGBA8Unorm,a=1,o,l=-1,h=0,u){a=cd.GetSample(a);let c=cd.IsImageBitmapArray(e)?e[0].width:e.width,d=cd.IsImageBitmapArray(e)?e[0].height:e.height,p=cy[n]?tq.RenderAttachment:0,_=cd.IsCompressedFormat(n),f=t?cd.ComputeNumMipmapLevels(c,d):1,m=l>=0?l:tq.CopySrc|tq.CopyDst|tq.TextureBinding;h|=t&&!_?tq.CopySrc|p:0,_||(h|=p|tq.CopyDst);let g=this._device.createTexture({label:`BabylonWebGPUDevice${this._engine.uniqueId}_TextureCube_${u?u+"_":""}${c}x${d}x6_${t?"wmips":"womips"}_${n}_samples${a}`,size:{width:c,height:d,depthOrArrayLayers:6},dimension:tj.E2d,format:n,usage:m|h,sampleCount:a,mipLevelCount:f});return cd.IsImageBitmapArray(e)&&(this.updateCubeTextures(e,g,c,d,n,r,s,0,0),t&&i&&this.generateCubeMipmaps(g,n,f,o)),g}generateCubeMipmaps(e,t,i,r){var s,n,a,o;let l=void 0===r;l&&(r=this._device.createCommandEncoder({})),null===(n=(s=r).pushDebugGroup)||void 0===n||n.call(s,`create cube mipmaps - ${i} levels`);for(let s=0;s<6;++s)this.generateMipmaps(e,t,i,s,r);null===(o=(a=r).popDebugGroup)||void 0===o||o.call(a),l&&(this._device.queue.submit([r.finish()]),r=null)}generateMipmaps(e,t,i,r=0,s){var n,a,o,l,h,u,c,d;let p;let _=void 0===s,[f,m]=this._getPipeline(t);if(r=Math.max(r,0),_&&(s=this._device.createCommandEncoder({})),null===(a=(n=s).pushDebugGroup)||void 0===a||a.call(n,`create mipmaps for face #${r} - ${i} levels`),cd.IsHardwareTexture(e)?(p=e.underlyingResource,e._mipmapGenRenderPassDescr=e._mipmapGenRenderPassDescr||[],e._mipmapGenBindGroup=e._mipmapGenBindGroup||[]):(p=e,e=void 0),!p)return;let g=e;for(let e=1;e15728640;)this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,15728640),h+=15728640;this._device.queue.writeBuffer(n,t+h,i.buffer,a+h,s-h)}_getHalfFloatAsFloatRGBAArrayBuffer(e,t,i){i||(i=new Float32Array(e));let r=new Uint16Array(t);for(;e--;)i[e]=uT(r[e]);return i}readDataFromBuffer(e,t,i,r,s,n,a=0,o=0,l=null,h=!0,u=!1){let c=1===a?2:2===a?1:0,d=this._engine.uniqueId;return new Promise((i,p)=>{e.mapAsync(tY.Read,o,t).then(()=>{let d=e.getMappedRange(o,t),p=l;if(u)p=null===p?(0,ul.A)(a,t,!0,d):(0,ul.A)(a,p.buffer,void 0,d);else if(null===p)switch(c){case 0:(p=new Uint8Array(t)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d);break;case 2:(p=new Float32Array(t/4)).set(new Float32Array(d))}else switch(c){case 0:(p=new Uint8Array(p.buffer)).set(new Uint8Array(d));break;case 1:p=this._getHalfFloatAsFloatRGBAArrayBuffer(t/2,d,l);break;case 2:(p=new Float32Array(p.buffer)).set(new Float32Array(d))}if(s!==n){1!==c||u||(s*=2,n*=2);let e=new Uint8Array(p.buffer),t=s,i=0;for(let a=1;a{this._engine.isDisposed||this._engine.uniqueId!==d?i(new Uint8Array):p(e)})})}releaseBuffer(e){return cP._IsGPUBuffer(e)?(this._deferredReleaseBuffers.push(e),!0):(e.references--,0===e.references&&(this._deferredReleaseBuffers.push(e.underlyingResource),!0))}destroyDeferredBuffers(){for(let e=0;e1?4:1;return cI[e.samplingMode]+cM[(e._comparisonFunction||514)-512+1]+cD[e.samplingMode]+((null!==(t=e._cachedWrapU)&&void 0!==t?t:1)<<8)+((null!==(i=e._cachedWrapV)&&void 0!==i?i:1)<<10)+((null!==(r=e._cachedWrapR)&&void 0!==r?r:1)<<12)+((e.useMipMaps?1:0)<<14)+(s<<15)}static _GetSamplerFilterDescriptor(e,t){let i,r,s,n,a;let o=e.useMipMaps;switch(e.samplingMode){case 11:i=tJ.Linear,r=tJ.Linear,s=tJ.Nearest,o||(n=a=0);break;case 3:case 3:i=tJ.Linear,r=tJ.Linear,o?s=tJ.Linear:(s=tJ.Nearest,n=a=0);break;case 8:i=tJ.Nearest,r=tJ.Nearest,o?s=tJ.Linear:(s=tJ.Nearest,n=a=0);break;case 4:i=tJ.Nearest,r=tJ.Nearest,s=tJ.Nearest,o||(n=a=0);break;case 5:i=tJ.Nearest,r=tJ.Linear,s=tJ.Nearest,o||(n=a=0);break;case 6:i=tJ.Nearest,r=tJ.Linear,o?s=tJ.Linear:(s=tJ.Nearest,n=a=0);break;case 7:i=tJ.Nearest,r=tJ.Linear,s=tJ.Nearest,n=a=0;break;case 1:case 1:default:i=tJ.Nearest,r=tJ.Nearest,s=tJ.Nearest,n=a=0;break;case 9:i=tJ.Linear,r=tJ.Nearest,s=tJ.Nearest,o||(n=a=0);break;case 10:i=tJ.Linear,r=tJ.Nearest,o?s=tJ.Linear:(s=tJ.Nearest,n=a=0);break;case 2:case 2:i=tJ.Linear,r=tJ.Linear,s=tJ.Nearest,n=a=0;break;case 12:i=tJ.Linear,r=tJ.Nearest,s=tJ.Nearest,n=a=0}return t>1&&(0!==n||0!==a)&&s!==tJ.Nearest?{magFilter:tJ.Linear,minFilter:tJ.Linear,mipmapFilter:tJ.Linear,anisotropyEnabled:!0}:{magFilter:i,minFilter:r,mipmapFilter:s,lodMinClamp:n,lodMaxClamp:a}}static _GetWrappingMode(e){switch(e){case 1:break;case 0:return tZ.ClampToEdge;case 2:return tZ.MirrorRepeat}return tZ.Repeat}static _GetSamplerWrappingDescriptor(e){return{addressModeU:this._GetWrappingMode(e._cachedWrapU),addressModeV:this._GetWrappingMode(e._cachedWrapV),addressModeW:this._GetWrappingMode(e._cachedWrapR)}}static _GetSamplerDescriptor(e,t){let i=e.useMipMaps&&e._cachedAnisotropicFilteringLevel&&e._cachedAnisotropicFilteringLevel>1?4:1,r=this._GetSamplerFilterDescriptor(e,i);return Object.assign(Object.assign(Object.assign({label:t},r),this._GetSamplerWrappingDescriptor(e)),{compare:e._comparisonFunction?cO.GetCompareFunction(e._comparisonFunction):void 0,maxAnisotropy:r.anisotropyEnabled?i:1})}static GetCompareFunction(e){switch(e){case 519:return t1.Always;case 514:return t1.Equal;case 516:return t1.Greater;case 518:return t1.GreaterEqual;case 513:default:return t1.Less;case 515:return t1.LessEqual;case 512:return t1.Never;case 517:return t1.NotEqual}}getSampler(e,t=!1,i=0,r){if(this.disabled)return this._device.createSampler(cO._GetSamplerDescriptor(e,r));t?i=0:0===i&&(i=cO.GetSamplerHashCode(e));let s=t?void 0:this._samplers[i];return s||(s=this._device.createSampler(cO._GetSamplerDescriptor(e,r)),t||(this._samplers[i]=s)),s}}(eE=iE||(iE={}))[eE.StencilReadMask=0]="StencilReadMask",eE[eE.StencilWriteMask=1]="StencilWriteMask",eE[eE.DepthBias=2]="DepthBias",eE[eE.DepthBiasSlopeScale=3]="DepthBiasSlopeScale",eE[eE.DepthStencilState=4]="DepthStencilState",eE[eE.MRTAttachments1=5]="MRTAttachments1",eE[eE.MRTAttachments2=6]="MRTAttachments2",eE[eE.RasterizationState=7]="RasterizationState",eE[eE.ColorStates=8]="ColorStates",eE[eE.ShaderStage=9]="ShaderStage",eE[eE.TextureStage=10]="TextureStage",eE[eE.VertexState=11]="VertexState",eE[eE.NumStates=12]="NumStates";let cN={0:1,1:2,768:3,769:4,770:5,771:6,772:7,773:8,774:9,775:10,776:11,32769:12,32770:13,32771:12,32772:13},cF={0:0,7680:1,7681:2,7682:3,7683:4,5386:5,34055:6,34056:7},cL={[sm.o.PositionKind]:!0,[sm.o.NormalKind]:!0,[sm.o.TangentKind]:!0,[sm.o.UVKind]:!0,[sm.o.UV2Kind]:!0,[sm.o.UV3Kind]:!0,[sm.o.UV4Kind]:!0,[sm.o.UV5Kind]:!0,[sm.o.UV6Kind]:!0,[sm.o.ColorKind]:!0,[sm.o.ColorInstanceKind]:!0,[sm.o.MatricesIndicesKind]:!0,[sm.o.MatricesWeightsKind]:!0,[sm.o.MatricesIndicesExtraKind]:!0,[sm.o.MatricesWeightsExtraKind]:!0};class cw{static _IsSignedType(e){switch(e){case sm.o.BYTE:case sm.o.SHORT:case sm.o.INT:case sm.o.FLOAT:return!0;case sm.o.UNSIGNED_BYTE:case sm.o.UNSIGNED_SHORT:case sm.o.UNSIGNED_INT:return!1;default:throw Error(`Invalid type '${e}'`)}}constructor(e,t){this.mrtTextureCount=0,this._device=e,this._useTextureStage=!0,this._states=Array(30),this._statesLength=0,this._stateDirtyLowestIndex=0,this._emptyVertexBuffer=t,this._mrtFormats=[],this._parameter={token:void 0,pipeline:null},this.disabled=!1,this.vertexBuffers=[],this._kMaxVertexBufferStride=e.limits.maxVertexBufferArrayStride||2048,this.reset()}reset(){this._isDirty=!0,this.vertexBuffers.length=0,this.setAlphaToCoverage(!1),this.resetDepthCullingState(),this.setClampDepth(!1),this.setDepthBias(0),this._webgpuColorFormat=[tQ.BGRA8Unorm],this.setColorFormat(tQ.BGRA8Unorm),this.setMRT([]),this.setAlphaBlendEnabled(!1),this.setAlphaBlendFactors([null,null,null,null],[null,null]),this.setWriteMask(15),this.setDepthStencilFormat(tQ.Depth24PlusStencil8),this.setStencilEnabled(!1),this.resetStencilState(),this.setBuffers(null,null,null),this._setTextureState(0)}get colorFormats(){return this._mrtAttachments1>0?this._mrtFormats:this._webgpuColorFormat}getRenderPipeline(e,t,i,r=0){if(i=cd.GetSample(i),this.disabled){let s=cw._GetTopology(e);return this._setVertexState(t),this._setTextureState(r),this._parameter.pipeline=this._createRenderPipeline(t,s,i),cw.NumCacheMiss++,cw._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}if(this._setShaderStage(t.uniqueId),this._setRasterizationState(e,i),this._setColorStates(),this._setDepthStencilState(),this._setVertexState(t),this._setTextureState(r),this.lastStateDirtyLowestIndex=this._stateDirtyLowestIndex,!this._isDirty&&this._parameter.pipeline)return this._stateDirtyLowestIndex=this._statesLength,cw.NumCacheHitWithoutHash++,this._parameter.pipeline;if(this._getRenderPipeline(this._parameter),this._isDirty=!1,this._stateDirtyLowestIndex=this._statesLength,this._parameter.pipeline)return cw.NumCacheHitWithHash++,this._parameter.pipeline;let s=cw._GetTopology(e);return this._parameter.pipeline=this._createRenderPipeline(t,s,i),this._setRenderPipeline(this._parameter),cw.NumCacheMiss++,cw._NumPipelineCreationCurrentFrame++,this._parameter.pipeline}endFrame(){cw.NumPipelineCreationLastFrame=cw._NumPipelineCreationCurrentFrame,cw._NumPipelineCreationCurrentFrame=0}setAlphaToCoverage(e){this._alphaToCoverageEnabled=e}setFrontFace(e){this._frontFace=e}setCullEnabled(e){this._cullEnabled=e}setCullFace(e){this._cullFace=e}setClampDepth(e){this._clampDepth=e}resetDepthCullingState(){this.setDepthCullingState(!1,2,1,0,0,!0,!0,519)}setDepthCullingState(e,t,i,r,s,n,a,o){this._depthWriteEnabled=a,this._depthTestEnabled=n,this._depthCompare=(null!=o?o:519)-512,this._cullFace=i,this._cullEnabled=e,this._frontFace=t,this.setDepthBiasSlopeScale(r),this.setDepthBias(s)}setDepthBias(e){this._depthBias!==e&&(this._depthBias=e,this._states[iE.DepthBias]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthBias))}setDepthBiasSlopeScale(e){this._depthBiasSlopeScale!==e&&(this._depthBiasSlopeScale=e,this._states[iE.DepthBiasSlopeScale]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthBiasSlopeScale))}setColorFormat(e){this._webgpuColorFormat[0]=e,this._colorFormat=cy[null!=e?e:""]}setMRTAttachments(e){this.mrtAttachments=e;let t=0;for(let i=0;i10)throw"Can't handle more than 10 attachments for a MRT in cache render pipeline!";this.mrtTextureArray=e,this.mrtTextureCount=t,this._mrtEnabledMask=65535;let s=[0,0],n=0,a=0,o=0;for(let l=0;l=32&&(a=0,n++)}this._mrtFormats.length=o,(this._mrtAttachments1!==s[0]||this._mrtAttachments2!==s[1])&&(this._mrtAttachments1=s[0],this._mrtAttachments2=s[1],this._states[iE.MRTAttachments1]=s[0],this._states[iE.MRTAttachments2]=s[1],this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.MRTAttachments1))}setAlphaBlendEnabled(e){this._alphaBlendEnabled=e}setAlphaBlendFactors(e,t){this._alphaBlendFuncParams=e,this._alphaBlendEqParams=t}setWriteMask(e){this._writeMask=e}setDepthStencilFormat(e){this._webgpuDepthStencilFormat=e,this._depthStencilFormat=void 0===e?0:cy[e]}setDepthTestEnabled(e){this._depthTestEnabled=e}setDepthWriteEnabled(e){this._depthWriteEnabled=e}setDepthCompare(e){this._depthCompare=(null!=e?e:519)-512}setStencilEnabled(e){this._stencilEnabled=e}setStencilCompare(e){this._stencilFrontCompare=(null!=e?e:519)-512}setStencilDepthFailOp(e){this._stencilFrontDepthFailOp=null===e?1:cF[e]}setStencilPassOp(e){this._stencilFrontPassOp=null===e?2:cF[e]}setStencilFailOp(e){this._stencilFrontFailOp=null===e?1:cF[e]}setStencilReadMask(e){this._stencilReadMask!==e&&(this._stencilReadMask=e,this._states[iE.StencilReadMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.StencilReadMask))}setStencilWriteMask(e){this._stencilWriteMask!==e&&(this._stencilWriteMask=e,this._states[iE.StencilWriteMask]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.StencilWriteMask))}resetStencilState(){this.setStencilState(!1,519,7680,7681,7680,255,255)}setStencilState(e,t,i,r,s,n,a){this._stencilEnabled=e,this._stencilFrontCompare=(null!=t?t:519)-512,this._stencilFrontDepthFailOp=null===i?1:cF[i],this._stencilFrontPassOp=null===r?2:cF[r],this._stencilFrontFailOp=null===s?1:cF[s],this.setStencilReadMask(n),this.setStencilWriteMask(a)}setBuffers(e,t,i){this._vertexBuffers=e,this._overrideVertexBuffers=i,this._indexBuffer=t}static _GetTopology(e){switch(e){case 0:default:return ie.TriangleList;case 2:case 3:return ie.PointList;case 1:case 4:return ie.LineList;case 5:throw"LineLoop is an unsupported fillmode in WebGPU";case 6:return ie.LineStrip;case 7:return ie.TriangleStrip;case 8:throw"TriangleFan is an unsupported fillmode in WebGPU"}}static _GetAphaBlendOperation(e){switch(e){case 32774:default:return ia.Add;case 32778:return ia.Subtract;case 32779:return ia.ReverseSubtract;case 32775:return ia.Min;case 32776:return ia.Max}}static _GetAphaBlendFactor(e){switch(e){case 0:return is.Zero;case 1:default:return is.One;case 768:return is.Src;case 769:return is.OneMinusSrc;case 770:return is.SrcAlpha;case 771:return is.OneMinusSrcAlpha;case 772:return is.DstAlpha;case 773:return is.OneMinusDstAlpha;case 774:return is.Dst;case 775:return is.OneMinusDst;case 776:return is.SrcAlphaSaturated;case 32769:case 32771:return is.Constant;case 32770:case 32772:return is.OneMinusConstant}}static _GetCompareFunction(e){switch(e){case 0:break;case 1:return t1.Less;case 2:return t1.Equal;case 3:return t1.LessEqual;case 4:return t1.Greater;case 5:return t1.NotEqual;case 6:return t1.GreaterEqual;case 7:return t1.Always}return t1.Never}static _GetStencilOpFunction(e){switch(e){case 0:return io.Zero;case 1:break;case 2:return io.Replace;case 3:return io.IncrementClamp;case 4:return io.DecrementClamp;case 5:return io.Invert;case 6:return io.IncrementWrap;case 7:return io.DecrementWrap}return io.Keep}static _GetVertexInputDescriptorFormat(e){let t=e.type,i=e.normalized,r=e.getSize();switch(t){case sm.o.BYTE:switch(r){case 1:case 2:return i?ih.Snorm8x2:ih.Sint8x2;case 3:case 4:return i?ih.Snorm8x4:ih.Sint8x4}break;case sm.o.UNSIGNED_BYTE:switch(r){case 1:case 2:return i?ih.Unorm8x2:ih.Uint8x2;case 3:case 4:return i?ih.Unorm8x4:ih.Uint8x4}break;case sm.o.SHORT:switch(r){case 1:case 2:return i?ih.Snorm16x2:ih.Sint16x2;case 3:case 4:return i?ih.Snorm16x4:ih.Sint16x4}break;case sm.o.UNSIGNED_SHORT:switch(r){case 1:case 2:return i?ih.Unorm16x2:ih.Uint16x2;case 3:case 4:return i?ih.Unorm16x4:ih.Uint16x4}break;case sm.o.INT:switch(r){case 1:return ih.Sint32;case 2:return ih.Sint32x2;case 3:return ih.Sint32x3;case 4:return ih.Sint32x4}break;case sm.o.UNSIGNED_INT:switch(r){case 1:return ih.Uint32;case 2:return ih.Uint32x2;case 3:return ih.Uint32x3;case 4:return ih.Uint32x4}break;case sm.o.FLOAT:switch(r){case 1:return ih.Float32;case 2:return ih.Float32x2;case 3:return ih.Float32x3;case 4:return ih.Float32x4}}throw Error(`Invalid Format '${e.getKind()}' - type=${t}, normalized=${i}, size=${r}`)}_getAphaBlendState(){return this._alphaBlendEnabled?{srcFactor:cw._GetAphaBlendFactor(this._alphaBlendFuncParams[2]),dstFactor:cw._GetAphaBlendFactor(this._alphaBlendFuncParams[3]),operation:cw._GetAphaBlendOperation(this._alphaBlendEqParams[1])}:null}_getColorBlendState(){return this._alphaBlendEnabled?{srcFactor:cw._GetAphaBlendFactor(this._alphaBlendFuncParams[0]),dstFactor:cw._GetAphaBlendFactor(this._alphaBlendFuncParams[1]),operation:cw._GetAphaBlendOperation(this._alphaBlendEqParams[0])}:null}_setShaderStage(e){this._shaderId!==e&&(this._shaderId=e,this._states[iE.ShaderStage]=e,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.ShaderStage))}_setRasterizationState(e,t){let i=this._frontFace,r=i-1+((this._cullEnabled?this._cullFace:0)<<1)+((this._clampDepth?1:0)<<3)+((this._alphaToCoverageEnabled?1:0)<<4)+(e<<5)+(t<<8);this._rasterizationState!==r&&(this._rasterizationState=r,this._states[iE.RasterizationState]=this._rasterizationState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.RasterizationState))}_setColorStates(){let e=((this._writeMask?1:0)<<22)+(this._colorFormat<<23)+((this._depthWriteEnabled?1:0)<<29);this._alphaBlendEnabled&&(e+=((null===this._alphaBlendFuncParams[0]?2:cN[this._alphaBlendFuncParams[0]])<<0)+((null===this._alphaBlendFuncParams[1]?2:cN[this._alphaBlendFuncParams[1]])<<4)+((null===this._alphaBlendFuncParams[2]?2:cN[this._alphaBlendFuncParams[2]])<<8)+((null===this._alphaBlendFuncParams[3]?2:cN[this._alphaBlendFuncParams[3]])<<12)+((null===this._alphaBlendEqParams[0]?1:this._alphaBlendEqParams[0]-32773)<<16)+((null===this._alphaBlendEqParams[1]?1:this._alphaBlendEqParams[1]-32773)<<19)),e!==this._colorStates&&(this._colorStates=e,this._states[iE.ColorStates]=this._colorStates,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.ColorStates))}_setDepthStencilState(){let e=this._stencilEnabled?this._stencilFrontCompare+(this._stencilFrontDepthFailOp<<3)+(this._stencilFrontPassOp<<6)+(this._stencilFrontFailOp<<9):591,t=this._depthStencilFormat+((this._depthTestEnabled?this._depthCompare:7)<<6)+(e<<10);this._depthStencilState!==t&&(this._depthStencilState=t,this._states[iE.DepthStencilState]=this._depthStencilState,this._isDirty=!0,this._stateDirtyLowestIndex=Math.min(this._stateDirtyLowestIndex,iE.DepthStencilState))}_setVertexState(e){var t,i;let r;let s=this._statesLength,n=iE.VertexState,a=e._pipelineContext,o=a.shaderProcessingContext.attributeNamesFromEffect,l=a.shaderProcessingContext.attributeLocationsFromEffect,h=0;for(let e=0;e0)for(let e=0;e=this._video.HAVE_CURRENT_DATA}dispose(){}}class cH{get forceBindGroupCreation(){return this._numExternalTextures>0}get hasFloatOrDepthTextures(){return this._numFloatOrDepthTextures>0}constructor(){this.uniqueId=cH._Counter++,this.updateId=0,this.textureState=0,this.reset()}reset(){this.samplers={},this.textures={},this.isDirty=!0,this._numFloatOrDepthTextures=0,this._numExternalTextures=0}setSampler(e,t){let i=this.samplers[e],r=-1;i?r=i.hashCode:this.samplers[e]=i={sampler:t,hashCode:0},i.sampler=t,i.hashCode=t?cO.GetSamplerHashCode(t):0;let s=r!==i.hashCode;s&&this.updateId++,this.isDirty||(this.isDirty=s)}setTexture(e,t){var i,r,s;let n=this.textures[e],a=-1;n?a=null!==(r=null===(i=n.texture)||void 0===i?void 0:i.uniqueId)&&void 0!==r?r:-1:this.textures[e]=n={texture:t,isFloatOrDepthTexture:!1,isExternalTexture:!1},n.isExternalTexture&&this._numExternalTextures--,n.isFloatOrDepthTexture&&this._numFloatOrDepthTextures--,t?(n.isFloatOrDepthTexture=1===t.type||t.format>=13&&t.format<=18,n.isExternalTexture=cW.IsExternalTexture(t),n.isFloatOrDepthTexture&&this._numFloatOrDepthTextures++,n.isExternalTexture&&this._numExternalTextures++):(n.isFloatOrDepthTexture=!1,n.isExternalTexture=!1),n.texture=t;let o=a!==(null!==(s=null==t?void 0:t.uniqueId)&&void 0!==s?s:-1);o&&this.updateId++,this.isDirty||(this.isDirty=o)}}cH._Counter=0;class cX{isDirty(e){return this._isDirty||this._materialContextUpdateId!==e}resetIsDirty(e){this._isDirty=!1,this._materialContextUpdateId=e}get useInstancing(){return this._useInstancing}set useInstancing(e){this._useInstancing!==e&&(e?(this.indirectDrawBuffer=this._bufferManager.createRawBuffer(20,tX.CopyDst|tX.Indirect|tX.Storage,void 0,"IndirectDrawBuffer"),this._indirectDrawData=new Uint32Array(5),this._indirectDrawData[3]=0,this._indirectDrawData[4]=0):(this.indirectDrawBuffer&&this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this._useInstancing=e,this._currentInstanceCount=-1)}constructor(e){this._bufferManager=e,this.uniqueId=cX._Counter++,this._useInstancing=!1,this._currentInstanceCount=0,this.reset()}reset(){this.buffers={},this._isDirty=!0,this._materialContextUpdateId=0,this.fastBundle=void 0,this.bindGroups=void 0}setBuffer(e,t){var i;this._isDirty||(this._isDirty=(null==t?void 0:t.uniqueId)!==(null===(i=this.buffers[e])||void 0===i?void 0:i.uniqueId)),this.buffers[e]=t}setIndirectData(e,t,i){t!==this._currentInstanceCount&&this.indirectDrawBuffer&&this._indirectDrawData&&(this._currentInstanceCount=t,this._indirectDrawData[0]=e,this._indirectDrawData[1]=t,this._indirectDrawData[2]=i,this._bufferManager.setRawData(this.indirectDrawBuffer,0,this._indirectDrawData,0,20))}dispose(){this.indirectDrawBuffer&&(this._bufferManager.releaseBuffer(this.indirectDrawBuffer),this.indirectDrawBuffer=void 0,this._indirectDrawData=void 0),this.fastBundle=void 0,this.bindGroups=void 0,this.buffers=void 0}}cX._Counter=0;class cY{constructor(){this.values={}}}class cj{static get Statistics(){return{totalCreated:cj.NumBindGroupsCreatedTotal,lastFrameCreated:cj.NumBindGroupsCreatedLastFrame,lookupLastFrame:cj.NumBindGroupsLookupLastFrame,noLookupLastFrame:cj.NumBindGroupsNoLookupLastFrame}}static ResetCache(){cj._Cache=new cY,cj.NumBindGroupsCreatedTotal=0,cj.NumBindGroupsCreatedLastFrame=0,cj.NumBindGroupsLookupLastFrame=0,cj.NumBindGroupsNoLookupLastFrame=0,cj._NumBindGroupsCreatedCurrentFrame=0,cj._NumBindGroupsLookupCurrentFrame=0,cj._NumBindGroupsNoLookupCurrentFrame=0}constructor(e,t,i){this.disabled=!1,this._device=e,this._cacheSampler=t,this._engine=i}endFrame(){cj.NumBindGroupsCreatedLastFrame=cj._NumBindGroupsCreatedCurrentFrame,cj.NumBindGroupsLookupLastFrame=cj._NumBindGroupsLookupCurrentFrame,cj.NumBindGroupsNoLookupLastFrame=cj._NumBindGroupsNoLookupCurrentFrame,cj._NumBindGroupsCreatedCurrentFrame=0,cj._NumBindGroupsLookupCurrentFrame=0,cj._NumBindGroupsNoLookupCurrentFrame=0}getBindGroups(e,t,i){var r,s,n,a,o,l,h,u,c,d;let p;let _=cj._Cache,f=this.disabled||i.forceBindGroupCreation;if(!f){if(!t.isDirty(i.updateId)&&!i.isDirty)return cj._NumBindGroupsNoLookupCurrentFrame++,t.bindGroups;for(let i of e.shaderProcessingContext.bufferNames){let e=null!==(s=null===(r=t.buffers[i])||void 0===r?void 0:r.uniqueId)&&void 0!==s?s:0,n=_.values[e];n||(n=new cY,_.values[e]=n),_=n}for(let t of e.shaderProcessingContext.samplerNames){let e=null!==(a=null===(n=i.samplers[t])||void 0===n?void 0:n.hashCode)&&void 0!==a?a:0,r=_.values[e];r||(r=new cY,_.values[e]=r),_=r}for(let t of e.shaderProcessingContext.textureNames){let e=null!==(h=null===(l=null===(o=i.textures[t])||void 0===o?void 0:o.texture)||void 0===l?void 0:l.uniqueId)&&void 0!==h?h:0,r=_.values[e];r||(r=new cY,_.values[e]=r),_=r}p=_.bindGroups}if(t.resetIsDirty(i.updateId),i.isDirty=!1,p)return t.bindGroups=p,cj._NumBindGroupsLookupCurrentFrame++,p;p=[],t.bindGroups=p,f||(_.bindGroups=p),cj.NumBindGroupsCreatedTotal++,cj._NumBindGroupsCreatedCurrentFrame++;let m=e.bindGroupLayouts[i.textureState];for(let r=0;r"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._cacheSampler.getSampler(t,!1,e.hashCode,t.label)}else rb.Y.Error(`Sampler "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.texture||s.storageTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){rb.Y.Error(`Trying to bind a null texture! entry=${JSON.stringify(s)}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture._hardwareTexture;if(this._engine.dbgSanityChecks&&(!t||s.texture&&!t.view||s.storageTexture&&!t.viewForWriting)){rb.Y.Error(`Trying to bind a null gpu texture or view! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, isReady=${null===(c=e.texture)||void 0===c?void 0:c.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=s.storageTexture?t.viewForWriting:t.view}else rb.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.externalTexture){let e=i.textures[l];if(e){if(this._engine.dbgSanityChecks&&null===e.texture){rb.Y.Error(`Trying to bind a null external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, materialContext.uniqueId=${i.uniqueId}`,50);continue}let t=e.texture.underlyingResource;if(this._engine.dbgSanityChecks&&!t){rb.Y.Error(`Trying to bind a null gpu external texture! entry=${JSON.stringify(s)}, name=${l}, bindingInfo=${JSON.stringify(e,(e,t)=>"texture"===e?"":t)}, isReady=${null===(d=e.texture)||void 0===d?void 0:d.isReady}, materialContext.uniqueId=${i.uniqueId}`,50);continue}n[a].resource=this._device.importExternalTexture({source:t})}else rb.Y.Error(`Texture "${l}" could not be bound. entry=${JSON.stringify(s)}, materialContext=${JSON.stringify(i,(e,t)=>"texture"===e||"sampler"===e?"":t)}`,50)}else if(s.buffer){let e=t.buffers[l];if(e){let t=e.underlyingResource;n[a].resource.buffer=t,n[a].resource.size=e.capacity}else rb.Y.Error(`Can't find buffer "${l}". entry=${JSON.stringify(s)}, buffers=${JSON.stringify(t.buffers)}, drawContext.uniqueId=${t.uniqueId}`,50)}}let a=m[r];p[r]=this._device.createBindGroup({layout:a,entries:n})}return p}}cj.NumBindGroupsCreatedTotal=0,cj.NumBindGroupsCreatedLastFrame=0,cj.NumBindGroupsLookupLastFrame=0,cj.NumBindGroupsNoLookupLastFrame=0,cj._Cache=new cY,cj._NumBindGroupsCreatedCurrentFrame=0,cj._NumBindGroupsLookupCurrentFrame=0,cj._NumBindGroupsNoLookupCurrentFrame=0;let cq=`uniform float depthValue;const vec2 pos[4]={vec2(-1.0,1.0), +vec2(1.0,1.0), +vec2(-1.0,-1.0), +vec2(1.0,-1.0)}; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +gl_Position=vec4(pos[gl_VertexID],depthValue,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`;nw.v.ShadersStore.clearQuadVertexShader=cq;let cK=`uniform vec4 color;void main() {gl_FragColor=color;} +`;nw.v.ShadersStore.clearQuadPixelShader=cK;class c${setDepthStencilFormat(e){this._depthTextureFormat=e,this._cacheRenderPipeline.setDepthStencilFormat(e)}setColorFormat(e){this._cacheRenderPipeline.setColorFormat(e)}setMRTAttachments(e,t,i){this._cacheRenderPipeline.setMRT(t,i),this._cacheRenderPipeline.setMRTAttachments(e)}constructor(e,t,i){this._bindGroups={},this._bundleCache={},this._keyTemp=[],this._device=e,this._engine=t,this._cacheRenderPipeline=new cU(this._device,i),this._cacheRenderPipeline.setDepthTestEnabled(!1),this._cacheRenderPipeline.setStencilReadMask(255),this._effect=t.createEffect("clearQuad",[],["color","depthValue"])}clear(e,t,i,r,s=1){var n,a;let o,l;let h=null,u=!!this._engine._currentRenderTarget;if(e)o=e;else{let e=0;this._keyTemp.length=0;for(let t=0;t1?68719476736:0)+137438953472*c,l=this._keyTemp.join("_"),h=this._bundleCache[l])return h;o=this._device.createRenderBundleEncoder({colorFormats:this._cacheRenderPipeline.colorFormats,depthStencilFormat:this._depthTextureFormat,sampleCount:cd.GetSample(s)})}this._cacheRenderPipeline.setDepthWriteEnabled(!!i),this._cacheRenderPipeline.setStencilEnabled(!!r&&!!this._depthTextureFormat&&cd.HasStencilAspect(this._depthTextureFormat)),this._cacheRenderPipeline.setStencilWriteMask(r?255:0),this._cacheRenderPipeline.setStencilCompare(r?519:512),this._cacheRenderPipeline.setStencilPassOp(r?7681:7680),this._cacheRenderPipeline.setWriteMask(t?15:0);let c=this._cacheRenderPipeline.getRenderPipeline(7,this._effect,s),d=this._effect._pipelineContext;t&&this._effect.setDirectColor4("color",t),this._effect.setFloat("depthValue",this._engine.useReverseDepthBuffer?this._engine._clearReverseDepthValue:this._engine._clearDepthValue),d.uniformBuffer.update();let p=u?this._engine._ubInvertY:this._engine._ubDontInvertY,_=d.uniformBuffer.getBuffer(),f=_.uniqueId+"-"+p.uniqueId,m=this._bindGroups[f];if(!m){let e=d.bindGroupLayouts[0];(m=this._bindGroups[f]=[]).push(this._device.createBindGroup({layout:e[0],entries:[]})),u1._SimplifiedKnownBindings||m.push(this._device.createBindGroup({layout:e[1],entries:[]})),m.push(this._device.createBindGroup({layout:e[u1._SimplifiedKnownBindings?1:2],entries:[{binding:0,resource:{buffer:p.underlyingResource,size:p.capacity}},{binding:1,resource:{buffer:_.underlyingResource,size:_.capacity}}]}))}o.setPipeline(c);for(let e=0;e{let e=new BigUint64Array(i.getMappedRange()).slice();return i.unmap(),this._dstBuffers[this._dstBuffers.length]=i,e},e=>{if(this._engine.isDisposed||this._engine.uniqueId!==r)return null;throw e})}async readValue(e=0){let t=this._getBuffer(e,1);if(null===t)return null;let i=this._engine.uniqueId;return t.mapAsync(tY.Read).then(()=>{let e=Number(new BigUint64Array(t.getMappedRange())[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,e},e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e})}async readTwoValuesAndSubtract(e=0){let t=this._getBuffer(e,2);if(null===t)return null;let i=this._engine.uniqueId;return t.mapAsync(tY.Read).then(()=>{let e=new BigUint64Array(t.getMappedRange()),i=Number(e[1]-e[0]);return t.unmap(),this._dstBuffers[this._dstBuffers.length]=t,i},e=>{if(this._engine.isDisposed||this._engine.uniqueId!==i)return 0;throw e})}dispose(){this._querySet.destroy(),this._bufferManager.releaseBuffer(this._queryBuffer);for(let e=0;e{null!==e&&e>=0&&(this._gpuFrameTimeCounter.fetchNewFrame(),this._gpuFrameTimeCounter.addCount(e,!0)),this._measureDurationState=0}))}startPass(e,t){this._enabled?this._measureDuration.startPass(e,t):e.timestampWrites=void 0}endPass(e,t){if(!this._enabled||!t)return;let i=this._engine.frameId;this._measureDuration.stopPass(e).then(e=>{t._addDuration(i,null!==e&&e>0?e:0)})}dispose(){var e;null===(e=this._measureDuration)||void 0===e||e.dispose()}}class c8{constructor(e,t,i,r=2,s){this._count=r,this._querySet=new c5(e,r,im.Timestamp,t,i,!0,s)}start(e){var t;null===(t=e.writeTimestamp)||void 0===t||t.call(e,this._querySet.querySet,0)}async stop(e){var t;return null===(t=e.writeTimestamp)||void 0===t||t.call(e,this._querySet.querySet,1),e.writeTimestamp?this._querySet.readTwoValuesAndSubtract(0):0}startPass(e,t){if(t+3>this._count)throw Error("WebGPUDurationMeasure: index out of range ("+t+")");e.timestampWrites={querySet:this._querySet.querySet,beginningOfPassWriteIndex:t+2,endOfPassWriteIndex:t+3}}async stopPass(e){return this._querySet.readTwoValuesAndSubtract(e+2)}dispose(){this._querySet.dispose()}}class c7{get querySet(){return this._querySet.querySet}get hasQueries(){return this._currentTotalIndices!==this._availableIndices.length}canBeginQuery(e){if(this._frameQuerySetIsDirty===this._engine.frameId||this._queryFrameId[e]===this._engine.frameId)return!1;let t=void 0!==this._engine._getCurrentRenderPassWrapper().renderPassDescriptor.occlusionQuerySet;return t&&(this._queryFrameId[e]=this._engine.frameId),t}constructor(e,t,i,r=50,s=100){this._availableIndices=[],this._frameQuerySetIsDirty=-1,this._queryFrameId=[],this._engine=e,this._device=t,this._bufferManager=i,this._frameLastBuffer=-1,this._currentTotalIndices=0,this._countIncrement=s,this._allocateNewIndices(r)}createQuery(){0===this._availableIndices.length&&this._allocateNewIndices();let e=this._availableIndices[this._availableIndices.length-1];return this._availableIndices.length--,e}deleteQuery(e){this._availableIndices[this._availableIndices.length]=e}isQueryResultAvailable(e){return this._retrieveQueryBuffer(),!!this._lastBuffer&&e{this._lastBuffer=e}))}_allocateNewIndices(e){e=null!=e?e:this._countIncrement,this._delayQuerySetDispose();for(let t=0;te.dispose,1e3)}dispose(){var e;null===(e=this._querySet)||void 0===e||e.dispose(),this._availableIndices.length=0}}class c9{async initTwgsl(e){return c9._twgsl?void 0:(e=e||{},(e=Object.assign(Object.assign({},c9._TWgslDefaultOptions),e)).twgsl)?(c9._twgsl=e.twgsl,Promise.resolve()):(e.jsPath&&e.wasmPath&&await sg.w1.LoadBabylonScriptAsync(e.jsPath),self.twgsl)?(c9._twgsl=await self.twgsl(sg.w1.GetBabylonScriptURL(e.wasmPath)),Promise.resolve()):Promise.reject("twgsl is not available.")}convertSpirV2WGSL(e,t=!1){let i=c9._twgsl.convertSpirV2WGSL(e,c9.DisableUniformityAnalysis||t);return c9.ShowWGSLShaderCode&&(rb.Y.Log(i),rb.Y.Log("***********************************************")),c9.DisableUniformityAnalysis||t?"diagnostic(off, derivative_uniformity);\n"+i:i}}c9._TWgslDefaultOptions={jsPath:`${sg.w1._DefaultCdnUrl}/twgsl/twgsl.js`,wasmPath:`${sg.w1._DefaultCdnUrl}/twgsl/twgsl.wasm`},c9.ShowWGSLShaderCode=!1,c9.DisableUniformityAnalysis=!1,c9._twgsl=null;class de{constructor(e,t,i){this._record=!1,this._play=!1,this._playBundleListIndex=0,this._allBundleLists=[],this._enabled=!1,this._engine=e,this._mode=t,this._bundleList=i}get enabled(){return this._enabled}get play(){return this._play}get record(){return this._record}set enabled(e){this._allBundleLists.length=0,this._record=this._enabled=e,this._play=!1,e&&(this._modeSaved=this._mode,this._mode=0)}get mode(){return this._mode}set mode(e){this._record?this._modeSaved=e:this._mode=e}endRenderPass(e){let t;if(!this._record&&!this._play)return!1;if(this._record)t=this._bundleList.clone(),this._allBundleLists.push(t),this._bundleList.reset();else{if(this._playBundleListIndex>=this._allBundleLists.length)throw Error(`Invalid playBundleListIndex! Your snapshot is no longer valid for the current frame, you should recreate a new one. playBundleListIndex=${this._playBundleListIndex}, allBundleLists.length=${this._allBundleLists.length}}`);t=this._allBundleLists[this._playBundleListIndex++]}return t.run(e),1===this._mode&&this._engine._reportDrawCall(t.numDrawCalls),!0}endFrame(){this._record&&(this._record=!1,this._play=!0,this._mode=this._modeSaved),this._playBundleListIndex=0}reset(){this.enabled=!1,this.enabled=!0}}let dt=`attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +@vertex +fn main(input : VertexInputs)->FragmentInputs { +#define CUSTOM_VERTEX_MAIN_BEGIN +vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +} +`;nw.v.ShadersStoreWGSL.postprocessVertexShader=dt;let di={label:"TextureView_SwapChain_ResolveTarget",dimension:tj.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},dr={label:"TextureView_SwapChain",dimension:tj.E2d,format:void 0,mipLevelCount:1,arrayLayerCount:1},ds="/* disable_uniformity_analysis */",dn=new rm.HE;class da extends sR.D{get snapshotRenderingMode(){return this._snapshotRendering.mode}set snapshotRenderingMode(e){this._snapshotRendering.mode=e}snapshotRenderingReset(){this._snapshotRendering.reset()}get snapshotRendering(){return this._snapshotRendering.enabled}set snapshotRendering(e){this._snapshotRendering.enabled=e}get disableCacheSamplers(){return!!this._cacheSampler&&this._cacheSampler.disabled}set disableCacheSamplers(e){this._cacheSampler&&(this._cacheSampler.disabled=e)}get disableCacheRenderPipelines(){return!!this._cacheRenderPipeline&&this._cacheRenderPipeline.disabled}set disableCacheRenderPipelines(e){this._cacheRenderPipeline&&(this._cacheRenderPipeline.disabled=e)}get disableCacheBindGroups(){return!!this._cacheBindGroups&&this._cacheBindGroups.disabled}set disableCacheBindGroups(e){this._cacheBindGroups&&(this._cacheBindGroups.disabled=e)}static get IsSupportedAsync(){return navigator.gpu?navigator.gpu.requestAdapter().then(e=>!!e,()=>!1).catch(()=>!1):Promise.resolve(!1)}static get IsSupported(){return rb.Y.Warn("You must call IsSupportedAsync for WebGPU!"),!1}get supportsUniformBuffers(){return!0}get supportedExtensions(){return this._adapterSupportedExtensions}get enabledExtensions(){return this._deviceEnabledExtensions}get supportedLimits(){return this._adapterSupportedLimits}get currentLimits(){return this._deviceLimits}get description(){return this.name+this.version}get version(){return 1}getInfo(){return{vendor:this._adapterInfo.vendor||"unknown vendor",renderer:this._adapterInfo.architecture||"unknown renderer",version:this._adapterInfo.description||"unknown version"}}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=e}get enableGPUTimingMeasurements(){return this._timestampQuery.enable}set enableGPUTimingMeasurements(e){this._timestampQuery.enable!==e&&(this.gpuTimeInFrameForMainPass=e?new hp:void 0,this._timestampQuery.enable=e)}get currentSampleCount(){return this._currentRenderTarget?this._currentRenderTarget.samples:this._mainPassSampleCount}static CreateAsync(e,t={}){let i=new da(e,t);return new Promise(e=>{i.initAsync(t.glslangOptions,t.twgslOptions).then(()=>e(i))})}constructor(e,t={}){var i,r;if(super(null,null===(i=t.antialias)||void 0===i||i,t),this.uniqueId=-1,this._uploadEncoderDescriptor={label:"upload"},this._renderEncoderDescriptor={label:"render"},this._clearDepthValue=1,this._clearReverseDepthValue=0,this._clearStencilValue=0,this._defaultSampleCount=4,this._glslang=null,this._tintWASM=null,this._adapterInfo={vendor:"",architecture:"",device:"",description:""},this._timestampIndex=0,this._compiledComputeEffects={},this._counters={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.countersLastFrame={numEnableEffects:0,numEnableDrawWrapper:0,numBundleCreationNonCompatMode:0,numBundleReuseNonCompatMode:0},this.numMaxUncapturedErrors=20,this._commandBuffers=[null,null],this._currentRenderPass=null,this._mainRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._rttRenderPassWrapper={renderPassDescriptor:null,colorAttachmentViewDescriptor:null,depthAttachmentViewDescriptor:null,colorAttachmentGPUTextures:[],depthTextureFormat:void 0},this._pendingDebugCommands=[],this._currentOverrideVertexBuffers=null,this._currentIndexBuffer=null,this._colorWriteLocal=!0,this._forceEnableEffect=!1,this.dbgShowShaderCode=!1,this.dbgSanityChecks=!0,this.dbgVerboseLogsForFirstFrames=!1,this.dbgVerboseLogsNumFrames=10,this.dbgLogIfNotDrawWrapper=!0,this.dbgShowEmptyEnableEffectCalls=!0,this.isNDCHalfZRange=!0,this.hasOriginBottomLeft=!1,this._viewportsCurrent={x:0,y:0,w:0,h:0},this._scissorsCurrent={x:0,y:0,w:0,h:0},this._scissorCached={x:0,y:0,z:0,w:0},this._stencilRefsCurrent=-1,this._blendColorsCurrent=[null,null,null,null],this._name="WebGPU",t.deviceDescriptor=t.deviceDescriptor||{},t.enableGPUDebugMarkers=null!==(r=t.enableGPUDebugMarkers)&&void 0!==r&&r,rb.Y.Log(`Babylon.js v${sR.D.Version} - ${this.description} engine`),!navigator.gpu){rb.Y.Error("WebGPU is not supported by your browser.");return}t.swapChainFormat=t.swapChainFormat||navigator.gpu.getPreferredCanvasFormat(),this._isWebGPU=!0,this._shaderPlatformName="WEBGPU",this._renderingCanvas=e,this._options=t,this._mainPassSampleCount=t.antialias?this._defaultSampleCount:1,this._setupMobileChecks(),this._sharedInit(e),this._shaderProcessor=new u2,this._shaderProcessorWGSL=new cc}initAsync(e,t){var i;return this.uniqueId=da._InstanceId++,this._glslangOptions=e,this._twgslOptions=t,this._initGlslang(null!=e?e:null===(i=this._options)||void 0===i?void 0:i.glslangOptions).then(e=>{var i;return this._glslang=e,this._tintWASM=da.UseTWGSL?new c9:null,this._tintWASM?this._tintWASM.initTwgsl(null!=t?t:null===(i=this._options)||void 0===i?void 0:i.twgslOptions).then(()=>navigator.gpu.requestAdapter(this._options),e=>{throw rb.Y.Error("Can not initialize twgsl!"),rb.Y.Error(e),Error("WebGPU initializations stopped.")}):navigator.gpu.requestAdapter(this._options)},e=>{throw rb.Y.Error("Can not initialize glslang!"),rb.Y.Error(e),Error("WebGPU initializations stopped.")}).then(e=>{var t,i,r;if(e){this._adapter=e,this._adapterSupportedExtensions=[],null===(t=this._adapter.features)||void 0===t||t.forEach(e=>this._adapterSupportedExtensions.push(e)),this._adapterSupportedLimits=this._adapter.limits,this._adapter.requestAdapterInfo().then(e=>{this._adapterInfo=e});let s=null!==(i=this._options.deviceDescriptor)&&void 0!==i?i:{},n=null!==(r=null==s?void 0:s.requiredFeatures)&&void 0!==r?r:this._options.enableAllFeatures?this._adapterSupportedExtensions:void 0;if(n){let e=[];for(let t of n)-1!==this._adapterSupportedExtensions.indexOf(t)&&e.push(t);s.requiredFeatures=e}if(this._options.setMaximumLimits&&!s.requiredLimits)for(let e in s.requiredLimits={},this._adapterSupportedLimits)s.requiredLimits[e]=this._adapterSupportedLimits[e];return s.label=`BabylonWebGPUDevice${this.uniqueId}`,this._adapter.requestDevice(s)}throw"Could not retrieve a WebGPU adapter (adapter is null)."}).then(e=>{var t,i;this._device=e,this._deviceEnabledExtensions=[],null===(t=this._device.features)||void 0===t||t.forEach(e=>this._deviceEnabledExtensions.push(e)),this._deviceLimits=e.limits;let r=-1;this._device.addEventListener("uncapturederror",e=>{++r{this._isDisposed||(this._contextWasLost=!0,rb.Y.Warn("WebGPU context lost. "+e),this.onContextLostObservable.notifyObservers(this),this._restoreEngineAfterContextLost(async()=>{var e,t,i,r;let s=this.snapshotRenderingMode,n=this.snapshotRendering,a=this.disableCacheSamplers,o=this.disableCacheRenderPipelines,l=this.disableCacheBindGroups,h=this.enableGPUTimingMeasurements;await this.initAsync(null!==(e=this._glslangOptions)&&void 0!==e?e:null===(t=this._options)||void 0===t?void 0:t.glslangOptions,null!==(i=this._twgslOptions)&&void 0!==i?i:null===(r=this._options)||void 0===r?void 0:r.twgslOptions),this.snapshotRenderingMode=s,this.snapshotRendering=n,this.disableCacheSamplers=a,this.disableCacheRenderPipelines=o,this.disableCacheBindGroups=l,this.enableGPUTimingMeasurements=h,this._currentRenderPass=null}))})},e=>{rb.Y.Error("Could not retrieve a WebGPU device."),rb.Y.Error(e)}).then(()=>{this._bufferManager=new cP(this,this._device),this._textureHelper=new cA(this,this._device,this._glslang,this._tintWASM,this._bufferManager,this._deviceEnabledExtensions),this._cacheSampler=new cO(this._device),this._cacheBindGroups=new cj(this._device,this._cacheSampler,this),this._timestampQuery=new c6(this,this._device,this._bufferManager),this._occlusionQuery=this._device.createQuerySet?new c7(this,this._device,this._bufferManager):void 0,this._bundleList=new c4(this._device),this._snapshotRendering=new de(this,this._snapshotRenderingMode,this._bundleList),this._ubInvertY=this._bufferManager.createBuffer(new Float32Array([-1,0]),tX.Uniform|tX.CopyDst,"UBInvertY"),this._ubDontInvertY=this._bufferManager.createBuffer(new Float32Array([1,0]),tX.Uniform|tX.CopyDst,"UBDontInvertY"),this.dbgVerboseLogsForFirstFrames&&void 0===this._count&&(this._count=0,rb.Y.Log(["%c frame #"+this._count+" - begin","background: #ffff00"])),this._uploadEncoder=this._device.createCommandEncoder(this._uploadEncoderDescriptor),this._renderEncoder=this._device.createCommandEncoder(this._renderEncoderDescriptor),this._initializeLimits(),this._emptyVertexBuffer=new sm.o(this,[0],"",{stride:1,offset:0,size:1,label:"EmptyVertexBuffer"}),this._cacheRenderPipeline=new cU(this._device,this._emptyVertexBuffer),this._depthCullingState=new cz(this._cacheRenderPipeline),this._stencilStateComposer=new ck(this._cacheRenderPipeline),this._stencilStateComposer.stencilGlobal=this._stencilState,this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=515,this._depthCullingState.depthMask=!0,this._textureHelper.setCommandEncoder(this._uploadEncoder),this._clearQuad=new c$(this._device,this,this._emptyVertexBuffer),this._defaultDrawContext=this.createDrawContext(),this._currentDrawContext=this._defaultDrawContext,this._defaultMaterialContext=this.createMaterialContext(),this._currentMaterialContext=this._defaultMaterialContext,this._initializeContextAndSwapChain(),this._initializeMainAttachments(),this.resize()}).catch(e=>{var t;rb.Y.Error("Can not create WebGPU Device and/or context."),rb.Y.Error(e),null===(t=null==console?void 0:console.trace)||void 0===t||t.call(console)})}_initGlslang(e){return(e=e||{},(e=Object.assign(Object.assign({},da._GLSLslangDefaultOptions),e)).glslang)?Promise.resolve(e.glslang):self.glslang?self.glslang(e.wasmPath):e.jsPath&&e.wasmPath?sg.w1.LoadBabylonScriptAsync(e.jsPath).then(()=>self.glslang(sg.w1.GetBabylonScriptURL(e.wasmPath))):Promise.reject("gslang is not available.")}_initializeLimits(){this._caps={maxTexturesImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxVertexTextureImageUnits:this._deviceLimits.maxSampledTexturesPerShaderStage,maxCombinedTexturesImageUnits:2*this._deviceLimits.maxSampledTexturesPerShaderStage,maxTextureSize:this._deviceLimits.maxTextureDimension2D,maxCubemapTextureSize:this._deviceLimits.maxTextureDimension2D,maxRenderTextureSize:this._deviceLimits.maxTextureDimension2D,maxVertexAttribs:this._deviceLimits.maxVertexAttributes,maxVaryingVectors:this._deviceLimits.maxInterStageShaderVariables,maxFragmentUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),maxVertexUniformVectors:Math.floor(this._deviceLimits.maxUniformBufferBindingSize/4),standardDerivatives:!0,astc:this._deviceEnabledExtensions.indexOf(tW.TextureCompressionASTC)>=0||void 0,s3tc:this._deviceEnabledExtensions.indexOf(tW.TextureCompressionBC)>=0||void 0,pvrtc:null,etc1:null,etc2:this._deviceEnabledExtensions.indexOf(tW.TextureCompressionETC2)>=0||void 0,bptc:this._deviceEnabledExtensions.indexOf(tW.TextureCompressionBC)>=0||void 0,maxAnisotropy:16,uintIndices:!0,fragmentDepthSupported:!0,highPrecisionShaderSupported:!0,colorBufferFloat:!0,supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:this._deviceEnabledExtensions.indexOf(tW.RG11B10UFloatRenderable)>=0,textureFloat:!0,textureFloatLinearFiltering:this._deviceEnabledExtensions.indexOf(tW.Float32Filterable)>=0,textureFloatRender:!0,textureHalfFloat:!0,textureHalfFloatLinearFiltering:!0,textureHalfFloatRender:!0,textureLOD:!0,texelFetch:!0,drawBuffersExtension:!0,depthTextureExtension:!0,vertexArrayObject:!1,instancedArrays:!0,timerQuery:"undefined"!=typeof BigUint64Array&&-1!==this._deviceEnabledExtensions.indexOf(tW.TimestampQuery)||void 0,supportOcclusionQuery:"undefined"!=typeof BigUint64Array,canUseTimestampForTimerQuery:!0,multiview:!1,oculusMultiview:!1,parallelShaderCompile:void 0,blendMinMax:!0,maxMSAASamples:4,canUseGLInstanceID:!0,canUseGLVertexID:!0,supportComputeShaders:!0,supportSRGBBuffers:!0,supportTransformFeedbacks:!1,textureMaxLevel:!0,texture2DArrayMaxLayerCount:this._deviceLimits.maxTextureArrayLayers,disableMorphTargetTexture:!1},this._caps.parallelShaderCompile=null,this._features={forceBitmapOverHTMLImageElement:!0,supportRenderAndCopyToLodForFloatTextures:!0,supportDepthStencilTexture:!0,supportShadowSamplers:!0,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:!0,trackUbosInFrame:!0,checkUbosContentBeforeUpload:!0,supportCSM:!0,basisNeedsPOT:!1,support3DTextures:!0,needTypeSuffixInShaderConstants:!0,supportMSAA:!0,supportSSAO2:!0,supportExtendedTextureFormats:!0,supportSwitchCaseInShader:!0,supportSyncTextureRead:!1,needsInvertingBitmap:!1,useUBOBindingCache:!1,needShaderCodeInlining:!0,needToAlwaysBindUniformBuffers:!0,supportRenderPasses:!0,supportSpriteInstancing:!0,forceVertexBufferStrideMultiple4Bytes:!0,_collectUbosUpdatedInFrame:!1}}_initializeContextAndSwapChain(){if(!this._renderingCanvas)throw"The rendering canvas has not been set!";this._context=this._renderingCanvas.getContext("webgpu"),this._configureContext(),this._colorFormat=this._options.swapChainFormat,this._mainRenderPassWrapper.colorAttachmentGPUTextures=[new cp],this._mainRenderPassWrapper.colorAttachmentGPUTextures[0].format=this._colorFormat,this._setColorFormat(this._mainRenderPassWrapper)}_initializeMainAttachments(){let e;if(!this._bufferManager)return;this.flushFramebuffer(),this._mainTextureExtends={width:this.getRenderWidth(!0),height:this.getRenderHeight(!0),depthOrArrayLayers:1};let t=new Float32Array([this.getRenderHeight(!0)]);if(this._bufferManager.setSubData(this._ubInvertY,4,t),this._bufferManager.setSubData(this._ubDontInvertY,4,t),this._options.antialias){let t={label:`Texture_MainColor_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}_antialiasing`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tj.E2d,format:this._options.swapChainFormat,usage:tq.RenderAttachment};this._mainTexture&&this._textureHelper.releaseTexture(this._mainTexture),this._mainTexture=this._device.createTexture(t),e=[{view:this._mainTexture.createView({label:"TextureView_MainColor_antialiasing",dimension:tj.E2d,format:this._options.swapChainFormat,mipLevelCount:1,arrayLayerCount:1}),clearValue:new rm.HE(0,0,0,1),loadOp:ip.Clear,storeOp:i_.Store}]}else e=[{view:void 0,clearValue:new rm.HE(0,0,0,1),loadOp:ip.Clear,storeOp:i_.Store}];this._mainRenderPassWrapper.depthTextureFormat=this.isStencilEnable?tQ.Depth24PlusStencil8:tQ.Depth32Float,this._setDepthTextureFormat(this._mainRenderPassWrapper),this._setColorFormat(this._mainRenderPassWrapper);let i={label:`Texture_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,size:this._mainTextureExtends,mipLevelCount:1,sampleCount:this._mainPassSampleCount,dimension:tj.E2d,format:this._mainRenderPassWrapper.depthTextureFormat,usage:tq.RenderAttachment};this._depthTexture&&this._textureHelper.releaseTexture(this._depthTexture),this._depthTexture=this._device.createTexture(i);let r={view:this._depthTexture.createView({label:`TextureView_MainDepthStencil_${this._mainTextureExtends.width}x${this._mainTextureExtends.height}`,dimension:tj.E2d,format:this._depthTexture.format,mipLevelCount:1,arrayLayerCount:1}),depthClearValue:this._clearDepthValue,depthLoadOp:ip.Clear,depthStoreOp:i_.Store,stencilClearValue:this._clearStencilValue,stencilLoadOp:this.isStencilEnable?ip.Clear:void 0,stencilStoreOp:this.isStencilEnable?i_.Store:void 0};this._mainRenderPassWrapper.renderPassDescriptor={label:"MainRenderPass",colorAttachments:e,depthStencilAttachment:r}}_configureContext(){this._context.configure({device:this._device,format:this._options.swapChainFormat,usage:tq.RenderAttachment|tq.CopySrc,alphaMode:this.premultipliedAlpha?ig.Premultiplied:ig.Opaque})}_rebuildBuffers(){for(let e of(super._rebuildBuffers(),this._storageBuffers))e.getBuffer().engineId!==this.uniqueId&&e._rebuild()}_restoreEngineAfterContextLost(e){cU.ResetCache(),cj.ResetCache();let t=e=>{var t;for(let i of e){for(let e of i.meshes){let t=e.subMeshes;if(t)for(let e of t)e._drawWrappers=[]}for(let e of i.materials)null===(t=e._materialContext)||void 0===t||t.reset()}};t(this.scenes),t(this._virtualScenes);let i=[];for(let e of this._uniformBuffers)0>e.name.indexOf("leftOver")&&i.push(e);this._uniformBuffers=i,super._restoreEngineAfterContextLost(e)}setSize(e,t,i=!1){return!!super.setSize(e,t,i)&&(this.dbgVerboseLogsForFirstFrames&&(void 0===this._count&&(this._count=0),(!this._count||this._count=0,s=t.indexOf(ds)>=0,n=i===nG.x.GLSL?this._compileRawShaderToSpirV(e,"vertex"):e,a=i===nG.x.GLSL?this._compileRawShaderToSpirV(t,"fragment"):t;return this._createPipelineStageDescriptor(n,a,i,r,s)}_compilePipelineStageDescriptor(e,t,i,r){this.onBeforeShaderCompilationObservable.notifyObservers(this);let s=e.indexOf(ds)>=0,n=t.indexOf(ds)>=0,a="#version 450\n",o=r===nG.x.GLSL?this._compileShaderToSpirV(e,"vertex",i,a):this._getWGSLShader(e,"vertex",i),l=r===nG.x.GLSL?this._compileShaderToSpirV(t,"fragment",i,a):this._getWGSLShader(t,"fragment",i),h=this._createPipelineStageDescriptor(o,l,r,s,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),h}createRawShaderProgram(){throw"Not available on WebGPU"}createShaderProgram(){throw"Not available on WebGPU"}inlineShaderCode(e){let t=new uU(e);return t.debug=!1,t.processCode(),t.code}createPipelineContext(e){return new uJ(e,this)}createMaterialContext(){return new cH}createDrawContext(){return new cX(this._bufferManager)}_preparePipelineContext(e,t,i,r,s,n,a,o){let l=e.shaderProcessingContext.shaderLanguage;this.dbgShowShaderCode&&(rb.Y.Log(["defines",o]),rb.Y.Log(t),rb.Y.Log(i),rb.Y.Log("***********************************************")),e.sources={fragment:i,vertex:t,rawVertex:s,rawFragment:n},r?e.stages=this._compileRawPipelineStageDescriptor(t,i,l):e.stages=this._compilePipelineStageDescriptor(t,i,o,l)}getAttributes(e,t){let i=Array(t.length);for(let r=0;r0,l._cachedWrapU=0,l._cachedWrapV=0,l._useSRGBBuffer=o.useSRGBBuffer,l.label=o.label,this._internalTexturesCache.push(l),i||this._textureHelper.createGPUTextureForInternalTexture(l,h,u,c||1,o.creationFlags),l}createTexture(e,t,i,r,s=3,n=null,a=null,o=null,l=null,h=null,u=null,c,d,p,_){return this._createTextureBase(e,t,i,r,s,n,a,(e,t,i,r,s,n,a,o)=>{var l;if(e.baseWidth=r.width,e.baseHeight=r.height,e.width=r.width,e.height=r.height,e.format=-1!==e.format?e.format:null!=h?h:5,e.type=-1!==e.type?e.type:0,e._creationFlags=null!=p?p:0,o(e.width,e.height,r,t,e,()=>{}),null===(l=e._hardwareTexture)||void 0===l?void 0:l.underlyingResource)n||a||this._generateMipmaps(e,this._uploadEncoder);else{let t=this._textureHelper.createGPUTextureForInternalTexture(e,r.width,r.height,void 0,p);!cd.IsImageBitmap(r)||(this._textureHelper.updateTexture(r,e,r.width,r.height,e.depth,t.format,0,0,s,!1,0,0),n||a||this._generateMipmaps(e,this._uploadEncoder))}i&&i.removePendingData(e),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()},()=>!1,o,l,h,u,c,d,_)}wrapWebGPUTexture(e){let t=new cp(e),i=new sq.l(this,sq.S.Unknown,!0);return i._hardwareTexture=t,i.isReady=!0,i}wrapWebGLTexture(){throw Error("wrapWebGLTexture is not supported, use wrapWebGPUTexture instead.")}generateMipMapsForCubemap(e){var t;e.generateMipMaps&&((null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource)||this._textureHelper.createGPUTextureForInternalTexture(e),this._generateMipmaps(e))}updateTextureSamplingMode(e,t,i=!1){i&&(t.generateMipMaps=!0,this._generateMipmaps(t)),t.samplingMode=e}updateTextureWrappingMode(e,t,i=null,r=null){null!==t&&(e._cachedWrapU=t),null!==i&&(e._cachedWrapV=i),(e.is2DArray||e.is3D)&&null!==r&&(e._cachedWrapR=r)}updateTextureDimensions(e,t,i,r=1){if(!e._hardwareTexture||e.width===t&&e.height===i&&e.depth===r)return;let s=e._hardwareTexture.textureAdditionalUsages;e._hardwareTexture.release(),this._textureHelper.createGPUTextureForInternalTexture(e,t,i,r,s)}_setInternalTexture(e,t,i){if(i=null!=i?i:e,this._currentEffect){let r=this._currentEffect._pipelineContext.shaderProcessingContext.availableTextures[i];if(this._currentMaterialContext.setTexture(e,t),r&&r.autoBindSampler){let e=i+uZ.AutoSamplerSuffix;this._currentMaterialContext.setSampler(e,t)}}}setTexture(e,t,i,r){this._setTexture(e,i,!1,!1,r,r)}setTextureArray(e,t,i,r){for(let e=0;e0;for(let t in e){let s=e[t],n=i[t],a=n.group,o=n.binding,l=s.type,h=s.object,u=s.indexInGroupEntries,c=this._bindGroupEntries[a];switch(c||(c=this._bindGroupEntries[a]=[]),l){case tU.Sampler:void 0!==u&&r?c[u].resource=this._cacheSampler.getSampler(h):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._cacheSampler.getSampler(h)}));break;case tU.Texture:case tU.TextureWithoutSampler:{let e=h._texture._hardwareTexture;void 0!==u&&r?(l===tU.Texture&&(c[u++].resource=this._cacheSampler.getSampler(h._texture)),c[u].resource=e.view):(s.indexInGroupEntries=c.length,l===tU.Texture&&c.push({binding:o-1,resource:this._cacheSampler.getSampler(h._texture)}),c.push({binding:o,resource:e.view}));break}case tU.StorageTexture:{let e=h._texture._hardwareTexture;(e.textureAdditionalUsages&tq.StorageBinding)==0&&rb.Y.Error(`computeDispatch: The texture (name=${h.name}, uniqueId=${h.uniqueId}) is not a storage texture!`,50),void 0!==u&&r?c[u].resource=e.viewForWriting:(s.indexInGroupEntries=c.length,c.push({binding:o,resource:e.viewForWriting}));break}case tU.ExternalTexture:{let e=h.underlyingResource;void 0!==u&&r?c[u].resource=this._device.importExternalTexture({source:e}):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:this._device.importExternalTexture({source:e})}));break}case tU.UniformBuffer:case tU.StorageBuffer:{let e=(tU.UniformBuffer,h).getBuffer(),t=e.underlyingResource;void 0!==u&&r?(c[u].resource.buffer=t,c[u].resource.size=e.capacity):(s.indexInGroupEntries=c.length,c.push({binding:o,resource:{buffer:t,offset:0,size:e.capacity}}))}}}for(let e=0;e0&&h.dispatchWorkgroups(r,s,n),h.end(),o&&(this._timestampQuery.endPass(this._timestampIndex,o),this._timestampIndex+=2)},da.prototype.releaseComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e].getPipelineContext();this._deleteComputePipelineContext(t)}this._compiledComputeEffects={}},da.prototype._prepareComputePipelineContext=function(e,t,i,r,s){this.dbgShowShaderCode&&(rb.Y.Log(r),rb.Y.Log(t)),e.sources={compute:t,rawCompute:i},e.stage=this._createComputePipelineStageDescriptor(t,r,s)},da.prototype._releaseComputeEffect=function(e){this._compiledComputeEffects[e._key]&&(delete this._compiledComputeEffects[e._key],this._deleteComputePipelineContext(e.getPipelineContext()))},da.prototype._rebuildComputeEffects=function(){for(let e in this._compiledComputeEffects){let t=this._compiledComputeEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}},da.prototype._deleteComputePipelineContext=function(e){e&&e.dispose()},da.prototype._createComputePipelineStageDescriptor=function(e,t,i){return t=t?"//"+t.split("\n").join("\n//")+"\n":"",{module:this._device.createShaderModule({code:t+e}),entryPoint:i}},da.prototype._createDepthStencilCubeTexture=function(e,t){let i=new sq.l(this,sq.S.DepthStencil);i.isCube=!0;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1},t);return i.format=r.generateStencil?13:14,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i),this._internalTexturesCache.push(i),i},da.prototype.createCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!1,h=0,u=0,c=null,d=!1){return this.createCubeTextureBase(e,t,i,!!r,s,n,a,o,l,h,u,c,null,(e,t)=>{let i=t[0].width;this._setCubeMapTextureParams(e,!r),e.format=null!=a?a:-1;let n=this._textureHelper.createGPUTextureForInternalTexture(e,i,i);this._textureHelper.updateCubeTextures(t,n.underlyingResource,i,i,n.format,!1,!1,0,0),r||this._generateMipmaps(e,this._uploadEncoder),e.isReady=!0,e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),s&&s()},!!d)},da.prototype._setCubeMapTextureParams=function(e,t,i){e.samplingMode=t?3:2,e._cachedWrapU=0,e._cachedWrapV=0,i&&(e._maxLodLevel=i)},da.prototype._debugPushGroup=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.pushDebugGroup(e):this._currentRenderPass?this._currentRenderPass.pushDebugGroup(e):this._pendingDebugCommands.push(["push",e]))},da.prototype._debugPopGroup=function(e){this._options.enableGPUDebugMarkers&&(0===e||1===e?this._renderEncoder.popDebugGroup():this._currentRenderPass?this._currentRenderPass.popDebugGroup():this._pendingDebugCommands.push(["pop",null]))},da.prototype._debugInsertMarker=function(e,t){this._options.enableGPUDebugMarkers&&(0===t||1===t?this._renderEncoder.insertDebugMarker(e):this._currentRenderPass?this._currentRenderPass.insertDebugMarker(e):this._pendingDebugCommands.push(["insert",e]))},da.prototype._debugFlushPendingCommands=function(){for(let e=0;e{let i=d.width,n=a(e);if(!n)return;let h=[0,2,4,1,3,5];if(o){let e=4===r,t=o(n),a=d._hardwareTexture,l=[0,1,2,3,4,5];for(let r=0;r>r,o=[];for(let i=0;i<6;i++){let a=t[r][l[i]];e&&(a=dd(a,n,n,s)),o.push(new Uint8Array(a.buffer,a.byteOffset,a.byteLength))}this._textureHelper.updateCubeTextures(o,a.underlyingResource,n,n,a.format,c,!1,0,0)}}else{let e=[];for(let t=0;t<6;t++)e.push(n[h[t]]);this.updateRawCubeTexture(d,e,r,s,c)}d.isReady=!0,null==t||t.removePendingData(d),l&&l()};return this._loadFile(e,e=>{p(e)},void 0,null==t?void 0:t.offlineProvider,!0,(e,i)=>{null==t||t.removePendingData(d),h&&e&&h(e.status+" "+e.statusText,i)}),d},da.prototype.createRawTexture3D=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=sq.S.Raw3D,d=new sq.l(this,c);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is3D=!0,d._creationFlags=u,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,void 0,u),this.updateRawTexture3D(d,e,s,a,l,h),this._internalTexturesCache.push(d),d},da.prototype.updateRawTexture3D=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture;4===i&&(t=dd(t,e.width,e.height,n));let a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(a,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},da.prototype.createRawTexture2DArray=function(e,t,i,r,s,n,a,o,l=null,h=0,u=0){let c=sq.S.Raw2DArray,d=new sq.l(this,c);return d.baseWidth=t,d.baseHeight=i,d.baseDepth=r,d.width=t,d.height=i,d.depth=r,d.format=s,d.type=h,d.generateMipMaps=n,d.samplingMode=o,d.is2DArray=!0,d._creationFlags=u,this._doNotHandleContextLost||(d._bufferView=e),this._textureHelper.createGPUTextureForInternalTexture(d,t,i,r,u),this.updateRawTexture2DArray(d,e,s,a,l,h),this._internalTexturesCache.push(d),d},da.prototype.updateRawTexture2DArray=function(e,t,i,r,s=null,n=0){if(this._doNotHandleContextLost||(e._bufferView=t,e.format=i,e.invertY=r,e._compression=s),t){let s=e._hardwareTexture;4===i&&(t=dd(t,e.width,e.height,n));let a=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);this._textureHelper.updateTexture(a,e,e.width,e.height,e.depth,s.format,0,0,r,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e,this._uploadEncoder)}e.isReady=!0},da.prototype._readTexturePixels=function(e,t,i,r=-1,s=0,n=null,a=!0,o=!1,l=0,h=0){let u=e._hardwareTexture;return a&&this.flushFramebuffer(),this._textureHelper.readPixels(u.underlyingResource,l,h,t,i,u.format,r,s,n,o)},da.prototype._readTexturePixelsSync=function(){throw"_readTexturePixelsSync is unsupported in WebGPU!"};class dp extends nU{constructor(e,t,i,r,s){super(e,t,i,r,s),r.enableGPUTimingMeasurements&&(this.gpuTimeInFrame=new hp)}}da.prototype._createHardwareRenderTargetWrapper=function(e,t,i){let r=new dp(e,t,i,this);return this._renderTargetWrapperCache.push(r),r},da.prototype.createRenderTargetTexture=function(e,t){var i,r,s;let n=this._createHardwareRenderTargetWrapper(!1,!1,e),a={};void 0!==t&&"object"==typeof t?(a.generateMipMaps=t.generateMipMaps,a.generateDepthBuffer=void 0===t.generateDepthBuffer||t.generateDepthBuffer,a.generateStencilBuffer=a.generateDepthBuffer&&t.generateStencilBuffer,a.samplingMode=void 0===t.samplingMode?3:t.samplingMode,a.creationFlags=null!==(i=t.creationFlags)&&void 0!==i?i:0,a.noColorAttachment=!!t.noColorAttachment,a.samples=t.samples,a.label=t.label):(a.generateMipMaps=t,a.generateDepthBuffer=!0,a.generateStencilBuffer=!1,a.samplingMode=3,a.creationFlags=0,a.noColorAttachment=!1);let o=a.noColorAttachment?null:this._createInternalTexture(e,t,!0,sq.S.RenderTarget);return n.label=null!==(r=a.label)&&void 0!==r?r:"RenderTargetWrapper",n._samples=null!==(s=a.samples)&&void 0!==s?s:1,n._generateDepthBuffer=a.generateDepthBuffer,n._generateStencilBuffer=!!a.generateStencilBuffer,n.setTextures(o),(n._generateDepthBuffer||n._generateStencilBuffer)&&n.createDepthStencilTexture(0,!1,n._generateStencilBuffer,n.samples,a.generateStencilBuffer?13:14,a.label?a.label+"-DepthStencil":void 0),o&&(void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(o.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(o,void 0,void 0,void 0,a.creationFlags),void 0!==t&&"object"==typeof t&&t.createMipMaps&&!a.generateMipMaps&&(o.generateMipMaps=!1)),n},da.prototype._createDepthStencilTexture=function(e,t){let i=new sq.l(this,sq.S.DepthStencil);i.label=t.label;let r=Object.assign({bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,samples:1,depthTextureFormat:t.generateStencil?13:14},t);i.format=r.depthTextureFormat,this._setupDepthStencilTexture(i,e,r.generateStencil,r.bilinearFiltering,r.comparisonFunction,r.samples),this._textureHelper.createGPUTextureForInternalTexture(i);let s=i._hardwareTexture;return i.type=cd.GetTextureTypeFromFormat(s.format),this._internalTexturesCache.push(i),i},da.prototype._setupDepthStencilTexture=function(e,t,i,r,s,n=1){let a=t.width||t,o=t.height||t,l=t.layers||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=l>0,e.depth=l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=r?2:1,e.type=1,e._comparisonFunction=s,e._cachedWrapU=0,e._cachedWrapV=0},da.prototype.updateRenderTargetTextureSampleCount=function(e,t){return e&&e.texture&&e.samples!==t&&(t=Math.min(t,this.getCaps().maxMSAASamples),this._textureHelper.createMSAATexture(e.texture,t),e._depthStencilTexture&&(this._textureHelper.createMSAATexture(e._depthStencilTexture,t),e._depthStencilTexture.samples=t),e._samples=t,e.texture.samples=t),t},da.prototype.createRenderTargetCubeTexture=function(e,t){var i;let r=this._createHardwareRenderTargetWrapper(!1,!0,e),s=Object.assign({generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:0,samplingMode:3,format:5,samples:1},t);s.generateStencilBuffer=s.generateDepthBuffer&&s.generateStencilBuffer,r.label=null!==(i=s.label)&&void 0!==i?i:"RenderTargetWrapper",r._generateDepthBuffer=s.generateDepthBuffer,r._generateStencilBuffer=s.generateStencilBuffer;let n=new sq.l(this,sq.S.RenderTarget);return n.width=e,n.height=e,n.depth=0,n.isReady=!0,n.isCube=!0,n.samples=s.samples,n.generateMipMaps=s.generateMipMaps,n.samplingMode=s.samplingMode,n.type=s.type,n.format=s.format,this._internalTexturesCache.push(n),r.setTextures(n),(r._generateDepthBuffer||r._generateStencilBuffer)&&r.createDepthStencilTexture(0,void 0===s.samplingMode||2===s.samplingMode||2===s.samplingMode||3===s.samplingMode||3===s.samplingMode||5===s.samplingMode||6===s.samplingMode||7===s.samplingMode||11===s.samplingMode,r._generateStencilBuffer,r.samples),t&&t.createMipMaps&&!s.generateMipMaps&&(n.generateMipMaps=!0),this._textureHelper.createGPUTextureForInternalTexture(n),t&&t.createMipMaps&&!s.generateMipMaps&&(n.generateMipMaps=!1),r},nd.Q.prototype.setTextureSampler=function(e,t){this._engine.setTextureSampler(e,t)},da.prototype.setTextureSampler=function(e,t){var i;null===(i=this._currentMaterialContext)||void 0===i||i.setSampler(e,t)},nd.Q.prototype.setStorageBuffer=function(e,t){this._engine.setStorageBuffer(e,t)},da.prototype.createStorageBuffer=function(e,t,i){return this._createBuffer(e,32|t,i)},da.prototype.updateStorageBuffer=function(e,t,i,r){let s;void 0===i&&(i=0),void 0===r?r=(s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t).byteLength:s=t instanceof Array?new Float32Array(t):t instanceof ArrayBuffer?new Uint8Array(t):t,this._bufferManager.setSubData(e,i,s,0,r)},da.prototype.readFromStorageBuffer=function(e,t,i,r,s){i=i||e.capacity;let n=this._bufferManager.createRawBuffer(i,tX.MapRead|tX.CopyDst,void 0,"TempReadFromStorageBuffer");return this._renderEncoder.copyBufferToBuffer(e.underlyingResource,null!=t?t:0,n,0,i),new Promise((e,t)=>{let a=()=>{n.mapAsync(tY.Read,0,i).then(()=>{let t=n.getMappedRange(0,i),s=r;if(void 0===s)(s=new Uint8Array(i)).set(new Uint8Array(t));else{let e=s.constructor;(s=new e(s.buffer)).set(new e(t))}n.unmap(),this._bufferManager.releaseBuffer(n),e(s)},i=>{this.isDisposed?e(new Uint8Array):t(i)})};s?(this.flushFramebuffer(),a()):this.onEndFrameObservable.addOnce(()=>{a()})})},da.prototype.setStorageBuffer=function(e,t){var i,r;null===(i=this._currentDrawContext)||void 0===i||i.setBuffer(e,null!==(r=null==t?void 0:t.getBuffer())&&void 0!==r?r:null)},da.prototype.updateVideoTexture=function(e,t,i){var r;if(!e||e._isDisabled)return;void 0===this._videoTextureSupported&&(this._videoTextureSupported=!0);let s=e._hardwareTexture;((null===(r=e._hardwareTexture)||void 0===r?void 0:r.underlyingResource)||(s=this._textureHelper.createGPUTextureForInternalTexture(e)),t&&void 0!==t.underlyingResource)?(this._textureHelper.copyVideoToTexture(t,e,s.format,!i),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0):t&&this.createImageBitmap(t).then(t=>{this._textureHelper.updateTexture(t,e,e.width,e.height,e.depth,s.format,0,0,!i,!1,0,0),e.generateMipMaps&&this._generateMipmaps(e),e.isReady=!0}).catch(()=>{e.isReady=!0})},i(856);class d_{}d_.COPY=1,d_.CUT=2,d_.PASTE=3;class df extends hy{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}get disableMaterial(){return this._disableMaterial}constructor(e,t=rm.Wo.Gray(),i=hb.DefaultUtilityLayer,r=null,s=1,n=rm.Wo.Yellow(),a=rm.Wo.Gray()){var o,l,h,u,c,d,p;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new r_.y$,this.uniformScaling=!1,this.sensitivity=1,this.dragScale=1,this.incrementalSnap=!1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._tmpVector=new rf.P(0,0,0),this._incrementalStartupValue=rf.P.Zero(),this._parent=r,this._coloredMaterial=new lj("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new rm.Wo(.1,.1,.1)),this._hoverMaterial=new lj("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=n,this._disableMaterial=new lj("",i.utilityLayerScene),this._disableMaterial.diffuseColor=a,this._disableMaterial.alpha=.4,this._gizmoMesh=new sp.Kj("axis",i.utilityLayerScene);let{arrowMesh:_,arrowTail:f}=this._createGizmoMesh(this._gizmoMesh,s),m=this._createGizmoMesh(this._gizmoMesh,s+4,!0);this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,hy.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3);let g=_.position.clone(),v=f.position.clone(),x=f.scaling.clone(),T=e=>{let t=3/this._rootMesh.scaling.length()*e*6;_.position.z+=t/3.5,f.scaling.y+=t,this.dragScale=f.scaling.y,f.position.z=_.position.z/2},S=()=>{_.position.set(g.x,g.y,g.z),f.position.set(v.x,v.y,v.z),f.scaling.set(x.x,x.y,x.z),this.dragScale=f.scaling.y,this._dragging=!1};this.dragBehavior=new nt({dragAxis:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.updateDragPlane=!1,this._rootMesh.addBehavior(this.dragBehavior);let E=0,C=0,b={snapDistance:0};this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let i=this.sensitivity*t.dragDistance*(3*this.scaleRatio/this._rootMesh.scaling.length()),r=this._tmpVector,s=!1,n=0;if(this.uniformScaling?r.setAll(.57735):r.copyFrom(e),0==this.snapDistance)r.scaleToRef(i,r);else{E+=i,C+=i;let e=this.incrementalSnap?C:E;Math.abs(e)>this.snapDistance?(n=Math.floor(Math.abs(e)/this.snapDistance),e<0&&(n*=-1),E%=this.snapDistance,r.scaleToRef(this.snapDistance*n,r),s=!0):r.scaleInPlace(0)}r.addInPlaceFromFloats(1,1,1),r.x=Math.abs(r.x)0&&this.incrementalSnap?(this.attachedNode.getWorldMatrix().decompose(void 0,rf.jp.Quaternion[0],rf.jp.Vector3[2],hy.PreserveScaling?a:void 0),r.addInPlace(this._incrementalStartupValue),r.addInPlaceFromFloats(-1,-1,-1),r.x=Math.abs(r.x)*(this._incrementalStartupValue.x>0?1:-1),r.y=Math.abs(r.y)*(this._incrementalStartupValue.y>0?1:-1),r.z=Math.abs(r.z)*(this._incrementalStartupValue.z>0?1:-1),rf.y3.ComposeToRef(r,rf.jp.Quaternion[0],rf.jp.Vector3[2],rf.jp.Matrix[1])):(rf.y3.ScalingToRef(r.x,r.y,r.z,rf.jp.Matrix[2]),rf.jp.Matrix[2].multiplyToRef(this.attachedNode.getWorldMatrix(),rf.jp.Matrix[1])),rf.jp.Matrix[1].decompose(rf.jp.Vector3[1],void 0,void 0,hy.PreserveScaling?a:void 0),1e5>Math.abs(rf.jp.Vector3[1].x)&&1e5>Math.abs(rf.jp.Vector3[1].y)&&1e5>Math.abs(rf.jp.Vector3[1].z)&&this.attachedNode.getWorldMatrix().copyFrom(rf.jp.Matrix[1]),s&&(b.snapDistance=this.snapDistance*n,this.onSnapObservable.notifyObservers(b)),this._matrixChanged()}}),this.dragBehavior.onDragStartObservable.add(()=>{var e;this._dragging=!0;let t=this.attachedNode._isMesh?this.attachedNode:void 0;null===(e=this.attachedNode)||void 0===e||e.getWorldMatrix().decompose(this._incrementalStartupValue,void 0,void 0,hy.PreserveScaling?t:void 0),E=0,C=0}),this.dragBehavior.onDragObservable.add(e=>T(e.dragDistance)),this.dragBehavior.onDragEndObservable.add(S),null===(h=null===(l=null===(o=null==r?void 0:r.uniformScaleGizmo)||void 0===o?void 0:o.dragBehavior)||void 0===l?void 0:l.onDragObservable)||void 0===h||h.add(e=>T(e.delta.y)),null===(d=null===(c=null===(u=null==r?void 0:r.uniformScaleGizmo)||void 0===u?void 0:u.dragBehavior)||void 0===c?void 0:c.onDragEndObservable)||void 0===d||d.add(S);let y={gizmoMeshes:[_,f],colliderMeshes:[m.arrowMesh,m.arrowTail],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(p=this._parent)||void 0===p||p.addToAxisCache(this._gizmoMesh,y),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this._isHovered=-1!=y.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=this.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(y.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(y.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)});let A=i._getSharedGizmoLight();A.includedOnlyMeshes=A.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes())}_createGizmoMesh(e,t,i=!1){let r=hP("yPosMesh",{size:.4*(1+(t-1)/4)},this.gizmoLayer.utilityLayerScene),s=hE("cylinder",{diameterTop:.005*t,height:.275,diameterBottom:.005*t,tessellation:96},this.gizmoLayer.utilityLayerScene);return r.scaling.scaleInPlace(.1),r.material=this._coloredMaterial,r.rotation.x=Math.PI/2,r.position.z+=.3,s.material=this._coloredMaterial,s.position.z+=.1375,s.rotation.x=Math.PI/2,i&&(r.visibility=0,s.visibility=0),e.addChild(r),e.addChild(s),{arrowMesh:r,arrowTail:s}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh,this.attachedNode=this._parent.attachedNode):(this.attachedMesh=null,this.attachedNode=null)}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}setCustomMesh(e,t=!1){super.setCustomMesh(e),t&&(this._rootMesh.getChildMeshes().forEach(e=>{e.material=this._coloredMaterial,e.color&&(e.color=this._coloredMaterial.diffuseColor)}),this._customMeshSet=!1)}}df.MinimumAbsoluteScale=r7.kn;class dm extends hy{get coloredMaterial(){return this._coloredMaterial}get hoverMaterial(){return this._hoverMaterial}set rotationColor(e){this._rotationShaderMaterial.setColor3("rotationColor",e)}get disableMaterial(){return this._disableMaterial}constructor(e,t=rm.Wo.Gray(),i=hb.DefaultUtilityLayer,r=32,s=null,n=!1,a=1,o=rm.Wo.Yellow(),l=rm.Wo.Gray()){var h;super(i),this._pointerObserver=null,this.snapDistance=0,this.onSnapObservable=new r_.y$,this.angle=0,this.sensitivity=1,this._isEnabled=!0,this._parent=null,this._dragging=!1,this._angles=new rf.P,this._parent=s,this._coloredMaterial=new lj("",i.utilityLayerScene),this._coloredMaterial.diffuseColor=t,this._coloredMaterial.specularColor=t.subtract(new rm.Wo(.1,.1,.1)),this._hoverMaterial=new lj("",i.utilityLayerScene),this._hoverMaterial.diffuseColor=o,this._hoverMaterial.specularColor=o,this._disableMaterial=new lj("",i.utilityLayerScene),this._disableMaterial.diffuseColor=l,this._disableMaterial.alpha=.4,this._gizmoMesh=new sp.Kj("",i.utilityLayerScene);let{rotationMesh:u,collider:c}=this._createGizmoMesh(this._gizmoMesh,a,r);this._rotationDisplayPlane=ne("rotationDisplay",{size:.6,updatable:!1},this.gizmoLayer.utilityLayerScene),this._rotationDisplayPlane.rotation.z=.5*Math.PI,this._rotationDisplayPlane.parent=this._gizmoMesh,this._rotationDisplayPlane.setEnabled(!1),nd.Q.ShadersStore.rotationGizmoVertexShader=dm._RotationGizmoVertexShader,nd.Q.ShadersStore.rotationGizmoFragmentShader=dm._RotationGizmoFragmentShader,this._rotationShaderMaterial=new hV("shader",this.gizmoLayer.utilityLayerScene,{vertex:"rotationGizmo",fragment:"rotationGizmo"},{attributes:["position","uv"],uniforms:["worldViewProjection","angles","rotationColor"]}),this._rotationShaderMaterial.backFaceCulling=!1,this.rotationColor=o,this._rotationDisplayPlane.material=this._rotationShaderMaterial,this._rotationDisplayPlane.visibility=.999,this._gizmoMesh.lookAt(this._rootMesh.position.add(e)),this._rootMesh.addChild(this._gizmoMesh,hy.PreserveScaling),this._gizmoMesh.scaling.scaleInPlace(1/3),this.dragBehavior=new nt({dragPlaneNormal:e}),this.dragBehavior.moveAttached=!1,this.dragBehavior.maxDragAngle=dm.MaxDragAngle,this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle=!0,this._rootMesh.addBehavior(this.dragBehavior);let d=new rf.P,p=new rf.y3,_=new rf.P,f=new rf.P;this.dragBehavior.onDragStartObservable.add(e=>{this.attachedNode&&(d.copyFrom(e.dragPlanePoint),this._rotationDisplayPlane.setEnabled(!0),this._rotationDisplayPlane.getWorldMatrix().invertToRef(p),rf.P.TransformCoordinatesToRef(e.dragPlanePoint,p,d),this._angles.x=Math.atan2(d.y,d.x)+Math.PI,this._angles.y=0,this._angles.z=this.updateGizmoRotationToMatchAttachedMesh?1:0,this._dragging=!0,d.copyFrom(e.dragPlanePoint),this._rotationShaderMaterial.setVector3("angles",this._angles),this.angle=0)}),this.dragBehavior.onDragEndObservable.add(()=>{this._dragging=!1,this._rotationDisplayPlane.setEnabled(!1)});let m={snapDistance:0},g=0,v=new rf.y3,x=new rf._f;this.dragBehavior.onDragObservable.add(t=>{if(this.attachedNode){let r=new rf.P(1,1,1),s=new rf._f(0,0,0,1),n=new rf.P(0,0,0);if(this.attachedNode.getWorldMatrix().decompose(r,s,n),!(Math.abs(Math.abs(r.x)-Math.abs(r.y))<=r7.kn&&Math.abs(Math.abs(r.x)-Math.abs(r.z))<=r7.kn)&&this.updateGizmoRotationToMatchAttachedMesh){rb.Y.Warn("Unable to use a rotation gizmo matching mesh rotation with non uniform scaling. Use uniform scaling or set updateGizmoRotationToMatchAttachedMesh to false.");return}s.normalize();let a=this.updateGizmoPositionToMatchAttachedMesh?n:this._rootMesh.absolutePosition,o=t.dragPlanePoint.subtract(a).normalize(),l=d.subtract(a).normalize(),h=rf.P.Cross(o,l),u=rf.P.Dot(o,l),c=Math.atan2(h.length(),u)*this.sensitivity;_.copyFrom(e),f.copyFrom(e),this.updateGizmoRotationToMatchAttachedMesh&&(s.toRotationMatrix(p),f=rf.P.TransformCoordinates(_,p));let T=!1;if(i.utilityLayerScene.activeCamera){let e=i.utilityLayerScene.activeCamera.position.subtract(a).normalize();rf.P.Dot(e,f)>0&&(_.scaleInPlace(-1),f.scaleInPlace(-1),T=!0)}rf.P.Dot(f,h)>0&&(c=-c),rf.jp.Vector3[0].set(c,0,0),this.dragBehavior.validateDrag(rf.jp.Vector3[0])||(c=0);let S=!1;if(0!=this.snapDistance){if(Math.abs(g+=c)>this.snapDistance){let e=Math.floor(Math.abs(g)/this.snapDistance);g<0&&(e*=-1),g%=this.snapDistance,c=this.snapDistance*e,S=!0}else c=0}let E=Math.sin(c/2);if(x.set(_.x*E,_.y*E,_.z*E,Math.cos(c/2)),v.determinant()>0){let e=new rf.P;x.toEulerAnglesToRef(e),rf._f.RotationYawPitchRollToRef(e.y,-e.x,-e.z,x)}if(this.updateGizmoRotationToMatchAttachedMesh)s.multiplyToRef(x,s),s.normalize(),rf.y3.ComposeToRef(r,s,n,this.attachedNode.getWorldMatrix());else{x.toRotationMatrix(rf.jp.Matrix[0]);let e=this.attachedNode.getWorldMatrix().getTranslation();this.attachedNode.getWorldMatrix().multiplyToRef(rf.jp.Matrix[0],this.attachedNode.getWorldMatrix()),this.attachedNode.getWorldMatrix().setTranslation(e)}d.copyFrom(t.dragPlanePoint),S&&(m.snapDistance=c,this.onSnapObservable.notifyObservers(m)),this._angles.y+=c,this.angle+=T?-c:c,this._rotationShaderMaterial.setVector3("angles",this._angles),this._matrixChanged()}});let T=i._getSharedGizmoLight();T.includedOnlyMeshes=T.includedOnlyMeshes.concat(this._rootMesh.getChildMeshes(!1));let S={colliderMeshes:[c],gizmoMeshes:[u],material:this._coloredMaterial,hoverMaterial:this._hoverMaterial,disableMaterial:this._disableMaterial,active:!1,dragBehavior:this.dragBehavior};null===(h=this._parent)||void 0===h||h.addToAxisCache(this._gizmoMesh,S),this._pointerObserver=i.utilityLayerScene.onPointerObservable.add(e=>{var t;if(!this._customMeshSet&&(this.dragBehavior.maxDragAngle=dm.MaxDragAngle,this._isHovered=-1!=S.colliderMeshes.indexOf(null===(t=null==e?void 0:e.pickInfo)||void 0===t?void 0:t.pickedMesh),!this._parent)){let e=S.dragBehavior.enabled?this._isHovered||this._dragging?this._hoverMaterial:this._coloredMaterial:this._disableMaterial;this._setGizmoMeshMaterial(S.gizmoMeshes,e)}}),this.dragBehavior.onEnabledObservable.add(e=>{this._setGizmoMeshMaterial(S.gizmoMeshes,e?this._coloredMaterial:this._disableMaterial)})}_createGizmoMesh(e,t,i){let r=hi("ignore",{diameter:.6,thickness:.03*t,tessellation:i},this.gizmoLayer.utilityLayerScene);r.visibility=0;let s=hi("",{diameter:.6,thickness:.005*t,tessellation:i},this.gizmoLayer.utilityLayerScene);return s.material=this._coloredMaterial,s.rotation.x=Math.PI/2,r.rotation.x=Math.PI/2,e.addChild(s,hy.PreserveScaling),e.addChild(r,hy.PreserveScaling),{rotationMesh:s,collider:r}}_attachedNodeChanged(e){this.dragBehavior&&(this.dragBehavior.enabled=!!e)}set isEnabled(e){this._isEnabled=e,e?this._parent&&(this.attachedMesh=this._parent.attachedMesh):this.attachedMesh=null}get isEnabled(){return this._isEnabled}dispose(){this.onSnapObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this.dragBehavior.detach(),this._gizmoMesh&&this._gizmoMesh.dispose(),this._rotationDisplayPlane&&this._rotationDisplayPlane.dispose(),this._rotationShaderMaterial&&this._rotationShaderMaterial.dispose(),[this._coloredMaterial,this._hoverMaterial,this._disableMaterial].forEach(e=>{e&&e.dispose()}),super.dispose()}}dm.MaxDragAngle=9*Math.PI/20,dm._RotationGizmoVertexShader=` + precision highp float; + attribute vec3 position; + attribute vec2 uv; + uniform mat4 worldViewProjection; + varying vec3 vPosition; + varying vec2 vUV; + + void main(void) { + gl_Position = worldViewProjection * vec4(position, 1.0); + vUV = uv; + }`,dm._RotationGizmoFragmentShader=` + precision highp float; + varying vec2 vUV; + varying vec3 vPosition; + uniform vec3 angles; + uniform vec3 rotationColor; + + #define twopi 6.283185307 + + void main(void) { + vec2 uv = vUV - vec2(0.5); + float angle = atan(uv.y, uv.x) + 3.141592; + float delta = gl_FrontFacing ? angles.y : -angles.y; + float begin = angles.x - delta * angles.z; + float start = (begin < (begin + delta)) ? begin : (begin + delta); + float end = (begin > (begin + delta)) ? begin : (begin + delta); + float len = sqrt(dot(uv,uv)); + float opacity = 1. - step(0.5, len); + + float base = abs(floor(start / twopi)) * twopi; + start += base; + end += base; + + float intensity = 0.; + for (int i = 0; i < 5; i++) + { + intensity += max(step(start, angle) - step(end, angle), 0.); + angle += twopi; + } + gl_FragColor = vec4(rotationColor, min(intensity * 0.25, 0.8)) * opacity; + } + `;class dg extends sE{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=rf.y3.Identity(),this._projectionMatrix=rf.y3.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=rf.P.Zero()),rf.P.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=rf.P.Zero()),rf.P.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=rf.P.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();let e=rf.P.Cross(this.direction,r5.RD.Y),t=rf.P.Cross(e,this.direction);return rf.P.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=rf.P.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?this._currentRenderId=this.getScene().getRenderId():(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=rf.y3.Identity()),rf.y3.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,i){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,i,e):this._setDefaultShadowProjectionMatrix(e,t,i),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){let t=rf.jp.Vector3[0],i=this.position;this.computeTransformedInformation()&&(i=this.transformedPosition),rf.P.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(rf.P.Dot(t,rf.P.Up()))&&(t.z=1e-13);let r=rf.jp.Vector3[1];return i.addToRef(t,r),rf.y3.LookAtLHToRef(i,r,rf.P.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,null!=e?e:this._viewMatrix,null!=t?t:[]),this._projectionMatrix}}(0,sx.gn)([(0,rG.hd)()],dg.prototype,"position",null),(0,sx.gn)([(0,rG.hd)()],dg.prototype,"direction",null),(0,sx.gn)([(0,rG.qC)()],dg.prototype,"shadowMinZ",null),(0,sx.gn)([(0,rG.qC)()],dg.prototype,"shadowMaxZ",null),rW.N.AddNodeConstructor("Light_Type_1",(e,t)=>()=>new dv(e,rf.P.Zero(),t));class dv extends dg{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,i){super(e,i),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 sE.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,i){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,i)}_setDefaultFixedFrustumShadowProjectionMatrix(e){let t=this.getScene().activeCamera;t&&rf.y3.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,i){let r=this.getScene().activeCamera;if(!r)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){let e=rf.P.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let r=Number.MAX_VALUE,s=-Number.MAX_VALUE;for(let n=0;nthis._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.zs&&(s=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=r,this._shadowMaxZ=s)}let s=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,l=this.getScene().getEngine().useReverseDepthBuffer;rf.y3.OrthoOffCenterLHToRef(this._orthoLeft-s*this.shadowOrthoScale,this._orthoRight+s*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,l?o:a,l?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._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):e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this}getDepthMinZ(e){let t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){let t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}function dx(e,t={},i){t.diameter||(t.diameter=1),t.segments||(t.segments=16);let r=hM("",{slice:.5,diameter:t.diameter,segments:t.segments},i),s=hL("",{radius:t.diameter/2,tessellation:3*t.segments+(4-t.segments)},i);s.rotation.x=-Math.PI/2,s.parent=r;let n=sp.Kj.MergeMeshes([s,r],!0);return n.name=e,n}(0,sx.gn)([(0,rG.qC)()],dv.prototype,"shadowFrustumSize",null),(0,sx.gn)([(0,rG.qC)()],dv.prototype,"shadowOrthoScale",null),(0,sx.gn)([(0,rG.qC)()],dv.prototype,"autoUpdateExtends",void 0),(0,sx.gn)([(0,rG.qC)()],dv.prototype,"autoCalcShadowZBounds",void 0),(0,sx.gn)([(0,rG.qC)("orthoLeft")],dv.prototype,"_orthoLeft",void 0),(0,sx.gn)([(0,rG.qC)("orthoRight")],dv.prototype,"_orthoRight",void 0),(0,sx.gn)([(0,rG.qC)("orthoTop")],dv.prototype,"_orthoTop",void 0),(0,sx.gn)([(0,rG.qC)("orthoBottom")],dv.prototype,"_orthoBottom",void 0),sp.Kj.CreateHemisphere=(e,t,i,r)=>dx(e,{segments:t,diameter:i},r),rW.N.AddNodeConstructor("Light_Type_2",(e,t)=>()=>new dT(e,rf.P.Zero(),rf.P.Zero(),0,0,t));class dT extends dg{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()&&(dT._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled(()=>{this._markMeshesAsLightDirty()}):dT._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,i,r,s,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=rf.y3.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=rf.P.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=rf.P.Zero(),this._projectionTextureViewLightMatrix=rf.y3.Zero(),this._projectionTextureProjectionLightMatrix=rf.y3.Zero(),this._projectionTextureScalingMatrix=rf.y3.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=i,this.angle=r,this.exponent=s}getClassName(){return"SpotLight"}getTypeID(){return sE.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;this._shadowAngleScale=this._shadowAngleScale||1;let s=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;rf.y3.PerspectiveFovLHToRef(s,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.direction,this._projectionTextureViewTargetVector),rf.y3.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;let e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,i=e/(e-t),r=1/Math.tan(this._angle/2);rf.y3.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,i,1,0,0,-i*t,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof sj){let e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;rf.y3.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("projectionLightSampler"+t,this.projectionTexture)),this}transferToEffect(e,t){let i;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),i=rf.P.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),i=rf.P.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",i.x,i.y,i.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let i;return i=this.computeTransformedInformation()?rf.P.Normalize(this.transformedDirection):rf.P.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-i.x,-i.y,-i.z):e.setFloat3(t,i.x,i.y,i.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){let t=this._scene.getEngine(),i=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?i:this._scene.getEngine().isNDCHalfZRange?0:i}getDepthMaxZ(e){let t=this._scene.getEngine(),i=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:i}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!!(this.projectionTexture&&this.projectionTexture.isReady())}}(0,sx.gn)([(0,rG.qC)()],dT.prototype,"angle",null),(0,sx.gn)([(0,rG.qC)()],dT.prototype,"innerAngle",null),(0,sx.gn)([(0,rG.qC)()],dT.prototype,"shadowAngleScale",null),(0,sx.gn)([(0,rG.qC)()],dT.prototype,"exponent",void 0),(0,sx.gn)([(0,rG.qC)()],dT.prototype,"projectionTextureLightNear",null),(0,sx.gn)([(0,rG.qC)()],dT.prototype,"projectionTextureLightFar",null),(0,sx.gn)([(0,rG.qC)()],dT.prototype,"projectionTextureUpDirection",null),(0,sx.gn)([(0,rG.oU)("projectedLightTexture")],dT.prototype,"_projectionTexture",void 0);class dS extends hy{constructor(e=hb.DefaultUtilityLayer){super(e),this._cachedPosition=new rf.P,this._cachedForward=new rf.P(0,0,1),this._pointerObserver=null,this.onClickedObservable=new r_.y$,this._light=null,this.attachedMesh=new sf.x("",this.gizmoLayer.utilityLayerScene),this._attachedMeshParent=new s_.Y("parent",this.gizmoLayer.utilityLayerScene),this.attachedMesh.parent=this._attachedMeshParent,this._material=new lj("light",this.gizmoLayer.utilityLayerScene),this._material.diffuseColor=new rm.Wo(.5,.5,.5),this._material.specularColor=new rm.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(e=>{this._light&&(this._isHovered=!!(e.pickInfo&&-1!=this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._light))},s0.kD.POINTERDOWN)}get attachedNode(){return this.attachedMesh}set attachedNode(e){rb.Y.Warn("Nodes cannot be attached to LightGizmo. Attach to a mesh instead.")}set light(e){if(this._light=e,e){this._lightMesh&&this._lightMesh.dispose(),e instanceof hC?this._lightMesh=dS._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof dv?this._lightMesh=dS._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene):e instanceof dT?this._lightMesh=dS._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene):this._lightMesh=dS._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene),this._lightMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._lightMesh.parent=this._rootMesh;let t=this.gizmoLayer._getSharedGizmoLight();if(t.includedOnlyMeshes=t.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(!1)),this._lightMesh.rotationQuaternion=new rf._f,this.attachedMesh.reservedDataStore||(this.attachedMesh.reservedDataStore={}),this.attachedMesh.reservedDataStore.lightGizmo=this,e.parent&&this._attachedMeshParent.freezeWorldMatrix(e.parent.getWorldMatrix()),e.position&&(this.attachedMesh.position.copyFrom(e.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position)),e.direction){this.attachedMesh.setDirection(e.direction),this.attachedMesh.computeWorldMatrix(!0);let t=this._getMeshForward();this._cachedForward.copyFrom(t)}this._update()}}get light(){return this._light}get material(){return this._material}_getMeshForward(){let e=this.attachedMesh.forward;return this.attachedMesh.getScene().useRightHandedSystem&&(e.negateToRef(rf.jp.Vector3[0]),e=rf.jp.Vector3[0]),e}_update(){if(super._update(),this._light){if(this._light.parent&&this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix()),this._light.position){if(this.attachedMesh.position.equals(this._cachedPosition))this.attachedMesh.position.copyFrom(this._light.position),this.attachedMesh.computeWorldMatrix(!0),this._cachedPosition.copyFrom(this.attachedMesh.position);else{let e=this.attachedMesh.position;this._light.position=new rf.P(e.x,e.y,e.z),this._cachedPosition.copyFrom(this.attachedMesh.position)}}if(this._light.direction){let e=this._getMeshForward();rf.P.DistanceSquared(e,this._cachedForward)>1e-4?(this._light.direction=new rf.P(e.x,e.y,e.z),this._cachedForward.copyFrom(e)):rf.P.DistanceSquared(e,this._light.direction)>1e-4&&(this.attachedMesh.setDirection(this._light.direction),this.attachedMesh.computeWorldMatrix(!0),this._cachedForward.copyFrom(e))}}}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._material.dispose(),super.dispose(),this._attachedMeshParent.dispose()}static _CreateHemisphericLightMesh(e){let t=new sp.Kj("hemisphereLight",e),i=dx(t.name,{segments:10,diameter:1},e);return i.position.z=-.15,i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(3,e).parent=t,t.scaling.scaleInPlace(dS._Scale),t.rotation.x=Math.PI/2,t}static _CreatePointLightMesh(e){let t=new sp.Kj("pointLight",e),i=hM(t.name,{segments:10,diameter:1},e);return i.rotation.x=Math.PI/2,i.parent=t,this._CreateLightLines(5,e).parent=t,t.scaling.scaleInPlace(dS._Scale),t.rotation.x=Math.PI/2,t}static _CreateSpotLightMesh(e){let t=new sp.Kj("spotLight",e);hM(t.name,{segments:10,diameter:1},e).parent=t;let i=dx(t.name,{segments:10,diameter:2},e);return i.parent=t,i.rotation.x=-Math.PI/2,this._CreateLightLines(2,e).parent=t,t.scaling.scaleInPlace(dS._Scale),t.rotation.x=Math.PI/2,t}static _CreateDirectionalLightMesh(e){let t=new sp.Kj("directionalLight",e),i=new sp.Kj(t.name,e);i.parent=t,hM(t.name,{diameter:1.2,segments:10},e).parent=i;let r=hE(t.name,{updatable:!1,height:6,diameterTop:.3,diameterBottom:.3,tessellation:6,subdivisions:1},e);r.parent=i;let s=r.clone(t.name);s.scaling.y=.5,s.position.x+=1.25;let n=r.clone(t.name);n.scaling.y=.5,n.position.x+=-1.25;let a=hE(t.name,{updatable:!1,height:1,diameterTop:0,diameterBottom:.6,tessellation:6,subdivisions:1},e);return a.position.y+=3,a.parent=i,(s=a.clone(t.name)).position.y=1.5,s.position.x+=1.25,(n=a.clone(t.name)).position.y=1.5,n.position.x+=-1.25,i.scaling.scaleInPlace(dS._Scale),i.rotation.z=Math.PI/2,i.rotation.y=Math.PI/2,t}}dS._Scale=.007,dS._CreateLightLines=(e,t)=>{let i=new sp.Kj("root",t);i.rotation.x=Math.PI/2;let r=new sp.Kj("linePivot",t);r.parent=i;let s=hE("line",{updatable:!1,height:2,diameterTop:.2,diameterBottom:.3,tessellation:6,subdivisions:1},t);if(s.position.y=s.scaling.y/2+1.2,s.parent=r,e<2)return r;for(let e=0;e<4;e++){let t=r.clone("lineParentClone");t.rotation.z=Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}if(e<3)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI/2,t.rotation.y=Math.PI/2*e}if(e<4)return i;for(let e=0;e<4;e++){let t=r.clone("linePivotClone");t.rotation.z=Math.PI+Math.PI/4,t.rotation.y=Math.PI/2+Math.PI/2*e,t.getChildMeshes()[0].scaling.y=.5,t.getChildMeshes()[0].scaling.x=t.getChildMeshes()[0].scaling.z=.8,t.getChildMeshes()[0].position.y=t.getChildMeshes()[0].scaling.y/2+1.2}return e<5||(r.clone("linePivotClone").rotation.z=Math.PI),i};class dE extends hy{constructor(e=hb.DefaultUtilityLayer,t){super(e),this._pointerObserver=null,this.onClickedObservable=new r_.y$,this._camera=null,this._invProjection=new rf.y3,this._material=new lj("cameraGizmoMaterial",this.gizmoLayer.utilityLayerScene),this._gizmoColor=t,this._material.diffuseColor=null!=t?t:new rm.Wo(.5,.5,.5),this._material.specularColor=new rm.Wo(.1,.1,.1),this._pointerObserver=e.utilityLayerScene.onPointerObservable.add(e=>{this._camera&&(this._isHovered=!!(e.pickInfo&&-1!=this._rootMesh.getChildMeshes().indexOf(e.pickInfo.pickedMesh)),this._isHovered&&0===e.event.button&&this.onClickedObservable.notifyObservers(this._camera))},s0.kD.POINTERDOWN)}get displayFrustum(){return this._cameraLinesMesh.isEnabled()}set displayFrustum(e){this._cameraLinesMesh.setEnabled(e)}set camera(e){var t,i;if(this._camera=e,this.attachedNode=e,e){this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._cameraMesh=dE._CreateCameraMesh(this.gizmoLayer.utilityLayerScene);let r=null!==(i=null===(t=this._gizmoColor)||void 0===t?void 0:t.toColor4(1))&&void 0!==i?i:new rm.HE(1,1,1,1);this._cameraLinesMesh=dE._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene,r),this._cameraMesh.getChildMeshes(!1).forEach(e=>{e.material=this._material}),this._cameraMesh.parent=this._rootMesh,this._cameraLinesMesh.parent=this._rootMesh,this.gizmoLayer.utilityLayerScene.activeCamera&&this.gizmoLayer.utilityLayerScene.activeCamera.maxZ<1.5*e.maxZ&&(this.gizmoLayer.utilityLayerScene.activeCamera.maxZ=1.5*e.maxZ),this.attachedNode.reservedDataStore||(this.attachedNode.reservedDataStore={}),this.attachedNode.reservedDataStore.cameraGizmo=this;let s=this.gizmoLayer._getSharedGizmoLight();s.includedOnlyMeshes=s.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(!1)),this._update()}}get camera(){return this._camera}get material(){return this._material}_update(){super._update(),this._camera&&(this._camera.getProjectionMatrix().invertToRef(this._invProjection),this._cameraLinesMesh.setPivotMatrix(this._invProjection,!1),this._cameraLinesMesh.scaling.x=1/this._rootMesh.scaling.x,this._cameraLinesMesh.scaling.y=1/this._rootMesh.scaling.y,this._cameraLinesMesh.scaling.z=1/this._rootMesh.scaling.z,this._cameraMesh.parent=null,this._cameraMesh.rotation.y=.5*Math.PI*(this._camera.getScene().useRightHandedSystem?1:-1),this._cameraMesh.parent=this._rootMesh)}dispose(){this.onClickedObservable.clear(),this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver),this._cameraMesh&&this._cameraMesh.dispose(),this._cameraLinesMesh&&this._cameraLinesMesh.dispose(),this._material.dispose(),super.dispose()}static _CreateCameraMesh(e){let t=new sp.Kj("rootCameraGizmo",e),i=new sp.Kj(t.name,e);i.parent=t,hP(t.name,{width:1,height:.8,depth:.5},e).parent=i;let r=hE(t.name,{height:.5,diameterTop:.8,diameterBottom:.8},e);r.parent=i,r.position.y=.3,r.position.x=-.6,r.rotation.x=.5*Math.PI;let s=hE(t.name,{height:.5,diameterTop:.6,diameterBottom:.6},e);s.parent=i,s.position.y=.5,s.position.x=.4,s.rotation.x=.5*Math.PI;let n=hE(t.name,{height:.5,diameterTop:.5,diameterBottom:.5},e);return n.parent=i,n.position.y=0,n.position.x=.6,n.rotation.z=.5*Math.PI,t.scaling.scaleInPlace(dE._Scale),i.position.x=-.9,t}static _CreateCameraFrustum(e,t){let i=new sp.Kj("rootCameraGizmo",e),r=new sp.Kj(i.name,e);r.parent=i;for(let i=0;i<4;i+=2)for(let s=0;s<4;s+=2){let n=hj("lines",{points:[new rf.P(-1+s,-1+i,-1),new rf.P(-1+s,-1+i,1)],colors:[t,t]},e);n.parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,(n=hj("lines",{points:[new rf.P(-1,-1+s,-1+i),new rf.P(1,-1+s,-1+i)],colors:[t,t]},e)).parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1,(n=hj("lines",{points:[new rf.P(-1+s,-1,-1+i),new rf.P(-1+s,1,-1+i)],colors:[t,t]},e)).parent=r,n.alwaysSelectAsActiveMesh=!0,n.isPickable=!1}return i}}dE._Scale=.05,nw.v.IncludesShadersStore.kernelBlurVaryingDeclaration="varying vec2 sampleCoord{X};";let dC=`vec4 pack(float depth) +{const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} +float unpack(vec4 color) +{const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`;nw.v.IncludesShadersStore.packingFunctions=dC;let db=`#ifdef DOF +factor=sampleCoC(sampleCoord{X}); +computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; +#endif +`;nw.v.IncludesShadersStore.kernelBlurFragment=db;let dy=`#ifdef DOF +factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; +#else +computedWeight=KERNEL_DEP_WEIGHT{X}; +#endif +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; +#else +blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; +#endif +`;nw.v.IncludesShadersStore.kernelBlurFragment2=dy;let dA=`uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; +#ifdef DOF +uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } +#endif +#include[0..varyingCount] +#ifdef PACKEDFLOAT +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float computedWeight=0.0; +#ifdef PACKEDFLOAT +float blend=0.; +#else +vec4 blend=vec4(0.); +#endif +#ifdef DOF +float sumOfWeights=CENTER_WEIGHT; +float factor=0.0; +#ifdef PACKEDFLOAT +blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; +#else +blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; +#endif +#endif +#include[0..varyingCount] +#include[0..depCount] +#ifdef PACKEDFLOAT +gl_FragColor=pack(blend); +#else +gl_FragColor=blend; +#endif +#ifdef DOF +gl_FragColor/=sumOfWeights; +#endif +}`;nw.v.ShadersStore.kernelBlurPixelShader=dA,nw.v.IncludesShadersStore.kernelBlurVertex="sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};";let dR=`attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; +#include[0..varyingCount] +const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +sampleCenter=(position*madd+madd); +#include[0..varyingCount] +gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.kernelBlurVertexShader=dR;class dP extends nz{set kernel(e){this._idealKernel!==e&&(e=Math.max(e,1),this._idealKernel=e,this._kernel=this._nearestBestKernel(e),this._blockCompilation||this._updateParameters())}get kernel(){return this._idealKernel}set packedFloat(e){this._packedFloat!==e&&(this._packedFloat=e,this._blockCompilation||this._updateParameters())}get packedFloat(){return this._packedFloat}getClassName(){return"BlurPostProcess"}constructor(e,t,i,r,s,n=sj.BILINEAR_SAMPLINGMODE,a,o,l=0,h="",u=!1,c=5){super(e,"kernelBlur",["delta","direction"],["circleOfConfusionSampler"],r,s,n,a,o,null,l,"kernelBlur",{varyingCount:0,depCount:0},!0,c),this._blockCompilation=u,this._packedFloat=!1,this._staticDefines="",this._staticDefines=h,this.direction=t,this.onApplyObservable.add(e=>{this._outputTexture?e.setFloat2("delta",1/this._outputTexture.width*this.direction.x,1/this._outputTexture.height*this.direction.y):e.setFloat2("delta",1/this.width*this.direction.x,1/this.height*this.direction.y)}),this.kernel=i}updateEffect(e=null,t=null,i=null,r,s,n){this._updateParameters(s,n)}_updateParameters(e,t){let i=this._kernel,r=(i-1)/2,s=[],n=[],a=0;for(let e=0;e0)return Math.max(e,3);return Math.max(t,3)}_gaussianWeight(e){return 1/(1/3*Math.sqrt(2*Math.PI))*Math.exp(-(e*e/(1/3*2*(1/3))))}_glslFloat(e,t=8){return e.toFixed(t).replace(/0+$/,"")}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new dP(e.name,e.direction,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,void 0,!1),e,i,r)}}(0,sx.gn)([(0,rG.qC)("kernel")],dP.prototype,"_kernel",void 0),(0,sx.gn)([(0,rG.qC)("packedFloat")],dP.prototype,"_packedFloat",void 0),(0,sx.gn)([(0,rG.QC)()],dP.prototype,"direction",void 0),(0,rg.H)("BABYLON.BlurPostProcess",dP);class dI extends as{set blurRatio(e){this._blurRatio!==e&&(this._blurRatio=e,this._preparePostProcesses())}get blurRatio(){return this._blurRatio}set adaptiveBlurKernel(e){this._adaptiveBlurKernel=e,this._autoComputeBlurKernel()}set blurKernel(e){this.blurKernelX=e,this.blurKernelY=e}set blurKernelX(e){this._blurKernelX!==e&&(this._blurKernelX=e,this._preparePostProcesses())}get blurKernelX(){return this._blurKernelX}set blurKernelY(e){this._blurKernelY!==e&&(this._blurKernelY=e,this._preparePostProcesses())}get blurKernelY(){return this._blurKernelY}_autoComputeBlurKernel(){let e=this.getScene().getEngine(),t=this.getRenderWidth()/e.getRenderWidth(),i=this.getRenderHeight()/e.getRenderHeight();this.blurKernelX=this._adaptiveBlurKernel*t,this.blurKernelY=this._adaptiveBlurKernel*i}_onRatioRescale(){this._sizeRatio&&(this.resize(this._initialSizeParameter),this._adaptiveBlurKernel||this._preparePostProcesses()),this._adaptiveBlurKernel&&this._autoComputeBlurKernel()}_updateGammaSpace(){let e=this.getScene();e&&(this.gammaSpace=!e.imageProcessingConfiguration.isEnabled||!e.imageProcessingConfiguration.applyByPostProcess)}constructor(e,t,i,r,s=0,n=sj.BILINEAR_SAMPLINGMODE,a=!0){let o;if(super(e,t,i,r,!0,s,!1,n,a),this.mirrorPlane=new sz.J(0,1,0,1),this._transformMatrix=rf.y3.Zero(),this._mirrorMatrix=rf.y3.Zero(),this._adaptiveBlurKernel=0,this._blurKernelX=0,this._blurKernelY=0,this._blurRatio=1,!(i=this.getScene()))return this;this.ignoreCameraViewport=!0,this._updateGammaSpace(),this._imageProcessingConfigChangeObserver=i.imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateGammaSpace()});let l=i.getEngine();l.supportsUniformBuffers&&(this._sceneUBO=i.createSceneUniformBuffer(`Scene for Mirror Texture (name "${e}")`)),this.onBeforeBindObservable.add(()=>{var t;null===(t=l._debugPushGroup)||void 0===t||t.call(l,`mirror generation for ${e}`,1)}),this.onAfterUnbindObservable.add(()=>{var e;null===(e=l._debugPopGroup)||void 0===e||e.call(l,1)}),this.onBeforeRenderObservable.add(()=>{this._sceneUBO&&(this._currentSceneUBO=i.getSceneUniformBuffer(),i.setSceneUniformBuffer(this._sceneUBO),i.getSceneUniformBuffer().unbindEffect()),rf.y3.ReflectionToRef(this.mirrorPlane,this._mirrorMatrix),this._mirrorMatrix.multiplyToRef(i.getViewMatrix(),this._transformMatrix),i.setTransformMatrix(this._transformMatrix,i.getProjectionMatrix()),o=i.clipPlane,i.clipPlane=this.mirrorPlane,i._mirroredCameraPosition=rf.P.TransformCoordinates(i.activeCamera.globalPosition,this._mirrorMatrix)}),this.onAfterRenderObservable.add(()=>{this._sceneUBO&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(),i._mirroredCameraPosition=null,i.clipPlane=o})}_preparePostProcesses(){if(this.clearPostProcesses(!0),this._blurKernelX&&this._blurKernelY){let e=this.getScene().getEngine(),t=e.getCaps().textureFloatRender&&e.getCaps().textureFloatLinearFiltering?1:2;this._blurX=new dP("horizontal blur",new rf.FM(1,0),this._blurKernelX,this._blurRatio,null,sj.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurX.autoClear=!1,1===this._blurRatio&&this.samples<2&&this._texture?this._blurX.inputTexture=this._renderTarget:this._blurX.alwaysForcePOT=!0,this._blurY=new dP("vertical blur",new rf.FM(0,1),this._blurKernelY,this._blurRatio,null,sj.BILINEAR_SAMPLINGMODE,e,!1,t),this._blurY.autoClear=!1,this._blurY.alwaysForcePOT=1!==this._blurRatio,this.addPostProcess(this._blurX),this.addPostProcess(this._blurY)}else this._blurY&&(this.removePostProcess(this._blurY),this._blurY.dispose(),this._blurY=null),this._blurX&&(this.removePostProcess(this._blurX),this._blurX.dispose(),this._blurX=null)}clone(){let e=this.getScene();if(!e)return this;let t=this.getSize(),i=new dI(this.name,t.width,e,this._renderTargetOptions.generateMipMaps,this._renderTargetOptions.type,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer);return i.hasAlpha=this.hasAlpha,i.level=this.level,i.mirrorPlane=this.mirrorPlane.clone(),this.renderList&&(i.renderList=this.renderList.slice(0)),i}serialize(){if(!this.name)return null;let e=super.serialize();return e.mirrorPlane=this.mirrorPlane.asArray(),e}dispose(){var e;super.dispose();let t=this.getScene();t&&t.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver),null===(e=this._sceneUBO)||void 0===e||e.dispose()}}sj._CreateMirror=(e,t,i,r)=>new dI(e,t,i,r);class dM extends sV{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(rf.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,i){let r="";return e.forEach(e=>r+=e),new dM(r,t,null,i,e)}static CreateFromPrefilteredData(e,t,i=null,r=!0){let s=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;let n=new dM(e,t,null,!1,null,null,null,void 0,!0,i,r);return t.useDelayedTextureLoading=s,n}constructor(e,t,i=null,r=!1,s=null,n=null,a=null,o=5,l=!1,h=null,u=!1,c=.8,d=0,p,_){var f;if(super(t),this._lodScale=.8,this._lodOffset=0,this.onLoadObservable=new r_.y$,this.boundingBoxPosition=rf.P.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new rf.y3,this.name=e,this.url=e,this._noMipmap=r,this.hasAlpha=!1,this._format=o,this.isCube=!0,this._textureMatrix=rf.y3.Identity(),this._createPolynomials=u,this.coordinatesMode=sj.CUBIC_MODE,this._extensions=i,this._files=s,this._forcedExtension=h,this._loaderOptions=p,this._useSRGBBuffer=_,this._lodScale=c,this._lodOffset=d,!e&&!s)return;this.updateURL(e,h,n,l,a,i,null===(f=this.getScene())||void 0===f?void 0:f.useDelayedTextureLoading,s)}getClassName(){return"CubeTexture"}updateURL(e,t,i=null,r=!1,s=null,n=null,a=!1,o=null){(!this.name||this.name.startsWith("data:"))&&(this.name=e),this.url=e,t&&(this._forcedExtension=t);let l=e.lastIndexOf("."),h=t||(l>-1?e.substring(l).toLowerCase():""),u=0===h.indexOf(".dds"),c=0===h.indexOf(".env"),d=0===h.indexOf(".basis");if(c?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=r,r&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(d||c||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-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!(null===(i=this.getScene())||void 0===i?void 0:i.useRightHandedSystem)))return;let r=rf.jp.Vector3[0],s=rf.jp.Quaternion[0],n=rf.jp.Vector3[1];this._textureMatrix.decompose(r,s,n),s.z*=-1,s.w*=-1,rf.y3.ComposeToRef(r,s,n,this._textureMatrixRefraction)}getRefractionTextureMatrix(){var e;return(null===(e=this.getScene())||void 0===e?void 0:e.useRightHandedSystem)?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){var i;let r=this.getScene(),s=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);let n=()=>{var t;this.onLoadObservable.notifyObservers(this),s&&(s.dispose(),null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1)),e&&e()},a=(e,i)=>{this._loadingError=!0,this._errorObject={message:e,exception:i},t&&t(e,i),sj.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?sg.w1.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(()=>n()):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,r,this._lodScale,this._lodOffset,e,a,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,r,this._files,this._noMipmap,e,a,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer),null===(i=this._texture)||void 0===i||i.onLoadedObservable.add(()=>this.onLoadObservable.notifyObservers(this)))}static Parse(e,t,i){let r=rG.p4.Parse(()=>{var r;let s=!1;return e.prefiltered&&(s=e.prefiltered),new dM(i+(null!==(r=e.url)&&void 0!==r?r:e.name),t,e.extensions,!1,e.files||null,null,null,void 0,s,e.forcedExtension)},e,t);if(e.boundingBoxPosition&&(r.boundingBoxPosition=rf.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=rf.P.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t{let t=new dM(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t},this);return t.uniqueId=e,t}}(0,sx.gn)([(0,rG.qC)()],dM.prototype,"url",void 0),(0,sx.gn)([(0,rG.hd)()],dM.prototype,"boundingBoxPosition",void 0),(0,sx.gn)([(0,rG.hd)()],dM.prototype,"boundingBoxSize",null),(0,sx.gn)([(0,rG.qC)("rotationY")],dM.prototype,"rotationY",null),(0,sx.gn)([(0,rG.qC)("files")],dM.prototype,"_files",void 0),(0,sx.gn)([(0,rG.qC)("forcedExtension")],dM.prototype,"_forcedExtension",void 0),(0,sx.gn)([(0,rG.qC)("extensions")],dM.prototype,"_extensions",void 0),(0,sx.gn)([(0,rG.oQ)("textureMatrix")],dM.prototype,"_textureMatrix",void 0),(0,sx.gn)([(0,rG.oQ)("textureMatrixRefraction")],dM.prototype,"_textureMatrixRefraction",void 0),sj._CubeTextureParser=dM.Parse,(0,rg.H)("BABYLON.CubeTexture",dM);let dD=`uniform vec4 vEyePosition;uniform vec4 vPrimaryColor; +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +uniform vec4 vPrimaryColorShadow; +#endif +uniform float shadowLevel;uniform float alpha; +#ifdef DIFFUSE +uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#endif +#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL) +uniform vec3 vBackgroundCenter; +#endif +#ifdef REFLECTIONFRESNEL +uniform vec4 vReflectionControl; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) +uniform mat4 view; +#endif +#ifdef PROJECTED_GROUND +uniform vec2 projectedGroundInfos; +#endif +`;nw.v.IncludesShadersStore.backgroundFragmentDeclaration=dD;let dO=`layout(std140,column_major) uniform;uniform Material +{uniform vec4 vPrimaryColor;uniform vec4 vPrimaryColorShadow;uniform vec2 vDiffuseInfos;uniform vec2 vReflectionInfos;uniform mat4 diffuseMatrix;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier;uniform float pointSize;uniform float shadowLevel;uniform float alpha;uniform vec3 vBackgroundCenter;uniform vec4 vReflectionControl;uniform vec2 projectedGroundInfos;}; +#include +`;nw.v.IncludesShadersStore.backgroundUboDeclaration=dO;let dN=`#ifdef TEXTURELODSUPPORT +#extension GL_EXT_shader_texture_lod : enable +#endif +precision highp float; +#include<__decl__backgroundFragment> +#include +varying vec3 vPositionW; +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef DIFFUSE +#if DIFFUSEDIRECTUV==1 +#define vDiffuseUV vMainUV1 +#elif DIFFUSEDIRECTUV==2 +#define vDiffuseUV vMainUV2 +#else +varying vec2 vDiffuseUV; +#endif +uniform sampler2D diffuseSampler; +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef TEXTURELODSUPPORT +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#include +#endif +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE; +#endif +#ifndef SHADOWONLY +#define SHADOWONLY; +#endif +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include +#include +#include +#ifdef REFLECTIONFRESNEL +#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +vec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#ifdef PROJECTED_GROUND +float diskIntersectWithBackFaceCulling(vec3 ro,vec3 rd,vec3 c,float r) {float d=rd.y;if(d>0.0) { return 1e6; } +vec3 o=ro-c;float t=-o.y/d;vec3 q=o+rd*t;return (dot(q,q) +vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=vec3(0.0,1.0,0.0); +#endif +float shadow=1.;float globalShadow=0.;float shadowLightCount=0.;float aggShadow=0.;float numLights=0.; +#include[0..maxSimultaneousLights] +#ifdef SHADOWINUSE +globalShadow/=shadowLightCount; +#else +globalShadow=1.0; +#endif +#ifndef BACKMAT_SHADOWONLY +vec4 reflectionColor=vec4(1.,1.,1.,1.); +#ifdef REFLECTION +#ifdef PROJECTED_GROUND +vec3 reflectionVector=project(viewDirectionW,vEyePosition.xyz);reflectionVector=vec3(reflectionMatrix*vec4(reflectionVector,1.)); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=reflectionVector; +#else +vec2 reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +#ifdef REFLECTIONBLUR +float reflectionLOD=vReflectionInfos.y; +#ifdef TEXTURELODSUPPORT +reflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;reflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#else +float lodReflectionNormalized=saturate(reflectionLOD);float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);if(lodReflectionNormalizedDoubled<1.0){reflectionColor=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +reflectionSpecularMid, +lodReflectionNormalizedDoubled +);} else {reflectionColor=mix( +reflectionSpecularMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#else +vec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);reflectionColor=reflectionSample; +#endif +#ifdef RGBDREFLECTION +reflectionColor.rgb=fromRGBD(reflectionColor); +#endif +#ifdef GAMMAREFLECTION +reflectionColor.rgb=toLinearSpace(reflectionColor.rgb); +#endif +#ifdef REFLECTIONBGR +reflectionColor.rgb=reflectionColor.bgr; +#endif +reflectionColor.rgb*=vReflectionInfos.x; +#endif +vec3 diffuseColor=vec3(1.,1.,1.);float finalAlpha=alpha; +#ifdef DIFFUSE +vec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV); +#ifdef GAMMADIFFUSE +diffuseMap.rgb=toLinearSpace(diffuseMap.rgb); +#endif +diffuseMap.rgb*=vDiffuseInfos.y; +#ifdef DIFFUSEHASALPHA +finalAlpha*=diffuseMap.a; +#endif +diffuseColor=diffuseMap.rgb; +#endif +#ifdef REFLECTIONFRESNEL +vec3 colorBase=diffuseColor; +#else +vec3 colorBase=reflectionColor.rgb*diffuseColor; +#endif +colorBase=max(colorBase,0.0); +#ifdef USERGBCOLOR +vec3 finalColor=colorBase; +#else +#ifdef USEHIGHLIGHTANDSHADOWCOLORS +vec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase); +#else +vec3 mainColor=vPrimaryColor.rgb; +#endif +vec3 finalColor=colorBase*mainColor; +#endif +#ifdef REFLECTIONFRESNEL +vec3 reflectionAmount=vReflectionControl.xxx;vec3 reflectionReflectance0=vReflectionControl.yyy;vec3 reflectionReflectance90=vReflectionControl.zzz;float VdotN=dot(normalize(vEyePosition.xyz),normalW);vec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(saturate(VdotN),reflectionReflectance0,reflectionReflectance90,1.0);reflectionAmount*=planarReflectionFresnel; +#ifdef REFLECTIONFALLOFF +float reflectionDistanceFalloff=1.0-saturate(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w);reflectionDistanceFalloff*=reflectionDistanceFalloff;reflectionAmount*=reflectionDistanceFalloff; +#endif +finalColor=mix(finalColor,reflectionColor.rgb,saturate(reflectionAmount)); +#endif +#ifdef OPACITYFRESNEL +float viewAngleToFloor=dot(normalW,normalize(vEyePosition.xyz-vBackgroundCenter));const float startAngle=0.1;float fadeFactor=saturate(viewAngleToFloor/startAngle);finalAlpha*=fadeFactor*fadeFactor; +#endif +#ifdef SHADOWINUSE +finalColor=mix(finalColor*shadowLevel,finalColor,globalShadow); +#endif +vec4 color=vec4(finalColor,finalAlpha); +#else +vec4 color=vec4(vPrimaryColor.rgb,(1.0-clamp(globalShadow,0.,1.))*alpha); +#endif +#include +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +#if !defined(SKIPFINALCOLORCLAMP) +color.rgb=clamp(color.rgb,0.,30.0); +#endif +#else +color=applyImageProcessing(color); +#endif +#ifdef PREMULTIPLYALPHA +color.rgb*=color.a; +#endif +#ifdef NOISE +color.rgb+=dither(vPositionW.xy,0.5);color=max(color,0.0); +#endif +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +} +`;nw.v.ShadersStore.backgroundPixelShader=dN;let dF=`uniform mat4 view;uniform mat4 viewProjection;uniform float shadowLevel; +#ifdef DIFFUSE +uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos;uniform float fFovMultiplier; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +`;nw.v.IncludesShadersStore.backgroundVertexDeclaration=dF;let dL=`precision highp float; +#include<__decl__backgroundVertex> +#include +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include +#include +#include +varying vec3 vPositionW; +#ifdef NORMAL +varying vec3 vNormalW; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef MAINUV1 +varying vec2 vMainUV1; +#endif +#ifdef MAINUV2 +varying vec2 vMainUV2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +varying vec2 vDiffuseUV; +#endif +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=position; +#endif +#include +#include +#include +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*finalWorld*vec4(position,1.0);} else {gl_Position=viewProjectionR*finalWorld*vec4(position,1.0);} +#else +gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#endif +vec4 worldPos=finalWorld*vec4(position,1.0);vPositionW=vec3(worldPos); +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normal); +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(position,0.0))); +#ifdef EQUIRECTANGULAR_RELFECTION_FOV +mat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));vec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));if (fFovMultiplier<=1.0) {vDirectionW=normalize(segment);} else {vDirectionW=normalize(vDirectionW+(vDirectionW-segment));} +#endif +#endif +#ifndef UV1 +vec2 uv=vec2(0.,0.); +#endif +#ifndef UV2 +vec2 uv2=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uv; +#endif +#ifdef MAINUV2 +vMainUV2=uv2; +#endif +#if defined(DIFFUSE) && DIFFUSEDIRECTUV==0 +if (vDiffuseInfos.x==0.) +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));} +else +{vDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));} +#endif +#include +#include +#include[0..maxSimultaneousLights] +#ifdef VERTEXCOLOR +vColor=color; +#endif +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +} +`;nw.v.ShadersStore.backgroundVertexShader=dL;class dw extends nf.H{constructor(){super(),this.DIFFUSE=!1,this.DIFFUSEDIRECTUV=0,this.GAMMADIFFUSE=!1,this.DIFFUSEHASALPHA=!1,this.OPACITYFRESNEL=!1,this.REFLECTIONBLUR=!1,this.REFLECTIONFRESNEL=!1,this.REFLECTIONFALLOFF=!1,this.TEXTURELODSUPPORT=!1,this.PREMULTIPLYALPHA=!1,this.USERGBCOLOR=!1,this.USEHIGHLIGHTANDSHADOWCOLORS=!1,this.BACKMAT_SHADOWONLY=!1,this.NOISE=!1,this.REFLECTIONBGR=!1,this.PROJECTED_GROUND=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=!1,this.TONEMAPPING_ACES=!1,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.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.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.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.EQUIRECTANGULAR_RELFECTION_FOV=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.UV1=!1,this.UV2=!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.NORMAL=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.SHADOWFLOAT=!1,this.LOGARITHMICDEPTH=!1,this.NONUNIFORMSCALING=!1,this.ALPHATEST=!1,this.rebuild()}}class dB extends nc{get _perceptualColor(){return this.__perceptualColor}set _perceptualColor(e){this.__perceptualColor=e,this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsLightsDirty()}get primaryColorShadowLevel(){return this._primaryColorShadowLevel}set primaryColorShadowLevel(e){this._primaryColorShadowLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}get primaryColorHighlightLevel(){return this._primaryColorHighlightLevel}set primaryColorHighlightLevel(e){this._primaryColorHighlightLevel=e,this._computePrimaryColors(),this._markAllSubMeshesAsLightsDirty()}set reflectionStandardFresnelWeight(e){let t=e;t<.5?(t*=2,this.reflectionReflectance0=dB.StandardReflectance0*t,this.reflectionReflectance90=dB.StandardReflectance90*t):(t=2*t-1,this.reflectionReflectance0=dB.StandardReflectance0+(1-dB.StandardReflectance0)*t,this.reflectionReflectance90=dB.StandardReflectance90+(1-dB.StandardReflectance90)*t)}get fovMultiplier(){return this._fovMultiplier}set fovMultiplier(e){isNaN(e)&&(e=1),this._fovMultiplier=Math.max(0,Math.min(2,e))}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._computePrimaryColorFromPerceptualColor(),this._markAllSubMeshesAsImageProcessingDirty()})))}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){super(e,t),this.primaryColor=rm.Wo.White(),this._primaryColorShadowLevel=0,this._primaryColorHighlightLevel=0,this.reflectionTexture=null,this.reflectionBlur=0,this.diffuseTexture=null,this._shadowLights=null,this.shadowLights=null,this.shadowLevel=0,this.sceneCenter=rf.P.Zero(),this.opacityFresnel=!0,this.reflectionFresnel=!1,this.reflectionFalloffDistance=0,this.reflectionAmount=1,this.reflectionReflectance0=.05,this.reflectionReflectance90=.5,this.useRGBColor=!0,this.enableNoise=!1,this._fovMultiplier=1,this.useEquirectangularFOV=!1,this._maxSimultaneousLights=4,this.maxSimultaneousLights=4,this._shadowOnly=!1,this.shadowOnly=!1,this._imageProcessingObserver=null,this.switchToBGR=!1,this._enableGroundProjection=!1,this.enableGroundProjection=!1,this.projectedGroundRadius=1e3,this.projectedGroundHeight=10,this._renderTargets=new nL.t(16),this._reflectionControls=rf.Lt.Zero(),this._white=rm.Wo.White(),this._primaryShadowColor=rm.Wo.Black(),this._primaryHighlightColor=rm.Wo.Black(),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._renderTargets.push(this._diffuseTexture),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._renderTargets)}get hasRenderTargetTextures(){return!!this._diffuseTexture&&!!this._diffuseTexture.isRenderTarget||!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget}needAlphaTesting(){return!0}needAlphaBlending(){return this.alpha<1||null!=this._diffuseTexture&&this._diffuseTexture.hasAlpha||this._shadowOnly}isReadyForSubMesh(e,t,i=!1){if(t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new dw);let r=this.getScene(),s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=r.getEngine();if(nE.G.PrepareDefinesForLights(r,e,s,!1,this._maxSimultaneousLights),s._needNormals=!0,nE.G.PrepareDefinesForMultiview(r,s),s._areTexturesDirty){if(s._needUVs=!1,r.texturesEnabled){if(r.getEngine().getCaps().textureLOD&&(s.TEXTURELODSUPPORT=!0),this._diffuseTexture&&ow.DiffuseTextureEnabled){if(!this._diffuseTexture.isReadyOrNotBlocking())return!1;nE.G.PrepareDefinesForMergedUV(this._diffuseTexture,s,"DIFFUSE"),s.DIFFUSEHASALPHA=this._diffuseTexture.hasAlpha,s.GAMMADIFFUSE=this._diffuseTexture.gammaSpace,s.OPACITYFRESNEL=this._opacityFresnel}else s.DIFFUSE=!1,s.DIFFUSEDIRECTUV=0,s.DIFFUSEHASALPHA=!1,s.GAMMADIFFUSE=!1,s.OPACITYFRESNEL=!1;let e=this._reflectionTexture;if(e&&ow.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;switch(s.REFLECTION=!0,s.GAMMAREFLECTION=e.gammaSpace,s.RGBDREFLECTION=e.isRGBD,s.REFLECTIONBLUR=this._reflectionBlur>0,s.LODINREFLECTIONALPHA=e.lodLevelInAlpha,s.EQUIRECTANGULAR_RELFECTION_FOV=this.useEquirectangularFOV,s.REFLECTIONBGR=this.switchToBGR,e.coordinatesMode===sj.INVCUBIC_MODE&&(s.INVERTCUBICMAP=!0),s.REFLECTIONMAP_3D=e.isCube,s.REFLECTIONMAP_OPPOSITEZ=s.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,e.coordinatesMode){case sj.EXPLICIT_MODE:s.REFLECTIONMAP_EXPLICIT=!0;break;case sj.PLANAR_MODE:s.REFLECTIONMAP_PLANAR=!0;break;case sj.PROJECTION_MODE:s.REFLECTIONMAP_PROJECTION=!0;break;case sj.SKYBOX_MODE:s.REFLECTIONMAP_SKYBOX=!0;break;case sj.SPHERICAL_MODE:s.REFLECTIONMAP_SPHERICAL=!0;break;case sj.EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case sj.FIXED_EQUIRECTANGULAR_MODE:s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case sj.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case sj.CUBIC_MODE:case sj.INVCUBIC_MODE:default:s.REFLECTIONMAP_CUBIC=!0}this.reflectionFresnel?(s.REFLECTIONFRESNEL=!0,s.REFLECTIONFALLOFF=this.reflectionFalloffDistance>0,this._reflectionControls.x=this.reflectionAmount,this._reflectionControls.y=this.reflectionReflectance0,this._reflectionControls.z=this.reflectionReflectance90,this._reflectionControls.w=1/this.reflectionFalloffDistance):(s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1)}else s.REFLECTION=!1,s.REFLECTIONFRESNEL=!1,s.REFLECTIONFALLOFF=!1,s.REFLECTIONBLUR=!1,s.REFLECTIONMAP_3D=!1,s.REFLECTIONMAP_SPHERICAL=!1,s.REFLECTIONMAP_PLANAR=!1,s.REFLECTIONMAP_CUBIC=!1,s.REFLECTIONMAP_PROJECTION=!1,s.REFLECTIONMAP_SKYBOX=!1,s.REFLECTIONMAP_EXPLICIT=!1,s.REFLECTIONMAP_EQUIRECTANGULAR=!1,s.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,s.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,s.INVERTCUBICMAP=!1,s.REFLECTIONMAP_OPPOSITEZ=!1,s.LODINREFLECTIONALPHA=!1,s.GAMMAREFLECTION=!1,s.RGBDREFLECTION=!1}s.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,s.USERGBCOLOR=this._useRGBColor,s.NOISE=this._enableNoise}if(s._areLightsDirty&&(s.USEHIGHLIGHTANDSHADOWCOLORS=!this._useRGBColor&&(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel),s.BACKMAT_SHADOWONLY=this._shadowOnly),s._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(s)}if(s._areMiscDirty&&(s.REFLECTIONMAP_3D&&this._enableGroundProjection?(s.PROJECTED_GROUND=!0,s.REFLECTIONMAP_SKYBOX=!0):s.PROJECTED_GROUND=!1),nE.G.PrepareDefinesForMisc(e,r,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),s),nE.G.PrepareDefinesForFrameBoundValues(r,n,this,s,i,null,t.getRenderingMesh().hasThinInstances),nE.G.PrepareDefinesForAttributes(e,s,!1,!0,!1)&&e&&!r.getEngine().getCaps().standardDerivatives&&!e.isVerticesDataPresent(sm.o.NormalKind)&&(e.createNormals(!0),rb.Y.Warn("BackgroundMaterial: Normals have been created for the mesh: "+e.name)),s.isDirty){s.markAsProcessed(),r.resetCachedMaterial();let i=new nF;s.FOG&&i.addFallback(0,"FOG"),s.POINTSIZE&&i.addFallback(1,"POINTSIZE"),s.MULTIVIEW&&i.addFallback(0,"MULTIVIEW"),nE.G.HandleFallbacksForShadows(s,i,this._maxSimultaneousLights);let a=[sm.o.PositionKind];s.NORMAL&&a.push(sm.o.NormalKind),s.UV1&&a.push(sm.o.UVKind),s.UV2&&a.push(sm.o.UV2Kind),nE.G.PrepareAttributesForBones(a,e,s,i),nE.G.PrepareAttributesForInstances(a,s);let o=["world","view","viewProjection","vEyePosition","vLightsType","vFogInfos","vFogColor","pointSize","mBones","vPrimaryColor","vPrimaryColorShadow","vReflectionInfos","reflectionMatrix","vReflectionMicrosurfaceInfos","fFovMultiplier","shadowLevel","alpha","vBackgroundCenter","vReflectionControl","vDiffuseInfos","diffuseMatrix","projectedGroundInfos","logarithmicDepthConstant"];(0,lH.qx)(o);let l=["diffuseSampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh"],h=["Material","Scene"];nY.$&&(nY.$.PrepareUniforms(o,s),nY.$.PrepareSamplers(l,s)),nE.G.PrepareUniformsAndSamplersList({uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:s,maxSimultaneousLights:this._maxSimultaneousLights});let u=s.toString(),c=r.getEngine().createEffect("background",{attributes:a,uniformsNames:o,uniformBuffersNames:h,samplers:l,defines:u,fallbacks:i,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},n);t.setEffect(c,s,this._materialContext),this.buildUniformLayout()}return!!(t.effect&&t.effect.isReady())&&(s._renderId=r.getRenderId(),t.effect._wasPreviouslyReady=!0,t.effect._wasPreviouslyUsingInstances=i,this._checkScenePerformancePriority(),!0)}_computePrimaryColorFromPerceptualColor(){this.__perceptualColor&&(this._primaryColor.copyFrom(this.__perceptualColor),this._primaryColor.toLinearSpaceToRef(this._primaryColor,this.getScene().getEngine().useExactSrgbConversions),this._imageProcessingConfiguration&&this._primaryColor.scaleToRef(1/this._imageProcessingConfiguration.exposure,this._primaryColor),this._computePrimaryColors())}_computePrimaryColors(){(0!==this._primaryColorShadowLevel||0!==this._primaryColorHighlightLevel)&&(this._primaryColor.scaleToRef(this._primaryColorShadowLevel,this._primaryShadowColor),this._primaryColor.subtractToRef(this._primaryShadowColor,this._primaryShadowColor),this._white.subtractToRef(this._primaryColor,this._primaryHighlightColor),this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel,this._primaryHighlightColor),this._primaryColor.addToRef(this._primaryHighlightColor,this._primaryHighlightColor))}buildUniformLayout(){this._uniformBuffer.addUniform("vPrimaryColor",4),this._uniformBuffer.addUniform("vPrimaryColorShadow",4),this._uniformBuffer.addUniform("vDiffuseInfos",2),this._uniformBuffer.addUniform("vReflectionInfos",2),this._uniformBuffer.addUniform("diffuseMatrix",16),this._uniformBuffer.addUniform("reflectionMatrix",16),this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos",3),this._uniformBuffer.addUniform("fFovMultiplier",1),this._uniformBuffer.addUniform("pointSize",1),this._uniformBuffer.addUniform("shadowLevel",1),this._uniformBuffer.addUniform("alpha",1),this._uniformBuffer.addUniform("vBackgroundCenter",3),this._uniformBuffer.addUniform("vReflectionControl",4),this._uniformBuffer.addUniform("projectedGroundInfos",2),this._uniformBuffer.create()}unbind(){this._diffuseTexture&&this._diffuseTexture.isRenderTarget&&this._uniformBuffer.setTexture("diffuseSampler",null),this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._uniformBuffer.setTexture("reflectionSampler",null),super.unbind()}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindForSubMesh(e,t,i){let r=this.getScene(),s=i.materialDefines;if(!s)return;let n=i.effect;if(!n)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),nE.G.BindBonesParameters(t,this._activeEffect);let a=this._mustRebind(r,n,t.visibility);if(a){this._uniformBuffer.bindToEffect(n,"Material"),this.bindViewProjection(n);let e=this._reflectionTexture;this._uniformBuffer.useUbo&&this.isFrozen&&this._uniformBuffer.isSync||(r.texturesEnabled&&(this._diffuseTexture&&ow.DiffuseTextureEnabled&&(this._uniformBuffer.updateFloat2("vDiffuseInfos",this._diffuseTexture.coordinatesIndex,this._diffuseTexture.level),nE.G.BindTextureMatrix(this._diffuseTexture,this._uniformBuffer,"diffuse")),e&&ow.ReflectionTextureEnabled&&(this._uniformBuffer.updateMatrix("reflectionMatrix",e.getReflectionTextureMatrix()),this._uniformBuffer.updateFloat2("vReflectionInfos",e.level,this._reflectionBlur),this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos",e.getSize().width,e.lodGenerationScale,e.lodGenerationOffset))),this.shadowLevel>0&&this._uniformBuffer.updateFloat("shadowLevel",this.shadowLevel),this._uniformBuffer.updateFloat("alpha",this.alpha),this.pointsCloud&&this._uniformBuffer.updateFloat("pointSize",this.pointSize),s.USEHIGHLIGHTANDSHADOWCOLORS?(this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryHighlightColor,1),this._uniformBuffer.updateColor4("vPrimaryColorShadow",this._primaryShadowColor,1)):this._uniformBuffer.updateColor4("vPrimaryColor",this._primaryColor,1)),this._uniformBuffer.updateFloat("fFovMultiplier",this._fovMultiplier),r.texturesEnabled&&(this._diffuseTexture&&ow.DiffuseTextureEnabled&&this._uniformBuffer.setTexture("diffuseSampler",this._diffuseTexture),e&&ow.ReflectionTextureEnabled&&(s.REFLECTIONBLUR&&s.TEXTURELODSUPPORT?this._uniformBuffer.setTexture("reflectionSampler",e):s.REFLECTIONBLUR?(this._uniformBuffer.setTexture("reflectionSampler",e._lodTextureMid||e),this._uniformBuffer.setTexture("reflectionSamplerLow",e._lodTextureLow||e),this._uniformBuffer.setTexture("reflectionSamplerHigh",e._lodTextureHigh||e)):this._uniformBuffer.setTexture("reflectionSampler",e),s.REFLECTIONFRESNEL&&(this._uniformBuffer.updateFloat3("vBackgroundCenter",this.sceneCenter.x,this.sceneCenter.y,this.sceneCenter.z),this._uniformBuffer.updateFloat4("vReflectionControl",this._reflectionControls.x,this._reflectionControls.y,this._reflectionControls.z,this._reflectionControls.w))),s.PROJECTED_GROUND&&this._uniformBuffer.updateFloat2("projectedGroundInfos",this.projectedGroundRadius,this.projectedGroundHeight)),(0,lH.an)(this._activeEffect,this,r),r.bindEyePosition(n)}else r.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._uniformBuffer.bindToEffect(n,"Material"),this._needToBindSceneUbo=!0);(a||!this.isFrozen)&&(r.lightsEnabled&&nE.G.BindLights(r,t,this._activeEffect,s,this._maxSimultaneousLights),this.bindView(n),nE.G.BindFogParameters(r,t,this._activeEffect,!0),this._useLogarithmicDepth&&nE.G.BindLogDepth(s,n,r),this._imageProcessingConfiguration&&this._imageProcessingConfiguration.bind(this._activeEffect)),this._afterBind(t,this._activeEffect),this._uniformBuffer.update()}hasTexture(e){return!!super.hasTexture(e)||this._reflectionTexture===e||this._diffuseTexture===e}dispose(e=!1,t=!1){t&&(this.diffuseTexture&&this.diffuseTexture.dispose(),this.reflectionTexture&&this.reflectionTexture.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return rG.p4.Clone(()=>new dB(e,this.getScene()),this)}serialize(){let e=super.serialize();return e.customType="BABYLON.BackgroundMaterial",e}getClassName(){return"BackgroundMaterial"}static Parse(e,t,i){return rG.p4.Parse(()=>new dB(e.name,t),e,t,i)}}dB.StandardReflectance0=.05,dB.StandardReflectance90=.5,(0,sx.gn)([(0,rG.n9)()],dB.prototype,"_primaryColor",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],dB.prototype,"primaryColor",void 0),(0,sx.gn)([(0,rG.n9)()],dB.prototype,"__perceptualColor",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_primaryColorShadowLevel",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_primaryColorHighlightLevel",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],dB.prototype,"primaryColorHighlightLevel",null),(0,sx.gn)([(0,rG.oU)()],dB.prototype,"_reflectionTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"reflectionTexture",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_reflectionBlur",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"reflectionBlur",void 0),(0,sx.gn)([(0,rG.oU)()],dB.prototype,"_diffuseTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"diffuseTexture",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"shadowLights",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_shadowLevel",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"shadowLevel",void 0),(0,sx.gn)([(0,rG.hd)()],dB.prototype,"_sceneCenter",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"sceneCenter",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_opacityFresnel",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"opacityFresnel",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_reflectionFresnel",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"reflectionFresnel",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_reflectionFalloffDistance",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"reflectionFalloffDistance",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_reflectionAmount",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"reflectionAmount",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_reflectionReflectance0",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"reflectionReflectance0",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_reflectionReflectance90",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"reflectionReflectance90",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_useRGBColor",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"useRGBColor",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_enableNoise",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"enableNoise",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_maxSimultaneousLights",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],dB.prototype,"maxSimultaneousLights",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"_shadowOnly",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],dB.prototype,"shadowOnly",void 0),(0,sx.gn)([(0,rG.rX)()],dB.prototype,"_imageProcessingConfiguration",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],dB.prototype,"enableGroundProjection",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"projectedGroundRadius",void 0),(0,sx.gn)([(0,rG.qC)()],dB.prototype,"projectedGroundHeight",void 0),(0,rg.H)("BABYLON.BackgroundMaterial",dB);class dU{static _GetDefaultOptions(e){return{createGround:!0,groundSize:15,groundTexture:this._GroundTextureCDNUrl,groundColor:new rm.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),groundOpacity:.9,enableGroundShadow:!0,groundShadowLevel:.5,enableGroundMirror:!1,groundMirrorSizeRatio:.3,groundMirrorBlurKernel:64,groundMirrorAmount:1,groundMirrorFresnelWeight:1,groundMirrorFallOffDistance:0,groundMirrorTextureType:0,groundYBias:1e-5,createSkybox:!0,skyboxSize:20,skyboxTexture:this._SkyboxTextureCDNUrl,skyboxColor:new rm.Wo(.2,.2,.3).toLinearSpace(e.getEngine().useExactSrgbConversions).scale(3),backgroundYRotation:0,sizeAuto:!0,rootPosition:rf.P.Zero(),setupImageProcessing:!0,environmentTexture:this._EnvironmentTextureCDNUrl,cameraExposure:.8,cameraContrast:1.2,toneMappingEnabled:!0}}get rootMesh(){return this._rootMesh}get skybox(){return this._skybox}get skyboxTexture(){return this._skyboxTexture}get skyboxMaterial(){return this._skyboxMaterial}get ground(){return this._ground}get groundTexture(){return this._groundTexture}get groundMirror(){return this._groundMirror}get groundMirrorRenderList(){return this._groundMirror?this._groundMirror.renderList:null}get groundMaterial(){return this._groundMaterial}constructor(e,t){this._errorHandler=(e,t)=>{this.onErrorObservable.notifyObservers({message:e,exception:t})},this._options=Object.assign(Object.assign({},dU._GetDefaultOptions(t)),e),this._scene=t,this.onErrorObservable=new r_.y$,this._setupBackground(),this._setupImageProcessing()}updateOptions(e){let t=Object.assign(Object.assign({},this._options),e);this._ground&&!t.createGround&&(this._ground.dispose(),this._ground=null),this._groundMaterial&&!t.createGround&&(this._groundMaterial.dispose(),this._groundMaterial=null),this._groundTexture&&this._options.groundTexture!=t.groundTexture&&(this._groundTexture.dispose(),this._groundTexture=null),this._skybox&&!t.createSkybox&&(this._skybox.dispose(),this._skybox=null),this._skyboxMaterial&&!t.createSkybox&&(this._skyboxMaterial.dispose(),this._skyboxMaterial=null),this._skyboxTexture&&this._options.skyboxTexture!=t.skyboxTexture&&(this._skyboxTexture.dispose(),this._skyboxTexture=null),this._groundMirror&&!t.enableGroundMirror&&(this._groundMirror.dispose(),this._groundMirror=null),this._scene.environmentTexture&&this._options.environmentTexture!=t.environmentTexture&&this._scene.environmentTexture.dispose(),this._options=t,this._setupBackground(),this._setupImageProcessing()}setMainColor(e){this.groundMaterial&&(this.groundMaterial.primaryColor=e),this.skyboxMaterial&&(this.skyboxMaterial.primaryColor=e),this.groundMirror&&(this.groundMirror.clearColor=new rm.HE(e.r,e.g,e.b,1))}_setupImageProcessing(){this._options.setupImageProcessing&&(this._scene.imageProcessingConfiguration.contrast=this._options.cameraContrast,this._scene.imageProcessingConfiguration.exposure=this._options.cameraExposure,this._scene.imageProcessingConfiguration.toneMappingEnabled=this._options.toneMappingEnabled,this._setupEnvironmentTexture())}_setupEnvironmentTexture(){if(this._scene.environmentTexture)return;if(this._options.environmentTexture instanceof sV){this._scene.environmentTexture=this._options.environmentTexture;return}let e=dM.CreateFromPrefilteredData(this._options.environmentTexture,this._scene);this._scene.environmentTexture=e}_setupBackground(){this._rootMesh||(this._rootMesh=new sp.Kj("BackgroundHelper",this._scene)),this._rootMesh.rotation.y=this._options.backgroundYRotation;let e=this._getSceneSize();this._options.createGround&&(this._setupGround(e),this._setupGroundMaterial(),this._setupGroundDiffuseTexture(),this._options.enableGroundMirror&&this._setupGroundMirrorTexture(e),this._setupMirrorInGroundMaterial()),this._options.createSkybox&&(this._setupSkybox(e),this._setupSkyboxMaterial(),this._setupSkyboxReflectionTexture()),this._rootMesh.position.x=e.rootPosition.x,this._rootMesh.position.z=e.rootPosition.z,this._rootMesh.position.y=e.rootPosition.y}_getSceneSize(){let e=this._options.groundSize,t=this._options.skyboxSize,i=this._options.rootPosition;if(!this._scene.meshes||1===this._scene.meshes.length)return{groundSize:e,skyboxSize:t,rootPosition:i};let r=this._scene.getWorldExtends(e=>e!==this._ground&&e!==this._rootMesh&&e!==this._skybox),s=r.max.subtract(r.min);if(this._options.sizeAuto){this._scene.activeCamera instanceof a2&&this._scene.activeCamera.upperRadiusLimit&&(t=e=2*this._scene.activeCamera.upperRadiusLimit);let n=s.length();n>e&&(t=e=2*n),e*=1.1,t*=1.5,(i=r.min.add(s.scale(.5))).y=r.min.y-this._options.groundYBias}return{groundSize:e,skyboxSize:t,rootPosition:i}}_setupGround(e){(!this._ground||this._ground.isDisposed())&&(this._ground=ne("BackgroundPlane",{size:e.groundSize},this._scene),this._ground.rotation.x=Math.PI/2,this._ground.parent=this._rootMesh,this._ground.onDisposeObservable.add(()=>{this._ground=null})),this._ground.receiveShadows=this._options.enableGroundShadow}_setupGroundMaterial(){this._groundMaterial||(this._groundMaterial=new dB("BackgroundPlaneMaterial",this._scene)),this._groundMaterial.alpha=this._options.groundOpacity,this._groundMaterial.alphaMode=8,this._groundMaterial.shadowLevel=this._options.groundShadowLevel,this._groundMaterial.primaryColor=this._options.groundColor,this._groundMaterial.useRGBColor=!1,this._groundMaterial.enableNoise=!0,this._ground&&(this._ground.material=this._groundMaterial)}_setupGroundDiffuseTexture(){if(this._groundMaterial&&!this._groundTexture){if(this._options.groundTexture instanceof sV){this._groundMaterial.diffuseTexture=this._options.groundTexture;return}this._groundTexture=new sj(this._options.groundTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._groundTexture.gammaSpace=!1,this._groundTexture.hasAlpha=!0,this._groundMaterial.diffuseTexture=this._groundTexture}}_setupGroundMirrorTexture(e){let t=sj.CLAMP_ADDRESSMODE;if(!this._groundMirror&&(this._groundMirror=new dI("BackgroundPlaneMirrorTexture",{ratio:this._options.groundMirrorSizeRatio},this._scene,!1,this._options.groundMirrorTextureType,sj.BILINEAR_SAMPLINGMODE,!0),this._groundMirror.mirrorPlane=new sz.J(0,-1,0,e.rootPosition.y),this._groundMirror.anisotropicFilteringLevel=1,this._groundMirror.wrapU=t,this._groundMirror.wrapV=t,this._groundMirror.renderList))for(let e=0;e{this._skybox=null})),this._skybox.parent=this._rootMesh}_setupSkyboxMaterial(){this._skybox&&(this._skyboxMaterial||(this._skyboxMaterial=new dB("BackgroundSkyboxMaterial",this._scene)),this._skyboxMaterial.useRGBColor=!1,this._skyboxMaterial.primaryColor=this._options.skyboxColor,this._skyboxMaterial.enableNoise=!0,this._skybox.material=this._skyboxMaterial)}_setupSkyboxReflectionTexture(){if(this._skyboxMaterial&&!this._skyboxTexture){if(this._options.skyboxTexture instanceof sV){this._skyboxMaterial.reflectionTexture=this._options.skyboxTexture;return}this._skyboxTexture=new dM(this._options.skyboxTexture,this._scene,void 0,void 0,void 0,void 0,this._errorHandler),this._skyboxTexture.coordinatesMode=sj.SKYBOX_MODE,this._skyboxTexture.gammaSpace=!1,this._skyboxMaterial.reflectionTexture=this._skyboxTexture}}dispose(){this._groundMaterial&&this._groundMaterial.dispose(!0,!0),this._skyboxMaterial&&this._skyboxMaterial.dispose(!0,!0),this._rootMesh.dispose(!1)}}dU._GroundTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundGround.png",dU._SkyboxTextureCDNUrl="https://assets.babylonjs.com/environments/backgroundSkybox.dds",dU._EnvironmentTextureCDNUrl="https://assets.babylonjs.com/environments/environmentSpecular.env";class dV extends s_.Y{get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._useDirectMapping?(this._texture.wrapU=sj.CLAMP_ADDRESSMODE,this._texture.wrapV=sj.CLAMP_ADDRESSMODE,this._material.diffuseTexture=this._texture):(this._texture.coordinatesMode=sj.FIXED_EQUIRECTANGULAR_MIRRORED_MODE,this._texture.wrapV=sj.CLAMP_ADDRESSMODE,this._material.reflectionTexture=this._texture),this._changeTextureMode(this._textureMode))}get mesh(){return this._mesh}get fovMultiplier(){return this._material.fovMultiplier}set fovMultiplier(e){this._material.fovMultiplier=e}get textureMode(){return this._textureMode}set textureMode(e){this._textureMode!==e&&this._changeTextureMode(e)}get halfDome(){return this._halfDome}set halfDome(e){this._halfDome=e,this._halfDomeMask.setEnabled(e),this._changeTextureMode(this._textureMode)}set crossEye(e){this._crossEye=e,this._changeTextureMode(this._textureMode)}get crossEye(){return this._crossEye}get material(){return this._material}constructor(e,t,i,r,s=null){super(e,r),this.onError=s,this._halfDome=!1,this._crossEye=!1,this._useDirectMapping=!1,this._textureMode=dV.MODE_MONOSCOPIC,this._onBeforeCameraRenderObserver=null,this.onLoadErrorObservable=new r_.y$,this.onLoadObservable=new r_.y$,r=this.getScene(),e=e||"textureDome",i.resolution=0|Math.abs(i.resolution)||32,i.clickToPlay=!!i.clickToPlay,i.autoPlay=void 0===i.autoPlay||!!i.autoPlay,i.loop=void 0===i.loop||!!i.loop,i.size=Math.abs(i.size)||(r.activeCamera?.48*r.activeCamera.maxZ:1e3),void 0===i.useDirectMapping?this._useDirectMapping=!0:this._useDirectMapping=i.useDirectMapping,void 0===i.faceForward&&(i.faceForward=!0),this._setReady(!1),i.mesh?this._mesh=i.mesh:this._mesh=hM(e+"_mesh",{segments:i.resolution,diameter:i.size,updatable:!1,sideOrientation:sp.Kj.BACKSIDE},r);let n=this._material=new dB(e+"_material",r);n.useEquirectangularFOV=!0,n.fovMultiplier=1,n.opacityFresnel=!1;let a=this._initTexture(t,r,i);if(this.texture=a,this._mesh.material=n,this._mesh.parent=this,this._halfDomeMask=hM("",{slice:.5,diameter:.98*i.size,segments:2*i.resolution,sideOrientation:sp.Kj.BACKSIDE},r),this._halfDomeMask.rotate(r5.RD.X,-Math.PI/2),this._halfDomeMask.parent=this._mesh,this._halfDome=!!i.halfDomeMode,this._halfDomeMask.setEnabled(this._halfDome),this._crossEye=!!i.crossEyeMode,this._texture.anisotropicFilteringLevel=1,this._texture.onLoadObservable.addOnce(()=>{this._setReady(!0)}),i.faceForward&&r.activeCamera){let e=r.activeCamera,t=rf.P.Forward(),i=rf.P.TransformNormal(t,e.getViewMatrix());i.normalize(),this.rotation.y=Math.acos(rf.P.Dot(t,i))}this._changeTextureMode(this._textureMode)}_changeTextureMode(e){switch(this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._textureMode=e,this._texture.uScale=1,this._texture.vScale=1,this._texture.uOffset=0,this._texture.vOffset=0,this._texture.vAng=0,e){case dV.MODE_MONOSCOPIC:this._halfDome&&(this._texture.uScale=2,this._texture.uOffset=-1);break;case dV.MODE_SIDEBYSIDE:{this._texture.uScale=this._halfDome?.99999:.5;let e=this._halfDome?0:.5,t=this._halfDome?-.5:0;this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(i=>{let r=i.isRightCamera;this._crossEye&&(r=!r),r?this._texture.uOffset=e:this._texture.uOffset=t});break}case dV.MODE_TOPBOTTOM:this._texture.vScale=this._halfDome?.99999:.5,this._onBeforeCameraRenderObserver=this._scene.onBeforeCameraRenderObservable.add(e=>{let t=e.isRightCamera;this._crossEye&&(t=!t),this._texture.vOffset=t?.5:0})}}dispose(e,t=!1){this._texture.dispose(),this._mesh.dispose(),this._material.dispose(),this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this.onLoadErrorObservable.clear(),this.onLoadObservable.clear(),super.dispose(e,t)}}dV.MODE_MONOSCOPIC=0,dV.MODE_TOPBOTTOM=1,dV.MODE_SIDEBYSIDE=2;class dk extends dV{get photoTexture(){return this.texture}set photoTexture(e){this.texture=e}get imageMode(){return this.textureMode}set imageMode(e){this.textureMode=e}_initTexture(e,t,i){return new sj(e,t,!i.generateMipMaps,!this._useDirectMapping,void 0,()=>{this.onLoadObservable.notifyObservers()},(e,t)=>{this.onLoadErrorObservable.notifyObservers(e||"Unknown error occured"),this.onError&&this.onError(e,t)})}}dk.MODE_MONOSCOPIC=dV.MODE_MONOSCOPIC,dk.MODE_TOPBOTTOM=dV.MODE_TOPBOTTOM,dk.MODE_SIDEBYSIDE=dV.MODE_SIDEBYSIDE;let dG=0,dz=e=>{if(!e.environmentBRDFTexture){let t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;let i=e._blockEntityCollection;e._blockEntityCollection=!1;let r=sj.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"+dG++,e,!0,!1,sj.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=i;let s=e.getEngine().getLoadedTexturesCache(),n=s.indexOf(r.getInternalTexture());-1!==n&&s.splice(n,1),r.isRGBD=!0,r.wrapU=sj.CLAMP_ADDRESSMODE,r.wrapV=sj.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=r,e.useDelayedTextureLoading=t,uC.ExpandRGBDTexture(r);let a=e.getEngine().onContextRestoredObservable.add(()=>{r.isRGBD=!0;let t=e.onBeforeRenderObservable.add(()=>{r.isReady()&&(e.onBeforeRenderObservable.remove(t),uC.ExpandRGBDTexture(r))})});e.onDisposeObservable.add(()=>{e.getEngine().onContextRestoredObservable.remove(a)})}return e.environmentBRDFTexture};class dW extends nf.H{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 dH extends lG{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}constructor(e,t=!0){super(e,"PBRBRDF",90,new dW,t),this._useEnergyConservation=dH.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=dH.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=dH.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=dH.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=dH.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=dH.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=dH.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=dH.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16],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"}}dH.DEFAULT_USE_ENERGY_CONSERVATION=!0,dH.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,dH.DEFAULT_USE_SPHERICAL_HARMONICS=!0,dH.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],dH.prototype,"useEnergyConservation",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],dH.prototype,"useSmithVisibilityHeightCorrelated",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],dH.prototype,"useSphericalHarmonics",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],dH.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);let dX=`uniform vec4 vEyePosition;uniform vec3 vReflectionColor;uniform vec4 vAlbedoColor;uniform vec4 vLightingIntensity;uniform vec4 vReflectivityColor;uniform vec4 vMetallicReflectanceFactors;uniform vec3 vEmissiveColor;uniform float visibility;uniform vec3 vAmbientColor; +#ifdef ALBEDO +uniform vec2 vAlbedoInfos; +#endif +#ifdef AMBIENT +uniform vec4 vAmbientInfos; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#ifdef OPACITY +uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos; +#endif +#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(SS_REFRACTION) || defined(PREPASS) +uniform mat4 view; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos; +#ifdef REALTIME_FILTERING +uniform vec2 vReflectionFilteringInfo; +#endif +uniform mat4 reflectionMatrix;uniform vec3 vReflectionMicrosurfaceInfos; +#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +#if defined(SS_REFRACTION) && defined(SS_USE_LOCAL_REFRACTIONMAP_CUBIC) +uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; +#endif +#ifdef CLEARCOAT +uniform vec2 vClearCoatParams;uniform vec4 vClearCoatRefractionParams; +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform vec2 vClearCoatTangentSpaceParams;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT +uniform vec4 vClearCoatTintParams;uniform float clearCoatColorAtDistance; +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#endif +#ifdef IRIDESCENCE +uniform vec4 vIridescenceParams; +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +uniform vec3 vAnisotropy; +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +uniform vec4 vSheenColor; +#ifdef SHEEN_ROUGHNESS +uniform float vSheenRoughness; +#endif +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionMicrosurfaceInfos;uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#ifdef REALTIME_FILTERING +uniform vec2 vRefractionFilteringInfo; +#endif +#ifdef SS_DISPERSION +uniform float dispersion; +#endif +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +uniform vec2 vThicknessParam;uniform vec3 vDiffusionDistance;uniform vec4 vTintColor;uniform vec3 vSubSurfaceIntensity; +#endif +#ifdef PREPASS +#ifdef SS_SCATTERING +uniform float scatteringDiffusionProfile; +#endif +#endif +#if DEBUGMODE>0 +uniform vec2 vDebugMode; +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos; +#endif +#include +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#define ADDITIONAL_FRAGMENT_DECLARATION +`;nw.v.IncludesShadersStore.pbrFragmentDeclaration=dX;let dY=`layout(std140,column_major) uniform;uniform Material {vec2 vAlbedoInfos;vec4 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec3 vReflectivityInfos;vec2 vMicroSurfaceSamplerInfos;vec2 vReflectionInfos;vec2 vReflectionFilteringInfo;vec3 vReflectionPosition;vec3 vReflectionSize;vec3 vBumpInfos;mat4 albedoMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 reflectivityMatrix;mat4 microSurfaceSamplerMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;mat4 reflectionMatrix;vec3 vReflectionColor;vec4 vAlbedoColor;vec4 vLightingIntensity;vec3 vReflectionMicrosurfaceInfos;float pointSize;vec4 vReflectivityColor;vec3 vEmissiveColor;vec3 vAmbientColor;vec2 vDebugMode;vec4 vMetallicReflectanceFactors;vec2 vMetallicReflectanceInfos;mat4 metallicReflectanceMatrix;vec2 vReflectanceInfos;mat4 reflectanceMatrix;vec3 vSphericalL00;vec3 vSphericalL1_1;vec3 vSphericalL10;vec3 vSphericalL11;vec3 vSphericalL2_2;vec3 vSphericalL2_1;vec3 vSphericalL20;vec3 vSphericalL21;vec3 vSphericalL22;vec3 vSphericalX;vec3 vSphericalY;vec3 vSphericalZ;vec3 vSphericalXX_ZZ;vec3 vSphericalYY_ZZ;vec3 vSphericalZZ;vec3 vSphericalXY;vec3 vSphericalYZ;vec3 vSphericalZX; +#define ADDITIONAL_UBO_DECLARATION +}; +#include +#include +`;nw.v.IncludesShadersStore.pbrUboDeclaration=dY;let dj=`varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#include[1..7] +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +`;nw.v.IncludesShadersStore.pbrFragmentExtraDeclaration=dj;let dq=`#ifdef _DEFINENAME_ +#if _DEFINENAME_DIRECTUV==1 +#define v_VARYINGNAME_UV vMainUV1 +#elif _DEFINENAME_DIRECTUV==2 +#define v_VARYINGNAME_UV vMainUV2 +#elif _DEFINENAME_DIRECTUV==3 +#define v_VARYINGNAME_UV vMainUV3 +#elif _DEFINENAME_DIRECTUV==4 +#define v_VARYINGNAME_UV vMainUV4 +#elif _DEFINENAME_DIRECTUV==5 +#define v_VARYINGNAME_UV vMainUV5 +#elif _DEFINENAME_DIRECTUV==6 +#define v_VARYINGNAME_UV vMainUV6 +#else +varying vec2 v_VARYINGNAME_UV; +#endif +#endif +`;nw.v.IncludesShadersStore.samplerFragmentAlternateDeclaration=dq;let dK=`#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_SAMPLERNAME_,albedo) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_SAMPLERNAME_,reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_SAMPLERNAME_,microSurface) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_SAMPLERNAME_,metallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_SAMPLERNAME_,reflectance) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_SAMPLERNAME_,clearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) +uniform sampler2D clearCoatRoughnessSampler; +#endif +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_SAMPLERNAME_,clearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_SAMPLERNAME_,clearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_SAMPLERNAME_,iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_SAMPLERNAME_,iridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_SAMPLERNAME_,sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) +uniform sampler2D sheenRoughnessSampler; +#endif +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_SAMPLERNAME_,anisotropy) +#endif +#ifdef REFLECTION +#ifdef REFLECTIONMAP_3D +#define sampleReflection(s,c) textureCube(s,c) +uniform samplerCube reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube reflectionSamplerLow;uniform samplerCube reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform samplerCube irradianceSampler; +#endif +#else +#define sampleReflection(s,c) texture2D(s,c) +uniform sampler2D reflectionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D reflectionSamplerLow;uniform sampler2D reflectionSamplerHigh; +#endif +#ifdef USEIRRADIANCEMAP +uniform sampler2D irradianceSampler; +#endif +#endif +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#else +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#endif +#endif +#ifdef ENVIRONMENTBRDF +uniform sampler2D environmentBrdfSampler; +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#ifdef SS_REFRACTIONMAP_3D +#define sampleRefraction(s,c) textureCube(s,c) +uniform samplerCube refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l) +#else +uniform samplerCube refractionSamplerLow;uniform samplerCube refractionSamplerHigh; +#endif +#else +#define sampleRefraction(s,c) texture2D(s,c) +uniform sampler2D refractionSampler; +#ifdef LODBASEDMICROSFURACE +#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l) +#else +uniform sampler2D refractionSamplerLow;uniform sampler2D refractionSamplerHigh; +#endif +#endif +#endif +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_SAMPLERNAME_,thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_SAMPLERNAME_,refractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_SAMPLERNAME_,translucencyIntensity) +#endif +`;nw.v.IncludesShadersStore.pbrFragmentSamplersDeclaration=dK;let d$=`bool testLightingForSSS(float diffusionProfile) +{return diffusionProfile<1.;}`;nw.v.IncludesShadersStore.subSurfaceScatteringFunctions=d$;let dQ=`vec3 hemisphereCosSample(vec2 u) {float phi=2.*PI*u.x;float cosTheta2=1.-u.y;float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDggx(vec2 u,float a) {float phi=2.*PI*u.x;float cosTheta2=(1.-u.y)/(1.+(a+1.)*((a-1.)*u.y));float cosTheta=sqrt(cosTheta2);float sinTheta=sqrt(1.-cosTheta2);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);} +vec3 hemisphereImportanceSampleDCharlie(vec2 u,float a) { +float phi=2.*PI*u.x;float sinTheta=pow(u.y,a/(2.*a+1.));float cosTheta=sqrt(1.-sinTheta*sinTheta);return vec3(sinTheta*cos(phi),sinTheta*sin(phi),cosTheta);}`;nw.v.IncludesShadersStore.importanceSampling=dQ;let dZ=`#define MINIMUMVARIANCE 0.0005 +float convertRoughnessToAverageSlope(float roughness) +{return square(roughness)+MINIMUMVARIANCE;} +float fresnelGrazingReflectance(float reflectance0) {float reflectance90=saturate(reflectance0*25.0);return reflectance90;} +vec2 getAARoughnessFactors(vec3 normalVector) { +#ifdef SPECULARAA +vec3 nDfdx=dFdx(normalVector.xyz);vec3 nDfdy=dFdy(normalVector.xyz);float slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));float geometricRoughnessFactor=pow(saturate(slopeSquare),0.333);float geometricAlphaGFactor=sqrt(slopeSquare);geometricAlphaGFactor*=0.75;return vec2(geometricRoughnessFactor,geometricAlphaGFactor); +#else +return vec2(0.); +#endif +} +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_LEGACY +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(alphaG*(1.0+anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG*(1.0-anisotropy),MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 anisotropicFrameDirection=anisotropy>=0.0 ? B : T;vec3 anisotropicFrameTangent=cross(normalize(anisotropicFrameDirection),V);vec3 anisotropicFrameNormal=cross(anisotropicFrameTangent,anisotropicFrameDirection);vec3 anisotropicNormal=normalize(mix(N,anisotropicFrameNormal,abs(anisotropy)));return anisotropicNormal;} +#else +vec2 getAnisotropicRoughness(float alphaG,float anisotropy) {float alphaT=max(mix(alphaG,1.0,anisotropy*anisotropy),MINIMUMVARIANCE);float alphaB=max(alphaG,MINIMUMVARIANCE);return vec2(alphaT,alphaB);} +vec3 getAnisotropicBentNormals(const vec3 T,const vec3 B,const vec3 N,const vec3 V,float anisotropy,float roughness) {vec3 bentNormal=cross(B,V);bentNormal=normalize(cross(bentNormal,B));float a=square(square(1.0-anisotropy*(1.0-roughness)));bentNormal=normalize(mix(bentNormal,N,a));return bentNormal;} +#endif +#endif +#if defined(CLEARCOAT) || defined(SS_REFRACTION) +vec3 cocaLambert(vec3 alpha,float distance) {return exp(-alpha*distance);} +vec3 cocaLambert(float NdotVRefract,float NdotLRefract,vec3 alpha,float thickness) {return cocaLambert(alpha,(thickness*((NdotLRefract+NdotVRefract)/(NdotLRefract*NdotVRefract))));} +vec3 computeColorAtDistanceInMedia(vec3 color,float distance) {return -log(color)/distance;} +vec3 computeClearCoatAbsorption(float NdotVRefract,float NdotLRefract,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 clearCoatAbsorption=mix(vec3(1.0), +cocaLambert(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness), +clearCoatIntensity);return clearCoatAbsorption;} +#endif +#ifdef MICROSURFACEAUTOMATIC +float computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor) +{const float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;float reflectivityLuminance=getLuminance(reflectivityColor);float reflectivityLuma=sqrt(reflectivityLuminance);microSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;return microSurface;} +#endif +`;nw.v.IncludesShadersStore.pbrHelperFunctions=dZ;let dJ=`#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +vec3 computeEnvironmentIrradiance(vec3 normal) {return vSphericalL00 ++ vSphericalL1_1*(normal.y) ++ vSphericalL10*(normal.z) ++ vSphericalL11*(normal.x) ++ vSphericalL2_2*(normal.y*normal.x) ++ vSphericalL2_1*(normal.y*normal.z) ++ vSphericalL20*((3.0*normal.z*normal.z)-1.0) ++ vSphericalL21*(normal.z*normal.x) ++ vSphericalL22*(normal.x*normal.x-(normal.y*normal.y));} +#else +vec3 computeEnvironmentIrradiance(vec3 normal) {float Nx=normal.x;float Ny=normal.y;float Nz=normal.z;vec3 C1=vSphericalZZ.rgb;vec3 Cx=vSphericalX.rgb;vec3 Cy=vSphericalY.rgb;vec3 Cz=vSphericalZ.rgb;vec3 Cxx_zz=vSphericalXX_ZZ.rgb;vec3 Cyy_zz=vSphericalYY_ZZ.rgb;vec3 Cxy=vSphericalXY.rgb;vec3 Cyz=vSphericalYZ.rgb;vec3 Czx=vSphericalZX.rgb;vec3 a1=Cyy_zz*Ny+Cy;vec3 a2=Cyz*Nz+a1;vec3 b1=Czx*Nz+Cx;vec3 b2=Cxy*Ny+b1;vec3 b3=Cxx_zz*Nx+b2;vec3 t1=Cz *Nz+C1;vec3 t2=a2 *Ny+t1;vec3 t3=b3 *Nx+t2;return t3;} +#endif +#endif +`;nw.v.IncludesShadersStore.harmonicsFunctions=dJ;let d0=`struct preLightingInfo +{vec3 lightOffset;float lightDistanceSquared;float lightDistance;float attenuation;vec3 L;vec3 H;float NdotV;float NdotLUnclamped;float NdotL;float VdotH;float roughness; +#ifdef IRIDESCENCE +float iridescenceIntensity; +#endif +};preLightingInfo computePointAndSpotPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightOffset=lightData.xyz-vPositionW;result.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);result.lightDistance=sqrt(result.lightDistanceSquared);result.L=normalize(result.lightOffset);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeDirectionalPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.lightDistance=length(-lightData.xyz);result.L=normalize(-lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H));result.NdotLUnclamped=dot(N,result.L);result.NdotL=saturateEps(result.NdotLUnclamped);return result;} +preLightingInfo computeHemisphericPreLightingInfo(vec4 lightData,vec3 V,vec3 N) {preLightingInfo result;result.NdotL=dot(N,lightData.xyz)*0.5+0.5;result.NdotL=saturateEps(result.NdotL);result.NdotLUnclamped=result.NdotL; +#ifdef SPECULARTERM +result.L=normalize(lightData.xyz);result.H=normalize(V+result.L);result.VdotH=saturate(dot(V,result.H)); +#endif +return result;}`;nw.v.IncludesShadersStore.pbrDirectLightingSetupFunctions=d0;let d1=`float computeDistanceLightFalloff_Standard(vec3 lightOffset,float range) +{return max(0.,1.0-length(lightOffset)/range);} +float computeDistanceLightFalloff_Physical(float lightDistanceSquared) +{return 1.0/maxEps(lightDistanceSquared);} +float computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange) +{float lightDistanceFalloff=1.0/maxEps(lightDistanceSquared);float factor=lightDistanceSquared*inverseSquaredRange;float attenuation=saturate(1.0-factor*factor);attenuation*=attenuation;lightDistanceFalloff*=attenuation;return lightDistanceFalloff;} +float computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDistanceLightFalloff_Physical(lightDistanceSquared); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange); +#else +return computeDistanceLightFalloff_Standard(lightOffset,range); +#endif +} +float computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent) +{float falloff=0.0;float cosAngle=maxEps(dot(-lightDirection,directionToLightCenterW));if (cosAngle>=cosHalfAngle) +{falloff=max(0.,pow(cosAngle,exponent));} +return falloff;} +float computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle) +{const float kMinusLog2ConeAngleIntensityRatio=6.64385618977; +float concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);vec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);float falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));return falloff;} +float computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset) +{float cd=dot(-lightDirection,directionToLightCenterW);float falloff=saturate(cd*lightAngleScale+lightAngleOffset);falloff*=falloff;return falloff;} +float computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset) +{ +#ifdef USEPHYSICALLIGHTFALLOFF +return computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle); +#elif defined(USEGLTFLIGHTFALLOFF) +return computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset); +#else +return computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent); +#endif +}`;nw.v.IncludesShadersStore.pbrDirectLightingFalloffFunctions=d1;let d2=`#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} +#endif +#ifdef ENVIRONMENTBRDF +vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); +#ifdef ENVIRONMENTBRDF_RGBD +brdfLookup.rgb=fromRGBD(brdfLookup.rgba); +#endif +return brdfLookup.rgb;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; +#endif +return reflectance;} +vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { +#ifdef BRDF_V_HEIGHT_CORRELATED +vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); +#else +vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; +#endif +return reflectance;} +#endif +/* NOT USED +#if defined(SHEEN) && defined(SHEEN_SOFTER) +float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) +{float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} +#endif +*/ +#if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) +vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) +{float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +/** +* The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. +* The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table +*/ +vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} +#endif +vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) +{return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} +#ifdef CLEARCOAT +vec3 getR0RemappedForClearCoat(vec3 f0) { +#ifdef CLEARCOAT_DEFAULTIOR +#ifdef MOBILE +return saturate(f0*(f0*0.526868+0.529324)-0.0482256); +#else +return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); +#endif +#else +vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); +#endif +} +#endif +#ifdef IRIDESCENCE +const mat3 XYZ_TO_REC709=mat3( +3.2404542,-0.9692660, 0.0556434, +-1.5371385, 1.8760108,-0.2040259, +-0.4985314, 0.0415560, 1.0572252 +);vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} +vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} +float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} +vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} +vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} +float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0 +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +float radicalInverse_VdC(uint bits) +{bits=(bits<<16u) | (bits>>16u);bits=((bits & 0x55555555u)<<1u) | ((bits & 0xAAAAAAAAu)>>1u);bits=((bits & 0x33333333u)<<2u) | ((bits & 0xCCCCCCCCu)>>2u);bits=((bits & 0x0F0F0F0Fu)<<4u) | ((bits & 0xF0F0F0F0u)>>4u);bits=((bits & 0x00FF00FFu)<<8u) | ((bits & 0xFF00FF00u)>>8u);return float(bits)*2.3283064365386963e-10; } +vec2 hammersley(uint i,uint N) +{return vec2(float(i)/float(N),radicalInverse_VdC(i));} +#else +float vanDerCorpus(int n,int base) +{float invBase=1.0/float(base);float denom =1.0;float result =0.0;for(int i=0; i<32; ++i) +{if(n>0) +{denom =mod(float(n),2.0);result+=denom*invBase;invBase=invBase/2.0;n =int(float(n)/2.0);}} +return result;} +vec2 hammersley(int i,int N) +{return vec2(float(i)/float(N),vanDerCorpus(i,2));} +#endif +float log4(float x) {return log2(x)/2.;} +const float NUM_SAMPLES_FLOAT=float(NUM_SAMPLES);const float NUM_SAMPLES_FLOAT_INVERSED=1./NUM_SAMPLES_FLOAT;const float K=4.; +#define inline +vec3 irradiance(samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);vec3 result=vec3(0.0);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0); +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i0.) {float pdf_inversed=PI/NoL;float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(l,0.0,maxLevel);vec3 c=textureCubeLodEXT(inputTexture,tbn*Ls,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c;}} +result=result*NUM_SAMPLES_FLOAT_INVERSED;return result;} +#define inline +vec3 radiance(float alphaG,samplerCube inputTexture,vec3 inputN,vec2 filteringInfo) +{vec3 n=normalize(inputN);vec3 c=textureCube(inputTexture,n).rgb; +if (alphaG==0.) { +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +return c;} else {vec3 result=vec3(0.);vec3 tangent=abs(n.z)<0.999 ? vec3(0.,0.,1.) : vec3(1.,0.,0.);tangent=normalize(cross(tangent,n));vec3 bitangent=cross(n,tangent);mat3 tbn=mat3(tangent,bitangent,n);float maxLevel=filteringInfo.y;float dim0=filteringInfo.x;float omegaP=(4.*PI)/(6.*dim0*dim0);float weight=0.; +#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +for(uint i=0u; i0.) {float pdf_inversed=4./normalDistributionFunction_TrowbridgeReitzGGX(NoH,alphaG);float omegaS=NUM_SAMPLES_FLOAT_INVERSED*pdf_inversed;float l=log4(omegaS)-log4(omegaP)+log4(K);float mipLevel=clamp(float(l),0.0,maxLevel);weight+=NoL;vec3 c=textureCubeLodEXT(inputTexture,tbn*L,mipLevel).rgb; +#ifdef GAMMA_INPUT +c=toLinearSpace(c); +#endif +result+=c*NoL;}} +result=result/weight;return result;}} +#endif +#endif +`;nw.v.IncludesShadersStore.hdrFilteringFunctions=d3;let d4=`#define CLEARCOATREFLECTANCE90 1.0 +struct lightingInfo +{vec3 diffuse; +#ifdef SPECULARTERM +vec3 specular; +#endif +#ifdef CLEARCOAT +vec4 clearCoat; +#endif +#ifdef SHEEN +vec3 sheen; +#endif +};float adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance) { +#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF) +float lightRoughness=lightRadius/lightDistance;float totalRoughness=saturate(lightRoughness+roughness);return totalRoughness; +#else +return roughness; +#endif +} +vec3 computeHemisphericDiffuseLighting(preLightingInfo info,vec3 lightColor,vec3 groundColor) {return mix(groundColor,lightColor,info.NdotL);} +vec3 computeDiffuseLighting(preLightingInfo info,vec3 lightColor) {float diffuseTerm=diffuseBRDF_Burley(info.NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*info.attenuation*info.NdotL*lightColor;} +#define inline +vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){vec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return toLinearSpace(textureColor);} +#ifdef SS_TRANSLUCENCY +vec3 computeDiffuseAndTransmittedLighting(preLightingInfo info,vec3 lightColor,vec3 transmittance) {float NdotL=absEps(info.NdotLUnclamped);float wrapNdotL=computeWrappedDiffuseNdotL(NdotL,0.02);float trAdapt=step(0.,info.NdotLUnclamped);vec3 transmittanceNdotL=mix(transmittance*wrapNdotL,vec3(wrapNdotL),trAdapt);float diffuseTerm=diffuseBRDF_Burley(NdotL,info.NdotV,info.VdotH,info.roughness);return diffuseTerm*transmittanceNdotL*info.attenuation*lightColor;} +#endif +#ifdef SPECULARTERM +vec3 computeSpecularLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG); +#ifdef BRDF_V_HEIGHT_CORRELATED +float smithVisibility=smithVisibility_GGXCorrelated(info.NdotL,info.NdotV,alphaG); +#else +float smithVisibility=smithVisibility_TrowbridgeReitzGGXFast(info.NdotL,info.NdotV,alphaG); +#endif +vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef ANISOTROPIC +vec3 computeAnisotropicSpecularLighting(preLightingInfo info,vec3 V,vec3 N,vec3 T,vec3 B,float anisotropy,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float TdotH=dot(T,info.H);float BdotH=dot(B,info.H);float TdotV=dot(T,V);float BdotV=dot(B,V);float TdotL=dot(T,info.L);float BdotL=dot(B,info.L);float alphaG=convertRoughnessToAverageSlope(info.roughness);vec2 alphaTB=getAnisotropicRoughness(alphaG,anisotropy);alphaTB=max(alphaTB,square(geometricRoughnessFactor));vec3 fresnel=fresnelSchlickGGX(info.VdotH,reflectance0,reflectance90); +#ifdef IRIDESCENCE +fresnel=mix(fresnel,reflectance0,info.iridescenceIntensity); +#endif +float distribution=normalDistributionFunction_BurleyGGX_Anisotropic(NdotH,TdotH,BdotH,alphaTB);float smithVisibility=smithVisibility_GGXCorrelated_Anisotropic(info.NdotL,info.NdotV,TdotV,BdotV,TdotL,BdotL,alphaTB);vec3 specTerm=fresnel*distribution*smithVisibility;return specTerm*info.attenuation*info.NdotL*lightColor;} +#endif +#ifdef CLEARCOAT +vec4 computeClearCoatLighting(preLightingInfo info,vec3 Ncc,float geometricRoughnessFactor,float clearCoatIntensity,vec3 lightColor) {float NccdotL=saturateEps(dot(Ncc,info.L));float NccdotH=saturateEps(dot(Ncc,info.H));float clearCoatRoughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(clearCoatRoughness);float fresnel=fresnelSchlickGGX(info.VdotH,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnel*=clearCoatIntensity;float distribution=normalDistributionFunction_TrowbridgeReitzGGX(NccdotH,alphaG);float kelemenVisibility=visibility_Kelemen(info.VdotH);float clearCoatTerm=fresnel*distribution*kelemenVisibility;return vec4( +clearCoatTerm*info.attenuation*NccdotL*lightColor, +1.0-fresnel +);} +vec3 computeClearCoatLightingAbsorption(float NdotVRefract,vec3 L,vec3 Ncc,vec3 clearCoatColor,float clearCoatThickness,float clearCoatIntensity) {vec3 LRefract=-refract(L,Ncc,vClearCoatRefractionParams.y);float NdotLRefract=saturateEps(dot(Ncc,LRefract));vec3 absorption=computeClearCoatAbsorption(NdotVRefract,NdotLRefract,clearCoatColor,clearCoatThickness,clearCoatIntensity);return absorption;} +#endif +#ifdef SHEEN +vec3 computeSheenLighting(preLightingInfo info,vec3 N,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,vec3 lightColor) {float NdotH=saturateEps(dot(N,info.H));float roughness=max(info.roughness,geometricRoughnessFactor);float alphaG=convertRoughnessToAverageSlope(roughness);float fresnel=1.;float distribution=normalDistributionFunction_CharlieSheen(NdotH,alphaG);/*#ifdef SHEEN_SOFTER +float visibility=visibility_CharlieSheen(info.NdotL,info.NdotV,alphaG); +#else */ +float visibility=visibility_Ashikhmin(info.NdotL,info.NdotV);/* #endif */ +float sheenTerm=fresnel*distribution*visibility;return sheenTerm*info.attenuation*info.NdotL*lightColor;} +#endif +`;nw.v.IncludesShadersStore.pbrDirectLightingFunctions=d4;let d5=`#if defined(REFLECTION) || defined(SS_REFRACTION) +float getLodFromAlphaG(float cubeMapDimensionPixels,float microsurfaceAverageSlope) {float microsurfaceAverageSlopeTexels=cubeMapDimensionPixels*microsurfaceAverageSlope;float lod=log2(microsurfaceAverageSlopeTexels);return lod;} +float getLinearLodFromRoughness(float cubeMapDimensionPixels,float roughness) {float lod=log2(cubeMapDimensionPixels)*roughness;return lod;} +#endif +#if defined(ENVIRONMENTBRDF) && defined(RADIANCEOCCLUSION) +float environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {float temp=NdotVUnclamped+ambientOcclusion;return saturate(square(temp)-1.0+ambientOcclusion);} +#endif +#if defined(ENVIRONMENTBRDF) && defined(HORIZONOCCLUSION) +float environmentHorizonOcclusion(vec3 view,vec3 normal,vec3 geometricNormal) {vec3 reflection=reflect(view,normal);float temp=saturate(1.0+1.1*dot(reflection,geometricNormal));return square(temp);} +#endif +#if defined(LODINREFLECTIONALPHA) || defined(SS_LODINREFRACTIONALPHA) +#define UNPACK_LOD(x) (1.0-x)*255.0 +float getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {float microsurfaceAverageSlope=alphaG;microsurfaceAverageSlope*=sqrt(abs(NdotV));return getLodFromAlphaG(cubeMapDimensionPixels,microsurfaceAverageSlope);} +#endif +`;nw.v.IncludesShadersStore.pbrIBLFunctions=d5;let d6=`struct albedoOpacityOutParams +{vec3 surfaceAlbedo;float alpha;}; +#define pbr_inline +void albedoOpacityBlock( +in vec4 vAlbedoColor, +#ifdef ALBEDO +in vec4 albedoTexture, +in vec2 albedoInfos, +#endif +#ifdef OPACITY +in vec4 opacityMap, +in vec2 vOpacityInfos, +#endif +#ifdef DETAIL +in vec4 detailColor, +in vec4 vDetailInfos, +#endif +#ifdef DECAL +in vec4 decalColor, +in vec4 vDecalInfos, +#endif +out albedoOpacityOutParams outParams +) +{vec3 surfaceAlbedo=vAlbedoColor.rgb;float alpha=vAlbedoColor.a; +#ifdef ALBEDO +#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST) +alpha*=albedoTexture.a; +#endif +#ifdef GAMMAALBEDO +surfaceAlbedo*=toLinearSpace(albedoTexture.rgb); +#else +surfaceAlbedo*=albedoTexture.rgb; +#endif +surfaceAlbedo*=albedoInfos.y; +#endif +#ifndef DECAL_AFTER_DETAIL +#include +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +surfaceAlbedo*=vColor.rgb; +#endif +#ifdef DETAIL +float detailAlbedo=2.0*mix(0.5,detailColor.r,vDetailInfos.y);surfaceAlbedo.rgb=surfaceAlbedo.rgb*detailAlbedo*detailAlbedo; +#endif +#ifdef DECAL_AFTER_DETAIL +#include +#endif +#define CUSTOM_FRAGMENT_UPDATE_ALBEDO +#ifdef OPACITY +#ifdef OPACITYRGB +alpha=getLuminance(opacityMap.rgb); +#else +alpha*=opacityMap.a; +#endif +alpha*=vOpacityInfos.y; +#endif +#if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) +alpha*=vColor.a; +#endif +#if !defined(SS_LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL) +#ifdef ALPHATEST +#if DEBUGMODE != 88 +if (alpha0 +#ifdef METALLICWORKFLOW +vec2 metallicRoughness; +#ifdef REFLECTIVITY +vec4 surfaceMetallicColorMap; +#endif +#ifndef FROSTBITE_REFLECTANCE +vec3 metallicF0; +#endif +#else +#ifdef REFLECTIVITY +vec4 surfaceReflectivityColorMap; +#endif +#endif +#endif +}; +#define pbr_inline +void reflectivityBlock( +in vec4 vReflectivityColor, +#ifdef METALLICWORKFLOW +in vec3 surfaceAlbedo, +in vec4 metallicReflectanceFactors, +#endif +#ifdef REFLECTIVITY +in vec3 reflectivityInfos, +in vec4 surfaceMetallicOrReflectivityColorMap, +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +in vec3 ambientOcclusionColorIn, +#endif +#ifdef MICROSURFACEMAP +in vec4 microSurfaceTexel, +#endif +#ifdef DETAIL +in vec4 detailColor, +in vec4 vDetailInfos, +#endif +out reflectivityOutParams outParams +) +{float microSurface=vReflectivityColor.a;vec3 surfaceReflectivityColor=vReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec2 metallicRoughness=surfaceReflectivityColor.rg; +#ifdef REFLECTIVITY +#if DEBUGMODE>0 +outParams.surfaceMetallicColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef AOSTOREINMETALMAPRED +vec3 aoStoreInMetalMap=vec3(surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r,surfaceMetallicOrReflectivityColorMap.r);outParams.ambientOcclusionColor=mix(ambientOcclusionColorIn,aoStoreInMetalMap,reflectivityInfos.z); +#endif +#ifdef METALLNESSSTOREINMETALMAPBLUE +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.b; +#else +metallicRoughness.r*=surfaceMetallicOrReflectivityColorMap.r; +#endif +#ifdef ROUGHNESSSTOREINMETALMAPALPHA +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.a; +#else +#ifdef ROUGHNESSSTOREINMETALMAPGREEN +metallicRoughness.g*=surfaceMetallicOrReflectivityColorMap.g; +#endif +#endif +#endif +#ifdef DETAIL +float detailRoughness=mix(0.5,detailColor.b,vDetailInfos.w);float loLerp=mix(0.,metallicRoughness.g,detailRoughness*2.);float hiLerp=mix(metallicRoughness.g,1.,(detailRoughness-0.5)*2.);metallicRoughness.g=mix(loLerp,hiLerp,step(detailRoughness,0.5)); +#endif +#ifdef MICROSURFACEMAP +metallicRoughness.g*=microSurfaceTexel.r; +#endif +#if DEBUGMODE>0 +outParams.metallicRoughness=metallicRoughness; +#endif +#define CUSTOM_FRAGMENT_UPDATE_METALLICROUGHNESS +microSurface=1.0-metallicRoughness.g;vec3 baseColor=surfaceAlbedo; +#ifdef FROSTBITE_REFLECTANCE +outParams.surfaceAlbedo=baseColor.rgb*(1.0-metallicRoughness.r);surfaceReflectivityColor=mix(0.16*reflectance*reflectance,baseColor,metallicRoughness.r); +#else +vec3 metallicF0=metallicReflectanceFactors.rgb; +#if DEBUGMODE>0 +outParams.metallicF0=metallicF0; +#endif +outParams.surfaceAlbedo=mix(baseColor.rgb*(1.0-metallicF0),vec3(0.,0.,0.),metallicRoughness.r);surfaceReflectivityColor=mix(metallicF0,baseColor,metallicRoughness.r); +#endif +#else +#ifdef REFLECTIVITY +surfaceReflectivityColor*=surfaceMetallicOrReflectivityColorMap.rgb; +#if DEBUGMODE>0 +outParams.surfaceReflectivityColorMap=surfaceMetallicOrReflectivityColorMap; +#endif +#ifdef MICROSURFACEFROMREFLECTIVITYMAP +microSurface*=surfaceMetallicOrReflectivityColorMap.a;microSurface*=reflectivityInfos.z; +#else +#ifdef MICROSURFACEAUTOMATIC +microSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor); +#endif +#ifdef MICROSURFACEMAP +microSurface*=microSurfaceTexel.r; +#endif +#define CUSTOM_FRAGMENT_UPDATE_MICROSURFACE +#endif +#endif +#endif +microSurface=saturate(microSurface);float roughness=1.-microSurface;outParams.microSurface=microSurface;outParams.roughness=roughness;outParams.surfaceReflectivityColor=surfaceReflectivityColor;} +`;nw.v.IncludesShadersStore.pbrBlockReflectivity=d8;let d7=`struct ambientOcclusionOutParams +{vec3 ambientOcclusionColor; +#if DEBUGMODE>0 && defined(AMBIENT) +vec3 ambientOcclusionColorMap; +#endif +}; +#define pbr_inline +void ambientOcclusionBlock( +#ifdef AMBIENT +in vec3 ambientOcclusionColorMap_, +in vec4 vAmbientInfos, +#endif +out ambientOcclusionOutParams outParams +) +{vec3 ambientOcclusionColor=vec3(1.,1.,1.); +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=ambientOcclusionColorMap_*vAmbientInfos.y; +#ifdef AMBIENTINGRAYSCALE +ambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r); +#endif +ambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z); +#if DEBUGMODE>0 +outParams.ambientOcclusionColorMap=ambientOcclusionColorMap; +#endif +#endif +outParams.ambientOcclusionColor=ambientOcclusionColor;} +`;nw.v.IncludesShadersStore.pbrBlockAmbientOcclusion=d7;let d9=`#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +struct alphaFresnelOutParams +{float alpha;}; +#define pbr_inline +void alphaFresnelBlock( +in vec3 normalW, +in vec3 viewDirectionW, +in float alpha, +in float microSurface, +out alphaFresnelOutParams outParams +) +{float opacityPerceptual=alpha; +#ifdef LINEARALPHAFRESNEL +float opacity0=opacityPerceptual; +#else +float opacity0=opacityPerceptual*opacityPerceptual; +#endif +float opacity90=fresnelGrazingReflectance(opacity0);vec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);outParams.alpha=getReflectanceFromAnalyticalBRDFLookup_Jones(saturate(dot(viewDirectionW,normalForward)),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x; +#ifdef ALPHATEST +if (outParams.alpha0 && defined(ANISOTROPIC_TEXTURE) +vec3 anisotropyMapData; +#endif +}; +#define pbr_inline +void anisotropicBlock( +in vec3 vAnisotropy, +in float roughness, +#ifdef ANISOTROPIC_TEXTURE +in vec3 anisotropyMapData, +#endif +in mat3 TBN, +in vec3 normalW, +in vec3 viewDirectionW, +out anisotropicOutParams outParams +) +{float anisotropy=vAnisotropy.b;vec3 anisotropyDirection=vec3(vAnisotropy.xy,0.); +#ifdef ANISOTROPIC_TEXTURE +anisotropy*=anisotropyMapData.b; +#if DEBUGMODE>0 +outParams.anisotropyMapData=anisotropyMapData; +#endif +anisotropyMapData.rg=anisotropyMapData.rg*2.0-1.0; +#ifdef ANISOTROPIC_LEGACY +anisotropyDirection.rg*=anisotropyMapData.rg; +#else +anisotropyDirection.xy=mat2(anisotropyDirection.x,anisotropyDirection.y,-anisotropyDirection.y,anisotropyDirection.x)*normalize(anisotropyMapData.rg); +#endif +#endif +mat3 anisoTBN=mat3(normalize(TBN[0]),normalize(TBN[1]),normalize(TBN[2]));vec3 anisotropicTangent=normalize(anisoTBN*anisotropyDirection);vec3 anisotropicBitangent=normalize(cross(anisoTBN[2],anisotropicTangent));outParams.anisotropy=anisotropy;outParams.anisotropicTangent=anisotropicTangent;outParams.anisotropicBitangent=anisotropicBitangent;outParams.anisotropicNormal=getAnisotropicBentNormals(anisotropicTangent,anisotropicBitangent,normalW,viewDirectionW,anisotropy,roughness);} +#endif +`;nw.v.IncludesShadersStore.pbrBlockAnisotropic=pe;let pt=`#ifdef REFLECTION +struct reflectionOutParams +{vec4 environmentRadiance;vec3 environmentIrradiance; +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords; +#else +vec2 reflectionCoords; +#endif +#ifdef SS_TRANSLUCENCY +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +vec3 irradianceVector; +#endif +#endif +#endif +}; +#define pbr_inline +void createReflectionCoords( +in vec3 vPositionW, +in vec3 normalW, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REFLECTIONMAP_3D +out vec3 reflectionCoords +#else +out vec2 reflectionCoords +#endif +) +{ +#ifdef ANISOTROPIC +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),anisotropicOut.anisotropicNormal); +#else +vec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW); +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +reflectionCoords=reflectionVector; +#else +reflectionCoords=reflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +reflectionCoords/=reflectionVector.z; +#endif +reflectionCoords.y=1.0-reflectionCoords.y; +#endif +} +#define pbr_inline +#define inline +void sampleReflectionTexture( +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +const vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +const vec2 reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out vec4 environmentRadiance +) +{ +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped); +#elif defined(LINEARSPECULARREFLECTION) +float reflectionLOD=getLinearLodFromRoughness(vReflectionMicrosurfaceInfos.x,roughness); +#else +float reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG); +#endif +#ifdef LODBASEDMICROSFURACE +reflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z; +#ifdef LODINREFLECTIONALPHA +float automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);float requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD); +#else +float requestedReflectionLOD=reflectionLOD; +#endif +#ifdef REALTIME_FILTERING +environmentRadiance=vec4(radiance(alphaG,reflectionSampler,reflectionCoords,vReflectionFilteringInfo),1.0); +#else +environmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD); +#endif +#else +float lodReflectionNormalized=saturate(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x));float lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;vec4 environmentMid=sampleReflection(reflectionSampler,reflectionCoords);if (lodReflectionNormalizedDoubled<1.0){environmentRadiance=mix( +sampleReflection(reflectionSamplerHigh,reflectionCoords), +environmentMid, +lodReflectionNormalizedDoubled +);} else {environmentRadiance=mix( +environmentMid, +sampleReflection(reflectionSamplerLow,reflectionCoords), +lodReflectionNormalizedDoubled-1.0 +);} +#endif +#ifdef RGBDREFLECTION +environmentRadiance.rgb=fromRGBD(environmentRadiance); +#endif +#ifdef GAMMAREFLECTION +environmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb); +#endif +environmentRadiance.rgb*=vReflectionInfos.x;environmentRadiance.rgb*=vReflectionColor.rgb;} +#define pbr_inline +#define inline +void reflectionBlock( +in vec3 vPositionW, +in vec3 normalW, +in float alphaG, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +in float NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +in float roughness, +#endif +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +#else +in sampler2D reflectionSampler, +#endif +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +in vec3 vEnvironmentIrradiance, +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +in mat4 reflectionMatrix, +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +in samplerCube irradianceSampler, +#else +in sampler2D irradianceSampler, +#endif +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +out reflectionOutParams outParams +) +{vec4 environmentRadiance=vec4(0.,0.,0.,0.); +#ifdef REFLECTIONMAP_3D +vec3 reflectionCoords=vec3(0.); +#else +vec2 reflectionCoords=vec2(0.); +#endif +createReflectionCoords( +vPositionW, +normalW, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +reflectionCoords +);sampleReflectionTexture( +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +#ifdef REFLECTIONMAP_3D +reflectionSampler, +reflectionCoords, +#else +reflectionSampler, +reflectionCoords, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentRadiance +);vec3 environmentIrradiance=vec3(0.,0.,0.); +#ifdef USESPHERICALFROMREFLECTIONMAP +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +environmentIrradiance=vEnvironmentIrradiance; +#else +#ifdef ANISOTROPIC +vec3 irradianceVector=vec3(reflectionMatrix*vec4(anisotropicOut.anisotropicNormal,0)).xyz; +#else +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#endif +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#if defined(REALTIME_FILTERING) +environmentIrradiance=irradiance(reflectionSampler,irradianceVector,vReflectionFilteringInfo); +#else +environmentIrradiance=computeEnvironmentIrradiance(irradianceVector); +#endif +#ifdef SS_TRANSLUCENCY +outParams.irradianceVector=irradianceVector; +#endif +#endif +#elif defined(USEIRRADIANCEMAP) +vec4 environmentIrradiance4=sampleReflection(irradianceSampler,reflectionCoords);environmentIrradiance=environmentIrradiance4.rgb; +#ifdef RGBDREFLECTION +environmentIrradiance.rgb=fromRGBD(environmentIrradiance4); +#endif +#ifdef GAMMAREFLECTION +environmentIrradiance.rgb=toLinearSpace(environmentIrradiance.rgb); +#endif +#endif +environmentIrradiance*=vReflectionColor.rgb;outParams.environmentRadiance=environmentRadiance;outParams.environmentIrradiance=environmentIrradiance;outParams.reflectionCoords=reflectionCoords;} +#endif +`;nw.v.IncludesShadersStore.pbrBlockReflection=pt;let pi=`#ifdef SHEEN +struct sheenOutParams +{float sheenIntensity;vec3 sheenColor;float sheenRoughness; +#ifdef SHEEN_LINKWITHALBEDO +vec3 surfaceAlbedo; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +float sheenAlbedoScaling; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 finalSheenRadianceScaled; +#endif +#if DEBUGMODE>0 +#ifdef SHEEN_TEXTURE +vec4 sheenMapData; +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +vec3 sheenEnvironmentReflectance; +#endif +#endif +}; +#define pbr_inline +#define inline +void sheenBlock( +in vec4 vSheenColor, +#ifdef SHEEN_ROUGHNESS +in float vSheenRoughness, +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +in vec4 sheenMapRoughnessData, +#endif +#endif +in float roughness, +#ifdef SHEEN_TEXTURE +in vec4 sheenMapData, +in float sheenMapLevel, +#endif +in float reflectance, +#ifdef SHEEN_LINKWITHALBEDO +in vec3 baseColor, +in vec3 surfaceAlbedo, +#endif +#ifdef ENVIRONMENTBRDF +in float NdotV, +in vec3 environmentBrdf, +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +in vec2 AARoughnessFactors, +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +in vec4 vLightingIntensity, +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +in vec3 reflectionCoords, +#else +in sampler2D reflectionSampler, +in vec2 reflectionCoords, +#endif +in float NdotVUnclamped, +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +in float seo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +in float eho, +#endif +#endif +out sheenOutParams outParams +) +{float sheenIntensity=vSheenColor.a; +#ifdef SHEEN_TEXTURE +#if DEBUGMODE>0 +outParams.sheenMapData=sheenMapData; +#endif +#endif +#ifdef SHEEN_LINKWITHALBEDO +float sheenFactor=pow5(1.0-sheenIntensity);vec3 sheenColor=baseColor.rgb*(1.0-sheenFactor);float sheenRoughness=sheenIntensity;outParams.surfaceAlbedo=surfaceAlbedo*sheenFactor; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#else +vec3 sheenColor=vSheenColor.rgb; +#ifdef SHEEN_TEXTURE +#ifdef SHEEN_GAMMATEXTURE +sheenColor.rgb*=toLinearSpace(sheenMapData.rgb); +#else +sheenColor.rgb*=sheenMapData.rgb; +#endif +sheenColor.rgb*=sheenMapLevel; +#endif +#ifdef SHEEN_ROUGHNESS +float sheenRoughness=vSheenRoughness; +#ifdef SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE +#if defined(SHEEN_TEXTURE) +sheenRoughness*=sheenMapData.a; +#endif +#elif defined(SHEEN_TEXTURE_ROUGHNESS) +#ifdef SHEEN_TEXTURE_ROUGHNESS_IDENTICAL +sheenRoughness*=sheenMapData.a; +#else +sheenRoughness*=sheenMapRoughnessData.a; +#endif +#endif +#else +float sheenRoughness=roughness; +#ifdef SHEEN_TEXTURE +sheenIntensity*=sheenMapData.a; +#endif +#endif +#if !defined(SHEEN_ALBEDOSCALING) +sheenIntensity*=(1.-reflectance); +#endif +sheenColor*=sheenIntensity; +#endif +#ifdef ENVIRONMENTBRDF +/*#ifdef SHEEN_SOFTER +vec3 environmentSheenBrdf=vec3(0.,0.,getBRDFLookupCharlieSheen(NdotV,sheenRoughness)); +#else*/ +#ifdef SHEEN_ROUGHNESS +vec3 environmentSheenBrdf=getBRDFLookup(NdotV,sheenRoughness); +#else +vec3 environmentSheenBrdf=environmentBrdf; +#endif +/*#endif*/ +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +float sheenAlphaG=convertRoughnessToAverageSlope(sheenRoughness); +#ifdef SPECULARAA +sheenAlphaG+=AARoughnessFactors.y; +#endif +vec4 environmentSheenRadiance=vec4(0.,0.,0.,0.);sampleReflectionTexture( +sheenAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +sheenRoughness, +#endif +reflectionSampler, +reflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentSheenRadiance +);vec3 sheenEnvironmentReflectance=getSheenReflectanceFromBRDFLookup(sheenColor,environmentSheenBrdf); +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +sheenEnvironmentReflectance*=seo; +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +sheenEnvironmentReflectance*=eho; +#endif +#if DEBUGMODE>0 +outParams.sheenEnvironmentReflectance=sheenEnvironmentReflectance; +#endif +outParams.finalSheenRadianceScaled= +environmentSheenRadiance.rgb * +sheenEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +outParams.sheenAlbedoScaling=1.0-sheenIntensity*max(max(sheenColor.r,sheenColor.g),sheenColor.b)*environmentSheenBrdf.b; +#endif +outParams.sheenIntensity=sheenIntensity;outParams.sheenColor=sheenColor;outParams.sheenRoughness=sheenRoughness;} +#endif +`;nw.v.IncludesShadersStore.pbrBlockSheen=pi;let pr=`struct clearcoatOutParams +{vec3 specularEnvironmentR0;float conservationFactor;vec3 clearCoatNormalW;vec2 clearCoatAARoughnessFactors;float clearCoatIntensity;float clearCoatRoughness; +#ifdef REFLECTION +vec3 finalClearCoatRadianceScaled; +#endif +#ifdef CLEARCOAT_TINT +vec3 absorption;float clearCoatNdotVRefract;vec3 clearCoatColor;float clearCoatThickness; +#endif +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +vec3 energyConservationFactorClearCoat; +#endif +#if DEBUGMODE>0 +#ifdef CLEARCOAT_BUMP +mat3 TBNClearCoat; +#endif +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData; +#endif +#ifdef REFLECTION +vec4 environmentClearCoatRadiance;vec3 clearCoatEnvironmentReflectance; +#endif +float clearCoatNdotV; +#endif +}; +#ifdef CLEARCOAT +#define pbr_inline +#define inline +void clearcoatBlock( +in vec3 vPositionW, +in vec3 geometricNormalW, +in vec3 viewDirectionW, +in vec2 vClearCoatParams, +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +in vec4 clearCoatMapRoughnessData, +#endif +in vec3 specularEnvironmentR0, +#ifdef CLEARCOAT_TEXTURE +in vec2 clearCoatMapData, +#endif +#ifdef CLEARCOAT_TINT +in vec4 vClearCoatTintParams, +in float clearCoatColorAtDistance, +in vec4 vClearCoatRefractionParams, +#ifdef CLEARCOAT_TINT_TEXTURE +in vec4 clearCoatTintMapData, +#endif +#endif +#ifdef CLEARCOAT_BUMP +in vec2 vClearCoatBumpInfos, +in vec4 clearCoatBumpMapData, +in vec2 vClearCoatBumpUV, +#if defined(TANGENT) && defined(NORMAL) +in mat3 vTBN, +#else +in vec2 vClearCoatTangentSpaceParams, +#endif +#ifdef OBJECTSPACE_NORMALMAP +in mat4 normalMatrix, +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +in vec3 faceNormal, +#endif +#ifdef REFLECTION +in vec3 vReflectionMicrosurfaceInfos, +in vec2 vReflectionInfos, +in vec3 vReflectionColor, +in vec4 vLightingIntensity, +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSampler, +#else +in sampler2D reflectionSampler, +#endif +#ifndef LODBASEDMICROSFURACE +#ifdef REFLECTIONMAP_3D +in samplerCube reflectionSamplerLow, +in samplerCube reflectionSamplerHigh, +#else +in sampler2D reflectionSamplerLow, +in sampler2D reflectionSamplerHigh, +#endif +#endif +#ifdef REALTIME_FILTERING +in vec2 vReflectionFilteringInfo, +#endif +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +in float ambientMonochrome, +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +in float frontFacingMultiplier, +#endif +out clearcoatOutParams outParams +) +{float clearCoatIntensity=vClearCoatParams.x;float clearCoatRoughness=vClearCoatParams.y; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#ifdef CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE +clearCoatRoughness*=clearCoatMapData.y; +#endif +#if DEBUGMODE>0 +outParams.clearCoatMapData=clearCoatMapData; +#endif +#endif +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL +clearCoatRoughness*=clearCoatMapData.y; +#else +clearCoatRoughness*=clearCoatMapRoughnessData.y; +#endif +#endif +outParams.clearCoatIntensity=clearCoatIntensity;outParams.clearCoatRoughness=clearCoatRoughness; +#ifdef CLEARCOAT_TINT +vec3 clearCoatColor=vClearCoatTintParams.rgb;float clearCoatThickness=vClearCoatTintParams.a; +#ifdef CLEARCOAT_TINT_TEXTURE +#ifdef CLEARCOAT_TINT_GAMMATEXTURE +clearCoatColor*=toLinearSpace(clearCoatTintMapData.rgb); +#else +clearCoatColor*=clearCoatTintMapData.rgb; +#endif +clearCoatThickness*=clearCoatTintMapData.a; +#if DEBUGMODE>0 +outParams.clearCoatTintMapData=clearCoatTintMapData; +#endif +#endif +outParams.clearCoatColor=computeColorAtDistanceInMedia(clearCoatColor,clearCoatColorAtDistance);outParams.clearCoatThickness=clearCoatThickness; +#endif +#ifdef CLEARCOAT_REMAP_F0 +vec3 specularEnvironmentR0Updated=getR0RemappedForClearCoat(specularEnvironmentR0); +#else +vec3 specularEnvironmentR0Updated=specularEnvironmentR0; +#endif +outParams.specularEnvironmentR0=mix(specularEnvironmentR0,specularEnvironmentR0Updated,clearCoatIntensity);vec3 clearCoatNormalW=geometricNormalW; +#ifdef CLEARCOAT_BUMP +#ifdef NORMALXYSCALE +float clearCoatNormalScale=1.0; +#else +float clearCoatNormalScale=vClearCoatBumpInfos.y; +#endif +#if defined(TANGENT) && defined(NORMAL) +mat3 TBNClearCoat=vTBN; +#else +vec2 TBNClearCoatUV=vClearCoatBumpUV*frontFacingMultiplier;mat3 TBNClearCoat=cotangent_frame(clearCoatNormalW*clearCoatNormalScale,vPositionW,TBNClearCoatUV,vClearCoatTangentSpaceParams); +#endif +#if DEBUGMODE>0 +outParams.TBNClearCoat=TBNClearCoat; +#endif +#ifdef OBJECTSPACE_NORMALMAP +clearCoatNormalW=normalize(clearCoatBumpMapData.xyz *2.0-1.0);clearCoatNormalW=normalize(mat3(normalMatrix)*clearCoatNormalW); +#else +clearCoatNormalW=perturbNormal(TBNClearCoat,clearCoatBumpMapData.xyz,vClearCoatBumpInfos.y); +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +clearCoatNormalW*=sign(dot(clearCoatNormalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +clearCoatNormalW=clearCoatNormalW*frontFacingMultiplier; +#endif +outParams.clearCoatNormalW=clearCoatNormalW;outParams.clearCoatAARoughnessFactors=getAARoughnessFactors(clearCoatNormalW.xyz);float clearCoatNdotVUnclamped=dot(clearCoatNormalW,viewDirectionW);float clearCoatNdotV=absEps(clearCoatNdotVUnclamped); +#if DEBUGMODE>0 +outParams.clearCoatNdotV=clearCoatNdotV; +#endif +#ifdef CLEARCOAT_TINT +vec3 clearCoatVRefract=refract(-viewDirectionW,clearCoatNormalW,vClearCoatRefractionParams.y);outParams.clearCoatNdotVRefract=absEps(dot(clearCoatNormalW,clearCoatVRefract)); +#endif +#if defined(ENVIRONMENTBRDF) && (!defined(REFLECTIONMAP_SKYBOX) || defined(MS_BRDF_ENERGY_CONSERVATION)) +vec3 environmentClearCoatBrdf=getBRDFLookup(clearCoatNdotV,clearCoatRoughness); +#endif +#if defined(REFLECTION) +float clearCoatAlphaG=convertRoughnessToAverageSlope(clearCoatRoughness); +#ifdef SPECULARAA +clearCoatAlphaG+=outParams.clearCoatAARoughnessFactors.y; +#endif +vec4 environmentClearCoatRadiance=vec4(0.,0.,0.,0.);vec3 clearCoatReflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),clearCoatNormalW); +#ifdef REFLECTIONMAP_OPPOSITEZ +clearCoatReflectionVector.z*=-1.0; +#endif +#ifdef REFLECTIONMAP_3D +vec3 clearCoatReflectionCoords=clearCoatReflectionVector; +#else +vec2 clearCoatReflectionCoords=clearCoatReflectionVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +clearCoatReflectionCoords/=clearCoatReflectionVector.z; +#endif +clearCoatReflectionCoords.y=1.0-clearCoatReflectionCoords.y; +#endif +sampleReflectionTexture( +clearCoatAlphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +clearCoatNdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +clearCoatRoughness, +#endif +reflectionSampler, +clearCoatReflectionCoords, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +environmentClearCoatRadiance +); +#if DEBUGMODE>0 +outParams.environmentClearCoatRadiance=environmentClearCoatRadiance; +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 clearCoatEnvironmentReflectance=getReflectanceFromBRDFLookup(vec3(vClearCoatRefractionParams.x),environmentClearCoatBrdf); +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float clearCoatEho=environmentHorizonOcclusion(-viewDirectionW,clearCoatNormalW,geometricNormalW);clearCoatEnvironmentReflectance*=clearCoatEho; +#endif +#endif +#endif +#else +vec3 clearCoatEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(clearCoatNdotV,vec3(1.),vec3(1.),sqrt(1.-clearCoatRoughness)); +#endif +clearCoatEnvironmentReflectance*=clearCoatIntensity; +#if DEBUGMODE>0 +outParams.clearCoatEnvironmentReflectance=clearCoatEnvironmentReflectance; +#endif +outParams.finalClearCoatRadianceScaled= +environmentClearCoatRadiance.rgb * +clearCoatEnvironmentReflectance * +vLightingIntensity.z; +#endif +#if defined(CLEARCOAT_TINT) +outParams.absorption=computeClearCoatAbsorption(outParams.clearCoatNdotVRefract,outParams.clearCoatNdotVRefract,outParams.clearCoatColor,clearCoatThickness,clearCoatIntensity); +#endif +float fresnelIBLClearCoat=fresnelSchlickGGX(clearCoatNdotV,vClearCoatRefractionParams.x,CLEARCOATREFLECTANCE90);fresnelIBLClearCoat*=clearCoatIntensity;outParams.conservationFactor=(1.-fresnelIBLClearCoat); +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +outParams.energyConservationFactorClearCoat=getEnergyConservationFactor(outParams.specularEnvironmentR0,environmentClearCoatBrdf); +#endif +} +#endif +`;nw.v.IncludesShadersStore.pbrBlockClearcoat=pr;let ps=`struct iridescenceOutParams +{float iridescenceIntensity;float iridescenceIOR;float iridescenceThickness;vec3 specularEnvironmentR0;}; +#ifdef IRIDESCENCE +#define pbr_inline +#define inline +void iridescenceBlock( +in vec4 vIridescenceParams, +in float viewAngle, +in vec3 specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +in vec2 iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +in vec2 iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +in float NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +in vec2 clearCoatMapData, +#endif +#endif +out iridescenceOutParams outParams +) +{float iridescenceIntensity=vIridescenceParams.x;float iridescenceIOR=vIridescenceParams.y;float iridescenceThicknessMin=vIridescenceParams.z;float iridescenceThicknessMax=vIridescenceParams.w;float iridescenceThicknessWeight=1.; +#ifdef IRIDESCENCE_TEXTURE +iridescenceIntensity*=iridescenceMapData.x; +#ifdef IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE +iridescenceThicknessWeight=iridescenceMapData.g; +#endif +#endif +#if defined(IRIDESCENCE_THICKNESS_TEXTURE) +iridescenceThicknessWeight=iridescenceThicknessMapData.g; +#endif +float iridescenceThickness=mix(iridescenceThicknessMin,iridescenceThicknessMax,iridescenceThicknessWeight);float topIor=1.; +#ifdef CLEARCOAT +float clearCoatIntensity=vClearCoatParams.x; +#ifdef CLEARCOAT_TEXTURE +clearCoatIntensity*=clearCoatMapData.x; +#endif +topIor=mix(1.0,vClearCoatRefractionParams.w-1.,clearCoatIntensity);viewAngle=sqrt(1.0+square(1.0/topIor)*(square(NdotVUnclamped)-1.0)); +#endif +vec3 iridescenceFresnel=evalIridescence(topIor,iridescenceIOR,viewAngle,iridescenceThickness,specularEnvironmentR0);outParams.specularEnvironmentR0=mix(specularEnvironmentR0,iridescenceFresnel,iridescenceIntensity);outParams.iridescenceIntensity=iridescenceIntensity;outParams.iridescenceThickness=iridescenceThickness;outParams.iridescenceIOR=iridescenceIOR;} +#endif +`;nw.v.IncludesShadersStore.pbrBlockIridescence=ps;let pn=`struct subSurfaceOutParams +{vec3 specularEnvironmentReflectance; +#ifdef SS_REFRACTION +vec3 finalRefraction;vec3 surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +float alpha; +#endif +#ifdef REFLECTION +float refractionFactorForIrradiance; +#endif +#endif +#ifdef SS_TRANSLUCENCY +vec3 transmittance;float translucencyIntensity; +#ifdef REFLECTION +vec3 refractionIrradiance; +#endif +#endif +#if DEBUGMODE>0 +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction;vec3 refractionTransmittance; +#endif +#endif +}; +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +#define pbr_inline +#define inline +vec4 sampleEnvironmentRefraction( +in float ior +,in float thickness +,in float refractionLOD +,in vec3 normalW +,in vec3 vPositionW +,in vec3 viewDirectionW +,in mat4 view +,in vec4 vRefractionInfos +,in mat4 refractionMatrix +,in vec4 vRefractionMicrosurfaceInfos +,in float alphaG +#ifdef SS_REFRACTIONMAP_3D +,in samplerCube refractionSampler +#ifndef LODBASEDMICROSFURACE +,in samplerCube refractionSamplerLow +,in samplerCube refractionSamplerHigh +#endif +#else +,in sampler2D refractionSampler +#ifndef LODBASEDMICROSFURACE +,in sampler2D refractionSamplerLow +,in sampler2D refractionSamplerHigh +#endif +#endif +#ifdef ANISOTROPIC +,in anisotropicOutParams anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,in vec2 vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,in vec3 refractionPosition +,in vec3 refractionSize +#endif +) {vec4 environmentRefraction=vec4(0.,0.,0.,0.); +#ifdef ANISOTROPIC +vec3 refractionVector=refract(-viewDirectionW,anisotropicOut.anisotropicNormal,ior); +#else +vec3 refractionVector=refract(-viewDirectionW,normalW,ior); +#endif +#ifdef SS_REFRACTIONMAP_OPPOSITEZ +refractionVector.z*=-1.0; +#endif +#ifdef SS_REFRACTIONMAP_3D +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,refractionSize,refractionPosition); +#endif +refractionVector.y=refractionVector.y*vRefractionInfos.w;vec3 refractionCoords=refractionVector;refractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0)); +#else +#ifdef SS_USE_THICKNESS_AS_DEPTH +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*thickness,1.0))); +#else +vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0))); +#endif +vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y; +#endif +#ifdef LODBASEDMICROSFURACE +refractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z; +#ifdef SS_LODINREFRACTIONALPHA +float automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);float requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD); +#else +float requestedRefractionLOD=refractionLOD; +#endif +#if defined(REALTIME_FILTERING) && defined(SS_REFRACTIONMAP_3D) +environmentRefraction=vec4(radiance(alphaG,refractionSampler,refractionCoords,vRefractionFilteringInfo),1.0); +#else +environmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD); +#endif +#else +float lodRefractionNormalized=saturate(refractionLOD/log2(vRefractionMicrosurfaceInfos.x));float lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;vec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);if (lodRefractionNormalizedDoubled<1.0){environmentRefraction=mix( +sampleRefraction(refractionSamplerHigh,refractionCoords), +environmentRefractionMid, +lodRefractionNormalizedDoubled +);} else {environmentRefraction=mix( +environmentRefractionMid, +sampleRefraction(refractionSamplerLow,refractionCoords), +lodRefractionNormalizedDoubled-1.0 +);} +#endif +#ifdef SS_RGBDREFRACTION +environmentRefraction.rgb=fromRGBD(environmentRefraction); +#endif +#ifdef SS_GAMMAREFRACTION +environmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb); +#endif +return environmentRefraction;} +#endif +#define pbr_inline +#define inline +void subSurfaceBlock( +in vec3 vSubSurfaceIntensity, +in vec2 vThicknessParam, +in vec4 vTintColor, +in vec3 normalW, +in vec3 specularEnvironmentReflectance, +#ifdef SS_THICKNESSANDMASK_TEXTURE +in vec4 thicknessMap, +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +in vec4 refractionIntensityMap, +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +in vec4 translucencyIntensityMap, +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +in mat4 reflectionMatrix, +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +in vec3 irradianceVector_, +#endif +#if defined(REALTIME_FILTERING) +in samplerCube reflectionSampler, +in vec2 vReflectionFilteringInfo, +#endif +#endif +#ifdef USEIRRADIANCEMAP +#ifdef REFLECTIONMAP_3D +in samplerCube irradianceSampler, +#else +in sampler2D irradianceSampler, +#endif +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +in vec3 surfaceAlbedo, +#endif +#ifdef SS_REFRACTION +in vec3 vPositionW, +in vec3 viewDirectionW, +in mat4 view, +in vec4 vRefractionInfos, +in mat4 refractionMatrix, +in vec4 vRefractionMicrosurfaceInfos, +in vec4 vLightingIntensity, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +in float alpha, +#endif +#ifdef SS_LODINREFRACTIONALPHA +in float NdotVUnclamped, +#endif +#ifdef SS_LINEARSPECULARREFRACTION +in float roughness, +#endif +in float alphaG, +#ifdef SS_REFRACTIONMAP_3D +in samplerCube refractionSampler, +#ifndef LODBASEDMICROSFURACE +in samplerCube refractionSamplerLow, +in samplerCube refractionSamplerHigh, +#endif +#else +in sampler2D refractionSampler, +#ifndef LODBASEDMICROSFURACE +in sampler2D refractionSamplerLow, +in sampler2D refractionSamplerHigh, +#endif +#endif +#ifdef ANISOTROPIC +in anisotropicOutParams anisotropicOut, +#endif +#ifdef REALTIME_FILTERING +in vec2 vRefractionFilteringInfo, +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +in vec3 refractionPosition, +in vec3 refractionSize, +#endif +#ifdef SS_DISPERSION +in float dispersion, +#endif +#endif +#ifdef SS_TRANSLUCENCY +in vec3 vDiffusionDistance, +#endif +out subSurfaceOutParams outParams +) +{outParams.specularEnvironmentReflectance=specularEnvironmentReflectance; +#ifdef SS_REFRACTION +float refractionIntensity=vSubSurfaceIntensity.x; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +refractionIntensity*=(1.0-alpha);outParams.alpha=1.0; +#endif +#endif +#ifdef SS_TRANSLUCENCY +float translucencyIntensity=vSubSurfaceIntensity.y; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +#if defined(SS_USE_GLTF_TEXTURES) +float thickness=thicknessMap.g*vThicknessParam.y+vThicknessParam.x; +#else +float thickness=thicknessMap.r*vThicknessParam.y+vThicknessParam.x; +#endif +#if DEBUGMODE>0 +outParams.thicknessMap=thicknessMap; +#endif +#ifdef SS_MASK_FROM_THICKNESS_TEXTURE +#if defined(SS_REFRACTION) && defined(SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE) +#if defined(SS_USE_GLTF_TEXTURES) +refractionIntensity*=thicknessMap.r; +#else +refractionIntensity*=thicknessMap.g; +#endif +#endif +#if defined(SS_TRANSLUCENCY) && defined(SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE) +translucencyIntensity*=thicknessMap.b; +#endif +#endif +#else +float thickness=vThicknessParam.y; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +#ifdef SS_USE_GLTF_TEXTURES +refractionIntensity*=refractionIntensityMap.r; +#else +refractionIntensity*=refractionIntensityMap.g; +#endif +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +translucencyIntensity*=translucencyIntensityMap.b; +#endif +#ifdef SS_TRANSLUCENCY +thickness=maxEps(thickness);vec3 transmittance=transmittanceBRDF_Burley(vTintColor.rgb,vDiffusionDistance,thickness);transmittance*=translucencyIntensity;outParams.transmittance=transmittance;outParams.translucencyIntensity=translucencyIntensity; +#endif +#ifdef SS_REFRACTION +vec4 environmentRefraction=vec4(0.,0.,0.,0.); +#ifdef SS_HAS_THICKNESS +float ior=vRefractionInfos.y; +#else +float ior=vRefractionMicrosurfaceInfos.w; +#endif +#ifdef SS_LODINREFRACTIONALPHA +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG,NdotVUnclamped); +#elif defined(SS_LINEARSPECULARREFRACTION) +float refractionRoughness=alphaG;refractionRoughness=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLinearLodFromRoughness(vRefractionMicrosurfaceInfos.x,refractionRoughness); +#else +float refractionAlphaG=alphaG;refractionAlphaG=mix(alphaG,0.0,clamp(ior*3.0-2.0,0.0,1.0));float refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,refractionAlphaG); +#endif +float refraction_ior=vRefractionInfos.y; +#ifdef SS_DISPERSION +float realIOR=1.0/refraction_ior;float iorDispersionSpread=0.04*dispersion*(realIOR-1.0);vec3 iors=vec3(1.0/(realIOR-iorDispersionSpread),refraction_ior,1.0/(realIOR+iorDispersionSpread));for (int i=0; i<3; i++) {refraction_ior=iors[i]; +#endif +vec4 envSample=sampleEnvironmentRefraction(refraction_ior,thickness,refractionLOD,normalW,vPositionW,viewDirectionW,view,vRefractionInfos,refractionMatrix,vRefractionMicrosurfaceInfos,alphaG +#ifdef SS_REFRACTIONMAP_3D +,refractionSampler +#ifndef LODBASEDMICROSFURACE +,refractionSamplerLow +,refractionSamplerHigh +#endif +#else +,refractionSampler +#ifndef LODBASEDMICROSFURACE +,refractionSamplerLow +,refractionSamplerHigh +#endif +#endif +#ifdef ANISOTROPIC +,anisotropicOut +#endif +#ifdef REALTIME_FILTERING +,vRefractionFilteringInfo +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +,refractionPosition +,refractionSize +#endif +); +#ifdef SS_DISPERSION +environmentRefraction[i]=envSample[i];} +#else +environmentRefraction=envSample; +#endif +environmentRefraction.rgb*=vRefractionInfos.x; +#endif +#ifdef SS_REFRACTION +vec3 refractionTransmittance=vec3(refractionIntensity); +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,thickness); +#elif defined(SS_LINKREFRACTIONTOTRANSPARENCY) +float maxChannel=max(max(surfaceAlbedo.r,surfaceAlbedo.g),surfaceAlbedo.b);vec3 volumeAlbedo=saturate(maxChannel*surfaceAlbedo);environmentRefraction.rgb*=volumeAlbedo; +#else +vec3 volumeAlbedo=computeColorAtDistanceInMedia(vTintColor.rgb,vTintColor.w);refractionTransmittance*=cocaLambert(volumeAlbedo,vThicknessParam.y); +#endif +#ifdef SS_ALBEDOFORREFRACTIONTINT +environmentRefraction.rgb*=surfaceAlbedo.rgb; +#endif +outParams.surfaceAlbedo=surfaceAlbedo*(1.-refractionIntensity); +#ifdef REFLECTION +outParams.refractionFactorForIrradiance=(1.-refractionIntensity); +#endif +#ifdef UNUSED_MULTIPLEBOUNCES +vec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);outParams.specularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,refractionIntensity); +#endif +refractionTransmittance*=1.0-outParams.specularEnvironmentReflectance; +#if DEBUGMODE>0 +outParams.refractionTransmittance=refractionTransmittance; +#endif +outParams.finalRefraction=environmentRefraction.rgb*refractionTransmittance*vLightingIntensity.z; +#if DEBUGMODE>0 +outParams.environmentRefraction=environmentRefraction; +#endif +#endif +#if defined(REFLECTION) && defined(SS_TRANSLUCENCY) +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) || !defined(USESPHERICALFROMREFLECTIONMAP) +vec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +irradianceVector.z*=-1.0; +#endif +#ifdef INVERTCUBICMAP +irradianceVector.y*=-1.0; +#endif +#else +vec3 irradianceVector=irradianceVector_; +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) +#if defined(REALTIME_FILTERING) +vec3 refractionIrradiance=irradiance(reflectionSampler,-irradianceVector,vReflectionFilteringInfo); +#else +vec3 refractionIrradiance=computeEnvironmentIrradiance(-irradianceVector); +#endif +#elif defined(USEIRRADIANCEMAP) +#ifdef REFLECTIONMAP_3D +vec3 irradianceCoords=irradianceVector; +#else +vec2 irradianceCoords=irradianceVector.xy; +#ifdef REFLECTIONMAP_PROJECTION +irradianceCoords/=irradianceVector.z; +#endif +irradianceCoords.y=1.0-irradianceCoords.y; +#endif +vec4 refractionIrradiance=sampleReflection(irradianceSampler,-irradianceCoords); +#ifdef RGBDREFLECTION +refractionIrradiance.rgb=fromRGBD(refractionIrradiance); +#endif +#ifdef GAMMAREFLECTION +refractionIrradiance.rgb=toLinearSpace(refractionIrradiance.rgb); +#endif +#else +vec4 refractionIrradiance=vec4(0.); +#endif +refractionIrradiance.rgb*=transmittance; +#ifdef SS_ALBEDOFORTRANSLUCENCYTINT +refractionIrradiance.rgb*=surfaceAlbedo.rgb; +#endif +outParams.refractionIrradiance=refractionIrradiance.rgb; +#endif +} +#endif +`;nw.v.IncludesShadersStore.pbrBlockSubSurface=pn;let pa=`vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW); +#ifdef NORMAL +vec3 normalW=normalize(vNormalW); +#else +vec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#endif +vec3 geometricNormalW=normalW; +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +geometricNormalW=gl_FrontFacing ? geometricNormalW : -geometricNormalW; +#endif +`;nw.v.IncludesShadersStore.pbrBlockNormalGeometric=pa;let po=`#if defined(FORCENORMALFORWARD) && defined(NORMAL) +vec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w; +#if defined(TWOSIDEDLIGHTING) +faceNormal=gl_FrontFacing ? faceNormal : -faceNormal; +#endif +normalW*=sign(dot(normalW,faceNormal)); +#endif +#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) +normalW=gl_FrontFacing ? normalW : -normalW; +#endif +`;nw.v.IncludesShadersStore.pbrBlockNormalFinal=po;let pl=`#ifdef LIGHTMAP +vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); +#ifdef RGBDLIGHTMAP +lightmapColor.rgb=fromRGBD(lightmapColor); +#endif +#ifdef GAMMALIGHTMAP +lightmapColor.rgb=toLinearSpace(lightmapColor.rgb); +#endif +lightmapColor.rgb*=vLightmapInfos.y; +#endif +`;nw.v.IncludesShadersStore.pbrBlockLightmapInit=pl;let ph=`float NdotVUnclamped=dot(normalW,viewDirectionW);float NdotV=absEps(NdotVUnclamped);float alphaG=convertRoughnessToAverageSlope(roughness);vec2 AARoughnessFactors=getAARoughnessFactors(normalW.xyz); +#ifdef SPECULARAA +alphaG+=AARoughnessFactors.y; +#endif +#if defined(ENVIRONMENTBRDF) +vec3 environmentBrdf=getBRDFLookup(NdotV,roughness); +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +#ifdef AMBIENTINGRAYSCALE +float ambientMonochrome=aoOut.ambientOcclusionColor.r; +#else +float ambientMonochrome=getLuminance(aoOut.ambientOcclusionColor); +#endif +float seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped); +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +float eho=environmentHorizonOcclusion(-viewDirectionW,normalW,geometricNormalW); +#endif +#endif +#endif +#endif +`;nw.v.IncludesShadersStore.pbrBlockGeometryInfo=ph;let pu=`float reflectance=max(max(reflectivityOut.surfaceReflectivityColor.r,reflectivityOut.surfaceReflectivityColor.g),reflectivityOut.surfaceReflectivityColor.b);vec3 specularEnvironmentR0=reflectivityOut.surfaceReflectivityColor.rgb; +#ifdef METALLICWORKFLOW +vec3 specularEnvironmentR90=vec3(metallicReflectanceFactors.a); +#else +vec3 specularEnvironmentR90=vec3(1.0,1.0,1.0); +#endif +#ifdef ALPHAFRESNEL +float reflectance90=fresnelGrazingReflectance(reflectance);specularEnvironmentR90=specularEnvironmentR90*reflectance90; +#endif +`;nw.v.IncludesShadersStore.pbrBlockReflectance0=pu;let pc=`#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +vec3 specularEnvironmentReflectance=getReflectanceFromBRDFLookup(clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,environmentBrdf); +#ifdef RADIANCEOCCLUSION +specularEnvironmentReflectance*=seo; +#endif +#ifdef HORIZONOCCLUSION +#ifdef BUMP +#ifdef REFLECTIONMAP_3D +specularEnvironmentReflectance*=eho; +#endif +#endif +#endif +#else +vec3 specularEnvironmentReflectance=getReflectanceFromAnalyticalBRDFLookup_Jones(NdotV,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface)); +#endif +#ifdef CLEARCOAT +specularEnvironmentReflectance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +specularEnvironmentReflectance*=clearcoatOut.absorption; +#endif +#endif +`;nw.v.IncludesShadersStore.pbrBlockReflectance=pc;let pd=`vec3 diffuseBase=vec3(0.,0.,0.); +#ifdef SPECULARTERM +vec3 specularBase=vec3(0.,0.,0.); +#endif +#ifdef CLEARCOAT +vec3 clearCoatBase=vec3(0.,0.,0.); +#endif +#ifdef SHEEN +vec3 sheenBase=vec3(0.,0.,0.); +#endif +preLightingInfo preInfo;lightingInfo info;float shadow=1.; +float aggShadow=0.;float numLights=0.; +#if defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +vec3 absorption=vec3(0.); +#endif +`;nw.v.IncludesShadersStore.pbrBlockDirectLighting=pd;let pp=`aggShadow=aggShadow/numLights; +#if defined(ENVIRONMENTBRDF) +#ifdef MS_BRDF_ENERGY_CONSERVATION +vec3 energyConservationFactor=getEnergyConservationFactor(clearcoatOut.specularEnvironmentR0,environmentBrdf); +#endif +#endif +#ifndef METALLICWORKFLOW +#ifdef SPECULAR_GLOSSINESS_ENERGY_CONSERVATION +surfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb; +#endif +#endif +#if defined(SHEEN) && defined(SHEEN_ALBEDOSCALING) && defined(ENVIRONMENTBRDF) +surfaceAlbedo.rgb=sheenOut.sheenAlbedoScaling*surfaceAlbedo.rgb; +#endif +#ifdef REFLECTION +vec3 finalIrradiance=reflectionOut.environmentIrradiance; +#if defined(CLEARCOAT) +finalIrradiance*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +finalIrradiance*=clearcoatOut.absorption; +#endif +#endif +#if defined(SS_REFRACTION) +finalIrradiance*=subSurfaceOut.refractionFactorForIrradiance; +#endif +#if defined(SS_TRANSLUCENCY) +finalIrradiance*=(1.0-subSurfaceOut.translucencyIntensity);finalIrradiance+=subSurfaceOut.refractionIrradiance; +#endif +finalIrradiance*=surfaceAlbedo.rgb;finalIrradiance*=vLightingIntensity.z;finalIrradiance*=aoOut.ambientOcclusionColor; +#endif +#ifdef SPECULARTERM +vec3 finalSpecular=specularBase;finalSpecular=max(finalSpecular,0.0);vec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalSpecularScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalSpecularScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef REFLECTION +vec3 finalRadiance=reflectionOut.environmentRadiance.rgb;finalRadiance*=subSurfaceOut.specularEnvironmentReflectance;vec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalRadianceScaled*=energyConservationFactor; +#endif +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) && defined(SHEEN_ALBEDOSCALING) +finalRadianceScaled*=sheenOut.sheenAlbedoScaling; +#endif +#endif +#ifdef SHEEN +vec3 finalSheen=sheenBase*sheenOut.sheenColor;finalSheen=max(finalSheen,0.0);vec3 finalSheenScaled=finalSheen*vLightingIntensity.x*vLightingIntensity.w; +#if defined(CLEARCOAT) && defined(REFLECTION) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.conservationFactor; +#if defined(CLEARCOAT_TINT) +sheenOut.finalSheenRadianceScaled*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef CLEARCOAT +vec3 finalClearCoat=clearCoatBase;finalClearCoat=max(finalClearCoat,0.0);vec3 finalClearCoatScaled=finalClearCoat*vLightingIntensity.x*vLightingIntensity.w; +#if defined(ENVIRONMENTBRDF) && defined(MS_BRDF_ENERGY_CONSERVATION) +finalClearCoatScaled*=clearcoatOut.energyConservationFactorClearCoat; +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction*=clearcoatOut.conservationFactor; +#ifdef CLEARCOAT_TINT +subSurfaceOut.finalRefraction*=clearcoatOut.absorption; +#endif +#endif +#endif +#ifdef ALPHABLEND +float luminanceOverAlpha=0.0; +#if defined(REFLECTION) && defined(RADIANCEOVERALPHA) +luminanceOverAlpha+=getLuminance(finalRadianceScaled); +#if defined(CLEARCOAT) +luminanceOverAlpha+=getLuminance(clearcoatOut.finalClearCoatRadianceScaled); +#endif +#endif +#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA) +luminanceOverAlpha+=getLuminance(finalSpecularScaled); +#endif +#if defined(CLEARCOAT) && defined(CLEARCOATOVERALPHA) +luminanceOverAlpha+=getLuminance(finalClearCoatScaled); +#endif +#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA) || defined(CLEARCOATOVERALPHA) +alpha=saturate(alpha+luminanceOverAlpha*luminanceOverAlpha); +#endif +#endif +`;nw.v.IncludesShadersStore.pbrBlockFinalLitComponents=pp;let p_=`vec3 finalDiffuse=diffuseBase;finalDiffuse*=surfaceAlbedo.rgb;finalDiffuse=max(finalDiffuse,0.0);finalDiffuse*=vLightingIntensity.x;vec3 finalAmbient=vAmbientColor;finalAmbient*=surfaceAlbedo.rgb;vec3 finalEmissive=vEmissiveColor; +#ifdef EMISSIVE +vec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb; +#ifdef GAMMAEMISSIVE +finalEmissive*=toLinearSpace(emissiveColorTex.rgb); +#else +finalEmissive*=emissiveColorTex.rgb; +#endif +finalEmissive*= vEmissiveInfos.y; +#endif +finalEmissive*=vLightingIntensity.y; +#ifdef AMBIENT +vec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),aoOut.ambientOcclusionColor,vAmbientInfos.w); +#else +vec3 ambientOcclusionForDirectDiffuse=aoOut.ambientOcclusionColor; +#endif +finalAmbient*=aoOut.ambientOcclusionColor;finalDiffuse*=ambientOcclusionForDirectDiffuse; +`;nw.v.IncludesShadersStore.pbrBlockFinalUnlitComponents=p_;let pf=`vec4 finalColor=vec4( +#ifndef UNLIT +#ifdef REFLECTION +finalIrradiance + +#endif +#ifdef SPECULARTERM +finalSpecularScaled + +#endif +#ifdef SHEEN +finalSheenScaled + +#endif +#ifdef CLEARCOAT +finalClearCoatScaled + +#endif +#ifdef REFLECTION +finalRadianceScaled + +#if defined(SHEEN) && defined(ENVIRONMENTBRDF) +sheenOut.finalSheenRadianceScaled + +#endif +#ifdef CLEARCOAT +clearcoatOut.finalClearCoatRadianceScaled + +#endif +#endif +#ifdef SS_REFRACTION +subSurfaceOut.finalRefraction + +#endif +#endif +finalAmbient + +finalDiffuse, +alpha); +#ifdef LIGHTMAP +#ifndef LIGHTMAPEXCLUDED +#ifdef USELIGHTMAPASSHADOWMAP +finalColor.rgb*=lightmapColor.rgb; +#else +finalColor.rgb+=lightmapColor.rgb; +#endif +#endif +#endif +finalColor.rgb+=finalEmissive; +#define CUSTOM_FRAGMENT_BEFORE_FOG +finalColor=max(finalColor,0.0); +`;nw.v.IncludesShadersStore.pbrBlockFinalColorComposition=pf;let pm=`#if defined(IMAGEPROCESSINGPOSTPROCESS) || defined(SS_SCATTERING) +#if !defined(SKIPFINALCOLORCLAMP) +finalColor.rgb=clamp(finalColor.rgb,0.,30.0); +#endif +#else +finalColor=applyImageProcessing(finalColor); +#endif +finalColor.a*=visibility; +#ifdef PREMULTIPLYALPHA +finalColor.rgb*=finalColor.a; +#endif +`;nw.v.IncludesShadersStore.pbrBlockImageProcessing=pm;let pg=`#if DEBUGMODE>0 +if (vClipSpacePosition.x/vClipSpacePosition.w>=vDebugMode.x) { +#if DEBUGMODE==1 +gl_FragColor.rgb=vPositionW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==2 && defined(NORMAL) +gl_FragColor.rgb=vNormalW.rgb; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==3 && defined(BUMP) || DEBUGMODE==3 && defined(PARALLAX) || DEBUGMODE==3 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==4 && defined(BUMP) || DEBUGMODE==4 && defined(PARALLAX) || DEBUGMODE==4 && defined(ANISOTROPIC) +gl_FragColor.rgb=TBN[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==5 +gl_FragColor.rgb=normalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==6 && defined(MAINUV1) +gl_FragColor.rgb=vec3(vMainUV1,0.0); +#elif DEBUGMODE==7 && defined(MAINUV2) +gl_FragColor.rgb=vec3(vMainUV2,0.0); +#elif DEBUGMODE==8 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[0]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==9 && defined(CLEARCOAT) && defined(CLEARCOAT_BUMP) +gl_FragColor.rgb=clearcoatOut.TBNClearCoat[1]; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==10 && defined(CLEARCOAT) +gl_FragColor.rgb=clearcoatOut.clearCoatNormalW; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==11 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicNormal; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==12 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicTangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==13 && defined(ANISOTROPIC) +gl_FragColor.rgb=anisotropicOut.anisotropicBitangent; +#define DEBUGMODE_NORMALIZE +#elif DEBUGMODE==20 && defined(ALBEDO) +gl_FragColor.rgb=albedoTexture.rgb; +#ifndef GAMMAALBEDO +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==21 && defined(AMBIENT) +gl_FragColor.rgb=aoOut.ambientOcclusionColorMap.rgb; +#elif DEBUGMODE==22 && defined(OPACITY) +gl_FragColor.rgb=opacityMap.rgb; +#elif DEBUGMODE==23 && defined(EMISSIVE) +gl_FragColor.rgb=emissiveColorTex.rgb; +#ifndef GAMMAEMISSIVE +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==24 && defined(LIGHTMAP) +gl_FragColor.rgb=lightmapColor.rgb; +#ifndef GAMMALIGHTMAP +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==25 && defined(REFLECTIVITY) && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceMetallicColorMap.rgb; +#elif DEBUGMODE==26 && defined(REFLECTIVITY) && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.surfaceReflectivityColorMap.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==27 && defined(CLEARCOAT) && defined(CLEARCOAT_TEXTURE) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatMapData.rg,0.0); +#elif DEBUGMODE==28 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +gl_FragColor.rgb=clearcoatOut.clearCoatTintMapData.rgb; +#elif DEBUGMODE==29 && defined(SHEEN) && defined(SHEEN_TEXTURE) +gl_FragColor.rgb=sheenOut.sheenMapData.rgb; +#elif DEBUGMODE==30 && defined(ANISOTROPIC) && defined(ANISOTROPIC_TEXTURE) +gl_FragColor.rgb=anisotropicOut.anisotropyMapData.rgb; +#elif DEBUGMODE==31 && defined(SUBSURFACE) && defined(SS_THICKNESSANDMASK_TEXTURE) +gl_FragColor.rgb=subSurfaceOut.thicknessMap.rgb; +#elif DEBUGMODE==32 && defined(BUMP) +gl_FragColor.rgb=texture2D(bumpSampler,vBumpUV).rgb; +#elif DEBUGMODE==40 && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.environmentRefraction.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==41 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentRadiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==42 && defined(CLEARCOAT) && defined(REFLECTION) +gl_FragColor.rgb=clearcoatOut.environmentClearCoatRadiance.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==50 +gl_FragColor.rgb=diffuseBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==51 && defined(SPECULARTERM) +gl_FragColor.rgb=specularBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==52 && defined(CLEARCOAT) +gl_FragColor.rgb=clearCoatBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==53 && defined(SHEEN) +gl_FragColor.rgb=sheenBase.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==54 && defined(REFLECTION) +gl_FragColor.rgb=reflectionOut.environmentIrradiance.rgb; +#ifndef GAMMAREFLECTION +#define DEBUGMODE_GAMMA +#endif +#elif DEBUGMODE==60 +gl_FragColor.rgb=surfaceAlbedo.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==61 +gl_FragColor.rgb=clearcoatOut.specularEnvironmentR0; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==62 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=vec3(reflectivityOut.metallicRoughness.r); +#elif DEBUGMODE==71 && defined(METALLICWORKFLOW) +gl_FragColor.rgb=reflectivityOut.metallicF0; +#elif DEBUGMODE==63 +gl_FragColor.rgb=vec3(roughness); +#elif DEBUGMODE==64 +gl_FragColor.rgb=vec3(alphaG); +#elif DEBUGMODE==65 +gl_FragColor.rgb=vec3(NdotV); +#elif DEBUGMODE==66 && defined(CLEARCOAT) && defined(CLEARCOAT_TINT) +gl_FragColor.rgb=clearcoatOut.clearCoatColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==67 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatRoughness); +#elif DEBUGMODE==68 && defined(CLEARCOAT) +gl_FragColor.rgb=vec3(clearcoatOut.clearCoatNdotV); +#elif DEBUGMODE==69 && defined(SUBSURFACE) && defined(SS_TRANSLUCENCY) +gl_FragColor.rgb=subSurfaceOut.transmittance; +#elif DEBUGMODE==70 && defined(SUBSURFACE) && defined(SS_REFRACTION) +gl_FragColor.rgb=subSurfaceOut.refractionTransmittance; +#elif DEBUGMODE==72 +gl_FragColor.rgb=vec3(microSurface); +#elif DEBUGMODE==73 +gl_FragColor.rgb=vAlbedoColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==74 && !defined(METALLICWORKFLOW) +gl_FragColor.rgb=vReflectivityColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==75 +gl_FragColor.rgb=vEmissiveColor.rgb; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==80 && defined(RADIANCEOCCLUSION) +gl_FragColor.rgb=vec3(seo); +#elif DEBUGMODE==81 && defined(HORIZONOCCLUSION) +gl_FragColor.rgb=vec3(eho); +#elif DEBUGMODE==82 && defined(MS_BRDF_ENERGY_CONSERVATION) +gl_FragColor.rgb=vec3(energyConservationFactor); +#elif DEBUGMODE==83 && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=specularEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==84 && defined(CLEARCOAT) && defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +gl_FragColor.rgb=clearcoatOut.clearCoatEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==85 && defined(SHEEN) && defined(REFLECTION) +gl_FragColor.rgb=sheenOut.sheenEnvironmentReflectance; +#define DEBUGMODE_GAMMA +#elif DEBUGMODE==86 && defined(ALPHABLEND) +gl_FragColor.rgb=vec3(luminanceOverAlpha); +#elif DEBUGMODE==87 +gl_FragColor.rgb=vec3(alpha); +#elif DEBUGMODE==88 && defined(ALBEDO) +gl_FragColor.rgb=vec3(albedoTexture.a); +#else +float stripeWidth=30.;float stripePos=floor((gl_FragCoord.x+gl_FragCoord.y)/stripeWidth);float whichColor=mod(stripePos,2.);vec3 color1=vec3(.6,.2,.2);vec3 color2=vec3(.3,.1,.1);gl_FragColor.rgb=mix(color1,color2,whichColor); +#endif +gl_FragColor.rgb*=vDebugMode.y; +#ifdef DEBUGMODE_NORMALIZE +gl_FragColor.rgb=normalize(gl_FragColor.rgb)*0.5+0.5; +#endif +#ifdef DEBUGMODE_GAMMA +gl_FragColor.rgb=toGammaSpace(gl_FragColor.rgb); +#endif +gl_FragColor.a=1.0; +#ifdef PREPASS +gl_FragData[0]=toLinearSpace(gl_FragColor); +gl_FragData[1]=vec4(0.,0.,0.,0.); +#endif +#ifdef DEBUGMODE_FORCERETURN +return; +#endif +} +#endif +`;nw.v.IncludesShadersStore.pbrDebug=pg;let pv=`#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) +#extension GL_OES_standard_derivatives : enable +#endif +#ifdef LODBASEDMICROSFURACE +#extension GL_EXT_shader_texture_lod : enable +#endif +#define CUSTOM_FRAGMENT_BEGIN +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include[SCENE_MRT_COUNT] +precision highp float; +#include +#ifndef FROMLINEARSPACE +#define FROMLINEARSPACE +#endif +#include<__decl__pbrFragment> +#include +#include<__decl__lightFragment>[0..maxSimultaneousLights] +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef REFLECTION +#include +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#include +#include +#include +albedoOpacityOutParams albedoOpacityOut; +#ifdef ALBEDO +vec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset); +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); +#endif +#ifdef DECAL +vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); +#endif +albedoOpacityBlock( +vAlbedoColor, +#ifdef ALBEDO +albedoTexture, +vAlbedoInfos, +#endif +#ifdef OPACITY +opacityMap, +vOpacityInfos, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +#ifdef DECAL +decalColor, +vDecalInfos, +#endif +albedoOpacityOut +);vec3 surfaceAlbedo=albedoOpacityOut.surfaceAlbedo;float alpha=albedoOpacityOut.alpha; +#define CUSTOM_FRAGMENT_UPDATE_ALPHA +#include +#define CUSTOM_FRAGMENT_BEFORE_LIGHTS +ambientOcclusionOutParams aoOut; +#ifdef AMBIENT +vec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb; +#endif +ambientOcclusionBlock( +#ifdef AMBIENT +ambientOcclusionColorMap, +vAmbientInfos, +#endif +aoOut +); +#include +#ifdef UNLIT +vec3 diffuseBase=vec3(1.,1.,1.); +#else +vec3 baseColor=surfaceAlbedo;reflectivityOutParams reflectivityOut; +#if defined(REFLECTIVITY) +vec4 surfaceMetallicOrReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);vec4 baseReflectivity=surfaceMetallicOrReflectivityColorMap; +#ifndef METALLICWORKFLOW +#ifdef REFLECTIVITY_GAMMA +surfaceMetallicOrReflectivityColorMap=toLinearSpace(surfaceMetallicOrReflectivityColorMap); +#endif +surfaceMetallicOrReflectivityColorMap.rgb*=vReflectivityInfos.y; +#endif +#endif +#if defined(MICROSURFACEMAP) +vec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y; +#endif +#ifdef METALLICWORKFLOW +vec4 metallicReflectanceFactors=vMetallicReflectanceFactors; +#ifdef REFLECTANCE +vec4 reflectanceFactorsMap=texture2D(reflectanceSampler,vReflectanceUV+uvOffset); +#ifdef REFLECTANCE_GAMMA +reflectanceFactorsMap=toLinearSpace(reflectanceFactorsMap); +#endif +metallicReflectanceFactors.rgb*=reflectanceFactorsMap.rgb; +#endif +#ifdef METALLIC_REFLECTANCE +vec4 metallicReflectanceFactorsMap=texture2D(metallicReflectanceSampler,vMetallicReflectanceUV+uvOffset); +#ifdef METALLIC_REFLECTANCE_GAMMA +metallicReflectanceFactorsMap=toLinearSpace(metallicReflectanceFactorsMap); +#endif +#ifndef METALLIC_REFLECTANCE_USE_ALPHA_ONLY +metallicReflectanceFactors.rgb*=metallicReflectanceFactorsMap.rgb; +#endif +metallicReflectanceFactors*=metallicReflectanceFactorsMap.a; +#endif +#endif +reflectivityBlock( +vReflectivityColor, +#ifdef METALLICWORKFLOW +surfaceAlbedo, +metallicReflectanceFactors, +#endif +#ifdef REFLECTIVITY +vReflectivityInfos, +surfaceMetallicOrReflectivityColorMap, +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor, +#endif +#ifdef MICROSURFACEMAP +microSurfaceTexel, +#endif +#ifdef DETAIL +detailColor, +vDetailInfos, +#endif +reflectivityOut +);float microSurface=reflectivityOut.microSurface;float roughness=reflectivityOut.roughness; +#ifdef METALLICWORKFLOW +surfaceAlbedo=reflectivityOut.surfaceAlbedo; +#endif +#if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) +aoOut.ambientOcclusionColor=reflectivityOut.ambientOcclusionColor; +#endif +#ifdef ALPHAFRESNEL +#if defined(ALPHATEST) || defined(ALPHABLEND) +alphaFresnelOutParams alphaFresnelOut;alphaFresnelBlock( +normalW, +viewDirectionW, +alpha, +microSurface, +alphaFresnelOut +);alpha=alphaFresnelOut.alpha; +#endif +#endif +#include +#ifdef ANISOTROPIC +anisotropicOutParams anisotropicOut; +#ifdef ANISOTROPIC_TEXTURE +vec3 anisotropyMapData=texture2D(anisotropySampler,vAnisotropyUV+uvOffset).rgb*vAnisotropyInfos.y; +#endif +anisotropicBlock( +vAnisotropy, +roughness, +#ifdef ANISOTROPIC_TEXTURE +anisotropyMapData, +#endif +TBN, +normalW, +viewDirectionW, +anisotropicOut +); +#endif +#ifdef REFLECTION +reflectionOutParams reflectionOut; +#ifndef USE_CUSTOM_REFLECTION +reflectionBlock( +vPositionW, +normalW, +alphaG, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +#ifdef ANISOTROPIC +anisotropicOut, +#endif +#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX) +NdotVUnclamped, +#endif +#ifdef LINEARSPECULARREFLECTION +roughness, +#endif +reflectionSampler, +#if defined(NORMAL) && defined(USESPHERICALINVERTEX) +vEnvironmentIrradiance, +#endif +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +reflectionMatrix, +#endif +#endif +#ifdef USEIRRADIANCEMAP +irradianceSampler, +#endif +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +reflectionOut +); +#else +#define CUSTOM_REFLECTION +#endif +#endif +#include +#ifdef SHEEN +sheenOutParams sheenOut; +#ifdef SHEEN_TEXTURE +vec4 sheenMapData=texture2D(sheenSampler,vSheenUV+uvOffset); +#endif +#if defined(SHEEN_ROUGHNESS) && defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 sheenMapRoughnessData=texture2D(sheenRoughnessSampler,vSheenRoughnessUV+uvOffset)*vSheenInfos.w; +#endif +sheenBlock( +vSheenColor, +#ifdef SHEEN_ROUGHNESS +vSheenRoughness, +#if defined(SHEEN_TEXTURE_ROUGHNESS) && !defined(SHEEN_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE) +sheenMapRoughnessData, +#endif +#endif +roughness, +#ifdef SHEEN_TEXTURE +sheenMapData, +vSheenInfos.y, +#endif +reflectance, +#ifdef SHEEN_LINKWITHALBEDO +baseColor, +surfaceAlbedo, +#endif +#ifdef ENVIRONMENTBRDF +NdotV, +environmentBrdf, +#endif +#if defined(REFLECTION) && defined(ENVIRONMENTBRDF) +AARoughnessFactors, +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +vLightingIntensity, +reflectionSampler, +reflectionOut.reflectionCoords, +NdotVUnclamped, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(RADIANCEOCCLUSION) +seo, +#endif +#if !defined(REFLECTIONMAP_SKYBOX) && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(REFLECTIONMAP_3D) +eho, +#endif +#endif +sheenOut +); +#ifdef SHEEN_LINKWITHALBEDO +surfaceAlbedo=sheenOut.surfaceAlbedo; +#endif +#endif +#ifdef CLEARCOAT +#ifdef CLEARCOAT_TEXTURE +vec2 clearCoatMapData=texture2D(clearCoatSampler,vClearCoatUV+uvOffset).rg*vClearCoatInfos.y; +#endif +#endif +#ifdef IRIDESCENCE +iridescenceOutParams iridescenceOut; +#ifdef IRIDESCENCE_TEXTURE +vec2 iridescenceMapData=texture2D(iridescenceSampler,vIridescenceUV+uvOffset).rg*vIridescenceInfos.y; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +vec2 iridescenceThicknessMapData=texture2D(iridescenceThicknessSampler,vIridescenceThicknessUV+uvOffset).rg*vIridescenceInfos.w; +#endif +iridescenceBlock( +vIridescenceParams, +NdotV, +specularEnvironmentR0, +#ifdef IRIDESCENCE_TEXTURE +iridescenceMapData, +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +iridescenceThicknessMapData, +#endif +#ifdef CLEARCOAT +NdotVUnclamped, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#endif +iridescenceOut +);float iridescenceIntensity=iridescenceOut.iridescenceIntensity;specularEnvironmentR0=iridescenceOut.specularEnvironmentR0; +#endif +clearcoatOutParams clearcoatOut; +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +vec4 clearCoatMapRoughnessData=texture2D(clearCoatRoughnessSampler,vClearCoatRoughnessUV+uvOffset)*vClearCoatInfos.w; +#endif +#if defined(CLEARCOAT_TINT) && defined(CLEARCOAT_TINT_TEXTURE) +vec4 clearCoatTintMapData=texture2D(clearCoatTintSampler,vClearCoatTintUV+uvOffset); +#endif +#ifdef CLEARCOAT_BUMP +vec4 clearCoatBumpMapData=texture2D(clearCoatBumpSampler,vClearCoatBumpUV+uvOffset); +#endif +clearcoatBlock( +vPositionW, +geometricNormalW, +viewDirectionW, +vClearCoatParams, +#if defined(CLEARCOAT_TEXTURE_ROUGHNESS) && !defined(CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL) && !defined(CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE) +clearCoatMapRoughnessData, +#endif +specularEnvironmentR0, +#ifdef CLEARCOAT_TEXTURE +clearCoatMapData, +#endif +#ifdef CLEARCOAT_TINT +vClearCoatTintParams, +clearCoatColorAtDistance, +vClearCoatRefractionParams, +#ifdef CLEARCOAT_TINT_TEXTURE +clearCoatTintMapData, +#endif +#endif +#ifdef CLEARCOAT_BUMP +vClearCoatBumpInfos, +clearCoatBumpMapData, +vClearCoatBumpUV, +#if defined(TANGENT) && defined(NORMAL) +vTBN, +#else +vClearCoatTangentSpaceParams, +#endif +#ifdef OBJECTSPACE_NORMALMAP +normalMatrix, +#endif +#endif +#if defined(FORCENORMALFORWARD) && defined(NORMAL) +faceNormal, +#endif +#ifdef REFLECTION +vReflectionMicrosurfaceInfos, +vReflectionInfos, +vReflectionColor, +vLightingIntensity, +reflectionSampler, +#ifndef LODBASEDMICROSFURACE +reflectionSamplerLow, +reflectionSamplerHigh, +#endif +#ifdef REALTIME_FILTERING +vReflectionFilteringInfo, +#endif +#endif +#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX) +#ifdef RADIANCEOCCLUSION +ambientMonochrome, +#endif +#endif +#if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) +(gl_FrontFacing ? 1. : -1.), +#endif +clearcoatOut +); +#else +clearcoatOut.specularEnvironmentR0=specularEnvironmentR0; +#endif +#include +subSurfaceOutParams subSurfaceOut; +#ifdef SUBSURFACE +#ifdef SS_THICKNESSANDMASK_TEXTURE +vec4 thicknessMap=texture2D(thicknessSampler,vThicknessUV+uvOffset); +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +vec4 refractionIntensityMap=texture2D(refractionIntensitySampler,vRefractionIntensityUV+uvOffset); +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +vec4 translucencyIntensityMap=texture2D(translucencyIntensitySampler,vTranslucencyIntensityUV+uvOffset); +#endif +subSurfaceBlock( +vSubSurfaceIntensity, +vThicknessParam, +vTintColor, +normalW, +specularEnvironmentReflectance, +#ifdef SS_THICKNESSANDMASK_TEXTURE +thicknessMap, +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +refractionIntensityMap, +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +translucencyIntensityMap, +#endif +#ifdef REFLECTION +#ifdef SS_TRANSLUCENCY +reflectionMatrix, +#ifdef USESPHERICALFROMREFLECTIONMAP +#if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) +reflectionOut.irradianceVector, +#endif +#if defined(REALTIME_FILTERING) +reflectionSampler, +vReflectionFilteringInfo, +#endif +#endif +#ifdef USEIRRADIANCEMAP +irradianceSampler, +#endif +#endif +#endif +#if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) +surfaceAlbedo, +#endif +#ifdef SS_REFRACTION +vPositionW, +viewDirectionW, +view, +vRefractionInfos, +refractionMatrix, +vRefractionMicrosurfaceInfos, +vLightingIntensity, +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha, +#endif +#ifdef SS_LODINREFRACTIONALPHA +NdotVUnclamped, +#endif +#ifdef SS_LINEARSPECULARREFRACTION +roughness, +#endif +alphaG, +refractionSampler, +#ifndef LODBASEDMICROSFURACE +refractionSamplerLow, +refractionSamplerHigh, +#endif +#ifdef ANISOTROPIC +anisotropicOut, +#endif +#ifdef REALTIME_FILTERING +vRefractionFilteringInfo, +#endif +#ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC +vRefractionPosition, +vRefractionSize, +#endif +#ifdef SS_DISPERSION +dispersion, +#endif +#endif +#ifdef SS_TRANSLUCENCY +vDiffusionDistance, +#endif +subSurfaceOut +); +#ifdef SS_REFRACTION +surfaceAlbedo=subSurfaceOut.surfaceAlbedo; +#ifdef SS_LINKREFRACTIONTOTRANSPARENCY +alpha=subSurfaceOut.alpha; +#endif +#endif +#else +subSurfaceOut.specularEnvironmentReflectance=specularEnvironmentReflectance; +#endif +#include +#include[0..maxSimultaneousLights] +#include +#endif +#include +#define CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION +#include +#include +#include(color,finalColor) +#include +#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR +#ifdef PREPASS +float writeGeometryInfo=finalColor.a>0.4 ? 1.0 : 0.0; +#ifdef PREPASS_POSITION +gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); +#endif +#ifdef PREPASS_VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_ALBEDO_SQRT +vec3 sqAlbedo=sqrt(surfaceAlbedo); +#endif +#ifdef PREPASS_IRRADIANCE +vec3 irradiance=finalDiffuse; +#ifndef UNLIT +#ifdef REFLECTION +irradiance+=finalIrradiance; +#endif +#endif +#ifdef SS_SCATTERING +gl_FragData[0]=vec4(finalColor.rgb-irradiance,finalColor.a); +irradiance/=sqAlbedo; +#else +gl_FragData[0]=finalColor; +float scatteringDiffusionProfile=255.; +#endif +gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(clamp(irradiance,vec3(0.),vec3(1.)),writeGeometryInfo*scatteringDiffusionProfile/255.); +#else +gl_FragData[0]=vec4(finalColor.rgb,finalColor.a); +#endif +#ifdef PREPASS_DEPTH +gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); +#endif +#ifdef PREPASS_NORMAL +#ifdef PREPASS_NORMAL_WORLDSPACE +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); +#else +gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); +#endif +#endif +#ifdef PREPASS_ALBEDO_SQRT +gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqAlbedo,writeGeometryInfo); +#endif +#ifdef PREPASS_REFLECTIVITY +#ifndef UNLIT +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(specularEnvironmentR0,microSurface)*writeGeometryInfo; +#else +gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4( 0.0,0.0,0.0,1.0 )*writeGeometryInfo; +#endif +#endif +#endif +#if !defined(PREPASS) || defined(WEBGL2) +gl_FragColor=finalColor; +#endif +#include +#if ORDER_INDEPENDENT_TRANSPARENCY +if (fragDepth==nearestDepth) {frontColor.rgb+=finalColor.rgb*finalColor.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-finalColor.a);} else {backColor+=finalColor;} +#endif +#include +#define CUSTOM_FRAGMENT_MAIN_END +} +`;nw.v.ShadersStore.pbrPixelShader=pv;let px=`uniform mat4 view;uniform mat4 viewProjection; +#ifdef ALBEDO +uniform mat4 albedoMatrix;uniform vec2 vAlbedoInfos; +#endif +#ifdef AMBIENT +uniform mat4 ambientMatrix;uniform vec4 vAmbientInfos; +#endif +#ifdef OPACITY +uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; +#endif +#ifdef EMISSIVE +uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; +#endif +#ifdef LIGHTMAP +uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; +#endif +#ifdef REFLECTIVITY +uniform vec3 vReflectivityInfos;uniform mat4 reflectivityMatrix; +#endif +#ifdef METALLIC_REFLECTANCE +uniform vec2 vMetallicReflectanceInfos;uniform mat4 metallicReflectanceMatrix; +#endif +#ifdef REFLECTANCE +uniform vec2 vReflectanceInfos;uniform mat4 reflectanceMatrix; +#endif +#ifdef MICROSURFACEMAP +uniform vec2 vMicroSurfaceSamplerInfos;uniform mat4 microSurfaceSamplerMatrix; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; +#endif +#ifdef POINTSIZE +uniform float pointSize; +#endif +#ifdef REFLECTION +uniform vec2 vReflectionInfos;uniform mat4 reflectionMatrix; +#endif +#ifdef CLEARCOAT +#if defined(CLEARCOAT_TEXTURE) || defined(CLEARCOAT_TEXTURE_ROUGHNESS) +uniform vec4 vClearCoatInfos; +#endif +#ifdef CLEARCOAT_TEXTURE +uniform mat4 clearCoatMatrix; +#endif +#ifdef CLEARCOAT_TEXTURE_ROUGHNESS +uniform mat4 clearCoatRoughnessMatrix; +#endif +#ifdef CLEARCOAT_BUMP +uniform vec2 vClearCoatBumpInfos;uniform mat4 clearCoatBumpMatrix; +#endif +#ifdef CLEARCOAT_TINT_TEXTURE +uniform vec2 vClearCoatTintInfos;uniform mat4 clearCoatTintMatrix; +#endif +#endif +#ifdef IRIDESCENCE +#if defined(IRIDESCENCE_TEXTURE) || defined(IRIDESCENCE_THICKNESS_TEXTURE) +uniform vec4 vIridescenceInfos; +#endif +#ifdef IRIDESCENCE_TEXTURE +uniform mat4 iridescenceMatrix; +#endif +#ifdef IRIDESCENCE_THICKNESS_TEXTURE +uniform mat4 iridescenceThicknessMatrix; +#endif +#endif +#ifdef ANISOTROPIC +#ifdef ANISOTROPIC_TEXTURE +uniform vec2 vAnisotropyInfos;uniform mat4 anisotropyMatrix; +#endif +#endif +#ifdef SHEEN +#if defined(SHEEN_TEXTURE) || defined(SHEEN_TEXTURE_ROUGHNESS) +uniform vec4 vSheenInfos; +#endif +#ifdef SHEEN_TEXTURE +uniform mat4 sheenMatrix; +#endif +#ifdef SHEEN_TEXTURE_ROUGHNESS +uniform mat4 sheenRoughnessMatrix; +#endif +#endif +#ifdef SUBSURFACE +#ifdef SS_REFRACTION +uniform vec4 vRefractionInfos;uniform mat4 refractionMatrix; +#endif +#ifdef SS_THICKNESSANDMASK_TEXTURE +uniform vec2 vThicknessInfos;uniform mat4 thicknessMatrix; +#endif +#ifdef SS_REFRACTIONINTENSITY_TEXTURE +uniform vec2 vRefractionIntensityInfos;uniform mat4 refractionIntensityMatrix; +#endif +#ifdef SS_TRANSLUCENCYINTENSITY_TEXTURE +uniform vec2 vTranslucencyIntensityInfos;uniform mat4 translucencyIntensityMatrix; +#endif +#endif +#ifdef NORMAL +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +#ifdef USESPHERICALFROMREFLECTIONMAP +#ifdef SPHERICAL_HARMONICS +uniform vec3 vSphericalL00;uniform vec3 vSphericalL1_1;uniform vec3 vSphericalL10;uniform vec3 vSphericalL11;uniform vec3 vSphericalL2_2;uniform vec3 vSphericalL2_1;uniform vec3 vSphericalL20;uniform vec3 vSphericalL21;uniform vec3 vSphericalL22; +#else +uniform vec3 vSphericalX;uniform vec3 vSphericalY;uniform vec3 vSphericalZ;uniform vec3 vSphericalXX_ZZ;uniform vec3 vSphericalYY_ZZ;uniform vec3 vSphericalZZ;uniform vec3 vSphericalXY;uniform vec3 vSphericalYZ;uniform vec3 vSphericalZX; +#endif +#endif +#endif +#endif +#ifdef DETAIL +uniform vec4 vDetailInfos;uniform mat4 detailMatrix; +#endif +#include +#define ADDITIONAL_VERTEX_DECLARATION +`;nw.v.IncludesShadersStore.pbrVertexDeclaration=px;let pT=`precision highp float; +#include<__decl__pbrVertex> +#define CUSTOM_VERTEX_BEGIN +attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#ifdef TANGENT +attribute vec4 tangent; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#include[2..7] +#include[1..7] +#ifdef VERTEXCOLOR +attribute vec4 color; +#endif +#include +#include +#include +#include +#include +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity) +#endif +varying vec3 vPositionW; +#if DEBUGMODE>0 +varying vec4 vClipSpacePosition; +#endif +#ifdef NORMAL +varying vec3 vNormalW; +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +varying vec3 vEnvironmentIrradiance; +#include +#endif +#endif +#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) +varying vec4 vColor; +#endif +#include +#include +#include +#include<__decl__lightVxFragment>[0..maxSimultaneousLights] +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +varying vec3 vPositionUVW; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +varying vec3 vDirectionW; +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#ifdef TANGENT +vec4 tangentUpdated=tangent; +#endif +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef REFLECTIONMAP_SKYBOX +vPositionUVW=positionUpdated; +#endif +#define CUSTOM_VERTEX_UPDATE_POSITION +#define CUSTOM_VERTEX_UPDATE_NORMAL +#include +#if defined(PREPASS) && defined(PREPASS_VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vPositionW=vec3(worldPos); +#include +#ifdef NORMAL +mat3 normalWorld=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normalWorld=transposeMat3(inverseMat3(normalWorld)); +#endif +vNormalW=normalize(normalWorld*normalUpdated); +#endif +#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) +vec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz; +#ifdef REFLECTIONMAP_OPPOSITEZ +reflectionVector.z*=-1.0; +#endif +vEnvironmentIrradiance=computeEnvironmentIrradiance(reflectionVector); +#endif +#endif +#define CUSTOM_VERTEX_UPDATE_WORLDPOS +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#if DEBUGMODE>0 +vClipSpacePosition=gl_Position; +#endif +#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) +vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); +#endif +#ifndef UV1 +vec2 uvUpdated=vec2(0.,0.); +#endif +#ifdef MAINUV1 +vMainUV1=uvUpdated; +#endif +#include[2..7] +#include(_DEFINENAME_,ALBEDO,_VARYINGNAME_,Albedo,_MATRIXNAME_,albedo,_INFONAME_,AlbedoInfos.x) +#include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) +#include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) +#include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) +#include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) +#include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) +#include(_DEFINENAME_,REFLECTIVITY,_VARYINGNAME_,Reflectivity,_MATRIXNAME_,reflectivity,_INFONAME_,ReflectivityInfos.x) +#include(_DEFINENAME_,MICROSURFACEMAP,_VARYINGNAME_,MicroSurfaceSampler,_MATRIXNAME_,microSurfaceSampler,_INFONAME_,MicroSurfaceSamplerInfos.x) +#include(_DEFINENAME_,METALLIC_REFLECTANCE,_VARYINGNAME_,MetallicReflectance,_MATRIXNAME_,metallicReflectance,_INFONAME_,MetallicReflectanceInfos.x) +#include(_DEFINENAME_,REFLECTANCE,_VARYINGNAME_,Reflectance,_MATRIXNAME_,reflectance,_INFONAME_,ReflectanceInfos.x) +#include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) +#include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) +#ifdef CLEARCOAT +#include(_DEFINENAME_,CLEARCOAT_TEXTURE,_VARYINGNAME_,ClearCoat,_MATRIXNAME_,clearCoat,_INFONAME_,ClearCoatInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TEXTURE_ROUGHNESS,_VARYINGNAME_,ClearCoatRoughness,_MATRIXNAME_,clearCoatRoughness,_INFONAME_,ClearCoatInfos.z) +#include(_DEFINENAME_,CLEARCOAT_BUMP,_VARYINGNAME_,ClearCoatBump,_MATRIXNAME_,clearCoatBump,_INFONAME_,ClearCoatBumpInfos.x) +#include(_DEFINENAME_,CLEARCOAT_TINT_TEXTURE,_VARYINGNAME_,ClearCoatTint,_MATRIXNAME_,clearCoatTint,_INFONAME_,ClearCoatTintInfos.x) +#endif +#ifdef IRIDESCENCE +#include(_DEFINENAME_,IRIDESCENCE_TEXTURE,_VARYINGNAME_,Iridescence,_MATRIXNAME_,iridescence,_INFONAME_,IridescenceInfos.x) +#include(_DEFINENAME_,IRIDESCENCE_THICKNESS_TEXTURE,_VARYINGNAME_,IridescenceThickness,_MATRIXNAME_,iridescenceThickness,_INFONAME_,IridescenceInfos.z) +#endif +#ifdef SHEEN +#include(_DEFINENAME_,SHEEN_TEXTURE,_VARYINGNAME_,Sheen,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.x) +#include(_DEFINENAME_,SHEEN_TEXTURE_ROUGHNESS,_VARYINGNAME_,SheenRoughness,_MATRIXNAME_,sheen,_INFONAME_,SheenInfos.z) +#endif +#ifdef ANISOTROPIC +#include(_DEFINENAME_,ANISOTROPIC_TEXTURE,_VARYINGNAME_,Anisotropy,_MATRIXNAME_,anisotropy,_INFONAME_,AnisotropyInfos.x) +#endif +#ifdef SUBSURFACE +#include(_DEFINENAME_,SS_THICKNESSANDMASK_TEXTURE,_VARYINGNAME_,Thickness,_MATRIXNAME_,thickness,_INFONAME_,ThicknessInfos.x) +#include(_DEFINENAME_,SS_REFRACTIONINTENSITY_TEXTURE,_VARYINGNAME_,RefractionIntensity,_MATRIXNAME_,refractionIntensity,_INFONAME_,RefractionIntensityInfos.x) +#include(_DEFINENAME_,SS_TRANSLUCENCYINTENSITY_TEXTURE,_VARYINGNAME_,TranslucencyIntensity,_MATRIXNAME_,translucencyIntensity,_INFONAME_,TranslucencyIntensityInfos.x) +#endif +#include +#include +#include +#include[0..maxSimultaneousLights] +#include +#if defined(POINTSIZE) && !defined(WEBGPU) +gl_PointSize=pointSize; +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.pbrVertexShader=pT;class pS extends nf.H{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_TEXTURE_ROUGHNESS_IDENTICAL=!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 pE extends lG{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRClearCoat",100,new pS,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=pE._DefaultIndexOfRefraction,this.indexOfRefraction=pE._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=rm.Wo.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i){if(!this._isEnabled)return!0;let r=this._material._disableBumpMap;return!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!ow.ClearCoatTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!ow.ClearCoatTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())&&(!i.getCaps().standardDerivatives||!this._bumpTexture||!ow.ClearCoatBumpTextureEnabled||!!r||!!this._bumpTexture.isReady())&&(!this._isTintEnabled||!this._tintTexture||!ow.ClearCoatTintTextureEnabled||!!this._tintTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ow.ClearCoatTextureEnabled?nE.G.PrepareDefinesForMergedUV(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&ow.ClearCoatTextureEnabled?nE.G.PrepareDefinesForMergedUV(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&ow.ClearCoatBumpTextureEnabled?nE.G.PrepareDefinesForMergedUV(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===pE._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&ow.ClearCoatTintTextureEnabled?(nE.G.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!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,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=this._material._disableBumpMap,f=this._material._invertNormalMapX,m=this._material._invertNormalMapY,g=d.CLEARCOAT_TEXTURE_ROUGHNESS_IDENTICAL;if(!e.useUbo||!p||!e.isSync){g&&ow.ClearCoatTextureEnabled?(e.updateFloat4("vClearCoatInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),nE.G.BindTextureMatrix(this._texture,e,"clearCoat")):(this._texture||this._textureRoughness)&&ow.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&nE.G.BindTextureMatrix(this._texture,e,"clearCoat"),!this._textureRoughness||g||d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE||nE.G.BindTextureMatrix(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&i.getCaps().standardDerivatives&&ow.ClearCoatTextureEnabled&&!_&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),nE.G.BindTextureMatrix(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",f?1:-1,m?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",f?-1:1,m?-1:1)),this._tintTexture&&ow.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),nE.G.BindTextureMatrix(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);let r=1-this._indexOfRefraction,p=1+this._indexOfRefraction,v=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",Math.pow(-r/p,2),v,r,p),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&&ow.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!g&&!d.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&ow.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&i.getCaps().standardDerivatives&&ow.ClearCoatBumpTextureEnabled&&!_&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&ow.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){var t,i,r,s;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose(),null===(r=this._bumpTexture)||void 0===r||r.dispose(),null===(s=this._tintTexture)||void 0===s||s.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,i){return e.CLEARCOAT_BUMP&&t.addFallback(i++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(i++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(i++,"CLEARCOAT"),i}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"}]}}}pE._DefaultIndexOfRefraction=1.5,(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"isEnabled",void 0),(0,sx.gn)([(0,rG.qC)()],pE.prototype,"intensity",void 0),(0,sx.gn)([(0,rG.qC)()],pE.prototype,"roughness",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"indexOfRefraction",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"texture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"useRoughnessFromMainTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"textureRoughness",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"remapF0OnInterfaceChange",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"bumpTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"isTintEnabled",void 0),(0,sx.gn)([(0,rG.n9)()],pE.prototype,"tintColor",void 0),(0,sx.gn)([(0,rG.qC)()],pE.prototype,"tintColorAtDistance",void 0),(0,sx.gn)([(0,rG.qC)()],pE.prototype,"tintThickness",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pE.prototype,"tintTexture",void 0);class pC extends nf.H{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0,this.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=!1}}class pb extends lG{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"PBRIridescence",110,new pC,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=pb._DefaultMinimumThickness,this.maximumThickness=pb._DefaultMaximumThickness,this.indexOfRefraction=pb._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!ow.IridescenceTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._thicknessTexture||!ow.IridescenceTextureEnabled||!!this._thicknessTexture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;this._isEnabled?(e.IRIDESCENCE=!0,e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE=null!==this._texture&&this._texture._texture===(null===(i=this._thicknessTexture)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._thicknessTexture),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ow.IridescenceTextureEnabled?nE.G.PrepareDefinesForMergedUV(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,!e.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&this._thicknessTexture&&ow.IridescenceTextureEnabled?nE.G.PrepareDefinesForMergedUV(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_USE_THICKNESS_FROM_MAINTEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE;e.useUbo&&p&&e.isSync||(_&&ow.IridescenceTextureEnabled?(e.updateFloat4("vIridescenceInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),nE.G.BindTextureMatrix(this._texture,e,"iridescence")):(this._texture||this._thicknessTexture)&&ow.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._thicknessTexture)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._thicknessTexture)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&nE.G.BindTextureMatrix(this._texture,e,"iridescence"),!this._thicknessTexture||_||d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE||nE.G.BindTextureMatrix(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&ow.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&!_&&!d.IRIDESCENCE_USE_THICKNESS_FROM_MAINTEXTURE&&ow.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._thicknessTexture)||void 0===i||i.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,i){return e.IRIDESCENCE&&t.addFallback(i++,"IRIDESCENCE"),i}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"}]}}}pb._DefaultMinimumThickness=100,pb._DefaultMaximumThickness=400,pb._DefaultIndexOfRefraction=1.3,(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pb.prototype,"isEnabled",void 0),(0,sx.gn)([(0,rG.qC)()],pb.prototype,"intensity",void 0),(0,sx.gn)([(0,rG.qC)()],pb.prototype,"minimumThickness",void 0),(0,sx.gn)([(0,rG.qC)()],pb.prototype,"maximumThickness",void 0),(0,sx.gn)([(0,rG.qC)()],pb.prototype,"indexOfRefraction",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pb.prototype,"texture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pb.prototype,"thicknessTexture",void 0);class py extends nf.H{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class pA extends lG{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()}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new py,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new rf.FM(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[16]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||!this._texture||!ow.AnisotropicTextureEnabled||!!this._texture.isReadyOrNotBlocking()}prepareDefinesBeforeAttributes(e,t,i){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!i.isVerticesDataPresent(sm.o.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ow.AnisotropicTextureEnabled?nE.G.PrepareDefinesForMergedUV(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;let i=this._material.isFrozen;e.useUbo&&i&&e.isSync||(this._texture&&ow.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),nE.G.BindTextureMatrix(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&ow.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,i){return e.ANISOTROPIC&&t.addFallback(i++,"ANISOTROPIC"),i}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,i){super.parse(e,t,i),void 0===e.legacy&&(this.legacy=!0)}}(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pA.prototype,"isEnabled",void 0),(0,sx.gn)([(0,rG.qC)()],pA.prototype,"intensity",void 0),(0,sx.gn)([(0,rG.QC)()],pA.prototype,"direction",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pA.prototype,"texture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],pA.prototype,"legacy",void 0);class pR extends nf.H{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,this.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=!1}}class pP extends lG{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"Sheen",120,new pR,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=rm.Wo.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[1]}isReadyForSubMesh(e,t){return!this._isEnabled||!e._areTexturesDirty||!t.texturesEnabled||(!this._texture||!ow.SheenTextureEnabled||!!this._texture.isReadyOrNotBlocking())&&(!this._textureRoughness||!ow.SheenTextureEnabled||!!this._textureRoughness.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t){var i;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.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL=null!==this._texture&&this._texture._texture===(null===(i=this._textureRoughness)||void 0===i?void 0:i._texture)&&this._texture.checkTransformsAreIdentical(this._textureRoughness),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&ow.SheenTextureEnabled?(nE.G.PrepareDefinesForMergedUV(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&ow.SheenTextureEnabled?nE.G.PrepareDefinesForMergedUV(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_TEXTURE_ROUGHNESS_IDENTICAL=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,i,r){var s,n,a,o,l,h,u,c;if(!this._isEnabled)return;let d=r.materialDefines,p=this._material.isFrozen,_=d.SHEEN_TEXTURE_ROUGHNESS_IDENTICAL;e.useUbo&&p&&e.isSync||(_&&ow.SheenTextureEnabled?(e.updateFloat4("vSheenInfos",this._texture.coordinatesIndex,this._texture.level,-1,-1),nE.G.BindTextureMatrix(this._texture,e,"sheen")):(this._texture||this._textureRoughness)&&ow.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",null!==(n=null===(s=this._texture)||void 0===s?void 0:s.coordinatesIndex)&&void 0!==n?n:0,null!==(o=null===(a=this._texture)||void 0===a?void 0:a.level)&&void 0!==o?o:0,null!==(h=null===(l=this._textureRoughness)||void 0===l?void 0:l.coordinatesIndex)&&void 0!==h?h:0,null!==(c=null===(u=this._textureRoughness)||void 0===u?void 0:u.level)&&void 0!==c?c:0),this._texture&&nE.G.BindTextureMatrix(this._texture,e,"sheen"),!this._textureRoughness||_||d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE||nE.G.BindTextureMatrix(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&&ow.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!_&&!d.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&ow.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){var t,i;e&&(null===(t=this._texture)||void 0===t||t.dispose(),null===(i=this._textureRoughness)||void 0===i||i.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,i){return e.SHEEN&&t.addFallback(i++,"SHEEN"),i}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"}]}}}(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pP.prototype,"isEnabled",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pP.prototype,"linkSheenWithAlbedo",void 0),(0,sx.gn)([(0,rG.qC)()],pP.prototype,"intensity",void 0),(0,sx.gn)([(0,rG.n9)()],pP.prototype,"color",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pP.prototype,"texture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pP.prototype,"useRoughnessFromMainTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pP.prototype,"roughness",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pP.prototype,"textureRoughness",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pP.prototype,"albedoScaling",void 0);class pI extends nf.H{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_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_MASK_FROM_THICKNESS_TEXTURE=!1,this.SS_USE_GLTF_TEXTURES=!1}}class pM extends lG{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){e>=1?this._volumeIndexOfRefraction=e:this._volumeIndexOfRefraction=-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}constructor(e,t=!0){super(e,"PBRSubSurface",130,new pI,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=rm.Wo.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=rm.Wo.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this._useGltfStyleTextures=!1,this.useGltfStyleTextures=!1,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[32]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&ow.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;let e=this._getRefractionTexture(t);if(e&&ow.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled){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_TEXTURE=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1;return}if(e._areTexturesDirty){e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=!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_MASK_FROM_THICKNESS_TEXTURE=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=!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;let i=!!this._thicknessTexture&&!!this._refractionIntensityTexture&&this._refractionIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._refractionIntensityTexture._texture===this._thicknessTexture._texture,r=!!this._thicknessTexture&&!!this._translucencyIntensityTexture&&this._translucencyIntensityTexture.checkTransformsAreIdentical(this._thicknessTexture)&&this._translucencyIntensityTexture._texture===this._thicknessTexture._texture,s=(i||!this._refractionIntensityTexture)&&(r||!this._translucencyIntensityTexture);if(e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&ow.ThicknessTextureEnabled&&nE.G.PrepareDefinesForMergedUV(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&ow.RefractionIntensityTextureEnabled&&!s&&nE.G.PrepareDefinesForMergedUV(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&ow.TranslucencyIntensityTextureEnabled&&!s&&nE.G.PrepareDefinesForMergedUV(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_MASK_FROM_THICKNESS_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture||!!this._translucencyIntensityTexture)&&s,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._refractionIntensityTexture)&&s,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_TEXTURE=(this._useMaskFromThicknessTexture||!!this._translucencyIntensityTexture)&&s,this._isRefractionEnabled&&t.texturesEnabled){let i=this._getRefractionTexture(t);i&&ow.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=i.isCube,e.SS_GAMMAREFRACTION=i.gammaSpace,e.SS_RGBDREFRACTION=i.isRGBD,e.SS_LINEARSPECULARREFRACTION=i.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&i.isCube?!i.invertZ:i.invertZ,e.SS_LODINREFRACTIONALPHA=i.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=i.isCube&&i.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;r.getRenderingMesh().getWorldMatrix().decompose(rf.jp.Vector3[0]);let s=Math.max(Math.abs(rf.jp.Vector3[0].x),Math.abs(rf.jp.Vector3[0].y),Math.abs(rf.jp.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*s,(this.maximumThickness-this.minimumThickness)*s)}bindForSubMesh(e,t,i,r){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;let s=r.materialDefines,n=this._material.isFrozen,a=this._material.realTimeFiltering,o=s.LODBASEDMICROSFURACE,l=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&ow.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),nE.G.BindTextureMatrix(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&ow.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),nE.G.BindTextureMatrix(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyIntensityTexture&&ow.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),nE.G.BindTextureMatrix(this._translucencyIntensityTexture,e,"translucencyIntensity")),l&&ow.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",l.getRefractionTextureMatrix());let t=1;!l.isCube&&l.depth&&(t=l.depth);let i=l.getSize().width,r=this.volumeIndexOfRefraction;e.updateFloat4("vRefractionInfos",l.level,1/r,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",i,l.lodGenerationScale,l.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",i,rk.R.Log2(i)),l.boundingBoxSize&&(e.updateVector3("vRefractionPosition",l.boundingBoxPosition),e.updateVector3("vRefractionSize",l.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.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&ow.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&ow.RefractionIntensityTextureEnabled&&s.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&ow.TranslucencyIntensityTextureEnabled&&s.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),l&&ow.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",l):(e.setTexture("refractionSampler",l._lodTextureMid||l),e.setTexture("refractionSamplerLow",l._lodTextureLow||l),e.setTexture("refractionSamplerHigh",l._lodTextureHigh||l))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){ow.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||this._refractionTexture===e}hasRenderTargetTextures(){return!!ow.RefractionTextureEnabled&&!!this._refractionTexture&&!!this._refractionTexture.isRenderTarget}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture)}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)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,i){return e.SS_SCATTERING&&t.addFallback(i++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(i++,"SS_TRANSLUCENCY"),i}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh")}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"}]}}}(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"isRefractionEnabled",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"isTranslucencyEnabled",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"isDispersionEnabled",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markScenePrePassDirty")],pM.prototype,"isScatteringEnabled",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"_scatteringDiffusionProfileIndex",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"refractionIntensity",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"translucencyIntensity",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"useAlbedoToTintRefraction",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"useAlbedoToTintTranslucency",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"thicknessTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"refractionTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"indexOfRefraction",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"_volumeIndexOfRefraction",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"volumeIndexOfRefraction",null),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"invertRefractionY",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"linkRefractionWithTransparency",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"minimumThickness",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"maximumThickness",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"useThicknessAsDepth",void 0),(0,sx.gn)([(0,rG.n9)()],pM.prototype,"tintColor",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"tintColorAtDistance",void 0),(0,sx.gn)([(0,rG.qC)()],pM.prototype,"dispersion",void 0),(0,sx.gn)([(0,rG.n9)()],pM.prototype,"diffusionDistance",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"useMaskFromThicknessTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"refractionIntensityTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"translucencyIntensityTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pM.prototype,"useGltfStyleTextures",void 0);let pD={effect:null,subMesh:null};class pO extends nf.H{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_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_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=!1,this.TONEMAPPING_ACES=!1,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 pN extends nc{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(1)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(1)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e?this._imageProcessingConfiguration=e:this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()})))}constructor(e,t){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new rf.Lt(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=pN.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=rm.Wo.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new rm.Wo(0,0,0),this._albedoColor=new rm.Wo(1,1,1),this._reflectivityColor=new rm.Wo(1,1,1),this._reflectionColor=new rm.Wo(1,1,1),this._emissiveColor=new rm.Wo(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=pN.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=8,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new nL.t(16),this._globalAmbientColor=new rm.Wo(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1,this.brdf=new dH(this),this.clearCoat=new pE(this),this.iridescence=new pb(this),this.anisotropy=new pA(this),this.sheen=new pP(this),this.subSurface=new pM(this),this.detailMap=new lW(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),ow.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=dz(this.getScene()),this.prePassConfiguration=new oF}get hasRenderTargetTextures(){return!!ow.ReflectionTextureEnabled&&!!this._reflectionTexture&&!!this._reflectionTexture.isRenderTarget||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){var e;return this._transparencyMode===pN.PBRMATERIAL_OPAQUE||this._transparencyMode===pN.PBRMATERIAL_ALPHATEST||(null===(e=this.subSurface)||void 0===e?void 0:e.disableAlphaBlending)}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){var e;return!!this._forceAlphaTest||(null===(e=this.subSurface)||void 0===e||!e.disableAlphaBlending)&&this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===pN.PBRMATERIAL_ALPHATEST)}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==pN.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,i){var r;if(this._uniformBufferLayoutBuilt||this.buildUniformLayout(),t.effect&&this.isFrozen&&t.effect._wasPreviouslyReady&&t.effect._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(this._callbackPluginEventGeneric(oL.S.GetDefineNames,this._eventInfo),t.materialDefines=new pO(this._eventInfo.defineNames));let s=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;let n=this.getScene(),a=n.getEngine();if(s._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&ow.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking()||this._ambientTexture&&ow.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking()||this._opacityTexture&&ow.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;let e=this._getReflectionTexture();if(e&&ow.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&(null===(r=e.getInternalTexture())||void 0===r?void 0:r._sphericalPolynomialPromise))return!1}if(this._lightmapTexture&&ow.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking()||this._emissiveTexture&&ow.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(ow.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()||this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking()||this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(a.getCaps().standardDerivatives&&this._bumpTexture&&ow.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady()||this._environmentBRDFTexture&&ow.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=s,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh||s._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;a.getCaps().standardDerivatives||e.isVerticesDataPresent(sm.o.NormalKind)||(e.createNormals(!0),rb.Y.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));let o=t.effect,l=s._areLightsDisposed,h=this._prepareEffect(e,s,this.onCompiled,this.onError,i,null,t.getRenderingMesh().hasThinInstances),u=!1;if(h){if(this._onEffectCreatedObservable&&(pD.effect=h,pD.subMesh=t,this._onEffectCreatedObservable.notifyObservers(pD)),this.allowShaderHotSwapping&&o&&!h.isReady()){if(h=o,s.markAsUnprocessed(),u=this.isFrozen,l)return s._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(h,s,this._materialContext)}return!!(t.effect&&t.effect.isReady())&&(s._renderId=n.getRenderId(),t.effect._wasPreviouslyReady=!u,t.effect._wasPreviouslyUsingInstances=!!i,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return null!=this._metallic||null!=this._roughness||!!this._metallicTexture}_prepareEffect(e,t,i=null,r=null,s=null,n=null,a){if(this._prepareDefines(e,t,s,n,a),!t.isDirty)return null;t.markAsProcessed();let o=this.getScene().getEngine(),l=new nF,h=0;t.USESPHERICALINVERTEX&&l.addFallback(h++,"USESPHERICALINVERTEX"),t.FOG&&l.addFallback(h,"FOG"),t.SPECULARAA&&l.addFallback(h,"SPECULARAA"),t.POINTSIZE&&l.addFallback(h,"POINTSIZE"),t.LOGARITHMICDEPTH&&l.addFallback(h,"LOGARITHMICDEPTH"),t.PARALLAX&&l.addFallback(h,"PARALLAX"),t.PARALLAX_RHS&&l.addFallback(h,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&l.addFallback(h++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&l.addFallback(h++,"ENVIRONMENTBRDF"),t.TANGENT&&l.addFallback(h++,"TANGENT"),t.BUMP&&l.addFallback(h++,"BUMP"),h=nE.G.HandleFallbacksForShadows(t,l,this._maxSimultaneousLights,h++),t.SPECULARTERM&&l.addFallback(h++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&l.addFallback(h++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&l.addFallback(h++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&l.addFallback(h++,"LIGHTMAP"),t.NORMAL&&l.addFallback(h++,"NORMAL"),t.AMBIENT&&l.addFallback(h++,"AMBIENT"),t.EMISSIVE&&l.addFallback(h++,"EMISSIVE"),t.VERTEXCOLOR&&l.addFallback(h++,"VERTEXCOLOR"),t.MORPHTARGETS&&l.addFallback(h++,"MORPHTARGETS"),t.MULTIVIEW&&l.addFallback(0,"MULTIVIEW");let u=[sm.o.PositionKind];t.NORMAL&&u.push(sm.o.NormalKind),t.TANGENT&&u.push(sm.o.TangentKind);for(let e=1;e<=6;++e)t["UV"+e]&&u.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&u.push(sm.o.ColorKind),nE.G.PrepareAttributesForBones(u,e,t,l),nE.G.PrepareAttributesForInstances(u,t),nE.G.PrepareAttributesForMorphTargets(u,e,t),nE.G.PrepareAttributesForBakedVertexAnimation(u,e,t);let c="pbr",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"],p=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],_=["Material","Scene","Mesh"],f={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=l,this._eventInfo.fallbackRank=h,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=u,this._eventInfo.samplers=p,this._eventInfo.uniformBuffersNames=_,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=f,this._callbackPluginEventGeneric(oL.S.PrepareEffect,this._eventInfo),oF.AddUniforms(d),oF.AddSamplers(p),(0,lH.qx)(d),nY.$&&(nY.$.PrepareUniforms(d,t),nY.$.PrepareSamplers(p,t)),nE.G.PrepareUniformsAndSamplersList({uniformsNames:d,uniformBuffersNames:_,samplers:p,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});let m={};this.customShaderNameResolve&&(c=this.customShaderNameResolve(c,d,_,p,t,u,m));let g=t.toString(),v=o.createEffect(c,{attributes:u,uniformsNames:d,uniformBuffersNames:_,samplers:p,defines:g,fallbacks:l,onCompiled:i,onError:r,indexParameters:f,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS},o);return this._eventInfo.customCode=void 0,v}_prepareDefines(e,t,i=null,r=null,s=!1){var n;let a=this.getScene(),o=a.getEngine();nE.G.PrepareDefinesForLights(a,e,t,!0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,nE.G.PrepareDefinesForMultiview(a,t);let l=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(nE.G.PrepareDefinesForPrePass(a,t,this.canRenderToMRT&&!l),nE.G.PrepareDefinesForOIT(a,t,l),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=6;++e)t["MAINUV"+e]=!1;if(a.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,o.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&ow.DiffuseTextureEnabled?(nE.G.PrepareDefinesForMergedUV(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&ow.AmbientTextureEnabled?(nE.G.PrepareDefinesForMergedUV(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&ow.OpacityTextureEnabled?(nE.G.PrepareDefinesForMergedUV(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;let e=this._getReflectionTexture();if(e&&ow.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,o._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===sj.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 sj.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case sj.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case sj.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case sj.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case sj.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case sj.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case sj.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case sj.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case sj.CUBIC_MODE:case sj.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==sj.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||o.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;if(this._lightmapTexture&&ow.LightmapTextureEnabled?(nE.G.PrepareDefinesForMergedUV(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&ow.EmissiveTextureEnabled?(nE.G.PrepareDefinesForMergedUV(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,ow.SpecularTextureEnabled){if(this._metallicTexture?(nE.G.PrepareDefinesForMergedUV(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?(nE.G.PrepareDefinesForMergedUV(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){let e=null!==this._metallicReflectanceTexture&&this._metallicReflectanceTexture._texture===(null===(n=this._reflectanceTexture)||void 0===n?void 0:n._texture)&&this._metallicReflectanceTexture.checkTransformsAreIdentical(this._reflectanceTexture);t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture&&!e,this._metallicReflectanceTexture?(nE.G.PrepareDefinesForMergedUV(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&!e&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(nE.G.PrepareDefinesForMergedUV(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1}else t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1;this._microSurfaceTexture?nE.G.PrepareDefinesForMergedUV(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1}else t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1;o.getCaps().standardDerivatives&&this._bumpTexture&&ow.BumpTextureEnabled&&!this._disableBumpMap?(nE.G.PrepareDefinesForMergedUV(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&ow.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=a.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&&ow.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===pN.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===pN.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=o.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=7===this.alphaMode||8===this.alphaMode,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&&(nE.G.PrepareDefinesForMisc(e,a,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(sm.o.NormalKind),t.DEBUGMODE=this._debugMode),nE.G.PrepareDefinesForFrameBoundValues(a,o,this,t,!!i,r,s),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),nE.G.PrepareDefinesForAttributes(e,t,!0,!0,!0,this._transparencyMode!==pN.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,i){let r=Object.assign({clipPlane:!1,useInstances:!1},i);this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(oL.S.GetDefineNames,this._eventInfo);let s=new pO(this._eventInfo.defineNames),n=this._prepareEffect(e,s,void 0,void 0,r.useInstances,r.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(pD.effect=n,pD.subMesh=null,this._onEffectCreatedObservable.notifyObservers(pD)),n.isReady()?t&&t(this):n.onCompileObservable.add(()=>{t&&t(this)})}buildUniformLayout(){let 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,i){var r,s,n,a;let o=this.getScene(),l=i.materialDefines;if(!l)return;let h=i.effect;if(!h)return;this._activeEffect=h,t.getMeshUniformBuffer().bindToEffect(h,"Mesh"),t.transferToEffect(e);let u=o.getEngine();this._uniformBuffer.bindToEffect(h,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,o,t,e,this.isFrozen),this._eventInfo.subMesh=i,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),l.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));let c=h._forceRebindOnNextCall||this._mustRebind(o,h,t.visibility);nE.G.BindBonesParameters(t,this._activeEffect,this.prePassConfiguration);let d=null,p=this._uniformBuffer;if(c){if(this.bindViewProjection(h),d=this._getReflectionTexture(),!p.useUbo||!this.isFrozen||!p.isSync||h._forceRebindOnNextCall){if(o.texturesEnabled){if(this._albedoTexture&&ow.DiffuseTextureEnabled&&(p.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),nE.G.BindTextureMatrix(this._albedoTexture,p,"albedo")),this._ambientTexture&&ow.AmbientTextureEnabled&&(p.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),nE.G.BindTextureMatrix(this._ambientTexture,p,"ambient")),this._opacityTexture&&ow.OpacityTextureEnabled&&(p.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),nE.G.BindTextureMatrix(this._opacityTexture,p,"opacity")),d&&ow.ReflectionTextureEnabled){if(p.updateMatrix("reflectionMatrix",d.getReflectionTextureMatrix()),p.updateFloat2("vReflectionInfos",d.level,0),d.boundingBoxSize){let e=d;p.updateVector3("vReflectionPosition",e.boundingBoxPosition),p.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){let e=d.getSize().width;p.updateFloat2("vReflectionFilteringInfo",e,rk.R.Log2(e))}if(!l.USEIRRADIANCEMAP){let e=d.sphericalPolynomial;if(l.USESPHERICALFROMREFLECTIONMAP&&e){if(l.SPHERICAL_HARMONICS){let t=e.preScaledHarmonics;p.updateVector3("vSphericalL00",t.l00),p.updateVector3("vSphericalL1_1",t.l1_1),p.updateVector3("vSphericalL10",t.l10),p.updateVector3("vSphericalL11",t.l11),p.updateVector3("vSphericalL2_2",t.l2_2),p.updateVector3("vSphericalL2_1",t.l2_1),p.updateVector3("vSphericalL20",t.l20),p.updateVector3("vSphericalL21",t.l21),p.updateVector3("vSphericalL22",t.l22)}else p.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),p.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),p.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),p.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),p.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),p.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),p.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),p.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),p.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}}p.updateFloat3("vReflectionMicrosurfaceInfos",d.getSize().width,d.lodGenerationScale,d.lodGenerationOffset)}this._emissiveTexture&&ow.EmissiveTextureEnabled&&(p.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),nE.G.BindTextureMatrix(this._emissiveTexture,p,"emissive")),this._lightmapTexture&&ow.LightmapTextureEnabled&&(p.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),nE.G.BindTextureMatrix(this._lightmapTexture,p,"lightmap")),ow.SpecularTextureEnabled&&(this._metallicTexture?(p.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),nE.G.BindTextureMatrix(this._metallicTexture,p,"reflectivity")):this._reflectivityTexture&&(p.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),nE.G.BindTextureMatrix(this._reflectivityTexture,p,"reflectivity")),this._metallicReflectanceTexture&&(p.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),nE.G.BindTextureMatrix(this._metallicReflectanceTexture,p,"metallicReflectance")),this._reflectanceTexture&&l.REFLECTANCE&&(p.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),nE.G.BindTextureMatrix(this._reflectanceTexture,p,"reflectance")),this._microSurfaceTexture&&(p.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),nE.G.BindTextureMatrix(this._microSurfaceTexture,p,"microSurfaceSampler"))),this._bumpTexture&&u.getCaps().standardDerivatives&&ow.BumpTextureEnabled&&!this._disableBumpMap&&(p.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),nE.G.BindTextureMatrix(this._bumpTexture,p,"bump"),o._mirroredCameraPosition?p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):p.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&p.updateFloat("pointSize",this.pointSize),l.METALLICWORKFLOW){rm.zZ.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,rm.zZ.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,p.updateColor4("vReflectivityColor",rm.zZ.Color3[0],1);let e=null!==(s=null===(r=this.subSurface)||void 0===r?void 0:r._indexOfRefraction)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((e-1)/(e+1),2)*this._metallicF0Factor,rm.zZ.Color3[0]);let t=this._metallicF0Factor;p.updateColor4("vMetallicReflectanceFactors",rm.zZ.Color3[0],t)}else p.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);p.updateColor3("vEmissiveColor",ow.EmissiveTextureEnabled?this._emissiveColor:rm.Wo.BlackReadOnly),p.updateColor3("vReflectionColor",this._reflectionColor),!l.SS_REFRACTION&&(null===(n=this.subSurface)||void 0===n?void 0:n._linkRefractionWithTransparency)?p.updateColor4("vAlbedoColor",this._albedoColor,1):p.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*o.environmentIntensity,this._lightingInfos.w=this._specularIntensity,p.updateVector4("vLightingIntensity",this._lightingInfos),o.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),p.updateColor3("vAmbientColor",this._globalAmbientColor),p.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}o.texturesEnabled&&(this._albedoTexture&&ow.DiffuseTextureEnabled&&p.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&ow.AmbientTextureEnabled&&p.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&ow.OpacityTextureEnabled&&p.setTexture("opacitySampler",this._opacityTexture),d&&ow.ReflectionTextureEnabled&&(l.LODBASEDMICROSFURACE?p.setTexture("reflectionSampler",d):(p.setTexture("reflectionSampler",d._lodTextureMid||d),p.setTexture("reflectionSamplerLow",d._lodTextureLow||d),p.setTexture("reflectionSamplerHigh",d._lodTextureHigh||d)),l.USEIRRADIANCEMAP&&p.setTexture("irradianceSampler",d.irradianceTexture)),l.ENVIRONMENTBRDF&&p.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&ow.EmissiveTextureEnabled&&p.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&ow.LightmapTextureEnabled&&p.setTexture("lightmapSampler",this._lightmapTexture),ow.SpecularTextureEnabled&&(this._metallicTexture?p.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&p.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&p.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&l.REFLECTANCE&&p.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&p.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&u.getCaps().standardDerivatives&&ow.BumpTextureEnabled&&!this._disableBumpMap&&p.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(h),this._eventInfo.subMesh=i,this._callbackPluginEventBindForSubMesh(this._eventInfo),(0,lH.an)(this._activeEffect,this,o),this.bindEyePosition(h)}else o.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);(c||!this.isFrozen)&&(o.lightsEnabled&&!this._disableLighting&&nE.G.BindLights(o,t,this._activeEffect,l,this._maxSimultaneousLights),(o.fogEnabled&&t.applyFog&&o.fogMode!==r2.x.FOGMODE_NONE||d||this.subSurface.refractionTexture||t.receiveShadows||l.PREPASS)&&this.bindView(h),nE.G.BindFogParameters(o,t,this._activeEffect,!0),l.NUM_MORPH_INFLUENCERS&&nE.G.BindMorphTargetParameters(t,this._activeEffect),l.BAKED_VERTEX_ANIMATION_TEXTURE&&(null===(a=t.bakedVertexAnimationManager)||void 0===a||a.bind(h,l.INSTANCES)),this._imageProcessingConfiguration.bind(this._activeEffect),nE.G.BindLogDepth(l,this._activeEffect,o)),this._afterBind(t,this._activeEffect),p.update()}getAnimatables(){let 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(){let 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(){var e;if(!(null===(e=this.subSurface)||void 0===e?void 0:e.isScatteringEnabled))return!1;let t=this.getScene().enableSubSurfaceForPrePass();return t&&(t.enabled=!0),!0}dispose(e,t){var i,r,s,n,a,o,l,h,u,c,d,p;t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),null===(i=this._albedoTexture)||void 0===i||i.dispose(),null===(r=this._ambientTexture)||void 0===r||r.dispose(),null===(s=this._opacityTexture)||void 0===s||s.dispose(),null===(n=this._reflectionTexture)||void 0===n||n.dispose(),null===(a=this._emissiveTexture)||void 0===a||a.dispose(),null===(o=this._metallicTexture)||void 0===o||o.dispose(),null===(l=this._reflectivityTexture)||void 0===l||l.dispose(),null===(h=this._bumpTexture)||void 0===h||h.dispose(),null===(u=this._lightmapTexture)||void 0===u||u.dispose(),null===(c=this._metallicReflectanceTexture)||void 0===c||c.dispose(),null===(d=this._reflectanceTexture)||void 0===d||d.dispose(),null===(p=this._microSurfaceTexture)||void 0===p||p.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}pN.PBRMATERIAL_OPAQUE=nu.F.MATERIAL_OPAQUE,pN.PBRMATERIAL_ALPHATEST=nu.F.MATERIAL_ALPHATEST,pN.PBRMATERIAL_ALPHABLEND=nu.F.MATERIAL_ALPHABLEND,pN.PBRMATERIAL_ALPHATESTANDBLEND=nu.F.MATERIAL_ALPHATESTANDBLEND,pN.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,pN.LIGHTFALLOFF_PHYSICAL=0,pN.LIGHTFALLOFF_GLTF=1,pN.LIGHTFALLOFF_STANDARD=2,(0,sx.gn)([(0,rG.rX)()],pN.prototype,"_imageProcessingConfiguration",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],pN.prototype,"debugMode",void 0);class pF extends pN{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===pN.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pN.LIGHTFALLOFF_PHYSICAL:this._lightFalloff=pN.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===pN.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),e?this._lightFalloff=pN.LIGHTFALLOFF_GLTF:this._lightFalloff=pN.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){super(e,t),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=pF.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=rm.Wo.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new rm.Wo(0,0,0),this.albedoColor=new rm.Wo(1,1,1),this.reflectivityColor=new rm.Wo(1,1,1),this.reflectionColor=new rm.Wo(1,1,1),this.emissiveColor=new rm.Wo(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=dz(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,i=""){let r=rG.p4.Clone(()=>new pF(e,this.getScene()),this,{cloneTexturesOnlyOnce:t});return r.id=e,r.name=e,this.stencil.copyTo(r.stencil),this._clonePlugins(r,i),r}serialize(){let e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,i){let r=rG.p4.Parse(()=>new pF(e.name,t),e,t,i);return e.stencil&&r.stencil.parse(e.stencil,t,i),nu.F._parsePlugins(e,r,t,i),e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}function pL(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}pF.PBRMATERIAL_OPAQUE=pN.PBRMATERIAL_OPAQUE,pF.PBRMATERIAL_ALPHATEST=pN.PBRMATERIAL_ALPHATEST,pF.PBRMATERIAL_ALPHABLEND=pN.PBRMATERIAL_ALPHABLEND,pF.PBRMATERIAL_ALPHATESTANDBLEND=pN.PBRMATERIAL_ALPHATESTANDBLEND,pF.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=pN.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"directIntensity",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"emissiveIntensity",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"environmentIntensity",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"specularIntensity",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"disableBumpMap",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"albedoTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"ambientTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"ambientTextureStrength",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pF.prototype,"opacityTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"reflectionTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"emissiveTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"reflectivityTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"metallicTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"metallic",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"roughness",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"metallicF0Factor",void 0),(0,sx.gn)([(0,rG.n9)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"metallicReflectanceColor",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"metallicReflectanceTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"reflectanceTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"microSurfaceTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"bumpTexture",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty",null)],pF.prototype,"lightmapTexture",void 0),(0,sx.gn)([(0,rG.n9)("ambient"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"ambientColor",void 0),(0,sx.gn)([(0,rG.n9)("albedo"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"albedoColor",void 0),(0,sx.gn)([(0,rG.n9)("reflectivity"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"reflectivityColor",void 0),(0,sx.gn)([(0,rG.n9)("reflection"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"reflectionColor",void 0),(0,sx.gn)([(0,rG.n9)("emissive"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"emissiveColor",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"microSurface",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useLightmapAsShadowmap",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pF.prototype,"useAlphaFromAlbedoTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pF.prototype,"forceAlphaTest",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesAndMiscDirty")],pF.prototype,"alphaCutOff",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useSpecularOverAlpha",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useRoughnessFromMetallicTextureGreen",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useMetallnessFromMetallicTextureBlue",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useAmbientInGrayScale",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),(0,sx.gn)([(0,rG.qC)()],pF.prototype,"usePhysicalLightFalloff",null),(0,sx.gn)([(0,rG.qC)()],pF.prototype,"useGLTFLightFalloff",null),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useRadianceOverAlpha",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useObjectSpaceNormalMap",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useParallax",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useParallaxOcclusion",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"parallaxScaleBias",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],pF.prototype,"disableLighting",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"forceIrradianceInFragment",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],pF.prototype,"maxSimultaneousLights",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"invertNormalMapX",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"invertNormalMapY",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"twoSidedLighting",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useAlphaFresnel",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useLinearAlphaFresnel",void 0),(0,sx.gn)([(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"environmentBRDFTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"forceNormalForward",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"enableSpecularAntiAliasing",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useHorizonOcclusion",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],pF.prototype,"useRadianceOcclusion",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],pF.prototype,"unlit",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsMiscDirty")],pF.prototype,"applyDecalMapAfterDetailMap",void 0),(0,rg.H)("BABYLON.PBRMaterial",pF);let pw=pL("DXT1"),pB=pL("DXT3"),pU=pL("DXT5"),pV=pL("DX10");class pk{static GetDDSInfo(e){let t=new Int32Array(e.buffer,e.byteOffset,31),i=new Int32Array(e.buffer,e.byteOffset,35),r=1;131072&t[2]&&(r=Math.max(1,t[7]));let s=t[21],n=s===pV?i[32]:0,a=0;switch(s){case 113:a=2;break;case 116:a=1;break;case pV:if(10===n){a=2;break}2===n&&(a=1)}return{width:t[4],height:t[3],mipmapCount:r,isFourCC:(4&t[20])==4,isRGB:(64&t[20])==64,isLuminance:(131072&t[20])==131072,isCube:(512&t[28])==512,isCompressed:s===pw||s===pB||s===pU,dxgiFormat:n,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,i,r,s,n){let a=new Float32Array(r),o=new Uint16Array(s,i),l=0;for(let i=0;i>8)}static _GetRGBArrayBuffer(e,t,i,r,s,n,a,o){let l=new Uint8Array(r),h=new Uint8Array(s,i),u=0;for(let i=0;i>8&255,f>>16&255,f>>24&255)]);return}let b=pk._ExtractLongWordOrder(_[23]),y=pk._ExtractLongWordOrder(_[24]),A=pk._ExtractLongWordOrder(_[25]),R=pk._ExtractLongWordOrder(_[26]);C&&(T=e._getRGBABufferInternalSizedFormat(r.textureType)),u=1,131072&_[2]&&!1!==s&&(u=Math.max(1,_[7]));let P=o||0,I=e.getCaps();for(let s=P;s0?r.sphericalPolynomial=uy.ConvertCubeMapToSphericalPolynomial({size:_[4],right:d[0],left:d[1],up:d[2],down:d[3],front:d[4],back:d[5],format:5,type:1,gammaSpace:!1}):r.sphericalPolynomial=void 0}}pk.StoreLODInAlphaChannel=!1,sK.B.prototype.createPrefilteredCubeTexture=function(e,t,i,r,s=null,n=null,a,o=null,l=!0){return this.createCubeTexture(e,t,null,!1,e=>{if(!e){s&&s(null);return}let n=e.texture;if(l?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new um,n._source=sq.S.CubePrefiltered,this.getCaps().textureLOD){s&&s(n);return}let a=this._gl,o=e.width;if(!o)return;let h=[];for(let s=0;s<3;s++){let l=1-s/2,u=rk.R.Log2(o)*i+r,c=Math.round(Math.min(Math.max(r+(u-r)*l,0),u)),d=new sq.l(this,sq.S.Temp);if(d.type=n.type,d.format=n.format,d.width=Math.pow(2,Math.max(rk.R.Log2(o)-c,0)),d.height=d.width,d.isCube=!0,d._cachedWrapU=0,d._cachedWrapV=0,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,d,!0),d.samplingMode=2,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){let t=e.info,i=e.data;this._unpackFlipY(t.isCompressed),pk.UploadDDSLevels(this,d,i,t,!0,6,c)}else rb.Y.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);let p=new sV(t);p._isCube=!0,p._texture=d,d.isReady=!0,h.push(p)}n._lodTextureHigh=h[2],n._lodTextureMid=h[1],n._lodTextureLow=h[0],s&&s(n)},n,a,o,l,i,r)};class pG{constructor(){this.supportCascades=!0}canLoad(e){return e.endsWith(".dds")}loadCubeData(e,t,i,r){let s;let n=t.getEngine(),a=!1,o=1e3;if(Array.isArray(e))for(let i=0;i1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),pk.UploadDDSLevels(n,t,r,s,a,6,-1,i),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t)}else s=pk.GetDDSInfo(e),t.width=s.width,t.height=s.height,i&&(s.sphericalPolynomial=new um),a=(s.isRGB||s.isLuminance||s.mipmapCount>1)&&t.generateMipMaps,n._unpackFlipY(s.isCompressed),pk.UploadDDSLevels(n,t,e,s,a,6),s.isFourCC||1!==s.mipmapCount?o=s.mipmapCount-1:n.generateMipMapsForCubemap(t,!1);n._setCubeMapTextureParams(t,a,o),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r({isDDS:!0,width:t.width,info:s,data:e,texture:t})}loadData(e,t,i){let r=pk.GetDDSInfo(e),s=(r.isRGB||r.isLuminance||r.mipmapCount>1)&&t.generateMipMaps&&r.width>>r.mipmapCount-1==1;i(r.width,r.height,s,r.isFourCC,()=>{pk.UploadDDSLevels(t.getEngine(),t,e,r,s,1)})}}sR.D._TextureLoaders.push(new pG);class pz{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".env")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=uI(e);if(n){t.width=n.width,t.height=n.width;try{uN(t,n),(function(e,t,i){let r=(i=uM(i)).specular;return r?(e._lodGenerationScale=r.lodGenerationScale,function(e,t,i=uR){if(!sg.w1.IsExponentOfTwo(e.width))throw Error("Texture size must be a power of two");let r=rk.R.ILog2(e.width)+1,s=e.getEngine(),n=!1,a=!1,o=null,l=null,h=null,u=s.getCaps();if(e.format=5,e.type=0,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,s.updateTextureSamplingMode(3,e),u.textureLOD?s._features.supportRenderAndCopyToLodForFloatTextures?u.textureHalfFloatRender&&u.textureHalfFloatLinearFiltering?(n=!0,e.type=2):u.textureFloatRender&&u.textureFloatLinearFiltering&&(n=!0,e.type=1):n=!1:(n=!1,a=!0,h={}),n)o=new nz("rgbdDecode","rgbdDecode",null,null,1,null,3,s,!1,void 0,e.type,void 0,null,!1),e._isRGBD=!1,e.invertY=!1,l=s.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:3,type:e.type,format:5});else if(e._isRGBD=!0,e.invertY=!0,a){let t=e._lodGenerationScale,i=e._lodGenerationOffset;for(let n=0;n<3;n++){let a=1-n/2,o=(r-1)*t+i,l=Math.round(Math.min(Math.max(i+(o-i)*a,0),o)),u=new sq.l(s,sq.S.Temp);u.isCube=!0,u.invertY=!0,u.generateMipMaps=!1,s.updateTextureSamplingMode(2,u);let c=new sV(null);switch(c._isCube=!0,c._texture=u,h[l]=c,n){case 0:e._lodTextureLow=c;break;case 1:e._lodTextureMid=c;break;case 2:e._lodTextureHigh=c}}}let c=[];for(let r=0;ruO(t,s,n,o,f,u,r,a,h,l,e));else{let t=new Image;t.src=f,d=new Promise((i,c)=>{t.onload=()=>{uO(t,s,n,o,f,u,r,a,h,l,e).then(()=>i()).catch(e=>{c(e)})},t.onerror=e=>{c(e)}})}c.push(d)}if(t.length{l&&(s._releaseTexture(e),l._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))})}(e,uD(t,i),i.imageType)):Promise.resolve()})(t,e,n).then(()=>{t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()},e=>{null==s||s("Can not upload environment levels",e)})}catch(e){null==s||s("Can not upload environment file",e)}}else s&&s("Can not parse the environment file",null)}loadData(){throw".env not supported in 2d."}}sR.D._TextureLoaders.push(new pz);class pW{constructor(e,t){if(this.data=e,this.isInvalid=!1,!pW.IsValid(e)){this.isInvalid=!0,rb.Y.Error("texture missing KTX identifier");return}let i=Uint32Array.BYTES_PER_ELEMENT,r=new DataView(this.data.buffer,this.data.byteOffset+12,13*i),s=67305985===r.getUint32(0,!0);if(this.glType=r.getUint32(1*i,s),this.glTypeSize=r.getUint32(2*i,s),this.glFormat=r.getUint32(3*i,s),this.glInternalFormat=r.getUint32(4*i,s),this.glBaseInternalFormat=r.getUint32(5*i,s),this.pixelWidth=r.getUint32(6*i,s),this.pixelHeight=r.getUint32(7*i,s),this.pixelDepth=r.getUint32(8*i,s),this.numberOfArrayElements=r.getUint32(9*i,s),this.numberOfFaces=r.getUint32(10*i,s),this.numberOfMipmapLevels=r.getUint32(11*i,s),this.bytesOfKeyValueData=r.getUint32(12*i,s),0!==this.glType){rb.Y.Error("only compressed formats currently supported"),this.isInvalid=!0;return}if(this.numberOfMipmapLevels=Math.max(1,this.numberOfMipmapLevels),0===this.pixelHeight||0!==this.pixelDepth){rb.Y.Error("only 2D textures currently supported"),this.isInvalid=!0;return}if(0!==this.numberOfArrayElements){rb.Y.Error("texture arrays not currently supported"),this.isInvalid=!0;return}if(this.numberOfFaces!==t){rb.Y.Error("number of faces expected"+t+", but found "+this.numberOfFaces),this.isInvalid=!0;return}this.loadType=pW.COMPRESSED_2D}uploadLevels(e,t){switch(this.loadType){case pW.COMPRESSED_2D:this._upload2DCompressedLevels(e,t);case pW.TEX_2D:case pW.COMPRESSED_3D:case pW.TEX_3D:}}_upload2DCompressedLevels(e,t){let i=pW.HEADER_LEN+this.bytesOfKeyValueData,r=this.pixelWidth,s=this.pixelHeight,n=t?this.numberOfMipmapLevels:1;for(let t=0;t=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&49===t[5]&&49===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}pW.HEADER_LEN=64,pW.COMPRESSED_2D=0,pW.COMPRESSED_3D=1,pW.TEX_2D=2,pW.TEX_3D=3;class pH{constructor(e){this._pendingActions=[],this._workerInfos=e.map(e=>({workerPromise:Promise.resolve(e),idle:!0}))}dispose(){for(let 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(let t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then(i=>{t(i,()=>{let t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0})})}}class pX extends pH{constructor(e,t,i=pX.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=i}push(e){if(!this._executeOnIdleWorker(e)){if(this._workerInfos.length{t(i,()=>{r(),e.idle&&(e.timeoutId=setTimeout(()=>{e.workerPromise.then(e=>{e.terminate()});let t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)},this._options.idleTimeElapsedBeforeRelease))})})}}function pY(e){e.wasmUASTCToASTC&&(KTX2DECODER.LiteTranscoder_UASTC_ASTC.WasmModuleURL=e.wasmUASTCToASTC),e.wasmUASTCToBC7&&(KTX2DECODER.LiteTranscoder_UASTC_BC7.WasmModuleURL=e.wasmUASTCToBC7),e.wasmUASTCToRGBA_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL=e.wasmUASTCToRGBA_UNORM),e.wasmUASTCToRGBA_SRGB&&(KTX2DECODER.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL=e.wasmUASTCToRGBA_SRGB),e.wasmUASTCToR8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL=e.wasmUASTCToR8_UNORM),e.wasmUASTCToRG8_UNORM&&(KTX2DECODER.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL=e.wasmUASTCToRG8_UNORM),e.jsMSCTranscoder&&(KTX2DECODER.MSCTranscoder.JSModuleURL=e.jsMSCTranscoder),e.wasmMSCTranscoder&&(KTX2DECODER.MSCTranscoder.WasmModuleURL=e.wasmMSCTranscoder),e.wasmZSTDDecoder&&(KTX2DECODER.ZSTDDecoder.WasmModuleURL=e.wasmZSTDDecoder)}pX.DefaultOptions={idleTimeElapsedBeforeRelease:1e3},(eC=iC||(iC={}))[eC.ETC1S=0]="ETC1S",eC[eC.UASTC4x4=1]="UASTC4x4",(eb=ib||(ib={}))[eb.ASTC_4X4_RGBA=0]="ASTC_4X4_RGBA",eb[eb.BC7_RGBA=1]="BC7_RGBA",eb[eb.BC3_RGBA=2]="BC3_RGBA",eb[eb.BC1_RGB=3]="BC1_RGB",eb[eb.PVRTC1_4_RGBA=4]="PVRTC1_4_RGBA",eb[eb.PVRTC1_4_RGB=5]="PVRTC1_4_RGB",eb[eb.ETC2_RGBA=6]="ETC2_RGBA",eb[eb.ETC1_RGB=7]="ETC1_RGB",eb[eb.RGBA32=8]="RGBA32",eb[eb.R8=9]="R8",eb[eb.RG8=10]="RG8",(ey=iy||(iy={}))[ey.COMPRESSED_RGBA_BPTC_UNORM_EXT=36492]="COMPRESSED_RGBA_BPTC_UNORM_EXT",ey[ey.COMPRESSED_RGBA_ASTC_4X4_KHR=37808]="COMPRESSED_RGBA_ASTC_4X4_KHR",ey[ey.COMPRESSED_RGB_S3TC_DXT1_EXT=33776]="COMPRESSED_RGB_S3TC_DXT1_EXT",ey[ey.COMPRESSED_RGBA_S3TC_DXT5_EXT=33779]="COMPRESSED_RGBA_S3TC_DXT5_EXT",ey[ey.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842]="COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",ey[ey.COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840]="COMPRESSED_RGB_PVRTC_4BPPV1_IMG",ey[ey.COMPRESSED_RGBA8_ETC2_EAC=37496]="COMPRESSED_RGBA8_ETC2_EAC",ey[ey.COMPRESSED_RGB8_ETC2=37492]="COMPRESSED_RGB8_ETC2",ey[ey.COMPRESSED_RGB_ETC1_WEBGL=36196]="COMPRESSED_RGB_ETC1_WEBGL",ey[ey.RGBA8Format=32856]="RGBA8Format",ey[ey.R8Format=33321]="R8Format",ey[ey.RG8Format=33323]="RG8Format";class pj{constructor(){this._isDirty=!0,this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=!0,this._ktx2DecoderOptions={}}get isDirty(){return this._isDirty}get useRGBAIfASTCBC7NotAvailableWhenUASTC(){return this._useRGBAIfASTCBC7NotAvailableWhenUASTC}set useRGBAIfASTCBC7NotAvailableWhenUASTC(e){this._useRGBAIfASTCBC7NotAvailableWhenUASTC!==e&&(this._useRGBAIfASTCBC7NotAvailableWhenUASTC=e,this._isDirty=!0)}get useRGBAIfOnlyBC1BC3AvailableWhenUASTC(){return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC}set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(e){this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC!==e&&(this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC=e,this._isDirty=!0)}get forceRGBA(){return this._forceRGBA}set forceRGBA(e){this._forceRGBA!==e&&(this._forceRGBA=e,this._isDirty=!0)}get forceR8(){return this._forceR8}set forceR8(e){this._forceR8!==e&&(this._forceR8=e,this._isDirty=!0)}get forceRG8(){return this._forceRG8}set forceRG8(e){this._forceRG8!==e&&(this._forceRG8=e,this._isDirty=!0)}get bypassTranscoders(){return this._bypassTranscoders}set bypassTranscoders(e){this._bypassTranscoders!==e&&(this._bypassTranscoders=e,this._isDirty=!0)}_getKTX2DecoderOptions(){if(!this._isDirty)return this._ktx2DecoderOptions;this._isDirty=!1;let e={useRGBAIfASTCBC7NotAvailableWhenUASTC:this._useRGBAIfASTCBC7NotAvailableWhenUASTC,forceRGBA:this._forceRGBA,forceR8:this._forceR8,forceRG8:this._forceRG8,bypassTranscoders:this._bypassTranscoders};return this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC&&(e.transcodeFormatDecisionTree={UASTC:{transcodeFormat:[ib.BC1_RGB,ib.BC3_RGBA],yes:{transcodeFormat:ib.RGBA32,engineFormat:iy.RGBA8Format,roundToMultiple4:!1}}}),this._ktx2DecoderOptions=e,e}}class pq{static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static _Initialize(e){if(pq._WorkerPoolPromise||pq._DecoderModulePromise)return;let t={jsDecoderModule:sg.w1.GetBabylonScriptURL(this.URLConfig.jsDecoderModule,!0),wasmUASTCToASTC:sg.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC,!0),wasmUASTCToBC7:sg.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7,!0),wasmUASTCToRGBA_UNORM:sg.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM,!0),wasmUASTCToRGBA_SRGB:sg.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB,!0),wasmUASTCToR8_UNORM:sg.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM,!0),wasmUASTCToRG8_UNORM:sg.w1.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM,!0),jsMSCTranscoder:sg.w1.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder,!0),wasmMSCTranscoder:sg.w1.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder,!0),wasmZSTDDecoder:sg.w1.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder,!0)};e&&"function"==typeof Worker&&"undefined"!=typeof URL?pq._WorkerPoolPromise=new Promise(i=>{let r=`${pY}(${pK})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));i(new pX(e,()=>new Promise((e,i)=>{let r=new Worker(s),n=e=>{r.removeEventListener("error",n),r.removeEventListener("message",a),i(e)},a=t=>{"init"===t.data.action&&(r.removeEventListener("error",n),r.removeEventListener("message",a),e(r))};r.addEventListener("error",n),r.addEventListener("message",a),r.postMessage({action:"init",urls:t})})))}):"undefined"==typeof KTX2DECODER?pq._DecoderModulePromise=sg.w1.LoadBabylonScriptAsync(t.jsDecoderModule).then(()=>(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,pY(t),new KTX2DECODER.KTX2Decoder)):(KTX2DECODER.MSCTranscoder.UseFromWorkerThread=!1,KTX2DECODER.WASMMemoryManager.LoadBinariesFromCurrentThread=!0,pq._DecoderModulePromise=Promise.resolve(new KTX2DECODER.KTX2Decoder))}constructor(e,t=pq.DefaultNumWorkers){this._engine=e,pq._Initialize(t)}uploadAsync(e,t,i){let r=this._engine.getCaps(),s={astc:!!r.astc,bptc:!!r.bptc,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,etc1:!!r.etc1};if(pq._WorkerPoolPromise)return pq._WorkerPoolPromise.then(r=>new Promise((n,a)=>{r.push((r,o)=>{let l=e=>{r.removeEventListener("error",l),r.removeEventListener("message",h),a(e),o()},h=e=>{if("decoded"===e.data.action){if(r.removeEventListener("error",l),r.removeEventListener("message",h),e.data.success)try{this._createTexture(e.data.decodedData,t,i),n()}catch(e){a({message:e})}else a({message:e.data.msg});o()}};r.addEventListener("error",l),r.addEventListener("message",h),r.postMessage({action:"setDefaultDecoderOptions",options:pq.DefaultDecoderOptions._getKTX2DecoderOptions()});let u=new Uint8Array(e.byteLength);u.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),r.postMessage({action:"decode",data:u,caps:s,options:i},[u.buffer])})}));if(pq._DecoderModulePromise)return pq._DecoderModulePromise.then(i=>(pq.DefaultDecoderOptions.isDirty&&(KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=pq.DefaultDecoderOptions._getKTX2DecoderOptions()),new Promise((s,n)=>{i.decode(e,r).then(e=>{this._createTexture(e,t),s()}).catch(e=>{n({message:e})})})));throw Error("KTX2 decoder module is not available")}_createTexture(e,t,i){this._engine._bindTextureDirectly(3553,t),i&&(i.transcodedFormat=e.transcodedFormat,i.isInGammaSpace=e.isInGammaSpace,i.hasAlpha=e.hasAlpha,i.transcoderName=e.transcoderName);let r=!0;switch(e.transcodedFormat){case 32856:t.type=0,t.format=5;break;case 33321:t.type=0,t.format=6;break;case 33323:t.type=0,t.format=7;break;default:t.format=e.transcodedFormat,r=!1}if(t._gammaSpace=e.isInGammaSpace,t.generateMipMaps=e.mipmaps.length>1,e.errors)throw Error("KTX2 container - could not transcode the data. "+e.errors);for(let i=0;i=12){let t=new Uint8Array(e.buffer,e.byteOffset,12);if(171===t[0]&&75===t[1]&&84===t[2]&&88===t[3]&&32===t[4]&&50===t[5]&&48===t[6]&&187===t[7]&&13===t[8]&&10===t[9]&&26===t[10]&&10===t[11])return!0}return!1}}function pK(){let e;onmessage=t=>{if(t.data)switch(t.data.action){case"init":{let i=t.data.urls;importScripts(i.jsDecoderModule),pY(i),e=new KTX2DECODER.KTX2Decoder,postMessage({action:"init"});break}case"setDefaultDecoderOptions":KTX2DECODER.KTX2Decoder.DefaultDecoderOptions=t.data.options;break;case"decode":e.decode(t.data.data,t.data.caps,t.data.options).then(e=>{let t=[];for(let i=0;i{postMessage({action:"decoded",success:!1,msg:e})})}}}pq.URLConfig={jsDecoderModule:"https://cdn.babylonjs.com/babylon.ktx2Decoder.js",wasmUASTCToASTC:null,wasmUASTCToBC7:null,wasmUASTCToRGBA_UNORM:null,wasmUASTCToRGBA_SRGB:null,wasmUASTCToR8_UNORM:null,wasmUASTCToRG8_UNORM:null,jsMSCTranscoder:null,wasmMSCTranscoder:null,wasmZSTDDecoder:null},pq.DefaultNumWorkers=pq.GetDefaultNumWorkers(),pq.DefaultDecoderOptions=new pj;class p${constructor(){this.supportCascades=!1}canLoad(e,t){return e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t}loadCubeData(e,t,i,r){if(Array.isArray(e))return;t._invertVScale=!t.invertY;let s=t.getEngine(),n=new pW(e,6),a=n.numberOfMipmapLevels>1&&t.generateMipMaps;s._unpackFlipY(!0),n.uploadLevels(t,t.generateMipMaps),t.width=n.pixelWidth,t.height=n.pixelHeight,s._setCubeMapTextureParams(t,a,n.numberOfMipmapLevels-1),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}loadData(e,t,i,r){if(pW.IsValid(e)){t._invertVScale=!t.invertY;let r=new pW(e,1),s=function(e){switch(e){case 35916:return 33776;case 35918:return 33778;case 35919:return 33779;case 37493:return 37492;case 37497:return 37496;case 37495:return 37494;case 37840:return 37808;case 36493:return 36492}return null}(r.glInternalFormat);s?(t.format=s,t._useSRGBBuffer=t.getEngine()._getUseSRGBBuffer(!0,t.generateMipMaps),t._gammaSpace=!0):t.format=r.glInternalFormat,i(r.pixelWidth,r.pixelHeight,t.generateMipMaps,!0,()=>{r.uploadLevels(t,t.generateMipMaps)},r.isInvalid)}else pq.IsValid(e)?new pq(t.getEngine()).uploadAsync(e,t,r).then(()=>{i(t.width,t.height,t.generateMipMaps,!0,()=>{},!1)},e=>{rb.Y.Warn(`Failed to load KTX2 texture data: ${e.message}`),i(0,0,!1,!1,()=>{},!0)}):(rb.Y.Error("texture missing KTX identifier"),i(0,0,!1,!1,()=>{},!0))}}sR.D._TextureLoaders.unshift(new p$);class pQ extends a0{constructor(e,t,i){super(e,rf.P.Zero(),t),this._xrSessionManager=i,this._firstFrame=!1,this._referenceQuaternion=rf._f.Identity(),this._referencedPosition=new rf.P,this._trackingState=tB.NOT_TRACKING,this.onXRCameraInitializedObservable=new r_.y$,this.onBeforeCameraTeleport=new r_.y$,this.onAfterCameraTeleport=new r_.y$,this.onTrackingStateChanged=new r_.y$,this.compensateOnFirstFrame=!0,this._rotate180=new rf._f(0,1,0,0),this.minZ=.1,this.rotationQuaternion=new rf._f,this.cameraRigMode=sC.V.RIG_MODE_CUSTOM,this.updateUpVectorFromRotation=!0,this._updateNumberOfRigCameras(1),this.freezeProjectionMatrix(),this._deferOnly=!0,this._xrSessionManager.onXRSessionInit.add(()=>{this._referencedPosition.copyFromFloats(0,0,0),this._referenceQuaternion.copyFromFloats(0,0,0,1),this._firstFrame=this.compensateOnFirstFrame}),this._xrSessionManager.onXRFrameObservable.add(()=>{this._firstFrame&&this._updateFromXRSession(),this.onXRCameraInitializedObservable.hasObservers()&&(this.onXRCameraInitializedObservable.notifyObservers(this),this.onXRCameraInitializedObservable.clear()),this._deferredUpdated&&(this.position.copyFrom(this._deferredPositionUpdate),this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate)),this._updateReferenceSpace(),this._updateFromXRSession()},void 0,!0)}get trackingState(){return this._trackingState}_setTrackingState(e){this._trackingState!==e&&(this._trackingState=e,this.onTrackingStateChanged.notifyObservers(e))}get realWorldHeight(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.baseReferenceSpace);return e&&e.transform?e.transform.position.y:0}_updateForDualEyeDebugging(){this._updateNumberOfRigCameras(2),this.rigCameras[0].viewport=new ny.l(0,0,.5,1),this.rigCameras[0].outputRenderTarget=null,this.rigCameras[1].viewport=new ny.l(.5,0,.5,1),this.rigCameras[1].outputRenderTarget=null}setTransformationFromNonVRCamera(e=this.getScene().activeCamera,t=!0){e&&e!==this&&(e.computeWorldMatrix().decompose(void 0,this.rotationQuaternion,this.position),this.position.y=0,rf._f.FromEulerAnglesToRef(0,this.rotationQuaternion.toEulerAngles().y,0,this.rotationQuaternion),this._firstFrame=!0,t&&this._xrSessionManager.resetReferenceSpace())}getClassName(){return"WebXRCamera"}setTarget(e){let t=rf.jp.Vector3[1];e.subtractToRef(this.position,t),t.y=0,t.normalize();let i=Math.atan2(t.x,t.z);this.rotationQuaternion.toEulerAnglesToRef(t),rf._f.FromEulerAnglesToRef(t.x,i,t.z,this.rotationQuaternion)}dispose(){super.dispose(),this._lastXRViewerPose=void 0}_updateFromXRSession(){let e=this._xrSessionManager.currentFrame&&this._xrSessionManager.currentFrame.getViewerPose(this._xrSessionManager.referenceSpace);if(this._lastXRViewerPose=e||void 0,!e){this._setTrackingState(tB.NOT_TRACKING);return}let t=e.emulatedPosition?tB.TRACKING_LOST:tB.TRACKING;if(this._setTrackingState(t),this.minZ!==this._cache.minZ||this.maxZ!==this._cache.maxZ){let e={depthFar:this.maxZ||1e4,depthNear:this.minZ};this._xrSessionManager.updateRenderState(e),this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ}if(e.transform){let t=e.transform.orientation;if(void 0===e.transform.orientation.x)return;let i=e.transform.position;this._referencedPosition.set(i.x,i.y,i.z),this._referenceQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this._referencedPosition.z*=-1,this._referenceQuaternion.z*=-1,this._referenceQuaternion.w*=-1),this._firstFrame?(this._firstFrame=!1,this.position.y+=this._referencedPosition.y,this._referenceQuaternion.copyFromFloats(0,0,0,1)):(this.rotationQuaternion.copyFrom(this._referenceQuaternion),this.position.copyFrom(this._referencedPosition))}this.rigCameras.length!==e.views.length&&this._updateNumberOfRigCameras(e.views.length),e.views.forEach((e,t)=>{var i;let r=this.rigCameras[t];r.isLeftCamera||r.isRightCamera||("right"===e.eye?r._isRightCamera=!0:"left"!==e.eye||(r._isLeftCamera=!0));let s=e.transform.position,n=e.transform.orientation;r.parent=this.parent,r.position.set(s.x,s.y,s.z),r.rotationQuaternion.set(n.x,n.y,n.z,n.w),this._scene.useRightHandedSystem?r.rotationQuaternion.multiplyInPlace(this._rotate180):(r.position.z*=-1,r.rotationQuaternion.z*=-1,r.rotationQuaternion.w*=-1),rf.y3.FromFloat32ArrayToRefScaled(e.projectionMatrix,0,1,r._projectionMatrix),this._scene.useRightHandedSystem||r._projectionMatrix.toggleProjectionMatrixHandInPlace(),0===t&&this._projectionMatrix.copyFrom(r._projectionMatrix);let a=this._xrSessionManager.getRenderTargetTextureForView(e);this._renderingMultiview=(null===(i=null==a?void 0:a._texture)||void 0===i?void 0:i.isMultiview)||!1,this._renderingMultiview?0==t&&(this._xrSessionManager.trySetViewportForView(this.viewport,e),this.outputRenderTarget=a):(this._xrSessionManager.trySetViewportForView(r.viewport,e),r.outputRenderTarget=a||this._xrSessionManager.getRenderTargetTextureForView(e)),r.layerMask=this.layerMask})}_updateNumberOfRigCameras(e=1){for(;this.rigCameras.lengthe;){let e=this.rigCameras.pop();e&&e.dispose()}}_updateReferenceSpace(){if(!this.position.equals(this._referencedPosition)||!this.rotationQuaternion.equals(this._referenceQuaternion)){let e=rf.jp.Matrix[0],t=rf.jp.Matrix[1],i=rf.jp.Matrix[2];rf.y3.ComposeToRef(pQ._ScaleReadOnly,this._referenceQuaternion,this._referencedPosition,e),rf.y3.ComposeToRef(pQ._ScaleReadOnly,this.rotationQuaternion,this.position,t),e.invert().multiplyToRef(t,i),i.invert(),this._scene.useRightHandedSystem||i.toggleModelMatrixHandInPlace(),i.decompose(void 0,this._referenceQuaternion,this._referencedPosition);let r=new XRRigidTransform({x:this._referencedPosition.x,y:this._referencedPosition.y,z:this._referencedPosition.z},{x:this._referenceQuaternion.x,y:this._referenceQuaternion.y,z:this._referenceQuaternion.z,w:this._referenceQuaternion.w});this._xrSessionManager.referenceSpace=this._xrSessionManager.referenceSpace.getOffsetReferenceSpace(r)}}}pQ._ScaleReadOnly=rf.P.One();class pZ{constructor(e){this._scene=e,this._nonVRCamera=null,this._attachedToElement=!1,this._spectatorCamera=null,this._originalSceneAutoClear=!0,this._supported=!1,this._spectatorMode=!1,this._lastTimestamp=0,this.onInitialXRPoseSetObservable=new r_.y$,this.onStateChangedObservable=new r_.y$,this.state=tw.NOT_IN_XR,this.sessionManager=new l5(e),this.camera=new pQ("webxr",e,this.sessionManager),this.featuresManager=new nr(this.sessionManager),e.onDisposeObservable.addOnce(()=>{this.dispose()})}static CreateAsync(e){let t=new pZ(e);return t.sessionManager.initializeAsync().then(()=>(t._supported=!0,t)).catch(e=>{throw t._setState(tw.NOT_IN_XR),t.dispose(),e})}dispose(){var e;this.exitXRAsync(),this.camera.dispose(),this.onStateChangedObservable.clear(),this.onInitialXRPoseSetObservable.clear(),this.sessionManager.dispose(),null===(e=this._spectatorCamera)||void 0===e||e.dispose(),this._nonVRCamera&&(this._scene.activeCamera=this._nonVRCamera)}async enterXRAsync(e,t,i=this.sessionManager.getWebXRRenderTarget(),r={}){var s,n,a;if(!this._supported)throw"WebXR not supported in this browser or environment";this._setState(tw.ENTERING_XR),"viewer"!==t&&"local"!==t&&(r.optionalFeatures=r.optionalFeatures||[],r.optionalFeatures.push(t)),r=await this.featuresManager._extendXRSessionInitObject(r),"immersive-ar"===e&&"unbounded"!==t&&rb.Y.Warn("We recommend using 'unbounded' reference space type when using 'immersive-ar' session mode");try{await this.sessionManager.initializeSessionAsync(e,r),await this.sessionManager.setReferenceSpaceTypeAsync(t);let o=await i.initializeXRLayerAsync(this.sessionManager.session),l={depthFar:this.camera.maxZ||1e4,depthNear:this.camera.minZ};return this.featuresManager.getEnabledFeature(ni.LAYERS)||(l.baseLayer=o),this.sessionManager.updateRenderState(l),this.sessionManager.runXRRenderLoop(),this._originalSceneAutoClear=this._scene.autoClear,this._nonVRCamera=this._scene.activeCamera,this._attachedToElement=!!(null===(n=null===(s=this._nonVRCamera)||void 0===s?void 0:s.inputs)||void 0===n?void 0:n.attachedToElement),null===(a=this._nonVRCamera)||void 0===a||a.detachControl(),this._scene.activeCamera=this.camera,"immersive-ar"!==e?this._nonXRToXRCamera():(this._scene.autoClear=!1,this.camera.compensateOnFirstFrame=!1,this.camera.position.set(0,0,0),this.camera.rotationQuaternion.set(0,0,0,1),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)),this.sessionManager.onXRSessionEnded.addOnce(()=>{this.state!==tw.EXITING_XR&&this._setState(tw.EXITING_XR),this.camera.rigCameras.forEach(e=>{e.outputRenderTarget=null}),this._scene.autoClear=this._originalSceneAutoClear,this._scene.activeCamera=this._nonVRCamera,this._attachedToElement&&this._nonVRCamera&&this._nonVRCamera.attachControl(!!this._nonVRCamera.inputs.noPreventDefault),"immersive-ar"!==e&&this.camera.compensateOnFirstFrame&&(this._nonVRCamera.setPosition?this._nonVRCamera.setPosition(this.camera.position):this._nonVRCamera.position.copyFrom(this.camera.position)),this._setState(tw.NOT_IN_XR)}),this.sessionManager.onXRFrameObservable.addOnce(()=>{this._setState(tw.IN_XR)}),this.sessionManager}catch(e){throw rb.Y.Log(e),rb.Y.Log(e.message),this._setState(tw.NOT_IN_XR),e}}exitXRAsync(){return this.state!==tw.IN_XR?Promise.resolve():(this._setState(tw.EXITING_XR),this.sessionManager.exitXRAsync())}enableSpectatorMode(e){this._spectatorMode||(this._spectatorMode=!0,this._switchSpectatorMode(e))}disableSpecatatorMode(){this._spectatorMode&&(this._spectatorMode=!1,this._switchSpectatorMode())}_switchSpectatorMode(e){let t=1/((null==e?void 0:e.fps)?e.fps:1e3)*1e3,i=(null==e?void 0:e.preferredCameraIndex)?null==e?void 0:e.preferredCameraIndex:0,r=()=>{this._spectatorCamera&&this.sessionManager.currentTimestamp-this._lastTimestamp>=t&&(this._lastTimestamp=this.sessionManager.currentTimestamp,this._spectatorCamera.position.copyFrom(this.camera.rigCameras[i].globalPosition),this._spectatorCamera.rotationQuaternion.copyFrom(this.camera.rigCameras[i].absoluteRotation))};if(this._spectatorMode){if(i>=this.camera.rigCameras.length)throw Error("the preferred camera index is beyond the length of rig camera array.");let e=()=>{this.state===tw.IN_XR?(this._spectatorCamera=new or("webxr-spectator",rf.P.Zero(),this._scene),this._spectatorCamera.rotationQuaternion=new rf._f,this._scene.activeCameras=[this.camera,this._spectatorCamera],this.sessionManager.onXRFrameObservable.add(r),this._scene.onAfterRenderCameraObservable.add(e=>{e===this.camera&&(this._scene.getEngine().framebufferDimensionsObject=null)})):this.state===tw.EXITING_XR&&(this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=null)};this.onStateChangedObservable.add(e),e()}else this.sessionManager.onXRFrameObservable.removeCallback(r),this._scene.activeCameras=[this.camera]}_nonXRToXRCamera(){this.camera.setTransformationFromNonVRCamera(this._nonVRCamera),this.onInitialXRPoseSetObservable.notifyObservers(this.camera)}_setState(e){this.state!==e&&(this.state=e,this.onStateChangedObservable.notifyObservers(this.state))}}class pJ{constructor(e,t,i=-1,r=[]){this.id=e,this.type=t,this._buttonIndex=i,this._axesIndices=r,this._axes={x:0,y:0},this._changes={},this._currentValue=0,this._hasChanges=!1,this._pressed=!1,this._touched=!1,this.onAxisValueChangedObservable=new r_.y$,this.onButtonStateChangedObservable=new r_.y$}get axes(){return this._axes}get changes(){return this._changes}get hasChanges(){return this._hasChanges}get pressed(){return this._pressed}get touched(){return this._touched}get value(){return this._currentValue}dispose(){this.onAxisValueChangedObservable.clear(),this.onButtonStateChangedObservable.clear()}isAxes(){return 0!==this._axesIndices.length}isButton(){return -1!==this._buttonIndex}update(e){let t=!1,i=!1;if(this._hasChanges=!1,this._changes={},this.isButton()){let i=e.buttons[this._buttonIndex];if(!i)return;this._currentValue!==i.value&&(this.changes.value={current:i.value,previous:this._currentValue},t=!0,this._currentValue=i.value),this._touched!==i.touched&&(this.changes.touched={current:i.touched,previous:this._touched},t=!0,this._touched=i.touched),this._pressed!==i.pressed&&(this.changes.pressed={current:i.pressed,previous:this._pressed},t=!0,this._pressed=i.pressed)}this.isAxes()&&(this._axes.x!==e.axes[this._axesIndices[0]]&&(this.changes.axes={current:{x:e.axes[this._axesIndices[0]],y:this._axes.y},previous:{x:this._axes.x,y:this._axes.y}},this._axes.x=e.axes[this._axesIndices[0]],i=!0),this._axes.y!==e.axes[this._axesIndices[1]]&&(this.changes.axes?this.changes.axes.current.y=e.axes[this._axesIndices[1]]:this.changes.axes={current:{x:this._axes.x,y:e.axes[this._axesIndices[1]]},previous:{x:this._axes.x,y:this._axes.y}},this._axes.y=e.axes[this._axesIndices[1]],i=!0)),t&&(this._hasChanges=!0,this.onButtonStateChangedObservable.notifyObservers(this)),i&&(this._hasChanges=!0,this.onAxisValueChangedObservable.notifyObservers(this._axes))}}pJ.BUTTON_TYPE="button",pJ.SQUEEZE_TYPE="squeeze",pJ.THUMBSTICK_TYPE="thumbstick",pJ.TOUCHPAD_TYPE="touchpad",pJ.TRIGGER_TYPE="trigger";class p0{constructor(e,t,i,r,s=!1,n){this.scene=e,this.layout=t,this.gamepadObject=i,this.handedness=r,this._doNotLoadControllerMesh=s,this._controllerCache=n,this._initComponent=e=>{if(!e)return;let t=this.layout.components[e],i=t.type,r=t.gamepadIndices.button,s=[];void 0!==t.gamepadIndices.xAxis&&void 0!==t.gamepadIndices.yAxis&&s.push(t.gamepadIndices.xAxis,t.gamepadIndices.yAxis),this.components[e]=new pJ(e,i,r,s)},this._modelReady=!1,this.components={},this.disableAnimation=!1,this.onModelLoadedObservable=new r_.y$,t.components&&Object.keys(t.components).forEach(this._initComponent)}dispose(){this.getComponentIds().forEach(e=>this.getComponent(e).dispose()),this.rootMesh&&(this.rootMesh.getChildren(void 0,!0).forEach(e=>{e.setEnabled(!1)}),this.rootMesh.dispose(!!this._controllerCache,!this._controllerCache))}getAllComponentsOfType(e){return this.getComponentIds().map(e=>this.components[e]).filter(t=>t.type===e)}getComponent(e){return this.components[e]}getComponentIds(){return Object.keys(this.components)}getComponentOfType(e){return this.getAllComponentsOfType(e)[0]||null}getMainComponent(){return this.getComponent(this.layout.selectComponentId)}async loadModel(){let e=!this._getModelLoadingConstraints(),t=this._getGenericFilenameAndPath();return e?rb.Y.Warn("Falling back to generic models"):t=this._getFilenameAndPath(),new Promise((i,r)=>{let s=t=>{e?this._getGenericParentMesh(t):this._setRootMesh(t),this._processLoadedModel(t),this._modelReady=!0,this.onModelLoadedObservable.notifyObservers(this),i(!0)};if(this._controllerCache){let e=this._controllerCache.filter(e=>e.filename===t.filename&&e.path===t.path);if(e[0]){e[0].meshes.forEach(e=>e.setEnabled(!0)),s(e[0].meshes);return}}nh.ImportMesh("",t.path,t.filename,this.scene,e=>{this._controllerCache&&this._controllerCache.push(Object.assign(Object.assign({},t),{meshes:e})),s(e)},null,(e,i)=>{rb.Y.Log(i),rb.Y.Warn(`Failed to retrieve controller model of type ${this.profileId} from the remote server: ${t.path}${t.filename}`),r(i)})})}updateFromXRFrame(e){this.getComponentIds().forEach(e=>this.getComponent(e).update(this.gamepadObject)),this.updateModel(e)}get handness(){return this.handedness}pulse(e,t,i=0){return this.gamepadObject.hapticActuators&&this.gamepadObject.hapticActuators[i]?this.gamepadObject.hapticActuators[i].pulse(e,t):Promise.resolve(!1)}_getChildByName(e,t){return e.getChildren(e=>e.name===t,!1)[0]}_getImmediateChildByName(e,t){return e.getChildren(e=>e.name==t,!0)[0]}_lerpTransform(e,t,i){if(!e.minMesh||!e.maxMesh||!e.valueMesh||!e.minMesh.rotationQuaternion||!e.maxMesh.rotationQuaternion||!e.valueMesh.rotationQuaternion)return;let r=i?.5*t+.5:t;rf._f.SlerpToRef(e.minMesh.rotationQuaternion,e.maxMesh.rotationQuaternion,r,e.valueMesh.rotationQuaternion),rf.P.LerpToRef(e.minMesh.position,e.maxMesh.position,r,e.valueMesh.position)}updateModel(e){this._modelReady&&this._updateModel(e)}_getGenericFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getGenericParentMesh(e){this.rootMesh=new sp.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.parent||(e.isPickable=!1,e.setParent(this.rootMesh))}),this.rootMesh.rotationQuaternion=rf._f.FromEulerAngles(0,Math.PI,0)}}class p1 extends p0{constructor(e,t,i){super(e,p2[i],t,i),this.profileId=p1.ProfileId}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){this.rootMesh=new sp.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1,e.parent||e.setParent(this.rootMesh)}),this.rootMesh.rotationQuaternion=rf._f.FromEulerAngles(0,Math.PI,0)}_updateModel(){}}p1.ProfileId="generic-trigger";let p2={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-trigger-none",assetPath:"none.glb"}};class p3 extends p0{constructor(e,t,i,r,s){super(e,i.layouts[t.handedness||"none"],t.gamepad,t.handedness,void 0,s),this._repositoryUrl=r,this.controllerCache=s,this._buttonMeshMapping={},this._touchDots={},this.profileId=i.profileId}dispose(){super.dispose(),this.controllerCache||Object.keys(this._touchDots).forEach(e=>{this._touchDots[e].dispose()})}_getFilenameAndPath(){return{filename:this.layout.assetPath,path:`${this._repositoryUrl}/profiles/${this.profileId}/`}}_getModelLoadingConstraints(){let e=nh.IsPluginForExtensionAvailable(".glb");return e||rb.Y.Warn("glTF / glb loader was not registered, using generic controller instead"),e}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=this.layout.components[e];this._buttonMeshMapping[e]={mainMesh:this._getChildByName(this.rootMesh,t.rootNodeName),states:{}},Object.keys(t.visualResponses).forEach(i=>{let r=t.visualResponses[i];if("transform"===r.valueNodeProperty)this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,r.valueNodeName),minMesh:this._getChildByName(this.rootMesh,r.minNodeName),maxMesh:this._getChildByName(this.rootMesh,r.maxNodeName)};else{let s=t.type===pJ.TOUCHPAD_TYPE&&t.touchPointNodeName?t.touchPointNodeName:r.valueNodeName;if(this._buttonMeshMapping[e].states[i]={valueMesh:this._getChildByName(this.rootMesh,s)},t.type===pJ.TOUCHPAD_TYPE&&!this._touchDots[i]){let t=hM(i+"dot",{diameter:.0015,segments:8},this.scene);t.material=new lj(i+"mat",this.scene),t.material.diffuseColor=rm.Wo.Red(),t.parent=this._buttonMeshMapping[e].states[i].valueMesh||null,t.isVisible=!1,this._touchDots[i]=t}}})})}_setRootMesh(e){let t;this.rootMesh=new sp.Kj(this.profileId+"-"+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;i{let t=this.getComponent(e);if(!t.hasChanges)return;let i=this._buttonMeshMapping[e],r=this.layout.components[e];Object.keys(r.visualResponses).forEach(e=>{let s=r.visualResponses[e],n=t.value;if("xAxis"===s.componentProperty?n=t.axes.x:"yAxis"===s.componentProperty&&(n=t.axes.y),"transform"===s.valueNodeProperty)this._lerpTransform(i.states[e],n,"button"!==s.componentProperty);else{let r=i.states[e].valueMesh;r&&(r.isVisible=t.touched||t.pressed),this._touchDots[e]&&(this._touchDots[e].isVisible=t.touched||t.pressed)}})})}}let p4=[];class p5{static ClearProfilesCache(){this._ProfilesList=null,this._ProfileLoadingPromises={}}static DefaultFallbacks(){this.RegisterFallbacksForProfileId("google-daydream",["generic-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive-focus",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("htc-vive",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("magicleap-one",["generic-trigger-squeeze-touchpad"]),this.RegisterFallbacksForProfileId("windows-mixed-reality",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("microsoft-mixed-reality",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-go",["generic-trigger-touchpad"]),this.RegisterFallbacksForProfileId("oculus-touch-v2",["oculus-touch","generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("oculus-touch",["generic-trigger-squeeze-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-gearvr",["windows-mixed-reality","generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("samsung-odyssey",["generic-touchpad"]),this.RegisterFallbacksForProfileId("valve-index",["generic-trigger-squeeze-touchpad-thumbstick"]),this.RegisterFallbacksForProfileId("generic-hand-select",["generic-trigger"])}static FindFallbackWithProfileId(e){let t=this._Fallbacks[e]||[];return t.unshift(e),t}static GetMotionControllerWithXRInput(e,t,i){let r=[];i&&r.push(i),r.push(...e.profiles||[]),r.length&&!r[0]&&r.pop(),e.gamepad&&e.gamepad.id&&e.gamepad.id===(e.gamepad.id.match(/oculus touch/gi)?e.gamepad.id:void 0)&&r.push("oculus-touch-v2");let s=r.indexOf("windows-mixed-reality");if(-1!==s&&r.splice(s,0,"microsoft-mixed-reality"),r.length||r.push("generic-trigger"),!this.UseOnlineRepository)return this._LoadProfilesFromAvailableControllers(r,e,t);{let i=this.PrioritizeOnlineRepository?this._LoadProfileFromRepository:this._LoadProfilesFromAvailableControllers,s=this.PrioritizeOnlineRepository?this._LoadProfilesFromAvailableControllers:this._LoadProfileFromRepository;return i.call(this,r,e,t).catch(()=>s.call(this,r,e,t))}}static RegisterController(e,t){this._AvailableControllers[e]=t}static RegisterFallbacksForProfileId(e,t){this._Fallbacks[e]?this._Fallbacks[e].push(...t):this._Fallbacks[e]=t}static UpdateProfilesList(){return this._ProfilesList=sg.w1.LoadFileAsync(this.BaseRepositoryUrl+"/profiles/profilesList.json",!1).then(e=>JSON.parse(e)),this._ProfilesList}static ClearControllerCache(){p4.forEach(e=>{e.meshes.forEach(e=>{e.dispose(!1,!0)})}),p4.length=0}static _LoadProfileFromRepository(e,t,i){return Promise.resolve().then(()=>this._ProfilesList?this._ProfilesList:this.UpdateProfilesList()).then(t=>{for(let i=0;i(this._ProfileLoadingPromises[e]||(this._ProfileLoadingPromises[e]=sg.w1.LoadFileAsync(`${this.BaseRepositoryUrl}/profiles/${e}/profile.json`,!1).then(e=>JSON.parse(e))),this._ProfileLoadingPromises[e])).then(e=>new p3(i,t,e,this.BaseRepositoryUrl,this.DisableControllerCache?void 0:p4))}static _LoadProfilesFromAvailableControllers(e,t,i){for(let r=0;rnew p1(t,e.gamepad,e.handedness)),p5.DefaultFallbacks();let p6=0;class p8{constructor(e,t,i={}){this._scene=e,this.inputSource=t,this._options=i,this._tmpVector=new rf.P,this._disposed=!1,this.onDisposeObservable=new r_.y$,this.onMeshLoadedObservable=new r_.y$,this.onMotionControllerInitObservable=new r_.y$,this._uniqueId=`controller-${p6++}-${t.targetRayMode}-${t.handedness}`,this.pointer=new sf.x(`${this._uniqueId}-pointer`,e),this.pointer.rotationQuaternion=new rf._f,this.inputSource.gripSpace&&(this.grip=new sf.x(`${this._uniqueId}-grip`,this._scene),this.grip.rotationQuaternion=new rf._f),this._tmpVector.set(0,0,this._scene.useRightHandedSystem?-1:1),this.inputSource.gamepad&&"tracked-pointer"===this.inputSource.targetRayMode&&p5.GetMotionControllerWithXRInput(t,e,this._options.forceControllerProfile).then(e=>{this.motionController=e,this.onMotionControllerInitObservable.notifyObservers(e),this._options.doNotLoadControllerMesh||this.motionController._doNotLoadControllerMesh||this.motionController.loadModel().then(e=>{var t;e&&this.motionController&&this.motionController.rootMesh&&(this._options.renderingGroupId&&(this.motionController.rootMesh.renderingGroupId=this._options.renderingGroupId,this.motionController.rootMesh.getChildMeshes(!1).forEach(e=>e.renderingGroupId=this._options.renderingGroupId)),this.onMeshLoadedObservable.notifyObservers(this.motionController.rootMesh),this.motionController.rootMesh.parent=this.grip||this.pointer,this.motionController.disableAnimation=!!this._options.disableMotionControllerAnimation),this._disposed&&(null===(t=this.motionController)||void 0===t||t.dispose())})},()=>{sg.w1.Warn("Could not find a matching motion controller for the registered input source")})}get uniqueId(){return this._uniqueId}dispose(){this.grip&&this.grip.dispose(!0),this.motionController&&this.motionController.dispose(),this.pointer.dispose(!0),this.onMotionControllerInitObservable.clear(),this.onMeshLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._disposed=!0}getWorldPointerRayToRef(e,t=!1){let i=t&&this.grip?this.grip:this.pointer;rf.P.TransformNormalToRef(this._tmpVector,i.getWorldMatrix(),e.direction),e.direction.normalize(),e.origin.copyFrom(i.absolutePosition),e.length=1e3}updateFromXRFrame(e,t,i){let r=e.getPose(this.inputSource.targetRaySpace,t);if(this._lastXRPose=r,r){let e=r.transform.position;this.pointer.position.set(e.x,e.y,e.z);let t=r.transform.orientation;this.pointer.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.pointer.position.z*=-1,this.pointer.rotationQuaternion.z*=-1,this.pointer.rotationQuaternion.w*=-1),this.pointer.parent=i.parent}if(this.inputSource.gripSpace&&this.grip){let r=e.getPose(this.inputSource.gripSpace,t);if(r){let e=r.transform.position,t=r.transform.orientation;this.grip.position.set(e.x,e.y,e.z),this.grip.rotationQuaternion.set(t.x,t.y,t.z,t.w),this._scene.useRightHandedSystem||(this.grip.position.z*=-1,this.grip.rotationQuaternion.z*=-1,this.grip.rotationQuaternion.w*=-1)}this.grip.parent=i.parent}this.motionController&&this.motionController.updateFromXRFrame(e)}}class p7{constructor(e,t,i={}){if(this.xrSessionManager=e,this.xrCamera=t,this._options=i,this.controllers=[],this.onControllerAddedObservable=new r_.y$,this.onControllerRemovedObservable=new r_.y$,this._onInputSourcesChange=e=>{this._addAndRemoveControllers(e.added,e.removed)},this._sessionEndedObserver=this.xrSessionManager.onXRSessionEnded.add(()=>{this._addAndRemoveControllers([],this.controllers.map(e=>e.inputSource))}),this._sessionInitObserver=this.xrSessionManager.onXRSessionInit.add(e=>{e.addEventListener("inputsourceschange",this._onInputSourcesChange)}),this._frameObserver=this.xrSessionManager.onXRFrameObservable.add(e=>{this.controllers.forEach(t=>{t.updateFromXRFrame(e,this.xrSessionManager.referenceSpace,this.xrCamera)})}),this._options.customControllersRepositoryURL&&(p5.BaseRepositoryUrl=this._options.customControllersRepositoryURL),p5.UseOnlineRepository=!this._options.disableOnlineControllerRepository,p5.UseOnlineRepository)try{p5.UpdateProfilesList().catch(()=>{p5.UseOnlineRepository=!1})}catch(e){p5.UseOnlineRepository=!1}}_addAndRemoveControllers(e,t){let i=this.controllers.map(e=>e.inputSource);for(let t of e)if(-1===i.indexOf(t)){let e=new p8(this.xrSessionManager.scene,t,Object.assign(Object.assign({},this._options.controllerOptions||{}),{forceControllerProfile:this._options.forceInputProfile,doNotLoadControllerMesh:this._options.doNotLoadControllerMeshes,disableMotionControllerAnimation:this._options.disableControllerAnimation}));this.controllers.push(e),this.onControllerAddedObservable.notifyObservers(e)}let r=[],s=[];this.controllers.forEach(e=>{-1===t.indexOf(e.inputSource)?r.push(e):s.push(e)}),this.controllers=r,s.forEach(e=>{this.onControllerRemovedObservable.notifyObservers(e),e.dispose()})}dispose(){this.controllers.forEach(e=>{e.dispose()}),this.xrSessionManager.onXRFrameObservable.remove(this._frameObserver),this.xrSessionManager.onXRSessionInit.remove(this._sessionInitObserver),this.xrSessionManager.onXRSessionEnded.remove(this._sessionEndedObserver),this.onControllerAddedObservable.clear(),this.onControllerRemovedObservable.clear(),p5.ClearControllerCache()}}class p9 extends ns{constructor(e,t){super(e),this._options=t,this._attachController=e=>{if(this._controllers[e.uniqueId])return;let{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e.pointer);switch(this._controllers[e.uniqueId]={xrController:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new s6(new rf.P,new rf.P),disabledByNearInteraction:!1,id:p9._IdCounter++},this._attachedController?!this._options.enablePointerSelectionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enablePointerSelectionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachTrackedPointerRayMode(e);case"gaze":return this._attachGazeMode(e);case"screen":return this._attachScreenRayMode(e)}},this._controllers={},this._tmpVectorForPickCompare=new rf.P,this.disablePointerLighting=!0,this.disableSelectionMeshLighting=!0,this.displayLaserPointer=!0,this.displaySelectionMesh=!0,this.laserPointerPickedColor=new rm.Wo(.9,.9,.9),this.laserPointerDefaultColor=new rm.Wo(.7,.7,.7),this.selectionMeshDefaultColor=new rm.Wo(.8,.8,.8),this.selectionMeshPickedColor=new rm.Wo(.3,.3,1),this._identityMatrix=rf.y3.Identity(),this._screenCoordinatesRef=rf.P.Zero(),this._viewportRef=new ny.l(0,0,0,0),this._scene=this._xrSessionManager.scene}attach(){if(!super.attach())return!1;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,this._options.gazeCamera){let e=this._options.gazeCamera,{laserPointer:t,selectionMesh:i}=this._generateNewMeshPair(e);this._controllers.camera={webXRCamera:e,laserPointer:t,selectionMesh:i,meshUnderPointer:null,pick:null,tmpRay:new s6(new rf.P,new rf.P),disabledByNearInteraction:!1,id:p9._IdCounter++},this._attachGazeMode()}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;i{let t;let i=this._controllers[e];if(!this._options.enablePointerSelectionOnAllControllers&&e!==this._attachedController||i.disabledByNearInteraction){i.selectionMesh.isVisible=!1,i.laserPointer.isVisible=!1,i.pick=null;return}if(i.laserPointer.isVisible=this.displayLaserPointer,i.xrController)t=i.xrController.pointer.position,i.xrController.getWorldPointerRayToRef(i.tmpRay);else{if(!i.webXRCamera)return;t=i.webXRCamera.position,i.webXRCamera.getForwardRayToRef(i.tmpRay)}if(this._options.maxPointerDistance&&(i.tmpRay.length=this._options.maxPointerDistance),!this._options.disableScenePointerVectorUpdate&&t){let e=this._xrSessionManager.scene,r=this._options.xrInput.xrCamera;!r||(r.viewport.toGlobalToRef(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),this._viewportRef),rf.P.ProjectToRef(t,this._identityMatrix,e.getTransformMatrix(),this._viewportRef,this._screenCoordinatesRef),"number"!=typeof this._screenCoordinatesRef.x||"number"!=typeof this._screenCoordinatesRef.y||isNaN(this._screenCoordinatesRef.x)||isNaN(this._screenCoordinatesRef.y)||(e.pointerX=this._screenCoordinatesRef.x,e.pointerY=this._screenCoordinatesRef.y,i.screenCoordinates={x:this._screenCoordinatesRef.x,y:this._screenCoordinatesRef.y}))}let r=null;this._utilityLayerScene&&(r=this._utilityLayerScene.pickWithRay(i.tmpRay,this._utilityLayerScene.pointerMovePredicate||this.raySelectionPredicate));let s=this._scene.pickWithRay(i.tmpRay,this._scene.pointerMovePredicate||this.raySelectionPredicate);r&&r.hit?s&&s.hit?r.distance{if(t.pick){if(this._augmentPointerInit(l,t.id,t.screenCoordinates),t.laserPointer.material.alpha=0,n.isVisible=!1,t.pick.hit){if(this._pickingMoved(s,t.pick))o&&!this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),o=!1,a=0;else if(a>i/10&&(n.isVisible=!0),(a+=this._scene.getEngine().getDeltaTime())>=i)this._scene.simulatePointerDown(t.pick,l),o=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,l),n.isVisible=!1;else{let e=1-a/i;n.scaling.set(e,e,e)}}else o=!1,a=0;this._scene.simulatePointerMove(t.pick,l),s=t.pick}}),void 0!==this._options.renderingGroupId&&(n.renderingGroupId=this._options.renderingGroupId),e&&e.onDisposeObservable.addOnce(()=>{t.pick&&!this._options.disablePointerUpOnTouchOut&&o&&(this._scene.simulatePointerUp(t.pick,l),t.finalPointerUpTriggered=!0),n.dispose()})}_attachScreenRayMode(e){let t=this._controllers[e.uniqueId],i=!1,r={pointerId:t.id,pointerType:"xr"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),t.pick&&(!this._options.disablePointerUpOnTouchOut||!i)&&(i?this._scene.simulatePointerMove(t.pick,r):(this._scene.simulatePointerDown(t.pick,r),t.pointerDownTriggered=!0,i=!0,this._options.disablePointerUpOnTouchOut&&this._scene.simulatePointerUp(t.pick,r)))}),e.onDisposeObservable.addOnce(()=>{this._augmentPointerInit(r,t.id,t.screenCoordinates),this._xrSessionManager.runInXRFrame(()=>{t.pick&&!t.finalPointerUpTriggered&&i&&!this._options.disablePointerUpOnTouchOut&&(this._scene.simulatePointerUp(t.pick,r),t.finalPointerUpTriggered=!0)})})}_attachTrackedPointerRayMode(e){let t=this._controllers[e.uniqueId];if(this._options.forceGazeMode)return this._attachGazeMode(e);let i={pointerId:t.id,pointerType:"xr"};if(t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{t.laserPointer.material.disableLighting=this.disablePointerLighting,t.selectionMesh.material.disableLighting=this.disableSelectionMeshLighting,t.pick&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),this._scene.simulatePointerMove(t.pick,i))}),e.inputSource.gamepad){let r=r=>{this._options.overrideButtonId&&(t.selectionComponent=r.getComponent(this._options.overrideButtonId)),t.selectionComponent||(t.selectionComponent=r.getMainComponent()),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(r=>{if(r.changes.pressed){let s=r.changes.pressed.current;t.pick?(this._options.enablePointerSelectionOnAllControllers||e.uniqueId===this._attachedController)&&(this._augmentPointerInit(i,t.id,t.screenCoordinates),s?(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor):(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)):!s||this._options.enablePointerSelectionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)}})};e.motionController?r(e.motionController):e.onMotionControllerInitObservable.add(r)}else{let e=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerDown(t.pick,i),t.pointerDownTriggered=!0,t.selectionMesh.material.emissiveColor=this.selectionMeshPickedColor,t.laserPointer.material.emissiveColor=this.laserPointerPickedColor)},r=e=>{this._augmentPointerInit(i,t.id,t.screenCoordinates),t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&(this._scene.simulatePointerUp(t.pick,i),t.selectionMesh.material.emissiveColor=this.selectionMeshDefaultColor,t.laserPointer.material.emissiveColor=this.laserPointerDefaultColor)};t.eventListeners={selectend:r,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_convertNormalToDirectionOfRay(e,t){return e&&Math.acos(rf.P.Dot(e,t.direction)){let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),!t.finalPointerUpTriggered&&t.pointerDownTriggered){let e={pointerId:t.id,pointerType:"xr"};this._xrSessionManager.runInXRFrame(()=>{this._augmentPointerInit(e,t.id,t.screenCoordinates),this._scene.simulatePointerUp(t.pick||new s4.p,e),t.finalPointerUpTriggered=!0})}this._xrSessionManager.scene.onBeforeRenderObservable.addOnce(()=>{try{if(t.selectionMesh.dispose(),t.laserPointer.dispose(),delete this._controllers[e],this._attachedController===e){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}catch(e){sg.w1.Warn("controller already detached.")}})}}_generateNewMeshPair(e){let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||hb.DefaultUtilityLayer.utilityLayerScene:this._scene,i=this._options.customLasterPointerMeshGenerator?this._options.customLasterPointerMeshGenerator():hE("laserPointer",{height:1,diameterTop:2e-4,diameterBottom:.004,tessellation:20,subdivisions:1},t);i.parent=e;let r=new lj("laserPointerMat",t);r.emissiveColor=this.laserPointerDefaultColor,r.alpha=.7,i.material=r,i.rotation.x=Math.PI/2,this._updatePointerDistance(i,1),i.isPickable=!1,i.isVisible=!1;let s=this._options.customSelectionMeshGenerator?this._options.customSelectionMeshGenerator():hi("gazeTracker",{diameter:.0105,thickness:.0075,tessellation:20},t);s.bakeCurrentTransformIntoVertices(),s.isPickable=!1,s.isVisible=!1;let n=new lj("targetMat",t);return n.specularColor=rm.Wo.Black(),n.emissiveColor=this.selectionMeshDefaultColor,n.backFaceCulling=!1,s.material=n,void 0!==this._options.renderingGroupId&&(i.renderingGroupId=this._options.renderingGroupId,s.renderingGroupId=this._options.renderingGroupId),{laserPointer:i,selectionMesh:s}}_pickingMoved(e,t){var i;if(!e.hit||!t.hit||!e.pickedMesh||!e.pickedPoint||!t.pickedMesh||!t.pickedPoint||e.pickedMesh!==t.pickedMesh)return!0;null===(i=e.pickedPoint)||void 0===i||i.subtractToRef(t.pickedPoint,this._tmpVectorForPickCompare),this._tmpVectorForPickCompare.set(Math.abs(this._tmpVectorForPickCompare.x),Math.abs(this._tmpVectorForPickCompare.y),Math.abs(this._tmpVectorForPickCompare.z));let r=.01*(this._options.gazeModePointerMovedFactor||1)*t.distance;return this._tmpVectorForPickCompare.length()>r}_updatePointerDistance(e,t=100){e.scaling.y=t,this._scene.useRightHandedSystem&&(t*=-1),e.position.z=t/2+.05}_augmentPointerInit(e,t,i){e.pointerId=t,e.pointerType="xr",i&&(e.screenX=i.x,e.screenY=i.y)}get lasterPointerDefaultColor(){return this.laserPointerDefaultColor}}p9._IdCounter=200,p9.Name=ni.POINTER_SELECTION,p9.Version=1,nr.AddWebXRFeature(p9.Name,(e,t)=>()=>new p9(e,t),p9.Version,!0);var _e=i(1091);_e.P.prototype._projectOnTrianglesToRef=function(e,t,i,r,s,n){let a=rf.jp.Vector3[0],o=rf.jp.Vector3[1],l=Infinity;for(let n=this.indexStart;n{if(this._controllers[e.uniqueId])return;let{touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r}=this._generateNewTouchPointMesh(),s=this._generateVisualCue();switch(this._controllers[e.uniqueId]={xrController:e,meshUnderPointer:null,nearInteractionTargetMesh:null,pick:null,stalePick:null,touchCollisionMesh:t,touchCollisionMeshFunction:i,hydrateCollisionMeshFunction:r,currentAnimationState:iA.DEHYDRATED,grabRay:new s6(new rf.P,new rf.P),hoverInteraction:!1,nearInteraction:!1,grabInteraction:!1,id:_t._IdCounter++,pickedPointVisualCue:s},this._attachedController?!this._options.enableNearInteractionOnAllControllers&&this._options.preferredHandedness&&e.inputSource.handedness===this._options.preferredHandedness&&(this._attachedController=e.uniqueId):this._options.enableNearInteractionOnAllControllers||(this._attachedController=e.uniqueId),e.inputSource.targetRayMode){case"tracked-pointer":return this._attachNearInteractionMode(e);case"gaze":case"screen":return null}},this._controllers={},this._farInteractionFeature=null,this.selectionMeshDefaultColor=new rm.Wo(.8,.8,.8),this.selectionMeshPickedColor=new rm.Wo(.3,.3,1),this._hoverRadius=.1,this._pickRadius=.02,this._controllerPickRadius=.03,this._nearGrabLengthScale=5,this._scene=this._xrSessionManager.scene,void 0===this._options.nearInteractionControllerMode&&(this._options.nearInteractionControllerMode=iR.CENTERED_IN_FRONT),this._options.farInteractionFeature&&(this._farInteractionFeature=this._options.farInteractionFeature)}attach(){return!!super.attach()&&(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._scene.constantlyUpdateMeshUnderPointer=!0,!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),!0)}getMeshUnderPointer(e){return this._controllers[e]?this._controllers[e].meshUnderPointer:null}getXRControllerByPointerId(e){let t=Object.keys(this._controllers);for(let i=0;ie.currentAnimationState)switch(e.currentAnimationState){case iA.DEHYDRATED:if(e.hydrateCollisionMeshFunction(!0),t===iA.HOVER)break;case iA.HOVER:e.touchCollisionMeshFunction(!0),iA.TOUCH}else switch(e.currentAnimationState){case iA.TOUCH:if(e.touchCollisionMeshFunction(!1),t===iA.HOVER)break;case iA.HOVER:e.hydrateCollisionMeshFunction(!1),iA.DEHYDRATED}e.currentAnimationState=t}}_processTouchPoint(e,t,i){var r;let s=this._controllers[e];s.grabRay.origin.copyFrom(t),i.toEulerAnglesToRef(rf.jp.Vector3[0]),s.grabRay.direction.copyFrom(rf.jp.Vector3[0]),this._options.nearInteractionControllerMode!==iR.CENTERED_IN_FRONT||(null===(r=s.xrController)||void 0===r?void 0:r.inputSource.hand)||(s.xrController.getWorldPointerRayToRef(this._tmpRay),s.grabRay.origin.addInPlace(this._tmpRay.direction.scale(.05))),s.grabRay.length=this._nearGrabLengthScale*this._hoverRadius,s.touchCollisionMesh.position.copyFrom(s.grabRay.origin)}_onXRFrame(e){Object.keys(this._controllers).forEach(t=>{var i;let r=this._controllers[t],s=null===(i=r.xrController)||void 0===i?void 0:i.inputSource.hand;if(!this._options.enableNearInteractionOnAllControllers&&t!==this._attachedController||!r.xrController||!s&&(!this._options.nearInteractionControllerMode||!r.xrController.inputSource.gamepad)){r.pick=null;return}if(r.hoverInteraction=!1,r.nearInteraction=!1,!r.xrController)return;if(s){let i=s.get("index-finger-tip");if(i){let r=e.getJointPose(i,this._xrSessionManager.referenceSpace);if(r&&r.transform){let e=this._scene.useRightHandedSystem?1:-1;rf.jp.Vector3[0].set(r.transform.position.x,r.transform.position.y,r.transform.position.z*e),rf.jp.Quaternion[0].set(r.transform.orientation.x,r.transform.orientation.y,r.transform.orientation.z*e,r.transform.orientation.w*e),this._processTouchPoint(t,rf.jp.Vector3[0],rf.jp.Quaternion[0])}}}else if(r.xrController.inputSource.gamepad&&this._options.nearInteractionControllerMode!==iR.DISABLED){let e=r.xrController.pointer;r.xrController.grip&&this._options.nearInteractionControllerMode===iR.CENTERED_ON_CONTROLLER&&(e=r.xrController.grip),this._processTouchPoint(t,e.position,e.rotationQuaternion)}let n=(e,t)=>t&&t.hit?e&&e.hit?t.distance{let t=new s4.p,i=!1,r=e&&e.pickedPoint&&e.hit;return(null==e?void 0:e.pickedPoint)&&(i=0===e.pickedPoint.x&&0===e.pickedPoint.y&&0===e.pickedPoint.z),r&&!i&&(t=e),t};if(!r.grabInteraction){let e=null,t=null;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,this._hoverRadius,this._utilityLayerScene,e=>this._nearInteractionPredicate(e)));let i=n(this._pickWithSphere(r,this._hoverRadius,this._scene,e=>this._nearInteractionPredicate(e)),t);if(i&&i.hit&&(e=a(i)).hit&&(r.hoverInteraction=!0),r.hoverInteraction){let t=null,i=s?this._pickRadius:this._controllerPickRadius;this._options.useUtilityLayer&&this._utilityLayerScene&&(t=this._pickWithSphere(r,i,this._utilityLayerScene,e=>this._nearPickPredicate(e)));let o=a(n(this._pickWithSphere(r,i,this._scene,e=>this._nearPickPredicate(e)),t));o.hit&&(e=o,r.nearInteraction=!0)}r.stalePick=r.pick,r.pick=e,r.pick&&r.pick.pickedPoint&&r.pick.hit?(r.meshUnderPointer=r.pick.pickedMesh,r.pickedPointVisualCue.position.copyFrom(r.pick.pickedPoint),r.pickedPointVisualCue.isVisible=!0,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!0)):(r.meshUnderPointer=null,r.pickedPointVisualCue.isVisible=!1,this._farInteractionFeature&&this._farInteractionFeature.attached&&this._farInteractionFeature._setPointerSelectionDisabledByPointerId(r.id,!1))}let o=iA.DEHYDRATED;r.grabInteraction||r.nearInteraction?o=iA.TOUCH:r.hoverInteraction&&(o=iA.HOVER),this._handleTransitionAnimation(r,o)})}get _utilityLayerScene(){return this._options.customUtilityLayerScene||hb.DefaultUtilityLayer.utilityLayerScene}_generateVisualCue(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||hb.DefaultUtilityLayer.utilityLayerScene:this._scene,t=hM("nearInteraction",{diameter:.0105},e);t.bakeCurrentTransformIntoVertices(),t.isPickable=!1,t.isVisible=!1,t.rotationQuaternion=rf._f.Identity();let i=new lj("targetMat",e);return i.specularColor=rm.Wo.Black(),i.emissiveColor=this.selectionMeshDefaultColor,i.backFaceCulling=!1,t.material=i,t}_isControllerReadyForNearInteraction(e){return!this._farInteractionFeature||this._farInteractionFeature._getPointerSelectionDisabledByPointerId(e)}_attachNearInteractionMode(e){let t=this._controllers[e.uniqueId],i={pointerId:t.id,pointerType:"xr-near"};t.onFrameObserver=this._xrSessionManager.onXRFrameObservable.add(()=>{(this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController)&&t.xrController&&(t.xrController.inputSource.hand||this._options.nearInteractionControllerMode&&t.xrController.inputSource.gamepad)&&(t.pick&&(t.pick.ray=t.grabRay),t.pick&&this._isControllerReadyForNearInteraction(t.id)&&this._scene.simulatePointerMove(t.pick,i),t.nearInteraction&&t.pick&&t.pick.hit?t.nearInteractionTargetMesh||(this._scene.simulatePointerDown(t.pick,i),t.nearInteractionTargetMesh=t.meshUnderPointer):t.nearInteractionTargetMesh&&t.stalePick&&(this._scene.simulatePointerUp(t.stalePick,i),t.nearInteractionTargetMesh=null))});let r=r=>{this._options.enableNearInteractionOnAllControllers||e.uniqueId===this._attachedController&&this._isControllerReadyForNearInteraction(t.id)?(t.pick&&(t.pick.ray=t.grabRay),r&&t.pick&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)?(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i)):!r&&t.pick&&t.grabInteraction&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)):!r||this._options.enableNearInteractionOnAllControllers||this._options.disableSwitchOnClick||(this._attachedController=e.uniqueId)};if(e.inputSource.gamepad){let i=e=>{t.squeezeComponent=e.getComponent("grasp"),t.squeezeComponent?t.onSqueezeButtonChangedObserver=t.squeezeComponent.onButtonStateChangedObservable.add(e=>{e.changes.pressed&&r(e.changes.pressed.current)}):(t.selectionComponent=e.getMainComponent(),t.onButtonChangedObserver=t.selectionComponent.onButtonStateChangedObservable.add(e=>{e.changes.pressed&&r(e.changes.pressed.current)}))};e.motionController?i(e.motionController):e.onMotionControllerInitObservable.add(i)}else{let e=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&t.meshUnderPointer&&this._nearGrabPredicate(t.meshUnderPointer)&&(t.grabInteraction=!0,t.pickedPointVisualCue.isVisible=!1,this._scene.simulatePointerDown(t.pick,i))},r=e=>{t.xrController&&e.inputSource===t.xrController.inputSource&&t.pick&&this._isControllerReadyForNearInteraction(t.id)&&(this._scene.simulatePointerUp(t.pick,i),t.grabInteraction=!1,t.pickedPointVisualCue.isVisible=!0)};t.eventListeners={selectend:r,selectstart:e},this._xrSessionManager.session.addEventListener("selectstart",e),this._xrSessionManager.session.addEventListener("selectend",r)}}_detachController(e){let t=this._controllers[e];if(t&&(t.squeezeComponent&&t.onSqueezeButtonChangedObserver&&t.squeezeComponent.onButtonStateChangedObservable.remove(t.onSqueezeButtonChangedObserver),t.selectionComponent&&t.onButtonChangedObserver&&t.selectionComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver),t.onFrameObserver&&this._xrSessionManager.onXRFrameObservable.remove(t.onFrameObserver),t.eventListeners&&Object.keys(t.eventListeners).forEach(e=>{let i=t.eventListeners&&t.eventListeners[e];i&&this._xrSessionManager.session.removeEventListener(e,i)}),t.touchCollisionMesh.dispose(),t.pickedPointVisualCue.dispose(),this._xrSessionManager.runInXRFrame(()=>{let e={pointerId:t.id,pointerType:"xr-near"};this._scene.simulatePointerUp(new s4.p,e)}),delete this._controllers[e],this._attachedController===e)){let e=Object.keys(this._controllers);e.length?this._attachedController=e[0]:this._attachedController=""}}_generateNewTouchPointMesh(){let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||hb.DefaultUtilityLayer.utilityLayerScene:this._scene,t=hM("PickSphere",{diameter:1},e);t.isVisible=!1,this._options.motionControllerOrbMaterial?t.material=this._options.motionControllerOrbMaterial:ac.ParseFromSnippetAsync("8RUNKL#3",e).then(e=>{t.material=e});let i=new sl;i.setEasingMode(ss.EASINGMODE_EASEINOUT);let r=new rf.P(this._controllerPickRadius,this._controllerPickRadius,this._controllerPickRadius),s=this._controllerPickRadius*(4/3),n=new rf.P(s,s,s),a=this._controllerPickRadius*(7/6),o=new rf.P(a,a,a),l=.8*this._controllerPickRadius,h=new rf.P(l,l,l),u=1.5*this._controllerPickRadius,c=[{frame:0,value:r},{frame:10,value:new rf.P(u,u,u)},{frame:18,value:n}],d=[{frame:0,value:n},{frame:10,value:h},{frame:18,value:r}],p=[{frame:0,value:rf.P.ZeroReadOnly},{frame:12,value:o},{frame:15,value:r}],_=[{frame:0,value:r},{frame:10,value:rf.P.ZeroReadOnly},{frame:15,value:rf.P.ZeroReadOnly}],f=new rJ("touch","scaling",60,rJ.ANIMATIONTYPE_VECTOR3,rJ.ANIMATIONLOOPMODE_CONSTANT),m=new rJ("release","scaling",60,rJ.ANIMATIONTYPE_VECTOR3,rJ.ANIMATIONLOOPMODE_CONSTANT),g=new rJ("hydrate","scaling",60,rJ.ANIMATIONTYPE_VECTOR3,rJ.ANIMATIONLOOPMODE_CONSTANT),v=new rJ("dehydrate","scaling",60,rJ.ANIMATIONTYPE_VECTOR3,rJ.ANIMATIONLOOPMODE_CONSTANT);return f.setEasingFunction(i),m.setEasingFunction(i),g.setEasingFunction(i),v.setEasingFunction(i),f.setKeys(c),m.setKeys(d),g.setKeys(p),v.setKeys(_),{touchCollisionMesh:t,touchCollisionMeshFunction:i=>{e.beginDirectAnimation(t,[i?f:m],0,18,!1,1)},hydrateCollisionMeshFunction:i=>{i&&(t.isVisible=!0),e.beginDirectAnimation(t,[i?g:v],0,15,!1,1,()=>{i||(t.isVisible=!1)})}}}_pickWithSphere(e,t,i,r){let s=new s4.p;if(s.distance=Infinity,e.touchCollisionMesh&&e.xrController){let n=e.touchCollisionMesh.position,a=hg.K.CreateFromCenterAndRadius(n,t);for(let t=0;ts&&(r=0,u.copyFrom(t.center)),-1!==r&&r()=>new _t(e,t),_t.Version,!0);class _i{constructor(e,t,i){this.element=e,this.sessionMode=t,this.referenceSpaceType=i}update(e){}}class _r{constructor(e,t){if(this._scene=e,this.options=t,this._activeButton=null,this._buttons=[],this.activeButtonChangedObservable=new r_.y$,this._onSessionGranted=e=>{this._helper&&this._enterXRWithButtonIndex(0)},this.overlay=document.createElement("div"),this.overlay.classList.add("xr-button-overlay"),!t.ignoreSessionGrantedEvent&&navigator.xr&&navigator.xr.addEventListener("sessiongranted",this._onSessionGranted),"undefined"!=typeof window&&window.location&&"http:"===window.location.protocol&&"localhost"!==window.location.hostname)throw sg.w1.Warn("WebXR can only be served over HTTPS"),Error("WebXR can only be served over HTTPS");if(t.customButtons)this._buttons=t.customButtons;else{this.overlay.style.cssText="z-index:11;position: absolute; right: 20px;bottom: 50px;";let e=t.sessionMode||"immersive-vr",i=t.referenceSpaceType||"local-floor",r=".babylonVRicon { color: #868686; border-color: #868686; border-style: solid; margin-left: 10px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url("+("undefined"==typeof SVGSVGElement?"https://cdn.babylonjs.com/Assets/vrButton.png":"data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";r+='.babylonVRicon.vrdisplaypresenting { background-image: none;} .vrdisplaypresenting::after { content: "EXIT"} .xr-error::after { content: "ERROR"}';let s=document.createElement("style");s.appendChild(document.createTextNode(r)),document.getElementsByTagName("head")[0].appendChild(s);let n=document.createElement("button");n.className="babylonVRicon",n.title=`${e} - ${i}`,this._buttons.push(new _i(n,e,i)),this._buttons[this._buttons.length-1].update=function(e){this.element.style.display=null===e||e===this?"":"none",n.className="babylonVRicon"+(e===this?" vrdisplaypresenting":"")},this._updateButtons(null)}let i=e.getEngine().getInputElement();i&&i.parentNode&&(i.parentNode.appendChild(this.overlay),e.onDisposeObservable.addOnce(()=>{this.dispose()}))}async setHelperAsync(e,t){this._helper=e,this._renderTarget=t;let i=this._buttons.map(t=>e.sessionManager.isSessionSupportedAsync(t.sessionMode));e.onStateChangedObservable.add(e=>{e==tw.NOT_IN_XR&&this._updateButtons(null)}),(await Promise.all(i)).forEach((e,t)=>{e?(this.overlay.appendChild(this._buttons[t].element),this._buttons[t].element.onclick=this._enterXRWithButtonIndex.bind(this,t)):sg.w1.Warn(`Session mode "${this._buttons[t].sessionMode}" not supported in browser`)})}static async CreateAsync(e,t,i){let r=new _r(e,i);return await r.setHelperAsync(t,i.renderTarget||void 0),r}async _enterXRWithButtonIndex(e=0){if(this._helper.state==tw.IN_XR)await this._helper.exitXRAsync(),this._updateButtons(null);else if(this._helper.state==tw.NOT_IN_XR)try{await this._helper.enterXRAsync(this._buttons[e].sessionMode,this._buttons[e].referenceSpaceType,this._renderTarget,{optionalFeatures:this.options.optionalFeatures,requiredFeatures:this.options.requiredFeatures}),this._updateButtons(this._buttons[e])}catch(r){this._updateButtons(null);let t=this._buttons[e].element,i=t.title;t.title="Error entering XR session : "+i,t.classList.add("xr-error"),this.options.onError&&this.options.onError(r)}}dispose(){let e=this._scene.getEngine().getInputElement();e&&e.parentNode&&e.parentNode.contains(this.overlay)&&e.parentNode.removeChild(this.overlay),this.activeButtonChangedObservable.clear(),navigator.xr.removeEventListener("sessiongranted",this._onSessionGranted)}_updateButtons(e){this._activeButton=e,this._buttons.forEach(e=>{e.update(this._activeButton)}),this.activeButtonChangedObservable.notifyObservers(this._activeButton)}}function _s(e){var t;let i=0,r=Date.now();e.observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{};let s=e.contextObservable.add(t=>{let n=Date.now();i=n-r;let a={startTime:r,currentTime:n,deltaTime:i,completeRate:i/e.timeout,payload:t};e.onTick&&e.onTick(a),e.breakCondition&&e.breakCondition()&&(e.contextObservable.remove(s),e.onAborted&&e.onAborted(a)),i>=e.timeout&&(e.contextObservable.remove(s),e.onEnded&&e.onEnded(a))},e.observableParameters.mask,e.observableParameters.insertFirst,e.observableParameters.scope);return s}(eP=iP||(iP={}))[eP.INIT=0]="INIT",eP[eP.STARTED=1]="STARTED",eP[eP.ENDED=2]="ENDED";class _n{constructor(e){var t,i;this.onEachCountObservable=new r_.y$,this.onTimerAbortedObservable=new r_.y$,this.onTimerEndedObservable=new r_.y$,this.onStateChangedObservable=new r_.y$,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{let t=Date.now();this._timer=t-this._startTime;let i={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},r=this._breakOnNextTick||this._breakCondition(i);r||this._timer>=this._timeToEnd?this._stop(i,r):this.onEachCountObservable.notifyObservers(i)},this._setState(iP.INIT),this._contextObservable=e.contextObservable,this._observableParameters=null!==(t=e.observableParameters)&&void 0!==t?t:{},this._breakCondition=null!==(i=e.breakCondition)&&void 0!==i?i:()=>!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(this._state===iP.STARTED)throw 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(iP.STARTED)}stop(){this._state===iP.STARTED&&(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(iP.ENDED),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class _a extends ns{get rotationEnabled(){return this._rotationEnabled}set rotationEnabled(e){if(this._rotationEnabled=e,this._options.teleportationTargetMesh){let t=this._options.teleportationTargetMesh.getChildMeshes(!1,e=>"rotationCone"===e.name);t[0]&&t[0].setEnabled(e)}}get teleportationTargetMesh(){return this._options.teleportationTargetMesh||null}constructor(e,t){super(e),this._options=t,this._controllers={},this._snappedToPoint=!1,this._cachedColor4White=new rm.HE(1,1,1,1),this._tmpRay=new s6(new rf.P,new rf.P),this._tmpVector=new rf.P,this._tmpQuaternion=new rf._f,this.skipNextTeleportation=!1,this.backwardsMovementEnabled=!0,this.backwardsTeleportationDistance=.7,this.parabolicCheckRadius=5,this.parabolicRayEnabled=!0,this.straightRayEnabled=!0,this.rotationAngle=Math.PI/8,this.onTargetMeshPositionUpdatedObservable=new r_.y$,this.teleportationEnabled=!0,this._rotationEnabled=!0,this.onBeforeCameraTeleportRotation=new r_.y$,this.onAfterCameraTeleportRotation=new r_.y$,this._attachController=e=>{if(this._controllers[e.uniqueId]||this._options.forceHandedness&&e.inputSource.handedness!==this._options.forceHandedness)return;this._controllers[e.uniqueId]={xrController:e,teleportationState:{forward:!1,backwards:!1,rotating:!1,currentRotation:0,baseRotation:0,blocked:!1}};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let i=()=>{if(e.motionController){let i=e.motionController.getComponentOfType(pJ.THUMBSTICK_TYPE)||e.motionController.getComponentOfType(pJ.TOUCHPAD_TYPE);if(!i||this._options.useMainComponentOnly){let i=e.motionController.getMainComponent();if(!i)return;t.teleportationComponent=i,t.onButtonChangedObserver=i.onButtonStateChangedObservable.add(()=>{this.teleportationEnabled&&i.changes.pressed&&(i.changes.pressed.current?(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,_s({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,breakCondition:()=>!i.pressed,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})):(t.teleportationState.forward=!1,this._currentTeleportationControllerId=""))})}else t.teleportationComponent=i,t.onAxisChangedObserver=i.onAxisValueChangedObservable.add(i=>{if(i.y<=.7&&t.teleportationState.backwards&&(t.teleportationState.backwards=!1),i.y>.7&&!t.teleportationState.forward&&this.backwardsMovementEnabled&&!this.snapPointsOnly&&!t.teleportationState.backwards){t.teleportationState.backwards=!0,this._tmpQuaternion.copyFrom(this._options.xrInput.xrCamera.rotationQuaternion),this._tmpQuaternion.toEulerAnglesToRef(this._tmpVector),this._tmpVector.x=0,this._tmpVector.z=0,rf._f.FromEulerVectorToRef(this._tmpVector,this._tmpQuaternion),this._tmpVector.set(0,0,this.backwardsTeleportationDistance*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),this._tmpVector.rotateByQuaternionToRef(this._tmpQuaternion,this._tmpVector),this._tmpVector.addInPlace(this._options.xrInput.xrCamera.position),this._tmpRay.origin.copyFrom(this._tmpVector),this._tmpRay.length=this._options.xrInput.xrCamera.realWorldHeight+.1,this._tmpRay.direction.set(0,-1,0);let e=this._xrSessionManager.scene.pickWithRay(this._tmpRay,e=>-1!==this._floorMeshes.indexOf(e));e&&e.pickedPoint&&(this._options.xrInput.xrCamera.position.x=e.pickedPoint.x,this._options.xrInput.xrCamera.position.z=e.pickedPoint.z)}if(i.y<-.7&&!this._currentTeleportationControllerId&&!t.teleportationState.rotating&&this.teleportationEnabled&&(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y),i.x){if(t.teleportationState.forward)this._currentTeleportationControllerId===t.xrController.uniqueId&&(this.rotationEnabled?setTimeout(()=>{t.teleportationState.currentRotation=Math.atan2(i.x,i.y*(this._xrSessionManager.scene.useRightHandedSystem?1:-1))}):t.teleportationState.currentRotation=0);else if(!t.teleportationState.rotating&&Math.abs(i.x)>.7){t.teleportationState.rotating=!0;let e=this.rotationAngle*(i.x>0?1:-1)*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this.onBeforeCameraTeleportRotation.notifyObservers(e),rf._f.FromEulerAngles(0,e,0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this.onAfterCameraTeleportRotation.notifyObservers(this._options.xrInput.xrCamera.rotationQuaternion)}}else t.teleportationState.rotating=!1;0===i.x&&0===i.y&&(t.teleportationState.blocked&&(t.teleportationState.blocked=!1,this._setTargetMeshVisibility(!1)),t.teleportationState.forward&&this._teleportForward(e.uniqueId))})}};e.motionController?i():e.onMotionControllerInitObservable.addOnce(()=>{i()})}else this._xrSessionManager.scene.onPointerObservable.add(i=>{i.type===s0.kD.POINTERDOWN?(t.teleportationState.forward=!0,this._currentTeleportationControllerId=t.xrController.uniqueId,t.teleportationState.baseRotation=this._options.xrInput.xrCamera.rotationQuaternion.toEulerAngles().y,t.teleportationState.currentRotation=0,_s({timeout:this._options.timeToTeleport||3e3,contextObservable:this._xrSessionManager.onXRFrameObservable,onEnded:()=>{this._currentTeleportationControllerId===t.xrController.uniqueId&&t.teleportationState.forward&&this._teleportForward(e.uniqueId)}})):i.type===s0.kD.POINTERUP&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="")})},this._options.teleportationTargetMesh||this._createDefaultTargetMesh(),this._floorMeshes=this._options.floorMeshes||[],this._snapToPositions=this._options.snapPositions||[],this._blockedRayColor=this._options.blockedRayColor||new rm.HE(1,0,0,.75),this._setTargetMeshVisibility(!1)}get snapPointsOnly(){return!!this._options.snapPointsOnly}set snapPointsOnly(e){this._options.snapPointsOnly=e}addFloorMesh(e){this._floorMeshes.push(e)}addBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[],this._options.pickBlockerMeshes.push(e)}addSnapPoint(e){this._snapToPositions.push(e)}attach(){return!!super.attach()&&(this._currentTeleportationControllerId="",this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._setTargetMeshVisibility(!1),this._currentTeleportationControllerId="",this._controllers={},!0)}dispose(){super.dispose(),this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.dispose(!1,!0)}removeFloorMesh(e){let t=this._floorMeshes.indexOf(e);-1!==t&&this._floorMeshes.splice(t,1)}removeBlockerMesh(e){this._options.pickBlockerMeshes=this._options.pickBlockerMeshes||[];let t=this._options.pickBlockerMeshes.indexOf(e);-1!==t&&this._options.pickBlockerMeshes.splice(t,1)}removeFloorMeshByName(e){let t=this._xrSessionManager.scene.getMeshByName(e);t&&this.removeFloorMesh(t)}removeSnapPoint(e){let t=this._snapToPositions.indexOf(e);if(-1===t){for(let i=0;i{if(this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e))return!0;let t=this._floorMeshes.indexOf(e);return -1!==t&&this._floorMeshes[t].absolutePosition.y!!this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(e)||-1!==this._floorMeshes.indexOf(e));if(n&&n.pickedMesh&&this._options.pickBlockerMeshes&&-1!==this._options.pickBlockerMeshes.indexOf(n.pickedMesh)){e.teleportationState.blocked=!0,this._setTargetMeshVisibility(!1),this._showParabolicPath(n);return}n&&n.pickedPoint&&(e.teleportationState.blocked=!1,t=!0,this._setTargetMeshPosition(n),this._setTargetMeshVisibility(!0),this._showParabolicPath(n))}this._setTargetMeshVisibility(t)}else this._setTargetMeshVisibility(!1)}else this._disposeBezierCurve(),this._setTargetMeshVisibility(!1)}_createDefaultTargetMesh(){this._options.defaultTargetMeshOptions=this._options.defaultTargetMeshOptions||{};let e=this._options.useUtilityLayer?this._options.customUtilityLayerScene||hb.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,t=he("teleportationTarget",{width:2,height:2,subdivisions:2},e);if(t.isPickable=!1,this._options.defaultTargetMeshOptions.teleportationCircleMaterial)t.material=this._options.defaultTargetMeshOptions.teleportationCircleMaterial;else{let i=new lq("teleportationPlaneDynamicTexture",512,e,!0);i.hasAlpha=!0;let r=i.getContext();r.beginPath(),r.arc(256,256,200,0,2*Math.PI,!1),r.fillStyle=this._options.defaultTargetMeshOptions.teleportationFillColor||"#444444",r.fill(),r.lineWidth=10,r.strokeStyle=this._options.defaultTargetMeshOptions.teleportationBorderColor||"#FFFFFF",r.stroke(),r.closePath(),i.update();let s=new lj("teleportationPlaneMaterial",e);s.diffuseTexture=i,t.material=s}let i=hi("torusTeleportation",{diameter:.75,thickness:.1,tessellation:20},e);if(i.isPickable=!1,i.parent=t,!this._options.defaultTargetMeshOptions.disableAnimation){let t=new rJ("animationInnerCircle","position.y",30,rJ.ANIMATIONTYPE_FLOAT,rJ.ANIMATIONLOOPMODE_CYCLE),r=[];r.push({frame:0,value:0}),r.push({frame:30,value:.4}),r.push({frame:60,value:0}),t.setKeys(r);let s=new sh;s.setEasingMode(ss.EASINGMODE_EASEINOUT),t.setEasingFunction(s),i.animations=[],i.animations.push(t),e.beginAnimation(i,0,60,!0)}let r=hE("rotationCone",{diameterTop:0,tessellation:4},e);if(r.isPickable=!1,r.scaling.set(.5,.12,.2),r.rotate(r5.RD.X,Math.PI/2),r.position.z=.6,r.parent=i,this._options.defaultTargetMeshOptions.torusArrowMaterial)i.material=this._options.defaultTargetMeshOptions.torusArrowMaterial,r.material=this._options.defaultTargetMeshOptions.torusArrowMaterial;else{let t=new lj("torusConsMat",e);t.disableLighting=!!this._options.defaultTargetMeshOptions.disableLighting,t.disableLighting?t.emissiveColor=new rm.Wo(.3,.3,1):t.diffuseColor=new rm.Wo(.3,.3,1),t.alpha=.9,i.material=t,r.material=t,this._teleportationRingMaterial=t}void 0!==this._options.renderingGroupId&&(t.renderingGroupId=this._options.renderingGroupId,i.renderingGroupId=this._options.renderingGroupId,r.renderingGroupId=this._options.renderingGroupId),this._options.teleportationTargetMesh=t,this._setTargetMeshVisibility(!1)}_detachController(e){let t=this._controllers[e];t&&(t.teleportationComponent&&(t.onAxisChangedObserver&&t.teleportationComponent.onAxisValueChangedObservable.remove(t.onAxisChangedObserver),t.onButtonChangedObserver&&t.teleportationComponent.onButtonStateChangedObservable.remove(t.onButtonChangedObserver)),delete this._controllers[e])}_findClosestSnapPointWithRadius(e,t=this._options.snapToPositionRadius||.8){let i=null,r=Number.MAX_VALUE;if(this._snapToPositions.length){let s=t*t;this._snapToPositions.forEach(t=>{let n=rf.P.DistanceSquared(t,e);n<=s&&n{t.isVisible=e}),e?this._selectionFeature&&this._selectionFeature.detach():(this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null),this._selectionFeature&&this._selectionFeature.attach()))}_disposeBezierCurve(){this._quadraticBezierCurve&&(this._quadraticBezierCurve.dispose(),this._quadraticBezierCurve=null)}_showParabolicPath(e){if(!e.pickedPoint||!this._currentTeleportationControllerId)return;let t=this._options.useUtilityLayer?this._options.customUtilityLayerScene||hb.DefaultUtilityLayer.utilityLayerScene:this._xrSessionManager.scene,i=this._controllers[this._currentTeleportationControllerId],r=sr.CreateQuadraticBezier(i.xrController.pointer.absolutePosition,e.ray.origin,e.pickedPoint,25),s=i.teleportationState.blocked?this._blockedRayColor:void 0,n=Array(26).fill(s||this._cachedColor4White);this._options.generateRayPathMesh?this._quadraticBezierCurve=this._options.generateRayPathMesh(r.getPoints(),e):this._quadraticBezierCurve=hj("teleportation path line",{points:r.getPoints(),instance:this._quadraticBezierCurve,updatable:!0,colors:n},t),this._quadraticBezierCurve.isPickable=!1,void 0!==this._options.renderingGroupId&&(this._quadraticBezierCurve.renderingGroupId=this._options.renderingGroupId)}_teleportForward(e){let t=this._controllers[e];if(t&&t.teleportationState.forward&&this.teleportationEnabled&&(t.teleportationState.forward=!1,this._currentTeleportationControllerId="",!this.snapPointsOnly||this._snappedToPoint)){if(this.skipNextTeleportation){this.skipNextTeleportation=!1;return}if(this._options.teleportationTargetMesh&&this._options.teleportationTargetMesh.isVisible){let e=this._options.xrInput.xrCamera.realWorldHeight;this._options.xrInput.xrCamera.onBeforeCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position),this._options.xrInput.xrCamera.position.copyFrom(this._options.teleportationTargetMesh.position),this._options.xrInput.xrCamera.position.y+=e,rf._f.FromEulerAngles(0,t.teleportationState.currentRotation-(this._xrSessionManager.scene.useRightHandedSystem?Math.PI:0),0).multiplyToRef(this._options.xrInput.xrCamera.rotationQuaternion,this._options.xrInput.xrCamera.rotationQuaternion),this._options.xrInput.xrCamera.onAfterCameraTeleport.notifyObservers(this._options.xrInput.xrCamera.position)}}}}_a.Name=ni.TELEPORTATION,_a.Version=1,nr.AddWebXRFeature(_a.Name,(e,t)=>()=>new _a(e,t),_a.Version,!0);class _o{constructor(){}static CreateAsync(e,t={}){let i=new _o;if(e.onDisposeObservable.addOnce(()=>{i.dispose()}),!t.disableDefaultUI){let r=Object.assign({renderTarget:i.renderTarget},t.uiOptions||{});t.optionalFeatures&&("boolean"==typeof t.optionalFeatures?r.optionalFeatures=["hit-test","anchors","plane-detection","hand-tracking"]:r.optionalFeatures=t.optionalFeatures),i.enterExitUI=new _r(e,r)}return pZ.CreateAsync(e).then(e=>{if(i.baseExperience=e,t.ignoreNativeCameraTransformation&&(i.baseExperience.camera.compensateOnFirstFrame=!1),i.input=new p7(e.sessionManager,e.camera,Object.assign({controllerOptions:{renderingGroupId:t.renderingGroupId}},t.inputOptions||{})),!t.disablePointerSelection){let e=Object.assign(Object.assign({},t.pointerSelectionOptions),{xrInput:i.input,renderingGroupId:t.renderingGroupId});i.pointerSelection=i.baseExperience.featuresManager.enableFeature(p9.Name,t.useStablePlugins?"stable":"latest",e),t.disableTeleportation||(i.teleportation=i.baseExperience.featuresManager.enableFeature(_a.Name,t.useStablePlugins?"stable":"latest",Object.assign({floorMeshes:t.floorMeshes,xrInput:i.input,renderingGroupId:t.renderingGroupId},t.teleportationOptions)),i.teleportation.setSelectionFeature(i.pointerSelection))}return(t.disableNearInteraction||(i.nearInteraction=i.baseExperience.featuresManager.enableFeature(_t.Name,t.useStablePlugins?"stable":"latest",Object.assign({xrInput:i.input,farInteractionFeature:i.pointerSelection,renderingGroupId:t.renderingGroupId,useUtilityLayer:!0,enableNearInteractionOnAllControllers:!0},t.nearInteractionOptions))),i.renderTarget=i.baseExperience.sessionManager.getWebXRRenderTarget(t.outputCanvasOptions),t.disableDefaultUI)?void 0:i.enterExitUI.setHelperAsync(i.baseExperience,i.renderTarget)}).then(()=>i).catch(e=>(rb.Y.Error("Error initializing XR"),rb.Y.Error(e),i))}dispose(){this.baseExperience&&this.baseExperience.dispose(),this.input&&this.input.dispose(),this.enterExitUI&&this.enterExitUI.dispose(),this.renderTarget&&this.renderTarget.dispose()}}function _l(e){for(;e.firstChild;)e.removeChild(e.firstChild);e.srcObject=null,e.src="",e.removeAttribute("src")}r2.x.prototype.createDefaultLight=function(e=!1){if(e&&this.lights)for(let e=0;ee.isVisible&&e.isEnabled()),s=r.max.subtract(r.min),n=r.min.add(s.scale(.5)),a=1.5*s.length();if(isFinite(a)||(a=1,n.copyFromFloats(0,0,0)),e){let e=new a2("default camera",-(Math.PI/2),Math.PI/2,a,n,this);e.lowerRadiusLimit=.01*a,e.wheelPrecision=100/a,t=e}else{let e=new a0("default camera",new rf.P(n.x,n.y,-a),this);e.setTarget(n),t=e}t.minZ=.01*a,t.maxZ=1e3*a,t.speed=.2*a,this.activeCamera=t,i&&t.attachControl()}},r2.x.prototype.createDefaultCameraOrLight=function(e=!1,t=!1,i=!1){this.createDefaultLight(t),this.createDefaultCamera(e,t,i)},r2.x.prototype.createDefaultSkybox=function(e,t=!1,i=1e3,r=0,s=!0){if(!e)return rb.Y.Warn("Can not create default skybox without environment texture."),null;s&&e&&(this.environmentTexture=e);let n=hP("hdrSkyBox",{size:i},this);if(t){let t=new pF("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=sj.SKYBOX_MODE),t.microSurface=1-r,t.disableLighting=!0,t.twoSidedLighting=!0,n.material=t}else{let t=new lj("skyBox",this);t.backFaceCulling=!1,t.reflectionTexture=e.clone(),t.reflectionTexture&&(t.reflectionTexture.coordinatesMode=sj.SKYBOX_MODE),t.disableLighting=!0,n.material=t}return n.isPickable=!1,n.infiniteDistance=!0,n.ignoreCameraMaxZ=!0,n},r2.x.prototype.createDefaultEnvironment=function(e){return dU?new dU(e,this):null},r2.x.prototype.createDefaultVRExperience=function(e={}){return new hn(this,e)},r2.x.prototype.createDefaultXRExperienceAsync=function(e={}){return _o.CreateAsync(this,e).then(e=>e)};class _h extends sj{get onUserActionRequestedObservable(){return this._onUserActionRequestedObservable||(this._onUserActionRequestedObservable=new r_.y$),this._onUserActionRequestedObservable}_processError(e){this._errorFound=!0,this._onError?this._onError(null==e?void 0:e.message):rb.Y.Error(null==e?void 0:e.message)}_handlePlay(){this._errorFound=!1,this.video.play().catch(e=>{if((null==e?void 0:e.name)==="NotAllowedError"){if(this._onUserActionRequestedObservable&&this._onUserActionRequestedObservable.hasObservers()){this._onUserActionRequestedObservable.notifyObservers(this);return}if(!this.video.muted){rb.Y.Warn("Unable to autoplay a video with sound. Trying again with muted turned true"),this.video.muted=!0,this._errorFound=!1,this.video.play().catch(e=>{this._processError(e)});return}}this._processError(e)})}constructor(e,t,i,r=!1,s=!1,n=sj.TRILINEAR_SAMPLINGMODE,a={},o,l=5){var h;super(null,i,!r,s),this._externalTexture=null,this._onUserActionRequestedObservable=null,this._stillImageCaptured=!1,this._displayingPosterTexture=!1,this._frameId=-1,this._currentSrc=null,this._errorFound=!1,this.isVideo=!0,this._resizeInternalTexture=()=>{var e;null!=this._texture&&this._texture.dispose(),!this._getEngine().needPOTTextures||sg.w1.IsExponentOfTwo(this.video.videoWidth)&&sg.w1.IsExponentOfTwo(this.video.videoHeight)?(this.wrapU=sj.WRAP_ADDRESSMODE,this.wrapV=sj.WRAP_ADDRESSMODE):(this.wrapU=sj.CLAMP_ADDRESSMODE,this.wrapV=sj.CLAMP_ADDRESSMODE,this._generateMipMaps=!1),this._texture=this._getEngine().createDynamicTexture(this.video.videoWidth,this.video.videoHeight,this._generateMipMaps,this.samplingMode),this._texture.format=null!==(e=this._format)&&void 0!==e?e:5,this._frameId=-1,this._updateInternalTexture()},this._createInternalTexture=()=>{if(null!=this._texture){if(!this._displayingPosterTexture)return;this._displayingPosterTexture=!1}if(this.video.addEventListener("resize",this._resizeInternalTexture),this._resizeInternalTexture(),this.video.autoplay||this._settings.poster||this._settings.independentVideoSource)this._updateInternalTexture(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this);else{let e=this.video.onplaying,t=this.video.muted;this.video.muted=!0,this.video.onplaying=()=>{this.video.muted=t,this.video.onplaying=e,this._updateInternalTexture(),this._errorFound||this.video.pause(),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this)},this._handlePlay()}},this._reset=()=>{null!=this._texture&&(this._displayingPosterTexture||(this._texture.dispose(),this._texture=null))},this._updateInternalTexture=()=>{if(null==this._texture||this.video.readyState=this.video.HAVE_CURRENT_DATA;!this._settings.poster||this._settings.autoPlay&&u?u&&this._createInternalTexture():(this._texture=this._getEngine().createTexture(this._settings.poster,!1,!this.invertY,i),this._displayingPosterTexture=!0)}getClassName(){return"VideoTexture"}_getName(e){return e instanceof HTMLVideoElement?e.currentSrc:"object"==typeof e?e.toString():e}_getVideo(e){if(e.isNative)return e;if(e instanceof HTMLVideoElement)return sg.w1.SetCorsBehavior(e.currentSrc,e),e;let t=document.createElement("video");return"string"==typeof e?(sg.w1.SetCorsBehavior(e,t),t.src=e):(sg.w1.SetCorsBehavior(e[0],t),e.forEach(e=>{let i=document.createElement("source");i.src=e,t.appendChild(i)})),this.onDisposeObservable.addOnce(()=>{_l(t)}),t}_rebuild(){this.update()}update(){this.autoUpdateTexture&&this.updateTexture(!0)}updateTexture(e){!e||this.video.paused&&this._stillImageCaptured||(this._stillImageCaptured=!0,this._updateInternalTexture())}get externalTexture(){return this._externalTexture}updateURL(e){this.video.src=e,this._currentSrc=e}clone(){return new _h(this.name,this._currentSrc,this.getScene(),this._generateMipMaps,this.invertY,this.samplingMode,this._settings)}dispose(){var e;super.dispose(),this._currentSrc=null,this._onUserActionRequestedObservable&&(this._onUserActionRequestedObservable.clear(),this._onUserActionRequestedObservable=null),this.video.removeEventListener(this._createInternalTextureOnEvent,this._createInternalTexture),this._settings.independentVideoSource||(this.video.removeEventListener("paused",this._updateInternalTexture),this.video.removeEventListener("seeked",this._updateInternalTexture),this.video.removeEventListener("emptied",this._reset),this.video.removeEventListener("resize",this._resizeInternalTexture),this.video.pause()),null===(e=this._externalTexture)||void 0===e||e.dispose()}static CreateFromStreamAsync(e,t,i,r=!0){let s=e.getEngine().createVideoElement(i);return e.getEngine()._badOS&&(document.body.appendChild(s),s.style.transform="scale(0.0001, 0.0001)",s.style.opacity="0",s.style.position="fixed",s.style.bottom="0px",s.style.right="0px"),s.setAttribute("autoplay",""),s.setAttribute("muted","true"),s.setAttribute("playsinline",""),s.muted=!0,s.isNative||(void 0!==s.mozSrcObject?s.mozSrcObject=t:"object"==typeof s.srcObject?s.srcObject=t:s.src=window.URL&&window.URL.createObjectURL(t)),new Promise(t=>{let i=()=>{let n=new _h("video",s,e,!0,r,void 0,void 0,void 0,4);e.getEngine()._badOS&&n.onDisposeObservable.addOnce(()=>{s.remove()}),n.onDisposeObservable.addOnce(()=>{_l(s)}),t(n),s.removeEventListener("playing",i)};s.addEventListener("playing",i),s.play()})}static async CreateFromWebCamAsync(e,t,i=!1,r=!0){if(navigator.mediaDevices){let s=await navigator.mediaDevices.getUserMedia({video:t,audio:i}),n=await this.CreateFromStreamAsync(e,s,t,r);return n.onDisposeObservable.addOnce(()=>{s.getTracks().forEach(e=>{e.stop()})}),n}return Promise.reject("No support for userMedia on this device")}static CreateFromWebCam(e,t,i,r=!1,s=!0){this.CreateFromWebCamAsync(e,i,r,s).then(function(e){t&&t(e)}).catch(function(e){rb.Y.Error(e.name)})}}(0,sx.gn)([(0,rG.qC)("settings")],_h.prototype,"_settings",void 0),(0,sx.gn)([(0,rG.qC)("src")],_h.prototype,"_currentSrc",void 0),(0,sx.gn)([(0,rG.qC)()],_h.prototype,"isVideo",void 0),sj._CreateVideoTexture=(e,t,i,r=!1,s=!1,n=sj.TRILINEAR_SAMPLINGMODE,a={},o,l=5)=>new _h(e,t,i,r,s,n,a,o,l),(0,rg.H)("BABYLON.VideoTexture",_h);class _u extends dV{get videoTexture(){return this._texture}get videoMode(){return this.textureMode}set videoMode(e){this.textureMode=e}_initTexture(e,t,i){let r={loop:i.loop,autoPlay:i.autoPlay,autoUpdateTexture:!0,poster:i.poster},s=new _h((this.name||"videoDome")+"_texture",e,t,i.generateMipMaps,this._useDirectMapping,sj.TRILINEAR_SAMPLINGMODE,r);return i.clickToPlay&&(this._pointerObserver=t.onPointerObservable.add(e=>{var t;(null===(t=e.pickInfo)||void 0===t?void 0:t.pickedMesh)===this.mesh&&this._texture.video.play()},s0.kD.POINTERDOWN)),this._textureObserver=s.onLoadObservable.add(()=>{this.onLoadObservable.notifyObservers()}),s}dispose(e,t=!1){this._texture.onLoadObservable.remove(this._textureObserver),this._scene.onPointerObservable.remove(this._pointerObserver),super.dispose(e,t)}}_u.MODE_MONOSCOPIC=dV.MODE_MONOSCOPIC,_u.MODE_TOPBOTTOM=dV.MODE_TOPBOTTOM,_u.MODE_SIDEBYSIDE=dV.MODE_SIDEBYSIDE;let _c=`#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) +#include +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; +#endif +#ifdef VERTEXALPHA +varying vec4 vColor; +#endif +uniform vec4 glowColor;uniform float glowIntensity; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +vec4 finalColor=glowColor; +#ifdef DIFFUSE +vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); +#ifdef DIFFUSE_ISLINEAR +albedoTexture=toGammaSpace(albedoTexture); +#endif +#ifdef GLOW +finalColor.a*=albedoTexture.a; +#endif +#ifdef HIGHLIGHT +finalColor.a=albedoTexture.a; +#endif +#endif +#ifdef OPACITY +vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); +#ifdef OPACITYRGB +finalColor.a*=getLuminance(opacityMap.rgb); +#else +finalColor.a*=opacityMap.a; +#endif +finalColor.a*=opacityIntensity; +#endif +#ifdef VERTEXALPHA +finalColor.a*=vColor.a; +#endif +#ifdef ALPHATEST +if (finalColor.a +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +uniform mat4 viewProjection;varying vec4 vPosition; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#ifdef DIFFUSE +varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; +#endif +#ifdef OPACITY +varying vec2 vUVOpacity;uniform mat4 opacityMatrix; +#endif +#ifdef EMISSIVE +varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; +#endif +#ifdef VERTEXALPHA +attribute vec4 color;varying vec4 vColor; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef CUBEMAP +vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); +#else +vPosition=viewProjection*worldPos;gl_Position=vPosition; +#endif +#ifdef DIFFUSE +#ifdef DIFFUSEUV1 +vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef DIFFUSEUV2 +vUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef OPACITY +#ifdef OPACITYUV1 +vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef OPACITYUV2 +vUVOpacity=vec2(opacityMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef EMISSIVE +#ifdef EMISSIVEUV1 +vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef EMISSIVEUV2 +vUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#ifdef VERTEXALPHA +vColor=color; +#endif +#include +}`;nw.v.ShadersStore.glowMapGenerationVertexShader=_d;class _p{get camera(){return this._effectLayerOptions.camera}get renderingGroupId(){return this._effectLayerOptions.renderingGroupId}set renderingGroupId(e){this._effectLayerOptions.renderingGroupId=e}get mainTexture(){return this._mainTexture}setMaterialForRendering(e,t){if(this._mainTexture.setMaterialForRendering(e,t),Array.isArray(e))for(let i=0;i{if((i||0===t)&&e.subMeshes)for(let t=0;t{let s;this.onBeforeRenderMainTextureObservable.notifyObservers(this);let n=this._scene.getEngine();if(r.length){for(n.setColorWrite(!1),s=0;s{e.clear(this.neutralColor,!0,!0,!0)}),this._scene.getBoundingBoxRenderer){let e=this._scene.getBoundingBoxRenderer().enabled;this._mainTexture.onBeforeBindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=!this.disableBoundingBoxesFromEffectLayer&&e}),this._mainTexture.onAfterUnbindObservable.add(()=>{this._scene.getBoundingBoxRenderer().enabled=e})}}_addCustomEffectDefines(e){}_isReady(e,t,i){var r;let s=this._scene.getEngine(),n=e.getMesh(),a=null===(r=n._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[s.currentRenderPassId];if(a)return a.isReadyForSubMesh(n,e,t);let o=e.getMaterial();if(!o)return!1;if(this._useMeshMaterial(e.getRenderingMesh()))return o.isReadyForSubMesh(e.getMesh(),e,t);let l=[],h=[sm.o.PositionKind],u=!1,c=!1;if(o){let e=o.needAlphaTesting(),t=o.getAlphaTestTexture(),i=t&&t.hasAlpha&&(o.useAlphaFromDiffuseTexture||o._useAlphaFromAlbedoTexture);t&&(e||i)&&(l.push("#define DIFFUSE"),n.isVerticesDataPresent(sm.o.UV2Kind)&&1===t.coordinatesIndex?(l.push("#define DIFFUSEUV2"),c=!0):n.isVerticesDataPresent(sm.o.UVKind)&&(l.push("#define DIFFUSEUV1"),u=!0),e&&(l.push("#define ALPHATEST"),l.push("#define ALPHATESTVALUE 0.4")),t.gammaSpace||l.push("#define DIFFUSE_ISLINEAR"));let r=o.opacityTexture;r&&(l.push("#define OPACITY"),n.isVerticesDataPresent(sm.o.UV2Kind)&&1===r.coordinatesIndex?(l.push("#define OPACITYUV2"),c=!0):n.isVerticesDataPresent(sm.o.UVKind)&&(l.push("#define OPACITYUV1"),u=!0))}i&&(l.push("#define EMISSIVE"),n.isVerticesDataPresent(sm.o.UV2Kind)&&1===i.coordinatesIndex?(l.push("#define EMISSIVEUV2"),c=!0):n.isVerticesDataPresent(sm.o.UVKind)&&(l.push("#define EMISSIVEUV1"),u=!0),i.gammaSpace||l.push("#define EMISSIVE_ISLINEAR")),n.useVertexColors&&n.isVerticesDataPresent(sm.o.ColorKind)&&n.hasVertexAlpha&&o.transparencyMode!==nu.F.MATERIAL_OPAQUE&&(h.push(sm.o.ColorKind),l.push("#define VERTEXALPHA")),u&&(h.push(sm.o.UVKind),l.push("#define UV1")),c&&(h.push(sm.o.UV2Kind),l.push("#define UV2"));let d=new nF;if(n.useBones&&n.computeBonesUsingShaders){h.push(sm.o.MatricesIndicesKind),h.push(sm.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(h.push(sm.o.MatricesIndicesExtraKind),h.push(sm.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers);let e=n.skeleton;e&&e.isUsingTextureForMatrices?l.push("#define BONETEXTURE"):l.push("#define BonesPerMesh "+(e?e.bones.length+1:0)),n.numBoneInfluencers>0&&d.addCPUSkinningFallback(0,n)}else l.push("#define NUM_BONE_INFLUENCERS 0");let p=n.morphTargetManager,_=0;p&&p.numInfluencers>0&&(l.push("#define MORPHTARGETS"),_=p.numInfluencers,l.push("#define NUM_MORPH_INFLUENCERS "+_),p.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),nE.G.PrepareAttributesForMorphTargetsInfluencers(h,n,_)),t&&(l.push("#define INSTANCES"),nE.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),(0,lH.lK)(o,this._scene,l),this._addCustomEffectDefines(l);let f=e._getDrawWrapper(void 0,!0),m=f.defines,g=l.join("\n");if(m!==g){let e=["world","mBones","viewProjection","glowColor","morphTargetInfluences","boneTextureWidth","diffuseMatrix","emissiveMatrix","opacityMatrix","opacityIntensity","morphTargetTextureInfo","morphTargetTextureIndices","glowIntensity"];(0,lH.qx)(e),f.setEffect(this._engine.createEffect("glowMapGeneration",h,e,["diffuseSampler","emissiveSampler","opacitySampler","boneSampler","morphTargets"],g,d,void 0,void 0,{maxSimultaneousMorphTargets:_}),g)}return f.effect.isReady()}render(){for(let e=0;el._getWorldMatrixDeterminant()&&(c=c===nu.F.ClockWiseSideOrientation?nu.F.CounterClockWiseSideOrientation:nu.F.ClockWiseSideOrientation);let d=c===nu.F.ClockWiseSideOrientation;u.setState(s.backFaceCulling,s.zOffset,void 0,d,s.cullBackFaces,void 0,s.zOffsetUnits);let p=o._getInstancesRenderList(e._id,!!a);if(p.mustReturn||!this._shouldRenderMesh(o))return;let _=p.hardwareInstancedRendering[e._id]||o.hasThinInstances;if(this._setEmissiveTextureAndColor(o,e,s),this.onBeforeRenderMeshToEffect.notifyObservers(n),this._useMeshMaterial(o))o.render(e,t,a||void 0);else if(this._isReady(e,_,this._emissiveTextureAndColor.texture)){let i=null===(r=l._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===r?void 0:r[u.currentRenderPassId],n=e._getDrawWrapper();if(!n&&i&&(n=i._getDrawWrapper()),!n)return;let a=n.effect;if(u.enableEffect(n),_||o._bind(e,a,s.fillMode),i?i.bindForSubMesh(l.getWorldMatrix(),l,e):(a.setMatrix("viewProjection",h.getTransformMatrix()),a.setMatrix("world",l.getWorldMatrix()),a.setFloat4("glowColor",this._emissiveTextureAndColor.color.r,this._emissiveTextureAndColor.color.g,this._emissiveTextureAndColor.color.b,this._emissiveTextureAndColor.color.a)),!i){let e=s.needAlphaTesting(),i=s.getAlphaTestTexture(),r=i&&i.hasAlpha&&(s.useAlphaFromDiffuseTexture||s._useAlphaFromAlbedoTexture);if(i&&(e||r)){a.setTexture("diffuseSampler",i);let e=i.getTextureMatrix();e&&a.setMatrix("diffuseMatrix",e)}let n=s.opacityTexture;if(n){a.setTexture("opacitySampler",n),a.setFloat("opacityIntensity",n.level);let e=n.getTextureMatrix();e&&a.setMatrix("opacityMatrix",e)}if(this._emissiveTextureAndColor.texture&&(a.setTexture("emissiveSampler",this._emissiveTextureAndColor.texture),a.setMatrix("emissiveMatrix",this._emissiveTextureAndColor.texture.getTextureMatrix())),o.useBones&&o.computeBonesUsingShaders&&o.skeleton){let e=o.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(o);if(!t)return;a.setTexture("boneSampler",t),a.setFloat("boneTextureWidth",4*(e.bones.length+1))}else a.setMatrices("mBones",e.getTransformMatrices(o))}nE.G.BindMorphTargetParameters(o,a),o.morphTargetManager&&o.morphTargetManager.isUsingTextureForTargets&&o.morphTargetManager._bind(a),t&&u.setAlphaMode(s.alphaMode),a.setFloat("glowIntensity",this.getEffectIntensity(o)),(0,lH.an)(a,s,h)}o._processRendering(l,e,a,s.fillMode,p,_,(e,t)=>a.setMatrix("world",t))}else this._mainTexture.resetRefreshCounter();this.onAfterRenderMeshToEffect.notifyObservers(n)}_useMeshMaterial(e){return!1}_rebuild(){let e=this._vertexBuffers[sm.o.PositionKind];e&&e._rebuild(),this._generateIndexBuffer()}_disposeTextureAndPostProcesses(){this._mainTexture.dispose();for(let e=0;e-1&&this._scene.effectLayers.splice(t,1),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onBeforeRenderMainTextureObservable.clear(),this.onBeforeComposeObservable.clear(),this.onBeforeRenderMeshToEffect.clear(),this.onAfterRenderMeshToEffect.clear(),this.onAfterComposeObservable.clear(),this.onSizeChangedObservable.clear()}getClassName(){return"EffectLayer"}static Parse(e,t,i){return sg.w1.Instantiate(e.customType).Parse(e,t,i)}}_p._SceneComponentInitialization=e=>{throw(0,sM.S)("EffectLayerSceneComponent")},(0,sx.gn)([(0,rG.qC)()],_p.prototype,"name",void 0),(0,sx.gn)([(0,rG.XX)()],_p.prototype,"neutralColor",void 0),(0,sx.gn)([(0,rG.qC)()],_p.prototype,"isEnabled",void 0),(0,sx.gn)([(0,rG.VE)()],_p.prototype,"camera",null),(0,sx.gn)([(0,rG.qC)()],_p.prototype,"renderingGroupId",null),(0,sx.gn)([(0,rG.qC)()],_p.prototype,"disableBoundingBoxesFromEffectLayer",void 0),rd.p.AddParser(sN.l.NAME_EFFECTLAYER,(e,t,i,r)=>{if(e.effectLayers){i.effectLayers||(i.effectLayers=[]);for(let s=0;s{this.scene.addEffectLayer(e)})}removeFromContainer(e,t){e.effectLayers&&e.effectLayers.forEach(e=>{this.scene.removeEffectLayer(e),t&&e.dispose()})}dispose(){let e=this.scene.effectLayers;for(;e.length;)e[0].dispose()}_isReadyForMesh(e,t){let i=this._engine.currentRenderPassId;for(let r of this.scene.effectLayers){if(!r.hasMesh(e))continue;let s=r._mainTexture;for(let n of(this._engine.currentRenderPassId=s.renderPassId,e.subMeshes))if(!r.isReady(n,t))return this._engine.currentRenderPassId=i,!1}return this._engine.currentRenderPassId=i,!0}_renderMainTexture(e){this._renderEffects=!1,this._needStencil=!1;let t=!1,i=this.scene.effectLayers;if(i&&i.length>0){for(let r of(this._previousStencilState=this._engine.getStencilBuffer(),i))if(r.shouldRender()&&(!r.camera||r.camera.cameraRigMode===sC.V.RIG_MODE_NONE&&e===r.camera||r.camera.cameraRigMode!==sC.V.RIG_MODE_NONE&&r.camera._rigCameras.indexOf(e)>-1)){this._renderEffects=!0,this._needStencil=this._needStencil||r.needStencil();let e=r._mainTexture;e._shouldRender()&&(this.scene.incrementRenderId(),e.render(!1,!1),t=!0)}this.scene.incrementRenderId()}return t}_setStencil(){this._needStencil&&this._engine.setStencilBuffer(!0)}_setStencilBack(){this._needStencil&&this._engine.setStencilBuffer(this._previousStencilState)}_draw(e){if(this._renderEffects){this._engine.setDepthBuffer(!1);let t=this.scene.effectLayers;for(let i=0;i{let t=e._getComponent(sN.l.NAME_EFFECTLAYER);t||(t=new __(e),e._addComponent(t))};let _f=`varying vec2 vUV;uniform sampler2D textureSampler; +#ifdef EMISSIVE +uniform sampler2D textureSampler2; +#endif +uniform float offset; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef EMISSIVE +baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; +#else +baseColor.a=abs(offset-baseColor.a); +#ifdef STROKE +float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; +#endif +#endif +#if LDR +baseColor=clamp(baseColor,0.,1.0); +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.glowMapMergePixelShader=_f;let _m=`attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.glowMapMergeVertexShader=_m,rd.p.prototype.getGlowLayerByName=function(e){var t;for(let i=0;i<(null===(t=this.effectLayers)||void 0===t?void 0:t.length);i++)if(this.effectLayers[i].name===e&&this.effectLayers[i].getEffectName()===_g.EffectName)return this.effectLayers[i];return null};class _g extends _p{set blurKernelSize(e){if(e===this._options.blurKernelSize)return;this._options.blurKernelSize=e;let t=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1.kernel=t,this._verticalBlurPostprocess1.kernel=t,this._horizontalBlurPostprocess2.kernel=t,this._verticalBlurPostprocess2.kernel=t}get blurKernelSize(){return this._options.blurKernelSize}set intensity(e){this._intensity=e}get intensity(){return this._intensity}constructor(e,t,i){super(e,t),this._intensity=1,this._includedOnlyMeshes=[],this._excludedMeshes=[],this._meshesUsingTheirOwnMaterials=[],this.neutralColor=new rm.HE(0,0,0,1),this._options=Object.assign({mainTextureRatio:_g.DefaultTextureRatio,blurKernelSize:32,mainTextureFixedSize:void 0,camera:null,mainTextureSamples:1,renderingGroupId:-1,ldrMerge:!1,alphaBlendingMode:1,mainTextureType:0,generateStencilBuffer:!1},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType,generateStencilBuffer:this._options.generateStencilBuffer})}getEffectName(){return _g.EffectName}_createMergeEffect(){let e="#define EMISSIVE \n";return this._options.ldrMerge&&(e+="#define LDR \n"),this._engine.createEffect("glowMapMerge",[sm.o.PositionKind],["offset"],["textureSampler","textureSampler2"],e)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width,t=this._mainTextureDesiredSize.height;e=this._engine.needPOTTextures?sR.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?sR.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture1=new as("GlowLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture1.wrapU=sj.CLAMP_ADDRESSMODE,this._blurTexture1.wrapV=sj.CLAMP_ADDRESSMODE,this._blurTexture1.updateSamplingMode(sj.BILINEAR_SAMPLINGMODE),this._blurTexture1.renderParticles=!1,this._blurTexture1.ignoreCameraViewport=!0;let r=Math.floor(e/2),s=Math.floor(t/2);this._blurTexture2=new as("GlowLayerBlurRTT2",{width:r,height:s},this._scene,!1,!0,i),this._blurTexture2.wrapU=sj.CLAMP_ADDRESSMODE,this._blurTexture2.wrapV=sj.CLAMP_ADDRESSMODE,this._blurTexture2.updateSamplingMode(sj.BILINEAR_SAMPLINGMODE),this._blurTexture2.renderParticles=!1,this._blurTexture2.ignoreCameraViewport=!0,this._textures=[this._blurTexture1,this._blurTexture2];let n=this._getEffectiveBlurKernelSize();this._horizontalBlurPostprocess1=new dP("GlowLayerHBP1",new rf.FM(1,0),n,{width:e,height:t},null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess1.width=e,this._horizontalBlurPostprocess1.height=t,this._horizontalBlurPostprocess1.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess1.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess1=new dP("GlowLayerVBP1",new rf.FM(0,1),n,{width:e,height:t},null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2=new dP("GlowLayerHBP2",new rf.FM(1,0),n,{width:r,height:s},null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess2.width=r,this._horizontalBlurPostprocess2.height=s,this._horizontalBlurPostprocess2.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess2.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._blurTexture1)}),this._verticalBlurPostprocess2=new dP("GlowLayerVBP2",new rf.FM(0,1),n,{width:r,height:s},null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1,this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._postProcesses1=[this._horizontalBlurPostprocess1,this._verticalBlurPostprocess1],this._postProcesses2=[this._horizontalBlurPostprocess2,this._verticalBlurPostprocess2],this._mainTexture.samples=this._options.mainTextureSamples,this._mainTexture.onAfterUnbindObservable.add(()=>{let e=this._blurTexture1.renderTarget;if(e){this._scene.postProcessManager.directRender(this._postProcesses1,e,!0);let t=this._blurTexture2.renderTarget;t&&this._scene.postProcessManager.directRender(this._postProcesses2,t,!0),this._engine.unBindFramebuffer(null!=t?t:e,!0)}}),this._postProcesses.map(e=>{e.autoClear=!1})}_getEffectiveBlurKernelSize(){return this._options.blurKernelSize/2}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r)return!1;let s=i.emissiveTexture;return super._isReady(e,t,s)}needStencil(){return!1}_canRenderMesh(e,t){return!0}_internalRender(e){e.setTexture("textureSampler",this._blurTexture1),e.setTexture("textureSampler2",this._blurTexture2),e.setFloat("offset",this._intensity);let t=this._engine,i=t.getStencilBuffer();t.setStencilBuffer(!1),t.drawElementsType(nu.F.TriangleFillMode,0,6),t.setStencilBuffer(i)}_setEmissiveTextureAndColor(e,t,i){var r;let s=1;this.customEmissiveTextureSelector?this._emissiveTextureAndColor.texture=this.customEmissiveTextureSelector(e,t,i):i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.texture&&(s=this._emissiveTextureAndColor.texture.level)):this._emissiveTextureAndColor.texture=null,this.customEmissiveColorSelector?this.customEmissiveColorSelector(e,t,i,this._emissiveTextureAndColor.color):i.emissiveColor?(s*=null!==(r=i.emissiveIntensity)&&void 0!==r?r:1,this._emissiveTextureAndColor.color.set(i.emissiveColor.r*s,i.emissiveColor.g*s,i.emissiveColor.b*s,i.alpha)):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a)}_shouldRenderMesh(e){return this.hasMesh(e)}_addCustomEffectDefines(e){e.push("#define GLOW")}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){let t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}addIncludedOnlyMesh(e){-1===this._includedOnlyMeshes.indexOf(e.uniqueId)&&this._includedOnlyMeshes.push(e.uniqueId)}removeIncludedOnlyMesh(e){let t=this._includedOnlyMeshes.indexOf(e.uniqueId);-1!==t&&this._includedOnlyMeshes.splice(t,1)}hasMesh(e){return!!super.hasMesh(e)&&(this._includedOnlyMeshes.length?-1!==this._includedOnlyMeshes.indexOf(e.uniqueId):!this._excludedMeshes.length||-1===this._excludedMeshes.indexOf(e.uniqueId))}_useMeshMaterial(e){return 0!=this._meshesUsingTheirOwnMaterials.length&&this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId)>-1}referenceMeshToUseItsOwnMaterial(e){e.resetDrawCache(this._mainTexture.renderPassId),this._meshesUsingTheirOwnMaterials.push(e.uniqueId),e.onDisposeObservable.add(()=>{this._disposeMesh(e)})}unReferenceMeshFromUsingItsOwnMaterial(e){let t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);for(;t>=0;)this._meshesUsingTheirOwnMaterials.splice(t,1),t=this._meshesUsingTheirOwnMaterials.indexOf(e.uniqueId);e.resetDrawCache(this._mainTexture.renderPassId)}_disposeMesh(e){this.removeIncludedOnlyMesh(e),this.removeExcludedMesh(e)}getClassName(){return"GlowLayer"}serialize(){let e;let t=rG.p4.Serialize(this);if(t.customType="BABYLON.GlowLayer",t.includedMeshes=[],this._includedOnlyMeshes.length)for(e=0;enew _g(e.name,t,e.options),e,t,i);for(r=0;r{e.setFloat2("screenSize",this.width,this.height),e.setVector2("direction",this.direction),e.setFloat("blurWidth",this.kernel)})}}class _T extends _p{set blurHorizontalSize(e){this._horizontalBlurPostprocess.kernel=e,this._options.blurHorizontalSize=e}set blurVerticalSize(e){this._verticalBlurPostprocess.kernel=e,this._options.blurVerticalSize=e}get blurHorizontalSize(){return this._horizontalBlurPostprocess.kernel}get blurVerticalSize(){return this._verticalBlurPostprocess.kernel}constructor(e,t,i){super(e,t),this.name=e,this.innerGlow=!0,this.outerGlow=!0,this.onBeforeBlurObservable=new r_.y$,this.onAfterBlurObservable=new r_.y$,this._instanceGlowingMeshStencilReference=_T.GlowingMeshStencilReference++,this._meshes={},this._excludedMeshes={},this.neutralColor=_T.NeutralColor,this._engine.isStencilEnable||rb.Y.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }"),this._options=Object.assign({mainTextureRatio:.5,blurTextureSizeRatio:.5,blurHorizontalSize:1,blurVerticalSize:1,alphaBlendingMode:2,camera:null,renderingGroupId:-1,mainTextureType:0},i),this._init({alphaBlendingMode:this._options.alphaBlendingMode,camera:this._options.camera,mainTextureFixedSize:this._options.mainTextureFixedSize,mainTextureRatio:this._options.mainTextureRatio,renderingGroupId:this._options.renderingGroupId,mainTextureType:this._options.mainTextureType}),this._shouldRender=!1}getEffectName(){return _T.EffectName}_numInternalDraws(){return 2}_createMergeEffect(){return this._engine.createEffect("glowMapMerge",[sm.o.PositionKind],["offset"],["textureSampler"],this._options.isStroke?"#define STROKE \n":void 0)}_createTextureAndPostProcesses(){let e=this._mainTextureDesiredSize.width*this._options.blurTextureSizeRatio,t=this._mainTextureDesiredSize.height*this._options.blurTextureSizeRatio;e=this._engine.needPOTTextures?sR.D.GetExponentOfTwo(e,this._maxSize):e,t=this._engine.needPOTTextures?sR.D.GetExponentOfTwo(t,this._maxSize):t;let i=0;i=this._engine.getCaps().textureHalfFloatRender?2:0,this._blurTexture=new as("HighlightLayerBlurRTT",{width:e,height:t},this._scene,!1,!0,i),this._blurTexture.wrapU=sj.CLAMP_ADDRESSMODE,this._blurTexture.wrapV=sj.CLAMP_ADDRESSMODE,this._blurTexture.anisotropicFilteringLevel=16,this._blurTexture.updateSamplingMode(sj.TRILINEAR_SAMPLINGMODE),this._blurTexture.renderParticles=!1,this._blurTexture.ignoreCameraViewport=!0,this._textures=[this._blurTexture],2===this._options.alphaBlendingMode?(this._downSamplePostprocess=new oa("HighlightLayerPPP",this._options.blurTextureSizeRatio,null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._downSamplePostprocess.externalTextureSamplerBinding=!0,this._downSamplePostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._horizontalBlurPostprocess=new _x("HighlightLayerHBP",new rf.FM(1,0),this._options.blurHorizontalSize,1,null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._horizontalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._verticalBlurPostprocess=new _x("HighlightLayerVBP",new rf.FM(0,1),this._options.blurVerticalSize,1,null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine()),this._verticalBlurPostprocess.onApplyObservable.add(i=>{i.setFloat2("screenSize",e,t)}),this._postProcesses=[this._downSamplePostprocess,this._horizontalBlurPostprocess,this._verticalBlurPostprocess]):(this._horizontalBlurPostprocess=new dP("HighlightLayerHBP",new rf.FM(1,0),this._options.blurHorizontalSize/2,{width:e,height:t},null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._horizontalBlurPostprocess.width=e,this._horizontalBlurPostprocess.height=t,this._horizontalBlurPostprocess.externalTextureSamplerBinding=!0,this._horizontalBlurPostprocess.onApplyObservable.add(e=>{e.setTexture("textureSampler",this._mainTexture)}),this._verticalBlurPostprocess=new dP("HighlightLayerVBP",new rf.FM(0,1),this._options.blurVerticalSize/2,{width:e,height:t},null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,i),this._postProcesses=[this._horizontalBlurPostprocess,this._verticalBlurPostprocess]),this._mainTexture.onAfterUnbindObservable.add(()=>{this.onBeforeBlurObservable.notifyObservers(this);let e=this._blurTexture.renderTarget;e&&(this._scene.postProcessManager.directRender(this._postProcesses,e,!0),this._engine.unBindFramebuffer(e,!0)),this.onAfterBlurObservable.notifyObservers(this)}),this._postProcesses.map(e=>{e.autoClear=!1})}needStencil(){return!0}isReady(e,t){let i=e.getMaterial(),r=e.getRenderingMesh();if(!i||!r||!this._meshes)return!1;let s=null,n=this._meshes[r.uniqueId];return n&&n.glowEmissiveOnly&&i&&(s=i.emissiveTexture),super._isReady(e,t,s)}_internalRender(e,t){e.setTexture("textureSampler",this._blurTexture);let i=this._engine;i.cacheStencilState(),i.setStencilOperationPass(7681),i.setStencilOperationFail(7680),i.setStencilOperationDepthFail(7680),i.setStencilMask(0),i.setStencilBuffer(!0),i.setStencilFunctionReference(this._instanceGlowingMeshStencilReference),this.outerGlow&&0===t&&(e.setFloat("offset",0),i.setStencilFunction(517),i.drawElementsType(nu.F.TriangleFillMode,0,6)),this.innerGlow&&1===t&&(e.setFloat("offset",1),i.setStencilFunction(514),i.drawElementsType(nu.F.TriangleFillMode,0,6)),i.restoreStencilState()}shouldRender(){return!!super.shouldRender()&&!!this._meshes}_shouldRenderMesh(e){return(!this._excludedMeshes||!this._excludedMeshes[e.uniqueId])&&!!super.hasMesh(e)}_canRenderMesh(e,t){return!0}_addCustomEffectDefines(e){e.push("#define HIGHLIGHT")}_setEmissiveTextureAndColor(e,t,i){let r=this._meshes[e.uniqueId];r?this._emissiveTextureAndColor.color.set(r.color.r,r.color.g,r.color.b,1):this._emissiveTextureAndColor.color.set(this.neutralColor.r,this.neutralColor.g,this.neutralColor.b,this.neutralColor.a),r&&r.glowEmissiveOnly&&i?(this._emissiveTextureAndColor.texture=i.emissiveTexture,this._emissiveTextureAndColor.color.set(1,1,1,1)):this._emissiveTextureAndColor.texture=null}addExcludedMesh(e){if(this._excludedMeshes&&!this._excludedMeshes[e.uniqueId]){let t={mesh:e,beforeBind:null,afterRender:null,stencilState:!1};t.beforeBind=e.onBeforeBindObservable.add(e=>{t.stencilState=e.getEngine().getStencilBuffer(),e.getEngine().setStencilBuffer(!1)}),t.afterRender=e.onAfterRenderObservable.add(e=>{e.getEngine().setStencilBuffer(t.stencilState)}),this._excludedMeshes[e.uniqueId]=t}}removeExcludedMesh(e){if(!this._excludedMeshes)return;let t=this._excludedMeshes[e.uniqueId];t&&(t.beforeBind&&e.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&e.onAfterRenderObservable.remove(t.afterRender)),this._excludedMeshes[e.uniqueId]=null}hasMesh(e){return!!(this._meshes&&super.hasMesh(e))&&void 0!==this._meshes[e.uniqueId]&&null!==this._meshes[e.uniqueId]}addMesh(e,t,i=!1){if(!this._meshes)return;let r=this._meshes[e.uniqueId];r?r.color=t:(this._meshes[e.uniqueId]={mesh:e,color:t,observerHighlight:e.onBeforeBindObservable.add(e=>{this.isEnabled&&(this._excludedMeshes&&this._excludedMeshes[e.uniqueId]?this._defaultStencilReference(e):e.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference))}),observerDefault:e.onAfterRenderObservable.add(e=>{this.isEnabled&&this._defaultStencilReference(e)}),glowEmissiveOnly:i},e.onDisposeObservable.add(()=>{this._disposeMesh(e)})),this._shouldRender=!0}removeMesh(e){if(!this._meshes)return;let t=this._meshes[e.uniqueId];for(let i in t&&(t.observerHighlight&&e.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&e.onAfterRenderObservable.remove(t.observerDefault),delete this._meshes[e.uniqueId]),this._shouldRender=!1,this._meshes)if(this._meshes[i]){this._shouldRender=!0;break}}removeAllMeshes(){if(this._meshes){for(let e in this._meshes)if(Object.prototype.hasOwnProperty.call(this._meshes,e)){let t=this._meshes[e];t&&this.removeMesh(t.mesh)}}}_defaultStencilReference(e){e.getScene().getEngine().setStencilFunctionReference(_T.NormalMeshStencilReference)}_disposeMesh(e){this.removeMesh(e),this.removeExcludedMesh(e)}dispose(){if(this._meshes){for(let e in this._meshes){let t=this._meshes[e];t&&t.mesh&&(t.observerHighlight&&t.mesh.onBeforeBindObservable.remove(t.observerHighlight),t.observerDefault&&t.mesh.onAfterRenderObservable.remove(t.observerDefault))}this._meshes=null}if(this._excludedMeshes){for(let e in this._excludedMeshes){let t=this._excludedMeshes[e];t&&(t.beforeBind&&t.mesh.onBeforeBindObservable.remove(t.beforeBind),t.afterRender&&t.mesh.onAfterRenderObservable.remove(t.afterRender))}this._excludedMeshes=null}super.dispose()}getClassName(){return"HighlightLayer"}serialize(){let e=rG.p4.Serialize(this);if(e.customType="BABYLON.HighlightLayer",e.meshes=[],this._meshes)for(let t in this._meshes){let i=this._meshes[t];i&&e.meshes.push({glowEmissiveOnly:i.glowEmissiveOnly,color:i.color.asArray(),meshId:i.mesh.id})}if(e.excludedMeshes=[],this._excludedMeshes)for(let t in this._excludedMeshes){let i=this._excludedMeshes[t];i&&e.excludedMeshes.push(i.mesh.id)}return e}static Parse(e,t,i){let r;let s=rG.p4.Parse(()=>new _T(e.name,t,e.options),e,t,i);for(r=0;r +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV); +#ifdef LINEAR +baseColor.rgb=toGammaSpace(baseColor.rgb); +#endif +#ifdef ALPHATEST +if (baseColor.a<0.4) +discard; +#endif +gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.layerPixelShader=_S;let _E=`attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.layerVertexShader=_E;class _C{static AddFlare(e,t,i,r,s){return new _C(e,t,i,r,s)}constructor(e,t,i,r,s){this.size=e,this.position=t,this.alphaMode=6,this.color=i||new rm.Wo(1,1,1),this.texture=r?new sj(r,s.getScene(),!0):null,this._system=s;let n=s.scene.getEngine();this._drawWrapper=new nk.q(n),this._drawWrapper.effect=n.createEffect("lensFlare",[sm.o.PositionKind],["color","viewportMatrix"],["textureSampler"],""),s.lensFlares.push(this)}dispose(){this.texture&&this.texture.dispose();let e=this._system.lensFlares.indexOf(this);this._system.lensFlares.splice(e,1)}}let _b=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec4 baseColor=texture2D(textureSampler,vUV);gl_FragColor=baseColor*color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.lensFlarePixelShader=_b;let _y=`attribute vec2 position;uniform mat4 viewportMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vUV=position*madd+madd;gl_Position=viewportMatrix*vec4(position,0.0,1.0); +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.lensFlareVertexShader=_y;class _A{get scene(){return this._scene}constructor(e,t,i){this.name=e,this.lensFlares=[],this.borderLimit=300,this.viewportBorder=0,this.layerMask=268435455,this._vertexBuffers={},this._isEnabled=!0,this._scene=i||rL.l.LastCreatedScene,_A._SceneComponentInitialization(this._scene),this._emitter=t,this.id=e,i.lensFlareSystems.push(this),this.meshesSelectionPredicate=e=>i.activeCamera&&e.material&&e.isVisible&&e.isEnabled()&&e.isBlocker&&(e.layerMask&i.activeCamera.layerMask)!=0;let r=i.getEngine(),s=[];s.push(1,1),s.push(-1,1),s.push(-1,-1),s.push(1,-1),this._vertexBuffers[sm.o.PositionKind]=new sm.o(r,s,sm.o.PositionKind,!1,!1,2),this._createIndexBuffer()}_createIndexBuffer(){let 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)}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled=e}getScene(){return this._scene}getEmitter(){return this._emitter}setEmitter(e){this._emitter=e}getEmitterPosition(){return this._emitter.getAbsolutePosition?this._emitter.getAbsolutePosition():this._emitter.position}computeEffectivePosition(e){let t=this.getEmitterPosition();t=rf.P.Project(t,rf.y3.Identity(),this._scene.getTransformMatrix(),e),this._positionX=t.x,this._positionY=t.y,t=rf.P.TransformCoordinates(this.getEmitterPosition(),this._scene.getViewMatrix()),this.viewportBorder>0&&(e.x-=this.viewportBorder,e.y-=this.viewportBorder,e.width+=2*this.viewportBorder,e.height+=2*this.viewportBorder,t.x+=this.viewportBorder,t.y+=this.viewportBorder,this._positionX+=this.viewportBorder,this._positionY+=this.viewportBorder);let i=this._scene.useRightHandedSystem;return(t.z>0&&!i||t.z<0&&!!i)&&(this._positionX>e.x&&this._positionXe.y&&(this._positionY,e.y,e.height),!0)}_isVisible(){if(!this._isEnabled||!this._scene.activeCamera)return!1;let e=this.getEmitterPosition().subtract(this._scene.activeCamera.globalPosition),t=e.length();e.normalize();let i=new s6(this._scene.activeCamera.globalPosition,e),r=this._scene.pickWithRay(i,this.meshesSelectionPredicate,!0);return!r||!r.hit||r.distance>t}render(){let e,t;if(!this._scene.activeCamera)return!1;let i=this._scene.getEngine(),r=this._scene.activeCamera.viewport.toGlobal(i.getRenderWidth(!0),i.getRenderHeight(!0));if(!this.computeEffectivePosition(r)||!this._isVisible())return!1;let s=(e=this._positionXr.x+r.width-this.borderLimit?this._positionX-r.x-r.width+this.borderLimit:0)>(t=this._positionYr.y+r.height-this.borderLimit?this._positionY-r.y-r.height+this.borderLimit:0)?e:t;(s-=this.viewportBorder)>this.borderLimit&&(s=this.borderLimit);let n=1-rk.R.Clamp(s/this.borderLimit,0,1);if(n<0)return!1;n>1&&(n=1),this.viewportBorder>0&&(r.x+=this.viewportBorder,r.y+=this.viewportBorder,r.width-=2*this.viewportBorder,r.height-=2*this.viewportBorder,this._positionX-=this.viewportBorder,this._positionY-=this.viewportBorder);let a=r.x+r.width/2,o=r.y+r.height/2,l=a-this._positionX,h=o-this._positionY;i.setState(!1),i.setDepthBuffer(!1);for(let e=0;e{throw(0,sM.S)("LensFlareSystemSceneComponent")},rd.p.AddParser(sN.l.NAME_LENSFLARESYSTEM,(e,t,i,r)=>{if(void 0!==e.lensFlareSystems&&null!==e.lensFlareSystems){i.lensFlareSystems||(i.lensFlareSystems=[]);for(let s=0,n=e.lensFlareSystems.length;s{this.scene.addLensFlareSystem(e)})}removeFromContainer(e,t){e.lensFlareSystems&&e.lensFlareSystems.forEach(e=>{this.scene.removeLensFlareSystem(e),t&&e.dispose()})}serialize(e){for(let t of(e.lensFlareSystems=[],this.scene.lensFlareSystems))e.lensFlareSystems.push(t.serialize())}dispose(){let e=this.scene.lensFlareSystems;for(;e.length;)e[0].dispose()}_draw(e){if(this.scene.lensFlaresEnabled){let t=this.scene.lensFlareSystems;for(let i of(sg.w1.StartPerformanceCounter("Lens flares",t.length>0),t))(e.layerMask&i.layerMask)!=0&&i.render();sg.w1.EndPerformanceCounter("Lens flares",t.length>0)}}}_A._SceneComponentInitialization=e=>{let t=e._getComponent(sN.l.NAME_LENSFLARESYSTEM);t||(t=new _R(e),e._addComponent(t))};let _P=`float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} +float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5*mod(_P,4.0)); +return 4.0*bayerDither2(P1)+bayerDither2(P2);} +float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); +vec2 P2=floor(0.5 *mod(_P,4.0)); +vec2 P4=floor(0.25*mod(_P,8.0)); +return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} +`;nw.v.IncludesShadersStore.bayerDitherFunctions=_P;let _I=`#if SM_FLOAT==0 +#include +#endif +#if SM_SOFTTRANSPARENTSHADOW==1 +#include +uniform float softTransparentShadowSM; +#endif +varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +uniform vec3 lightDataSM;varying vec3 vPositionWSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`;nw.v.IncludesShadersStore.shadowMapFragmentExtraDeclaration=_I;let _M=`float depthSM=vDepthMetricSM; +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +#if SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); +#else +gl_FragDepth=clamp(depthSM,0.0,1.0); +#endif +#elif SM_USEDISTANCE==1 +depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#if SM_ESM==1 +depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); +#endif +#if SM_FLOAT==1 +gl_FragColor=vec4(depthSM,1.0,1.0,1.0); +#else +gl_FragColor=pack(depthSM); +#endif +return;`;nw.v.IncludesShadersStore.shadowMapFragment=_M;let _D=`#include +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +#ifdef ALPHATEXTURE +float alphaFromAlphaTexture=texture2D(diffuseSampler,vUV).a; +#ifdef ALPHATESTVALUE +if (alphaFromAlphaTexture=softTransparentShadowSM*alphaFromAlphaTexture) discard; +#else +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM) discard; +#endif +#endif +#include +}`;nw.v.ShadersStore.shadowMapPixelShader=_D;let _O=`uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; +`;nw.v.IncludesShadersStore.sceneVertexDeclaration=_O;let _N=`uniform mat4 world;uniform float visibility; +`;nw.v.IncludesShadersStore.meshVertexDeclaration=_N;let _F=`#include +#include +`;nw.v.IncludesShadersStore.shadowMapVertexDeclaration=_F;let _L=`layout(std140,column_major) uniform; +#include +#include +`;nw.v.IncludesShadersStore.shadowMapUboDeclaration=_L;let _w=`#if SM_NORMALBIAS==1 +uniform vec3 lightDataSM; +#endif +uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; +#if SM_USEDISTANCE==1 +varying vec3 vPositionWSM; +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +varying float zSM; +#endif +`;nw.v.IncludesShadersStore.shadowMapVertexExtraDeclaration=_w;let _B=`#if SM_NORMALBIAS==1 +#if SM_DIRECTIONINLIGHTDATA==1 +vec3 worldLightDirSM=normalize(-lightDataSM.xyz); +#else +vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); +#endif +float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; +#endif +`;nw.v.IncludesShadersStore.shadowMapVertexNormalBias=_B;let _U=`#if SM_USEDISTANCE==1 +vPositionWSM=worldPos.xyz; +#endif +#if SM_DEPTHTEXTURE==1 +#ifdef IS_NDC_HALF_ZRANGE +#define BIASFACTOR 0.5 +#else +#define BIASFACTOR 1.0 +#endif +#ifdef USE_REVERSE_DEPTHBUFFER +gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#else +gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; +#endif +#endif +#if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 +zSM=gl_Position.z;gl_Position.z=0.0; +#elif SM_USEDISTANCE==0 +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#else +vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; +#endif +#endif +`;nw.v.IncludesShadersStore.shadowMapVertexMetric=_U;let _V=`attribute vec3 position; +#ifdef NORMAL +attribute vec3 normal; +#endif +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#ifdef INSTANCES +attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; +#endif +#include +#include<__decl__shadowMapVertex> +#ifdef ALPHATEXTURE +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#ifdef NORMAL +vec3 normalUpdated=normal; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#ifdef NORMAL +mat3 normWorldSM=mat3(finalWorld); +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vec3 vNormalW=normalize(normWorldSM*normalUpdated); +#endif +#endif +#include +gl_Position=viewProjection*worldPos; +#include +#ifdef ALPHATEXTURE +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include +}`;nw.v.ShadersStore.shadowMapVertexShader=_V;let _k=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) +for (int y=-OFFSET; y<=OFFSET; y++) +colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`;nw.v.ShadersStore.depthBoxBlurPixelShader=_k;let _G=`#if SM_SOFTTRANSPARENTSHADOW==1 +if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM*alpha) discard; +#endif +`;nw.v.IncludesShadersStore.shadowMapFragmentSoftTransparentShadow=_G;class _z{get bias(){return this._bias}set bias(e){this._bias=e}get normalBias(){return this._normalBias}set normalBias(e){this._normalBias=e}get blurBoxOffset(){return this._blurBoxOffset}set blurBoxOffset(e){this._blurBoxOffset!==e&&(this._blurBoxOffset=e,this._disposeBlurPostProcesses())}get blurScale(){return this._blurScale}set blurScale(e){this._blurScale!==e&&(this._blurScale=e,this._disposeBlurPostProcesses())}get blurKernel(){return this._blurKernel}set blurKernel(e){this._blurKernel!==e&&(this._blurKernel=e,this._disposeBlurPostProcesses())}get useKernelBlur(){return this._useKernelBlur}set useKernelBlur(e){this._useKernelBlur!==e&&(this._useKernelBlur=e,this._disposeBlurPostProcesses())}get depthScale(){return void 0!==this._depthScale?this._depthScale:this._light.getDepthScale()}set depthScale(e){this._depthScale=e}_validateFilter(e){return e}get filter(){return this._filter}set filter(e){if(e=this._validateFilter(e),this._light.needCube()){if(e===_z.FILTER_BLUREXPONENTIALSHADOWMAP){this.useExponentialShadowMap=!0;return}if(e===_z.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP){this.useCloseExponentialShadowMap=!0;return}if(e===_z.FILTER_PCF||e===_z.FILTER_PCSS){this.usePoissonSampling=!0;return}}if((e===_z.FILTER_PCF||e===_z.FILTER_PCSS)&&!this._scene.getEngine()._features.supportShadowSamplers){this.usePoissonSampling=!0;return}this._filter!==e&&(this._filter=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get usePoissonSampling(){return this.filter===_z.FILTER_POISSONSAMPLING}set usePoissonSampling(e){let t=this._validateFilter(_z.FILTER_POISSONSAMPLING);(e||this.filter===_z.FILTER_POISSONSAMPLING)&&(this.filter=e?t:_z.FILTER_NONE)}get useExponentialShadowMap(){return this.filter===_z.FILTER_EXPONENTIALSHADOWMAP}set useExponentialShadowMap(e){let t=this._validateFilter(_z.FILTER_EXPONENTIALSHADOWMAP);(e||this.filter===_z.FILTER_EXPONENTIALSHADOWMAP)&&(this.filter=e?t:_z.FILTER_NONE)}get useBlurExponentialShadowMap(){return this.filter===_z.FILTER_BLUREXPONENTIALSHADOWMAP}set useBlurExponentialShadowMap(e){let t=this._validateFilter(_z.FILTER_BLUREXPONENTIALSHADOWMAP);(e||this.filter===_z.FILTER_BLUREXPONENTIALSHADOWMAP)&&(this.filter=e?t:_z.FILTER_NONE)}get useCloseExponentialShadowMap(){return this.filter===_z.FILTER_CLOSEEXPONENTIALSHADOWMAP}set useCloseExponentialShadowMap(e){let t=this._validateFilter(_z.FILTER_CLOSEEXPONENTIALSHADOWMAP);(e||this.filter===_z.FILTER_CLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:_z.FILTER_NONE)}get useBlurCloseExponentialShadowMap(){return this.filter===_z.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP}set useBlurCloseExponentialShadowMap(e){let t=this._validateFilter(_z.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);(e||this.filter===_z.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP)&&(this.filter=e?t:_z.FILTER_NONE)}get usePercentageCloserFiltering(){return this.filter===_z.FILTER_PCF}set usePercentageCloserFiltering(e){let t=this._validateFilter(_z.FILTER_PCF);(e||this.filter===_z.FILTER_PCF)&&(this.filter=e?t:_z.FILTER_NONE)}get filteringQuality(){return this._filteringQuality}set filteringQuality(e){this._filteringQuality!==e&&(this._filteringQuality=e,this._disposeBlurPostProcesses(),this._applyFilterValues(),this._light._markMeshesAsLightDirty())}get useContactHardeningShadow(){return this.filter===_z.FILTER_PCSS}set useContactHardeningShadow(e){let t=this._validateFilter(_z.FILTER_PCSS);(e||this.filter===_z.FILTER_PCSS)&&(this.filter=e?t:_z.FILTER_NONE)}get contactHardeningLightSizeUVRatio(){return this._contactHardeningLightSizeUVRatio}set contactHardeningLightSizeUVRatio(e){this._contactHardeningLightSizeUVRatio=e}get darkness(){return this._darkness}set darkness(e){this.setDarkness(e)}getDarkness(){return this._darkness}setDarkness(e){return e>=1?this._darkness=1:e<=0?this._darkness=0:this._darkness=e,this}get transparencyShadow(){return this._transparencyShadow}set transparencyShadow(e){this.setTransparencyShadow(e)}setTransparencyShadow(e){return this._transparencyShadow=e,this}getShadowMap(){return this._shadowMap}getShadowMapForRendering(){return this._shadowMap2?this._shadowMap2:this._shadowMap}getClassName(){return _z.CLASSNAME}addShadowCaster(e,t=!0){if(!this._shadowMap)return this;if(this._shadowMap.renderList||(this._shadowMap.renderList=[]),-1===this._shadowMap.renderList.indexOf(e)&&this._shadowMap.renderList.push(e),t)for(let t of e.getChildMeshes())-1===this._shadowMap.renderList.indexOf(t)&&this._shadowMap.renderList.push(t);return this}removeShadowCaster(e,t=!0){if(!this._shadowMap||!this._shadowMap.renderList)return this;let i=this._shadowMap.renderList.indexOf(e);if(-1!==i&&this._shadowMap.renderList.splice(i,1),t)for(let t of e.getChildren())this.removeShadowCaster(t);return this}getLight(){return this._light}_getCamera(){var e;return null!==(e=this._camera)&&void 0!==e?e:this._scene.activeCamera}get mapSize(){return this._mapSize}set mapSize(e){this._mapSize=e,this._light._markMeshesAsLightDirty(),this.recreateShadowMap()}constructor(e,t,i,r,s){this.onBeforeShadowMapRenderObservable=new r_.y$,this.onAfterShadowMapRenderObservable=new r_.y$,this.onBeforeShadowMapRenderMeshObservable=new r_.y$,this.onAfterShadowMapRenderMeshObservable=new r_.y$,this._bias=5e-5,this._normalBias=0,this._blurBoxOffset=1,this._blurScale=2,this._blurKernel=1,this._useKernelBlur=!1,this._filter=_z.FILTER_NONE,this._filteringQuality=_z.QUALITY_HIGH,this._contactHardeningLightSizeUVRatio=.1,this._darkness=0,this._transparencyShadow=!1,this.enableSoftTransparentShadow=!1,this.useOpacityTextureForTransparentShadow=!1,this.frustumEdgeFalloff=0,this.forceBackFacesOnly=!1,this._lightDirection=rf.P.Zero(),this._viewMatrix=rf.y3.Zero(),this._projectionMatrix=rf.y3.Zero(),this._transformMatrix=rf.y3.Zero(),this._cachedPosition=new rf.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cachedDirection=new rf.P(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._currentFaceIndex=0,this._currentFaceIndexCache=0,this._defaultTextureMatrix=rf.y3.Identity(),this._mapSize=e,this._light=t,this._scene=t.getScene(),this._camera=null!=r?r:null,this._useRedTextureType=!!s;let n=t._shadowGenerators;n||(n=t._shadowGenerators=new Map),n.set(this._camera,this),this.id=t.id,this._useUBO=this._scene.getEngine().supportsUniformBuffers,this._useUBO&&(this._sceneUBOs=[],this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`))),_z._SceneComponentInitialization(this._scene);let a=this._scene.getEngine().getCaps();i?a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:this._textureType=0:a.textureHalfFloatRender&&a.textureHalfFloatLinearFiltering?this._textureType=2:a.textureFloatRender&&a.textureFloatLinearFiltering?this._textureType=1:this._textureType=0,this._initializeGenerator(),this._applyFilterValues()}_initializeGenerator(){this._light._markMeshesAsLightDirty(),this._initializeShadowMap()}_createTargetRenderTexture(){let e=this._scene.getEngine();e._features.supportDepthStencilTexture?(this._shadowMap=new as(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube(),void 0,!1,!1,void 0,this._useRedTextureType?6:5),this._shadowMap.createDepthStencilTexture(e.useReverseDepthBuffer?516:513,!0)):this._shadowMap=new as(this._light.name+"_shadowMap",this._mapSize,this._scene,!1,!0,this._textureType,this._light.needCube()),this._shadowMap.noPrePassRenderer=!0}_initializeShadowMap(){if(this._createTargetRenderTexture(),null===this._shadowMap)return;this._shadowMap.wrapU=sj.CLAMP_ADDRESSMODE,this._shadowMap.wrapV=sj.CLAMP_ADDRESSMODE,this._shadowMap.anisotropicFilteringLevel=1,this._shadowMap.updateSamplingMode(sj.BILINEAR_SAMPLINGMODE),this._shadowMap.renderParticles=!1,this._shadowMap.ignoreCameraViewport=!0,this._storedUniqueId&&(this._shadowMap.uniqueId=this._storedUniqueId),this._shadowMap.customRenderFunction=(e,t,i,r)=>this._renderForShadowMap(e,t,i,r),this._shadowMap.customIsReadyFunction=()=>!0;let e=this._scene.getEngine();this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`shadow map generation for pass id ${e.currentRenderPassId}`,1)}),this._shadowMap.onBeforeRenderObservable.add(t=>{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[0]),this._currentFaceIndex=t,this._filter===_z.FILTER_PCF&&e.setColorWrite(!1),this.getTransformMatrix(),this._scene.setTransformMatrix(this._viewMatrix,this._projectionMatrix),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onAfterUnbindObservable.add(()=>{var t,i;if(this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._currentSceneUBO),this._scene.updateTransformMatrix(),this._filter===_z.FILTER_PCF&&e.setColorWrite(!0),!this.useBlurExponentialShadowMap&&!this.useBlurCloseExponentialShadowMap){null===(t=e._debugPopGroup)||void 0===t||t.call(e,1);return}let r=this.getShadowMapForRendering();r&&(this._scene.postProcessManager.directRender(this._blurPostProcesses,r.renderTarget,!0),e.unBindFramebuffer(r.renderTarget,!0),null===(i=e._debugPopGroup)||void 0===i||i.call(e,1))});let t=new rm.HE(0,0,0,0),i=new rm.HE(1,1,1,1);this._shadowMap.onClearObservable.add(e=>{this._filter===_z.FILTER_PCF?e.clear(i,!1,!0,!1):this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e.clear(t,!0,!0,!1):e.clear(i,!0,!0,!1)}),this._shadowMap.onResizeObservable.add(e=>{this._storedUniqueId=this._shadowMap.uniqueId,this._mapSize=e.getRenderSize(),this._light._markMeshesAsLightDirty(),this.recreateShadowMap()});for(let e=n6.$.MIN_RENDERINGGROUPS;e{e.setTexture("textureSampler",this._shadowMap)}),this._kernelBlurYPostprocess=new dP(this._light.name+"KernelBlurY",new rf.FM(0,1),this.blurKernel,1,null,sj.BILINEAR_SAMPLINGMODE,e,!1,this._textureType),this._kernelBlurXPostprocess.autoClear=!1,this._kernelBlurYPostprocess.autoClear=!1,0===this._textureType&&(this._kernelBlurXPostprocess.packedFloat=!0,this._kernelBlurYPostprocess.packedFloat=!0),this._blurPostProcesses=[this._kernelBlurXPostprocess,this._kernelBlurYPostprocess]):(this._boxBlurPostprocess=new nz(this._light.name+"DepthBoxBlur","depthBoxBlur",["screenSize","boxOffset"],[],1,null,sj.BILINEAR_SAMPLINGMODE,e,!1,"#define OFFSET "+this._blurBoxOffset,this._textureType),this._boxBlurPostprocess.externalTextureSamplerBinding=!0,this._boxBlurPostprocess.onApplyObservable.add(e=>{e.setFloat2("screenSize",t,t),e.setTexture("textureSampler",this._shadowMap)}),this._boxBlurPostprocess.autoClear=!1,this._blurPostProcesses=[this._boxBlurPostprocess])}_renderForShadowMap(e,t,i,r){let s;if(r.length)for(s=0;sn._getWorldMatrixDeterminant(),u=null!==(i=s.overrideMaterialSideOrientation)&&void 0!==i?i:l.sideOrientation;h&&(u=0===u?1:0);let c=0===u;o.setState(l.backFaceCulling,void 0,void 0,c,l.cullBackFaces);let d=s._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(d.mustReturn)return;let p=o.getCaps().instancedArrays&&(null!==d.visibleInstances[e._id]&&void 0!==d.visibleInstances[e._id]||s.hasThinInstances);if(!this.customAllowRendering||this.customAllowRendering(e)){if(this.isReady(e,p,t)){e._renderId=a.getRenderId();let i=l.shadowDepthWrapper,h=null!==(r=null==i?void 0:i.getEffect(e,this,o.currentRenderPassId))&&void 0!==r?r:e._getDrawWrapper(),u=nk.q.GetEffect(h);o.enableEffect(h),p||s._bind(e,u,l.fillMode),this.getTransformMatrix(),u.setFloat3("biasAndScaleSM",this.bias,this.normalBias,this.depthScale),this.getLight().getTypeID()===sE.LIGHTTYPEID_DIRECTIONALLIGHT?u.setVector3("lightDataSM",this._cachedDirection):u.setVector3("lightDataSM",this._cachedPosition);let c=this._getCamera();if(c&&u.setFloat2("depthValuesSM",this.getLight().getDepthMinZ(c),this.getLight().getDepthMinZ(c)+this.getLight().getDepthMaxZ(c)),t&&this.enableSoftTransparentShadow&&u.setFloat("softTransparentShadowSM",n.visibility*l.alpha),i)e._setMainDrawWrapperOverride(h),i.standalone?i.baseMaterial.bindForSubMesh(n.getWorldMatrix(),s,e):l.bindForSubMesh(n.getWorldMatrix(),s,e),e._setMainDrawWrapperOverride(null);else{if(this._opacityTexture&&(u.setTexture("diffuseSampler",this._opacityTexture),u.setMatrix("diffuseMatrix",this._opacityTexture.getTextureMatrix()||this._defaultTextureMatrix)),s.useBones&&s.computeBonesUsingShaders&&s.skeleton){let e=s.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(s);if(!t)return;u.setTexture("boneSampler",t),u.setFloat("boneTextureWidth",4*(e.bones.length+1))}else u.setMatrices("mBones",e.getTransformMatrices(s))}nE.G.BindMorphTargetParameters(s,u),s.morphTargetManager&&s.morphTargetManager.isUsingTextureForTargets&&s.morphTargetManager._bind(u),(0,lH.an)(u,l,a)}this._useUBO||i||this._bindCustomEffectForRenderSubMeshForShadowMap(e,u,n),nE.G.BindSceneUniformBuffer(u,this._scene.getSceneUniformBuffer()),this._scene.getSceneUniformBuffer().bindUniformBuffer();let _=n.getWorldMatrix();p&&(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(_)),this.forceBackFacesOnly&&o.setState(!0,0,!1,!0,l.cullBackFaces),this.onBeforeShadowMapRenderMeshObservable.notifyObservers(s),this.onBeforeShadowMapRenderObservable.notifyObservers(u),s._processRendering(n,e,u,l.fillMode,d,p,(e,t)=>{n===s||e?(n.getMeshUniformBuffer().bindToEffect(u,"Mesh"),n.transferToEffect(e?t:_)):(s.getMeshUniformBuffer().bindToEffect(u,"Mesh"),s.transferToEffect(t))}),this.forceBackFacesOnly&&o.setState(!0,0,!1,!1,l.cullBackFaces),this.onAfterShadowMapRenderObservable.notifyObservers(u),this.onAfterShadowMapRenderMeshObservable.notifyObservers(s)}else this._shadowMap&&this._shadowMap.resetRefreshCounter()}}_applyFilterValues(){this._shadowMap&&(this.filter===_z.FILTER_NONE||this.filter===_z.FILTER_PCSS?this._shadowMap.updateSamplingMode(sj.NEAREST_SAMPLINGMODE):this._shadowMap.updateSamplingMode(sj.BILINEAR_SAMPLINGMODE))}forceCompilation(e,t){let i=Object.assign({useInstances:!1},t),r=this.getShadowMap();if(!r){e&&e(this);return}let s=r.renderList;if(!s){e&&e(this);return}let n=[];for(let e of s)n.push(...e.subMeshes);if(0===n.length){e&&e(this);return}let a=0,o=()=>{var t,r;if(this._scene&&this._scene.getEngine()){for(;this.isReady(n[a],i.useInstances,null!==(r=null===(t=n[a].getMaterial())||void 0===t?void 0:t.needAlphaBlendingForMesh(n[a].getMesh()))&&void 0!==r&&r);)if(++a>=n.length){e&&e(this);return}setTimeout(o,16)}};o()}forceCompilationAsync(e){return new Promise(t=>{this.forceCompilation(()=>{t()},e)})}_isReadyCustomDefines(e,t,i){}_prepareShadowDefines(e,t,i,r){i.push("#define SM_LIGHTTYPE_"+this._light.getClassName().toUpperCase()),i.push("#define SM_FLOAT "+(0!==this._textureType?"1":"0")),i.push("#define SM_ESM "+(this.useExponentialShadowMap||this.useBlurExponentialShadowMap?"1":"0")),i.push("#define SM_DEPTHTEXTURE "+(this.usePercentageCloserFiltering||this.useContactHardeningShadow?"1":"0"));let s=e.getMesh();return i.push("#define SM_NORMALBIAS "+(this.normalBias&&s.isVerticesDataPresent(sm.o.NormalKind)?"1":"0")),i.push("#define SM_DIRECTIONINLIGHTDATA "+(this.getLight().getTypeID()===sE.LIGHTTYPEID_DIRECTIONALLIGHT?"1":"0")),i.push("#define SM_USEDISTANCE "+(this._light.needCube()?"1":"0")),i.push("#define SM_SOFTTRANSPARENTSHADOW "+(this.enableSoftTransparentShadow&&r?"1":"0")),this._isReadyCustomDefines(i,e,t),i}isReady(e,t,i){var r;let s=e.getMaterial(),n=null==s?void 0:s.shadowDepthWrapper;if(this._opacityTexture=null,!s)return!1;let a=[];if(this._prepareShadowDefines(e,t,a,i),n){if(!n.isReadyForSubMesh(e,a,this,t,this._scene.getEngine().currentRenderPassId))return!1}else{let i=e._getDrawWrapper(void 0,!0),n=i.effect,o=i.defines,l=[sm.o.PositionKind],h=e.getMesh();this.normalBias&&h.isVerticesDataPresent(sm.o.NormalKind)&&(l.push(sm.o.NormalKind),a.push("#define NORMAL"),h.nonUniformScaling&&a.push("#define NONUNIFORMSCALING"));let u=s.needAlphaTesting();if((u||s.needAlphaBlending())&&(this.useOpacityTextureForTransparentShadow?this._opacityTexture=s.opacityTexture:this._opacityTexture=s.getAlphaTestTexture(),this._opacityTexture)){if(!this._opacityTexture.isReady())return!1;let e=null!==(r=s.alphaCutOff)&&void 0!==r?r:_z.DEFAULT_ALPHA_CUTOFF;a.push("#define ALPHATEXTURE"),u&&a.push(`#define ALPHATESTVALUE ${e}${e%1==0?".":""}`),h.isVerticesDataPresent(sm.o.UVKind)&&(l.push(sm.o.UVKind),a.push("#define UV1")),h.isVerticesDataPresent(sm.o.UV2Kind)&&1===this._opacityTexture.coordinatesIndex&&(l.push(sm.o.UV2Kind),a.push("#define UV2"))}let c=new nF;if(h.useBones&&h.computeBonesUsingShaders&&h.skeleton){l.push(sm.o.MatricesIndicesKind),l.push(sm.o.MatricesWeightsKind),h.numBoneInfluencers>4&&(l.push(sm.o.MatricesIndicesExtraKind),l.push(sm.o.MatricesWeightsExtraKind));let e=h.skeleton;a.push("#define NUM_BONE_INFLUENCERS "+h.numBoneInfluencers),h.numBoneInfluencers>0&&c.addCPUSkinningFallback(0,h),e.isUsingTextureForMatrices?a.push("#define BONETEXTURE"):a.push("#define BonesPerMesh "+(e.bones.length+1))}else a.push("#define NUM_BONE_INFLUENCERS 0");let d=h.morphTargetManager,p=0;if(d&&d.numInfluencers>0&&(a.push("#define MORPHTARGETS"),p=d.numInfluencers,a.push("#define NUM_MORPH_INFLUENCERS "+p),d.isUsingTextureForTargets&&a.push("#define MORPHTARGETS_TEXTURE"),nE.G.PrepareAttributesForMorphTargetsInfluencers(l,h,p)),(0,lH.lK)(s,this._scene,a),t&&(a.push("#define INSTANCES"),nE.G.PushAttributesForInstances(l),e.getRenderingMesh().hasThinInstances&&a.push("#define THIN_INSTANCES")),this.customShaderOptions&&this.customShaderOptions.defines)for(let e of this.customShaderOptions.defines)-1===a.indexOf(e)&&a.push(e);let _=a.join("\n");if(o!==_){o=_;let e="shadowMap",t=["world","mBones","viewProjection","diffuseMatrix","lightDataSM","depthValuesSM","biasAndScaleSM","morphTargetInfluences","boneTextureWidth","softTransparentShadowSM","morphTargetTextureInfo","morphTargetTextureIndices"],r=["diffuseSampler","boneSampler","morphTargets"];if((0,lH.qx)(t),this.customShaderOptions){if(e=this.customShaderOptions.shaderName,this.customShaderOptions.attributes)for(let e of this.customShaderOptions.attributes)-1===l.indexOf(e)&&l.push(e);if(this.customShaderOptions.uniforms)for(let e of this.customShaderOptions.uniforms)-1===t.indexOf(e)&&t.push(e);if(this.customShaderOptions.samplers)for(let e of this.customShaderOptions.samplers)-1===r.indexOf(e)&&r.push(e)}let s=this._scene.getEngine();n=s.createEffect(e,{attributes:l,uniformsNames:t,uniformBuffersNames:["Scene","Mesh"],samplers:r,defines:_,fallbacks:c,onCompiled:null,onError:null,indexParameters:{maxSimultaneousMorphTargets:p}},s),i.setEffect(n,o)}if(!n.isReady())return!1}return(this.useBlurExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(!this._blurPostProcesses||!this._blurPostProcesses.length)&&this._initializeBlurRTTAndPostProcesses(),(!this._kernelBlurXPostprocess||!!this._kernelBlurXPostprocess.isReady())&&(!this._kernelBlurYPostprocess||!!this._kernelBlurYPostprocess.isReady())&&(!this._boxBlurPostprocess||!!this._boxBlurPostprocess.isReady())}prepareDefines(e,t){let i=this._scene,r=this._light;i.shadowsEnabled&&r.shadowEnabled&&(e["SHADOW"+t]=!0,this.useContactHardeningShadow?(e["SHADOWPCSS"+t]=!0,this._filteringQuality===_z.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===_z.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePercentageCloserFiltering?(e["SHADOWPCF"+t]=!0,this._filteringQuality===_z.QUALITY_LOW?e["SHADOWLOWQUALITY"+t]=!0:this._filteringQuality===_z.QUALITY_MEDIUM&&(e["SHADOWMEDIUMQUALITY"+t]=!0)):this.usePoissonSampling?e["SHADOWPOISSON"+t]=!0:this.useExponentialShadowMap||this.useBlurExponentialShadowMap?e["SHADOWESM"+t]=!0:(this.useCloseExponentialShadowMap||this.useBlurCloseExponentialShadowMap)&&(e["SHADOWCLOSEESM"+t]=!0),r.needCube()&&(e["SHADOWCUBE"+t]=!0))}bindShadowLight(e,t){let i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;let r=this._getCamera();if(!r)return;let s=this.getShadowMap();s&&(i.needCube()||t.setMatrix("lightMatrix"+e,this.getTransformMatrix()),this._filter===_z.FILTER_PCF?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),s.getSize().width,1/s.getSize().width,this.frustumEdgeFalloff,e)):this._filter===_z.FILTER_PCSS?(t.setDepthStencilTexture("shadowSampler"+e,this.getShadowMapForRendering()),t.setTexture("depthSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),1/s.getSize().width,this._contactHardeningLightSizeUVRatio*s.getSize().width,this.frustumEdgeFalloff,e)):(t.setTexture("shadowSampler"+e,this.getShadowMapForRendering()),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),this.blurScale/s.getSize().width,this.depthScale,this.frustumEdgeFalloff,e)),i._uniformBuffer.updateFloat2("depthValues",this.getLight().getDepthMinZ(r),this.getLight().getDepthMinZ(r)+this.getLight().getDepthMaxZ(r),e))}get viewMatrix(){return this._viewMatrix}get projectionMatrix(){return this._projectionMatrix}getTransformMatrix(){let e=this._scene;if(this._currentRenderId===e.getRenderId()&&this._currentFaceIndexCache===this._currentFaceIndex)return this._transformMatrix;this._currentRenderId=e.getRenderId(),this._currentFaceIndexCache=this._currentFaceIndex;let t=this._light.position;if(this._light.computeTransformedInformation()&&(t=this._light.transformedPosition),rf.P.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex),this._lightDirection),1===Math.abs(rf.P.Dot(this._lightDirection,rf.P.Up()))&&(this._lightDirection.z=1e-13),this._light.needProjectionMatrixCompute()||!this._cachedPosition||!this._cachedDirection||!t.equals(this._cachedPosition)||!this._lightDirection.equals(this._cachedDirection)){this._cachedPosition.copyFrom(t),this._cachedDirection.copyFrom(this._lightDirection),rf.y3.LookAtLHToRef(t,t.add(this._lightDirection),rf.P.Up(),this._viewMatrix);let e=this.getShadowMap();if(e){let t=e.renderList;t&&this._light.setShadowProjectionMatrix(this._projectionMatrix,this._viewMatrix,t)}this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix)}return this._transformMatrix}recreateShadowMap(){let e=this._shadowMap;if(!e)return;let t=e.renderList;if(this._disposeRTTandPostProcesses(),this._initializeGenerator(),this.filter=this._filter,this._applyFilterValues(),t)for(let e of(this._shadowMap.renderList||(this._shadowMap.renderList=[]),t))this._shadowMap.renderList.push(e);else this._shadowMap.renderList=null}_disposeBlurPostProcesses(){this._shadowMap2&&(this._shadowMap2.dispose(),this._shadowMap2=null),this._boxBlurPostprocess&&(this._boxBlurPostprocess.dispose(),this._boxBlurPostprocess=null),this._kernelBlurXPostprocess&&(this._kernelBlurXPostprocess.dispose(),this._kernelBlurXPostprocess=null),this._kernelBlurYPostprocess&&(this._kernelBlurYPostprocess.dispose(),this._kernelBlurYPostprocess=null),this._blurPostProcesses=[]}_disposeRTTandPostProcesses(){this._shadowMap&&(this._shadowMap.dispose(),this._shadowMap=null),this._disposeBlurPostProcesses()}_disposeSceneUBOs(){if(this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}dispose(){if(this._disposeRTTandPostProcesses(),this._disposeSceneUBOs(),this._light){if(this._light._shadowGenerators){let e=this._light._shadowGenerators.entries();for(let t=e.next();!0!==t.done;t=e.next()){let[e,i]=t.value;i===this&&this._light._shadowGenerators.delete(e)}0===this._light._shadowGenerators.size&&(this._light._shadowGenerators=null)}this._light._markMeshesAsLightDirty()}this.onBeforeShadowMapRenderMeshObservable.clear(),this.onBeforeShadowMapRenderObservable.clear(),this.onAfterShadowMapRenderMeshObservable.clear(),this.onAfterShadowMapRenderObservable.clear()}serialize(){var e;let t={},i=this.getShadowMap();if(!i)return t;if(t.className=this.getClassName(),t.lightId=this._light.id,t.cameraId=null===(e=this._camera)||void 0===e?void 0:e.id,t.id=this.id,t.mapSize=i.getRenderSize(),t.forceBackFacesOnly=this.forceBackFacesOnly,t.darkness=this.getDarkness(),t.transparencyShadow=this._transparencyShadow,t.frustumEdgeFalloff=this.frustumEdgeFalloff,t.bias=this.bias,t.normalBias=this.normalBias,t.usePercentageCloserFiltering=this.usePercentageCloserFiltering,t.useContactHardeningShadow=this.useContactHardeningShadow,t.contactHardeningLightSizeUVRatio=this.contactHardeningLightSizeUVRatio,t.filteringQuality=this.filteringQuality,t.useExponentialShadowMap=this.useExponentialShadowMap,t.useBlurExponentialShadowMap=this.useBlurExponentialShadowMap,t.useCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.useBlurCloseExponentialShadowMap=this.useBlurExponentialShadowMap,t.usePoissonSampling=this.usePoissonSampling,t.depthScale=this.depthScale,t.blurBoxOffset=this.blurBoxOffset,t.blurKernel=this.blurKernel,t.blurScale=this.blurScale,t.useKernelBlur=this.useKernelBlur,t.renderList=[],i.renderList)for(let e=0;e{throw(0,sM.S)("ShadowGeneratorSceneComponent")};let _W=`#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +varying float vDepthMetric; +#ifdef PACKED +#include +#endif +#ifdef STORE_CAMERASPACE_Z +varying vec4 vViewPos; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#ifdef STORE_CAMERASPACE_Z +#ifdef PACKED +gl_FragColor=pack(vViewPos.z); +#else +gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); +#endif +#else +#ifdef NONLINEARDEPTH +#ifdef PACKED +gl_FragColor=pack(gl_FragCoord.z); +#else +gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); +#endif +#else +#ifdef PACKED +gl_FragColor=pack(vDepthMetric); +#else +gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); +#endif +#endif +#endif +}`;nw.v.ShadersStore.depthPixelShader=_W;let _H=`#ifdef POINTSIZE +uniform float pointSize; +#endif +`;nw.v.IncludesShadersStore.pointCloudVertexDeclaration=_H;let _X=`attribute vec3 position; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef STORE_CAMERASPACE_Z +uniform mat4 view;varying vec4 vViewPos; +#endif +#include +varying float vDepthMetric; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); +#include +gl_Position=viewProjection*worldPos; +#ifdef STORE_CAMERASPACE_Z +vViewPos=view*worldPos; +#else +#ifdef USE_REVERSE_DEPTHBUFFER +vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); +#else +vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); +#endif +#endif +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include +} +`;nw.v.ShadersStore.depthVertexShader=_X;class _Y{setMaterialForRendering(e,t){this._depthMap.setMaterialForRendering(e,t)}constructor(e,t=1,i=null,r=!1,s=sj.TRILINEAR_SAMPLINGMODE,n=!1,a){this.enabled=!0,this.forceDepthWriteTransparentMeshes=!1,this.useOnlyInActiveCamera=!1,this.reverseCulling=!1,this._scene=e,this._storeNonLinearDepth=r,this._storeCameraSpaceZ=n,this.isPacked=0===t,this.isPacked?this.clearColor=new rm.HE(1,1,1,1):this.clearColor=new rm.HE(n?1e8:1,0,0,1),_Y._SceneComponentInitialization(this._scene);let o=e.getEngine();this._camera=i,s===sj.NEAREST_SAMPLINGMODE||(1!==t||o._caps.textureFloatLinearFiltering||(s=sj.NEAREST_SAMPLINGMODE),2!==t||o._caps.textureHalfFloatLinearFiltering||(s=sj.NEAREST_SAMPLINGMODE));let l=this.isPacked||!o._features.supportExtendedTextureFormats?5:6;this._depthMap=new as(null!=a?a:"DepthRenderer",{width:o.getRenderWidth(),height:o.getRenderHeight()},this._scene,!1,!0,t,!1,s,void 0,void 0,void 0,l),this._depthMap.wrapU=sj.CLAMP_ADDRESSMODE,this._depthMap.wrapV=sj.CLAMP_ADDRESSMODE,this._depthMap.refreshRate=1,this._depthMap.renderParticles=!1,this._depthMap.renderList=null,this._depthMap.noPrePassRenderer=!0,this._depthMap.activeCamera=this._camera,this._depthMap.ignoreCameraViewport=!0,this._depthMap.useCameraPostProcesses=!1,this._depthMap.onClearObservable.add(e=>{e.clear(this.clearColor,!0,!0,!0)}),this._depthMap.onBeforeBindObservable.add(()=>{var e;null===(e=o._debugPushGroup)||void 0===e||e.call(o,"depth renderer",1)}),this._depthMap.onAfterUnbindObservable.add(()=>{var e;null===(e=o._debugPopGroup)||void 0===e||e.call(o,1)}),this._depthMap.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{var t,i;let r=e.getRenderingMesh(),s=e.getEffectiveMesh(),n=this._scene,a=n.getEngine(),o=e.getMaterial();if(s._internalAbstractMeshDataInfo._isActiveIntermediate=!1,!o||s.infiniteDistance||o.disableDepthWrite||0===e.verticesCount||e._renderId===n.getRenderId())return;let l=0>s._getWorldMatrixDeterminant(),h=null!==(t=r.overrideMaterialSideOrientation)&&void 0!==t?t:o.sideOrientation;l&&(h=0===h?1:0);let u=0===h;a.setState(o.backFaceCulling,0,!1,u,this.reverseCulling?!o.cullBackFaces:o.cullBackFaces);let c=r._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(c.mustReturn)return;let d=a.getCaps().instancedArrays&&(null!==c.visibleInstances[e._id]&&void 0!==c.visibleInstances[e._id]||r.hasThinInstances),p=this._camera||n.activeCamera;if(this.isReady(e,d)&&p){let t,l;e._renderId=n.getRenderId();let h=null===(i=s._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[a.currentRenderPassId],u=e._getDrawWrapper();!u&&h&&(u=h._getDrawWrapper());let _=p.mode===sC.V.ORTHOGRAPHIC_CAMERA;if(!u)return;let f=u.effect;if(a.enableEffect(u),d||r._bind(e,f,o.fillMode),h?h.bindForSubMesh(s.getWorldMatrix(),s,e):(f.setMatrix("viewProjection",n.getTransformMatrix()),f.setMatrix("world",s.getWorldMatrix()),this._storeCameraSpaceZ&&f.setMatrix("view",n.getViewMatrix())),_?(t=!a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:1):(t=a.useReverseDepthBuffer&&a.isNDCHalfZRange?p.minZ:a.isNDCHalfZRange?0:p.minZ,l=a.useReverseDepthBuffer&&a.isNDCHalfZRange?0:p.maxZ),f.setFloat2("depthValues",t,t+l),!h){if(o.needAlphaTesting()){let e=o.getAlphaTestTexture();e&&(f.setTexture("diffuseSampler",e),f.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(r.useBones&&r.computeBonesUsingShaders&&r.skeleton){let e=r.skeleton;if(e.isUsingTextureForMatrices){let t=e.getTransformMatrixTexture(r);if(!t)return;f.setTexture("boneSampler",t),f.setFloat("boneTextureWidth",4*(e.bones.length+1))}else f.setMatrices("mBones",e.getTransformMatrices(r))}(0,lH.an)(f,o,n),nE.G.BindMorphTargetParameters(r,f),r.morphTargetManager&&r.morphTargetManager.isUsingTextureForTargets&&r.morphTargetManager._bind(f),o.pointsCloud&&f.setFloat("pointSize",o.pointSize)}r._processRendering(s,e,f,o.fillMode,c,d,(e,t)=>f.setMatrix("world",t))}};this._depthMap.customRenderFunction=(e,t,i,r)=>{let s;if(r.length)for(s=0;s4&&(h.push(sm.o.MatricesIndicesExtraKind),h.push(sm.o.MatricesWeightsExtraKind)),l.push("#define NUM_BONE_INFLUENCERS "+s.numBoneInfluencers),l.push("#define BonesPerMesh "+(s.skeleton?s.skeleton.bones.length+1:0));let t=e.getRenderingMesh().skeleton;(null==t?void 0:t.isUsingTextureForMatrices)&&l.push("#define BONETEXTURE")}else l.push("#define NUM_BONE_INFLUENCERS 0");let u=s.morphTargetManager,c=0;u&&u.numInfluencers>0&&(c=u.numInfluencers,l.push("#define MORPHTARGETS"),l.push("#define NUM_MORPH_INFLUENCERS "+c),u.isUsingTextureForTargets&&l.push("#define MORPHTARGETS_TEXTURE"),nE.G.PrepareAttributesForMorphTargetsInfluencers(h,s,c)),o.pointsCloud&&l.push("#define POINTSIZE"),t&&(l.push("#define INSTANCES"),nE.G.PushAttributesForInstances(h),e.getRenderingMesh().hasThinInstances&&l.push("#define THIN_INSTANCES")),this._storeNonLinearDepth&&l.push("#define NONLINEARDEPTH"),this._storeCameraSpaceZ&&l.push("#define STORE_CAMERASPACE_Z"),this.isPacked&&l.push("#define PACKED"),(0,lH.lK)(o,n,l);let d=e._getDrawWrapper(void 0,!0),p=d.defines,_=l.join("\n");if(p!==_){let e=["world","mBones","boneTextureWidth","pointSize","viewProjection","view","diffuseMatrix","depthValues","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,lH.qx)(e),d.setEffect(r.createEffect("depth",h,e,["diffuseSampler","morphTargets","boneSampler"],_,void 0,void 0,void 0,{maxSimultaneousMorphTargets:c}),_)}return d.effect.isReady()}getDepthMap(){return this._depthMap}dispose(){let e=[];for(let t in this._scene._depthRenderer)this._scene._depthRenderer[t]===this&&e.push(t);if(e.length>0)for(let t of(this._depthMap.dispose(),e))delete this._scene._depthRenderer[t]}}_Y._SceneComponentInitialization=e=>{throw(0,sM.S)("DepthRendererSceneComponent")};let _j=`varying vec2 vUV;uniform sampler2D textureSampler; +#if defined(INITIAL) +uniform sampler2D sourceTexture;uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(sourceTexture,coord,0).r;float f2=texelFetch(sourceTexture,coord+ivec2(1,0),0).r;float f3=texelFetch(sourceTexture,coord+ivec2(1,1),0).r;float f4=texelFetch(sourceTexture,coord+ivec2(0,1),0).r;float minz=min(min(min(f1,f2),f3),f4); +#ifdef DEPTH_REDUX +float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); +#else +float maxz=max(max(max(f1,f2),f3),f4); +#endif +glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(MAIN) +uniform vec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(ONEBEFORELAST) +uniform ivec2 texSize;void main(void) +{ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(f1.x,f2.x);float maxz=max(f1.y,f2.y);glFragColor=vec4(minz,maxz,0.,0.);} +#elif defined(LAST) +void main(void) +{glFragColor=vec4(0.);if (true) { +discard;}} +#endif +`;nw.v.ShadersStore.minmaxReduxPixelShader=_j;class _q{constructor(e){this.onAfterReductionPerformed=new r_.y$,this._forceFullscreenViewport=!0,this._activated=!1,this._camera=e,this._postProcessManager=new n5.O(e.getScene()),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add(()=>{this._postProcessManager._rebuild()})}get sourceTexture(){return this._sourceTexture}setSourceTexture(e,t,i=2,r=!0){var s,n,a,o;if(e===this._sourceTexture)return;this.dispose(!1),this._sourceTexture=e,this._reductionSteps=[],this._forceFullscreenViewport=r;let l=this._camera.getScene(),h=new nz("Initial reduction phase","minmaxRedux",["texSize"],["sourceTexture"],1,null,1,l.getEngine(),!1,"#define INITIAL"+(t?"\n#define DEPTH_REDUX":""),i,void 0,void 0,void 0,7);h.autoClear=!1,h.forceFullscreenViewport=r;let u=this._sourceTexture.getRenderWidth(),c=this._sourceTexture.getRenderHeight();h.onApply=(s=u,n=c,e=>{e.setTexture("sourceTexture",this._sourceTexture),e.setFloat2("texSize",s,n)}),this._reductionSteps.push(h);let d=1;for(;u>1||c>1;){let e=new nz("Reduction phase "+d,"minmaxRedux",["texSize"],null,{width:u=Math.max(Math.round(u/2),1),height:c=Math.max(Math.round(c/2),1)},null,1,l.getEngine(),!1,"#define "+(1==u&&1==c?"LAST":1==u||1==c?"ONEBEFORELAST":"MAIN"),i,void 0,void 0,void 0,7);if(e.autoClear=!1,e.forceFullscreenViewport=r,e.onApply=(a=u,o=c,e=>{1==a||1==o?e.setInt2("texSize",a,o):e.setFloat2("texSize",a,o)}),this._reductionSteps.push(e),d++,1==u&&1==c){let t=(e,t,i)=>{let r=new Float32Array(4*e*t),s={min:0,max:0};return()=>{l.getEngine()._readTexturePixels(i.inputTexture.texture,e,t,-1,0,r,!1),s.min=r[0],s.max=r[1],this.onAfterReductionPerformed.notifyObservers(s)}};e.onAfterRenderObservable.add(t(u,c,e))}}}get refreshRate(){return this._sourceTexture?this._sourceTexture.refreshRate:-1}set refreshRate(e){this._sourceTexture&&(this._sourceTexture.refreshRate=e)}get activated(){return this._activated}activate(){!this._onAfterUnbindObserver&&this._sourceTexture&&(this._onAfterUnbindObserver=this._sourceTexture.onAfterUnbindObservable.add(()=>{var e,t;let i=this._camera.getScene().getEngine();null===(e=i._debugPushGroup)||void 0===e||e.call(i,"min max reduction",1),this._reductionSteps[0].activate(this._camera),this._postProcessManager.directRender(this._reductionSteps,this._reductionSteps[0].inputTexture,this._forceFullscreenViewport),i.unBindFramebuffer(this._reductionSteps[0].inputTexture,!1),null===(t=i._debugPopGroup)||void 0===t||t.call(i,1)}),this._activated=!0)}deactivate(){this._onAfterUnbindObserver&&this._sourceTexture&&(this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=null,this._activated=!1)}dispose(e=!0){if(e&&(this.onAfterReductionPerformed.clear(),this._onContextRestoredObserver&&(this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)),this.deactivate(),this._reductionSteps){for(let e=0;ethis._computeShadowCastersBoundingInfo())),this._freezeShadowCastersBoundingInfo=e,e&&this._computeShadowCastersBoundingInfo()}_computeShadowCastersBoundingInfo(){if(this._scbiMin.copyFromFloats(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._scbiMax.copyFromFloats(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),this._shadowMap&&this._shadowMap.renderList){let e=this._shadowMap.renderList;for(let t=0;tt&&(e=0,t=1),e<0&&(e=0),t>1&&(t=1),this._minDistance=e,this._maxDistance=t,this._breaksAreDirty=!0)}get minDistance(){return this._minDistance}get maxDistance(){return this._maxDistance}getClassName(){return _1.CLASSNAME}getCascadeMinExtents(e){return e>=0&&e=0&&et.maxZ&&0!==t.maxZ||(this._shadowMaxZ=e,this._light._markMeshesAsLightDirty(),this._breaksAreDirty=!0)}get debug(){return this._debug}set debug(e){this._debug=e,this._light._markMeshesAsLightDirty()}get depthClamp(){return this._depthClamp}set depthClamp(e){this._depthClamp=e}get cascadeBlendPercentage(){return this._cascadeBlendPercentage}set cascadeBlendPercentage(e){this._cascadeBlendPercentage=e,this._light._markMeshesAsLightDirty()}get lambda(){return this._lambda}set lambda(e){let t=Math.min(Math.max(e,0),1);this._lambda!=t&&(this._lambda=t,this._breaksAreDirty=!0)}getCascadeViewMatrix(e){return e>=0&&e=0&&e=0&&e{let t=e.min,i=e.max;t>=i&&(t=0,i=1),(t!=this._minDistance||i!=this._maxDistance)&&this.setMinMaxDistance(t,i)}),this._depthReducer.setDepthRenderer(this._depthRenderer)),this._depthReducer.activate()}}get autoCalcDepthBoundsRefreshRate(){var e,t,i;return null!==(i=null===(t=null===(e=this._depthReducer)||void 0===e?void 0:e.depthRenderer)||void 0===t?void 0:t.getDepthMap().refreshRate)&&void 0!==i?i:-1}set autoCalcDepthBoundsRefreshRate(e){var t;(null===(t=this._depthReducer)||void 0===t?void 0:t.depthRenderer)&&(this._depthReducer.depthRenderer.getDepthMap().refreshRate=e)}splitFrustum(){this._breaksAreDirty=!0}_splitFrustum(){let e=this._getCamera();if(!e)return;let t=e.minZ,i=e.maxZ||this._shadowMaxZ,r=i-t,s=this._minDistance,n=this._shadowMaxZ=t?Math.min((this._shadowMaxZ-t)/(i-t),this._maxDistance):this._maxDistance,a=t+s*r,o=t+n*r,l=o-a,h=o/a;for(let e=0;e{this._sceneUBOs&&this._scene.setSceneUniformBuffer(this._sceneUBOs[t]),this._currentLayer=t,this._filter===_z.FILTER_PCF&&e.setColorWrite(!1),this._scene.setTransformMatrix(this.getCascadeViewMatrix(t),this.getCascadeProjectionMatrix(t)),this._useUBO&&(this._scene.getSceneUniformBuffer().unbindEffect(),this._scene.finalizeSceneUbo())}),this._shadowMap.onBeforeBindObservable.add(()=>{var t;this._currentSceneUBO=this._scene.getSceneUniformBuffer(),null===(t=e._debugPushGroup)||void 0===t||t.call(e,`cascaded shadow map generation for pass id ${e.currentRenderPassId}`,1),this._breaksAreDirty&&this._splitFrustum(),this._computeMatrices()}),this._splitFrustum()}_bindCustomEffectForRenderSubMeshForShadowMap(e,t){t.setMatrix("viewProjection",this.getCascadeTransformMatrix(this._currentLayer))}_isReadyCustomDefines(e){e.push("#define SM_DEPTHCLAMP "+(this._depthClamp&&this._filter!==_z.FILTER_PCSS?"1":"0"))}prepareDefines(e,t){super.prepareDefines(e,t);let i=this._scene,r=this._light;if(!i.shadowsEnabled||!r.shadowEnabled)return;e["SHADOWCSM"+t]=!0,e["SHADOWCSMDEBUG"+t]=this.debug,e["SHADOWCSMNUM_CASCADES"+t]=this.numCascades,e["SHADOWCSM_RIGHTHANDED"+t]=i.useRightHandedSystem;let s=this._getCamera();s&&this._shadowMaxZ<=(s.maxZ||this._shadowMaxZ)&&(e["SHADOWCSMUSESHADOWMAXZ"+t]=!0),0===this.cascadeBlendPercentage&&(e["SHADOWCSMNOBLEND"+t]=!0)}bindShadowLight(e,t){let i=this._light;if(!this._scene.shadowsEnabled||!i.shadowEnabled)return;let r=this._getCamera();if(!r)return;let s=this.getShadowMap();if(!s)return;let n=s.getSize().width;if(t.setMatrices("lightMatrix"+e,this._transformMatricesAsArray),t.setArray("viewFrustumZ"+e,this._viewSpaceFrustumsZ),t.setFloat("cascadeBlendFactor"+e,0===this.cascadeBlendPercentage?1e4:1/this.cascadeBlendPercentage),t.setArray("frustumLengths"+e,this._frustumLengths),this._filter===_z.FILTER_PCF)t.setDepthStencilTexture("shadowSampler"+e,s),i._uniformBuffer.updateFloat4("shadowsInfo",this.getDarkness(),n,1/n,this.frustumEdgeFalloff,e);else if(this._filter===_z.FILTER_PCSS){for(let e=0;enew _1(e,t,void 0,i));return void 0!==e.numCascades&&(i.numCascades=e.numCascades),void 0!==e.debug&&(i.debug=e.debug),void 0!==e.stabilizeCascades&&(i.stabilizeCascades=e.stabilizeCascades),void 0!==e.lambda&&(i.lambda=e.lambda),void 0!==e.cascadeBlendPercentage&&(i.cascadeBlendPercentage=e.cascadeBlendPercentage),void 0!==e.depthClamp&&(i.depthClamp=e.depthClamp),void 0!==e.autoCalcDepthBounds&&(i.autoCalcDepthBounds=e.autoCalcDepthBounds),void 0!==e.shadowMaxZ&&(i.shadowMaxZ=e.shadowMaxZ),void 0!==e.penumbraDarkness&&(i.penumbraDarkness=e.penumbraDarkness),void 0!==e.freezeShadowCastersBoundingInfo&&(i.freezeShadowCastersBoundingInfo=e.freezeShadowCastersBoundingInfo),void 0!==e.minDistance&&void 0!==e.maxDistance&&i.setMinMaxDistance(e.minDistance,e.maxDistance),i}}_1._FrustumCornersNDCSpace=[new rf.P(-1,1,-1),new rf.P(1,1,-1),new rf.P(1,-1,-1),new rf.P(-1,-1,-1),new rf.P(-1,1,1),new rf.P(1,1,1),new rf.P(1,-1,1),new rf.P(-1,-1,1)],_1.CLASSNAME="CascadedShadowGenerator",_1.DEFAULT_CASCADES_COUNT=4,_1.MIN_CASCADES_COUNT=2,_1.MAX_CASCADES_COUNT=4,_1._SceneComponentInitialization=e=>{throw(0,sM.S)("ShadowGeneratorSceneComponent")},rd.p.AddParser(sN.l.NAME_SHADOWGENERATOR,(e,t)=>{if(void 0!==e.shadowGenerators&&null!==e.shadowGenerators)for(let i=0,r=e.shadowGenerators.length;i{let t=e._getComponent(sN.l.NAME_SHADOWGENERATOR);t||(t=new _2(e),e._addComponent(t))},rW.N.AddNodeConstructor("Light_Type_0",(e,t)=>()=>new _3(e,rf.P.Zero(),t));class _3 extends dg{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){let t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){let e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next())t.value.recreateShadowMap()}}constructor(e,t,i){super(e,i),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return sE.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new rf.P(1,0,0);case 1:return new rf.P(-1,0,0);case 2:return new rf.P(0,-1,0);case 3:return new rf.P(0,1,0);case 4:return new rf.P(0,0,1);case 5:return new rf.P(0,0,-1)}return rf.P.Zero()}_setDefaultShadowProjectionMatrix(e,t,i){let r=this.getScene().activeCamera;if(!r)return;let s=void 0!==this.shadowMinZ?this.shadowMinZ:r.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:r.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;rf.y3.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:s,a?s: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}}(0,sx.gn)([(0,rG.qC)()],_3.prototype,"shadowAngle",null);class _4{constructor(e,t="",i="black"){this._renderingCanvas=e,this._loadingText=t,this._loadingDivBackgroundColor=i,this._resizeLoadingUI=()=>{let e=this._renderingCanvas.getBoundingClientRect(),t=window.getComputedStyle(this._renderingCanvas).position;this._loadingDiv&&(this._loadingDiv.style.position="fixed"===t?"fixed":"absolute",this._loadingDiv.style.left=e.left+"px",this._loadingDiv.style.top=e.top+"px",this._loadingDiv.style.width=e.width+"px",this._loadingDiv.style.height=e.height+"px")}}displayLoadingUI(){if(this._loadingDiv)return;this._loadingDiv=document.createElement("div"),this._loadingDiv.id="babylonjsLoadingDiv",this._loadingDiv.style.opacity="0",this._loadingDiv.style.transition="opacity 1.5s ease",this._loadingDiv.style.pointerEvents="none",this._loadingDiv.style.display="grid",this._loadingDiv.style.gridTemplateRows="100%",this._loadingDiv.style.gridTemplateColumns="100%",this._loadingDiv.style.justifyItems="center",this._loadingDiv.style.alignItems="center",this._loadingTextDiv=document.createElement("div"),this._loadingTextDiv.style.position="absolute",this._loadingTextDiv.style.left="0",this._loadingTextDiv.style.top="50%",this._loadingTextDiv.style.marginTop="80px",this._loadingTextDiv.style.width="100%",this._loadingTextDiv.style.height="20px",this._loadingTextDiv.style.fontFamily="Arial",this._loadingTextDiv.style.fontSize="14px",this._loadingTextDiv.style.color="white",this._loadingTextDiv.style.textAlign="center",this._loadingTextDiv.style.zIndex="1",this._loadingTextDiv.innerHTML="Loading",this._loadingDiv.appendChild(this._loadingTextDiv),this._loadingTextDiv.innerHTML=this._loadingText,this._style=document.createElement("style"),this._style.type="text/css";let e=`@-webkit-keyframes spin1 {\ + 0% { -webkit-transform: rotate(0deg);} + 100% { -webkit-transform: rotate(360deg);} + }\ + @keyframes spin1 {\ + 0% { transform: rotate(0deg);} + 100% { transform: rotate(360deg);} + }`;this._style.innerHTML=e,document.getElementsByTagName("head")[0].appendChild(this._style);let t=!!window.SVGSVGElement,i=new Image;_4.DefaultLogoUrl?i.src=_4.DefaultLogoUrl:i.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+":"https://cdn.babylonjs.com/Assets/babylonLogo.png",i.style.width="150px",i.style.gridColumn="1",i.style.gridRow="1",i.style.top="50%",i.style.left="50%",i.style.transform="translate(-50%, -50%)",i.style.position="absolute";let r=document.createElement("div");r.style.width="300px",r.style.gridColumn="1",r.style.gridRow="1",r.style.top="50%",r.style.left="50%",r.style.transform="translate(-50%, -50%)",r.style.position="absolute";let s=new Image;if(_4.DefaultSpinnerUrl?s.src=_4.DefaultSpinnerUrl:s.src=t?"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==":"https://cdn.babylonjs.com/Assets/loadingIcon.png",s.style.animation="spin1 0.75s infinite linear",s.style.webkitAnimation="spin1 0.75s infinite linear",s.style.transformOrigin="50% 50%",s.style.webkitTransformOrigin="50% 50%",!t){let e={w:16,h:18.5},t={w:30,h:30};i.style.width=`${e.w}vh`,i.style.height=`${e.h}vh`,i.style.left=`calc(50% - ${e.w/2}vh)`,i.style.top=`calc(50% - ${e.h/2}vh)`,s.style.width=`${t.w}vh`,s.style.height=`${t.h}vh`,s.style.left=`calc(50% - ${t.w/2}vh)`,s.style.top=`calc(50% - ${t.h/2}vh)`}r.appendChild(s),this._loadingDiv.appendChild(i),this._loadingDiv.appendChild(r),this._resizeLoadingUI(),window.addEventListener("resize",this._resizeLoadingUI),this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor,document.body.appendChild(this._loadingDiv),this._loadingDiv.style.opacity="1"}hideLoadingUI(){this._loadingDiv&&(this._loadingDiv.style.opacity="0",this._loadingDiv.addEventListener("transitionend",()=>{this._loadingTextDiv&&(this._loadingTextDiv.remove(),this._loadingTextDiv=null),this._loadingDiv&&(this._loadingDiv.remove(),this._loadingDiv=null),this._style&&(this._style.remove(),this._style=null),window.removeEventListener("resize",this._resizeLoadingUI)}))}set loadingUIText(e){this._loadingText=e,this._loadingTextDiv&&(this._loadingTextDiv.innerHTML=this._loadingText)}get loadingUIText(){return this._loadingText}get loadingUIBackgroundColor(){return this._loadingDivBackgroundColor}set loadingUIBackgroundColor(e){this._loadingDivBackgroundColor=e,this._loadingDiv&&(this._loadingDiv.style.backgroundColor=this._loadingDivBackgroundColor)}}_4.DefaultLogoUrl="",_4.DefaultSpinnerUrl="",sR.D.DefaultLoadingScreenFactory=e=>new _4(e);var _5=i(1687),_6=i(5461);class _8{static ConvertPanoramaToCubemap(e,t,i,r,s=!1){if(!e)throw"ConvertPanoramaToCubemap: input cannot be null";if(e.length!=t*i*3)throw"ConvertPanoramaToCubemap: input size is wrong";let n=this.CreateCubemapTexture(r,this.FACE_FRONT,e,t,i,s),a=this.CreateCubemapTexture(r,this.FACE_BACK,e,t,i,s),o=this.CreateCubemapTexture(r,this.FACE_LEFT,e,t,i,s);return{front:n,back:a,left:o,right:this.CreateCubemapTexture(r,this.FACE_RIGHT,e,t,i,s),up:this.CreateCubemapTexture(r,this.FACE_UP,e,t,i,s),down:this.CreateCubemapTexture(r,this.FACE_DOWN,e,t,i,s),size:r,type:1,format:4,gammaSpace:!1}}static CreateCubemapTexture(e,t,i,r,s,n=!1){let a=new ArrayBuffer(e*e*12),o=new Float32Array(a),l=n?Math.max(1,Math.round(r/4/e)):1,h=1/l,u=h*h,c=t[1].subtract(t[0]).scale(h/e),d=t[3].subtract(t[2]).scale(h/e),p=1/e,_=0;for(let n=0;nMath.PI;)s-=2*Math.PI;let a=s/Math.PI,o=Math.round((a=.5*a+.5)*i);o<0?o=0:o>=i&&(o=i-1);let l=Math.round(n/Math.PI*r);l<0?l=0:l>=r&&(l=r-1);let h=r-l-1;return{r:t[h*i*3+3*o+0],g:t[h*i*3+3*o+1],b:t[h*i*3+3*o+2]}}}_8.FACE_LEFT=[new rf.P(-1,-1,-1),new rf.P(1,-1,-1),new rf.P(-1,1,-1),new rf.P(1,1,-1)],_8.FACE_RIGHT=[new rf.P(1,-1,1),new rf.P(-1,-1,1),new rf.P(1,1,1),new rf.P(-1,1,1)],_8.FACE_FRONT=[new rf.P(1,-1,-1),new rf.P(1,-1,1),new rf.P(1,1,-1),new rf.P(1,1,1)],_8.FACE_BACK=[new rf.P(-1,-1,1),new rf.P(-1,-1,-1),new rf.P(-1,1,1),new rf.P(-1,1,-1)],_8.FACE_DOWN=[new rf.P(1,1,-1),new rf.P(1,1,1),new rf.P(-1,1,-1),new rf.P(-1,1,1)],_8.FACE_UP=[new rf.P(-1,-1,-1),new rf.P(-1,-1,1),new rf.P(1,-1,-1),new rf.P(1,-1,1)];class _7{static _Ldexp(e,t){return t>1023?898846567431158e293*e*Math.pow(2,t-1023):t<-1074?5e-324*e*Math.pow(2,t+1074):e*Math.pow(2,t)}static _Rgbe2float(e,t,i,r,s,n){s>0?(s=this._Ldexp(1,s-136),e[n+0]=t*s,e[n+1]=i*s,e[n+2]=r*s):(e[n+0]=0,e[n+1]=0,e[n+2]=0)}static _ReadStringLine(e,t){let i="",r="";for(let s=t;s32767)throw"HDR Bad header format, unsupported size";return{height:t,width:i,dataPosition:a+=r.length+1}}static GetCubeMapTextureData(e,t,i=!1){let r=new Uint8Array(e),s=this.RGBE_ReadHeader(r),n=this.RGBE_ReadPixels(r,s);return _8.ConvertPanoramaToCubemap(n,s.width,s.height,t,i)}static RGBE_ReadPixels(e,t){return this._RGBEReadPixelsRLE(e,t)}static _RGBEReadPixelsRLE(e,t){let i,r,s,n,a,o=t.height,l=t.width,h=t.dataPosition,u=0,c=0,d=0,p=new ArrayBuffer(4*l),_=new Uint8Array(p),f=new ArrayBuffer(t.width*t.height*12),m=new Float32Array(f);for(;o>0;){if(i=e[h++],r=e[h++],s=e[h++],n=e[h++],2!=i||2!=r||128&s||t.width<8||t.width>32767)return this._RGBEReadPixelsNOTRLE(e,t);if((s<<8|n)!=l)throw"HDR Bad header format, wrong scan line width";for(d=0,u=0;d<4;d++)for(c=(d+1)*l;u128){if(0==(a=i-128)||a>c-u)throw"HDR Bad Format, bad scanline data (run)";for(;a-- >0;)_[u++]=r}else{if(0==(a=i)||a>c-u)throw"HDR Bad Format, bad scanline data (non-run)";if(_[u++]=r,--a>0)for(let t=0;t0;){for(a=0;a +#include +#include +#include +uniform float alphaG;uniform samplerCube inputTexture;uniform vec2 vFilteringInfo;uniform float hdrScale;varying vec3 direction;void main() {vec3 color=radiance(alphaG,inputTexture,direction,vFilteringInfo);gl_FragColor=vec4(color*hdrScale,1.0);}`;nw.v.ShadersStore.hdrFilteringPixelShader=fe;class ft{constructor(e,t={}){this._lodGenerationOffset=0,this._lodGenerationScale=.8,this.quality=4096,this.hdrScale=1,this._engine=e,this.hdrScale=t.hdrScale||this.hdrScale,this.quality=t.quality||this.quality}_createRenderTarget(e){let t=0;this._engine.getCaps().textureHalfFloatRender?t=2:this._engine.getCaps().textureFloatRender&&(t=1);let i=this._engine.createRenderTargetCubeTexture(e,{format:5,type:t,createMipMaps:!0,generateMipMaps:!1,generateDepthBuffer:!1,generateStencilBuffer:!1,samplingMode:1});return this._engine.updateTextureWrappingMode(i.texture,0,0,0),this._engine.updateTextureSamplingMode(3,i.texture,!0),i}_prefilterInternal(e){let t=e.getSize().width,i=rk.R.ILog2(t)+1,r=this._effectWrapper.effect,s=this._createRenderTarget(t);this._effectRenderer.saveStates(),this._effectRenderer.setViewport();let n=e.getInternalTexture();n&&this._engine.updateTextureSamplingMode(3,n,!0),this._effectRenderer.applyEffectWrapper(this._effectWrapper);let a=[[new rf.P(0,0,-1),new rf.P(0,-1,0),new rf.P(1,0,0)],[new rf.P(0,0,1),new rf.P(0,-1,0),new rf.P(-1,0,0)],[new rf.P(1,0,0),new rf.P(0,0,1),new rf.P(0,1,0)],[new rf.P(1,0,0),new rf.P(0,0,-1),new rf.P(0,-1,0)],[new rf.P(1,0,0),new rf.P(0,-1,0),new rf.P(0,0,1)],[new rf.P(-1,0,0),new rf.P(0,-1,0),new rf.P(0,0,-1)]];r.setFloat("hdrScale",this.hdrScale),r.setFloat2("vFilteringInfo",e.getSize().width,i),r.setTexture("inputTexture",e);for(let e=0;e<6;e++){r.setVector3("up",a[e][0]),r.setVector3("right",a[e][1]),r.setVector3("front",a[e][2]);for(let n=0;n{this._effectRenderer=new n7(this._engine),this._effectWrapper=this._createEffect(e),this._effectWrapper.effect.executeWhenCompiled(()=>{this._prefilterInternal(e),this._effectRenderer.dispose(),this._effectWrapper.dispose(),i(),t&&t()})}):(rb.Y.Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."),Promise.reject("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead."))}}class fi extends sV{set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(rf.y3.RotationY(this._rotationY))}get rotationY(){return this._rotationY}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;let t=this.getScene();t&&t.markAllMaterialsAsDirty(1)}get boundingBoxSize(){return this._boundingBoxSize}constructor(e,t,i,r=!1,s=!0,n=!1,a=!1,o=null,l=null,h=!1){var u;if(super(t),this._generateHarmonics=!0,this._onError=null,this._isBlocking=!0,this._rotationY=0,this.boundingBoxPosition=rf.P.Zero(),this.onLoadObservable=new r_.y$,!e)return;this._coordinatesMode=sj.CUBIC_MODE,this.name=e,this.url=e,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=rf.y3.Identity(),this._prefilterOnLoad=a,this._onLoad=()=>{this.onLoadObservable.notifyObservers(this),o&&o()},this._onError=l,this.gammaSpace=n,this._noMipmap=r,this._size=i,this._supersample=h,this._generateHarmonics=s,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?this._texture.isReady?sg.w1.SetImmediate(()=>this._onLoad()):this._texture.onLoadedObservable.add(this._onLoad):(null===(u=this.getScene())||void 0===u?void 0:u.useDelayedTextureLoading)?this.delayLoadState=4:this._loadTexture()}getClassName(){return"HDRCubeTexture"}_loadTexture(){let e=this._getEngine(),t=e.getCaps(),i=0;if(t.textureFloat&&t.textureFloatLinearFiltering?i=1:t.textureHalfFloat&&t.textureHalfFloatLinearFiltering&&(i=2),e._features.allowTexturePrefiltering&&this._prefilterOnLoad){let t=this._onLoad,i=new ft(e);this._onLoad=()=>{i.prefilter(this,t)}}this._texture=e.createRawCubeTextureFromUrl(this.url,this.getScene(),this._size,4,i,this._noMipmap,e=>{this.lodGenerationOffset=0,this.lodGenerationScale=.8;let t=_7.GetCubeMapTextureData(e,this._size,this._supersample);if(this._generateHarmonics){let e=uy.ConvertCubeMapToSphericalPolynomial(t);this.sphericalPolynomial=e}let r=[],s=null,n=null;for(let e=0;e<6;e++){2===i?n=new Uint16Array(this._size*this._size*3):0===i&&(s=new Uint8Array(this._size*this._size*3));let a=t[fi._FacesMapping[e]];if(this.gammaSpace||n||s){for(let e=0;e255){let e=255/n;t*=e,i*=e,r*=e}s[3*e+0]=t,s[3*e+1]=i,s[3*e+2]=r}}n?r.push(n):s?r.push(s):r.push(a)}return r},null,this._onLoad,this._onError)}clone(){let e=new fi(this.url,this.getScene()||this._getEngine(),this._size,this._noMipmap,this._generateHarmonics,this.gammaSpace);return e.level=this.level,e.wrapU=this.wrapU,e.wrapV=this.wrapV,e.coordinatesIndex=this.coordinatesIndex,e.coordinatesMode=this.coordinatesMode,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,this._noMipmap),this._texture||this._loadTexture())}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){var t;this._textureMatrix=e,e.updateFlag!==this._textureMatrix.updateFlag&&e.isIdentity()!==this._textureMatrix.isIdentity()&&(null===(t=this.getScene())||void 0===t||t.markAllMaterialsAsDirty(1,e=>-1!==e.getActiveTextures().indexOf(this)))}dispose(){this.onLoadObservable.clear(),super.dispose()}static Parse(e,t,i){let r=null;return e.name&&!e.isRenderTarget&&((r=new fi(i+e.name,t,e.size,e.noMipmap,e.generateHarmonics,e.useInGammaSpace)).name=e.name,r.hasAlpha=e.hasAlpha,r.level=e.level,r.coordinatesMode=e.coordinatesMode,r.isBlocking=e.isBlocking),r&&(e.boundingBoxPosition&&(r.boundingBoxPosition=rf.P.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(r.boundingBoxSize=rf.P.FromArray(e.boundingBoxSize)),e.rotationY&&(r.rotationY=e.rotationY)),r}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.hasAlpha=this.hasAlpha,e.isCube=!0,e.level=this.level,e.size=this._size,e.coordinatesMode=this.coordinatesMode,e.useInGammaSpace=this.gammaSpace,e.generateHarmonics=this._generateHarmonics,e.customType="BABYLON.HDRCubeTexture",e.noMipmap=this._noMipmap,e.isBlocking=this._isBlocking,e.rotationY=this._rotationY,e}}fi._FacesMapping=["right","left","up","down","front","back"],(0,rg.H)("BABYLON.HDRCubeTexture",fi);class fr{get influence(){return this._influence}set influence(e){if(this._influence===e)return;let 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,i=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new r_.y$,this._onDataLayoutChanged=new r_.y$,this._animationPropertiesOverride=null,this._scene=i||rL.l.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){let t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){let t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){let t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){let t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){let e=rG.p4.Clone(()=>new fr(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(){let 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())),rG.p4.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){let i=new fr(e.name,e.influence);if(i.setPositions(e.positions),null!=e.id&&(i.id=e.id),e.normals&&i.setNormals(e.normals),e.tangents&&i.setTangents(e.tangents),e.uvs&&i.setUVs(e.uvs),e.animations){for(let t=0;t0}constructor(e=null){if(this._targets=[],this._targetInfluenceChangedObservers=[],this._targetDataLayoutChangedObservers=[],this._activeTargets=new nL.t(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._uniqueId=0,this._tempInfluences=[],this._canUseTextureForTargets=!1,this._blockCounter=0,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._useTextureToStoreTargets=!0,e||(e=rL.l.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();let e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}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(){var e;return fn.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!(null===(e=this._scene)||void 0===e?void 0:e.getEngine().getCaps().disableMorphTargetTexture)}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}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){let 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)}clone(){let e=new fn(this._scene);for(let t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){let e={};for(let t of(e.id=this.uniqueId,e.targets=[],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 i=-1;for(let e of this._targets){if(i++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=fn.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=i,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;let r=e.getPositions();if(r){let e=r.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e){rb.Y.Error("Incompatible target. Targets must all have the same vertices count.");return}}}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;ee&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){let 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();let e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4),i=0;for(let r=0;r-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(let e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){let i=new fn(t);for(let r of(i._uniqueId=e.id,e.targets))i.addTarget(fr.Parse(r,t));return i}}fn.EnableTextureStorage=!0,fn.MaxActiveMorphTargetsInVertexAttributeMode=8;class fa{constructor(){this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld=rf.P.Zero(),this._hitPointWorld=rf.P.Zero(),this._rayFromWorld=rf.P.Zero(),this._rayToWorld=rf.P.Zero(),this._triangleIndex=-1}get hasHit(){return this._hasHit}get hitDistance(){return this._hitDistance}get hitNormalWorld(){return this._hitNormalWorld}get hitPointWorld(){return this._hitPointWorld}get rayFromWorld(){return this._rayFromWorld}get rayToWorld(){return this._rayToWorld}get triangleIndex(){return this._triangleIndex}setHitData(e,t,i){this._hasHit=!0,this._hitNormalWorld.set(e.x,e.y,e.z),this._hitPointWorld.set(t.x,t.y,t.z),this._triangleIndex=null!=i?i:-1}setHitDistance(e){this._hitDistance=e}calculateHitDistance(){this._hitDistance=rf.P.Distance(this._rayFromWorld,this._hitPointWorld)}reset(e=rf.P.Zero(),t=rf.P.Zero()){this._rayFromWorld.copyFrom(e),this._rayToWorld.copyFrom(t),this._hasHit=!1,this._hitDistance=0,this._hitNormalWorld.setAll(0),this._hitPointWorld.setAll(0),this._triangleIndex=-1,this.body=void 0,this.bodyIndex=void 0}}class fo{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,sM.S)("CannonJSPlugin")}constructor(e,t=fo.DefaultPluginFactory()){if(this._physicsPlugin=t,this._impostors=[],this._joints=[],this._subTimeStep=0,this._uniqueIdCounter=0,!this._physicsPlugin.isSupported())throw Error("Physics Engine "+this._physicsPlugin.name+" cannot be found. Please make sure it is included.");e=e||new rf.P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._impostors.forEach(function(e){e.dispose()}),this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}addImpostor(e){this._impostors.push(e),e.uniqueId=this._uniqueIdCounter++,e.parent||this._physicsPlugin.generatePhysicsBody(e)}removeImpostor(e){let t=this._impostors.indexOf(e);t>-1&&this._impostors.splice(t,1).length&&this.getPhysicsPlugin().removePhysicsBody(e)}addJoint(e,t,i){let r={mainImpostor:e,connectedImpostor:t,joint:i};i.physicsPlugin=this._physicsPlugin,this._joints.push(r),this._physicsPlugin.generateJoint(r)}removeJoint(e,t,i){let r=this._joints.filter(function(r){return r.connectedImpostor===t&&r.joint===i&&r.mainImpostor===e});r.length&&this._physicsPlugin.removeJoint(r[0])}_step(e){this._impostors.forEach(e=>{e.isBodyInitRequired()&&this._physicsPlugin.generatePhysicsBody(e)}),e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._impostors)}getPhysicsPlugin(){return this._physicsPlugin}getImpostors(){return this._impostors}getImpostorForPhysicsObject(e){for(let t=0;t0&&(this._physicsBodiesToRemoveAfterStep.forEach(e=>{"function"==typeof this.world.removeBody?this.world.removeBody(e):this.world.remove(e)}),this._physicsBodiesToRemoveAfterStep.length=0)}applyImpulse(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyImpulse(s,r)}applyForce(e,t,i){let r=new this.BJSCANNON.Vec3(i.x,i.y,i.z),s=new this.BJSCANNON.Vec3(t.x,t.y,t.z);e.physicsBody.applyForce(s,r)}generatePhysicsBody(e){if(this._removeMarkedPhysicsBodiesFromWorld(),e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){let t=this._createShape(e);if(!t){rb.Y.Warn("It was not possible to create a physics body for this object.");return}let i=e.physicsBody;i&&this.removePhysicsBody(e);let r=this._addMaterial("mat-"+e.uniqueId,e.getParam("friction"),e.getParam("restitution")),s={mass:e.getParam("mass"),material:r},n=e.getParam("nativeOptions");for(let e in n)Object.prototype.hasOwnProperty.call(n,e)&&(s[e]=n[e]);e.physicsBody=new this.BJSCANNON.Body(s),e.physicsBody.addEventListener("collide",e.onCollide),this.world.addEventListener("preStep",e.beforeStep),this.world.addEventListener("postStep",e.afterStep),e.physicsBody.addShape(t),"function"==typeof this.world.addBody?this.world.addBody(e.physicsBody):this.world.add(e.physicsBody),i&&["force","torque","velocity","angularVelocity"].forEach(function(t){let r=i[t];e.physicsBody[t].set(r.x,r.y,r.z)}),this._processChildMeshes(e)}this._updatePhysicsBodyTransformation(e)}_processChildMeshes(e){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[],i=e.object.rotationQuaternion;if(i?i.conjugateToRef(this._tmpQuaternion):this._tmpQuaternion.set(0,0,0,1),t.length){let i=t=>{if(!t.rotationQuaternion)return;let r=t.getPhysicsImpostor();if(r&&r.parent!==e&&t.parent){let i=t.getAbsolutePosition().subtract(t.parent.getAbsolutePosition()),s=t.rotationQuaternion.multiply(this._tmpQuaternion);r.physicsBody&&(this.removePhysicsBody(r),r.physicsBody=null),r.parent=e,r.resetUpdateFlags(),e.physicsBody.addShape(this._createShape(r),new this.BJSCANNON.Vec3(i.x,i.y,i.z),new this.BJSCANNON.Quaternion(s.x,s.y,s.z,s.w)),e.physicsBody.mass+=r.getParam("mass")}t.getChildMeshes(!0).filter(e=>!!e.physicsImpostor).forEach(i)};t.filter(e=>!!e.physicsImpostor).forEach(i)}}removePhysicsBody(e){e.physicsBody.removeEventListener("collide",e.onCollide),this.world.removeEventListener("preStep",e.beforeStep),this.world.removeEventListener("postStep",e.afterStep),-1===this._physicsBodiesToRemoveAfterStep.indexOf(e.physicsBody)&&this._physicsBodiesToRemoveAfterStep.push(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n={pivotA:s.mainPivot?new this.BJSCANNON.Vec3().set(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z):null,pivotB:s.connectedPivot?new this.BJSCANNON.Vec3().set(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z):null,axisA:s.mainAxis?new this.BJSCANNON.Vec3().set(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z):null,axisB:s.connectedAxis?new this.BJSCANNON.Vec3().set(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z):null,maxForce:s.nativeParams.maxForce,collideConnected:!!s.collision};switch(e.joint.type){case nn.HingeJoint:case nn.Hinge2Joint:t=new this.BJSCANNON.HingeConstraint(i,r,n);break;case nn.DistanceJoint:t=new this.BJSCANNON.DistanceConstraint(i,r,s.maxDistance||2);break;case nn.SpringJoint:t=new this.BJSCANNON.Spring(i,r,{restLength:s.length,stiffness:s.stiffness,damping:s.damping,localAnchorA:n.pivotA,localAnchorB:n.pivotB});break;case nn.LockJoint:t=new this.BJSCANNON.LockConstraint(i,r,n);break;case nn.PointToPointJoint:case nn.BallAndSocketJoint:default:t=new this.BJSCANNON.PointToPointConstraint(i,n.pivotA,r,n.pivotB,n.maxForce)}t.collideConnected=!!s.collision,e.joint.physicsJoint=t,e.joint.type!==nn.SpringJoint?this.world.addConstraint(t):(e.joint.jointData.forceApplicationCallback=e.joint.jointData.forceApplicationCallback||function(){t.applyForce()},e.mainImpostor.registerAfterPhysicsStep(e.joint.jointData.forceApplicationCallback))}removeJoint(e){e.joint.type!==nn.SpringJoint?this.world.removeConstraint(e.joint.physicsJoint):e.mainImpostor.unregisterAfterPhysicsStep(e.joint.jointData.forceApplicationCallback)}_addMaterial(e,t,i){let r,s;for(r=0;r1e3*i));e++);this.time+=r;let o=this.time%i/i,l=this.bodies;for(let i=0;i!==l.length;i++){let r=l[i];r.type!==t.Body.STATIC&&r.sleepState!==t.Body.SLEEPING?(r.position.vsub(r.previousPosition,e),e.scale(o,e),r.position.vadd(e,r.interpolatedPosition)):(r.interpolatedPosition.set(r.position.x,r.position.y,r.position.z),r.interpolatedQuaternion.set(r.quaternion.x,r.quaternion.y,r.quaternion.z,r.quaternion.w))}}}}raycast(e,t){return this._raycastResult.reset(e,t),this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._cannonRaycastResult.reset(),this.world.raycastClosest(e,t,{},this._cannonRaycastResult),i.reset(e,t),this._cannonRaycastResult.hasHit&&(i.setHitData({x:this._cannonRaycastResult.hitNormalWorld.x,y:this._cannonRaycastResult.hitNormalWorld.y,z:this._cannonRaycastResult.hitNormalWorld.z},{x:this._cannonRaycastResult.hitPointWorld.x,y:this._cannonRaycastResult.hitPointWorld.y,z:this._cannonRaycastResult.hitPointWorld.z}),i.setHitDistance(this._cannonRaycastResult.distance))}}fo.DefaultPluginFactory=()=>new fl;class fh{constructor(e=!0,t,i=OIMO){this._useDeltaForWorldStep=e,this.name="OimoJSPlugin",this._fixedTimeStep=1/60,this._tmpImpostorsArray=[],this._tmpPositionVector=rf.P.Zero(),this.BJSOIMO=i,this.world=new this.BJSOIMO.World({iterations:t}),this.world.clear(),this._raycastResult=new fa}getPluginVersion(){return 1}setGravity(e){this.world.gravity.set(e.x,e.y,e.z)}setTimeStep(e){this.world.timeStep=e}getTimeStep(){return this.world.timeStep}executeStep(e,t){t.forEach(function(e){e.beforeStep()}),this.world.timeStep=this._useDeltaForWorldStep?e:this._fixedTimeStep,this.world.step(),t.forEach(e=>{e.afterStep(),this._tmpImpostorsArray[e.uniqueId]=e});let i=this.world.contacts;for(;null!==i;){if(i.touching&&!i.body1.sleeping&&!i.body2.sleeping){i=i.next;continue}let e=this._tmpImpostorsArray[+i.body1.name],t=this._tmpImpostorsArray[+i.body2.name];if(!e||!t){i=i.next;continue}e.onCollide({body:t.physicsBody,point:null,distance:0,impulse:0,normal:null}),t.onCollide({body:e.physicsBody,point:null,distance:0,impulse:0,normal:null}),i=i.next}}applyImpulse(e,t,i){let r=e.physicsBody.mass;e.physicsBody.applyImpulse(i.scale(this.world.invScale),t.scale(this.world.invScale*r))}applyForce(e,t,i){rb.Y.Warn("Oimo doesn't support applying force. Using impulse instead."),this.applyImpulse(e,t,i)}generatePhysicsBody(e){if(e.parent){e.physicsBody&&(this.removePhysicsBody(e),e.forceUpdate());return}if(e.isBodyInitRequired()){var t;let i={name:e.uniqueId,config:[e.getParam("mass")||.001,e.getParam("friction"),e.getParam("restitution")],size:[],type:[],pos:[],posShape:[],rot:[],rotShape:[],move:0!==e.getParam("mass"),density:e.getParam("mass"),friction:e.getParam("friction"),restitution:e.getParam("restitution"),world:this.world},r=[e];(t=e.object).getChildMeshes&&t.getChildMeshes().forEach(function(e){e.physicsImpostor&&r.push(e.physicsImpostor)});let s=e=>Math.max(e,r7.kn),n=new rf._f;r.forEach(t=>{if(!t.object.rotationQuaternion)return;let r=t.object.rotationQuaternion;n.copyFrom(r),t.object.rotationQuaternion.set(0,0,0,1),t.object.computeWorldMatrix(!0);let a=n.toEulerAngles(),o=t.getObjectExtents();if(t===e){let t=e.getObjectCenter();e.object.getAbsolutePivotPoint().subtractToRef(t,this._tmpPositionVector),this._tmpPositionVector.divideInPlace(e.object.scaling),i.pos.push(t.x),i.pos.push(t.y),i.pos.push(t.z),i.posShape.push(0,0,0),i.rotShape.push(0,0,0)}else{let e=t.object.position.clone();i.posShape.push(e.x),i.posShape.push(e.y),i.posShape.push(e.z),i.rotShape.push(57.29577951308232*a.x,57.29577951308232*a.y,57.29577951308232*a.z)}switch(t.object.rotationQuaternion.copyFrom(n),t.type){case na.ParticleImpostor:rb.Y.Warn("No Particle support in OIMO.js. using SphereImpostor instead");case na.SphereImpostor:{let e=o.x,t=o.y,r=o.z,n=Math.max(s(e),s(t),s(r))/2;i.type.push("sphere"),i.size.push(n),i.size.push(n),i.size.push(n);break}case na.CylinderImpostor:{let e=s(o.x)/2,t=s(o.y);i.type.push("cylinder"),i.size.push(e),i.size.push(t),i.size.push(t);break}case na.PlaneImpostor:case na.BoxImpostor:default:{let e=s(o.x),t=s(o.y),r=s(o.z);i.type.push("box"),i.size.push(e),i.size.push(t),i.size.push(r)}}t.object.rotationQuaternion=r}),e.physicsBody=this.world.add(i),e.physicsBody.resetQuaternion(n),e.physicsBody.updatePosition(0)}else this._tmpPositionVector.copyFromFloats(0,0,0);e.setDeltaPosition(this._tmpPositionVector)}removePhysicsBody(e){this.world.removeRigidBody(e.physicsBody)}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData,n=s.nativeParams||{},a={body1:i,body2:r,axe1:n.axe1||(s.mainAxis?s.mainAxis.asArray():null),axe2:n.axe2||(s.connectedAxis?s.connectedAxis.asArray():null),pos1:n.pos1||(s.mainPivot?s.mainPivot.asArray():null),pos2:n.pos2||(s.connectedPivot?s.connectedPivot.asArray():null),min:n.min,max:n.max,collision:n.collision||s.collision,spring:n.spring,world:this.world};switch(e.joint.type){case nn.BallAndSocketJoint:t="jointBall";break;case nn.SpringJoint:rb.Y.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead"),a.min=s.length||a.min,a.max=Math.max(a.min,a.max);case nn.DistanceJoint:t="jointDistance",a.max=s.maxDistance;break;case nn.PrismaticJoint:t="jointPrisme";break;case nn.SliderJoint:t="jointSlide";break;case nn.WheelJoint:t="jointWheel";break;case nn.HingeJoint:default:t="jointHinge"}a.type=t,e.joint.physicsJoint=this.world.add(a)}removeJoint(e){try{this.world.removeJoint(e.joint.physicsJoint)}catch(e){rb.Y.Warn(e)}}isSupported(){return void 0!==this.BJSOIMO}setTransformationFromPhysicsBody(e){if(!e.physicsBody.sleeping){if(e.physicsBody.shapes.next){let t=e.physicsBody.shapes;for(;t.next;)t=t.next;e.object.position.set(t.position.x,t.position.y,t.position.z)}else{let t=e.physicsBody.getPosition();e.object.position.set(t.x,t.y,t.z)}if(e.object.rotationQuaternion){let t=e.physicsBody.getQuaternion();e.object.rotationQuaternion.set(t.x,t.y,t.z,t.w)}}}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody;e.physicsBody.shapes.next||(r.position.set(t.x,t.y,t.z),r.orientation.set(i.x,i.y,i.z,i.w),r.syncShapes(),r.awake())}setLinearVelocity(e,t){e.physicsBody.linearVelocity.set(t.x,t.y,t.z)}setAngularVelocity(e,t){e.physicsBody.angularVelocity.set(t.x,t.y,t.z)}getLinearVelocity(e){let t=e.physicsBody.linearVelocity;return t?new rf.P(t.x,t.y,t.z):null}getAngularVelocity(e){let t=e.physicsBody.angularVelocity;return t?new rf.P(t.x,t.y,t.z):null}setBodyMass(e,t){let i=0===t;e.physicsBody.shapes.density=i?1:t,e.physicsBody.setupMass(i?2:1)}getBodyMass(e){return e.physicsBody.shapes.density}getBodyFriction(e){return e.physicsBody.shapes.friction}setBodyFriction(e,t){e.physicsBody.shapes.friction=t}getBodyRestitution(e){return e.physicsBody.shapes.restitution}setBodyRestitution(e,t){e.physicsBody.shapes.restitution=t}sleepBody(e){e.physicsBody.sleep()}wakeUpBody(e){e.physicsBody.awake()}updateDistanceJoint(e,t,i){e.physicsJoint.limitMotor.upperLimit=t,void 0!==i&&(e.physicsJoint.limitMotor.lowerLimit=i)}setMotor(e,t,i,r){void 0!==i?rb.Y.Warn("OimoJS plugin currently has unexpected behavior when using setMotor with force parameter"):i=1e6,t*=-1;let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setMotor(t,i)}setLimit(e,t,i,r){let s=r?e.physicsJoint.rotationalLimitMotor2:e.physicsJoint.rotationalLimitMotor1||e.physicsJoint.rotationalLimitMotor||e.physicsJoint.limitMotor;s&&s.setLimit(t,void 0===i?-t:i)}syncMeshWithImpostor(e,t){let i=t.physicsBody;e.position.x=i.position.x,e.position.y=i.position.y,e.position.z=i.position.z,e.rotationQuaternion&&(e.rotationQuaternion.x=i.orientation.x,e.rotationQuaternion.y=i.orientation.y,e.rotationQuaternion.z=i.orientation.z,e.rotationQuaternion.w=i.orientation.w)}getRadius(e){return e.physicsBody.shapes.radius}getBoxSizeToRef(e,t){let i=e.physicsBody.shapes;t.x=2*i.halfWidth,t.y=2*i.halfHeight,t.z=2*i.halfDepth}dispose(){this.world.clear()}raycast(e,t){return rb.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),this._raycastResult.reset(e,t),this._raycastResult}raycastToRef(e,t,i){rb.Y.Warn("raycast is not currently supported by the Oimo physics plugin"),i.reset(e,t)}}class fu{constructor(e=!0,t=Ammo,i=null){if(this._useDeltaForWorldStep=e,this.bjsAMMO={},this.name="AmmoJSPlugin",this._timeStep=1/60,this._fixedTimeStep=1/60,this._maxSteps=5,this._tmpQuaternion=new rf._f,this._tmpContactCallbackResult=!1,this._tmpContactPoint=new rf.P,this._tmpContactNormal=new rf.P,this._tmpVec3=new rf.P,this._tmpMatrix=new rf.y3,"function"==typeof t){rb.Y.Error("AmmoJS is not ready. Please make sure you await Ammo() before using the plugin.");return}if(this.bjsAMMO=t,!this.isSupported()){rb.Y.Error("AmmoJS is not available. Please make sure you included the js file.");return}this._collisionConfiguration=new this.bjsAMMO.btSoftBodyRigidBodyCollisionConfiguration,this._dispatcher=new this.bjsAMMO.btCollisionDispatcher(this._collisionConfiguration),this._overlappingPairCache=i||new this.bjsAMMO.btDbvtBroadphase,this._solver=new this.bjsAMMO.btSequentialImpulseConstraintSolver,this._softBodySolver=new this.bjsAMMO.btDefaultSoftBodySolver,this.world=new this.bjsAMMO.btSoftRigidDynamicsWorld(this._dispatcher,this._overlappingPairCache,this._solver,this._collisionConfiguration,this._softBodySolver),this._tmpAmmoConcreteContactResultCallback=new this.bjsAMMO.ConcreteContactResultCallback,this._tmpAmmoConcreteContactResultCallback.addSingleResult=e=>{let t=(e=this.bjsAMMO.wrapPointer(e,this.bjsAMMO.btManifoldPoint)).getPositionWorldOnA(),i=e.m_normalWorldOnB;this._tmpContactPoint.x=t.x(),this._tmpContactPoint.y=t.y(),this._tmpContactPoint.z=t.z(),this._tmpContactNormal.x=i.x(),this._tmpContactNormal.y=i.y(),this._tmpContactNormal.z=i.z(),this._tmpContactImpulse=e.getAppliedImpulse(),this._tmpContactDistance=e.getDistance(),this._tmpContactCallbackResult=!0},this._raycastResult=new fa,this._tmpAmmoTransform=new this.bjsAMMO.btTransform,this._tmpAmmoTransform.setIdentity(),this._tmpAmmoQuaternion=new this.bjsAMMO.btQuaternion(0,0,0,1),this._tmpAmmoVectorA=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorB=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorC=new this.bjsAMMO.btVector3(0,0,0),this._tmpAmmoVectorD=new this.bjsAMMO.btVector3(0,0,0)}getPluginVersion(){return 1}setGravity(e){this._tmpAmmoVectorA.setValue(e.x,e.y,e.z),this.world.setGravity(this._tmpAmmoVectorA),this.world.getWorldInfo().set_m_gravity(this._tmpAmmoVectorA)}setTimeStep(e){this._timeStep=e}setFixedTimeStep(e){this._fixedTimeStep=e}setMaxSteps(e){this._maxSteps=e}getTimeStep(){return this._timeStep}_isImpostorInContact(e){return this._tmpContactCallbackResult=!1,this.world.contactTest(e.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_isImpostorPairInContact(e,t){return this._tmpContactCallbackResult=!1,this.world.contactPairTest(e.physicsBody,t.physicsBody,this._tmpAmmoConcreteContactResultCallback),this._tmpContactCallbackResult}_stepSimulation(e=1/60,t=10,i=1/60){if(0==t)this.world.stepSimulation(e,0);else for(;t>0&&e>0;)e-i0&&this._isImpostorInContact(i))for(let e of i._onPhysicsCollideCallbacks)for(let t of e.otherImpostors)(i.physicsBody.isActive()||t.physicsBody.isActive())&&this._isImpostorPairInContact(i,t)&&(i.onCollide({body:t.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}),t.onCollide({body:i.physicsBody,point:this._tmpContactPoint,distance:this._tmpContactDistance,impulse:this._tmpContactImpulse,normal:this._tmpContactNormal}))}_afterSoftStep(e){e.type===na.RopeImpostor?this._ropeStep(e):this._softbodyOrClothStep(e)}_ropeStep(e){let t,i,r,s;let n=e.physicsBody.get_m_nodes(),a=n.size(),o=[];for(let e=0;e{this.bjsAMMO.destroy(e)}),e._pluginData.toDispose=[]))}generateJoint(e){let t;let i=e.mainImpostor.physicsBody,r=e.connectedImpostor.physicsBody;if(!i||!r)return;let s=e.joint.jointData;switch(s.mainPivot||(s.mainPivot=new rf.P(0,0,0)),s.connectedPivot||(s.connectedPivot=new rf.P(0,0,0)),e.joint.type){case nn.DistanceJoint:{let e=s.maxDistance;e&&(s.mainPivot=new rf.P(0,-e/2,0),s.connectedPivot=new rf.P(0,e/2,0)),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break}case nn.HingeJoint:{s.mainAxis||(s.mainAxis=new rf.P(0,0,0)),s.connectedAxis||(s.connectedAxis=new rf.P(0,0,0));let e=new this.bjsAMMO.btVector3(s.mainAxis.x,s.mainAxis.y,s.mainAxis.z),n=new this.bjsAMMO.btVector3(s.connectedAxis.x,s.connectedAxis.y,s.connectedAxis.z);t=new this.bjsAMMO.btHingeConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z),e,n);break}case nn.BallAndSocketJoint:t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z));break;default:rb.Y.Warn("JointType not currently supported by the Ammo plugin, falling back to PhysicsJoint.BallAndSocketJoint"),t=new this.bjsAMMO.btPoint2PointConstraint(i,r,new this.bjsAMMO.btVector3(s.mainPivot.x,s.mainPivot.y,s.mainPivot.z),new this.bjsAMMO.btVector3(s.connectedPivot.x,s.connectedPivot.y,s.connectedPivot.z))}this.world.addConstraint(t,!e.joint.jointData.collision),e.joint.physicsJoint=t}removeJoint(e){this.world&&this.world.removeConstraint(e.joint.physicsJoint)}_addMeshVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s,n=i.getIndices();n||(n=[]);let a=i.getVerticesData(sm.o.PositionKind);if(a||(a=[]),t&&t!==i){let e;e=t.rotationQuaternion?t.rotationQuaternion:t.rotation?rf._f.FromEulerAngles(t.rotation.x,t.rotation.y,t.rotation.z):rf._f.Identity(),rf.y3.Compose(rf.P.One(),e,t.position).invertToRef(this._tmpMatrix),s=i.computeWorldMatrix(!1).multiply(this._tmpMatrix)}else rf.y3.ScalingToRef(i.scaling.x,i.scaling.y,i.scaling.z,this._tmpMatrix),s=this._tmpMatrix;let o=n.length/3;for(let t=0;t{r+=this._addMeshVerts(e,t,i)})}return r}_softVertexData(e){let t=e.object;if(t&&t.getIndices&&t.getWorldMatrix&&t.getChildMeshes){let e=t.getIndices();e||(e=[]);let i=t.getVerticesData(sm.o.PositionKind);i||(i=[]);let r=t.getVerticesData(sm.o.NormalKind);r||(r=[]),t.computeWorldMatrix(!1);let s=[],n=[];for(let e=0;ee*e).reduce((e,t)=>e+t))i=(t=s.length)/3-1,this._tmpAmmoVectorA.setValue(s[0],s[1],s[2]),this._tmpAmmoVectorB.setValue(s[t-3],s[t-2],s[t-1]);else{e._isFromLine=!1;let r=e.getParam("path");if(null===e.getParam("shape"))return rb.Y.Warn("No shape available for extruded mesh"),new this.bjsAMMO.btCompoundShape;i=(t=r.length)-1,this._tmpAmmoVectorA.setValue(r[0].x,r[0].y,r[0].z),this._tmpAmmoVectorB.setValue(r[t-1].x,r[t-1].y,r[t-1].z)}e.segments=i;let a=e.getParam("fixedPoints");a=a>3?3:a;let o=new this.bjsAMMO.btSoftBodyHelpers().CreateRope(this.world.getWorldInfo(),this._tmpAmmoVectorA,this._tmpAmmoVectorB,i-1,a);return o.get_m_cfg().set_collisions(17),o}_createCustom(e){let t=null;return this.onCreateCustomShape&&(t=this.onCreateCustomShape(e)),null==t&&(t=new this.bjsAMMO.btCompoundShape),t}_addHullVerts(e,t,i){let r=0;if(i&&i.getIndices&&i.getWorldMatrix&&i.getChildMeshes){let s=i.getIndices();s||(s=[]);let n=i.getVerticesData(sm.o.PositionKind);n||(n=[]),i.computeWorldMatrix(!1);let a=s.length/3;for(let t=0;t{r+=this._addHullVerts(e,t,i)})}return r}_createShape(e,t=!1){let i;let r=e.object,s=e.getObjectExtents();if(!t){let t=e.object.getChildMeshes?e.object.getChildMeshes(!0):[];i=new this.bjsAMMO.btCompoundShape;let r=0;if(t.forEach(e=>{let t=e.getPhysicsImpostor();if(t){if(t.type==na.MeshImpostor)throw"A child MeshImpostor is not supported. Only primitive impostors are supported as children (eg. box or sphere)";let s=this._createShape(t),n=e.parent.getWorldMatrix().clone(),a=new rf.P;n.decompose(a),this._tmpAmmoTransform.getOrigin().setValue(e.position.x*a.x,e.position.y*a.y,e.position.z*a.z),this._tmpAmmoQuaternion.setValue(e.rotationQuaternion.x,e.rotationQuaternion.y,e.rotationQuaternion.z,e.rotationQuaternion.w),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,s),t.dispose(),r++}}),r>0){if(e.type!=na.NoImpostor){let t=this._createShape(e,!0);t&&(this._tmpAmmoTransform.getOrigin().setValue(0,0,0),this._tmpAmmoQuaternion.setValue(0,0,0,1),this._tmpAmmoTransform.setRotation(this._tmpAmmoQuaternion),i.addChildShape(this._tmpAmmoTransform,t))}return i}this.bjsAMMO.destroy(i),i=null}switch(e.type){case na.SphereImpostor:if(rk.R.WithinEpsilon(s.x,s.y,1e-4)&&rk.R.WithinEpsilon(s.x,s.z,1e-4))i=new this.bjsAMMO.btSphereShape(s.x/2);else{let e=[new this.bjsAMMO.btVector3(0,0,0)];(i=new this.bjsAMMO.btMultiSphereShape(e,[1],1)).setLocalScaling(new this.bjsAMMO.btVector3(s.x/2,s.y/2,s.z/2))}break;case na.CapsuleImpostor:{let e=s.x/2;i=new this.bjsAMMO.btCapsuleShape(e,s.y-2*e)}break;case na.CylinderImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btCylinderShape(this._tmpAmmoVectorA);break;case na.PlaneImpostor:case na.BoxImpostor:this._tmpAmmoVectorA.setValue(s.x/2,s.y/2,s.z/2),i=new this.bjsAMMO.btBoxShape(this._tmpAmmoVectorA);break;case na.MeshImpostor:if(0==e.getParam("mass")){if(this.onCreateCustomMeshImpostor)i=this.onCreateCustomMeshImpostor(e);else{let t=new this.bjsAMMO.btTriangleMesh;e._pluginData.toDispose.push(t),i=0==this._addMeshVerts(t,r,r)?new this.bjsAMMO.btCompoundShape:new this.bjsAMMO.btBvhTriangleMeshShape(t)}break}case na.ConvexHullImpostor:if(this.onCreateCustomConvexHullImpostor)i=this.onCreateCustomConvexHullImpostor(e);else{let t=new this.bjsAMMO.btConvexHullShape;0==this._addHullVerts(t,r,r)?(e._pluginData.toDispose.push(t),i=new this.bjsAMMO.btCompoundShape):i=t}break;case na.NoImpostor:i=new this.bjsAMMO.btSphereShape(s.x/2);break;case na.CustomImpostor:i=this._createCustom(e);break;case na.SoftbodyImpostor:i=this._createSoftbody(e);break;case na.ClothImpostor:i=this._createCloth(e);break;case na.RopeImpostor:i=this._createRope(e);break;default:rb.Y.Warn("The impostor type is not currently supported by the ammo plugin.")}return i}setTransformationFromPhysicsBody(e){e.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.object.position.set(this._tmpAmmoTransform.getOrigin().x(),this._tmpAmmoTransform.getOrigin().y(),this._tmpAmmoTransform.getOrigin().z()),e.object.rotationQuaternion?e.object.rotationQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()):e.object.rotation&&(this._tmpQuaternion.set(this._tmpAmmoTransform.getRotation().x(),this._tmpAmmoTransform.getRotation().y(),this._tmpAmmoTransform.getRotation().z(),this._tmpAmmoTransform.getRotation().w()),this._tmpQuaternion.toEulerAnglesToRef(e.object.rotation))}setPhysicsBodyTransformation(e,t,i){let r=e.physicsBody.getWorldTransform();if(Math.abs(r.getOrigin().x()-t.x)>r7.kn||Math.abs(r.getOrigin().y()-t.y)>r7.kn||Math.abs(r.getOrigin().z()-t.z)>r7.kn||Math.abs(r.getRotation().x()-i.x)>r7.kn||Math.abs(r.getRotation().y()-i.y)>r7.kn||Math.abs(r.getRotation().z()-i.z)>r7.kn||Math.abs(r.getRotation().w()-i.w)>r7.kn){if(this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),r.setOrigin(this._tmpAmmoVectorA),this._tmpAmmoQuaternion.setValue(i.x,i.y,i.z,i.w),r.setRotation(this._tmpAmmoQuaternion),e.physicsBody.setWorldTransform(r),0==e.mass){let t=e.physicsBody.getMotionState();t&&t.setWorldTransform(r)}else e.physicsBody.activate()}}isSupported(){return void 0!==this.bjsAMMO}setLinearVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.linearVelocity(this._tmpAmmoVectorA):e.physicsBody.setLinearVelocity(this._tmpAmmoVectorA)}setAngularVelocity(e,t){this._tmpAmmoVectorA.setValue(t.x,t.y,t.z),e.soft?e.physicsBody.angularVelocity(this._tmpAmmoVectorA):e.physicsBody.setAngularVelocity(this._tmpAmmoVectorA)}getLinearVelocity(e){let t;if(!(t=e.soft?e.physicsBody.linearVelocity():e.physicsBody.getLinearVelocity()))return null;let i=new rf.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}getAngularVelocity(e){let t;if(!(t=e.soft?e.physicsBody.angularVelocity():e.physicsBody.getAngularVelocity()))return null;let i=new rf.P(t.x(),t.y(),t.z());return this.bjsAMMO.destroy(t),i}setBodyMass(e,t){e.soft?e.physicsBody.setTotalMass(t,!1):e.physicsBody.setMassProps(t),e._pluginData.mass=t}getBodyMass(e){return e._pluginData.mass||0}getBodyFriction(e){return e._pluginData.friction||0}setBodyFriction(e,t){e.soft?e.physicsBody.get_m_cfg().set_kDF(t):e.physicsBody.setFriction(t),e._pluginData.friction=t}getBodyRestitution(e){return e._pluginData.restitution||0}setBodyRestitution(e,t){e.physicsBody.setRestitution(t),e._pluginData.restitution=t}getBodyPressure(e){return e.soft?e._pluginData.pressure||0:(rb.Y.Warn("Pressure is not a property of a rigid body"),0)}setBodyPressure(e,t){e.soft?e.type===na.SoftbodyImpostor?(e.physicsBody.get_m_cfg().set_kPR(t),e._pluginData.pressure=t):(e.physicsBody.get_m_cfg().set_kPR(0),e._pluginData.pressure=0):rb.Y.Warn("Pressure can only be applied to a softbody")}getBodyStiffness(e){return e.soft?e._pluginData.stiffness||0:(rb.Y.Warn("Stiffness is not a property of a rigid body"),0)}setBodyStiffness(e,t){e.soft?(t=(t=t<0?0:t)>1?1:t,e.physicsBody.get_m_materials().at(0).set_m_kLST(t),e._pluginData.stiffness=t):rb.Y.Warn("Stiffness cannot be applied to a rigid body")}getBodyVelocityIterations(e){return e.soft?e._pluginData.velocityIterations||0:(rb.Y.Warn("Velocity iterations is not a property of a rigid body"),0)}setBodyVelocityIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_viterations(t),e._pluginData.velocityIterations=t):rb.Y.Warn("Velocity iterations cannot be applied to a rigid body")}getBodyPositionIterations(e){return e.soft?e._pluginData.positionIterations||0:(rb.Y.Warn("Position iterations is not a property of a rigid body"),0)}setBodyPositionIterations(e,t){e.soft?(t=t<0?0:t,e.physicsBody.get_m_cfg().set_piterations(t),e._pluginData.positionIterations=t):rb.Y.Warn("Position iterations cannot be applied to a rigid body")}appendAnchor(e,t,i,r,s=1,n=!1){let a=e.segments;e.physicsBody.appendAnchor(Math.round((a-1)*i)+a*(a-1-Math.round((a-1)*r)),t.physicsBody,n,s)}appendHook(e,t,i,r=1,s=!1){let n=Math.round(e.segments*i);e.physicsBody.appendAnchor(n,t.physicsBody,s,r)}sleepBody(e){e.physicsBody.forceActivationState(0)}wakeUpBody(e){e.physicsBody.activate()}updateDistanceJoint(){rb.Y.Warn("updateDistanceJoint is not currently supported by the Ammo physics plugin")}setMotor(e,t,i){e.physicsJoint.enableAngularMotor(!0,t,i)}setLimit(){rb.Y.Warn("setLimit is not currently supported by the Ammo physics plugin")}syncMeshWithImpostor(e,t){t.physicsBody.getMotionState().getWorldTransform(this._tmpAmmoTransform),e.position.x=this._tmpAmmoTransform.getOrigin().x(),e.position.y=this._tmpAmmoTransform.getOrigin().y(),e.position.z=this._tmpAmmoTransform.getOrigin().z(),e.rotationQuaternion&&(e.rotationQuaternion.x=this._tmpAmmoTransform.getRotation().x(),e.rotationQuaternion.y=this._tmpAmmoTransform.getRotation().y(),e.rotationQuaternion.z=this._tmpAmmoTransform.getRotation().z(),e.rotationQuaternion.w=this._tmpAmmoTransform.getRotation().w())}getRadius(e){return e.getObjectExtents().x/2}getBoxSizeToRef(e,t){let i=e.getObjectExtents();t.x=i.x,t.y=i.y,t.z=i.z}dispose(){this.bjsAMMO.destroy(this.world),this.bjsAMMO.destroy(this._solver),this.bjsAMMO.destroy(this._overlappingPairCache),this.bjsAMMO.destroy(this._dispatcher),this.bjsAMMO.destroy(this._collisionConfiguration),this.bjsAMMO.destroy(this._tmpAmmoVectorA),this.bjsAMMO.destroy(this._tmpAmmoVectorB),this.bjsAMMO.destroy(this._tmpAmmoVectorC),this.bjsAMMO.destroy(this._tmpAmmoTransform),this.bjsAMMO.destroy(this._tmpAmmoQuaternion),this.bjsAMMO.destroy(this._tmpAmmoConcreteContactResultCallback),this.world=null}raycast(e,t){return this.raycastToRef(e,t,this._raycastResult),this._raycastResult}raycastToRef(e,t,i){this._tmpAmmoVectorRCA=new this.bjsAMMO.btVector3(e.x,e.y,e.z),this._tmpAmmoVectorRCB=new this.bjsAMMO.btVector3(t.x,t.y,t.z);let r=new this.bjsAMMO.ClosestRayResultCallback(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB);this.world.rayTest(this._tmpAmmoVectorRCA,this._tmpAmmoVectorRCB,r),i.reset(e,t),r.hasHit()&&(i.setHitData({x:r.get_m_hitNormalWorld().x(),y:r.get_m_hitNormalWorld().y(),z:r.get_m_hitNormalWorld().z()},{x:r.get_m_hitPointWorld().x(),y:r.get_m_hitPointWorld().y(),z:r.get_m_hitPointWorld().z()}),i.calculateHitDistance()),this.bjsAMMO.destroy(r),this.bjsAMMO.destroy(this._tmpAmmoVectorRCA),this.bjsAMMO.destroy(this._tmpAmmoVectorRCB)}}fu._DISABLE_COLLISION_FLAG=4,fu._KINEMATIC_FLAG=2,fu._DISABLE_DEACTIVATION_FLAG=4,rd.p.prototype.removeReflectionProbe=function(e){if(!this.reflectionProbes)return -1;let t=this.reflectionProbes.indexOf(e);return -1!==t&&this.reflectionProbes.splice(t,1),t},rd.p.prototype.addReflectionProbe=function(e){this.reflectionProbes||(this.reflectionProbes=[]),this.reflectionProbes.push(e)};class fc{constructor(e,t,i,r=!0,s=!1,n=!1){let a;if(this.name=e,this._viewMatrix=rf.y3.Identity(),this._target=rf.P.Zero(),this._add=rf.P.Zero(),this._invertYAxis=!1,this.position=rf.P.Zero(),this.metadata=null,this._parentContainer=null,this._scene=i,i.getEngine().supportsUniformBuffers){this._sceneUBOs=[];for(let t=0;t<6;++t)this._sceneUBOs.push(i.createSceneUniformBuffer(`Scene for Reflection Probe (name "${e}") face #${t}`))}this._scene.reflectionProbes||(this._scene.reflectionProbes=[]),this._scene.reflectionProbes.push(this);let o=0;if(s){let e=this._scene.getEngine().getCaps();e.textureHalfFloatRender?o=2:e.textureFloatRender&&(o=1)}this._renderTargetTexture=new as(e,t,i,r,!0,o,!0),this._renderTargetTexture.gammaSpace=!n,this._renderTargetTexture.invertZ=i.useRightHandedSystem;let l=i.getEngine().useReverseDepthBuffer;this._renderTargetTexture.onBeforeRenderObservable.add(e=>{switch(this._sceneUBOs&&(i.setSceneUniformBuffer(this._sceneUBOs[e]),i.getSceneUniformBuffer().unbindEffect()),e){case 0:this._add.copyFromFloats(1,0,0);break;case 1:this._add.copyFromFloats(-1,0,0);break;case 2:this._add.copyFromFloats(0,this._invertYAxis?1:-1,0);break;case 3:this._add.copyFromFloats(0,this._invertYAxis?-1:1,0);break;case 4:this._add.copyFromFloats(0,0,i.useRightHandedSystem?-1:1);break;case 5:this._add.copyFromFloats(0,0,i.useRightHandedSystem?1:-1)}this._attachedMesh&&this.position.copyFrom(this._attachedMesh.getAbsolutePosition()),this.position.addToRef(this._add,this._target);let t=i.useRightHandedSystem?rf.y3.LookAtRHToRef:rf.y3.LookAtLHToRef,r=i.useRightHandedSystem?rf.y3.PerspectiveFovRH:rf.y3.PerspectiveFovLH;t(this.position,this._target,rf.P.Up(),this._viewMatrix),i.activeCamera&&(this._projectionMatrix=r(Math.PI/2,1,l?i.activeCamera.maxZ:i.activeCamera.minZ,l?i.activeCamera.minZ:i.activeCamera.maxZ,this._scene.getEngine().isNDCHalfZRange),i.setTransformMatrix(this._viewMatrix,this._projectionMatrix),i.activeCamera.isRigCamera&&!this._renderTargetTexture.activeCamera&&(this._renderTargetTexture.activeCamera=i.activeCamera.rigParent||null)),i._forcedViewPosition=this.position}),this._renderTargetTexture.onBeforeBindObservable.add(()=>{var t,r;this._currentSceneUBO=i.getSceneUniformBuffer(),null===(r=(t=i.getEngine())._debugPushGroup)||void 0===r||r.call(t,`reflection probe generation for ${e}`,1),a=this._scene.imageProcessingConfiguration.applyByPostProcess,n&&(i.imageProcessingConfiguration.applyByPostProcess=!0)}),this._renderTargetTexture.onAfterUnbindObservable.add(()=>{var e,t;i.imageProcessingConfiguration.applyByPostProcess=a,i._forcedViewPosition=null,this._sceneUBOs&&i.setSceneUniformBuffer(this._currentSceneUBO),i.updateTransformMatrix(!0),null===(t=(e=i.getEngine())._debugPopGroup)||void 0===t||t.call(e,1)})}get samples(){return this._renderTargetTexture.samples}set samples(e){this._renderTargetTexture.samples=e}get refreshRate(){return this._renderTargetTexture.refreshRate}set refreshRate(e){this._renderTargetTexture.refreshRate=e}getScene(){return this._scene}get cubeTexture(){return this._renderTargetTexture}get renderList(){return this._renderTargetTexture.renderList}set renderList(e){this._renderTargetTexture.renderList=e}attachToMesh(e){this._attachedMesh=e}setRenderingAutoClearDepthStencil(e,t){this._renderTargetTexture.setRenderingAutoClearDepthStencil(e,t)}dispose(){let e=this._scene.reflectionProbes.indexOf(this);if(-1!==e&&this._scene.reflectionProbes.splice(e,1),this._parentContainer){let e=this._parentContainer.reflectionProbes.indexOf(this);e>-1&&this._parentContainer.reflectionProbes.splice(e,1),this._parentContainer=null}if(this._renderTargetTexture&&(this._renderTargetTexture.dispose(),this._renderTargetTexture=null),this._sceneUBOs){for(let e of this._sceneUBOs)e.dispose();this._sceneUBOs=[]}}toString(e){let t="Name: "+this.name;return e&&(t+=", position: "+this.position.toString(),this._attachedMesh&&(t+=", attached mesh: "+this._attachedMesh.name)),t}getClassName(){return"ReflectionProbe"}serialize(){let e=rG.p4.Serialize(this,this._renderTargetTexture.serialize());return e.isReflectionProbe=!0,e.metadata=this.metadata,e}static Parse(e,t,i){let r=null;if(t.reflectionProbes)for(let i=0;ir||new fc(e.name,e.renderTargetSize,t,e._generateMipMaps),e,t,i)).cubeTexture._waitingRenderList=e.renderList,e._attachedMesh&&r.attachToMesh(t.getMeshById(e._attachedMesh)),e.metadata&&(r.metadata=e.metadata),r}}(0,sx.gn)([(0,rG.RR)()],fc.prototype,"_attachedMesh",void 0),(0,sx.gn)([(0,rG.hd)()],fc.prototype,"position",void 0);class fd{}fd.LoaderInjectedPhysicsEngine=void 0;let fp={},f_={},ff=(e,t,i,r)=>{if(!t.materials)return null;for(let s=0,n=t.materials.length;s{for(let r in t)if(e.name===t[r])return i.push(e.id),!0;return void 0!==e.parentId&&-1!==i.indexOf(e.parentId)&&(i.push(e.id),!0)},fg=(e,t)=>e+" of "+(t?t.file+" from "+t.name+" version: "+t.version+", exporter version: "+t.exporter_version:"unknown"),fv=(e,t)=>{if(t._waitingData.lods){if(t._waitingData.lods.ids&&t._waitingData.lods.ids.length>0){let i=t._waitingData.lods.ids,r=t.isEnabled(!1);if(t._waitingData.lods.distances){let s=t._waitingData.lods.distances;if(s.length>=i.length){let n=s.length>i.length?s[s.length-1]:0;t.setEnabled(!1);for(let r=0;r0&&t.addLODLevel(n,null),!0===r&&t.setEnabled(!0)}else sg.w1.Warn("Invalid level of detail distances for "+t.name)}}t._waitingData.lods=null}},fx=(e,t,i)=>{if("number"!=typeof e){let r=i.getLastEntryById(e);return r&&null!=t?r.instances[parseInt(t)]:r}let r=fp[e];return r&&null!=t?r.instances[parseInt(t)]:r},fT=(e,t)=>"number"!=typeof e?t.getLastMaterialById(e,!0):f_[e],fS=(e,t,i,r,s=!1)=>{let n=new sA(e),a="importScene has failed JSON parse";try{let r,s;var o=JSON.parse(t);a="";let l=nh.loggingLevel===nh.DETAILED_LOGGING;if(void 0!==o.environmentTexture&&null!==o.environmentTexture){let t=void 0===o.isPBR||o.isPBR;if(o.environmentTextureType&&"BABYLON.HDRCubeTexture"===o.environmentTextureType){let r=o.environmentTextureSize?o.environmentTextureSize:128,s=new fi((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,r,!0,!t,void 0,o.environmentTexturePrefilterOnLoad);o.environmentTextureRotationY&&(s.rotationY=o.environmentTextureRotationY),e.environmentTexture=s}else if("object"==typeof o.environmentTexture){let t=dM.Parse(o.environmentTexture,e,i);e.environmentTexture=t}else if(o.environmentTexture.endsWith(".env")){let t=new dM((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}else{let t=dM.CreateFromPrefilteredData((o.environmentTexture.match(/https?:\/\//g)?"":i)+o.environmentTexture,e,o.environmentTextureForcedExtension);o.environmentTextureRotationY&&(t.rotationY=o.environmentTextureRotationY),e.environmentTexture=t}if(!0===o.createDefaultSkybox){let i=void 0!==e.activeCamera&&null!==e.activeCamera?(e.activeCamera.maxZ-e.activeCamera.minZ)/2:1e3,r=o.skyboxBlurLevel||0;e.createDefaultSkybox(e.environmentTexture,t,i,r)}n.environmentTexture=e.environmentTexture}if(void 0!==o.environmentIntensity&&null!==o.environmentIntensity&&(e.environmentIntensity=o.environmentIntensity),void 0!==o.lights&&null!==o.lights)for(r=0,s=o.lights.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)}))}if(void 0!==o.multiMaterials&&null!==o.multiMaterials)for(r=0,s=o.multiMaterials.length;r{-1==n.textures.indexOf(e)&&(n.textures.push(e),e._parentContainer=n)})}if(void 0!==o.morphTargetManagers&&null!==o.morphTargetManagers)for(let t of o.morphTargetManagers){let i=fn.Parse(t,e);n.morphTargetManagers.push(i),i._parentContainer=n}if(void 0!==o.skeletons&&null!==o.skeletons)for(r=0,s=o.skeletons.length;r{e&&(n.geometries.push(e),e._parentContainer=n)})}if(void 0!==o.transformNodes&&null!==o.transformNodes)for(r=0,s=o.transformNodes.length;r{t._waitingSubMaterialsUniqueIds.forEach(i=>{t.subMaterials.push(fT(i,e))}),t._waitingSubMaterialsUniqueIds=[]}),e.meshes.forEach(t=>{null!==t._waitingMaterialId&&(t.material=fT(t._waitingMaterialId,e),t._waitingMaterialId=null)}),r=0,s=e.skeletons.length;r{if(t._waitingTransformNodeId){let i=e.getLastEntryById(t._waitingTransformNodeId);i&&t.linkTransformNode(i),t._waitingTransformNodeId=null}}),t._hasWaitingData=null)}for(r=0,s=e.meshes.length;r0){for(let i=0;i0){for(let i=0;i{e._loadedUniqueId=""}),rd.p.Parse(o,e,n,i),r=0,s=e.meshes.length;r-1!==e.indexOf("babylon"),importMesh:(e,t,i,r,s,n,a,o)=>{var l;let h="importMesh has failed JSON parse";try{var u=JSON.parse(i);h="";let o=nh.loggingLevel===nh.DETAILED_LOGGING;e?Array.isArray(e)||(e=[e]):e=null;let c=[],d=new Map,p=[];if(void 0!==u.transformNodes&&null!==u.transformNodes)for(let e=0,i=u.transformNodes.length;e{!0!==e&&u.geometries[i]&&Array.isArray(u.geometries[i])&&u.geometries[i].forEach(s=>{s.id===l.geometryId&&("vertexData"===i&&_5.Z.Parse(s,t,r),e=!0)})}),!1===e&&rb.Y.Warn("Geometry not found for mesh "+l.id)}if(l.materialUniqueId||l.materialId){let e=l.materialUniqueId?f:_,i=-1!==e.indexOf(l.materialUniqueId||l.materialId);if(!1===i&&void 0!==u.multiMaterials&&null!==u.multiMaterials){let s=(i,s)=>{e.push(i);let n=ff(s,u,t,r);n&&n.material&&(f_[n.parsedMaterial.uniqueId||n.parsedMaterial.id]=n.material,h+="\n Material "+n.material.toString(o))};for(let r=0,n=u.multiMaterials.length;rs(e,t=>t.uniqueId===e)):n.materials.forEach(e=>s(e,t=>t.id===e)),e.push(n.uniqueId||n.id);let r=_6.G.ParseMultiMaterial(n,t);f_[n.uniqueId||n.id]=r,r&&(i=!0,h+="\n Multi-Material "+r.toString(o));break}}}if(!1===i){e.push(l.materialUniqueId||l.materialId);let i=ff(e=>l.materialUniqueId&&e.uniqueId===l.materialUniqueId||e.id===l.materialId,u,t,r);i&&i.material?(f_[i.parsedMaterial.uniqueId||i.parsedMaterial.id]=i.material,h+="\n Material "+i.material.toString(o)):rb.Y.Warn("Material not found for mesh "+l.id)}}if(null!==l.skeletonId&&void 0!==l.skeletonId&&-1!==u.skeletonId&&void 0!==u.skeletons&&null!==u.skeletons&&!(n.indexOf(l.skeletonId)>-1))for(let e=0,i=u.skeletons.length;e-1&&void 0!==u.morphTargetManagers&&null!==u.morphTargetManagers&&!(m.indexOf(l.morphTargetManagerId)>-1))for(let e=0,i=u.morphTargetManagers.length;e{e._waitingSubMaterialsUniqueIds.forEach(i=>{e.subMaterials.push(fT(i,t))}),e._waitingSubMaterialsUniqueIds=[]}),t.meshes.forEach(e=>{null!==e._waitingMaterialId&&(e.material=fT(e._waitingMaterialId,t),e._waitingMaterialId=null)});for(let e=0,i=t.transformNodes.length;e-1&&p.splice(e,1)}i._waitingParentId=null}i._waitingData.lods&&fv(t,i)}for(let e of p)e.dispose();for(let e=0,i=t.skeletons.length;e{if(e._waitingTransformNodeId){let i=t.getLastEntryById(e._waitingTransformNodeId);i&&e.linkTransformNode(i),e._waitingTransformNodeId=null}}),i._hasWaitingData=null)}for(let e=0,r=t.meshes.length;e{e._loadedUniqueId=""}),!0}catch(t){let e=fg("importMesh",u?u.producer:"Unknown")+h;if(o)o(e,t);else throw rb.Y.Log(e),t}finally{null!==h&&nh.loggingLevel!==nh.NO_LOGGING&&rb.Y.Log(fg("importMesh",u?u.producer:"Unknown")+(nh.loggingLevel!==nh.MINIMAL_LOGGING?h:"")),f_={}}return!1},load:(e,t,i,r)=>{let s="importScene has failed JSON parse";try{var n=JSON.parse(t);if(s="",void 0!==n.useDelayedTextureLoading&&null!==n.useDelayedTextureLoading&&(e.useDelayedTextureLoading=n.useDelayedTextureLoading&&!nh.ForceFullSceneLoadingForIncremental),void 0!==n.autoClear&&null!==n.autoClear&&(e.autoClear=n.autoClear),void 0!==n.clearColor&&null!==n.clearColor&&(e.clearColor=rm.HE.FromArray(n.clearColor)),void 0!==n.ambientColor&&null!==n.ambientColor&&(e.ambientColor=rm.Wo.FromArray(n.ambientColor)),void 0!==n.gravity&&null!==n.gravity&&(e.gravity=rf.P.FromArray(n.gravity)),void 0!==n.useRightHandedSystem&&(e.useRightHandedSystem=!!n.useRightHandedSystem),n.fogMode&&0!==n.fogMode)switch(e.fogMode=n.fogMode,e.fogColor=rm.Wo.FromArray(n.fogColor),e.fogStart=n.fogStart,e.fogEnd=n.fogEnd,e.fogDensity=n.fogDensity,s+=" Fog mode for scene: ",e.fogMode){case 1:s+="exp\n";break;case 2:s+="exp2\n";break;case 3:s+="linear\n"}if(n.physicsEnabled){let t;"cannon"===n.physicsEngine||n.physicsEngine===fl.name?t=new fl(void 0,void 0,fd.LoaderInjectedPhysicsEngine):"oimo"===n.physicsEngine||n.physicsEngine===fh.name?t=new fh(void 0,fd.LoaderInjectedPhysicsEngine):("ammo"===n.physicsEngine||n.physicsEngine===fu.name)&&(t=new fu(void 0,fd.LoaderInjectedPhysicsEngine,void 0)),s=" Physics engine "+(n.physicsEngine?n.physicsEngine:"oimo")+" enabled\n";let i=n.physicsGravity?rf.P.FromArray(n.physicsGravity):null;e.enablePhysics(i,t)}if(void 0!==n.metadata&&null!==n.metadata&&(e.metadata=n.metadata),void 0!==n.collisionsEnabled&&null!==n.collisionsEnabled&&(e.collisionsEnabled=n.collisionsEnabled),!fS(e,t,i,r,!0))return!1;return n.autoAnimate&&e.beginAnimation(e,n.autoAnimateFrom,n.autoAnimateTo,n.autoAnimateLoop,n.autoAnimateSpeed||1),void 0!==n.activeCameraID&&null!==n.activeCameraID&&e.setActiveCameraById(n.activeCameraID),!0}catch(t){let e=fg("importScene",n?n.producer:"Unknown")+s;if(r)r(e,t);else throw rb.Y.Log(e),t}finally{null!==s&&nh.loggingLevel!==nh.NO_LOGGING&&rb.Y.Log(fg("importScene",n?n.producer:"Unknown")+(nh.loggingLevel!==nh.MINIMAL_LOGGING?s:""))}return!1},loadAssetContainer:(e,t,i,r)=>fS(e,t,i,r)}),i(9087);class fE{get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,sR.D.MarkAllMaterialsAsDirty(20))}constructor(e={}){this._isEnabled=!0,this.bias=void 0===e.bias?0:e.bias,this.power=void 0===e.power?1:e.power,this.leftColor=e.leftColor||rm.Wo.White(),this.rightColor=e.rightColor||rm.Wo.Black(),!1===e.isEnabled&&(this.isEnabled=!1)}clone(){let e=new fE;return rw.j.DeepCopy(this,e),e}equals(e){return e&&this.bias===e.bias&&this.power===e.power&&this.leftColor.equals(e.leftColor)&&this.rightColor.equals(e.rightColor)&&this.isEnabled===e.isEnabled}serialize(){return{isEnabled:this.isEnabled,leftColor:this.leftColor.asArray(),rightColor:this.rightColor.asArray(),bias:this.bias,power:this.power}}static Parse(e){return new fE({isEnabled:e.isEnabled,leftColor:rm.Wo.FromArray(e.leftColor),rightColor:rm.Wo.FromArray(e.rightColor),bias:e.bias,power:e.power||1})}}rG.p4._FresnelParametersParser=fE.Parse;class fC extends pN{get doubleSided(){return this._twoSidedLighting}set doubleSided(e){this._twoSidedLighting!==e&&(this._twoSidedLighting=e,this.backFaceCulling=!e,this._markAllSubMeshesAsTexturesDirty())}constructor(e,t){super(e,t),this.maxSimultaneousLights=4,this.disableLighting=!1,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.emissiveColor=new rm.Wo(0,0,0),this.occlusionStrength=1,this.useLightmapAsShadowmap=!1,this._useAlphaFromAlbedoTexture=!0,this._useAmbientInGrayScale=!0}getClassName(){return"PBRBaseSimpleMaterial"}}(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],fC.prototype,"maxSimultaneousLights",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsLightsDirty")],fC.prototype,"disableLighting",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_reflectionTexture")],fC.prototype,"environmentTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],fC.prototype,"invertNormalMapX",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],fC.prototype,"invertNormalMapY",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_bumpTexture")],fC.prototype,"normalTexture",void 0),(0,sx.gn)([(0,rG.n9)("emissive"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],fC.prototype,"emissiveColor",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],fC.prototype,"emissiveTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTextureStrength")],fC.prototype,"occlusionStrength",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_ambientTexture")],fC.prototype,"occlusionTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_alphaCutOff")],fC.prototype,"alphaCutOff",void 0),(0,sx.gn)([(0,rG.qC)()],fC.prototype,"doubleSided",null),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty",null)],fC.prototype,"lightmapTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],fC.prototype,"useLightmapAsShadowmap",void 0);class fb extends fC{constructor(e,t){super(e,t),this._useRoughnessFromMetallicTextureAlpha=!1,this._useRoughnessFromMetallicTextureGreen=!0,this._useMetallnessFromMetallicTextureBlue=!0,this.metallic=1,this.roughness=1}getClassName(){return"PBRMetallicRoughnessMaterial"}clone(e){let t=rG.p4.Clone(()=>new fb(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){let e=rG.p4.Serialize(this);return e.customType="BABYLON.PBRMetallicRoughnessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){let r=rG.p4.Parse(()=>new fb(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}(0,sx.gn)([(0,rG.n9)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],fb.prototype,"baseColor",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],fb.prototype,"baseTexture",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],fb.prototype,"metallic",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],fb.prototype,"roughness",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_metallicTexture")],fb.prototype,"metallicRoughnessTexture",void 0),(0,rg.H)("BABYLON.PBRMetallicRoughnessMaterial",fb);class fy extends fC{get useMicroSurfaceFromReflectivityMapAlpha(){return this._useMicroSurfaceFromReflectivityMapAlpha}constructor(e,t){super(e,t),this._useMicroSurfaceFromReflectivityMapAlpha=!0}getClassName(){return"PBRSpecularGlossinessMaterial"}clone(e){let t=rG.p4.Clone(()=>new fy(e,this.getScene()),this);return t.id=e,t.name=e,this.clearCoat.copyTo(t.clearCoat),this.anisotropy.copyTo(t.anisotropy),this.brdf.copyTo(t.brdf),this.sheen.copyTo(t.sheen),this.subSurface.copyTo(t.subSurface),t}serialize(){let e=rG.p4.Serialize(this);return e.customType="BABYLON.PBRSpecularGlossinessMaterial",e.clearCoat=this.clearCoat.serialize(),e.anisotropy=this.anisotropy.serialize(),e.brdf=this.brdf.serialize(),e.sheen=this.sheen.serialize(),e.subSurface=this.subSurface.serialize(),e.iridescence=this.iridescence.serialize(),e}static Parse(e,t,i){let r=rG.p4.Parse(()=>new fy(e.name,t),e,t,i);return e.clearCoat&&r.clearCoat.parse(e.clearCoat,t,i),e.anisotropy&&r.anisotropy.parse(e.anisotropy,t,i),e.brdf&&r.brdf.parse(e.brdf,t,i),e.sheen&&r.sheen.parse(e.sheen,t,i),e.subSurface&&r.subSurface.parse(e.subSurface,t,i),e.iridescence&&r.iridescence.parse(e.iridescence,t,i),r}}(0,sx.gn)([(0,rG.n9)("diffuse"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_albedoColor")],fy.prototype,"diffuseColor",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_albedoTexture")],fy.prototype,"diffuseTexture",void 0),(0,sx.gn)([(0,rG.n9)("specular"),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityColor")],fy.prototype,"specularColor",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_microSurface")],fy.prototype,"glossiness",void 0),(0,sx.gn)([(0,rG.oU)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty","_reflectivityTexture")],fy.prototype,"specularGlossinessTexture",void 0),(0,rg.H)("BABYLON.PBRSpecularGlossinessMaterial",fy);class fA extends sV{constructor(e,t,i=null){if(super(t),!e)return;if(this._textureMatrix=rf.y3.Identity(),this.name=e,this.url=e,this._onLoad=i,this._texture=this._getFromCache(e,!0),this._texture)this._triggerOnLoad();else{let e=this.getScene();e&&e.useDelayedTextureLoading?this.delayLoadState=4:this._loadTexture()}}_triggerOnLoad(){this._onLoad&&this._onLoad()}getTextureMatrix(){return this._textureMatrix}_load3dlTexture(){let e;let t=this._getEngine();e=t._features.support3DTextures?t.createRawTexture3D(null,1,1,1,5,!1,!1,2,null,0):t.createRawTexture(null,1,1,5,!1,!1,2,null,0),this._texture=e,this._texture.isReady=!1,this.isCube=!1,this.is3D=t._features.support3DTextures,this.wrapU=0,this.wrapV=0,this.wrapR=0,this.anisotropicFilteringLevel=1;let i=i=>{let r;if("string"!=typeof i)return;let s=null,n=null,a=i.split("\n"),o=0,l=0,h=0,u=0,c=0;for(let e=0;e0&&(e+1)%4==0)s[e]=255;else{let t=n[e];s[e]=t/c*255}e.is3D?(e.updateSize(o,o,o),t.updateRawTexture3D(e,s,5,!1)):(e.updateSize(o*o,o),t.updateRawTexture(e,s,5,!1)),e.isReady=!0,this._triggerOnLoad()},r=this.getScene();return r?r._loadFile(this.url,i):t._loadFile(this.url,i),this._texture}_loadTexture(){this.url&&this.url.toLocaleLowerCase().indexOf(".3dl")==this.url.length-4&&this._load3dlTexture()}clone(){let e=new fA(this.url,this.getScene()||this._getEngine());return e.level=this.level,e}delayLoad(){4===this.delayLoadState&&(this.delayLoadState=1,this._texture=this._getFromCache(this.url,!0),this._texture||this._loadTexture())}static Parse(e,t){let i=null;return e.name&&!e.isRenderTarget&&((i=new fA(e.name,t)).name=e.name,i.level=e.level),i}serialize(){if(!this.name)return null;let e={};return e.name=this.name,e.level=this.level,e.customType="BABYLON.ColorGradingTexture",e}}fA._NoneEmptyLineRegex=/\S+/,(0,rg.H)("BABYLON.ColorGradingTexture",fA);class fR extends sV{constructor(e,t,i,r=!1,s=!0,n=null,a=null,o=!1){if(super(t),this._onLoad=null,this._onError=null,!e)throw Error("Image url is not set");this._coordinatesMode=sj.CUBIC_MODE,this.name=e,this.url=e,this._size=i,this._supersample=o,this._noMipmap=r,this.gammaSpace=s,this._onLoad=n,this._onError=a,this.hasAlpha=!1,this.isCube=!0,this._texture=this._getFromCache(e,this._noMipmap,void 0,void 0,void 0,this.isCube),this._texture?n&&(this._texture.isReady?sg.w1.SetImmediate(()=>n()):this._texture.onLoadedObservable.add(n)):t.useDelayedTextureLoading?this.delayLoadState=4:this._loadImage(()=>this._loadTexture(),this._onError)}_loadImage(e,t){let i=this.getScene();if(!i)return;let r=i.getEngine().createRawCubeTexture(null,this._size,4,i.getEngine().getCaps().textureFloat?1:7,this._noMipmap,!1,3);r.generateMipMaps=!this._noMipmap,i.addPendingData(r),r.url=this.url,r.isReady=!1,i.getEngine()._internalTexturesCache.push(r),this._texture=r;let s=document.createElement("canvas");(0,sB.r6)(this.url,t=>{this._width=t.width,this._height=t.height,s.width=this._width,s.height=this._height;let i=s.getContext("2d");i.drawImage(t,0,0);let r=i.getImageData(0,0,t.width,t.height);this._buffer=r.data.buffer,s.remove(),e()},(e,s)=>{i.removePendingData(r),t&&t(`${this.getClassName()} could not be loaded`,s)},i?i.offlineProvider:null)}_loadTexture(){let e=this.getScene();if(!e)return;let t=(()=>{let e=this._getFloat32ArrayFromArrayBuffer(this._buffer),t=_8.ConvertPanoramaToCubemap(e,this._width,this._height,this._size,this._supersample),i=[];for(let e=0;e<6;e++){let r=t[fR._FacesMapping[e]];i.push(r)}return i})(),i=this._texture;e.getEngine().updateRawCubeTexture(i,t,i.format,i.type,i.invertY),i.isReady=!0,e.removePendingData(i),i.onLoadedObservable.notifyObservers(i),i.onLoadedObservable.clear(),this._onLoad&&this._onLoad()}_getFloat32ArrayFromArrayBuffer(e){let t=new DataView(e),i=new Float32Array(3*e.byteLength/4),r=0;for(let s=0;st.length){rb.Y.Error("Unable to load TGA file - Not enough data");return}u+=c.id_length;let d=!1,p=!1,_=!1;switch(c.image_type){case 9:d=!0;case 1:p=!0;break;case 10:d=!0;case 2:break;case 11:d=!0;case 3:_=!0}let f=c.pixel_size>>3,m=c.width*c.height*f;if(p&&(r=t.subarray(u,u+=c.colormap_length*(c.colormap_size>>3))),d){let e,r,s;i=new Uint8Array(m);let n=0,a=new Uint8Array(f);for(;u>4){default:case 2:s=0,a=1,h=c.width,n=0,o=1,l=c.height;break;case 0:s=0,a=1,h=c.width,n=c.height-1,o=-1,l=-1;break;case 3:s=c.width-1,a=-1,h=-1,n=0,o=1,l=c.height;break;case 1:s=c.width-1,a=-1,h=-1,n=c.height-1,o=-1,l=-1}let g=fD["_getImageData"+(_?"Grey":"")+c.pixel_size+"bits"](c,r,i,n,o,l,s,a,h);e.getEngine()._uploadDataToTextureDirectly(e,g)}fP._DefaultOptions={generateMipMaps:!1,samplingMode:2,format:5,engine:null,scene:null};let fD={GetTGAHeader:fI,UploadContent:fM,_getImageData8bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+3]=255,f[(p+h*_)*4+2]=t[3*c+0],f[(p+h*_)*4+1]=t[3*c+1],f[(p+h*_)*4+0]=t[3*c+2];return f},_getImageData16bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d+=2){let e=((31744&(c=i[d+0]+(i[d+1]<<8)))>>10)*255/31|0,t=((992&c)>>5)*255/31|0,r=(31&c)*255/31|0;f[(p+h*_)*4+0]=e,f[(p+h*_)*4+1]=t,f[(p+h*_)*4+2]=r,f[(p+h*_)*4+3]=32768&c?0:255}return f},_getImageData24bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=3)_[(d+h*p)*4+3]=255,_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2];return _},_getImageData32bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=4)_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+1]=i[c+1],_[(d+h*p)*4+0]=i[c+2],_[(d+h*p)*4+3]=i[c+3];return _},_getImageDataGrey8bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c,d=0,p,_,f=new Uint8Array(h*u*4);for(_=r;_!==n;_+=s)for(p=a;p!==l;p+=o,d++)c=i[d],f[(p+h*_)*4+0]=c,f[(p+h*_)*4+1]=c,f[(p+h*_)*4+2]=c,f[(p+h*_)*4+3]=255;return f},_getImageDataGrey16bits:function(e,t,i,r,s,n,a,o,l){let h=e.width,u=e.height,c=0,d,p,_=new Uint8Array(h*u*4);for(p=r;p!==n;p+=s)for(d=a;d!==l;d+=o,c+=2)_[(d+h*p)*4+0]=i[c+0],_[(d+h*p)*4+1]=i[c+0],_[(d+h*p)*4+2]=i[c+0],_[(d+h*p)*4+3]=i[c+1];return _}};class fO{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".tga")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=fI(r);i(s.width,s.height,t.generateMipMaps,!1,()=>{fM(t,r)})}}sR.D._TextureLoaders.push(new fO);class fN{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".hdr")}loadCubeData(){throw".env not supported in Cube."}loadData(e,t,i){let r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=_7.RGBE_ReadHeader(r),n=_7.RGBE_ReadPixels(r,s),a=s.width*s.height,o=new Float32Array(4*a);for(let e=0;e{let e=t.getEngine();t.type=1,t.format=5,t._gammaSpace=!1,e._uploadDataToTextureDirectly(t,o)})}}sR.D._TextureLoaders.push(new fN),(eI=iI||(iI={}))[eI.cTFETC1=0]="cTFETC1",eI[eI.cTFETC2=1]="cTFETC2",eI[eI.cTFBC1=2]="cTFBC1",eI[eI.cTFBC3=3]="cTFBC3",eI[eI.cTFBC4=4]="cTFBC4",eI[eI.cTFBC5=5]="cTFBC5",eI[eI.cTFBC7=6]="cTFBC7",eI[eI.cTFPVRTC1_4_RGB=8]="cTFPVRTC1_4_RGB",eI[eI.cTFPVRTC1_4_RGBA=9]="cTFPVRTC1_4_RGBA",eI[eI.cTFASTC_4x4=10]="cTFASTC_4x4",eI[eI.cTFATC_RGB=11]="cTFATC_RGB",eI[eI.cTFATC_RGBA_INTERPOLATED_ALPHA=12]="cTFATC_RGBA_INTERPOLATED_ALPHA",eI[eI.cTFRGBA32=13]="cTFRGBA32",eI[eI.cTFRGB565=14]="cTFRGB565",eI[eI.cTFBGR565=15]="cTFBGR565",eI[eI.cTFRGBA4444=16]="cTFRGBA4444",eI[eI.cTFFXT1_RGB=17]="cTFFXT1_RGB",eI[eI.cTFPVRTC2_4_RGB=18]="cTFPVRTC2_4_RGB",eI[eI.cTFPVRTC2_4_RGBA=19]="cTFPVRTC2_4_RGBA",eI[eI.cTFETC2_EAC_R11=20]="cTFETC2_EAC_R11",eI[eI.cTFETC2_EAC_RG11=21]="cTFETC2_EAC_RG11";let fF={JSModuleURL:`${sg.w1._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`,WasmModuleURL:`${sg.w1._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm`},fL=null,fw=null,fB=0,fU=()=>(fL||(fL=new Promise((e,t)=>{fw?e(fw):sg.w1.LoadFileAsync(sg.w1.GetBabylonScriptURL(fF.WasmModuleURL)).then(i=>{if("function"!=typeof URL)return t("Basis transcoder requires an environment with a URL constructor");let r=URL.createObjectURL(new Blob([`(${fW})()`],{type:"application/javascript"}));fw=new Worker(r);let s=i=>{"init"===i.data.action?(fw.removeEventListener("message",s),e(fw)):"error"===i.data.action&&t(i.data.error||"error initializing worker")};fw.addEventListener("message",s),fw.postMessage({action:"init",url:sg.w1.GetBabylonScriptURL(fF.JSModuleURL),wasmBinary:i})}).catch(t)})),fL),fV=(e,t)=>{let i=e instanceof ArrayBuffer?new Uint8Array(e):e;return new Promise((e,r)=>{fU().then(()=>{let s=fB++,n=t=>{"transcode"===t.data.action&&t.data.id===s&&(fw.removeEventListener("message",n),t.data.success?e(t.data):r("Transcode is not supported on this device"))};fw.addEventListener("message",n);let a=new Uint8Array(i.byteLength);a.set(new Uint8Array(i.buffer,i.byteOffset,i.byteLength)),fw.postMessage({action:"transcode",id:s,imageData:a,config:t,ignoreSupportedFormats:!1},[a.buffer])},e=>{r(e)})})},fk=(e,t)=>{var i,r;let s=null===(i=t._gl)||void 0===i?void 0:i.TEXTURE_2D;e.isCube&&(s=null===(r=t._gl)||void 0===r?void 0:r.TEXTURE_CUBE_MAP),t._bindTextureDirectly(s,e,!0)},fG=(e,t)=>{let i=e.getEngine();for(let r=0;r{i._releaseTexture(t),fk(e,i)})}else e._invertVScale=!e.invertY,e.width=s.width+3&-4,e.height=s.height+3&-4,e.samplingMode=2,fk(e,i),i._uploadDataToTextureDirectly(e,new Uint16Array(s.transcodedPixels.buffer),r,0,4,!0)}else{e.width=s.width,e.height=s.height,e.generateMipMaps=t.fileInfo.images[r].levels.length>1;let n=fz.GetInternalFormatFromBasisFormat(t.format,i);e.format=n,fk(e,i),t.fileInfo.images[r].levels.forEach((t,s)=>{i._uploadCompressedDataToTextureDirectly(e,n,t.width,t.height,t.transcodedPixels,r,s)}),i._features.basisNeedsPOT&&(rk.R.Log2(e.width)%1!=0||rk.R.Log2(e.height)%1!=0)&&(sg.w1.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."),e._cachedWrapU=sj.CLAMP_ADDRESSMODE,e._cachedWrapV=sj.CLAMP_ADDRESSMODE)}}},fz={JSModuleURL:fF.JSModuleURL,WasmModuleURL:fF.WasmModuleURL,GetInternalFormatFromBasisFormat:(e,t)=>{let i;switch(e){case iI.cTFETC1:i=36196;break;case iI.cTFBC1:i=33776;break;case iI.cTFBC4:i=33779;break;case iI.cTFASTC_4x4:i=37808;break;case iI.cTFETC2:i=37496;break;case iI.cTFBC7:i=36492}if(void 0===i)throw"The chosen Basis transcoder format is not currently supported";return i},TranscodeAsync:fV,LoadTextureFromTranscodeResult:fG};function fW(){let e={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFBC7:6,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFRGB565:14},t=null;onmessage=i=>{if("init"===i.data.action){if(!t){try{importScripts(i.data.url)}catch(e){postMessage({action:"error",error:e})}t=BASIS({wasmBinary:i.data.wasmBinary})}null!==t&&t.then(e=>{BASIS=e,e.initializeBasis(),postMessage({action:"init"})})}else if("transcode"===i.data.action){var r;let t;let s=i.data.config,n=i.data.imageData,a=new BASIS.BasisFile(n),o=function(e){let t=e.getHasAlpha(),i=e.getNumImages(),r=[];for(let t=0;t>2&3],n[h++]=s[l>>4&3],n[h++]=s[l>>6&3]}}return n}(a,0,e.getImageWidth(t,i)+3&-4,e.getImageHeight(t,i)+3&-4)),a):null}(a,e,r,l,h);if(!s){u=!1;break}i.transcodedPixels=s,c.push(i.transcodedPixels.buffer)}}}a.close(),a.delete(),h&&(l=-1),u?postMessage({action:"transcode",success:u,id:i.data.id,fileInfo:o,format:l},c):postMessage({action:"transcode",success:u,id:i.data.id})}}}Object.defineProperty(fz,"JSModuleURL",{get:function(){return fF.JSModuleURL},set:function(e){fF.JSModuleURL=e}}),Object.defineProperty(fz,"WasmModuleURL",{get:function(){return fF.WasmModuleURL},set:function(e){fF.WasmModuleURL=e}});class fH{constructor(){this.supportCascades=!1}canLoad(e){return e.endsWith(".basis")}loadCubeData(e,t,i,r,s){if(Array.isArray(e))return;let n=t.getEngine().getCaps();fV(e,{supportedCompressionFormats:{etc1:!!n.etc1,s3tc:!!n.s3tc,pvrtc:!!n.pvrtc,etc2:!!n.etc2,astc:!!n.astc,bc7:!!n.bptc}}).then(e=>{let i=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;fG(t,e),t.getEngine()._setCubeMapTextureParams(t,i),t.isReady=!0,t.onLoadedObservable.notifyObservers(t),t.onLoadedObservable.clear(),r&&r()}).catch(e=>{sg.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),t.isReady=!0,s&&s(e)})}loadData(e,t,i){let r=t.getEngine().getCaps();fV(e,{supportedCompressionFormats:{etc1:!!r.etc1,s3tc:!!r.s3tc,pvrtc:!!r.pvrtc,etc2:!!r.etc2,astc:!!r.astc,bc7:!!r.bptc}}).then(e=>{let r=e.fileInfo.images[0].levels[0],s=e.fileInfo.images[0].levels.length>1&&t.generateMipMaps;i(r.width,r.height,s,-1!==e.format,()=>{fG(t,e)})}).catch(e=>{sg.w1.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"),sg.w1.Warn(`Failed to transcode Basis file: ${e}`),i(0,0,!1,!1,()=>{},!0)})}}sR.D._TextureLoaders.push(new fH);class fX extends as{get isSupported(){var e,t;return null!==(t=null===(e=this._engine)||void 0===e?void 0:e.getCaps().drawBuffersExtension)&&void 0!==t&&t}get textures(){return this._textures}get count(){return this._count}get depthTexture(){return this._textures[this._textures.length-1]}set wrapU(e){if(this._textures)for(let t=0;t0&&(this._createInternalTextures(),this._createTextures(n))}_initTypes(e,t,i,r,s,n,a,o,l,h){for(let u=0;u{this.onAfterRenderObservable.notifyObservers(t)})}dispose(e=!1){this._releaseTextures(),e?this._texture=null:this.releaseInternalTextures(),super.dispose()}releaseInternalTextures(){var e,t;let i=null===(e=this._renderTarget)||void 0===e?void 0:e.textures;if(i){for(let e=i.length-1;e>=0;e--)this._textures[e]._texture=null;null===(t=this._renderTarget)||void 0===t||t.dispose(),this._renderTarget=null}}}class fY{constructor(e,t,i){this.id=e,this.scale=t,this.offset=i}}class fj{constructor(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m;return this.name=e,this.meshes=t,this.scene=r,this.options=i,this.options.map=null!==(s=this.options.map)&&void 0!==s?s:["ambientTexture","bumpTexture","diffuseTexture","emissiveTexture","lightmapTexture","opacityTexture","reflectionTexture","refractionTexture","specularTexture"],this.options.uvsIn=null!==(n=this.options.uvsIn)&&void 0!==n?n:sm.o.UVKind,this.options.uvsOut=null!==(a=this.options.uvsOut)&&void 0!==a?a:sm.o.UVKind,this.options.layout=null!==(o=this.options.layout)&&void 0!==o?o:fj.LAYOUT_STRIP,this.options.layout===fj.LAYOUT_COLNUM&&(this.options.colnum=null!==(l=this.options.colnum)&&void 0!==l?l:8),this.options.updateInputMeshes=null===(h=this.options.updateInputMeshes)||void 0===h||h,this.options.disposeSources=null===(u=this.options.disposeSources)||void 0===u||u,this._expecting=0,this.options.fillBlanks=null===(c=this.options.fillBlanks)||void 0===c||c,!0===this.options.fillBlanks&&(this.options.customFillColor=null!==(d=this.options.customFillColor)&&void 0!==d?d:"black"),this.options.frameSize=null!==(p=this.options.frameSize)&&void 0!==p?p:256,this.options.paddingRatio=null!==(_=this.options.paddingRatio)&&void 0!==_?_:.0115,this._paddingValue=Math.ceil(this.options.frameSize*this.options.paddingRatio),this._paddingValue%2!=0&&this._paddingValue++,this.options.paddingMode=null!==(f=this.options.paddingMode)&&void 0!==f?f:fj.SUBUV_WRAP,this.options.paddingMode===fj.SUBUV_COLOR&&(this.options.paddingColor=null!==(m=this.options.paddingColor)&&void 0!==m?m:new rm.HE(0,0,0,1)),this.sets={},this.frames=[],this}_createFrames(e){let t=this._calculateSize(),i=new rf.FM(1,1).divide(t),r=0,s=this._expecting,n=this.meshes.length,a=Object.keys(this.sets);for(let e=0;e{this._calculateMeshUVFrames(o,l,t,i,this.options.updateInputMeshes||!1)};for(let i=0;i{r++,d.update(!1);let i=p.getImageData(0,0,h,h),n=this.sets[m];if(n.getContext().putImageData(i,t.x*_.x,t.y*_.y),d.dispose(),n.update(!1),r==s){u(),e();return}},m=a[c]||"_blank";if(n&&null!==n[m]){let e=n[m],t=new Image;e instanceof lq?t.src=e.getContext().canvas.toDataURL("image/png"):t.src=e.url,sg.w1.SetCorsBehavior(t.src,t),t.onload=()=>{p.fillStyle="rgba(0,0,0,0)",p.fillRect(0,0,h,h),d.update(!1),p.setTransform(1,0,0,-1,0,0);let e=[0,0,1,0,1,1,0,1,-1,1,-1,0,-2,0,-1,1,-1];switch(this.options.paddingMode){case 0:for(let i=0;i<9;i++)p.drawImage(t,0,0,t.width,t.height,l+o*e[i],l+o*e[i+1]-h,o,o);break;case 1:for(let e=0;e{e.dispose&&e.dispose()};for(let e=0;e{try{if(0===this.meshes.length){e();return}let t=0,i=i=>{if(t++,this.options.map){for(let e=0;e{i(n)})}}catch(e){return t(e)}})}dispose(){let e=Object.keys(this.sets);for(let t=0;t{let i={name:this.name,sets:{},options:{},frames:[]},r=Object.keys(this.sets),s=Object.keys(this.options);try{for(let s=0;s!0){if(!this.matricesIndices.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesIndices"===e.name&&t(e));i||(i=new nI("matricesIndices")).setAsAttribute("matricesIndices"),i.output.connectTo(this.matricesIndices)}if(!this.matricesWeights.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"matricesWeights"===e.name&&t(e));i||(i=new nI("matricesWeights")).setAsAttribute("matricesWeights"),i.output.connectTo(this.matricesWeights)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.World&&t(e));i||(i=new nI("world")).setAsSystemValue(tS.World),i.output.connectTo(this.world)}}provideFallbacks(e,t){e&&e.useBones&&e.computeBonesUsingShaders&&e.skeleton&&t.addCPUSkinningFallback(0,e)}bind(e,t,i){nE.G.BindBonesParameters(i,e)}prepareDefines(e,t,i){i._areAttributesDirty&&nE.G.PrepareDefinesForBones(e,i)}_buildBlock(e){super._buildBlock(e),e.sharedData.blocksWithFallbacks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.uniforms.push("boneTextureWidth"),e.uniforms.push("mBones"),e.samplers.push("boneSampler");let t=`//${this.name}`;e._emitFunctionFromInclude("bonesDeclaration",t,{removeAttributes:!0,removeUniforms:!1,removeVaryings:!0,removeIfDef:!1});let i=e._getFreeVariableName("influence");e.compilationString+=e._emitCodeFromInclude("bonesVertex",t,{replaceStrings:[{search:/finalWorld=finalWorld\*influence;/,replace:""},{search:/influence/gm,replace:i}]});let r=this._outputs[0],s=this.world;return e.compilationString+=`#if NUM_BONE_INFLUENCERS>0 +`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName} * ${i}; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(r,e)+` = ${s.associatedVariableName}; +`,e.compilationString+=`#endif +`,this}}(0,rg.H)("BABYLON.BonesBlock",fQ);class fZ extends nv{constructor(e){super(e,tm.Vertex),this.registerInput("world0",tf.Vector4),this.registerInput("world1",tf.Vector4),this.registerInput("world2",tf.Vector4),this.registerInput("world3",tf.Vector4),this.registerInput("world",tf.Matrix,!0),this.registerOutput("output",tf.Matrix),this.registerOutput("instanceID",tf.Float)}getClassName(){return"InstancesBlock"}get world0(){return this._inputs[0]}get world1(){return this._inputs[1]}get world2(){return this._inputs[2]}get world3(){return this._inputs[3]}get world(){return this._inputs[4]}get output(){return this._outputs[0]}get instanceID(){return this._outputs[1]}autoConfigure(e,t=()=>!0){if(!this.world0.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world0"===e.name&&t(e));i||(i=new nI("world0")).setAsAttribute("world0"),i.output.connectTo(this.world0)}if(!this.world1.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world1"===e.name&&t(e));i||(i=new nI("world1")).setAsAttribute("world1"),i.output.connectTo(this.world1)}if(!this.world2.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world2"===e.name&&t(e));i||(i=new nI("world2")).setAsAttribute("world2"),i.output.connectTo(this.world2)}if(!this.world3.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world3"===e.name&&t(e));i||(i=new nI("world3")).setAsAttribute("world3"),i.output.connectTo(this.world3)}if(!this.world.connectedPoint){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"world"===e.name&&t(e));i||(i=new nI("world")).setAsSystemValue(tS.World),i.output.connectTo(this.world)}this.world.define="!INSTANCES || THIN_INSTANCES"}prepareDefines(e,t,i,r=!1,s){let n=!1;i.INSTANCES!==r&&(i.setValue("INSTANCES",r),n=!0),s&&!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)!==i.THIN_INSTANCES&&(i.setValue("THIN_INSTANCES",!!(null==s?void 0:s.getRenderingMesh().hasThinInstances)),n=!0),n&&i.markAsUnprocessed()}_buildBlock(e){super._buildBlock(e);let t=e.sharedData.scene.getEngine();e.sharedData.blocksWithDefines.push(this);let i=this._outputs[0],r=this._outputs[1],s=this.world0,n=this.world1,a=this.world2,o=this.world3;return e.compilationString+=`#ifdef INSTANCES +`,e.compilationString+=this._declareOutput(i,e)+` = mat4(${s.associatedVariableName}, ${n.associatedVariableName}, ${a.associatedVariableName}, ${o.associatedVariableName}); +`,e.compilationString+=`#ifdef THIN_INSTANCES +`,e.compilationString+=`${i.associatedVariableName} = ${this.world.associatedVariableName} * ${i.associatedVariableName}; +`,e.compilationString+=`#endif +`,t._caps.canUseGLInstanceID?e.compilationString+=this._declareOutput(r,e)+` = float(gl_InstanceID); +`:e.compilationString+=this._declareOutput(r,e)+` = 0.0; +`,e.compilationString+=`#else +`,e.compilationString+=this._declareOutput(i,e)+` = ${this.world.associatedVariableName}; +`,e.compilationString+=this._declareOutput(r,e)+` = 0.0; +`,e.compilationString+=`#endif +`,this}}(0,rg.H)("BABYLON.InstancesBlock",fZ);class fJ extends nv{constructor(e){super(e,tm.Vertex),this.registerInput("position",tf.Vector3),this.registerInput("normal",tf.Vector3),this.registerInput("tangent",tf.AutoDetect),this.tangent.addExcludedConnectionPointFromAllowedTypes(tf.Color4|tf.Vector4|tf.Vector3),this.registerInput("uv",tf.Vector2),this.registerOutput("positionOutput",tf.Vector3),this.registerOutput("normalOutput",tf.Vector3),this.registerOutput("tangentOutput",tf.Vector4),this.registerOutput("uvOutput",tf.Vector2)}getClassName(){return"MorphTargetsBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get tangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get positionOutput(){return this._outputs[0]}get normalOutput(){return this._outputs[1]}get tangentOutput(){return this._outputs[2]}get uvOutput(){return this._outputs[3]}initialize(e){e._excludeVariableName("morphTargetInfluences")}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new nI("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new nI("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&t(e));i||(i=new nI("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new nI("uv")).setAsAttribute("uv"),i.output.connectTo(this.uv)}}prepareDefines(e,t,i){if(e.morphTargetManager){let t=e.morphTargetManager;(null==t?void 0:t.isUsingTextureForTargets)&&t.numInfluencers!==i.NUM_MORPH_INFLUENCERS&&i.markAsAttributesDirty()}i._areAttributesDirty&&nE.G.PrepareDefinesForMorphTargets(e,i)}bind(e,t,i){i&&i.morphTargetManager&&i.morphTargetManager.numInfluencers>0&&(nE.G.BindMorphTargetParameters(i,e),i.morphTargetManager.isUsingTextureForTargets&&i.morphTargetManager._bind(e))}replaceRepeatableContent(e,t,i,r){let s=this.position,n=this.normal,a=this.tangent,o=this.uv,l=this.positionOutput,h=this.normalOutput,u=this.tangentOutput,c=this.uvOutput,d=r.NUM_MORPH_INFLUENCERS,p=i.morphTargetManager,_=p&&p.supportsNormals&&r.NORMAL,f=p&&p.supportsTangents&&r.TANGENT,m=p&&p.supportsUVs&&r.UV1,g="";(null==p?void 0:p.isUsingTextureForTargets)&&d>0&&(g+=`float vertexID; +`);for(let e=0;e0)for(let t=0;t!0){if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.isSystemValue&&e.systemValue===tS.World&&t(e));i||(i=new nI("world")).setAsSystemValue(tS.World),i.output.connectTo(this.world)}if(!this.normal.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"normal"===e.name&&t(e));i||(i=new nI("normal")).setAsAttribute("normal"),i.output.connectTo(this.normal)}if(!this.tangent.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"tangent"===e.name&&e.type===tf.Vector4&&t(e));i||(i=new nI("tangent")).setAsAttribute("tangent"),i.output.connectTo(this.tangent)}}prepareDefines(e,t,i){var r,s,n,a;let o=this.normal,l=this.tangent,h=o.isConnected;(null===(r=o.connectInputBlock)||void 0===r?void 0:r.isAttribute)&&!e.isVerticesDataPresent(null===(s=o.connectInputBlock)||void 0===s?void 0:s.name)&&(h=!1);let u=l.isConnected;(null===(n=l.connectInputBlock)||void 0===n?void 0:n.isAttribute)&&!e.isVerticesDataPresent(null===(a=l.connectInputBlock)||void 0===a?void 0:a.name)&&(u=!1);let c=h&&u;i.setValue("TBNBLOCK",c,!0)}_buildBlock(e){super._buildBlock(e);let t=this.normal,i=this.tangent,r=this.world,s=this.TBN,n=this.row0,a=this.row1,o=this.row2;return e.target===tm.Fragment&&(e.compilationString+=` + // ${this.name} + vec3 tbnNormal = normalize(${t.associatedVariableName}).xyz; + vec3 tbnTangent = normalize(${i.associatedVariableName}.xyz); + vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${i.associatedVariableName}.w; + mat3 ${s.associatedVariableName} = mat3(${r.associatedVariableName}) * mat3(tbnTangent, tbnBitangent, tbnNormal); + `,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = vec3(${s.associatedVariableName}[0][0], ${s.associatedVariableName}[0][1], ${s.associatedVariableName}[0][2]); +`),a.hasEndpoints&&(e.compilationString+=this._declareOutput(a,e)+` = vec3(${s.associatedVariableName}[1[0], ${s.associatedVariableName}[1][1], ${s.associatedVariableName}[1][2]); +`),o.hasEndpoints&&(e.compilationString+=this._declareOutput(o,e)+` = vec3(${s.associatedVariableName}[2][0], ${s.associatedVariableName}[2][1], ${s.associatedVariableName}[2][2]); +`),e.sharedData.blocksWithDefines.push(this)),this}}(0,rg.H)("BABYLON.TBNBlock",f2);class f3 extends nv{constructor(e){super(e,tm.Fragment),this._tangentSpaceParameterName="",this._tangentCorrectionFactorName="",this._worldMatrixName="",this.invertX=!1,this.invertY=!1,this.useParallaxOcclusion=!1,this.useObjectSpaceNormalMap=!1,this._isUnique=!0,this.registerInput("worldPosition",tf.Vector4,!1),this.registerInput("worldNormal",tf.Vector4,!1),this.registerInput("worldTangent",tf.Vector4,!0),this.registerInput("uv",tf.Vector2,!1),this.registerInput("normalMapColor",tf.Color3,!1),this.registerInput("strength",tf.Float,!1),this.registerInput("viewDirection",tf.Vector3,!0),this.registerInput("parallaxScale",tf.Float,!0),this.registerInput("parallaxHeight",tf.Float,!0),this.registerInput("TBN",tf.Object,!0,tm.VertexAndFragment,new f$("TBN",this,tv.Input,f2,"TBNBlock")),this.registerInput("world",tf.Matrix,!0),this.registerOutput("output",tf.Vector4),this.registerOutput("uvOffset",tf.Vector2)}getClassName(){return"PerturbNormalBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get worldTangent(){return this._inputs[2]}get uv(){return this._inputs[3]}get normalMapColor(){return this._inputs[4]}get strength(){return this._inputs[5]}get viewDirection(){return this._inputs[6]}get parallaxScale(){return this._inputs[7]}get parallaxHeight(){return this._inputs[8]}get TBN(){return this._inputs[9]}get world(){return this._inputs[10]}get output(){return this._outputs[0]}get uvOffset(){return this._outputs[1]}prepareDefines(e,t,i){let r=this.normalMapColor.connectedPoint._ownerBlock.samplerName,s=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&r||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected);i.setValue("BUMP",!0),i.setValue("PARALLAX",s,!0),i.setValue("PARALLAX_RHS",t.getScene().useRightHandedSystem,!0),i.setValue("PARALLAXOCCLUSION",this.useParallaxOcclusion,!0),i.setValue("OBJECTSPACE_NORMALMAP",this.useObjectSpaceNormalMap,!0)}bind(e,t,i){t.getScene()._mirroredCameraPosition?e.setFloat2(this._tangentSpaceParameterName,this.invertX?1:-1,this.invertY?1:-1):e.setFloat2(this._tangentSpaceParameterName,this.invertX?-1:1,this.invertY?-1:1),i&&(e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1),this.useObjectSpaceNormalMap&&!this.world.isConnected&&e.setMatrix(this._worldMatrixName,i.getWorldMatrix()))}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"uv"===e.name&&t(e));i||(i=new nI("uv")).setAsAttribute(),i.output.connectTo(this.uv)}if(!this.strength.isConnected){let e=new nI("strength");e.value=1,e.output.connectTo(this.strength)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`,i=this.uv,r=this.worldPosition,s=this.worldNormal,n=this.worldTangent;e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentSpaceParameterName=e._getFreeDefineName("tangentSpaceParameter"),e._emitUniformFromString(this._tangentSpaceParameterName,"vec2"),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float"),this._worldMatrixName=e._getFreeDefineName("perturbNormalWorldMatrix"),e._emitUniformFromString(this._worldMatrixName,"mat4");let a=null;this.normalMapColor.connectedPoint&&(a=this.normalMapColor.connectedPoint._ownerBlock.samplerName);let o=this.viewDirection.isConnected&&(this.useParallaxOcclusion&&a||!this.useParallaxOcclusion&&this.parallaxHeight.isConnected),l=this.parallaxScale.isConnectedToInputBlock?this.parallaxScale.connectInputBlock.isConstant?e._emitFloat(this.parallaxScale.connectInputBlock.value):this.parallaxScale.associatedVariableName:"0.05",h=this.strength.isConnectedToInputBlock&&this.strength.connectInputBlock.isConstant?` +#if !defined(NORMALXYSCALE) +1.0/ +#endif +${e._emitFloat(this.strength.connectInputBlock.value)}`:` +#if !defined(NORMALXYSCALE) +1.0/ +#endif +${this.strength.associatedVariableName}`;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let u={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},c=this.TBN;c.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${c.associatedVariableName}; + #endif + `:n.isConnected&&(e.compilationString+=`vec3 tbnNormal = normalize(${s.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); +`,e.compilationString+=`vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +`,e.compilationString+=`mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",t,{replaceStrings:[u,{search:/varying mat3 vTBN;/g,replace:""},{search:/uniform mat4 normalMatrix;/g,replace:""}]}),e._emitFunctionFromInclude("bumpFragmentFunctions",t,{replaceStrings:[{search:/#include\(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump\)/g,replace:""},{search:/uniform sampler2D bumpSampler;/g,replace:""},{search:/vec2 parallaxOcclusion\(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale\)/g,replace:"#define inline\nvec2 parallaxOcclusion(vec3 vViewDirCoT, vec3 vNormalCoT, vec2 texCoord, float parallaxScale, sampler2D bumpSampler)"},{search:/vec2 parallaxOffset\(vec3 viewDir,float heightScale\)/g,replace:"vec2 parallaxOffset(vec3 viewDir, float heightScale, float height_)"},{search:/texture2D\(bumpSampler,vBumpUV\)\.w/g,replace:"height_"}]});let d=o&&a?`texture2D(${a}, ${i.associatedVariableName} + uvOffset).xyz`:this.normalMapColor.associatedVariableName;return e.compilationString+=this._declareOutput(this.output,e)+" = vec4(0.);\n",e.compilationString+=e._emitCodeFromInclude("bumpFragment",t,{replaceStrings:[{search:/texture2D\(bumpSampler,vBumpUV\)/g,replace:`${d}`},{search:/#define CUSTOM_FRAGMENT_BUMP_FRAGMENT/g,replace:`mat4 normalMatrix = toNormalMatrix(${this.world.isConnected?this.world.associatedVariableName:this._worldMatrixName});`},{search:/perturbNormal\(TBN,texture2D\(bumpSampler,vBumpUV\+uvOffset\).xyz,vBumpInfos.y\)/g,replace:`perturbNormal(TBN, ${d}, vBumpInfos.y)`},{search:/parallaxOcclusion\(invTBN\*-viewDirectionW,invTBN\*normalW,vBumpUV,vBumpInfos.z\)/g,replace:`parallaxOcclusion((invTBN * -viewDirectionW), (invTBN * normalW), vBumpUV, vBumpInfos.z, ${o&&this.useParallaxOcclusion?a:"bumpSampler"})`},{search:/parallaxOffset\(invTBN\*viewDirectionW,vBumpInfos\.z\)/g,replace:`parallaxOffset(invTBN * viewDirectionW, vBumpInfos.z, ${o?this.parallaxHeight.associatedVariableName:"0."})`},{search:/vTangentSpaceParams/g,replace:this._tangentSpaceParameterName},{search:/vBumpInfos.y/g,replace:h},{search:/vBumpInfos.z/g,replace:l},{search:/vBumpUV/g,replace:i.associatedVariableName},{search:/vPositionW/g,replace:r.associatedVariableName+".xyz"},{search:/normalW=/g,replace:this.output.associatedVariableName+".xyz = "},{search:/mat3\(normalMatrix\)\*normalW/g,replace:"mat3(normalMatrix) * "+this.output.associatedVariableName+".xyz"},{search:/normalW/g,replace:s.associatedVariableName+".xyz"},{search:/viewDirectionW/g,replace:o?this.viewDirection.associatedVariableName:"vec3(0.)"},u]}),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.invertX = ${this.invertX}; +`+`${this._codeVariableName}.invertY = ${this.invertY}; +${this._codeVariableName}.useParallaxOcclusion = ${this.useParallaxOcclusion}; +${this._codeVariableName}.useObjectSpaceNormalMap = ${this.useObjectSpaceNormalMap}; +`}serialize(){let e=super.serialize();return e.invertX=this.invertX,e.invertY=this.invertY,e.useParallaxOcclusion=this.useParallaxOcclusion,e.useObjectSpaceNormalMap=this.useObjectSpaceNormalMap,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.invertX=e.invertX,this.invertY=e.invertY,this.useParallaxOcclusion=!!e.useParallaxOcclusion,this.useObjectSpaceNormalMap=!!e.useObjectSpaceNormalMap}}(0,sx.gn)([nS("Invert X axis",tx.Boolean,"PROPERTIES",{notifiers:{update:!1}})],f3.prototype,"invertX",void 0),(0,sx.gn)([nS("Invert Y axis",tx.Boolean,"PROPERTIES",{notifiers:{update:!1}})],f3.prototype,"invertY",void 0),(0,sx.gn)([nS("Use parallax occlusion",tx.Boolean)],f3.prototype,"useParallaxOcclusion",void 0),(0,sx.gn)([nS("Object Space Mode",tx.Boolean,"PROPERTIES",{notifiers:{update:!1}})],f3.prototype,"useObjectSpaceNormalMap",void 0),(0,rg.H)("BABYLON.PerturbNormalBlock",f3);class f4 extends nv{constructor(e){super(e,tm.Fragment,!0),this.registerInput("value",tf.Float,!0),this.registerInput("cutoff",tf.Float,!0)}getClassName(){return"DiscardBlock"}get value(){return this._inputs[0]}get cutoff(){return this._inputs[1]}_buildBlock(e){if(super._buildBlock(e),e.sharedData.hints.needAlphaTesting=!0,this.cutoff.isConnected&&this.value.isConnected)return e.compilationString+=`if (${this.value.associatedVariableName} < ${this.cutoff.associatedVariableName}) discard; +`,this}}(0,rg.H)("BABYLON.DiscardBlock",f4);class f5 extends nv{constructor(e){super(e,tm.Fragment),this.registerOutput("output",tf.Float,tm.Fragment)}getClassName(){return"FrontFacingBlock"}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),e.target===tm.Vertex)throw"FrontFacingBlock must only be used in a fragment shader";let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = gl_FrontFacing ? 1.0 : 0.0; +`,this}}(0,rg.H)("BABYLON.FrontFacingBlock",f5);class f6 extends nv{constructor(e){super(e,tm.Fragment),this.registerInput("input",tf.AutoDetect,!1),this.registerOutput("dx",tf.BasedOnInput),this.registerOutput("dy",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._outputs[1]._typeConnectionSource=this._inputs[0]}getClassName(){return"DerivativeBlock"}get input(){return this._inputs[0]}get dx(){return this._outputs[0]}get dy(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._outputs[1];return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),t.hasEndpoints&&(e.compilationString+=this._declareOutput(t,e)+` = dFdx(${this.input.associatedVariableName}); +`),i.hasEndpoints&&(e.compilationString+=this._declareOutput(i,e)+` = dFdy(${this.input.associatedVariableName}); +`),this}}(0,rg.H)("BABYLON.DerivativeBlock",f6);class f8 extends nv{constructor(e){super(e,tm.Fragment),this.registerOutput("xy",tf.Vector2,tm.Fragment),this.registerOutput("xyz",tf.Vector3,tm.Fragment),this.registerOutput("xyzw",tf.Vector4,tm.Fragment),this.registerOutput("x",tf.Float,tm.Fragment),this.registerOutput("y",tf.Float,tm.Fragment),this.registerOutput("z",tf.Float,tm.Fragment),this.registerOutput("w",tf.Float,tm.Fragment)}getClassName(){return"FragCoordBlock"}get xy(){return this._outputs[0]}get xyz(){return this._outputs[1]}get xyzw(){return this._outputs[2]}get x(){return this._outputs[3]}get y(){return this._outputs[4]}get z(){return this._outputs[5]}get output(){return this._outputs[6]}writeOutputs(e){let t="";for(let i of this._outputs)i.hasEndpoints&&(t+=`${this._declareOutput(i,e)} = gl_FragCoord.${i.name}; +`);return t}_buildBlock(e){if(super._buildBlock(e),e.target===tm.Vertex)throw"FragCoordBlock must only be used in a fragment shader";return e.compilationString+=this.writeOutputs(e),this}}(0,rg.H)("BABYLON.FragCoordBlock",f8);class f7 extends nv{constructor(e){super(e,tm.Fragment),this.registerOutput("xy",tf.Vector2,tm.Fragment),this.registerOutput("x",tf.Float,tm.Fragment),this.registerOutput("y",tf.Float,tm.Fragment)}getClassName(){return"ScreenSizeBlock"}get xy(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}bind(e){let t=this._scene.getEngine();e.setFloat2(this._varName,t.getRenderWidth(),t.getRenderHeight())}writeOutputs(e,t){let i="";for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; +`);return i}_buildBlock(e){if(super._buildBlock(e),this._scene=e.sharedData.scene,e.target===tm.Vertex)throw"ScreenSizeBlock must only be used in a fragment shader";return e.sharedData.bindableBlocks.push(this),this._varName=e._getFreeVariableName("screenSize"),e._emitUniformFromString(this._varName,"vec2"),e.compilationString+=this.writeOutputs(e,this._varName),this}}(0,rg.H)("BABYLON.ScreenSizeBlock",f7);class f9 extends nv{constructor(e){super(e,tm.Fragment),this.registerInput("vector",tf.AutoDetect),this.registerInput("worldViewProjection",tf.Matrix),this.registerOutput("output",tf.Vector2),this.registerOutput("x",tf.Float),this.registerOutput("y",tf.Float),this.inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Vector4)}getClassName(){return"ScreenSpaceBlock"}get vector(){return this._inputs[0]}get worldViewProjection(){return this._inputs[1]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.worldViewProjection.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.WorldViewProjection&&t(e));i||(i=new nI("worldViewProjection")).setAsSystemValue(tS.WorldViewProjection),i.output.connectTo(this.worldViewProjection)}}_buildBlock(e){super._buildBlock(e);let t=this.vector,i=this.worldViewProjection;if(!t.connectedPoint)return;let r=i.associatedVariableName,s=e._getFreeVariableName("screenSpaceTemp");switch(t.connectedPoint.type){case tf.Vector3:e.compilationString+=`vec4 ${s} = ${r} * vec4(${t.associatedVariableName}, 1.0); +`;break;case tf.Vector4:e.compilationString+=`vec4 ${s} = ${r} * ${t.associatedVariableName}; +`}return e.compilationString+=`${s}.xy /= ${s}.w;`,e.compilationString+=`${s}.xy = ${s}.xy * 0.5 + vec2(0.5, 0.5);`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${s}.xy; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${s}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${s}.y; +`),this}}(0,rg.H)("BABYLON.ScreenSpaceBlock",f9);class me extends nv{constructor(e){super(e,tm.Fragment),this.registerInput("input",tf.Vector2),this.registerInput("strength",tf.Float),this.registerInput("center",tf.Vector2),this.registerInput("offset",tf.Vector2),this.registerOutput("output",tf.Vector2),this.registerOutput("x",tf.Float),this.registerOutput("y",tf.Float)}getClassName(){return"TwirlBlock"}get input(){return this._inputs[0]}get strength(){return this._inputs[1]}get center(){return this._inputs[2]}get offset(){return this._inputs[3]}get output(){return this._outputs[0]}get x(){return this._outputs[1]}get y(){return this._outputs[2]}autoConfigure(){if(!this.center.isConnected){let e=new nI("center");e.value=new rf.FM(.5,.5),e.output.connectTo(this.center)}if(!this.strength.isConnected){let e=new nI("strength");e.value=1,e.output.connectTo(this.strength)}if(!this.offset.isConnected){let e=new nI("offset");e.value=new rf.FM(0,0),e.output.connectTo(this.offset)}}_buildBlock(e){super._buildBlock(e);let t=e._getFreeVariableName("delta"),i=e._getFreeVariableName("angle"),r=e._getFreeVariableName("x"),s=e._getFreeVariableName("y"),n=e._getFreeVariableName("result");return e.compilationString+=` + vec2 ${t} = ${this.input.associatedVariableName} - ${this.center.associatedVariableName}; + float ${i} = ${this.strength.associatedVariableName} * length(${t}); + float ${r} = cos(${i}) * ${t}.x - sin(${i}) * ${t}.y; + float ${s} = sin(${i}) * ${t}.x + cos(${i}) * ${t}.y; + vec2 ${n} = vec2(${r} + ${this.center.associatedVariableName}.x + ${this.offset.associatedVariableName}.x, ${s} + ${this.center.associatedVariableName}.y + ${this.offset.associatedVariableName}.y); + `,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${n}; +`),this.x.hasEndpoints&&(e.compilationString+=this._declareOutput(this.x,e)+` = ${n}.x; +`),this.y.hasEndpoints&&(e.compilationString+=this._declareOutput(this.y,e)+` = ${n}.y; +`),this}}(0,rg.H)("BABYLON.TwirlBlock",me);class mt extends nv{constructor(e){super(e,tm.Fragment),this.generateInWorldSpace=!1,this.automaticNormalizationNormal=!0,this.automaticNormalizationTangent=!0,this.registerInput("input",tf.Float),this.registerInput("worldPosition",tf.Vector3),this.registerInput("worldNormal",tf.Vector3),this.registerInput("worldTangent",tf.AutoDetect,!0),this.registerOutput("output",tf.Vector4),this.registerOutput("xyz",tf.Vector3),this._inputs[3].addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Vector4)}getClassName(){return"HeightToNormalBlock"}get input(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get worldTangent(){return this._inputs[3]}get output(){return this._outputs[0]}get xyz(){return this._outputs[1]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];this.generateInWorldSpace||this.worldTangent.isConnected||rb.Y.Error(`You must connect the 'worldTangent' input of the ${this.name} block!`);let i=this.generateInWorldSpace?"":` + vec3 biTangent = cross(normal, tangent); + mat3 TBN = mat3(tangent, biTangent, normal); + `,r=this.generateInWorldSpace?"":` + result = TBN * result; + result = result * vec3(0.5) + vec3(0.5); + `,s=` + vec4 heightToNormal(in float height, in vec3 position, in vec3 tangent, in vec3 normal) { + ${i} + ${this.automaticNormalizationTangent?"tangent = normalize(tangent);":""} + ${this.automaticNormalizationNormal?"normal = normalize(normal);":""} + vec3 worlddX = dFdx(position); + vec3 worlddY = dFdy(position); + vec3 crossX = cross(normal, worlddX); + vec3 crossY = cross(normal, worlddY); + float d = abs(dot(crossY, worlddX)); + vec3 inToNormal = vec3(((((height + dFdx(height)) - height) * crossY) + (((height + dFdy(height)) - height) * crossX)) * sign(d)); + inToNormal.y *= -1.0; + vec3 result = normalize((d * normal) - inToNormal); + ${r} + return vec4(result, 0.); + }`;return e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitFunction("heightToNormal",s,"// heightToNormal"),e.compilationString+=this._declareOutput(t,e)+` = heightToNormal(${this.input.associatedVariableName}, ${this.worldPosition.associatedVariableName}, ${this.worldTangent.isConnected?this.worldTangent.associatedVariableName:"vec3(0.)"}.xyz, ${this.worldNormal.associatedVariableName}); +`,this.xyz.hasEndpoints&&(e.compilationString+=this._declareOutput(this.xyz,e)+` = ${this.output.associatedVariableName}.xyz; +`),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.generateInWorldSpace = ${this.generateInWorldSpace}; +${this._codeVariableName}.automaticNormalizationNormal = ${this.automaticNormalizationNormal}; +${this._codeVariableName}.automaticNormalizationTangent = ${this.automaticNormalizationTangent}; +`}serialize(){let e=super.serialize();return e.generateInWorldSpace=this.generateInWorldSpace,e.automaticNormalizationNormal=this.automaticNormalizationNormal,e.automaticNormalizationTangent=this.automaticNormalizationTangent,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.generateInWorldSpace=e.generateInWorldSpace,this.automaticNormalizationNormal=e.automaticNormalizationNormal,this.automaticNormalizationTangent=e.automaticNormalizationTangent}}(0,sx.gn)([nS("Generate in world space instead of tangent space",tx.Boolean,"PROPERTIES",{notifiers:{update:!0}})],mt.prototype,"generateInWorldSpace",void 0),(0,sx.gn)([nS("Force normalization for the worldNormal input",tx.Boolean,"PROPERTIES",{notifiers:{update:!0}})],mt.prototype,"automaticNormalizationNormal",void 0),(0,sx.gn)([nS("Force normalization for the worldTangent input",tx.Boolean,"PROPERTIES",{notifiers:{update:!0}})],mt.prototype,"automaticNormalizationTangent",void 0),(0,rg.H)("BABYLON.HeightToNormalBlock",mt);class mi extends nv{constructor(e){super(e,tm.Fragment,!0),this.registerInput("depth",tf.Float,!0),this.registerInput("worldPos",tf.Vector4,!0),this.registerInput("viewProjection",tf.Matrix,!0)}getClassName(){return"FragDepthBlock"}get depth(){return this._inputs[0]}get worldPos(){return this._inputs[1]}get viewProjection(){return this._inputs[2]}_buildBlock(e){return super._buildBlock(e),this.depth.isConnected?e.compilationString+=`gl_FragDepth = ${this.depth.associatedVariableName}; +`:this.worldPos.isConnected&&this.viewProjection.isConnected?e.compilationString+=` + vec4 p = ${this.viewProjection.associatedVariableName} * ${this.worldPos.associatedVariableName}; + float v = p.z / p.w; + #ifndef IS_NDC_HALF_ZRANGE + v = v * 0.5 + 0.5; + #endif + gl_FragDepth = v; + + `:rb.Y.Warn("FragDepthBlock: either the depth input or both the worldPos and viewProjection inputs must be connected!"),this}}(0,rg.H)("BABYLON.FragDepthBlock",mi);class mr extends nv{constructor(e){super(e,tm.Fragment),this.registerInput("worldPosition",tf.Vector4,!1),this.registerInput("viewProjection",tf.Matrix,!1),this.registerInput("worldNormal",tf.AutoDetect,!0),this.registerOutput("depth",tf.Vector3),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Vector4)}getClassName(){return"ShadowMapBlock"}initialize(e){e._excludeVariableName("vPositionWSM"),e._excludeVariableName("lightDataSM"),e._excludeVariableName("biasAndScaleSM"),e._excludeVariableName("depthValuesSM"),e._excludeVariableName("clipPos"),e._excludeVariableName("worldPos"),e._excludeVariableName("zSM")}get worldPosition(){return this._inputs[0]}get viewProjection(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get depth(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;return e._emitUniformFromString("biasAndScaleSM","vec3"),e._emitUniformFromString("lightDataSM","vec3"),e._emitUniformFromString("depthValuesSM","vec2"),e._emitFunctionFromInclude("packingFunctions",t),e.compilationString+=`vec4 worldPos = ${this.worldPosition.associatedVariableName}; +`,e.compilationString+=`vec3 vPositionWSM; +`,e.compilationString+=`float vDepthMetricSM = 0.0; +`,e.compilationString+=`float zSM; +`,this.worldNormal.isConnected&&(e.compilationString+=`vec3 vNormalW = ${this.worldNormal.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexNormalBias",t)),e.compilationString+=`vec4 clipPos = ${this.viewProjection.associatedVariableName} * worldPos; +`,e.compilationString+=e._emitCodeFromInclude("shadowMapVertexMetric",t,{replaceStrings:[{search:/gl_Position/g,replace:"clipPos"}]}),e.compilationString+=e._emitCodeFromInclude("shadowMapFragment",t,{replaceStrings:[{search:/return;/g,replace:""}]}),e.compilationString+=` + #if SM_DEPTHTEXTURE == 1 + #ifdef IS_NDC_HALF_ZRANGE + gl_FragDepth = (clipPos.z / clipPos.w); + #else + gl_FragDepth = (clipPos.z / clipPos.w) * 0.5 + 0.5; + #endif + #endif + `,e.compilationString+=`${this._declareOutput(this.depth,e)} = vec3(depthSM, 1., 1.); +`,this}}(0,rg.H)("BABYLON.ShadowMapBlock",mr);class ms extends nv{constructor(e){super(e,tm.Fragment,!0),this.registerInput("viewDepth",tf.Float,!0),this.registerInput("worldPosition",tf.AutoDetect,!0),this.registerInput("viewNormal",tf.AutoDetect,!0),this.registerInput("reflectivity",tf.AutoDetect,!0),this.inputs[1].addExcludedConnectionPointFromAllowedTypes(tf.Vector3|tf.Vector4),this.inputs[2].addExcludedConnectionPointFromAllowedTypes(tf.Vector3|tf.Vector4),this.inputs[3].addExcludedConnectionPointFromAllowedTypes(tf.Vector3|tf.Vector4|tf.Color3|tf.Color4)}getClassName(){return"PrePassOutputBlock"}get viewDepth(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get viewNormal(){return this._inputs[2]}get reflectivity(){return this._inputs[3]}_buildBlock(e){super._buildBlock(e);let t=this.worldPosition,i=this.viewNormal,r=this.viewDepth,s=this.reflectivity;e.sharedData.blocksWithDefines.push(this);let n=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",n),e.compilationString+=`#if defined(PREPASS)\r +`,e.compilationString+=`#ifdef PREPASS_DEPTH\r +`,r.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(${r.associatedVariableName}, 0.0, 0.0, 1.0);\r +`:e.compilationString+=` gl_FragData[PREPASS_DEPTH_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_POSITION\r +`,t.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(${t.associatedVariableName}.rgb, ${t.connectedPoint.type===tf.Vector4?t.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_POSITION_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_NORMAL\r +`,i.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(${i.associatedVariableName}.rgb, ${i.connectedPoint.type===tf.Vector4?i.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_NORMAL_INDEX] = vec4(0.0, 0.0, 0.0, 0.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#ifdef PREPASS_REFLECTIVITY\r +`,s.connectedPoint?e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(${s.associatedVariableName}.rgb, ${s.connectedPoint.type===tf.Vector4?s.associatedVariableName+".a":"1.0"});\r +`:e.compilationString+=` gl_FragData[PREPASS_REFLECTIVITY_INDEX] = vec4(0.0, 0.0, 0.0, 1.0);\r +`,e.compilationString+=`#endif\r +`,e.compilationString+=`#endif\r +`,this}}(0,rg.H)("BABYLON.PrePassOutputBlock",ms);class mn extends nv{constructor(e){super(e,tm.VertexAndFragment,!1),this.registerInput("worldPosition",tf.Vector4,!1,tm.Vertex),this.registerInput("view",tf.Matrix,!1,tm.Vertex),this.registerInput("input",tf.AutoDetect,!1,tm.Fragment),this.registerInput("fogColor",tf.AutoDetect,!1,tm.Fragment),this.registerOutput("output",tf.Color3,tm.Fragment),this.input.addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Color4),this.fogColor.addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Color4)}getClassName(){return"FogBlock"}get worldPosition(){return this._inputs[0]}get view(){return this._inputs[1]}get input(){return this._inputs[2]}get fogColor(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(e,t=()=>!0){if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.View&&t(e));i||(i=new nI("view")).setAsSystemValue(tS.View),i.output.connectTo(this.view)}if(!this.fogColor.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.FogColor&&t(e));i||(i=new nI("fogColor",void 0,tf.Color3)).setAsSystemValue(tS.FogColor),i.output.connectTo(this.fogColor)}}prepareDefines(e,t,i){let r=e.getScene();i.setValue("FOG",t.fogEnabled&&nE.G.GetFogState(e,r))}bind(e,t,i){if(!i)return;let r=i.getScene();e.setFloat4(this._fogParameters,r.fogMode,r.fogStart,r.fogEnd,r.fogDensity)}_buildBlock(e){if(super._buildBlock(e),e.target===tm.Fragment){e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),e._emitFunctionFromInclude("fogFragmentDeclaration",`//${this.name}`,{removeUniforms:!0,removeVaryings:!0,removeIfDef:!1,replaceStrings:[{search:/float CalcFogFactor\(\)/,replace:"float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)"}]});let t=e._getFreeVariableName("fog"),i=this.input,r=this.fogColor;this._fogParameters=e._getFreeVariableName("fogParameters");let s=this._outputs[0];e._emitUniformFromString(this._fogParameters,"vec4"),e.compilationString+=`#ifdef FOG +`,e.compilationString+=`float ${t} = CalcFogFactor(${this._fogDistanceName}, ${this._fogParameters}); +`,e.compilationString+=this._declareOutput(s,e)+` = ${t} * ${i.associatedVariableName}.rgb + (1.0 - ${t}) * ${r.associatedVariableName}.rgb; +`,e.compilationString+=`#else +${this._declareOutput(s,e)} = ${i.associatedVariableName}.rgb; +`,e.compilationString+=`#endif +`}else{let t=this.worldPosition,i=this.view;this._fogDistanceName=e._getFreeVariableName("vFogDistance"),e._emitVaryingFromString(this._fogDistanceName,"vec3"),e.compilationString+=`${this._fogDistanceName} = (${i.associatedVariableName} * ${t.associatedVariableName}).xyz; +`}return this}}(0,rg.H)("BABYLON.FogBlock",mn);class ma extends nv{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,rb.Y.Error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tm.Fragment:tm.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tm.Fragment:tm.Vertex}constructor(e){super(e,tm.VertexAndFragment),this._lightId=0,this.generateOnlyFragmentCode=!1,this._isUnique=!0,this.registerInput("worldPosition",tf.Vector4,!1,tm.Vertex),this.registerInput("worldNormal",tf.Vector4,!1,tm.Fragment),this.registerInput("cameraPosition",tf.Vector3,!1,tm.Fragment),this.registerInput("glossiness",tf.Float,!0,tm.Fragment),this.registerInput("glossPower",tf.Float,!0,tm.Fragment),this.registerInput("diffuseColor",tf.Color3,!0,tm.Fragment),this.registerInput("specularColor",tf.Color3,!0,tm.Fragment),this.registerInput("view",tf.Matrix,!0),this.registerOutput("diffuseOutput",tf.Color3,tm.Fragment),this.registerOutput("specularOutput",tf.Color3,tm.Fragment),this.registerOutput("shadow",tf.Float,tm.Fragment)}getClassName(){return"LightBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get cameraPosition(){return this._inputs[2]}get glossiness(){return this._inputs[3]}get glossPower(){return this._inputs[4]}get diffuseColor(){return this._inputs[5]}get specularColor(){return this._inputs[6]}get view(){return this._inputs[7]}get diffuseOutput(){return this._outputs[0]}get specularOutput(){return this._outputs[1]}get shadow(){return this._outputs[2]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.CameraPosition&&t(e));i||(i=new nI("cameraPosition")).setAsSystemValue(tS.CameraPosition),i.output.connectTo(this.cameraPosition)}}prepareDefines(e,t,i){if(!i._areLightsDirty)return;let r=e.getScene();if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};nE.G.PrepareDefinesForLight(r,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else nE.G.PrepareDefinesForLights(r,e,i,!0,t.maxSimultaneousLights)}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;nE.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}bind(e,t,i){if(!i)return;let r=i.getScene();this.light?nE.G.BindLight(this.light,this._lightId,r,e,!0):nE.G.BindLights(r,i,e,!0,t.maxSimultaneousLights)}_injectVertexCode(e){let t=this.worldPosition,i=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",i,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));let r="v_"+t.associatedVariableName;e._emitVaryingFromString(r,"vec4")&&(e.compilationString+=`${r} = ${t.associatedVariableName}; +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:t.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${t.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",i,{repeatKey:"maxSimultaneousLights"}))}_buildBlock(e){if(super._buildBlock(e),e.target!==tm.Fragment){this._injectVertexCode(e);return}this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this),e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this);let t=`//${this.name}`,i=this.worldPosition,r=i.associatedVariableName;this.generateOnlyFragmentCode?(r=e._getFreeVariableName("globalWorldPos"),e._emitFunction("light_globalworldpos",`vec3 ${r}; +`,t),e.compilationString+=`${r} = ${i.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${i.associatedVariableName}`:void 0})):r="v_"+r+".xyz",e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("lightsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),e._emitFunctionFromInclude("shadowsFragmentFunctions",t,{replaceStrings:[{search:/vPositionW/g,replace:r}]}),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",t,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),0===this._lightId&&(e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${r}); +`),e.compilationString+=`lightingInfo info; +`,e.compilationString+=`float shadow = 1.; +`,e.compilationString+=`float aggShadow = 0.; +`,e.compilationString+=`float numLights = 0.; +`,e.compilationString+=`float glossiness = ${this.glossiness.isConnected?this.glossiness.associatedVariableName:"1.0"} * ${this.glossPower.isConnected?this.glossPower.associatedVariableName:"1024.0"}; +`,e.compilationString+=`vec3 diffuseBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 specularBase = vec3(0., 0., 0.); +`,e.compilationString+=`vec3 normalW = ${this.worldNormal.associatedVariableName}.xyz; +`),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:r+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",t,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${r}.xyz`}),0===this._lightId&&(e.compilationString+=`aggShadow = aggShadow / numLights; +`);let s=this.diffuseOutput,n=this.specularOutput;return e.compilationString+=this._declareOutput(s,e)+` = diffuseBase${this.diffuseColor.isConnected?" * "+this.diffuseColor.associatedVariableName:""}; +`,n.hasEndpoints&&(e.compilationString+=this._declareOutput(n,e)+` = specularBase${this.specularColor.isConnected?" * "+this.specularColor.associatedVariableName:""}; +`),this.shadow.hasEndpoints&&(e.compilationString+=this._declareOutput(this.shadow,e)+` = aggShadow; +`),this}serialize(){let e=super.serialize();return e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,this.light&&(e.lightId=this.light.id),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,sx.gn)([nS("Generate only fragment code",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:ma._OnGenerateOnlyFragmentCodeChanged}})],ma.prototype,"generateOnlyFragmentCode",void 0),(0,rg.H)("BABYLON.LightBlock",ma);class mo extends nv{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rL.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}get samplerName(){return this._samplerName}constructor(e){super(e,tm.VertexAndFragment),this.registerOutput("source",tf.Object,tm.VertexAndFragment,new f$("source",this,tv.Output,mo,"ImageSourceBlock"))}bind(e){this.texture&&e.setTexture(this._samplerName,this.texture)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}getClassName(){return"ImageSourceBlock"}get source(){return this._outputs[0]}_buildBlock(e){return super._buildBlock(e),e.target===tm.Vertex&&(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this)),e._emit2DSampler(this._samplerName),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&"VideoTexture"!==this.texture.getClassName()&&(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!ac.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=sj.Parse(e.texture,t,i))}}(0,rg.H)("BABYLON.ImageSourceBlock",mo);class ml extends nv{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rL.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _IsPrePassTextureBlock(e){return(null==e?void 0:e.getClassName())==="PrePassTextureBlock"}get _isSourcePrePass(){return ml._IsPrePassTextureBlock(this._imageSource)}get samplerName(){if(this._imageSource){if(!ml._IsPrePassTextureBlock(this._imageSource))return this._imageSource.samplerName;if(this.source.connectedPoint)return this._imageSource.getSamplerName(this.source.connectedPoint)}return this._samplerName}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rL.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rL.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,t?tm.Fragment:tm.VertexAndFragment),this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this._fragmentOnly=t,this.registerInput("uv",tf.AutoDetect,!1,tm.VertexAndFragment),this.registerInput("source",tf.Object,!0,tm.VertexAndFragment,new f$("source",this,tv.Input,mo,"ImageSourceBlock")),this.registerInput("layer",tf.Float,!0),this.registerInput("lod",tf.Float,!0),this.registerOutput("rgba",tf.Color4,tm.Neutral),this.registerOutput("rgb",tf.Color3,tm.Neutral),this.registerOutput("r",tf.Float,tm.Neutral),this.registerOutput("g",tf.Float,tm.Neutral),this.registerOutput("b",tf.Float,tm.Neutral),this.registerOutput("a",tf.Float,tm.Neutral),this.registerOutput("level",tf.Float,tm.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Vector2|tf.Vector3|tf.Vector4),this._inputs[0]._prioritizeVertex=!t}getClassName(){return"TextureBlock"}get uv(){return this._inputs[0]}get source(){return this._inputs[1]}get layer(){return this._inputs[2]}get lod(){return this._inputs[3]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}get target(){if(this._fragmentOnly)return tm.Fragment;if(!this.uv.isConnected||this.uv.sourceBlock.isInput)return tm.VertexAndFragment;let e=this.uv.connectedPoint;for(;e;){if(e.target===tm.Fragment)return tm.Fragment;if(e.target===tm.Vertex)break;if(e.target===tm.Neutral||e.target===tm.VertexAndFragment){let t=e.ownerBlock;if(t.target===tm.Fragment)return tm.Fragment;for(let i of(e=null,t.inputs))if(i.connectedPoint){e=i.connectedPoint;break}}}return tm.VertexAndFragment}set target(e){}autoConfigure(e,t=()=>!0){if(!this.uv.isConnected){if(e.mode===tC.PostProcess){let i=e.getBlockByPredicate(e=>"uv"===e.name&&t(e));i&&i.connectTo(this)}else{let i=e.mode===tC.Particle?"particle_uv":"uv",r=e.getInputBlockByPredicate(e=>e.isAttribute&&e.name===i&&t(e));r||(r=new nI("uv")).setAsAttribute(i),r.output.connectTo(this.uv)}}}initializeDefines(e,t,i){i._areTexturesDirty&&void 0!==this._mainUVDefineName&&i.setValue(this._mainUVDefineName,!1,!0)}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;if(!this.texture||!this.texture.getTextureMatrix){this._isMixed&&(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0));return}let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0),this._isMixed&&(this.texture.getTextureMatrix().isIdentityAs3x2()?(i.setValue(this._defineName,!1,!0),i.setValue(this._mainUVDefineName,!0,!0)):(i.setValue(this._defineName,!0),void 0==i[this._mainUVDefineName]&&i.setValue(this._mainUVDefineName,!1,!0)))}isReady(){return!!this._isSourcePrePass||!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this._isSourcePrePass&&e.setFloat(this._textureInfoName,1),this.texture&&(this._isMixed&&(e.setFloat(this._textureInfoName,this.texture.level),e.setMatrix(this._textureTransformName,this.texture.getTextureMatrix())),this._imageSource||e.setTexture(this._samplerName,this.texture))}get _isMixed(){return this.target!==tm.Fragment}_injectVertexCode(e){let t=this.uv;if(this._defineName=e._getFreeDefineName("UVTRANSFORM"),this._mainUVDefineName="VMAIN"+t.associatedVariableName.toUpperCase(),this._mainUVName="vMain"+t.associatedVariableName,this._transformedUVName=e._getFreeVariableName("transformedUV"),this._textureTransformName=e._getFreeVariableName("textureTransform"),this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,e._emitVaryingFromString(this._transformedUVName,"vec2",this._defineName),e._emitVaryingFromString(this._mainUVName,"vec2",this._mainUVDefineName),e._emitUniformFromString(this._textureTransformName,"mat4",this._defineName),e.compilationString+=`#ifdef ${this._defineName} +`,e.compilationString+=`${this._transformedUVName} = vec2(${this._textureTransformName} * vec4(${t.associatedVariableName}.xy, 1.0, 0.0)); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,e.compilationString+=`#endif +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name,!0)}_getUVW(e){var t,i,r;let s=e;if(null!==(r=null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)&&void 0!==r&&r){let t=this.layer.isConnected?this.layer.associatedVariableName:"0";s=`vec3(${e}, ${t})`}return s}get _samplerFunc(){return this.lod.isConnected?"texture2DLodEXT":"texture2D"}get _samplerLodSuffix(){return this.lod.isConnected?`, ${this.lod.associatedVariableName}`:""}_generateTextureLookup(e){let t=this.samplerName;e.compilationString+=`#ifdef ${this._defineName} +`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._transformedUVName)}${this._samplerLodSuffix}); +`,e.compilationString+=`#elif defined(${this._mainUVDefineName}) +`,e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${t}, ${this._getUVW(this._mainUVName?this._mainUVName:this.uv.associatedVariableName)}${this._samplerLodSuffix}); +`,e.compilationString+=`#endif +`}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tm.Fragment)return;this._generateTextureLookup(e);return}if(this.uv.ownerBlock.target===tm.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = ${this._samplerFunc}(${this.samplerName}, ${this._getUVW(i.associatedVariableName)}${this._samplerLodSuffix}); +`;return}this._generateTextureLookup(e)}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} + ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); + #endif + `),e.compilationString+=`#ifdef ${this._gammaDefineName} + ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tm.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}if(this.uv.ownerBlock.target===tm.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`,this._generateConversionCode(e,t,i);return}let s="";this.disableLevelMultiplication||(s=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${s}; +`,this._generateConversionCode(e,t,i)}_buildBlock(e){var t,i,r,s;if(super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,(e.target===tm.Vertex||this._fragmentOnly||e.target===tm.Fragment)&&(this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA")),(!this._isMixed&&e.target===tm.Fragment||this._isMixed&&e.target===tm.Vertex)&&(this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),(null===(i=null===(t=this._texture)||void 0===t?void 0:t._texture)||void 0===i?void 0:i.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this)),e.target!==tm.Fragment){this._injectVertexCode(e);return}if(!this._outputs.some(e=>e.isConnectedInFragmentShader))return;this._isMixed&&!this._imageSource&&((null===(s=null===(r=this._texture)||void 0===r?void 0:r._texture)||void 0===s?void 0:s.is2DArray)?e._emit2DArraySampler(this._samplerName):e._emit2DSampler(this._samplerName));let n=`//${this.name}`;for(let t of(e._emitFunctionFromInclude("helperFunctions",n),this._isMixed&&e._emitUniformFromString(this._textureInfoName,"float"),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&"level"!==t.name&&this._writeOutput(e,t,t.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.fragmentOnly=this._fragmentOnly,e.disableLevelMultiplication=this.disableLevelMultiplication,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this._fragmentOnly=!!e.fragmentOnly,this.disableLevelMultiplication=!!e.disableLevelMultiplication,e.texture&&!ac.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=sj.Parse(e.texture,t,i))}}(0,rg.H)("BABYLON.TextureBlock",ml);class mh extends nv{get texture(){return this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rL.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}static _OnGenerateOnlyFragmentCodeChanged(e,t){return e._onGenerateOnlyFragmentCodeChanged()}_onGenerateOnlyFragmentCodeChanged(){return this._setTarget(),!0}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tm.Fragment:tm.VertexAndFragment)}constructor(e){super(e,tm.VertexAndFragment),this.generateOnlyFragmentCode=!1}getClassName(){return"ReflectionTextureBaseBlock"}_getTexture(){return this.texture}autoConfigure(e,t=()=>!0){if(!this.position.isConnected){let i=e.getInputBlockByPredicate(e=>e.isAttribute&&"position"===e.name&&t(e));i||(i=new nI("position")).setAsAttribute(),i.output.connectTo(this.position)}if(!this.world.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.World&&t(e));i||(i=new nI("world")).setAsSystemValue(tS.World),i.output.connectTo(this.world)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.View&&t(e));i||(i=new nI("view")).setAsSystemValue(tS.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this._getTexture();r&&r.getTextureMatrix&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLocalCubicName,!!r.boundingBoxSize,!0),i.setValue(this._defineExplicitName,0===r.coordinatesMode,!0),i.setValue(this._defineSkyboxName,5===r.coordinatesMode,!0),i.setValue(this._defineCubicName,3===r.coordinatesMode||6===r.coordinatesMode,!0),i.setValue("INVERTCUBICMAP",6===r.coordinatesMode,!0),i.setValue(this._defineSphericalName,1===r.coordinatesMode,!0),i.setValue(this._definePlanarName,2===r.coordinatesMode,!0),i.setValue(this._defineProjectionName,4===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularName,7===r.coordinatesMode,!0),i.setValue(this._defineEquirectangularFixedName,8===r.coordinatesMode,!0),i.setValue(this._defineMirroredEquirectangularFixedName,9===r.coordinatesMode,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){let r=this._getTexture();i&&r&&(e.setMatrix(this._reflectionMatrixName,r.getReflectionTextureMatrix()),r.isCube?e.setTexture(this._cubeSamplerName,r):e.setTexture(this._2DSamplerName,r),r.boundingBoxSize&&(e.setVector3(this._reflectionPositionName,r.boundingBoxPosition),e.setVector3(this._reflectionSizeName,r.boundingBoxSize)))}handleVertexSide(e){if(this.generateOnlyFragmentCode&&e.target===tm.Vertex)return"";this._define3DName=e._getFreeDefineName("REFLECTIONMAP_3D"),this._defineCubicName=e._getFreeDefineName("REFLECTIONMAP_CUBIC"),this._defineSphericalName=e._getFreeDefineName("REFLECTIONMAP_SPHERICAL"),this._definePlanarName=e._getFreeDefineName("REFLECTIONMAP_PLANAR"),this._defineProjectionName=e._getFreeDefineName("REFLECTIONMAP_PROJECTION"),this._defineExplicitName=e._getFreeDefineName("REFLECTIONMAP_EXPLICIT"),this._defineEquirectangularName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR"),this._defineLocalCubicName=e._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC"),this._defineMirroredEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"),this._defineEquirectangularFixedName=e._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED"),this._defineSkyboxName=e._getFreeDefineName("REFLECTIONMAP_SKYBOX"),this._defineOppositeZ=e._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ"),this._reflectionMatrixName=e._getFreeVariableName("reflectionMatrix"),e._emitUniformFromString(this._reflectionMatrixName,"mat4");let t="";this._worldPositionNameInFragmentOnlyMode=e._getFreeVariableName("worldPosition");let i=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName;return(this.generateOnlyFragmentCode||e._emitVaryingFromString(i,"vec4"))&&(t+=`${this.generateOnlyFragmentCode?"vec4 ":""}${i} = ${this.worldPosition.associatedVariableName}; +`),this._positionUVWName=e._getFreeVariableName("positionUVW"),this._directionWName=e._getFreeVariableName("directionW"),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._positionUVWName,"vec3",this._defineSkyboxName))&&(t+=`#ifdef ${this._defineSkyboxName} +${this.generateOnlyFragmentCode?"vec3 ":""}${this._positionUVWName} = ${this.position.associatedVariableName}.xyz; +#endif +`),(this.generateOnlyFragmentCode||e._emitVaryingFromString(this._directionWName,"vec3",`defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName})`))&&(t+=`#if defined(${this._defineEquirectangularFixedName}) || defined(${this._defineMirroredEquirectangularFixedName}) +${this.generateOnlyFragmentCode?"vec3 ":""}${this._directionWName} = normalize(vec3(${this.world.associatedVariableName} * vec4(${this.position.associatedVariableName}.xyz, 0.0))); +#endif +`),t}handleFragmentSideInits(e){e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),e._samplerDeclaration+=`#ifdef ${this._define3DName} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,e._samplerDeclaration+=`#endif +`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;e._emitFunctionFromInclude("helperFunctions",t),e._emitFunctionFromInclude("reflectionFunction",t,{replaceStrings:[{search:/vec3 computeReflectionCoords/g,replace:"void DUMMYFUNC"}]}),this._reflectionColorName=e._getFreeVariableName("reflectionColor"),this._reflectionVectorName=e._getFreeVariableName("reflectionUVW"),this._reflectionCoordsName=e._getFreeVariableName("reflectionCoords"),this._reflectionPositionName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionPositionName,"vec3"),this._reflectionSizeName=e._getFreeVariableName("vReflectionPosition"),e._emitUniformFromString(this._reflectionSizeName,"vec3")}handleFragmentSideCodeReflectionCoords(e,t,i=!1,r=!1){t||(t=this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:`v_${this.worldPosition.associatedVariableName}`);let s=this._reflectionMatrixName,n=`normalize(${this._directionWName})`,a=`${this._positionUVWName}`,o=`${this.cameraPosition.associatedVariableName}`,l=`${this.view.associatedVariableName}`;e+=".xyz";let h=` + #ifdef ${this._defineMirroredEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeMirroredFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularFixedName} + vec3 ${this._reflectionVectorName} = computeFixedEquirectangularCoords(${t}, ${e}, ${n}); + #endif + + #ifdef ${this._defineEquirectangularName} + vec3 ${this._reflectionVectorName} = computeEquirectangularCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + + #ifdef ${this._defineSphericalName} + vec3 ${this._reflectionVectorName} = computeSphericalCoords(${t}, ${e}, ${l}, ${s}); + #endif + + #ifdef ${this._definePlanarName} + vec3 ${this._reflectionVectorName} = computePlanarCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + + #ifdef ${this._defineCubicName} + #ifdef ${this._defineLocalCubicName} + vec3 ${this._reflectionVectorName} = computeCubicLocalCoords(${t}, ${e}, ${o}.xyz, ${s}, ${this._reflectionSizeName}, ${this._reflectionPositionName}); + #else + vec3 ${this._reflectionVectorName} = computeCubicCoords(${t}, ${e}, ${o}.xyz, ${s}); + #endif + #endif + + #ifdef ${this._defineProjectionName} + vec3 ${this._reflectionVectorName} = computeProjectionCoords(${t}, ${l}, ${s}); + #endif + + #ifdef ${this._defineSkyboxName} + vec3 ${this._reflectionVectorName} = computeSkyBoxCoords(${a}, ${s}); + #endif + + #ifdef ${this._defineExplicitName} + vec3 ${this._reflectionVectorName} = vec3(0, 0, 0); + #endif +`;return r||(h+=`#ifdef ${this._defineOppositeZ} + ${this._reflectionVectorName}.z *= -1.0; + #endif +`),i||(h+=` + #ifdef ${this._define3DName} + vec3 ${this._reflectionCoordsName} = ${this._reflectionVectorName}; + #else + vec2 ${this._reflectionCoordsName} = ${this._reflectionVectorName}.xy; + #ifdef ${this._defineProjectionName} + ${this._reflectionCoordsName} /= ${this._reflectionVectorName}.z; + #endif + ${this._reflectionCoordsName}.y = 1.0 - ${this._reflectionCoordsName}.y; + #endif +`),h}handleFragmentSideCodeReflectionColor(e,t=".rgb"){let i="vec"+(0===t.length?"4":t.length-1),r=`${i} ${this._reflectionColorName}; + #ifdef ${this._define3DName} +`;return e?r+=`${this._reflectionColorName} = textureCubeLodEXT(${this._cubeSamplerName}, ${this._reflectionVectorName}, ${e})${t}; +`:r+=`${this._reflectionColorName} = textureCube(${this._cubeSamplerName}, ${this._reflectionVectorName})${t}; +`,r+=` + #else +`,e?r+=`${this._reflectionColorName} = texture2DLodEXT(${this._2DSamplerName}, ${this._reflectionCoordsName}, ${e})${t}; +`:r+=`${this._reflectionColorName} = texture2D(${this._2DSamplerName}, ${this._reflectionCoordsName})${t}; +`,r+=`#endif +`}writeOutputs(e,t){let i="";if(e.target===tm.Fragment)for(let r of this._outputs)r.hasEndpoints&&(i+=`${this._declareOutput(r,e)} = ${t}.${r.name}; +`);return i}_buildBlock(e){return super._buildBlock(e),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();if(!this.texture)return e;if(this.texture.isCube){let t=this.texture.forcedExtension;e+=`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}", undefined, undefined, ${this.texture.noMipmap}, null, undefined, undefined, undefined, ${this.texture._prefiltered}, ${t?'"'+t+'"':"null"}); +`}else e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null); +`;return e+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&!ac.IgnoreTexturesAtLoadTime&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=dM.Parse(e.texture,t,i):this.texture=sj.Parse(e.texture,t,i)),this.generateOnlyFragmentCode=e.generateOnlyFragmentCode,this._setTarget()}}(0,sx.gn)([nS("Generate only fragment code",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:mh._OnGenerateOnlyFragmentCodeChanged}})],mh.prototype,"generateOnlyFragmentCode",void 0),(0,rg.H)("BABYLON.ReflectionTextureBaseBlock",mh);class mu extends mh{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,rb.Y.Error("The position input must not be connected to be able to switch!"),!1):this.worldPosition.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,rb.Y.Error("The worldPosition input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?tm.Fragment:tm.Vertex,this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tm.Fragment:tm.Vertex}constructor(e){super(e),this.registerInput("position",tf.AutoDetect,!1,tm.Vertex),this.registerInput("worldPosition",tf.Vector4,!1,tm.Vertex),this.registerInput("worldNormal",tf.Vector4,!1,tm.Fragment),this.registerInput("world",tf.Matrix,!1,tm.Vertex),this.registerInput("cameraPosition",tf.Vector3,!1,tm.Fragment),this.registerInput("view",tf.Matrix,!1,tm.Fragment),this.registerOutput("rgb",tf.Color3,tm.Fragment),this.registerOutput("rgba",tf.Color4,tm.Fragment),this.registerOutput("r",tf.Float,tm.Fragment),this.registerOutput("g",tf.Float,tm.Fragment),this.registerOutput("b",tf.Float,tm.Fragment),this.registerOutput("a",tf.Float,tm.Fragment),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Vector4)}getClassName(){return"ReflectionTextureBlock"}get position(){return this._inputs[0]}get worldPosition(){return this._inputs[1]}get worldNormal(){return this._inputs[2]}get world(){return this._inputs[3]}get cameraPosition(){return this._inputs[4]}get view(){return this._inputs[5]}get rgb(){return this._outputs[0]}get rgba(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}autoConfigure(e,t=()=>!0){if(super.autoConfigure(e),!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.CameraPosition&&t(e));i||(i=new nI("cameraPosition")).setAsSystemValue(tS.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){if(super._buildBlock(e),!this.texture)return e.compilationString+=this.writeOutputs(e,"vec4(0.)"),this;if(e.target!==tm.Fragment)return e.compilationString+=this.handleVertexSide(e),this;this.generateOnlyFragmentCode&&(e.compilationString+=this.handleVertexSide(e)),this.handleFragmentSideInits(e);let t=e._getFreeVariableName("normalWUnit");return e.compilationString+=`vec4 ${t} = normalize(${this.worldNormal.associatedVariableName}); +`,e.compilationString+=this.handleFragmentSideCodeReflectionCoords(t),e.compilationString+=this.handleFragmentSideCodeReflectionColor(void 0,""),e.compilationString+=this.writeOutputs(e,this._reflectionColorName),this}}(0,rg.H)("BABYLON.ReflectionTextureBlock",mu);class mc extends nv{constructor(e){super(e,tm.VertexAndFragment),this.useNonLinearDepth=!1,this.storeCameraSpaceZ=!1,this.force32itsFloat=!1,this._isUnique=!0,this.registerInput("uv",tf.AutoDetect,!1,tm.VertexAndFragment),this.registerOutput("depth",tf.Float,tm.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Vector2|tf.Vector3|tf.Vector4),this._inputs[0]._prioritizeVertex=!1}getClassName(){return"SceneDepthBlock"}get uv(){return this._inputs[0]}get depth(){return this._outputs[0]}initialize(e){e._excludeVariableName("textureSampler")}get target(){return!this.uv.isConnected||this.uv.sourceBlock.isInput?tm.VertexAndFragment:tm.Fragment}_getTexture(e){return e.enableDepthRenderer(void 0,this.useNonLinearDepth,this.force32itsFloat,void 0,this.storeCameraSpaceZ).getDepthMap()}bind(e,t){let i=this._getTexture(t.getScene());e.setTexture(this._samplerName,i)}_injectVertexCode(e){let t=this.uv;if(t.connectedPoint.ownerBlock.isInput&&!t.connectedPoint.ownerBlock.isAttribute&&e._emitUniformFromString(t.associatedVariableName,"vec"+(t.type===tf.Vector3?"3":t.type===tf.Vector4?"4":"2")),this._mainUVName="vMain"+t.associatedVariableName,e._emitVaryingFromString(this._mainUVName,"vec2"),e.compilationString+=`${this._mainUVName} = ${t.associatedVariableName}.xy; +`,this._outputs.some(e=>e.isConnectedInVertexShader))for(let t of(this._writeTextureRead(e,!0),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r",!0)}_writeTextureRead(e,t=!1){let i=this.uv;if(t){if(e.target===tm.Fragment)return;e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}if(this.uv.ownerBlock.target===tm.Fragment){e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${i.associatedVariableName}.xy); +`;return}e.compilationString+=`vec4 ${this._tempTextureRead} = texture2D(${this._samplerName}, ${this._mainUVName}); +`}_writeOutput(e,t,i,r=!1){if(r){if(e.target===tm.Fragment)return;e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}if(this.uv.ownerBlock.target===tm.Fragment){e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`;return}e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}; +`}_buildBlock(e){if(super._buildBlock(e),this._samplerName=e._getFreeVariableName(this.name+"Sampler"),this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),0>e.sharedData.bindableBlocks.indexOf(this)&&e.sharedData.bindableBlocks.push(this),e.target!==tm.Fragment){e._emit2DSampler(this._samplerName),this._injectVertexCode(e);return}if(this._outputs.some(e=>e.isConnectedInFragmentShader)){for(let t of(e._emit2DSampler(this._samplerName),this._writeTextureRead(e),this._outputs))t.hasEndpoints&&this._writeOutput(e,t,"r");return this}}serialize(){let e=super.serialize();return e.useNonLinearDepth=this.useNonLinearDepth,e.storeCameraSpaceZ=this.storeCameraSpaceZ,e.force32itsFloat=this.force32itsFloat,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.useNonLinearDepth=e.useNonLinearDepth,this.storeCameraSpaceZ=!!e.storeCameraSpaceZ,this.force32itsFloat=e.force32itsFloat}}(0,sx.gn)([nS("Use non linear depth",tx.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.useNonLinearDepth&&(t.storeCameraSpaceZ=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],mc.prototype,"useNonLinearDepth",void 0),(0,sx.gn)([nS("Store Camera space Z",tx.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:(e,t)=>{let i=!1;return t.storeCameraSpaceZ&&(t.useNonLinearDepth=!1,i=!0),e&&e.disableDepthRenderer(),i}}})],mc.prototype,"storeCameraSpaceZ",void 0),(0,sx.gn)([nS("Force 32 bits float",tx.Boolean,"ADVANCED",{notifiers:{activatePreviewCommand:!0,callback:e=>null==e?void 0:e.disableDepthRenderer()}})],mc.prototype,"force32itsFloat",void 0),(0,rg.H)("BABYLON.SceneDepthBlock",mc);class md extends nv{constructor(e){super(e,tm.VertexAndFragment,!0),this.registerInput("worldPosition",tf.Vector4,!1)}getClassName(){return"ClipPlanesBlock"}initialize(e){e._excludeVariableName("vClipPlane"),e._excludeVariableName("fClipDistance"),e._excludeVariableName("vClipPlane2"),e._excludeVariableName("fClipDistance2"),e._excludeVariableName("vClipPlane3"),e._excludeVariableName("fClipDistance3"),e._excludeVariableName("vClipPlane4"),e._excludeVariableName("fClipDistance4"),e._excludeVariableName("vClipPlane5"),e._excludeVariableName("fClipDistance5"),e._excludeVariableName("vClipPlane6"),e._excludeVariableName("fClipDistance6")}get worldPosition(){return this._inputs[0]}get target(){return tm.VertexAndFragment}set target(e){}prepareDefines(e,t,i){var r,s,n,a,o,l;let h=e.getScene(),u=null!==(r=t.clipPlane)&&void 0!==r?!!r:!!h.clipPlane,c=null!==(s=t.clipPlane2)&&void 0!==s?!!s:!!h.clipPlane2,d=null!==(n=t.clipPlane3)&&void 0!==n?!!n:!!h.clipPlane3,p=null!==(a=t.clipPlane4)&&void 0!==a?!!a:!!h.clipPlane4,_=null!==(o=t.clipPlane5)&&void 0!==o?!!o:!!h.clipPlane5,f=null!==(l=t.clipPlane6)&&void 0!==l?!!l:!!h.clipPlane6;i.setValue("CLIPPLANE",u,!0),i.setValue("CLIPPLANE2",c,!0),i.setValue("CLIPPLANE3",d,!0),i.setValue("CLIPPLANE4",p,!0),i.setValue("CLIPPLANE5",_,!0),i.setValue("CLIPPLANE6",f,!0)}bind(e,t,i){if(!i)return;let r=i.getScene();(0,lH.an)(e,t,r)}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;if(e.target!==tm.Fragment){let i=this.worldPosition;e._emitFunctionFromInclude("clipPlaneVertexDeclaration",t,{replaceStrings:[{search:/uniform vec4 vClipPlane\d*;/g,replace:""}]}),e.compilationString+=e._emitCodeFromInclude("clipPlaneVertex",t,{replaceStrings:[{search:/worldPos/g,replace:i.associatedVariableName}]}),e._emitUniformFromString("vClipPlane","vec4"),e._emitUniformFromString("vClipPlane2","vec4"),e._emitUniformFromString("vClipPlane3","vec4"),e._emitUniformFromString("vClipPlane4","vec4"),e._emitUniformFromString("vClipPlane5","vec4"),e._emitUniformFromString("vClipPlane6","vec4");return}return e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e._emitFunctionFromInclude("clipPlaneFragmentDeclaration",t),e.compilationString+=e._emitCodeFromInclude("clipPlaneFragment",t),this}}(0,rg.H)("BABYLON.ClipPlanesBlock",md);class mp extends nv{get texture(){return null}set texture(e){}constructor(e,t=tm.VertexAndFragment){super(e,t,!1),this.registerOutput("position",tf.Object,tm.VertexAndFragment,new f$("position",this,tv.Output,mo,"ImageSourceBlock")),this.registerOutput("depth",tf.Object,tm.VertexAndFragment,new f$("depth",this,tv.Output,mo,"ImageSourceBlock")),this.registerOutput("normal",tf.Object,tm.VertexAndFragment,new f$("normal",this,tv.Output,mo,"ImageSourceBlock"))}getSamplerName(e){return e===this._outputs[0]?this._positionSamplerName:e===this._outputs[1]?this._depthSamplerName:e===this._outputs[2]?this._normalSamplerName:""}get position(){return this._outputs[0]}get depth(){return this._outputs[1]}get normal(){return this._outputs[2]}get positionSamplerName(){return this._positionSamplerName}get normalSamplerName(){return this._normalSamplerName}get depthSamplerName(){return this._depthSamplerName}getClassName(){return"PrePassTextureBlock"}_buildBlock(e){if(super._buildBlock(e),e.target!==tm.Vertex)return this._positionSamplerName="prepassPositionSampler",this._depthSamplerName="prepassDepthSampler",this._normalSamplerName="prepassNormalSampler",e.sharedData.variableNames.prepassPositionSampler=0,e.sharedData.variableNames.prepassDepthSampler=0,e.sharedData.variableNames.prepassNormalSampler=0,e.sharedData.textureBlocks.push(this),e.sharedData.bindableBlocks.push(this),e._emit2DSampler(this._positionSamplerName),e._emit2DSampler(this._depthSamplerName),e._emit2DSampler(this._normalSamplerName),this}bind(e,t){let i=t.getScene().enablePrePassRenderer();if(!i)return;let r=i.defaultRT;r.textures&&(this.position.isConnected&&e.setTexture(this._positionSamplerName,r.textures[i.getIndex(1)]),this.depth.isConnected&&e.setTexture(this._depthSamplerName,r.textures[i.getIndex(5)]),this.normal.isConnected&&e.setTexture(this._normalSamplerName,r.textures[i.getIndex(6)]))}}(0,rg.H)("BABYLON.PrePassTextureBlock",mp);class m_ extends nv{get endpoints(){return this._endpoints}get target(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==tm.VertexAndFragment)return t.target;if(e.connectedPoint.target!==tm.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}constructor(e){super(e,tm.Neutral),this._endpoints=[],this.registerInput("input",tf.AutoDetect)}getClassName(){return"NodeMaterialTeleportInBlock"}get input(){return this._inputs[0]}isConnectedInFragmentShader(){return this.endpoints.some(e=>e.output.isConnectedInFragmentShader)}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}dispose(){for(let e of(super.dispose(),this._endpoints))this.detachFromEndpoint(e);this._endpoints=[]}}(0,rg.H)("BABYLON.NodeMaterialTeleportInBlock",m_);class mf extends nv{constructor(e){super(e,tm.Neutral),this._entryPoint=null,this._tempEntryPointUniqueId=null,this.registerOutput("output",tf.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"NodeMaterialTeleportOutBlock"}get output(){return this._outputs[0]}get target(){return this._entryPoint?this._entryPoint.target:this._target}set target(e){(this._target&e)==0&&(this._target=e)}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(e){super._buildBlock(e),this.entryPoint&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${this.entryPoint.input.associatedVariableName}; +`)}clone(e,t=""){let i=super.clone(e,t);return this.entryPoint&&this.entryPoint.attachToEndpoint(i),i}_customBuildStep(e,t){this.entryPoint&&this.entryPoint.build(e,t)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); +`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e,t,i){super._deserialize(e,t,i),this._tempEntryPointUniqueId=e.entryPoint}}(0,rg.H)("BABYLON.NodeMaterialTeleportOutBlock",mf);class mm extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("left",tf.AutoDetect),this.registerInput("right",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].acceptedConnectionPointTypes.push(tf.Float),this._inputs[1].acceptedConnectionPointTypes.push(tf.Float)}getClassName(){return"AddBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.left.associatedVariableName} + ${this.right.associatedVariableName}; +`,this}}(0,rg.H)("BABYLON.AddBlock",mm);class mg extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("input",tf.AutoDetect),this.registerInput("factor",tf.Float),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ScaleBlock"}get input(){return this._inputs[0]}get factor(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} * ${this.factor.associatedVariableName}; +`,this}}(0,rg.H)("BABYLON.ScaleBlock",mg);class mv extends nv{constructor(e){super(e,tm.Neutral),this.minimum=0,this.maximum=1,this.registerInput("value",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ClampBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = clamp(${this.value.associatedVariableName}, ${this._writeFloat(this.minimum)}, ${this._writeFloat(this.maximum)}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.minimum = ${this.minimum}; +`+`${this._codeVariableName}.maximum = ${this.maximum}; +`}serialize(){let e=super.serialize();return e.minimum=this.minimum,e.maximum=this.maximum,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.minimum=e.minimum,this.maximum=e.maximum}}(0,sx.gn)([nS("Minimum",tx.Float)],mv.prototype,"minimum",void 0),(0,sx.gn)([nS("Maximum",tx.Float)],mv.prototype,"maximum",void 0),(0,rg.H)("BABYLON.ClampBlock",mv);class mx extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("left",tf.AutoDetect),this.registerInput("right",tf.AutoDetect),this.registerOutput("output",tf.Vector3),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tf.Float),this._inputs[0].excludedConnectionPointTypes.push(tf.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tf.Vector2),this._inputs[1].excludedConnectionPointTypes.push(tf.Float),this._inputs[1].excludedConnectionPointTypes.push(tf.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tf.Vector2)}getClassName(){return"CrossBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = cross(${this.left.associatedVariableName}.xyz, ${this.right.associatedVariableName}.xyz); +`,this}}(0,rg.H)("BABYLON.CrossBlock",mx);class mT extends nv{get options(){return this._options}set options(e){this._deserializeOptions(e)}constructor(e){super(e)}getClassName(){return"CustomBlock"}_buildBlock(e){super._buildBlock(e);let t=this._code,i=this._options.functionName;this._inputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),this._outputs.forEach(r=>{let s=RegExp("\\{TYPE_"+r.name+"\\}","gm"),n=e._getGLType(r.type);t=t.replace(s,n),i=i.replace(s,n)}),e._emitFunction(i,t,""),this._outputs.forEach(t=>{e.compilationString+=this._declareOutput(t,e)+";\n"}),e.compilationString+=i+"(";let r=!1;return this._inputs.forEach((t,i)=>{var s,n,a;i>0&&(e.compilationString+=", "),this._inputSamplers&&-1!==this._inputSamplers.indexOf(t.name)?e.compilationString+=null!==(a=null===(n=null===(s=t.connectedPoint)||void 0===s?void 0:s.ownerBlock)||void 0===n?void 0:n.samplerName)&&void 0!==a?a:t.associatedVariableName:e.compilationString+=t.associatedVariableName,r=!0}),this._outputs.forEach((t,i)=>{(i>0||r)&&(e.compilationString+=", "),e.compilationString+=t.associatedVariableName}),e.compilationString+=");\n",this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.options = ${JSON.stringify(this._options)}; +`}serialize(){let e=super.serialize();return e.options=this._options,e}_deserialize(e,t,i){this._deserializeOptions(e.options),super._deserialize(e,t,i)}_deserializeOptions(e){var t,i,r;this._options=e,this._code=e.code.join("\n")+"\n",this.name=this.name||e.name,this.target=tm[e.target],null===(t=e.inParameters)||void 0===t||t.forEach((e,t)=>{let i=tf[e.type];"sampler2D"===e.type||"samplerCube"===e.type?(this._inputSamplers=this._inputSamplers||[],this._inputSamplers.push(e.name),this.registerInput(e.name,tf.Object,!0,tm.VertexAndFragment,new f$(e.name,this,tv.Input,mo,"ImageSourceBlock"))):this.registerInput(e.name,i),Object.defineProperty(this,e.name,{get:function(){return this._inputs[t]},enumerable:!0,configurable:!0})}),null===(i=e.outParameters)||void 0===i||i.forEach((e,t)=>{this.registerOutput(e.name,tf[e.type]),Object.defineProperty(this,e.name,{get:function(){return this._outputs[t]},enumerable:!0,configurable:!0}),"BasedOnInput"===e.type&&(this._outputs[t]._typeConnectionSource=this._findInputByName(e.typeFromInput)[0])}),null===(r=e.inLinkedConnectionTypes)||void 0===r||r.forEach(e=>{this._linkConnectionTypes(this._findInputByName(e.input1)[1],this._findInputByName(e.input2)[1])})}_findInputByName(e){if(!e)return null;for(let t=0;t!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.CameraPosition&&t(e));i||(i=new nI("cameraPosition")).setAsSystemValue(tS.CameraPosition),i.output.connectTo(this.cameraPosition)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = normalize(${this.cameraPosition.associatedVariableName} - ${this.worldPosition.associatedVariableName}.xyz); +`,this}}(0,rg.H)("BABYLON.ViewDirectionBlock",mM);class mD extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("worldNormal",tf.Vector4),this.registerInput("viewDirection",tf.Vector3),this.registerInput("bias",tf.Float),this.registerInput("power",tf.Float),this.registerOutput("fresnel",tf.Float)}getClassName(){return"FresnelBlock"}get worldNormal(){return this._inputs[0]}get viewDirection(){return this._inputs[1]}get bias(){return this._inputs[2]}get power(){return this._inputs[3]}get fresnel(){return this._outputs[0]}autoConfigure(e){if(!this.viewDirection.isConnected){let t=new mM("View direction");t.output.connectTo(this.viewDirection),t.autoConfigure(e)}if(!this.bias.isConnected){let e=new nI("bias");e.value=0,e.output.connectTo(this.bias)}if(!this.power.isConnected){let e=new nI("power");e.value=1,e.output.connectTo(this.power)}}_buildBlock(e){super._buildBlock(e);let t=`//${this.name}`;return e._emitFunctionFromInclude("fresnelFunction",t,{removeIfDef:!0}),e.compilationString+=this._declareOutput(this.fresnel,e)+` = computeFresnelTerm(${this.viewDirection.associatedVariableName}.xyz, ${this.worldNormal.associatedVariableName}.xyz, ${this.bias.associatedVariableName}, ${this.power.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.FresnelBlock",mD);class mO extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("left",tf.AutoDetect),this.registerInput("right",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MaxBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = max(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.MaxBlock",mO);class mN extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("left",tf.AutoDetect),this.registerInput("right",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"MinBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = min(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.MinBlock",mN);class mF extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("left",tf.AutoDetect),this.registerInput("right",tf.AutoDetect),this.registerOutput("output",tf.Float),this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tf.Float),this._inputs[0].excludedConnectionPointTypes.push(tf.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tf.Float),this._inputs[1].excludedConnectionPointTypes.push(tf.Matrix)}getClassName(){return"DistanceBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.left.associatedVariableName} - ${this.right.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.DistanceBlock",mF);class mL extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("value",tf.AutoDetect),this.registerOutput("output",tf.Float),this._inputs[0].excludedConnectionPointTypes.push(tf.Float),this._inputs[0].excludedConnectionPointTypes.push(tf.Matrix)}getClassName(){return"LengthBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = length(${this.value.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.LengthBlock",mL);class mw extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("value",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NegateBlock"}get value(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = -1.0 * ${this.value.associatedVariableName}; +`,this}}(0,rg.H)("BABYLON.NegateBlock",mw);class mB extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("value",tf.AutoDetect),this.registerInput("power",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"PowBlock"}get value(){return this._inputs[0]}get power(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = pow(${this.value.associatedVariableName}, ${this.power.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.PowBlock",mB);class mU extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("seed",tf.AutoDetect),this.registerOutput("output",tf.Float),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Vector2|tf.Vector3|tf.Vector4|tf.Color3|tf.Color4)}getClassName(){return"RandomNumberBlock"}get seed(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=`//${this.name}`;return e._emitFunctionFromInclude("helperFunctions",i),e.compilationString+=this._declareOutput(t,e)+` = getRand(${this.seed.associatedVariableName}.xy); +`,this}}(0,rg.H)("BABYLON.RandomNumberBlock",mU);class mV extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("x",tf.Float),this.registerInput("y",tf.Float),this.registerOutput("output",tf.Float)}getClassName(){return"ArcTan2Block"}get x(){return this._inputs[0]}get y(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = atan(${this.x.associatedVariableName}, ${this.y.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.ArcTan2Block",mV);class mk extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("value",tf.AutoDetect),this.registerInput("edge0",tf.Float),this.registerInput("edge1",tf.Float),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"SmoothStepBlock"}get value(){return this._inputs[0]}get edge0(){return this._inputs[1]}get edge1(){return this._inputs[2]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = smoothstep(${this.edge0.associatedVariableName}, ${this.edge1.associatedVariableName}, ${this.value.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.SmoothStepBlock",mk);class mG extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("input",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ReciprocalBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return this.input.type===tf.Matrix?e.compilationString+=this._declareOutput(t,e)+` = inverse(${this.input.associatedVariableName}); +`:e.compilationString+=this._declareOutput(t,e)+` = 1. / ${this.input.associatedVariableName}; +`,this}}(0,rg.H)("BABYLON.ReciprocalBlock",mG);class mz extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("value",tf.AutoDetect),this.registerInput("reference",tf.AutoDetect),this.registerInput("distance",tf.Float),this.registerInput("replacement",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._linkConnectionTypes(0,3),this._inputs[0].excludedConnectionPointTypes.push(tf.Float),this._inputs[0].excludedConnectionPointTypes.push(tf.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tf.Float),this._inputs[1].excludedConnectionPointTypes.push(tf.Matrix),this._inputs[3].excludedConnectionPointTypes.push(tf.Float),this._inputs[3].excludedConnectionPointTypes.push(tf.Matrix)}getClassName(){return"ReplaceColorBlock"}get value(){return this._inputs[0]}get reference(){return this._inputs[1]}get distance(){return this._inputs[2]}get replacement(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+`; +`,e.compilationString+=`if (length(${this.value.associatedVariableName} - ${this.reference.associatedVariableName}) < ${this.distance.associatedVariableName}) { +`,e.compilationString+=`${t.associatedVariableName} = ${this.replacement.associatedVariableName}; +`,e.compilationString+=`} else { +`,e.compilationString+=`${t.associatedVariableName} = ${this.value.associatedVariableName}; +`,e.compilationString+=`} +`,this}}(0,rg.H)("BABYLON.ReplaceColorBlock",mz);class mW extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("value",tf.AutoDetect),this.registerInput("steps",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].excludedConnectionPointTypes.push(tf.Matrix),this._inputs[1].excludedConnectionPointTypes.push(tf.Matrix)}getClassName(){return"PosterizeBlock"}get value(){return this._inputs[0]}get steps(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = floor(${this.value.associatedVariableName} / (1.0 / ${this.steps.associatedVariableName})) * (1.0 / ${this.steps.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.PosterizeBlock",mW),(eM=iM||(iM={}))[eM.SawTooth=0]="SawTooth",eM[eM.Square=1]="Square",eM[eM.Triangle=2]="Triangle";class mH extends nv{constructor(e){super(e,tm.Neutral),this.kind=iM.SawTooth,this.registerInput("input",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tf.Matrix)}getClassName(){return"WaveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];switch(this.kind){case iM.SawTooth:e.compilationString+=this._declareOutput(t,e)+` = ${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}); +`;break;case iM.Square:e.compilationString+=this._declareOutput(t,e)+` = 1.0 - 2.0 * round(fract(${this.input.associatedVariableName})); +`;break;case iM.Triangle:e.compilationString+=this._declareOutput(t,e)+` = 2.0 * abs(2.0 * (${this.input.associatedVariableName} - floor(0.5 + ${this.input.associatedVariableName}))) - 1.0; +`}return this}serialize(){let e=super.serialize();return e.kind=this.kind,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.kind=e.kind}}(0,rg.H)("BABYLON.WaveBlock",mH);class mX{get step(){return this._step}set step(e){this._step=e}get color(){return this._color}set color(e){this._color=e}constructor(e,t){this.step=e,this.color=t}}class mY extends nv{colorStepsUpdated(){this.onValueChangedObservable.notifyObservers(this)}constructor(e){super(e,tm.Neutral),this.colorSteps=[new mX(0,rm.Wo.Black()),new mX(1,rm.Wo.White())],this.onValueChangedObservable=new r_.y$,this.registerInput("gradient",tf.AutoDetect),this.registerOutput("output",tf.Color3),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Float|tf.Vector2|tf.Vector3|tf.Vector4|tf.Color3|tf.Color4)}getClassName(){return"GradientBlock"}get gradient(){return this._inputs[0]}get output(){return this._outputs[0]}_writeColorConstant(e){let t=this.colorSteps[e];return`vec3(${t.color.r}, ${t.color.g}, ${t.color.b})`}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];if(!this.colorSteps.length||!this.gradient.connectedPoint){e.compilationString+=this._declareOutput(t,e)+` = vec3(0., 0., 0.); +`;return}let i=e._getFreeVariableName("gradientTempColor"),r=e._getFreeVariableName("gradientTempPosition");e.compilationString+=`vec3 ${i} = ${this._writeColorConstant(0)}; +`,e.compilationString+=`float ${r}; +`;let s=this.gradient.associatedVariableName;this.gradient.connectedPoint.type!==tf.Float&&(s+=".x");for(let t=1;ti.getWorldMatrix().determinant()?-1:1)}_buildBlock(e){return e.target===tm.Fragment&&(e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}}(0,rg.H)("BABYLON.AnisotropyBlock",m2);class m3 extends mh{_onGenerateOnlyFragmentCodeChanged(){return this.position.isConnected?(this.generateOnlyFragmentCode=!this.generateOnlyFragmentCode,rb.Y.Error("The position input must not be connected to be able to switch!"),!1):(this._setTarget(),!0)}_setTarget(){super._setTarget(),this.getInputByName("position").target=this.generateOnlyFragmentCode?tm.Fragment:tm.Vertex,this.generateOnlyFragmentCode&&(this.forceIrradianceInFragment=!0)}constructor(e){super(e),this.useSphericalHarmonics=!0,this.forceIrradianceInFragment=!1,this._isUnique=!0,this.registerInput("position",tf.AutoDetect,!1,tm.Vertex),this.registerInput("world",tf.Matrix,!1,tm.Vertex),this.registerInput("color",tf.Color3,!0,tm.Fragment),this.registerOutput("reflection",tf.Object,tm.Fragment,new f$("reflection",this,tv.Output,m3,"ReflectionBlock")),this.position.addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Vector4)}getClassName(){return"ReflectionBlock"}get position(){return this._inputs[0]}get worldPosition(){return this.worldPositionConnectionPoint}get worldNormal(){return this.worldNormalConnectionPoint}get world(){return this._inputs[1]}get cameraPosition(){return this.cameraPositionConnectionPoint}get view(){return this.viewConnectionPoint}get color(){return this._inputs[2]}get reflection(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}get reflectionColor(){return this.color.isConnected?this.color.associatedVariableName:"vec3(1., 1., 1.)"}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("REFLECTION",s,!0),s&&(i.setValue(this._defineLODReflectionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularReflection,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem?!r.invertZ:r.invertZ,!0),i.setValue("SPHERICAL_HARMONICS",this.useSphericalHarmonics,!0),i.setValue("GAMMAREFLECTION",r.gammaSpace,!0),i.setValue("RGBDREFLECTION",r.isRGBD,!0),r&&r.coordinatesMode!==sj.SKYBOX_MODE&&r.isCube&&(i.setValue("USESPHERICALFROMREFLECTIONMAP",!0),i.setValue("USEIRRADIANCEMAP",!1),this.forceIrradianceInFragment||this._scene.getEngine().getCaps().maxVaryingVectors<=8?i.setValue("USESPHERICALINVERTEX",!1):i.setValue("USESPHERICALINVERTEX",!0)))}bind(e,t,i,r){super.bind(e,t,i);let s=this._getTexture();if(!s||!r)return;s.isCube?e.setTexture(this._cubeSamplerName,s):e.setTexture(this._2DSamplerName,s);let n=s.getSize().width;e.setFloat3(this._vReflectionMicrosurfaceInfosName,n,s.lodGenerationScale,s.lodGenerationOffset),e.setFloat2(this._vReflectionFilteringInfoName,n,rk.R.Log2(n));let a=r.materialDefines,o=s.sphericalPolynomial;if(a.USESPHERICALFROMREFLECTIONMAP&&o){if(a.SPHERICAL_HARMONICS){let t=o.preScaledHarmonics;e.setVector3("vSphericalL00",t.l00),e.setVector3("vSphericalL1_1",t.l1_1),e.setVector3("vSphericalL10",t.l10),e.setVector3("vSphericalL11",t.l11),e.setVector3("vSphericalL2_2",t.l2_2),e.setVector3("vSphericalL2_1",t.l2_1),e.setVector3("vSphericalL20",t.l20),e.setVector3("vSphericalL21",t.l21),e.setVector3("vSphericalL22",t.l22)}else e.setFloat3("vSphericalX",o.x.x,o.x.y,o.x.z),e.setFloat3("vSphericalY",o.y.x,o.y.y,o.y.z),e.setFloat3("vSphericalZ",o.z.x,o.z.y,o.z.z),e.setFloat3("vSphericalXX_ZZ",o.xx.x-o.zz.x,o.xx.y-o.zz.y,o.xx.z-o.zz.z),e.setFloat3("vSphericalYY_ZZ",o.yy.x-o.zz.x,o.yy.y-o.zz.y,o.yy.z-o.zz.z),e.setFloat3("vSphericalZZ",o.zz.x,o.zz.y,o.zz.z),e.setFloat3("vSphericalXY",o.xy.x,o.xy.y,o.xy.z),e.setFloat3("vSphericalYZ",o.yz.x,o.yz.y,o.yz.z),e.setFloat3("vSphericalZX",o.zx.x,o.zx.y,o.zx.z)}}handleVertexSide(e){let t=super.handleVertexSide(e);e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]});let i=e._getFreeVariableName("reflectionVector");return this._vEnvironmentIrradianceName=e._getFreeVariableName("vEnvironmentIrradiance"),e._emitVaryingFromString(this._vEnvironmentIrradianceName,"vec3","defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)"),e._emitUniformFromString("vSphericalL00","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL1_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL10","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL11","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_2","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL2_1","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL20","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL21","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalL22","vec3","SPHERICAL_HARMONICS"),e._emitUniformFromString("vSphericalX","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXX_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYY_ZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalXY","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalYZ","vec3","SPHERICAL_HARMONICS",!0),e._emitUniformFromString("vSphericalZX","vec3","SPHERICAL_HARMONICS",!0),t+=`#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX) + vec3 ${i} = vec3(${this._reflectionMatrixName} * vec4(normalize(${this.worldNormal.associatedVariableName}).xyz, 0)).xyz; + #ifdef ${this._defineOppositeZ} + ${i}.z *= -1.0; + #endif + ${this._vEnvironmentIrradianceName} = computeEnvironmentIrradiance(${i}); + #endif +`}getCode(e,t){let i="";this.handleFragmentSideInits(e),e._emitFunctionFromInclude("harmonicsFunctions",`//${this.name}`,{replaceStrings:[{search:/uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g,replace:""},{search:/uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g,replace:""}]}),e._emitFunction("sampleReflection",` + #ifdef ${this._define3DName} + #define sampleReflection(s, c) textureCube(s, c) + #else + #define sampleReflection(s, c) texture2D(s, c) + #endif +`,`//${this.name}`),e._emitFunction("sampleReflectionLod",` + #ifdef ${this._define3DName} + #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif +`,`//${this.name}`);let r=` + vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) { + ${this.handleFragmentSideCodeReflectionCoords("worldNormal","worldPos",!0,!0)} + return ${this._reflectionVectorName}; + } +`;return e._emitFunction("computeReflectionCoordsPBR",r,`//${this.name}`),this._vReflectionMicrosurfaceInfosName=e._getFreeVariableName("vReflectionMicrosurfaceInfos"),e._emitUniformFromString(this._vReflectionMicrosurfaceInfosName,"vec3"),this._vReflectionInfosName=e._getFreeVariableName("vReflectionInfos"),this._vReflectionFilteringInfoName=e._getFreeVariableName("vReflectionFilteringInfo"),e._emitUniformFromString(this._vReflectionFilteringInfoName,"vec2"),i+=`#ifdef REFLECTION + vec2 ${this._vReflectionInfosName} = vec2(1., 0.); + + reflectionOutParams reflectionOut; + + reflectionBlock( + ${this.generateOnlyFragmentCode?this._worldPositionNameInFragmentOnlyMode:"v_"+this.worldPosition.associatedVariableName}.xyz, + ${t}, + alphaG, + ${this._vReflectionMicrosurfaceInfosName}, + ${this._vReflectionInfosName}, + ${this.reflectionColor}, + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #if defined(${this._defineLODReflectionAlpha}) && !defined(${this._defineSkyboxName}) + NdotVUnclamped, + #endif + #ifdef ${this._defineLinearSpecularReflection} + roughness, + #endif + #ifdef ${this._define3DName} + ${this._cubeSamplerName}, + #else + ${this._2DSamplerName}, + #endif + #if defined(NORMAL) && defined(USESPHERICALINVERTEX) + ${this._vEnvironmentIrradianceName}, + #endif + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + ${this._reflectionMatrixName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, // ** not handled ** + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${this._define3DName} + ${this._cubeSamplerName}, + ${this._cubeSamplerName}, + #else + ${this._2DSamplerName}, + ${this._2DSamplerName}, + #endif + #endif + #ifdef REALTIME_FILTERING + ${this._vReflectionFilteringInfoName}, + #endif + reflectionOut + ); + #endif +`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target!==tm.Fragment&&(this._defineLODReflectionAlpha=e._getFreeDefineName("LODINREFLECTIONALPHA"),this._defineLinearSpecularReflection=e._getFreeDefineName("LINEARSPECULARREFLECTION")),this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e+=`${this._codeVariableName}.texture.gammaSpace = ${this.texture.gammaSpace}; +`),e+=`${this._codeVariableName}.useSphericalHarmonics = ${this.useSphericalHarmonics}; +${this._codeVariableName}.forceIrradianceInFragment = ${this.forceIrradianceInFragment}; +`}serialize(){var e,t;let i=super.serialize();return i.useSphericalHarmonics=this.useSphericalHarmonics,i.forceIrradianceInFragment=this.forceIrradianceInFragment,i.gammaSpace=null===(t=null===(e=this.texture)||void 0===e?void 0:e.gammaSpace)||void 0===t||t,i}_deserialize(e,t,i){super._deserialize(e,t,i),this.useSphericalHarmonics=e.useSphericalHarmonics,this.forceIrradianceInFragment=e.forceIrradianceInFragment,this.texture&&(this.texture.gammaSpace=e.gammaSpace)}}(0,sx.gn)([nS("Spherical Harmonics",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m3.prototype,"useSphericalHarmonics",void 0),(0,sx.gn)([nS("Force irradiance in fragment",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m3.prototype,"forceIrradianceInFragment",void 0),(0,rg.H)("BABYLON.ReflectionBlock",m3);class m4 extends nv{constructor(e){super(e,tm.Fragment),this._tangentCorrectionFactorName="",this.remapF0OnInterfaceChange=!0,this._isUnique=!0,this.registerInput("intensity",tf.Float,!1,tm.Fragment),this.registerInput("roughness",tf.Float,!0,tm.Fragment),this.registerInput("indexOfRefraction",tf.Float,!0,tm.Fragment),this.registerInput("normalMapColor",tf.Color3,!0,tm.Fragment),this.registerInput("uv",tf.Vector2,!0,tm.Fragment),this.registerInput("tintColor",tf.Color3,!0,tm.Fragment),this.registerInput("tintAtDistance",tf.Float,!0,tm.Fragment),this.registerInput("tintThickness",tf.Float,!0,tm.Fragment),this.registerInput("worldTangent",tf.Vector4,!0),this.registerInput("worldNormal",tf.AutoDetect,!0),this.worldNormal.addExcludedConnectionPointFromAllowedTypes(tf.Color4|tf.Vector4|tf.Vector3),this.registerInput("TBN",tf.Object,!0,tm.VertexAndFragment,new f$("TBN",this,tv.Input,f2,"TBNBlock")),this.registerOutput("clearcoat",tf.Object,tm.Fragment,new f$("clearcoat",this,tv.Output,m4,"ClearCoatBlock"))}initialize(e){e._excludeVariableName("clearcoatOut"),e._excludeVariableName("vClearCoatParams"),e._excludeVariableName("vClearCoatTintParams"),e._excludeVariableName("vClearCoatRefractionParams"),e._excludeVariableName("vClearCoatTangentSpaceParams"),e._excludeVariableName("vGeometricNormaClearCoatW")}getClassName(){return"ClearCoatBlock"}get intensity(){return this._inputs[0]}get roughness(){return this._inputs[1]}get indexOfRefraction(){return this._inputs[2]}get normalMapColor(){return this._inputs[3]}get uv(){return this._inputs[4]}get tintColor(){return this._inputs[5]}get tintAtDistance(){return this._inputs[6]}get tintThickness(){return this._inputs[7]}get worldTangent(){return this._inputs[8]}get worldNormal(){return this._inputs[9]}get TBN(){return this._inputs[10]}get clearcoat(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new nI("ClearCoat intensity",tm.Fragment,tf.Float);e.value=1,e.output.connectTo(this.intensity)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("CLEARCOAT",!0),i.setValue("CLEARCOAT_TEXTURE",!1,!0),i.setValue("CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE",!0,!0),i.setValue("CLEARCOAT_TINT",this.tintColor.isConnected||this.tintThickness.isConnected||this.tintAtDistance.isConnected,!0),i.setValue("CLEARCOAT_BUMP",this.normalMapColor.isConnected,!0),i.setValue("CLEARCOAT_DEFAULTIOR",!this.indexOfRefraction.isConnected||this.indexOfRefraction.connectInputBlock.value===pE._DefaultIndexOfRefraction,!0),i.setValue("CLEARCOAT_REMAP_F0",this.remapF0OnInterfaceChange,!0)}bind(e,t,i){var r,s;super.bind(e,t,i);let n=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:pE._DefaultIndexOfRefraction,a=1-n,o=1+n;e.setFloat4("vClearCoatRefractionParams",Math.pow(-a/o,2),1/n,a,o);let l=this.clearcoat.hasEndpoints?this.clearcoat.endpoints[0].ownerBlock:null,h=(null==l?void 0:l.perturbedNormal.isConnected)?l.perturbedNormal.connectedPoint.ownerBlock:null;this._scene._mirroredCameraPosition?e.setFloat2("vClearCoatTangentSpaceParams",(null==h?void 0:h.invertX)?1:-1,(null==h?void 0:h.invertY)?1:-1):e.setFloat2("vClearCoatTangentSpaceParams",(null==h?void 0:h.invertX)?-1:1,(null==h?void 0:h.invertY)?-1:1),i&&e.setFloat(this._tangentCorrectionFactorName,0>i.getWorldMatrix().determinant()?-1:1)}_generateTBNSpace(e,t,i){let r="",s=`//${this.name}`,n=this.worldTangent;e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable");let a={search:/defined\(TANGENT\)/g,replace:n.isConnected?"defined(TANGENT)":"defined(IGNORE)"},o=this.TBN;return o.isConnected?e.compilationString+=` + #ifdef TBNBLOCK + mat3 vTBN = ${o.associatedVariableName}; + #endif + `:n.isConnected&&(r+=`vec3 tbnNormal = normalize(${i}.xyz); +vec3 tbnTangent = normalize(${n.associatedVariableName}.xyz); +vec3 tbnBitangent = cross(tbnNormal, tbnTangent) * ${this._tangentCorrectionFactorName}; +mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal); +`),e._emitFunctionFromInclude("bumpFragmentMainFunctions",s,{replaceStrings:[a]}),r}static GetCode(e,t,i,r,s,n,a){let o="",l=(null==t?void 0:t.intensity.isConnected)?t.intensity.associatedVariableName:"1.",h=(null==t?void 0:t.roughness.isConnected)?t.roughness.associatedVariableName:"0.",u=(null==t?void 0:t.normalMapColor.isConnected)?t.normalMapColor.associatedVariableName:"vec3(0.)",c=(null==t?void 0:t.uv.isConnected)?t.uv.associatedVariableName:"vec2(0.)",d=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",p=(null==t?void 0:t.tintThickness.isConnected)?t.tintThickness.associatedVariableName:"1.",_=(null==t?void 0:t.tintAtDistance.isConnected)?t.tintAtDistance.associatedVariableName:"1.";if(t){e._emitUniformFromString("vClearCoatRefractionParams","vec4"),e._emitUniformFromString("vClearCoatTangentSpaceParams","vec2");let i=t.worldNormal;o+=`vec3 vGeometricNormaClearCoatW = ${i.isConnected?"normalize("+i.associatedVariableName+".xyz)":"geometricNormalW"}; +`}else o+=`vec3 vGeometricNormaClearCoatW = geometricNormalW; +`;return s&&t&&(o+=t._generateTBNSpace(e,r,a),n=t.worldTangent.isConnected),o+=`clearcoatOutParams clearcoatOut; + + #ifdef CLEARCOAT + vec2 vClearCoatParams = vec2(${l}, ${h}); + vec4 vClearCoatTintParams = vec4(${d}, ${p}); + + clearcoatBlock( + ${r}.xyz, + vGeometricNormaClearCoatW, + viewDirectionW, + vClearCoatParams, + specularEnvironmentR0, + #ifdef CLEARCOAT_TEXTURE + vec2(0.), + #endif + #ifdef CLEARCOAT_TINT + vClearCoatTintParams, + ${_}, + vClearCoatRefractionParams, + #ifdef CLEARCOAT_TINT_TEXTURE + vec4(0.), + #endif + #endif + #ifdef CLEARCOAT_BUMP + vec2(0., 1.), + vec4(${u}, 0.), + ${c}, + #if defined(${n?"TANGENT":"IGNORE"}) && defined(NORMAL) + vTBN, + #else + vClearCoatTangentSpaceParams, + #endif + #ifdef OBJECTSPACE_NORMALMAP + normalMatrix, + #endif + #endif + #if defined(FORCENORMALFORWARD) && defined(NORMAL) + faceNormal, + #endif + #ifdef REFLECTION + ${null==i?void 0:i._vReflectionMicrosurfaceInfosName}, + ${null==i?void 0:i._vReflectionInfosName}, + ${null==i?void 0:i.reflectionColor}, + vLightingIntensity, + #ifdef ${null==i?void 0:i._define3DName} + ${null==i?void 0:i._cubeSamplerName}, + #else + ${null==i?void 0:i._2DSamplerName}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${null==i?void 0:i._define3DName} + ${null==i?void 0:i._cubeSamplerName}, + ${null==i?void 0:i._cubeSamplerName}, + #else + ${null==i?void 0:i._2DSamplerName}, + ${null==i?void 0:i._2DSamplerName}, + #endif + #endif + #endif + #if defined(ENVIRONMENTBRDF) && !defined(${null==i?void 0:i._defineSkyboxName}) + #ifdef RADIANCEOCCLUSION + ambientMonochrome, + #endif + #endif + #if defined(CLEARCOAT_BUMP) || defined(TWOSIDEDLIGHTING) + (gl_FrontFacing ? 1. : -1.), + #endif + clearcoatOut + ); + #else + clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0; + #endif +`}_buildBlock(e){return this._scene=e.sharedData.scene,e.target===tm.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),this._tangentCorrectionFactorName=e._getFreeDefineName("tangentCorrectionFactor"),e._emitUniformFromString(this._tangentCorrectionFactorName,"float")),this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.remapF0OnInterfaceChange = ${this.remapF0OnInterfaceChange}; +`}serialize(){let e=super.serialize();return e.remapF0OnInterfaceChange=this.remapF0OnInterfaceChange,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.remapF0OnInterfaceChange=null===(r=e.remapF0OnInterfaceChange)||void 0===r||r}}(0,sx.gn)([nS("Remap F0 on interface change",tx.Boolean,"ADVANCED")],m4.prototype,"remapF0OnInterfaceChange",void 0),(0,rg.H)("BABYLON.ClearCoatBlock",m4);class m5 extends nv{constructor(e){super(e,tm.Fragment),this._isUnique=!0,this.registerInput("intensity",tf.Float,!0,tm.Fragment),this.registerInput("indexOfRefraction",tf.Float,!0,tm.Fragment),this.registerInput("thickness",tf.Float,!0,tm.Fragment),this.registerOutput("iridescence",tf.Object,tm.Fragment,new f$("iridescence",this,tv.Output,m5,"IridescenceBlock"))}initialize(e){e._excludeVariableName("iridescenceOut"),e._excludeVariableName("vIridescenceParams")}getClassName(){return"IridescenceBlock"}get intensity(){return this._inputs[0]}get indexOfRefraction(){return this._inputs[1]}get thickness(){return this._inputs[2]}get iridescence(){return this._outputs[0]}autoConfigure(){if(!this.intensity.isConnected){let e=new nI("Iridescence intensity",tm.Fragment,tf.Float);e.value=1,e.output.connectTo(this.intensity);let t=new nI("Iridescence ior",tm.Fragment,tf.Float);t.value=1.3,t.output.connectTo(this.indexOfRefraction);let i=new nI("Iridescence thickness",tm.Fragment,tf.Float);i.value=400,i.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i),i.setValue("IRIDESCENCE",!0,!0),i.setValue("IRIDESCENCE_TEXTURE",!1,!0),i.setValue("IRIDESCENCE_THICKNESS_TEXTURE",!1,!0)}static GetCode(e){let t=(null==e?void 0:e.intensity.isConnected)?e.intensity.associatedVariableName:"1.",i=(null==e?void 0:e.indexOfRefraction.isConnected)?e.indexOfRefraction.associatedVariableName:pb._DefaultIndexOfRefraction,r=(null==e?void 0:e.thickness.isConnected)?e.thickness.associatedVariableName:pb._DefaultMaximumThickness;return`iridescenceOutParams iridescenceOut; + + #ifdef IRIDESCENCE + iridescenceBlock( + vec4(${t}, ${i}, 1., ${r}), + NdotV, + specularEnvironmentR0, + #ifdef CLEARCOAT + NdotVUnclamped, + #endif + iridescenceOut + ); + + float iridescenceIntensity = iridescenceOut.iridescenceIntensity; + specularEnvironmentR0 = iridescenceOut.specularEnvironmentR0; + #endif +`}_buildBlock(e){return e.target===tm.Fragment&&(e.sharedData.bindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this)),this}serialize(){return super.serialize()}_deserialize(e,t,i){super._deserialize(e,t,i)}}(0,rg.H)("BABYLON.IridescenceBlock",m5);class m6 extends nv{constructor(e){super(e,tm.Fragment),this.linkRefractionWithTransparency=!1,this.invertRefractionY=!1,this.useThicknessAsDepth=!1,this._isUnique=!0,this.registerInput("intensity",tf.Float,!1,tm.Fragment),this.registerInput("tintAtDistance",tf.Float,!0,tm.Fragment),this.registerInput("volumeIndexOfRefraction",tf.Float,!0,tm.Fragment),this.registerOutput("refraction",tf.Object,tm.Fragment,new f$("refraction",this,tv.Output,m6,"RefractionBlock"))}initialize(e){e._excludeVariableName("vRefractionPosition"),e._excludeVariableName("vRefractionSize")}getClassName(){return"RefractionBlock"}get intensity(){return this._inputs[0]}get tintAtDistance(){return this._inputs[1]}get volumeIndexOfRefraction(){return this._inputs[2]}get view(){return this.viewConnectionPoint}get refraction(){return this._outputs[0]}get hasTexture(){return!!this._getTexture()}_getTexture(){return this.texture?this.texture:this._scene.environmentTexture}autoConfigure(e,t=()=>!0){if(!this.intensity.isConnected){let e=new nI("Refraction intensity",tm.Fragment,tf.Float);e.value=1,e.output.connectTo(this.intensity)}if(this.view&&!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.View&&t(e));i||(i=new nI("view")).setAsSystemValue(tS.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this._getTexture(),s=r&&r.getTextureMatrix;i.setValue("SS_REFRACTION",s,!0),s&&(i.setValue(this._define3DName,r.isCube,!0),i.setValue(this._defineLODRefractionAlpha,r.lodLevelInAlpha,!0),i.setValue(this._defineLinearSpecularRefraction,r.linearSpecularLOD,!0),i.setValue(this._defineOppositeZ,this._scene.useRightHandedSystem&&r.isCube?!r.invertZ:r.invertZ,!0),i.setValue("SS_LINKREFRACTIONTOTRANSPARENCY",this.linkRefractionWithTransparency,!0),i.setValue("SS_GAMMAREFRACTION",r.gammaSpace,!0),i.setValue("SS_RGBDREFRACTION",r.isRGBD,!0),i.setValue("SS_USE_LOCAL_REFRACTIONMAP_CUBIC",!!r.boundingBoxSize,!0),i.setValue("SS_USE_THICKNESS_AS_DEPTH",this.useThicknessAsDepth,!0))}isReady(){let e=this._getTexture();return!e||!!e.isReadyOrNotBlocking()}bind(e,t,i){var r,s,n,a;super.bind(e,t,i);let o=this._getTexture();if(!o)return;o.isCube?e.setTexture(this._cubeSamplerName,o):e.setTexture(this._2DSamplerName,o),e.setMatrix(this._refractionMatrixName,o.getRefractionTextureMatrix());let l=1;!o.isCube&&o.depth&&(l=o.depth);let h=null!==(a=null!==(s=null===(r=this.volumeIndexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:null===(n=this.indexOfRefractionConnectionPoint.connectInputBlock)||void 0===n?void 0:n.value)&&void 0!==a?a:1.5;e.setFloat4(this._vRefractionInfosName,o.level,1/h,l,this.invertRefractionY?-1:1),e.setFloat4(this._vRefractionMicrosurfaceInfosName,o.getSize().width,o.lodGenerationScale,o.lodGenerationOffset,1/h);let u=o.getSize().width;e.setFloat2(this._vRefractionFilteringInfoName,u,rk.R.Log2(u)),o.boundingBoxSize&&(e.setVector3("vRefractionPosition",o.boundingBoxPosition),e.setVector3("vRefractionSize",o.boundingBoxSize))}getCode(e){return e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),this._cubeSamplerName=e._getFreeVariableName(this.name+"CubeSampler"),e.samplers.push(this._cubeSamplerName),this._2DSamplerName=e._getFreeVariableName(this.name+"2DSampler"),e.samplers.push(this._2DSamplerName),this._define3DName=e._getFreeDefineName("SS_REFRACTIONMAP_3D"),e._samplerDeclaration+=`#ifdef ${this._define3DName} +`,e._samplerDeclaration+=`uniform samplerCube ${this._cubeSamplerName}; +`,e._samplerDeclaration+=`#else +`,e._samplerDeclaration+=`uniform sampler2D ${this._2DSamplerName}; +`,e._samplerDeclaration+=`#endif +`,e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this),this._defineLODRefractionAlpha=e._getFreeDefineName("SS_LODINREFRACTIONALPHA"),this._defineLinearSpecularRefraction=e._getFreeDefineName("SS_LINEARSPECULARREFRACTION"),this._defineOppositeZ=e._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ"),this._refractionMatrixName=e._getFreeVariableName("refractionMatrix"),e._emitUniformFromString(this._refractionMatrixName,"mat4"),e._emitFunction("sampleRefraction",` + #ifdef ${this._define3DName} + #define sampleRefraction(s, c) textureCube(s, c) + #else + #define sampleRefraction(s, c) texture2D(s, c) + #endif +`,`//${this.name}`),e._emitFunction("sampleRefractionLod",` + #ifdef ${this._define3DName} + #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l) + #else + #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l) + #endif +`,`//${this.name}`),this._vRefractionMicrosurfaceInfosName=e._getFreeVariableName("vRefractionMicrosurfaceInfos"),e._emitUniformFromString(this._vRefractionMicrosurfaceInfosName,"vec4"),this._vRefractionInfosName=e._getFreeVariableName("vRefractionInfos"),e._emitUniformFromString(this._vRefractionInfosName,"vec4"),this._vRefractionFilteringInfoName=e._getFreeVariableName("vRefractionFilteringInfo"),e._emitUniformFromString(this._vRefractionFilteringInfoName,"vec2"),e._emitUniformFromString("vRefractionPosition","vec3"),e._emitUniformFromString("vRefractionSize","vec3"),""}_buildBlock(e){return this._scene=e.sharedData.scene,this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.texture&&(e=(this.texture.isCube?`${this._codeVariableName}.texture = new BABYLON.CubeTexture("${this.texture.name}"); +`:`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}"); +`)+`${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`),e+=`${this._codeVariableName}.linkRefractionWithTransparency = ${this.linkRefractionWithTransparency}; +${this._codeVariableName}.invertRefractionY = ${this.invertRefractionY}; +${this._codeVariableName}.useThicknessAsDepth = ${this.useThicknessAsDepth}; +`}serialize(){let e=super.serialize();return this.texture&&!this.texture.isRenderTarget&&(e.texture=this.texture.serialize()),e.linkRefractionWithTransparency=this.linkRefractionWithTransparency,e.invertRefractionY=this.invertRefractionY,e.useThicknessAsDepth=this.useThicknessAsDepth,e}_deserialize(e,t,i){super._deserialize(e,t,i),e.texture&&(i=0===e.texture.url.indexOf("data:")?"":i,e.texture.isCube?this.texture=dM.Parse(e.texture,t,i):this.texture=sj.Parse(e.texture,t,i)),this.linkRefractionWithTransparency=e.linkRefractionWithTransparency,this.invertRefractionY=e.invertRefractionY,this.useThicknessAsDepth=!!e.useThicknessAsDepth}}(0,sx.gn)([nS("Link refraction to transparency",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m6.prototype,"linkRefractionWithTransparency",void 0),(0,sx.gn)([nS("Invert refraction Y",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m6.prototype,"invertRefractionY",void 0),(0,sx.gn)([nS("Use thickness as depth",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m6.prototype,"useThicknessAsDepth",void 0),(0,rg.H)("BABYLON.RefractionBlock",m6);class m8 extends nv{constructor(e){super(e,tm.Fragment),this._isUnique=!0,this.registerInput("thickness",tf.Float,!1,tm.Fragment),this.registerInput("tintColor",tf.Color3,!0,tm.Fragment),this.registerInput("translucencyIntensity",tf.Float,!0,tm.Fragment),this.registerInput("translucencyDiffusionDist",tf.Color3,!0,tm.Fragment),this.registerInput("refraction",tf.Object,!0,tm.Fragment,new f$("refraction",this,tv.Input,m6,"RefractionBlock")),this.registerInput("dispersion",tf.Float,!0,tm.Fragment),this.registerOutput("subsurface",tf.Object,tm.Fragment,new f$("subsurface",this,tv.Output,m8,"SubSurfaceBlock"))}initialize(e){e._excludeVariableName("subSurfaceOut"),e._excludeVariableName("vThicknessParam"),e._excludeVariableName("vTintColor"),e._excludeVariableName("vSubSurfaceIntensity"),e._excludeVariableName("dispersion")}getClassName(){return"SubSurfaceBlock"}get thickness(){return this._inputs[0]}get tintColor(){return this._inputs[1]}get translucencyIntensity(){return this._inputs[2]}get translucencyDiffusionDist(){return this._inputs[3]}get refraction(){return this._inputs[4]}get dispersion(){return this._inputs[5]}get subsurface(){return this._outputs[0]}autoConfigure(){if(!this.thickness.isConnected){let e=new nI("SubSurface thickness",tm.Fragment,tf.Float);e.value=0,e.output.connectTo(this.thickness)}}prepareDefines(e,t,i){super.prepareDefines(e,t,i);let r=this.translucencyDiffusionDist.isConnected||this.translucencyIntensity.isConnected;i.setValue("SUBSURFACE",r||this.refraction.isConnected,!0),i.setValue("SS_TRANSLUCENCY",r,!0),i.setValue("SS_THICKNESSANDMASK_TEXTURE",!1,!0),i.setValue("SS_REFRACTIONINTENSITY_TEXTURE",!1,!0),i.setValue("SS_TRANSLUCENCYINTENSITY_TEXTURE",!1,!0),i.setValue("SS_MASK_FROM_THICKNESS_TEXTURE",!1,!0),i.setValue("SS_USE_GLTF_TEXTURES",!1,!0),i.setValue("SS_DISPERSION",this.dispersion.isConnected,!0)}static GetCode(e,t,i,r){var s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x;let T=(null==t?void 0:t.thickness.isConnected)?t.thickness.associatedVariableName:"0.",S=(null==t?void 0:t.tintColor.isConnected)?t.tintColor.associatedVariableName:"vec3(1.)",E=(null==t?void 0:t.translucencyIntensity.isConnected)?null==t?void 0:t.translucencyIntensity.associatedVariableName:"1.",C=(null==t?void 0:t.translucencyDiffusionDist.isConnected)?null==t?void 0:t.translucencyDiffusionDist.associatedVariableName:"vec3(1.)",b=(null==t?void 0:t.refraction.isConnected)?null===(s=null==t?void 0:t.refraction.connectedPoint)||void 0===s?void 0:s.ownerBlock:null,y=(null==b?void 0:b.tintAtDistance.isConnected)?b.tintAtDistance.associatedVariableName:"1.",A=(null==b?void 0:b.intensity.isConnected)?b.intensity.associatedVariableName:"1.",R=(null==b?void 0:b.view.isConnected)?b.view.associatedVariableName:"",P=(null==t?void 0:t.dispersion.isConnected)?null==t?void 0:t.dispersion.associatedVariableName:"0.0";return""+(null!==(n=null==b?void 0:b.getCode(e))&&void 0!==n?n:"")+`subSurfaceOutParams subSurfaceOut; + + #ifdef SUBSURFACE + vec2 vThicknessParam = vec2(0., ${T}); + vec4 vTintColor = vec4(${S}, ${y}); + vec3 vSubSurfaceIntensity = vec3(${A}, ${E}, 0.); + float dispersion = ${P}; + subSurfaceBlock( + vSubSurfaceIntensity, + vThicknessParam, + vTintColor, + normalW, + specularEnvironmentReflectance, + #ifdef SS_THICKNESSANDMASK_TEXTURE + vec4(0.), + #endif + #ifdef REFLECTION + #ifdef SS_TRANSLUCENCY + ${null==i?void 0:i._reflectionMatrixName}, + #ifdef USESPHERICALFROMREFLECTIONMAP + #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX) + reflectionOut.irradianceVector, + #endif + #if defined(REALTIME_FILTERING) + ${null==i?void 0:i._cubeSamplerName}, + ${null==i?void 0:i._vReflectionFilteringInfoName}, + #endif + #endif + #ifdef USEIRRADIANCEMAP + irradianceSampler, + #endif + #endif + #endif + #if defined(SS_REFRACTION) || defined(SS_TRANSLUCENCY) + surfaceAlbedo, + #endif + #ifdef SS_REFRACTION + ${r}.xyz, + viewDirectionW, + ${R}, + ${null!==(a=null==b?void 0:b._vRefractionInfosName)&&void 0!==a?a:""}, + ${null!==(o=null==b?void 0:b._refractionMatrixName)&&void 0!==o?o:""}, + ${null!==(l=null==b?void 0:b._vRefractionMicrosurfaceInfosName)&&void 0!==l?l:""}, + vLightingIntensity, + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha, + #endif + #ifdef ${null!==(h=null==b?void 0:b._defineLODRefractionAlpha)&&void 0!==h?h:"IGNORE"} + NdotVUnclamped, + #endif + #ifdef ${null!==(u=null==b?void 0:b._defineLinearSpecularRefraction)&&void 0!==u?u:"IGNORE"} + roughness, + #endif + alphaG, + #ifdef ${null!==(c=null==b?void 0:b._define3DName)&&void 0!==c?c:"IGNORE"} + ${null!==(d=null==b?void 0:b._cubeSamplerName)&&void 0!==d?d:""}, + #else + ${null!==(p=null==b?void 0:b._2DSamplerName)&&void 0!==p?p:""}, + #endif + #ifndef LODBASEDMICROSFURACE + #ifdef ${null!==(_=null==b?void 0:b._define3DName)&&void 0!==_?_:"IGNORE"} + ${null!==(f=null==b?void 0:b._cubeSamplerName)&&void 0!==f?f:""}, + ${null!==(m=null==b?void 0:b._cubeSamplerName)&&void 0!==m?m:""}, + #else + ${null!==(g=null==b?void 0:b._2DSamplerName)&&void 0!==g?g:""}, + ${null!==(v=null==b?void 0:b._2DSamplerName)&&void 0!==v?v:""}, + #endif + #endif + #ifdef ANISOTROPIC + anisotropicOut, + #endif + #ifdef REALTIME_FILTERING + ${null!==(x=null==b?void 0:b._vRefractionFilteringInfoName)&&void 0!==x?x:""}, + #endif + #ifdef SS_USE_LOCAL_REFRACTIONMAP_CUBIC + vRefractionPosition, + vRefractionSize, + #endif + #ifdef SS_DISPERSION + dispersion, + #endif + #endif + #ifdef SS_TRANSLUCENCY + ${C}, + #endif + subSurfaceOut + ); + + #ifdef SS_REFRACTION + surfaceAlbedo = subSurfaceOut.surfaceAlbedo; + #ifdef SS_LINKREFRACTIONTOTRANSPARENCY + alpha = subSurfaceOut.alpha; + #endif + #endif + #else + subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance; + #endif +`}_buildBlock(e){return e.target===tm.Fragment&&e.sharedData.blocksWithDefines.push(this),this}}(0,rg.H)("BABYLON.SubSurfaceBlock",m8);let m7={ambientClr:["finalAmbient",""],diffuseDir:["finalDiffuse",""],specularDir:["finalSpecularScaled","!defined(UNLIT) && defined(SPECULARTERM)"],clearcoatDir:["finalClearCoatScaled","!defined(UNLIT) && defined(CLEARCOAT)"],sheenDir:["finalSheenScaled","!defined(UNLIT) && defined(SHEEN)"],diffuseInd:["finalIrradiance","!defined(UNLIT) && defined(REFLECTION)"],specularInd:["finalRadianceScaled","!defined(UNLIT) && defined(REFLECTION)"],clearcoatInd:["clearcoatOut.finalClearCoatRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],sheenInd:["sheenOut.finalSheenRadianceScaled","!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],refraction:["subSurfaceOut.finalRefraction","!defined(UNLIT) && defined(SS_REFRACTION)"],lighting:["finalColor.rgb",""],shadow:["aggShadow",""],alpha:["alpha",""]};class m9 extends nv{static _OnGenerateOnlyFragmentCodeChanged(e,t){return e.worldPosition.isConnected?(e.generateOnlyFragmentCode=!e.generateOnlyFragmentCode,rb.Y.Error("The worldPosition input must not be connected to be able to switch!"),!1):(e._setTarget(),!0)}_setTarget(){this._setInitialTarget(this.generateOnlyFragmentCode?tm.Fragment:tm.VertexAndFragment),this.getInputByName("worldPosition").target=this.generateOnlyFragmentCode?tm.Fragment:tm.Vertex}constructor(e){super(e,tm.VertexAndFragment),this._environmentBRDFTexture=null,this._metallicReflectanceColor=rm.Wo.White(),this._metallicF0Factor=1,this.directIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.lightFalloff=0,this.useAlphaTest=!1,this.alphaTestCutoff=.5,this.useAlphaBlending=!1,this.useRadianceOverAlpha=!0,this.useSpecularOverAlpha=!0,this.enableSpecularAntiAliasing=!1,this.realTimeFiltering=!1,this.realTimeFilteringQuality=8,this.useEnergyConservation=!0,this.useRadianceOcclusion=!0,this.useHorizonOcclusion=!0,this.unlit=!1,this.forceNormalForward=!1,this.generateOnlyFragmentCode=!1,this.debugMode=0,this.debugLimit=0,this.debugFactor=1,this._isUnique=!0,this.registerInput("worldPosition",tf.Vector4,!1,tm.Vertex),this.registerInput("worldNormal",tf.Vector4,!1,tm.Fragment),this.registerInput("view",tf.Matrix,!1),this.registerInput("cameraPosition",tf.Vector3,!1,tm.Fragment),this.registerInput("perturbedNormal",tf.Vector4,!0,tm.Fragment),this.registerInput("baseColor",tf.Color3,!0,tm.Fragment),this.registerInput("metallic",tf.Float,!1,tm.Fragment),this.registerInput("roughness",tf.Float,!1,tm.Fragment),this.registerInput("ambientOcc",tf.Float,!0,tm.Fragment),this.registerInput("opacity",tf.Float,!0,tm.Fragment),this.registerInput("indexOfRefraction",tf.Float,!0,tm.Fragment),this.registerInput("ambientColor",tf.Color3,!0,tm.Fragment),this.registerInput("reflection",tf.Object,!0,tm.Fragment,new f$("reflection",this,tv.Input,m3,"ReflectionBlock")),this.registerInput("clearcoat",tf.Object,!0,tm.Fragment,new f$("clearcoat",this,tv.Input,m4,"ClearCoatBlock")),this.registerInput("sheen",tf.Object,!0,tm.Fragment,new f$("sheen",this,tv.Input,m1,"SheenBlock")),this.registerInput("subsurface",tf.Object,!0,tm.Fragment,new f$("subsurface",this,tv.Input,m8,"SubSurfaceBlock")),this.registerInput("anisotropy",tf.Object,!0,tm.Fragment,new f$("anisotropy",this,tv.Input,m2,"AnisotropyBlock")),this.registerInput("iridescence",tf.Object,!0,tm.Fragment,new f$("iridescence",this,tv.Input,m5,"IridescenceBlock")),this.registerOutput("ambientClr",tf.Color3,tm.Fragment),this.registerOutput("diffuseDir",tf.Color3,tm.Fragment),this.registerOutput("specularDir",tf.Color3,tm.Fragment),this.registerOutput("clearcoatDir",tf.Color3,tm.Fragment),this.registerOutput("sheenDir",tf.Color3,tm.Fragment),this.registerOutput("diffuseInd",tf.Color3,tm.Fragment),this.registerOutput("specularInd",tf.Color3,tm.Fragment),this.registerOutput("clearcoatInd",tf.Color3,tm.Fragment),this.registerOutput("sheenInd",tf.Color3,tm.Fragment),this.registerOutput("refraction",tf.Color3,tm.Fragment),this.registerOutput("lighting",tf.Color3,tm.Fragment),this.registerOutput("shadow",tf.Float,tm.Fragment),this.registerOutput("alpha",tf.Float,tm.Fragment)}initialize(e){e._excludeVariableName("vLightingIntensity"),e._excludeVariableName("geometricNormalW"),e._excludeVariableName("normalW"),e._excludeVariableName("faceNormal"),e._excludeVariableName("albedoOpacityOut"),e._excludeVariableName("surfaceAlbedo"),e._excludeVariableName("alpha"),e._excludeVariableName("aoOut"),e._excludeVariableName("baseColor"),e._excludeVariableName("reflectivityOut"),e._excludeVariableName("microSurface"),e._excludeVariableName("roughness"),e._excludeVariableName("NdotVUnclamped"),e._excludeVariableName("NdotV"),e._excludeVariableName("alphaG"),e._excludeVariableName("AARoughnessFactors"),e._excludeVariableName("environmentBrdf"),e._excludeVariableName("ambientMonochrome"),e._excludeVariableName("seo"),e._excludeVariableName("eho"),e._excludeVariableName("environmentRadiance"),e._excludeVariableName("irradianceVector"),e._excludeVariableName("environmentIrradiance"),e._excludeVariableName("diffuseBase"),e._excludeVariableName("specularBase"),e._excludeVariableName("preInfo"),e._excludeVariableName("info"),e._excludeVariableName("shadow"),e._excludeVariableName("finalDiffuse"),e._excludeVariableName("finalAmbient"),e._excludeVariableName("ambientOcclusionForDirectDiffuse"),e._excludeVariableName("finalColor"),e._excludeVariableName("vClipSpacePosition"),e._excludeVariableName("vDebugMode")}getClassName(){return"PBRMetallicRoughnessBlock"}get worldPosition(){return this._inputs[0]}get worldNormal(){return this._inputs[1]}get view(){return this._inputs[2]}get cameraPosition(){return this._inputs[3]}get perturbedNormal(){return this._inputs[4]}get baseColor(){return this._inputs[5]}get metallic(){return this._inputs[6]}get roughness(){return this._inputs[7]}get ambientOcc(){return this._inputs[8]}get opacity(){return this._inputs[9]}get indexOfRefraction(){return this._inputs[10]}get ambientColor(){return this._inputs[11]}get reflection(){return this._inputs[12]}get clearcoat(){return this._inputs[13]}get sheen(){return this._inputs[14]}get subsurface(){return this._inputs[15]}get anisotropy(){return this._inputs[16]}get iridescence(){return this._inputs[17]}get ambientClr(){return this._outputs[0]}get diffuseDir(){return this._outputs[1]}get specularDir(){return this._outputs[2]}get clearcoatDir(){return this._outputs[3]}get sheenDir(){return this._outputs[4]}get diffuseInd(){return this._outputs[5]}get specularInd(){return this._outputs[6]}get clearcoatInd(){return this._outputs[7]}get sheenInd(){return this._outputs[8]}get refraction(){return this._outputs[9]}get lighting(){return this._outputs[10]}get shadow(){return this._outputs[11]}get alpha(){return this._outputs[12]}autoConfigure(e,t=()=>!0){if(!this.cameraPosition.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.CameraPosition&&t(e));i||(i=new nI("cameraPosition")).setAsSystemValue(tS.CameraPosition),i.output.connectTo(this.cameraPosition)}if(!this.view.isConnected){let i=e.getInputBlockByPredicate(e=>e.systemValue===tS.View&&t(e));i||(i=new nI("view")).setAsSystemValue(tS.View),i.output.connectTo(this.view)}}prepareDefines(e,t,i){i.setValue("PBR",!0),i.setValue("METALLICWORKFLOW",!0),i.setValue("DEBUGMODE",this.debugMode,!0),i.setValue("DEBUGMODE_FORCERETURN",!0),i.setValue("NORMALXYSCALE",!0),i.setValue("BUMP",this.perturbedNormal.isConnected,!0),i.setValue("LODBASEDMICROSFURACE",this._scene.getEngine().getCaps().textureLOD),i.setValue("ALBEDO",!1,!0),i.setValue("OPACITY",this.opacity.isConnected,!0),i.setValue("AMBIENT",!0,!0),i.setValue("AMBIENTINGRAYSCALE",!1,!0),i.setValue("REFLECTIVITY",!1,!0),i.setValue("AOSTOREINMETALMAPRED",!1,!0),i.setValue("METALLNESSSTOREINMETALMAPBLUE",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPALPHA",!1,!0),i.setValue("ROUGHNESSSTOREINMETALMAPGREEN",!1,!0),this.lightFalloff===pN.LIGHTFALLOFF_STANDARD?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!1)):this.lightFalloff===pN.LIGHTFALLOFF_GLTF?(i.setValue("USEPHYSICALLIGHTFALLOFF",!1),i.setValue("USEGLTFLIGHTFALLOFF",!0)):(i.setValue("USEPHYSICALLIGHTFALLOFF",!0),i.setValue("USEGLTFLIGHTFALLOFF",!1));let r=this.alphaTestCutoff.toString();i.setValue("ALPHABLEND",this.useAlphaBlending,!0),i.setValue("ALPHAFROMALBEDO",!1,!0),i.setValue("ALPHATEST",this.useAlphaTest,!0),i.setValue("ALPHATESTVALUE",0>r.indexOf(".")?r+".":r,!0),i.setValue("OPACITYRGB",!1,!0),i.setValue("RADIANCEOVERALPHA",this.useRadianceOverAlpha,!0),i.setValue("SPECULAROVERALPHA",this.useSpecularOverAlpha,!0),i.setValue("SPECULARAA",this._scene.getEngine().getCaps().standardDerivatives&&this.enableSpecularAntiAliasing,!0),i.setValue("REALTIME_FILTERING",this.realTimeFiltering,!0);let s=e.getScene();if(s.getEngine()._features.needTypeSuffixInShaderConstants?i.setValue("NUM_SAMPLES",this.realTimeFilteringQuality+"u",!0):i.setValue("NUM_SAMPLES",""+this.realTimeFilteringQuality,!0),i.setValue("BRDF_V_HEIGHT_CORRELATED",!0),i.setValue("MS_BRDF_ENERGY_CONSERVATION",this.useEnergyConservation,!0),i.setValue("RADIANCEOCCLUSION",this.useRadianceOcclusion,!0),i.setValue("HORIZONOCCLUSION",this.useHorizonOcclusion,!0),i.setValue("UNLIT",this.unlit,!0),i.setValue("FORCENORMALFORWARD",this.forceNormalForward,!0),this._environmentBRDFTexture&&ow.ReflectionTextureEnabled?(i.setValue("ENVIRONMENTBRDF",!0),i.setValue("ENVIRONMENTBRDF_RGBD",this._environmentBRDFTexture.isRGBD,!0)):(i.setValue("ENVIRONMENTBRDF",!1),i.setValue("ENVIRONMENTBRDF_RGBD",!1)),i._areImageProcessingDirty&&t.imageProcessingConfiguration&&t.imageProcessingConfiguration.prepareDefines(i),i._areLightsDirty){if(this.light){let t={needNormals:!1,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};nE.G.PrepareDefinesForLight(s,e,this.light,this._lightId,i,!0,t),t.needRebuild&&i.rebuild()}else nE.G.PrepareDefinesForLights(s,e,i,!0,t.maxSimultaneousLights),i._needNormals=!0,nE.G.PrepareDefinesForMultiview(s,i)}}updateUniformsAndSamples(e,t,i,r){for(let s=0;s=0;nE.G.PrepareUniformsAndSamplersForLight(s,e.uniforms,e.samplers,i["PROJECTEDLIGHTTEXTURE"+s],r,t)}}isReady(e,t,i){return(!this._environmentBRDFTexture||!!this._environmentBRDFTexture.isReady())&&(!i._areImageProcessingDirty||!t.imageProcessingConfiguration||!!t.imageProcessingConfiguration.isReady())}bind(e,t,i){var r,s;if(!i)return;let n=i.getScene();this.light?nE.G.BindLight(this.light,this._lightId,n,e,!0):nE.G.BindLights(n,i,e,!0,t.maxSimultaneousLights),e.setTexture(this._environmentBrdfSamplerName,this._environmentBRDFTexture),e.setFloat2("vDebugMode",this.debugLimit,this.debugFactor);let a=this._scene.ambientColor;a&&e.setColor3("ambientFromScene",a);let o=n.useRightHandedSystem===(null!=n._mirroredCameraPosition);e.setFloat(this._invertNormalName,o?-1:1),e.setFloat4("vLightingIntensity",this.directIntensity,1,this.environmentIntensity*this._scene.environmentIntensity,this.specularIntensity);let l=null!==(s=null===(r=this.indexOfRefraction.connectInputBlock)||void 0===r?void 0:r.value)&&void 0!==s?s:1.5;this._metallicReflectanceColor.scaleToRef(Math.pow((l-1)/(l+1),2)*this._metallicF0Factor,rm.zZ.Color3[0]);let h=this._metallicF0Factor;e.setColor4(this._vMetallicReflectanceFactorsName,rm.zZ.Color3[0],h),t.imageProcessingConfiguration&&t.imageProcessingConfiguration.bind(e)}_injectVertexCode(e){var t,i;let r=this.worldPosition,s=`//${this.name}`;this.light?(this._lightId=(void 0!==e.counters.lightCounter?e.counters.lightCounter:-1)+1,e.counters.lightCounter=this._lightId,e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString())):(e._emitFunctionFromInclude(e.supportUniformBuffers?"lightVxUboDeclaration":"lightVxFragmentDeclaration",s,{repeatKey:"maxSimultaneousLights"}),this._lightId=0,e.sharedData.dynamicUniformBlocks.push(this));let n="v_"+r.associatedVariableName;e._emitVaryingFromString(n,"vec4")&&(e.compilationString+=`${n} = ${r.associatedVariableName}; +`);let a=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;a&&(a.viewConnectionPoint=this.view),e.compilationString+=null!==(i=null==a?void 0:a.handleVertexSide(e))&&void 0!==i?i:"",e._emitVaryingFromString("vClipSpacePosition","vec4","defined(IGNORE) || DEBUGMODE > 0")&&(e._injectAtEnd+=`#if DEBUGMODE > 0 +`,e._injectAtEnd+=`vClipSpacePosition = gl_Position; +`,e._injectAtEnd+=`#endif +`),this.light?e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/worldPos/g,replace:r.associatedVariableName}]}):(e.compilationString+=`vec4 worldPos = ${r.associatedVariableName}; +`,this.view.isConnected&&(e.compilationString+=`mat4 view = ${this.view.associatedVariableName}; +`),e.compilationString+=e._emitCodeFromInclude("shadowsVertex",s,{repeatKey:"maxSimultaneousLights"}))}_getAlbedoOpacityCode(){let e=`albedoOpacityOutParams albedoOpacityOut; +`,t=this.baseColor.isConnected?this.baseColor.associatedVariableName:"vec3(1.)",i=this.opacity.isConnected?this.opacity.associatedVariableName:"1.";return e+`albedoOpacityBlock( + vec4(${t}, 1.), + #ifdef ALBEDO + vec4(1.), + vec2(1., 1.), + #endif + #ifdef OPACITY + vec4(${i}), + vec2(1., 1.), + #endif + albedoOpacityOut + ); + + vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo; + float alpha = albedoOpacityOut.alpha; +`}_getAmbientOcclusionCode(){let e=`ambientOcclusionOutParams aoOut; +`,t=this.ambientOcc.isConnected?this.ambientOcc.associatedVariableName:"1.";return e+`ambientOcclusionBlock( + #ifdef AMBIENT + vec3(${t}), + vec4(0., 1.0, 1.0, 0.), + #endif + aoOut + ); +`}_getReflectivityCode(e){let t=`reflectivityOutParams reflectivityOut; +`;return this._vMetallicReflectanceFactorsName=e._getFreeVariableName("vMetallicReflectanceFactors"),e._emitUniformFromString(this._vMetallicReflectanceFactorsName,"vec4"),t+=`vec3 baseColor = surfaceAlbedo; + + reflectivityBlock( + vec4(${this.metallic.associatedVariableName}, ${this.roughness.associatedVariableName}, 0., 0.), + #ifdef METALLICWORKFLOW + surfaceAlbedo, + ${this._vMetallicReflectanceFactorsName}, + #endif + #ifdef REFLECTIVITY + vec3(0., 0., 1.), + vec4(1.), + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor, + #endif + #ifdef MICROSURFACEMAP + microSurfaceTexel, <== not handled! + #endif + reflectivityOut + ); + + float microSurface = reflectivityOut.microSurface; + float roughness = reflectivityOut.roughness; + + #ifdef METALLICWORKFLOW + surfaceAlbedo = reflectivityOut.surfaceAlbedo; + #endif + #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED) + aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor; + #endif +`}_buildBlock(e){var t,i,r,s,n,a,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,E,C,b,y,A,R,P,I,M,D,O,N,F,L,w,B,U,V,k,G;super._buildBlock(e),this._scene=e.sharedData.scene,this._environmentBRDFTexture||(this._environmentBRDFTexture=dz(this._scene));let z=this.reflection.isConnected?null===(t=this.reflection.connectedPoint)||void 0===t?void 0:t.ownerBlock:null;if(z&&(z.worldPositionConnectionPoint=this.worldPosition,z.cameraPositionConnectionPoint=this.cameraPosition,z.worldNormalConnectionPoint=this.worldNormal,z.viewConnectionPoint=this.view),e.target!==tm.Fragment)return this._injectVertexCode(e),this;e.sharedData.forcedBindableBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.blockingBlocks.push(this),this.generateOnlyFragmentCode&&e.sharedData.dynamicUniformBlocks.push(this);let W=`//${this.name}`,H=this.perturbedNormal,X=this.worldPosition.associatedVariableName;this.generateOnlyFragmentCode?(X=e._getFreeVariableName("globalWorldPos"),e._emitFunction("pbr_globalworldpos",`vec3 ${X}; +`,W),e.compilationString+=`${X} = ${this.worldPosition.associatedVariableName}.xyz; +`,e.compilationString+=e._emitCodeFromInclude("shadowsVertex",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?`worldPos,${this.worldPosition.associatedVariableName}`:void 0}),e.compilationString+=`#if DEBUGMODE > 0 +`,e.compilationString+=`vec4 vClipSpacePosition = vec4((vec2(gl_FragCoord.xy) / vec2(1.0)) * 2.0 - 1.0, 0.0, 1.0); +`,e.compilationString+=`#endif +`):X="v_"+X,this._environmentBrdfSamplerName=e._getFreeVariableName("environmentBrdfSampler"),e._emit2DSampler(this._environmentBrdfSamplerName),e.sharedData.hints.needAlphaBlending=e.sharedData.hints.needAlphaBlending||this.useAlphaBlending,e.sharedData.hints.needAlphaTesting=e.sharedData.hints.needAlphaTesting||this.useAlphaTest,e._emitExtension("lod","#extension GL_EXT_shader_texture_lod : enable","defined(LODBASEDMICROSFURACE)"),e._emitExtension("derivatives","#extension GL_OES_standard_derivatives : enable"),e._emitUniformFromString("vDebugMode","vec2","defined(IGNORE) || DEBUGMODE > 0"),e._emitUniformFromString("ambientFromScene","vec3"),e.uniforms.push("exposureLinear"),e.uniforms.push("contrast"),e.uniforms.push("vInverseScreenSize"),e.uniforms.push("vignetteSettings1"),e.uniforms.push("vignetteSettings2"),e.uniforms.push("vCameraColorCurveNegative"),e.uniforms.push("vCameraColorCurveNeutral"),e.uniforms.push("vCameraColorCurvePositive"),e.uniforms.push("txColorTransform"),e.uniforms.push("colorTransformSettings"),e.uniforms.push("ditherIntensity"),this.light?e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()}]},this._lightId.toString()):e._emitFunctionFromInclude(e.supportUniformBuffers?"lightUboDeclaration":"lightFragmentDeclaration",W,{repeatKey:"maxSimultaneousLights",substitutionVars:this.generateOnlyFragmentCode?"varying,":void 0}),e._emitFunctionFromInclude("helperFunctions",W),e._emitFunctionFromInclude("importanceSampling",W),e._emitFunctionFromInclude("pbrHelperFunctions",W),e._emitFunctionFromInclude("imageProcessingDeclaration",W),e._emitFunctionFromInclude("imageProcessingFunctions",W),e._emitFunctionFromInclude("shadowsFragmentFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingSetupFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions",W),e._emitFunctionFromInclude("pbrBRDFFunctions",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(i=null==z?void 0:z._defineSkyboxName)&&void 0!==i?i:"REFLECTIONMAP_SKYBOX"}]}),e._emitFunctionFromInclude("hdrFilteringFunctions",W),e._emitFunctionFromInclude("pbrDirectLightingFunctions",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"}]}),e._emitFunctionFromInclude("pbrIBLFunctions",W),e._emitFunctionFromInclude("pbrBlockAlbedoOpacity",W),e._emitFunctionFromInclude("pbrBlockReflectivity",W),e._emitFunctionFromInclude("pbrBlockAmbientOcclusion",W),e._emitFunctionFromInclude("pbrBlockAlphaFresnel",W),e._emitFunctionFromInclude("pbrBlockAnisotropic",W),e._emitUniformFromString("vLightingIntensity","vec4"),(null==z?void 0:z.generateOnlyFragmentCode)&&(e.compilationString+=z.handleVertexSide(e)),this._vNormalWName=e._getFreeVariableName("vNormalW"),e.compilationString+=`vec4 ${this._vNormalWName} = normalize(${this.worldNormal.associatedVariableName}); +`,e._registerTempVariable("viewDirectionW")&&(e.compilationString+=`vec3 viewDirectionW = normalize(${this.cameraPosition.associatedVariableName} - ${X}.xyz); +`),e.compilationString+=`vec3 geometricNormalW = ${this._vNormalWName}.xyz; +`,e.compilationString+=`vec3 normalW = ${H.isConnected?"normalize("+H.associatedVariableName+".xyz)":"geometricNormalW"}; +`,this._invertNormalName=e._getFreeVariableName("invertNormal"),e._emitUniformFromString(this._invertNormalName,"float"),e.compilationString+=e._emitCodeFromInclude("pbrBlockNormalFinal",W,{replaceStrings:[{search:/vPositionW/g,replace:X+".xyz"},{search:/vEyePosition.w/g,replace:this._invertNormalName}]}),e.compilationString+=this._getAlbedoOpacityCode(),e.compilationString+=e._emitCodeFromInclude("depthPrePass",W),e.compilationString+=this._getAmbientOcclusionCode(),e.compilationString+=e._emitCodeFromInclude("pbrBlockLightmapInit",W),e.compilationString+=`#ifdef UNLIT + vec3 diffuseBase = vec3(1., 1., 1.); + #else +`,e.compilationString+=this._getReflectivityCode(e),e.compilationString+=e._emitCodeFromInclude("pbrBlockGeometryInfo",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(r=null==z?void 0:z._defineSkyboxName)&&void 0!==r?r:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(s=null==z?void 0:z._define3DName)&&void 0!==s?s:"REFLECTIONMAP_3D"}]});let Y=this.anisotropy.isConnected?null===(n=this.anisotropy.connectedPoint)||void 0===n?void 0:n.ownerBlock:null;Y&&(Y.worldPositionConnectionPoint=this.worldPosition,Y.worldNormalConnectionPoint=this.worldNormal,e.compilationString+=Y.getCode(e,!this.perturbedNormal.isConnected)),z&&z.hasTexture&&(e.compilationString+=z.getCode(e,Y?"anisotropicOut.anisotropicNormal":"normalW")),e._emitFunctionFromInclude("pbrBlockReflection",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(a=null==z?void 0:z._define3DName)&&void 0!==a?a:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(o=null==z?void 0:z._defineOppositeZ)&&void 0!==o?o:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(l=null==z?void 0:z._defineProjectionName)&&void 0!==l?l:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(h=null==z?void 0:z._defineSkyboxName)&&void 0!==h?h:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(u=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==u?u:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(c=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==c?c:"LINEARSPECULARREFLECTION"},{search:/vReflectionFilteringInfo/g,replace:null!==(d=null==z?void 0:z._vReflectionFilteringInfoName)&&void 0!==d?d:"vReflectionFilteringInfo"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance0",W,{replaceStrings:[{search:/metallicReflectanceFactors/g,replace:this._vMetallicReflectanceFactorsName}]});let j=this.sheen.isConnected?null===(p=this.sheen.connectedPoint)||void 0===p?void 0:p.ownerBlock:null;j&&(e.compilationString+=j.getCode(z)),e._emitFunctionFromInclude("pbrBlockSheen",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(_=null==z?void 0:z._define3DName)&&void 0!==_?_:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(f=null==z?void 0:z._defineSkyboxName)&&void 0!==f?f:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(m=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==m?m:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(g=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==g?g:"LINEARSPECULARREFLECTION"}]});let q=this.iridescence.isConnected?null===(v=this.iridescence.connectedPoint)||void 0===v?void 0:v.ownerBlock:null;e.compilationString+=m5.GetCode(q),e._emitFunctionFromInclude("pbrBlockIridescence",W,{replaceStrings:[]});let K=this.clearcoat.isConnected?null===(x=this.clearcoat.connectedPoint)||void 0===x?void 0:x.ownerBlock:null,$=!this.perturbedNormal.isConnected&&!this.anisotropy.isConnected,Q=this.perturbedNormal.isConnected&&(null===(S=(null===(T=this.perturbedNormal.connectedPoint)||void 0===T?void 0:T.ownerBlock).worldTangent)||void 0===S?void 0:S.isConnected),Z=this.anisotropy.isConnected&&(null===(E=this.anisotropy.connectedPoint)||void 0===E?void 0:E.ownerBlock).worldTangent.isConnected,J=Q||!this.perturbedNormal.isConnected&&Z;e.compilationString+=m4.GetCode(e,K,z,X,$,J,this.worldNormal.associatedVariableName),$&&(J=null!==(C=null==K?void 0:K.worldTangent.isConnected)&&void 0!==C&&C),e._emitFunctionFromInclude("pbrBlockClearcoat",W,{replaceStrings:[{search:/computeReflectionCoords/g,replace:"computeReflectionCoordsPBR"},{search:/REFLECTIONMAP_3D/g,replace:null!==(b=null==z?void 0:z._define3DName)&&void 0!==b?b:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(y=null==z?void 0:z._defineOppositeZ)&&void 0!==y?y:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(A=null==z?void 0:z._defineProjectionName)&&void 0!==A?A:"REFLECTIONMAP_PROJECTION"},{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(R=null==z?void 0:z._defineSkyboxName)&&void 0!==R?R:"REFLECTIONMAP_SKYBOX"},{search:/LODINREFLECTIONALPHA/g,replace:null!==(P=null==z?void 0:z._defineLODReflectionAlpha)&&void 0!==P?P:"LODINREFLECTIONALPHA"},{search:/LINEARSPECULARREFLECTION/g,replace:null!==(I=null==z?void 0:z._defineLinearSpecularReflection)&&void 0!==I?I:"LINEARSPECULARREFLECTION"},{search:/defined\(TANGENT\)/g,replace:J?"defined(TANGENT)":"defined(IGNORE)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockReflectance",W,{replaceStrings:[{search:/REFLECTIONMAP_SKYBOX/g,replace:null!==(M=null==z?void 0:z._defineSkyboxName)&&void 0!==M?M:"REFLECTIONMAP_SKYBOX"},{search:/REFLECTIONMAP_3D/g,replace:null!==(D=null==z?void 0:z._define3DName)&&void 0!==D?D:"REFLECTIONMAP_3D"}]});let ee=this.subsurface.isConnected?null===(O=this.subsurface.connectedPoint)||void 0===O?void 0:O.ownerBlock:null,et=this.subsurface.isConnected?null===(F=(null===(N=this.subsurface.connectedPoint)||void 0===N?void 0:N.ownerBlock).refraction.connectedPoint)||void 0===F?void 0:F.ownerBlock:null;et&&(et.viewConnectionPoint=this.view,et.indexOfRefractionConnectionPoint=this.indexOfRefraction),e.compilationString+=m8.GetCode(e,ee,z,X),e._emitFunctionFromInclude("pbrBlockSubSurface",W,{replaceStrings:[{search:/REFLECTIONMAP_3D/g,replace:null!==(L=null==z?void 0:z._define3DName)&&void 0!==L?L:"REFLECTIONMAP_3D"},{search:/REFLECTIONMAP_OPPOSITEZ/g,replace:null!==(w=null==z?void 0:z._defineOppositeZ)&&void 0!==w?w:"REFLECTIONMAP_OPPOSITEZ"},{search:/REFLECTIONMAP_PROJECTION/g,replace:null!==(B=null==z?void 0:z._defineProjectionName)&&void 0!==B?B:"REFLECTIONMAP_PROJECTION"},{search:/SS_REFRACTIONMAP_3D/g,replace:null!==(U=null==et?void 0:et._define3DName)&&void 0!==U?U:"SS_REFRACTIONMAP_3D"},{search:/SS_LODINREFRACTIONALPHA/g,replace:null!==(V=null==et?void 0:et._defineLODRefractionAlpha)&&void 0!==V?V:"SS_LODINREFRACTIONALPHA"},{search:/SS_LINEARSPECULARREFRACTION/g,replace:null!==(k=null==et?void 0:et._defineLinearSpecularRefraction)&&void 0!==k?k:"SS_LINEARSPECULARREFRACTION"},{search:/SS_REFRACTIONMAP_OPPOSITEZ/g,replace:null!==(G=null==et?void 0:et._defineOppositeZ)&&void 0!==G?G:"SS_REFRACTIONMAP_OPPOSITEZ"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockDirectLighting",W),this.light?e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{replaceStrings:[{search:/{X}/g,replace:this._lightId.toString()},{search:/vPositionW/g,replace:X+".xyz"}]}):e.compilationString+=e._emitCodeFromInclude("lightFragment",W,{repeatKey:"maxSimultaneousLights",substitutionVars:`vPositionW,${X}.xyz`}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalLitComponents",W),e.compilationString+=`#endif +`;let ei=this.ambientColor.isConnected?this.ambientColor.associatedVariableName:"vec3(0., 0., 0.)",er=pN.DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();for(let t of(-1===er.indexOf(".")&&(er+="."),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalUnlitComponents",W,{replaceStrings:[{search:/vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g,replace:""},{search:/vAmbientColor/g,replace:ei+" * ambientFromScene"},{search:/vAmbientInfos\.w/g,replace:er}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockFinalColorComposition",W,{replaceStrings:[{search:/finalEmissive/g,replace:"vec3(0.)"}]}),e.compilationString+=e._emitCodeFromInclude("pbrBlockImageProcessing",W,{replaceStrings:[{search:/visibility/g,replace:"1."}]}),e.compilationString+=e._emitCodeFromInclude("pbrDebug",W,{replaceStrings:[{search:/vNormalW/g,replace:this._vNormalWName},{search:/vPositionW/g,replace:X},{search:/albedoTexture\.rgb;/g,replace:"vec3(1.);\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\n"}]}),this._outputs))if(t.hasEndpoints){let i=m7[t.name];if(i){let[r,s]=i;s&&(e.compilationString+=`#if ${s} +`),e.compilationString+=`${this._declareOutput(t,e)} = ${r}; +`,s&&(e.compilationString+=`#else +`,e.compilationString+=`${this._declareOutput(t,e)} = vec3(0.); +`,e.compilationString+=`#endif +`)}else rb.Y.Error(`There's no remapping for the ${t.name} end point! No code generated`)}return this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lightFalloff = ${this.lightFalloff}; +${this._codeVariableName}.useAlphaTest = ${this.useAlphaTest}; +${this._codeVariableName}.alphaTestCutoff = ${this.alphaTestCutoff}; +${this._codeVariableName}.useAlphaBlending = ${this.useAlphaBlending}; +${this._codeVariableName}.useRadianceOverAlpha = ${this.useRadianceOverAlpha}; +${this._codeVariableName}.useSpecularOverAlpha = ${this.useSpecularOverAlpha}; +${this._codeVariableName}.enableSpecularAntiAliasing = ${this.enableSpecularAntiAliasing}; +${this._codeVariableName}.realTimeFiltering = ${this.realTimeFiltering}; +${this._codeVariableName}.realTimeFilteringQuality = ${this.realTimeFilteringQuality}; +${this._codeVariableName}.useEnergyConservation = ${this.useEnergyConservation}; +${this._codeVariableName}.useRadianceOcclusion = ${this.useRadianceOcclusion}; +${this._codeVariableName}.useHorizonOcclusion = ${this.useHorizonOcclusion}; +${this._codeVariableName}.unlit = ${this.unlit}; +${this._codeVariableName}.forceNormalForward = ${this.forceNormalForward}; +${this._codeVariableName}.debugMode = ${this.debugMode}; +${this._codeVariableName}.debugLimit = ${this.debugLimit}; +${this._codeVariableName}.debugFactor = ${this.debugFactor}; +`}serialize(){let e=super.serialize();return this.light&&(e.lightId=this.light.id),e.lightFalloff=this.lightFalloff,e.useAlphaTest=this.useAlphaTest,e.alphaTestCutoff=this.alphaTestCutoff,e.useAlphaBlending=this.useAlphaBlending,e.useRadianceOverAlpha=this.useRadianceOverAlpha,e.useSpecularOverAlpha=this.useSpecularOverAlpha,e.enableSpecularAntiAliasing=this.enableSpecularAntiAliasing,e.realTimeFiltering=this.realTimeFiltering,e.realTimeFilteringQuality=this.realTimeFilteringQuality,e.useEnergyConservation=this.useEnergyConservation,e.useRadianceOcclusion=this.useRadianceOcclusion,e.useHorizonOcclusion=this.useHorizonOcclusion,e.unlit=this.unlit,e.forceNormalForward=this.forceNormalForward,e.debugMode=this.debugMode,e.debugLimit=this.debugLimit,e.debugFactor=this.debugFactor,e.generateOnlyFragmentCode=this.generateOnlyFragmentCode,e}_deserialize(e,t,i){var r,s;super._deserialize(e,t,i),e.lightId&&(this.light=t.getLightById(e.lightId)),this.lightFalloff=null!==(r=e.lightFalloff)&&void 0!==r?r:0,this.useAlphaTest=e.useAlphaTest,this.alphaTestCutoff=e.alphaTestCutoff,this.useAlphaBlending=e.useAlphaBlending,this.useRadianceOverAlpha=e.useRadianceOverAlpha,this.useSpecularOverAlpha=e.useSpecularOverAlpha,this.enableSpecularAntiAliasing=e.enableSpecularAntiAliasing,this.realTimeFiltering=!!e.realTimeFiltering,this.realTimeFilteringQuality=null!==(s=e.realTimeFilteringQuality)&&void 0!==s?s:8,this.useEnergyConservation=e.useEnergyConservation,this.useRadianceOcclusion=e.useRadianceOcclusion,this.useHorizonOcclusion=e.useHorizonOcclusion,this.unlit=e.unlit,this.forceNormalForward=!!e.forceNormalForward,this.debugMode=e.debugMode,this.debugLimit=e.debugLimit,this.debugFactor=e.debugFactor,this.generateOnlyFragmentCode=!!e.generateOnlyFragmentCode,this._setTarget()}}(0,sx.gn)([nS("Direct lights",tx.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],m9.prototype,"directIntensity",void 0),(0,sx.gn)([nS("Environment lights",tx.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],m9.prototype,"environmentIntensity",void 0),(0,sx.gn)([nS("Specular highlights",tx.Float,"INTENSITY",{min:0,max:1,notifiers:{update:!0}})],m9.prototype,"specularIntensity",void 0),(0,sx.gn)([nS("Light falloff",tx.List,"LIGHTING & COLORS",{notifiers:{update:!0},options:[{label:"Physical",value:pN.LIGHTFALLOFF_PHYSICAL},{label:"GLTF",value:pN.LIGHTFALLOFF_GLTF},{label:"Standard",value:pN.LIGHTFALLOFF_STANDARD}]})],m9.prototype,"lightFalloff",void 0),(0,sx.gn)([nS("Alpha Testing",tx.Boolean,"OPACITY")],m9.prototype,"useAlphaTest",void 0),(0,sx.gn)([nS("Alpha CutOff",tx.Float,"OPACITY",{min:0,max:1,notifiers:{update:!0}})],m9.prototype,"alphaTestCutoff",void 0),(0,sx.gn)([nS("Alpha blending",tx.Boolean,"OPACITY")],m9.prototype,"useAlphaBlending",void 0),(0,sx.gn)([nS("Radiance over alpha",tx.Boolean,"RENDERING",{notifiers:{update:!0}})],m9.prototype,"useRadianceOverAlpha",void 0),(0,sx.gn)([nS("Specular over alpha",tx.Boolean,"RENDERING",{notifiers:{update:!0}})],m9.prototype,"useSpecularOverAlpha",void 0),(0,sx.gn)([nS("Specular anti-aliasing",tx.Boolean,"RENDERING",{notifiers:{update:!0}})],m9.prototype,"enableSpecularAntiAliasing",void 0),(0,sx.gn)([nS("Realtime filtering",tx.Boolean,"RENDERING",{notifiers:{update:!0}})],m9.prototype,"realTimeFiltering",void 0),(0,sx.gn)([nS("Realtime filtering quality",tx.List,"RENDERING",{notifiers:{update:!0},options:[{label:"Low",value:8},{label:"Medium",value:16},{label:"High",value:64}]})],m9.prototype,"realTimeFilteringQuality",void 0),(0,sx.gn)([nS("Energy Conservation",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m9.prototype,"useEnergyConservation",void 0),(0,sx.gn)([nS("Radiance occlusion",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m9.prototype,"useRadianceOcclusion",void 0),(0,sx.gn)([nS("Horizon occlusion",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m9.prototype,"useHorizonOcclusion",void 0),(0,sx.gn)([nS("Unlit",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m9.prototype,"unlit",void 0),(0,sx.gn)([nS("Force normal forward",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],m9.prototype,"forceNormalForward",void 0),(0,sx.gn)([nS("Generate only fragment code",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0,update:!0,onValidation:m9._OnGenerateOnlyFragmentCodeChanged}})],m9.prototype,"generateOnlyFragmentCode",void 0),(0,sx.gn)([nS("Debug mode",tx.List,"DEBUG",{notifiers:{update:!0},options:[{label:"None",value:0},{label:"Normalized position",value:1},{label:"Normals",value:2},{label:"Tangents",value:3},{label:"Bitangents",value:4},{label:"Bump Normals",value:5},{label:"ClearCoat Normals",value:8},{label:"ClearCoat Tangents",value:9},{label:"ClearCoat Bitangents",value:10},{label:"Anisotropic Normals",value:11},{label:"Anisotropic Tangents",value:12},{label:"Anisotropic Bitangents",value:13},{label:"Env Refraction",value:40},{label:"Env Reflection",value:41},{label:"Env Clear Coat",value:42},{label:"Direct Diffuse",value:50},{label:"Direct Specular",value:51},{label:"Direct Clear Coat",value:52},{label:"Direct Sheen",value:53},{label:"Env Irradiance",value:54},{label:"Surface Albedo",value:60},{label:"Reflectance 0",value:61},{label:"Metallic",value:62},{label:"Metallic F0",value:71},{label:"Roughness",value:63},{label:"AlphaG",value:64},{label:"NdotV",value:65},{label:"ClearCoat Color",value:66},{label:"ClearCoat Roughness",value:67},{label:"ClearCoat NdotV",value:68},{label:"Transmittance",value:69},{label:"Refraction Transmittance",value:70},{label:"SEO",value:80},{label:"EHO",value:81},{label:"Energy Factor",value:82},{label:"Specular Reflectance",value:83},{label:"Clear Coat Reflectance",value:84},{label:"Sheen Reflectance",value:85},{label:"Luminance Over Alpha",value:86},{label:"Alpha",value:87}]})],m9.prototype,"debugMode",void 0),(0,sx.gn)([nS("Split position",tx.Float,"DEBUG",{min:-1,max:1,notifiers:{update:!0}})],m9.prototype,"debugLimit",void 0),(0,sx.gn)([nS("Output factor",tx.Float,"DEBUG",{min:0,max:5,notifiers:{update:!0}})],m9.prototype,"debugFactor",void 0),(0,rg.H)("BABYLON.PBRMetallicRoughnessBlock",m9);class ge extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("left",tf.AutoDetect),this.registerInput("right",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[1].acceptedConnectionPointTypes.push(tf.Float)}getClassName(){return"ModBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0];return e.compilationString+=this._declareOutput(t,e)+` = mod(${this.left.associatedVariableName}, ${this.right.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.ModBlock",ge);class gt extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("row0",tf.Vector4),this.registerInput("row1",tf.Vector4),this.registerInput("row2",tf.Vector4),this.registerInput("row3",tf.Vector4),this.registerOutput("output",tf.Matrix)}getClassName(){return"MatrixBuilder"}get row0(){return this._inputs[0]}get row1(){return this._inputs[1]}get row2(){return this._inputs[2]}get row3(){return this._inputs[3]}get output(){return this._outputs[0]}autoConfigure(){if(!this.row0.isConnected){let e=new nI("row0");e.value=new rf.Lt(1,0,0,0),e.output.connectTo(this.row0)}if(!this.row1.isConnected){let e=new nI("row1");e.value=new rf.Lt(0,1,0,0),e.output.connectTo(this.row1)}if(!this.row2.isConnected){let e=new nI("row2");e.value=new rf.Lt(0,0,1,0),e.output.connectTo(this.row2)}if(!this.row3.isConnected){let e=new nI("row3");e.value=new rf.Lt(0,0,0,1),e.output.connectTo(this.row3)}}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.row0,r=this.row1,s=this.row2,n=this.row3;return e.compilationString+=this._declareOutput(t,e)+` = mat4(${i.associatedVariableName}, ${r.associatedVariableName}, ${s.associatedVariableName}, ${n.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.MatrixBuilder",gt),(eD=iD||(iD={}))[eD.Equal=0]="Equal",eD[eD.NotEqual=1]="NotEqual",eD[eD.LessThan=2]="LessThan",eD[eD.GreaterThan=3]="GreaterThan",eD[eD.LessOrEqual=4]="LessOrEqual",eD[eD.GreaterOrEqual=5]="GreaterOrEqual",eD[eD.Xor=6]="Xor",eD[eD.Or=7]="Or",eD[eD.And=8]="And";class gi extends nv{constructor(e){super(e,tm.Neutral),this.condition=iD.LessThan,this.registerInput("a",tf.Float),this.registerInput("b",tf.Float),this.registerInput("true",tf.AutoDetect,!0),this.registerInput("false",tf.AutoDetect,!0),this.registerOutput("output",tf.BasedOnInput),this._linkConnectionTypes(2,3),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=tf.Float}getClassName(){return"ConditionalBlock"}get a(){return this._inputs[0]}get b(){return this._inputs[1]}get true(){return this._inputs[2]}get false(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this.true.isConnected?this.true.associatedVariableName:"1.0",r=this.false.isConnected?this.false.associatedVariableName:"0.0";switch(this.condition){case iD.Equal:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} == ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iD.NotEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} != ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iD.LessThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} < ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iD.LessOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} <= ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iD.GreaterThan:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} > ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iD.GreaterOrEqual:e.compilationString+=this._declareOutput(t,e)+` = ${this.a.associatedVariableName} >= ${this.b.associatedVariableName} ? ${i} : ${r}; +`;break;case iD.Xor:e.compilationString+=this._declareOutput(t,e)+` = (mod(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 2.0) > 0.0) ? ${i} : ${r}; +`;break;case iD.Or:e.compilationString+=this._declareOutput(t,e)+` = (min(${this.a.associatedVariableName} + ${this.b.associatedVariableName}, 1.0) > 0.0) ? ${i} : ${r}; +`;break;case iD.And:e.compilationString+=this._declareOutput(t,e)+` = (${this.a.associatedVariableName} * ${this.b.associatedVariableName} > 0.0) ? ${i} : ${r}; +`}return this}serialize(){let e=super.serialize();return e.condition=this.condition,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.condition=e.condition}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.condition = BABYLON.ConditionalBlockConditions.${iD[this.condition]}; +`}}(0,rg.H)("BABYLON.ConditionalBlock",gi);class gr extends nv{constructor(e){super(e,tm.Neutral),this.octaves=6,this.registerInput("seed",tf.AutoDetect),this.registerInput("chaos",tf.AutoDetect,!0),this.registerInput("offsetX",tf.Float,!0),this.registerInput("offsetY",tf.Float,!0),this.registerInput("offsetZ",tf.Float,!0),this.registerOutput("output",tf.Float),this._inputs[0].acceptedConnectionPointTypes.push(tf.Vector2),this._inputs[0].acceptedConnectionPointTypes.push(tf.Vector3),this._linkConnectionTypes(0,1)}getClassName(){return"CloudBlock"}get seed(){return this._inputs[0]}get chaos(){return this._inputs[1]}get offsetX(){return this._inputs[2]}get offsetY(){return this._inputs[3]}get offsetZ(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){var t,i;if(super._buildBlock(e),!this.seed.isConnected||!this._outputs[0].hasEndpoints)return;let r=` + + float cloudRandom(in float p) { p = fract(p * 0.011); p *= p + 7.5; p *= p + p; return fract(p); } + + // Based on Morgan McGuire @morgan3d + // https://www.shadertoy.com/view/4dS3Wd + float cloudNoise(in vec2 x, in vec2 chaos) { + vec2 step = chaos * vec2(75., 120.) + vec2(75., 120.); + + vec2 i = floor(x); + vec2 f = fract(x); + + float n = dot(i, step); + + vec2 u = f * f * (3.0 - 2.0 * f); + return mix( + mix(cloudRandom(n + dot(step, vec2(0, 0))), cloudRandom(n + dot(step, vec2(1, 0))), u.x), + mix(cloudRandom(n + dot(step, vec2(0, 1))), cloudRandom(n + dot(step, vec2(1, 1))), u.x), + u.y + ); + } + + float cloudNoise(in vec3 x, in vec3 chaos) { + vec3 step = chaos * vec3(60., 120., 75.) + vec3(60., 120., 75.); + + vec3 i = floor(x); + vec3 f = fract(x); + + float n = dot(i, step); + + vec3 u = f * f * (3.0 - 2.0 * f); + return mix(mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 0))), cloudRandom(n + dot(step, vec3(1, 0, 0))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 0))), cloudRandom(n + dot(step, vec3(1, 1, 0))), u.x), u.y), + mix(mix( cloudRandom(n + dot(step, vec3(0, 0, 1))), cloudRandom(n + dot(step, vec3(1, 0, 1))), u.x), + mix( cloudRandom(n + dot(step, vec3(0, 1, 1))), cloudRandom(n + dot(step, vec3(1, 1, 1))), u.x), u.y), u.z); + }`,s=` + float fbm(in vec2 st, in vec2 chaos) { + // Initial values + float value = 0.0; + float amplitude = .5; + float frequency = 0.; + + // Loop of octaves + for (int i = 0; i < OCTAVES; i++) { + value += amplitude * cloudNoise(st, chaos); + st *= 2.0; + amplitude *= 0.5; + } + return value; + } + + float fbm(in vec3 x, in vec3 chaos) { + // Initial values + float value = 0.0; + float amplitude = 0.5; + for (int i = 0; i < OCTAVES; ++i) { + value += amplitude * cloudNoise(x, chaos); + x = x * 2.0; + amplitude *= 0.5; + } + return value; + }`,n=`fbm${this.octaves}`;e._emitFunction("CloudBlockCode",r,"// CloudBlockCode"),e._emitFunction("CloudBlockCodeFBM"+this.octaves,s.replace(/fbm/gi,n).replace(/OCTAVES/gi,(0|this.octaves).toString()),"// CloudBlockCode FBM");let a=e._getFreeVariableName("st"),o=(null===(t=this.seed.connectedPoint)||void 0===t?void 0:t.type)===tf.Vector2?"vec2":"vec3";e.compilationString+=`${o} ${a} = ${this.seed.associatedVariableName}; +`,this.offsetX.isConnected&&(e.compilationString+=`${a}.x += 0.1 * ${this.offsetX.associatedVariableName}; +`),this.offsetY.isConnected&&(e.compilationString+=`${a}.y += 0.1 * ${this.offsetY.associatedVariableName}; +`),this.offsetZ.isConnected&&"vec3"===o&&(e.compilationString+=`${a}.z += 0.1 * ${this.offsetZ.associatedVariableName}; +`);let l="";return l=this.chaos.isConnected?this.chaos.associatedVariableName:(null===(i=this.seed.connectedPoint)||void 0===i?void 0:i.type)===tf.Vector2?"vec2(0., 0.)":"vec3(0., 0., 0.)",e.compilationString+=this._declareOutput(this._outputs[0],e)+` = ${n}(${a}, ${l}); +`,this}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.octaves = ${this.octaves}; +`}serialize(){let e=super.serialize();return e.octaves=this.octaves,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.octaves=e.octaves}}(0,sx.gn)([nS("Octaves",tx.Int)],gr.prototype,"octaves",void 0),(0,rg.H)("BABYLON.CloudBlock",gr);class gs extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("seed",tf.Vector2),this.registerInput("offset",tf.Float),this.registerInput("density",tf.Float),this.registerOutput("output",tf.Float),this.registerOutput("cells",tf.Float)}getClassName(){return"VoronoiNoiseBlock"}get seed(){return this._inputs[0]}get offset(){return this._inputs[1]}get density(){return this._inputs[2]}get output(){return this._outputs[0]}get cells(){return this._outputs[1]}_buildBlock(e){if(super._buildBlock(e),!this.seed.isConnected)return;let t=`vec2 voronoiRandom(vec2 seed, float offset){ + mat2 m = mat2(15.27, 47.63, 99.41, 89.98); + vec2 uv = fract(sin(m * seed) * 46839.32); + return vec2(sin(uv.y * offset) * 0.5 + 0.5, cos(uv.x * offset) * 0.5 + 0.5); + } + `;e._emitFunction("voronoiRandom",t,"// Voronoi random generator"),t=`void voronoi(vec2 seed, float offset, float density, out float outValue, out float cells){ + vec2 g = floor(seed * density); + vec2 f = fract(seed * density); + float t = 8.0; + vec3 res = vec3(8.0, 0.0, 0.0); + + for(int y=-1; y<=1; y++) + { + for(int x=-1; x<=1; x++) + { + vec2 lattice = vec2(x,y); + vec2 randomOffset = voronoiRandom(lattice + g, offset); + float d = distance(lattice + randomOffset, f); + if(d < res.x) + { + res = vec3(d, randomOffset.x, randomOffset.y); + outValue = res.x; + cells = res.y; + } + } + } + } + `,e._emitFunction("voronoi",t,"// Voronoi");let i=e._getFreeVariableName("tempOutput"),r=e._getFreeVariableName("tempCells");return e.compilationString+=`float ${i} = 0.0; +`,e.compilationString+=`float ${r} = 0.0; +`,e.compilationString+=`voronoi(${this.seed.associatedVariableName}, ${this.offset.associatedVariableName}, ${this.density.associatedVariableName}, ${i}, ${r}); +`,this.output.hasEndpoints&&(e.compilationString+=this._declareOutput(this.output,e)+` = ${i}; +`),this.cells.hasEndpoints&&(e.compilationString+=this._declareOutput(this.cells,e)+` = ${r}; +`),this}}(0,rg.H)("BABYLON.VoronoiNoiseBlock",gs);class gn extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("input",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"ElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}get target(){let e=this._inputs[0];if(e.isConnected){let t=e.connectedPoint.ownerBlock;if(t.target!==tm.VertexAndFragment)return t.target;if(e.connectedPoint.target!==tm.VertexAndFragment)return e.connectedPoint.target}return this._target}set target(e){(this._target&e)==0&&(this._target=e)}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];return e.compilationString+=this._declareOutput(t,e)+` = ${i.associatedVariableName}; +`,this}}(0,rg.H)("BABYLON.ElbowBlock",gn);class ga extends nv{get texture(){var e;return this.source.isConnected?(null===(e=this.source.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:this._texture}set texture(e){var t;if(this._texture===e)return;let i=null!==(t=null==e?void 0:e.getScene())&&void 0!==t?t:rL.l.LastCreatedScene;!e&&i&&i.markAllMaterialsAsDirty(1,e=>e.hasTexture(this._texture)),this._texture=e,e&&i&&i.markAllMaterialsAsDirty(1,t=>t.hasTexture(e))}get textureY(){var e;return this.sourceY.isConnected?(null===(e=this.sourceY.connectedPoint)||void 0===e?void 0:e.ownerBlock).texture:null}get textureZ(){var e,t;return(null===(e=this.sourceZ)||void 0===e?void 0:e.isConnected)?(null===(t=this.sourceY.connectedPoint)||void 0===t?void 0:t.ownerBlock).texture:null}_getImageSourceBlock(e){return(null==e?void 0:e.isConnected)?e.connectedPoint.ownerBlock:null}get samplerName(){let e=this._getImageSourceBlock(this.source);return e?e.samplerName:this._samplerName}get samplerYName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceY))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get samplerZName(){var e,t;return null!==(t=null===(e=this._getImageSourceBlock(this.sourceZ))||void 0===e?void 0:e.samplerName)&&void 0!==t?t:null}get hasImageSource(){return this.source.isConnected}set convertToGammaSpace(e){var t;if(e!==this._convertToGammaSpace&&(this._convertToGammaSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rL.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToGammaSpace(){return this._convertToGammaSpace}set convertToLinearSpace(e){var t;if(e!==this._convertToLinearSpace&&(this._convertToLinearSpace=e,this.texture)){let e=null!==(t=this.texture.getScene())&&void 0!==t?t:rL.l.LastCreatedScene;null==e||e.markAllMaterialsAsDirty(1,e=>e.hasTexture(this.texture))}}get convertToLinearSpace(){return this._convertToLinearSpace}constructor(e,t=!1){super(e,tm.Neutral),this.projectAsCube=!1,this._convertToGammaSpace=!1,this._convertToLinearSpace=!1,this.disableLevelMultiplication=!1,this.registerInput("position",tf.AutoDetect,!1),this.registerInput("normal",tf.AutoDetect,!1),this.registerInput("sharpness",tf.Float,!0),this.registerInput("source",tf.Object,!0,tm.VertexAndFragment,new f$("source",this,tv.Input,mo,"ImageSourceBlock")),this.registerInput("sourceY",tf.Object,!0,tm.VertexAndFragment,new f$("sourceY",this,tv.Input,mo,"ImageSourceBlock")),t||this.registerInput("sourceZ",tf.Object,!0,tm.VertexAndFragment,new f$("sourceZ",this,tv.Input,mo,"ImageSourceBlock")),this.registerOutput("rgba",tf.Color4,tm.Neutral),this.registerOutput("rgb",tf.Color3,tm.Neutral),this.registerOutput("r",tf.Float,tm.Neutral),this.registerOutput("g",tf.Float,tm.Neutral),this.registerOutput("b",tf.Float,tm.Neutral),this.registerOutput("a",tf.Float,tm.Neutral),this.registerOutput("level",tf.Float,tm.Neutral),this._inputs[0].addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Vector4),this._inputs[1].addExcludedConnectionPointFromAllowedTypes(tf.Color3|tf.Vector3|tf.Vector4)}getClassName(){return"TriPlanarBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get sharpness(){return this._inputs[2]}get source(){return this._inputs[3]}get sourceY(){return this._inputs[4]}get sourceZ(){return this._inputs[5]}get rgba(){return this._outputs[0]}get rgb(){return this._outputs[1]}get r(){return this._outputs[2]}get g(){return this._outputs[3]}get b(){return this._outputs[4]}get a(){return this._outputs[5]}get level(){return this._outputs[6]}prepareDefines(e,t,i){if(!i._areTexturesDirty)return;let r=this.convertToGammaSpace&&this.texture&&!this.texture.gammaSpace,s=this.convertToLinearSpace&&this.texture&&this.texture.gammaSpace;i.setValue(this._linearDefineName,r,!0),i.setValue(this._gammaDefineName,s,!0)}isReady(){return!this.texture||!!this.texture.isReadyOrNotBlocking()}bind(e){this.texture&&(e.setFloat(this._textureInfoName,this.texture.level),this._imageSource||e.setTexture(this._samplerName,this.texture))}_generateTextureLookup(e){var t,i;let r=this.samplerName,s=null!==(t=this.samplerYName)&&void 0!==t?t:r,n=null!==(i=this.samplerZName)&&void 0!==i?i:r,a=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",o=e._getFreeVariableName("x"),l=e._getFreeVariableName("y"),h=e._getFreeVariableName("z"),u=e._getFreeVariableName("w"),c=e._getFreeVariableName("n"),d=e._getFreeVariableName("uvx"),p=e._getFreeVariableName("uvy"),_=e._getFreeVariableName("uvz");e.compilationString+=` + vec3 ${c} = ${this.normal.associatedVariableName}.xyz; + + vec2 ${d} = ${this.position.associatedVariableName}.yz; + vec2 ${p} = ${this.position.associatedVariableName}.zx; + vec2 ${_} = ${this.position.associatedVariableName}.xy; + `,this.projectAsCube&&(e.compilationString+=` + ${d}.xy = ${d}.yx; + + if (${c}.x >= 0.0) { + ${d}.x = -${d}.x; + } + if (${c}.y < 0.0) { + ${p}.y = -${p}.y; + } + if (${c}.z < 0.0) { + ${_}.x = -${_}.x; + } + `),e.compilationString+=` + vec4 ${o} = texture2D(${r}, ${d}); + vec4 ${l} = texture2D(${s}, ${p}); + vec4 ${h} = texture2D(${n}, ${_}); + + // blend weights + vec3 ${u} = pow(abs(${c}), vec3(${a})); + + // blend and return + vec4 ${this._tempTextureRead} = (${o}*${u}.x + ${l}*${u}.y + ${h}*${u}.z) / (${u}.x + ${u}.y + ${u}.z); + `}_generateConversionCode(e,t,i){"a"!==i&&(this.texture&&this.texture.gammaSpace||(e.compilationString+=`#ifdef ${this._linearDefineName} + ${t.associatedVariableName} = toGammaSpace(${t.associatedVariableName}); + #endif + `),e.compilationString+=`#ifdef ${this._gammaDefineName} + ${t.associatedVariableName} = toLinearSpace(${t.associatedVariableName}); + #endif + `)}_writeOutput(e,t,i){let r="";this.disableLevelMultiplication||(r=` * ${this._textureInfoName}`),e.compilationString+=`${this._declareOutput(t,e)} = ${this._tempTextureRead}.${i}${r}; +`,this._generateConversionCode(e,t,i)}_buildBlock(e){super._buildBlock(e),this.source.isConnected?this._imageSource=this.source.connectedPoint.ownerBlock:this._imageSource=null,this._textureInfoName=e._getFreeVariableName("textureInfoName"),this.level.associatedVariableName=this._textureInfoName,this._tempTextureRead=e._getFreeVariableName("tempTextureRead"),this._linearDefineName=e._getFreeDefineName("ISLINEAR"),this._gammaDefineName=e._getFreeDefineName("ISGAMMA"),this._imageSource||(this._samplerName=e._getFreeVariableName(this.name+"Sampler"),e._emit2DSampler(this._samplerName)),e.sharedData.blockingBlocks.push(this),e.sharedData.textureBlocks.push(this),e.sharedData.blocksWithDefines.push(this),e.sharedData.bindableBlocks.push(this);let t=`//${this.name}`;for(let i of(e._emitFunctionFromInclude("helperFunctions",t),e._emitUniformFromString(this._textureInfoName,"float"),this._generateTextureLookup(e),this._outputs))i.hasEndpoints&&"level"!==i.name&&this._writeOutput(e,i,i.name);return this}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return(e+=`${this._codeVariableName}.convertToGammaSpace = ${this.convertToGammaSpace}; +${this._codeVariableName}.convertToLinearSpace = ${this.convertToLinearSpace}; +${this._codeVariableName}.disableLevelMultiplication = ${this.disableLevelMultiplication}; +${this._codeVariableName}.projectAsCube = ${this.projectAsCube}; +`,this.texture)?e+=`${this._codeVariableName}.texture = new BABYLON.Texture("${this.texture.name}", null, ${this.texture.noMipmap}, ${this.texture.invertY}, ${this.texture.samplingMode}); +${this._codeVariableName}.texture.wrapU = ${this.texture.wrapU}; +${this._codeVariableName}.texture.wrapV = ${this.texture.wrapV}; +${this._codeVariableName}.texture.uAng = ${this.texture.uAng}; +${this._codeVariableName}.texture.vAng = ${this.texture.vAng}; +${this._codeVariableName}.texture.wAng = ${this.texture.wAng}; +${this._codeVariableName}.texture.uOffset = ${this.texture.uOffset}; +${this._codeVariableName}.texture.vOffset = ${this.texture.vOffset}; +${this._codeVariableName}.texture.uScale = ${this.texture.uScale}; +${this._codeVariableName}.texture.vScale = ${this.texture.vScale}; +${this._codeVariableName}.texture.coordinatesMode = ${this.texture.coordinatesMode}; +`:e}serialize(){let e=super.serialize();return e.convertToGammaSpace=this.convertToGammaSpace,e.convertToLinearSpace=this.convertToLinearSpace,e.disableLevelMultiplication=this.disableLevelMultiplication,e.projectAsCube=this.projectAsCube,this.hasImageSource||!this.texture||this.texture.isRenderTarget||"VideoTexture"===this.texture.getClassName()||(e.texture=this.texture.serialize()),e}_deserialize(e,t,i){super._deserialize(e,t,i),this.convertToGammaSpace=e.convertToGammaSpace,this.convertToLinearSpace=!!e.convertToLinearSpace,this.disableLevelMultiplication=!!e.disableLevelMultiplication,this.projectAsCube=!!e.projectAsCube,e.texture&&!ac.IgnoreTexturesAtLoadTime&&void 0!==e.texture.url&&(i=0===e.texture.url.indexOf("data:")?"":i,this.texture=sj.Parse(e.texture,t,i))}}(0,sx.gn)([nS("Project as cube",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],ga.prototype,"projectAsCube",void 0),(0,rg.H)("BABYLON.TriPlanarBlock",ga);class go extends ga{constructor(e){super(e,!0)}getClassName(){return"BiPlanarBlock"}_generateTextureLookup(e){var t;let i=this.samplerName,r=null!==(t=this.samplerYName)&&void 0!==t?t:this.samplerName,s=this.sharpness.isConnected?this.sharpness.associatedVariableName:"1.0",n=e._getFreeVariableName("dpdx"),a=e._getFreeVariableName("dpdy"),o=e._getFreeVariableName("n"),l=e._getFreeVariableName("ma"),h=e._getFreeVariableName("mi"),u=e._getFreeVariableName("me"),c=e._getFreeVariableName("x"),d=e._getFreeVariableName("y"),p=e._getFreeVariableName("y");e.compilationString+=` + // grab coord derivatives for texturing + vec3 ${n} = dFdx(${this.position.associatedVariableName}.xyz); + vec3 ${a} = dFdy(${this.position.associatedVariableName}.xyz); + vec3 ${o} = abs(${this.normal.associatedVariableName}.xyz); + + // determine major axis (in x; yz are following axis) + ivec3 ${l} = (${o}.x>${o}.y && ${o}.x>${o}.z) ? ivec3(0,1,2) : + (${o}.y>${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine minor axis (in x; yz are following axis) + ivec3 ${h} = (${o}.x<${o}.y && ${o}.x<${o}.z) ? ivec3(0,1,2) : + (${o}.y<${o}.z) ? ivec3(1,2,0) : + ivec3(2,0,1) ; + // determine median axis (in x; yz are following axis) + ivec3 ${u} = ivec3(3) - ${h} - ${l}; + + // project+fetch + vec4 ${c} = textureGrad( ${i}, vec2( ${this.position.associatedVariableName}[${l}.y], ${this.position.associatedVariableName}[${l}.z]), + vec2(${n}[${l}.y],${n}[${l}.z]), + vec2(${a}[${l}.y],${a}[${l}.z]) ); + vec4 ${d} = textureGrad( ${r}, vec2( ${this.position.associatedVariableName}[${u}.y], ${this.position.associatedVariableName}[${u}.z]), + vec2(${n}[${u}.y],${n}[${u}.z]), + vec2(${a}[${u}.y],${a}[${u}.z]) ); + + // blend factors + vec2 ${p} = vec2(${o}[${l}.x],${o}[${u}.x]); + // make local support + ${p} = clamp( (${p}-0.5773)/(1.0-0.5773), 0.0, 1.0 ); + // shape transition + ${p} = pow( ${p}, vec2(${s}/8.0) ); + // blend and return + vec4 ${this._tempTextureRead} = (${c}*${p}.x + ${d}*${p}.y) / (${p}.x + ${p}.y); + `}}(0,rg.H)("BABYLON.BiPlanarBlock",go);class gl extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("input",tf.Matrix),this.registerOutput("output",tf.Float)}getClassName(){return"MatrixDeterminantBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = determinant(${i.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.MatrixDeterminantBlock",gl);class gh extends nv{constructor(e){super(e,tm.Neutral),this.registerInput("input",tf.Matrix),this.registerOutput("output",tf.Matrix)}getClassName(){return"MatrixTransposeBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this.output,i=this.input;return e.compilationString+=this._declareOutput(t,e)+`${t.associatedVariableName} = transpose(${i.associatedVariableName}); +`,this}}(0,rg.H)("BABYLON.MatrixTransposeBlock",gh),(eO=iO||(iO={}))[eO.None=0]="None",eO[eO.Normal=1]="Normal",eO[eO.Tangent=2]="Tangent",eO[eO.VertexColor=3]="VertexColor",eO[eO.UV1=4]="UV1",eO[eO.UV2=5]="UV2",eO[eO.UV3=6]="UV3",eO[eO.UV4=7]="UV4",eO[eO.UV5=8]="UV5",eO[eO.UV6=9]="UV6";class gu extends nv{constructor(e){super(e,tm.Neutral),this.attributeType=iO.None,this.registerInput("input",tf.AutoDetect),this.registerInput("fallback",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1),this._inputs[0].onConnectionObservable.add(e=>{var t;if(this.attributeType)return;let i=e.ownerBlock;if(i instanceof nI&&i.isAttribute)switch(i.name){case"color":this.attributeType=iO.VertexColor;break;case"normal":this.attributeType=iO.Normal;break;case"tangent":this.attributeType=iO.Tangent;break;case"uv":this.attributeType=iO.UV1;break;case"uv2":this.attributeType=iO.UV2;break;case"uv3":this.attributeType=iO.UV3;break;case"uv4":this.attributeType=iO.UV4;break;case"uv5":this.attributeType=iO.UV5;break;case"uv6":this.attributeType=iO.UV6}else if(i instanceof fJ)switch(null===(t=this.input.connectedPoint)||void 0===t?void 0:t.name){case"normalOutput":this.attributeType=iO.Normal;break;case"tangentOutput":this.attributeType=iO.Tangent;break;case"uvOutput":this.attributeType=iO.UV1}})}getClassName(){return"MeshAttributeExistsBlock"}get input(){return this._inputs[0]}get fallback(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.attributeType){case iO.VertexColor:t="VERTEXCOLOR_NME";break;case iO.Normal:t="NORMAL";break;case iO.Tangent:t="TANGENT";break;case iO.UV1:t="UV1";break;case iO.UV2:t="UV2";break;case iO.UV3:t="UV3";break;case iO.UV4:t="UV4";break;case iO.UV5:t="UV5";break;case iO.UV6:t="UV6"}let i=this._declareOutput(this.output,e);return t&&(e.compilationString+=`#ifdef ${t} +`),e.compilationString+=`${i} = ${this.input.associatedVariableName}; +`,t&&(e.compilationString+=`#else +`,e.compilationString+=`${i} = ${this.fallback.associatedVariableName}; +`,e.compilationString+=`#endif +`),this}serialize(){let e=super.serialize();return e.attributeType=this.attributeType,e}_deserialize(e,t,i){var r;super._deserialize(e,t,i),this.attributeType=null!==(r=e.attributeType)&&void 0!==r?r:iO.None}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.attributeType = ${this.attributeType}; +`}}(0,sx.gn)([nS("Attribute lookup",tx.List,void 0,{notifiers:{update:!0},options:[{label:"(None)",value:iO.None},{label:"Normal",value:iO.Normal},{label:"Tangent",value:iO.Tangent},{label:"Vertex Color",value:iO.VertexColor},{label:"UV1",value:iO.UV1},{label:"UV2",value:iO.UV2},{label:"UV3",value:iO.UV3},{label:"UV4",value:iO.UV4},{label:"UV5",value:iO.UV5},{label:"UV6",value:iO.UV6}]})],gu.prototype,"attributeType",void 0),(0,rg.H)("BABYLON.MeshAttributeExistsBlock",gu),(eN=iN||(iN={}))[eN.EaseInSine=0]="EaseInSine",eN[eN.EaseOutSine=1]="EaseOutSine",eN[eN.EaseInOutSine=2]="EaseInOutSine",eN[eN.EaseInQuad=3]="EaseInQuad",eN[eN.EaseOutQuad=4]="EaseOutQuad",eN[eN.EaseInOutQuad=5]="EaseInOutQuad",eN[eN.EaseInCubic=6]="EaseInCubic",eN[eN.EaseOutCubic=7]="EaseOutCubic",eN[eN.EaseInOutCubic=8]="EaseInOutCubic",eN[eN.EaseInQuart=9]="EaseInQuart",eN[eN.EaseOutQuart=10]="EaseOutQuart",eN[eN.EaseInOutQuart=11]="EaseInOutQuart",eN[eN.EaseInQuint=12]="EaseInQuint",eN[eN.EaseOutQuint=13]="EaseOutQuint",eN[eN.EaseInOutQuint=14]="EaseInOutQuint",eN[eN.EaseInExpo=15]="EaseInExpo",eN[eN.EaseOutExpo=16]="EaseOutExpo",eN[eN.EaseInOutExpo=17]="EaseInOutExpo",eN[eN.EaseInCirc=18]="EaseInCirc",eN[eN.EaseOutCirc=19]="EaseOutCirc",eN[eN.EaseInOutCirc=20]="EaseInOutCirc",eN[eN.EaseInBack=21]="EaseInBack",eN[eN.EaseOutBack=22]="EaseOutBack",eN[eN.EaseInOutBack=23]="EaseInOutBack",eN[eN.EaseInElastic=24]="EaseInElastic",eN[eN.EaseOutElastic=25]="EaseOutElastic",eN[eN.EaseInOutElastic=26]="EaseInOutElastic";class gc extends nv{constructor(e){super(e,tm.Neutral),this.type=iN.EaseInOutSine,this.registerInput("input",tf.AutoDetect),this.registerOutput("output",tf.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(tf.Matrix),this._inputs[0].excludedConnectionPointTypes.push(tf.Object),this._inputs[0].excludedConnectionPointTypes.push(tf.Int)}getClassName(){return"CurveBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_duplicateEntry(e,t){return`ret.${t} = ${e.replace(/VAL/g,"v."+t)}`}_duplicateEntryDirect(e){return`return ${e.replace(/VAL/g,"v")}`}_duplicateVector(e,t){if("float"===t)return this._duplicateEntryDirect(e);let i=parseInt(t.replace("vec","")),r=` + vec${i} ret = vec${i}(0.0); + `;for(let t=1;t<=i;t++)r+=this._duplicateEntry(e,1===t?"x":2===t?"y":3===t?"z":"w")+";\n";return r+"return ret;\n"}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i="",r="",s="";switch(this.input.type){case tf.Float:s="float";break;case tf.Vector2:s="vec2";break;case tf.Vector3:case tf.Color3:s="vec3";break;case tf.Vector4:case tf.Color4:s="vec4"}switch(r=iN[this.type]+"_"+s,this.type){case iN.EaseInSine:i="return 1.0 - cos((v * 3.1415) / 2.0)";break;case iN.EaseOutSine:i="return sin((v * 3.1415) / 2.0)";break;case iN.EaseInOutSine:i="return -(cos(v * 3.1415) - 1.0) / 2.0";break;case iN.EaseInQuad:i="return v * v";break;case iN.EaseOutQuad:i="return (1.0 - v) * (1.0 - v)";break;case iN.EaseInOutQuad:i=this._duplicateVector("VAL < 0.5 ? 2.0 * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 2.0) / 2.0",s);break;case iN.EaseInCubic:i="return v * v * v";break;case iN.EaseOutCubic:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 3.0)",s);break;case iN.EaseInOutCubic:i=this._duplicateVector("VAL < 0.5 ? 4.0 * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 3.0) / 2.0",s);break;case iN.EaseInQuart:i="return v * v * v * v";break;case iN.EaseOutQuart:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 4.0)",s);break;case iN.EaseInOutQuart:i=this._duplicateVector("VAL < 0.5 ? 8.0 * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 4.0) / 2.0",s);break;case iN.EaseInQuint:i="return v * v * v * v * v";break;case iN.EaseOutQuint:i=this._duplicateVector("1.0 - pow(1.0 - VAL, 5.0)",s);break;case iN.EaseInOutQuint:i=this._duplicateVector("VAL < 0.5 ? 16.0 * VAL * VAL * VAL * VAL * VAL : 1.0 - pow(-2.0 * VAL + 2.0, 5.0) / 2.0",s);break;case iN.EaseInExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : pow(2.0, 10.0 * VAL - 10.0)",s);break;case iN.EaseOutExpo:i=this._duplicateVector("VAL == 1.0 ? 1.0 : 1.0 - pow(2.0, -10.0 * VAL)",s);break;case iN.EaseInOutExpo:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? pow(2.0, 20.0 * VAL - 10.0) / 2.0 : (2.0 - pow(2.0, -20.0 * VAL + 10.0)) / 2.0",s);break;case iN.EaseInCirc:i=this._duplicateVector("1.0 - sqrt(1.0 - pow(VAL, 2.0))",s);break;case iN.EaseOutCirc:i=this._duplicateVector("sqrt(1.0 - pow(VAL - 1.0, 2.0))",s);break;case iN.EaseInOutCirc:i=this._duplicateVector("VAL < 0.5 ? (1.0 - sqrt(1.0 - pow(2.0 * VAL, 2.0))) / 2.0 : (sqrt(1.0 - pow(-2.0 * VAL + 2.0, 2.0)) + 1.0) / 2.0",s);break;case iN.EaseInBack:i="return 2.70158 * v * v * v - 1.70158 * v * v";break;case iN.EaseOutBack:i=this._duplicateVector("2.70158 * pow(VAL - 1.0, 3.0) + 1.70158 * pow(VAL - 1.0, 2.0)",s);break;case iN.EaseInOutBack:i=this._duplicateVector("VAL < 0.5 ? (pow(2.0 * VAL, 2.0) * ((3.5949095) * 2.0 * VAL - 2.5949095)) / 2.0 : (pow(2.0 * VAL - 2.0, 2.0) * (3.5949095 * (VAL * 2.0 - 2.0) + 3.5949095) + 2.0) / 2.0",s);break;case iN.EaseInElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : -pow(2.0, 10.0 * VAL - 10.0) * sin((VAL * 10.0 - 10.75) * ((2.0 * 3.1415) / 3.0))",s);break;case iN.EaseOutElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : pow(2.0, -10.0 * VAL) * sin((VAL * 10.0 - 0.75) * ((2.0 * 3.1415) / 3.0)) + 1.0",s);break;case iN.EaseInOutElastic:i=this._duplicateVector("VAL == 0.0 ? 0.0 : VAL == 1.0 ? 1.0 : VAL < 0.5 ? -(pow(2.0, 20.0 * VAL - 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 : (pow(2.0, -20.0 * VAL + 10.0) * sin((20.0 * VAL - 11.125) * ((2.0 * 3.1415) / 4.5))) / 2.0 + 1.0",s)}return e._emitFunction(r,`${s} ${r}(${s} v) {${i};} +`,""),e.compilationString+=this._declareOutput(t,e)+` = ${r}(${this.input.associatedVariableName}); +`,this}serialize(){let e=super.serialize();return e.curveType=this.type,e}_deserialize(e,t,i){super._deserialize(e,t,i),this.type=e.curveType}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.type = BABYLON.CurveBlockTypes.${iN[this.type]}; +`}}(0,rg.H)("BABYLON.CurveBlock",gc);class gd extends nf.H{constructor(){super(...arguments),this.DECAL=!1,this.DECALDIRECTUV=0,this.DECAL_SMOOTHALPHA=!1,this.GAMMADECAL=!1}}class gp extends lG{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}constructor(e,t=!0){super(e,"DecalMap",150,new gd,t),this._isEnabled=!1,this.isEnabled=!1,this._smoothAlpha=!1,this.smoothAlpha=!1,this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[1]}isReadyForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;return!this._isEnabled||null==s||!s.texture||!ow.DecalMapEnabled||!t.texturesEnabled||s.isReady()}prepareDefines(e,t,i){let r=i.decalMap;this._isEnabled&&(null==r?void 0:r.texture)&&ow.DecalMapEnabled&&t.texturesEnabled?(e.DECAL&&e.GAMMADECAL===r.texture.gammaSpace||e.markAsTexturesDirty(),e.DECAL=!0,e.GAMMADECAL=r.texture.gammaSpace,e.DECAL_SMOOTHALPHA=this._smoothAlpha,nE.G.PrepareDefinesForMergedUV(r.texture,e,"DECAL")):(e.DECAL&&e.markAsTexturesDirty(),e.DECAL=!1)}hardBindForSubMesh(e,t,i,r){let s=r.getMesh().decalMap;if(!this._isEnabled||!(null==s?void 0:s.texture)||!ow.DecalMapEnabled||!t.texturesEnabled)return;let n=this._material.isFrozen,a=s.texture;e.useUbo&&n&&e.isSync||(e.updateFloat4("vDecalInfos",a.coordinatesIndex,0,0,0),nE.G.BindTextureMatrix(a,e,"decal")),e.setTexture("decalSampler",a)}getClassName(){return"DecalMapConfiguration"}getSamplers(e){e.push("decalSampler")}getUniforms(){return{ubo:[{name:"vDecalInfos",size:4,type:"vec4"},{name:"decalMatrix",size:16,type:"mat4"}]}}}(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],gp.prototype,"isEnabled",void 0),(0,sx.gn)([(0,rG.qC)(),(0,rG.wz)("_markAllSubMeshesAsTexturesDirty")],gp.prototype,"smoothAlpha",void 0),(0,rg.H)("BABYLON.DecalMapConfiguration",gp),(eF=iF||(iF={}))[eF.MATERIAL_TYPE_STANDARD=0]="MATERIAL_TYPE_STANDARD",eF[eF.MATERIAL_TYPE_PBR=1]="MATERIAL_TYPE_PBR",eF[eF.MATERIAL_TYPE_SIMPLE=2]="MATERIAL_TYPE_SIMPLE",(eL=iL||(iL={}))[eL.COLOR_MODE_SET=0]="COLOR_MODE_SET",eL[eL.COLOR_MODE_ADD=1]="COLOR_MODE_ADD",eL[eL.COLOR_MODE_MULTIPLY=2]="COLOR_MODE_MULTIPLY",(ew=iw||(iw={}))[ew.COLOR_DISTRIBUTION_TYPE_SEGMENT=0]="COLOR_DISTRIBUTION_TYPE_SEGMENT",ew[ew.COLOR_DISTRIBUTION_TYPE_LINE=1]="COLOR_DISTRIBUTION_TYPE_LINE";class g_{}g_.DEFAULT_COLOR=rm.Wo.White(),g_.DEFAULT_WIDTH_ATTENUATED=1,g_.DEFAULT_WIDTH=.1;class gf{static ConvertPoints(e){if(e.length&&Array.isArray(e)&&"number"==typeof e[0])return[e];if(e.length&&Array.isArray(e[0])&&"number"==typeof e[0][0])return e;if(e.length&&!Array.isArray(e[0])&&e[0]instanceof rf.P){let t=[];for(let i=0;i0&&Array.isArray(e[0])&&e[0].length>0&&e[0][0]instanceof rf.P){let t=[];return e.forEach(e=>{t.push(e.flatMap(e=>[e.x,e.y,e.z]))}),t}if(e instanceof Float32Array)return[Array.from(e)];if(e.length&&e[0]instanceof Float32Array){let t=[];return e.forEach(e=>{t.push(Array.from(e))}),t}return[]}static OmitZeroLengthPredicate(e,t,i){let r=[];return t.subtract(e).lengthSquared()>0&&r.push([e,t]),i.subtract(t).lengthSquared()>0&&r.push([t,i]),e.subtract(i).lengthSquared()>0&&r.push([i,e]),0===r.length?null:r}static OmitDuplicatesPredicate(e,t,i,r){let s=[];return gf._SearchInPoints(e,t,r)||s.push([e,t]),gf._SearchInPoints(t,i,r)||s.push([t,i]),gf._SearchInPoints(i,e,r)||s.push([i,e]),0===s.length?null:s}static _SearchInPoints(e,t,i){var r,s,n;for(let a of i)for(let i=0;i{let s=e.getVerticesData(sm.o.PositionKind),n=e.getIndices();if(s&&n)for(let a=0,o=0;a[e.x,e.y,e.z])}static GetPointsCountInfo(e){let t=Array(e.length),i=0;for(let r=e.length;r--;)t[r]=e[r].length/3,i+=t[r];return{total:i,counts:t}}static GetLineLength(e){let t;if(0===e.length)return 0;t="number"==typeof e[0]?gf.ToVector3Array(e):e;let i=rf.jp.Vector3[0],r=0;for(let e=0;e{e.length>t?gf.SegmentizeSegmentByCount(e.point1,e.point2,Math.ceil(e.length/t)).forEach(e=>{r.push(e)}):(r.push(e.point1),r.push(e.point2))}),r}static SegmentizeLineBySegmentCount(e,t){let i="number"==typeof e[0]?gf.ToVector3Array(e):e,r=gf.GetLineLength(i)/t;return gf.SegmentizeLineBySegmentLength(i,r)}static GetLineSegments(e){let t=[];for(let i=0;ie.length);return{min:t[0].length,max:t[t.length-1].length}}static GetPositionOnLineByVisibility(e,t,i,r=!1){let s=t*i,n=0,a=0,o=e.length;for(let t=0;t[e.x,e.y,e.z])}static GetArrowCap(e,t,i,r,s,n=0,a=0){return{points:[e.clone(),e.add(t.multiplyByFloats(i,i,i))],widths:[r,s,n,a]}}static GetPointsFromText(e,t,i,r,s=0,n=!0){let a=[];for(let o of function(e,t,i,r){let s=Array.from(e),n=t/r.resolution,a=(r.boundingBox.yMax-r.boundingBox.yMin+r.underlineThickness)*n,o=[],l=0,h=0;for(let e=0;e{gf.DisposeEmptyColorsTexture()}),this._enable(!0)}getAttributes(e){e.push("grl_offsets"),e.push("grl_widths"),e.push("grl_colorPointers"),e.push("grl_counters"),this._cameraFacing?(e.push("grl_previousAndSide"),e.push("grl_nextAndCounters")):e.push("grl_slopes")}getSamplers(e){e.push("grl_colors")}getActiveTextures(e){this.colorsTexture&&e.push(this.colorsTexture)}getUniforms(){let e=[{name:"grl_singleColor",size:3,type:"vec3"},{name:"grl_dashOptions",size:4,type:"vec4"},{name:"grl_colorMode_visibility_colorsWidth_useColors",size:4,type:"vec4"}];return this._cameraFacing&&e.push({name:"grl_projection",size:16,type:"mat4"},{name:"grl_aspect_resolution_lineWidth",size:4,type:"vec4"}),{ubo:e,vertex:this._cameraFacing?` + uniform vec4 grl_aspect_resolution_lineWidth; + uniform mat4 grl_projection; + `:"",fragment:` + uniform vec4 grl_dashOptions; + uniform vec4 grl_colorMode_visibility_colorsWidth_useColors; + uniform vec3 grl_singleColor; + `}}get isEnabled(){return!0}bindForSubMesh(e){var t;if(this._cameraFacing){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();e.updateMatrix("grl_projection",i)}else throw Error("GreasedLinePluginMaterial requires an active camera.");let i=rf.jp.Vector4[0];i.x=this._aspect,i.y=this._resolution.x,i.z=this._resolution.y,i.w=this.width,e.updateVector4("grl_aspect_resolution_lineWidth",i)}let i=rf.jp.Vector4[0];i.x=gf.BooleanToNumber(this.useDash),i.y=this._dashArray,i.z=this.dashOffset,i.w=this.dashRatio,e.updateVector4("grl_dashOptions",i);let r=rf.jp.Vector4[1];r.x=this.colorMode,r.y=this.visibility,r.z=this.colorsTexture?this.colorsTexture.getSize().width:0,r.w=gf.BooleanToNumber(this.useColors),e.updateVector4("grl_colorMode_visibility_colorsWidth_useColors",r),this._color&&e.updateColor3("grl_singleColor",this._color),e.setTexture("grl_colors",null!==(t=this.colorsTexture)&&void 0!==t?t:g_.EmptyColorsTexture)}prepareDefines(e,t,i){e.GREASED_LINE_HAS_COLOR=!!this.color&&!this.useColors,e.GREASED_LINE_SIZE_ATTENUATION=this._sizeAttenuation,e.GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE=this._colorsDistributionType===iw.COLOR_DISTRIBUTION_TYPE_LINE,e.GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM=t.useRightHandedSystem,e.GREASED_LINE_CAMERA_FACING=this._cameraFacing}getClassName(){return gg.GREASED_LINE_MATERIAL_NAME}getCustomCode(e){if("vertex"===e){let e={CUSTOM_VERTEX_DEFINITIONS:` + attribute float grl_widths; + attribute vec3 grl_offsets; + attribute float grl_colorPointers; + + varying float grlCounters; + varying float grlColorPointer; + + #ifdef GREASED_LINE_CAMERA_FACING + attribute vec4 grl_previousAndSide; + attribute vec4 grl_nextAndCounters; + + vec2 grlFix( vec4 i, float aspect ) { + vec2 res = i.xy / i.w; + res.x *= aspect; + return res; + } + #else + attribute vec3 grl_slopes; + attribute float grl_counters; + #endif + `,CUSTOM_VERTEX_UPDATE_POSITION:` + #ifdef GREASED_LINE_CAMERA_FACING + vec3 grlPositionOffset = grl_offsets; + positionUpdated += grlPositionOffset; + #else + positionUpdated = (positionUpdated + grl_offsets) + (grl_slopes * grl_widths); + #endif + `,CUSTOM_VERTEX_MAIN_END:` + grlColorPointer = grl_colorPointers; + + #ifdef GREASED_LINE_CAMERA_FACING + + float grlAspect = grl_aspect_resolution_lineWidth.x; + float grlBaseWidth = grl_aspect_resolution_lineWidth.w; + + + vec3 grlPrevious = grl_previousAndSide.xyz; + float grlSide = grl_previousAndSide.w; + + vec3 grlNext = grl_nextAndCounters.xyz; + grlCounters = grl_nextAndCounters.w; + + mat4 grlMatrix = viewProjection * finalWorld; + vec4 grlFinalPosition = grlMatrix * vec4( positionUpdated , 1.0 ); + vec4 grlPrevPos = grlMatrix * vec4( grlPrevious + grlPositionOffset, 1.0 ); + vec4 grlNextPos = grlMatrix * vec4( grlNext + grlPositionOffset, 1.0 ); + + vec2 grlCurrentP = grlFix( grlFinalPosition, grlAspect ); + vec2 grlPrevP = grlFix( grlPrevPos, grlAspect ); + vec2 grlNextP = grlFix( grlNextPos, grlAspect ); + + float grlWidth = grlBaseWidth * grl_widths; + + vec2 grlDir; + if( grlNextP == grlCurrentP ) grlDir = normalize( grlCurrentP - grlPrevP ); + else if( grlPrevP == grlCurrentP ) grlDir = normalize( grlNextP - grlCurrentP ); + else { + vec2 grlDir1 = normalize( grlCurrentP - grlPrevP ); + vec2 grlDir2 = normalize( grlNextP - grlCurrentP ); + grlDir = normalize( grlDir1 + grlDir2 ); + } + vec4 grlNormal = vec4( -grlDir.y, grlDir.x, 0., 1. ); + #ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM + grlNormal.xy *= -.5 * grlWidth; + #else + grlNormal.xy *= .5 * grlWidth; + #endif + + grlNormal *= grl_projection; + + #ifdef GREASED_LINE_SIZE_ATTENUATION + grlNormal.xy *= grlFinalPosition.w; + grlNormal.xy /= ( vec4( grl_aspect_resolution_lineWidth.yz, 0., 1. ) * grl_projection ).xy; + #endif + + grlFinalPosition.xy += grlNormal.xy * grlSide; + gl_Position = grlFinalPosition; + + vPositionW = vec3(grlFinalPosition); + #else + grlCounters = grl_counters; + #endif + `};return this._cameraFacing&&(e["!gl_Position\\=viewProjection\\*worldPos;"]="//"),e}return"fragment"===e?{CUSTOM_FRAGMENT_DEFINITIONS:` + varying float grlCounters; + varying float grlColorPointer; + uniform sampler2D grl_colors; + `,CUSTOM_FRAGMENT_MAIN_END:` + float grlColorMode = grl_colorMode_visibility_colorsWidth_useColors.x; + float grlVisibility = grl_colorMode_visibility_colorsWidth_useColors.y; + float grlColorsWidth = grl_colorMode_visibility_colorsWidth_useColors.z; + float grlUseColors = grl_colorMode_visibility_colorsWidth_useColors.w; + + float grlUseDash = grl_dashOptions.x; + float grlDashArray = grl_dashOptions.y; + float grlDashOffset = grl_dashOptions.z; + float grlDashRatio = grl_dashOptions.w; + + gl_FragColor.a *= step(grlCounters, grlVisibility); + if( gl_FragColor.a == 0. ) discard; + + if(grlUseDash == 1.){ + gl_FragColor.a *= ceil(mod(grlCounters + grlDashOffset, grlDashArray) - (grlDashArray * grlDashRatio)); + if (gl_FragColor.a == 0.) discard; + } + + #ifdef GREASED_LINE_HAS_COLOR + if (grlColorMode == ${iL.COLOR_MODE_SET}.) { + gl_FragColor.rgb = grl_singleColor; + } else if (grlColorMode == ${iL.COLOR_MODE_ADD}.) { + gl_FragColor.rgb += grl_singleColor; + } else if (grlColorMode == ${iL.COLOR_MODE_MULTIPLY}.) { + gl_FragColor.rgb *= grl_singleColor; + } + #else + if (grlUseColors == 1.) { + #ifdef GREASED_LINE_COLOR_DISTRIBUTION_TYPE_LINE + vec4 grlColor = texture2D(grl_colors, vec2(grlCounters, 0.), 0.); + #else + vec4 grlColor = texture2D(grl_colors, vec2(grlColorPointer/grlColorsWidth, 0.), 0.); + #endif + if (grlColorMode == ${iL.COLOR_MODE_SET}.) { + gl_FragColor = grlColor; + } else if (grlColorMode == ${iL.COLOR_MODE_ADD}.) { + gl_FragColor += grlColor; + } else if (grlColorMode == ${iL.COLOR_MODE_MULTIPLY}.) { + gl_FragColor *= grlColor; + } + } + #endif + + `}:null}dispose(){var e;null===(e=this.colorsTexture)||void 0===e||e.dispose(),super.dispose()}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this.colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this.colorsTexture&&o===e.length&&!i){let t=gf.Color3toRGBAUint8(e);this.colorsTexture.update(t)}else null===(a=this.colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=gf.CreateColorsTexture(`${this._material.name}-colors-texture`,e,this.colorsSampling,this._scene)}}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.markAllDefinesAsDirty()}get color(){return this._color}set color(e){this.setColor(e)}setColor(e,t=!1){null===this._color&&null!==e||null!==this._color&&null===e?(this._color=e,t||this.markAllDefinesAsDirty()):this._color=e}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this.markAllDefinesAsDirty()}get resolution(){return this._resolution}set resolution(e){this._aspect=e.x/e.y,this._resolution=e}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this.colorsSampling,colorMode:this.colorMode,dashCount:this._dashCount,dashOffset:this.dashOffset,dashRatio:this.dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this.useColors,useDash:this.useDash,visibility:this.visibility,width:this.width};return this._colors&&(t.colors=this._colors),this._color&&(t.color=this._color),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r;super.parse(e,t,i);let s=e.greasedLineMaterialOptions;null===(r=this.colorsTexture)||void 0===r||r.dispose(),s.color&&this.setColor(s.color,!0),s.colorDistributionType&&(this.colorsDistributionType=s.colorDistributionType),s.colors&&(this.colors=s.colors),s.colorsSampling&&(this.colorsSampling=s.colorsSampling),s.colorMode&&(this.colorMode=s.colorMode),s.useColors&&(this.useColors=s.useColors),s.visibility&&(this.visibility=s.visibility),s.useDash&&(this.useDash=s.useDash),s.dashCount&&(this.dashCount=s.dashCount),s.dashRatio&&(this.dashRatio=s.dashRatio),s.dashOffset&&(this.dashOffset=s.dashOffset),s.width&&(this.width=s.width),s.sizeAttenuation&&(this.sizeAttenuation=s.sizeAttenuation),s.resolution&&(this.resolution=s.resolution),this.colors?this.colorsTexture=gf.CreateColorsTexture(`${this._material.name}-colors-texture`,this.colors,this.colorsSampling,t):gf.PrepareEmptyColorsTexture(t),this.markAllDefinesAsDirty()}copyTo(e){var t;null===(t=e.colorsTexture)||void 0===t||t.dispose(),this._colors&&(e.colorsTexture=gf.CreateColorsTexture(`${e._material.name}-colors-texture`,this._colors,e.colorsSampling,this._scene)),e.setColor(this.color,!0),e.colorsDistributionType=this.colorsDistributionType,e.colorsSampling=this.colorsSampling,e.colorMode=this.colorMode,e.useColors=this.useColors,e.visibility=this.visibility,e.useDash=this.useDash,e.dashCount=this.dashCount,e.dashRatio=this.dashRatio,e.dashOffset=this.dashOffset,e.width=this.width,e.sizeAttenuation=this.sizeAttenuation,e.resolution=this.resolution,e.markAllDefinesAsDirty()}}gg.GREASED_LINE_MATERIAL_NAME="GreasedLinePluginMaterial",(0,rg.H)(`BABYLON.${gg.GREASED_LINE_MATERIAL_NAME}`,gg);let gv=`precision highp float;uniform sampler2D grlColors;uniform float grlUseColors;uniform float grlUseDash;uniform float grlDashArray;uniform float grlDashOffset;uniform float grlDashRatio;uniform float grlVisibility;uniform float grlColorsWidth;uniform vec2 grl_colorModeAndColorDistributionType;uniform vec3 grlColor;varying float grlCounters;varying float grlColorPointer;void main() {float grlColorMode=grl_colorModeAndColorDistributionType.x;float grlColorDistributionType=grl_colorModeAndColorDistributionType.y;gl_FragColor=vec4(grlColor,1.);gl_FragColor.a=step(grlCounters,grlVisibility);if (gl_FragColor.a==0.) discard;if( grlUseDash==1. ){gl_FragColor.a=ceil(mod(grlCounters+grlDashOffset,grlDashArray)-(grlDashArray*grlDashRatio));if (gl_FragColor.a==0.) discard;} +if (grlUseColors==1.) {vec4 textureColor;if (grlColorDistributionType==COLOR_DISTRIBUTION_TYPE_LINE) { +textureColor=texture2D(grlColors,vec2(grlCounters,0.),0.);} else {textureColor=texture2D(grlColors,vec2(grlColorPointer/grlColorsWidth,0.),0.);} +if (grlColorMode==COLOR_MODE_SET) {gl_FragColor=textureColor;} else if (grlColorMode==COLOR_MODE_ADD) {gl_FragColor+=textureColor;} else if (grlColorMode==COLOR_MODE_MULTIPLY) {gl_FragColor*=textureColor;}}} +`;nw.v.ShadersStore.greasedLinePixelShader=gv;let gx=`precision highp float; +#include +attribute float grl_widths;attribute vec3 grl_offsets;attribute float grl_colorPointers;attribute vec3 position;uniform mat4 viewProjection;uniform mat4 projection;varying float grlCounters;varying float grlColorPointer; +#ifdef GREASED_LINE_CAMERA_FACING +attribute vec4 grl_nextAndCounters;attribute vec4 grl_previousAndSide;uniform vec2 grlResolution;uniform float grlAspect;uniform float grlWidth;uniform float grlSizeAttenuation;vec2 grlFix( vec4 i,float aspect ) {vec2 res=i.xy/i.w;res.x*=aspect;return res;} +#else +attribute vec3 grl_slopes;attribute float grl_counters; +#endif +void main() { +#include +grlColorPointer=grl_colorPointers; +#ifdef GREASED_LINE_CAMERA_FACING +float grlBaseWidth=grlWidth;vec3 grlPrevious=grl_previousAndSide.xyz;float grlSide=grl_previousAndSide.w;vec3 grlNext=grl_nextAndCounters.xyz;grlCounters=grl_nextAndCounters.w;mat4 grlMatrix=viewProjection*finalWorld ;vec3 grlPositionOffset=grl_offsets;vec4 grlFinalPosition=grlMatrix*vec4( position+grlPositionOffset ,1.0 );vec4 grlPrevPos=grlMatrix*vec4( grlPrevious+grlPositionOffset,1.0 );vec4 grlNextPos=grlMatrix*vec4( grlNext+grlPositionOffset,1.0 );vec2 grlCurrentP=grlFix( grlFinalPosition,grlAspect );vec2 grlPrevP=grlFix( grlPrevPos,grlAspect );vec2 grlNextP=grlFix( grlNextPos,grlAspect );float grlWidth=grlBaseWidth*grl_widths;vec2 grlDir;if( grlNextP==grlCurrentP ) grlDir=normalize( grlCurrentP-grlPrevP );else if( grlPrevP==grlCurrentP ) grlDir=normalize( grlNextP-grlCurrentP );else {vec2 grlDir1=normalize( grlCurrentP-grlPrevP );vec2 grlDir2=normalize( grlNextP-grlCurrentP );grlDir=normalize( grlDir1+grlDir2 );} +vec4 grlNormal=vec4( -grlDir.y,grlDir.x,0.,1. ); +#ifdef GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM +grlNormal.xy*=-.5*grlWidth; +#else +grlNormal.xy*=.5*grlWidth; +#endif +grlNormal*=projection;if (grlSizeAttenuation==1.) {grlNormal.xy*=grlFinalPosition.w;grlNormal.xy/=( vec4( grlResolution,0.,1. )*projection ).xy;} +grlFinalPosition.xy+=grlNormal.xy*grlSide;gl_Position=grlFinalPosition; +#else +grlCounters=grl_counters;vec4 grlFinalPosition=worldViewProjection*vec4( (position+grl_offsets)+grl_slopes*grl_widths ,1.0 ) ;gl_Position=grlFinalPosition; +#endif +} +`;nw.v.ShadersStore.greasedLineVertexShader=gx;class gT extends hV{constructor(e,t,i){var r,s,n,a,o,l,h,u,c,d,p,_,f,m;let g=[`COLOR_DISTRIBUTION_TYPE_LINE ${iw.COLOR_DISTRIBUTION_TYPE_LINE}.`,`COLOR_DISTRIBUTION_TYPE_SEGMENT ${iw.COLOR_DISTRIBUTION_TYPE_SEGMENT}.`,`COLOR_MODE_SET ${iL.COLOR_MODE_SET}.`,`COLOR_MODE_ADD ${iL.COLOR_MODE_ADD}.`,`COLOR_MODE_MULTIPLY ${iL.COLOR_MODE_MULTIPLY}.`],v=["position","grl_widths","grl_offsets","grl_colorPointers"];t.useRightHandedSystem&&g.push("GREASED_LINE_RIGHT_HANDED_COORDINATE_SYSTEM"),i.cameraFacing?(g.push("GREASED_LINE_CAMERA_FACING"),v.push("grl_previousAndSide","grl_nextAndCounters")):(v.push("grl_slopes"),v.push("grl_counters")),super(e,t,{vertex:"greasedLine",fragment:"greasedLine"},{attributes:v,uniforms:["world","viewProjection","view","projection","grlColorsWidth","grlUseColors","grlWidth","grlColor","grl_colorModeAndColorDistributionType","grlResolution","grlAspect","grlAizeAttenuation","grlDashArray","grlDashOffset","grlDashRatio","grlUseDash","grlVisibility"],samplers:["grlColors"],defines:g}),this._color=rm.Wo.White(),this._colorsDistributionType=iw.COLOR_DISTRIBUTION_TYPE_SEGMENT,this._colorsTexture=null,i=i||{color:g_.DEFAULT_COLOR};let x=t.getEngine();this.visibility=null!==(r=i.visibility)&&void 0!==r?r:1,this.useDash=null!==(s=i.useDash)&&void 0!==s&&s,this.dashRatio=null!==(n=i.dashRatio)&&void 0!==n?n:.5,this.dashOffset=null!==(a=i.dashOffset)&&void 0!==a?a:0,this.dashCount=null!==(o=i.dashCount)&&void 0!==o?o:1,this.width=i.width?i.width:i.sizeAttenuation&&i.cameraFacing?g_.DEFAULT_WIDTH_ATTENUATED:g_.DEFAULT_WIDTH,this.sizeAttenuation=null!==(l=i.sizeAttenuation)&&void 0!==l&&l,this.color=null!==(h=i.color)&&void 0!==h?h:rm.Wo.White(),this.useColors=null!==(u=i.useColors)&&void 0!==u&&u,this.colorsDistributionType=null!==(c=i.colorDistributionType)&&void 0!==c?c:iw.COLOR_DISTRIBUTION_TYPE_SEGMENT,this.colorsSampling=null!==(d=i.colorsSampling)&&void 0!==d?d:sJ.NEAREST_NEAREST,this.colorMode=null!==(p=i.colorMode)&&void 0!==p?p:iL.COLOR_MODE_SET,this._colors=null!==(_=i.colors)&&void 0!==_?_:null,this._cameraFacing=null===(f=i.cameraFacing)||void 0===f||f,this.resolution=null!==(m=i.resolution)&&void 0!==m?m:new rf.FM(x.getRenderWidth(),x.getRenderHeight()),i.colorsTexture?this.colorsTexture=i.colorsTexture:this.colorsTexture=gf.PrepareEmptyColorsTexture(t),this._colors&&this.setColors(this._colors),x.onDisposeObservable.add(()=>{gf.DisposeEmptyColorsTexture()})}dispose(){var e;null===(e=this._colorsTexture)||void 0===e||e.dispose(),super.dispose()}_setColorModeAndColorDistributionType(){this.setVector2("grl_colorModeAndColorDistributionType",new rf.FM(this._colorMode,this._colorsDistributionType))}updateLazy(){this._colors&&this.setColors(this._colors,!1,!0)}get colors(){return this._colors}set colors(e){this.setColors(e)}setColors(e,t=!1,i=!1){var r,s,n,a;let o=null!==(s=null===(r=this._colors)||void 0===r?void 0:r.length)&&void 0!==s?s:0;if(this._colors=e,null===e||0===e.length){null===(n=this._colorsTexture)||void 0===n||n.dispose();return}if(!t||i){if(this._colorsTexture&&o===e.length&&!i){let t=gf.Color3toRGBAUint8(e);this._colorsTexture.update(t)}else null===(a=this._colorsTexture)||void 0===a||a.dispose(),this.colorsTexture=gf.CreateColorsTexture(`${this.name}-colors-texture`,e,this.colorsSampling,this.getScene())}}get colorsTexture(){var e;return null!==(e=this._colorsTexture)&&void 0!==e?e:null}set colorsTexture(e){this._colorsTexture=e,this.setFloat("grlColorsWidth",this._colorsTexture.getSize().width),this.setTexture("grlColors",this._colorsTexture)}get width(){return this._width}set width(e){this._width=e,this.setFloat("grlWidth",e)}get useColors(){return this._useColors}set useColors(e){this._useColors=e,this.setFloat("grlUseColors",gf.BooleanToNumber(e))}get colorsSampling(){return this._colorsSampling}set colorsSampling(e){this._colorsSampling=e}get visibility(){return this._visibility}set visibility(e){this._visibility=e,this.setFloat("grlVisibility",e)}get useDash(){return this._useDash}set useDash(e){this._useDash=e,this.setFloat("grlUseDash",gf.BooleanToNumber(e))}get dashOffset(){return this._dashOffset}set dashOffset(e){this._dashOffset=e,this.setFloat("grlDashOffset",e)}get dashRatio(){return this._dashRatio}set dashRatio(e){this._dashRatio=e,this.setFloat("grlDashRatio",e)}get dashCount(){return this._dashCount}set dashCount(e){this._dashCount=e,this._dashArray=1/e,this.setFloat("grlDashArray",this._dashArray)}get sizeAttenuation(){return this._sizeAttenuation}set sizeAttenuation(e){this._sizeAttenuation=e,this.setFloat("grlSizeAttenuation",gf.BooleanToNumber(e))}get color(){return this.color}set color(e){this.setColor(e)}setColor(e){e=null!=e?e:g_.DEFAULT_COLOR,this._color=e,this.setColor3("grlColor",e)}get colorsDistributionType(){return this._colorsDistributionType}set colorsDistributionType(e){this._colorsDistributionType=e,this._setColorModeAndColorDistributionType()}get colorMode(){return this._colorMode}set colorMode(e){this._colorMode=e,this._setColorModeAndColorDistributionType()}get resolution(){return this._resolution}set resolution(e){this._resolution=e,this.setVector2("grlResolution",e),this.setFloat("grlAspect",e.x/e.y)}serialize(){let e=super.serialize(),t={colorDistributionType:this._colorsDistributionType,colorsSampling:this._colorsSampling,colorMode:this._colorMode,color:this._color,dashCount:this._dashCount,dashOffset:this._dashOffset,dashRatio:this._dashRatio,resolution:this._resolution,sizeAttenuation:this._sizeAttenuation,useColors:this._useColors,useDash:this._useDash,visibility:this._visibility,width:this._width,cameraFacing:this._cameraFacing};return this._colors&&(t.colors=this._colors),e.greasedLineMaterialOptions=t,e}parse(e,t,i){var r,s;let n=e.greasedLineMaterialOptions;null===(r=this._colorsTexture)||void 0===r||r.dispose(),n.color&&(this.color=n.color),n.colorDistributionType&&(this.colorsDistributionType=n.colorDistributionType),n.colorsSampling&&(this.colorsSampling=n.colorsSampling),n.colorMode&&(this.colorMode=n.colorMode),n.useColors&&(this.useColors=n.useColors),n.visibility&&(this.visibility=n.visibility),n.useDash&&(this.useDash=n.useDash),n.dashCount&&(this.dashCount=n.dashCount),n.dashRatio&&(this.dashRatio=n.dashRatio),n.dashOffset&&(this.dashOffset=n.dashOffset),n.width&&(this.width=n.width),n.sizeAttenuation&&(this.sizeAttenuation=n.sizeAttenuation),n.resolution&&(this.resolution=n.resolution),n.colors?this.colorsTexture=gf.CreateColorsTexture(`${this.name}-colors-texture`,n.colors,this.colorsSampling,this.getScene()):this.colorsTexture=gf.PrepareEmptyColorsTexture(t),this._cameraFacing=null===(s=n.cameraFacing)||void 0===s||s,this.setDefine("GREASED_LINE_CAMERA_FACING",this._cameraFacing)}}let gS=`#if defined(DBG_ENABLED) +attribute float dbg_initialPass; +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; +#endif`,gE=`#if defined(DBG_ENABLED) +float dbg_vertexIndex = mod(float(gl_VertexID), 3.); +if (dbg_vertexIndex == 0.0) { + dbg_vBarycentric = vec3(1.,0.,0.); +} +else if (dbg_vertexIndex == 1.0) { + dbg_vBarycentric = vec3(0.,1.,0.); +} +else { + dbg_vBarycentric = vec3(0.,0.,1.); +} + +dbg_vVertexWorldPos = vPositionW; +dbg_vPass = dbg_initialPass; +#endif`,gC=`#if defined(DBG_ENABLED) +uniform vec3 dbg_shadedDiffuseColor; +uniform vec4 dbg_shadedSpecularColorPower; +uniform vec3 dbg_thicknessRadiusScale; + +#if DBG_MODE == 2 || DBG_MODE == 3 + uniform vec3 dbg_vertexColor; +#endif + +#if DBG_MODE == 1 + uniform vec3 dbg_wireframeTrianglesColor; +#elif DBG_MODE == 3 + uniform vec3 dbg_wireframeVerticesColor; +#elif DBG_MODE == 4 || DBG_MODE == 5 + uniform vec3 dbg_uvPrimaryColor; + uniform vec3 dbg_uvSecondaryColor; +#elif DBG_MODE == 7 + uniform vec3 dbg_materialColor; +#endif +#endif`,gb=`#if defined(DBG_ENABLED) +varying vec3 dbg_vBarycentric; +flat varying vec3 dbg_vVertexWorldPos; +flat varying float dbg_vPass; + +#if !defined(DBG_MULTIPLY) + vec3 dbg_applyShading(vec3 color) { + vec3 N = vNormalW.xyz; + vec3 L = normalize(vEyePosition.xyz - vPositionW.xyz); + vec3 H = normalize(L + L); + float LdotN = clamp(dot(L,N), 0., 1.); + float HdotN = clamp(dot(H,N), 0., 1.); + float specTerm = pow(HdotN, dbg_shadedSpecularColorPower.w); + color *= (LdotN / PI); + color += dbg_shadedSpecularColorPower.rgb * (specTerm / PI); + return color; + } +#endif + +#if DBG_MODE == 1 || DBG_MODE == 3 + float dbg_edgeFactor() { + vec3 d = fwidth(dbg_vBarycentric); + vec3 a3 = smoothstep(vec3(0.), d * dbg_thicknessRadiusScale.x, dbg_vBarycentric); + return min(min(a3.x, a3.y), a3.z); + } +#endif + +#if DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor() { + vec3 worldPos = vPositionW; + float dist = length(worldPos - dbg_vVertexWorldPos); + float camDist = length(worldPos - vEyePosition.xyz); + float d = sqrt(camDist) * .001; + return smoothstep((dbg_thicknessRadiusScale.y * d), ((dbg_thicknessRadiusScale.y * 1.01) * d), dist); + } +#endif + +#if (DBG_MODE == 4 && defined(UV1)) || (DBG_MODE == 5 && defined(UV2)) + float dbg_checkerboardFactor(vec2 uv) { + vec2 f = fract(uv * dbg_thicknessRadiusScale.z); + f -= .5; + return (f.x * f.y) > 0. ? 1. : 0.; + } +#endif +#endif`,gy=`#if defined(DBG_ENABLED) +vec3 dbg_color = vec3(1.); +#if DBG_MODE == 1 + dbg_color = mix(dbg_wireframeTrianglesColor, vec3(1.), dbg_edgeFactor()); +#elif DBG_MODE == 2 || DBG_MODE == 3 + float dbg_cornerFactor = dbg_cornerFactor(); + if (dbg_vPass == 0. && dbg_cornerFactor == 1.) discard; + dbg_color = mix(dbg_vertexColor, vec3(1.), dbg_cornerFactor); + #if DBG_MODE == 3 + dbg_color *= mix(dbg_wireframeVerticesColor, vec3(1.), dbg_edgeFactor()); + #endif +#elif DBG_MODE == 4 && defined(UV1) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV1)); +#elif DBG_MODE == 5 && defined(UV2) + dbg_color = mix(dbg_uvPrimaryColor, dbg_uvSecondaryColor, dbg_checkerboardFactor(vMainUV2)); +#elif DBG_MODE == 6 && defined(VERTEXCOLOR) + dbg_color = vColor.rgb; +#elif DBG_MODE == 7 + dbg_color = dbg_materialColor; +#endif + +#if defined(DBG_MULTIPLY) + gl_FragColor *= vec4(dbg_color, 1.); +#else + #if DBG_MODE != 6 + gl_FragColor = vec4(dbg_applyShading(dbg_shadedDiffuseColor) * dbg_color, 1.); + #else + gl_FragColor = vec4(dbg_color, 1.); + #endif +#endif +#endif`,gA=[new rm.Wo(.98,.26,.38),new rm.Wo(.47,.75,.3),new rm.Wo(0,.26,.77),new rm.Wo(.97,.6,.76),new rm.Wo(.19,.63,.78),new rm.Wo(.98,.8,.6),new rm.Wo(.65,.43,.15),new rm.Wo(.15,.47,.22),new rm.Wo(.67,.71,.86),new rm.Wo(.09,.46,.56),new rm.Wo(.8,.98,.02),new rm.Wo(.39,.29,.13),new rm.Wo(.53,.63,.06),new rm.Wo(.95,.96,.41),new rm.Wo(1,.72,.94),new rm.Wo(.63,.08,.31),new rm.Wo(.66,.96,.95),new rm.Wo(.22,.14,.19),new rm.Wo(.14,.65,.59),new rm.Wo(.93,1,.68),new rm.Wo(.93,.14,.44),new rm.Wo(.47,.86,.67),new rm.Wo(.85,.07,.78),new rm.Wo(.53,.64,.98),new rm.Wo(.43,.37,.56),new rm.Wo(.71,.65,.25),new rm.Wo(.66,.19,.01),new rm.Wo(.94,.53,.12),new rm.Wo(.41,.44,.44),new rm.Wo(.24,.71,.96),new rm.Wo(.57,.28,.56),new rm.Wo(.44,.98,.42)];(eB=iB||(iB={}))[eB.NONE=0]="NONE",eB[eB.TRIANGLES=1]="TRIANGLES",eB[eB.VERTICES=2]="VERTICES",eB[eB.TRIANGLES_VERTICES=3]="TRIANGLES_VERTICES",eB[eB.UV0=4]="UV0",eB[eB.UV1=5]="UV1",eB[eB.VERTEXCOLORS=6]="VERTEXCOLORS",eB[eB.MATERIALIDS=7]="MATERIALIDS";class gR extends nf.H{constructor(){super(...arguments),this.DBG_MODE=iB.NONE,this.DBG_MULTIPLY=!0,this.DBG_ENABLED=!0}}class gP extends lG{_markAllDefinesAsDirty(){this._enable(this._isEnabled),this.markAllDefinesAsDirty()}constructor(e,t={}){var i,r,s,n,a,o,l,h,u,c,d,p,_;let f=new gR;f.DBG_MODE=null!==(i=t.mode)&&void 0!==i?i:f.DBG_MODE,f.DBG_MULTIPLY=null!==(r=t.multiply)&&void 0!==r?r:f.DBG_MULTIPLY,super(e,"MeshDebug",200,f,!0,!0),this._mode=f.DBG_MODE,this._multiply=f.DBG_MULTIPLY,this.shadedDiffuseColor=null!==(s=t.shadedDiffuseColor)&&void 0!==s?s:new rm.Wo(1,1,1),this.shadedSpecularColor=null!==(n=t.shadedSpecularColor)&&void 0!==n?n:new rm.Wo(.8,.8,.8),this.shadedSpecularPower=null!==(a=t.shadedSpecularPower)&&void 0!==a?a:10,this.wireframeThickness=null!==(o=t.wireframeThickness)&&void 0!==o?o:.7,this.wireframeTrianglesColor=null!==(l=t.wireframeTrianglesColor)&&void 0!==l?l:new rm.Wo(0,0,0),this.wireframeVerticesColor=null!==(h=t.wireframeVerticesColor)&&void 0!==h?h:new rm.Wo(.8,.8,.8),this.vertexColor=null!==(u=t.vertexColor)&&void 0!==u?u:new rm.Wo(0,0,0),this.vertexRadius=null!==(c=t.vertexRadius)&&void 0!==c?c:1.2,this.uvScale=null!==(d=t.uvScale)&&void 0!==d?d:20,this.uvPrimaryColor=null!==(p=t.uvPrimaryColor)&&void 0!==p?p:new rm.Wo(1,1,1),this.uvSecondaryColor=null!==(_=t.uvSecondaryColor)&&void 0!==_?_:new rm.Wo(.5,.5,.5),this._materialColor=gP.MaterialColors[gP._PluginCount++%gP.MaterialColors.length],this.isEnabled=!0}getClassName(){return"MeshDebugPluginMaterial"}get isEnabled(){return this._isEnabled}set isEnabled(e){if(this._isEnabled!==e){if(!this._material.getScene().getEngine().isWebGPU&&1==this._material.getScene().getEngine().webGLVersion){rb.Y.Error("MeshDebugPluginMaterial is not supported on WebGL 1.0."),this._isEnabled=!1;return}this._isEnabled=e,this._markAllDefinesAsDirty()}}prepareDefines(e,t,i){this._mode!=iB.VERTICES&&this._mode!=iB.TRIANGLES&&this._mode!=iB.TRIANGLES_VERTICES||i.isVerticesDataPresent("dbg_initialPass")||rb.Y.Warn("For best results with TRIANGLES, TRIANGLES_VERTICES, or VERTICES modes, please use MeshDebugPluginMaterial.PrepareMeshForTrianglesAndVerticesMode() on mesh.",1),e.DBG_MODE=this._mode,e.DBG_MULTIPLY=this._multiply,e.DBG_ENABLED=this._isEnabled}getAttributes(e){e.push("dbg_initialPass")}getUniforms(){return{ubo:[{name:"dbg_shadedDiffuseColor",size:3,type:"vec3"},{name:"dbg_shadedSpecularColorPower",size:4,type:"vec4"},{name:"dbg_thicknessRadiusScale",size:3,type:"vec3"},{name:"dbg_wireframeTrianglesColor",size:3,type:"vec3"},{name:"dbg_wireframeVerticesColor",size:3,type:"vec3"},{name:"dbg_vertexColor",size:3,type:"vec3"},{name:"dbg_uvPrimaryColor",size:3,type:"vec3"},{name:"dbg_uvSecondaryColor",size:3,type:"vec3"},{name:"dbg_materialColor",size:3,type:"vec3"}],fragment:gC}}bindForSubMesh(e){this._isEnabled&&(e.updateFloat3("dbg_shadedDiffuseColor",this.shadedDiffuseColor.r,this.shadedDiffuseColor.g,this.shadedDiffuseColor.b),e.updateFloat4("dbg_shadedSpecularColorPower",this.shadedSpecularColor.r,this.shadedSpecularColor.g,this.shadedSpecularColor.b,this.shadedSpecularPower),e.updateFloat3("dbg_thicknessRadiusScale",this.wireframeThickness,this.vertexRadius,this.uvScale),e.updateColor3("dbg_wireframeTrianglesColor",this.wireframeTrianglesColor),e.updateColor3("dbg_wireframeVerticesColor",this.wireframeVerticesColor),e.updateColor3("dbg_vertexColor",this.vertexColor),e.updateColor3("dbg_uvPrimaryColor",this.uvPrimaryColor),e.updateColor3("dbg_uvSecondaryColor",this.uvSecondaryColor),e.updateColor3("dbg_materialColor",this._materialColor))}getCustomCode(e){return"vertex"===e?{CUSTOM_VERTEX_DEFINITIONS:gS,CUSTOM_VERTEX_MAIN_END:gE}:{CUSTOM_FRAGMENT_DEFINITIONS:gb,CUSTOM_FRAGMENT_MAIN_END:gy}}static Reset(){this._PluginCount=0,this.MaterialColors=gA}static PrepareMeshForTrianglesAndVerticesMode(e,t=!1){let i=()=>{};if(0==e.getTotalIndices())return i;if(t){let t=e.getVerticesDataKinds(),r=e.getIndices(),s={};for(let i of t)s[i]=e.getVerticesData(i);i=function(){for(let i of(e.setIndices(r),t)){let t=e.getVertexBuffer(i).getStrideSize();e.setVerticesData(i,s[i],void 0,t)}e.removeVerticesData("dbg_initialPass")}}let r=Array.from(e.getIndices()),s=[];for(let e=0;e{let a=n.data_type(),o=n.num_components(),l=n.normalized(),h=n.byte_stride(),c=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 Error(`Invalid data type ${a}`);let p=u*o,_=p*d.typedArrayConstructor.BYTES_PER_ELEMENT,f=e._malloc(_);try{t.GetAttributeDataArrayForAllPoints(i,n,a,_,f);let e=new d.typedArrayConstructor(d.heap.buffer,f,p);s(r,e.slice(),o,c,h,l)}finally{e._free(f)}};if(i)for(let e in i){let t=i[e],r=n.GetAttributeByUniqueId(o,t);c(n,o,e,r)}else{let t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(let e in t){let i=n.GetAttributeId(o,t[e]);if(-1!==i){let t=n.GetAttribute(o,i);c(n,o,e,t)}}}return u}finally{o&&e.destroy(o),a&&e.destroy(a),n&&e.destroy(n)}}function gD(){let e;onmessage=t=>{let i=t.data;switch(i.id){case"init":{let t=i.decoder;t.url&&(importScripts(t.url),e=DracoDecoderModule({wasmBinary:t.wasmBinary})),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw Error("Draco decoder module is not available");e.then(e=>{let t=gM(e,i.dataView,i.attributes,e=>{postMessage({id:"indices",data:e},[e.buffer])},(e,t,i,r,s,n)=>{postMessage({id:"attribute",kind:e,data:t,size:i,byteOffset:r,byteStride:s,normalized:n},[t.buffer])});postMessage({id:"decodeMeshDone",totalVertices:t})})}}}class gO{static get DecoderAvailable(){let e=gO.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 gO._Default||(gO._Default=new gO),gO._Default}constructor(e=gO.DefaultNumWorkers){let t=gO.Configuration.decoder,i=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:sg.w1.GetBabylonScriptURL(t.wasmUrl,!0),wasmBinaryPromise:sg.w1.LoadFileAsync(sg.w1.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:sg.w1.GetBabylonScriptURL(t.fallbackUrl),wasmBinaryPromise:Promise.resolve(void 0)};e&&"function"==typeof Worker&&"function"==typeof URL?this._workerPoolPromise=i.wasmBinaryPromise.then(t=>{let r=`${gM}(${gD})()`,s=URL.createObjectURL(new Blob([r],{type:"application/javascript"}));return new pX(e,()=>new Promise((e,r)=>{let n=new Worker(s),a=e=>{n.removeEventListener("error",a),n.removeEventListener("message",o),r(e)},o=t=>{"initDone"===t.data.id&&(n.removeEventListener("error",a),n.removeEventListener("message",o),e(n))};n.addEventListener("error",a),n.addEventListener("message",o),n.postMessage({id:"init",decoder:{url:i.url,wasmBinary:t}})}))}):this._decoderModulePromise=i.wasmBinaryPromise.then(e=>{if(!i.url)throw Error("Draco decoder module is not available");return sg.w1.LoadBabylonScriptAsync(i.url).then(()=>new Promise(t=>{DracoDecoderModule({wasmBinary:e}).then(e=>{t({module:e})})}))})}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then(e=>{e.dispose()}),delete this._workerPoolPromise,delete this._decoderModulePromise}whenReadyAsync(){return this._workerPoolPromise?this._workerPoolPromise.then(()=>{}):this._decoderModulePromise?this._decoderModulePromise.then(()=>{}):Promise.resolve()}_decodeMeshAsync(e,t,i){let r=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength),s=(e,t)=>i&&void 0!==i[e]?(t!==i[e]&&rb.Y.Warn(`Normalized flag from Draco data (${t}) does not match normalized flag from glTF accessor (${i[e]}). Using flag from glTF accessor.`),i[e]):t;if(this._workerPoolPromise)return this._workerPoolPromise.then(e=>new Promise((i,n)=>{e.push((e,a)=>{let o=null,l=[],h=t=>{e.removeEventListener("error",h),e.removeEventListener("message",u),n(t),a()},u=t=>{let r=t.data;switch(r.id){case"decodeMeshDone":e.removeEventListener("error",h),e.removeEventListener("message",u),i({indices:o,attributes:l,totalVertices:r.totalVertices}),a();break;case"indices":o=r.data;break;case"attribute":l.push({kind:r.kind,data:r.data,size:r.size,byteOffset:r.byteOffset,byteStride:r.byteStride,normalized:s(r.kind,r.normalized)})}};e.addEventListener("error",h),e.addEventListener("message",u);let c=r.slice();e.postMessage({id:"decodeMesh",dataView:c,attributes:t},[c.buffer])})}));if(this._decoderModulePromise)return this._decoderModulePromise.then(e=>{let i=null,s=[],n=gM(e.module,r,t,e=>{i=e},(e,t,i,r,n,a)=>{s.push({kind:e,data:t,size:i,byteOffset:r,byteStride:n,normalized:a})});return{indices:i,attributes:s,totalVertices:n}});throw Error("Draco decoder module is not available")}decodeMeshToGeometryAsync(e,t,i,r){return this._decodeMeshAsync(i,r).then(i=>{let r=new _5.Z(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new sm.o(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}_decodeMeshToGeometryForGltfAsync(e,t,i,r,s){return this._decodeMeshAsync(i,r,s).then(i=>{let r=new _5.Z(e,t);for(let e of(i.indices&&r.setIndices(i.indices),i.attributes))r.setVerticesBuffer(new sm.o(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),i.totalVertices);return r})}decodeMeshAsync(e,t){return this._decodeMeshAsync(e,t).then(e=>{let t=new s7.x;for(let i of(e.indices&&(t.indices=e.indices),e.attributes)){let r=sm.o.GetFloatData(i.data,i.size,sm.o.GetDataType(i.data),i.byteOffset,i.byteStride,i.normalized,e.totalVertices);t.set(r,i.kind)}return t})}}gO.Configuration={decoder:{wasmUrl:`${sg.w1._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${sg.w1._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${sg.w1._DefaultCdnUrl}/draco_decoder_gltf.js`}},gO.DefaultNumWorkers=gO.GetDefaultNumWorkers(),gO._Default=null;class gN{static get Default(){return gN._Default||(gN._Default=new gN),gN._Default}constructor(){let e=gN.Configuration.decoder;this._decoderModulePromise=sg.w1.LoadBabylonScriptAsync(e.url).then(()=>MeshoptDecoder.ready)}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,i,r,s){return this._decoderModulePromise.then(()=>{let n=new Uint8Array(t*i);return MeshoptDecoder.decodeGltfBuffer(n,t,i,e,r,s),n})}}gN.Configuration={decoder:{url:`${sg.w1._DefaultCdnUrl}/meshopt_decoder.js`}},gN._Default=null;let gF=0;class gL{constructor(e,t,i,r){this.pos=e,this.normal=t,this.uv=i,this.vertColor=r}clone(){var e,t;return new gL(this.pos.clone(),this.normal.clone(),null===(e=this.uv)||void 0===e?void 0:e.clone(),null===(t=this.vertColor)||void 0===t?void 0:t.clone())}flip(){this.normal=this.normal.scale(-1)}interpolate(e,t){return new gL(rf.P.Lerp(this.pos,e.pos,t),rf.P.Lerp(this.normal,e.normal,t),this.uv&&e.uv?rf.FM.Lerp(this.uv,e.uv,t):void 0,this.vertColor&&e.vertColor?rm.HE.Lerp(this.vertColor,e.vertColor,t):void 0)}}class gw{constructor(e,t){this.normal=e,this.w=t}static FromPoints(e,t,i){let r=i.subtract(e),s=t.subtract(e);if(0===r.lengthSquared()||0===s.lengthSquared())return null;let n=rf.P.Normalize(rf.P.Cross(r,s));return new gw(n,rf.P.Dot(n,e))}clone(){return new gw(this.normal.clone(),this.w)}flip(){this.normal.scaleInPlace(-1),this.w=-this.w}splitPolygon(e,t,i,r,s){let n,a;let o=0,l=[];for(n=0;ngw.EPSILON?1:0;o|=t,l.push(t)}switch(o){case 0:(rf.P.Dot(this.normal,e.plane.normal)>0?t:i).push(e);break;case 1:r.push(e);break;case 2:s.push(e);break;case 3:{let t;let i=[],o=[];for(n=0;n=3&&(t=new gB(i,e.shared)).plane&&r.push(t),o.length>=3&&(t=new gB(o,e.shared)).plane&&s.push(t)}}}}gw.EPSILON=1e-5;class gB{constructor(e,t){this.vertices=e,this.shared=t,this.plane=gw.FromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){return new gB(this.vertices.map(e=>e.clone()),this.shared)}flip(){this.vertices.reverse().map(e=>{e.flip()}),this.plane.flip()}}class gU{constructor(e){this._plane=null,this._front=null,this._back=null,this._polygons=[],e&&this.build(e)}clone(){let e=new gU;return e._plane=this._plane&&this._plane.clone(),e._front=this._front&&this._front.clone(),e._back=this._back&&this._back.clone(),e._polygons=this._polygons.map(e=>e.clone()),e}invert(){for(let e=0;ee.clone()),e.copyTransformAttributes(this),e}union(e){let t=new gU(this.clone()._polygons),i=new gU(e.clone()._polygons);return t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),gV._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}unionInPlace(e){let t=new gU(this._polygons),i=new gU(e._polygons);t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),this._polygons=t.allPolygons()}subtract(e){let t=new gU(this.clone()._polygons),i=new gU(e.clone()._polygons);return t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),gV._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}subtractInPlace(e){let t=new gU(this._polygons),i=new gU(e._polygons);t.invert(),t.clipTo(i),i.clipTo(t),i.invert(),i.clipTo(t),i.invert(),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}intersect(e){let t=new gU(this.clone()._polygons),i=new gU(e.clone()._polygons);return t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),gV._FromPolygons(t.allPolygons()).copyTransformAttributes(this)}intersectInPlace(e){let t=new gU(this._polygons),i=new gU(e._polygons);t.invert(),i.clipTo(t),i.invert(),t.clipTo(i),i.clipTo(t),t.build(i.allPolygons()),t.invert(),this._polygons=t.allPolygons()}inverse(){let e=this.clone();return e.inverseInPlace(),e}inverseInPlace(){this._polygons.map(e=>{e.flip()})}copyTransformAttributes(e){return this.matrix=e.matrix,this.position=e.position,this.rotation=e.rotation,this.scaling=e.scaling,this.rotationQuaternion=e.rotationQuaternion,this}toVertexData(e=null,t=null){let i;let r=this.matrix.clone();r.invert();let s=this._polygons,n=[],a=[],o=[],l=null,h=null,u=rf.P.Zero(),c=rf.P.Zero(),d=rf.FM.Zero(),p=new rm.HE(0,0,0,0),_=[0,0,0],f={};for(let m=0,g=s.length;me.shared.meshId===t.shared.meshId?e.shared.subMeshId-t.shared.subMeshId:e.shared.meshId-t.shared.meshId),this.toVertexData(e=>{o[e.shared.meshId]||(o[e.shared.meshId]={}),o[e.shared.meshId][e.shared.subMeshId]||(o[e.shared.meshId][e.shared.subMeshId]={indexStart:Infinity,indexEnd:-1/0,materialIndex:e.shared.materialIndex}),r=o[e.shared.meshId][e.shared.subMeshId]},()=>{r.indexStart=Math.min(a,r.indexStart),r.indexEnd=Math.max(a,r.indexEnd),a++}).applyToMesh(s),i){let e=0,t;for(let i in s.subMeshes=[],o){for(let n in t=-1,o[i])r=o[i][n],_e.P.CreateFromIndices(r.materialIndex+e,r.indexStart,r.indexEnd-r.indexStart+1,s),t=Math.max(r.materialIndex,t);e+=++t}}return s}toMesh(e,t=null,i,r){let s=this.buildMeshGeometry(e,i,r);return s.material=t,s.position.copyFrom(this.position),s.rotation.copyFrom(this.rotation),this.rotationQuaternion&&(s.rotationQuaternion=this.rotationQuaternion.clone()),s.scaling.copyFrom(this.scaling),s.computeWorldMatrix(!0),s}}let gk=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;uniform mat4 projMatrix;varying vec2 vDecalTC; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +void main(void) {vec3 positionUpdated=position;vec3 normalUpdated=normal; +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);mat3 normWorldSM=mat3(finalWorld);vec3 vNormalW; +#if defined(INSTANCES) && defined(THIN_INSTANCES) +vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); +#else +#ifdef NONUNIFORMSCALING +normWorldSM=transposeMat3(inverseMat3(normWorldSM)); +#endif +vNormalW=normalize(normWorldSM*normalUpdated); +#endif +vec3 normalView=normalize((projMatrix*vec4(vNormalW,0.0)).xyz);vec3 decalTC=(projMatrix*worldPos).xyz;vDecalTC=decalTC.xy;gl_Position=vec4(uv*2.0-1.0,normalView.z>0.0 ? 2. : decalTC.z,1.0);}`;nw.v.ShadersStore.meshUVSpaceRendererVertexShader=gk;let gG=`precision highp float;varying vec2 vDecalTC;uniform sampler2D textureSampler;void main(void) {if (vDecalTC.x<0. || vDecalTC.x>1. || vDecalTC.y<0. || vDecalTC.y>1.) {discard;} +gl_FragColor=texture2D(textureSampler,vDecalTC);} +`;nw.v.ShadersStore.meshUVSpaceRendererPixelShader=gG,nw.v.ShadersStore.meshUVSpaceRendererMaskerVertexShader="attribute vec2 uv;varying vec2 vUV;void main(void) {gl_Position=vec4(vec2(uv.x,uv.y)*2.0-1.0,0.,1.0);vUV=uv;}";let gz=`varying vec2 vUV;void main(void) {gl_FragColor=vec4(1.0,1.0,1.0,1.0);} +`;nw.v.ShadersStore.meshUVSpaceRendererMaskerPixelShader=gz;let gW=`precision highp float;varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D maskTextureSampler;uniform vec2 textureSize;void main() {vec4 mask=texture2D(maskTextureSampler,vUV).rgba;if (mask.r>0.5) {gl_FragColor=texture2D(textureSampler,vUV);} else {vec2 texelSize=4.0/textureSize;vec2 uv_p01=vUV+vec2(-1.0,0.0)*texelSize;vec2 uv_p21=vUV+vec2(1.0,0.0)*texelSize;vec2 uv_p10=vUV+vec2(0.0,-1.0)*texelSize;vec2 uv_p12=vUV+vec2(0.0,1.0)*texelSize;float mask_p01=texture2D(maskTextureSampler,uv_p01).r;float mask_p21=texture2D(maskTextureSampler,uv_p21).r;float mask_p10=texture2D(maskTextureSampler,uv_p10).r;float mask_p12=texture2D(maskTextureSampler,uv_p12).r;vec4 col=vec4(0.0,0.0,0.0,0.0);float total_weight=0.0;if (mask_p01>0.5) {col+=texture2D(textureSampler,uv_p01);total_weight+=1.0;} +if (mask_p21>0.5) {col+=texture2D(textureSampler,uv_p21);total_weight+=1.0;} +if (mask_p10>0.5) {col+=texture2D(textureSampler,uv_p10);total_weight+=1.0;} +if (mask_p12>0.5) {col+=texture2D(textureSampler,uv_p12);total_weight+=1.0;} +if (total_weight>0.0) {gl_FragColor=col/total_weight;} else {gl_FragColor=col;}}} +`;nw.v.ShadersStore.meshUVSpaceRendererFinaliserPixelShader=gW;let gH=`precision highp float;attribute vec3 position;attribute vec2 uv;uniform mat4 worldViewProjection;varying vec2 vUV;void main() {gl_Position=worldViewProjection*vec4(position,1.0);vUV=uv;} +`;nw.v.ShadersStore.meshUVSpaceRendererFinaliserVertexShader=gH,sp.Kj._TrailMeshParser=(e,t)=>gX.Parse(e,t);class gX extends sp.Kj{constructor(e,t,i,r=1,s=60,n=!0){super(e,i),this._sectionPolygonPointsCount=4,this._running=!1,this._autoStart=n,this._generator=t,this.diameter=r,this._length=s,this._sectionVectors=[],this._sectionNormalVectors=[];for(let e=0;e{this.update()}))}stop(){this._beforeRenderObserver&&this._running&&(this._running=!1,this.getScene().onBeforeRenderObservable.remove(this._beforeRenderObserver))}update(){let e=this.getVerticesData(sm.o.PositionKind),t=this.getVerticesData(sm.o.NormalKind),i=this._generator.getWorldMatrix();if(e&&t){for(let i=3*this._sectionPolygonPointsCount;i{this._getSimplifier(e).simplify(t,i=>{void 0!==t.distance&&e.mesh.addLODLevel(t.distance,i),i.isVisible=!0,t.quality===e.settings[e.settings.length-1].quality&&e.successCallback&&e.successCallback(),this.executeNext()})});else{let t=this._getSimplifier(e),i=(i,r)=>{t.simplify(i,t=>{void 0!==i.distance&&e.mesh.addLODLevel(i.distance,t),t.isVisible=!0,r()})};sg.$g.Run(e.settings.length,t=>{i(e.settings[t.index],()=>{t.executeNext()})},()=>{e.successCallback&&e.successCallback(),this.executeNext()})}}_getSimplifier(e){return e.simplificationType,iU.QUADRATIC,new gQ(e.mesh)}}(eU=iU||(iU={}))[eU.QUADRATIC=0]="QUADRATIC";class gj{constructor(e){this._vertices=e,this.error=[,,,,],this.deleted=!1,this.isDirty=!1,this.deletePending=!1,this.borderFactor=0}}class gq{constructor(e,t){this.position=e,this.id=t,this.isBorder=!0,this.q=new gK,this.triangleCount=0,this.triangleStart=0,this.originalOffsets=[]}updatePosition(e){this.position.copyFrom(e)}}class gK{constructor(e){this.data=Array(10);for(let t=0;t<10;++t)e&&e[t]?this.data[t]=e[t]:this.data[t]=0}det(e,t,i,r,s,n,a,o,l){return this.data[e]*this.data[s]*this.data[l]+this.data[i]*this.data[r]*this.data[o]+this.data[t]*this.data[n]*this.data[a]-this.data[i]*this.data[s]*this.data[a]-this.data[e]*this.data[n]*this.data[o]-this.data[t]*this.data[r]*this.data[l]}addInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e.data[t]}addArrayInPlace(e){for(let t=0;t<10;++t)this.data[t]+=e[t]}add(e){let t=new gK;for(let i=0;i<10;++i)t.data[i]=this.data[i]+e.data[i];return t}static FromData(e,t,i,r){return new gK(gK.DataFromNumbers(e,t,i,r))}static DataFromNumbers(e,t,i,r){return[e*e,e*t,e*i,e*r,t*t,t*i,t*r,i*i,i*r,r*r]}}class g${constructor(e,t){this.vertexId=e,this.triangleId=t}}class gQ{constructor(e){this._mesh=e,this.syncIterations=5e3,this.aggressiveness=7,this.decimationIterations=100,this.boundingBoxEpsilon=r7.kn}simplify(e,t){this._initDecimatedMesh(),sg.$g.Run(this._mesh.subMeshes.length,t=>{this._initWithMesh(t.index,()=>{this._runDecimation(e,t.index,()=>{t.executeNext()})},e.optimizeMesh)},()=>{setTimeout(()=>{t(this._reconstructedMesh)},0)})}_runDecimation(e,t,i){let r=~~(this._triangles.length*e.quality),s=0,n=this._triangles.length,a=(e,t)=>{setTimeout(()=>{e%5==0&&this._updateMesh(0===e);for(let e=0;e{let t=~~((this._triangles.length/2+e)%this._triangles.length),r=this._triangles[t];if(r&&!(r.error[3]>i)&&!r.deleted&&!r.isDirty){for(let e=0;e<3;++e)if(r.error[e]t.indexOf(!0)||0>i.indexOf(!0))continue;let h=[];if(l.forEach(e=>{-1===h.indexOf(e)&&(e.deletePending=!0,h.push(e))}),h.length%2!=0)continue;n.q=a.q.add(n.q),n.updatePosition(o);let u=this._references.length;s=this._updateTriangles(n,n,t,s),s=this._updateTriangles(n,a,i,s);let c=this._references.length-u;if(c<=n.triangleCount){if(c)for(let e=0;en-s<=r)},0)};sg.$g.Run(this.decimationIterations,e=>{n-s<=r?e.breakLoop():a(e.index,()=>{e.executeNext()})},()=>{setTimeout(()=>{this._reconstructMesh(t),i()},0)})}_initWithMesh(e,t,i){this._vertices=[],this._triangles=[];let r=this._mesh.getVerticesData(sm.o.PositionKind),s=this._mesh.getIndices(),n=this._mesh.subMeshes[e],a=e=>{if(i){for(let t=0;t>0,e=>{if(!r)return;let t=e+n.verticesStart,i=rf.P.FromArray(r,3*t),s=a(i)||new gq(i,this._vertices.length);s.originalOffsets.push(t),s.id===this._vertices.length&&this._vertices.push(s),o.push(s.id)},()=>{sg.$g.SyncAsyncForLoop(n.indexCount/3,this.syncIterations,e=>{if(!s)return;let t=3*(n.indexStart/3+e),i=s[t+0],r=s[t+1],a=s[t+2],l=new gj([this._vertices[o[i-n.verticesStart]],this._vertices[o[r-n.verticesStart]],this._vertices[o[a-n.verticesStart]]]);l.originalOffset=t,this._triangles.push(l)},()=>{this._init(t)})})}_init(e){sg.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];t.normal=rf.P.Cross(t._vertices[1].position.subtract(t._vertices[0].position),t._vertices[2].position.subtract(t._vertices[0].position)).normalize();for(let e=0;e<3;e++)t._vertices[e].q.addArrayInPlace(gK.DataFromNumbers(t.normal.x,t.normal.y,t.normal.z,-rf.P.Dot(t.normal,t._vertices[0].position)))},()=>{sg.$g.SyncAsyncForLoop(this._triangles.length,this.syncIterations,e=>{let t=this._triangles[e];for(let e=0;e<3;++e)t.error[e]=this._calculateError(t._vertices[e],t._vertices[(e+1)%3]);t.error[3]=Math.min(t.error[0],t.error[1],t.error[2])},()=>{e()})})}_reconstructMesh(e){let t,i,r;let s=[];for(t=0;t{n.push(e.position.x),n.push(e.position.y),n.push(e.position.z),h&&h.length&&(a.push(h[3*t]),a.push(h[3*t+1]),a.push(h[3*t+2])),u&&u.length&&(o.push(u[2*t]),o.push(u[2*t+1])),c&&c.length&&(l.push(c[4*t]),l.push(c[4*t+1]),l.push(c[4*t+2]),l.push(c[4*t+3])),++d})}let p=this._reconstructedMesh.getTotalIndices(),_=this._reconstructedMesh.getTotalVertices(),f=this._reconstructedMesh.subMeshes;this._reconstructedMesh.subMeshes=[];let m=this._reconstructedMesh.getIndices(),g=this._mesh.getIndices();for(t=0;t{let t=g[i.originalOffset+e],r=i._vertices[e].originalOffsets.indexOf(t);r<0&&(r=0),m.push(i._vertices[e].id+r+_)});this._reconstructedMesh.setIndices(m),this._reconstructedMesh.setVerticesData(sm.o.PositionKind,n),a.length>0&&this._reconstructedMesh.setVerticesData(sm.o.NormalKind,a),o.length>0&&this._reconstructedMesh.setVerticesData(sm.o.UVKind,o),l.length>0&&this._reconstructedMesh.setVerticesData(sm.o.ColorKind,l);let v=this._mesh.subMeshes[e];e>0&&(this._reconstructedMesh.subMeshes=[],f.forEach(e=>{_e.P.AddToMesh(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,e.getMesh())}),_e.P.AddToMesh(v.materialIndex,_,d,p,3*s.length,this._reconstructedMesh))}_initDecimatedMesh(){this._reconstructedMesh=new sp.Kj(this._mesh.name+"Decimated",this._mesh.getScene()),this._reconstructedMesh.material=this._mesh.material,this._reconstructedMesh.parent=this._mesh.parent,this._reconstructedMesh.isVisible=!1,this._reconstructedMesh.renderingGroupId=this._mesh.renderingGroupId}_isFlipped(e,t,i,r,s){for(let n=0;n.999)return!0;let d=rf.P.Cross(u,c).normalize();if(r[n]=!1,.2>rf.P.Dot(d,a.normal))return!0}return!1}_updateTriangles(e,t,i,r){let s=r;for(let r=0;rg0.Parse(e,t);class g0 extends gJ{constructor(e,t,i){super(e,t,i),this.name=e,this.intersectionThreshold=.1,this._previousAndSide=[],this._nextAndCounters=[],i.points&&this.addPoints(gf.ConvertPoints(i.points))}getClassName(){return"GreasedLineMesh"}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[],this._points.forEach(t=>{for(let i=0;i{var i;let r=[],s=[],n=[],a=gf.GetLineLength(e);for(let i=0,o=0;o0&&(a=g0._CopyV3(o,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]));return a=g0._CompareV3(n-1,0,e)?g0._CopyV3(1,e):g0._CopyV3(n-1,e),i.push(a[0],a[1],a[2]),i.push(a[0],a[1],a[2]),{previous:t,next:i,uvs:s,side:r}}_createVertexBuffers(){let e=super._createVertexBuffers(),t=this._scene.getEngine(),i=new sm.l(t,this._previousAndSide,!1,4);this.setVerticesBuffer(i.createVertexBuffer("grl_previousAndSide",0,4));let r=new sm.l(t,this._nextAndCounters,!1,4);this.setVerticesBuffer(r.createVertexBuffer("grl_nextAndCounters",0,4));let s=new sm.l(t,this._widths,this._updatable,1);this.setVerticesBuffer(s.createVertexBuffer("grl_widths",0,1)),this._widthsBuffer=s;let n=new sm.l(t,this._colorPointers,this._updatable,1);return this.setVerticesBuffer(n.createVertexBuffer("grl_colorPointers",0,1)),this._colorPointersBuffer=n,e}}g0._V_START=new rf.P,g0._V_END=new rf.P,g0._V_OFFSET_START=new rf.P,g0._V_OFFSET_END=new rf.P,sp.Kj._GreasedLineRibbonMeshParser=(e,t)=>g1.Parse(e,t);class g1 extends gJ{constructor(e,t,i,r){var s;if(super(e,t,i),this.name=e,!i.ribbonOptions)throw"'GreasedLineMeshOptions.ribbonOptions' is not set.";this._paths=[],this._counters=[],this._slopes=[],this._widths=null!==(s=i.widths)&&void 0!==s?s:[],this._ribbonWidths=[],this._pathsOptions=null!=r?r:[],i.points&&this.addPoints(gf.ConvertPoints(i.points),i,!!r)}addPoints(e,t,i=!1){if(!t.ribbonOptions)throw"addPoints() on GreasedLineRibbonMesh instance requires 'GreasedLineMeshOptions.ribbonOptions'.";i||this._pathsOptions.push({options:t,pathCount:e.length}),super.addPoints(e,t)}getClassName(){return"GreasedLineRibbonMesh"}get isFlatLine(){return this._paths.length<3}get slopes(){return this._slopes}set slopes(e){this._slopes=e}_updateColorPointers(){if(this._options.colorPointers)return;let e=0;this._colorPointers=[];for(let t=0;t{let i=g1._ConvertToRibbonPath(e,o.ribbonOptions,this._scene.useRightHandedSystem,s?s[t]:s);n=this._preprocess(i,n,o)})}}this._lazy||(this._createVertexBuffers(),this.refreshBoundingInfo())}static _GetDirectionPlanesFromDirectionsOption(e,t){return Array.isArray(t)?t:Array(e).fill(t)}static _CreateRibbonVertexData(e,t){var i,r,s;let n=e.length;if(n<2)throw"Minimum of two paths are required to create a GreasedLineRibbonMesh.";let a=[],o=[],l=e[0];for(let t=0;t2)for(let e=0;e0&&(h[0]+=1,h[1]+=1),o.push(h[1]+(e%2!=0?n:0),h[0],h[2]),u&&o.push(h[0],h[1]+(e%2!=0?n:0),h[2])}else for(let e=0;ee.y&&e.x>e.z?i?g1._RightHandedForwardReadOnlyQuaternion:g1._LeftHandedForwardReadOnlyQuaternion:g1._LeftReadOnlyQuaternion),l=e.normalize()}h=l.multiplyByFloats(a,a,a),s.push(u.add(h)),n.push(u.subtract(h))}r||(s.push(o[o.length-1].add(h)),n.push(o[o.length-1].subtract(h)))}return[s,n]}static _GetDirectionFromPoints(e,t,i){return e.x!==t.x||i&&(null==i?void 0:i.x)!==1?e.y===t.y?g1.DIRECTION_XZ:e.z===t.z?g1.DIRECTION_XY:g1.DIRECTION_XZ:g1.DIRECTION_YZ}clone(e=`${this.name}-cloned`,t){let i=this._createLineOptions(),r={},s=[];rw.j.DeepCopy(this._pathsOptions,s,void 0,void 0,!0),rw.j.DeepCopy(i,r,["instance"],void 0,!0);let n=new g1(e,this._scene,r,s);return t&&(n.parent=t),n.material=this.material,n}serialize(e){super.serialize(e),e.type=this.getClassName(),e.lineOptions=this._createLineOptions(),e.pathsOptions=this._pathsOptions}static Parse(e,t){let i=e.lineOptions;return new g1(e.name,t,i,e.pathOptions)}_initGreasedLine(){super._initGreasedLine(),this._paths=[],this._counters=[],this._slopes=[],this._ribbonWidths=[]}_calculateSegmentLengths(e){let t=e.length;this._vSegmentLengths=Array(t),this._vTotalLengths=Array(t);let i=0;for(let r=0;r=this._thinInstanceDataStorage.instancesCount)return!1;let r=this._thinInstanceDataStorage.matrixData;return t.copyToArray(r,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),i&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},sp.Kj.prototype.thinInstanceSetAttributeAt=function(e,t,i,r=!0){return e===sm.o.ColorKind&&(e=sm.o.ColorInstanceKind),!!this._userThinInstanceBuffersStorage&&!!this._userThinInstanceBuffersStorage.data[e]&&!(t>=this._thinInstanceDataStorage.instancesCount)&&(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(i,t*this._userThinInstanceBuffersStorage.strides[e]),r&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(sp.Kj.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){var t,i;let r=null!==(t=this._thinInstanceDataStorage.matrixData)&&void 0!==t?t:null===(i=this.source)||void 0===i?void 0:i._thinInstanceDataStorage.matrixData;e<=(r?r.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),sp.Kj.prototype._thinInstanceCreateMatrixBuffer=function(e,t,i=!1){e===sm.o.ColorKind&&(e=sm.o.ColorInstanceKind);let r=new sm.l(this.getEngine(),t,!i,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(r.createVertexBuffer(e+t,4*t,4));return r},sp.Kj.prototype.thinInstanceSetBuffer=function(e,t,i=0,r=!1){var s,n,a;i=i||16,"matrix"===e?(null===(s=this._thinInstanceDataStorage.matrixBuffer)||void 0===s||s.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*i,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/i,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,r),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(null===(n=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===n||n.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,r))):(e===sm.o.ColorKind&&(e=sm.o.ColorInstanceKind),null===t?(null===(a=this._userThinInstanceBuffersStorage)||void 0===a?void 0:a.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]=i,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new sm.o(this.getEngine(),t,e,!r,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},sp.Kj.prototype.thinInstanceBufferUpdated=function(e){var t,i,r;"matrix"===e?null===(t=this._thinInstanceDataStorage.matrixBuffer)||void 0===t||t.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount):"previousMatrix"===e?null===(i=this._thinInstanceDataStorage.previousMatrixBuffer)||void 0===i||i.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount):(e===sm.o.ColorKind&&(e=sm.o.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0))},sp.Kj.prototype.thinInstancePartialBufferUpdate=function(e,t,i){var r;"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,i):(e===sm.o.ColorKind&&(e=sm.o.ColorInstanceKind),(null===(r=this._userThinInstanceBuffersStorage)||void 0===r?void 0:r.vertexBuffers[e])&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,i))},sp.Kj.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];let e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;te.ownerBlock)}get endpoints(){return this._endpoints}get hasEndpoints(){return this._endpoints&&this._endpoints.length>0}get innerType(){return this._linkedConnectionSource&&this._linkedConnectionSource.isConnected?this.type:this._type}_resetCounters(){this._callCount=0,this._executionCount=0}get callCount(){return this._callCount}get executionCount(){return this._executionCount}getConnectedValue(e){var t;return this.isConnected?(null===(t=this._connectedPoint)||void 0===t?void 0:t._storedFunction)?(this._connectedPoint._callCount++,this._connectedPoint._executionCount++,this._connectedPoint._storedFunction(e)):(this._connectedPoint._callCount++,this._connectedPoint._executionCount=1,this._connectedPoint._storedValue):(this._callCount++,this._executionCount=1,this.value)}constructor(e,t,i){this._connectedPoint=null,this._storedValue=null,this._storedFunction=null,this._acceptedConnectionPointType=null,this._endpoints=[],this._type=iH.Geometry,this._linkedConnectionSource=null,this._typeConnectionSource=null,this._defaultConnectionPointType=null,this.acceptedConnectionPointTypes=[],this.excludedConnectionPointTypes=[],this.onConnectionObservable=new r_.y$,this.isExposedOnFrame=!1,this.exposedPortPosition=-1,this.defaultValue=null,this.value=null,this.valueMin=null,this.valueMax=null,this._callCount=0,this._executionCount=0,this._ownerBlock=t,this.name=e,this._direction=i}getClassName(){return"NodeGeometryConnectionPoint"}canConnectTo(e){return this.checkCompatibilityState(e)===iX.Compatible}checkCompatibilityState(e){let t=this._ownerBlock,i=e.ownerBlock;if(this.type!==e.type&&e.innerType!==iH.AutoDetect)return e.acceptedConnectionPointTypes&&-1!==e.acceptedConnectionPointTypes.indexOf(this.type)?iX.Compatible:iX.TypeIncompatible;if(e.excludedConnectionPointTypes&&-1!==e.excludedConnectionPointTypes.indexOf(this.type))return iX.TypeIncompatible;let r=i,s=t;return(this.direction===iY.Input&&(r=t,s=i),r.isAnAncestorOf(s))?iX.HierarchyIssue:iX.Compatible}connectTo(e,t=!1){if(!t&&!this.canConnectTo(e))throw"Cannot connect these two connectors.";return this._endpoints.push(e),e._connectedPoint=this,this.onConnectionObservable.notifyObservers(e),e.onConnectionObservable.notifyObservers(this),this}disconnectFrom(e){let t=this._endpoints.indexOf(e);return -1===t||(this._endpoints.splice(t,1),e._connectedPoint=null),this}addExcludedConnectionPointFromAllowedTypes(e){let t=1;for(;t0){if(!this._outputs.some(e=>e.hasEndpoints)&&!this.isDebug)return!1;this.outputs.forEach(e=>e._resetCounters())}for(let t of(this._buildId=e.buildId,this._inputs)){if(!t.connectedPoint){t.isOptional||e.notConnectedNonOptionalInputs.push(t);continue}let i=t.connectedPoint.ownerBlock;i&&i!==this&&i.build(e)}this._customBuildStep(e),e.verbose&&rb.Y.Log(`Building ${this.name} [${this.getClassName()}]`);let t=r3.F.Now;for(let i of(this._buildBlock(e),this._buildExecutionTime=r3.F.Now-t,this._outputs))for(let t of i.endpoints){let i=t.ownerBlock;i&&i.build(e)}return this.onBuildObservable.notifyObservers(this),!1}_linkConnectionTypes(e,t,i=!1){i?this._inputs[t]._acceptedConnectionPointType=this._inputs[e]:this._inputs[e]._linkedConnectionSource=this._inputs[t],this._inputs[t]._linkedConnectionSource=this._inputs[e]}initialize(){}autoConfigure(){}getInputByName(e){let t=this._inputs.filter(t=>t.name===e);return t.length?t[0]:null}getOutputByName(e){let t=this._outputs.filter(t=>t.name===e);return t.length?t[0]:null}serialize(){let e={};for(let t of(e.customType="BABYLON."+this.getClassName(),e.id=this.uniqueId,e.name=this.name,e.inputs=[],e.outputs=[],this.inputs))e.inputs.push(t.serialize());for(let t of this.outputs)e.outputs.push(t.serialize(!1));return e}_deserialize(e){this._name=e.name,this.comments=e.comments,this.visibleOnFrame=!!e.visibleOnFrame,this._deserializePortDisplayNamesAndExposedOnFrame(e)}_deserializePortDisplayNamesAndExposedOnFrame(e){let t=e.inputs,i=e.outputs;t&&t.forEach(e=>{let t=this.inputs.find(t=>t.name===e.name);if(t&&(e.displayName&&(t.displayName=e.displayName),e.isExposedOnFrame&&(t.isExposedOnFrame=e.isExposedOnFrame,t.exposedPortPosition=e.exposedPortPosition),void 0!==e.value&&null!==e.value)){if("number"===e.valueType)t.value=e.value;else{let i=(0,rg.q)(e.valueType);i&&(t.value=i.FromArray(e.value))}}}),i&&i.forEach((e,t)=>{e.displayName&&(this.outputs[t].displayName=e.displayName),e.isExposedOnFrame&&(this.outputs[t].isExposedOnFrame=e.isExposedOnFrame,this.outputs[t].exposedPortPosition=e.exposedPortPosition)})}_dumpPropertiesCode(){let e=this._codeVariableName;return`${e}.visibleOnFrame = ${this.visibleOnFrame}; +`}_dumpCodeForOutputConnections(e){let t="";if(-1!==e.indexOf(this))return t;for(let i of(e.push(this),this.inputs)){if(!i.isConnected)continue;let r=i.connectedPoint,s=r.ownerBlock;t+=s._dumpCodeForOutputConnections(e)+`${s._codeVariableName}.${s._outputRename(r.name)}.connectTo(${this._codeVariableName}.${this._inputRename(i.name)}); +`}return t}_dumpCode(e,t){t.push(this);let i=this.name.replace(/[^A-Za-z_]+/g,"");if(this._codeVariableName=i||`${this.getClassName()}_${this.uniqueId}`,-1!==e.indexOf(this._codeVariableName)){let t=0;do t++,this._codeVariableName=i+t;while(-1!==e.indexOf(this._codeVariableName))}e.push(this._codeVariableName);let r=` +// ${this.getClassName()} +`;this.comments&&(r+=`// ${this.comments} +`);let s=this.getClassName();if("GeometryInputBlock"===s){let e=this.type;r+=`var ${this._codeVariableName} = new BABYLON.GeometryInputBlock("${this.name}", ${e}); +`}else r+=`var ${this._codeVariableName} = new BABYLON.${s}("${this.name}"); +`;for(let i of(r+=this._dumpPropertiesCode(),this.inputs)){if(!i.isConnected)continue;let s=i.connectedPoint.ownerBlock;-1===t.indexOf(s)&&(r+=s._dumpCode(e,t))}for(let i of this.outputs)if(i.hasEndpoints)for(let s of i.endpoints){let i=s.ownerBlock;i&&-1===t.indexOf(i)&&(r+=i._dumpCode(e,t))}return r}clone(){let e=this.serialize(),t=(0,rg.q)(e.customType);if(t){let i=new t;return i._deserialize(e),i}return null}dispose(){for(let e of this.inputs)e.dispose();for(let e of this.outputs)e.dispose();this.onBuildObservable.clear()}}(0,sx.gn)([(0,rG.qC)("comment")],g3.prototype,"comments",void 0);class g4 extends g3{get currentVertexData(){return this._vertexData}constructor(e){super(e),this._vertexData=null,this._isUnique=!0,this.registerInput("geometry",iH.Geometry)}getClassName(){return"GeometryOutputBlock"}get geometry(){return this._inputs[0]}_buildBlock(e){e.vertexData=this.geometry.getConnectedValue(e),this._vertexData=e.vertexData}}(0,rg.H)("BABYLON.GeometryOutputBlock",g4),(ej=ij||(ij={}))[ej.None=0]="None",ej[ej.Positions=1]="Positions",ej[ej.Normals=2]="Normals",ej[ej.Tangents=3]="Tangents",ej[ej.UV=4]="UV",ej[ej.UV2=5]="UV2",ej[ej.UV3=6]="UV3",ej[ej.UV4=7]="UV4",ej[ej.UV5=8]="UV5",ej[ej.UV6=9]="UV6",ej[ej.Colors=10]="Colors",ej[ej.VertexID=11]="VertexID",ej[ej.FaceID=12]="FaceID",ej[ej.GeometryID=13]="GeometryID",ej[ej.CollectionID=14]="CollectionID",ej[ej.LoopID=15]="LoopID",ej[ej.InstanceID=16]="InstanceID";class g5{constructor(){this._rotationMatrix=new rf.y3,this._scalingMatrix=new rf.y3,this._positionMatrix=new rf.y3,this._scalingRotationMatrix=new rf.y3,this._transformMatrix=new rf.y3,this._tempVector3=new rf.P,this.notConnectedNonOptionalInputs=[],this.noContextualData=[],this.vertexData=null,this._geometryContext=null,this._executionContext=null,this._instancingContext=null,this._geometryContextStack=[],this._executionContextStack=[],this._instancingContextStack=[]}get geometryContext(){return this._geometryContext}get executionContext(){return this._executionContext}get instancingContext(){return this._instancingContext}pushGeometryContext(e){this._geometryContext=e,this._geometryContextStack.push(this._geometryContext)}pushExecutionContext(e){this._executionContext=e,this._executionContextStack.push(this._executionContext)}pushInstancingContext(e){this._instancingContext=e,this._instancingContextStack.push(this._instancingContext)}restoreGeometryContext(){this._geometryContextStack.pop(),this._geometryContext=this._geometryContextStack.length>0?this._geometryContextStack[this._geometryContextStack.length-1]:null}restoreExecutionContext(){this._executionContextStack.pop(),this._executionContext=this._executionContextStack.length>0?this._executionContextStack[this._executionContextStack.length-1]:null}restoreInstancingContext(){this._instancingContextStack.pop(),this._instancingContext=this._instancingContextStack.length>0?this._instancingContextStack[this._instancingContextStack.length-1]:null}getContextualValue(e,t=!1){if(!this.executionContext)return t||this.noContextualData.push(e),null;let i=this.executionContext.getExecutionIndex();switch(e){case ij.Positions:if(this.executionContext.getOverridePositionsContextualValue)return this.executionContext.getOverridePositionsContextualValue();if(!this.geometryContext||!this.geometryContext.positions)return rf.P.Zero();return rf.P.FromArray(this.geometryContext.positions,3*i);case ij.Normals:if(this.executionContext.getOverrideNormalsContextualValue)return this.executionContext.getOverrideNormalsContextualValue();if(!this.geometryContext||!this.geometryContext.normals)return rf.P.Zero();return rf.P.FromArray(this.geometryContext.normals,3*i);case ij.Colors:if(!this.geometryContext||!this.geometryContext.colors)return rf.Lt.Zero();return rf.Lt.FromArray(this.geometryContext.colors,4*i);case ij.Tangents:if(!this.geometryContext||!this.geometryContext.tangents)return rf.Lt.Zero();return rf.Lt.FromArray(this.geometryContext.tangents,4*i);case ij.UV:if(this.executionContext.getOverrideUVs1ContextualValue)return this.executionContext.getOverrideUVs1ContextualValue();if(!this.geometryContext||!this.geometryContext.uvs)return rf.FM.Zero();return rf.FM.FromArray(this.geometryContext.uvs,2*i);case ij.UV2:if(!this.geometryContext||!this.geometryContext.uvs2)return rf.FM.Zero();return rf.FM.FromArray(this.geometryContext.uvs2,2*i);case ij.UV3:if(!this.geometryContext||!this.geometryContext.uvs3)return rf.FM.Zero();return rf.FM.FromArray(this.geometryContext.uvs3,2*i);case ij.UV4:if(!this.geometryContext||!this.geometryContext.uvs4)return rf.FM.Zero();return rf.FM.FromArray(this.geometryContext.uvs4,2*i);case ij.UV5:if(!this.geometryContext||!this.geometryContext.uvs5)return rf.FM.Zero();return rf.FM.FromArray(this.geometryContext.uvs5,2*i);case ij.UV6:if(!this.geometryContext||!this.geometryContext.uvs6)return rf.FM.Zero();return rf.FM.FromArray(this.geometryContext.uvs6,2*i);case ij.VertexID:return i;case ij.FaceID:return this.executionContext.getExecutionFaceIndex();case ij.LoopID:return this.executionContext.getExecutionLoopIndex();case ij.InstanceID:return this.instancingContext?this.instancingContext.getInstanceIndex():0;case ij.GeometryID:return this.geometryContext?this.geometryContext.uniqueId:0;case ij.CollectionID:if(!this.geometryContext||!this.geometryContext.metadata)return 0;return this.geometryContext.metadata.collectionId||0}return null}adapt(e,t){let i=e.getConnectedValue(this)||0;if(e.type===t)return i;switch(t){case iH.Vector2:return new rf.FM(i,i);case iH.Vector3:return new rf.P(i,i,i);case iH.Vector4:return new rf.Lt(i,i,i,i)}return null}adaptInput(e,t,i){var r;if(!e.isConnected)return e.value||i;let s=e.getConnectedValue(this);if((null===(r=e._connectedPoint)||void 0===r?void 0:r.type)===t)return s;switch(t){case iH.Vector2:return new rf.FM(s,s);case iH.Vector3:return new rf.P(s,s,s);case iH.Vector4:return new rf.Lt(s,s,s,s)}return null}emitErrors(){let e="";for(let t of this.notConnectedNonOptionalInputs)e+=`input ${t.name} from block ${t.ownerBlock.name}[${t.ownerBlock.getClassName()}] is not connected and is not optional. +`;for(let t of this.noContextualData)e+=`Contextual input ${ij[t]} has no context to pull data from (must be connected to a setXXX block or a instantiateXXX block). +`;if(e)throw"Build of NodeGeometry failed:\n"+e}_instantiate(e,t,i,r,s){rf.y3.ScalingToRef(r.x,r.y,r.z,this._scalingMatrix),rf.y3.RotationYawPitchRollToRef(i.y,i.x,i.z,this._rotationMatrix),rf.y3.TranslationToRef(t.x,t.y,t.z,this._positionMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._positionMatrix,this._transformMatrix);for(let t=0;te.getContextualValue(this._contextualSource)):(this.output._storedFunction=null,this.output._storedValue=this.value)}dispose(){this.onValueChangedObservable.clear(),super.dispose()}_dumpPropertiesCode(){let e=this._codeVariableName;if(this.isContextual)return super._dumpPropertiesCode()+`${e}.contextualValue = BABYLON.NodeGeometryContextualSources.${ij[this._contextualSource]}; +`;let t=[],i="";switch(this.type){case iH.Float:case iH.Int:i=`${this.value}`;break;case iH.Vector2:i=`new BABYLON.Vector2(${this.value.x}, ${this.value.y})`;break;case iH.Vector3:i=`new BABYLON.Vector3(${this.value.x}, ${this.value.y}, ${this.value.z})`;break;case iH.Vector4:i=`new BABYLON.Vector4(${this.value.x}, ${this.value.y}, ${this.value.z}, ${this.value.w})`}return t.push(`${e}.value = ${i}`),(this.type===iH.Float||this.type===iH.Int)&&t.push(`${e}.min = ${this.min}`,`${e}.max = ${this.max}`),t.push(""),super._dumpPropertiesCode()+t.join(";\n")}serialize(){let e=super.serialize();return e.type=this.type,e.contextualValue=this.contextualValue,e.min=this.min,e.max=this.max,e.groupInInspector=this.groupInInspector,null===this._storedValue||this.isContextual||(this._storedValue.asArray?(e.valueType="BABYLON."+this._storedValue.getClassName(),e.value=this._storedValue.asArray()):(e.valueType="number",e.value=this._storedValue)),e}_deserialize(e){if(super._deserialize(e),this._type=e.type,this.contextualValue=e.contextualValue,this.min=e.min||0,this.max=e.max||0,this.groupInInspector=e.groupInInspector||"",e.valueType){if("number"===e.valueType)this._storedValue=e.value;else{let t=(0,rg.q)(e.valueType);t&&(this._storedValue=t.FromArray(e.value))}}}}(0,rg.H)("BABYLON.GeometryInputBlock",g6);class g8 extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",iH.Float,!0,1),this.registerInput("width",iH.Float,!0,0),this.registerInput("height",iH.Float,!0,0),this.registerInput("depth",iH.Float,!0,0),this.registerInput("subdivisions",iH.Int,!0,1),this.registerInput("subdivisionsX",iH.Int,!0,0),this.registerInput("subdivisionsY",iH.Int,!0,0),this.registerInput("subdivisionsZ",iH.Int,!0,0),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"BoxBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get depth(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get subdivisionsX(){return this._inputs[5]}get subdivisionsY(){return this._inputs[6]}get subdivisionsZ(){return this._inputs[7]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected&&!this.depth.isConnected){let e=new g6("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new g6("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new g6("Height");e.value=1,e.output.connectTo(this.height)}if(!this.depth.isConnected){let e=new g6("Depth");e.value=1,e.output.connectTo(this.depth)}}}_buildBlock(e){let t={},i=e=>{t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.depth=this.depth.getConnectedValue(e);let i=this.subdivisions.getConnectedValue(e),r=this.subdivisionsX.getConnectedValue(e),s=this.subdivisionsY.getConnectedValue(e),n=this.subdivisionsZ.getConnectedValue(e);return i&&(t.segments=i),r&&(t.widthSegments=r),s&&(t.heightSegments=s),n&&(t.depthSegments=n),function(e){let t=e.width||e.size||1,i=e.height||e.size||1,r=e.depth||e.size||1,s=0|(e.widthSegments||e.segments||1),n=0|(e.heightSegments||e.segments||1),a=0|(e.depthSegments||e.segments||1),o=new rf.y3,l=new rf.y3,h=new rf.y3,u=l8({width:t,height:r,subdivisionsX:s,subdivisionsY:a});rf.y3.TranslationToRef(0,-i/2,0,l),rf.y3.RotationZToRef(Math.PI,o),o.multiplyToRef(l,h),u.transform(h);let c=l8({width:t,height:r,subdivisionsX:s,subdivisionsY:a});rf.y3.TranslationToRef(0,i/2,0,h),c.transform(h);let d=l8({width:i,height:r,subdivisionsX:n,subdivisionsY:a});rf.y3.TranslationToRef(-t/2,0,0,l),rf.y3.RotationZToRef(Math.PI/2,o),o.multiplyToRef(l,h),d.transform(h);let p=l8({width:i,height:r,subdivisionsX:n,subdivisionsY:a});rf.y3.TranslationToRef(t/2,0,0,l),rf.y3.RotationZToRef(-Math.PI/2,o),o.multiplyToRef(l,h),p.transform(h);let _=l8({width:t,height:i,subdivisionsX:s,subdivisionsY:n});rf.y3.TranslationToRef(0,0,-r/2,l),rf.y3.RotationXToRef(-Math.PI/2,o),o.multiplyToRef(l,h),_.transform(h);let f=l8({width:t,height:i,subdivisionsX:s,subdivisionsY:n});return rf.y3.TranslationToRef(0,0,r/2,l),rf.y3.RotationXToRef(Math.PI/2,o),o.multiplyToRef(l,h),f.transform(h),u.merge([c,p,d,_,f],!0),u}(t)};if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],g8.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.BoxBlock",g8);class g7{_getGlobalNodeGeometryEditor(){return"undefined"!=typeof NODEGEOMETRYEDITOR?NODEGEOMETRYEDITOR:"undefined"!=typeof BABYLON&&void 0!==BABYLON.NodeGeometryEditor?BABYLON:void 0}get buildExecutionTime(){return this._buildExecutionTime}constructor(e){this._buildId=g7._BuildIdGenerator++,this._buildWasSuccessful=!1,this._vertexData=null,this._buildExecutionTime=0,this.BJSNODEGEOMETRYEDITOR=this._getGlobalNodeGeometryEditor(),this.editorData=null,this.attachedBlocks=[],this.onBuildObservable=new r_.y$,this.outputBlock=null,this.name=e}getClassName(){return"NodeGeometry"}getBlockByName(e){let t=null;for(let i of this.attachedBlocks)if(i.name===e){if(t){sg.w1.Warn("More than one block was found with the name `"+e+"`");break}t=i}return t}getBlockByPredicate(e){for(let t of this.attachedBlocks)if(e(t))return t;return null}getInputBlocks(){let e=[];for(let t of this.attachedBlocks)t.isInput&&e.push(t);return e}edit(e){return new Promise(t=>{if(this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),void 0===this.BJSNODEGEOMETRYEDITOR){let i=e&&e.editorURL?e.editorURL:g7.EditorURL;sg.w1.LoadBabylonScript(i,()=>{this.BJSNODEGEOMETRYEDITOR=this.BJSNODEGEOMETRYEDITOR||this._getGlobalNodeGeometryEditor(),this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}else this._createNodeEditor(null==e?void 0:e.nodeGeometryEditorConfig),t()})}_createNodeEditor(e){let t=Object.assign({nodeGeometry:this},e);this.BJSNODEGEOMETRYEDITOR.NodeGeometryEditor.Show(t)}build(e=!1,t=!0,i=!1){if(this._buildWasSuccessful=!1,!this.outputBlock)throw"You must define the outputBlock property before building the geometry";let r=r3.F.Now;this._initializeBlock(this.outputBlock,i);let s=new g5;s.buildId=this._buildId,s.verbose=e,this.outputBlock.build(s),t&&(this._buildId=g7._BuildIdGenerator++),this._buildExecutionTime=r3.F.Now-r,s.emitErrors(),this._buildWasSuccessful=!0,this._vertexData=s.vertexData,this.onBuildObservable.notifyObservers(this)}createMesh(e,t=null){if(this._buildWasSuccessful||this.build(),!this._vertexData)return null;let i=new sp.Kj(e,t);return this._vertexData.applyToMesh(i),i._internalMetadata=i._internalMetadata||{},i._internalMetadata.nodeGeometry=this,i}updateMesh(e){return this._buildWasSuccessful||this.build(),!!this._vertexData&&(this._vertexData.applyToMesh(e),e._internalMetadata=e._internalMetadata||{},e._internalMetadata.nodeGeometry=this,e)}_initializeBlock(e,t=!0){for(let i of(e.initialize(),t&&e.autoConfigure(),e._preparationId=this._buildId,-1===this.attachedBlocks.indexOf(e)&&this.attachedBlocks.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._initializeBlock(i,t)}}}clear(){this.outputBlock=null,this.attachedBlocks.length=0}removeBlock(e){let t=this.attachedBlocks.indexOf(e);t>-1&&this.attachedBlocks.splice(t,1),e===this.outputBlock&&(this.outputBlock=null)}parseSerializedObject(e,t=!1){t||this.clear();let i={};for(let t of e.blocks){let e=(0,rg.q)(t.customType);if(e){let r=new e;r._deserialize(t),i[t.id]=r,this.attachedBlocks.push(r)}}for(let e of this.attachedBlocks)if(e.isTeleportOut){let t=e._tempEntryPointUniqueId;if(t){let r=i[t];r&&r.attachToEndpoint(e)}}for(let r=0;re.targetConnectionName)&&!t||this._restoreConnections(n,e,i)}if(e.outputNodeId&&(this.outputBlock=i[e.outputNodeId]),e.locations||e.editorData&&e.editorData.locations){let r=e.locations||e.editorData.locations;for(let e of r)i[e.blockId]&&(e.blockId=i[e.blockId].uniqueId);t&&this.editorData&&this.editorData.locations&&r.concat(this.editorData.locations),e.locations?this.editorData={locations:r}:(this.editorData=e.editorData,this.editorData.locations=r);let s=[];for(let e in i)s[e]=i[e].uniqueId;this.editorData.map=s}this.comment=e.comment}_restoreConnections(e,t,i){for(let r of e.outputs)for(let s of t.blocks){let n=i[s.id];if(n){for(let a of s.inputs)if(i[a.targetBlockId]===e&&a.targetConnectionName===r.name){let e=n.getInputByName(a.inputName);if(!e||e.isConnected)continue;r.connectTo(e,!0),this._restoreConnections(n,t,i);continue}}}}generateCode(){let e=[],t=[],i=["const","var","let"];this.outputBlock&&this._gatherBlocks(this.outputBlock,t);let r=`let nodeGeometry = new BABYLON.NodeGeometry("${this.name||"node geometry"}"); +`;for(let s of t)s.isInput&&-1===e.indexOf(s)&&(r+=s._dumpCode(i,e));return this.outputBlock&&(e=[],r+="// Connections\n"+this.outputBlock._dumpCodeForOutputConnections(e)+"// Output nodes\n"+`nodeGeometry.outputBlock = ${this.outputBlock._codeVariableName}; +`+`nodeGeometry.build(); +`),r}_gatherBlocks(e,t){if(-1===t.indexOf(e)){for(let i of(t.push(e),e.inputs)){let r=i.connectedPoint;if(r){let i=r.ownerBlock;i!==e&&this._gatherBlocks(i,t)}}e.isTeleportOut&&e.entryPoint&&this._gatherBlocks(e.entryPoint,t)}}setToDefault(){this.clear(),this.editorData=null;let e=new g8("Box");e.autoConfigure();let t=new g4("Geometry Output");e.geometry.connectTo(t.geometry),this.outputBlock=t}clone(e){let t=this.serialize(),i=rG.p4.Clone(()=>new g7(e),this);return i.name=e,i.parseSerializedObject(t),i._buildId=this._buildId,i.build(!1),i}serialize(e){let t=e?{}:rG.p4.Serialize(this);t.editorData=JSON.parse(JSON.stringify(this.editorData));let i=[];for(let r of(e?i=e:(t.customType="BABYLON.NodeGeometry",this.outputBlock&&(t.outputNodeId=this.outputBlock.uniqueId)),t.blocks=[],i))t.blocks.push(r.serialize());if(!e)for(let e of this.attachedBlocks)-1===i.indexOf(e)&&t.blocks.push(e.serialize());return t}dispose(){for(let e of this.attachedBlocks)e.dispose();this.attachedBlocks.length=0,this.onBuildObservable.clear()}static CreateDefault(e){let t=new g7(e);return t.setToDefault(),t.build(),t}static Parse(e){let t=rG.p4.Parse(()=>new g7(e.name),e,null);return t.parseSerializedObject(e),t.build(),t}static ParseFromSnippetAsync(e,t,i=!1){return"_BLANK"===e?Promise.resolve(g7.CreateDefault("blank")):new Promise((r,s)=>{let n=new rX.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let a=JSON.parse(JSON.parse(JSON.parse(n.responseText).jsonPayload).nodeGeometry);t||(t=rG.p4.Parse(()=>new g7(e),a,null)),t.parseSerializedObject(a),t.snippetId=e;try{i||t.build(),r(t)}catch(e){s(e)}}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}g7._BuildIdGenerator=0,g7.EditorURL=`${sg.w1._DefaultCdnUrl}/v${sR.D.Version}/nodeGeometryEditor/babylon.nodeGeometryEditor.js`,g7.SnippetUrl="https://snippet.babylonjs.com",(0,sx.gn)([(0,rG.qC)()],g7.prototype,"name",void 0),(0,sx.gn)([(0,rG.qC)("comment")],g7.prototype,"comment",void 0);class g9 extends g3{constructor(e){super(e),this.evaluateContext=!0,this.epsilon=r7.kn,this.registerInput("geometry",iH.Geometry),this.registerOutput("output",iH.Geometry)}getClassName(){return"GeometryOptimizeBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e),i=[],r={};for(let e=0;er[e]),s};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`+`${this._codeVariableName}.epsilon = ${this.epsilon}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.epsilon=this.epsilon,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,this.epsilon=e.epsilon}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],g9.prototype,"evaluateContext",void 0),(0,sx.gn)([nS("Epsilon",tx.Float,"ADVANCED",{notifiers:{rebuild:!0}})],g9.prototype,"epsilon",void 0),(0,rg.H)("BABYLON.GeometryOptimizeBlock",g9);class ve extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("size",iH.Float,!0,1),this.registerInput("width",iH.Float,!0,0),this.registerInput("height",iH.Float,!0,0),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"PlaneBlock"}get size(){return this._inputs[0]}get width(){return this._inputs[1]}get height(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.size.isConnected){if(!this.width.isConnected&&!this.height.isConnected){let e=new g6("Size");e.value=1,e.output.connectTo(this.size);return}if(!this.width.isConnected){let e=new g6("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new g6("Height");e.value=1,e.output.connectTo(this.height)}}}_buildBlock(e){let t={},i=e=>(t.size=this.size.getConnectedValue(e),t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),s9(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],ve.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.PlaneBlock",ve);class vt extends g3{get mesh(){return this._mesh}set mesh(e){this._mesh=e}constructor(e){super(e),this._cachedVertexData=null,this.reverseWindingOrder=!1,this.serializedCachedData=!1,this.registerOutput("geometry",iH.Geometry)}getClassName(){return"MeshBlock"}get isUsingCachedData(){return!this.mesh&&!!this._cachedVertexData}get geometry(){return this._outputs[0]}cleanData(){this._mesh=null,this._cachedVertexData=null}_buildBlock(){if(!this._mesh){this._cachedVertexData?this.geometry._storedValue=this._cachedVertexData.clone():this.geometry._storedValue=null;return}let e=s7.x.ExtractFromMesh(this._mesh,!1,!0);if(this._cachedVertexData=null,this.reverseWindingOrder&&e.indices)for(let t=0;te.clone()}serialize(){let e=super.serialize();return e.serializedCachedData=this.serializedCachedData,this.serializedCachedData&&(this._mesh?e.cachedVertexData=s7.x.ExtractFromMesh(this._mesh,!1,!0).serialize():this._cachedVertexData&&(e.cachedVertexData=this._cachedVertexData.serialize())),e.reverseWindingOrder=this.reverseWindingOrder,e}_deserialize(e){super._deserialize(e),e.cachedVertexData&&(this._cachedVertexData=s7.x.Parse(e.cachedVertexData)),this.serializedCachedData=!!e.serializedCachedData,this.reverseWindingOrder=e.reverseWindingOrder}}(0,sx.gn)([nS("Serialize cached data",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vt.prototype,"serializedCachedData",void 0),(0,rg.H)("BABYLON.MeshBlock",vt);class vi extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",iH.Float,!0,1),this.registerInput("radiusX",iH.Float,!0,0),this.registerInput("radiusY",iH.Float,!0,0),this.registerInput("radiusZ",iH.Float,!0,0),this.registerInput("subdivisions",iH.Int,!0,4),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"IcoSphereBlock"}get radius(){return this._inputs[0]}get radiusX(){return this._inputs[1]}get radiusY(){return this._inputs[2]}get radiusZ(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new g6("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.radiusX=this.radiusX.getConnectedValue(e),t.radiusY=this.radiusY.getConnectedValue(e),t.radiusZ=this.radiusZ.getConnectedValue(e),ad(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vi.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.IcoSphereBlock",vi);class vr extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("segments",iH.Int,!0,32),this.registerInput("diameter",iH.Float,!0,1),this.registerInput("diameterX",iH.Float,!0,0),this.registerInput("diameterY",iH.Float,!0,0),this.registerInput("diameterZ",iH.Float,!0,0),this.registerInput("arc",iH.Float,!0,1),this.registerInput("slice",iH.Float,!0,1),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"SphereBlock"}get segments(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterX(){return this._inputs[2]}get diameterY(){return this._inputs[3]}get diameterZ(){return this._inputs[4]}get arc(){return this._inputs[5]}get slice(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new g6("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},i=e=>(t.segments=this.segments.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterX=this.diameterX.getConnectedValue(e),t.diameterY=this.diameterY.getConnectedValue(e),t.diameterZ=this.diameterZ.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),t.slice=this.slice.getConnectedValue(e),hI(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vr.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.SphereBlock",vr);class vs extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("width",iH.Float,!0,1),this.registerInput("height",iH.Float,!0,1),this.registerInput("subdivisions",iH.Int,!0,1),this.registerInput("subdivisionsX",iH.Int,!0,0),this.registerInput("subdivisionsY",iH.Int,!0,0),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"GridBlock"}get width(){return this._inputs[0]}get height(){return this._inputs[1]}get subdivisions(){return this._inputs[2]}get subdivisionsX(){return this._inputs[3]}get subdivisionsY(){return this._inputs[4]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.width.isConnected){let e=new g6("Width");e.value=1,e.output.connectTo(this.width)}if(!this.height.isConnected){let e=new g6("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},i=e=>(t.width=this.width.getConnectedValue(e),t.height=this.height.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.subdivisionsX=this.subdivisionsX.getConnectedValue(e),t.subdivisionsY=this.subdivisionsY.getConnectedValue(e),l8(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vs.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.GridBlock",vs);class vn extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("diameter",iH.Float,!0,1),this.registerInput("thickness",iH.Float,!0,.5),this.registerInput("tessellation",iH.Int,!0,16),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"TorusBlock"}get diameter(){return this._inputs[0]}get thickness(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new g6("Diameter");e.value=1,e.output.connectTo(this.diameter)}}_buildBlock(e){let t={},i=e=>(t.thickness=this.thickness.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),ht(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vn.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.TorusBlock",vn);class va extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",iH.Float,!0,25),this.registerInput("diameter",iH.Float,!0,1),this.registerInput("diameterTop",iH.Float,!0,-1),this.registerInput("diameterBottom",iH.Float,!0,-1),this.registerInput("subdivisions",iH.Int,!0,1),this.registerInput("tessellation",iH.Int,!0,24),this.registerInput("arc",iH.Float,!0,1),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"CylinderBlock"}get height(){return this._inputs[0]}get diameter(){return this._inputs[1]}get diameterTop(){return this._inputs[2]}get diameterBottom(){return this._inputs[3]}get subdivisions(){return this._inputs[4]}get tessellation(){return this._inputs[5]}get arc(){return this._inputs[6]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.diameter.isConnected){let e=new g6("Diameter");e.value=1,e.output.connectTo(this.diameter)}if(!this.height.isConnected){let e=new g6("Height");e.value=1,e.output.connectTo(this.height)}}_buildBlock(e){let t={},i=e=>(t.height=this.height.getConnectedValue(e),t.diameter=this.diameter.getConnectedValue(e),t.diameterTop=this.diameterTop.getConnectedValue(e),t.diameterBottom=this.diameterBottom.getConnectedValue(e),-1===t.diameterTop&&(t.diameterTop=t.diameter),-1===t.diameterBottom&&(t.diameterBottom=t.diameter),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),hS(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],va.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.CylinderBlock",va);class vo extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("height",iH.Float,!0,1),this.registerInput("radius",iH.Float,!0,.25),this.registerInput("tessellation",iH.Int,!0,16),this.registerInput("subdivisions",iH.Int,!0,2),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"CapsuleBlock"}get height(){return this._inputs[0]}get radius(){return this._inputs[1]}get tessellation(){return this._inputs[2]}get subdivisions(){return this._inputs[3]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.height.isConnected){let e=new g6("Height");e.value=1,e.output.connectTo(this.height)}if(!this.radius.isConnected){let e=new g6("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.height=this.height.getConnectedValue(e),t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.subdivisions=this.subdivisions.getConnectedValue(e),hD(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vo.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.CapsuleBlock",vo);class vl extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("radius",iH.Float,!0,.5),this.registerInput("tessellation",iH.Int,!0,64),this.registerInput("arc",iH.Float,!0,1),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"DiscBlock"}get radius(){return this._inputs[0]}get tessellation(){return this._inputs[1]}get arc(){return this._inputs[2]}get geometry(){return this._outputs[0]}autoConfigure(){if(!this.radius.isConnected){let e=new g6("Radius");e.value=.2,e.output.connectTo(this.radius)}}_buildBlock(e){let t={},i=e=>(t.radius=this.radius.getConnectedValue(e),t.tessellation=this.tessellation.getConnectedValue(e),t.arc=this.arc.getConnectedValue(e),hF(t));if(this.evaluateContext)this.geometry._storedFunction=i;else{let t=i(e);this.geometry._storedFunction=()=>(this.geometry._executionCount=1,t.clone())}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vl.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.DiscBlock",vl);class vh extends g3{constructor(e){super(e),this.registerOutput("geometry",iH.Geometry)}getClassName(){return"NullBlock"}get geometry(){return this._outputs[0]}_buildBlock(){this.geometry._storedValue=null}}(0,rg.H)("BABYLON.NullBlock",vh);class vu extends g3{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iH.Geometry),this.registerInput("positions",iH.Vector3),this.registerOutput("output",iH.Geometry)}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"SetPositionsBlock"}get geometry(){return this._inputs[0]}get positions(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.positions.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.normals.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.normals||(this._vertexData.normals=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.uvs.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}let t=[],i=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.colors.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.colors||(this._vertexData.colors=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndex{if(e.pushExecutionContext(this),this._vertexData=this.geometry.getConnectedValue(e),this._vertexData&&(this._vertexData=this._vertexData.clone()),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=null;return}if(!this.tangents.isConnected){e.restoreGeometryContext(),e.restoreExecutionContext(),this.output._storedValue=this._vertexData;return}this._vertexData.tangents||(this._vertexData.tangents=[]);let t=this._vertexData.positions.length/3;for(this._currentIndex=0;this._currentIndext.getConnectedValue(e)+i.getConnectedValue(e):e=>t.getConnectedValue(e).add(e.adapt(i,t.type));break;case iq.Subtract:e=r?e=>t.getConnectedValue(e)-i.getConnectedValue(e):e=>t.getConnectedValue(e).subtract(e.adapt(i,t.type));break;case iq.Multiply:e=r?e=>t.getConnectedValue(e)*i.getConnectedValue(e):e=>t.getConnectedValue(e).multiply(e.adapt(i,t.type));break;case iq.Divide:e=r?e=>t.getConnectedValue(e)/i.getConnectedValue(e):e=>t.getConnectedValue(e).divide(e.adapt(i,t.type));break;case iq.Min:if(r)e=e=>Math.min(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case iH.Vector2:e=e=>rf.FM.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iH.Vector3:e=e=>rf.P.Minimize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iH.Vector4:e=e=>rf.Lt.Minimize(t.getConnectedValue(e),e.adapt(i,t.type))}break;case iq.Max:if(r)e=e=>Math.max(t.getConnectedValue(e),i.getConnectedValue(e));else switch(t.type){case iH.Vector2:e=e=>rf.FM.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iH.Vector3:e=e=>rf.P.Maximize(t.getConnectedValue(e),e.adapt(i,t.type));break;case iH.Vector4:e=e=>rf.Lt.Maximize(t.getConnectedValue(e),e.adapt(i,t.type))}}this.output._storedFunction=i=>t.type===iH.Int?0|e(i):e(i)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.MathBlockOperations.${iq[this.operation]}; +`}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}}(0,sx.gn)([nS("Operation",tx.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Add",value:iq.Add},{label:"Subtract",value:iq.Subtract},{label:"Multiply",value:iq.Multiply},{label:"Divide",value:iq.Divide},{label:"Max",value:iq.Max},{label:"Min",value:iq.Min}]})],vf.prototype,"operation",void 0),(0,rg.H)("BABYLON.MathBlock",vf);class vm extends g3{constructor(e){super(e),this.registerInput("value",iH.AutoDetect),this.registerInput("fromMin",iH.Float,!0,0),this.registerInput("fromMax",iH.Float,!0,1),this.registerInput("toMin",iH.Float,!0,0),this.registerInput("toMax",iH.Float,!0,1),this.registerOutput("output",iH.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iH.Vector2),this._inputs[0].excludedConnectionPointTypes.push(iH.Vector3),this._inputs[0].excludedConnectionPointTypes.push(iH.Vector4),this._inputs[0].excludedConnectionPointTypes.push(iH.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iH.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iH.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"MapRangeBlock"}get value(){return this._inputs[0]}get fromMin(){return this._inputs[1]}get fromMax(){return this._inputs[2]}get toMin(){return this._inputs[3]}get toMax(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.output._storedFunction=e=>{let t=this.value.getConnectedValue(e),i=this.fromMin.getConnectedValue(e),r=this.fromMax.getConnectedValue(e),s=this.toMin.getConnectedValue(e),n=(t-i)/(r-i)*(this.toMax.getConnectedValue(e)-s)+s;return this.output.type===iH.Int?Math.floor(n):n}}}(0,rg.H)("BABYLON.MapRangeBlock",vm),(eK=iK||(iK={}))[eK.Equal=0]="Equal",eK[eK.NotEqual=1]="NotEqual",eK[eK.LessThan=2]="LessThan",eK[eK.GreaterThan=3]="GreaterThan",eK[eK.LessOrEqual=4]="LessOrEqual",eK[eK.GreaterOrEqual=5]="GreaterOrEqual",eK[eK.Xor=6]="Xor",eK[eK.Or=7]="Or",eK[eK.And=8]="And";class vg extends g3{constructor(e){super(e),this.test=iK.Equal,this.registerInput("left",iH.Float),this.registerInput("right",iH.Float,!0,0),this.registerInput("ifTrue",iH.AutoDetect,!0,1),this.registerInput("ifFalse",iH.AutoDetect,!0,0),this.registerOutput("output",iH.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[2],this._outputs[0]._defaultConnectionPointType=iH.Float,this._inputs[0].acceptedConnectionPointTypes.push(iH.Int),this._inputs[1].acceptedConnectionPointTypes.push(iH.Int),this._linkConnectionTypes(2,3)}getClassName(){return"ConditionBlock"}get left(){return this._inputs[0]}get right(){return this._inputs[1]}get ifTrue(){return this._inputs[2]}get ifFalse(){return this._inputs[3]}get output(){return this._outputs[0]}_buildBlock(){if(!this.left.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let e=e=>{let t=this.left.getConnectedValue(e),i=this.right.getConnectedValue(e),r=!1;switch(this.test){case iK.Equal:r=rk.R.WithinEpsilon(t,i,r7.kn);break;case iK.NotEqual:r=t!==i;break;case iK.LessThan:r=ti;break;case iK.LessOrEqual:r=t<=i;break;case iK.GreaterOrEqual:r=t>=i;break;case iK.Xor:r=!!t&&!i||!t&&!!i;break;case iK.Or:r=!!t||!!i;break;case iK.And:r=!!t&&!!i}return r};this.output._storedFunction=t=>e(t)?this.ifTrue.getConnectedValue(t):this.ifFalse.getConnectedValue(t)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.test = BABYLON.ConditionBlockTests.${iK[this.test]}; +`}serialize(){let e=super.serialize();return e.test=this.test,e}_deserialize(e){super._deserialize(e),this.test=e.test}}(0,sx.gn)([nS("Test",tx.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Equal",value:iK.Equal},{label:"NotEqual",value:iK.NotEqual},{label:"LessThan",value:iK.LessThan},{label:"GreaterThan",value:iK.GreaterThan},{label:"LessOrEqual",value:iK.LessOrEqual},{label:"GreaterOrEqual",value:iK.GreaterOrEqual},{label:"Xor",value:iK.Xor},{label:"Or",value:iK.Or},{label:"And",value:iK.And}]})],vg.prototype,"test",void 0),(0,rg.H)("BABYLON.ConditionBlock",vg),(e$=i$||(i$={}))[e$.None=0]="None",e$[e$.LoopID=1]="LoopID",e$[e$.InstanceID=2]="InstanceID";class vv extends g3{constructor(e){super(e),this._currentLockId=-1,this.lockMode=i$.None,this.registerInput("min",iH.AutoDetect),this.registerInput("max",iH.AutoDetect),this.registerOutput("output",iH.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iH.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iH.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iH.Texture),this._inputs[1].excludedConnectionPointTypes.push(iH.Matrix),this._inputs[1].excludedConnectionPointTypes.push(iH.Geometry),this._inputs[1].excludedConnectionPointTypes.push(iH.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"RandomBlock"}get min(){return this._inputs[0]}get max(){return this._inputs[1]}get output(){return this._outputs[0]}autoConfigure(){if(!this.min.isConnected){let e=new g6("Min");e.value=0,e.output.connectTo(this.min)}if(!this.max.isConnected){let e=new g6("Max");e.value=1,e.output.connectTo(this.max)}}_buildBlock(){let e=null;switch(this._currentLockId=-1,this.min.type){case iH.Int:case iH.Float:e=e=>{let t=this.min.getConnectedValue(e)||0;return t+Math.random()*((this.max.getConnectedValue(e)||0)-t)};break;case iH.Vector2:e=e=>{let t=this.min.getConnectedValue(e)||rf.FM.Zero(),i=this.max.getConnectedValue(e)||rf.FM.Zero();return new rf.FM(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y))};break;case iH.Vector3:e=e=>{let t=this.min.getConnectedValue(e)||rf.P.Zero(),i=this.max.getConnectedValue(e)||rf.P.Zero();return new rf.P(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z))};break;case iH.Vector4:e=e=>{let t=this.min.getConnectedValue(e)||rf.Lt.Zero(),i=this.max.getConnectedValue(e)||rf.Lt.Zero();return new rf.Lt(t.x+Math.random()*(i.x-t.x),t.y+Math.random()*(i.y-t.y),t.z+Math.random()*(i.z-t.z),t.w+Math.random()*(i.w-t.w))}}this.lockMode!==i$.None&&e?this.output._storedFunction=t=>{let i=0;switch(this.lockMode){case i$.InstanceID:i=t.getContextualValue(ij.InstanceID,!0)||0;break;case i$.LoopID:i=t.getContextualValue(ij.LoopID,!0)||0}return(this._currentLockId!==i||this.lockMode===i$.None)&&(this._currentLockId=i,this.output._storedValue=e(t)),this.output._storedValue}:this.output._storedFunction=e}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.lockMode = BABYLON.RandomBlockLocks.${i$[this.lockMode]}; +`}serialize(){let e=super.serialize();return e.lockMode=this.lockMode,e}_deserialize(e){super._deserialize(e),this.lockMode=e.lockMode}}(0,sx.gn)([nS("LockMode",tx.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"None",value:i$.None},{label:"LoopID",value:i$.LoopID},{label:"InstanceID",value:i$.InstanceID}]})],vv.prototype,"lockMode",void 0),(0,rg.H)("BABYLON.RandomBlock",vv);class vx extends g3{constructor(e){super(e),this.registerInput("offset",iH.Vector3,!0,rf.P.Zero()),this.registerInput("scale",iH.Float,!0,1),this.registerInput("octaves",iH.Float,!0,2,0,16),this.registerInput("roughness",iH.Float,!0,.5,0,1),this.registerOutput("output",iH.Float)}getClassName(){return"NoiseBlock"}get offset(){return this._inputs[0]}get scale(){return this._inputs[1]}get octaves(){return this._inputs[2]}get roughness(){return this._inputs[3]}get output(){return this._outputs[0]}_negateIf(e,t){return 0!==t?-e:e}_noiseGrad(e,t,i,r){let s=15&e,n=s<8?t:i,a=s<4?i:12===s||14==s?t:r;return this._negateIf(n,s&n)+this._negateIf(a,2&s)}_fade(e){return e*e*e*(e*(6*e-15)+10)}_hashBitRotate(e,t){return e<>32-t}_hash(e,t,i){let r,s,n;return r=s=n=3735928584,n+=i,s+=t,r+=e,n^=s,n-=this._hashBitRotate(s,14),r^=n,r-=this._hashBitRotate(n,11),s^=r,s-=this._hashBitRotate(r,25),n^=s,n-=this._hashBitRotate(s,16),r^=n,r-=this._hashBitRotate(n,4),s^=r,s-=this._hashBitRotate(r,14),n^=s,n-=this._hashBitRotate(s,24)}_mix(e,t,i,r,s,n,a,o,l,h,u){let c=1-l,d=1-h;return(1-u)*(d*(e*c+t*l)+h*(i*c+r*l))+u*(d*(s*c+n*l)+h*(a*c+o*l))}_perlinNoise(e){let t=(0|e.x)-(e.x<0?1:0),i=(0|e.y)-(e.y<0?1:0),r=(0|e.z)-(e.z<0?1:0),s=e.x-t,n=e.y-i,a=e.z-r,o=this._fade(s),l=this._fade(n),h=this._fade(a);return this._mix(this._noiseGrad(this._hash(t,i,r),s,n,a),this._noiseGrad(this._hash(t+1,i,r),s-1,n,a),this._noiseGrad(this._hash(t,i+1,r),s,n-1,a),this._noiseGrad(this._hash(t+1,i+1,r),s-1,n-1,a),this._noiseGrad(this._hash(t,i,r+1),s,n,a-1),this._noiseGrad(this._hash(t+1,i,r+1),s-1,n,a-1),this._noiseGrad(this._hash(t,i+1,r+1),s,n-1,a-1),this._noiseGrad(this._hash(t+1,i+1,r+1),s-1,n-1,a-1),o,l,h)}_perlinSigned(e){return .982*this._perlinNoise(e)}_perlin(e){return this._perlinSigned(e)/2+.5}noise(e,t,i,r,s){let n=new rf.P(i.x*s+r.x,i.y*s+r.y,i.z*s+r.z),a=1,o=1,l=0,h=0,u=0|(e=rk.R.Clamp(e,0,15));for(let e=0;e<=u;e++)h+=this._perlin(n.scale(a))*o,l+=o,o*=rk.R.Clamp(t,0,1),a*=2;let c=e-Math.floor(e);if(0==c)return h/l;let d=h+this._perlin(n.scale(a))*o;return(1-c)*(h/=l)+c*(d/=l+o)}_buildBlock(){this.output._storedFunction=e=>{let t=e.getContextualValue(ij.Positions),i=this.octaves.getConnectedValue(e),r=this.roughness.getConnectedValue(e),s=this.offset.getConnectedValue(e),n=this.scale.getConnectedValue(e);return this.noise(i,r,t,s,n)}}}(0,rg.H)("BABYLON.NoiseBlock",vx);class vT extends g3{constructor(e){super(e),this.evaluateContext=!1,this.registerInput("geometry0",iH.Geometry),this.registerInput("geometry1",iH.Geometry,!0),this.registerInput("geometry2",iH.Geometry,!0),this.registerInput("geometry3",iH.Geometry,!0),this.registerInput("geometry4",iH.Geometry,!0),this.registerOutput("output",iH.Geometry)}getClassName(){return"MergeGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{let t=this.geometry0.getConnectedValue(e),i=[];if(!t)return null;if(t=t.clone(),this.geometry1.isConnected){let t=this.geometry1.getConnectedValue(e);t&&i.push(t)}if(this.geometry2.isConnected){let t=this.geometry2.getConnectedValue(e);t&&i.push(t)}if(this.geometry3.isConnected){let t=this.geometry3.getConnectedValue(e);t&&i.push(t)}if(this.geometry4.isConnected){let t=this.geometry4.getConnectedValue(e);t&&i.push(t)}return i.length&&t&&(t=t.merge(i,!0,!1,!0,!0)),t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vT.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.MergeGeometryBlock",vT);class vS extends g3{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry0",iH.Geometry,!0),this.registerInput("geometry1",iH.Geometry,!0),this.registerInput("geometry2",iH.Geometry,!0),this.registerInput("geometry3",iH.Geometry,!0),this.registerInput("geometry4",iH.Geometry,!0),this.registerInput("geometry5",iH.Geometry,!0),this.registerInput("geometry6",iH.Geometry,!0),this.registerInput("geometry7",iH.Geometry,!0),this.registerInput("geometry8",iH.Geometry,!0),this.registerInput("geometry9",iH.Geometry,!0),this.registerOutput("output",iH.Geometry),this._outputs[0]._typeConnectionSource=this._inputs[0],this._linkConnectionTypes(0,1)}getClassName(){return"GeometryCollectionBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get geometry2(){return this._inputs[2]}get geometry3(){return this._inputs[3]}get geometry4(){return this._inputs[4]}get geometry5(){return this._inputs[5]}get geometry6(){return this._inputs[6]}get geometry7(){return this._inputs[7]}get geometry8(){return this._inputs[8]}get geometry9(){return this._inputs[9]}get output(){return this._outputs[0]}_storeGeometry(e,t,i,r){if(e.isConnected){let s=e.getConnectedValue(t);s&&(s.metadata=s.metadata||{},s.metadata.collectionId=i,r.push(s))}}_buildBlock(e){let t=e=>{let t=[];return(this._storeGeometry(this.geometry0,e,0,t),this._storeGeometry(this.geometry1,e,1,t),this._storeGeometry(this.geometry2,e,2,t),this._storeGeometry(this.geometry3,e,3,t),this._storeGeometry(this.geometry4,e,4,t),this._storeGeometry(this.geometry5,e,5,t),this._storeGeometry(this.geometry6,e,6,t),this._storeGeometry(this.geometry7,e,7,t),this._storeGeometry(this.geometry8,e,8,t),this._storeGeometry(this.geometry9,e,9,t),t.length)?t[Math.round(Math.random()*(t.length-1))]:null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vS.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.GeometryCollectionBlock",vS);class vE extends g3{constructor(e){super(e),this.registerInput("input",iH.AutoDetect),this.registerOutput("output",iH.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0]}get buildExecutionTime(){return 0}getClassName(){return"GeometryElbowBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=this._outputs[0],i=this._inputs[0];t._storedFunction=e=>i.getConnectedValue(e)}}(0,rg.H)("BABYLON.GeometryElbowBlock",vE);class vC extends g3{constructor(e){super(e),this.registerInput("geometry",iH.Geometry),this.registerOutput("output",iH.Geometry)}getClassName(){return"ComputeNormalsBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.geometry.isConnected)return null;let t=this.geometry.getConnectedValue(e);return t.normals||(t.normals=[]),s7.x.ComputeNormals(t.positions,t.indices,t.normals),t}}}(0,rg.H)("BABYLON.ComputeNormalsBlock",vC);class vb extends g3{constructor(e){super(e),this.registerInput("xyzw ",iH.Vector4,!0),this.registerInput("xyz ",iH.Vector3,!0),this.registerInput("xy ",iH.Vector2,!0),this.registerInput("zw ",iH.Vector2,!0),this.registerInput("x ",iH.Float,!0),this.registerInput("y ",iH.Float,!0),this.registerInput("z ",iH.Float,!0),this.registerInput("w ",iH.Float,!0),this.registerOutput("xyzw",iH.Vector4),this.registerOutput("xyz",iH.Vector3),this.registerOutput("xy",iH.Vector2),this.registerOutput("zw",iH.Vector2),this.registerOutput("x",iH.Float),this.registerOutput("y",iH.Float),this.registerOutput("z",iH.Float),this.registerOutput("w",iH.Float)}getClassName(){return"VectorConverterBlock"}get xyzwIn(){return this._inputs[0]}get xyzIn(){return this._inputs[1]}get xyIn(){return this._inputs[2]}get zwIn(){return this._inputs[3]}get xIn(){return this._inputs[4]}get yIn(){return this._inputs[5]}get zIn(){return this._inputs[6]}get wIn(){return this._inputs[7]}get xyzwOut(){return this._outputs[0]}get xyzOut(){return this._outputs[1]}get xyOut(){return this._outputs[2]}get zwOut(){return this._outputs[3]}get xOut(){return this._outputs[4]}get yOut(){return this._outputs[5]}get zOut(){return this._outputs[6]}get wOut(){return this._outputs[7]}_inputRename(e){return"xyzw "===e?"xyzwIn":"xyz "===e?"xyzIn":"xy "===e?"xyIn":"zw "===e?"zwIn":"x "===e?"xIn":"y "===e?"yIn":"z "===e?"zIn":"w "===e?"wIn":e}_outputRename(e){switch(e){case"x":return"xOut";case"y":return"yOut";case"z":return"zOut";case"w":return"wOut";case"xy":return"xyOut";case"zw":return"zwOut";case"xyz":return"xyzOut";case"xyzw":return"xyzwOut";default:return e}}_buildBlock(e){super._buildBlock(e);let t=this.xIn,i=this.yIn,r=this.zIn,s=this.wIn,n=this.xyIn,a=this.zwIn,o=this.xyzIn,l=this.xyzwIn,h=this.xyzwOut,u=this.xyzOut,c=this.xyOut,d=this.zwOut,p=this.xOut,_=this.yOut,f=this.zOut,m=this.wOut,g=e=>{if(l.isConnected)return l.getConnectedValue(e);let h=0,u=0,c=0,d=0;if(t.isConnected&&(h=t.getConnectedValue(e)),i.isConnected&&(u=i.getConnectedValue(e)),r.isConnected&&(c=r.getConnectedValue(e)),s.isConnected&&(d=s.getConnectedValue(e)),n.isConnected){let t=n.getConnectedValue(e);t&&(h=t.x,u=t.y)}if(a.isConnected){let t=a.getConnectedValue(e);t&&(c=t.x,d=t.y)}if(o.isConnected){let t=o.getConnectedValue(e);t&&(h=t.x,u=t.y,c=t.z)}return new rf.Lt(h,u,c,d)};h._storedFunction=e=>g(e),u._storedFunction=e=>{let t=g(e);return new rf.P(t.x,t.y,t.z)},c._storedFunction=e=>{let t=g(e);return new rf.FM(t.x,t.y)},d._storedFunction=e=>{let t=g(e);return new rf.FM(t.z,t.w)},p._storedFunction=e=>g(e).x,_._storedFunction=e=>g(e).y,f._storedFunction=e=>g(e).z,m._storedFunction=e=>g(e).w}}(0,rg.H)("BABYLON.VectorConverterBlock",vb);class vy extends g3{constructor(e){super(e),this.registerInput("input",iH.AutoDetect),this.registerOutput("output",iH.BasedOnInput),this._inputs[0].excludedConnectionPointTypes.push(iH.Float),this._inputs[0].excludedConnectionPointTypes.push(iH.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iH.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iH.Texture),this._outputs[0]._typeConnectionSource=this._inputs[0]}getClassName(){return"NormalizeVectorBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(super._buildBlock(e),this.output._storedFunction=null,!this.input.isConnected){this.output._storedValue=null;return}this.output._storedFunction=e=>this.input.getConnectedValue(e).normalize()}}(0,rg.H)("BABYLON.NormalizeVectorBlock",vy);class vA extends g3{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("geometry",iH.Geometry),this.registerInput("id",iH.Int,!0,0),this.registerOutput("output",iH.Geometry),this.id.acceptedConnectionPointTypes.push(iH.Float)}getClassName(){return"SetMaterialIDBlock"}get geometry(){return this._inputs[0]}get id(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.geometry.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let t=e=>{let t=this.geometry.getConnectedValue(e);if(!t||!t.indices||!t.positions)return t;let i=new s7.D;return i.materialIndex=0|this.id.getConnectedValue(e),i.indexStart=0,i.indexCount=t.indices.length,i.verticesStart=0,i.verticesCount=t.positions.length/3,t.materialInfos=[i],t};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vA.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.SetMaterialIDBlock",vA),(eQ=iQ||(iQ={}))[eQ.Cos=0]="Cos",eQ[eQ.Sin=1]="Sin",eQ[eQ.Abs=2]="Abs",eQ[eQ.Exp=3]="Exp",eQ[eQ.Round=4]="Round",eQ[eQ.Floor=5]="Floor",eQ[eQ.Ceiling=6]="Ceiling",eQ[eQ.Sqrt=7]="Sqrt",eQ[eQ.Log=8]="Log",eQ[eQ.Tan=9]="Tan",eQ[eQ.ArcTan=10]="ArcTan",eQ[eQ.ArcCos=11]="ArcCos",eQ[eQ.ArcSin=12]="ArcSin",eQ[eQ.Sign=13]="Sign",eQ[eQ.Negate=14]="Negate",eQ[eQ.OneMinus=15]="OneMinus",eQ[eQ.Reciprocal=16]="Reciprocal",eQ[eQ.ToDegrees=17]="ToDegrees",eQ[eQ.ToRadians=18]="ToRadians";class vR extends g3{constructor(e){super(e),this.operation=iQ.Cos,this.registerInput("input",iH.AutoDetect),this.registerOutput("output",iH.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iH.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iH.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iH.Texture)}getClassName(){return"GeometryTrigonometryBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e);let t=null;switch(this.operation){case iQ.Cos:t=e=>Math.cos(e);break;case iQ.Sin:t=e=>Math.sin(e);break;case iQ.Abs:t=e=>Math.abs(e);break;case iQ.Exp:t=e=>Math.exp(e);break;case iQ.Round:t=e=>Math.round(e);break;case iQ.Floor:t=e=>Math.floor(e);break;case iQ.Ceiling:t=e=>Math.ceil(e);break;case iQ.Sqrt:t=e=>Math.sqrt(e);break;case iQ.Log:t=e=>Math.log(e);break;case iQ.Tan:t=e=>Math.tan(e);break;case iQ.ArcTan:t=e=>Math.atan(e);break;case iQ.ArcCos:t=e=>Math.acos(e);break;case iQ.ArcSin:t=e=>Math.asin(e);break;case iQ.Sign:t=e=>Math.sign(e);break;case iQ.Negate:t=e=>-e;break;case iQ.OneMinus:t=e=>1-e;break;case iQ.Reciprocal:t=e=>1/e;break;case iQ.ToRadians:t=e=>e*Math.PI/180;break;case iQ.ToDegrees:t=e=>180*e/Math.PI}if(!t){this.input._storedFunction=null,this.input._storedValue=null;return}switch(this.input.type){case iH.Int:case iH.Float:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return t(i)};break;case iH.Vector2:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rf.FM(t(i.x),t(i.y))};break;case iH.Vector3:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rf.P(t(i.x),t(i.y),t(i.z))};break;case iH.Vector4:this.output._storedFunction=e=>{let i=this.input.getConnectedValue(e);return new rf.Lt(t(i.x),t(i.y),t(i.z),t(i.w))}}return this}serialize(){let e=super.serialize();return e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.operation=e.operation}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.operation = BABYLON.GeometryTrigonometryBlockOperations.${iQ[this.operation]}; +`}}(0,sx.gn)([nS("Operation",tx.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Cos",value:iQ.Cos},{label:"Sin",value:iQ.Sin},{label:"Abs",value:iQ.Abs},{label:"Exp",value:iQ.Exp},{label:"Round",value:iQ.Round},{label:"Floor",value:iQ.Floor},{label:"Ceiling",value:iQ.Ceiling},{label:"Sqrt",value:iQ.Sqrt},{label:"Log",value:iQ.Log},{label:"Tan",value:iQ.Tan},{label:"ArcTan",value:iQ.ArcTan},{label:"ArcCos",value:iQ.ArcCos},{label:"ArcSin",value:iQ.ArcSin},{label:"Sign",value:iQ.Sign},{label:"Negate",value:iQ.Negate},{label:"OneMinus",value:iQ.OneMinus},{label:"Reciprocal",value:iQ.Reciprocal},{label:"ToDegrees",value:iQ.ToDegrees},{label:"ToRadians",value:iQ.ToRadians}]})],vR.prototype,"operation",void 0),(0,rg.H)("BABYLON.GeometryTrigonometryBlock",vR);class vP extends g3{constructor(e){super(e),this._rotationMatrix=new rf.y3,this._scalingMatrix=new rf.y3,this._translationMatrix=new rf.y3,this._scalingRotationMatrix=new rf.y3,this._transformMatrix=new rf.y3,this.evaluateContext=!0,this.registerInput("value",iH.AutoDetect),this.registerInput("matrix",iH.Matrix,!0),this.registerInput("translation",iH.Vector3,!0,rf.P.Zero()),this.registerInput("rotation",iH.Vector3,!0,rf.P.Zero()),this.registerInput("scaling",iH.Vector3,!0,rf.P.One()),this.registerOutput("output",iH.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iH.Float),this._inputs[0].excludedConnectionPointTypes.push(iH.Matrix),this._inputs[0].excludedConnectionPointTypes.push(iH.Texture)}getClassName(){return"GeometryTransformBlock"}get value(){return this._inputs[0]}get matrix(){return this._inputs[1]}get translation(){return this._inputs[2]}get rotation(){return this._inputs[3]}get scaling(){return this._inputs[4]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.value.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}let t=e=>{let t;let i=this.value.getConnectedValue(e);if(!i)return null;if(this.matrix.isConnected)t=this.matrix.getConnectedValue(e);else{let i=this.scaling.getConnectedValue(e),r=this.rotation.getConnectedValue(e),s=this.translation.getConnectedValue(e);rf.y3.ScalingToRef(i.x,i.y,i.z,this._scalingMatrix),rf.y3.RotationYawPitchRollToRef(r.y,r.x,r.z,this._rotationMatrix),rf.y3.TranslationToRef(s.x,s.y,s.z,this._translationMatrix),this._scalingMatrix.multiplyToRef(this._rotationMatrix,this._scalingRotationMatrix),this._scalingRotationMatrix.multiplyToRef(this._translationMatrix,this._transformMatrix),t=this._transformMatrix}switch(this.value.type){case iH.Geometry:{let e=i.clone();return e.transform(t),e}case iH.Vector2:return rf.FM.Transform(i,t);case iH.Vector3:return rf.P.TransformCoordinates(i,t);case iH.Vector4:return rf.Lt.TransformCoordinates(i,t)}return null};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vP.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.GeometryTransformBlock",vP);class vI extends g3{constructor(e){super(e),this.registerInput("angle",iH.Float,!1,0),this.registerOutput("matrix",iH.Matrix)}getClassName(){return"RotationXBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new g6("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rf.y3.RotationX(this.angle.getConnectedValue(e))}}(0,rg.H)("BABYLON.RotationXBlock",vI);class vM extends g3{constructor(e){super(e),this.registerInput("angle",iH.Float,!1,0),this.registerOutput("matrix",iH.Matrix)}getClassName(){return"RotationYBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new g6("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rf.y3.RotationY(this.angle.getConnectedValue(e))}}(0,rg.H)("BABYLON.RotationYBlock",vM);class vD extends g3{constructor(e){super(e),this.registerInput("angle",iH.Float,!1,0),this.registerOutput("matrix",iH.Matrix)}getClassName(){return"RotationZBlock"}get angle(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.angle.isConnected){let e=new g6("Angle");e.value=0,e.output.connectTo(this.angle)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>rf.y3.RotationZ(this.angle.getConnectedValue(e))}}(0,rg.H)("BABYLON.RotationZBlock",vD);class vO extends g3{constructor(e){super(e),this.registerInput("scale",iH.Vector3,!1,rf.P.One()),this.registerOutput("matrix",iH.Matrix)}getClassName(){return"ScalingBlock"}get scale(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.scale.isConnected){let e=new g6("Scale");e.value=new rf.P(1,1,1),e.output.connectTo(this.scale)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.scale.getConnectedValue(e);return rf.y3.Scaling(t.x,t.y,t.z)}}}(0,rg.H)("BABYLON.ScalingBlock",vO);class vN extends g3{constructor(e){super(e),this.registerInput("source",iH.Vector3,!0,rf.P.Up()),this.registerInput("target",iH.Vector3,!0,rf.P.Left()),this.registerOutput("matrix",iH.Matrix)}getClassName(){return"AlignBlock"}get source(){return this._inputs[0]}get target(){return this._inputs[1]}get matrix(){return this._outputs[0]}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.source.getConnectedValue(e).clone(),i=this.target.getConnectedValue(e).clone(),r=new rf.y3;return t.normalize(),i.normalize(),rf.y3.RotationAlignToRef(t,i,r,!0),r}}}(0,rg.H)("BABYLON.AlignBlock",vN);class vF extends g3{constructor(e){super(e),this.registerInput("translation",iH.Vector3,!1,rf.P.Zero()),this.registerOutput("matrix",iH.Matrix)}getClassName(){return"TranslationBlock"}get translation(){return this._inputs[0]}get matrix(){return this._outputs[0]}autoConfigure(){if(!this.translation.isConnected){let e=new g6("Translation");e.value=new rf.P(0,0,0),e.output.connectTo(this.translation)}}_buildBlock(e){super._buildBlock(e),this.matrix._storedFunction=e=>{let t=this.translation.getConnectedValue(e);return rf.y3.Translation(t.x,t.y,t.z)}}}(0,rg.H)("BABYLON.TranslationBlock",vF);class vL extends g3{constructor(e){super(e),this._indexTranslation=null,this.evaluateContext=!0,this.removeDuplicatedPositions=!0,this.registerInput("geometry",iH.Geometry),this.registerInput("instance",iH.Geometry,!0),this.registerInput("density",iH.Float,!0,1,0,1),this.registerInput("matrix",iH.Matrix,!0),this.registerInput("rotation",iH.Vector3,!0,rf.P.Zero()),this.registerInput("scaling",iH.Vector3,!0,rf.P.One()),this.scaling.acceptedConnectionPointTypes.push(iH.Float),this.registerOutput("output",iH.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return this._indexTranslation?this._indexTranslation[this._currentIndex]:this._currentIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateOnVerticesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get density(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=this._vertexData.positions.length/3,i=[],r=new rf.P,s=[],n=this._vertexData.positions;if(this._currentLoopIndex=0,this.removeDuplicatedPositions){for(this._indexTranslation={},this._currentIndex=0;this._currentIndexs)continue;r.fromArray(n,3*this._currentIndex);let a=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(a,r,t,i)}else{let t=e.adaptInput(this.scaling,iH.Vector3,rf.P.OneReadOnly),s=this.rotation.getConnectedValue(e)||rf.P.ZeroReadOnly;e._instantiate(a,r,s,t,i)}this._currentLoopIndex++}if(e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),!i.length)return null;if(1===i.length)this._vertexData=i[0];else{let e=i.splice(0,1)[0];this._vertexData=e.merge(i,!0,!1,!0,!0)}return this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.removeDuplicatedPositions = ${this.removeDuplicatedPositions?"true":"false"}; +`+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.removeDuplicatedPositions=this.removeDuplicatedPositions,e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),this.removeDuplicatedPositions=e.removeDuplicatedPositions,void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vL.prototype,"evaluateContext",void 0),(0,sx.gn)([nS("Remove duplicated positions",tx.Boolean,"ADVANCED",{notifiers:{update:!0}})],vL.prototype,"removeDuplicatedPositions",void 0),(0,rg.H)("BABYLON.InstantiateOnVerticesBlock",vL);class vw extends g3{constructor(e){super(e),this._currentPosition=new rf.P,this._currentUV=new rf.FM,this._vertex0=new rf.P,this._vertex1=new rf.P,this._vertex2=new rf.P,this._tempVector0=new rf.P,this._tempVector1=new rf.P,this._uv0=new rf.FM,this._uv1=new rf.FM,this._uv2=new rf.FM,this.evaluateContext=!0,this.registerInput("geometry",iH.Geometry),this.registerInput("instance",iH.Geometry,!0),this.registerInput("count",iH.Int,!0,256),this.registerInput("matrix",iH.Matrix,!0),this.registerInput("rotation",iH.Vector3,!0,rf.P.Zero()),this.registerInput("scaling",iH.Vector3,!0,rf.P.One()),this.scaling.acceptedConnectionPointTypes.push(iH.Float),this.registerOutput("output",iH.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return this._currentFaceIndex}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getOverrideNormalsContextualValue(){return this._vertex1.subtractToRef(this._vertex0,this._tempVector0),this._vertex2.subtractToRef(this._vertex1,this._tempVector1),this._tempVector0.normalize(),this._tempVector1.normalize(),rf.P.Cross(this._tempVector1,this._tempVector0)}getOverrideUVs1ContextualValue(){return this._currentUV}getClassName(){return"InstantiateOnFacesBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=this._vertexData.indices.length/3,s=i/r,n=0,a=[],o=0;for(this._currentLoopIndex=0,this._currentFaceIndex=0;this._currentFaceIndex=i);l++){let i=Math.random(),r=Math.random();if(i>r){let e=i;i=r,r=e}let l=i,h=r-i,u=1-l-h;if(this._currentPosition.set(l*this._vertex0.x+h*this._vertex1.x+u*this._vertex2.x,l*this._vertex0.y+h*this._vertex1.y+u*this._vertex2.y,l*this._vertex0.z+h*this._vertex1.z+u*this._vertex2.z),this._vertexData.uvs&&this._currentUV.set(l*this._uv0.x+h*this._uv1.x+u*this._uv2.x,l*this._uv0.y+h*this._uv1.y+u*this._uv2.y),!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length){n-=s;continue}let c=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(c,this._currentPosition,t,a)}else{let t=e.adaptInput(this.scaling,iH.Vector3,rf.P.OneReadOnly),i=this.rotation.getConnectedValue(e)||rf.P.ZeroReadOnly;e._instantiate(c,this._currentPosition,i,t,a)}o++,this._currentLoopIndex++}}if(a.length){if(1===a.length)this._vertexData=a[0];else{let e=a.splice(0,1)[0];this._vertexData=e.merge(a,!0,!1,!0,!0)}}return e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vw.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.InstantiateOnFacesBlock",vw);class vB extends g3{constructor(e){super(e),this._currentPosition=new rf.P,this._vertex0=new rf.P,this._vertex1=new rf.P,this._vertex2=new rf.P,this.evaluateContext=!0,this.registerInput("geometry",iH.Geometry),this.registerInput("instance",iH.Geometry,!0),this.registerInput("count",iH.Int,!0,256),this.registerInput("matrix",iH.Matrix,!0),this.registerInput("rotation",iH.Vector3,!0,rf.P.Zero()),this.registerInput("scaling",iH.Vector3,!0,rf.P.One()),this.scaling.acceptedConnectionPointTypes.push(iH.Float),this.registerOutput("output",iH.Geometry)}getInstanceIndex(){return this._currentLoopIndex}getExecutionIndex(){return 0}getExecutionFaceIndex(){return 0}getExecutionLoopIndex(){return this._currentLoopIndex}getOverridePositionsContextualValue(){return this._currentPosition}getClassName(){return"InstantiateOnVolumeBlock"}get geometry(){return this._inputs[0]}get instance(){return this._inputs[1]}get count(){return this._inputs[2]}get matrix(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{if(e.pushExecutionContext(this),e.pushInstancingContext(this),this._vertexData=this.geometry.getConnectedValue(e),e.pushGeometryContext(this._vertexData),!this._vertexData||!this._vertexData.positions||!this._vertexData.indices||!this.instance.isConnected){e.restoreExecutionContext(),e.restoreInstancingContext(),e.restoreGeometryContext(),this.output._storedValue=null;return}let t=null,i=this.count.getConnectedValue(e),r=[],s=(0,gI.k)(this._vertexData.positions,0,this._vertexData.positions.length/3),n=s.minimum,a=s.maximum,o=new rf.P(1,0,0),l=this._vertexData.indices.length/3;this._currentLoopIndex=0;for(let s=0;s0&&h++}if(h%2==0){s--;continue}if(!(t=this.instance.getConnectedValue(e))||!t.positions||0===t.positions.length)continue;let u=t.clone();if(this.matrix.isConnected){let t=this.matrix.getConnectedValue(e);e._instantiateWithPositionAndMatrix(u,this._currentPosition,t,r)}else{let t=e.adaptInput(this.scaling,iH.Vector3,rf.P.OneReadOnly),i=this.rotation.getConnectedValue(e)||rf.P.ZeroReadOnly;e._instantiate(u,this._currentPosition,i,t,r)}this._currentLoopIndex++}if(r.length){if(1===r.length)this._vertexData=r[0];else{let e=r.splice(0,1)[0];this._vertexData=e.merge(r,!0,!1,!0,!0)}}return e.restoreGeometryContext(),e.restoreExecutionContext(),e.restoreInstancingContext(),this._vertexData};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vB.prototype,"evaluateContext",void 0),(0,rg.H)("BABYLON.InstantiateOnVolumeBlock",vB);class vU extends g3{constructor(e){super(e),this.evaluateContext=!0,this.registerInput("instance",iH.Geometry,!0),this.registerInput("count",iH.Int,!0,1),this.registerOutput("output",iH.Geometry)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBaseBlock"}get instance(){return this._inputs[0]}get count(){return this._inputs[1]}get output(){return this._outputs[0]}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e}_deserialize(e){super._deserialize(e),void 0!==e.evaluateContext&&(this.evaluateContext=e.evaluateContext)}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vU.prototype,"evaluateContext",void 0);class vV extends vU{constructor(e){super(e),this.registerInput("matrix",iH.Matrix,!0),this.registerInput("position",iH.Vector3,!0,rf.P.Zero()),this.registerInput("rotation",iH.Vector3,!0,rf.P.Zero()),this.registerInput("scaling",iH.Vector3,!0,rf.P.One()),this.scaling.acceptedConnectionPointTypes.push(iH.Float)}getInstanceIndex(){return this._currentIndex}getExecutionIndex(){return this._currentIndex}getExecutionLoopIndex(){return this._currentIndex}getExecutionFaceIndex(){return 0}getClassName(){return"InstantiateBlock"}get matrix(){return this._inputs[2]}get position(){return this._inputs[3]}get rotation(){return this._inputs[4]}get scaling(){return this._inputs[5]}_buildBlock(e){let t=e=>{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[];for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=rf.y3.Identity(),s=rf.P.Zero(),n=rf.P.Zero(),a=rf.P.Zero();for(this._currentIndex=0;this._currentIndex{e.pushExecutionContext(this),e.pushInstancingContext(this);let t=this.count.getConnectedValue(e),i=[],r=rf.y3.Identity(),s=rf.y3.Identity(),n=rf.y3.Identity(),a=rf.P.Zero(),o=rf.P.Zero(),l=rf.P.Zero();for(this._currentIndex=0;this._currentIndexthis.floatIn.isConnected?this.floatIn.getConnectedValue(e):this.intIn.isConnected?this.intIn.getConnectedValue(e):0,this.intOut._storedFunction=e=>this.floatIn.isConnected?Math.floor(this.floatIn.getConnectedValue(e)):this.intIn.isConnected?Math.floor(this.intIn.getConnectedValue(e)):0}}(0,rg.H)("BABYLON.IntFloatConverterBlock",vz);class vW extends g3{constructor(e){super(e),this.log=[],this._isDebug=!0,this.registerInput("input",iH.AutoDetect),this.registerOutput("output",iH.BasedOnInput),this._outputs[0]._typeConnectionSource=this._inputs[0],this._inputs[0].excludedConnectionPointTypes.push(iH.Geometry),this._inputs[0].excludedConnectionPointTypes.push(iH.Texture)}get buildExecutionTime(){return 0}getClassName(){return"DebugBlock"}get input(){return this._inputs[0]}get output(){return this._outputs[0]}_buildBlock(e){if(!this.input.isConnected){this.output._storedFunction=null,this.output._storedValue=null;return}this.log=[];let t=e=>{let t=this.input.getConnectedValue(e);return null==t?this.log.push("null"):this.log.push(t.toString()),t};this.output.isConnected?this.output._storedFunction=t:this.output._storedValue=t(e)}}(0,rg.H)("BABYLON.DebugBlock",vW);class vH extends g3{constructor(e){super(e),this.registerInput("geometry",iH.Geometry),this.registerOutput("output",iH.Geometry),this.registerOutput("id",iH.Int),this.registerOutput("collectionId",iH.Int),this.registerOutput("verticesCount",iH.Int),this.registerOutput("facesCount",iH.Int)}getClassName(){return"GeometryInfoBlock"}get geometry(){return this._inputs[0]}get output(){return this._outputs[0]}get id(){return this._outputs[1]}get collectionId(){return this._outputs[2]}get verticesCount(){return this._outputs[3]}get facesCount(){return this._outputs[4]}_buildBlock(){if(!this.geometry.isConnected){this.id._storedValue=0,this.collectionId._storedValue=0,this.verticesCount._storedValue=0,this.facesCount._storedValue=0,this.output._storedValue=0,this.id._storedFunction=null,this.collectionId._storedFunction=null,this.verticesCount._storedFunction=null,this.facesCount._storedFunction=null,this.output._storedFunction=null;return}this.output._storedFunction=e=>(this._currentVertexData=this.geometry.getConnectedValue(e),this._currentVertexData),this.id._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.uniqueId),this.collectionId._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.metadata?this._currentVertexData.metadata.collectionId:0),this.verticesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.positions?this._currentVertexData.positions.length/3:0),this.facesCount._storedFunction=e=>(this._currentVertexData=this._currentVertexData||this.geometry.getConnectedValue(e),this._currentVertexData.indices?this._currentVertexData.indices.length/3:0)}}(0,rg.H)("BABYLON.GeometryInfoBlock",vH),(eZ=iZ||(iZ={}))[eZ.Spherical=0]="Spherical",eZ[eZ.Cylindrical=1]="Cylindrical",eZ[eZ.Cubic=2]="Cubic";class vX extends g3{constructor(e){super(e),this.mapping=iZ.Spherical,this.registerInput("position",iH.Vector3),this.registerInput("normal",iH.Vector3),this.registerInput("center",iH.Vector3,!0,rf.P.Zero()),this.registerOutput("uv",iH.Vector2)}getClassName(){return"MappingBlock"}get position(){return this._inputs[0]}get normal(){return this._inputs[1]}get center(){return this._inputs[2]}get uv(){return this._outputs[0]}_buildBlock(){if(!this.position.isConnected){this.uv._storedFunction=null,this.uv._storedValue=null;return}let e=rf.P.Zero(),t=t=>{let i=this.position.getConnectedValue(t)||rf.P.Zero(),r=this.normal.getConnectedValue(t)||rf.P.Zero(),s=this.center.getConnectedValue(t),n=rf.FM.Zero();switch(this.mapping){case iZ.Spherical:{i.subtractToRef(s,e);let t=e.length();t>0&&(n.x=Math.acos(e.y/t)/Math.PI,(0!==e.x||0!==e.z)&&(n.y=Math.atan2(e.x,e.z)/(2*Math.PI)));break}case iZ.Cylindrical:{i.subtractToRef(s,e);let t=e.length();t>0&&(n.x=Math.atan2(e.x/t,e.z/t)/(2*Math.PI),n.y=(e.y+1)/2);break}case iZ.Cubic:{let e=Math.abs(r.x),t=Math.abs(r.y),a=Math.abs(r.z),o=Math.max(Math.abs(i.x),Math.abs(i.y),Math.abs(i.z)),l=0,h=0;e>=t&&e>=a?(l=i.y/o-s.y,h=i.z/o-s.z):t>=e&&t>=a?(l=i.x/o-s.x,h=i.z/o-s.z):(l=i.x/o-s.x,h=i.y/o-s.y),n.x=(l+1)/2,n.y=(h+1)/2}}return n};this.uv._storedFunction=e=>t(e)}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.mapping = BABYLON.MappingTypes.${iZ[this.mapping]}; +`}serialize(){let e=super.serialize();return e.mapping=this.mapping,e}_deserialize(e){super._deserialize(e),this.mapping=e.mapping}}(0,sx.gn)([nS("Mapping",tx.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Spherical",value:iZ.Spherical},{label:"Cylindrical",value:iZ.Cylindrical},{label:"Cubic",value:iZ.Cubic}]})],vX.prototype,"mapping",void 0),(0,rg.H)("BABYLON.MappingBlock",vX);class vY extends g3{constructor(e){super(e),this.registerInput("matrix0",iH.Matrix),this.registerInput("matrix1",iH.Matrix),this.registerOutput("output",iH.Matrix)}getClassName(){return"MatrixComposeBlock"}get matrix0(){return this._inputs[0]}get matrix1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(){this.output._storedFunction=e=>{if(!this.matrix0.isConnected||!this.matrix1.isConnected)return null;let t=this.matrix0.getConnectedValue(e),i=this.matrix1.getConnectedValue(e);return t&&i?t.multiply(i):null}}}(0,rg.H)("BABYLON.MatrixComposeBlock",vY);class vj extends g3{get endpoints(){return this._endpoints}constructor(e){super(e),this._endpoints=[],this._isTeleportIn=!0,this.registerInput("input",iH.AutoDetect)}getClassName(){return"TeleportInBlock"}get input(){return this._inputs[0]}_dumpCode(e,t){let i=super._dumpCode(e,t);for(let r of this.endpoints)-1===t.indexOf(r)&&(i+=r._dumpCode(e,t));return i}isAnAncestorOfType(e){if(this.getClassName()===e)return!0;for(let t of this.endpoints)if(t.isAnAncestorOfType(e))return!0;return!1}isAnAncestorOf(e){for(let t of this.endpoints)if(t===e||t.isAnAncestorOf(e))return!0;return!1}getDescendantOfPredicate(e){if(e(this))return this;for(let t of this.endpoints){let i=t.getDescendantOfPredicate(e);if(i)return i}return null}attachToEndpoint(e){e.detach(),this._endpoints.push(e),e._entryPoint=this,e._outputs[0]._typeConnectionSource=this._inputs[0],e._tempEntryPointUniqueId=null,e.name="> "+this.name}detachFromEndpoint(e){let t=this._endpoints.indexOf(e);-1!==t&&(this._endpoints.splice(t,1),e._outputs[0]._typeConnectionSource=null,e._entryPoint=null)}_buildBlock(){for(let e of this._endpoints)e.output._storedFunction=e=>this.input.getConnectedValue(e)}}(0,rg.H)("BABYLON.TeleportInBlock",vj);class vq extends g3{constructor(e){super(e),this._entryPoint=null,this._tempEntryPointUniqueId=null,this._isTeleportOut=!0,this.registerOutput("output",iH.BasedOnInput)}get entryPoint(){return this._entryPoint}getClassName(){return"TeleportOutBlock"}get output(){return this._outputs[0]}detach(){this._entryPoint&&this._entryPoint.detachFromEndpoint(this)}_buildBlock(){}_customBuildStep(e){this.entryPoint&&this.entryPoint.build(e)}_dumpCode(e,t){let i="";return this.entryPoint&&-1===t.indexOf(this.entryPoint)&&(i+=this.entryPoint._dumpCode(e,t)),i+super._dumpCode(e,t)}_dumpCodeForOutputConnections(e){let t=super._dumpCodeForOutputConnections(e);return this.entryPoint&&(t+=this.entryPoint._dumpCodeForOutputConnections(e)),t}clone(){let e=super.clone();return this.entryPoint&&this.entryPoint.attachToEndpoint(e),e}_dumpPropertiesCode(){let e=super._dumpPropertiesCode();return this.entryPoint&&(e+=`${this.entryPoint._codeVariableName}.attachToEndpoint(${this._codeVariableName}); +`),e}serialize(){var e,t;let i=super.serialize();return i.entryPoint=null!==(t=null===(e=this.entryPoint)||void 0===e?void 0:e.uniqueId)&&void 0!==t?t:"",i}_deserialize(e){super._deserialize(e),this._tempEntryPointUniqueId=e.entryPoint}}(0,rg.H)("BABYLON.TeleportOutBlock",vq);class vK extends g3{get textureData(){return this._data}get textureWidth(){return this._width}get textureHeight(){return this._height}constructor(e){super(e),this._data=null,this.serializedCachedData=!1,this.registerOutput("texture",iH.Texture)}getClassName(){return"GeometryTextureBlock"}get texture(){return this._outputs[0]}_prepareImgToLoadAsync(e){return new Promise((t,i)=>{let r=new Image,s=document.createElement("canvas"),n=s.getContext("2d");r.onload=()=>{s.width=r.width,s.height=r.height,n.drawImage(r,0,0);let e=n.getImageData(0,0,r.width,r.height).data,i=new Float32Array(e.length);for(let t=0;t{this._data=null,i()},r.src=e})}cleanData(){this._data=null}loadTextureFromFileAsync(e){return this._prepareImgToLoadAsync(URL.createObjectURL(e))}loadTextureFromUrlAsync(e){return this._prepareImgToLoadAsync(e)}extractFromTextureAsync(e){return new Promise((t,i)=>{if(!e.isReady()){e.onLoadObservable.addOnce(()=>this.extractFromTextureAsync(e).then(t).catch(i));return}let r=e.getSize();uE.GetTextureDataAsync(e,r.width,r.height).then(async e=>{let i=new Float32Array(e.length);for(let t=0;t=0?e%1:1-Math.abs(e)%1}_buildBlock(){let e=e=>{let t=this.texture.getConnectedValue(e);if(!t||!t.data)return null;let i=this.coordinates.getConnectedValue(e);if(!i)return null;let r=this.clampCoordinates?Math.max(0,Math.min(i.x,1)):this._repeatClamp(i.x),s=this.clampCoordinates?Math.max(0,Math.min(i.y,1)):this._repeatClamp(i.y),n=Math.floor(r*(t.width-1)),a=Math.floor(s*(t.height-1)),o=n+t.width*a;return rf.Lt.FromArray(t.data,4*o)};this.rgba._storedFunction=t=>e(t),this.rgb._storedFunction=t=>{let i=e(t);return i?i.toVector3():null},this.r._storedFunction=t=>{let i=e(t);return i?i.x:null},this.g._storedFunction=t=>{let i=e(t);return i?i.y:null},this.b._storedFunction=t=>{let i=e(t);return i?i.z:null},this.a._storedFunction=t=>{let i=e(t);return i?i.w:null}}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.clampCoordinates = ${this.clampCoordinates}; +`}serialize(){let e=super.serialize();return e.clampCoordinates=this.clampCoordinates,e}_deserialize(e){super._deserialize(e),this.clampCoordinates=e.clampCoordinates}}(0,sx.gn)([nS("Clamp Coordinates",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],v$.prototype,"clampCoordinates",void 0),(0,rg.H)("BABYLON.GeometryTextureFetchBlock",v$);class vQ extends g3{constructor(e){super(e),this.registerInput("geometry",iH.Geometry),this.registerOutput("min",iH.Vector3),this.registerOutput("max",iH.Vector3)}getClassName(){return"BoundingBlock"}get geometry(){return this._inputs[0]}get min(){return this._outputs[0]}get max(){return this._outputs[1]}_buildBlock(){this.min._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);return t?(0,gI.k)(t.positions,0,t.positions.length/3).minimum:null},this.max._storedFunction=e=>{let t=this.geometry.getConnectedValue(e);return t?(0,gI.k)(t.positions,0,t.positions.length/3).maximum:null}}}(0,rg.H)("BABYLON.BoundingBlock",vQ),(eJ=iJ||(iJ={}))[eJ.Intersect=0]="Intersect",eJ[eJ.Subtract=1]="Subtract",eJ[eJ.Union=2]="Union";class vZ extends g3{constructor(e){super(e),this.evaluateContext=!1,this.operation=iJ.Intersect,this.registerInput("geometry0",iH.Geometry),this.registerInput("geometry1",iH.Geometry),this.registerOutput("output",iH.Geometry)}getClassName(){return"BooleanGeometryBlock"}get geometry0(){return this._inputs[0]}get geometry1(){return this._inputs[1]}get output(){return this._outputs[0]}_buildBlock(e){let t=e=>{let t;let i=this.geometry0.getConnectedValue(e),r=this.geometry1.getConnectedValue(e);if(!i||!r)return null;let s=i.positions.length/3;!i.normals&&r.normals&&(i.normals=Array(i.positions.length)),!r.normals&&i.normals&&(r.normals=Array(r.positions.length)),!i.uvs&&r.uvs&&(i.uvs=Array(2*s)),!r.uvs&&i.uvs&&(r.uvs=Array(2*s)),!i.colors&&r.colors&&(i.colors=Array(4*s)),!r.colors&&i.colors&&(r.colors=Array(4*s));let n=gV.FromVertexData(i),a=gV.FromVertexData(r);switch(this.operation){case iJ.Intersect:t=n.intersect(a);break;case iJ.Subtract:t=n.subtract(a);break;case iJ.Union:t=n.union(a)}return t.toVertexData()};this.evaluateContext?this.output._storedFunction=t:(this.output._storedFunction=null,this.output._storedValue=t(e))}_dumpPropertiesCode(){return super._dumpPropertiesCode()+`${this._codeVariableName}.evaluateContext = ${this.evaluateContext?"true":"false"}; +`+`${this._codeVariableName}.operation = BABYLON.BooleanGeometryOperations.${iJ[this.operation]}; +`}serialize(){let e=super.serialize();return e.evaluateContext=this.evaluateContext,e.operation=this.operation,e}_deserialize(e){super._deserialize(e),this.evaluateContext=e.evaluateContext,e.operation&&(this.operation=e.operation)}}(0,sx.gn)([nS("Evaluate context",tx.Boolean,"ADVANCED",{notifiers:{rebuild:!0}})],vZ.prototype,"evaluateContext",void 0),(0,sx.gn)([nS("Operation",tx.List,"ADVANCED",{notifiers:{rebuild:!0},options:[{label:"Intersect",value:iJ.Intersect},{label:"Subtract",value:iJ.Subtract},{label:"Union",value:iJ.Union}]})],vZ.prototype,"operation",void 0),(0,rg.H)("BABYLON.BooleanGeometryBlock",vZ),sR.D.OfflineProviderFactory=(e,t,i=!1)=>new vJ(e,t,i);class vJ{get enableSceneOffline(){return this._enableSceneOffline}get enableTexturesOffline(){return this._enableTexturesOffline}constructor(e,t,i=!1){this._idbFactory="undefined"!=typeof indexedDB?indexedDB:void 0,this._currentSceneUrl=vJ._ReturnFullUrlLocation(e),this._db=null,this._enableSceneOffline=!1,this._enableTexturesOffline=!1,this._manifestVersionFound=0,this._mustUpdateRessources=!1,this._hasReachedQuota=!1,vJ.IDBStorageEnabled?i?(this._enableSceneOffline=!0,this._enableTexturesOffline=!0,this._manifestVersionFound=1,sg.w1.SetImmediate(()=>{t(!0)})):this._checkManifestFile(t):t(!0)}_checkManifestFile(e){let t=()=>{this._enableSceneOffline=!1,this._enableTexturesOffline=!1,e(!1)},i=()=>{try{if("function"==typeof URL&&0===this._currentSceneUrl.indexOf("http")){let e=new URL(this._currentSceneUrl);return e.pathname+=".manifest",e.toString()}}catch(e){}return`${this._currentSceneUrl}.manifest`},r=!1,s=i(),n=new rX.g;navigator.onLine&&(r=!0,s=s+(null==s.match(/\?/)?"?":"&")+Date.now()),n.open("GET",s),n.addEventListener("load",()=>{if(200===n.status||vJ._ValidateXHRData(n,1))try{let t=JSON.parse(n.response);this._enableSceneOffline=t.enableSceneOffline,this._enableTexturesOffline=t.enableTexturesOffline&&vJ._IsUASupportingBlobStorage,t.version&&!isNaN(parseInt(t.version))&&(this._manifestVersionFound=t.version),e(!0)}catch(e){t()}else t()},!1),n.addEventListener("error",()=>{if(r){r=!1;let e=i();n.open("GET",e),n.send()}else t()},!1);try{n.send()}catch(t){rb.Y.Error("Error on XHR send request."),e(!1)}}open(e,t){let i=()=>{this._isSupported=!1,t&&t()};if(this._idbFactory&&(this._enableSceneOffline||this._enableTexturesOffline)){if(this._db)e&&e();else{this._hasReachedQuota=!1,this._isSupported=!0;let t=this._idbFactory.open("babylonjs",1);t.onerror=()=>{i()},t.onblocked=()=>{rb.Y.Error("IDB request blocked. Please reload the page."),i()},t.onsuccess=()=>{this._db=t.result,e()},t.onupgradeneeded=e=>{if(this._db=e.target.result,this._db)try{this._db.createObjectStore("scenes",{keyPath:"sceneUrl"}),this._db.createObjectStore("versions",{keyPath:"sceneUrl"}),this._db.createObjectStore("textures",{keyPath:"textureUrl"})}catch(e){rb.Y.Error("Error while creating object stores. Exception: "+e.message),i()}}}}else this._isSupported=!1,t&&t()}loadImage(e,t){let i=vJ._ReturnFullUrlLocation(e),r=()=>{this._hasReachedQuota||null===this._db?t.src=e:this._saveImageIntoDBAsync(i,t)};this._mustUpdateRessources?r():this._loadImageFromDBAsync(i,t,r)}_loadImageFromDBAsync(e,t,i){if(this._isSupported&&null!==this._db){let r;let s=this._db.transaction(["textures"]);s.onabort=()=>{t.src=e},s.oncomplete=()=>{let s;r&&"function"==typeof URL?(s=URL.createObjectURL(r.data),t.onerror=()=>{rb.Y.Error("Error loading image from blob URL: "+s+" switching back to web url: "+e),t.src=e},t.src=s):i()};let n=s.objectStore("textures").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{rb.Y.Error("Error loading texture "+e+" from DB."),t.src=e}}else rb.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t.src=e}_saveImageIntoDBAsync(e,t){let i;if(this._isSupported){let r=()=>{let e;if(i&&"function"==typeof URL)try{e=URL.createObjectURL(i)}catch(t){e=URL.createObjectURL(i)}e&&(t.src=e)};if(vJ._IsUASupportingBlobStorage){let s=new rX.g;s.open("GET",e),s.responseType="blob",s.addEventListener("load",()=>{if(200===s.status&&this._db){i=s.response;let n=this._db.transaction(["textures"],"readwrite");n.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}r()},n.oncomplete=()=>{r()};let a={textureUrl:e,data:i};try{let e=n.objectStore("textures").put(a);e.onsuccess=()=>{},e.onerror=()=>{r()}}catch(i){25===i.code&&(vJ._IsUASupportingBlobStorage=!1,this._enableTexturesOffline=!1),t.src=e}}else t.src=e},!1),s.addEventListener("error",()=>{rb.Y.Error("Error in XHR request in BABYLON.Database."),t.src=e},!1),s.send()}else t.src=e}else rb.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t.src=e}_checkVersionFromDB(e,t){this._loadVersionFromDBAsync(e,t,()=>{this._saveVersionIntoDBAsync(e,t)})}_loadVersionFromDBAsync(e,t,i){if(this._isSupported&&this._db){let r;try{let s=this._db.transaction(["versions"]);s.oncomplete=()=>{r?this._manifestVersionFound!==r.data?(this._mustUpdateRessources=!0,i()):t(r.data):(this._mustUpdateRessources=!0,i())},s.onabort=()=>{t(-1)};let n=s.objectStore("versions").get(e);n.onsuccess=e=>{r=e.target.result},n.onerror=()=>{rb.Y.Error("Error loading version for scene "+e+" from DB."),t(-1)}}catch(e){rb.Y.Error("Error while accessing 'versions' object store (READ OP). Exception: "+e.message),t(-1)}}else rb.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),t(-1)}_saveVersionIntoDBAsync(e,t){if(this._isSupported&&!this._hasReachedQuota&&this._db)try{let i=this._db.transaction(["versions"],"readwrite");i.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(-1)},i.oncomplete=()=>{t(this._manifestVersionFound)};let r={sceneUrl:e,data:this._manifestVersionFound},s=i.objectStore("versions").put(r);s.onsuccess=()=>{},s.onerror=()=>{rb.Y.Error("Error in DB add version request in BABYLON.Database.")}}catch(e){rb.Y.Error("Error while accessing 'versions' object store (WRITE OP). Exception: "+e.message),t(-1)}else t(-1)}loadFile(e,t,i,r,s){let n=vJ._ReturnFullUrlLocation(e),a=()=>{this._saveFileAsync(n,t,i,s,r)};this._checkVersionFromDB(n,e=>{-1!==e?this._mustUpdateRessources?this._saveFileAsync(n,t,i,s,r):this._loadFileAsync(n,t,a):r&&r()})}_loadFileAsync(e,t,i){if(this._isSupported&&this._db){let r,s;r=-1!==e.indexOf(".babylon")?"scenes":"textures";let n=this._db.transaction([r]);n.oncomplete=()=>{s?t(s.data):i()},n.onabort=()=>{i()};let a=n.objectStore(r).get(e);a.onsuccess=e=>{s=e.target.result},a.onerror=()=>{rb.Y.Error("Error loading file "+e+" from DB."),i()}}else rb.Y.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open."),t()}_saveFileAsync(e,t,i,r,s){if(this._isSupported){let n,a;n=-1!==e.indexOf(".babylon")?"scenes":"textures";let o=new rX.g;o.open("GET",e+(null==e.match(/\?/)?"?":"&")+Date.now()),r&&(o.responseType="arraybuffer"),i&&(o.onprogress=i),o.addEventListener("load",()=>{if(200===o.status||o.status<400&&vJ._ValidateXHRData(o,r?6:1)){if(a=r?o.response:o.responseText,!this._hasReachedQuota&&this._db){let i;let r=this._db.transaction([n],"readwrite");r.onabort=e=>{try{let t=e.target.error;t&&"QuotaExceededError"===t.name&&(this._hasReachedQuota=!0)}catch(e){}t(a)},r.oncomplete=()=>{t(a)},i="scenes"===n?{sceneUrl:e,data:a,version:this._manifestVersionFound}:{textureUrl:e,data:a};try{let e=r.objectStore(n).put(i);e.onsuccess=()=>{},e.onerror=()=>{rb.Y.Error("Error in DB add file request in BABYLON.Database.")}}catch(e){t(a)}}else t(a)}else o.status>=400&&s?s(o):t()},!1),o.addEventListener("error",()=>{rb.Y.Error("error on XHR request."),s&&s()},!1),o.send()}else rb.Y.Error("Error: IndexedDB not supported by your browser or Babylon.js database is not open."),s&&s()}static _ValidateXHRData(e,t=7){try{if(1&t){if(e.responseText&&e.responseText.length>0)return!0;if(1===t)return!1}if(2&t){let i=fI(e.response);if(i.width&&i.height&&i.width>0&&i.height>0)return!0;if(2===t)return!1}if(4&t){let t=new Uint8Array(e.response,0,3);if(68===t[0]&&68===t[1]&&83===t[2])return!0}}catch(e){}return!1}}vJ._IsUASupportingBlobStorage=!0,vJ.IDBStorageEnabled=!1,vJ._ParseURL=e=>{document.createElement("a").href=e;let t=e.substring(0,e.lastIndexOf("#")),i=e.substring(t.lastIndexOf("/")+1,e.length);return e.substring(0,e.indexOf(i,0))},vJ._ReturnFullUrlLocation=e=>-1===e.indexOf("http:/")&&-1===e.indexOf("https:/")&&"undefined"!=typeof window?vJ._ParseURL(window.location.href)+e:e;class v0{_isUbo(e){return void 0!==e.addUniform}constructor(e){this._isUbo(e)?(this.setMatrix3x3=e.updateMatrix3x3.bind(e),this.setMatrix2x2=e.updateMatrix2x2.bind(e),this.setFloat=e.updateFloat.bind(e),this.setFloat2=e.updateFloat2.bind(e),this.setFloat3=e.updateFloat3.bind(e),this.setFloat4=e.updateFloat4.bind(e),this.setFloatArray=e.updateFloatArray.bind(e),this.setArray=e.updateArray.bind(e),this.setIntArray=e.updateIntArray.bind(e),this.setMatrix=e.updateMatrix.bind(e),this.setMatrices=e.updateMatrices.bind(e),this.setVector3=e.updateVector3.bind(e),this.setVector4=e.updateVector4.bind(e),this.setColor3=e.updateColor3.bind(e),this.setColor4=e.updateColor4.bind(e),this.setDirectColor4=e.updateDirectColor4.bind(e),this.setInt=e.updateInt.bind(e),this.setInt2=e.updateInt2.bind(e),this.setInt3=e.updateInt3.bind(e),this.setInt4=e.updateInt4.bind(e)):(this.setMatrix3x3=e.setMatrix3x3.bind(e),this.setMatrix2x2=e.setMatrix2x2.bind(e),this.setFloat=e.setFloat.bind(e),this.setFloat2=e.setFloat2.bind(e),this.setFloat3=e.setFloat3.bind(e),this.setFloat4=e.setFloat4.bind(e),this.setFloatArray=e.setFloatArray.bind(e),this.setArray=e.setArray.bind(e),this.setIntArray=e.setIntArray.bind(e),this.setMatrix=e.setMatrix.bind(e),this.setMatrices=e.setMatrices.bind(e),this.setVector3=e.setVector3.bind(e),this.setVector4=e.setVector4.bind(e),this.setColor3=e.setColor3.bind(e),this.setColor4=e.setColor4.bind(e),this.setDirectColor4=e.setDirectColor4.bind(e),this.setInt=e.setInt.bind(e),this.setInt2=e.setInt2.bind(e),this.setInt3=e.setInt3.bind(e),this.setInt4=e.setInt4.bind(e))}}let v1=`#version 300 es +void main() {discard;} +`;nw.v.ShadersStore.gpuUpdateParticlesPixelShader=v1;let v2=`#version 300 es +#define PI 3.14159 +uniform float currentCount;uniform float timeDelta;uniform float stopFactor; +#ifndef LOCAL +uniform mat4 emitterWM; +#endif +uniform vec2 lifeTime;uniform vec2 emitPower;uniform vec2 sizeRange;uniform vec4 scaleRange; +#ifndef COLORGRADIENTS +uniform vec4 color1;uniform vec4 color2; +#endif +uniform vec3 gravity;uniform sampler2D randomSampler;uniform sampler2D randomSampler2;uniform vec4 angleRange; +#ifdef BOXEMITTER +uniform vec3 direction1;uniform vec3 direction2;uniform vec3 minEmitBox;uniform vec3 maxEmitBox; +#endif +#ifdef POINTEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#endif +#ifdef HEMISPHERICEMITTER +uniform float radius;uniform float radiusRange;uniform float directionRandomizer; +#endif +#ifdef SPHEREEMITTER +uniform float radius;uniform float radiusRange; +#ifdef DIRECTEDSPHEREEMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CYLINDEREMITTER +uniform float radius;uniform float height;uniform float radiusRange; +#ifdef DIRECTEDCYLINDEREMITTER +uniform vec3 direction1;uniform vec3 direction2; +#else +uniform float directionRandomizer; +#endif +#endif +#ifdef CONEEMITTER +uniform vec2 radius;uniform float coneAngle;uniform vec2 height;uniform float directionRandomizer; +#endif +in vec3 position; +#ifdef CUSTOMEMITTER +in vec3 initialPosition; +#endif +in float age;in float life;in vec4 seed;in vec3 size; +#ifndef COLORGRADIENTS +in vec4 color; +#endif +in vec3 direction; +#ifndef BILLBOARD +in vec3 initialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +in float angle; +#else +in vec2 angle; +#endif +#ifdef ANIMATESHEET +in float cellIndex; +#ifdef ANIMATESHEETRANDOMSTART +in float cellStartOffset; +#endif +#endif +#ifdef NOISE +in vec3 noiseCoordinates1;in vec3 noiseCoordinates2; +#endif +out vec3 outPosition; +#ifdef CUSTOMEMITTER +out vec3 outInitialPosition; +#endif +out float outAge;out float outLife;out vec4 outSeed;out vec3 outSize; +#ifndef COLORGRADIENTS +out vec4 outColor; +#endif +out vec3 outDirection; +#ifndef BILLBOARD +out vec3 outInitialDirection; +#endif +#ifdef ANGULARSPEEDGRADIENTS +out float outAngle; +#else +out vec2 outAngle; +#endif +#ifdef ANIMATESHEET +out float outCellIndex; +#ifdef ANIMATESHEETRANDOMSTART +out float outCellStartOffset; +#endif +#endif +#ifdef NOISE +out vec3 outNoiseCoordinates1;out vec3 outNoiseCoordinates2; +#endif +#ifdef SIZEGRADIENTS +uniform sampler2D sizeGradientSampler; +#endif +#ifdef ANGULARSPEEDGRADIENTS +uniform sampler2D angularSpeedGradientSampler; +#endif +#ifdef VELOCITYGRADIENTS +uniform sampler2D velocityGradientSampler; +#endif +#ifdef LIMITVELOCITYGRADIENTS +uniform sampler2D limitVelocityGradientSampler;uniform float limitVelocityDamping; +#endif +#ifdef DRAGGRADIENTS +uniform sampler2D dragGradientSampler; +#endif +#ifdef NOISE +uniform vec3 noiseStrength;uniform sampler2D noiseSampler; +#endif +#ifdef ANIMATESHEET +uniform vec4 cellInfos; +#endif +vec3 getRandomVec3(float offset) {return texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;} +vec4 getRandomVec4(float offset) {return texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));} +void main() {float newAge=age+timeDelta; +if (newAge>=life && stopFactor != 0.) {vec3 newPosition;vec3 newDirection;vec4 randoms=getRandomVec4(seed.x);outLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;outAge=newAge-life;outSeed=seed; +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(0,0)).r; +#else +outSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g; +#endif +outSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;outSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; +#ifndef COLORGRADIENTS +outColor=color1+(color2-color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +outAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;outAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#else +outAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r; +#endif +#ifdef POINTEMITTER +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=vec3(0,0,0);newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(BOXEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);newPosition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;newDirection=direction1+(direction2-direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=newPosition+directionRandomizer*randoms3; +#elif defined(SPHEREEMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float phi=2.0*PI*randoms2.x;float theta=acos(2.0*randoms2.y-1.0);float randX=cos(phi)*sin(theta);float randY=cos(theta);float randZ=sin(phi)*sin(theta);newPosition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(direction1+(direction2-direction1)*randoms3); +#else +newDirection=normalize(newPosition+directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +vec3 randoms2=getRandomVec3(seed.y);vec3 randoms3=getRandomVec3(seed.z);float yPos=(randoms2.x-0.5)*height;float angle=randoms2.y*PI*2.;float inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));float positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));float xPos=positionRadius*cos(angle);float zPos=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=direction1+(direction2-direction1)*randoms3; +#else +angle=angle+((randoms3.x-0.5)*PI)*directionRandomizer;newDirection=vec3(cos(angle),(randoms3.y-0.5)*directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +vec3 randoms2=getRandomVec3(seed.y);float s=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +float h=0.0001; +#else +float h=randoms2.y*height.y;h=1.-h*h; +#endif +float lRadius=radius.x-radius.x*randoms2.z*radius.y;lRadius=lRadius*h;float randX=lRadius*sin(s);float randZ=lRadius*cos(s);float randY=h *height.x;newPosition=vec3(randX,randY,randZ); +if (abs(cos(coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {vec3 randoms3=getRandomVec3(seed.z);newDirection=normalize(newPosition+directionRandomizer*randoms3); } +#elif defined(CUSTOMEMITTER) +newPosition=initialPosition;outInitialPosition=initialPosition; +#else +newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5)); +#endif +float power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a; +#ifdef LOCAL +outPosition=newPosition; +#else +outPosition=(emitterWM*vec4(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#ifndef BILLBOARD +outInitialDirection=direction; +#endif +#else +#ifdef LOCAL +vec3 initial=newDirection; +#else +vec3 initial=(emitterWM*vec4(newDirection,0.)).xyz; +#endif +outDirection=initial*power; +#ifndef BILLBOARD +outInitialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +outCellIndex=cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +} else {float directionScale=timeDelta;outAge=newAge;float ageGradient=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r; +#endif +#ifdef DRAGGRADIENTS +directionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r; +#endif +#if defined(CUSTOMEMITTER) +outPosition=position+(direction-position)*ageGradient; +outInitialPosition=initialPosition; +#else +outPosition=position+direction*directionScale; +#endif +outLife=life;outSeed=seed; +#ifndef COLORGRADIENTS +outColor=color; +#endif +#ifdef SIZEGRADIENTS +outSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;outSize.yz=size.yz; +#else +outSize=size; +#endif +#ifndef BILLBOARD +outInitialDirection=initialDirection; +#endif +#ifdef CUSTOMEMITTER +outDirection=direction; +#else +vec3 updatedDirection=direction+gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +float limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;float currentVelocity=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*limitVelocityDamping;} +#endif +outDirection=updatedDirection; +#ifdef NOISE +float fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;float fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;float fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;vec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;outDirection=outDirection+force*timeDelta;outNoiseCoordinates1=noiseCoordinates1;outNoiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +float angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;outAngle=angle+angularSpeed*timeDelta; +#else +outAngle=vec2(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +float offsetAge=outAge;float dist=cellInfos.y-cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +outCellStartOffset=cellStartOffset;offsetAge+=cellStartOffset; +#else +float cellStartOffset=0.; +#endif +float ratio=0.;if (cellInfos.w==1.0) {ratio=clamp(mod(cellStartOffset+cellInfos.z*offsetAge,life)/life,0.,1.0);} +else {ratio=clamp(cellStartOffset+cellInfos.z*offsetAge/life,0.,1.0);} +outCellIndex=float(int(cellInfos.x+ratio*dist)); +#endif +}}`;nw.v.ShadersStore.gpuUpdateParticlesVertexShader=v2;class v3{constructor(e,t){this._renderVAO=[],this._updateVAO=[],this.alignDataInBuffer=!1,this._parent=e,this._engine=t,this._updateEffectOptions={attributes:["position","initialPosition","age","life","seed","size","color","direction","initialDirection","angle","cellIndex","cellStartOffset","noiseCoordinates1","noiseCoordinates2"],uniformsNames:["currentCount","timeDelta","emitterWM","lifeTime","color1","color2","sizeRange","scaleRange","gravity","emitPower","direction1","direction2","minEmitBox","maxEmitBox","radius","directionRandomizer","height","coneAngle","stopFactor","angleRange","radiusRange","cellInfos","noiseStrength","limitVelocityDamping"],uniformBuffersNames:[],samplers:["randomSampler","randomSampler2","sizeGradientSampler","angularSpeedGradientSampler","velocityGradientSampler","limitVelocityGradientSampler","noiseSampler","dragGradientSampler"],defines:"",fallbacks:null,onCompiled:null,onError:null,indexParameters:null,maxSimultaneousLights:0,transformFeedbackVaryings:[]}}contextLost(){this._updateEffect=void 0,this._renderVAO.length=0,this._updateVAO.length=0}isUpdateBufferCreated(){return!!this._updateEffect}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateEffect)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){return this._updateEffectOptions.transformFeedbackVaryings=["outPosition"],this._updateEffectOptions.transformFeedbackVaryings.push("outAge"),this._updateEffectOptions.transformFeedbackVaryings.push("outSize"),this._updateEffectOptions.transformFeedbackVaryings.push("outLife"),this._updateEffectOptions.transformFeedbackVaryings.push("outSeed"),this._updateEffectOptions.transformFeedbackVaryings.push("outDirection"),this._parent.particleEmitterType instanceof n1&&this._updateEffectOptions.transformFeedbackVaryings.push("outInitialPosition"),this._parent._colorGradientsTexture||this._updateEffectOptions.transformFeedbackVaryings.push("outColor"),this._parent._isBillboardBased||this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection"),this._parent.noiseTexture&&(this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1"),this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2")),this._updateEffectOptions.transformFeedbackVaryings.push("outAngle"),this._parent.isAnimationSheetEnabled&&(this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex"),this._parent.spriteRandomStartCell&&this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset")),this._updateEffectOptions.defines=e,this._updateEffect=new nd.Q("gpuUpdateParticles",this._updateEffectOptions,this._engine),new v0(this._updateEffect)}createVertexBuffers(e,t){this._updateVAO.push(this._createUpdateVAO(e)),this._renderVAO.push(this._engine.recordVertexArrayObject(t,null,this._parent._getWrapper(this._parent.blendMode).effect)),this._engine.bindArrayBuffer(null),this._renderVertexBuffers=t}createParticleBuffer(e){return e}bindDrawBuffers(e,t,i){i?this._engine.bindBuffers(this._renderVertexBuffers,i,t):this._engine.bindVertexArrayObject(this._renderVAO[e],null)}preUpdateParticleBuffer(){let e=this._engine;if(this._engine.enableEffect(this._updateEffect),!e.setState)throw Error("GPU particles cannot work without a full Engine. ThinEngine is not supported")}updateParticleBuffer(e,t,i){this._updateEffect.setTexture("randomSampler",this._parent._randomTexture),this._updateEffect.setTexture("randomSampler2",this._parent._randomTexture2),this._parent._sizeGradientsTexture&&this._updateEffect.setTexture("sizeGradientSampler",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateEffect.setTexture("angularSpeedGradientSampler",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateEffect.setTexture("velocityGradientSampler",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateEffect.setTexture("limitVelocityGradientSampler",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateEffect.setTexture("dragGradientSampler",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateEffect.setTexture("noiseSampler",this._parent.noiseTexture),this._engine.bindVertexArrayObject(this._updateVAO[e],null);let r=this._engine;r.bindTransformFeedbackBuffer(t.getBuffer()),r.setRasterizerState(!1),r.beginTransformFeedback(!0),r.drawArraysType(3,0,i),r.endTransformFeedback(),r.setRasterizerState(!0),r.bindTransformFeedbackBuffer(null)}releaseBuffers(){}releaseVertexBuffers(){for(let e=0;e, +age : f32, +size : vec3, +life : f32, +seed : vec4, +direction : vec3, +dummy0: f32, +#ifdef CUSTOMEMITTER +initialPosition : vec3, +dummy1: f32, +#endif +#ifndef COLORGRADIENTS +color : vec4, +#endif +#ifndef BILLBOARD +initialDirection : vec3, +dummy2: f32, +#endif +#ifdef NOISE +noiseCoordinates1 : vec3, +dummy3: f32, +noiseCoordinates2 : vec3, +dummy4: f32, +#endif +#ifdef ANGULARSPEEDGRADIENTS +angle : f32, +#else +angle : vec2, +#endif +#ifdef ANIMATESHEET +cellIndex : f32, +#ifdef ANIMATESHEETRANDOMSTART +cellStartOffset : f32, +#endif +#endif +};struct Particles {particles : array,};struct SimParams {currentCount : f32, +timeDelta : f32, +stopFactor : f32, +randomTextureSize: i32, +lifeTime : vec2, +emitPower : vec2, +#ifndef COLORGRADIENTS +color1 : vec4, +color2 : vec4, +#endif +sizeRange : vec2, +scaleRange : vec4, +angleRange : vec4, +gravity : vec3, +#ifdef LIMITVELOCITYGRADIENTS +limitVelocityDamping : f32, +#endif +#ifdef ANIMATESHEET +cellInfos : vec4, +#endif +#ifdef NOISE +noiseStrength : vec3, +#endif +#ifndef LOCAL +emitterWM : mat4x4, +#endif +#ifdef BOXEMITTER +direction1 : vec3, +direction2 : vec3, +minEmitBox : vec3, +maxEmitBox : vec3, +#endif +#ifdef CONEEMITTER +radius : vec2, +coneAngle : f32, +height : vec2, +directionRandomizer : f32, +#endif +#ifdef CYLINDEREMITTER +radius : f32, +height : f32, +radiusRange : f32, +#ifdef DIRECTEDCYLINDEREMITTER +direction1 : vec3, +direction2 : vec3, +#else +directionRandomizer : f32, +#endif +#endif +#ifdef HEMISPHERICEMITTER +radius : f32, +radiusRange : f32, +directionRandomizer : f32, +#endif +#ifdef POINTEMITTER +direction1 : vec3, +direction2 : vec3, +#endif +#ifdef SPHEREEMITTER +radius : f32, +radiusRange : f32, +#ifdef DIRECTEDSPHEREEMITTER +direction1 : vec3, +direction2 : vec3, +#else +directionRandomizer : f32, +#endif +#endif +};@binding(0) @group(0) var params : SimParams;@binding(1) @group(0) var particlesIn : Particles;@binding(2) @group(0) var particlesOut : Particles;@binding(3) @group(0) var randomTexture : texture_2d;@binding(4) @group(0) var randomTexture2 : texture_2d; +#ifdef SIZEGRADIENTS +@binding(0) @group(1) var sizeGradientSampler : sampler;@binding(1) @group(1) var sizeGradientTexture : texture_2d; +#endif +#ifdef ANGULARSPEEDGRADIENTS +@binding(2) @group(1) var angularSpeedGradientSampler : sampler;@binding(3) @group(1) var angularSpeedGradientTexture : texture_2d; +#endif +#ifdef VELOCITYGRADIENTS +@binding(4) @group(1) var velocityGradientSampler : sampler;@binding(5) @group(1) var velocityGradientTexture : texture_2d; +#endif +#ifdef LIMITVELOCITYGRADIENTS +@binding(6) @group(1) var limitVelocityGradientSampler : sampler;@binding(7) @group(1) var limitVelocityGradientTexture : texture_2d; +#endif +#ifdef DRAGGRADIENTS +@binding(8) @group(1) var dragGradientSampler : sampler;@binding(9) @group(1) var dragGradientTexture : texture_2d; +#endif +#ifdef NOISE +@binding(10) @group(1) var noiseSampler : sampler;@binding(11) @group(1) var noiseTexture : texture_2d; +#endif +fn getRandomVec3(offset : f32,vertexID : f32)->vec3 {return textureLoad(randomTexture2,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0).rgb;} +fn getRandomVec4(offset : f32,vertexID : f32)->vec4 {return textureLoad(randomTexture,vec2(i32(vertexID*offset/params.currentCount*f32(params.randomTextureSize)) % params.randomTextureSize,0),0);} +@compute @workgroup_size(64) +fn main(@builtin(global_invocation_id) GlobalInvocationID : vec3) {let index : u32=GlobalInvocationID.x;let vertexID : f32=f32(index);if (index>=u32(params.currentCount)) {return;} +let PI : f32=3.14159;let timeDelta : f32=params.timeDelta;let newAge : f32=particlesIn.particles[index].age+timeDelta;let life : f32=particlesIn.particles[index].life;let seed : vec4=particlesIn.particles[index].seed;let direction : vec3=particlesIn.particles[index].direction;if (newAge>=life && params.stopFactor != 0.) {var newPosition : vec3;var newDirection : vec3;let randoms : vec4=getRandomVec4(seed.x,vertexID);let outLife : f32=params.lifeTime.x+(params.lifeTime.y-params.lifeTime.x)*randoms.r;particlesOut.particles[index].life=outLife;particlesOut.particles[index].age=newAge-life;particlesOut.particles[index].seed=seed;var sizex : f32; +#ifdef SIZEGRADIENTS +sizex=textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(0.,0.),0.).r; +#else +sizex=params.sizeRange.x+(params.sizeRange.y-params.sizeRange.x)*randoms.g; +#endif +particlesOut.particles[index].size=vec3( +sizex, +params.scaleRange.x+(params.scaleRange.y-params.scaleRange.x)*randoms.b, +params.scaleRange.z+(params.scaleRange.w-params.scaleRange.z)*randoms.a); +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=params.color1+(params.color2-params.color1)*randoms.b; +#endif +#ifndef ANGULARSPEEDGRADIENTS +particlesOut.particles[index].angle=vec2( +params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r, +params.angleRange.x+(params.angleRange.y-params.angleRange.x)*randoms.a); +#else +particlesOut.particles[index].angle=params.angleRange.z+(params.angleRange.w-params.angleRange.z)*randoms.r; +#endif +#if defined(POINTEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=vec3(0.,0.,0.);newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(BOXEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newPosition=params.minEmitBox+(params.maxEmitBox-params.minEmitBox)*randoms2;newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#elif defined(HEMISPHERICEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#elif defined(SPHEREEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let phi : f32=2.0*PI*randoms2.x;let theta : f32=acos(-1.0+2.0*randoms2.y);let randX : f32=cos(phi)*sin(theta);let randY : f32=cos(theta);let randZ : f32=sin(phi)*sin(theta);newPosition=(params.radius-(params.radius*params.radiusRange*randoms2.z))*vec3(randX,randY,randZ); +#ifdef DIRECTEDSPHEREEMITTER +newDirection=normalize(params.direction1+(params.direction2-params.direction1)*randoms3); +#else +newDirection=normalize(newPosition+params.directionRandomizer*randoms3); +#endif +#elif defined(CYLINDEREMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let randoms3 : vec3=getRandomVec3(seed.z,vertexID);let yPos : f32=(-0.5+randoms2.x)*params.height;var angle : f32=randoms2.y*PI*2.;let inverseRadiusRangeSquared : f32=(1.-params.radiusRange)*(1.-params.radiusRange);let positionRadius : f32=params.radius*sqrt(inverseRadiusRangeSquared+randoms2.z*(1.-inverseRadiusRangeSquared));let xPos : f32=positionRadius*cos(angle);let zPos : f32=positionRadius*sin(angle);newPosition=vec3(xPos,yPos,zPos); +#ifdef DIRECTEDCYLINDEREMITTER +newDirection=params.direction1+(params.direction2-params.direction1)*randoms3; +#else +angle=angle+(-0.5+randoms3.x)*PI*params.directionRandomizer;newDirection=vec3(cos(angle),(-0.5+randoms3.y)*params.directionRandomizer,sin(angle));newDirection=normalize(newDirection); +#endif +#elif defined(CONEEMITTER) +let randoms2 : vec3=getRandomVec3(seed.y,vertexID);let s : f32=2.0*PI*randoms2.x; +#ifdef CONEEMITTERSPAWNPOINT +let h : f32=0.0001; +#else +var h : f32=randoms2.y*params.height.y;h=1.-h*h; +#endif +var lRadius : f32=params.radius.x-params.radius.x*randoms2.z*params.radius.y;lRadius=lRadius*h;let randX : f32=lRadius*sin(s);let randZ : f32=lRadius*cos(s);let randY : f32=h *params.height.x;newPosition=vec3(randX,randY,randZ); +if (abs(cos(params.coneAngle))==1.0) {newDirection=vec3(0.,1.0,0.);} else {let randoms3 : vec3=getRandomVec3(seed.z,vertexID);newDirection=normalize(newPosition+params.directionRandomizer*randoms3); } +#elif defined(CUSTOMEMITTER) +newPosition=particlesIn.particles[index].initialPosition;particlesOut.particles[index].initialPosition=newPosition; +#else +newPosition=vec3(0.,0.,0.);newDirection=2.0*(getRandomVec3(seed.w,vertexID)-vec3(0.5,0.5,0.5)); +#endif +let power : f32=params.emitPower.x+(params.emitPower.y-params.emitPower.x)*randoms.a; +#ifdef LOCAL +particlesOut.particles[index].position=newPosition; +#else +particlesOut.particles[index].position=(params.emitterWM*vec4(newPosition,1.)).xyz; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=direction; +#endif +#else +#ifdef LOCAL +let initial : vec3=newDirection; +#else +let initial : vec3=(params.emitterWM*vec4(newDirection,0.)).xyz; +#endif +particlesOut.particles[index].direction=initial*power; +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=initial; +#endif +#endif +#ifdef ANIMATESHEET +particlesOut.particles[index].cellIndex=params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +particlesOut.particles[index].cellStartOffset=randoms.a*outLife; +#endif +#endif +#ifdef NOISE +particlesOut.particles[index].noiseCoordinates1=particlesIn.particles[index].noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=particlesIn.particles[index].noiseCoordinates2; +#endif +} else {var directionScale : f32=timeDelta;particlesOut.particles[index].age=newAge;let ageGradient : f32=newAge/life; +#ifdef VELOCITYGRADIENTS +directionScale=directionScale*textureSampleLevel(velocityGradientTexture,velocityGradientSampler,vec2(ageGradient,0.),0.).r; +#endif +#ifdef DRAGGRADIENTS +directionScale=directionScale*(1.0-textureSampleLevel(dragGradientTexture,dragGradientSampler,vec2(ageGradient,0.),0.).r); +#endif +let position : vec3=particlesIn.particles[index].position; +#if defined(CUSTOMEMITTER) +particlesOut.particles[index].position=position+(direction-position)*ageGradient; +particlesOut.particles[index].initialPosition=particlesIn.particles[index].initialPosition; +#else +particlesOut.particles[index].position=position+direction*directionScale; +#endif +particlesOut.particles[index].life=life;particlesOut.particles[index].seed=seed; +#ifndef COLORGRADIENTS +particlesOut.particles[index].color=particlesIn.particles[index].color; +#endif +#ifdef SIZEGRADIENTS +particlesOut.particles[index].size=vec3( +textureSampleLevel(sizeGradientTexture,sizeGradientSampler,vec2(ageGradient,0.),0.).r, +particlesIn.particles[index].size.yz); +#else +particlesOut.particles[index].size=particlesIn.particles[index].size; +#endif +#ifndef BILLBOARD +particlesOut.particles[index].initialDirection=particlesIn.particles[index].initialDirection; +#endif +#ifdef CUSTOMEMITTER +particlesOut.particles[index].direction=direction; +#else +var updatedDirection : vec3=direction+params.gravity*timeDelta; +#ifdef LIMITVELOCITYGRADIENTS +let limitVelocity : f32=textureSampleLevel(limitVelocityGradientTexture,limitVelocityGradientSampler,vec2(ageGradient,0.),0.).r;let currentVelocity : f32=length(updatedDirection);if (currentVelocity>limitVelocity) {updatedDirection=updatedDirection*params.limitVelocityDamping;} +#endif +particlesOut.particles[index].direction=updatedDirection; +#ifdef NOISE +let noiseCoordinates1 : vec3=particlesIn.particles[index].noiseCoordinates1;let noiseCoordinates2 : vec3=particlesIn.particles[index].noiseCoordinates2;let fetchedR : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedG : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let fetchedB : f32=textureSampleLevel(noiseTexture,noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5,0.5)+vec2(0.5,0.5),0.).r;let force : vec3=vec3(-1.+2.*fetchedR,-1.+2.*fetchedG,-1.+2.*fetchedB)*params.noiseStrength;particlesOut.particles[index].direction=particlesOut.particles[index].direction+force*timeDelta;particlesOut.particles[index].noiseCoordinates1=noiseCoordinates1;particlesOut.particles[index].noiseCoordinates2=noiseCoordinates2; +#endif +#endif +#ifdef ANGULARSPEEDGRADIENTS +let angularSpeed : f32=textureSampleLevel(angularSpeedGradientTexture,angularSpeedGradientSampler,vec2(ageGradient,0.),0.).r;particlesOut.particles[index].angle=particlesIn.particles[index].angle+angularSpeed*timeDelta; +#else +let angle : vec2=particlesIn.particles[index].angle;particlesOut.particles[index].angle=vec2(angle.x+angle.y*timeDelta,angle.y); +#endif +#ifdef ANIMATESHEET +var offsetAge : f32=particlesOut.particles[index].age;let dist : f32=params.cellInfos.y-params.cellInfos.x; +#ifdef ANIMATESHEETRANDOMSTART +let cellStartOffset : f32=particlesIn.particles[index].cellStartOffset;particlesOut.particles[index].cellStartOffset=cellStartOffset;offsetAge=offsetAge+cellStartOffset; +#else +let cellStartOffset : f32=0.; +#endif +var ratio : f32;if (params.cellInfos.w==1.0) {ratio=clamp(((cellStartOffset+params.cellInfos.z*offsetAge) % life)/life,0.,1.0);} +else {ratio=clamp((cellStartOffset+params.cellInfos.z*offsetAge)/life,0.,1.0);} +particlesOut.particles[index].cellIndex=f32(i32(params.cellInfos.x+ratio*dist)); +#endif +}} +`;nw.v.ShadersStoreWGSL.gpuUpdateParticlesComputeShader=v4;class v5{constructor(e,t){this._bufferComputeShader=[],this._renderVertexBuffers=[],this.alignDataInBuffer=!0,this._parent=e,this._engine=t}contextLost(){this._updateComputeShader=void 0,this._bufferComputeShader.length=0,this._renderVertexBuffers.length=0}isUpdateBufferCreated(){return!!this._updateComputeShader}isUpdateBufferReady(){var e,t;return null!==(t=null===(e=this._updateComputeShader)||void 0===e?void 0:e.isReady())&&void 0!==t&&t}createUpdateBuffer(e){var t;let i={params:{group:0,binding:0},particlesIn:{group:0,binding:1},particlesOut:{group:0,binding:2},randomTexture:{group:0,binding:3},randomTexture2:{group:0,binding:4}};return this._parent._sizeGradientsTexture&&(i.sizeGradientTexture={group:1,binding:1}),this._parent._angularSpeedGradientsTexture&&(i.angularSpeedGradientTexture={group:1,binding:3}),this._parent._velocityGradientsTexture&&(i.velocityGradientTexture={group:1,binding:5}),this._parent._limitVelocityGradientsTexture&&(i.limitVelocityGradientTexture={group:1,binding:7}),this._parent._dragGradientsTexture&&(i.dragGradientTexture={group:1,binding:9}),this._parent.noiseTexture&&(i.noiseTexture={group:1,binding:11}),this._updateComputeShader=new h_("updateParticles",this._engine,"gpuUpdateParticles",{bindingsMapping:i,defines:e.split("\n")}),null===(t=this._simParamsComputeShader)||void 0===t||t.dispose(),this._simParamsComputeShader=new sT.M(this._engine,void 0,void 0,"ComputeShaderParticleSystemUBO"),this._simParamsComputeShader.addUniform("currentCount",1),this._simParamsComputeShader.addUniform("timeDelta",1),this._simParamsComputeShader.addUniform("stopFactor",1),this._simParamsComputeShader.addUniform("randomTextureSize",1),this._simParamsComputeShader.addUniform("lifeTime",2),this._simParamsComputeShader.addUniform("emitPower",2),this._parent._colorGradientsTexture||(this._simParamsComputeShader.addUniform("color1",4),this._simParamsComputeShader.addUniform("color2",4)),this._simParamsComputeShader.addUniform("sizeRange",2),this._simParamsComputeShader.addUniform("scaleRange",4),this._simParamsComputeShader.addUniform("angleRange",4),this._simParamsComputeShader.addUniform("gravity",3),this._parent._limitVelocityGradientsTexture&&this._simParamsComputeShader.addUniform("limitVelocityDamping",1),this._parent.isAnimationSheetEnabled&&this._simParamsComputeShader.addUniform("cellInfos",4),this._parent.noiseTexture&&this._simParamsComputeShader.addUniform("noiseStrength",3),this._parent.isLocal||this._simParamsComputeShader.addUniform("emitterWM",16),this._parent.particleEmitterType&&this._parent.particleEmitterType.buildUniformLayout(this._simParamsComputeShader),this._updateComputeShader.setUniformBuffer("params",this._simParamsComputeShader),new v0(this._simParamsComputeShader)}createVertexBuffers(e,t){this._renderVertexBuffers.push(t)}createParticleBuffer(e){let t=new aE(this._engine,4*e.length,11,"ComputeShaderParticleSystemBuffer");return t.update(e),this._bufferComputeShader.push(t),t.getBuffer()}bindDrawBuffers(e,t,i){this._engine.bindBuffers(this._renderVertexBuffers[e],i,t)}preUpdateParticleBuffer(){}updateParticleBuffer(e,t,i){this._simParamsComputeShader.update(),this._updateComputeShader.setTexture("randomTexture",this._parent._randomTexture,!1),this._updateComputeShader.setTexture("randomTexture2",this._parent._randomTexture2,!1),this._parent._sizeGradientsTexture&&this._updateComputeShader.setTexture("sizeGradientTexture",this._parent._sizeGradientsTexture),this._parent._angularSpeedGradientsTexture&&this._updateComputeShader.setTexture("angularSpeedGradientTexture",this._parent._angularSpeedGradientsTexture),this._parent._velocityGradientsTexture&&this._updateComputeShader.setTexture("velocityGradientTexture",this._parent._velocityGradientsTexture),this._parent._limitVelocityGradientsTexture&&this._updateComputeShader.setTexture("limitVelocityGradientTexture",this._parent._limitVelocityGradientsTexture),this._parent._dragGradientsTexture&&this._updateComputeShader.setTexture("dragGradientTexture",this._parent._dragGradientsTexture),this._parent.noiseTexture&&this._updateComputeShader.setTexture("noiseTexture",this._parent.noiseTexture),this._updateComputeShader.setStorageBuffer("particlesIn",this._bufferComputeShader[e]),this._updateComputeShader.setStorageBuffer("particlesOut",this._bufferComputeShader[1^e]),this._updateComputeShader.dispatch(Math.ceil(i/64))}releaseBuffers(){var e;for(let e=0;ee){i(t[0],t[0],1);return}for(let r=0;r=s.gradient&&e<=n.gradient){let t=(e-s.gradient)/(n.gradient-s.gradient);i(s,n,t);return}}let r=t.length-1;i(t[r],t[r],1)}}class xe{constructor(e){if(this.particleSystem=e,this.position=rf.P.Zero(),this.direction=rf.P.Zero(),this.color=new rm.HE(0,0,0,0),this.colorStep=new rm.HE(0,0,0,0),this.lifeTime=1,this.age=0,this.size=0,this.scale=new rf.FM(1,1),this.angle=0,this.angularSpeed=0,this.cellIndex=0,this._attachedSubEmitters=null,this._currentColor1=new rm.HE(0,0,0,0),this._currentColor2=new rm.HE(0,0,0,0),this._currentSize1=0,this._currentSize2=0,this._currentAngularSpeed1=0,this._currentAngularSpeed2=0,this._currentVelocity1=0,this._currentVelocity2=0,this._currentLimitVelocity1=0,this._currentLimitVelocity2=0,this._currentDrag1=0,this._currentDrag2=0,this.id=xe._Count++,!this.particleSystem.isAnimationSheetEnabled)return;this._updateCellInfoFromSystem()}_updateCellInfoFromSystem(){this.cellIndex=this.particleSystem.startSpriteCellID}updateCellIndex(){let e,t=this.age,i=this.particleSystem.spriteCellChangeSpeed;this.particleSystem.spriteRandomStartCell&&(void 0===this._randomCellOffset&&(this._randomCellOffset=Math.random()*this.lifeTime),0===i?(i=1,t=this._randomCellOffset):t+=this._randomCellOffset);let r=this._initialEndSpriteCellID-this._initialStartSpriteCellID;e=this._initialSpriteCellLoop?rk.R.Clamp(t*i%this.lifeTime/this.lifeTime):rk.R.Clamp(t*i/this.lifeTime),this.cellIndex=this._initialStartSpriteCellID+e*r|0}_inheritParticleInfoToSubEmitter(e){if(e.particleSystem.emitter.position){let t=e.particleSystem.emitter;if(t.position.copyFrom(this.position),e.inheritDirection){let e=rf.jp.Vector3[0];this.direction.normalizeToRef(e),t.setDirection(e,0,Math.PI/2)}}else e.particleSystem.emitter.copyFrom(this.position);this.direction.scaleToRef(e.inheritedVelocityAmount/2,rf.jp.Vector3[0]),e.particleSystem._inheritedVelocityOffset.copyFrom(rf.jp.Vector3[0])}_inheritParticleInfoToSubEmitters(){this._attachedSubEmitters&&this._attachedSubEmitters.length>0&&this._attachedSubEmitters.forEach(e=>{this._inheritParticleInfoToSubEmitter(e)})}_reset(){this.age=0,this.id=xe._Count++,this._currentColorGradient=null,this._currentSizeGradient=null,this._currentAngularSpeedGradient=null,this._currentVelocityGradient=null,this._currentLimitVelocityGradient=null,this._currentDragGradient=null,this.cellIndex=this.particleSystem.startSpriteCellID,this._randomCellOffset=void 0}copyTo(e){e.position.copyFrom(this.position),this._initialDirection?e._initialDirection?e._initialDirection.copyFrom(this._initialDirection):e._initialDirection=this._initialDirection.clone():e._initialDirection=null,e.direction.copyFrom(this.direction),this._localPosition&&(e._localPosition?e._localPosition.copyFrom(this._localPosition):e._localPosition=this._localPosition.clone()),e.color.copyFrom(this.color),e.colorStep.copyFrom(this.colorStep),e.lifeTime=this.lifeTime,e.age=this.age,e._randomCellOffset=this._randomCellOffset,e.size=this.size,e.scale.copyFrom(this.scale),e.angle=this.angle,e.angularSpeed=this.angularSpeed,e.particleSystem=this.particleSystem,e.cellIndex=this.cellIndex,e.id=this.id,e._attachedSubEmitters=this._attachedSubEmitters,this._currentColorGradient&&(e._currentColorGradient=this._currentColorGradient,e._currentColor1.copyFrom(this._currentColor1),e._currentColor2.copyFrom(this._currentColor2)),this._currentSizeGradient&&(e._currentSizeGradient=this._currentSizeGradient,e._currentSize1=this._currentSize1,e._currentSize2=this._currentSize2),this._currentAngularSpeedGradient&&(e._currentAngularSpeedGradient=this._currentAngularSpeedGradient,e._currentAngularSpeed1=this._currentAngularSpeed1,e._currentAngularSpeed2=this._currentAngularSpeed2),this._currentVelocityGradient&&(e._currentVelocityGradient=this._currentVelocityGradient,e._currentVelocity1=this._currentVelocity1,e._currentVelocity2=this._currentVelocity2),this._currentLimitVelocityGradient&&(e._currentLimitVelocityGradient=this._currentLimitVelocityGradient,e._currentLimitVelocity1=this._currentLimitVelocity1,e._currentLimitVelocity2=this._currentLimitVelocity2),this._currentDragGradient&&(e._currentDragGradient=this._currentDragGradient,e._currentDrag1=this._currentDrag1,e._currentDrag2=this._currentDrag2),this.particleSystem.isAnimationSheetEnabled&&(e._initialStartSpriteCellID=this._initialStartSpriteCellID,e._initialEndSpriteCellID=this._initialEndSpriteCellID,e._initialSpriteCellLoop=this._initialSpriteCellLoop),this.particleSystem.useRampGradients&&(e.remapData&&this.remapData?e.remapData.copyFrom(this.remapData):e.remapData=new rf.Lt(0,0,0,0)),this._randomNoiseCoordinates1&&(e._randomNoiseCoordinates1?(e._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1),e._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2)):(e._randomNoiseCoordinates1=this._randomNoiseCoordinates1.clone(),e._randomNoiseCoordinates2=this._randomNoiseCoordinates2.clone()))}}xe._Count=0,(e0=i0||(i0={}))[e0.ATTACHED=0]="ATTACHED",e0[e0.END=1]="END";class xt{constructor(e){if(this.particleSystem=e,this.type=i0.END,this.inheritDirection=!1,this.inheritedVelocityAmount=0,!e.emitter||!e.emitter.dispose){let t=(0,rg.q)("BABYLON.AbstractMesh");e.emitter=new t("SubemitterSystemEmitter",e.getScene()),e._disposeEmitterOnDispose=!0}}clone(){let e=this.particleSystem.emitter;e?e instanceof rf.P?e=e.clone():-1!==e.getClassName().indexOf("Mesh")&&((e=new((0,rg.q)("BABYLON.Mesh"))("",e.getScene())).isVisible=!1):e=new rf.P;let t=new xt(this.particleSystem.clone(this.particleSystem.name,e));return t.particleSystem.name+="Clone",t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem._disposeEmitterOnDispose=!0,t.particleSystem.disposeOnStop=!0,t}serialize(e=!1){let t={};return t.type=this.type,t.inheritDirection=this.inheritDirection,t.inheritedVelocityAmount=this.inheritedVelocityAmount,t.particleSystem=this.particleSystem.serialize(e),t}static _ParseParticleSystem(e,t,i,r=!1){throw(0,sM.S)("ParseParticle")}static Parse(e,t,i){let r=e.particleSystem,s=new xt(xt._ParseParticleSystem(r,t,i,!0));return s.type=e.type,s.inheritDirection=e.inheritDirection,s.inheritedVelocityAmount=e.inheritedVelocityAmount,s.particleSystem._isSubEmitter=!0,s}dispose(){this.particleSystem.dispose()}}let xi=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; +#include +#include +#include +#include +#include +#ifdef RAMPGRADIENT +varying vec4 remapRanges;uniform sampler2D rampSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; +#ifdef RAMPGRADIENT +float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); +#endif +#ifdef BLENDMULTIPLYMODE +float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); +#endif +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +baseColor.rgb=toLinearSpace(baseColor.rgb); +#else +#ifdef IMAGEPROCESSING +baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); +#endif +#endif +gl_FragColor=baseColor; +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.particlesPixelShader=xi;let xr=`attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +#ifndef BILLBOARD +attribute vec3 direction; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +#ifdef RAMPGRADIENT +attribute vec4 remapData; +#endif +attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; +#ifdef ANIMATESHEET +uniform vec3 particlesInfos; +#endif +varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#ifdef RAMPGRADIENT +varying vec4 remapRanges; +#endif +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include +#include +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); +#ifdef BILLBOARDSTRETCHED_LOCAL +vec3 row1=direction; +#else +vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); +#endif +mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec2 cornerPos;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; +#ifdef BILLBOARD +vec3 rotatedCorner; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; +#endif +#ifdef RAMPGRADIENT +remapRanges=remapData; +#endif +gl_Position=projection*vec4(viewPos,1.0); +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); +#endif +vColor=color; +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=offset; +#endif +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include +#include +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.particlesVertexShader=xr;class xs extends n3{set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get useRampGradients(){return this._useRampGradients}set useRampGradients(e){this._useRampGradients!==e&&(this._useRampGradients=e,this._resetEffect())}get particles(){return this._particles}getActiveCount(){return this._particles.length}getClassName(){return"ParticleSystem"}isStopping(){return this._stopped&&this.isAlive()}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new nk.q(this._engine),this._customWrappers[t].effect=e,this._customWrappers[t].drawContext&&(this._customWrappers[t].drawContext.useInstancing=this._useInstancing)}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new r_.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"particles"}get vertexBuffers(){return this._vertexBuffers}get indexBuffer(){return this._indexBuffer}constructor(e,t,i,r=null,s=!1,n=.01){super(e),this._emitterInverseWorldMatrix=rf.y3.Identity(),this._inheritedVelocityOffset=new rf.P,this.onDisposeObservable=new r_.y$,this.onStoppedObservable=new r_.y$,this._particles=[],this._stockParticles=[],this._newPartsExcess=0,this._vertexBuffers={},this._scaledColorStep=new rm.HE(0,0,0,0),this._colorDiff=new rm.HE(0,0,0,0),this._scaledDirection=rf.P.Zero(),this._scaledGravity=rf.P.Zero(),this._currentRenderId=-1,this._useInstancing=!1,this._started=!1,this._stopped=!1,this._actualFrame=0,this._currentEmitRate1=0,this._currentEmitRate2=0,this._currentStartSize1=0,this._currentStartSize2=0,this.updateInAnimate=!0,this._rawTextureWidth=256,this._useRampGradients=!1,this._disposeEmitterOnDispose=!1,this.isLocal=!1,this.isGPU=!1,this._onBeforeDrawParticlesObservable=null,this.recycleParticle=e=>{let t=this._particles.pop();t!==e&&t.copyTo(e),this._stockParticles.push(t)},this._createParticle=()=>{let e;if(0!==this._stockParticles.length?(e=this._stockParticles.pop())._reset():e=new xe(this),this._subEmitters&&this._subEmitters.length>0){let t=this._subEmitters[Math.floor(Math.random()*this._subEmitters.length)];e._attachedSubEmitters=[],t.forEach(t=>{if(t.type===i0.ATTACHED){let i=t.clone();e._attachedSubEmitters.push(i),i.particleSystem.start()}})}return e},this._emitFromParticle=e=>{if(!this._subEmitters||0===this._subEmitters.length)return;let t=Math.floor(Math.random()*this._subEmitters.length);this._subEmitters[t].forEach(t=>{if(t.type===i0.END){let i=t.clone();e._inheritParticleInfoToSubEmitter(i),i.particleSystem._rootParticleSystem=this,this.activeSubSystems.push(i.particleSystem),i.particleSystem.start()}})},this._capacity=t,this._epsilon=n,this._isAnimationSheetEnabled=s,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=rf.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||rL.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObject=null),this._attachImageProcessingConfiguration(null),this._customWrappers={0:new nk.q(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers=[],this._useInstancing=this._engine.getCaps().instancedArrays,this._createIndexBuffer(),this._createVertexBuffers(),this.particleEmitterType=new nj;let a=null;this.updateFunction=e=>{var t;let i=null;this.noiseTexture&&(i=this.noiseTexture.getSize(),null===(t=this.noiseTexture.getContent())||void 0===t||t.then(e=>{a=e}));let r=e===this._particles;for(let t=0;ts.lifeTime){let e=s.age-o;n=(s.lifeTime-o)*n/e,s.age=s.lifeTime}let l=s.age/s.lifeTime;this._colorGradients&&this._colorGradients.length>0?v9.GetCurrentGradient(l,this._colorGradients,(e,t,i)=>{e!==s._currentColorGradient&&(s._currentColor1.copyFrom(s._currentColor2),t.getColorToRef(s._currentColor2),s._currentColorGradient=e),rm.HE.LerpToRef(s._currentColor1,s._currentColor2,i,s.color)}):(s.colorStep.scaleToRef(n,this._scaledColorStep),s.color.addInPlace(this._scaledColorStep),s.color.a<0&&(s.color.a=0)),this._angularSpeedGradients&&this._angularSpeedGradients.length>0&&v9.GetCurrentGradient(l,this._angularSpeedGradients,(e,t,i)=>{e!==s._currentAngularSpeedGradient&&(s._currentAngularSpeed1=s._currentAngularSpeed2,s._currentAngularSpeed2=t.getFactor(),s._currentAngularSpeedGradient=e),s.angularSpeed=rk.R.Lerp(s._currentAngularSpeed1,s._currentAngularSpeed2,i)}),s.angle+=s.angularSpeed*n;let h=n;if(this._velocityGradients&&this._velocityGradients.length>0&&v9.GetCurrentGradient(l,this._velocityGradients,(e,t,i)=>{e!==s._currentVelocityGradient&&(s._currentVelocity1=s._currentVelocity2,s._currentVelocity2=t.getFactor(),s._currentVelocityGradient=e),h*=rk.R.Lerp(s._currentVelocity1,s._currentVelocity2,i)}),s.direction.scaleToRef(h,this._scaledDirection),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&v9.GetCurrentGradient(l,this._limitVelocityGradients,(e,t,i)=>{e!==s._currentLimitVelocityGradient&&(s._currentLimitVelocity1=s._currentLimitVelocity2,s._currentLimitVelocity2=t.getFactor(),s._currentLimitVelocityGradient=e);let r=rk.R.Lerp(s._currentLimitVelocity1,s._currentLimitVelocity2,i);s.direction.length()>r&&s.direction.scaleInPlace(this.limitVelocityDamping)}),this._dragGradients&&this._dragGradients.length>0&&v9.GetCurrentGradient(l,this._dragGradients,(e,t,i)=>{e!==s._currentDragGradient&&(s._currentDrag1=s._currentDrag2,s._currentDrag2=t.getFactor(),s._currentDragGradient=e);let r=rk.R.Lerp(s._currentDrag1,s._currentDrag2,i);this._scaledDirection.scaleInPlace(1-r)}),this.isLocal&&s._localPosition?(s._localPosition.addInPlace(this._scaledDirection),rf.P.TransformCoordinatesToRef(s._localPosition,this._emitterWorldMatrix,s.position)):s.position.addInPlace(this._scaledDirection),a&&i&&s._randomNoiseCoordinates1){let e=this._fetchR(s._randomNoiseCoordinates1.x,s._randomNoiseCoordinates1.y,i.width,i.height,a),t=this._fetchR(s._randomNoiseCoordinates1.z,s._randomNoiseCoordinates2.x,i.width,i.height,a),r=this._fetchR(s._randomNoiseCoordinates2.y,s._randomNoiseCoordinates2.z,i.width,i.height,a),o=rf.jp.Vector3[0],l=rf.jp.Vector3[1];o.copyFromFloats((2*e-1)*this.noiseStrength.x,(2*t-1)*this.noiseStrength.y,(2*r-1)*this.noiseStrength.z),o.scaleToRef(n,l),s.direction.addInPlace(l)}if(this.gravity.scaleToRef(n,this._scaledGravity),s.direction.addInPlace(this._scaledGravity),this._sizeGradients&&this._sizeGradients.length>0&&v9.GetCurrentGradient(l,this._sizeGradients,(e,t,i)=>{e!==s._currentSizeGradient&&(s._currentSize1=s._currentSize2,s._currentSize2=t.getFactor(),s._currentSizeGradient=e),s.size=rk.R.Lerp(s._currentSize1,s._currentSize2,i)}),this._useRampGradients&&(this._colorRemapGradients&&this._colorRemapGradients.length>0&&v9.GetCurrentGradient(l,this._colorRemapGradients,(e,t,i)=>{let r=rk.R.Lerp(e.factor1,t.factor1,i),n=rk.R.Lerp(e.factor2,t.factor2,i);s.remapData.x=r,s.remapData.y=n-r}),this._alphaRemapGradients&&this._alphaRemapGradients.length>0&&v9.GetCurrentGradient(l,this._alphaRemapGradients,(e,t,i)=>{let r=rk.R.Lerp(e.factor1,t.factor1,i),n=rk.R.Lerp(e.factor2,t.factor2,i);s.remapData.z=r,s.remapData.w=n-r})),this._isAnimationSheetEnabled&&s.updateCellIndex(),s._inheritParticleInfoToSubEmitters(),s.age>=s.lifeTime){this._emitFromParticle(s),s._attachedSubEmitters&&(s._attachedSubEmitters.forEach(e=>{e.particleSystem.disposeOnStop=!0,e.particleSystem.stop()}),s._attachedSubEmitters=null),this.recycleParticle(s),r&&t--;continue}}}}_addFactorGradient(e,t,i,r){let s=new v7(t,i,r);e.push(s),e.sort((e,t)=>e.gradientt.gradient?1:0)}_removeFactorGradient(e,t){if(!e)return;let i=0;for(let r of e){if(r.gradient===t){e.splice(i,1);break}i++}}addLifeTimeGradient(e,t,i){return this._lifeTimeGradients||(this._lifeTimeGradients=[]),this._addFactorGradient(this._lifeTimeGradients,e,t,i),this}removeLifeTimeGradient(e){return this._removeFactorGradient(this._lifeTimeGradients,e),this}addSizeGradient(e,t,i){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t,i),this}removeSizeGradient(e){return this._removeFactorGradient(this._sizeGradients,e),this}addColorRemapGradient(e,t,i){return this._colorRemapGradients||(this._colorRemapGradients=[]),this._addFactorGradient(this._colorRemapGradients,e,t,i),this}removeColorRemapGradient(e){return this._removeFactorGradient(this._colorRemapGradients,e),this}addAlphaRemapGradient(e,t,i){return this._alphaRemapGradients||(this._alphaRemapGradients=[]),this._addFactorGradient(this._alphaRemapGradients,e,t,i),this}removeAlphaRemapGradient(e){return this._removeFactorGradient(this._alphaRemapGradients,e),this}addAngularSpeedGradient(e,t,i){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t,i),this}removeAngularSpeedGradient(e){return this._removeFactorGradient(this._angularSpeedGradients,e),this}addVelocityGradient(e,t,i){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t,i),this}removeVelocityGradient(e){return this._removeFactorGradient(this._velocityGradients,e),this}addLimitVelocityGradient(e,t,i){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t,i),this}removeLimitVelocityGradient(e){return this._removeFactorGradient(this._limitVelocityGradients,e),this}addDragGradient(e,t,i){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t,i),this}removeDragGradient(e){return this._removeFactorGradient(this._dragGradients,e),this}addEmitRateGradient(e,t,i){return this._emitRateGradients||(this._emitRateGradients=[]),this._addFactorGradient(this._emitRateGradients,e,t,i),this}removeEmitRateGradient(e){return this._removeFactorGradient(this._emitRateGradients,e),this}addStartSizeGradient(e,t,i){return this._startSizeGradients||(this._startSizeGradients=[]),this._addFactorGradient(this._startSizeGradients,e,t,i),this}removeStartSizeGradient(e){return this._removeFactorGradient(this._startSizeGradients,e),this}_createRampGradientTexture(){if(!this._rampGradients||!this._rampGradients.length||this._rampGradientsTexture||!this._scene)return;let e=new Uint8Array(4*this._rawTextureWidth),t=rm.zZ.Color3[0];for(let i=0;i{rm.Wo.LerpToRef(r.color,s.color,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255})}this._rampGradientsTexture=sJ.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1)}getRampGradients(){return this._rampGradients}forceRefreshGradients(){this._syncRampGradientTexture()}_syncRampGradientTexture(){this._rampGradients&&(this._rampGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._createRampGradientTexture())}addRampGradient(e,t){this._rampGradients||(this._rampGradients=[]);let i=new v8(e,t);return this._rampGradients.push(i),this._syncRampGradientTexture(),this}removeRampGradient(e){return this._removeGradientAndTexture(e,this._rampGradients,this._rampGradientsTexture),this._rampGradientsTexture=null,this._rampGradients&&this._rampGradients.length>0&&this._createRampGradientTexture(),this}addColorGradient(e,t,i){this._colorGradients||(this._colorGradients=[]);let r=new v6(e,t,i);return this._colorGradients.push(r),this._colorGradients.sort((e,t)=>e.gradientt.gradient?1:0),this}removeColorGradient(e){if(!this._colorGradients)return this;let t=0;for(let i of this._colorGradients){if(i.gradient===e){this._colorGradients.splice(t,1);break}t++}return this}resetDrawCache(){for(let e of this._drawWrappers)if(e)for(let t of e)null==t||t.dispose();this._drawWrappers=[]}_fetchR(e,t,i,r,s){return s[(((e=.5*Math.abs(e)+.5)*i%i|0)+((t=.5*Math.abs(t)+.5)*r%r|0)*i)*4]/255}_reset(){this._resetEffect()}_resetEffect(){this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),this._createVertexBuffers()}_createVertexBuffers(){let e;this._vertexBufferSize=this._useInstancing?10:12,this._isAnimationSheetEnabled&&(this._vertexBufferSize+=1),this._isBillboardBased&&this.billboardMode!==xs.BILLBOARDMODE_STRETCHED&&this.billboardMode!==xs.BILLBOARDMODE_STRETCHED_LOCAL||(this._vertexBufferSize+=3),this._useRampGradients&&(this._vertexBufferSize+=4);let t=this._engine,i=this._vertexBufferSize*(this._useInstancing?1:4);this._vertexData=new Float32Array(this._capacity*i),this._vertexBuffer=new sm.l(t,this._vertexData,!0,i);let r=0,s=this._vertexBuffer.createVertexBuffer(sm.o.PositionKind,r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[sm.o.PositionKind]=s,r+=3;let n=this._vertexBuffer.createVertexBuffer(sm.o.ColorKind,r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[sm.o.ColorKind]=n,r+=4;let a=this._vertexBuffer.createVertexBuffer("angle",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.angle=a,r+=1;let o=this._vertexBuffer.createVertexBuffer("size",r,2,this._vertexBufferSize,this._useInstancing);if(this._vertexBuffers.size=o,r+=2,this._isAnimationSheetEnabled){let e=this._vertexBuffer.createVertexBuffer("cellIndex",r,1,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.cellIndex=e,r+=1}if(!this._isBillboardBased||this.billboardMode===xs.BILLBOARDMODE_STRETCHED||this.billboardMode===xs.BILLBOARDMODE_STRETCHED_LOCAL){let e=this._vertexBuffer.createVertexBuffer("direction",r,3,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.direction=e,r+=3}if(this._useRampGradients){let e=this._vertexBuffer.createVertexBuffer("remapData",r,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers.remapData=e,r+=4}if(this._useInstancing){let i=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new sm.l(t,i,!1,2),e=this._spriteBuffer.createVertexBuffer("offset",0,2)}else e=this._vertexBuffer.createVertexBuffer("offset",r,2,this._vertexBufferSize,this._useInstancing),r+=2;this._vertexBuffers.offset=e,this.resetDrawCache()}_createIndexBuffer(){if(this._useInstancing){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]));return}let e=[],t=[],i=0;for(let r=0;r{e instanceof xs?this._subEmitters.push([new xt(e)]):e instanceof xt?this._subEmitters.push([e]):e instanceof Array&&this._subEmitters.push(e)})}start(e=this.startDelay){var t;if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}if(this._prepareSubEmitterInternalArray(),this._started=!0,this._stopped=!1,this._actualFrame=0,this._subEmitters&&0!=this._subEmitters.length&&(this.activeSubSystems=[]),this._emitRateGradients&&(this._emitRateGradients.length>0&&(this._currentEmitRateGradient=this._emitRateGradients[0],this._currentEmitRate1=this._currentEmitRateGradient.getFactor(),this._currentEmitRate2=this._currentEmitRate1),this._emitRateGradients.length>1&&(this._currentEmitRate2=this._emitRateGradients[1].getFactor())),this._startSizeGradients&&(this._startSizeGradients.length>0&&(this._currentStartSizeGradient=this._startSizeGradients[0],this._currentStartSize1=this._currentStartSizeGradient.getFactor(),this._currentStartSize2=this._currentStartSize1),this._startSizeGradients.length>1&&(this._currentStartSize2=this._startSizeGradients[1].getFactor())),this.preWarmCycles){(null===(t=this.emitter)||void 0===t?void 0:t.getClassName().indexOf("Mesh"))!==-1&&this.emitter.computeWorldMatrix(!0);let e=this.noiseTexture;if(e&&e.onGeneratedObservable)e.onGeneratedObservable.addOnce(()=>{setTimeout(()=>{for(let t=0;t0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(e=!0){!this._stopped&&(this.onStoppedObservable.notifyObservers(this),this._stopped=!0,e&&this._stopSubEmitters())}reset(){this._stockParticles.length=0,this._particles.length=0}_appendParticleVertex(e,t,i,r){let s=e*this._vertexBufferSize;if(this._vertexData[s++]=t.position.x+this.worldOffset.x,this._vertexData[s++]=t.position.y+this.worldOffset.y,this._vertexData[s++]=t.position.z+this.worldOffset.z,this._vertexData[s++]=t.color.r,this._vertexData[s++]=t.color.g,this._vertexData[s++]=t.color.b,this._vertexData[s++]=t.color.a,this._vertexData[s++]=t.angle,this._vertexData[s++]=t.scale.x*t.size,this._vertexData[s++]=t.scale.y*t.size,this._isAnimationSheetEnabled&&(this._vertexData[s++]=t.cellIndex),this._isBillboardBased)(this.billboardMode===xs.BILLBOARDMODE_STRETCHED||this.billboardMode===xs.BILLBOARDMODE_STRETCHED_LOCAL)&&(this._vertexData[s++]=t.direction.x,this._vertexData[s++]=t.direction.y,this._vertexData[s++]=t.direction.z);else if(t._initialDirection){let e=t._initialDirection;this.isLocal&&(rf.P.TransformNormalToRef(e,this._emitterWorldMatrix,rf.jp.Vector3[0]),e=rf.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}else{let e=t.direction;this.isLocal&&(rf.P.TransformNormalToRef(e,this._emitterWorldMatrix,rf.jp.Vector3[0]),e=rf.jp.Vector3[0]),0===e.x&&0===e.z&&(e.x=.001),this._vertexData[s++]=e.x,this._vertexData[s++]=e.y,this._vertexData[s++]=e.z}this._useRampGradients&&t.remapData&&(this._vertexData[s++]=t.remapData.x,this._vertexData[s++]=t.remapData.y,this._vertexData[s++]=t.remapData.z,this._vertexData[s++]=t.remapData.w),this._useInstancing||(this._isAnimationSheetEnabled&&(0===i?i=this._epsilon:1===i&&(i=1-this._epsilon),0===r?r=this._epsilon:1===r&&(r=1-this._epsilon)),this._vertexData[s++]=i,this._vertexData[s++]=r)}_stopSubEmitters(){this.activeSubSystems&&(this.activeSubSystems.forEach(e=>{e.stop(!0)}),this.activeSubSystems=[])}_removeFromRoot(){if(!this._rootParticleSystem)return;let e=this._rootParticleSystem.activeSubSystems.indexOf(this);-1!==e&&this._rootParticleSystem.activeSubSystems.splice(e,1),this._rootParticleSystem=null}_update(e){let t;if(this._alive=this._particles.length>0,this.emitter.position){let e=this.emitter;this._emitterWorldMatrix=e.getWorldMatrix()}else{let e=this.emitter;this._emitterWorldMatrix=rf.y3.Translation(e.x,e.y,e.z)}this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix),this.updateFunction(this._particles);for(let i=0;i0){let e=rk.R.Clamp(this._actualFrame/this.targetStopDuration);v9.GetCurrentGradient(e,this._lifeTimeGradients,(i,r)=>{let s=i.getFactor(),n=r.getFactor(),a=(e-i.gradient)/(r.gradient-i.gradient);t.lifeTime=rk.R.Lerp(s,n,a)})}else t.lifeTime=rk.R.RandomRange(this.minLifeTime,this.maxLifeTime);let e=rk.R.RandomRange(this.minEmitPower,this.maxEmitPower);if(this.startPositionFunction?this.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal):this.particleEmitterType.startPositionFunction(this._emitterWorldMatrix,t.position,t,this.isLocal),this.isLocal&&(t._localPosition?t._localPosition.copyFrom(t.position):t._localPosition=t.position.clone(),rf.P.TransformCoordinatesToRef(t._localPosition,this._emitterWorldMatrix,t.position)),this.startDirectionFunction?this.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal):this.particleEmitterType.startDirectionFunction(this._emitterWorldMatrix,t.direction,t,this.isLocal,this._emitterInverseWorldMatrix),0===e?t._initialDirection?t._initialDirection.copyFrom(t.direction):t._initialDirection=t.direction.clone():t._initialDirection=null,t.direction.scaleInPlace(e),this._sizeGradients&&0!==this._sizeGradients.length?(t._currentSizeGradient=this._sizeGradients[0],t._currentSize1=t._currentSizeGradient.getFactor(),t.size=t._currentSize1,this._sizeGradients.length>1?t._currentSize2=this._sizeGradients[1].getFactor():t._currentSize2=t._currentSize1):t.size=rk.R.RandomRange(this.minSize,this.maxSize),t.scale.copyFromFloats(rk.R.RandomRange(this.minScaleX,this.maxScaleX),rk.R.RandomRange(this.minScaleY,this.maxScaleY)),this._startSizeGradients&&this._startSizeGradients[0]&&this.targetStopDuration){let e=this._actualFrame/this.targetStopDuration;v9.GetCurrentGradient(e,this._startSizeGradients,(e,i,r)=>{e!==this._currentStartSizeGradient&&(this._currentStartSize1=this._currentStartSize2,this._currentStartSize2=i.getFactor(),this._currentStartSizeGradient=e);let s=rk.R.Lerp(this._currentStartSize1,this._currentStartSize2,r);t.scale.scaleInPlace(s)})}if(this._angularSpeedGradients&&0!==this._angularSpeedGradients.length?(t._currentAngularSpeedGradient=this._angularSpeedGradients[0],t.angularSpeed=t._currentAngularSpeedGradient.getFactor(),t._currentAngularSpeed1=t.angularSpeed,this._angularSpeedGradients.length>1?t._currentAngularSpeed2=this._angularSpeedGradients[1].getFactor():t._currentAngularSpeed2=t._currentAngularSpeed1):t.angularSpeed=rk.R.RandomRange(this.minAngularSpeed,this.maxAngularSpeed),t.angle=rk.R.RandomRange(this.minInitialRotation,this.maxInitialRotation),this._velocityGradients&&this._velocityGradients.length>0&&(t._currentVelocityGradient=this._velocityGradients[0],t._currentVelocity1=t._currentVelocityGradient.getFactor(),this._velocityGradients.length>1?t._currentVelocity2=this._velocityGradients[1].getFactor():t._currentVelocity2=t._currentVelocity1),this._limitVelocityGradients&&this._limitVelocityGradients.length>0&&(t._currentLimitVelocityGradient=this._limitVelocityGradients[0],t._currentLimitVelocity1=t._currentLimitVelocityGradient.getFactor(),this._limitVelocityGradients.length>1?t._currentLimitVelocity2=this._limitVelocityGradients[1].getFactor():t._currentLimitVelocity2=t._currentLimitVelocity1),this._dragGradients&&this._dragGradients.length>0&&(t._currentDragGradient=this._dragGradients[0],t._currentDrag1=t._currentDragGradient.getFactor(),this._dragGradients.length>1?t._currentDrag2=this._dragGradients[1].getFactor():t._currentDrag2=t._currentDrag1),this._colorGradients&&0!==this._colorGradients.length)t._currentColorGradient=this._colorGradients[0],t._currentColorGradient.getColorToRef(t.color),t._currentColor1.copyFrom(t.color),this._colorGradients.length>1?this._colorGradients[1].getColorToRef(t._currentColor2):t._currentColor2.copyFrom(t.color);else{let e=rk.R.RandomRange(0,1);rm.HE.LerpToRef(this.color1,this.color2,e,t.color),this.colorDead.subtractToRef(t.color,this._colorDiff),this._colorDiff.scaleToRef(1/t.lifeTime,t.colorStep)}this._isAnimationSheetEnabled&&(t._initialStartSpriteCellID=this.startSpriteCellID,t._initialEndSpriteCellID=this.endSpriteCellID,t._initialSpriteCellLoop=this.spriteCellLoop),t.direction.addInPlace(this._inheritedVelocityOffset),this._useRampGradients&&(t.remapData=new rf.Lt(0,1,0,1)),this.noiseTexture&&(t._randomNoiseCoordinates1?(t._randomNoiseCoordinates1.copyFromFloats(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2.copyFromFloats(Math.random(),Math.random(),Math.random())):(t._randomNoiseCoordinates1=new rf.P(Math.random(),Math.random(),Math.random()),t._randomNoiseCoordinates2=new rf.P(Math.random(),Math.random(),Math.random()))),t._inheritParticleInfoToSubEmitters()}}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1){let r=[sm.o.PositionKind,sm.o.ColorKind,"angle","offset","size"];return e&&r.push("cellIndex"),t||r.push("direction"),i&&r.push("remapData"),r}static _GetEffectCreationOptions(e=!1,t=!1){let i=["invView","view","projection","textureMask","translationPivot","eyePosition"];return(0,lH.qx)(i),e&&i.push("particlesInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t){if(this._scene&&(0,lH.lK)(this,this._scene,e),this._isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),t===xs.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this._useRampGradients&&e.push("#define RAMPGRADIENT"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case xs.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case xs.BILLBOARDMODE_STRETCHED:case xs.BILLBOARDMODE_STRETCHED_LOCAL:e.push("#define BILLBOARDSTRETCHED"),this.billboardMode===xs.BILLBOARDMODE_STRETCHED_LOCAL&&e.push("#define BILLBOARDSTRETCHED_LOCAL");break;case xs.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...xs._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled,this._isBillboardBased&&this.billboardMode!==xs.BILLBOARDMODE_STRETCHED&&this.billboardMode!==xs.BILLBOARDMODE_STRETCHED_LOCAL,this._useRampGradients)),e.push(...xs._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","rampSampler"),this._imageProcessingConfiguration&&(nY.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),nY.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._engine._features.supportRenderPasses?this._engine.currentRenderPassId:0,s=this._drawWrappers[r];s||(s=this._drawWrappers[r]=[]);let n=s[e];n||((n=new nk.q(this._engine)).drawContext&&(n.drawContext.useInstancing=this._useInstancing),s[e]=n);let a=i.join("\n");if(n.defines!==a){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),n.setEffect(this._engine.createEffect("particles",e,t,i,a),a)}return n}animate(e=!1){var t;let i;if(this._started){if(!e&&this._scene){if(!this.isReady()||this._currentRenderId===this._scene.getFrameId())return;this._currentRenderId=this._scene.getFrameId()}if(this._scaledUpdateSpeed=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this.manualEmitCount>-1)i=this.manualEmitCount,this._newPartsExcess=0,this.manualEmitCount=0;else{let e=this.emitRate;if(this._emitRateGradients&&this._emitRateGradients.length>0&&this.targetStopDuration){let t=this._actualFrame/this.targetStopDuration;v9.GetCurrentGradient(t,this._emitRateGradients,(t,i,r)=>{t!==this._currentEmitRateGradient&&(this._currentEmitRate1=this._currentEmitRate2,this._currentEmitRate2=i.getFactor(),this._currentEmitRateGradient=t),e=rk.R.Lerp(this._currentEmitRate1,this._currentEmitRate2,r)})}i=e*this._scaledUpdateSpeed>>0,this._newPartsExcess+=e*this._scaledUpdateSpeed-i}if(this._newPartsExcess>1&&(i+=this._newPartsExcess>>0,this._newPartsExcess-=this._newPartsExcess>>0),this._alive=!1,this._stopped?i=0:(this._actualFrame+=this._scaledUpdateSpeed,this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop()),this._update(i),this._stopped&&!this._alive&&(this._started=!1,this.onAnimationEnd&&this.onAnimationEnd(),this.disposeOnStop&&this._scene&&this._scene._toBeDisposed.push(this)),!e){let e=0;for(let t=0;t=0&&(d.invertToRef(rf.jp.Matrix[0]),u.setMatrix("invView",rf.jp.Matrix[0])),void 0!==this._vertexArrayObject?(null===(r=this._scene)||void 0===r?void 0:r.forceWireframe)?c.bindBuffers(this._vertexBuffers,this._linesIndexBufferUseInstancing,u):(this._vertexArrayObject||(this._vertexArrayObject=this._engine.recordVertexArrayObject(this._vertexBuffers,null,u)),this._engine.bindVertexArrayObject(this._vertexArrayObject,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:this._indexBuffer)):this._indexBuffer?c.bindBuffers(this._vertexBuffers,(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)?this._linesIndexBuffer:this._indexBuffer,u):c.bindBuffers(this._vertexBuffers,(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._linesIndexBufferUseInstancing:null,u),this.useLogarithmicDepth&&this._scene&&nE.G.BindLogDepth(p,u,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(u),e){case xs.BLENDMODE_ADD:c.setAlphaMode(1);break;case xs.BLENDMODE_ONEONE:c.setAlphaMode(6);break;case xs.BLENDMODE_STANDARD:c.setAlphaMode(2);break;case xs.BLENDMODE_MULTIPLY:c.setAlphaMode(4)}return this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(u),this._useInstancing?(null===(o=this._scene)||void 0===o?void 0:o.forceWireframe)?c.drawElementsType(6,0,10,this._particles.length):c.drawArraysType(7,0,4,this._particles.length):(null===(l=this._scene)||void 0===l?void 0:l.forceWireframe)?c.drawElementsType(1,0,10*this._particles.length):c.drawElementsType(0,0,6*this._particles.length),this._particles.length}render(){if(!this.isReady()||!this._particles.length)return 0;let e=this._engine;e.setState&&(e.setState(!1),this.forceDepthWrite&&e.setDepthWrite(!0));let t=0;return t=this.blendMode===xs.BLENDMODE_MULTIPLYADD?this._render(xs.BLENDMODE_MULTIPLY)+this._render(xs.BLENDMODE_ADD):this._render(this.blendMode),this._engine.unbindInstanceAttributes(),this._engine.setAlphaMode(0),t}dispose(e=!0){if(this.resetDrawCache(),this._vertexBuffer&&(this._vertexBuffer.dispose(),this._vertexBuffer=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._indexBuffer&&(this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null),this._linesIndexBuffer&&(this._engine._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null),this._linesIndexBufferUseInstancing&&(this._engine._releaseBuffer(this._linesIndexBufferUseInstancing),this._linesIndexBufferUseInstancing=null),this._vertexArrayObject&&(this._engine.releaseVertexArrayObject(this._vertexArrayObject),this._vertexArrayObject=null),e&&this.particleTexture&&(this.particleTexture.dispose(),this.particleTexture=null),e&&this.noiseTexture&&(this.noiseTexture.dispose(),this.noiseTexture=null),this._rampGradientsTexture&&(this._rampGradientsTexture.dispose(),this._rampGradientsTexture=null),this._removeFromRoot(),this.subEmitters&&!this._subEmitters&&this._prepareSubEmitterInternalArray(),this._subEmitters&&this._subEmitters.length){for(let e=0;e-1&&this._scene.particleSystems.splice(e,1),this._scene._activeParticleSystems.dispose()}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onStoppedObservable.clear(),this.reset()}clone(e,t,i=!1){let r=Object.assign({},this._customWrappers),s=null,n=this._engine;if(n.createEffectForParticles&&null!=this.customShader){let e=(s=this.customShader).shaderOptions.defines.length>0?s.shaderOptions.defines.join("\n"):"",t=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e);r[0]?r[0].effect=t:this.setCustomEffect(t,0)}let a=this.serialize(i),o=xs.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,this.preventAutoStart||o.start(),o}serialize(e=!1){let t={};if(xs._Serialize(t,this,e),t.textureMask=this.textureMask.asArray(),t.customShader=this.customShader,t.preventAutoStart=this.preventAutoStart,this.subEmitters)for(let i of(t.subEmitters=[],this._subEmitters||this._prepareSubEmitterInternalArray(),this._subEmitters)){let r=[];for(let t of i)r.push(t.serialize(e));t.subEmitters.push(r)}return t}static _Serialize(e,t,i){if(e.name=t.name,e.id=t.id,e.capacity=t.getCapacity(),e.disposeOnStop=t.disposeOnStop,e.manualEmitCount=t.manualEmitCount,t.emitter.position){let i=t.emitter;e.emitterId=i.id}else{let i=t.emitter;e.emitter=i.asArray()}t.particleEmitterType&&(e.particleEmitterType=t.particleEmitterType.serialize()),t.particleTexture&&(i?e.texture=t.particleTexture.serialize():(e.textureName=t.particleTexture.name,e.invertY=!!t.particleTexture._invertY)),e.isLocal=t.isLocal,rG.p4.AppendSerializedAnimations(t,e),e.beginAnimationOnStart=t.beginAnimationOnStart,e.beginAnimationFrom=t.beginAnimationFrom,e.beginAnimationTo=t.beginAnimationTo,e.beginAnimationLoop=t.beginAnimationLoop,e.startDelay=t.startDelay,e.renderingGroupId=t.renderingGroupId,e.isBillboardBased=t.isBillboardBased,e.billboardMode=t.billboardMode,e.minAngularSpeed=t.minAngularSpeed,e.maxAngularSpeed=t.maxAngularSpeed,e.minSize=t.minSize,e.maxSize=t.maxSize,e.minScaleX=t.minScaleX,e.maxScaleX=t.maxScaleX,e.minScaleY=t.minScaleY,e.maxScaleY=t.maxScaleY,e.minEmitPower=t.minEmitPower,e.maxEmitPower=t.maxEmitPower,e.minLifeTime=t.minLifeTime,e.maxLifeTime=t.maxLifeTime,e.emitRate=t.emitRate,e.gravity=t.gravity.asArray(),e.noiseStrength=t.noiseStrength.asArray(),e.color1=t.color1.asArray(),e.color2=t.color2.asArray(),e.colorDead=t.colorDead.asArray(),e.updateSpeed=t.updateSpeed,e.targetStopDuration=t.targetStopDuration,e.blendMode=t.blendMode,e.preWarmCycles=t.preWarmCycles,e.preWarmStepOffset=t.preWarmStepOffset,e.minInitialRotation=t.minInitialRotation,e.maxInitialRotation=t.maxInitialRotation,e.startSpriteCellID=t.startSpriteCellID,e.spriteCellLoop=t.spriteCellLoop,e.endSpriteCellID=t.endSpriteCellID,e.spriteCellChangeSpeed=t.spriteCellChangeSpeed,e.spriteCellWidth=t.spriteCellWidth,e.spriteCellHeight=t.spriteCellHeight,e.spriteRandomStartCell=t.spriteRandomStartCell,e.isAnimationSheetEnabled=t.isAnimationSheetEnabled,e.useLogarithmicDepth=t.useLogarithmicDepth;let r=t.getColorGradients();if(r)for(let t of(e.colorGradients=[],r)){let i={gradient:t.gradient,color1:t.color1.asArray()};t.color2?i.color2=t.color2.asArray():i.color2=t.color1.asArray(),e.colorGradients.push(i)}let s=t.getRampGradients();if(s){for(let t of(e.rampGradients=[],s)){let i={gradient:t.gradient,color:t.color.asArray()};e.rampGradients.push(i)}e.useRampGradients=t.useRampGradients}let n=t.getColorRemapGradients();if(n)for(let t of(e.colorRemapGradients=[],n)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.colorRemapGradients.push(i)}let a=t.getAlphaRemapGradients();if(a)for(let t of(e.alphaRemapGradients=[],a)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.alphaRemapGradients.push(i)}let o=t.getSizeGradients();if(o)for(let t of(e.sizeGradients=[],o)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.sizeGradients.push(i)}let l=t.getAngularSpeedGradients();if(l)for(let t of(e.angularSpeedGradients=[],l)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.angularSpeedGradients.push(i)}let h=t.getVelocityGradients();if(h)for(let t of(e.velocityGradients=[],h)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.velocityGradients.push(i)}let u=t.getDragGradients();if(u)for(let t of(e.dragGradients=[],u)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.dragGradients.push(i)}let c=t.getEmitRateGradients();if(c)for(let t of(e.emitRateGradients=[],c)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.emitRateGradients.push(i)}let d=t.getStartSizeGradients();if(d)for(let t of(e.startSizeGradients=[],d)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.startSizeGradients.push(i)}let p=t.getLifeTimeGradients();if(p)for(let t of(e.lifeTimeGradients=[],p)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.lifeTimeGradients.push(i)}let _=t.getLimitVelocityGradients();if(_){for(let t of(e.limitVelocityGradients=[],_)){let i={gradient:t.gradient,factor1:t.factor1};void 0!==t.factor2?i.factor2=t.factor2:i.factor2=t.factor1,e.limitVelocityGradients.push(i)}e.limitVelocityDamping=t.limitVelocityDamping}t.noiseTexture&&(e.noiseTexture=t.noiseTexture.serialize())}static _Parse(e,t,i,r){var s,n,a;let o,l;o=i instanceof sK.B?null:i;let h=(0,rg.q)("BABYLON.Texture");if(h&&o&&(e.texture?t.particleTexture=h.Parse(e.texture,o,r):e.textureName&&(t.particleTexture=new h(r+e.textureName,o,!1,void 0===e.invertY||e.invertY),t.particleTexture.name=e.textureName)),e.emitterId||0===e.emitterId||void 0!==e.emitter?e.emitterId&&o?t.emitter=o.getLastMeshById(e.emitterId):t.emitter=rf.P.FromArray(e.emitter):t.emitter=rf.P.Zero(),t.isLocal=!!e.isLocal,void 0!==e.renderingGroupId&&(t.renderingGroupId=e.renderingGroupId),void 0!==e.isBillboardBased&&(t.isBillboardBased=e.isBillboardBased),void 0!==e.billboardMode&&(t.billboardMode=e.billboardMode),void 0!==e.useLogarithmicDepth&&(t.useLogarithmicDepth=e.useLogarithmicDepth),e.animations){for(let i=0;i0?l.shaderOptions.defines.join("\n"):"";o=n.createEffectForParticles(l.shaderPath.fragmentElement,l.shaderOptions.uniforms,l.shaderOptions.samplers,t)}let h=new xs(a,s||e.capacity,t,o,e.isAnimationSheetEnabled);if(h.customShader=l,h._rootUrl=i,e.id&&(h.id=e.id),e.subEmitters)for(let r of(h.subEmitters=[],e.subEmitters)){let e=[];for(let s of r)e.push(xt.Parse(s,t,i));h.subEmitters.push(e)}return xs._Parse(e,h,t,i),e.textureMask&&(h.textureMask=rm.HE.FromArray(e.textureMask)),e.preventAutoStart&&(h.preventAutoStart=e.preventAutoStart),r||h.preventAutoStart||h.start(),h}}xs.BILLBOARDMODE_Y=2,xs.BILLBOARDMODE_ALL=7,xs.BILLBOARDMODE_STRETCHED=8,xs.BILLBOARDMODE_STRETCHED_LOCAL=9,xt._ParseParticleSystem=xs.Parse;let xn=`#ifdef CLIPPLANE +in float fClipDistance; +#endif +#ifdef CLIPPLANE2 +in float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +in float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +in float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +in float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +in float fClipDistance6; +#endif +`;nw.v.IncludesShadersStore.clipPlaneFragmentDeclaration2=xn;let xa=`precision highp float; +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; +#include +#include +#include +#include +#include +void main() { +#include +vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; +#ifdef BLENDMULTIPLYMODE +float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); +#endif +#include +#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); +#else +#ifdef IMAGEPROCESSING +gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); +#endif +#endif +} +`;nw.v.ShadersStore.gpuRenderParticlesPixelShader=xa;let xo=`#ifdef CLIPPLANE +uniform vec4 vClipPlane;out float fClipDistance; +#endif +#ifdef CLIPPLANE2 +uniform vec4 vClipPlane2;out float fClipDistance2; +#endif +#ifdef CLIPPLANE3 +uniform vec4 vClipPlane3;out float fClipDistance3; +#endif +#ifdef CLIPPLANE4 +uniform vec4 vClipPlane4;out float fClipDistance4; +#endif +#ifdef CLIPPLANE5 +uniform vec4 vClipPlane5;out float fClipDistance5; +#endif +#ifdef CLIPPLANE6 +uniform vec4 vClipPlane6;out float fClipDistance6; +#endif +`;nw.v.IncludesShadersStore.clipPlaneVertexDeclaration2=xo;let xl=`precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; +#ifdef LOCAL +uniform mat4 emitterWM; +#endif +attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; +#ifndef BILLBOARD +attribute vec3 initialDirection; +#endif +#ifdef BILLBOARDSTRETCHED +attribute vec3 direction; +#endif +attribute float angle; +#ifdef ANIMATESHEET +attribute float cellIndex; +#endif +attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; +#if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) +uniform mat4 invView; +#endif +#include +#include +#ifdef COLORGRADIENTS +uniform sampler2D colorGradientSampler; +#else +uniform vec4 colorDead;attribute vec4 color; +#endif +#ifdef ANIMATESHEET +uniform vec3 sheetInfos; +#endif +#ifdef BILLBOARD +uniform vec3 eyePosition; +#endif +vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#ifdef BILLBOARDSTRETCHED +vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; +#ifdef LOCAL +return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; +#else +return (position+worldOffset)+alignedCorner; +#endif +} +#endif +void main() { +#ifdef ANIMATESHEET +float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; +#else +vUV=uv; +#endif +float ratio=age/life; +#ifdef COLORGRADIENTS +vColor=texture2D(colorGradientSampler,vec2(ratio,0)); +#else +vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); +#endif +vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; +#ifdef BILLBOARD +vec4 rotatedCorner;rotatedCorner.w=0.; +#ifdef BILLBOARDY +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#elif defined(BILLBOARDSTRETCHED) +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); +#else +rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; +#ifdef LOCAL +vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; +#else +vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; +#endif +vPositionW=(invView*viewPosition).xyz; +#endif +#else +vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); +#endif +gl_Position=projection*viewPosition; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=vec4(vPositionW,1.0); +#endif +#include +#include +}`;nw.v.ShadersStore.gpuRenderParticlesVertexShader=xl;class xh extends n3{static get IsSupported(){if(!rL.l.LastCreatedEngine)return!1;let e=rL.l.LastCreatedEngine.getCaps();return e.supportTransformFeedbacks||e.supportComputeShaders}_createIndexBuffer(){this._linesIndexBufferUseInstancing=this._engine.createIndexBuffer(new Uint32Array([0,1,1,3,3,2,2,0,0,3]),void 0,"GPUParticleSystemLinesIndexBuffer")}getCapacity(){return this._capacity}get maxActiveParticleCount(){return this._maxActiveParticleCount}set maxActiveParticleCount(e){this._maxActiveParticleCount=Math.min(e,this._capacity)}get activeParticleCount(){return this.maxActiveParticleCount}set activeParticleCount(e){this.maxActiveParticleCount=e}isReady(){if(!this.emitter||this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady()||!this.particleTexture||!this.particleTexture.isReady())return!1;if(this.blendMode!==xs.BLENDMODE_MULTIPLYADD){if(!this._getWrapper(this.blendMode).effect.isReady())return!1}else if(!this._getWrapper(xs.BLENDMODE_MULTIPLY).effect.isReady()||!this._getWrapper(xs.BLENDMODE_ADD).effect.isReady())return!1;return this._platform.isUpdateBufferCreated()?this._platform.isUpdateBufferReady():(this._recreateUpdateEffect(),!1)}isStarted(){return this._started}isStopped(){return this._stopped}isStopping(){return!1}getActiveCount(){return this._currentActiveCount}start(e=this.startDelay){if(!this.targetStopDuration&&this._hasTargetStopDurationDependantGradient())throw"Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";if(e){setTimeout(()=>{this.start(0)},e);return}this._started=!0,this._stopped=!1,this._preWarmDone=!1,this.beginAnimationOnStart&&this.animations&&this.animations.length>0&&this._scene&&this._scene.beginAnimation(this,this.beginAnimationFrom,this.beginAnimationTo,this.beginAnimationLoop)}stop(){this._stopped||(this._stopped=!0)}reset(){this._releaseBuffers(),this._platform.releaseVertexBuffers(),this._currentActiveCount=0,this._targetIndex=0}getClassName(){return"GPUParticleSystem"}getCustomEffect(e=0){var t,i;return null!==(i=null===(t=this._customWrappers[e])||void 0===t?void 0:t.effect)&&void 0!==i?i:this._customWrappers[0].effect}_getCustomDrawWrapper(e=0){var t;return null!==(t=this._customWrappers[e])&&void 0!==t?t:this._customWrappers[0]}setCustomEffect(e,t=0){this._customWrappers[t]=new nk.q(this._engine),this._customWrappers[t].effect=e}get onBeforeDrawParticlesObservable(){return this._onBeforeDrawParticlesObservable||(this._onBeforeDrawParticlesObservable=new r_.y$),this._onBeforeDrawParticlesObservable}get vertexShaderName(){return"gpuRenderParticles"}get vertexBuffers(){return this._renderVertexBuffers[1^this._targetIndex]}get indexBuffer(){return null}_removeGradientAndTexture(e,t,i){return super._removeGradientAndTexture(e,t,i),this._releaseBuffers(),this}addColorGradient(e,t){this._colorGradients||(this._colorGradients=[]);let i=new v6(e,t);return this._colorGradients.push(i),this._refreshColorGradient(!0),this._releaseBuffers(),this}_refreshColorGradient(e=!1){this._colorGradients&&(e&&this._colorGradients.sort((e,t)=>e.gradientt.gradient?1:0),this._colorGradientsTexture&&(this._colorGradientsTexture.dispose(),this._colorGradientsTexture=null))}forceRefreshGradients(){this._refreshColorGradient(),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture"),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture"),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture"),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture"),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture"),this.reset()}removeColorGradient(e){return this._removeGradientAndTexture(e,this._colorGradients,this._colorGradientsTexture),this._colorGradientsTexture=null,this}resetDrawCache(){var e;for(let t in this._drawWrappers)null===(e=this._drawWrappers[t].drawContext)||void 0===e||e.reset()}_addFactorGradient(e,t,i){let r=new v7(t,i);e.push(r),this._releaseBuffers()}addSizeGradient(e,t){return this._sizeGradients||(this._sizeGradients=[]),this._addFactorGradient(this._sizeGradients,e,t),this._refreshFactorGradient(this._sizeGradients,"_sizeGradientsTexture",!0),this._releaseBuffers(),this}removeSizeGradient(e){return this._removeGradientAndTexture(e,this._sizeGradients,this._sizeGradientsTexture),this._sizeGradientsTexture=null,this}_refreshFactorGradient(e,t,i=!1){e&&(i&&e.sort((e,t)=>e.gradientt.gradient?1:0),this[t]&&(this[t].dispose(),this[t]=null))}addAngularSpeedGradient(e,t){return this._angularSpeedGradients||(this._angularSpeedGradients=[]),this._addFactorGradient(this._angularSpeedGradients,e,t),this._refreshFactorGradient(this._angularSpeedGradients,"_angularSpeedGradientsTexture",!0),this._releaseBuffers(),this}removeAngularSpeedGradient(e){return this._removeGradientAndTexture(e,this._angularSpeedGradients,this._angularSpeedGradientsTexture),this._angularSpeedGradientsTexture=null,this}addVelocityGradient(e,t){return this._velocityGradients||(this._velocityGradients=[]),this._addFactorGradient(this._velocityGradients,e,t),this._refreshFactorGradient(this._velocityGradients,"_velocityGradientsTexture",!0),this._releaseBuffers(),this}removeVelocityGradient(e){return this._removeGradientAndTexture(e,this._velocityGradients,this._velocityGradientsTexture),this._velocityGradientsTexture=null,this}addLimitVelocityGradient(e,t){return this._limitVelocityGradients||(this._limitVelocityGradients=[]),this._addFactorGradient(this._limitVelocityGradients,e,t),this._refreshFactorGradient(this._limitVelocityGradients,"_limitVelocityGradientsTexture",!0),this._releaseBuffers(),this}removeLimitVelocityGradient(e){return this._removeGradientAndTexture(e,this._limitVelocityGradients,this._limitVelocityGradientsTexture),this._limitVelocityGradientsTexture=null,this}addDragGradient(e,t){return this._dragGradients||(this._dragGradients=[]),this._addFactorGradient(this._dragGradients,e,t),this._refreshFactorGradient(this._dragGradients,"_dragGradientsTexture",!0),this._releaseBuffers(),this}removeDragGradient(e){return this._removeGradientAndTexture(e,this._dragGradients,this._dragGradientsTexture),this._dragGradientsTexture=null,this}addEmitRateGradient(){return this}removeEmitRateGradient(){return this}addStartSizeGradient(){return this}removeStartSizeGradient(){return this}addColorRemapGradient(){return this}removeColorRemapGradient(){return this}addAlphaRemapGradient(){return this}removeAlphaRemapGradient(){return this}addRampGradient(){return this}removeRampGradient(){return this}getRampGradients(){return null}get useRampGradients(){return!1}set useRampGradients(e){}addLifeTimeGradient(){return this}removeLifeTimeGradient(){return this}constructor(e,t,i,r=null,s=!1){if(super(e),this.layerMask=268435455,this._accumulatedCount=0,this._renderVertexBuffers=[],this._targetIndex=0,this._currentRenderId=-1,this._currentRenderingCameraUniqueId=-1,this._started=!1,this._stopped=!1,this._timeDelta=0,this.updateInAnimate=!1,this._actualFrame=0,this._rawTextureWidth=256,this.onDisposeObservable=new r_.y$,this.onStoppedObservable=new r_.y$,this.forceDepthWrite=!1,this._preWarmDone=!1,this.isLocal=!1,this.isGPU=!0,this._onBeforeDrawParticlesObservable=null,i&&"Scene"!==i.getClassName()?(this._engine=i,this.defaultProjectionMatrix=rf.y3.PerspectiveFovLH(.8,1,.1,100,this._engine.isNDCHalfZRange)):(this._scene=i||rL.l.LastCreatedScene,this._engine=this._scene.getEngine(),this.uniqueId=this._scene.getUniqueId(),this._scene.particleSystems.push(this)),this._engine.getCaps().supportComputeShaders){if(!(0,rg.q)("BABYLON.ComputeShaderParticleSystem"))throw Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,rg.q)("BABYLON.ComputeShaderParticleSystem"))(this,this._engine)}else{if(!(0,rg.q)("BABYLON.WebGL2ParticleSystem"))throw Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it.");this._platform=new((0,rg.q)("BABYLON.WebGL2ParticleSystem"))(this,this._engine)}this._customWrappers={0:new nk.q(this._engine)},this._customWrappers[0].effect=r,this._drawWrappers={0:new nk.q(this._engine)},this._drawWrappers[0].drawContext&&(this._drawWrappers[0].drawContext.useInstancing=!0),this._createIndexBuffer(),this._attachImageProcessingConfiguration(null),(t=null!=t?t:{}).randomTextureSize||delete t.randomTextureSize;let n=Object.assign({capacity:5e4,randomTextureSize:this._engine.getCaps().maxTextureSize},t),a=t;isFinite(a)&&(n.capacity=a),this._capacity=n.capacity,this._maxActiveParticleCount=n.capacity,this._currentActiveCount=0,this._isAnimationSheetEnabled=s,this.particleEmitterType=new nj;let o=Math.min(this._engine.getCaps().maxTextureSize,n.randomTextureSize),l=[];for(let e=0;e0;)i.push(0)}let a=new Float32Array([.5,.5,1,1,-.5,.5,0,1,.5,-.5,1,0,-.5,-.5,0,0]),o=this._platform.createParticleBuffer(i),l=this._platform.createParticleBuffer(i);this._buffer0=new sm.l(t,o,!1,this._attributesStrideSize),this._buffer1=new sm.l(t,l,!1,this._attributesStrideSize),this._spriteBuffer=new sm.l(t,a,!1,4),this._renderVertexBuffers=[],this._createVertexBuffers(this._buffer0,this._buffer1,this._spriteBuffer),this._createVertexBuffers(this._buffer1,this._buffer0,this._spriteBuffer),this._sourceBuffer=this._buffer0,this._targetBuffer=this._buffer1}_recreateUpdateEffect(){this._createColorGradientTexture(),this._createSizeGradientTexture(),this._createAngularSpeedGradientTexture(),this._createVelocityGradientTexture(),this._createLimitVelocityGradientTexture(),this._createDragGradientTexture();let e=this.particleEmitterType?this.particleEmitterType.getEffectDefines():"";return this._isBillboardBased&&(e+="\n#define BILLBOARD"),this._colorGradientsTexture&&(e+="\n#define COLORGRADIENTS"),this._sizeGradientsTexture&&(e+="\n#define SIZEGRADIENTS"),this._angularSpeedGradientsTexture&&(e+="\n#define ANGULARSPEEDGRADIENTS"),this._velocityGradientsTexture&&(e+="\n#define VELOCITYGRADIENTS"),this._limitVelocityGradientsTexture&&(e+="\n#define LIMITVELOCITYGRADIENTS"),this._dragGradientsTexture&&(e+="\n#define DRAGGRADIENTS"),this.isAnimationSheetEnabled&&(e+="\n#define ANIMATESHEET",this.spriteRandomStartCell&&(e+="\n#define ANIMATESHEETRANDOMSTART")),this.noiseTexture&&(e+="\n#define NOISE"),this.isLocal&&(e+="\n#define LOCAL"),!!this._platform.isUpdateBufferCreated()&&this._cachedUpdateDefines===e||(this._cachedUpdateDefines=e,this._updateBuffer=this._platform.createUpdateBuffer(e),this._platform.isUpdateBufferReady())}_getWrapper(e){let t=this._getCustomDrawWrapper(e);if(null==t?void 0:t.effect)return t;let i=[];this.fillDefines(i,e);let r=this._drawWrappers[e];r||((r=new nk.q(this._engine)).drawContext&&(r.drawContext.useInstancing=!0),this._drawWrappers[e]=r);let s=i.join("\n");if(r.defines!==s){let e=[],t=[],i=[];this.fillUniformsAttributesAndSamplerNames(t,e,i),r.setEffect(this._engine.createEffect("gpuRenderParticles",e,t,i,s),s)}return r}static _GetAttributeNamesOrOptions(e=!1,t=!1,i=!1,r=!1){let s=[sm.o.PositionKind,"age","life","size","angle"];return e||s.push(sm.o.ColorKind),t&&s.push("cellIndex"),i||s.push("initialDirection"),r&&s.push("direction"),s.push("offset",sm.o.UVKind),s}static _GetEffectCreationOptions(e=!1,t=!1){let i=["emitterWM","worldOffset","view","projection","colorDead","invView","translationPivot","eyePosition"];return(0,lH.qx)(i),e&&i.push("sheetInfos"),t&&i.push("logarithmicDepthConstant"),i}fillDefines(e,t=0){if(this._scene&&(0,lH.lK)(this,this._scene,e),t===xs.BLENDMODE_MULTIPLY&&e.push("#define BLENDMULTIPLYMODE"),this.isLocal&&e.push("#define LOCAL"),this.useLogarithmicDepth&&e.push("#define LOGARITHMICDEPTH"),this._isBillboardBased)switch(e.push("#define BILLBOARD"),this.billboardMode){case xs.BILLBOARDMODE_Y:e.push("#define BILLBOARDY");break;case xs.BILLBOARDMODE_STRETCHED:e.push("#define BILLBOARDSTRETCHED");break;case xs.BILLBOARDMODE_ALL:e.push("#define BILLBOARDMODE_ALL")}this._colorGradientsTexture&&e.push("#define COLORGRADIENTS"),this.isAnimationSheetEnabled&&e.push("#define ANIMATESHEET"),this._imageProcessingConfiguration&&(this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines),e.push(""+this._imageProcessingConfigurationDefines.toString()))}fillUniformsAttributesAndSamplerNames(e,t,i){t.push(...xh._GetAttributeNamesOrOptions(!!this._colorGradientsTexture,this._isAnimationSheetEnabled,this._isBillboardBased,this._isBillboardBased&&this.billboardMode===xs.BILLBOARDMODE_STRETCHED)),e.push(...xh._GetEffectCreationOptions(this._isAnimationSheetEnabled,this.useLogarithmicDepth)),i.push("diffuseSampler","colorGradientSampler"),this._imageProcessingConfiguration&&(nY.$.PrepareUniforms(e,this._imageProcessingConfigurationDefines),nY.$.PrepareSamplers(i,this._imageProcessingConfigurationDefines))}animate(e=!1){var t;this._timeDelta=this.updateSpeed*(e?this.preWarmStepOffset:(null===(t=this._scene)||void 0===t?void 0:t.getAnimationRatio())||1),this._actualFrame+=this._timeDelta,!this._stopped&&this.targetStopDuration&&this._actualFrame>=this.targetStopDuration&&this.stop(),this.updateInAnimate&&this._update()}_createFactorGradientTexture(e,t){let i=this[t];if(!e||!e.length||i)return;let r=new Float32Array(this._rawTextureWidth);for(let t=0;t{r[t]=rk.R.Lerp(e.factor1,i.factor1,s)})}this[t]=sJ.CreateRTexture(r,this._rawTextureWidth,1,this._scene||this._engine,!1,!1,1),this[t].name=t.substring(1)}_createSizeGradientTexture(){this._createFactorGradientTexture(this._sizeGradients,"_sizeGradientsTexture")}_createAngularSpeedGradientTexture(){this._createFactorGradientTexture(this._angularSpeedGradients,"_angularSpeedGradientsTexture")}_createVelocityGradientTexture(){this._createFactorGradientTexture(this._velocityGradients,"_velocityGradientsTexture")}_createLimitVelocityGradientTexture(){this._createFactorGradientTexture(this._limitVelocityGradients,"_limitVelocityGradientsTexture")}_createDragGradientTexture(){this._createFactorGradientTexture(this._dragGradients,"_dragGradientsTexture")}_createColorGradientTexture(){if(!this._colorGradients||!this._colorGradients.length||this._colorGradientsTexture)return;let e=new Uint8Array(4*this._rawTextureWidth),t=rm.zZ.Color4[0];for(let i=0;i{rm.HE.LerpToRef(r.color1,s.color1,n,t),e[4*i]=255*t.r,e[4*i+1]=255*t.g,e[4*i+2]=255*t.b,e[4*i+3]=255*t.a})}this._colorGradientsTexture=sJ.CreateRGBATexture(e,this._rawTextureWidth,1,this._scene,!1,!1,1),this._colorGradientsTexture.name="colorGradients"}_render(e,t){var i,r,s,n,a;let o=this._getWrapper(e),l=o.effect;this._engine.enableEffect(o);let h=(null===(i=this._scene)||void 0===i?void 0:i.getViewMatrix())||rf.y3.IdentityReadOnly;if(l.setMatrix("view",h),l.setMatrix("projection",null!==(r=this.defaultProjectionMatrix)&&void 0!==r?r:this._scene.getProjectionMatrix()),l.setTexture("diffuseSampler",this.particleTexture),l.setVector2("translationPivot",this.translationPivot),l.setVector3("worldOffset",this.worldOffset),this.isLocal&&l.setMatrix("emitterWM",t),this._colorGradientsTexture?l.setTexture("colorGradientSampler",this._colorGradientsTexture):l.setDirectColor4("colorDead",this.colorDead),this._isAnimationSheetEnabled&&this.particleTexture){let e=this.particleTexture.getBaseSize();l.setFloat3("sheetInfos",this.spriteCellWidth/e.width,this.spriteCellHeight/e.height,e.width/this.spriteCellWidth)}if(this._isBillboardBased&&this._scene){let e=this._scene.activeCamera;l.setVector3("eyePosition",e.globalPosition)}let u=l.defines;if(this._scene&&(0,lH.an)(l,this,this._scene),u.indexOf("#define BILLBOARDMODE_ALL")>=0){let e=h.clone();e.invert(),l.setMatrix("invView",e)}switch(this.useLogarithmicDepth&&this._scene&&nE.G.BindLogDepth(u,l,this._scene),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(l),e){case xs.BLENDMODE_ADD:this._engine.setAlphaMode(1);break;case xs.BLENDMODE_ONEONE:this._engine.setAlphaMode(6);break;case xs.BLENDMODE_STANDARD:this._engine.setAlphaMode(2);break;case xs.BLENDMODE_MULTIPLY:this._engine.setAlphaMode(4)}return this._platform.bindDrawBuffers(this._targetIndex,l,(null===(s=this._scene)||void 0===s?void 0:s.forceWireframe)?this._linesIndexBufferUseInstancing:null),this._onBeforeDrawParticlesObservable&&this._onBeforeDrawParticlesObservable.notifyObservers(l),(null===(n=this._scene)||void 0===n?void 0:n.forceWireframe)?this._engine.drawElementsType(6,0,10,this._currentActiveCount):this._engine.drawArraysType(7,0,4,this._currentActiveCount),this._engine.setAlphaMode(0),(null===(a=this._scene)||void 0===a?void 0:a.forceWireframe)&&this._engine.unbindInstanceAttributes(),this._currentActiveCount}_update(e){if(!this.emitter||!this._targetBuffer||!this._recreateUpdateEffect())return;if(!e){if(this.emitter.position)e=this.emitter.getWorldMatrix();else{let t=this.emitter;e=rf.jp.Matrix[0],rf.y3.TranslationToRef(t.x,t.y,t.z,e)}}this._platform.preUpdateParticleBuffer(),this._updateBuffer.setFloat("currentCount",this._currentActiveCount),this._updateBuffer.setFloat("timeDelta",this._timeDelta),this._updateBuffer.setFloat("stopFactor",this._stopped?0:1),this._updateBuffer.setInt("randomTextureSize",this._randomTextureSize),this._updateBuffer.setFloat2("lifeTime",this.minLifeTime,this.maxLifeTime),this._updateBuffer.setFloat2("emitPower",this.minEmitPower,this.maxEmitPower),this._colorGradientsTexture||(this._updateBuffer.setDirectColor4("color1",this.color1),this._updateBuffer.setDirectColor4("color2",this.color2)),this._updateBuffer.setFloat2("sizeRange",this.minSize,this.maxSize),this._updateBuffer.setFloat4("scaleRange",this.minScaleX,this.maxScaleX,this.minScaleY,this.maxScaleY),this._updateBuffer.setFloat4("angleRange",this.minAngularSpeed,this.maxAngularSpeed,this.minInitialRotation,this.maxInitialRotation),this._updateBuffer.setVector3("gravity",this.gravity),this._limitVelocityGradientsTexture&&this._updateBuffer.setFloat("limitVelocityDamping",this.limitVelocityDamping),this.particleEmitterType&&this.particleEmitterType.applyToShader(this._updateBuffer),this._isAnimationSheetEnabled&&this._updateBuffer.setFloat4("cellInfos",this.startSpriteCellID,this.endSpriteCellID,this.spriteCellChangeSpeed,this.spriteCellLoop?1:0),this.noiseTexture&&this._updateBuffer.setVector3("noiseStrength",this.noiseStrength),this.isLocal||this._updateBuffer.setMatrix("emitterWM",e),this._platform.updateParticleBuffer(this._targetIndex,this._targetBuffer,this._currentActiveCount),this._targetIndex++,2===this._targetIndex&&(this._targetIndex=0);let t=this._sourceBuffer;this._sourceBuffer=this._targetBuffer,this._targetBuffer=t}render(e=!1,t=!1){let i;if(!this._started||!this.isReady())return 0;if(!e&&this._scene){if(!this._preWarmDone&&this.preWarmCycles){for(let e=0;e1){let e=0|this._accumulatedCount;this._accumulatedCount-=e,this._currentActiveCount+=e}if(this._currentActiveCount=Math.min(this._maxActiveParticleCount,this._currentActiveCount),!this._currentActiveCount)return 0;if(this.emitter.position)i=this.emitter.getWorldMatrix();else{let e=this.emitter;i=rf.jp.Matrix[0],rf.y3.TranslationToRef(e.x,e.y,e.z,i)}let r=this._engine;this.updateInAnimate||this._update(i);let s=0;return e||t||(r.setState(!1),this.forceDepthWrite&&r.setDepthWrite(!0),s=this.blendMode===xs.BLENDMODE_MULTIPLYADD?this._render(xs.BLENDMODE_MULTIPLY,i)+this._render(xs.BLENDMODE_ADD,i):this._render(this.blendMode,i),this._engine.setAlphaMode(0)),s}rebuild(){let e=()=>{this._recreateUpdateEffect()&&this._platform.isUpdateBufferReady()?this._initialize(!0):setTimeout(e,10)};this._createIndexBuffer(),this._cachedUpdateDefines="",this._platform.contextLost(),e()}_releaseBuffers(){this._buffer0&&(this._buffer0.dispose(),this._buffer0=null),this._buffer1&&(this._buffer1.dispose(),this._buffer1=null),this._spriteBuffer&&(this._spriteBuffer.dispose(),this._spriteBuffer=null),this._platform.releaseBuffers()}dispose(e=!0){for(let e in this._drawWrappers)this._drawWrappers[e].dispose();if(this._drawWrappers={},this._scene){let e=this._scene.particleSystems.indexOf(this);e>-1&&this._scene.particleSystems.splice(e,1)}this._releaseBuffers(),this._platform.releaseVertexBuffers();for(let e=0;e0?s.shaderOptions.defines.join("\n"):"";r[0]=n.createEffectForParticles(s.shaderPath.fragmentElement,s.shaderOptions.uniforms,s.shaderOptions.samplers,e,void 0,void 0,void 0,this)}let a=this.serialize(i),o=xh.Parse(a,this._scene||this._engine,this._rootUrl);return o.name=e,o.customShader=s,o._customWrappers=r,void 0===t&&(t=this.emitter),this.noiseTexture&&(o.noiseTexture=this.noiseTexture.clone()),o.emitter=t,o}serialize(e=!1){let t={};return xs._Serialize(t,this,e),t.activeParticleCount=this.activeParticleCount,t.randomTextureSize=this._randomTextureSize,t.customShader=this.customShader,t}static Parse(e,t,i,r=!1,s){let n;let a=e.name;n=t instanceof sK.B?t:t.getEngine();let o=new xh(a,{capacity:s||e.capacity,randomTextureSize:e.randomTextureSize},t,null,e.isAnimationSheetEnabled);if(o._rootUrl=i,e.customShader&&n.createEffectForParticles){let t=e.customShader,i=t.shaderOptions.defines.length>0?t.shaderOptions.defines.join("\n"):"",r=n.createEffectForParticles(t.shaderPath.fragmentElement,t.shaderOptions.uniforms,t.shaderOptions.samplers,i,void 0,void 0,void 0,o);o.setCustomEffect(r,0),o.customShader=t}return e.id&&(o.id=e.id),e.activeParticleCount&&(o.activeParticleCount=e.activeParticleCount),xs._Parse(e,o,t,i),e.preventAutoStart&&(o.preventAutoStart=e.preventAutoStart),r||o.preventAutoStart||o.start(),o}}class xu{constructor(){this._emitterNodeIsOwned=!0,this.systems=[]}get emitterNode(){return this._emitterNode}set emitterNode(e){for(let t of(this._emitterNodeIsOwned&&this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!1),this.systems))t.emitter=e;this._emitterNode=e}setEmitterAsSphere(e,t,i){this._emitterNodeIsOwned&&this._emitterNode&&this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNodeIsOwned=!0,this._emitterCreationOptions={kind:"Sphere",options:e,renderingGroupId:t};let r=hM("emitterSphere",{diameter:e.diameter,segments:e.segments},i);r.renderingGroupId=t;let s=new lj("emitterSphereMaterial",i);for(let t of(s.emissiveColor=e.color,r.material=s,this.systems))t.emitter=r;this._emitterNode=r}start(e){for(let t of this.systems)e&&(t.emitter=e),t.start()}dispose(){for(let e of this.systems)e.dispose();this.systems.length=0,this._emitterNode&&(this._emitterNode.dispose&&this._emitterNode.dispose(),this._emitterNode=null)}serialize(e=!1){let t={};for(let i of(t.systems=[],this.systems))t.systems.push(i.serialize(e));return this._emitterNode&&(t.emitter=this._emitterCreationOptions),t}static Parse(e,t,i=!1,r){let s=new xu,n=this.BaseAssetsUrl+"/textures/";for(let a of(t=t||rL.l.LastCreatedScene,e.systems))s.systems.push(i?xh.Parse(a,t,n,!0,r):xs.Parse(a,t,n,!0,r));if(e.emitter){let i=e.emitter.options;"Sphere"===e.emitter.kind&&s.setEmitterAsSphere({diameter:i.diameter,segments:i.segments,color:rm.Wo.FromArray(i.color)},e.emitter.renderingGroupId,t)}return s}}xu.BaseAssetsUrl="https://assets.babylonjs.com/particles";class xc{static CreateDefault(e,t=500,i,r=!1){let s;return(s=r?new xh("default system",{capacity:t},i):new xs("default system",t,i)).emitter=e,s.particleTexture=new sj("https://assets.babylonjs.com/textures/flare.png",s.getScene()),s.createConeEmitter(.1,Math.PI/4),s.color1=new rm.HE(1,1,1,1),s.color2=new rm.HE(1,1,1,1),s.colorDead=new rm.HE(1,1,1,0),s.minSize=.1,s.maxSize=.1,s.minEmitPower=2,s.maxEmitPower=2,s.updateSpeed=1/60,s.emitRate=30,s}static CreateAsync(e,t,i=!1,r){t||(t=rL.l.LastCreatedScene);let s={};return t.addPendingData(s),new Promise((n,a)=>{if(i&&!xh.IsSupported)return t.removePendingData(s),a("Particle system with GPU is not supported.");sg.w1.LoadFile(`${xc.BaseAssetsUrl}/systems/${e}.json`,e=>{t.removePendingData(s);let a=JSON.parse(e.toString());return n(xu.Parse(a,t,i,r))},void 0,void 0,void 0,()=>(t.removePendingData(s),a(`An error occurred with the creation of your particle system. Check if your type '${e}' exists.`)))})}static ExportSet(e){let t=new xu;for(let i of e)t.systems.push(i);return t}static ParseFromFileAsync(e,t,i,r=!1,s="",n){return new Promise((a,o)=>{let l=new rX.g;l.addEventListener("readystatechange",()=>{if(4==l.readyState){if(200==l.status){let t;let o=JSON.parse(l.responseText);t=r?xh.Parse(o,i,s,!1,n):xs.Parse(o,i,s,!1,n),e&&(t.name=e),a(t)}else o("Unable to load the particle system")}}),l.open("GET",t),l.send()})}static ParseFromSnippetAsync(e,t,i=!1,r="",s){if("_BLANK"===e){let e=this.CreateDefault(null);return e.start(),Promise.resolve(e)}return new Promise((n,a)=>{let o=new rX.g;o.addEventListener("readystatechange",()=>{if(4==o.readyState){if(200==o.status){let a;let l=JSON.parse(JSON.parse(JSON.parse(o.responseText).jsonPayload).particleSystem);(a=i?xh.Parse(l,t,r,!1,s):xs.Parse(l,t,r,!1,s)).snippetId=e,n(a)}else a("Unable to load the snippet "+e)}}),o.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),o.send()})}}xc.BaseAssetsUrl=xu.BaseAssetsUrl,xc.SnippetUrl="https://snippet.babylonjs.com",xc.CreateFromSnippetAsync=xc.ParseFromSnippetAsync,rd.p.AddParser(sN.l.NAME_PARTICLESYSTEM,(e,t,i,r)=>{let s=rd.p.GetIndividualParser(sN.l.NAME_PARTICLESYSTEM);if(s&&void 0!==e.particleSystems&&null!==e.particleSystems)for(let n=0,a=e.particleSystems.length;ne.activeParticleCount?xh.Parse(e,t,i):xs.Parse(e,t,i)),sR.D.prototype.createEffectForParticles=function(e,t=[],i=[],r="",s,n,a,o){var l;let h=[],u=[],c=[];return o?o.fillUniformsAttributesAndSamplerNames(u,h,c):(h=xs._GetAttributeNamesOrOptions(),u=xs._GetEffectCreationOptions()),-1===r.indexOf(" BILLBOARD")&&(r+="\n#define BILLBOARD\n"),(null==o?void 0:o.isAnimationSheetEnabled)&&-1===r.indexOf(" ANIMATESHEET")&&(r+="\n#define ANIMATESHEET\n"),-1===i.indexOf("diffuseSampler")&&i.push("diffuseSampler"),this.createEffect({vertex:null!==(l=null==o?void 0:o.vertexShaderName)&&void 0!==l?l:"particles",fragmentElement:e},h,u.concat(t),c.concat(i),r,s,n,a)},sp.Kj.prototype.getEmittedParticleSystems=function(){let e=[];for(let t=0;t{this.physicsImpostor&&(this.physicsImpostor.dispose(),this.physicsImpostor=null)})))},enumerable:!0,configurable:!0}),sf.x.prototype.getPhysicsImpostor=function(){return this.physicsImpostor},sf.x.prototype.applyImpulse=function(e,t){return this.physicsImpostor&&this.physicsImpostor.applyImpulse(e,t),this},sf.x.prototype.setPhysicsLinkWith=function(e,t,i,r){return this.physicsImpostor&&e.physicsImpostor&&this.physicsImpostor.createJoint(e.physicsImpostor,nn.HingeJoint,{mainPivot:t,connectedPivot:i,nativeParams:r}),this};class xd{getPluginVersion(){return this._physicsPlugin.getPluginVersion()}static DefaultPluginFactory(){throw(0,sM.S)("")}constructor(e,t=xd.DefaultPluginFactory()){this._physicsPlugin=t,this._physicsBodies=[],this._subTimeStep=0,e=e||new rf.P(0,-9.807,0),this.setGravity(e),this.setTimeStep()}setGravity(e){this.gravity=e,this._physicsPlugin.setGravity(this.gravity)}setTimeStep(e=1/60){this._physicsPlugin.setTimeStep(e)}getTimeStep(){return this._physicsPlugin.getTimeStep()}setSubTimeStep(e=0){this._subTimeStep=e}getSubTimeStep(){return this._subTimeStep}dispose(){this._physicsPlugin.dispose()}getPhysicsPluginName(){return this._physicsPlugin.name}_step(e){e>.1?e=.1:e<=0&&(e=1/60),this._physicsPlugin.executeStep(e,this._physicsBodies)}addBody(e){this._physicsBodies.push(e)}removeBody(e){let t=this._physicsBodies.indexOf(e);t>-1&&this._physicsBodies.splice(t,1)}getBodies(){return this._physicsBodies}getPhysicsPlugin(){return this._physicsPlugin}raycastToRef(e,t,i,r){this._physicsPlugin.raycast(e,t,i,r)}raycast(e,t,i){let r=new fa;return this._physicsPlugin.raycast(e,t,r,i),r}}(e2=i2||(i2={}))[e2.FREE=0]="FREE",e2[e2.LIMITED=1]="LIMITED",e2[e2.LOCKED=2]="LOCKED",(e3=i3||(i3={}))[e3.LINEAR_X=0]="LINEAR_X",e3[e3.LINEAR_Y=1]="LINEAR_Y",e3[e3.LINEAR_Z=2]="LINEAR_Z",e3[e3.ANGULAR_X=3]="ANGULAR_X",e3[e3.ANGULAR_Y=4]="ANGULAR_Y",e3[e3.ANGULAR_Z=5]="ANGULAR_Z",e3[e3.LINEAR_DISTANCE=6]="LINEAR_DISTANCE",(e4=i4||(i4={}))[e4.BALL_AND_SOCKET=1]="BALL_AND_SOCKET",e4[e4.DISTANCE=2]="DISTANCE",e4[e4.HINGE=3]="HINGE",e4[e4.SLIDER=4]="SLIDER",e4[e4.LOCK=5]="LOCK",e4[e4.PRISMATIC=6]="PRISMATIC",e4[e4.SIX_DOF=7]="SIX_DOF",(e5=i5||(i5={}))[e5.SPHERE=0]="SPHERE",e5[e5.CAPSULE=1]="CAPSULE",e5[e5.CYLINDER=2]="CYLINDER",e5[e5.BOX=3]="BOX",e5[e5.CONVEX_HULL=4]="CONVEX_HULL",e5[e5.CONTAINER=5]="CONTAINER",e5[e5.MESH=6]="MESH",e5[e5.HEIGHTFIELD=7]="HEIGHTFIELD",(e6=i6||(i6={}))[e6.NONE=0]="NONE",e6[e6.VELOCITY=1]="VELOCITY",e6[e6.POSITION=2]="POSITION",(e8=i8||(i8={})).COLLISION_STARTED="COLLISION_STARTED",e8.COLLISION_CONTINUED="COLLISION_CONTINUED",e8.COLLISION_FINISHED="COLLISION_FINISHED",e8.TRIGGER_ENTERED="TRIGGER_ENTERED",e8.TRIGGER_EXITED="TRIGGER_EXITED",(e7=i7||(i7={}))[e7.STATIC=0]="STATIC",e7[e7.ANIMATED=1]="ANIMATED",e7[e7.DYNAMIC=2]="DYNAMIC",(e9=i9||(i9={}))[e9.GEOMETRIC_MEAN=0]="GEOMETRIC_MEAN",e9[e9.MINIMUM=1]="MINIMUM",e9[e9.MAXIMUM=2]="MAXIMUM",e9[e9.ARITHMETIC_MEAN=3]="ARITHMETIC_MEAN",e9[e9.MULTIPLY=4]="MULTIPLY",r2.x.prototype.getPhysicsEngine=function(){return this._physicsEngine},r2.x.prototype.enablePhysics=function(e=null,t){if(this._physicsEngine)return!0;let i=this._getComponent(sN.l.NAME_PHYSICSENGINE);i||(i=new xp(this),this._addComponent(i));try{if(t&&(null==t?void 0:t.getPluginVersion())!==1){if((null==t?void 0:t.getPluginVersion())===2)this._physicsEngine=new xd(e,t);else throw Error("Unsupported Physics plugin version.")}else this._physicsEngine=new fo(e,t);return this._physicsTimeAccumulator=0,!0}catch(e){return rb.Y.Error(e.message),!1}},r2.x.prototype.disablePhysicsEngine=function(){this._physicsEngine&&(this._physicsEngine.dispose(),this._physicsEngine=null)},r2.x.prototype.isPhysicsEnabled=function(){return void 0!==this._physicsEngine},r2.x.prototype.deleteCompoundImpostor=function(e){let t=e.parts[0].mesh;t.physicsImpostor&&(t.physicsImpostor.dispose(),t.physicsImpostor=null)},r2.x.prototype._advancePhysicsEngineStep=function(e){if(this._physicsEngine){let t=this._physicsEngine.getSubTimeStep();if(t>0)for(this._physicsTimeAccumulator+=e;this._physicsTimeAccumulator>t;)this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(t/1e3),this.onAfterPhysicsObservable.notifyObservers(this),this._physicsTimeAccumulator-=t;else this.onBeforePhysicsObservable.notifyObservers(this),this._physicsEngine._step(e/1e3),this.onAfterPhysicsObservable.notifyObservers(this)}};class xp{constructor(e){this.name=sN.l.NAME_PHYSICSENGINE,this.scene=e,this.scene.onBeforePhysicsObservable=new r_.y$,this.scene.onAfterPhysicsObservable=new r_.y$,this.scene.getDeterministicFrameTime=()=>this.scene._physicsEngine?1e3*this.scene._physicsEngine.getTimeStep():1e3/60}register(){}rebuild(){}dispose(){this.scene.onBeforePhysicsObservable.clear(),this.scene.onAfterPhysicsObservable.clear(),this.scene._physicsEngine&&this.scene.disablePhysicsEngine()}}Object.defineProperty(s_.Y.prototype,"physicsBody",{get:function(){return this._physicsBody},set:function(e){this._physicsBody!==e&&(this._disposePhysicsObserver&&this.onDisposeObservable.remove(this._disposePhysicsObserver),this._physicsBody=e,e&&(this._disposePhysicsObserver=this.onDisposeObservable.add(()=>{this.physicsBody&&(this.physicsBody.dispose(),this.physicsBody=null)})))},enumerable:!0,configurable:!0}),s_.Y.prototype.getPhysicsBody=function(){return this.physicsBody},s_.Y.prototype.applyImpulse=function(e,t){if(!this.physicsBody)throw Error("No Physics Body for TransformNode");return this.physicsBody.applyImpulse(e,t),this};class x_{static GetContactPointToRef(e,t,i,r,s){let n=e.getScene().getPhysicsEngine(),a=null==n?void 0:n.getPluginVersion();if(1===a){let s=new s6(t,i).intersectsMesh(e);if(s.hit&&s.pickedPoint)return r.copyFrom(s.pickedPoint),!0}else if(2===a)return e.physicsBody.getObjectCenterWorldToRef(r,s),!0;return!1}static HasAppliedForces(e,t){var i,r,s;return e.getMotionType(t)===i7.STATIC||(null!==(r=null===(i=e.getMassProperties(t))||void 0===i?void 0:i.mass)&&void 0!==r?r:0)===0||(null===(s=e.transformNode)||void 0===s?void 0:s.getTotalVertices())===0}static IsInsideCylinder(e,t,i,r){let s=rf.jp.Vector3[0];return e.subtractToRef(t,s),Math.abs(s.x)<=i&&Math.abs(s.z)<=i&&s.y>=0&&s.y<=r}}class xf{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=rf.P.Zero(),this._originDirection=rf.P.Zero(),this._cylinderPosition=rf.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new xg),this._options),this._origin.addToRef(new rf.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new rf.P(0,this._options.height,0),this._originTop),this._options.updraftMode===rt.Perpendicular&&(this._originDirection=this._origin.subtract(this._originTop).normalize()),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?(this._cylinder.dispose(),this._cylinder=void 0):setTimeout(()=>{!this._dataFetched&&this._cylinder&&(this._cylinder.dispose(),this._cylinder=void 0)},0))}_getHitData(e,t){let i;i=this._options.updraftMode===rt.Perpendicular?this._originDirection:e.subtract(this._originTop);let r=rf.P.Distance(this._origin,e),s=-1*this._options.strength,n=i.multiplyByFloats(s,s,s);t.force.copyFrom(n),t.contactPoint.copyFrom(e),t.distanceFromOrigin=r}_getBodyHitData(e,t,i){if(x_.HasAppliedForces(e))return!1;let r=e.getObjectCenterWorld(i);return!!x_.IsInsideCylinder(r,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,t),!0)}_getImpostorHitData(e,t){if(0===e.mass)return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(r,t),!0}_tick(){let e=xf._HitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=hE("updraftEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return!!this._cylinder&&(this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0))}}xf._HitData={force:new rf.P,contactPoint:new rf.P,distanceFromOrigin:0};class xm{constructor(e,t,i){this._scene=e,this._origin=t,this._options=i,this._originTop=rf.P.Zero(),this._cylinderPosition=rf.P.Zero(),this._dataFetched=!1,this._physicsEngine=this._scene.getPhysicsEngine(),this._options=Object.assign(Object.assign({},new xv),this._options),this._origin.addToRef(new rf.P(0,this._options.height/2,0),this._cylinderPosition),this._origin.addToRef(new rf.P(0,this._options.height,0),this._originTop),this._tickCallback=()=>this._tick(),1===this._physicsEngine.getPluginVersion()&&this._prepareCylinder()}getData(){return this._dataFetched=!0,{cylinder:this._cylinder}}enable(){this._tickCallback.call(this),this._scene.registerBeforeRender(this._tickCallback)}disable(){this._scene.unregisterBeforeRender(this._tickCallback)}dispose(e=!0){this._cylinder&&(e?this._cylinder.dispose():setTimeout(()=>{this._dataFetched||this._cylinder.dispose()},0))}_getHitData(e,t,i){let r,s,n;let a=xm.originOnPlane;a.set(this._origin.x,t.y,this._origin.z);let o=rf.jp.Vector3[0];t.subtractToRef(a,o);let l=rf.jp.Vector3[1];if(!x_.GetContactPointToRef(e,a,o,l,i.instanceIndex))return!1;let h=rf.P.Distance(l,a)/this._options.radius,u=rf.jp.Vector3[2];if(l.normalizeToRef(u),h>this._options.centripetalForceThreshold&&u.negateInPlace(),h>this._options.centripetalForceThreshold)r=u.x*this._options.centripetalForceMultiplier,s=u.y*this._options.updraftForceMultiplier,n=u.z*this._options.centripetalForceMultiplier;else{let e=rf.P.Cross(a,t).normalize();r=(e.x+u.x)*this._options.centrifugalForceMultiplier,s=this._originTop.y*this._options.updraftForceMultiplier,n=(e.z+u.z)*this._options.centrifugalForceMultiplier}let c=rf.jp.Vector3[3];return c.set(r,s,n),c.scaleInPlace(this._options.strength),i.force.copyFrom(c),i.contactPoint.copyFrom(t),i.distanceFromOrigin=h,!0}_getBodyHitData(e,t,i){if(x_.HasAppliedForces(e,i))return!1;let r=e.transformNode,s=e.getObjectCenterWorld(i);return!!x_.IsInsideCylinder(s,this._origin,this._options.radius,this._options.height)&&(t.instanceIndex=i,this._getHitData(r,s,t))}_getImpostorHitData(e,t){if(0===e.mass||"Mesh"!==e.object.getClassName()&&"InstancedMesh"!==e.object.getClassName())return!1;let i=e.object;if(!this._intersectsWithCylinder(i))return!1;let r=e.getObjectCenter();return this._getHitData(i,r,t),!0}_tick(){let e=xm.hitData;1===this._physicsEngine.getPluginVersion()?this._physicsEngine.getImpostors().forEach(t=>{this._getImpostorHitData(t,e)&&t.applyForce(e.force,e.contactPoint)}):this._physicsEngine.getBodies().forEach(t=>{t.iterateOverAllInstances((t,i)=>{this._getBodyHitData(t,e,i)&&t.applyForce(e.force,e.contactPoint,e.instanceIndex)})})}_prepareCylinder(){this._cylinder||(this._cylinder=hE("vortexEventCylinder",{height:this._options.height,diameter:2*this._options.radius},this._scene),this._cylinder.isVisible=!1)}_intersectsWithCylinder(e){return this._cylinder.position=this._cylinderPosition,this._cylinder.intersectsMesh(e,!0)}}xm.originOnPlane=rf.P.Zero(),xm.hitData={force:new rf.P,contactPoint:new rf.P,distanceFromOrigin:0};class xg{constructor(){this.radius=5,this.strength=10,this.height=10,this.updraftMode=rt.Center}}class xv{constructor(){this.radius=5,this.strength=10,this.height=10,this.centripetalForceThreshold=.7,this.centripetalForceMultiplier=5,this.centrifugalForceMultiplier=.5,this.updraftForceMultiplier=.02}}(te=re||(re={}))[te.Constant=0]="Constant",te[te.Linear=1]="Linear",(tt=rt||(rt={}))[tt.Center=0]="Center",tt[tt.Perpendicular=1]="Perpendicular";let xx=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float degree; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 color=texture2D(textureSampler,vUV).rgb;float luminance=dot(color,vec3(0.3,0.59,0.11)); +vec3 blackAndWhite=vec3(luminance,luminance,luminance);gl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);}`;nw.v.ShadersStore.blackAndWhitePixelShader=xx;class xT extends nz{getClassName(){return"BlackAndWhitePostProcess"}constructor(e,t,i,r,s,n){super(e,"blackAndWhite",["degree"],null,t,i,r,s,n),this.degree=1,this.onApplyObservable.add(e=>{e.setFloat("degree",this.degree)})}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new xT(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],xT.prototype,"degree",void 0),(0,rg.H)("BABYLON.BlackAndWhitePostProcess",xT);class xS{constructor(e,t,i,r){this._name=t,this._singleInstance=r||!0,this._getPostProcesses=i,this._cameras={},this._indicesForCamera={},this._postProcesses={}}get isSupported(){for(let e in this._postProcesses)if(Object.prototype.hasOwnProperty.call(this._postProcesses,e)){let t=this._postProcesses[e];for(let e=0;e{let t=r.attachPostProcess(e);this._indicesForCamera[s].push(t)}),this._cameras[s]||(this._cameras[s]=r)}}_detachCameras(e){let t=sg.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)}),this._cameras[r]&&(this._cameras[r]=null),delete this._indicesForCamera[r]}}_enable(e){let t=sg.w1.MakeArray(e||this._cameras);if(t)for(let e=0;e{i.detachPostProcess(e)})}}getPostProcesses(e){return this._singleInstance?this._postProcesses[0]:e?this._postProcesses[e.name]:null}}let xE=`#include +varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`;nw.v.ShadersStore.extractHighlightsPixelShader=xE;class xC extends nz{getClassName(){return"ExtractHighlightsPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"extractHighlights",["threshold","exposure"],null,t,i,r,s,n,null,a,void 0,null,o),this.threshold=.9,this._exposure=1,this._inputPostProcess=null,this.onApplyObservable.add(e=>{this.externalTextureSamplerBinding=!!this._inputPostProcess,this._inputPostProcess&&e.setTextureFromPostProcess("textureSampler",this._inputPostProcess),e.setFloat("threshold",Math.pow(this.threshold,r7.zp)),e.setFloat("exposure",this._exposure)})}}(0,sx.gn)([(0,rG.qC)()],xC.prototype,"threshold",void 0),(0,rg.H)("BABYLON.ExtractHighlightsPostProcess",xC);let xb=`uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } +`;nw.v.ShadersStore.bloomMergePixelShader=xb;class xy extends nz{getClassName(){return"BloomMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"bloomMerge",["bloomWeight"],["bloomBlur"],s,n,a,o,l,null,h,void 0,null,!0),this.weight=1,this.weight=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("bloomBlur",i),e.setFloat("bloomWeight",this.weight)}),u||this.updateEffect()}}(0,sx.gn)([(0,rG.qC)()],xy.prototype,"weight",void 0),(0,rg.H)("BABYLON.BloomMergePostProcess",xy);class xA extends xS{get threshold(){return this._downscale.threshold}set threshold(e){this._downscale.threshold=e}get weight(){return this._merge.weight}set weight(e){this._merge.weight=e}get kernel(){return this._blurX.kernel/this._bloomScale}set kernel(e){this._blurX.kernel=e*this._bloomScale,this._blurY.kernel=e*this._bloomScale}constructor(e,t,i,r,s=0,n=!1){super(e.getEngine(),"bloom",()=>this._effects,!0),this._bloomScale=t,this._effects=[],this._downscale=new xC("highlights",1,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._blurX=new dP("horizontal blur",new rf.FM(1,0),10,t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurX.alwaysForcePOT=!0,this._blurX.autoClear=!1,this._blurY=new dP("vertical blur",new rf.FM(0,1),10,t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,void 0,n),this._blurY.alwaysForcePOT=!0,this._blurY.autoClear=!1,this.kernel=r,this._effects=[this._downscale,this._blurX,this._blurY],this._merge=new xy("bloomMerge",this._downscale,this._blurY,i,t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,n),this._merge.autoClear=!1,this._effects.push(this._merge)}disposeEffects(e){for(let t=0;t{e.setFloat("chromatic_aberration",this.aberrationAmount),e.setFloat("screen_width",t),e.setFloat("screen_height",i),e.setFloat("radialIntensity",this.radialIntensity),e.setFloat2("direction",this.direction.x,this.direction.y),e.setFloat2("centerPosition",this.centerPosition.x,this.centerPosition.y)})}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new xP(e.name,e.screenWidth,e.screenHeight,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],xP.prototype,"aberrationAmount",void 0),(0,sx.gn)([(0,rG.qC)()],xP.prototype,"radialIntensity",void 0),(0,sx.gn)([(0,rG.qC)()],xP.prototype,"direction",void 0),(0,sx.gn)([(0,rG.qC)()],xP.prototype,"centerPosition",void 0),(0,sx.gn)([(0,rG.qC)()],xP.prototype,"screenWidth",void 0),(0,sx.gn)([(0,rG.qC)()],xP.prototype,"screenHeight",void 0),(0,rg.H)("BABYLON.ChromaticAberrationPostProcess",xP);let xI=`uniform sampler2D depthSampler;varying vec2 vUV;uniform vec2 cameraMinMaxZ;uniform float focusDistance;uniform float cocPrecalculation; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float depth=texture2D(depthSampler,vUV).r; +#define CUSTOM_COC_DEPTH +float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; +#define CUSTOM_COC_PIXELDISTANCE +float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} +`;nw.v.ShadersStore.circleOfConfusionPixelShader=xI;class xM extends nz{getClassName(){return"CircleOfConfusionPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1){super(e,"circleOfConfusion",["cameraMinMaxZ","focusDistance","cocPrecalculation"],["depthSampler"],i,r,s,n,a,null,o,void 0,null,l),this.lensSize=50,this.fStop=1.4,this.focusDistance=2e3,this.focalLength=50,this._depthTexture=null,this._depthTexture=t,this.onApplyObservable.add(e=>{if(!this._depthTexture){rb.Y.Warn("No depth texture set on CircleOfConfusionPostProcess");return}e.setTexture("depthSampler",this._depthTexture);let t=this.lensSize/this.fStop*this.focalLength/(this.focusDistance-this.focalLength);e.setFloat("focusDistance",this.focusDistance),e.setFloat("cocPrecalculation",t);let i=this._depthTexture.activeCamera;e.setFloat2("cameraMinMaxZ",i.minZ,i.maxZ-i.minZ)})}set depthTexture(e){this._depthTexture=e}}(0,sx.gn)([(0,rG.qC)()],xM.prototype,"lensSize",void 0),(0,sx.gn)([(0,rG.qC)()],xM.prototype,"fStop",void 0),(0,sx.gn)([(0,rG.qC)()],xM.prototype,"focusDistance",void 0),(0,sx.gn)([(0,rG.qC)()],xM.prototype,"focalLength",void 0),(0,rg.H)("BABYLON.CircleOfConfusionPostProcess",xM);let xD=`uniform sampler2D textureSampler; +uniform sampler2D colorTable; +varying vec2 vUV;const float SLICE_COUNT=16.0; +vec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {float sliceSize=1.0/width; +float slicePixelSize=sliceSize/width; +float sliceInnerSize=slicePixelSize*(width-1.0); +float zSlice0=min(floor(uv.z*width),width-1.0);float zSlice1=min(zSlice0+1.0,width-1.0);float xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;float s0=xOffset+(zSlice0*sliceSize);float s1=xOffset+(zSlice1*sliceSize);vec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));vec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));float zOffset=mod(uv.z*width,1.0);vec4 result=mix(slice0Color,slice1Color,zOffset);return result;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 screen_color=texture2D(textureSampler,vUV);gl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);}`;nw.v.ShadersStore.colorCorrectionPixelShader=xD;class xO extends nz{getClassName(){return"ColorCorrectionPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"colorCorrection",null,["colorTable"],i,r,s,n,a);let o=(null==r?void 0:r.getScene())||null;this._colorTableTexture=new sj(t,o,!0,!1,sj.TRILINEAR_SAMPLINGMODE),this._colorTableTexture.anisotropicFilteringLevel=1,this._colorTableTexture.wrapU=sj.CLAMP_ADDRESSMODE,this._colorTableTexture.wrapV=sj.CLAMP_ADDRESSMODE,this.colorTableUrl=t,this.onApply=e=>{e.setTexture("colorTable",this._colorTableTexture)}}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new xO(e.name,e.colorTableUrl,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],xO.prototype,"colorTableUrl",void 0),(0,rg.H)("BABYLON.ColorCorrectionPostProcess",xO);let xN=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform float kernel[9]; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 colorSum = +texture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] + +texture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] + +texture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] + +texture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] + +texture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] + +texture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] + +texture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] + +texture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];float kernelWeight = +kernel[0] + +kernel[1] + +kernel[2] + +kernel[3] + +kernel[4] + +kernel[5] + +kernel[6] + +kernel[7] + +kernel[8];if (kernelWeight<=0.0) {kernelWeight=1.0;} +gl_FragColor=vec4((colorSum/kernelWeight).rgb,1);}`;nw.v.ShadersStore.convolutionPixelShader=xN;class xF extends nz{getClassName(){return"ConvolutionPostProcess"}constructor(e,t,i,r,s,n,a,o=0){super(e,"convolution",["kernel","screenSize"],null,i,r,s,n,a,null,o),this.kernel=t,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setArray("kernel",this.kernel)}}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new xF(e.name,e.kernel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType),e,i,r)}}xF.EdgeDetect0Kernel=[1,0,-1,0,0,0,-1,0,1],xF.EdgeDetect1Kernel=[0,1,0,1,-4,1,0,1,0],xF.EdgeDetect2Kernel=[-1,-1,-1,-1,8,-1,-1,-1,-1],xF.SharpenKernel=[0,-1,0,-1,5,-1,0,-1,0],xF.EmbossKernel=[-2,-1,0,-1,1,1,0,1,2],xF.GaussianKernel=[0,1,0,1,1,1,0,1,0],(0,sx.gn)([(0,rG.qC)()],xF.prototype,"kernel",void 0),(0,rg.H)("BABYLON.ConvolutionPostProcess",xF);class xL extends dP{getClassName(){return"DepthOfFieldBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=null,l=sj.BILINEAR_SAMPLINGMODE,h,u,c=0,d=!1,p=5){super(e,i,r,s,n,2,h,u,c,`#define DOF 1 +`,d,p),this.direction=i,this.externalTextureSamplerBinding=!!o,this.onApplyObservable.add(e=>{null!=o&&e.setTextureFromPostProcess("textureSampler",o),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",a)})}}(0,sx.gn)([(0,rG.qC)()],xL.prototype,"direction",void 0),(0,rg.H)("BABYLON.DepthOfFieldBlurPostProcess",xL);let xw=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; +#if BLUR_LEVEL>0 +uniform sampler2D blurStep1; +#endif +#if BLUR_LEVEL>1 +uniform sampler2D blurStep2; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; +#if BLUR_LEVEL==0 +vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); +#endif +#if BLUR_LEVEL==1 +if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} +#endif +#if BLUR_LEVEL==2 +if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} +#endif +} +`;nw.v.ShadersStore.depthOfFieldMergePixelShader=xw;class xB extends nz{getClassName(){return"DepthOfFieldMergePostProcess"}constructor(e,t,i,r,s,n,a,o,l,h=0,u=!1){super(e,"depthOfFieldMerge",[],["circleOfConfusionSampler","blurStep0","blurStep1","blurStep2"],s,n,a,o,l,null,h,void 0,null,!0),this._blurSteps=r,this.externalTextureSamplerBinding=!0,this.onApplyObservable.add(e=>{e.setTextureFromPostProcess("textureSampler",t),e.setTextureFromPostProcessOutput("circleOfConfusionSampler",i),r.forEach((t,i)=>{e.setTextureFromPostProcessOutput("blurStep"+(r.length-i-1),t)})}),u||this.updateEffect()}updateEffect(e=null,t=null,i=null,r,s,n){e||(e="#define BLUR_LEVEL "+(this._blurSteps.length-1)+"\n"),super.updateEffect(e,t,i,r,s,n)}}(ti=ri||(ri={}))[ti.Low=0]="Low",ti[ti.Medium=1]="Medium",ti[ti.High=2]="High";class xU extends xS{set focalLength(e){this._circleOfConfusion.focalLength=e}get focalLength(){return this._circleOfConfusion.focalLength}set fStop(e){this._circleOfConfusion.fStop=e}get fStop(){return this._circleOfConfusion.fStop}set focusDistance(e){this._circleOfConfusion.focusDistance=e}get focusDistance(){return this._circleOfConfusion.focusDistance}set lensSize(e){this._circleOfConfusion.lensSize=e}get lensSize(){return this._circleOfConfusion.lensSize}constructor(e,t,i=ri.Low,r=0,s=!1){super(e.getEngine(),"depth of field",()=>this._effects,!0),this._effects=[];let n=e.getEngine(),a=n.isWebGPU||n.webGLVersion>1?6:5;this._circleOfConfusion=new xM("circleOfConfusion",t,1,null,sj.BILINEAR_SAMPLINGMODE,n,!1,r,s),this._depthOfFieldBlurY=[],this._depthOfFieldBlurX=[];let o=1,l=15;switch(i){case ri.High:o=3,l=51;break;case ri.Medium:o=2,l=31;break;default:l=15,o=1}let h=l/Math.pow(2,o-1),u=1;for(let t=0;tnew xk(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,rg.H)("BABYLON.DisplayPassPostProcess",xk);let xG=`varying vec2 vUV;uniform sampler2D textureSampler;uniform mat4 kernelMatrix; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 baseColor=texture2D(textureSampler,vUV).rgb;vec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;gl_FragColor=vec4(updatedColor,1.0);}`;nw.v.ShadersStore.filterPixelShader=xG;class xz extends nz{getClassName(){return"FilterPostProcess"}constructor(e,t,i,r,s,n,a){super(e,"filter",["kernelMatrix"],null,i,r,s,n,a),this.kernelMatrix=t,this.onApply=e=>{e.setMatrix("kernelMatrix",this.kernelMatrix)}}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new xz(e.name,e.kernelMatrix,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,sx.gn)([(0,rG.oQ)()],xz.prototype,"kernelMatrix",void 0),(0,rg.H)("BABYLON.FilterPostProcess",xz);let xW=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); +#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) +void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); +#ifndef MALI +if(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) +{lumaN=lumaW;} +if (!horzSpan) +{lumaS=lumaE;} +if (horzSpan) +{lengthSign=texelSize.y;} +float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) +{lengthSign=-lengthSign;} +float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) +{posB.x+=lengthSign*0.5;} +if (horzSpan) +{posB.y+=lengthSign*0.5;} +vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) +{lumaNN=lumaSS;} +float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) +{posN.x-=offNP.x*3.0;} +if (!doneN) +{posN.y-=offNP.y*3.0;} +bool doneNP=(!doneN) || (!doneP);if (!doneP) +{posP.x+=offNP.x*3.0;} +if (!doneP) +{posP.y+=offNP.y*3.0;} +if (doneNP) +{if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} +float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) +{dstN=posM.y-posN.y;} +if (!horzSpan) +{dstP=posP.y-posM.y;} +bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN{let t=this.texelSize;e.setFloat2("texelSize",t.x,t.y)})}_getDefines(){let e=this.getEngine();if(!e)return null;let t=e.getGlInfo();return t&&t.renderer&&t.renderer.toLowerCase().indexOf("mali")>-1?"#define MALI 1\n":null}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new xX(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,rg.H)("BABYLON.FxaaPostProcess",xX);let xY=`#include +uniform sampler2D textureSampler; +uniform float intensity;uniform float animatedSeed;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`;nw.v.ShadersStore.grainPixelShader=xY;class xj extends nz{getClassName(){return"GrainPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"grain",["intensity","animatedSeed"],[],t,i,r,s,n,null,a,void 0,null,o),this.intensity=30,this.animated=!1,this.onApplyObservable.add(e=>{e.setFloat("intensity",this.intensity),e.setFloat("animatedSeed",this.animated?Math.random()+1:1)})}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new xj(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],xj.prototype,"intensity",void 0),(0,sx.gn)([(0,rG.qC)()],xj.prototype,"animated",void 0),(0,rg.H)("BABYLON.GrainPostProcess",xj);let xq=`varying vec2 vUV;uniform sampler2D textureSampler;const vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722); +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 tex=texture2D(textureSampler,vUV);vec3 c=tex.rgb;float luma=dot(c.rgb,RGBLuminanceCoefficients);gl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); }`;nw.v.ShadersStore.highlightsPixelShader=xq;let xK=`varying vec2 vUV;uniform sampler2D textureSampler; +#include +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 result=texture2D(textureSampler,vUV); +#ifdef IMAGEPROCESSING +#ifndef FROMLINEARSPACE +result.rgb=toLinearSpace(result.rgb); +#endif +result=applyImageProcessing(result); +#else +#ifdef FROMLINEARSPACE +result=applyImageProcessing(result); +#endif +#endif +gl_FragColor=result;}`;nw.v.ShadersStore.imageProcessingPixelShader=xK;class x$ extends nz{get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){e.applyByPostProcess=!0,this._attachImageProcessingConfiguration(e)}_attachImageProcessingConfiguration(e,t=!1){if(e!==this._imageProcessingConfiguration){if(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),e)this._imageProcessingConfiguration=e;else{let e=null,t=this.getEngine(),i=this.getCamera();if(i)e=i.getScene();else if(t&&t.scenes){let i=t.scenes;e=i[i.length-1]}else e=rL.l.LastCreatedScene;e?this._imageProcessingConfiguration=e.imageProcessingConfiguration:this._imageProcessingConfiguration=new nY.$}this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._updateParameters()})),t||this._updateParameters()}}get isSupported(){let e=this.getEffect();return!e||e.isSupported}get colorCurves(){return this.imageProcessingConfiguration.colorCurves}set colorCurves(e){this.imageProcessingConfiguration.colorCurves=e}get colorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set colorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get colorGradingTexture(){return this.imageProcessingConfiguration.colorGradingTexture}set colorGradingTexture(e){this.imageProcessingConfiguration.colorGradingTexture=e}get colorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set colorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get exposure(){return this.imageProcessingConfiguration.exposure}set exposure(e){this.imageProcessingConfiguration.exposure=e}get toneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set toneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get toneMappingType(){return this._imageProcessingConfiguration.toneMappingType}set toneMappingType(e){this._imageProcessingConfiguration.toneMappingType=e}get contrast(){return this.imageProcessingConfiguration.contrast}set contrast(e){this.imageProcessingConfiguration.contrast=e}get vignetteStretch(){return this.imageProcessingConfiguration.vignetteStretch}set vignetteStretch(e){this.imageProcessingConfiguration.vignetteStretch=e}get vignetteCentreX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCentreX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteCentreY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCentreY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterY(){return this.imageProcessingConfiguration.vignetteCenterY}set vignetteCenterY(e){this.imageProcessingConfiguration.vignetteCenterY=e}get vignetteCenterX(){return this.imageProcessingConfiguration.vignetteCenterX}set vignetteCenterX(e){this.imageProcessingConfiguration.vignetteCenterX=e}get vignetteWeight(){return this.imageProcessingConfiguration.vignetteWeight}set vignetteWeight(e){this.imageProcessingConfiguration.vignetteWeight=e}get vignetteColor(){return this.imageProcessingConfiguration.vignetteColor}set vignetteColor(e){this.imageProcessingConfiguration.vignetteColor=e}get vignetteCameraFov(){return this.imageProcessingConfiguration.vignetteCameraFov}set vignetteCameraFov(e){this.imageProcessingConfiguration.vignetteCameraFov=e}get vignetteBlendMode(){return this.imageProcessingConfiguration.vignetteBlendMode}set vignetteBlendMode(e){this.imageProcessingConfiguration.vignetteBlendMode=e}get vignetteEnabled(){return this.imageProcessingConfiguration.vignetteEnabled}set vignetteEnabled(e){this.imageProcessingConfiguration.vignetteEnabled=e}get ditheringIntensity(){return this.imageProcessingConfiguration.ditheringIntensity}set ditheringIntensity(e){this.imageProcessingConfiguration.ditheringIntensity=e}get ditheringEnabled(){return this.imageProcessingConfiguration.ditheringEnabled}set ditheringEnabled(e){this.imageProcessingConfiguration.ditheringEnabled=e}get fromLinearSpace(){return this._fromLinearSpace}set fromLinearSpace(e){this._fromLinearSpace!==e&&(this._fromLinearSpace=e,this._updateParameters())}constructor(e,t,i=null,r,s,n,a=0,o){super(e,"imageProcessing",[],[],t,i,r,s,n,null,a,"postprocess",null,!0),this._fromLinearSpace=!0,this._defines={IMAGEPROCESSING:!1,VIGNETTE:!1,VIGNETTEBLENDMODEMULTIPLY:!1,VIGNETTEBLENDMODEOPAQUE:!1,TONEMAPPING:!1,TONEMAPPING_ACES:!1,CONTRAST:!1,COLORCURVES:!1,COLORGRADING:!1,COLORGRADING3D:!1,FROMLINEARSPACE:!1,SAMPLER3DGREENDEPTH:!1,SAMPLER3DBGRMAP:!1,DITHER:!1,IMAGEPROCESSINGPOSTPROCESS:!1,EXPOSURE:!1,SKIPFINALCOLORCLAMP:!1},o?(o.applyByPostProcess=!0,this._attachImageProcessingConfiguration(o,!0),this._updateParameters()):(this._attachImageProcessingConfiguration(null,!0),this.imageProcessingConfiguration.applyByPostProcess=!0),this.onApply=e=>{this.imageProcessingConfiguration.bind(e,this.aspectRatio)}}getClassName(){return"ImageProcessingPostProcess"}_updateParameters(){this._defines.FROMLINEARSPACE=this._fromLinearSpace,this.imageProcessingConfiguration.prepareDefines(this._defines,!0);let e="";for(let t in this._defines)this._defines[t]&&(e+=`#define ${t}; +`);let t=["textureSampler"],i=["scale"];nY.$&&(nY.$.PrepareSamplers(t,this._defines),nY.$.PrepareUniforms(i,this._defines)),this.updateEffect(e,i,t)}dispose(e){super.dispose(e),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration&&(this.imageProcessingConfiguration.applyByPostProcess=!1)}}(0,sx.gn)([(0,rG.qC)()],x$.prototype,"_fromLinearSpace",void 0);let xQ=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +layout(location=0) out vec4 glFragData[{X}]; +#endif +`;nw.v.IncludesShadersStore.mrtFragmentDeclaration=xQ;let xZ=`#extension GL_EXT_draw_buffers : require +#if defined(BUMP) || !defined(NORMAL) +#extension GL_OES_standard_derivatives : enable +#endif +precision highp float; +#ifdef BUMP +varying mat4 vWorldView;varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#ifdef VELOCITY +varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#ifdef NEED_UV +varying vec2 vUV; +#endif +#ifdef BUMP +uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; +#endif +#if defined(REFLECTIVITY) +#if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; +#endif +#ifdef ALBEDOTEXTURE +varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; +#endif +#ifdef REFLECTIVITYCOLOR +uniform vec3 reflectivityColor; +#endif +#ifdef ALBEDOCOLOR +uniform vec3 albedoColor; +#endif +#ifdef METALLIC +uniform float metallic; +#endif +#if defined(ROUGHNESS) || defined(GLOSSINESS) +uniform float glossiness; +#endif +#endif +#if defined(ALPHATEST) && defined(NEED_UV) +uniform sampler2D diffuseSampler; +#endif +#include +#include[RENDER_TARGET_COUNT] +#include +#include +#include +void main() { +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +vec3 normalOutput; +#ifdef BUMP +vec3 normalW=normalize(vNormalW); +#include +#ifdef NORMAL_WORLDSPACE +normalOutput=normalW; +#else +normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); +#endif +#else +normalOutput=normalize(vNormalV); +#endif +#ifdef ENCODE_NORMAL +normalOutput=normalOutput*0.5+0.5; +#endif +#ifdef PREPASS +#ifdef PREPASS_DEPTH +gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); +#endif +#ifdef PREPASS_NORMAL +gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); +#endif +#else +gl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);gl_FragData[1]=vec4(normalOutput,1.0); +#endif +#ifdef POSITION +gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); +#endif +#ifdef VELOCITY +vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); +#endif +#ifdef REFLECTIVITY +vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); +#ifdef METALLICWORKFLOW +float metal=1.0;float roughness=1.0; +#ifdef ORMTEXTURE +metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; +#endif +#ifdef METALLIC +metal*=metallic; +#endif +#ifdef ROUGHNESS +roughness*=(1.0-glossiness); +#endif +reflectivity.a-=roughness;vec3 color=vec3(1.0); +#ifdef ALBEDOTEXTURE +color=texture2D(albedoSampler,vAlbedoUV).rgb; +#ifdef GAMMAALBEDO +color=toLinearSpace(color); +#endif +#endif +#ifdef ALBEDOCOLOR +color*=albedoColor.xyz; +#endif +reflectivity.rgb=mix(vec3(0.04),color,metal); +#else +#if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) +reflectivity=texture2D(reflectivitySampler,vReflectivityUV); +#ifdef GAMMAREFLECTIVITYTEXTURE +reflectivity.rgb=toLinearSpace(reflectivity.rgb); +#endif +#else +#ifdef REFLECTIVITYCOLOR +reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; +#endif +#endif +#ifdef GLOSSINESSS +reflectivity.a*=glossiness; +#endif +#endif +gl_FragData[REFLECTIVITY_INDEX]=reflectivity; +#endif +} +`;nw.v.ShadersStore.geometryPixelShader=xZ,nw.v.IncludesShadersStore.geometryVertexDeclaration="uniform mat4 viewProjection;uniform mat4 view;";let xJ=`#include +`;nw.v.IncludesShadersStore.geometryUboDeclaration=xJ;let x0=`precision highp float; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include<__decl__geometryVertex> +#include +attribute vec3 position;attribute vec3 normal; +#ifdef NEED_UV +varying vec2 vUV; +#ifdef ALPHATEST +uniform mat4 diffuseMatrix; +#endif +#ifdef BUMP +uniform mat4 bumpMatrix;varying vec2 vBumpUV; +#endif +#ifdef REFLECTIVITY +uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; +#endif +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#ifdef BUMP +varying mat4 vWorldView; +#endif +#ifdef BUMP +varying vec3 vNormalW; +#else +varying vec3 vNormalV; +#endif +varying vec4 vViewPos; +#if defined(POSITION) || defined(BUMP) +varying vec3 vPositionW; +#endif +#ifdef VELOCITY +uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#if defined(VELOCITY) && !defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#include +#include +vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); +#ifdef BUMP +vWorldView=view*finalWorld;vNormalW=normalUpdated; +#else +#ifdef NORMAL_WORLDSPACE +vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); +#else +vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); +#endif +#endif +vViewPos=view*worldPos; +#if defined(VELOCITY) && defined(BONES_VELOCITY_ENABLED) +vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if NUM_BONE_INFLUENCERS>0 +mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; +#if NUM_BONE_INFLUENCERS>1 +previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; +#endif +#if NUM_BONE_INFLUENCERS>2 +previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; +#endif +#if NUM_BONE_INFLUENCERS>3 +previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; +#endif +#if NUM_BONE_INFLUENCERS>4 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; +#endif +#if NUM_BONE_INFLUENCERS>5 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; +#endif +#if NUM_BONE_INFLUENCERS>6 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; +#endif +#if NUM_BONE_INFLUENCERS>7 +previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; +#endif +vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); +#else +vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); +#endif +#endif +#if defined(POSITION) || defined(BUMP) +vPositionW=worldPos.xyz/worldPos.w; +#endif +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#include +#ifdef NEED_UV +#ifdef UV1 +#if defined(ALPHATEST) && defined(ALPHATEST_UV1) +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#else +vUV=uv; +#endif +#ifdef BUMP_UV1 +vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV1 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef ALBEDO_UV1 +vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#endif +#ifdef UV2 +#if defined(ALPHATEST) && defined(ALPHATEST_UV2) +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#else +vUV=uv2; +#endif +#ifdef BUMP_UV2 +vBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0)); +#endif +#ifdef REFLECTIVITY_UV2 +vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0)); +#endif +#ifdef ALBEDO_UV2 +vAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#endif +#include +} +`;nw.v.ShadersStore.geometryVertexShader=x0;let x1=["world","mBones","viewProjection","diffuseMatrix","view","previousWorld","previousViewProjection","mPreviousBones","bumpMatrix","reflectivityMatrix","albedoMatrix","reflectivityColor","albedoColor","metallic","glossiness","vTangentSpaceParams","vBumpInfos","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices","boneTextureWidth"];(0,lH.qx)(x1);class x2{get normalsAreUnsigned(){return this._normalsAreUnsigned}_linkPrePassRenderer(e){this._linkedWithPrePass=!0,this._prePassRenderer=e,this._multiRenderTarget&&(this._multiRenderTarget.onClearObservable.clear(),this._multiRenderTarget.onClearObservable.add(()=>{}))}_unlinkPrePassRenderer(){this._linkedWithPrePass=!1,this._createRenderTargets()}_resetLayout(){this._enablePosition=!1,this._enableReflectivity=!1,this._enableVelocity=!1,this._attachmentsFromPrePass=[]}_forceTextureType(e,t){e===x2.POSITION_TEXTURE_TYPE?(this._positionIndex=t,this._enablePosition=!0):e===x2.VELOCITY_TEXTURE_TYPE?(this._velocityIndex=t,this._enableVelocity=!0):e===x2.REFLECTIVITY_TEXTURE_TYPE?(this._reflectivityIndex=t,this._enableReflectivity=!0):e===x2.DEPTH_TEXTURE_TYPE?this._depthIndex=t:e===x2.NORMAL_TEXTURE_TYPE&&(this._normalIndex=t)}_setAttachments(e){this._attachmentsFromPrePass=e}_linkInternalTexture(e){this._multiRenderTarget.setInternalTexture(e,0,!1)}get renderList(){return this._multiRenderTarget.renderList}set renderList(e){this._multiRenderTarget.renderList=e}get isSupported(){return this._multiRenderTarget.isSupported}getTextureIndex(e){switch(e){case x2.POSITION_TEXTURE_TYPE:return this._positionIndex;case x2.VELOCITY_TEXTURE_TYPE:return this._velocityIndex;case x2.REFLECTIVITY_TEXTURE_TYPE:return this._reflectivityIndex;case x2.DEPTH_TEXTURE_TYPE:return this._linkedWithPrePass?this._depthIndex:0;case x2.NORMAL_TEXTURE_TYPE:return this._linkedWithPrePass?this._normalIndex:1;default:return -1}}get enablePosition(){return this._enablePosition}set enablePosition(e){this._enablePosition=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get enableVelocity(){return this._enableVelocity}set enableVelocity(e){this._enableVelocity=e,e||(this._previousTransformationMatrices={}),this._linkedWithPrePass||(this.dispose(),this._createRenderTargets()),this._scene.needsPreviousWorldMatrices=e}get enableReflectivity(){return this._enableReflectivity}set enableReflectivity(e){this._enableReflectivity=e,this._linkedWithPrePass||(this.dispose(),this._createRenderTargets())}get scene(){return this._scene}get ratio(){return"object"==typeof this._ratioOrDimensions?1:this._ratioOrDimensions}constructor(e,t=1,i=15,r){this._previousTransformationMatrices={},this._previousBonesTransformationMatrices={},this.excludedSkinnedMeshesFromVelocity=[],this.renderTransparentMeshes=!0,this.generateNormalsInWorldSpace=!1,this._normalsAreUnsigned=!1,this._resizeObserver=null,this._enablePosition=!1,this._enableVelocity=!1,this._enableReflectivity=!1,this._clearColor=new rm.HE(0,0,0,0),this._clearDepthColor=new rm.HE(1e8,0,0,1),this._positionIndex=-1,this._velocityIndex=-1,this._reflectivityIndex=-1,this._depthIndex=-1,this._normalIndex=-1,this._linkedWithPrePass=!1,this.useSpecificClearForDepthTexture=!1,this._scene=e,this._ratioOrDimensions=t,this._useUbo=e.getEngine().supportsUniformBuffers,this._depthFormat=i,this._textureTypesAndFormats=r||{},x2._SceneComponentInitialization(this._scene),this._createRenderTargets()}isReady(e,t){let i=e.getMaterial();if(i&&i.disableDepthWrite)return!1;let r=[],s=[sm.o.PositionKind,sm.o.NormalKind],n=e.getMesh();if(i){let e=!1;if(i.needAlphaTesting()&&i.getAlphaTestTexture()&&(r.push("#define ALPHATEST"),r.push(`#define ALPHATEST_UV${i.getAlphaTestTexture().coordinatesIndex+1}`),e=!0),i.bumpTexture&&ow.BumpTextureEnabled&&(r.push("#define BUMP"),r.push(`#define BUMP_UV${i.bumpTexture.coordinatesIndex+1}`),e=!0),this._enableReflectivity){let t=!1;"PBRMetallicRoughnessMaterial"===i.getClassName()?(null!==i.metallicRoughnessTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicRoughnessTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t&&(null!==i.baseTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.baseTexture.coordinatesIndex+1}`),i.baseTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.baseColor&&r.push("#define ALBEDOCOLOR"))):"PBRSpecularGlossinessMaterial"===i.getClassName()?(null!==i.specularGlossinessTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularGlossinessTexture.coordinatesIndex+1}`),e=!0,i.specularGlossinessTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE")):null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.glossiness&&r.push("#define GLOSSINESS")):"PBRMaterial"===i.getClassName()?(null!==i.metallicTexture&&(r.push("#define ORMTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.metallicTexture.coordinatesIndex+1}`),r.push("#define METALLICWORKFLOW"),e=!0,t=!0),null!==i.metallic&&(r.push("#define METALLIC"),r.push("#define METALLICWORKFLOW"),t=!0),null!==i.roughness&&(r.push("#define ROUGHNESS"),r.push("#define METALLICWORKFLOW"),t=!0),t?(null!==i.albedoTexture&&(r.push("#define ALBEDOTEXTURE"),r.push(`#define ALBEDO_UV${i.albedoTexture.coordinatesIndex+1}`),i.albedoTexture.gammaSpace&&r.push("#define GAMMAALBEDO"),e=!0),null!==i.albedoColor&&r.push("#define ALBEDOCOLOR")):(null!==i.reflectivityTexture?(r.push("#define SPECULARGLOSSINESSTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.reflectivityTexture.coordinatesIndex+1}`),i.reflectivityTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0):null!==i.reflectivityColor&&r.push("#define REFLECTIVITYCOLOR"),null!==i.microSurface&&r.push("#define GLOSSINESS"))):"StandardMaterial"===i.getClassName()&&(null!==i.specularTexture&&(r.push("#define REFLECTIVITYTEXTURE"),r.push(`#define REFLECTIVITY_UV${i.specularTexture.coordinatesIndex+1}`),i.specularTexture.gammaSpace&&r.push("#define GAMMAREFLECTIVITYTEXTURE"),e=!0),null!==i.specularColor&&r.push("#define REFLECTIVITYCOLOR"))}e&&(r.push("#define NEED_UV"),n.isVerticesDataPresent(sm.o.UVKind)&&(s.push(sm.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(sm.o.UV2Kind)&&(s.push(sm.o.UV2Kind),r.push("#define UV2")))}this._linkedWithPrePass&&(r.push("#define PREPASS"),-1!==this._depthIndex&&(r.push("#define DEPTH_INDEX "+this._depthIndex),r.push("#define PREPASS_DEPTH")),-1!==this._normalIndex&&(r.push("#define NORMAL_INDEX "+this._normalIndex),r.push("#define PREPASS_NORMAL"))),this._enablePosition&&(r.push("#define POSITION"),r.push("#define POSITION_INDEX "+this._positionIndex)),this._enableVelocity&&(r.push("#define VELOCITY"),r.push("#define VELOCITY_INDEX "+this._velocityIndex),-1===this.excludedSkinnedMeshesFromVelocity.indexOf(n)&&r.push("#define BONES_VELOCITY_ENABLED")),this._enableReflectivity&&(r.push("#define REFLECTIVITY"),r.push("#define REFLECTIVITY_INDEX "+this._reflectivityIndex)),this.generateNormalsInWorldSpace&&r.push("#define NORMAL_WORLDSPACE"),this._normalsAreUnsigned&&r.push("#define ENCODE_NORMAL"),n.useBones&&n.computeBonesUsingShaders&&n.skeleton?(s.push(sm.o.MatricesIndicesKind),s.push(sm.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(sm.o.MatricesIndicesExtraKind),s.push(sm.o.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BONETEXTURE "+n.skeleton.isUsingTextureForMatrices),r.push("#define BonesPerMesh "+(n.skeleton.bones.length+1))):(r.push("#define NUM_BONE_INFLUENCERS 0"),r.push("#define BONETEXTURE false"),r.push("#define BonesPerMesh 0"));let a=n.morphTargetManager,o=0;a&&a.numInfluencers>0&&(o=a.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+o),a.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),nE.G.PrepareAttributesForMorphTargetsInfluencers(s,n,o)),t&&(r.push("#define INSTANCES"),nE.G.PushAttributesForInstances(s,this._enableVelocity),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES")),this._linkedWithPrePass?r.push("#define RENDER_TARGET_COUNT "+this._attachmentsFromPrePass.length):r.push("#define RENDER_TARGET_COUNT "+this._multiRenderTarget.textures.length),(0,lH.lK)(i,this._scene,r);let l=this._scene.getEngine(),h=e._getDrawWrapper(void 0,!0),u=h.defines,c=r.join("\n");return u!==c&&h.setEffect(l.createEffect("geometry",{attributes:s,uniformsNames:x1,samplers:["diffuseSampler","bumpSampler","reflectivitySampler","albedoSampler","morphTargets","boneSampler"],defines:c,onCompiled:null,fallbacks:null,onError:null,uniformBuffersNames:["Scene"],indexParameters:{buffersCount:this._multiRenderTarget.textures.length-1,maxSimultaneousMorphTargets:o}},l),c),h.effect.isReady()}getGBuffer(){return this._multiRenderTarget}get samples(){return this._multiRenderTarget.samples}set samples(e){this._multiRenderTarget.samples=e}dispose(){this._resizeObserver&&(this._scene.getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.getGBuffer().dispose()}_assignRenderTargetIndices(){let e=[],t=[],i=2;return e.push("gBuffer_Depth","gBuffer_Normal"),t.push(this._textureTypesAndFormats[x2.DEPTH_TEXTURE_TYPE]),t.push(this._textureTypesAndFormats[x2.NORMAL_TEXTURE_TYPE]),this._enablePosition&&(this._positionIndex=i,i++,e.push("gBuffer_Position"),t.push(this._textureTypesAndFormats[x2.POSITION_TEXTURE_TYPE])),this._enableVelocity&&(this._velocityIndex=i,i++,e.push("gBuffer_Velocity"),t.push(this._textureTypesAndFormats[x2.VELOCITY_TEXTURE_TYPE])),this._enableReflectivity&&(this._reflectivityIndex=i,i++,e.push("gBuffer_Reflectivity"),t.push(this._textureTypesAndFormats[x2.REFLECTIVITY_TEXTURE_TYPE])),[i,e,t]}_createRenderTargets(){let e=this._scene.getEngine(),[t,i,r]=this._assignRenderTargetIndices(),s=0;e._caps.textureFloat&&e._caps.textureFloatLinearFiltering?s=1:e._caps.textureHalfFloat&&e._caps.textureHalfFloatLinearFiltering&&(s=2);let n=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions},a=[],o=[];for(let e of r)e?(a.push(e.textureType),o.push(e.textureFormat)):(a.push(s),o.push(5));if(this._normalsAreUnsigned=11===a[x2.NORMAL_TEXTURE_TYPE]||13===a[x2.NORMAL_TEXTURE_TYPE],this._multiRenderTarget=new fX("gBuffer",n,t,this._scene,{generateMipMaps:!1,generateDepthTexture:!0,types:a,formats:o,depthTextureFormat:this._depthFormat},i.concat("gBuffer_DepthBuffer")),!this.isSupported)return;this._multiRenderTarget.wrapU=sj.CLAMP_ADDRESSMODE,this._multiRenderTarget.wrapV=sj.CLAMP_ADDRESSMODE,this._multiRenderTarget.refreshRate=1,this._multiRenderTarget.renderParticles=!1,this._multiRenderTarget.renderList=null;let l=[!0],h=[!1],u=[!0];for(let e=1;e{e.bindAttachments(this.useSpecificClearForDepthTexture?d:c),e.clear(this._clearColor,!0,!0,!0),this.useSpecificClearForDepthTexture&&(e.bindAttachments(p),e.clear(this._clearDepthColor,!0,!0,!0)),e.bindAttachments(c)}),this._resizeObserver=e.onResizeObservable.add(()=>{if(this._multiRenderTarget){let t=void 0!==this._ratioOrDimensions.width?this._ratioOrDimensions:{width:e.getRenderWidth()*this._ratioOrDimensions,height:e.getRenderHeight()*this._ratioOrDimensions};this._multiRenderTarget.resize(t)}});let _=e=>{let t=e.getRenderingMesh(),i=e.getEffectiveMesh(),r=this._scene,s=r.getEngine(),n=e.getMaterial();if(!n)return;if(i._internalAbstractMeshDataInfo._isActiveIntermediate=!1,this._enableVelocity&&!this._previousTransformationMatrices[i.uniqueId]&&(this._previousTransformationMatrices[i.uniqueId]={world:rf.y3.Identity(),viewProjection:r.getTransformMatrix()},t.skeleton)){let e=t.skeleton.getTransformMatrices(t);this._previousBonesTransformationMatrices[t.uniqueId]=this._copyBonesTransformationMatrices(e,new Float32Array(e.length))}let a=t._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(a.mustReturn)return;let o=s.getCaps().instancedArrays&&(null!==a.visibleInstances[e._id]||t.hasThinInstances),l=i.getWorldMatrix();if(this.isReady(e,o)){let h;let u=e._getDrawWrapper();if(!u)return;let c=u.effect;s.enableEffect(u),o||t._bind(e,c,n.fillMode),this._useUbo?(nE.G.BindSceneUniformBuffer(c,this._scene.getSceneUniformBuffer()),this._scene.finalizeSceneUbo()):(c.setMatrix("viewProjection",r.getTransformMatrix()),c.setMatrix("view",r.getViewMatrix()));let d=t._instanceDataStorage;if(!d.isFrozen&&(n.backFaceCulling||null!==t.overrideMaterialSideOrientation)){let e=i._getWorldMatrixDeterminant();null===(h=t.overrideMaterialSideOrientation)&&(h=n.sideOrientation),e<0&&(h=h===nu.F.ClockWiseSideOrientation?nu.F.CounterClockWiseSideOrientation:nu.F.ClockWiseSideOrientation)}else h=d.sideOrientation;if(n._preBind(u,h),n.needAlphaTesting()){let e=n.getAlphaTestTexture();e&&(c.setTexture("diffuseSampler",e),c.setMatrix("diffuseMatrix",e.getTextureMatrix()))}if(n.bumpTexture&&r.getEngine().getCaps().standardDerivatives&&ow.BumpTextureEnabled&&(c.setFloat3("vBumpInfos",n.bumpTexture.coordinatesIndex,1/n.bumpTexture.level,n.parallaxScaleBias),c.setMatrix("bumpMatrix",n.bumpTexture.getTextureMatrix()),c.setTexture("bumpSampler",n.bumpTexture),c.setFloat2("vTangentSpaceParams",n.invertNormalMapX?-1:1,n.invertNormalMapY?-1:1)),this._enableReflectivity&&("PBRMetallicRoughnessMaterial"===n.getClassName()?(null!==n.metallicRoughnessTexture&&(c.setTexture("reflectivitySampler",n.metallicRoughnessTexture),c.setMatrix("reflectivityMatrix",n.metallicRoughnessTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.baseTexture&&(c.setTexture("albedoSampler",n.baseTexture),c.setMatrix("albedoMatrix",n.baseTexture.getTextureMatrix())),null!==n.baseColor&&c.setColor3("albedoColor",n.baseColor)):"PBRSpecularGlossinessMaterial"===n.getClassName()?(null!==n.specularGlossinessTexture?(c.setTexture("reflectivitySampler",n.specularGlossinessTexture),c.setMatrix("reflectivityMatrix",n.specularGlossinessTexture.getTextureMatrix())):null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor),null!==n.glossiness&&c.setFloat("glossiness",n.glossiness)):"PBRMaterial"===n.getClassName()?(null!==n.metallicTexture&&(c.setTexture("reflectivitySampler",n.metallicTexture),c.setMatrix("reflectivityMatrix",n.metallicTexture.getTextureMatrix())),null!==n.metallic&&c.setFloat("metallic",n.metallic),null!==n.roughness&&c.setFloat("glossiness",1-n.roughness),null!==n.roughness||null!==n.metallic||null!==n.metallicTexture?(null!==n.albedoTexture&&(c.setTexture("albedoSampler",n.albedoTexture),c.setMatrix("albedoMatrix",n.albedoTexture.getTextureMatrix())),null!==n.albedoColor&&c.setColor3("albedoColor",n.albedoColor)):(null!==n.reflectivityTexture?(c.setTexture("reflectivitySampler",n.reflectivityTexture),c.setMatrix("reflectivityMatrix",n.reflectivityTexture.getTextureMatrix())):null!==n.reflectivityColor&&c.setColor3("reflectivityColor",n.reflectivityColor),null!==n.microSurface&&c.setFloat("glossiness",n.microSurface))):"StandardMaterial"===n.getClassName()&&(null!==n.specularTexture&&(c.setTexture("reflectivitySampler",n.specularTexture),c.setMatrix("reflectivityMatrix",n.specularTexture.getTextureMatrix())),null!==n.specularColor&&c.setColor3("reflectivityColor",n.specularColor))),(0,lH.an)(c,n,this._scene),t.useBones&&t.computeBonesUsingShaders&&t.skeleton){let e=t.skeleton;if(e.isUsingTextureForMatrices&&c.getUniformIndex("boneTextureWidth")>-1){let i=e.getTransformMatrixTexture(t);c.setTexture("boneSampler",i),c.setFloat("boneTextureWidth",4*(e.bones.length+1))}else c.setMatrices("mBones",t.skeleton.getTransformMatrices(t));this._enableVelocity&&c.setMatrices("mPreviousBones",this._previousBonesTransformationMatrices[t.uniqueId])}nE.G.BindMorphTargetParameters(t,c),t.morphTargetManager&&t.morphTargetManager.isUsingTextureForTargets&&t.morphTargetManager._bind(c),this._enableVelocity&&(c.setMatrix("previousWorld",this._previousTransformationMatrices[i.uniqueId].world),c.setMatrix("previousViewProjection",this._previousTransformationMatrices[i.uniqueId].viewProjection)),o&&t.hasThinInstances&&c.setMatrix("world",l),t._processRendering(i,e,c,n.fillMode,a,o,(e,t)=>{e||c.setMatrix("world",t)})}this._enableVelocity&&(this._previousTransformationMatrices[i.uniqueId].world=l.clone(),this._previousTransformationMatrices[i.uniqueId].viewProjection=this._scene.getTransformMatrix().clone(),t.skeleton&&this._copyBonesTransformationMatrices(t.skeleton.getTransformMatrices(t),this._previousBonesTransformationMatrices[i.uniqueId]))};this._multiRenderTarget.customIsReadyFunction=(t,i,r)=>{if((r||0===i)&&t.subMeshes)for(let i=0;i{let n;if(this._linkedWithPrePass){if(!this._prePassRenderer.enabled)return;this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass)}if(s.length){for(e.setColorWrite(!1),n=0;n{throw(0,sM.S)("GeometryBufferRendererSceneComponent")};class x3{constructor(){this.enabled=!1,this.name="motionBlur",this.texturesRequired=[2]}}Object.defineProperty(r2.x.prototype,"geometryBufferRenderer",{get:function(){return this._geometryBufferRenderer},set:function(e){e&&e.isSupported&&(this._geometryBufferRenderer=e)},enumerable:!0,configurable:!0}),r2.x.prototype.enableGeometryBufferRenderer=function(e=1,t=15,i){return this._geometryBufferRenderer||(this._geometryBufferRenderer=new x2(this,e,t,i),this._geometryBufferRenderer.isSupported||(this._geometryBufferRenderer=null)),this._geometryBufferRenderer},r2.x.prototype.disableGeometryBufferRenderer=function(){this._geometryBufferRenderer&&(this._geometryBufferRenderer.dispose(),this._geometryBufferRenderer=null)};class x4{constructor(e){this.name=sN.l.NAME_GEOMETRYBUFFERRENDERER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sN.l.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER,this,this._gatherRenderTargets)}rebuild(){}dispose(){}_gatherRenderTargets(e){this.scene._geometryBufferRenderer&&e.push(this.scene._geometryBufferRenderer.getGBuffer())}}x2._SceneComponentInitialization=e=>{let t=e._getComponent(sN.l.NAME_GEOMETRYBUFFERRENDERER);t||(t=new x4(e),e._addComponent(t))};let x5=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; +#ifdef OBJECT_BASED +uniform sampler2D velocitySampler; +#else +uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#ifdef GEOMETRY_SUPPORTED +#ifdef OBJECT_BASED +vec2 texelSize=1.0/screenSize;vec4 velocityColor=texture2D(velocitySampler,vUV);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 velocity=vec2(pow(velocityColor.r,3.0),pow(velocityColor.g,3.0))*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=samplesCount) +break;vec2 offset=vUV+velocity*(hlim+float(i)); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset,0.0); +#else +result+=texture2D(textureSampler,offset); +#endif +} +gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; +#else +vec2 texelSize=1.0/screenSize;float depth=texture2D(depthSampler,vUV).r;depth=projection[2].z+projection[3].z/depth; +vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));vec4 result=texture2D(textureSampler,vUV);for (int i=1; i=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5); +#if defined(WEBGPU) +result+=texture2DLodEXT(textureSampler,offset1,0.0); +#else +result+=texture2D(textureSampler,offset1); +#endif +} +gl_FragColor=result/float(nSamples); +#endif +#else +gl_FragColor=texture2D(textureSampler,vUV); +#endif +} +`;nw.v.ShadersStore.motionBlurPixelShader=x5;class x6 extends nz{get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this._motionBlurSamples=e,this._updateEffect()}get isObjectBased(){return this._isObjectBased}set isObjectBased(e){this._isObjectBased!==e&&(this._isObjectBased=e,this._applyMode())}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}getClassName(){return"MotionBlurPostProcess"}constructor(e,t,i,r,s,n,a,o=0,l=!1,h=!1){super(e,"motionBlur",["motionStrength","motionScale","screenSize","inverseViewProjection","prevViewProjection","projection"],["velocitySampler","depthSampler"],i,r,s,n,a,"#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED",o,void 0,null,l),this.motionStrength=1,this._motionBlurSamples=32,this._isObjectBased=!0,this._forceGeometryBuffer=!1,this._invViewProjection=null,this._previousViewProjection=null,this._forceGeometryBuffer=h,this._forceGeometryBuffer?(t.enableGeometryBufferRenderer(),this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased)):(t.enablePrePassRenderer(),this._prePassRenderer&&(this._prePassRenderer.markAsDirty(),this._prePassEffectConfiguration=new x3)),this._applyMode()}excludeSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}t.push(e)}}removeExcludedSkinnedMesh(e){if(e.skeleton){let t;if(this._geometryBufferRenderer)t=this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity;else{if(!this._prePassRenderer)return;t=this._prePassRenderer.excludedSkinnedMesh}let i=t.indexOf(e);-1!==i&&t.splice(i,1)}}dispose(e){this._geometryBufferRenderer&&(this._geometryBufferRenderer._previousTransformationMatrices={},this._geometryBufferRenderer._previousBonesTransformationMatrices={},this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity=[]),super.dispose(e)}_applyMode(){if(!this._geometryBufferRenderer&&!this._prePassRenderer)return rb.Y.Warn("Multiple Render Target support needed to compute object based motion blur"),this.updateEffect();this._geometryBufferRenderer&&(this._geometryBufferRenderer.enableVelocity=this._isObjectBased),this._updateEffect(),this._invViewProjection=null,this._previousViewProjection=null,this.isObjectBased?(this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=2),this.onApply=e=>this._onApplyObjectBased(e)):(this._invViewProjection=rf.y3.Identity(),this._previousViewProjection=this._scene.getTransformMatrix().clone(),this._prePassRenderer&&this._prePassEffectConfiguration&&(this._prePassEffectConfiguration.texturesRequired[0]=5),this.onApply=e=>this._onApplyScreenBased(e))}_onApplyObjectBased(e){if(e.setVector2("screenSize",new rf.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(x2.VELOCITY_TEXTURE_TYPE);e.setTexture("velocitySampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(2);e.setTexture("velocitySampler",this._prePassRenderer.getRenderTarget().textures[t])}}_onApplyScreenBased(e){let t=rf.jp.Matrix[0];if(t.copyFrom(this._scene.getTransformMatrix()),t.invertToRef(this._invViewProjection),e.setMatrix("inverseViewProjection",this._invViewProjection),e.setMatrix("prevViewProjection",this._previousViewProjection),this._previousViewProjection.copyFrom(t),e.setMatrix("projection",this._scene.getProjectionMatrix()),e.setVector2("screenSize",new rf.FM(this.width,this.height)),e.setFloat("motionScale",this._scene.getAnimationRatio()),e.setFloat("motionStrength",this.motionStrength),this._geometryBufferRenderer){let t=this._geometryBufferRenderer.getTextureIndex(x2.DEPTH_TEXTURE_TYPE);e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[t])}else if(this._prePassRenderer){let t=this._prePassRenderer.getIndex(5);e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[t])}}_updateEffect(){if(this._geometryBufferRenderer||this._prePassRenderer){let e=["#define GEOMETRY_SUPPORTED","#define SAMPLES "+this._motionBlurSamples.toFixed(1),this._isObjectBased?"#define OBJECT_BASED":"#define SCREEN_BASED"];this.updateEffect(e.join("\n"))}}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new x6(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable,e.textureType,!1),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],x6.prototype,"motionStrength",void 0),(0,sx.gn)([(0,rG.qC)()],x6.prototype,"motionBlurSamples",null),(0,sx.gn)([(0,rG.qC)()],x6.prototype,"isObjectBased",null),(0,rg.H)("BABYLON.MotionBlurPostProcess",x6),nw.v.ShadersStore.refractionPixelShader="varying vec2 vUV;uniform sampler2D textureSampler;uniform sampler2D refractionSampler;uniform vec3 baseColor;uniform float depth;uniform float colorLevel;void main() {float ref=1.0-texture2D(refractionSampler,vUV).r;vec2 uv=vUV-vec2(0.5);vec2 offset=uv*depth*ref;vec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;gl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);}";class x8 extends nz{get refractionTexture(){return this._refTexture}set refractionTexture(e){this._refTexture&&this._ownRefractionTexture&&this._refTexture.dispose(),this._refTexture=e,this._ownRefractionTexture=!1}getClassName(){return"RefractionPostProcess"}constructor(e,t,i,r,s,n,a,o,l,h){super(e,"refraction",["baseColor","depth","colorLevel"],["refractionSampler"],n,a,o,l,h),this._ownRefractionTexture=!0,this.color=i,this.depth=r,this.colorLevel=s,this.refractionTextureUrl=t,this.onActivateObservable.add(e=>{this._refTexture=this._refTexture||new sj(t,e.getScene())}),this.onApplyObservable.add(e=>{e.setColor3("baseColor",this.color),e.setFloat("depth",this.depth),e.setFloat("colorLevel",this.colorLevel),e.setTexture("refractionSampler",this._refTexture)})}dispose(e){this._refTexture&&this._ownRefractionTexture&&(this._refTexture.dispose(),this._refTexture=null),super.dispose(e)}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new x8(e.name,e.refractionTextureUrl,e.color,e.depth,e.colorLevel,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.reusable),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],x8.prototype,"color",void 0),(0,sx.gn)([(0,rG.qC)()],x8.prototype,"depth",void 0),(0,sx.gn)([(0,rG.qC)()],x8.prototype,"colorLevel",void 0),(0,sx.gn)([(0,rG.qC)()],x8.prototype,"refractionTextureUrl",void 0),(0,rg.H)("BABYLON.RefractionPostProcess",x8);let x7=`varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + +texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + +texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - +color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`;nw.v.ShadersStore.sharpenPixelShader=x7;class x9 extends nz{getClassName(){return"SharpenPostProcess"}constructor(e,t,i,r,s,n,a=0,o=!1){super(e,"sharpen",["sharpnessAmounts","screenSize"],null,t,i,r,s,n,null,a,void 0,null,o),this.colorAmount=1,this.edgeAmount=.3,this.onApply=e=>{e.setFloat2("screenSize",this.width,this.height),e.setFloat2("sharpnessAmounts",this.edgeAmount,this.colorAmount)}}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new x9(e.name,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],x9.prototype,"colorAmount",void 0),(0,sx.gn)([(0,rG.qC)()],x9.prototype,"edgeAmount",void 0),(0,rg.H)("BABYLON.SharpenPostProcess",x9);class Te{get name(){return this._name}get cameras(){return this._cameras}constructor(e,t){this._engine=e,this._name=t,this._renderEffects={},this._renderEffectsForIsolatedPass=[],this._cameras=[]}getClassName(){return"PostProcessRenderPipeline"}get isSupported(){for(let e in this._renderEffects)if(Object.prototype.hasOwnProperty.call(this._renderEffects,e)&&!this._renderEffects[e].isSupported)return!1;return!0}addEffect(e){this._renderEffects[e._name]=e}_rebuild(){}_enableEffect(e,t){let i=this._renderEffects[e];i&&i._enable(sg.w1.MakeArray(t||this._cameras))}_disableEffect(e,t){let i=this._renderEffects[e];i&&i._disable(sg.w1.MakeArray(t||this._cameras))}_attachCameras(e,t){let i;let r=sg.w1.MakeArray(e||this._cameras);if(!r)return;let s=[];for(i=0;i0){let i=this._renderEffects[t[0]].getPostProcesses();i&&(i[0].samples=e)}return!0}_adaptPostProcessesToViewPort(){for(let e of Object.keys(this._renderEffects)){let t=this._renderEffects[e].getPostProcesses();if(t)for(let e of t)e.adaptScaleToCurrentViewport=!0}}setPrePassRenderer(e){return!1}dispose(){}}(0,sx.gn)([(0,rG.qC)()],Te.prototype,"_name",void 0);class Tt{constructor(){this._renderPipelines={}}get supportedPipelines(){let e=[];for(let t in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,t)){let i=this._renderPipelines[t];i.isSupported&&e.push(i)}return e}addPipeline(e){this._renderPipelines[e._name]=e}removePipeline(e){delete this._renderPipelines[e]}attachCamerasToRenderPipeline(e,t,i=!1){let r=this._renderPipelines[e];r&&r._attachCameras(t,i)}detachCamerasFromRenderPipeline(e,t){let i=this._renderPipelines[e];i&&i._detachCameras(t)}enableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._enableEffect(t,i)}disableEffectInPipeline(e,t,i){let r=this._renderPipelines[e];r&&r._disableEffect(t,i)}update(){for(let e in this._renderPipelines)if(Object.prototype.hasOwnProperty.call(this._renderPipelines,e)){let t=this._renderPipelines[e];t.isSupported?t._update():(t.dispose(),delete this._renderPipelines[e])}}_rebuild(){for(let e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e]._rebuild()}dispose(){for(let e in this._renderPipelines)Object.prototype.hasOwnProperty.call(this._renderPipelines,e)&&this._renderPipelines[e].dispose()}}Object.defineProperty(r2.x.prototype,"postProcessRenderPipelineManager",{get:function(){if(!this._postProcessRenderPipelineManager){let e=this._getComponent(sN.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER);e||(e=new Ti(this),this._addComponent(e)),this._postProcessRenderPipelineManager=new Tt}return this._postProcessRenderPipelineManager},enumerable:!0,configurable:!0});class Ti{constructor(e){this.name=sN.l.NAME_POSTPROCESSRENDERPIPELINEMANAGER,this.scene=e}register(){this.scene._gatherRenderTargetsStage.registerStep(sN.l.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER,this,this._gatherRenderTargets)}rebuild(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager._rebuild()}dispose(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.dispose()}_gatherRenderTargets(){this.scene._postProcessRenderPipelineManager&&this.scene._postProcessRenderPipelineManager.update()}}class Tr extends Te{get automaticBuild(){return this._buildAllowed}set automaticBuild(e){this._buildAllowed=e}get scene(){return this._scene}set sharpenEnabled(e){this._sharpenEnabled!==e&&(this._sharpenEnabled=e,this._buildPipeline())}get sharpenEnabled(){return this._sharpenEnabled}get bloomKernel(){return this._bloomKernel}set bloomKernel(e){this._bloomKernel=e,this.bloom.kernel=e/this._hardwareScaleLevel}set bloomWeight(e){this._bloomWeight!==e&&(this.bloom.weight=e,this._bloomWeight=e)}get bloomWeight(){return this._bloomWeight}set bloomThreshold(e){this._bloomThreshold!==e&&(this.bloom.threshold=e,this._bloomThreshold=e)}get bloomThreshold(){return this._bloomThreshold}set bloomScale(e){this._bloomScale!==e&&(this._bloomScale=e,this._rebuildBloom(),this._buildPipeline())}get bloomScale(){return this._bloomScale}set bloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get bloomEnabled(){return this._bloomEnabled}_rebuildBloom(){let e=this.bloom;this.bloom=new xA(this._scene,this.bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!1),this.bloom.threshold=e.threshold;for(let t=0;tthis.sharpen,!0),this.depthOfField=new xU(this._scene,null,this._depthOfFieldBlurLevel,this._defaultPipelineTextureType,!0),this._hardwareScaleLevel=a.getHardwareScalingLevel(),this._resizeObserver=a.onResizeObservable.add(()=>{this._hardwareScaleLevel=a.getHardwareScalingLevel(),this.bloomKernel=this._bloomKernel}),this.bloom=new xA(this._scene,this._bloomScale,this._bloomWeight,this.bloomKernel/this._hardwareScaleLevel,this._defaultPipelineTextureType,!0),this.chromaticAberration=new xP("ChromaticAberration",a.getRenderWidth(),a.getRenderHeight(),1,null,sj.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._chromaticAberrationEffect=new xS(a,this.ChromaticAberrationPostProcessId,()=>this.chromaticAberration,!0),this.grain=new xj("Grain",1,null,sj.BILINEAR_SAMPLINGMODE,a,!1,this._defaultPipelineTextureType,!0),this._grainEffect=new xS(a,this.GrainPostProcessId,()=>this.grain,!0);let o=!0;this._imageProcessingConfigurationObserver=this._scene.imageProcessingConfiguration.onUpdateParameters.add(()=>{this.bloom._downscale._exposure=this._scene.imageProcessingConfiguration.exposure,this.imageProcessingEnabled!==this._scene.imageProcessingConfiguration.isEnabled&&(this._imageProcessingEnabled=this._scene.imageProcessingConfiguration.isEnabled,o?sg.w1.SetImmediate(()=>{this._buildPipeline()}):this._buildPipeline())}),this._buildPipeline(),o=!1}getClassName(){return"DefaultRenderingPipeline"}prepare(){let e=this._buildAllowed;this._buildAllowed=!0,this._buildPipeline(),this._buildAllowed=e}_setAutoClearAndTextureSharing(e,t=!1){this._hasCleared?e.autoClear=!1:(e.autoClear=!0,this._scene.autoClear=!1,this._hasCleared=!0),t||(this._prevPrevPostProcess?e.shareOutputWith(this._prevPrevPostProcess):e.useOwnOutput(),this._prevPostProcess&&(this._prevPrevPostProcess=this._prevPostProcess),this._prevPostProcess=e)}_buildPipeline(){if(!this._buildAllowed)return;this._scene.autoClear=!0;let e=this._scene.getEngine();if(this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._prevPostProcess=null,this._prevPrevPostProcess=null,this._hasCleared=!1,this.depthOfFieldEnabled){if(this._cameras.length>1){for(let e of this._cameras)this._scene.enableDepthRenderer(e).useOnlyInActiveCamera=!0;this._depthOfFieldSceneObserver=this._scene.onAfterRenderTargetsRenderObservable.add(e=>{this._cameras.indexOf(e.activeCamera)>-1&&(this.depthOfField.depthTexture=e.enableDepthRenderer(e.activeCamera).getDepthMap())})}else{this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);let e=this._scene.enableDepthRenderer(this._cameras[0]);this.depthOfField.depthTexture=e.getDepthMap()}this.depthOfField._isReady()||this.depthOfField._updateEffects(),this.addEffect(this.depthOfField),this._setAutoClearAndTextureSharing(this.depthOfField._effects[0],!0)}else this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);this.bloomEnabled&&(this.bloom._isReady()||this.bloom._updateEffects(),this.addEffect(this.bloom),this._setAutoClearAndTextureSharing(this.bloom._effects[0],!0)),this._imageProcessingEnabled&&(this.imageProcessing=new x$("imageProcessing",1,null,sj.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType,this.scene.imageProcessingConfiguration),this._hdr?(this.addEffect(new xS(e,this.ImageProcessingPostProcessId,()=>this.imageProcessing,!0)),this._setAutoClearAndTextureSharing(this.imageProcessing)):this._scene.imageProcessingConfiguration.applyByPostProcess=!1,this._cameras&&0!==this._cameras.length||(this._scene.imageProcessingConfiguration.applyByPostProcess=!1),this.imageProcessing.getEffect()||this.imageProcessing._updateParameters()),this.sharpenEnabled&&(this.sharpen.isReady()||this.sharpen.updateEffect(),this.addEffect(this._sharpenEffect),this._setAutoClearAndTextureSharing(this.sharpen)),this.grainEnabled&&(this.grain.isReady()||this.grain.updateEffect(),this.addEffect(this._grainEffect),this._setAutoClearAndTextureSharing(this.grain)),this.chromaticAberrationEnabled&&(this.chromaticAberration.isReady()||this.chromaticAberration.updateEffect(),this.addEffect(this._chromaticAberrationEffect),this._setAutoClearAndTextureSharing(this.chromaticAberration)),this.fxaaEnabled&&(this.fxaa=new xX("fxaa",1,null,sj.BILINEAR_SAMPLINGMODE,e,!1,this._defaultPipelineTextureType),this.addEffect(new xS(e,this.FxaaPostProcessId,()=>this.fxaa,!0)),this._setAutoClearAndTextureSharing(this.fxaa,!0)),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),(this._scene.activeCameras&&this._scene.activeCameras.length>1||this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera))&&(this._scene.autoClear=!0),this._activeCameraChangedObserver||(this._activeCameraChangedObserver=this._scene.onActiveCameraChanged.add(()=>{this._scene.activeCamera&&-1===this._cameras.indexOf(this._scene.activeCamera)&&(this._scene.autoClear=!0)})),this._activeCamerasChangedObserver||(this._activeCamerasChangedObserver=this._scene.onActiveCamerasChanged.add(()=>{this._scene.activeCameras&&this._scene.activeCameras.length>1&&(this._scene.autoClear=!0)})),this._adaptPostProcessesToViewPort(),!this._enableMSAAOnFirstPostProcess(this.samples)&&this.samples>1&&rb.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"),this.onBuildObservable.notifyObservers(this)}_disposePostProcesses(e=!1){for(let t=0;tnew Tr(e._name,e._name._hdr,t),e,t,i)}}(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"sharpenEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"bloomKernel",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"_bloomWeight",void 0),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"_bloomThreshold",void 0),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"_hdr",void 0),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"bloomWeight",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"bloomThreshold",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"bloomScale",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"bloomEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"depthOfFieldEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"depthOfFieldBlurLevel",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"fxaaEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"samples",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"imageProcessingEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"glowLayerEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"chromaticAberrationEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tr.prototype,"grainEnabled",null),(0,rg.H)("BABYLON.DefaultRenderingPipeline",Tr);let Ts=`uniform sampler2D textureSampler; +uniform float gain;uniform float threshold;uniform float screen_width;uniform float screen_height;varying vec2 vUV;vec4 highlightColor(vec4 color) {vec4 highlight=color;float luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));float lum_threshold;if (threshold>1.0) { lum_threshold=0.94+0.01*threshold; } +else { lum_threshold=0.5+0.44*threshold; } +luminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);highlight*=luminance*gain;highlight.a=1.0;return highlight;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 original=texture2D(textureSampler,vUV);if (gain==-1.0) {gl_FragColor=vec4(0.0,0.0,0.0,1.0);return;} +float w=2.0/screen_width;float h=2.0/screen_height;float weight=1.0;vec4 blurred=vec4(0.0,0.0,0.0,0.0); +#ifdef PENTAGON +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h))); +#else +blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));blurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h))); +#endif +blurred/=39.0;gl_FragColor=blurred;}`;nw.v.ShadersStore.lensHighlightsPixelShader=Ts;let Tn=`uniform sampler2D textureSampler;uniform sampler2D highlightsSampler;uniform sampler2D depthSampler;uniform sampler2D grainSampler;uniform float grain_amount;uniform bool blur_noise;uniform float screen_width;uniform float screen_height;uniform float distortion;uniform bool dof_enabled;uniform float screen_distance; +uniform float aperture;uniform float darken;uniform float edge_blur;uniform bool highlights;uniform float near;uniform float far;varying vec2 vUV; +#define PI 3.14159265 +#define TWOPI 6.28318530 +#define inverse_focal_length 0.1 +vec2 centered_screen_pos;vec2 distorted_coords;float radius2;float radius;vec2 rand(vec2 co) +{float noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));float noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));return clamp(vec2(noise1,noise2),0.0,1.0);} +vec2 getDistortedCoords(vec2 coords) {if (distortion==0.0) { return coords; } +vec2 direction=1.0*normalize(centered_screen_pos);vec2 dist_coords=vec2(0.5,0.5);dist_coords.x=0.5+direction.x*radius2*1.0;dist_coords.y=0.5+direction.y*radius2*1.0;float dist_amount=clamp(distortion*0.23,0.0,1.0);dist_coords=mix(coords,dist_coords,dist_amount);return dist_coords;} +float sampleScreen(inout vec4 color,in vec2 offset,in float weight) {vec2 coords=distorted_coords;float angle=rand(coords*100.0).x*TWOPI;coords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));color+=texture2D(textureSampler,coords)*weight;return weight;} +float getBlurLevel(float size) {return min(3.0,ceil(size/1.0));} +vec4 getBlurColor(float size) {vec4 col=texture2D(textureSampler,distorted_coords);float blur_level=getBlurLevel(size);float w=(size/screen_width);float h=(size/screen_height);float total_weight=1.0;vec2 sample_coords;total_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);total_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);total_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);total_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);total_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);total_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);total_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);total_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);total_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);total_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);if (blur_level>1.0) {total_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);total_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);total_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);total_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);total_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);total_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);total_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);total_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);total_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);total_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);} +if (blur_level>2.0) {total_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);total_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);total_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);total_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);total_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);total_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);total_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);total_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);total_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);} +col/=total_weight; +if (darken>0.0) {col.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);} +return col;} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);radius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;radius=sqrt(radius2);distorted_coords=getDistortedCoords(vUV); +vec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); +float depth=texture2D(depthSampler,distorted_coords).r; +float distance=near+(far-near)*depth; +vec4 color=texture2D(textureSampler,vUV); +float coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));if (dof_enabled==false || coc<0.07) { coc=0.0; } +float edge_blur_amount=0.0;if (edge_blur>0.0) {edge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;} +float blur_amount=max(edge_blur_amount,coc);if (blur_amount==0.0) {gl_FragColor=texture2D(textureSampler,distorted_coords);} +else {gl_FragColor=getBlurColor(blur_amount*1.7);if (highlights) {gl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;} +if (blur_noise) {vec2 noise=rand(distorted_coords)*0.01*blur_amount;vec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);gl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;}} +if (grain_amount>0.0) {vec4 grain_color=texture2D(grainSampler,texels_coords*0.003);gl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;}} +`;nw.v.ShadersStore.depthOfFieldPixelShader=Tn;class Ta{constructor(){this.enabled=!1,this.name="ssao2",this.texturesRequired=[6,5]}}let To=`precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +float scales[16]=float[16]( +0.1, +0.11406250000000001, +0.131640625, +0.15625, +0.187890625, +0.2265625, +0.272265625, +0.325, +0.384765625, +0.4515625, +0.525390625, +0.60625, +0.694140625, +0.7890625, +0.891015625, +1.0 +);uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base;uniform float xViewport;uniform float yViewport;uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() +{vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=depth/abs(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near);vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;} +float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} +occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} +#endif +#ifdef BLUR +uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; +#ifndef BLUR_BYPASS +uniform sampler2D depthSampler; +#ifdef BLUR_LEGACY +#define inline +float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} +#endif +#endif +void main() +{float result=0.0; +#ifdef BLUR_BYPASS +result=textureLod(textureSampler,vUV,0.0).r; +#else +#ifdef BLUR_H +vec2 step=vec2(1.0/outSize,0.0); +#else +vec2 step=vec2(0.0,1.0/outSize); +#endif +#ifdef BLUR_LEGACY +result=blur13Bilateral(textureSampler,vUV,step); +#else +float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; ithis._originalColorPostProcess,!0)),this.addEffect(new xS(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new xS(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new xS(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new xS(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}getClassName(){return"SSAO2RenderingPipeline"}dispose(e=!1){for(let e=0;e{if(!this._scene.activeCamera)return;let t=n?this._ssaoCombinePostProcess.width:this._ssaoCombinePostProcess.height,i=n?this._originalColorPostProcess.width:this._originalColorPostProcess.height;e.setFloat("outSize",t>0?t:i),e.setInt("samples",this.bilateralSamples),e.setFloat("soften",this.bilateralSoften),e.setFloat("tolerance",this.bilateralTolerance),this._geometryBufferRenderer?e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]):this._prePassRenderer&&e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)])},a.samples=this.textureSamples,a}_radicalInverse_VdC(e){return this._bits[0]=e,this._bits[0]=(this._bits[0]<<16|this._bits[0]>>16)>>>0,this._bits[0]=(1431655765&this._bits[0])<<1|(2863311530&this._bits[0])>>>1>>>0,this._bits[0]=(858993459&this._bits[0])<<2|(3435973836&this._bits[0])>>>2>>>0,this._bits[0]=(252645135&this._bits[0])<<4|(4042322160&this._bits[0])>>>4>>>0,this._bits[0]=(16711935&this._bits[0])<<8|(4278255360&this._bits[0])>>>8>>>0,23283064365386963e-26*this._bits[0]}_hammersley(e,t){return[e/t,this._radicalInverse_VdC(e)]}_hemisphereSample_uniform(e,t){let i=2*t*Math.PI,r=1-.85*e,s=Math.sqrt(1-r*r);return new rf.P(Math.cos(i)*s,Math.sin(i)*s,r)}_generateHemisphere(){let e;let t=this.samples,i=[],r=0;for(;r{var t,i,r,s;if(this._scene.activeCamera){if(e.setArray3("sampleSphere",this._sampleSphere),e.setFloat("randTextureTiles",32),e.setFloat("samplesFactor",1/this.samples),e.setFloat("totalStrength",this.totalStrength),e.setFloat2("texelSize",1/this._ssaoPostProcess.width,1/this._ssaoPostProcess.height),e.setFloat("radius",this.radius),e.setFloat("maxZ",this.maxZ),e.setFloat("minZAspect",this.minZAspect),e.setFloat("base",this.base),e.setFloat("near",this._scene.activeCamera.minZ),this._scene.activeCamera.mode===sC.V.PERSPECTIVE_CAMERA)e.setMatrix3x3("depthProjection",Th.PERSPECTIVE_DEPTH_PROJECTION),e.setFloat("xViewport",Math.tan(this._scene.activeCamera.fov/2)*this._scene.getEngine().getAspectRatio(this._scene.activeCamera,!0)),e.setFloat("yViewport",Math.tan(this._scene.activeCamera.fov/2));else{let n=this._scene.getEngine().getRenderWidth()/2,a=this._scene.getEngine().getRenderHeight()/2,o=null!==(t=this._scene.activeCamera.orthoLeft)&&void 0!==t?t:-n,l=null!==(i=this._scene.activeCamera.orthoRight)&&void 0!==i?i:n,h=null!==(r=this._scene.activeCamera.orthoBottom)&&void 0!==r?r:-a,u=null!==(s=this._scene.activeCamera.orthoTop)&&void 0!==s?s:a;e.setMatrix3x3("depthProjection",Th.ORTHO_DEPTH_PROJECTION),e.setFloat("xViewport",(l-o)*.5),e.setFloat("yViewport",(u-h)*.5)}e.setMatrix("projection",this._scene.getProjectionMatrix()),this._geometryBufferRenderer?(e.setTexture("depthSampler",this._geometryBufferRenderer.getGBuffer().textures[0]),e.setTexture("normalSampler",this._geometryBufferRenderer.getGBuffer().textures[1])):this._prePassRenderer&&(e.setTexture("depthSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]),e.setTexture("normalSampler",this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)])),e.setTexture("randomSampler",this._randomTexture)}},this._ssaoPostProcess.samples=this.textureSamples,this._forceGeometryBuffer||(this._ssaoPostProcess._prePassEffectConfiguration=new Ta)}_createSSAOCombinePostProcess(e,t){this._ssaoCombinePostProcess=new nz("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,void 0,t),this._ssaoCombinePostProcess.onApply=e=>{let t=this._scene.activeCamera.viewport;e.setVector4("viewport",rf.jp.Vector4[0].copyFromFloats(t.x,t.y,t.width,t.height)),e.setTextureFromPostProcessOutput("originalColor",this._originalColorPostProcess)},this._ssaoCombinePostProcess.samples=this.textureSamples}_createRandomTexture(){let e=new Uint8Array(65536),t=rf.FM.Zero();for(let i=0;inew Th(e._name,t,e._ratio,void 0,e._forceGeometryBuffer,e._textureType),e,t,i)}}Th.ORTHO_DEPTH_PROJECTION=[1,0,0,0,1,0,0,0,1],Th.PERSPECTIVE_DEPTH_PROJECTION=[0,0,0,0,0,0,1,1,1],(0,sx.gn)([(0,rG.qC)()],Th.prototype,"totalStrength",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"maxZ",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"minZAspect",void 0),(0,sx.gn)([(0,rG.qC)("epsilon")],Th.prototype,"_epsilon",void 0),(0,sx.gn)([(0,rG.qC)("samples")],Th.prototype,"_samples",void 0),(0,sx.gn)([(0,rG.qC)("textureSamples")],Th.prototype,"_textureSamples",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"_forceGeometryBuffer",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"_ratio",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"_textureType",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"radius",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"base",void 0),(0,sx.gn)([(0,rG.qC)("bypassBlur")],Th.prototype,"_bypassBlur",void 0),(0,sx.gn)([(0,rG.qC)("expensiveBlur")],Th.prototype,"_expensiveBlur",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"bilateralSamples",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"bilateralSoften",void 0),(0,sx.gn)([(0,rG.qC)()],Th.prototype,"bilateralTolerance",void 0),(0,rg.H)("BABYLON.SSAO2RenderingPipeline",Th);let Tu=`uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSAO +uniform sampler2D randomSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float radius;uniform float area;uniform float fallOff;uniform float base;vec3 normalFromDepth(float depth,vec2 coords) +{vec2 offset1=vec2(0.0,radius);vec2 offset2=vec2(radius,0.0);float depth1=texture2D(textureSampler,coords+offset1).r;float depth2=texture2D(textureSampler,coords+offset2).r;vec3 p1=vec3(offset1,depth1-depth);vec3 p2=vec3(offset2,depth2-depth);vec3 normal=cross(p1,p2);normal.z=-normal.z;return normalize(normal);} +void main() +{vec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);float depth=texture2D(textureSampler,vUV).r;vec3 position=vec3(vUV,depth);vec3 normal=normalFromDepth(depth,vUV);float radiusDepth=radius/depth;float occlusion=0.0;vec3 ray;vec3 hemiRay;float occlusionDepth;float difference;for (int i=0; ithis._originalColorPostProcess,!0)),this.addEffect(new xS(t.getEngine(),this.SSAORenderEffect,()=>this._ssaoPostProcess,!0)),this.addEffect(new xS(t.getEngine(),this.SSAOBlurHRenderEffect,()=>this._blurHPostProcess,!0)),this.addEffect(new xS(t.getEngine(),this.SSAOBlurVRenderEffect,()=>this._blurVPostProcess,!0)),this.addEffect(new xS(t.getEngine(),this.SSAOCombineRenderEffect,()=>this._ssaoCombinePostProcess,!0)),t.postProcessRenderPipelineManager.addPipeline(this),r&&t.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(e,r)}_attachCameras(e,t){for(let i of(super._attachCameras(e,t),this._cameras))this._scene.enableDepthRenderer(i).getDepthMap()}getClassName(){return"SSAORenderingPipeline"}dispose(e=!1){for(let e=0;e{let e=this._blurHPostProcess.width/this._scene.getEngine().getRenderWidth();this._blurHPostProcess.kernel=16*e}),this._blurVPostProcess.onActivateObservable.add(()=>{let e=this._blurVPostProcess.height/this._scene.getEngine().getRenderHeight();this._blurVPostProcess.kernel=16*e})}_rebuild(){this._firstUpdate=!0,super._rebuild()}_createSSAOPostProcess(e){let t=[.5381,.1856,-.4319,.1379,.2486,.443,.3371,.5679,-.0057,-.6999,-.0451,-.0019,.0689,-.1598,-.8547,.056,.0069,-.1843,-.0146,.1402,.0762,.01,-.1924,-.0344,-.3577,-.5301,-.4358,-.3169,.1063,.0158,.0103,-.5869,.0046,-.0897,-.494,.3287,.7119,-.0154,-.0918,-.0533,.0596,-.5411,.0352,-.0631,.546,-.4776,.2847,-.0271];this._ssaoPostProcess=new nz("ssao","ssao",["sampleSphere","samplesFactor","randTextureTiles","totalStrength","radius","area","fallOff","base","range","viewport"],["randomSampler"],e,null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1,"#define SAMPLES 16\n#define SSAO"),this._ssaoPostProcess.externalTextureSamplerBinding=!0,this._ssaoPostProcess.onApply=e=>{this._firstUpdate&&(e.setArray3("sampleSphere",t),e.setFloat("samplesFactor",.0625),e.setFloat("randTextureTiles",4)),e.setFloat("totalStrength",this.totalStrength),e.setFloat("radius",this.radius),e.setFloat("area",this.area),e.setFloat("fallOff",this.fallOff),e.setFloat("base",this.base),e.setTexture("textureSampler",this._scene.enableDepthRenderer(this._scene.activeCamera).getDepthMap()),e.setTexture("randomSampler",this._randomTexture)}}_createSSAOCombinePostProcess(e){this._ssaoCombinePostProcess=new nz("ssaoCombine","ssaoCombine",[],["originalColor","viewport"],e,null,sj.BILINEAR_SAMPLINGMODE,this._scene.getEngine(),!1),this._ssaoCombinePostProcess.onApply=e=>{e.setVector4("viewport",rf.jp.Vector4[0].copyFromFloats(0,0,1,1)),e.setTextureFromPostProcess("originalColor",this._originalColorPostProcess)}}_createRandomTexture(){let e=new Uint8Array(1048576);for(let t=0;t0.0) +hitCoord-=dir;else +hitCoord+=dir;info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;} +projectedCoord=projection*vec4(hitCoord,1.0);projectedCoord.xy/=projectedCoord.w;projectedCoord.xy=0.5*projectedCoord.xy+vec2(0.5);info.coords=vec4(projectedCoord.xy,sampledDepth,1.0);info.color+=texture2D(textureSampler,projectedCoord.xy).rgb;info.color/=float(SMOOTH_STEPS+1);return info;} +/** +* Tests the given world position (hitCoord) according to the given reflection vector (dir) +* until it finds a collision (means that depth is enough close to say "it's the pixel to sample!"). +*/ +ReflectionInfo getReflectionInfo(vec3 dir,vec3 hitCoord) +{ReflectionInfo info;vec4 projectedCoord;float sampledDepth;dir*=stepSize;for(int i=0; i{let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(!r&&!i)return;if(i){let t=i.getTextureIndex(x2.POSITION_TEXTURE_TYPE),r=i.getTextureIndex(x2.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("positionSampler",i.getGBuffer().textures[t]),e.setTexture("reflectivitySampler",i.getGBuffer().textures[r])}else if(r){let t=r.getIndex(1),i=r.getIndex(3),s=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[s]),e.setTexture("positionSampler",r.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",r.getRenderTarget().textures[i])}let s=t.activeCamera;if(!s)return;let n=s.getViewMatrix(!0),a=s.getProjectionMatrix(!0);e.setMatrix("projection",a),e.setMatrix("view",n),e.setFloat("threshold",this.threshold),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("roughnessFactor",this.roughnessFactor)},this._isSceneRightHanded=t.useRightHandedSystem}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get reflectionSamples(){return this._reflectionSamples}set reflectionSamples(e){e!==this._reflectionSamples&&(this._reflectionSamples=e,this._updateEffectDefines())}get smoothSteps(){return this._smoothSteps}set smoothSteps(e){e!==this._smoothSteps&&(this._smoothSteps=e,this._updateEffectDefines())}_updateEffectDefines(){let e=[];(this._geometryBufferRenderer||this._prePassRenderer)&&e.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&e.push("#define ENABLE_SMOOTH_REFLECTIONS"),this._isSceneRightHanded&&e.push("#define RIGHT_HANDED_SCENE"),e.push("#define REFLECTION_SAMPLES "+(this._reflectionSamples>>0)),e.push("#define SMOOTH_STEPS "+(this._smoothSteps>>0)),this.updateEffect(e.join("\n"))}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new T_(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],T_.prototype,"threshold",void 0),(0,sx.gn)([(0,rG.qC)()],T_.prototype,"strength",void 0),(0,sx.gn)([(0,rG.qC)()],T_.prototype,"reflectionSpecularFalloffExponent",void 0),(0,sx.gn)([(0,rG.qC)()],T_.prototype,"step",void 0),(0,sx.gn)([(0,rG.qC)()],T_.prototype,"roughnessFactor",void 0),(0,sx.gn)([(0,rG.qC)()],T_.prototype,"enableSmoothReflections",null),(0,sx.gn)([(0,rG.qC)()],T_.prototype,"reflectionSamples",null),(0,sx.gn)([(0,rG.qC)()],T_.prototype,"smoothSteps",null),(0,rg.H)("BABYLON.ScreenSpaceReflectionPostProcess",T_);let Tf=`uniform sampler2D textureSampler;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +#if defined(PASS_POST_PROCESS) +void main(void) +{vec4 color=texture2D(textureSampler,vUV);gl_FragColor=color;} +#endif +#if defined(DOWN_SAMPLE_X4) +uniform vec2 dsOffsets[16];void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+dsOffsets[0]);average+=texture2D(textureSampler,vUV+dsOffsets[1]);average+=texture2D(textureSampler,vUV+dsOffsets[2]);average+=texture2D(textureSampler,vUV+dsOffsets[3]);average+=texture2D(textureSampler,vUV+dsOffsets[4]);average+=texture2D(textureSampler,vUV+dsOffsets[5]);average+=texture2D(textureSampler,vUV+dsOffsets[6]);average+=texture2D(textureSampler,vUV+dsOffsets[7]);average+=texture2D(textureSampler,vUV+dsOffsets[8]);average+=texture2D(textureSampler,vUV+dsOffsets[9]);average+=texture2D(textureSampler,vUV+dsOffsets[10]);average+=texture2D(textureSampler,vUV+dsOffsets[11]);average+=texture2D(textureSampler,vUV+dsOffsets[12]);average+=texture2D(textureSampler,vUV+dsOffsets[13]);average+=texture2D(textureSampler,vUV+dsOffsets[14]);average+=texture2D(textureSampler,vUV+dsOffsets[15]);average/=16.0;gl_FragColor=average;} +#endif +#if defined(BRIGHT_PASS) +uniform vec2 dsOffsets[4];uniform float brightThreshold;void main(void) +{vec4 average=vec4(0.0,0.0,0.0,0.0);average=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));average+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));average*=0.25;float luminance=length(average.rgb);if (luminanceshadowPixelDepth) +accumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));currentPosition+=stepL;} +accumFog/=NB_STEPS;vec3 color=accumFog*scatteringPower;gl_FragColor=vec4(color*exp(color) ,1.0);} +#endif +#if defined(VLSMERGE) +uniform sampler2D originalSampler;void main(void) +{gl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);} +#endif +#if defined(LUMINANCE) +uniform vec2 lumOffsets[4];void main() +{float average=0.0;vec4 color=vec4(0.0);float maximum=-1e20;vec3 weight=vec3(0.299,0.587,0.114);for (int i=0; i<4; i++) +{color=texture2D(textureSampler,vUV+ lumOffsets[i]);float GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33)); +#ifdef WEIGHTED_AVERAGE +float GreyValue=dot(color.rgb,weight); +#endif +#ifdef BRIGHTNESS +float GreyValue=max(color.r,max(color.g,color.b)); +#endif +#ifdef HSL_COMPONENT +float GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b))); +#endif +#ifdef MAGNITUDE +float GreyValue=length(color.rgb); +#endif +maximum=max(maximum,GreyValue);average+=(0.25*log(1e-5+GreyValue));} +average=exp(average);gl_FragColor=vec4(average,maximum,0.0,1.0);} +#endif +#if defined(LUMINANCE_DOWN_SAMPLE) +uniform vec2 dsOffsets[9];uniform float halfDestPixelSize; +#ifdef FINAL_DOWN_SAMPLER +#include +#endif +void main() +{vec4 color=vec4(0.0);float average=0.0;for (int i=0; i<9; i++) +{color=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);average+=color.r;} +average/=9.0; +#ifdef FINAL_DOWN_SAMPLER +gl_FragColor=pack(average); +#else +gl_FragColor=vec4(average,average,0.0,1.0); +#endif +} +#endif +#if defined(HDR) +uniform sampler2D textureAdderSampler;uniform float averageLuminance;void main() +{vec4 color=texture2D(textureAdderSampler,vUV); +#ifndef AUTO_EXPOSURE +vec4 adjustedColor=color/averageLuminance;color=adjustedColor;color.a=1.0; +#endif +gl_FragColor=color;} +#endif +#if defined(LENS_FLARE) +#define GHOSTS 3 +uniform sampler2D lensColorSampler;uniform float strength;uniform float ghostDispersal;uniform float haloWidth;uniform vec2 resolution;uniform float distortionStrength;float hash(vec2 p) +{float h=dot(p,vec2(127.1,311.7));return -1.0+2.0*fract(sin(h)*43758.5453123);} +float noise(in vec2 p) +{vec2 i=floor(p);vec2 f=fract(p);vec2 u=f*f*(3.0-2.0*f);return mix(mix(hash(i+vec2(0.0,0.0)), +hash(i+vec2(1.0,0.0)),u.x), +mix(hash(i+vec2(0.0,1.0)), +hash(i+vec2(1.0,1.0)),u.x),u.y);} +float fbm(vec2 p) +{float f=0.0;f+=0.5000*noise(p); p*=2.02;f+=0.2500*noise(p); p*=2.03;f+=0.1250*noise(p); p*=2.01;f+=0.0625*noise(p); p*=2.04;f/=0.9375;return f;} +vec3 pattern(vec2 uv) +{vec2 p=-1.0+2.0*uv;float p2=dot(p,p);float f=fbm(vec2(15.0*p2))/2.0;float r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));float g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));float b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));return (1.0-f)*vec3(r,g,b);} +float luminance(vec3 color) +{return dot(color.rgb,vec3(0.2126,0.7152,0.0722));} +vec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion) +{return vec4( +texture2D(tex,texcoord+direction*distortion.r).r, +texture2D(tex,texcoord+direction*distortion.g).g, +texture2D(tex,texcoord+direction*distortion.b).b, +1.0 +);} +void main(void) +{vec2 uv=-vUV+vec2(1.0);vec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;vec2 texelSize=1.0/resolution;vec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);vec4 result=vec4(0.0);float ghostIndice=1.0;for (int i=0; i=nSamples) +break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=texture2D(textureSampler,offset1);} +gl_FragColor=result/float(nSamples);} +#endif +`;nw.v.ShadersStore.standardPixelShader=Tf;class Tm extends Te{get exposure(){return this._fixedExposure}set exposure(e){this._fixedExposure=e,this._currentExposure=e}get hdrAutoExposure(){return this._hdrAutoExposure}set hdrAutoExposure(e){if(this._hdrAutoExposure=e,this.hdrPostProcess){let t=["#define HDR"];e&&t.push("#define AUTO_EXPOSURE"),this.hdrPostProcess.updateEffect(t.join("\n"))}}get motionStrength(){return this._motionStrength}set motionStrength(e){this._motionStrength=e,this._isObjectBasedMotionBlur&&this.motionBlurPostProcess&&(this.motionBlurPostProcess.motionStrength=e)}get objectBasedMotionBlur(){return this._isObjectBasedMotionBlur}set objectBasedMotionBlur(e){let t=this._isObjectBasedMotionBlur!==e;this._isObjectBasedMotionBlur=e,t&&this._buildPipeline()}get BloomEnabled(){return this._bloomEnabled}set BloomEnabled(e){this._bloomEnabled!==e&&(this._bloomEnabled=e,this._buildPipeline())}get DepthOfFieldEnabled(){return this._depthOfFieldEnabled}set DepthOfFieldEnabled(e){this._depthOfFieldEnabled!==e&&(this._depthOfFieldEnabled=e,this._buildPipeline())}get LensFlareEnabled(){return this._lensFlareEnabled}set LensFlareEnabled(e){this._lensFlareEnabled!==e&&(this._lensFlareEnabled=e,this._buildPipeline())}get HDREnabled(){return this._hdrEnabled}set HDREnabled(e){this._hdrEnabled!==e&&(this._hdrEnabled=e,this._buildPipeline())}get VLSEnabled(){return this._vlsEnabled}set VLSEnabled(e){if(this._vlsEnabled!==e){if(e&&!this._scene.enableGeometryBufferRenderer()){rb.Y.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");return}this._vlsEnabled=e,this._buildPipeline()}}get MotionBlurEnabled(){return this._motionBlurEnabled}set MotionBlurEnabled(e){this._motionBlurEnabled!==e&&(this._motionBlurEnabled=e,this._buildPipeline())}get fxaaEnabled(){return this._fxaaEnabled}set fxaaEnabled(e){this._fxaaEnabled!==e&&(this._fxaaEnabled=e,this._buildPipeline())}get screenSpaceReflectionsEnabled(){return this._screenSpaceReflectionsEnabled}set screenSpaceReflectionsEnabled(e){this._screenSpaceReflectionsEnabled!==e&&(this._screenSpaceReflectionsEnabled=e,this._buildPipeline())}get volumetricLightStepsCount(){return this._volumetricLightStepsCount}set volumetricLightStepsCount(e){this.volumetricLightPostProcess&&this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS "+e.toFixed(1)),this._volumetricLightStepsCount=e}get motionBlurSamples(){return this._motionBlurSamples}set motionBlurSamples(e){this.motionBlurPostProcess&&(this._isObjectBasedMotionBlur?this.motionBlurPostProcess.motionBlurSamples=e:this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+e.toFixed(1))),this._motionBlurSamples=e}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}constructor(e,t,i,r=null,s){super(t.getEngine(),e),this.downSampleX4PostProcess=null,this.brightPassPostProcess=null,this.blurHPostProcesses=[],this.blurVPostProcesses=[],this.textureAdderPostProcess=null,this.volumetricLightPostProcess=null,this.volumetricLightSmoothXPostProcess=null,this.volumetricLightSmoothYPostProcess=null,this.volumetricLightMergePostProces=null,this.volumetricLightFinalPostProcess=null,this.luminancePostProcess=null,this.luminanceDownSamplePostProcesses=[],this.hdrPostProcess=null,this.textureAdderFinalPostProcess=null,this.lensFlareFinalPostProcess=null,this.hdrFinalPostProcess=null,this.lensFlarePostProcess=null,this.lensFlareComposePostProcess=null,this.motionBlurPostProcess=null,this.depthOfFieldPostProcess=null,this.fxaaPostProcess=null,this.screenSpaceReflectionPostProcess=null,this.brightThreshold=1,this.blurWidth=512,this.horizontalBlur=!1,this.lensTexture=null,this.volumetricLightCoefficient=.2,this.volumetricLightPower=4,this.volumetricLightBlurScale=64,this.sourceLight=null,this.hdrMinimumLuminance=1,this.hdrDecreaseRate=.5,this.hdrIncreaseRate=.5,this.lensColorTexture=null,this.lensFlareStrength=20,this.lensFlareGhostDispersal=1.4,this.lensFlareHaloWidth=.7,this.lensFlareDistortionStrength=16,this.lensFlareBlurWidth=512,this.lensStarTexture=null,this.lensFlareDirtTexture=null,this.depthOfFieldDistance=10,this.depthOfFieldBlurWidth=64,this.animations=[],this._currentDepthOfFieldSource=null,this._fixedExposure=1,this._currentExposure=1,this._hdrAutoExposure=!1,this._hdrCurrentLuminance=1,this._motionStrength=1,this._isObjectBasedMotionBlur=!1,this._camerasToBeAttached=[],this._bloomEnabled=!1,this._depthOfFieldEnabled=!1,this._vlsEnabled=!1,this._lensFlareEnabled=!1,this._hdrEnabled=!1,this._motionBlurEnabled=!1,this._fxaaEnabled=!1,this._screenSpaceReflectionsEnabled=!1,this._motionBlurSamples=64,this._volumetricLightStepsCount=50,this._samples=1,this._cameras=s||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._basePostProcess=r,this._ratio=i,this._floatTextureType=t.getEngine().getCaps().textureFloatRender?1:2,t.postProcessRenderPipelineManager.addPipeline(this),this._buildPipeline()}_buildPipeline(){let e=this._ratio,t=this._scene;this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._screenSpaceReflectionsEnabled&&(this.screenSpaceReflectionPostProcess=new T_("HDRPass",t,e,null,sj.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,this._floatTextureType),this.screenSpaceReflectionPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.screenSpaceReflectionPostProcess}),this.addEffect(new xS(t.getEngine(),"HDRScreenSpaceReflections",()=>this.screenSpaceReflectionPostProcess,!0))),this._basePostProcess?this.originalPostProcess=this._basePostProcess:this.originalPostProcess=new nz("HDRPass","standard",[],[],e,null,sj.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",this._floatTextureType),this.originalPostProcess.autoClear=!this.screenSpaceReflectionPostProcess,this.originalPostProcess.onApplyObservable.add(()=>{this._currentDepthOfFieldSource=this.originalPostProcess}),this.addEffect(new xS(t.getEngine(),"HDRPassPostProcess",()=>this.originalPostProcess,!0)),this._bloomEnabled&&(this._createDownSampleX4PostProcess(t,e/4),this._createBrightPassPostProcess(t,e/4),this._createBlurPostProcesses(t,e/4,1),this._createTextureAdderPostProcess(t,e),this.textureAdderFinalPostProcess=new nz("HDRDepthOfFieldSource","standard",[],[],e,null,sj.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new xS(t.getEngine(),"HDRBaseDepthOfFieldSource",()=>this.textureAdderFinalPostProcess,!0))),this._vlsEnabled&&(this._createVolumetricLightPostProcess(t,e),this.volumetricLightFinalPostProcess=new nz("HDRVLSFinal","standard",[],[],e,null,sj.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new xS(t.getEngine(),"HDRVLSFinal",()=>this.volumetricLightFinalPostProcess,!0))),this._lensFlareEnabled&&(this._createLensFlarePostProcess(t,e),this.lensFlareFinalPostProcess=new nz("HDRPostLensFlareDepthOfFieldSource","standard",[],[],e,null,sj.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new xS(t.getEngine(),"HDRPostLensFlareDepthOfFieldSource",()=>this.lensFlareFinalPostProcess,!0))),this._hdrEnabled&&(this._createLuminancePostProcesses(t,this._floatTextureType),this._createHdrPostProcess(t,e),this.hdrFinalPostProcess=new nz("HDRPostHDReDepthOfFieldSource","standard",[],[],e,null,sj.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,"#define PASS_POST_PROCESS",0),this.addEffect(new xS(t.getEngine(),"HDRPostHDReDepthOfFieldSource",()=>this.hdrFinalPostProcess,!0))),this._depthOfFieldEnabled&&(this._createBlurPostProcesses(t,e/2,3,"depthOfFieldBlurWidth"),this._createDepthOfFieldPostProcess(t,e)),this._motionBlurEnabled&&this._createMotionBlurPostProcess(t,e),this._fxaaEnabled&&(this.fxaaPostProcess=new xX("fxaa",1,null,sj.BILINEAR_SAMPLINGMODE,t.getEngine(),!1,0),this.addEffect(new xS(t.getEngine(),"HDRFxaa",()=>this.fxaaPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras),!this._enableMSAAOnFirstPostProcess(this._samples)&&this._samples>1&&rb.Y.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0")}_createDownSampleX4PostProcess(e,t){let i=Array(32);this.downSampleX4PostProcess=new nz("HDRDownSampleX4","standard",["dsOffsets"],[],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DOWN_SAMPLE_X4",this._floatTextureType),this.downSampleX4PostProcess.onApply=e=>{let t=0,r=this.downSampleX4PostProcess.width,s=this.downSampleX4PostProcess.height;for(let e=-2;e<2;e++)for(let n=-2;n<2;n++)i[t]=1/r*(e+.5),i[t+1]=1/s*(n+.5),t+=2;e.setArray2("dsOffsets",i)},this.addEffect(new xS(e.getEngine(),"HDRDownSampleX4",()=>this.downSampleX4PostProcess,!0))}_createBrightPassPostProcess(e,t){let i=Array(8);this.brightPassPostProcess=new nz("HDRBrightPass","standard",["dsOffsets","brightThreshold"],[],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define BRIGHT_PASS",this._floatTextureType),this.brightPassPostProcess.onApply=e=>{let t=1/this.brightPassPostProcess.width,r=1/this.brightPassPostProcess.height;i[0]=-.5*t,i[1]=.5*r,i[2]=.5*t,i[3]=.5*r,i[4]=-.5*t,i[5]=-.5*r,i[6]=.5*t,i[7]=-.5*r,e.setArray2("dsOffsets",i),e.setFloat("brightThreshold",this.brightThreshold)},this.addEffect(new xS(e.getEngine(),"HDRBrightPass",()=>this.brightPassPostProcess,!0))}_createBlurPostProcesses(e,t,i,r="blurWidth"){let s=e.getEngine(),n=new dP("HDRBlurH_"+i,new rf.FM(1,0),this[r],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType),a=new dP("HDRBlurV_"+i,new rf.FM(0,1),this[r],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,this._floatTextureType);n.onActivateObservable.add(()=>{let e=n.width/s.getRenderWidth();n.kernel=this[r]*e}),a.onActivateObservable.add(()=>{let e=a.height/s.getRenderHeight();a.kernel=this.horizontalBlur?64*e:this[r]*e}),this.addEffect(new xS(e.getEngine(),"HDRBlurH"+i,()=>n,!0)),this.addEffect(new xS(e.getEngine(),"HDRBlurV"+i,()=>a,!0)),this.blurHPostProcesses.push(n),this.blurVPostProcesses.push(a)}_createTextureAdderPostProcess(e,t){this.textureAdderPostProcess=new nz("HDRTextureAdder","standard",["exposure"],["otherSampler","lensSampler"],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define TEXTURE_ADDER",this._floatTextureType),this.textureAdderPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._vlsEnabled?this._currentDepthOfFieldSource:this.originalPostProcess),e.setTexture("lensSampler",this.lensTexture),e.setFloat("exposure",this._currentExposure),this._currentDepthOfFieldSource=this.textureAdderFinalPostProcess},this.addEffect(new xS(e.getEngine(),"HDRTextureAdder",()=>this.textureAdderPostProcess,!0))}_createVolumetricLightPostProcess(e,t){let i=e.enableGeometryBufferRenderer();i.enablePosition=!0;let r=i.getGBuffer();this.volumetricLightPostProcess=new nz("HDRVLS","standard",["shadowViewProjection","cameraPosition","sunDirection","sunColor","scatteringCoefficient","scatteringPower","depthValues"],["shadowMapSampler","positionSampler"],t/8,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLS\n#define NB_STEPS "+this._volumetricLightStepsCount.toFixed(1));let s=rf.FM.Zero();this.volumetricLightPostProcess.onApply=e=>{if(this.sourceLight&&this.sourceLight.getShadowGenerator()&&this._scene.activeCamera){let t=this.sourceLight.getShadowGenerator();e.setTexture("shadowMapSampler",t.getShadowMap()),e.setTexture("positionSampler",r.textures[2]),e.setColor3("sunColor",this.sourceLight.diffuse),e.setVector3("sunDirection",this.sourceLight.getShadowDirection()),e.setVector3("cameraPosition",this._scene.activeCamera.globalPosition),e.setMatrix("shadowViewProjection",t.getTransformMatrix()),e.setFloat("scatteringCoefficient",this.volumetricLightCoefficient),e.setFloat("scatteringPower",this.volumetricLightPower),s.x=this.sourceLight.getDepthMinZ(this._scene.activeCamera),s.y=this.sourceLight.getDepthMaxZ(this._scene.activeCamera),e.setVector2("depthValues",s)}},this.addEffect(new xS(e.getEngine(),"HDRVLS",()=>this.volumetricLightPostProcess,!0)),this._createBlurPostProcesses(e,t/4,0,"volumetricLightBlurScale"),this.volumetricLightMergePostProces=new nz("HDRVLSMerge","standard",[],["originalSampler"],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define VLSMERGE"),this.volumetricLightMergePostProces.onApply=e=>{e.setTextureFromPostProcess("originalSampler",this._bloomEnabled?this.textureAdderFinalPostProcess:this.originalPostProcess),this._currentDepthOfFieldSource=this.volumetricLightFinalPostProcess},this.addEffect(new xS(e.getEngine(),"HDRVLSMerge",()=>this.volumetricLightMergePostProces,!0))}_createLuminancePostProcesses(e,t){let i=Math.pow(3,Tm.LuminanceSteps);this.luminancePostProcess=new nz("HDRLuminance","standard",["lumOffsets"],[],{width:i,height:i},null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LUMINANCE",t);let r=[];this.luminancePostProcess.onApply=e=>{let t=1/this.luminancePostProcess.width,i=1/this.luminancePostProcess.height;r[0]=-.5*t,r[1]=.5*i,r[2]=.5*t,r[3]=.5*i,r[4]=-.5*t,r[5]=-.5*i,r[6]=.5*t,r[7]=-.5*i,e.setArray2("lumOffsets",r)},this.addEffect(new xS(e.getEngine(),"HDRLuminance",()=>this.luminancePostProcess,!0));for(let r=Tm.LuminanceSteps-1;r>=0;r--){i=Math.pow(3,r);let s="#define LUMINANCE_DOWN_SAMPLE\n";0===r&&(s+="#define FINAL_DOWN_SAMPLER");let n=new nz("HDRLuminanceDownSample"+r,"standard",["dsOffsets","halfDestPixelSize"],[],{width:i,height:i},null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,s,t);this.luminanceDownSamplePostProcesses.push(n)}let s=this.luminancePostProcess;this.luminanceDownSamplePostProcesses.forEach((t,i)=>{let r=Array(18);t.onApply=e=>{if(!s)return;let n=0;for(let e=-1;e<2;e++)for(let t=-1;t<2;t++)r[n]=e/s.width,r[n+1]=t/s.height,n+=2;e.setArray2("dsOffsets",r),e.setFloat("halfDestPixelSize",.5/s.width),s=i===this.luminanceDownSamplePostProcesses.length-1?this.luminancePostProcess:t},i===this.luminanceDownSamplePostProcesses.length-1&&(t.onAfterRender=()=>{let t=e.getEngine().readPixels(0,0,1,1),i=new rf.Lt(6030862941101084e-23,1/65025,1/255,1);t.then(e=>{let t=new Uint8Array(e.buffer);this._hdrCurrentLuminance=(t[0]*i.x+t[1]*i.y+t[2]*i.z+t[3]*i.w)/100})}),this.addEffect(new xS(e.getEngine(),"HDRLuminanceDownSample"+i,()=>t,!0))})}_createHdrPostProcess(e,t){let i=["#define HDR"];this._hdrAutoExposure&&i.push("#define AUTO_EXPOSURE"),this.hdrPostProcess=new nz("HDR","standard",["averageLuminance"],["textureAdderSampler"],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,i.join("\n"),0);let r=1,s=0,n=0;this.hdrPostProcess.onApply=t=>{if(t.setTextureFromPostProcess("textureAdderSampler",this._currentDepthOfFieldSource),s+=e.getEngine().getDeltaTime(),r<0)r=this._hdrCurrentLuminance;else{let e=(n-s)/1e3;this._hdrCurrentLuminancer-this.hdrIncreaseRate*e?r-=this.hdrIncreaseRate*e:r=this._hdrCurrentLuminance}this.hdrAutoExposure?this._currentExposure=this._fixedExposure/r:(r=rk.R.Clamp(r,this.hdrMinimumLuminance,1e20),t.setFloat("averageLuminance",r)),n=s,this._currentDepthOfFieldSource=this.hdrFinalPostProcess},this.addEffect(new xS(e.getEngine(),"HDR",()=>this.hdrPostProcess,!0))}_createLensFlarePostProcess(e,t){this.lensFlarePostProcess=new nz("HDRLensFlare","standard",["strength","ghostDispersal","haloWidth","resolution","distortionStrength"],["lensColorSampler"],t/2,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE",0),this.addEffect(new xS(e.getEngine(),"HDRLensFlare",()=>this.lensFlarePostProcess,!0)),this._createBlurPostProcesses(e,t/4,2,"lensFlareBlurWidth"),this.lensFlareComposePostProcess=new nz("HDRLensFlareCompose","standard",["lensStarMatrix"],["otherSampler","lensDirtSampler","lensStarSampler"],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define LENS_FLARE_COMPOSE",0),this.addEffect(new xS(e.getEngine(),"HDRLensFlareCompose",()=>this.lensFlareComposePostProcess,!0));let i=new rf.FM(0,0);this.lensFlarePostProcess.externalTextureSamplerBinding=!0,this.lensFlarePostProcess.onApply=e=>{e.setTextureFromPostProcess("textureSampler",this._bloomEnabled?this.blurHPostProcesses[0]:this.originalPostProcess),e.setTexture("lensColorSampler",this.lensColorTexture),e.setFloat("strength",this.lensFlareStrength),e.setFloat("ghostDispersal",this.lensFlareGhostDispersal),e.setFloat("haloWidth",this.lensFlareHaloWidth),i.x=this.lensFlarePostProcess.width,i.y=this.lensFlarePostProcess.height,e.setVector2("resolution",i),e.setFloat("distortionStrength",this.lensFlareDistortionStrength)};let r=rf.y3.FromValues(2,0,-1,0,0,2,-1,0,0,0,1,0,0,0,0,1),s=rf.y3.FromValues(.5,0,.5,0,0,.5,.5,0,0,0,1,0,0,0,0,1);this.lensFlareComposePostProcess.onApply=e=>{if(!this._scene.activeCamera)return;e.setTextureFromPostProcess("otherSampler",this.lensFlarePostProcess),e.setTexture("lensDirtSampler",this.lensFlareDirtTexture),e.setTexture("lensStarSampler",this.lensStarTexture);let t=this._scene.activeCamera.getViewMatrix().getRow(0),i=this._scene.activeCamera.getViewMatrix().getRow(2),n=rf.P.Dot(t.toVector3(),new rf.P(1,0,0))+rf.P.Dot(i.toVector3(),new rf.P(0,0,1));n*=4;let a=rf.y3.FromValues(.5*Math.cos(n),-Math.sin(n),0,0,Math.sin(n),.5*Math.cos(n),0,0,0,0,1,0,0,0,0,1),o=s.multiply(a).multiply(r);e.setMatrix("lensStarMatrix",o),this._currentDepthOfFieldSource=this.lensFlareFinalPostProcess}}_createDepthOfFieldPostProcess(e,t){this.depthOfFieldPostProcess=new nz("HDRDepthOfField","standard",["distance"],["otherSampler","depthSampler"],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define DEPTH_OF_FIELD",0),this.depthOfFieldPostProcess.onApply=e=>{e.setTextureFromPostProcess("otherSampler",this._currentDepthOfFieldSource),e.setTexture("depthSampler",this._getDepthTexture()),e.setFloat("distance",this.depthOfFieldDistance)},this.addEffect(new xS(e.getEngine(),"HDRDepthOfField",()=>this.depthOfFieldPostProcess,!0))}_createMotionBlurPostProcess(e,t){if(this._isObjectBasedMotionBlur){let i=new x6("HDRMotionBlur",e,t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,0);i.motionStrength=this.motionStrength,i.motionBlurSamples=this.motionBlurSamples,this.motionBlurPostProcess=i}else{this.motionBlurPostProcess=new nz("HDRMotionBlur","standard",["inverseViewProjection","prevViewProjection","screenSize","motionScale","motionStrength"],["depthSampler"],t,null,sj.BILINEAR_SAMPLINGMODE,e.getEngine(),!1,"#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES "+this.motionBlurSamples.toFixed(1),0);let i=0,r=rf.y3.Identity(),s=rf.y3.Identity(),n=rf.y3.Identity(),a=rf.FM.Zero();this.motionBlurPostProcess.onApply=t=>{(n=e.getProjectionMatrix().multiply(e.getViewMatrix())).invertToRef(s),t.setMatrix("inverseViewProjection",s),t.setMatrix("prevViewProjection",r),r=n,a.x=this.motionBlurPostProcess.width,a.y=this.motionBlurPostProcess.height,t.setVector2("screenSize",a),i=e.getEngine().getFps()/60,t.setFloat("motionScale",i),t.setFloat("motionStrength",this.motionStrength),t.setTexture("depthSampler",this._getDepthTexture())}}this.addEffect(new xS(e.getEngine(),"HDRMotionBlur",()=>this.motionBlurPostProcess,!0))}_getDepthTexture(){return this._scene.getEngine().getCaps().drawBuffersExtension?this._scene.enableGeometryBufferRenderer().getGBuffer().textures[0]:this._scene.enableDepthRenderer().getDepthMap()}_disposePostProcesses(){for(let e=0;enew Tm(e._name,t,e._ratio),e,t,i);return e.sourceLightId&&(r.sourceLight=t.getLightById(e.sourceLightId)),e.screenSpaceReflectionPostProcess&&rG.p4.Parse(()=>r.screenSpaceReflectionPostProcess,e.screenSpaceReflectionPostProcess,t,i),r}}Tm.LuminanceSteps=6,(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"brightThreshold",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"blurWidth",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"horizontalBlur",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"exposure",null),(0,sx.gn)([(0,rG.oU)("lensTexture")],Tm.prototype,"lensTexture",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"volumetricLightCoefficient",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"volumetricLightPower",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"volumetricLightBlurScale",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"hdrMinimumLuminance",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"hdrDecreaseRate",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"hdrIncreaseRate",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"hdrAutoExposure",null),(0,sx.gn)([(0,rG.oU)("lensColorTexture")],Tm.prototype,"lensColorTexture",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"lensFlareStrength",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"lensFlareGhostDispersal",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"lensFlareHaloWidth",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"lensFlareDistortionStrength",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"lensFlareBlurWidth",void 0),(0,sx.gn)([(0,rG.oU)("lensStarTexture")],Tm.prototype,"lensStarTexture",void 0),(0,sx.gn)([(0,rG.oU)("lensFlareDirtTexture")],Tm.prototype,"lensFlareDirtTexture",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"depthOfFieldDistance",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"depthOfFieldBlurWidth",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"motionStrength",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"objectBasedMotionBlur",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"_ratio",void 0),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"BloomEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"DepthOfFieldEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"LensFlareEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"HDREnabled",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"VLSEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"MotionBlurEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"fxaaEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"screenSpaceReflectionsEnabled",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"volumetricLightStepsCount",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"motionBlurSamples",null),(0,sx.gn)([(0,rG.qC)()],Tm.prototype,"samples",null),(0,rg.H)("BABYLON.StandardRenderingPipeline",Tm);class Tg{constructor(){this.enabled=!1,this.name="screenSpaceReflections2",this.texturesRequired=[6,3,5]}}let Tv=`float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } +/** +param csOrigin Camera-space ray origin,which must be +within the view volume and must have z>0.01 and project within the valid screen rectangle +param csDirection Unit length camera-space ray direction +param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates +(**not** [-1,+1] normalized device coordinates). +param csZBuffer The camera-space Z buffer +param csZBufferSize Dimensions of csZBuffer +param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer +param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value +for clipping rays headed towards the camera +param stride Step in horizontal or vertical pixels between samples. This is a float +because integer math is slow on GPUs,but should be set to an integer>=1 +param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units +to conceal banding artifacts,plus the stride ray offset. +param maxSteps Maximum number of iterations. Higher gives better images but may be slow +param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss +param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. +1 is a reasonable value,depending on the scene you may need to set this value to 2 +param hitPixel Pixel coordinates of the first intersection with the scene +param numIterations number of iterations performed +param csHitPoint Camera space location of the ray hit +*/ +#define inline +bool traceScreenSpaceRay1( +vec3 csOrigin, +vec3 csDirection, +mat4 projectToPixelMatrix, +sampler2D csZBuffer, +vec2 csZBufferSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +sampler2D csZBackBuffer, +float csZBackSizeFactor, +#endif +float csZThickness, +float nearPlaneZ, +float stride, +float jitterFraction, +float maxSteps, +float maxRayTraceDistance, +float selfCollisionNumSkip, +out vec2 startPixel, +out vec2 hitPixel, +out vec3 csHitPoint, +out float numIterations +#ifdef SSRAYTRACE_DEBUG +,out vec3 debugColor +#endif +) +{ +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; +#else +float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);} +if ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));} +P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); +#endif +P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { +float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} +sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); +#else +hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); +#endif +#else +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); +#else +hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); +#endif +#endif +} +pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} +#ifdef SSRAYTRACE_ENABLE_REFINEMENT +if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || +(refinementStepCount<=stride*1.4) && +(rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} +#endif +return hit;} +/** +texCoord: in the [0,1] range +depth: depth in view space (range [znear,zfar]]) +*/ +vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +ndc.z=-projection[2].z-projection[3].z/depth; +#else +ndc.z=projection[2].z+projection[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +`;nw.v.IncludesShadersStore.screenSpaceRayTrace=Tv;let Tx=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV; +#ifdef SSR_SUPPORTED +uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +uniform sampler2D backDepthSampler;uniform float backSizeFactor; +#endif +#ifdef SSR_USE_ENVIRONMENT_CUBE +uniform samplerCube envCubeSampler; +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; +#endif +#endif +uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; +#include +#include +#include +vec3 hash(vec3 a) +{a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} +float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; +#ifdef SSR_ATTENUATE_SCREEN_BORDERS +vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE +attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); +#endif +#ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS +attenuation*=1.0-(numIterations/maxSteps); +#endif +#ifdef SSR_ATTENUATE_BACKFACE_REFLECTION +vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; +#endif +return attenuation;} +#endif +void main() +{ +#ifdef SSR_SUPPORTED +vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=TEXTUREFUNC(reflectivitySampler,vUV,0.0); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { +#ifdef SSR_USE_BLUR +gl_FragColor=vec4(0.); +#else +gl_FragColor=colorFull; +#endif +return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; +#ifdef SSR_DECODE_NORMAL +csNormal=csNormal*2.0-1.0; +#endif +#ifdef SSR_NORMAL_IS_IN_WORLDSPACE +csNormal=(view*vec4(csNormal,0.0)).xyz; +#endif +float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 csReflectedVector=reflect(csViewDirection,csNormal); +#ifdef SSR_USE_ENVIRONMENT_CUBE +vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); +#ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC +vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); +#endif +#ifdef SSR_INVERTCUBICMAP +wReflectedVector.y*=-1.0; +#endif +#ifdef SSRAYTRACE_RIGHT_HANDED_SCENE +wReflectedVector.z*=-1.0; +#endif +vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; +#ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE +envColor=toLinearSpace(envColor); +#endif +#else +vec3 envColor=color; +#endif +float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; +#ifdef SSRAYTRACE_DEBUG +vec3 debugColor; +#endif +#ifdef SSR_ATTENUATE_FACING_CAMERA +reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); +#endif +if (reflectionAttenuation>0.0) { +#ifdef SSR_USE_BLUR +vec3 jitt=vec3(0.); +#else +float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; +#endif +vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); +rayHasHit=traceScreenSpaceRay1( +csPosition, +normalize(csReflectedVector+jitt), +projectionPixel, +depthSampler, +texSize, +#ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER +backDepthSampler, +backSizeFactor, +#endif +thickness, +nearPlaneZ, +stepSize, +jitter, +maxSteps, +maxDistance, +selfCollisionNumSkip, +startPixel, +hitPixel, +hitPoint, +numIterations +#ifdef SSRAYTRACE_DEBUG +,debugColor +#endif +);} +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=vec4(debugColor,1.);return; +#endif +vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; +#ifdef SSR_INPUT_IS_GAMMA_SPACE +reflectedColor=toLinearSpace(reflectedColor); +#endif +reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} +#ifndef SSR_BLEND_WITH_FRESNEL +SSR*=fresnel; +#endif +#ifdef SSR_USE_BLUR +float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; +float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} +gl_FragColor=vec4(SSR,blur_radius/255.0); +#else +#ifdef SSR_BLEND_WITH_FRESNEL +vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,colorFull.a); +#endif +#else +gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); +#endif +} +`;nw.v.ShadersStore.screenSpaceReflection2PixelShader=Tx;let TT=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) +#else +#define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) +#endif +uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) +{vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} +void main() +{vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} +float blurRadius=colorFull.a*255.0; +vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} +`;nw.v.ShadersStore.screenSpaceReflection2BlurPixelShader=TT;let TS=`uniform sampler2D textureSampler; +uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; +#include +#ifdef SSR_BLEND_WITH_FRESNEL +#include +#include +uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform sampler2D normalSampler;uniform sampler2D depthSampler; +#endif +void main() +{ +#ifdef SSRAYTRACE_DEBUG +gl_FragColor=texture2D(textureSampler,vUV); +#else +vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); +#ifndef SSR_DISABLE_REFLECTIVITY_TEST +if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} +#endif +#ifdef SSR_INPUT_IS_GAMMA_SPACE +color=toLinearSpace(color); +#endif +#ifdef SSR_BLEND_WITH_FRESNEL +vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz;float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r;vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#else +vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); +#endif +vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); +#ifdef SSR_OUTPUT_IS_GAMMA_SPACE +finalColor=toGammaSpace(finalColor); +#endif +gl_FragColor=vec4(finalColor,color.a); +#endif +} +`;nw.v.ShadersStore.screenSpaceReflection2BlurCombinerPixelShader=TS;let TE=rf.y3.Compose(new rf.P(.5,.5,.5),rf._f.Identity(),new rf.P(.5,.5,.5)),TC=rf.y3.Compose(new rf.P(.5,.5,1),rf._f.Identity(),new rf.P(.5,.5,0));class Tb extends Te{set samples(e){this._samples!==e&&(this._samples=e,this._buildPipeline())}get samples(){return this._samples}get reflectivityThreshold(){return this._reflectivityThreshold}set reflectivityThreshold(e){e!==this._reflectivityThreshold&&(0===e&&0!==this._reflectivityThreshold||0!==e&&0===this._reflectivityThreshold?(this._reflectivityThreshold=e,this._buildPipeline()):this._reflectivityThreshold=e)}get ssrDownsample(){return this._ssrDownsample}set ssrDownsample(e){e!==this._ssrDownsample&&(this._ssrDownsample=e,this._buildPipeline())}get blurDispersionStrength(){return this._blurDispersionStrength}set blurDispersionStrength(e){if(e===this._blurDispersionStrength)return;let t=0===e&&0!==this._blurDispersionStrength||0!==e&&0===this._blurDispersionStrength;this._blurDispersionStrength=e,t&&this._buildPipeline()}_useBlur(){return this._blurDispersionStrength>0}get blurDownsample(){return this._blurDownsample}set blurDownsample(e){e!==this._blurDownsample&&(this._blurDownsample=e,this._buildPipeline())}get enableSmoothReflections(){return this._enableSmoothReflections}set enableSmoothReflections(e){e!==this._enableSmoothReflections&&(this._enableSmoothReflections=e,this._updateEffectDefines())}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e,this._updateEffectDefines()}get environmentTextureIsProbe(){return this._environmentTextureIsProbe}set environmentTextureIsProbe(e){this._environmentTextureIsProbe=e,this._updateEffectDefines()}get attenuateScreenBorders(){return this._attenuateScreenBorders}set attenuateScreenBorders(e){this._attenuateScreenBorders!==e&&(this._attenuateScreenBorders=e,this._updateEffectDefines())}get attenuateIntersectionDistance(){return this._attenuateIntersectionDistance}set attenuateIntersectionDistance(e){this._attenuateIntersectionDistance!==e&&(this._attenuateIntersectionDistance=e,this._updateEffectDefines())}get attenuateIntersectionIterations(){return this._attenuateIntersectionIterations}set attenuateIntersectionIterations(e){this._attenuateIntersectionIterations!==e&&(this._attenuateIntersectionIterations=e,this._updateEffectDefines())}get attenuateFacingCamera(){return this._attenuateFacingCamera}set attenuateFacingCamera(e){this._attenuateFacingCamera!==e&&(this._attenuateFacingCamera=e,this._updateEffectDefines())}get attenuateBackfaceReflection(){return this._attenuateBackfaceReflection}set attenuateBackfaceReflection(e){this._attenuateBackfaceReflection!==e&&(this._attenuateBackfaceReflection=e,this._updateEffectDefines())}get clipToFrustum(){return this._clipToFrustum}set clipToFrustum(e){this._clipToFrustum!==e&&(this._clipToFrustum=e,this._updateEffectDefines())}get useFresnel(){return this._useFresnel}set useFresnel(e){this._useFresnel!==e&&(this._useFresnel=e,this._buildPipeline())}get enableAutomaticThicknessComputation(){return this._enableAutomaticThicknessComputation}set enableAutomaticThicknessComputation(e){this._enableAutomaticThicknessComputation!==e&&(this._enableAutomaticThicknessComputation=e,this._buildPipeline())}get backfaceDepthRenderer(){return this._depthRenderer}get backfaceDepthTextureDownsample(){return this._backfaceDepthTextureDownsample}set backfaceDepthTextureDownsample(e){this._backfaceDepthTextureDownsample!==e&&(this._backfaceDepthTextureDownsample=e,this._resizeDepthRenderer())}get backfaceForceDepthWriteTransparentMeshes(){return this._backfaceForceDepthWriteTransparentMeshes}set backfaceForceDepthWriteTransparentMeshes(e){this._backfaceForceDepthWriteTransparentMeshes!==e&&(this._backfaceForceDepthWriteTransparentMeshes=e,this._depthRenderer&&(this._depthRenderer.forceDepthWriteTransparentMeshes=e))}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?e&&(this._isDirty?this._buildPipeline():null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)):null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()))}get inputTextureColorIsInGammaSpace(){return this._inputTextureColorIsInGammaSpace}set inputTextureColorIsInGammaSpace(e){this._inputTextureColorIsInGammaSpace!==e&&(this._inputTextureColorIsInGammaSpace=e,this._buildPipeline())}get generateOutputInGammaSpace(){return this._generateOutputInGammaSpace}set generateOutputInGammaSpace(e){this._generateOutputInGammaSpace!==e&&(this._generateOutputInGammaSpace=e,this._buildPipeline())}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._buildPipeline())}getScene(){return this._scene}get _geometryBufferRenderer(){return this._forceGeometryBuffer?this._scene.geometryBufferRenderer:null}get _prePassRenderer(){return this._forceGeometryBuffer?null:this._scene.prePassRenderer}get scene(){return this._scene}get isSupported(){let e=this._scene.getEngine().getCaps();return e.drawBuffersExtension&&e.texelFetch}constructor(e,t,i,r=!1,s=0){if(super(t.getEngine(),e),this.SSRRenderEffect="SSRRenderEffect",this.SSRBlurRenderEffect="SSRBlurRenderEffect",this.SSRCombineRenderEffect="SSRCombineRenderEffect",this._samples=1,this.maxDistance=1e3,this.step=1,this.thickness=.5,this.strength=1,this.reflectionSpecularFalloffExponent=1,this.maxSteps=1e3,this.roughnessFactor=.2,this.selfCollisionNumSkip=1,this._reflectivityThreshold=.04,this._ssrDownsample=0,this._blurDispersionStrength=.03,this._blurDownsample=0,this._enableSmoothReflections=!1,this._environmentTextureIsProbe=!1,this._attenuateScreenBorders=!0,this._attenuateIntersectionDistance=!0,this._attenuateIntersectionIterations=!0,this._attenuateFacingCamera=!1,this._attenuateBackfaceReflection=!1,this._clipToFrustum=!0,this._useFresnel=!1,this._enableAutomaticThicknessComputation=!1,this._backfaceDepthTextureDownsample=0,this._backfaceForceDepthWriteTransparentMeshes=!0,this._isEnabled=!0,this._inputTextureColorIsInGammaSpace=!0,this._generateOutputInGammaSpace=!0,this._debug=!1,this._forceGeometryBuffer=!1,this._isDirty=!1,this._camerasToBeAttached=[],this._cameras=i||t.cameras,this._cameras=this._cameras.slice(),this._camerasToBeAttached=this._cameras.slice(),this._scene=t,this._textureType=s,this._forceGeometryBuffer=r,this.isSupported){if(t.postProcessRenderPipelineManager.addPipeline(this),this._forceGeometryBuffer){let e=t.enableGeometryBufferRenderer();e&&(e.enableReflectivity=!0,e.useSpecificClearForDepthTexture=!0)}else{let e=t.enablePrePassRenderer();e&&(e.useSpecificClearForDepthTexture=!0,e.markAsDirty())}this._buildPipeline()}}getClassName(){return"SSRRenderingPipeline"}addCamera(e){this._camerasToBeAttached.push(e),this._buildPipeline()}removeCamera(e){let t=this._camerasToBeAttached.indexOf(e);this._camerasToBeAttached.splice(t,1),this._buildPipeline()}dispose(e=!1){this._disposeDepthRenderer(),this._disposePostProcesses(),e&&this._scene.disableGeometryBufferRenderer(),this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),super.dispose()}_getTextureSize(){var e,t;let i=this._scene.getEngine(),r=this._prePassRenderer,s={width:i.getRenderWidth(),height:i.getRenderHeight()};if(r&&(null===(e=this._scene.activeCamera)||void 0===e?void 0:e._getFirstPostProcess())===this._ssrPostProcess){let e=r.getRenderTarget();e&&e.textures&&(s=e.textures[r.getIndex(4)].getSize())}else(null===(t=this._ssrPostProcess)||void 0===t?void 0:t.inputTexture)&&(s.width=this._ssrPostProcess.inputTexture.width,s.height=this._ssrPostProcess.inputTexture.height);return s}_updateEffectDefines(){var e,t,i,r,s;let n=[];(this._geometryBufferRenderer||this._prePassRenderer)&&n.push("#define SSR_SUPPORTED"),this._enableSmoothReflections&&n.push("#define SSRAYTRACE_ENABLE_REFINEMENT"),this._scene.useRightHandedSystem&&n.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"),this._environmentTexture&&(n.push("#define SSR_USE_ENVIRONMENT_CUBE"),this._environmentTexture.boundingBoxSize&&n.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"),this._environmentTexture.gammaSpace&&n.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE")),this._environmentTextureIsProbe&&n.push("#define SSR_INVERTCUBICMAP"),this._enableAutomaticThicknessComputation&&n.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"),this._attenuateScreenBorders&&n.push("#define SSR_ATTENUATE_SCREEN_BORDERS"),this._attenuateIntersectionDistance&&n.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"),this._attenuateIntersectionIterations&&n.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"),this._attenuateFacingCamera&&n.push("#define SSR_ATTENUATE_FACING_CAMERA"),this._attenuateBackfaceReflection&&n.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"),this._clipToFrustum&&n.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"),this._useBlur()&&n.push("#define SSR_USE_BLUR"),this._debug&&n.push("#define SSRAYTRACE_DEBUG"),this._inputTextureColorIsInGammaSpace&&n.push("#define SSR_INPUT_IS_GAMMA_SPACE"),this._generateOutputInGammaSpace&&n.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"),this._useFresnel&&n.push("#define SSR_BLEND_WITH_FRESNEL"),0===this._reflectivityThreshold&&n.push("#define SSR_DISABLE_REFLECTIVITY_TEST"),(null!==(t=null===(e=this._geometryBufferRenderer)||void 0===e?void 0:e.generateNormalsInWorldSpace)&&void 0!==t?t:null===(i=this._prePassRenderer)||void 0===i?void 0:i.generateNormalsInWorldSpace)&&n.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"),(null===(r=this._geometryBufferRenderer)||void 0===r?void 0:r.normalsAreUnsigned)&&n.push("#define SSR_DECODE_NORMAL"),null===(s=this._ssrPostProcess)||void 0===s||s.updateEffect(n.join("\n"))}_buildPipeline(){var e;if(!this.isSupported)return;if(!this._isEnabled){this._isDirty=!0;return}this._isDirty=!1;let t=this._scene.getEngine();if(this._disposeDepthRenderer(),this._disposePostProcesses(),null!==this._cameras&&(this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name,this._cameras),this._cameras=this._camerasToBeAttached.slice()),this._reset(),this._enableAutomaticThicknessComputation){let t=null===(e=this._cameras)||void 0===e?void 0:e[0];t&&(this._depthRendererCamera=t,this._depthRenderer=new _Y(this._scene,void 0,void 0,void 0,1,!0,"SSRBackDepth"),this._depthRenderer.clearColor.r=1e8,this._depthRenderer.reverseCulling=!0,this._depthRenderer.forceDepthWriteTransparentMeshes=this._backfaceForceDepthWriteTransparentMeshes,this._resizeDepthRenderer(),t.customRenderTargets.push(this._depthRenderer.getDepthMap()))}this._createSSRPostProcess(),this.addEffect(new xS(t,this.SSRRenderEffect,()=>this._ssrPostProcess,!0)),this._useBlur()&&(this._createBlurAndCombinerPostProcesses(),this.addEffect(new xS(t,this.SSRBlurRenderEffect,()=>[this._blurPostProcessX,this._blurPostProcessY],!0)),this.addEffect(new xS(t,this.SSRCombineRenderEffect,()=>this._blurCombinerPostProcess,!0))),null!==this._cameras&&this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name,this._cameras)}_resizeDepthRenderer(){if(!this._depthRenderer)return;let e=this._getTextureSize(),t=this._depthRenderer.getDepthMap().getSize(),i=Math.floor(e.width/(this._backfaceDepthTextureDownsample+1)),r=Math.floor(e.height/(this._backfaceDepthTextureDownsample+1));(t.width!==i||t.height!==r)&&this._depthRenderer.getDepthMap().resize({width:i,height:r})}_disposeDepthRenderer(){var e;if(this._depthRenderer){if(this._depthRendererCamera){let t=null!==(e=this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()))&&void 0!==e?e:-1;-1!==t&&this._depthRendererCamera.customRenderTargets.splice(t,1)}this._depthRendererCamera=null,this._depthRenderer.getDepthMap().dispose()}this._depthRenderer=null}_disposePostProcesses(){var e,t,i,r;for(let s=0;s{this._resizeDepthRenderer();let t=this._geometryBufferRenderer,i=this._prePassRenderer;if(!i&&!t)return;if(t){let i=t.getTextureIndex(x2.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("normalSampler",t.getGBuffer().textures[1]),e.setTexture("reflectivitySampler",t.getGBuffer().textures[i]),e.setTexture("depthSampler",t.getGBuffer().textures[0])}else if(i){let t=i.getIndex(5),r=i.getIndex(3),s=i.getIndex(6);e.setTexture("normalSampler",i.getRenderTarget().textures[s]),e.setTexture("depthSampler",i.getRenderTarget().textures[t]),e.setTexture("reflectivitySampler",i.getRenderTarget().textures[r])}this._enableAutomaticThicknessComputation&&this._depthRenderer&&(e.setTexture("backDepthSampler",this._depthRenderer.getDepthMap()),e.setFloat("backSizeFactor",this._backfaceDepthTextureDownsample+1));let r=this._scene.activeCamera;if(!r)return;let s=r.getViewMatrix(),n=r.getProjectionMatrix();n.invertToRef(rf.jp.Matrix[0]),s.invertToRef(rf.jp.Matrix[1]),e.setMatrix("projection",n),e.setMatrix("view",s),e.setMatrix("invView",rf.jp.Matrix[1]),e.setMatrix("invProjectionMatrix",rf.jp.Matrix[0]),e.setFloat("thickness",this.thickness),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("strength",this.strength),e.setFloat("stepSize",this.step),e.setFloat("maxSteps",this.maxSteps),e.setFloat("roughnessFactor",this.roughnessFactor),e.setFloat("nearPlaneZ",r.minZ),e.setFloat("maxDistance",this.maxDistance),e.setFloat("selfCollisionNumSkip",this.selfCollisionNumSkip),e.setFloat("reflectivityThreshold",this._reflectivityThreshold);let a=this._getTextureSize();rf.y3.ScalingToRef(a.width,a.height,1,rf.jp.Matrix[2]),n.multiplyToRef(this._scene.getEngine().isWebGPU?TC:TE,rf.jp.Matrix[3]),rf.jp.Matrix[3].multiplyToRef(rf.jp.Matrix[2],rf.jp.Matrix[4]),e.setMatrix("projectionPixel",rf.jp.Matrix[4]),this._environmentTexture&&(e.setTexture("envCubeSampler",this._environmentTexture),this._environmentTexture.boundingBoxSize&&(e.setVector3("vReflectionPosition",this._environmentTexture.boundingBoxPosition),e.setVector3("vReflectionSize",this._environmentTexture.boundingBoxSize)))},this._ssrPostProcess.samples=this.samples,this._forceGeometryBuffer||(this._ssrPostProcess._prePassEffectConfiguration=new Tg)}_createBlurAndCombinerPostProcesses(){let e=this._scene.getEngine();this._blurPostProcessX=new nz("SSRblurX","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._ssrDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessX.autoClear=!1,this._blurPostProcessX.onApplyObservable.add(e=>{var t,i;let r=null!==(i=null===(t=this._blurPostProcessX)||void 0===t?void 0:t.inputTexture.width)&&void 0!==i?i:this._scene.getEngine().getRenderWidth();e.setFloat2("texelOffsetScale",this._blurDispersionStrength/r,0)}),this._blurPostProcessY=new nz("SSRblurY","screenSpaceReflection2Blur",["texelOffsetScale"],["textureSampler"],this._useBlur()?1/(this._blurDownsample+1):1,null,2,e,!1,"",this._textureType),this._blurPostProcessY.autoClear=!1,this._blurPostProcessY.onApplyObservable.add(e=>{var t,i;let r=null!==(i=null===(t=this._blurPostProcessY)||void 0===t?void 0:t.inputTexture.height)&&void 0!==i?i:this._scene.getEngine().getRenderHeight();e.setFloat2("texelOffsetScale",0,this._blurDispersionStrength/r)});let t=["strength","reflectionSpecularFalloffExponent","reflectivityThreshold"],i=["textureSampler","mainSampler","reflectivitySampler"],r="";this._debug&&(r+="#define SSRAYTRACE_DEBUG\n"),this._inputTextureColorIsInGammaSpace&&(r+="#define SSR_INPUT_IS_GAMMA_SPACE\n"),this._generateOutputInGammaSpace&&(r+="#define SSR_OUTPUT_IS_GAMMA_SPACE\n"),this.useFresnel&&(r+="#define SSR_BLEND_WITH_FRESNEL\n",t.push("projection","invProjectionMatrix"),i.push("depthSampler","normalSampler")),0===this._reflectivityThreshold&&(r+="#define SSR_DISABLE_REFLECTIVITY_TEST"),this._blurCombinerPostProcess=new nz("SSRblurCombiner","screenSpaceReflection2BlurCombiner",t,i,this._useBlur()?1/(this._blurDownsample+1):1,null,1,e,!1,r,this._textureType),this._blurCombinerPostProcess.autoClear=!1,this._blurCombinerPostProcess.onApplyObservable.add(e=>{var t;let i=this._geometryBufferRenderer,r=this._prePassRenderer;if(r||i){if(r&&(null===(t=this._scene.activeCamera)||void 0===t?void 0:t._getFirstPostProcess())===this._ssrPostProcess){let t=r.getRenderTarget();t&&t.textures&&e.setTexture("mainSampler",t.textures[r.getIndex(4)])}else e.setTextureFromPostProcess("mainSampler",this._ssrPostProcess);if(i){let t=i.getTextureIndex(x2.REFLECTIVITY_TEXTURE_TYPE);e.setTexture("reflectivitySampler",i.getGBuffer().textures[t]),this.useFresnel&&(e.setTexture("normalSampler",i.getGBuffer().textures[1]),e.setTexture("depthSampler",i.getGBuffer().textures[0]))}else if(r){let t=r.getIndex(3);if(e.setTexture("reflectivitySampler",r.getRenderTarget().textures[t]),this.useFresnel){let t=r.getIndex(5),i=r.getIndex(6);e.setTexture("normalSampler",r.getRenderTarget().textures[i]),e.setTexture("depthSampler",r.getRenderTarget().textures[t])}}if(e.setFloat("strength",this.strength),e.setFloat("reflectionSpecularFalloffExponent",this.reflectionSpecularFalloffExponent),e.setFloat("reflectivityThreshold",this._reflectivityThreshold),this.useFresnel){let t=this._scene.activeCamera;if(t){let i=t.getProjectionMatrix();i.invertToRef(rf.jp.Matrix[0]),e.setMatrix("projection",i),e.setMatrix("invProjectionMatrix",rf.jp.Matrix[0])}}}})}serialize(){let e=rG.p4.Serialize(this);return e.customType="SSRRenderingPipeline",e}static Parse(e,t,i){return rG.p4.Parse(()=>new Tb(e._name,t,e._ratio),e,t,i)}}(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"samples",null),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"maxDistance",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"step",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"thickness",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"strength",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"reflectionSpecularFalloffExponent",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"maxSteps",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"roughnessFactor",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"selfCollisionNumSkip",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"_reflectivityThreshold",void 0),(0,sx.gn)([(0,rG.qC)("_ssrDownsample")],Tb.prototype,"_ssrDownsample",void 0),(0,sx.gn)([(0,rG.qC)()],Tb.prototype,"ssrDownsample",null),(0,sx.gn)([(0,rG.qC)("blurDispersionStrength")],Tb.prototype,"_blurDispersionStrength",void 0),(0,sx.gn)([(0,rG.qC)("blurDownsample")],Tb.prototype,"_blurDownsample",void 0),(0,sx.gn)([(0,rG.qC)("enableSmoothReflections")],Tb.prototype,"_enableSmoothReflections",void 0),(0,sx.gn)([(0,rG.qC)("environmentTexture")],Tb.prototype,"_environmentTexture",void 0),(0,sx.gn)([(0,rG.qC)("environmentTextureIsProbe")],Tb.prototype,"_environmentTextureIsProbe",void 0),(0,sx.gn)([(0,rG.qC)("attenuateScreenBorders")],Tb.prototype,"_attenuateScreenBorders",void 0),(0,sx.gn)([(0,rG.qC)("attenuateIntersectionDistance")],Tb.prototype,"_attenuateIntersectionDistance",void 0),(0,sx.gn)([(0,rG.qC)("attenuateIntersectionIterations")],Tb.prototype,"_attenuateIntersectionIterations",void 0),(0,sx.gn)([(0,rG.qC)("attenuateFacingCamera")],Tb.prototype,"_attenuateFacingCamera",void 0),(0,sx.gn)([(0,rG.qC)("attenuateBackfaceReflection")],Tb.prototype,"_attenuateBackfaceReflection",void 0),(0,sx.gn)([(0,rG.qC)("clipToFrustum")],Tb.prototype,"_clipToFrustum",void 0),(0,sx.gn)([(0,rG.qC)("useFresnel")],Tb.prototype,"_useFresnel",void 0),(0,sx.gn)([(0,rG.qC)("enableAutomaticThicknessComputation")],Tb.prototype,"_enableAutomaticThicknessComputation",void 0),(0,sx.gn)([(0,rG.qC)("backfaceDepthTextureDownsample")],Tb.prototype,"_backfaceDepthTextureDownsample",void 0),(0,sx.gn)([(0,rG.qC)("backfaceForceDepthWriteTransparentMeshes")],Tb.prototype,"_backfaceForceDepthWriteTransparentMeshes",void 0),(0,sx.gn)([(0,rG.qC)("isEnabled")],Tb.prototype,"_isEnabled",void 0),(0,sx.gn)([(0,rG.qC)("inputTextureColorIsInGammaSpace")],Tb.prototype,"_inputTextureColorIsInGammaSpace",void 0),(0,sx.gn)([(0,rG.qC)("generateOutputInGammaSpace")],Tb.prototype,"_generateOutputInGammaSpace",void 0),(0,sx.gn)([(0,rG.qC)("debug")],Tb.prototype,"_debug",void 0),(0,rg.H)("BABYLON.SSRRenderingPipeline",Tb);let Ty=`varying vec2 vUV;uniform sampler2D textureSampler;uniform float _ExposureAdjustment; +#if defined(HABLE_TONEMAPPING) +const float A=0.15;const float B=0.50;const float C=0.10;const float D=0.20;const float E=0.02;const float F=0.30;const float W=11.2; +#endif +float Luminance(vec3 c) +{return dot(c,vec3(0.22,0.707,0.071));} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec3 colour=texture2D(textureSampler,vUV).rgb; +#if defined(REINHARD_TONEMAPPING) +float lum=Luminance(colour.rgb); +float lumTm=lum*_ExposureAdjustment;float scale=lumTm/(1.0+lumTm); +colour*=scale/lum; +#elif defined(HABLE_TONEMAPPING) +colour*=_ExposureAdjustment;const float ExposureBias=2.0;vec3 x=ExposureBias*colour;vec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;x=vec3(W,W,W);vec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);colour=curr*whiteScale; +#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING) +colour*=_ExposureAdjustment;vec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);vec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);colour=retColor*retColor; +#elif defined(PHOTOGRAPHIC_TONEMAPPING) +colour= vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour); +#endif +gl_FragColor=vec4(colour.rgb,1.0);}`;nw.v.ShadersStore.tonemapPixelShader=Ty,(tr=rr||(rr={}))[tr.Hable=0]="Hable",tr[tr.Reinhard=1]="Reinhard",tr[tr.HejiDawson=2]="HejiDawson",tr[tr.Photographic=3]="Photographic";let TA=`uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform mat4 viewProjection;uniform vec2 depthValues; +#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position; +#if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +#include +#include +#include +gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); +#if defined(ALPHATEST) || defined(BASIC_RENDER) +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +} +`;nw.v.ShadersStore.volumetricLightScatteringPassVertexShader=TR;let TP=`#if defined(ALPHATEST) || defined(NEED_UV) +varying vec2 vUV; +#endif +#if defined(ALPHATEST) +uniform sampler2D diffuseSampler; +#endif +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{ +#if defined(ALPHATEST) +vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) +discard; +#endif +gl_FragColor=vec4(0.0,0.0,0.0,1.0);} +`;nw.v.ShadersStore.volumetricLightScatteringPassPixelShader=TP;class TI extends nz{get useDiffuseColor(){return rb.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"),!1}set useDiffuseColor(e){rb.Y.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead")}constructor(e,t,i,r,s=100,n=sj.BILINEAR_SAMPLINGMODE,a,o,l){var h,u;super(e,"volumetricLightScattering",["decay","exposure","weight","meshPositionOnScreen","density"],["lightScatteringSampler"],t.postProcessRatio||t,i,n,a,o,"#define NUM_SAMPLES "+s),this._screenCoordinates=rf.FM.Zero(),this.customMeshPosition=rf.P.Zero(),this.useCustomMeshPosition=!1,this.invert=!0,this.excludedMeshes=[],this.includedMeshes=[],this.exposure=.3,this.decay=.96815,this.weight=.58767,this.density=.926,a=(l=null!==(u=null!==(h=null==i?void 0:i.getScene())&&void 0!==h?h:l)&&void 0!==u?u:this._scene).getEngine(),this._viewPort=new ny.l(0,0,1,1).toGlobal(a.getRenderWidth(),a.getRenderHeight()),this.mesh=null!=r?r:TI.CreateDefaultMesh("VolumetricLightScatteringMesh",l),this._createPass(l,t.passRatio||t),this.onActivate=e=>{this.isSupported||this.dispose(e),this.onActivate=null},this.onApplyObservable.add(e=>{this._updateMeshScreenCoordinates(l),e.setTexture("lightScatteringSampler",this._volumetricLightScatteringRTT),e.setFloat("exposure",this.exposure),e.setFloat("decay",this.decay),e.setFloat("weight",this.weight),e.setFloat("density",this.density),e.setVector2("meshPositionOnScreen",this._screenCoordinates)})}getClassName(){return"VolumetricLightScatteringPostProcess"}_isReady(e,t){var i;let r=e.getMesh();if(r===this.mesh&&r.material)return r.material.isReady(r);let s=null===(i=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===i?void 0:i[this._scene.getEngine().currentRenderPassId];if(s)return s.isReadyForSubMesh(r,e,t);let n=[],a=[sm.o.PositionKind],o=e.getMaterial();o&&(o.needAlphaTesting()&&n.push("#define ALPHATEST"),r.isVerticesDataPresent(sm.o.UVKind)&&(a.push(sm.o.UVKind),n.push("#define UV1")),r.isVerticesDataPresent(sm.o.UV2Kind)&&(a.push(sm.o.UV2Kind),n.push("#define UV2"))),r.useBones&&r.computeBonesUsingShaders?(a.push(sm.o.MatricesIndicesKind),a.push(sm.o.MatricesWeightsKind),n.push("#define NUM_BONE_INFLUENCERS "+r.numBoneInfluencers),n.push("#define BonesPerMesh "+(r.skeleton?r.skeleton.bones.length+1:0))):n.push("#define NUM_BONE_INFLUENCERS 0"),t&&(n.push("#define INSTANCES"),nE.G.PushAttributesForInstances(a),e.getRenderingMesh().hasThinInstances&&n.push("#define THIN_INSTANCES"));let l=e._getDrawWrapper(void 0,!0),h=l.defines,u=n.join("\n");return h!==u&&l.setEffect(r.getScene().getEngine().createEffect("volumetricLightScatteringPass",a,["world","mBones","viewProjection","diffuseMatrix"],["diffuseSampler"],u,void 0,void 0,void 0,{maxSimultaneousMorphTargets:r.numBoneInfluencers}),u),l.effect.isReady()}setCustomMeshPosition(e){this.customMeshPosition=e}getCustomMeshPosition(){return this.customMeshPosition}dispose(e){let t=e.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);-1!==t&&e.getScene().customRenderTargets.splice(t,1),this._volumetricLightScatteringRTT.dispose(),super.dispose(e)}getPass(){return this._volumetricLightScatteringRTT}_meshExcluded(e){return this.includedMeshes.length>0&&-1===this.includedMeshes.indexOf(e)||this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e)}_createPass(e,t){let i;let r=e.getEngine();this._volumetricLightScatteringRTT=new as("volumetricLightScatteringMap",{width:r.getRenderWidth()*t,height:r.getRenderHeight()*t},e,!1,!0,0),this._volumetricLightScatteringRTT.wrapU=sj.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.wrapV=sj.CLAMP_ADDRESSMODE,this._volumetricLightScatteringRTT.renderList=null,this._volumetricLightScatteringRTT.renderParticles=!1,this._volumetricLightScatteringRTT.ignoreCameraViewport=!0;let s=this.getCamera();s?s.customRenderTargets.push(this._volumetricLightScatteringRTT):e.customRenderTargets.push(this._volumetricLightScatteringRTT);let n=e=>{var t;let i=e.getRenderingMesh(),r=e.getEffectiveMesh();if(this._meshExcluded(i))return;r._internalAbstractMeshDataInfo._isActiveIntermediate=!1;let s=e.getMaterial();if(!s)return;let n=i.getScene(),a=n.getEngine();a.setState(s.backFaceCulling,void 0,void 0,void 0,s.cullBackFaces);let o=i._getInstancesRenderList(e._id,!!e.getReplacementMesh());if(o.mustReturn)return;let l=a.getCaps().instancedArrays&&(null!==o.visibleInstances[e._id]||i.hasThinInstances);if(this._isReady(e,l)){let h=null===(t=r._internalAbstractMeshDataInfo._materialForRenderPass)||void 0===t?void 0:t[a.currentRenderPassId],u=e._getDrawWrapper();if(i!==this.mesh||u||(u=s._getDrawWrapper()),!u)return;let c=u.effect;if(a.enableEffect(u),l||i._bind(e,c,s.fillMode),i===this.mesh)s.bind(r.getWorldMatrix(),i);else if(h)h.bindForSubMesh(r.getWorldMatrix(),r,e);else{if(c.setMatrix("viewProjection",n.getTransformMatrix()),s&&s.needAlphaTesting()){let e=s.getAlphaTestTexture();c.setTexture("diffuseSampler",e),e&&c.setMatrix("diffuseMatrix",e.getTextureMatrix())}i.useBones&&i.computeBonesUsingShaders&&i.skeleton&&c.setMatrices("mBones",i.skeleton.getTransformMatrices(i))}l&&i.hasThinInstances&&c.setMatrix("world",r.getWorldMatrix()),i._processRendering(r,e,c,nu.F.TriangleFillMode,o,l,(e,t)=>{e||c.setMatrix("world",t)})}},a=new rm.HE(0,0,0,1);this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(()=>{i=e.clearColor,e.clearColor=a}),this._volumetricLightScatteringRTT.onAfterRenderObservable.add(()=>{e.clearColor=i}),this._volumetricLightScatteringRTT.customIsReadyFunction=(e,t,i)=>{if((i||0===t)&&e.subMeshes)for(let t=0;t{let a;let o=e.getEngine();if(s.length){for(o.setColorWrite(!1),a=0;ae._alphaIndex>t._alphaIndex?1:e._alphaIndext._distanceToCamera?-1:0),o.setAlphaMode(2),a=0;a{e.setFloat("curvature_ridge",.5/Math.max(this.ridge*this.ridge,1e-4)),e.setFloat("curvature_valley",.7/Math.max(this.valley*this.valley,1e-4));let t=this._geometryBufferRenderer.getGBuffer().textures[1];e.setTexture("normalSampler",t)}):rb.Y.Error("Multiple Render Target support needed for screen space curvature post process. Please use IsSupported test first.")}static get IsSupported(){let e=rL.l.LastCreatedEngine;return!!e&&e.getCaps().drawBuffersExtension}static _Parse(e,t,i,r){return rG.p4.Parse(()=>new TD(e.name,i,e.options,t,e.renderTargetSamplingMode,i.getEngine(),e.textureType,e.reusable),e,i,r)}}(0,sx.gn)([(0,rG.qC)()],TD.prototype,"ridge",void 0),(0,sx.gn)([(0,rG.qC)()],TD.prototype,"valley",void 0),(0,rg.H)("BABYLON.ScreenSpaceCurvaturePostProcess",TD);let TO=`uniform vec4 color; +`;nw.v.IncludesShadersStore.boundingBoxRendererFragmentDeclaration=TO;let TN=`#ifdef WEBGL2 +uniform vec4 color;uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +#else +layout(std140,column_major) uniform;uniform BoundingBoxRenderer {vec4 color;mat4 world;mat4 viewProjection;mat4 viewProjectionR;}; +#endif +`;nw.v.IncludesShadersStore.boundingBoxRendererUboDeclaration=TN;let TF=`#include<__decl__boundingBoxRendererFragment> +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.boundingBoxRendererPixelShader=TF;let TL=`uniform mat4 world;uniform mat4 viewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR; +#endif +`;nw.v.IncludesShadersStore.boundingBoxRendererVertexDeclaration=TL;let Tw=`attribute vec3 position; +#include<__decl__boundingBoxRendererVertex> +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec4 worldPos=world*vec4(position,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} +#else +gl_Position=viewProjection*worldPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +} +`;nw.v.ShadersStore.boundingBoxRendererVertexShader=Tw,Object.defineProperty(r2.x.prototype,"forceShowBoundingBoxes",{get:function(){return this._forceShowBoundingBoxes||!1},set:function(e){this._forceShowBoundingBoxes=e,e&&this.getBoundingBoxRenderer()},enumerable:!0,configurable:!0}),r2.x.prototype.getBoundingBoxRenderer=function(){return this._boundingBoxRenderer||(this._boundingBoxRenderer=new TB(this)),this._boundingBoxRenderer},Object.defineProperty(sf.x.prototype,"showBoundingBox",{get:function(){return this._showBoundingBox||!1},set:function(e){this._showBoundingBox=e,e&&this.getScene().getBoundingBoxRenderer()},enumerable:!0,configurable:!0});class TB{constructor(e){this.name=sN.l.NAME_BOUNDINGBOXRENDERER,this.frontColor=new rm.Wo(1,1,1),this.backColor=new rm.Wo(.1,.1,.1),this.showBackLines=!0,this.onBeforeBoxRenderingObservable=new r_.y$,this.onAfterBoxRenderingObservable=new r_.y$,this.onResourcesReadyObservable=new r_.y$,this.enabled=!0,this.renderList=new nL.t(32),this._vertexBuffers={},this._fillIndexBuffer=null,this._fillIndexData=null,this.scene=e,e._addComponent(this),this._uniformBufferFront=new sT.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererFront",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferFront),this._uniformBufferBack=new sT.M(this.scene.getEngine(),void 0,void 0,"BoundingBoxRendererBack",!this.scene.getEngine().isWebGPU),this._buildUniformLayout(this._uniformBufferBack)}_buildUniformLayout(e){e.addUniform("color",4),e.addUniform("world",16),e.addUniform("viewProjection",16),e.addUniform("viewProjectionR",16),e.create()}register(){this.scene._beforeEvaluateActiveMeshStage.registerStep(sN.l.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER,this,this.reset),this.scene._preActiveMeshStage.registerStep(sN.l.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER,this,this._preActiveMesh),this.scene._evaluateSubMeshStage.registerStep(sN.l.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER,this,this._evaluateSubMesh),this.scene._afterRenderingGroupDrawStage.registerStep(sN.l.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER,this,this.render)}_evaluateSubMesh(e,t){if(e.showSubMeshesBoundingBox){let i=t.getBoundingInfo();null!=i&&(i.boundingBox._tag=e.renderingGroupId,this.renderList.push(i.boundingBox))}}_preActiveMesh(e){if(e.showBoundingBox||this.scene.forceShowBoundingBoxes){let t=e.getBoundingInfo();t.boundingBox._tag=e.renderingGroupId,this.renderList.push(t.boundingBox)}}_prepareResources(){if(this._colorShader)return;this._colorShader=new hV("colorShader",this.scene,"boundingBoxRenderer",{attributes:[sm.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!1),this._colorShader.doNotSerialize=!0,this._colorShader.reservedDataStore={hidden:!0},this._colorShaderForOcclusionQuery=new hV("colorShaderOccQuery",this.scene,"boundingBoxRenderer",{attributes:[sm.o.PositionKind],uniforms:["world","viewProjection","viewProjectionR","color"],uniformBuffers:["BoundingBoxRenderer"]},!0),this._colorShaderForOcclusionQuery.doNotSerialize=!0,this._colorShaderForOcclusionQuery.reservedDataStore={hidden:!0};let e=this.scene.getEngine(),t=hR({size:1});this._vertexBuffers[sm.o.PositionKind]=new sm.o(e,t.positions,sm.o.PositionKind,!1),this._createIndexBuffer(),this._fillIndexData=t.indices,this.onResourcesReadyObservable.notifyObservers(this)}_createIndexBuffer(){let e=this.scene.getEngine();this._indexBuffer=e.createIndexBuffer([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,7,1,6,2,5,3,4])}rebuild(){let e=this._vertexBuffers[sm.o.PositionKind];e&&e._rebuild(),this._createIndexBuffer()}reset(){this.renderList.reset()}render(e){var t,i;if(0===this.renderList.length||!this.enabled||(this._prepareResources(),!this._colorShader.isReady()))return;let r=this.scene.getEngine();r.setDepthWrite(!1);let s=this.scene.getTransformMatrix();for(let n=0;n{let t=e._getComponent(sN.l.NAME_DEPTHRENDERER);t||(t=new TU(e),e._addComponent(t))};let TV=`precision highp float;uniform sampler2D uFrontColor;uniform sampler2D uBackColor;void main() {ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec4 frontColor=texelFetch(uFrontColor,fragCoord,0);vec4 backColor=texelFetch(uBackColor,fragCoord,0);float alphaMultiplier=1.0-frontColor.a;glFragColor=vec4( +frontColor.rgb+alphaMultiplier*backColor.rgb, +frontColor.a+backColor.a +);}`;nw.v.ShadersStore.oitFinalPixelShader=TV;let Tk=`precision highp float;uniform sampler2D uBackColor;void main() {glFragColor=texelFetch(uBackColor,ivec2(gl_FragCoord.xy),0);if (glFragColor.a==0.0) { +discard;}}`;nw.v.ShadersStore.oitBackBlendPixelShader=Tk;class TG{constructor(){this.enabled=!0,this.name="depthPeeling",this.texturesRequired=[4]}}class Tz{get passCount(){return this._passCount}set passCount(e){this._passCount!==e&&(this._passCount=e,this._createRenderPassIds())}get useRenderPasses(){return this._useRenderPasses}set useRenderPasses(e){this._useRenderPasses!==e&&(this._useRenderPasses=e,this._createRenderPassIds())}addExcludedMesh(e){-1===this._excludedMeshes.indexOf(e.uniqueId)&&this._excludedMeshes.push(e.uniqueId)}removeExcludedMesh(e){let t=this._excludedMeshes.indexOf(e.uniqueId);-1!==t&&this._excludedMeshes.splice(t,1)}constructor(e,t=5){if(this._thinTextures=[],this._currentPingPongState=0,this._layoutCacheFormat=[[!0],[!0,!0],[!0,!0,!0]],this._layoutCache=[],this._candidateSubMeshes=new nL.t(10),this._excludedSubMeshes=new nL.t(10),this._excludedMeshes=[],this._colorCache=[new rm.HE(Tz._DEPTH_CLEAR_VALUE,Tz._DEPTH_CLEAR_VALUE,0,0),new rm.HE(-Tz._MIN_DEPTH,Tz._MAX_DEPTH,0,0),new rm.HE(0,0,0,0)],this._scene=e,this._engine=e.getEngine(),this._passCount=t,!e.enablePrePassRenderer()){rb.Y.Warn("Depth peeling for order independant transparency could not enable PrePass, aborting.");return}for(let e=0;e +uniform vec4 color; +#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#include +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.linePixelShader=TH;let TX=`#include +#include +attribute vec3 position;attribute vec4 normal;uniform mat4 viewProjection;uniform float width;uniform float aspectRatio; +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +#include +mat4 worldViewProjection=viewProjection*finalWorld;vec4 viewPosition=worldViewProjection*vec4(position,1.0);vec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);vec2 currentScreen=viewPosition.xy/viewPosition.w;vec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;currentScreen.x*=aspectRatio;nextScreen.x*=aspectRatio;vec2 dir=normalize(nextScreen-currentScreen);vec2 normalDir=vec2(-dir.y,dir.x);normalDir*=width/2.0;normalDir.x/=aspectRatio;vec4 offset=vec4(normalDir*normal.w,0.0,0.0);gl_Position=viewPosition+offset; +#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) +vec4 worldPos=finalWorld*vec4(position,1.0); +#include +#endif +#include +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.lineVertexShader=TX,sf.x.prototype.disableEdgesRendering=function(){return this._edgesRenderer&&(this._edgesRenderer.dispose(),this._edgesRenderer=null),this},sf.x.prototype.enableEdgesRendering=function(e=.95,t=!1,i){return this.disableEdgesRendering(),this._edgesRenderer=new Tj(this,e,t,!0,i),this},Object.defineProperty(sf.x.prototype,"edgesRenderer",{get:function(){return this._edgesRenderer},enumerable:!0,configurable:!0}),hz.prototype.enableEdgesRendering=function(e=.95,t=!1){return this.disableEdgesRendering(),this._edgesRenderer=new Tq(this,e,t),this},hW.prototype.enableEdgesRendering=function(e=.95,t=!1){return hz.prototype.enableEdgesRendering.apply(this,arguments),this};class TY{constructor(){this.edges=[],this.edgesConnectedCount=0}}class Tj{get linesPositions(){return this._linesPositions}get linesNormals(){return this._linesNormals}get linesIndices(){return this._linesIndices}get lineShader(){return this._lineShader}set lineShader(e){this._lineShader=e}static _GetShader(e){if(!e._edgeRenderLineShader){let t=new hV("lineShader",e,"line",{attributes:["position","normal"],uniforms:["world","viewProjection","color","width","aspectRatio"]},!1);t.disableDepthWrite=!0,t.backFaceCulling=!1,t.checkReadyOnEveryCall=e.getEngine().isWebGPU,e._edgeRenderLineShader=t}return e._edgeRenderLineShader}constructor(e,t=.95,i=!1,r=!0,s){var n;this.edgesWidthScalerForOrthographic=1e3,this.edgesWidthScalerForPerspective=50,this._linesPositions=[],this._linesNormals=[],this._linesIndices=[],this._buffers={},this._buffersForInstances={},this._checkVerticesInsteadOfIndices=!1,this.isEnabled=!0,this.customInstances=new nL.t(32),this._source=e,this._checkVerticesInsteadOfIndices=i,this._options=null!=s?s:null,this._epsilon=t,this._source.getScene().getEngine().isWebGPU&&(this._drawWrapper=new nk.q(e.getEngine())),this._prepareRessources(),r&&(null===(n=null==s?void 0:s.useAlternateEdgeFinder)||void 0===n||n?this._generateEdgesLinesAlternate():this._generateEdgesLines()),this._meshRebuildObserver=this._source.onRebuildObservable.add(()=>{this._rebuild()}),this._meshDisposeObserver=this._source.onDisposeObservable.add(()=>{this.dispose()})}_prepareRessources(){this._lineShader||(this._lineShader=Tj._GetShader(this._source.getScene()))}_rebuild(){let e=this._buffers[sm.o.PositionKind];e&&e._rebuild(),(e=this._buffers[sm.o.NormalKind])&&e._rebuild();let t=this._source.getScene().getEngine();this._ib=t.createIndexBuffer(this._linesIndices)}dispose(){var e;this._source.onRebuildObservable.remove(this._meshRebuildObserver),this._source.onDisposeObservable.remove(this._meshDisposeObserver);let t=this._buffers[sm.o.PositionKind];t&&(t.dispose(),this._buffers[sm.o.PositionKind]=null),(t=this._buffers[sm.o.NormalKind])&&(t.dispose(),this._buffers[sm.o.NormalKind]=null),this._ib&&this._source.getScene().getEngine()._releaseBuffer(this._ib),this._lineShader.dispose(),null===(e=this._drawWrapper)||void 0===e||e.dispose()}_processEdgeForAdjacencies(e,t,i,r,s){return e===i&&t===r||e===r&&t===i?0:e===r&&t===s||e===s&&t===r?1:e===s&&t===i||e===i&&t===s?2:-1}_processEdgeForAdjacenciesWithVertices(e,t,i,r,s){return e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(r,1e-10)||e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(i,1e-10)?0:e.equalsWithEpsilon(r,1e-10)&&t.equalsWithEpsilon(s,1e-10)||e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(r,1e-10)?1:e.equalsWithEpsilon(s,1e-10)&&t.equalsWithEpsilon(i,1e-10)||e.equalsWithEpsilon(i,1e-10)&&t.equalsWithEpsilon(s,1e-10)?2:-1}_checkEdge(e,t,i,r,s){(void 0===t||rf.P.Dot(i[e],i[t]){i>=0&&t.push(i);for(let i=0;i=e[0].length&&e[1].length>=e[2].length?n=1:e[2].length>=e[0].length&&e[2].length>=e[1].length&&(n=2);for(let t=0;t<3;++t)t===n?e[t].sort((e,t)=>e[1]t[1]?1:0):e[t].sort((e,t)=>e[1]>t[1]?-1:e[1]=n+1;--a)s(e[a%3],o,a!==n+2?r[i[t+(a+1)%3]]:-1);let h=o.length;i.push(r[i[t+n]],a[0],o[0]),i.push(r[i[t+(n+1)%3]],o[h-1],a[l-1]);let u=l<=h,c=u?l:h,d=u?h:l,p=u?l-1:h-1,_=u?0:1,f=l+h-2,m=0,g=0,v=u?a:o,x=u?o:a,T=0;for(;f-- >0;){let e;_?i.push(v[m],x[g]):i.push(x[g],v[m]),(T+=c)>=d&&ms){let e=r;r=s,s=e}let a=r+"_"+s,o=m[a];o?o.done||(rf.P.Dot(t,o.normal)0||this._source.hasThinInstances)}render(){let e=this._source.getScene(),t=this._lineShader._getDrawWrapper();if(this._drawWrapper&&this._lineShader._setDrawWrapper(this._drawWrapper),!this.isReady()||!e.activeCamera){this._lineShader._setDrawWrapper(t);return}let i=this._source.hasInstances&&this.customInstances.length>0,r=i||this._source.hasThinInstances,s=0;if(r){if(this._buffersForInstances.world0=this._source.getVertexBuffer("world0"),this._buffersForInstances.world1=this._source.getVertexBuffer("world1"),this._buffersForInstances.world2=this._source.getVertexBuffer("world2"),this._buffersForInstances.world3=this._source.getVertexBuffer("world3"),i){let e=this._source._instanceDataStorage;if(s=this.customInstances.length,!e.instancesData){this._source.getScene()._activeMeshesFrozen||this.customInstances.reset();return}if(!e.isFrozen){let t=0;for(let i=0;i0&&(this._useSpecificClearForDepthTexture&&5===this._mrtLayout[s]?(t.push(!1),i.push(!0)):(t.push(!0),i.push(!1)),r.push(!1));this._multiRenderAttachments=this._engine.buildTextureLayout(e),this._clearAttachments=this._engine.buildTextureLayout(t),this._clearDepthAttachments=this._engine.buildTextureLayout(i),this._defaultAttachments=this._engine.buildTextureLayout(r)}_resetLayout(){for(let e=0;enull!=e),this._scene.autoClear=!0;let r=this._hasImageProcessing(this._postProcessesSourceForThisPass);this._needsCompositionForThisPass=!r&&!this.disableGammaTransform&&this._needsImageProcessing()&&!i;let s=this._getFirstPostProcess(this._postProcessesSourceForThisPass),n=e._beforeCompositionPostProcesses&&e._beforeCompositionPostProcesses[0],a=null;this._scene.imageProcessingConfiguration.applyByPostProcess=this._needsCompositionForThisPass||r,this._needsCompositionForThisPass&&!e.imageProcessingPostProcess&&e._createCompositionEffect(),n?a=n:this._needsCompositionForThisPass?a=e.imageProcessingPostProcess:s&&(a=s),this._bindFrameBuffer(),this._linkInternalTexture(e,a)}_linkInternalTexture(e,t){t&&(t.autoClear=!1,t.inputTexture=e.renderTarget),e._outputPostProcess!==t&&(e._outputPostProcess&&this._unlinkInternalTexture(e),e._outputPostProcess=t),e._internalTextureDirty&&(this._updateGeometryBufferLayout(),e._internalTextureDirty=!1)}_unlinkInternalTexture(e){e._outputPostProcess&&(e._outputPostProcess.autoClear=!0,e._outputPostProcess.restoreDefaultInputTexture(),e._outputPostProcess=null)}_needsImageProcessing(){for(let e=0;enull!=e))){for(let r=0;r=0;e--)this.renderTargets[e].dispose();for(let e=0;e{throw(0,sM.S)("PrePassRendererSceneComponent")},T$.TextureFormats=[{purpose:0,type:2,format:5,name:"prePass_Irradiance"},{purpose:1,type:2,format:5,name:"prePass_Position"},{purpose:2,type:0,format:5,name:"prePass_Velocity"},{purpose:3,type:0,format:5,name:"prePass_Reflectivity"},{purpose:4,type:2,format:5,name:"prePass_Color"},{purpose:5,type:1,format:6,name:"prePass_Depth"},{purpose:6,type:2,format:5,name:"prePass_Normal"},{purpose:7,type:0,format:5,name:"prePass_Albedo"}],Object.defineProperty(r2.x.prototype,"prePassRenderer",{get:function(){return this._prePassRenderer},set:function(e){e&&e.isSupported&&(this._prePassRenderer=e)},enumerable:!0,configurable:!0}),r2.x.prototype.enablePrePassRenderer=function(){return this._prePassRenderer||(this._prePassRenderer=new T$(this),this._prePassRenderer.isSupported||(this._prePassRenderer=null,rb.Y.Error("PrePassRenderer needs WebGL 2 support.\nMaybe you tried to use the following features that need the PrePassRenderer :\n + Subsurface Scattering"))),this._prePassRenderer},r2.x.prototype.disablePrePassRenderer=function(){this._prePassRenderer&&(this._prePassRenderer.dispose(),this._prePassRenderer=null)};class TQ{constructor(e){this.name=sN.l.NAME_PREPASSRENDERER,this.scene=e}register(){this.scene._beforeCameraDrawStage.registerStep(sN.l.STEP_BEFORECAMERADRAW_PREPASS,this,this._beforeCameraDraw),this.scene._afterCameraDrawStage.registerStep(sN.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterCameraDraw),this.scene._beforeRenderTargetDrawStage.registerStep(sN.l.STEP_BEFORERENDERTARGETDRAW_PREPASS,this,this._beforeRenderTargetDraw),this.scene._afterRenderTargetDrawStage.registerStep(sN.l.STEP_AFTERCAMERADRAW_PREPASS,this,this._afterRenderTargetDraw),this.scene._beforeClearStage.registerStep(sN.l.STEP_BEFORECLEAR_PREPASS,this,this._beforeClearStage),this.scene._beforeRenderTargetClearStage.registerStep(sN.l.STEP_BEFORERENDERTARGETCLEAR_PREPASS,this,this._beforeRenderTargetClearStage),this.scene._beforeRenderingMeshStage.registerStep(sN.l.STEP_BEFORERENDERINGMESH_PREPASS,this,this._beforeRenderingMeshStage),this.scene._afterRenderingMeshStage.registerStep(sN.l.STEP_AFTERRENDERINGMESH_PREPASS,this,this._afterRenderingMeshStage)}_beforeRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._beforeDraw(void 0,t,i))}_afterRenderTargetDraw(e,t,i){this.scene.prePassRenderer&&!e.noPrePassRenderer&&this.scene.prePassRenderer._afterDraw(t,i)}_beforeRenderTargetClearStage(e){this.scene.prePassRenderer&&!e.noPrePassRenderer&&(e._prePassRenderTarget||(e._prePassRenderTarget=this.scene.prePassRenderer._createRenderTarget(e.name+"_prePassRTT",e)),this.scene.prePassRenderer._setRenderTarget(e._prePassRenderTarget),this.scene.prePassRenderer._clear())}_beforeCameraDraw(e){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._beforeDraw(e))}_afterCameraDraw(){this.scene.prePassRenderer&&this.scene.prePassRenderer._afterDraw()}_beforeClearStage(){this.scene.prePassRenderer&&(this.scene.prePassRenderer._setRenderTarget(null),this.scene.prePassRenderer._clear())}_beforeRenderingMeshStage(e,t,i,r){if(!r)return;let s=e.getScene();s.prePassRenderer&&s.prePassRenderer.bindAttachmentsForEffect(r,t)}_afterRenderingMeshStage(e){let t=e.getScene();t.prePassRenderer&&t.prePassRenderer.restoreAttachments()}rebuild(){this.scene.disablePrePassRenderer(),this.scene.enablePrePassRenderer()}dispose(){this.scene.disablePrePassRenderer()}}T$._SceneComponentInitialization=e=>{let t=e._getComponent(sN.l.NAME_PREPASSRENDERER);t||(t=new TQ(e),e._addComponent(t))};let TZ=`#define rcp(x) 1./x +#define GOLDEN_RATIO 1.618033988749895 +#define TWO_PI 6.2831855 +vec2 Golden2dSeq(int i,float n) +{return vec2(float(i)/n+(0.5/n),fract(float(i)*rcp(GOLDEN_RATIO)));} +vec2 SampleDiskGolden(int i,int sampleCount) +{vec2 f=Golden2dSeq(i,float(sampleCount));return vec2(sqrt(f.x),TWO_PI*f.y);}`;nw.v.IncludesShadersStore.fibonacci=TZ,nw.v.IncludesShadersStore.diffusionProfile="uniform vec3 diffusionS[5];uniform float diffusionD[5];uniform float filterRadii[5];";let TJ=`#include +#include +#include +#include +varying vec2 vUV;uniform vec2 texelSize;uniform sampler2D textureSampler;uniform sampler2D irradianceSampler;uniform sampler2D depthSampler;uniform sampler2D albedoSampler;uniform vec2 viewportSize;uniform float metersPerUnit;const float LOG2_E=1.4426950408889634;const float SSS_PIXELS_PER_SAMPLE=4.;const int _SssSampleBudget=40; +#define rcp(x) 1./x +#define Sq(x) x*x +#define SSS_BILATERAL_FILTER true +vec3 EvalBurleyDiffusionProfile(float r,vec3 S) +{vec3 exp_13=exp2(((LOG2_E*(-1.0/3.0))*r)*S); +vec3 expSum=exp_13*(1.+exp_13*exp_13); +return (S*rcp(8.*PI))*expSum; } +vec2 SampleBurleyDiffusionProfile(float u,float rcpS) +{u=1.-u; +float g=1.+(4.*u)*(2.*u+sqrt(1.+(4.*u)*u));float n=exp2(log2(g)*(-1.0/3.0)); +float p=(g*n)*n; +float c=1.+p+n; +float d=(3./LOG2_E*2.)+(3./LOG2_E)*log2(u); +float x=(3./LOG2_E)*log2(c)-d; +float rcpExp=((c*c)*c)*rcp((4.*u)*((c*c)+(4.*u)*(4.*u)));float r=x*rcpS;float rcpPdf=(8.*PI*rcpS)*rcpExp; +return vec2(r,rcpPdf);} +vec3 ComputeBilateralWeight(float xy2,float z,float mmPerUnit,vec3 S,float rcpPdf) +{ +#ifndef SSS_BILATERAL_FILTER +z=0.; +#endif +float r=sqrt(xy2+(z*mmPerUnit)*(z*mmPerUnit));float area=rcpPdf; +#if SSS_CLAMP_ARTIFACT +return clamp(EvalBurleyDiffusionProfile(r,S)*area,0.0,1.0); +#else +return EvalBurleyDiffusionProfile(r,S)*area; +#endif +} +void EvaluateSample(int i,int n,vec3 S,float d,vec3 centerPosVS,float mmPerUnit,float pixelsPerMm, +float phase,inout vec3 totalIrradiance,inout vec3 totalWeight) +{float scale =rcp(float(n));float offset=rcp(float(n))*0.5;float sinPhase,cosPhase;sinPhase=sin(phase);cosPhase=cos(phase);vec2 bdp=SampleBurleyDiffusionProfile(float(i)*scale+offset,d);float r=bdp.x;float rcpPdf=bdp.y;float phi=SampleDiskGolden(i,n).y;float sinPhi,cosPhi;sinPhi=sin(phi);cosPhi=cos(phi);float sinPsi=cosPhase*sinPhi+sinPhase*cosPhi; +float cosPsi=cosPhase*cosPhi-sinPhase*sinPhi; +vec2 vec=r*vec2(cosPsi,sinPsi);vec2 position; +float xy2;position=vUV+round((pixelsPerMm*r)*vec2(cosPsi,sinPsi))*texelSize;xy2 =r*r;vec4 textureSample=texture2D(irradianceSampler,position);float viewZ=texture2D(depthSampler,position).r;vec3 irradiance =textureSample.rgb;if (testLightingForSSS(textureSample.a)) +{float relZ=viewZ-centerPosVS.z;vec3 weight=ComputeBilateralWeight(xy2,relZ,mmPerUnit,S,rcpPdf);totalIrradiance+=weight*irradiance;totalWeight +=weight;} +else +{}} +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) +{vec4 irradianceAndDiffusionProfile =texture2D(irradianceSampler,vUV);vec3 centerIrradiance=irradianceAndDiffusionProfile.rgb;int diffusionProfileIndex=int(round(irradianceAndDiffusionProfile.a*255.));float centerDepth =0.;vec4 inputColor=texture2D(textureSampler,vUV);bool passedStencilTest=testLightingForSSS(irradianceAndDiffusionProfile.a);if (passedStencilTest) +{centerDepth=texture2D(depthSampler,vUV).r;} +if (!passedStencilTest) { +gl_FragColor=inputColor;return;} +float distScale =1.;vec3 S =diffusionS[diffusionProfileIndex];float d =diffusionD[diffusionProfileIndex];float filterRadius=filterRadii[diffusionProfileIndex];vec2 centerPosNDC=vUV;vec2 cornerPosNDC=vUV+0.5*texelSize;vec3 centerPosVS =vec3(centerPosNDC*viewportSize,1.0)*centerDepth; +vec3 cornerPosVS =vec3(cornerPosNDC*viewportSize,1.0)*centerDepth; +float mmPerUnit =1000.*(metersPerUnit*rcp(distScale));float unitsPerMm=rcp(mmPerUnit);float unitsPerPixel=2.*abs(cornerPosVS.x-centerPosVS.x);float pixelsPerMm =rcp(unitsPerPixel)*unitsPerMm;float filterArea =PI*Sq(filterRadius*pixelsPerMm);int sampleCount =int(filterArea*rcp(SSS_PIXELS_PER_SAMPLE));int sampleBudget=_SssSampleBudget;int texturingMode=0;vec3 albedo =texture2D(albedoSampler,vUV).rgb;if (distScale==0. || sampleCount<1) +{ +#ifdef DEBUG_SSS_SAMPLES +vec3 green=vec3(0.,1.,0.);gl_FragColor=vec4(green,1.0);return; +#endif +gl_FragColor=vec4(inputColor.rgb+albedo*centerIrradiance,1.0);return;} +#ifdef DEBUG_SSS_SAMPLES +vec3 red =vec3(1.,0.,0.);vec3 blue=vec3(0.,0.,1.);gl_FragColor=vec4(mix(blue,red,clamp(float(sampleCount)/float(sampleBudget),0.0,1.0)),1.0);return; +#endif +float phase=0.;int n=min(sampleCount,sampleBudget);vec3 centerWeight =vec3(0.); +vec3 totalIrradiance=vec3(0.);vec3 totalWeight =vec3(0.);for (int i=0; i{if(!t.prePassRenderer||!t.subSurfaceConfiguration){rb.Y.Error("PrePass and subsurface configuration needs to be enabled for subsurface scattering.");return}let i=this.texelSize;e.setFloat("metersPerUnit",t.subSurfaceConfiguration.metersPerUnit),e.setFloat2("texelSize",i.x,i.y),e.setTexture("irradianceSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(0)]),e.setTexture("depthSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(5)]),e.setTexture("albedoSampler",t.prePassRenderer.getRenderTarget().textures[t.prePassRenderer.getIndex(7)]),e.setFloat2("viewportSize",Math.tan(t.activeCamera.fov/2)*t.getEngine().getAspectRatio(t.activeCamera,!0),Math.tan(t.activeCamera.fov/2)),e.setArray3("diffusionS",t.subSurfaceConfiguration.ssDiffusionS),e.setArray("diffusionD",t.subSurfaceConfiguration.ssDiffusionD),e.setArray("filterRadii",t.subSurfaceConfiguration.ssFilterRadii)})}}class T1{get ssDiffusionS(){return this._ssDiffusionS}get ssDiffusionD(){return this._ssDiffusionD}get ssFilterRadii(){return this._ssFilterRadii}constructor(e){this._ssDiffusionS=[],this._ssFilterRadii=[],this._ssDiffusionD=[],this.enabled=!1,this.needsImageProcessing=!0,this.name=sN.l.NAME_SUBSURFACE,this.ssDiffusionProfileColors=[],this.metersPerUnit=1,this.texturesRequired=[5,7,4,0],this.addDiffusionProfile(new rm.Wo(1,1,1)),this._scene=e,T1._SceneComponentInitialization(this._scene)}addDiffusionProfile(e){if(this.ssDiffusionD.length>=5)return rb.Y.Error("You already reached the maximum number of diffusion profiles."),0;for(let t=0;t{throw(0,sM.S)("SubSurfaceSceneComponent")},rd.p.AddParser(sN.l.NAME_SUBSURFACE,(e,t)=>{if(void 0!==e.ssDiffusionProfileColors&&null!==e.ssDiffusionProfileColors&&(t.enableSubSurfaceForPrePass(),t.subSurfaceConfiguration))for(let i=0,r=e.ssDiffusionProfileColors.length;i{let t=e._getComponent(sN.l.NAME_SUBSURFACE);t||(t=new T2(e),e._addComponent(t))};let T3=`#ifdef LOGARITHMICDEPTH +#extension GL_EXT_frag_depth : enable +#endif +uniform vec4 color; +#ifdef ALPHATEST +varying vec2 vUV;uniform sampler2D diffuseSampler; +#endif +#include +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#include +#ifdef ALPHATEST +if (texture2D(diffuseSampler,vUV).a<0.4) +discard; +#endif +#include +gl_FragColor=color; +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.outlinePixelShader=T3;let T4=`attribute vec3 position;attribute vec3 normal; +#include +#include +#include +#include[0..maxSimultaneousMorphTargets] +#include +uniform float offset; +#include +uniform mat4 viewProjection; +#ifdef ALPHATEST +varying vec2 vUV;uniform mat4 diffuseMatrix; +#ifdef UV1 +attribute vec2 uv; +#endif +#ifdef UV2 +attribute vec2 uv2; +#endif +#endif +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) +{vec3 positionUpdated=position;vec3 normalUpdated=normal; +#ifdef UV1 +vec2 uvUpdated=uv; +#endif +#include +#include[0..maxSimultaneousMorphTargets] +vec3 offsetPosition=positionUpdated+(normalUpdated*offset); +#include +#include +#include +vec4 worldPos=finalWorld*vec4(offsetPosition,1.0);gl_Position=viewProjection*worldPos; +#ifdef ALPHATEST +#ifdef UV1 +vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); +#endif +#ifdef UV2 +vUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0)); +#endif +#endif +#include +#include +} +`;nw.v.ShadersStore.outlineVertexShader=T4,r2.x.prototype.getOutlineRenderer=function(){return this._outlineRenderer||(this._outlineRenderer=new T5(this)),this._outlineRenderer},Object.defineProperty(sp.Kj.prototype,"renderOutline",{get:function(){return this._renderOutline},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOutline=e},enumerable:!0,configurable:!0}),Object.defineProperty(sp.Kj.prototype,"renderOverlay",{get:function(){return this._renderOverlay},set:function(e){e&&this.getScene().getOutlineRenderer(),this._renderOverlay=e},enumerable:!0,configurable:!0});class T5{constructor(e){this.name=sN.l.NAME_OUTLINERENDERER,this.zOffset=1,this.zOffsetUnits=4,this.scene=e,this._engine=e.getEngine(),this.scene._addComponent(this),this._passIdForDrawWrapper=[];for(let e=0;e<4;++e)this._passIdForDrawWrapper[e]=this._engine.createRenderPassId(`Outline Renderer (${e})`)}register(){this.scene._beforeRenderingMeshStage.registerStep(sN.l.STEP_BEFORERENDERINGMESH_OUTLINE,this,this._beforeRenderingMesh),this.scene._afterRenderingMeshStage.registerStep(sN.l.STEP_AFTERRENDERINGMESH_OUTLINE,this,this._afterRenderingMesh)}rebuild(){}dispose(){for(let e=0;e{p.setMatrix("world",t)}),n.setZOffset(0),n.setZOffsetUnits(0)}isReady(e,t,i){i=null!=i?i:this._passIdForDrawWrapper[0];let r=[],s=[sm.o.PositionKind,sm.o.NormalKind],n=e.getMesh(),a=e.getMaterial();if(!a)return!1;let o=n.getScene();a.needAlphaTesting()&&(r.push("#define ALPHATEST"),n.isVerticesDataPresent(sm.o.UVKind)&&(s.push(sm.o.UVKind),r.push("#define UV1")),n.isVerticesDataPresent(sm.o.UV2Kind)&&(s.push(sm.o.UV2Kind),r.push("#define UV2"))),a.useLogarithmicDepth&&r.push("#define LOGARITHMICDEPTH"),(0,lH.lK)(a,o,r),n.useBones&&n.computeBonesUsingShaders?(s.push(sm.o.MatricesIndicesKind),s.push(sm.o.MatricesWeightsKind),n.numBoneInfluencers>4&&(s.push(sm.o.MatricesIndicesExtraKind),s.push(sm.o.MatricesWeightsExtraKind)),r.push("#define NUM_BONE_INFLUENCERS "+n.numBoneInfluencers),r.push("#define BonesPerMesh "+(n.skeleton?n.skeleton.bones.length+1:0))):r.push("#define NUM_BONE_INFLUENCERS 0");let l=n.morphTargetManager,h=0;l&&l.numInfluencers>0&&(h=l.numInfluencers,r.push("#define MORPHTARGETS"),r.push("#define NUM_MORPH_INFLUENCERS "+h),l.isUsingTextureForTargets&&r.push("#define MORPHTARGETS_TEXTURE"),nE.G.PrepareAttributesForMorphTargetsInfluencers(s,n,h)),t&&(r.push("#define INSTANCES"),nE.G.PushAttributesForInstances(s),e.getRenderingMesh().hasThinInstances&&r.push("#define THIN_INSTANCES"));let u=e._getDrawWrapper(i,!0),c=u.defines,d=r.join("\n");if(c!==d){let e=["world","mBones","viewProjection","diffuseMatrix","offset","color","logarithmicDepthConstant","morphTargetInfluences","morphTargetTextureInfo","morphTargetTextureIndices"];(0,lH.qx)(e),u.setEffect(this.scene.getEngine().createEffect("outline",s,e,["diffuseSampler","morphTargets"],d,void 0,void 0,void 0,{maxSimultaneousMorphTargets:h}),d)}return u.effect.isReady()}_beforeRenderingMesh(e,t,i){if(this._savedDepthWrite=this._engine.getDepthWrite(),e.renderOutline){let r=t.getMaterial();r&&r.needAlphaBlendingForMesh(e)&&(this._engine.cacheStencilState(),this._engine.setDepthWrite(!1),this._engine.setColorWrite(!1),this._engine.setStencilBuffer(!0),this._engine.setStencilOperationPass(7681),this._engine.setStencilFunction(519),this._engine.setStencilMask(T5._StencilReference),this._engine.setStencilFunctionReference(T5._StencilReference),this._engine.stencilStateComposer.useStencilGlobalOnly=!0,this.render(t,i,!0,this._passIdForDrawWrapper[1]),this._engine.setColorWrite(!0),this._engine.setStencilFunction(517)),this._engine.setDepthWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[0]),this._engine.setDepthWrite(this._savedDepthWrite),r&&r.needAlphaBlendingForMesh(e)&&(this._engine.stencilStateComposer.useStencilGlobalOnly=!1,this._engine.restoreStencilState())}}_afterRenderingMesh(e,t,i){if(e.renderOverlay){let e=this._engine.getAlphaMode(),r=this._engine.alphaState.alphaBlend;this._engine.setAlphaMode(2),this.render(t,i,!0,this._passIdForDrawWrapper[3]),this._engine.setAlphaMode(e),this._engine.setDepthWrite(this._savedDepthWrite),this._engine.alphaState.alphaBlend=r}e.renderOutline&&this._savedDepthWrite&&(this._engine.setDepthWrite(!0),this._engine.setColorWrite(!1),this.render(t,i,!1,this._passIdForDrawWrapper[2]),this._engine.setColorWrite(!0))}}T5._StencilReference=4,i(7254);class T6{get particleSize(){return this._particleSize}set particleSize(e){e!==this._particleSize&&(this._particleSize=e,this.onParticleSizeChanged.notifyObservers(this))}get useInstancing(){return!this.indexBuffer}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&this._hasVelocity()&&(this._useVelocity=e,this._effectsAreDirty=!0)}_hasVelocity(){var e;return!!(null===(e=this.vertexBuffers)||void 0===e?void 0:e.velocity)}get indexBuffer(){return null}getClassName(){return"FluidRenderingObject"}constructor(e){this.priority=0,this._particleSize=.1,this.onParticleSizeChanged=new r_.y$,this.particleThicknessAlpha=.05,this._useVelocity=!1,this._scene=e,this._engine=e.getEngine(),this._effectsAreDirty=!0,this._depthEffectWrapper=null,this._thicknessEffectWrapper=null}_createEffects(){let e=["view","projection","particleRadius","size"],t=["position","offset"],i=[];this._effectsAreDirty=!1,this.useVelocity&&(t.push("velocity"),i.push("#define FLUIDRENDERING_VELOCITY")),this._scene.useRightHandedSystem&&i.push("#define FLUIDRENDERING_RHS"),this._depthEffectWrapper=new n9({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDepth",fragmentShader:"fluidRenderingParticleDepth",attributeNames:t,uniformNames:e,samplerNames:[],defines:i}),e.push("particleAlpha"),this._thicknessEffectWrapper=new n9({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleThickness",fragmentShader:"fluidRenderingParticleThickness",attributeNames:["position","offset"],uniformNames:e,samplerNames:[]})}isReady(){if(this._effectsAreDirty&&this._createEffects(),!this._depthEffectWrapper||!this._thicknessEffectWrapper)return!1;let e=this._depthEffectWrapper._drawWrapper.effect,t=this._thicknessEffectWrapper._drawWrapper.effect;return e.isReady()&&t.isReady()}renderDepthTexture(){let e=this.numParticles;if(!this._depthEffectWrapper||0===e)return;let t=this._depthEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat2("size",this._particleSize,this._particleSize),i.setFloat("particleRadius",this._particleSize/2),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}renderThicknessTexture(){let e=this.numParticles;if(!this._thicknessEffectWrapper||0===e)return;let t=this._thicknessEffectWrapper._drawWrapper,i=t.effect;this._engine.setAlphaMode(6),this._engine.setDepthWrite(!1),this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),i.setFloat("particleAlpha",this.particleThicknessAlpha),i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0)}renderDiffuseTexture(){}dispose(){var e,t;null===(e=this._depthEffectWrapper)||void 0===e||e.dispose(),null===(t=this._thicknessEffectWrapper)||void 0===t||t.dispose()}}class T8 extends T6{get particleSystem(){return this._particleSystem}getClassName(){return"FluidRenderingObjectParticleSystem"}get useTrueRenderingForDiffuseTexture(){return this._useTrueRenderingForDiffuseTexture}set useTrueRenderingForDiffuseTexture(e){this._useTrueRenderingForDiffuseTexture!==e&&(this._useTrueRenderingForDiffuseTexture=e,e?(this._particleSystem.blendMode=this._blendMode,this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null):(this._particleSystem.blendMode=-1,this._onBeforeDrawParticleObserver=this._particleSystem.onBeforeDrawParticlesObservable.add(()=>{this._engine.setAlphaMode(2)})))}get vertexBuffers(){return this._particleSystem.vertexBuffers}get indexBuffer(){return this._particleSystem.indexBuffer}constructor(e,t){super(e),this._useTrueRenderingForDiffuseTexture=!0,this._particleSystem=t,this._originalRender=t.render.bind(t),this._blendMode=t.blendMode,this._onBeforeDrawParticleObserver=null,this._updateInAnimate=this._particleSystem.updateInAnimate,this._particleSystem.updateInAnimate=!0,this._particleSystem.render=()=>0,this.particleSize=(t.minSize+t.maxSize)/2,this.useTrueRenderingForDiffuseTexture=!1}isReady(){return super.isReady()&&this._particleSystem.isReady()}get numParticles(){return this._particleSystem.getActiveCount()}renderDiffuseTexture(){this._originalRender()}dispose(){super.dispose(),this._particleSystem.onBeforeDrawParticlesObservable.remove(this._onBeforeDrawParticleObserver),this._onBeforeDrawParticleObserver=null,this._particleSystem.render=this._originalRender,this._particleSystem.blendMode=this._blendMode,this._particleSystem.updateInAnimate=this._updateInAnimate}}class T7{get blurNumIterations(){return this._blurNumIterations}set blurNumIterations(e){if(this._blurNumIterations!==e&&(this._blurNumIterations=e,null!==this._blurPostProcesses)){let e=this._blurPostProcesses[0],t=this._blurPostProcesses[1];this._blurPostProcesses=[];for(let i=0;i<2*this._blurNumIterations;++i)this._blurPostProcesses[i]=1&i?t:e}}get renderTarget(){return this._rt}get renderTargetBlur(){return this._rtBlur}get texture(){return this._texture}get textureBlur(){return this._textureBlurred}constructor(e,t,i,r,s,n,a=1,o=6,l=1,h=6,u=!1,c=null,d=!0,p=1){this.enableBlur=!0,this.blurSizeDivisor=1,this.blurFilterSize=7,this._blurNumIterations=3,this.blurMaxFilterSize=100,this.blurDepthScale=10,this.particleSize=.02,this.onDisposeObservable=new r_.y$,this._name=e,this._scene=t,this._camera=c,this._engine=t.getEngine(),this._width=i,this._height=r,this._blurTextureSizeX=s,this._blurTextureSizeY=n,this._textureType=a,this._textureFormat=o,this._blurTextureType=l,this._blurTextureFormat=h,this._useStandardBlur=u,this._generateDepthBuffer=d,this._samples=p,this._postProcessRunningIndex=0,this.enableBlur=0!==s&&0!==n,this._rt=null,this._texture=null,this._rtBlur=null,this._textureBlurred=null,this._blurPostProcesses=null}initialize(){if(this.dispose(),this._createRenderTarget(),this.enableBlur&&this._texture){let[e,t,i]=this._createBlurPostProcesses(this._texture,this._blurTextureType,this._blurTextureFormat,this.blurSizeDivisor,this._name,this._useStandardBlur);this._rtBlur=e,this._textureBlurred=t,this._blurPostProcesses=i}}applyBlurPostProcesses(){this.enableBlur&&this._blurPostProcesses&&(this._postProcessRunningIndex=0,this._scene.postProcessManager.directRender(this._blurPostProcesses,this._rtBlur,!0),this._engine.unBindFramebuffer(this._rtBlur))}_createRenderTarget(){this._rt=this._engine.createRenderTargetTexture({width:this._width,height:this._height},{generateMipMaps:!1,type:this._textureType,format:this._textureFormat,samplingMode:1,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTT-${this._name}`});let e=this._rt.texture;e.incrementReferences(),this._texture=new sj(null,this._scene),this._texture.name="rtt"+this._name,this._texture._texture=e,this._texture.wrapU=sj.CLAMP_ADDRESSMODE,this._texture.wrapV=sj.CLAMP_ADDRESSMODE,this._texture.anisotropicFilteringLevel=1}_createBlurPostProcesses(e,t,i,r,s,n=!1){let a=this._scene.getEngine(),o=new rf.FM(Math.floor(this._blurTextureSizeX/r),Math.floor(this._blurTextureSizeY/r)),l=1===t&&a.getCaps().textureFloatLinearFiltering||2===t&&a.getCaps().textureHalfFloatLinearFiltering,h=this._engine.createRenderTargetTexture({width:o.x,height:o.y},{generateMipMaps:!1,type:t,format:i,samplingMode:l?2:1,generateDepthBuffer:!1,generateStencilBuffer:!1,samples:this._samples,label:`FluidRenderingRTTBlur-${s}`}),u=h.texture;u.incrementReferences();let c=new sj(null,this._scene);if(c.name="rttBlurred"+s,c._texture=u,c.wrapU=sj.CLAMP_ADDRESSMODE,c.wrapV=sj.CLAMP_ADDRESSMODE,c.anisotropicFilteringLevel=1,n){let r=new nz("BilateralBlurX","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);r.samples=this._samples,r.externalTextureSamplerBinding=!0,r.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",r.inputTexture.texture),t.setInt("filterSize",this.blurFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),this._postProcessRunningIndex++}),r.onSizeChangedObservable.add(()=>{r._textures.forEach(e=>{e.texture.wrapU=sj.CLAMP_ADDRESSMODE,e.texture.wrapV=sj.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(r);let s=new nz("BilateralBlurY","fluidRenderingStandardBlur",["filterSize","blurDir"],null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.onApplyObservable.add(e=>{e.setInt("filterSize",this.blurFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),this._postProcessRunningIndex++}),s.onSizeChangedObservable.add(()=>{s._textures.forEach(e=>{e.texture.wrapU=sj.CLAMP_ADDRESSMODE,e.texture.wrapV=sj.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s),r.autoClear=!1,s.autoClear=!1;let n=[];for(let e=0;e<2*this._blurNumIterations;++e)n[e]=1&e?s:r;return[h,c,n]}{let r=["maxFilterSize","blurDir","projectedParticleConstant","depthThreshold"],s=new nz("BilateralBlurX","fluidRenderingBilateralBlur",r,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);s.samples=this._samples,s.externalTextureSamplerBinding=!0,s.onApplyObservable.add(t=>{0===this._postProcessRunningIndex?t.setTexture("textureSampler",e):t._bindTexture("textureSampler",s.inputTexture.texture),t.setInt("maxFilterSize",this.blurMaxFilterSize),t.setFloat2("blurDir",1/this._blurTextureSizeX,0),t.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),t.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),s.onSizeChangedObservable.add(()=>{s._textures.forEach(e=>{e.texture.wrapU=sj.CLAMP_ADDRESSMODE,e.texture.wrapV=sj.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(s);let n=new nz("BilateralBlurY","fluidRenderingBilateralBlur",r,null,1,null,1,a,!0,null,t,void 0,void 0,void 0,i);n.samples=this._samples,n.onApplyObservable.add(e=>{e.setInt("maxFilterSize",this.blurMaxFilterSize),e.setFloat2("blurDir",0,1/this._blurTextureSizeY),e.setFloat("projectedParticleConstant",this._getProjectedParticleConstant()),e.setFloat("depthThreshold",this._getDepthThreshold()),this._postProcessRunningIndex++}),n.onSizeChangedObservable.add(()=>{n._textures.forEach(e=>{e.texture.wrapU=sj.CLAMP_ADDRESSMODE,e.texture.wrapV=sj.CLAMP_ADDRESSMODE})}),this._fixReusablePostProcess(n),s.autoClear=!1,n.autoClear=!1;let o=[];for(let e=0;e<2*this._blurNumIterations;++e)o[e]=1&e?n:s;return[h,c,o]}}_fixReusablePostProcess(e){e.isReusable()&&(e.onActivateObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}),e.onApplyObservable.add(()=>{e._currentRenderTextureInd=(e._currentRenderTextureInd+1)%2}))}_getProjectedParticleConstant(){var e,t;return this.blurFilterSize*this.particleSize*.05*(this._height/2)/Math.tan((null!==(t=null===(e=this._camera)||void 0===e?void 0:e.fov)&&void 0!==t?t:45*Math.PI/180)/2)}_getDepthThreshold(){return this.particleSize/2*this.blurDepthScale}dispose(){var e,t,i,r;this.onDisposeObservable.hasObservers()&&this.onDisposeObservable.notifyObservers(this),null===(e=this._rt)||void 0===e||e.dispose(),this._rt=null,null===(t=this._texture)||void 0===t||t.dispose(),this._texture=null,null===(i=this._rtBlur)||void 0===i||i.dispose(),this._rtBlur=null,null===(r=this._textureBlurred)||void 0===r||r.dispose(),this._textureBlurred=null,this._blurPostProcesses&&(this._blurPostProcesses[0].dispose(),this._blurPostProcesses[1].dispose()),this._blurPostProcesses=null}}(ts=rs||(rs={}))[ts.DepthTexture=0]="DepthTexture",ts[ts.DepthBlurredTexture=1]="DepthBlurredTexture",ts[ts.ThicknessTexture=2]="ThicknessTexture",ts[ts.ThicknessBlurredTexture=3]="ThicknessBlurredTexture",ts[ts.DiffuseTexture=4]="DiffuseTexture",ts[ts.Normals=5]="Normals",ts[ts.DiffuseRendering=6]="DiffuseRendering";class T9{get needInitialization(){return this._needInitialization}get generateDiffuseTexture(){return this._generateDiffuseTexture}set generateDiffuseTexture(e){this._generateDiffuseTexture!==e&&(this._generateDiffuseTexture=e,this._needInitialization=!0)}get debugFeature(){return this._debugFeature}set debugFeature(e){this._debugFeature!==e&&(this._needInitialization=!0,this._debugFeature=e)}get debug(){return this._debug}set debug(e){this._debug!==e&&(this._debug=e,this._needInitialization=!0)}get environmentMap(){return this._environmentMap}set environmentMap(e){this._environmentMap!==e&&(this._needInitialization=!0,this._environmentMap=e)}get enableBlurDepth(){return this._enableBlurDepth}set enableBlurDepth(e){this._enableBlurDepth!==e&&(this._enableBlurDepth=e,this._needInitialization=!0)}get blurDepthSizeDivisor(){return this._blurDepthSizeDivisor}set blurDepthSizeDivisor(e){this._blurDepthSizeDivisor!==e&&(this._blurDepthSizeDivisor=e,this._needInitialization=!0)}get blurDepthFilterSize(){return this._blurDepthFilterSize}set blurDepthFilterSize(e){this._blurDepthFilterSize!==e&&(this._blurDepthFilterSize=e,this._setBlurParameters())}get blurDepthNumIterations(){return this._blurDepthNumIterations}set blurDepthNumIterations(e){this._blurDepthNumIterations!==e&&(this._blurDepthNumIterations=e,this._setBlurParameters())}get blurDepthMaxFilterSize(){return this._blurDepthMaxFilterSize}set blurDepthMaxFilterSize(e){this._blurDepthMaxFilterSize!==e&&(this._blurDepthMaxFilterSize=e,this._setBlurParameters())}get blurDepthDepthScale(){return this._blurDepthDepthScale}set blurDepthDepthScale(e){this._blurDepthDepthScale!==e&&(this._blurDepthDepthScale=e,this._setBlurParameters())}get enableBlurThickness(){return this._enableBlurThickness}set enableBlurThickness(e){this._enableBlurThickness!==e&&(this._enableBlurThickness=e,this._needInitialization=!0)}get blurThicknessSizeDivisor(){return this._blurThicknessSizeDivisor}set blurThicknessSizeDivisor(e){this._blurThicknessSizeDivisor!==e&&(this._blurThicknessSizeDivisor=e,this._needInitialization=!0)}get blurThicknessFilterSize(){return this._blurThicknessFilterSize}set blurThicknessFilterSize(e){this._blurThicknessFilterSize!==e&&(this._blurThicknessFilterSize=e,this._setBlurParameters())}get blurThicknessNumIterations(){return this._blurThicknessNumIterations}set blurThicknessNumIterations(e){this._blurThicknessNumIterations!==e&&(this._blurThicknessNumIterations=e,this._setBlurParameters())}get useFixedThickness(){return this._useFixedThickness}set useFixedThickness(e){this._useFixedThickness!==e&&(this._useFixedThickness=e,this._needInitialization=!0)}get useVelocity(){return this._useVelocity}set useVelocity(e){this._useVelocity!==e&&(this._useVelocity=e,this._needInitialization=!0,this._onUseVelocityChanged.notifyObservers(this))}get depthMapSize(){return this._depthMapSize}set depthMapSize(e){this._depthMapSize!==e&&(this._depthMapSize=e,this._needInitialization=!0)}get thicknessMapSize(){return this._thicknessMapSize}set thicknessMapSize(e){this._thicknessMapSize!==e&&(this._thicknessMapSize=e,this._needInitialization=!0)}get diffuseMapSize(){return this._diffuseMapSize}set diffuseMapSize(e){this._diffuseMapSize!==e&&(this._diffuseMapSize=e,this._needInitialization=!0)}get samples(){return this._samples}set samples(e){this._samples!==e&&(this._samples=e,this._needInitialization=!0)}get camera(){return this._camera}constructor(e,t){this._generateDiffuseTexture=!1,this.fluidColor=new rm.Wo(.085,.6375,.765),this.density=2,this.refractionStrength=.1,this.fresnelClamp=1,this.specularPower=250,this.minimumThickness=0,this.dirLight=new rf.P(-2,-1,1).normalize(),this._debugFeature=rs.DepthBlurredTexture,this._debug=!1,this._enableBlurDepth=!0,this._blurDepthSizeDivisor=1,this._blurDepthFilterSize=7,this._blurDepthNumIterations=3,this._blurDepthMaxFilterSize=100,this._blurDepthDepthScale=10,this._enableBlurThickness=!0,this._blurThicknessSizeDivisor=1,this._blurThicknessFilterSize=5,this._blurThicknessNumIterations=1,this._useFixedThickness=!1,this._onUseVelocityChanged=new r_.y$,this._useVelocity=!1,this._depthMapSize=null,this._thicknessMapSize=null,this._diffuseMapSize=null,this._samples=1,this._scene=e,this._engine=e.getEngine(),this._camera=null!=t?t:e.activeCamera,this._needInitialization=!0,this._bgDepthTexture=null,this._invProjectionMatrix=new rf.y3,this._depthClearColor=new rm.HE(1e6,1e6,1e6,1),this._thicknessClearColor=new rm.HE(0,0,0,1),this._depthRenderTarget=null,this._diffuseRenderTarget=null,this._thicknessRenderTarget=null,this._renderPostProcess=null}_initialize(){var e,t,i;this.dispose(),this._needInitialization=!1;let r=null!==(e=this._depthMapSize)&&void 0!==e?e:this._engine.getRenderWidth(),s=null!==this._depthMapSize?Math.round(this._depthMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();if(this._depthRenderTarget=new T7("Depth",this._scene,r,s,r,s,1,7,1,7,!1,this._camera,!0,this._samples),this._initializeRenderTarget(this._depthRenderTarget),this.generateDiffuseTexture){let e=null!==(t=this._diffuseMapSize)&&void 0!==t?t:this._engine.getRenderWidth(),i=null!==this._diffuseMapSize?Math.round(this._diffuseMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._diffuseRenderTarget=new T7("Diffuse",this._scene,e,i,0,0,0,5,0,5,!0,this._camera,!0,this._samples),this._initializeRenderTarget(this._diffuseRenderTarget)}let n=null!==(i=this._thicknessMapSize)&&void 0!==i?i:this._engine.getRenderWidth(),a=null!==this._thicknessMapSize?Math.round(this._thicknessMapSize*this._engine.getRenderHeight()/this._engine.getRenderWidth()):this._engine.getRenderHeight();this._useFixedThickness||(this._thicknessRenderTarget=new T7("Thickness",this._scene,n,a,n,a,2,6,2,6,!0,this._camera,!1,this._samples),this._initializeRenderTarget(this._thicknessRenderTarget)),this._createLiquidRenderingPostProcess()}_setBlurParameters(e=null){(null===e||e===this._depthRenderTarget)&&this._setBlurDepthParameters(),(null===e||e===this._thicknessRenderTarget)&&this._setBlurThicknessParameters()}_setBlurDepthParameters(){this._depthRenderTarget&&(this._depthRenderTarget.blurFilterSize=this.blurDepthFilterSize,this._depthRenderTarget.blurMaxFilterSize=this.blurDepthMaxFilterSize,this._depthRenderTarget.blurNumIterations=this.blurDepthNumIterations,this._depthRenderTarget.blurDepthScale=this.blurDepthDepthScale)}_setBlurThicknessParameters(){this._thicknessRenderTarget&&(this._thicknessRenderTarget.blurFilterSize=this.blurThicknessFilterSize,this._thicknessRenderTarget.blurNumIterations=this.blurThicknessNumIterations)}_initializeRenderTarget(e){e!==this._diffuseRenderTarget&&(e.enableBlur=e===this._depthRenderTarget?this.enableBlurDepth:this.enableBlurThickness,e.blurSizeDivisor=e===this._depthRenderTarget?this.blurDepthSizeDivisor:this.blurThicknessSizeDivisor),this._setBlurParameters(e),e.initialize()}_createLiquidRenderingPostProcess(){var e;let t=this._scene.getEngine(),i=["viewMatrix","projectionMatrix","invProjectionMatrix","texelSize","dirLight","cameraFar","density","refractionStrength","fresnelClamp","specularPower"],r=["depthSampler"],s=[];if(this.dispose(!0),!this._camera)return;let n=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture,a=new rf.FM(1/n.getSize().width,1/n.getSize().height);this._scene.useRightHandedSystem&&s.push("#define FLUIDRENDERING_RHS"),null!==this._environmentMap&&(null!==(e=this._environmentMap)&&void 0!==e?e:this._scene.environmentTexture)&&(r.push("reflectionSampler"),s.push("#define FLUIDRENDERING_ENVIRONMENT")),this._diffuseRenderTarget?(r.push("diffuseSampler"),s.push("#define FLUIDRENDERING_DIFFUSETEXTURE")):i.push("diffuseColor"),this._useVelocity&&(r.push("velocitySampler"),s.push("#define FLUIDRENDERING_VELOCITY")),this._useFixedThickness?(i.push("thickness"),r.push("bgDepthSampler"),s.push("#define FLUIDRENDERING_FIXED_THICKNESS")):(i.push("minimumThickness"),r.push("thicknessSampler")),this._debug&&(s.push("#define FLUIDRENDERING_DEBUG"),this._debugFeature===rs.Normals?s.push("#define FLUIDRENDERING_DEBUG_SHOWNORMAL"):this._debugFeature===rs.DiffuseRendering?s.push("#define FLUIDRENDERING_DEBUG_DIFFUSERENDERING"):(s.push("#define FLUIDRENDERING_DEBUG_TEXTURE"),r.push("debugSampler"),(this._debugFeature===rs.DepthTexture||this._debugFeature===rs.DepthBlurredTexture)&&s.push("#define FLUIDRENDERING_DEBUG_DEPTH"))),this._renderPostProcess=new nz("FluidRendering","fluidRenderingRender",i,r,1,null,2,t,!1,null,0,void 0,void 0,!0,void 0),this._renderPostProcess.updateEffect(s.join("\n")),this._renderPostProcess.samples=this._samples,this._renderPostProcess.onApplyObservable.add(e=>{var i,r,s,n,o,l,h,u,c,d,p,_,f,m,g,v,x,T,S,E,C,b,y;if(this._invProjectionMatrix.copyFrom(this._scene.getProjectionMatrix()),this._invProjectionMatrix.invert(),t.isWebGPU&&e.setTextureSampler("textureSamplerSampler",this._renderPostProcess.inputTexture.texture),this._depthRenderTarget.enableBlur?(e.setTexture("depthSampler",this._depthRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(n=null===(s=this._depthRenderTarget.textureBlur)||void 0===s?void 0:s.getInternalTexture())&&void 0!==n?n:null)):(e.setTexture("depthSampler",this._depthRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("depthSamplerSampler",null!==(r=null===(i=this._depthRenderTarget.texture)||void 0===i?void 0:i.getInternalTexture())&&void 0!==r?r:null)),this._diffuseRenderTarget?this._diffuseRenderTarget.enableBlur?(e.setTexture("diffuseSampler",this._diffuseRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(u=null===(h=this._diffuseRenderTarget.textureBlur)||void 0===h?void 0:h.getInternalTexture())&&void 0!==u?u:null)):(e.setTexture("diffuseSampler",this._diffuseRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("diffuseSamplerSampler",null!==(l=null===(o=this._diffuseRenderTarget.texture)||void 0===o?void 0:o.getInternalTexture())&&void 0!==l?l:null)):e.setColor3("diffuseColor",this.fluidColor),this._useFixedThickness?(e.setFloat("thickness",this.minimumThickness),e._bindTexture("bgDepthSampler",this._bgDepthTexture),t.isWebGPU&&e.setTextureSampler("bgDepthSamplerSampler",null!==(c=this._bgDepthTexture)&&void 0!==c?c:null)):(this._thicknessRenderTarget.enableBlur?(e.setTexture("thicknessSampler",this._thicknessRenderTarget.textureBlur),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(f=null===(_=this._thicknessRenderTarget.textureBlur)||void 0===_?void 0:_.getInternalTexture())&&void 0!==f?f:null)):(e.setTexture("thicknessSampler",this._thicknessRenderTarget.texture),t.isWebGPU&&e.setTextureSampler("thicknessSamplerSampler",null!==(p=null===(d=this._thicknessRenderTarget.texture)||void 0===d?void 0:d.getInternalTexture())&&void 0!==p?p:null)),e.setFloat("minimumThickness",this.minimumThickness)),null!==this._environmentMap){let i=null!==(m=this._environmentMap)&&void 0!==m?m:this._scene.environmentTexture;i&&(e.setTexture("reflectionSampler",i),t.isWebGPU&&e.setTextureSampler("reflectionSamplerSampler",null!==(g=null==i?void 0:i.getInternalTexture())&&void 0!==g?g:null))}if(e.setMatrix("viewMatrix",this._scene.getViewMatrix()),e.setMatrix("invProjectionMatrix",this._invProjectionMatrix),e.setMatrix("projectionMatrix",this._scene.getProjectionMatrix()),e.setVector2("texelSize",a),e.setFloat("density",this.density),e.setFloat("refractionStrength",this.refractionStrength),e.setFloat("fresnelClamp",this.fresnelClamp),e.setFloat("specularPower",this.specularPower),e.setVector3("dirLight",this.dirLight),e.setFloat("cameraFar",this._camera.maxZ),this._debug){let i=null;switch(this._debugFeature){case rs.DepthTexture:i=this._depthRenderTarget.texture;break;case rs.DepthBlurredTexture:i=this._depthRenderTarget.enableBlur?this._depthRenderTarget.textureBlur:this._depthRenderTarget.texture;break;case rs.ThicknessTexture:i=null!==(x=null===(v=this._thicknessRenderTarget)||void 0===v?void 0:v.texture)&&void 0!==x?x:null;break;case rs.ThicknessBlurredTexture:i=(null===(T=this._thicknessRenderTarget)||void 0===T?void 0:T.enableBlur)?null!==(E=null===(S=this._thicknessRenderTarget)||void 0===S?void 0:S.textureBlur)&&void 0!==E?E:null:null!==(b=null===(C=this._thicknessRenderTarget)||void 0===C?void 0:C.texture)&&void 0!==b?b:null;break;case rs.DiffuseTexture:this._diffuseRenderTarget&&(i=this._diffuseRenderTarget.texture)}this._debugFeature!==rs.Normals&&(e.setTexture("debugSampler",i),t.isWebGPU&&e.setTextureSampler("debugSamplerSampler",null!==(y=null==i?void 0:i.getInternalTexture())&&void 0!==y?y:null))}})}_clearTargets(){var e,t,i;(null===(e=this._depthRenderTarget)||void 0===e?void 0:e.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),this._engine.clear(this._depthClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(t=this._diffuseRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!0,!1),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(i=this._thicknessRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),this._engine.clear(this._thicknessClearColor,!0,!1,!1),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget))}_render(e){var t,i,r,s,n,a;if(this._needInitialization||!e.isReady())return;let o=this._engine._currentRenderTarget;this._engine.setState(!1,void 0,void 0,void 0,!0),this._engine.setDepthBuffer(!0),this._engine.setDepthWrite(!0),this._engine.setAlphaMode(0),(null===(t=this._depthRenderTarget)||void 0===t?void 0:t.renderTarget)&&(this._engine.bindFramebuffer(this._depthRenderTarget.renderTarget),e.renderDepthTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._depthRenderTarget.renderTarget)),(null===(i=this._diffuseRenderTarget)||void 0===i?void 0:i.renderTarget)&&(this._engine.bindFramebuffer(this._diffuseRenderTarget.renderTarget),e.renderDiffuseTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._diffuseRenderTarget.renderTarget)),(null===(r=this._thicknessRenderTarget)||void 0===r?void 0:r.renderTarget)&&(this._engine.bindFramebuffer(this._thicknessRenderTarget.renderTarget),e.renderThicknessTexture(),this._engine.unbindInstanceAttributes(),this._engine.unBindFramebuffer(this._thicknessRenderTarget.renderTarget)),null===(s=this._depthRenderTarget)||void 0===s||s.applyBlurPostProcesses(),null===(n=this._diffuseRenderTarget)||void 0===n||n.applyBlurPostProcesses(),null===(a=this._thicknessRenderTarget)||void 0===a||a.applyBlurPostProcesses(),o&&this._engine.bindFramebuffer(o)}dispose(e=!1){var t,i,r,s;e||(null===(t=this._depthRenderTarget)||void 0===t||t.dispose(),this._depthRenderTarget=null,null===(i=this._diffuseRenderTarget)||void 0===i||i.dispose(),this._diffuseRenderTarget=null,null===(r=this._thicknessRenderTarget)||void 0===r||r.dispose(),this._thicknessRenderTarget=null),this._renderPostProcess&&this._camera&&this._camera.detachPostProcess(this._renderPostProcess),null===(s=this._renderPostProcess)||void 0===s||s.dispose(),this._renderPostProcess=null,this._needInitialization=!1}}class Se extends T6{getClassName(){return"FluidRenderingObjectCustomParticles"}get vertexBuffers(){return this._vertexBuffers}constructor(e,t,i){super(e),this._numParticles=i,this._diffuseEffectWrapper=null,this._vertexBuffers={},this.addBuffers(t)}addBuffers(e){for(let t in e){let i;let r=!0;switch(t){case"velocity":i=3;break;case"offset":r=!1}this._vertexBuffers[t]=new sm.o(this._engine,e[t],t,!0,!1,i,r)}}_createEffects(){super._createEffects(),this._diffuseEffectWrapper=new n9({engine:this._engine,useShaderStore:!0,vertexShader:"fluidRenderingParticleDiffuse",fragmentShader:"fluidRenderingParticleDiffuse",attributeNames:["position","offset","color"],uniformNames:["view","projection","size"],samplerNames:[]})}isReady(){var e,t;return this._vertexBuffers.offset||(this._vertexBuffers.offset=new sm.o(this._engine,[0,0,1,0,0,1,1,1],"offset",!1,!1,2)),super.isReady()&&null!==(t=null===(e=this._diffuseEffectWrapper)||void 0===e?void 0:e.effect.isReady())&&void 0!==t&&t}get numParticles(){return this._numParticles}setNumParticles(e){this._numParticles=e}renderDiffuseTexture(){let e=this.numParticles;if(!this._diffuseEffectWrapper||0===e)return;let t=this._diffuseEffectWrapper._drawWrapper,i=t.effect;this._engine.enableEffect(t),this._engine.bindBuffers(this.vertexBuffers,this.indexBuffer,i),i.setMatrix("view",this._scene.getViewMatrix()),i.setMatrix("projection",this._scene.getProjectionMatrix()),null!==this._particleSize&&i.setFloat2("size",this._particleSize,this._particleSize),this.useInstancing?this._engine.drawArraysType(7,0,4,e):this._engine.drawElementsType(0,0,e)}dispose(){var e;for(let t in super.dispose(),null===(e=this._diffuseEffectWrapper)||void 0===e||e.dispose(),this._vertexBuffers)this._vertexBuffers[t].dispose();this._vertexBuffers={}}}let St=`uniform float conversion;uniform sampler2D textureSampler;varying vec2 vUV; +#include +void main(void) +{vec4 color=texture2D(textureSampler,vUV); +#ifdef DEPTH_TEXTURE +gl_FragDepth=color.r; +#else +if (conversion==1.) {color=toLinearSpace(color);} else if (conversion==2.) {color=toGammaSpace(color);} +gl_FragColor=color; +#endif +} +`;nw.v.ShadersStore.copyTextureToTexturePixelShader=St,(tn=rn||(rn={}))[tn.None=0]="None",tn[tn.ToLinearSpace=1]="ToLinearSpace",tn[tn.ToGammaSpace=2]="ToGammaSpace";class Si{_textureIsInternal(e){return void 0===e.getInternalTexture}constructor(e,t=!1){this._engine=e,this._isDepthTexture=t,this._renderer=new n7(e),this._effectWrapper=new n9({engine:e,name:"CopyTextureToTexture",fragmentShader:"copyTextureToTexture",useShaderStore:!0,uniformNames:["conversion"],samplerNames:["textureSampler"],defines:t?["#define DEPTH_TEXTURE"]:[]}),this._effectWrapper.onApplyObservable.add(()=>{t&&(e.setState(!1),e.setDepthBuffer(!0),e.depthCullingState.depthMask=!0,e.depthCullingState.depthFunc=519),this._textureIsInternal(this._source)?this._effectWrapper.effect._bindTexture("textureSampler",this._source):this._effectWrapper.effect.setTexture("textureSampler",this._source),this._effectWrapper.effect.setFloat("conversion",this._conversion)})}isReady(){return this._effectWrapper.effect.isReady()}copy(e,t,i=rn.None){if(!this.isReady())return!1;this._source=e,this._conversion=i;let r=this._engine.depthCullingState.depthFunc;return this._renderer.render(this._effectWrapper,t),this._isDepthTexture&&r&&(this._engine.depthCullingState.depthFunc=r),!0}dispose(){this._effectWrapper.dispose(),this._renderer.dispose()}}class Sr{get depthRTWrapper(){return this._depthRTWrapper}constructor(e,t,i,r=1){this._engine=e,this._copyTextureToTexture=new Si(e,!0),this._depthRTWrapper=this._engine.createRenderTargetTexture({width:t,height:i},{generateMipMaps:!1,type:0,format:6,samplingMode:1,generateDepthBuffer:!0,generateStencilBuffer:!1,samples:r,noColorAttachment:!0,label:"FluidRenderingDepthTextureCopyRTT"}),this._depthRTWrapper.createDepthStencilTexture(0,!1,!1,1,void 0,"FluidRenderingDepthTextureCopyRTTDepthStencil").label=`FluidDepthTextureCopy${t}x${i}x${r}`}copy(e){return this._copyTextureToTexture.copy(e,this._depthRTWrapper)}dispose(){this._depthRTWrapper.dispose(),this._copyTextureToTexture.dispose()}}let Ss=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +attribute vec3 velocity;varying float velocityNorm; +#endif +void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;viewPos=(view*vec4(position,1.0)).xyz;gl_Position=projection*vec4(viewPos+cornerPos,1.0);uv=offset;sphereRadius=size.x/2.0; +#ifdef FLUIDRENDERING_VELOCITY +velocityNorm=length(velocity); +#endif +} +`;nw.v.ShadersStore.fluidRenderingParticleDepthVertexShader=Ss;let Sn=`uniform mat4 projection;varying vec2 uv;varying vec3 viewPos;varying float sphereRadius; +#ifdef FLUIDRENDERING_VELOCITY +varying float velocityNorm; +#endif +void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;normal.z=sqrt(1.0-r2); +#ifndef FLUIDRENDERING_RHS +normal.z=-normal.z; +#endif +vec4 realViewPos=vec4(viewPos+normal*sphereRadius,1.0);vec4 clipSpacePos=projection*realViewPos; +#ifdef WEBGPU +gl_FragDepth=clipSpacePos.z/clipSpacePos.w; +#else +gl_FragDepth=(clipSpacePos.z/clipSpacePos.w)*0.5+0.5; +#endif +#ifdef FLUIDRENDERING_RHS +realViewPos.z=-realViewPos.z; +#endif +#ifdef FLUIDRENDERING_VELOCITY +glFragColor=vec4(realViewPos.z,velocityNorm,0.,1.); +#else +glFragColor=vec4(realViewPos.z,0.,0.,1.); +#endif +} +`;nw.v.ShadersStore.fluidRenderingParticleDepthPixelShader=Sn;let Sa=`attribute vec3 position;attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;} +`;nw.v.ShadersStore.fluidRenderingParticleThicknessVertexShader=Sa;let So=`uniform float particleAlpha;varying vec2 uv;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;float thickness=sqrt(1.0-r2);glFragColor=vec4(vec3(particleAlpha*thickness),1.0);} +`;nw.v.ShadersStore.fluidRenderingParticleThicknessPixelShader=So;let Sl=`attribute vec3 position;attribute vec2 offset;attribute vec4 color;uniform mat4 view;uniform mat4 projection;uniform vec2 size;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 cornerPos;cornerPos.xy=vec2(offset.x-0.5,offset.y-0.5)*size;cornerPos.z=0.0;vec3 viewPos=(view*vec4(position,1.0)).xyz+cornerPos;gl_Position=projection*vec4(viewPos,1.0);uv=offset;diffuseColor=color.rgb;} +`;nw.v.ShadersStore.fluidRenderingParticleDiffuseVertexShader=Sl;let Sh=`uniform float particleAlpha;varying vec2 uv;varying vec3 diffuseColor;void main(void) {vec3 normal;normal.xy=uv*2.0-1.0;float r2=dot(normal.xy,normal.xy);if (r2>1.0) discard;glFragColor=vec4(diffuseColor,1.0);} +`;nw.v.ShadersStore.fluidRenderingParticleDiffusePixelShader=Sh;let Su=`uniform sampler2D textureSampler;uniform int maxFilterSize;uniform vec2 blurDir;uniform float projectedParticleConstant;uniform float depthThreshold;varying vec2 vUV;void main(void) {float depth=textureLod(textureSampler,vUV,0.).x;if (depth>=1e6 || depth<=0.) {glFragColor=vec4(vec3(depth),1.);return;} +int filterSize=min(maxFilterSize,int(ceil(projectedParticleConstant/depth)));float sigma=float(filterSize)/3.0;float two_sigma2=2.0*sigma*sigma;float sigmaDepth=depthThreshold/3.0;float two_sigmaDepth2=2.0*sigmaDepth*sigmaDepth;float sum=0.;float wsum=0.;float sumVel=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec2 sampleDepthVel=textureLod(textureSampler,vUV+coords*blurDir,0.).rg;float r=dot(coords,coords);float w=exp(-r/two_sigma2);float rDepth=sampleDepthVel.r-depth;float wd=exp(-rDepth*rDepth/two_sigmaDepth2);sum+=sampleDepthVel.r*w*wd;sumVel+=sampleDepthVel.g*w*wd;wsum+=w*wd;} +glFragColor=vec4(sum/wsum,sumVel/wsum,0.,1.);} +`;nw.v.ShadersStore.fluidRenderingBilateralBlurPixelShader=Su;let Sc=`uniform sampler2D textureSampler;uniform int filterSize;uniform vec2 blurDir;varying vec2 vUV;void main(void) {vec4 s=textureLod(textureSampler,vUV,0.);if (s.r==0.) {glFragColor=vec4(0.,0.,0.,1.);return;} +float sigma=float(filterSize)/3.0;float twoSigma2=2.0*sigma*sigma;vec4 sum=vec4(0.);float wsum=0.;for (int x=-filterSize; x<=filterSize; ++x) {vec2 coords=vec2(x);vec4 sampl=textureLod(textureSampler,vUV+coords*blurDir,0.);float w=exp(-coords.x*coords.x/twoSigma2);sum+=sampl*w;wsum+=w;} +sum/=wsum;glFragColor=vec4(sum.rgb,1.);} +`;nw.v.ShadersStore.fluidRenderingStandardBlurPixelShader=Sc;let Sd=`/* disable_uniformity_analysis */ +#define IOR 1.333 +#define ETA 1.0/IOR +#define F0 0.02 +uniform sampler2D textureSampler;uniform sampler2D depthSampler; +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +uniform sampler2D diffuseSampler; +#else +uniform vec3 diffuseColor; +#endif +#ifdef FLUIDRENDERING_FIXED_THICKNESS +uniform float thickness;uniform sampler2D bgDepthSampler; +#else +uniform float minimumThickness;uniform sampler2D thicknessSampler; +#endif +#ifdef FLUIDRENDERING_ENVIRONMENT +uniform samplerCube reflectionSampler; +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +uniform sampler2D debugSampler; +#endif +uniform mat4 viewMatrix;uniform mat4 projectionMatrix;uniform mat4 invProjectionMatrix;uniform vec2 texelSize;uniform vec3 dirLight;uniform float cameraFar;uniform float density;uniform float refractionStrength;uniform float fresnelClamp;uniform float specularPower;varying vec2 vUV;vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; +#ifdef FLUIDRENDERING_RHS +ndc.z=-projectionMatrix[2].z+projectionMatrix[3].z/depth; +#else +ndc.z=projectionMatrix[2].z+projectionMatrix[3].z/depth; +#endif +ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} +vec3 getViewPosFromTexCoord(vec2 texCoord) {float depth=textureLod(depthSampler,texCoord,0.).x;return computeViewPosFromUVDepth(texCoord,depth);} +void main(void) {vec2 texCoord=vUV; +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_TEXTURE) +vec4 color=texture2D(debugSampler,texCoord); +#ifdef FLUIDRENDERING_DEBUG_DEPTH +glFragColor=vec4(color.rgb/vec3(2.0),1.);if (color.r>0.999 && color.g>0.999) {glFragColor=texture2D(textureSampler,texCoord);} +#else +glFragColor=vec4(color.rgb,1.);if (color.r<0.001 && color.g<0.001 && color.b<0.001) {glFragColor=texture2D(textureSampler,texCoord);} +#endif +return; +#endif +vec2 depthVel=textureLod(depthSampler,texCoord,0.).rg;float depth=depthVel.r; +#ifndef FLUIDRENDERING_FIXED_THICKNESS +float thickness=texture2D(thicknessSampler,texCoord).x; +#else +float bgDepth=texture2D(bgDepthSampler,texCoord).x;float depthNonLinear=projectionMatrix[2].z+projectionMatrix[3].z/depth;depthNonLinear=depthNonLinear*0.5+0.5; +#endif +vec4 backColor=texture2D(textureSampler,texCoord); +#ifndef FLUIDRENDERING_FIXED_THICKNESS +if (depth>=cameraFar || depth<=0. || thickness<=minimumThickness) { +#else +if (depth>=cameraFar || depth<=0. || bgDepth<=depthNonLinear) { +#endif +glFragColor=backColor;return;} +vec3 viewPos=computeViewPosFromUVDepth(texCoord,depth);vec3 ddx=getViewPosFromTexCoord(texCoord+vec2(texelSize.x,0.))-viewPos;vec3 ddy=getViewPosFromTexCoord(texCoord+vec2(0.,texelSize.y))-viewPos;vec3 ddx2=viewPos-getViewPosFromTexCoord(texCoord+vec2(-texelSize.x,0.));if (abs(ddx.z)>abs(ddx2.z)) {ddx=ddx2;} +vec3 ddy2=viewPos-getViewPosFromTexCoord(texCoord+vec2(0.,-texelSize.y));if (abs(ddy.z)>abs(ddy2.z)) {ddy=ddy2;} +vec3 normal=normalize(cross(ddy,ddx)); +#ifdef FLUIDRENDERING_RHS +normal=-normal; +#endif +#ifndef WEBGPU +if(isnan(normal.x) || isnan(normal.y) || isnan(normal.z) || isinf(normal.x) || isinf(normal.y) || isinf(normal.z)) {normal=vec3(0.,0.,-1.);} +#endif +#if defined(FLUIDRENDERING_DEBUG) && defined(FLUIDRENDERING_DEBUG_SHOWNORMAL) +glFragColor=vec4(normal*0.5+0.5,1.0);return; +#endif +vec3 rayDir=normalize(viewPos); +#ifdef FLUIDRENDERING_DIFFUSETEXTURE +vec3 diffuseColor=textureLod(diffuseSampler,texCoord,0.0).rgb; +#endif +vec3 lightDir=normalize(vec3(viewMatrix*vec4(-dirLight,0.)));vec3 H =normalize(lightDir-rayDir);float specular=pow(max(0.0,dot(H,normal)),specularPower); +#ifdef FLUIDRENDERING_DEBUG_DIFFUSERENDERING +float diffuse =max(0.0,dot(lightDir,normal))*1.0;glFragColor=vec4(vec3(0.1) /*ambient*/+vec3(0.42,0.50,1.00)*diffuse+vec3(0,0,0.2)+specular,1.);return; +#endif +vec3 refractionDir=refract(rayDir,normal,ETA);vec4 transmitted=textureLod(textureSampler,vec2(texCoord+refractionDir.xy*thickness*refractionStrength),0.0);vec3 transmittance=exp(-density*thickness*(1.0-diffuseColor)); +vec3 refractionColor=transmitted.rgb*transmittance; +#ifdef FLUIDRENDERING_ENVIRONMENT +vec3 reflectionDir=reflect(rayDir,normal);vec3 reflectionColor=(textureCube(reflectionSampler,reflectionDir).rgb);float fresnel=clamp(F0+(1.0-F0)*pow(1.0-dot(normal,-rayDir),5.0),0.,fresnelClamp);vec3 finalColor=mix(refractionColor,reflectionColor,fresnel)+specular; +#else +vec3 finalColor=refractionColor+specular; +#endif +#ifdef FLUIDRENDERING_VELOCITY +float velocity=depthVel.g;finalColor=mix(finalColor,vec3(1.0),smoothstep(0.3,1.0,velocity/6.0)); +#endif +glFragColor=vec4(finalColor,transmitted.a);} +`;nw.v.ShadersStore.fluidRenderingRenderPixelShader=Sd,Object.defineProperty(r2.x.prototype,"fluidRenderer",{get:function(){return this._fluidRenderer},set:function(e){this._fluidRenderer=e},enumerable:!0,configurable:!0}),r2.x.prototype.enableFluidRenderer=function(){return this._fluidRenderer||(this._fluidRenderer=new S_(this)),this._fluidRenderer},r2.x.prototype.disableFluidRenderer=function(){var e;null===(e=this._fluidRenderer)||void 0===e||e.dispose(),this._fluidRenderer=null};class Sp{constructor(e){this.name=sN.l.NAME_FLUIDRENDERER,this.scene=e}register(){this.scene._gatherActiveCameraRenderTargetsStage.registerStep(sN.l.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER,this,this._gatherActiveCameraRenderTargets),this.scene._afterCameraDrawStage.registerStep(sN.l.STEP_AFTERCAMERADRAW_FLUIDRENDERER,this,this._afterCameraDraw)}_gatherActiveCameraRenderTargets(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._prepareRendering()}_afterCameraDraw(e){var t;null===(t=this.scene.fluidRenderer)||void 0===t||t._render(e)}rebuild(){}dispose(){this.scene.disableFluidRenderer()}}class S_{static _SceneComponentInitialization(e){let t=e._getComponent(sN.l.NAME_FLUIDRENDERER);t||(t=new Sp(e),e._addComponent(t))}constructor(e){this._scene=e,this._engine=e.getEngine(),this._onEngineResizeObserver=null,this.renderObjects=[],this.targetRenderers=[],this._cameras=new Map,S_._SceneComponentInitialization(this._scene),this._onEngineResizeObserver=this._engine.onResizeObservable.add(()=>{this._initialize()})}recreate(){this._sortRenderingObjects(),this._initialize()}getRenderObjectFromParticleSystem(e){let t=this._getParticleSystemIndex(e);return -1!==t?this.renderObjects[t]:null}addParticleSystem(e,t,i,r){let s=new T8(this._scene,e);s.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),i||(i=new T9(this._scene,r),this.targetRenderers.push(i)),i._onUseVelocityChanged.hasObservers()||i._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==t&&(i.generateDiffuseTexture=t);let n={object:s,targetRenderer:i};return this.renderObjects.push(n),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),n}addCustomParticles(e,t,i,r,s){let n=new Se(this._scene,e,t);n.onParticleSizeChanged.add(()=>this._setParticleSizeForRenderTargets()),r||(r=new T9(this._scene,s),this.targetRenderers.push(r)),r._onUseVelocityChanged.hasObservers()||r._onUseVelocityChanged.add(()=>this._setUseVelocityForRenderObject()),void 0!==i&&(r.generateDiffuseTexture=i);let a={object:n,targetRenderer:r};return this.renderObjects.push(a),this._sortRenderingObjects(),this._setParticleSizeForRenderTargets(),a}removeRenderObject(e,t=!0){let i=this.renderObjects.indexOf(e);return -1!==i&&(e.object.dispose(),this.renderObjects.splice(i,1),t&&this._removeUnusedTargetRenderers()?this._initialize():this._setParticleSizeForRenderTargets(),!0)}_sortRenderingObjects(){this.renderObjects.sort((e,t)=>e.object.priorityt.object.priority?1:0)}_removeUnusedTargetRenderers(){let e={};for(let t=0;t{var e;for(let t of(s.inputTexture.depthStencilTexture||s.inputTexture.createDepthStencilTexture(0,!0,this._engine.isStencilEnable,n[0].samples,this._engine.isStencilEnable?13:14,`PostProcessRTTDepthStencil-${s.name}`),n)){let i=null===(e=t._thicknessRenderTarget)||void 0===e?void 0:e.renderTarget,r=null==i?void 0:i.texture;if(i&&r){let e=r.width+"_"+r.height,t=a[e];t||(t=a[e]=new Sr(this._engine,r.width,r.height)),t.depthRTWrapper._shareDepth(i)}}})}t=this._cameras.keys();for(let i=t.next();!0!==i.done;i=t.next()){let t=i.value,r=this._cameras.get(t)[1],s=e.get(t);if(s)for(let e in r)s[1][e]||r[e].dispose();else for(let e in r)r[e].dispose()}this._cameras.clear(),this._cameras=e,this._setParticleSizeForRenderTargets()}_setParticleSizeForRenderTargets(){let e=new Map;for(let t=0;t{t._depthRenderTarget&&(t._depthRenderTarget.particleSize=e)})}_setUseVelocityForRenderObject(){for(let e of this.renderObjects)e.object.useVelocity=e.targetRenderer.useVelocity}_prepareRendering(){for(let e of this.targetRenderers)if(e.needInitialization){this._initialize();return}}_render(e){var t;for(let t=0;t{let t=e[1];for(let e in t)t[e].dispose()}),this.renderObjects=[],this.targetRenderers=[],this._cameras.clear()}}class Sf{get vertexCount(){return this._vertexCount}_createMaterial(e){nd.Q.ShadersStore.gaussianSplattingVertexShader=Sf._VertexShaderSource,nd.Q.ShadersStore.gaussianSplattingFragmentShader=Sf._FragmentShaderSource;let t=new hV("GaussianSplattingShader",e,{vertex:"gaussianSplatting",fragment:"gaussianSplatting"},{attributes:["position"],uniforms:["projection","modelView","viewport"]});t.backFaceCulling=!1,t.alpha=.9999,this._material=t}_getMesh(e){let t=new sp.Kj(this.name,e),i=new s7.x;i.positions=[-2,-2,0,2,-2,0,2,2,0,-2,2,0],i.indices=[0,1,2,0,2,3],i.applyToMesh(t);let r=t.getBoundingInfo();return r.reConstruct(this._minimum,this._maximum),r.isLocked=!0,t.doNotSyncBoundingInfo=!0,t.material=this._material,t}_setData(e){this._vertexCount=e.length/32;let t=this._vertexCount;this._positions=new Float32Array(3*t),this._covA=new Float32Array(3*t),this._covB=new Float32Array(3*t);let i=new Float32Array(e.buffer);this._uBuffer=new Uint8Array(e.buffer);let r=rf.y3.Zero(),s=rf.y3.Zero(),n=rf._f.Identity();this._minimum.set(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._maximum.set(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let e=0;e{var i;for(let i=0;i{i(new Uint32Array(e.data.depthMix.buffer))};let r=new rf.FM;this._sceneBeforeRenderObserver=this.scene.onBeforeRenderObservable.add(()=>{var e;let t=this.scene.getEngine();r.set(t.getRenderWidth(),t.getRenderHeight()),this._material.setVector2("viewport",r);let i=this.mesh.getWorldMatrix();i.multiplyToRef(this.scene.activeCamera.getViewMatrix(),this._modelViewMatrix);let s=this.mesh.getBoundingInfo();s.reConstruct(this._minimum,this._maximum,i),s.isLocked=!0,this._material.setMatrix("modelView",this._modelViewMatrix),null===(e=this._worker)||void 0===e||e.postMessage({view:this._modelViewMatrix.m,positions:this._positions})}),this._sceneDisposeObserver=this.scene.onDisposeObservable.add(()=>{this.dispose()})}loadDataAsync(e){return Promise.resolve(this._loadData(e))}loadFileAsync(e){return sg.w1.LoadFileAsync(e,!0).then(e=>{this._loadData(e)})}dispose(){var e,t;this.scene.onDisposeObservable.remove(this._sceneDisposeObserver),this.scene.onBeforeRenderObservable.remove(this._sceneBeforeRenderObserver),null===(e=this._worker)||void 0===e||e.terminate(),this._worker=null,null===(t=this.mesh)||void 0===t||t.dispose(),this.mesh=null}}Sf._VertexShaderSource=` + precision mediump float; + attribute vec2 position; + + attribute vec4 world0; + attribute vec4 world1; + attribute vec4 world2; + attribute vec4 world3; + + uniform mat4 projection, modelView; + uniform vec2 viewport; + + varying vec4 vColor; + varying vec2 vPosition; + void main () { + vec3 center = world0.xyz; + vec4 color = world1; + vec3 covA = world2.xyz; + vec3 covB = world3.xyz; + + vec4 camspace = modelView * vec4(center, 1); + vec4 pos2d = projection * camspace; + + float bounds = 1.2 * pos2d.w; + if (pos2d.z < -pos2d.w || pos2d.x < -bounds || pos2d.x > bounds + || pos2d.y < -bounds || pos2d.y > bounds) { + gl_Position = vec4(0.0, 0.0, 2.0, 1.0); + return; + } + + mat3 Vrk = mat3( + covA.x, covA.y, covA.z, + covA.y, covB.x, covB.y, + covA.z, covB.y, covB.z + ); + vec2 focal = vec2(1132., 1132.); + mat3 J = mat3( + focal.x / camspace.z, 0., -(focal.x * camspace.x) / (camspace.z * camspace.z), + 0., focal.y / camspace.z, -(focal.y * camspace.y) / (camspace.z * camspace.z), + 0., 0., 0. + ); + + mat3 invy = mat3(1,0,0, 0,-1,0,0,0,1); + + mat3 T = invy * transpose(mat3(modelView)) * J; + mat3 cov2d = transpose(T) * Vrk * T; + + float mid = (cov2d[0][0] + cov2d[1][1]) / 2.0; + float radius = length(vec2((cov2d[0][0] - cov2d[1][1]) / 2.0, cov2d[0][1])); + float lambda1 = mid + radius, lambda2 = mid - radius; + + if(lambda2 < 0.0) return; + vec2 diagonalVector = normalize(vec2(cov2d[0][1], lambda1 - cov2d[0][0])); + vec2 majorAxis = min(sqrt(2.0 * lambda1), 1024.0) * diagonalVector; + vec2 minorAxis = min(sqrt(2.0 * lambda2), 1024.0) * vec2(diagonalVector.y, -diagonalVector.x); + + vColor = color; + vPosition = position; + vec2 vCenter = vec2(pos2d); + gl_Position = vec4( + vCenter + + (position.x * majorAxis * 1. / viewport + + position.y * minorAxis * 1. / viewport) * pos2d.w, pos2d.zw); + }`,Sf._FragmentShaderSource=` + precision highp float; + varying vec4 vColor; + varying vec2 vPosition; + void main () { + float A = -dot(vPosition, vPosition); + if (A < -4.0) discard; + float B = exp(A) * vColor.a; + gl_FragColor = vec4(vColor.rgb, B); + }`,Sf._CreateWorker=function(e){let t,i;let r=[],s=0,n=t=>{s=i.length;let n=new BigInt64Array(s),a=new Uint32Array(n.buffer);for(let e=0;e{if(!a){a=!0;let e=t;n(e),setTimeout(()=>{a=!1,e!==t&&o()},0)}};e.onmessage=e=>{t=e.data.view,.01>Math.abs(r[2]*t[2]+r[6]*t[6]+r[10]*t[10]-1)||(i=e.data.positions,o())}};class Sm{get animationStarted(){return this._animationStarted}get fromIndex(){return this._fromIndex}get toIndex(){return this._toIndex}get loopAnimation(){return this._loopAnimation}get delay(){return Math.max(this._delay,1)}constructor(){this.width=1,this.height=1,this.angle=0,this.invertU=!1,this.invertV=!1,this.isVisible=!0,this._animationStarted=!1,this._loopAnimation=!1,this._fromIndex=0,this._toIndex=0,this._delay=0,this._direction=1,this._time=0,this._onBaseAnimationEnd=null,this.position={x:1,y:1,z:1},this.color={r:1,g:1,b:1,a:1}}playAnimation(e,t,i,r,s){this._fromIndex=e,this._toIndex=t,this._loopAnimation=i,this._delay=r||1,this._animationStarted=!0,this._onBaseAnimationEnd=s,ethis._delay&&(this._time=this._time%this._delay,this.cellIndex+=this._direction,(this._direction>0&&this.cellIndex>this._toIndex||this._direction<0&&this.cellIndex0?this._fromIndex:this._toIndex:(this.cellIndex=this._toIndex,this._animationStarted=!1,this._onBaseAnimationEnd&&this._onBaseAnimationEnd()))))}}class Sg extends Sm{get size(){return this.width}set size(e){this.width=e,this.height=e}get manager(){return this._manager}constructor(e,t){super(),this.name=e,this.animations=[],this.isPickable=!1,this.useAlphaForPicking=!1,this.onDisposeObservable=new r_.y$,this._onAnimationEnd=null,this._endAnimation=()=>{this._onAnimationEnd&&this._onAnimationEnd(),this.disposeWhenFinishedAnimating&&this.dispose()},this.color=new rm.HE(1,1,1,1),this.position=rf.P.Zero(),this._manager=t,this._manager.sprites.push(this),this.uniqueId=this._manager.scene.getUniqueId()}getClassName(){return"Sprite"}get fromIndex(){return this._fromIndex}set fromIndex(e){this.playAnimation(e,this._toIndex,this._loopAnimation,this._delay,this._onAnimationEnd)}get toIndex(){return this._toIndex}set toIndex(e){this.playAnimation(this._fromIndex,e,this._loopAnimation,this._delay,this._onAnimationEnd)}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){this.playAnimation(this._fromIndex,this._toIndex,e,this._delay,this._onAnimationEnd)}get delay(){return Math.max(this._delay,1)}set delay(e){this.playAnimation(this._fromIndex,this._toIndex,this._loopAnimation,e,this._onAnimationEnd)}playAnimation(e,t,i,r,s=null){this._onAnimationEnd=s,super.playAnimation(e,t,i,r,this._endAnimation)}dispose(){for(let e=0;e0)for(let n=0;n=s.distance))&&(s=o,i))break}return s||new s4.p},r2.x.prototype._internalMultiPickSprites=function(e,t,i){if(!s4.p)return null;let r=[];if(!i){if(!this.activeCamera)return null;i=this.activeCamera}if(this.spriteManagers&&this.spriteManagers.length>0)for(let s=0;s!!e.actionManager&&e.isPickable&&e.actionManager.hasPointerTriggers}register(){this.scene._pointerMoveStage.registerStep(sN.l.STEP_POINTERMOVE_SPRITE,this,this._pointerMove),this.scene._pointerDownStage.registerStep(sN.l.STEP_POINTERDOWN_SPRITE,this,this._pointerDown),this.scene._pointerUpStage.registerStep(sN.l.STEP_POINTERUP_SPRITE,this,this._pointerUp)}rebuild(){}dispose(){this.scene.onBeforeSpritesRenderingObservable.clear(),this.scene.onAfterSpritesRenderingObservable.clear();let e=this.scene.spriteManagers;if(e)for(;e.length;)e[0].dispose()}_pickSpriteButKeepRay(e,t,i,r,s){let n=this.scene.pickSprite(t,i,this._spritePredicate,r,s);return n&&(n.ray=e?e.ray:null),n}_pointerMove(e,t,i,r,s){let n=this.scene;return r?n.setPointerOverSprite(null):(i=this._pickSpriteButKeepRay(i,e,t,!1,n.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite?(n.setPointerOverSprite(i.pickedSprite),!n.doNotHandleCursors&&s&&(n._pointerOverSprite&&n._pointerOverSprite.actionManager&&n._pointerOverSprite.actionManager.hoverCursor?s.style.cursor=n._pointerOverSprite.actionManager.hoverCursor:s.style.cursor=n.hoverCursor)):n.setPointerOverSprite(null),i}_pointerDown(e,t,i,r){let s=this.scene;if(s._pickedDownSprite=null,s.spriteManagers&&s.spriteManagers.length>0&&(i=s.pickSprite(e,t,this._spritePredicate,!1,s.cameraToUseForPointers||void 0))&&i.hit&&i.pickedSprite&&i.pickedSprite.actionManager){switch(s._pickedDownSprite=i.pickedSprite,r.button){case 0:i.pickedSprite.actionManager.processTrigger(2,rx.V.CreateNewFromSprite(i.pickedSprite,s,r));break;case 1:i.pickedSprite.actionManager.processTrigger(4,rx.V.CreateNewFromSprite(i.pickedSprite,s,r));break;case 2:i.pickedSprite.actionManager.processTrigger(3,rx.V.CreateNewFromSprite(i.pickedSprite,s,r))}i.pickedSprite.actionManager&&i.pickedSprite.actionManager.processTrigger(5,rx.V.CreateNewFromSprite(i.pickedSprite,s,r))}return i}_pointerUp(e,t,i,r,s){let n=this.scene;if(n.spriteManagers&&n.spriteManagers.length>0){let i=n.pickSprite(e,t,this._spritePredicate,!1,n.cameraToUseForPointers||void 0);i&&(i.hit&&i.pickedSprite&&i.pickedSprite.actionManager&&(i.pickedSprite.actionManager.processTrigger(7,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)),i.pickedSprite.actionManager&&(this.scene._inputManager._isPointerSwiping()||i.pickedSprite.actionManager.processTrigger(1,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)),s&&i.pickedSprite.actionManager.processTrigger(6,rx.V.CreateNewFromSprite(i.pickedSprite,n,r)))),n._pickedDownSprite&&n._pickedDownSprite.actionManager&&n._pickedDownSprite!==i.pickedSprite&&n._pickedDownSprite.actionManager.processTrigger(16,rx.V.CreateNewFromSprite(n._pickedDownSprite,n,r)))}return i}}let Sx=`#ifdef IMAGEPROCESSINGPOSTPROCESS +gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); +#endif +`;nw.v.IncludesShadersStore.imageProcessingCompatibility=Sx;let ST=`uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; +#include +#define CUSTOM_FRAGMENT_DEFINITIONS +#ifdef PIXEL_PERFECT +vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} +#endif +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +#ifdef PIXEL_PERFECT +vec2 uv=uvPixelPerfect(vUV); +#else +vec2 uv=vUV; +#endif +vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) +{if (color.a<0.95) +discard;} +color*=vColor; +#include +gl_FragColor=color; +#include +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.spritesPixelShader=ST;let SS=`attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; +#include +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; +vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); +vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; +#ifdef FOG +vFogDistance=viewPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.spritesVertexShader=SS;class SE{get capacity(){return this._capacity}get pixelPerfect(){return this._pixelPerfect}set pixelPerfect(e){this._pixelPerfect!==e&&(this._pixelPerfect=e,this._createEffects())}constructor(e,t,i=.01,r=null){let s;this.blendMode=2,this.autoResetAlpha=!0,this.disableDepthWrite=!1,this.fogEnabled=!0,this._pixelPerfect=!1,this._useVAO=!1,this._useInstancing=!1,this._vertexBuffers={},this._capacity=t,this._epsilon=i,this._engine=e,this._useInstancing=e.getCaps().instancedArrays&&e._features.supportSpriteInstancing,this._useVAO=e.getCaps().vertexArrayObject&&!e.disableVertexArrayObjects,this._scene=r,this._useInstancing||this._buildIndexBuffer(),this._vertexBufferSize=this._useInstancing?16:18,this._vertexData=new Float32Array(t*this._vertexBufferSize*(this._useInstancing?1:4)),this._buffer=new sm.l(e,this._vertexData,!0,this._vertexBufferSize);let n=this._buffer.createVertexBuffer(sm.o.PositionKind,0,4,this._vertexBufferSize,this._useInstancing),a=this._buffer.createVertexBuffer("options",4,2,this._vertexBufferSize,this._useInstancing),o=6;if(this._useInstancing){let t=new Float32Array([0,0,1,0,0,1,1,1]);this._spriteBuffer=new sm.l(e,t,!1,2),s=this._spriteBuffer.createVertexBuffer("offsets",0,2)}else s=this._buffer.createVertexBuffer("offsets",o,2,this._vertexBufferSize,this._useInstancing),o+=2;let l=this._buffer.createVertexBuffer("inverts",o,2,this._vertexBufferSize,this._useInstancing),h=this._buffer.createVertexBuffer("cellInfo",o+2,4,this._vertexBufferSize,this._useInstancing),u=this._buffer.createVertexBuffer(sm.o.ColorKind,o+6,4,this._vertexBufferSize,this._useInstancing);this._vertexBuffers[sm.o.PositionKind]=n,this._vertexBuffers.options=a,this._vertexBuffers.offsets=s,this._vertexBuffers.inverts=l,this._vertexBuffers.cellInfo=h,this._vertexBuffers[sm.o.ColorKind]=u,this._createEffects()}_createEffects(){var e,t,i,r;null===(e=this._drawWrapperBase)||void 0===e||e.dispose(),null===(t=this._drawWrapperFog)||void 0===t||t.dispose(),null===(i=this._drawWrapperDepth)||void 0===i||i.dispose(),null===(r=this._drawWrapperFogDepth)||void 0===r||r.dispose(),this._drawWrapperBase=new nk.q(this._engine),this._drawWrapperFog=new nk.q(this._engine),this._drawWrapperDepth=new nk.q(this._engine,!1),this._drawWrapperFogDepth=new nk.q(this._engine,!1),this._drawWrapperBase.drawContext&&(this._drawWrapperBase.drawContext.useInstancing=this._useInstancing),this._drawWrapperFog.drawContext&&(this._drawWrapperFog.drawContext.useInstancing=this._useInstancing),this._drawWrapperDepth.drawContext&&(this._drawWrapperDepth.drawContext.useInstancing=this._useInstancing),this._drawWrapperFogDepth.drawContext&&(this._drawWrapperFogDepth.drawContext.useInstancing=this._useInstancing);let s=this._pixelPerfect?"#define PIXEL_PERFECT\n":"";this._drawWrapperBase.effect=this._engine.createEffect("sprites",[sm.o.PositionKind,"options","offsets","inverts","cellInfo",sm.o.ColorKind],["view","projection","textureInfos","alphaTest"],["diffuseSampler"],s),this._drawWrapperDepth.effect=this._drawWrapperBase.effect,this._drawWrapperDepth.materialContext=this._drawWrapperBase.materialContext,this._scene&&(this._drawWrapperFog.effect=this._scene.getEngine().createEffect("sprites",[sm.o.PositionKind,"options","offsets","inverts","cellInfo",sm.o.ColorKind],["view","projection","textureInfos","alphaTest","vFogInfos","vFogColor"],["diffuseSampler"],s+"#define FOG"),this._drawWrapperFogDepth.effect=this._drawWrapperFog.effect,this._drawWrapperFogDepth.materialContext=this._drawWrapperFog.materialContext)}render(e,t,i,r,s=null){if(!this.texture||!this.texture.isReady()||!e.length)return;let n=this._drawWrapperBase,a=this._drawWrapperDepth,o=!1;this.fogEnabled&&this._scene&&this._scene.fogEnabled&&0!==this._scene.fogMode&&(n=this._drawWrapperFog,a=this._drawWrapperFogDepth,o=!0);let l=n.effect;if(!l.isReady())return;let h=this._engine,u=!!(this._scene&&this._scene.useRightHandedSystem),c=this.texture.getBaseSize(),d=Math.min(this._capacity,e.length),p=0,_=!0;for(let i=0;i>0;t._xOffset=(t.cellIndex-i*e)*this.cellWidth/s.width,t._yOffset=i*this.cellHeight/s.height,t._xSize=this.cellWidth,t._ySize=this.cellHeight}this._vertexData[o]=t.position.x,this._vertexData[o+1]=t.position.y,this._vertexData[o+2]=t.position.z,this._vertexData[o+3]=t.angle,this._vertexData[o+4]=t.width,this._vertexData[o+5]=t.height,this._useInstancing?o-=2:(this._vertexData[o+6]=i,this._vertexData[o+7]=r),n?this._vertexData[o+8]=t.invertU?0:1:this._vertexData[o+8]=t.invertU?1:0,this._vertexData[o+9]=t.invertV?1:0,this._vertexData[o+10]=t._xOffset,this._vertexData[o+11]=t._yOffset,this._vertexData[o+12]=t._xSize/s.width,this._vertexData[o+13]=t._ySize/s.height,this._vertexData[o+14]=t.color.r,this._vertexData[o+15]=t.color.g,this._vertexData[o+16]=t.color.b,this._vertexData[o+17]=t.color.a}_buildIndexBuffer(){let e=[],t=0;for(let i=0;i{e.cellRef||(e.cellIndex=0);let i=e.cellIndex;"number"==typeof i&&isFinite(i)&&Math.floor(i)===i&&(e.cellRef=this._spriteMap[e.cellIndex]),e._xOffset=this._cellData[e.cellRef].frame.x/t.width,e._yOffset=this._cellData[e.cellRef].frame.y/t.height,e._xSize=this._cellData[e.cellRef].frame.w,e._ySize=this._cellData[e.cellRef].frame.h},s||(s=rL.l.LastCreatedScene),s._getComponent(sN.l.NAME_SPRITE)||s._addComponent(new Sv(s)),this._fromPacked=o,this._scene=s;let h=this._scene.getEngine();if(this._spriteRenderer=new SE(h,i,n,s),r.width&&r.height)this.cellWidth=r.width,this.cellHeight=r.height;else if(void 0!==r)this.cellWidth=r,this.cellHeight=r;else{this._spriteRenderer=null;return}this._scene.spriteManagers&&this._scene.spriteManagers.push(this),this.uniqueId=this.scene.getUniqueId(),t&&(this.texture=new sj(t,s,!0,!1,a)),this._fromPacked&&this._makePacked(t,l)}getClassName(){return"SpriteManager"}_makePacked(e,t){if(null!==t)try{let e;if((e="string"==typeof t?JSON.parse(t):t).frames.length){let t={};for(let i=0;i0);let r=e.substring(0,t-1)+".json";sg.w1.LoadFile(r,e=>{try{let t=JSON.parse(e),i=Reflect.ownKeys(t.frames);this._spriteMap=i,this._packedAndReady=!0,this._cellData=t.frames}catch(e){throw this._fromPacked=!1,this._packedAndReady=!1,Error("Invalid JSON format. Please check documentation for format specifications.")}},void 0,void 0,!1,()=>{rb.Y.Error("JSON ERROR: Unable to load JSON file."),this._fromPacked=!1,this._packedAndReady=!1})}}_checkTextureAlpha(e,t,i,r,s){if(!e.useAlphaForPicking||!this.texture)return!0;let n=this.texture.getSize();this._textureContent||(this._textureContent=new Uint8Array(n.width*n.height*4),this.texture.readPixels(0,0,this._textureContent));let a=rf.jp.Vector3[0];a.copyFrom(t.direction),a.normalize(),a.scaleInPlace(i),a.addInPlace(t.origin);let o=(a.x-r.x)/(s.x-r.x),l=1-(a.y-r.y)/(s.y-r.y),h=e._xOffset*n.width+o*e._xSize|0,u=e._yOffset*n.height+l*e._ySize|0;return this._textureContent[(h+u*n.width)*4+3]>.5}intersects(e,t,i,r){let s=Math.min(this.capacity,this.sprites.length),n=rf.P.Zero(),a=rf.P.Zero(),o=Number.MAX_VALUE,l=null,h=rf.jp.Vector3[0],u=rf.jp.Vector3[1],c=t.getViewMatrix(),d=e,p=e;for(let t=0;te){if(!this._checkTextureAlpha(s,d,e,n,a))continue;if(p=d,o=e,l=s,r)break}}}}if(l){let e=new s4.p;c.invertToRef(rf.jp.Matrix[0]),e.hit=!0,e.pickedSprite=l,e.distance=o;let t=rf.jp.Vector3[2];return t.copyFrom(p.direction),t.normalize(),t.scaleInPlace(o),p.origin.addToRef(t,h),e.pickedPoint=rf.P.TransformCoordinates(h,rf.jp.Matrix[0]),e}return null}multiIntersects(e,t,i){let r;let s=Math.min(this.capacity,this.sprites.length),n=rf.P.Zero(),a=rf.P.Zero(),o=[],l=rf.jp.Vector3[0].copyFromFloats(0,0,0),h=rf.jp.Vector3[1].copyFromFloats(0,0,0),u=t.getViewMatrix();for(let t=0;t{let a=new rX.g;a.addEventListener("readystatechange",()=>{if(4==a.readyState){if(200==a.status){let t=JSON.parse(a.responseText),n=SC.Parse(t,i||rL.l.LastCreatedScene,r);e&&(n.name=e),s(n)}else n("Unable to load the sprite manager")}}),a.open("GET",t),a.send()})}static ParseFromSnippetAsync(e,t,i=""){return"_BLANK"===e?Promise.resolve(new SC("Default sprite manager","//playground.babylonjs.com/textures/player.png",500,64,t)):new Promise((r,s)=>{let n=new rX.g;n.addEventListener("readystatechange",()=>{if(4==n.readyState){if(200==n.status){let s=JSON.parse(JSON.parse(JSON.parse(n.responseText).jsonPayload).spriteManager),a=SC.Parse(s,t||rL.l.LastCreatedScene,i);a.snippetId=e,r(a)}else s("Unable to load the snippet "+e)}}),n.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),n.send()})}}SC.SnippetUrl="https://snippet.babylonjs.com",SC.CreateFromSnippetAsync=SC.ParseFromSnippetAsync;let Sb=`#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) +#define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) +#else +#define TEXTUREFUNC(s,c,b) texture2D(s,c,b) +#endif +precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul;float mt;const float fdStep=1./4.;const float aFrameSteps=1./MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID){float fX=frameID/spriteCount;return mat4( +texture2D(frameMap,vec2(fX,0.),0.), +texture2D(frameMap,vec2(fX,fdStep*1.),0.), +texture2D(frameMap,vec2(fX,fdStep*2.),0.), +vec4(0.) +);} +void main(){vec4 color=vec4(0.);vec2 tileUV=fract(tUV); +#ifdef FLIPU +tileUV.y=1.0-tileUV.y; +#endif +vec2 tileID=floor(tUV);vec2 sheetUnits=1./spriteMapSize;float spriteUnits=1./spriteCount;vec2 stageUnits=1./stageSize;for(int i=0; i0.) {mt=mod(time*animationData.z,1.0);for(float f=0.; fmt){frameID=animationData.x;break;} +animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.);}} +mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw;if (frameData[2].z==1.){tileUV.xy=tileUV.yx;} +vec4 nc=texture2D(spriteSheet,tileUV*frameSize+offset);if (i==0){color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} +color.xyz*=colorMul;gl_FragColor=color;}`;nw.v.ShadersStore.spriteMapPixelShader=Sb;let Sy=`precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;varying vec2 stageUnits;varying vec2 levelUnits;varying vec2 tileID;uniform float time;uniform mat4 worldViewProjection;uniform vec2 outputSize;uniform vec2 stageSize;uniform vec2 spriteMapSize;uniform float stageScale;void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; +gl_Position=worldViewProjection*p;}`;nw.v.ShadersStore.spriteMapVertexShader=Sy,i(3609),i(6807),i(1146),(ta=ra||(ra={}))[ta.INIT=0]="INIT",ta[ta.RUNNING=1]="RUNNING",ta[ta.DONE=2]="DONE",ta[ta.ERROR=3]="ERROR",i(320),r_.y$.prototype.notifyObserversWithPromise=async function(e,t=-1,i,r,s){let n=Promise.resolve(e);if(!this.observers.length)return n;let a=this._eventState;return a.mask=t,a.target=i,a.currentTarget=r,a.skipNextObservers=!1,a.userInfo=s,this.observers.forEach(i=>{!a.skipNextObservers&&!i._willBeUnregistered&&i.mask&t&&(n=i.scope?n.then(t=>(a.lastReturnValue=t,i.callback.apply(i.scope,[e,a]))):n.then(t=>(a.lastReturnValue=t,i.callback(e,a))),i.unregisterOnNextCall&&this._deferUnregister(i))}),await n,e},i(8786);class SA{getDescription(){return""}apply(e,t){return!0}constructor(e=0){this.priority=e}}class SR extends SA{constructor(){super(...arguments),this._canBeMerged=e=>e instanceof sp.Kj&&!e.isDisposed()&&!!e.isVisible&&!!e.isEnabled()&&!(e.instances.length>0)&&!e.skeleton&&!e.hasLODLevels&&0!==e.getTotalVertices()}static get UpdateSelectionTree(){return SR._UpdateSelectionTree}static set UpdateSelectionTree(e){SR._UpdateSelectionTree=e}getDescription(){return"Merging similar meshes together"}apply(e,t,i){let r=e.meshes.slice(0),s=r.length;for(let e=0;e{e.doNotSerialize||(t.vertexData.push(e.serializeVerticeData()),SP[e.id]=!0)},SM=(e,t)=>{let i={},r=e._geometry;return r&&!e.getScene().getGeometryById(r.id)&&SI(r,t.geometries),e.serialize&&e.serialize(i),i},SD=(e,t)=>{if(e._isMesh){if(1===e.delayLoadState||0===e.delayLoadState){let i=i=>{t.materials=t.materials||[],e.material&&!t.materials.some(t=>t.id===e.material.id)&&t.materials.push(i.serialize())};if(e.material&&!e.material.doNotSerialize){if(e.material instanceof _6.G){if(t.multiMaterials=t.multiMaterials||[],!t.multiMaterials.some(t=>t.id===e.material.id))for(let r of(t.multiMaterials.push(e.material.serialize()),e.material.subMaterials))r&&i(r)}else i(e.material)}else e.material||i(e.getScene().defaultMaterial);let r=e._geometry;r&&(t.geometries||(t.geometries={},t.geometries.boxes=[],t.geometries.spheres=[],t.geometries.cylinders=[],t.geometries.toruses=[],t.geometries.grounds=[],t.geometries.planes=[],t.geometries.torusKnots=[],t.geometries.vertexData=[]),SI(r,t.geometries)),e.skeleton&&!e.skeleton.doNotSerialize&&(t.skeletons=t.skeletons||[],t.skeletons.push(e.skeleton.serialize())),t.meshes=t.meshes||[],t.meshes.push(SM(e,t))}}else"TransformNode"===e.getClassName()?t.transformNodes.push(e.serialize()):-1!==e.getClassName().indexOf("Camera")?t.cameras.push(e.serialize()):-1!==e.getClassName().indexOf("Light")&&t.lights.push(e.serialize())};class SO{static ClearCache(){SP=[]}static Serialize(e){return SO._Serialize(e)}static _Serialize(e,t=!0){let i,r,s;let n={};if(t&&!e.getEngine()._features.supportSyncTextureRead&&sj.ForceSerializeBuffers&&rb.Y.Warn("The serialization object may not contain the proper base64 encoded texture data! You should use the SerializeAsync method instead."),SO.ClearCache(),n.useDelayedTextureLoading=e.useDelayedTextureLoading,n.autoClear=e.autoClear,n.clearColor=e.clearColor.asArray(),n.ambientColor=e.ambientColor.asArray(),n.gravity=e.gravity.asArray(),n.collisionsEnabled=e.collisionsEnabled,n.useRightHandedSystem=e.useRightHandedSystem,e.fogMode&&0!==e.fogMode&&(n.fogMode=e.fogMode,n.fogColor=e.fogColor.asArray(),n.fogStart=e.fogStart,n.fogEnd=e.fogEnd,n.fogDensity=e.fogDensity),e.isPhysicsEnabled&&e.isPhysicsEnabled()){let t=e.getPhysicsEngine();t&&(n.physicsEnabled=!0,n.physicsGravity=t.gravity.asArray(),n.physicsEngine=t.getPhysicsPluginName())}for(let t of(e.metadata&&(n.metadata=e.metadata),n.morphTargetManagers=[],e.meshes)){let e=t.morphTargetManager;e&&n.morphTargetManagers.push(e.serialize())}for(i=0,n.lights=[];i0){n.animationGroups=[];for(let t=0;t0)for(i=0,n.reflectionProbes=[];it)}static _CollectPromises(e,t){if(Array.isArray(e))for(let i=0;ie[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}else if(e instanceof Object){for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let r=e[i];r instanceof Promise?t.push(r.then(t=>e[i]=t)):(r instanceof Object||Array.isArray(r))&&this._CollectPromises(r,t)}}}static SerializeMesh(e,t=!1,i=!1){let r={};if(r.meshes=[],r.transformNodes=[],r.cameras=[],r.lights=[],SO.ClearCache(),e=e instanceof Array?e:[e],t||i)for(let r=0;r{0>e.indexOf(t)&&!t.doNotSerialize&&e.push(t)}),t&&e[r].parent&&0>e.indexOf(e[r].parent)&&!e[r].parent.doNotSerialize&&e.push(e[r].parent);return e.forEach(e=>{SD(e,r)}),r}}class SN{static IsSupported(e){let t=e.getRenderingCanvas();return!!t&&"function"==typeof t.captureStream}get isRecording(){return!!this._canvas&&this._canvas.isRecording}constructor(e,t={}){if(!SN.IsSupported(e))throw"Your browser does not support recording so far.";let i=e.getRenderingCanvas();if(!i)throw"The babylon engine must have a canvas to be recorded";this._canvas=i,this._canvas.isRecording=!1,this._options=Object.assign(Object.assign({},SN._DefaultOptions),t);let r=this._canvas.captureStream(this._options.fps);if(this._options.audioTracks)for(let e of this._options.audioTracks)r.addTrack(e);this._mediaRecorder=new MediaRecorder(r,{mimeType:this._options.mimeType}),this._mediaRecorder.ondataavailable=e=>this._handleDataAvailable(e),this._mediaRecorder.onerror=e=>this._handleError(e),this._mediaRecorder.onstop=()=>this._handleStop()}stopRecording(){this._canvas&&this._mediaRecorder&&this.isRecording&&(this._canvas.isRecording=!1,this._mediaRecorder.stop())}startRecording(e="babylonjs.webm",t=7){if(!this._canvas||!this._mediaRecorder)throw"Recorder has already been disposed";if(this.isRecording)throw"Recording already in progress";return t>0&&setTimeout(()=>{this.stopRecording()},1e3*t),this._fileName=e,this._recordedChunks=[],this._resolve=null,this._reject=null,this._canvas.isRecording=!0,this._mediaRecorder.start(this._options.recordChunckSize),new Promise((e,t)=>{this._resolve=e,this._reject=t})}dispose(){this._canvas=null,this._mediaRecorder=null,this._recordedChunks=[],this._fileName=null,this._resolve=null,this._reject=null}_handleDataAvailable(e){e.data.size>0&&this._recordedChunks.push(e.data)}_handleError(e){if(this.stopRecording(),this._reject)this._reject(e.error);else throw new e.error}_handleStop(){this.stopRecording();let e=new Blob(this._recordedChunks);this._resolve&&this._resolve(e),window.URL.createObjectURL(e),this._fileName&&sg.w1.Download(e,this._fileName)}}SN._DefaultOptions={mimeType:"video/webm",fps:25,recordChunckSize:3e3};let SF=null;function SL(e,t,i,r,s="image/png",n=!1,a){let{height:o,width:l}=SB(e,t,i);if(!(o&&l)){rb.Y.Error("Invalid 'size' parameter !");return}SF||(SF=document.createElement("canvas")),SF.width=l,SF.height=o;let h=SF.getContext("2d"),u=e.getRenderWidth()/e.getRenderHeight(),c=l,d=c/u;d>o&&(c=(d=o)*u);let p=Math.max(0,l-c)/2,_=Math.max(0,o-d)/2;t.getScene().activeCamera!==t?Sw(e,t,i,e=>{if(n){let t=new Blob([e]);sg.w1.DownloadBlob(t),r&&r("")}else r&&r(e)},s,1,e.getCreationOptions().antialias,void 0,void 0,void 0,void 0,a):e.onEndFrameObservable.addOnce(()=>{let t=e.getRenderingCanvas();h&&t&&h.drawImage(t,p,_,c,d),SF&&(n?(sg.w1.EncodeScreenshotCanvasData(SF,void 0,s,void 0,a),r&&r("")):sg.w1.EncodeScreenshotCanvasData(SF,r,s,void 0,a))})}function Sw(e,t,i,r,s="image/png",n=1,a=!1,o,l=!1,h=!1,u=!0,c,d){let{height:p,width:_,finalWidth:f,finalHeight:m}=SB(e,t,i);if(!(p&&_)){rb.Y.Error("Invalid 'size' parameter !");return}let g={width:e.getRenderWidth(),height:e.getRenderHeight()};e.setSize(_,p);let v=t.getScene(),x=new as("screenShot",{width:_,height:p},v,!1,!1,0,!1,sj.BILINEAR_SAMPLINGMODE,void 0,h,void 0,void 0,void 0,n);x.renderList=v.meshes.slice(),x.samples=n,x.renderSprites=l,x.activeCamera=t,x.forceLayerMaskCheck=u,null==d||d(x);let T=()=>{x.isReadyForRendering()&&t.isReady(!0)?(e.onEndFrameObservable.addOnce(()=>{f===_&&m===p?x.readPixels(void 0,void 0,void 0,!1).then(e=>{ar.DumpData(_,p,e,r,s,o,!0,void 0,c),x.dispose()}):uv("pass",x.getInternalTexture(),v,void 0,void 0,void 0,f,m).then(t=>{e._readTexturePixels(t,f,m,-1,0,null,!0,!1,0,0).then(e=>{ar.DumpData(f,m,e,r,s,o,!0,void 0,c),t.dispose()})})}),x.render(!0),v.incrementRenderId(),v.resetCachedMaterial(),e.setSize(g.width,g.height),t.getProjectionMatrix(!0),v.render()):setTimeout(T,16)},S=()=>{v.incrementRenderId(),v.resetCachedMaterial(),T()};if(a){let e=new xX("antialiasing",1,v.activeCamera);x.addPostProcess(e),e.getEffect().isReady()?S():e.getEffect().onCompiled=()=>{S()}}else S()}function SB(e,t,i){let r=0,s=0,n=0,a=0;if("object"==typeof i){let o=i.precision?Math.abs(i.precision):1;i.width&&i.height?(r=i.height*o,s=i.width*o):i.width&&!i.height?r=Math.round((s=i.width*o)/e.getAspectRatio(t)):i.height&&!i.width?s=Math.round((r=i.height*o)*e.getAspectRatio(t)):r=Math.round((s=Math.round(e.getRenderWidth()*o))/e.getAspectRatio(t)),i.finalWidth&&i.finalHeight?(a=i.finalHeight,n=i.finalWidth):i.finalWidth&&!i.finalHeight?a=Math.round((n=i.finalWidth)/e.getAspectRatio(t)):i.finalHeight&&!i.finalWidth?n=Math.round((a=i.finalHeight)*e.getAspectRatio(t)):(n=s,a=r)}else isNaN(i)||(r=i,s=i,n=i,a=i);return s&&(s=Math.floor(s)),r&&(r=Math.floor(r)),n&&(n=Math.floor(n)),a&&(a=Math.floor(a)),{height:0|r,width:0|s,finalWidth:0|n,finalHeight:0|a}}sg.w1.CreateScreenshot=SL,sg.w1.CreateScreenshotAsync=function(e,t,i,r="image/png",s){return new Promise((n,a)=>{SL(e,t,i,e=>{void 0!==e?n(e):a(Error("Data is undefined"))},r,void 0,s)})},sg.w1.CreateScreenshotUsingRenderTarget=Sw,sg.w1.CreateScreenshotUsingRenderTargetAsync=function(e,t,i,r="image/png",s=1,n=!1,a,o=!1,l=!1,h=!0,u){return new Promise((c,d)=>{Sw(e,t,i,e=>{void 0!==e?c(e):d(Error("Data is undefined"))},r,s,n,a,o,l,h,u)})},(to=ro||(ro={}))[to.Checkbox=0]="Checkbox",to[to.Slider=1]="Slider",to[to.Vector3=2]="Vector3",to[to.Quaternion=3]="Quaternion",to[to.Color3=4]="Color3",to[to.String=5]="String",to[to.Button=6]="Button",to[to.Options=7]="Options",to[to.Tab=8]="Tab",to[to.FileButton=9]="FileButton",to[to.Vector2=10]="Vector2",i(9983);class SU{static _GetStorage(){try{return localStorage.setItem("test",""),localStorage.removeItem("test"),localStorage}catch(t){let e={};return{getItem:t=>{let i=e[t];return void 0===i?null:i},setItem:(t,i)=>{e[t]=i}}}}static ReadString(e,t){let i=this._Storage.getItem(e);return null!==i?i:t}static WriteString(e,t){this._Storage.setItem(e,t)}static ReadBoolean(e,t){let i=this._Storage.getItem(e);return null!==i?"true"===i:t}static WriteBoolean(e,t){this._Storage.setItem(e,t?"true":"false")}static ReadNumber(e,t){let i=this._Storage.getItem(e);return null!==i?parseFloat(i):t}static WriteNumber(e,t){this._Storage.setItem(e,t.toString())}}SU._Storage=SU._GetStorage(),function(e){class t{serialize(){let e={},t=Array(this._characterToIdx.size);return this._characterToIdx.forEach((e,i)=>{t[e]=i}),e.characters=t,e.insertionCosts=this._insertionCosts,e.deletionCosts=this._deletionCosts,e.substitutionCosts=this._substitutionCosts,JSON.stringify(e)}static Deserialize(e){let i=JSON.parse(e),r=new t(i.characters);return r._insertionCosts=i.insertionCosts,r._deletionCosts=i.deletionCosts,r._substitutionCosts=i.substitutionCosts,r}constructor(e,t=null,i=null,r=null){let s;t=null!=t?t:()=>1,i=null!=i?i:()=>1,r=null!=r?r:(e,t)=>e===t?0:1,this._characterToIdx=new Map,this._insertionCosts=Array(e.length),this._deletionCosts=Array(e.length),this._substitutionCosts=Array(e.length);for(let n=0;ni._MAX_SEQUENCE_LENGTH)throw Error("Sequences longer than "+i._MAX_SEQUENCE_LENGTH+" not supported.");this._alphabet=t,this._characters=e.map(e=>this._alphabet.getCharacterIdx(e))}distance(e){return i._Distance(this,e)}static _Distance(e,t){let r=e._alphabet;if(r!==t._alphabet)throw Error("Cannot Levenshtein compare Sequences built from different alphabets.");let s=e._characters,n=t._characters,a=s.length,o=n.length,l=i._CostMatrix;l[0][0]=0;for(let e=0;eArray(i._MAX_SEQUENCE_LENGTH+1)),e.Sequence=i}(rl||(rl={}));class SV{serialize(){return JSON.stringify(this)}static Deserialize(e){let t=JSON.parse(e),i=new SV(t._segmentLength);return i._points=t._points.map(e=>new rf.P(e._x,e._y,e._z)),i}constructor(e=.01){this._points=[],this._segmentLength=e}getLength(){return this._points.length*this._segmentLength}add(e){let t=this._points.length;if(0===t)this._points.push(e.clone());else{let i=()=>this._segmentLength/rf.P.Distance(this._points[t-1],e);for(let r=i();r<=1;r=i()){let i=this._points[t-1].scale(1-r);e.scaleAndAddToRef(r,i),this._points.push(i),++t}}}resampleAtTargetResolution(e){let t=new SV(this.getLength()/e);return this._points.forEach(e=>{t.add(e)}),t}tokenize(e){let t=[],i=new rf.P;for(let r=2;r.98)&&(rf.P.CrossToRef(SV._ForwardDir,SV._InverseFromVec,SV._UpDir),SV._UpDir.normalize(),rf.y3.LookAtLHToRef(e,t,SV._UpDir,SV._LookMatrix),i.subtractToRef(t,SV._FromToVec),SV._FromToVec.normalize(),rf.P.TransformNormalToRef(SV._FromToVec,SV._LookMatrix,r),!0)}static _TokenizeSegment(e,t){SV._BestMatch=0,SV._Score=rf.P.Dot(e,t[0]),SV._BestScore=SV._Score;for(let i=1;iSV._BestScore&&(SV._BestMatch=i,SV._BestScore=SV._Score);return SV._BestMatch}}SV._ForwardDir=new rf.P,SV._InverseFromVec=new rf.P,SV._UpDir=new rf.P,SV._FromToVec=new rf.P,SV._LookMatrix=new rf.y3;class Sk{serialize(){return JSON.stringify(this._sequences.map(e=>e.serialize()))}static Deserialize(e,t){let i=new Sk;return i._sequences=JSON.parse(e).map(e=>rl.Sequence.Deserialize(e,t)),i}static CreateFromTrajectory(e,t,i){return Sk.CreateFromTokenizationPyramid(Sk._GetTokenizationPyramid(e,t),i)}static CreateFromTokenizationPyramid(e,t){let i=new Sk;return i._sequences=e.map(e=>new rl.Sequence(e,t)),i}constructor(){this._sequences=[]}static _GetTokenizationPyramid(e,t,i=Sk._FINEST_DESCRIPTOR_RESOLUTION){let r=[];for(let s=i;s>4;s=Math.floor(s/2))r.push(e.resampleAtTargetResolution(s).tokenize(t.chars));return r}distance(e){let t=0;for(let i=0;ie.serialize()),e.centroidIdx=this._centroidIdx,e.averageDistance=this._averageDistance,JSON.stringify(e)}static Deserialize(e,t){let i=JSON.parse(e),r=new SG;return r._descriptors=i.descriptors.map(e=>Sk.Deserialize(e,t)),r._centroidIdx=i.centroidIdx,r._averageDistance=i.averageDistance,r}constructor(e=[]){this._descriptors=e,this._centroidIdx=-1,this._averageDistance=0,this._refreshDescription()}add(e){this._descriptors.push(e),this._refreshDescription()}getMatchCost(e){return e.distance(this._descriptors[this._centroidIdx])/this._averageDistance}getMatchMinimumDistance(e){return Math.min(...this._descriptors.map(t=>t.distance(e)))}_refreshDescription(){let e;this._centroidIdx=-1;let t=this._descriptors.map(t=>(e=0,this._descriptors.forEach(i=>{e+=t.distance(i)}),e));for(let e=0;e{this._averageDistance+=e.distance(this._descriptors[this._centroidIdx])}),this._descriptors.length>0&&(this._averageDistance=Math.max(this._averageDistance/this._descriptors.length,SG._MIN_AVERAGE_DISTANCE))}}SG._MIN_AVERAGE_DISTANCE=1;class Sz{constructor(e,t,i){this._scene=e,rb.Y.Log(`[Reflector] Connecting to ws://${t}:${i}`),this._webSocket=new WebSocket(`ws://${t}:${i}`),this._webSocket.onmessage=e=>{let t=e.data;if(t.startsWith(Sz._SERVER_PREFIX)){let e=t.substr(Sz._SERVER_PREFIX.length);rb.Y.Log(`[Reflector] Received server message: ${e.substr(0,64)}`),this._handleServerMessage(e);return}rb.Y.Log(`[Reflector] Received client message: ${t.substr(0,64)}`),this._handleClientMessage()},this._webSocket.onclose=e=>{rb.Y.Log(`[Reflector] Disconnected ${e.code} ${e.reason}`)}}close(){this._webSocket.close()}_handleServerMessage(e){"connected"===e&&SO.SerializeAsync(this._scene).then(e=>{this._webSocket.send(`load|${JSON.stringify(e)}`)})}_handleClientMessage(){}}Sz._SERVER_PREFIX="$$";class SW{constructor(e){this._view=new Float32Array(e),this._itemLength=0}get itemLength(){return this._itemLength}at(e){return e<0||e>=this._itemLength?NaN:this._view[e]}subarray(e,t){return e>=t||e<0?new Float32Array(0):(t>this._itemLength&&(t=this._itemLength),this._view.subarray(e,t))}push(e){this._view[this._itemLength]=e,this._itemLength++,this._itemLength>=this._view.length&&this._growArray()}_growArray(){let e=Math.floor(1.5*this._view.length),t=new Float32Array(e);t.set(this._view),this._view=t}}let SH="timestamp",SX="numPoints",SY=/\r/g;class Sj{static get SliceDataOffset(){return 2}static get NumberOfPointsOffset(){return 1}constructor(e,t){this._scene=e,this._collectDataAtFrame=()=>{let e=r3.F.Now-this._startingTimestamp,t=this.datasets.ids.length,i=this.datasets.startingIndices.itemLength,r=0;if(i>0){let e=this.datasets.startingIndices.at(i-1);r=e+this.datasets.data.at(e+Sj.NumberOfPointsOffset)+Sj.SliceDataOffset}if(this.datasets.startingIndices.push(r),this.datasets.data.push(e),this.datasets.data.push(t),this.datasets.ids.forEach(e=>{let t=this._strategies.get(e);t&&this.datasets.data.push(t.getData())}),this.datasetObservable.hasObservers()){let i=[e,t];for(let e=0;ee.callback(this._datasetMeta,new r_.he(0))),t&&this.addCollectionStrategies(...t)}registerEvent(e,t,i){var r;return this._strategies.has(e)&&!t?void 0:(this._strategies.has(e)&&t&&(null===(r=this._strategies.get(e))||void 0===r||r.dispose(),this._strategies.delete(e)),this._eventRestoreSet.add(e),this.addCollectionStrategies({strategyCallback:t=>{let i=0,r=0,s=t.onAfterRenderObservable.add(()=>{r=i,i=0}),n=this._customEventObservable.add(t=>{e===t.name&&(void 0!==t.value?i=t.value:i++)});return{id:e,getData:()=>r,dispose:()=>{t.onAfterRenderObservable.remove(s),this._customEventObservable.remove(n)}}},category:i}),{name:e})}sendEvent(e){this._customEventObservable.notifyObservers(e)}_restoreStringEvents(){this._eventRestoreSet.size!==this._customEventObservable.observers.length&&this._eventRestoreSet.forEach(e=>{this.registerEvent(e,!0)})}addCollectionStrategies(...e){for(let{strategyCallback:t,category:i,hidden:r}of e){let e=t(this._scene);if(this._strategies.has(e.id)){e.dispose();continue}this.datasets.ids.push(e.id),i&&(i=i.replace(RegExp("@","g"),"")),this._datasetMeta.set(e.id,{color:this._getHexColorFromId(e.id),category:i,hidden:r}),this._strategies.set(e.id,e)}this.metadataObservable.notifyObservers(this._datasetMeta)}_getHexColorFromId(e){let t=0;for(let i=0;i>e&255).toString(16)).substr(-2);return i}getCurrentSlice(){let e=[r3.F.Now-this._startingTimestamp,this.datasets.ids.length];this.datasets.ids.forEach(t=>{let i=this._strategies.get(t);i&&this.datasetObservable.hasObservers()&&e.push(i.getData())}),this.datasetObservable.hasObservers()&&this.datasetObservable.notifyObservers(e)}updateMetadata(e,t,i){let r=this._datasetMeta.get(e);r&&(r[t]=i,this.metadataObservable.notifyObservers(this._datasetMeta))}clear(e){this.datasets.data=new SW(1800),this.datasets.ids.length=0,this.datasets.startingIndices=new SW(1800),this._datasetMeta.clear(),this._strategies.forEach(e=>e.dispose()),this._strategies.clear(),e||this._eventRestoreSet.clear(),this._hasLoadedData=!1}get hasLoadedData(){return this._hasLoadedData}loadFromFileData(e,t){let i=e.replace(SY,"").split("\n").map(e=>e.split(",").filter(e=>e.length>0)).filter(e=>e.length>0),r=Sj.NumberOfPointsOffset;if(i.length<2)return!1;let s={ids:[],data:new SW(1800),startingIndices:new SW(1800)},[n,...a]=i;if(n.length<2||n[0]!==SH||n[r]!==SX)return!1;let o=new Map;for(let e=Sj.SliceDataOffset;ee.dispose()),this._strategies.clear(),!t)for(let e of this.datasets.ids){let t=o.get(e);this._datasetMeta.set(e,{category:t,color:this._getHexColorFromId(e)})}return this.metadataObservable.notifyObservers(this._datasetMeta),this._hasLoadedData=!0,!0}exportDataToCsv(){let e="";e+=`${SH},${SX}`;for(let t=0;t{e.dispose()}),this.datasetObservable.clear(),this.metadataObservable.clear(),this._isStarted=!1,this.datasets=null}}r2.x.prototype.getPerfCollector=function(){return this._perfCollector||(this._perfCollector=new Sj(this)),this._perfCollector};var Sq=i(7521);r_.y$.prototype.runCoroutineAsync=function(e){if(!this._coroutineScheduler){let e=function(e){let t=[],i=[],r=[],s=e.add(()=>{let e=t.length;for(let s=0;s{t.push(e),i.push(s),r.push(n)},dispose:()=>{e.remove(s)}}}(this);this._coroutineScheduler=e.scheduler,this._coroutineSchedulerDispose=e.dispose}return(0,Sq.sM)(e,this._coroutineScheduler)},r_.y$.prototype.cancelAllCoroutines=function(){this._coroutineSchedulerDispose&&this._coroutineSchedulerDispose(),this._coroutineScheduler=void 0,this._coroutineSchedulerDispose=void 0};let SK=`#ifdef GL_ES +precision highp float; +#endif +#define M_PI 3.1415926535897932384626433832795 +varying vec2 vUV;uniform samplerCube cubeMap;void main(void) {vec2 uv=vUV;float longitude=uv.x*2.*M_PI-M_PI+M_PI/2.;float latitude=(1.-uv.y)*M_PI;vec3 dir=vec3( +- sin( longitude )*sin( latitude ), +cos( latitude ), +- cos( longitude )*sin( latitude ) +);normalize( dir );gl_FragColor=textureCube( cubeMap,dir );}`;nw.v.ShadersStore.equirectangularPanoramaPixelShader=SK;class S$ extends ns{constructor(e,t={}){super(e),this.options=t,this._direction=new rf.P(0,0,-1),this._mat=new rf.y3,this._onSelectEnabled=!1,this._origin=new rf.P(0,0,0),this.lastNativeXRHitResults=[],this.onHitTestResultObservable=new r_.y$,this._onHitTestResults=e=>{let t=e.map(e=>{let t=rf.y3.FromArray(e.hitMatrix);return this._xrSessionManager.scene.useRightHandedSystem||t.toggleModelMatrixHandInPlace(),this.options.worldParentNode&&t.multiplyToRef(this.options.worldParentNode.getWorldMatrix(),t),{xrHitResult:e,transformationMatrix:t}});this.lastNativeXRHitResults=e,this.onHitTestResultObservable.notifyObservers(t)},this._onSelect=e=>{this._onSelectEnabled&&S$.XRHitTestWithSelectEvent(e,this._xrSessionManager.referenceSpace)},this.xrNativeFeatureName="hit-test",sg.w1.Warn("A newer version of this plugin is available")}static XRHitTestWithRay(e,t,i,r){return e.requestHitTest(t,i).then(e=>e.filter(r||(e=>!!e.hitMatrix)))}static XRHitTestWithSelectEvent(e,t){let i=e.frame.getPose(e.inputSource.targetRaySpace,t);if(!i)return Promise.resolve([]);let r=new XRRay(i.transform);return this.XRHitTestWithRay(e.frame.session,r,t)}attach(){return!!super.attach()&&(this.options.testOnPointerDownOnly&&this._xrSessionManager.session.addEventListener("select",this._onSelect,!1),!0)}detach(){return!!super.detach()&&(this._onSelectEnabled=!1,this._xrSessionManager.session.removeEventListener("select",this._onSelect),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(!this.attached||this.options.testOnPointerDownOnly)return;let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;rf.y3.FromArrayToRef(t.transform.matrix,0,this._mat),rf.P.TransformCoordinatesFromFloatsToRef(0,0,0,this._mat,this._origin),rf.P.TransformCoordinatesFromFloatsToRef(0,0,-1,this._mat,this._direction),this._direction.subtractInPlace(this._origin),this._direction.normalize();let i=new XRRay({x:this._origin.x,y:this._origin.y,z:this._origin.z,w:0},{x:this._direction.x,y:this._direction.y,z:this._direction.z,w:0});S$.XRHitTestWithRay(this._xrSessionManager.session,i,this._xrSessionManager.referenceSpace).then(this._onHitTestResults)}}S$.Name=ni.HIT_TEST,S$.Version=1,nr.AddWebXRFeature(S$.Name,(e,t)=>()=>new S$(e,t),S$.Version,!1);let SQ=0;class SZ extends ns{set referenceSpaceForFrameAnchors(e){this._referenceSpaceForFrameAnchors=e}constructor(e,t={}){super(e),this._options=t,this._lastFrameDetected=new Set,this._trackedAnchors=[],this._futureAnchors=[],this.onAnchorAddedObservable=new r_.y$,this.onAnchorRemovedObservable=new r_.y$,this.onAnchorUpdatedObservable=new r_.y$,this._tmpVector=new rf.P,this._tmpQuaternion=new rf._f,this.xrNativeFeatureName="anchors"}_populateTmpTransformation(e,t){return this._tmpVector.copyFrom(e),this._tmpQuaternion.copyFrom(t),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpVector.z*=-1,this._tmpQuaternion.z*=-1,this._tmpQuaternion.w*=-1),{position:this._tmpVector,rotationQuaternion:this._tmpQuaternion}}async addAnchorPointUsingHitTestResultAsync(e,t=new rf.P,i=new rf._f){this._populateTmpTransformation(t,i);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w});if(e.xrHitResult.createAnchor)try{let t=await e.xrHitResult.createAnchor(r);return new Promise((e,i)=>{this._futureAnchors.push({nativeAnchor:t,resolved:!1,submitted:!0,xrTransformation:r,resolve:e,reject:i})})}catch(e){throw Error(e)}else throw this.detach(),Error("Anchors not enabled in this environment/browser")}async addAnchorAtPositionAndRotationAsync(e,t=new rf._f,i=!1){this._populateTmpTransformation(e,t);let r=new XRRigidTransform({x:this._tmpVector.x,y:this._tmpVector.y,z:this._tmpVector.z},{x:this._tmpQuaternion.x,y:this._tmpQuaternion.y,z:this._tmpQuaternion.z,w:this._tmpQuaternion.w}),s=i&&this.attached&&this._xrSessionManager.currentFrame?await this._createAnchorAtTransformation(r,this._xrSessionManager.currentFrame):void 0;return new Promise((e,t)=>{this._futureAnchors.push({nativeAnchor:s,resolved:!1,submitted:!1,xrTransformation:r,resolve:e,reject:t})})}get anchors(){return this._trackedAnchors}detach(){if(!super.detach())return!1;if(!this._options.doNotRemoveAnchorsOnSessionEnded)for(;this._trackedAnchors.length;){let e=this._trackedAnchors.pop();if(e){try{e.remove()}catch(e){}this.onAnchorRemovedObservable.notifyObservers(e)}}return!0}dispose(){this._futureAnchors.length=0,super.dispose(),this.onAnchorAddedObservable.clear(),this.onAnchorRemovedObservable.clear(),this.onAnchorUpdatedObservable.clear()}_onXRFrame(e){if(!this.attached||!e)return;let t=e.trackedAnchors;if(t){let i=this._trackedAnchors.filter(e=>!t.has(e.xrAnchor)).map(e=>this._trackedAnchors.indexOf(e)),r=0;i.forEach(e=>{let t=this._trackedAnchors.splice(e-r,1)[0];this.onAnchorRemovedObservable.notifyObservers(t),r++}),t.forEach(t=>{if(this._lastFrameDetected.has(t)){let i=this._findIndexInAnchorArray(t),r=this._trackedAnchors[i];try{this._updateAnchorWithXRFrame(t,r,e),r.attachedNode&&(r.attachedNode.rotationQuaternion=r.attachedNode.rotationQuaternion||new rf._f,r.transformationMatrix.decompose(r.attachedNode.scaling,r.attachedNode.rotationQuaternion,r.attachedNode.position)),this.onAnchorUpdatedObservable.notifyObservers(r)}catch(e){sg.w1.Warn("Anchor could not be updated")}}else{let i={id:SQ++,xrAnchor:t,remove:()=>t.delete()},r=this._updateAnchorWithXRFrame(t,i,e);this._trackedAnchors.push(r),this.onAnchorAddedObservable.notifyObservers(r);let s=this._futureAnchors.filter(e=>e.nativeAnchor===t)[0];s&&(s.resolve(r),s.resolved=!0)}}),this._lastFrameDetected=t}this._futureAnchors.forEach(t=>{t.resolved||t.submitted||(this._createAnchorAtTransformation(t.xrTransformation,e).then(e=>{t.nativeAnchor=e},e=>{t.resolved=!0,t.reject(e)}),t.submitted=!0)})}_findIndexInAnchorArray(e){for(let t=0;t()=>new SZ(e,t),SZ.Version);let SJ=0;class S0 extends ns{constructor(e,t={}){super(e),this._options=t,this._detectedPlanes=[],this._enabled=!1,this._lastFrameDetected=new Set,this.onPlaneAddedObservable=new r_.y$,this.onPlaneRemovedObservable=new r_.y$,this.onPlaneUpdatedObservable=new r_.y$,this.xrNativeFeatureName="plane-detection",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){if(!super.detach())return!1;if(!this._options.doNotRemovePlanesOnSessionEnded)for(;this._detectedPlanes.length;){let e=this._detectedPlanes.pop();e&&this.onPlaneRemovedObservable.notifyObservers(e)}return!0}dispose(){super.dispose(),this.onPlaneAddedObservable.clear(),this.onPlaneRemovedObservable.clear(),this.onPlaneUpdatedObservable.clear()}isCompatible(){return"undefined"!=typeof XRPlane}async initiateRoomCapture(){return this._xrSessionManager.session.initiateRoomCapture?this._xrSessionManager.session.initiateRoomCapture():Promise.reject("initiateRoomCapture is not supported on this session")}_onXRFrame(e){var t;if(!this.attached||!this._enabled||!e)return;let i=e.detectedPlanes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedPlanes);if(i){for(let e=0;e{if(this._lastFrameDetected.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._findIndexInPlaneArray(t),r=this._detectedPlanes[i];this._updatePlaneWithXRPlane(t,r,e),this.onPlaneUpdatedObservable.notifyObservers(r)}}else{let i={id:SJ++,xrPlane:t,polygonDefinition:[]},r=this._updatePlaneWithXRPlane(t,i,e);this._detectedPlanes.push(r),this.onPlaneAddedObservable.notifyObservers(r)}}),this._lastFrameDetected=i}}_init(){let e=()=>{this._enabled=!0,this._detectedPlanes.length&&(this._detectedPlanes.length=0)};if(this._xrSessionManager.isNative&&this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions&&this._xrSessionManager.session.trySetPreferredPlaneDetectorOptions(this._options.preferredDetectorOptions),!this._xrSessionManager.session.updateWorldTrackingState){e();return}this._xrSessionManager.session.updateWorldTrackingState({planeDetectionState:{enabled:!0}}),e()}_updatePlaneWithXRPlane(e,t,i){t.polygonDefinition=e.polygon.map(e=>{let t=this._xrSessionManager.scene.useRightHandedSystem?1:-1;return new rf.P(e.x,e.y,e.z*t)});let r=i.getPose(e.planeSpace,this._xrSessionManager.referenceSpace);if(r){let e=t.transformationMatrix||new rf.y3;rf.y3.FromArrayToRef(r.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),t.transformationMatrix=e,this._options.worldParentNode&&e.multiplyToRef(this._options.worldParentNode.getWorldMatrix(),e)}return t}_findIndexInPlaneArray(e){for(let t=0;t()=>new S0(e,t),S0.Version);class S1 extends ns{constructor(e,t={}){super(e),this.options=t,this.onBackgroundStateChangedObservable=new r_.y$}attach(){return this._setBackgroundState(!1),super.attach()}detach(){return this._setBackgroundState(!0),super.detach()}dispose(){super.dispose(),this.onBackgroundStateChangedObservable.clear()}_onXRFrame(e){}_setBackgroundState(e){let t=this._xrSessionManager.scene;if(!this.options.ignoreEnvironmentHelper){if(this.options.environmentHelperRemovalFlags){if(this.options.environmentHelperRemovalFlags.skyBox){let i=t.getMeshByName("BackgroundSkybox");i&&i.setEnabled(e)}if(this.options.environmentHelperRemovalFlags.ground){let i=t.getMeshByName("BackgroundPlane");i&&i.setEnabled(e)}}else{let i=t.getMeshByName("BackgroundHelper");i&&i.setEnabled(e)}}this.options.backgroundMeshes&&this.options.backgroundMeshes.forEach(t=>t.setEnabled(e)),this.onBackgroundStateChangedObservable.notifyObservers(e)}}S1.Name=ni.BACKGROUND_REMOVER,S1.Version=1,nr.AddWebXRFeature(S1.Name,(e,t)=>()=>new S1(e,t),S1.Version,!0);class S2 extends ns{_createPhysicsImpostor(e){let t=this._options.physicsProperties.impostorType||na.SphereImpostor,i=this._options.physicsProperties.impostorSize||.1,r=hM("impostor-mesh-"+e.uniqueId,{diameterX:"number"==typeof i?i:i.width,diameterY:"number"==typeof i?i:i.height,diameterZ:"number"==typeof i?i:i.depth});r.isVisible=this._debugMode,r.isPickable=!1,r.rotationQuaternion=new rf._f;let s=e.grip||e.pointer;r.position.copyFrom(s.position),r.rotationQuaternion.copyFrom(s.rotationQuaternion);let n=new na(r,t,Object.assign({mass:0},this._options.physicsProperties));this._controllers[e.uniqueId]={xrController:e,impostor:n,impostorMesh:r}}constructor(e,t){super(e),this._options=t,this._attachController=e=>{this._controllers[e.uniqueId]||(this._xrSessionManager.scene.isPhysicsEnabled()||rb.Y.Warn("physics engine not enabled, skipped. Please add this controller manually."),this._options.physicsProperties.useControllerMesh&&e.inputSource.gamepad?e.onMotionControllerInitObservable.addOnce(t=>{t._doNotLoadControllerMesh?this._createPhysicsImpostor(e):t.onModelLoadedObservable.addOnce(()=>{let i=new na(t.rootMesh,na.MeshImpostor,Object.assign({mass:0},this._options.physicsProperties)),r=e.grip||e.pointer;this._controllers[e.uniqueId]={xrController:e,impostor:i,oldPos:r.position.clone(),oldRotation:r.rotationQuaternion.clone()}})}):this._createPhysicsImpostor(e))},this._controllers={},this._debugMode=!1,this._delta=0,this._lastTimestamp=0,this._tmpQuaternion=new rf._f,this._tmpVector=new rf.P,this._options.physicsProperties||(this._options.physicsProperties={})}_enablePhysicsDebug(){this._debugMode=!0,Object.keys(this._controllers).forEach(e=>{let t=this._controllers[e];t.impostorMesh&&(t.impostorMesh.isVisible=!0)})}addController(e){this._attachController(e)}attach(){if(!super.attach())return!1;if(!this._options.xrInput)return!0;if(this._options.xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._options.xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),this._options.enableHeadsetImpostor){let e=this._options.headsetImpostorParams||{impostorType:na.SphereImpostor,restitution:.8,impostorSize:.3},t=e.impostorSize||.3;this._headsetMesh=hM("headset-mesh",{diameterX:"number"==typeof t?t:t.width,diameterY:"number"==typeof t?t:t.height,diameterZ:"number"==typeof t?t:t.depth}),this._headsetMesh.rotationQuaternion=new rf._f,this._headsetMesh.isVisible=!1,this._headsetImpostor=new na(this._headsetMesh,e.impostorType,Object.assign({mass:0},e))}return!0}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._headsetMesh&&this._headsetMesh.dispose(),!0)}getHeadsetImpostor(){return this._headsetImpostor}getImpostorForController(e){let t="string"==typeof e?e:e.uniqueId;return this._controllers[t]?this._controllers[t].impostor:null}setPhysicsProperties(e){this._options.physicsProperties=Object.assign(Object.assign({},this._options.physicsProperties),e)}_onXRFrame(e){var t,i;if(this._delta=this._xrSessionManager.currentTimestamp-this._lastTimestamp,this._lastTimestamp=this._xrSessionManager.currentTimestamp,this._headsetMesh&&this._headsetImpostor){if(this._headsetMesh.position.copyFrom(this._options.xrInput.xrCamera.globalPosition),this._headsetMesh.rotationQuaternion.copyFrom(this._options.xrInput.xrCamera.absoluteRotation),null===(t=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===t?void 0:t.linearVelocity){let e=this._options.xrInput.xrCamera._lastXRViewerPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setLinearVelocity(this._tmpVector)}if(null===(i=this._options.xrInput.xrCamera._lastXRViewerPose)||void 0===i?void 0:i.angularVelocity){let e=this._options.xrInput.xrCamera._lastXRViewerPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),this._headsetImpostor.setAngularVelocity(this._tmpVector)}}Object.keys(this._controllers).forEach(e=>{var t,i;let r=this._controllers[e],s=r.xrController.grip||r.xrController.pointer,n=r.oldPos||r.impostorMesh.position;if(null===(t=r.xrController._lastXRPose)||void 0===t?void 0:t.linearVelocity){let e=r.xrController._lastXRPose.linearVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setLinearVelocity(this._tmpVector)}else s.position.subtractToRef(n,this._tmpVector),this._tmpVector.scaleInPlace(1e3/this._delta),r.impostor.setLinearVelocity(this._tmpVector);n.copyFrom(s.position),this._debugMode&&rb.Y.Log([this._tmpVector,"linear"]);let a=r.oldRotation||r.impostorMesh.rotationQuaternion;if(null===(i=r.xrController._lastXRPose)||void 0===i?void 0:i.angularVelocity){let e=r.xrController._lastXRPose.angularVelocity;this._tmpVector.set(e.x,e.y,e.z),r.impostor.setAngularVelocity(this._tmpVector)}else if(!a.equalsWithEpsilon(s.rotationQuaternion)){a.conjugateInPlace().multiplyToRef(s.rotationQuaternion,this._tmpQuaternion);let e=Math.sqrt(this._tmpQuaternion.x*this._tmpQuaternion.x+this._tmpQuaternion.y*this._tmpQuaternion.y+this._tmpQuaternion.z*this._tmpQuaternion.z);if(this._tmpVector.set(this._tmpQuaternion.x,this._tmpQuaternion.y,this._tmpQuaternion.z),e<.001)this._tmpVector.scaleInPlace(2);else{let t=2*Math.atan2(e,this._tmpQuaternion.w);this._tmpVector.scaleInPlace(t/(this._delta/1e3*e))}r.impostor.setAngularVelocity(this._tmpVector)}a.copyFrom(s.rotationQuaternion),this._debugMode&&rb.Y.Log([this._tmpVector,this._tmpQuaternion,"angular"])})}_detachController(e){let t=this._controllers[e];t&&(t.impostorMesh&&t.impostorMesh.dispose(),delete this._controllers[e])}}S2.Name=ni.PHYSICS_CONTROLLERS,S2.Version=1,nr.AddWebXRFeature(S2.Name,(e,t)=>()=>new S2(e,t),S2.Version,!0);class S3 extends ns{constructor(e,t={}){super(e),this.options=t,this._tmpMat=new rf.y3,this._tmpPos=new rf.P,this._tmpQuat=new rf._f,this._initHitTestSource=e=>{if(!e)return;let t=new XRRay(this.options.offsetRay||{}),i={space:this.options.useReferenceSpace?e:this._xrSessionManager.viewerReferenceSpace,offsetRay:t};if(this.options.entityTypes&&(i.entityTypes=this.options.entityTypes),!i.space){sg.w1.Warn("waiting for viewer reference space to initialize");return}this._xrSessionManager.session.requestHitTestSource(i).then(e=>{this._xrHitTestSource&&this._xrHitTestSource.cancel(),this._xrHitTestSource=e})},this.autoCloneTransformation=!1,this.onHitTestResultObservable=new r_.y$,this.paused=!1,this.xrNativeFeatureName="hit-test",sg.w1.Warn("Hit test is an experimental and unstable feature.")}attach(){if(!super.attach()||!this._xrSessionManager.session.requestHitTestSource)return!1;if(this.options.disablePermanentHitTest||(this._xrSessionManager.referenceSpace&&this._initHitTestSource(this._xrSessionManager.referenceSpace),this._xrSessionManager.onXRReferenceSpaceChanged.add(this._initHitTestSource)),this.options.enableTransientHitTest){let e=new XRRay(this.options.transientOffsetRay||{});this._xrSessionManager.session.requestHitTestSourceForTransientInput({profile:this.options.transientHitTestProfile||"generic-touchscreen",offsetRay:e,entityTypes:this.options.entityTypes}).then(e=>{this._transientXrHitTestSource=e})}return!0}detach(){return!!super.detach()&&(this._xrHitTestSource&&(this._xrHitTestSource.cancel(),this._xrHitTestSource=null),this._xrSessionManager.onXRReferenceSpaceChanged.removeCallback(this._initHitTestSource),this._transientXrHitTestSource&&(this._transientXrHitTestSource.cancel(),this._transientXrHitTestSource=null),!0)}dispose(){super.dispose(),this.onHitTestResultObservable.clear()}_onXRFrame(e){if(this.attached&&!this.paused){if(this._xrHitTestSource){let t=e.getHitTestResults(this._xrHitTestSource);this._processWebXRHitTestResult(t)}this._transientXrHitTestSource&&e.getHitTestResultsForTransientInput(this._transientXrHitTestSource).forEach(e=>{this._processWebXRHitTestResult(e.results,e.inputSource)})}}_processWebXRHitTestResult(e,t){let i=[];e.forEach(e=>{let r=e.getPose(this._xrSessionManager.referenceSpace);if(!r)return;let s=r.transform.position,n=r.transform.orientation;this._tmpPos.set(s.x,s.y,s.z),this._tmpQuat.set(n.x,n.y,n.z,n.w),rf.y3.FromFloat32ArrayToRefScaled(r.transform.matrix,0,1,this._tmpMat),this._xrSessionManager.scene.useRightHandedSystem||(this._tmpPos.z*=-1,this._tmpQuat.z*=-1,this._tmpQuat.w*=-1,this._tmpMat.toggleModelMatrixHandInPlace());let a={position:this.autoCloneTransformation?this._tmpPos.clone():this._tmpPos,rotationQuaternion:this.autoCloneTransformation?this._tmpQuat.clone():this._tmpQuat,transformationMatrix:this.autoCloneTransformation?this._tmpMat.clone():this._tmpMat,inputSource:t,isTransient:!!t,xrHitResult:e};i.push(a)}),this.onHitTestResultObservable.notifyObservers(i)}}S3.Name=ni.HIT_TEST,S3.Version=2,nr.AddWebXRFeature(S3.Name,(e,t)=>()=>new S3(e,t),S3.Version,!1);class S4 extends ns{get featurePointCloud(){return this._featurePointCloud}constructor(e){super(e),this._enabled=!1,this._featurePointCloud=[],this.onFeaturePointsAddedObservable=new r_.y$,this.onFeaturePointsUpdatedObservable=new r_.y$,this.xrNativeFeatureName="bjsfeature-points",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return!!super.detach()&&(this.featurePointCloud.length=0,!0)}dispose(){super.dispose(),this._featurePointCloud.length=0,this.onFeaturePointsUpdatedObservable.clear(),this.onFeaturePointsAddedObservable.clear()}_onXRFrame(e){if(!this.attached||!this._enabled||!e)return;let t=e.featurePointCloud;if(t&&0!==t.length){if(t.length%5!=0)throw Error("Received malformed feature point cloud of length: "+t.length);let e=t.length/5,i=[],r=[];for(let s=0;s0&&this.onFeaturePointsAddedObservable.notifyObservers(r),i.length>0&&this.onFeaturePointsUpdatedObservable.notifyObservers(i)}}_init(){this._xrSessionManager.session.trySetFeaturePointCloudEnabled&&this._xrSessionManager.session.trySetFeaturePointCloudEnabled(!0)&&(this._enabled=!0)}}S4.Name=ni.FEATURE_POINTS,S4.Version=1,nr.AddWebXRFeature(S4.Name,e=>()=>new S4(e),S4.Version);let S5=0;class S6 extends ns{constructor(e,t={}){super(e),this._options=t,this._detectedMeshes=new Map,this.onMeshAddedObservable=new r_.y$,this.onMeshRemovedObservable=new r_.y$,this.onMeshUpdatedObservable=new r_.y$,this.xrNativeFeatureName="mesh-detection",this._options.generateMeshes&&(this._options.convertCoordinateSystems=!0),this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}detach(){return!!super.detach()&&(this._xrSessionManager.isNative&&this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!1),this._options.doNotRemoveMeshesOnSessionEnded||(this._detectedMeshes.forEach(e=>{this.onMeshRemovedObservable.notifyObservers(e)}),this._detectedMeshes.clear()),!0)}dispose(){super.dispose(),this.onMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onMeshUpdatedObservable.clear()}_onXRFrame(e){var t;try{if(!this.attached||!e)return;let i=e.detectedMeshes||(null===(t=e.worldInformation)||void 0===t?void 0:t.detectedMeshes);if(i){let t=new Set;this._detectedMeshes.forEach((e,r)=>{i.has(r)||t.add(r)}),t.forEach(e=>{let t=this._detectedMeshes.get(e);t&&(this.onMeshRemovedObservable.notifyObservers(t),this._detectedMeshes.delete(e))}),i.forEach(t=>{if(this._detectedMeshes.has(t)){if(t.lastChangedTime===this._xrSessionManager.currentTimestamp){let i=this._detectedMeshes.get(t);i&&(this._updateVertexDataWithXRMesh(t,i,e),this.onMeshUpdatedObservable.notifyObservers(i))}}else{let i={id:S5++,xrMesh:t},r=this._updateVertexDataWithXRMesh(t,i,e);this._detectedMeshes.set(t,r),this.onMeshAddedObservable.notifyObservers(r)}})}}catch(e){rb.Y.Log(e.stack)}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.trySetMeshDetectorEnabled&&this._xrSessionManager.session.trySetMeshDetectorEnabled(!0),this._options.preferredDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions&&this._xrSessionManager.session.trySetPreferredMeshDetectorOptions(this._options.preferredDetectorOptions))}_updateVertexDataWithXRMesh(e,t,i){var r;t.xrMesh=e,t.worldParentNode=this._options.worldParentNode;let s=e.vertices||e.positions;if(this._options.convertCoordinateSystems){if(this._xrSessionManager.scene.useRightHandedSystem)t.positions=s,t.normals=e.normals;else{t.positions=new Float32Array(s.length);for(let e=0;e()=>new S6(e,t),S6.Version,!1),(tl=rh||(rh={}))[tl.NotReceived=0]="NotReceived",tl[tl.Waiting=1]="Waiting",tl[tl.Received=2]="Received";class S8 extends ns{constructor(e,t){super(e),this.options=t,this.onUntrackableImageFoundObservable=new r_.y$,this.onTrackableImageFoundObservable=new r_.y$,this.onTrackedImageUpdatedObservable=new r_.y$,this._trackableScoreStatus=rh.NotReceived,this._trackedImages=[],this.xrNativeFeatureName="image-tracking"}attach(){return super.attach()}detach(){return super.detach()}getTrackedImageById(e){return this._trackedImages[e]||null}dispose(){super.dispose(),this._trackedImages.forEach(e=>{e.originalBitmap.close()}),this._trackedImages.length=0,this.onTrackableImageFoundObservable.clear(),this.onUntrackableImageFoundObservable.clear(),this.onTrackedImageUpdatedObservable.clear()}async getXRSessionInitExtension(){if(!this.options.images||!this.options.images.length)return{};let e=this.options.images.map(e=>"string"==typeof e.src?this._xrSessionManager.scene.getEngine()._createImageBitmapFromSource(e.src):Promise.resolve(e.src));try{let t=await Promise.all(e);return this._originalTrackingRequest=t.map((e,t)=>({image:e,widthInMeters:this.options.images[t].estimatedRealWorldWidth})),{trackedImages:this._originalTrackingRequest}}catch(e){return sg.w1.Error("Error loading images for tracking, WebXRImageTracking disabled for this session."),{}}}_onXRFrame(e){if(e.getImageTrackingResults&&this._trackableScoreStatus!==rh.Waiting){if(this._trackableScoreStatus===rh.NotReceived){this._checkScoresAsync();return}for(let t of e.getImageTrackingResults()){let i=!1,r=t.index,s=this._trackedImages[r];if(!s)continue;s.xrTrackingResult=t,s.realWorldWidth!==t.measuredWidthInMeters&&(s.realWorldWidth=t.measuredWidthInMeters,i=!0);let n=e.getPose(t.imageSpace,this._xrSessionManager.referenceSpace);if(n){let e=s.transformationMatrix;rf.y3.FromArrayToRef(n.transform.matrix,0,e),this._xrSessionManager.scene.useRightHandedSystem||e.toggleModelMatrixHandInPlace(),i=!0}let a="emulated"===t.trackingState;s.emulated!==a&&(s.emulated=a,i=!0),i&&this.onTrackedImageUpdatedObservable.notifyObservers(s)}}}async _checkScoresAsync(){if(!this._xrSessionManager.session.getTrackedImageScores||this._trackableScoreStatus!==rh.NotReceived)return;this._trackableScoreStatus=rh.Waiting;let e=await this._xrSessionManager.session.getTrackedImageScores();if(!e||0===e.length){this._trackableScoreStatus=rh.NotReceived;return}for(let t=0;t0?rh.Received:rh.NotReceived}}S8.Name=ni.IMAGE_TRACKING,S8.Version=1,nr.AddWebXRFeature(S8.Name,(e,t)=>()=>new S8(e,t),S8.Version,!1);class S7 extends ns{constructor(e,t){super(e),this.options=t,this._domOverlayType=null,this._beforeXRSelectListener=null,this._element=null,this.xrNativeFeatureName="dom-overlay",sg.w1.Warn("dom-overlay is an experimental and unstable feature.")}attach(){return!!super.attach()&&!!this._xrSessionManager.session.domOverlayState&&null!==this._xrSessionManager.session.domOverlayState.type&&(this._domOverlayType=this._xrSessionManager.session.domOverlayState.type,null!==this._element&&!0===this.options.supressXRSelectEvents&&(this._beforeXRSelectListener=e=>{e.preventDefault()},this._element.addEventListener("beforexrselect",this._beforeXRSelectListener)),!0)}get domOverlayType(){return this._domOverlayType}dispose(){super.dispose(),null!==this._element&&this._beforeXRSelectListener&&this._element.removeEventListener("beforexrselect",this._beforeXRSelectListener)}_onXRFrame(e){}async getXRSessionInitExtension(){if(void 0===this.options.element)return sg.w1.Warn('"element" option must be provided to attach xr-dom-overlay feature.'),{};if("string"==typeof this.options.element){let e=document.querySelector(this.options.element);if(null===e)return sg.w1.Warn(`element not found '${this.options.element}' (not requesting xr-dom-overlay)`),{};this._element=e}else this._element=this.options.element;return{domOverlay:{root:this._element}}}}S7.Name=ni.DOM_OVERLAY,S7.Version=1,nr.AddWebXRFeature(S7.Name,(e,t)=>()=>new S7(e,t),S7.Version,!1);class S9 extends ns{get movementDirection(){return this._movementDirection}get movementEnabled(){return this._featureContext.movementEnabled}set movementEnabled(e){this._featureContext.movementEnabled=e}get movementOrientationFollowsViewerPose(){return this._featureContext.movementOrientationFollowsViewerPose}set movementOrientationFollowsViewerPose(e){this._featureContext.movementOrientationFollowsViewerPose=e}get movementSpeed(){return this._featureContext.movementSpeed}set movementSpeed(e){this._featureContext.movementSpeed=e}get movementThreshold(){return this._featureContext.movementThreshold}set movementThreshold(e){this._featureContext.movementThreshold=e}get rotationEnabled(){return this._featureContext.rotationEnabled}set rotationEnabled(e){this._featureContext.rotationEnabled=e}get rotationSpeed(){return this._featureContext.rotationSpeed}set rotationSpeed(e){this._featureContext.rotationSpeed=e}get rotationThreshold(){return this._featureContext.rotationThreshold}set rotationThreshold(e){this._featureContext.rotationThreshold=e}constructor(e,t){var i,r,s,n,a,o;if(super(e),this._controllers={},this._currentRegistrationConfigurations=[],this._movementDirection=new rf._f,this._tmpRotationMatrix=rf.y3.Identity(),this._tmpTranslationDirection=new rf.P,this._tmpMovementTranslation=new rf.P,this._tempCacheQuaternion=new rf._f,this._attachController=e=>{if(this._controllers[e.uniqueId])return;this._controllers[e.uniqueId]={xrController:e,registeredComponents:[]};let t=this._controllers[e.uniqueId];if("tracked-pointer"===t.xrController.inputSource.targetRayMode&&t.xrController.inputSource.gamepad){let i=()=>{if(e.motionController)for(let i of this._currentRegistrationConfigurations){let r=null;if(i.allowedComponentTypes)for(let t of i.allowedComponentTypes){let i=e.motionController.getComponentOfType(t);if(null!==i){r=i;break}}if(i.mainComponentOnly){let t=e.motionController.getMainComponent();if(null===t)continue;r=t}if("function"==typeof i.componentSelectionPredicate&&(r=i.componentSelectionPredicate(e)),r&&i.forceHandedness&&e.inputSource.handedness!==i.forceHandedness||null===r)continue;let s={registrationConfiguration:i,component:r};t.registeredComponents.push(s),"axisChangedHandler"in i&&(s.onAxisChangedObserver=r.onAxisValueChangedObservable.add(e=>{i.axisChangedHandler(e,this._movementState,this._featureContext,this._xrInput)})),"buttonChangedhandler"in i&&(s.onButtonChangedObserver=r.onButtonStateChangedObservable.add(()=>{r.changes.pressed&&i.buttonChangedhandler(r.changes.pressed,this._movementState,this._featureContext,this._xrInput)}))}};e.motionController?i():e.onMotionControllerInitObservable.addOnce(()=>{i()})}},!t||void 0===t.xrInput){sg.w1.Error('WebXRControllerMovement feature requires "xrInput" option.');return}Array.isArray(t.customRegistrationConfigurations)?this._currentRegistrationConfigurations=t.customRegistrationConfigurations:this._currentRegistrationConfigurations=S9.REGISTRATIONS.default,this._featureContext={movementEnabled:t.movementEnabled||!0,movementOrientationFollowsViewerPose:null===(i=t.movementOrientationFollowsViewerPose)||void 0===i||i,movementSpeed:null!==(r=t.movementSpeed)&&void 0!==r?r:1,movementThreshold:null!==(s=t.movementThreshold)&&void 0!==s?s:.25,rotationEnabled:null===(n=t.rotationEnabled)||void 0===n||n,rotationSpeed:null!==(a=t.rotationSpeed)&&void 0!==a?a:1,rotationThreshold:null!==(o=t.rotationThreshold)&&void 0!==o?o:.25},this._movementState={moveX:0,moveY:0,rotateX:0,rotateY:0},this._xrInput=t.xrInput}attach(){return!!super.attach()&&(this._xrInput.controllers.forEach(this._attachController),this._addNewAttachObserver(this._xrInput.onControllerAddedObservable,this._attachController),this._addNewAttachObserver(this._xrInput.onControllerRemovedObservable,e=>{this._detachController(e.uniqueId)}),!0)}detach(){return!!super.detach()&&(Object.keys(this._controllers).forEach(e=>{this._detachController(e)}),this._controllers={},!0)}_onXRFrame(e){if(this.attached){if(0!==this._movementState.rotateX&&this._featureContext.rotationEnabled){let e=.001*this._xrSessionManager.scene.getEngine().getDeltaTime()*this._featureContext.rotationSpeed*this._movementState.rotateX*(this._xrSessionManager.scene.useRightHandedSystem?-1:1);this._featureContext.movementOrientationFollowsViewerPose?(this._xrInput.xrCamera.cameraRotation.y+=e,rf._f.RotationYawPitchRollToRef(e,0,0,this._tempCacheQuaternion),this._xrInput.xrCamera.rotationQuaternion.multiplyToRef(this._tempCacheQuaternion,this._movementDirection)):(rf._f.RotationYawPitchRollToRef(3*e,0,0,this._tempCacheQuaternion),this._movementDirection.multiplyInPlace(this._tempCacheQuaternion))}else this._featureContext.movementOrientationFollowsViewerPose&&this._movementDirection.copyFrom(this._xrInput.xrCamera.rotationQuaternion);(this._movementState.moveX||this._movementState.moveY)&&this._featureContext.movementEnabled&&(rf.y3.FromQuaternionToRef(this._movementDirection,this._tmpRotationMatrix),this._tmpTranslationDirection.set(this._movementState.moveX,0,this._movementState.moveY*(this._xrSessionManager.scene.useRightHandedSystem?1:-1)),rf.P.TransformCoordinatesToRef(this._tmpTranslationDirection,this._tmpRotationMatrix,this._tmpMovementTranslation),this._tmpMovementTranslation.scaleInPlace(this._xrInput.xrCamera._computeLocalCameraSpeed()*this._featureContext.movementSpeed),this._xrInput.xrCamera.cameraDirection.addInPlace(this._tmpMovementTranslation))}}_detachController(e){let t=this._controllers[e];if(t){for(let e of t.registeredComponents)e.onAxisChangedObserver&&e.component.onAxisValueChangedObservable.remove(e.onAxisChangedObserver),e.onButtonChangedObserver&&e.component.onButtonStateChangedObservable.remove(e.onButtonChangedObserver);delete this._controllers[e]}}}S9.Name=ni.MOVEMENT,S9.REGISTRATIONS={default:[{allowedComponentTypes:[pJ.THUMBSTICK_TYPE,pJ.TOUCHPAD_TYPE],forceHandedness:"left",axisChangedHandler:(e,t,i)=>{t.rotateX=Math.abs(e.x)>i.rotationThreshold?e.x:0,t.rotateY=Math.abs(e.y)>i.rotationThreshold?e.y:0}},{allowedComponentTypes:[pJ.THUMBSTICK_TYPE,pJ.TOUCHPAD_TYPE],forceHandedness:"right",axisChangedHandler:(e,t,i)=>{t.moveX=Math.abs(e.x)>i.movementThreshold?e.x:0,t.moveY=Math.abs(e.y)>i.movementThreshold?e.y:0}}]},S9.Version=1,nr.AddWebXRFeature(S9.Name,(e,t)=>()=>new S9(e,t),S9.Version,!0);class Ee extends ns{constructor(e,t){super(e),this.options=t,this._canvasContext=null,this._reflectionCubeMap=null,this._xrLightEstimate=null,this._xrLightProbe=null,this._xrWebGLBinding=null,this._lightDirection=rf.P.Up().negateInPlace(),this._lightColor=rm.Wo.White(),this._intensity=1,this._sphericalHarmonics=new uf,this._cubeMapPollTime=Date.now(),this._lightEstimationPollTime=Date.now(),this._reflectionCubeMapTextureSize=16,this.directionalLight=null,this.onReflectionCubeMapUpdatedObservable=new r_.y$,this._updateReflectionCubeMap=()=>{var e;if(!this._xrLightProbe)return;if(this.options.cubeMapPollInterval){let e=Date.now();if(e-this._cubeMapPollTime{this._xrSessionManager.scene.markAllMaterialsAsDirty(1),this.onReflectionCubeMapUpdatedObservable.notifyObservers(this._reflectionCubeMap),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap)}))}},this.xrNativeFeatureName="light-estimation",this.options.createDirectionalLightSource&&(this.directionalLight=new dv("light estimation directional",this._lightDirection,this._xrSessionManager.scene),this.directionalLight.position=new rf.P(0,8,0),this.directionalLight.intensity=0,this.directionalLight.falloffType=sS.m.FALLOFF_GLTF),this._hdrFilter=new ft(this._xrSessionManager.scene.getEngine()),sg.w1.Warn("light-estimation is an experimental and unstable feature.")}get reflectionCubeMapTexture(){return this._reflectionCubeMap}get xrLightingEstimate(){return this._xrLightEstimate?{lightColor:this._lightColor,lightDirection:this._lightDirection,lightIntensity:this._intensity,sphericalHarmonics:this._sphericalHarmonics}:this._xrLightEstimate}_getCanvasContext(){return null===this._canvasContext&&(this._canvasContext=this._xrSessionManager.scene.getEngine()._gl),this._canvasContext}_getXRGLBinding(){if(null===this._xrWebGLBinding){let e=this._getCanvasContext();this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,e)}return this._xrWebGLBinding}attach(){var e;if(!super.attach())return!1;let t=null!==(e=this.options.reflectionFormat)&&void 0!==e?e:this._xrSessionManager.session.preferredReflectionFormat||"srgba8";return this.options.reflectionFormat=t,this._xrSessionManager.session.requestLightProbe({reflectionFormat:t}).then(e=>{this._xrLightProbe=e,this.options.disableCubeMapReflection||(!this._reflectionCubeMap&&(this._reflectionCubeMap=new sV(this._xrSessionManager.scene),this._reflectionCubeMap._isCube=!0,this._reflectionCubeMap.coordinatesMode=3,this.options.setSceneEnvironmentTexture&&(this._xrSessionManager.scene.environmentTexture=this._reflectionCubeMap)),this._xrLightProbe.addEventListener("reflectionchange",this._updateReflectionCubeMap))}),!0}detach(){let e=super.detach();return null===this._xrLightProbe||this.options.disableCubeMapReflection||(this._xrLightProbe.removeEventListener("reflectionchange",this._updateReflectionCubeMap),this._xrLightProbe=null),this._canvasContext=null,this._xrLightEstimate=null,this._xrWebGLBinding=null,e}dispose(){super.dispose(),this.onReflectionCubeMapUpdatedObservable.clear(),this.directionalLight&&(this.directionalLight.dispose(),this.directionalLight=null),null!==this._reflectionCubeMap&&(this._reflectionCubeMap._texture&&this._reflectionCubeMap._texture.dispose(),this._reflectionCubeMap.dispose(),this._reflectionCubeMap=null)}_onXRFrame(e){var t;if(null!==this._xrLightProbe){if(this.options.lightEstimationPollInterval){let e=Date.now();if(e-this._lightEstimationPollTime()=>new Ee(e,t),Ee.Version,!1);class Et extends ns{constructor(e){super(e),this.onEyeTrackingStartedObservable=new r_.y$,this.onEyeTrackingEndedObservable=new r_.y$,this.onEyeTrackingFrameUpdateObservable=new r_.y$,this._eyeTrackingStartListener=e=>{this._latestEyeSpace=e.gazeSpace,this._gazeRay=new s6(rf.P.Zero(),rf.P.Forward()),this.onEyeTrackingStartedObservable.notifyObservers(this._gazeRay)},this._eyeTrackingEndListener=()=>{this._latestEyeSpace=null,this._gazeRay=null,this.onEyeTrackingEndedObservable.notifyObservers()},this.xrNativeFeatureName="eye-tracking",this._xrSessionManager.session?this._init():this._xrSessionManager.onXRSessionInit.addOnce(()=>{this._init()})}dispose(){super.dispose(),this._xrSessionManager.session.removeEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.removeEventListener("eyetrackingend",this._eyeTrackingEndListener),this.onEyeTrackingStartedObservable.clear(),this.onEyeTrackingEndedObservable.clear(),this.onEyeTrackingFrameUpdateObservable.clear()}get isEyeGazeValid(){return!!this._gazeRay}getEyeGaze(){return this._gazeRay}_onXRFrame(e){if(this.attached&&e&&this._latestEyeSpace&&this._gazeRay){let t=e.getPose(this._latestEyeSpace,this._xrSessionManager.referenceSpace);if(t){this._gazeRay.origin.set(t.transform.position.x,t.transform.position.y,t.transform.position.z);let e=t.transform.orientation;rf.jp.Quaternion[0].set(e.x,e.y,e.z,e.w),this._xrSessionManager.scene.useRightHandedSystem?rf.P.RightHandedForwardReadOnly.rotateByQuaternionToRef(rf.jp.Quaternion[0],this._gazeRay.direction):(this._gazeRay.origin.z*=-1,rf.jp.Quaternion[0].z*=-1,rf.jp.Quaternion[0].w*=-1,rf.P.LeftHandedForwardReadOnly.rotateByQuaternionToRef(rf.jp.Quaternion[0],this._gazeRay.direction)),this.onEyeTrackingFrameUpdateObservable.notifyObservers(this._gazeRay)}}}_init(){this._xrSessionManager.isNative&&(this._xrSessionManager.session.addEventListener("eyetrackingstart",this._eyeTrackingStartListener),this._xrSessionManager.session.addEventListener("eyetrackingend",this._eyeTrackingEndListener))}}Et.Name=ni.EYE_TRACKING,Et.Version=1,nr.AddWebXRFeature(Et.Name,e=>()=>new Et(e),Et.Version,!1);class Ei{constructor(e,t){this._samples=[],this._idx=0;for(let i=0;i=this._samples.length)throw Error("Index out of bounds");return this._samples[(this._idx+e)%this._samples.length]}}class Er{constructor(){this._samples=new Ei(20),this._entropy=0,this.onFirstStepDetected=new r_.y$}update(e,t,i,r){let s,n;this._samples.push(e,t);let a=this._samples.at(0);if(this._entropy*=this._entropyDecayFactor,this._entropy+=rf.FM.Distance(a,this._samples.at(1)),this._entropy>this._entropyThreshold)return;for(s=this._samePointCheckStartIdx;so&&(l=t,o=e);if(os*this._squaredProjectionDistanceThreshold)return;let p=rf.jp.Vector3[0];p.set(i,r,0);let _=rf.jp.Vector3[1];_.set(u.x,u.y,0);let f=rf.P.Cross(p,_).z>0,m=a.clone(),g=a.clone();h.subtractToRef(a,u),f?(u.scaleAndAddToRef(this._axisToApexShrinkFactor,m),u.scaleAndAddToRef(this._axisToApexExtendFactor,g)):(u.scaleAndAddToRef(this._axisToApexExtendFactor,m),u.scaleAndAddToRef(this._axisToApexShrinkFactor,g)),this.onFirstStepDetected.notifyObservers({leftApex:m,rightApex:g,currentPosition:a,currentStepDirection:f?"right":"left"})}reset(){for(let e=0;ethis._maxT&&(this._maxT=this._t,this._maxTPosition.copyFromFloats(e,t)),!(this._vitalityi&&(this.onMovement.notifyObservers({deltaT:this._t-i}),i<.5&&this._t>=.5&&this.onFootfall.notifyObservers({foot:this._steppingLeft?"left":"right"})),this._t<.95*this._maxT&&(this._currentPosition.copyFromFloats(e,t),this._steppingLeft?this._leftApex.copyFrom(this._maxTPosition):this._rightApex.copyFrom(this._maxTPosition),this._reset(this._leftApex,this._rightApex,this._currentPosition,!this._steppingLeft)),!(this._axisLength<.03))}get _vitalityThreshold(){return .1}get forward(){return this._forward}}class En{static get _MillisecondsPerUpdate(){return 1e3/15}constructor(e){this._detector=new Er,this._walker=null,this._movement=new rf.FM,this._millisecondsSinceLastUpdate=En._MillisecondsPerUpdate,this.movementThisFrame=rf.P.Zero(),this._engine=e,this._detector.onFirstStepDetected.add(e=>{this._walker||(this._walker=new Es(e.leftApex,e.rightApex,e.currentPosition,e.currentStepDirection),this._walker.onFootfall.add(()=>{rb.Y.Log("Footfall!")}),this._walker.onMovement.add(e=>{this._walker.forward.scaleAndAddToRef(.024*e.deltaT,this._movement)}))})}update(e,t){t.y=0,t.normalize(),this._millisecondsSinceLastUpdate+=this._engine.getDeltaTime(),this._millisecondsSinceLastUpdate>=En._MillisecondsPerUpdate&&(this._millisecondsSinceLastUpdate-=En._MillisecondsPerUpdate,this._detector.update(e.x,e.z,t.x,t.z),this._walker&&!this._walker.update(e.x,e.z)&&(this._walker=null),this._movement.scaleInPlace(.85)),this.movementThisFrame.set(this._movement.x,0,this._movement.y)}}class Ea extends ns{static get Name(){return ni.WALKING_LOCOMOTION}static get Version(){return 1}get locomotionTarget(){return this._locomotionTarget}set locomotionTarget(e){this._locomotionTarget=e,this._isLocomotionTargetWebXRCamera="WebXRCamera"===this._locomotionTarget.getClassName()}constructor(e,t){super(e),this._up=new rf.P,this._forward=new rf.P,this._position=new rf.P,this._movement=new rf.P,this._sessionManager=e,this.locomotionTarget=t.locomotionTarget,this._isLocomotionTargetWebXRCamera&&rb.Y.Warn("Using walking locomotion directly on a WebXRCamera may have unintended interactions with other XR techniques. Using an XR space parent is highly recommended")}isCompatible(){return void 0===this._sessionManager.sessionMode||"immersive-vr"===this._sessionManager.sessionMode}attach(){return!!(this.isCompatible&&super.attach())&&(this._walker=new En(this._sessionManager.scene.getEngine()),!0)}detach(){return!!super.detach()&&(this._walker=null,!0)}_onXRFrame(e){let t=e.getViewerPose(this._sessionManager.baseReferenceSpace);if(!t)return;let i=this.locomotionTarget.getScene().useRightHandedSystem?1:-1,r=t.transform.matrix;this._up.copyFromFloats(r[4],r[5],i*r[6]),this._forward.copyFromFloats(r[8],r[9],i*r[10]),this._position.copyFromFloats(r[12],r[13],i*r[14]),this._forward.scaleAndAddToRef(.05,this._position),this._up.scaleAndAddToRef(-.05,this._position),this._walker.update(this._position,this._forward),this._movement.copyFrom(this._walker.movementThisFrame),this._isLocomotionTargetWebXRCamera||rf.P.TransformNormalToRef(this._movement,this.locomotionTarget.getWorldMatrix(),this._movement),this.locomotionTarget.position.addInPlace(this._movement)}}nr.AddWebXRFeature(Ea.Name,(e,t)=>()=>new Ea(e,t),Ea.Version,!1);class Eo extends lK{constructor(e,t,i,r,s,n){super(e,t,i,r,n),this.getWidth=e,this.getHeight=t,this.layer=i,this.layerType=r,this.isMultiview=s,this.createRTTProvider=n}}class El extends lQ{constructor(e,t,i){super(e.scene,i),this._xrSessionManager=e,this._xrWebGLBinding=t,this.layerWrapper=i,this._lastSubImages=new Map,this._compositionLayer=i.layer}_getRenderTargetForSubImage(e,t){var i,r,s,n;let a=this._lastSubImages.get(t),o="left"==t?0:1,l=null!==(i=e.colorTextureWidth)&&void 0!==i?i:e.textureWidth,h=null!==(r=e.colorTextureHeight)&&void 0!==r?r:e.textureHeight;if(!this._renderTargetTextures[o]||(null==a?void 0:a.textureWidth)!==l||(null==a?void 0:a.textureHeight)!==h){let t;let i=null!==(s=e.depthStencilTextureWidth)&&void 0!==s?s:l,r=null!==(n=e.depthStencilTextureHeight)&&void 0!==n?n:h;(l===i||h===r)&&(t=e.depthStencilTexture),this._renderTargetTextures[o]=this._createRenderTargetTexture(l,h,null,e.colorTexture,t,this.layerWrapper.isMultiview),this._framebufferDimensions={framebufferWidth:l,framebufferHeight:h}}return this._lastSubImages.set(t,e),this._renderTargetTextures[o]}_getSubImageForEye(e){let t=this._xrSessionManager.currentFrame;return t?this._xrWebGLBinding.getSubImage(this._compositionLayer,t,e):null}getRenderTargetTextureForEye(e){let t=this._getSubImageForEye(e);return t?this._getRenderTargetForSubImage(t,e):null}getRenderTargetTextureForView(e){return this.getRenderTargetTextureForEye(e.eye)}_setViewportForSubImage(e,t){var i,r;let s=null!==(i=t.colorTextureWidth)&&void 0!==i?i:t.textureWidth,n=null!==(r=t.colorTextureWidth)&&void 0!==r?r:t.textureHeight,a=t.viewport;e.x=a.x/s,e.y=a.y/n,e.width=a.width/s,e.height=a.height/n}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForEye(t.eye);return!!i&&(this._setViewportForSubImage(e,i),!0)}}class Eh extends Eo{constructor(e,t,i){super(()=>e.textureWidth,()=>e.textureHeight,e,"XRProjectionLayer",t,e=>new Eu(e,i,this)),this.layer=e}}class Eu extends El{constructor(e,t,i){super(e,t,i),this.layerWrapper=i,this._projectionLayer=i.layer}_getSubImageForView(e){return this._xrWebGLBinding.getViewSubImage(this._projectionLayer,e)}getRenderTargetTextureForView(e){return this._getRenderTargetForSubImage(this._getSubImageForView(e),e.eye)}getRenderTargetTextureForEye(e){let t=this._lastSubImages.get(e);return t?this._getRenderTargetForSubImage(t,e):null}trySetViewportForView(e,t){let i=this._lastSubImages.get(t.eye)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}}let Ec={},Ed={textureType:"texture",colorFormat:6408,depthFormat:35056,scaleFactor:1};class Ep extends ns{constructor(e,t={}){super(e),this._options=t,this._existingLayers=[],this.xrNativeFeatureName="layers"}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this._existingLayers.length=0;let t=Object.assign({},Ed),i=this._options.preferMultiviewOnInit&&e.getCaps().multiview;return i&&(t.textureType="texture-array"),this.addXRSessionLayer(this.createProjectionLayer(t,i)),!0}detach(){return!!super.detach()&&(this._existingLayers.length=0,!0)}createXRWebGLLayer(e=Ec){return new lZ(new XRWebGLLayer(this._xrSessionManager.session,this._glContext,e))}createProjectionLayer(e=Ed,t=!1){if(t&&"texture-array"!==e.textureType)throw Error("Projection layers can only be made multiview if they use texture arrays. Set the textureType parameter to 'texture-array'.");if(!t&&"texture-array"===e.textureType)throw Error("We currently only support multiview rendering when the textureType parameter is set to 'texture-array'.");return new Eh(this._xrWebGLBinding.createProjectionLayer(e),t,this._xrWebGLBinding)}addXRSessionLayer(e){this.setXRSessionLayers([...this._existingLayers,e])}setXRSessionLayers(e){this._existingLayers=e;let t=Object.assign({},this._xrSessionManager.session.renderState);t.baseLayer=void 0,t.layers=e.map(e=>e.layer),this._xrSessionManager.updateRenderState(t),this._xrSessionManager._setBaseLayerWrapper(e.length>0?e[0]:null)}isCompatible(){return!this._xrSessionManager.isNative&&"undefined"!=typeof XRWebGLBinding&&!!XRWebGLBinding.prototype.createProjectionLayer}dispose(){super.dispose()}_onXRFrame(e){}}Ep.Name=ni.LAYERS,Ep.Version=1,nr.AddWebXRFeature(Ep.Name,(e,t)=>()=>new Ep(e,t),Ep.Version,!1);class E_ extends ns{get width(){return this._width}get height(){return this._height}get rawValueToMeters(){return this._rawValueToMeters}get normDepthBufferFromNormView(){return this._normDepthBufferFromNormView}get depthUsage(){switch(this._xrSessionManager.session.depthUsage){case"cpu-optimized":return"cpu";case"gpu-optimized":return"gpu"}}get depthDataFormat(){switch(this._xrSessionManager.session.depthDataFormat){case"luminance-alpha":return"ushort";case"float32":return"float"}}get latestInternalTexture(){var e,t;if(!this._cachedWebGLTexture)return null;let i=this._xrSessionManager.scene.getEngine(),r=new sq.l(i,sq.S.Unknown);return r.isCube=!1,r.invertY=!1,r._useSRGBBuffer=!1,r.format="ushort"===this.depthDataFormat?2:5,r.generateMipMaps=!1,r.type="ushort"===this.depthDataFormat?5:1,r.samplingMode=7,r.width=null!==(e=this.width)&&void 0!==e?e:0,r.height=null!==(t=this.height)&&void 0!==t?t:0,r._cachedWrapU=1,r._cachedWrapV=1,r._hardwareTexture=new l$.B(this._cachedWebGLTexture,i._gl),r}get latestDepthBuffer(){return this._cachedDepthBuffer?"ushort"===this.depthDataFormat?new Uint16Array(this._cachedDepthBuffer):new Float32Array(this._cachedDepthBuffer):null}get latestDepthImageTexture(){return this._cachedDepthImageTexture}constructor(e,t){super(e),this.options=t,this._width=null,this._height=null,this._rawValueToMeters=null,this._normDepthBufferFromNormView=null,this._cachedDepthBuffer=null,this._cachedWebGLTexture=null,this._cachedDepthImageTexture=null,this.onGetDepthInMetersAvailable=new r_.y$,this.xrNativeFeatureName="depth-sensing",sg.w1.Warn("depth-sensing is an experimental and unstable feature.")}attach(e){return!!super.attach(e)&&null!=this._xrSessionManager.session.depthDataFormat&&null!=this._xrSessionManager.session.depthUsage&&(this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._xrSessionManager.scene.getEngine()._gl),!0)}dispose(){var e;null===(e=this._cachedDepthImageTexture)||void 0===e||e.dispose()}_onXRFrame(e){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(null!=i)for(let t of i.views)switch(this.depthUsage){case"cpu":this._updateDepthInformationAndTextureCPUDepthUsage(e,t,this.depthDataFormat);break;case"gpu":if(!this._glBinding)break;this._updateDepthInformationAndTextureWebGLDepthUsage(this._glBinding,t,this.depthDataFormat);break;default:sg.w1.Error("Unknown depth usage"),this.detach()}}_updateDepthInformationAndTextureCPUDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{data:s,width:n,height:a,rawValueToMeters:o,getDepthInMeters:l}=r;switch(this._width=n,this._height=a,this._rawValueToMeters=o,this._cachedDepthBuffer=s,this.onGetDepthInMetersAvailable.notifyObservers(l.bind(r)),this._cachedDepthImageTexture||(this._cachedDepthImageTexture=sJ.CreateRTexture(null,n,a,this._xrSessionManager.scene,!1,!0,sj.NEAREST_SAMPLINGMODE,sR.D.TEXTURETYPE_FLOAT)),i){case"ushort":this._cachedDepthImageTexture.update(Float32Array.from(new Uint16Array(s)).map(e=>e*o));break;case"float":this._cachedDepthImageTexture.update(new Float32Array(s).map(e=>e*o))}}_updateDepthInformationAndTextureWebGLDepthUsage(e,t,i){let r=e.getDepthInformation(t);if(null===r)return;let{texture:s,width:n,height:a}=r;this._width=n,this._height=a,this._cachedWebGLTexture=s;let o=this._xrSessionManager.scene,l=o.getEngine().wrapWebGLTexture(s);this._cachedDepthImageTexture||(this._cachedDepthImageTexture=sJ.CreateRTexture(null,n,a,o,!1,!0,sj.NEAREST_SAMPLINGMODE,"ushort"===i?sR.D.TEXTURETYPE_UNSIGNED_BYTE:sR.D.TEXTURETYPE_FLOAT)),this._cachedDepthImageTexture._texture=l}getXRSessionInitExtension(){let e=null!=this.options.usagePreference&&0!==this.options.usagePreference.length,t=null!=this.options.dataFormatPreference&&0!==this.options.dataFormatPreference.length;return new Promise(i=>{i(e&&t?{depthSensing:{usagePreference:this.options.usagePreference.map(e=>{switch(e){case"cpu":return"cpu-optimized";case"gpu":return"gpu-optimized"}}),dataFormatPreference:this.options.dataFormatPreference.map(e=>{switch(e){case"ushort":return"luminance-alpha";case"float":return"float32"}})}}:{})})}}E_.Name=ni.DEPTH_SENSING,E_.Version=1,nr.AddWebXRFeature(E_.Name,(e,t)=>()=>new E_(e,t),E_.Version,!1);let Ef=`precision highp float; +#define CUSTOM_FRAGMENT_BEGIN +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_FRAGMENT_DEFINITIONS +void main(void) { +#define CUSTOM_FRAGMENT_MAIN_BEGIN +highp vec4 motionVector=( clipPos/clipPos.w-previousClipPos/previousClipPos.w );gl_FragColor=motionVector; +#define CUSTOM_FRAGMENT_MAIN_END +}`;nw.v.ShadersStore.velocityPixelShader=Ef;let Em=`#define CUSTOM_VERTEX_BEGIN +#define VELOCITY +attribute vec3 position; +#include +uniform mat4 viewProjection;uniform mat4 previousViewProjection; +#ifdef MULTIVIEW +uniform mat4 viewProjectionR;uniform mat4 previousViewProjectionR; +#endif +varying vec4 clipPos;varying vec4 previousClipPos; +#define CUSTOM_VERTEX_DEFINITIONS +void main(void) { +#define CUSTOM_VERTEX_MAIN_BEGIN +vec3 positionUpdated=position; +#include +vec4 worldPos=finalWorld*vec4(positionUpdated,1.0);vec4 previousWorldPos=finalPreviousWorld*vec4(positionUpdated,1.0); +#ifdef MULTIVIEW +if (gl_ViewID_OVR==0u) {clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos;} else {clipPos=viewProjectionR*worldPos;previousClipPos=previousViewProjectionR*previousWorldPos;gl_Position=clipPos;} +#elif +clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousWorldPos;gl_Position=clipPos; +#endif +#define CUSTOM_VERTEX_MAIN_END +}`;nw.v.ShadersStore.velocityVertexShader=Em;class Eg extends as{constructor(e,t,i,r=512){super("spacewarp rtt",r,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[rf.y3.Identity(),rf.y3.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new hV("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(e=>{this._previousWorldMatrices[e.uniqueId]=this._previousWorldMatrices[e.uniqueId]||e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[e.uniqueId]),this._previousWorldMatrices[e.uniqueId]=e.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)}),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;let i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach(e=>{this._originalPairing.push([e,e.material]),e.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(e=>{e[0].material=e[1]})}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class Ev{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){let t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if("XRProjectionLayer"!==t.layerType)throw Error('For Space Warp, the base layer type should "XRProjectionLayer".');let i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,r,s){if(!this._engine)throw Error("Engine is disposed");let n=new Eg(r,s,this._scene,{width:e,height:t}),a=n.renderTarget;return i&&(a._framebuffer=i),a._colorTextureArray=r,a._depthStencilTextureArray=s,n.disableRescaling(),n.renderListPredicate=()=>!0,n}_getRenderTargetForSubImage(e,t){let i=this._lastSubImages.get(t),r=this._renderTargetTextures.get(t.eye),s=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return r&&(null==i?void 0:i.textureWidth)===s&&(null==i?void 0:i.textureHeight)==n||(r=this._createRenderTargetTexture(s,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,r),this._framebufferDimensions={framebufferWidth:s,framebufferHeight:n}),this._lastSubImages.set(t,e),r}trySetViewportForView(e,t){let i=this._lastSubImages.get(t)||this._getSubImageForView(t);return!!i&&(this._setViewportForSubImage(e,i),!0)}accessMotionVector(e){let t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){let t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}}class Ex extends ns{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[ni.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;let e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new Ev(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){let t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;let i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}Ex.Name=ni.SPACE_WARP,Ex.Version=1,nr.AddWebXRFeature(Ex.Name,e=>()=>new Ex(e),Ex.Version,!1);class ET extends ns{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new r_.y$,this.xrNativeFeatureName="camera-access"}attach(e){return!!super.attach(e)&&(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0)}detach(){return!!super.detach()&&(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach(e=>e.dispose()),this.texturesData.forEach(e=>e.dispose()),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0)}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){let i={width:e.camera.width,height:e.camera.height,x:0,y:0},r=e.projectionMatrix,s=(1-r[8])*i.width/2+i.x,n=(1-r[9])*i.height/2+i.y,a=i.width/2*r[0],o=i.height/2*r[5],l=i.width/2*r[4];this.cameraIntrinsics[t]={u0:s,v0:n,ax:a,ay:o,gamma:l,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var i,r;if(!e.camera)return!1;this.viewIndex[t]=e.eye;let s=null===(i=this._glBinding)||void 0===i?void 0:i.getCameraImage(e.camera);if(this._cachedInternalTextures[t])null===(r=this._cachedInternalTextures[t]._hardwareTexture)||void 0===r||r.set(s);else{let i=new sq.l(this._xrSessionManager.scene.getEngine(),sq.S.Unknown,!0);i.isCube=!0,i.invertY=!1,i.format=5,i.generateMipMaps=!0,i.type=1,i.samplingMode=3,i.width=e.camera.width,i.height=e.camera.height,i._cachedWrapU=1,i._cachedWrapV=1,i._hardwareTexture=new l$.B(s,this._glContext),this._cachedInternalTextures[t]=i;let r=new sV(this._xrSessionManager.scene);r.name=`WebXR Raw Camera Access (${t})`,r._texture=this._cachedInternalTextures[t],this.texturesData[t]=r,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){let t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let r=!0;i.views.forEach((e,t)=>{r=r&&this._updateInternalTextures(e,t)}),r&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}ET.Name=ni.RAW_CAMERA_ACCESS,ET.Version=1,nr.AddWebXRFeature(ET.Name,(e,t)=>()=>new ET(e,t),ET.Version,!1);class ES extends p0{constructor(e,t,i){super(e,EE[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}p5.RegisterController("generic-hand-select-grasp",(e,t)=>new ES(t,e.gamepad,e.handedness));let EE={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class EC extends p0{constructor(e,t,i){super(e,Eb["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";return{filename:"left"===this.handedness?EC.MODEL_LEFT_FILENAME:EC.MODEL_RIGHT_FILENAME,path:EC.MODEL_BASE_URL+"default/"}}_getModelLoadingConstraints(){let e=nh.IsPluginForExtensionAvailable(".glb");return e||rb.Y.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach((e,t)=>{if(!this.disableAnimation&&e&&this.rootMesh){let i=this._mapping.buttons[e],r=i.rootNodeName;if(!r){rb.Y.Log("Skipping unknown button at index: "+t+" with mapped name: "+e);return}let s=this._getChildByName(this.rootMesh,r);if(!s){rb.Y.Warn("Missing button mesh with name: "+r);return}if(i.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.valueNodeName),i.pressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.pressedNodeName),i.unpressedMesh=this._getImmediateChildByName(s,this._mapping.defaultButton.unpressedNodeName),i.valueMesh&&i.pressedMesh&&i.unpressedMesh){let t=this.getComponent(e);t&&t.onButtonStateChangedObservable.add(e=>{this._lerpTransform(i,e.value)},void 0,!0)}else rb.Y.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(e=>{let t=this.getComponent(e);t.isAxes()&&["x-axis","y-axis"].forEach(i=>{if(!this.rootMesh)return;let r=this._mapping.axes[e][i],s=this._getChildByName(this.rootMesh,r.rootNodeName);if(!s){rb.Y.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(s,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?t&&t.onAxisValueChangedObservable.add(e=>{let t="x-axis"===i?e.x:e.y;this._lerpTransform(r,t,!0)},void 0,!0):rb.Y.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){let t;this.rootMesh=new sp.Kj(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;for(let i=0;inew EC(t,e.gamepad,e.handedness));let Eb={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class Ey extends p0{constructor(e,t,i,r=!1,s=!1){super(e,EA[i],t,i),this._forceLegacyControllers=s,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";return{filename:"left"===this.handedness?Ey.MODEL_LEFT_FILENAME:Ey.MODEL_RIGHT_FILENAME,path:this._isQuest()?Ey.QUEST_MODEL_BASE_URL:Ey.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){let t=this._isQuest(),i="right"===this.handedness?-1:1;this.getComponentIds().forEach(e=>{let r=e&&this.getComponent(e);r&&r.onButtonStateChangedObservable.add(r=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-(.2*r.value),this._modelRootNode.getChildren()[3].position.y=-(.005*r.value),this._modelRootNode.getChildren()[3].position.z=-(.005*r.value));return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*r.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(r.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(r.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new sp.Kj(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=rf._f.FromEulerAngles(0,Math.PI,0)),e.forEach(e=>{e.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}Ey.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/",Ey.MODEL_LEFT_FILENAME="left.babylon",Ey.MODEL_RIGHT_FILENAME="right.babylon",Ey.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/",p5.RegisterController("oculus-touch",(e,t)=>new Ey(t,e.gamepad,e.handedness)),p5.RegisterController("oculus-touch-legacy",(e,t)=>new Ey(t,e.gamepad,e.handedness,!0));let EA={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class ER extends p0{constructor(e,t,i){super(e,EP[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){return{filename:ER.MODEL_FILENAME,path:ER.MODEL_BASE_URL}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(e=>{let t=e&&this.getComponent(e);t&&t.onButtonStateChangedObservable.add(t=>{if(this.rootMesh&&!this.disableAnimation)switch(e){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-(.15*t.value);return;case"xr-standard-touchpad":case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new sp.Kj(this.profileId+" "+this.handedness,this.scene),e.forEach(e=>{e.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=rf._f.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}ER.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/",ER.MODEL_FILENAME="wand.babylon",p5.RegisterController("htc-vive",(e,t)=>new ER(t,e.gamepad,e.handedness));let EP={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class EI{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>{var e;return null!==(e=this._nativeImpl._imageTrackingResults)&&void 0!==e?e:[]}}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;let i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];let r=this._xrTransform.orientation;return r.x=this._xrPoseVectorData[4],r.y=this._xrPoseVectorData[5],r.z=this._xrPoseVectorData[6],r.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw Error("This function is not available in Babylon Native")}}uj("NativeXRFrame",EI),(th=ru||(ru={}))[th.Input=0]="Input",th[th.Output=1]="Output";class EM{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=(0,sw.f)(),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 Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){for(let t of(e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName(),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){let i=new(sg.w1.Instantiate(e.className))(e.name,e._connectionType,t);return i.deserialize(e),i}}class ED{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new ED(e.typeName,e.defaultValue)}}let EO=new ED("any",void 0),EN=new ED("string",""),EF=new ED("number",0),EL=new ED("boolean",!1),Ew=new ED("Vector2",rf.FM.Zero()),EB=new ED("Vector3",rf.P.Zero()),EU=new ED("Vector4",rf.Lt.Zero());new ED("Matrix",rf.y3.Identity());let EV=new ED("Color3",rm.Wo.Black()),Ek=new ED("Color4",new rm.HE(0,0,0,0)),EG=new ED("Quaternion",rf._f.Identity());class Ez extends EM{constructor(e,t,i,r){super(e,t,i),this.richType=r}_isSingularConnection(){return this.connectionType===ru.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===ru.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){let i=EM.Parse(e,t);return i.richType=ED.Parse(e.richType),i}}function EW(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function EH(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function EX(e,t,i){var r,s;let n=null!==(s=null===(r=null==t?void 0:t.getClassName)||void 0===r?void 0:r.call(t))&&void 0!==s?s:"";EW(n)?i[e]={name:t.name,className:n}:EH(n)?i[e]={value:t.asArray(),className:n}:i[e]=t}function EY(e,t,i){let r=t[e],s=null==r?void 0:r.className;return EW(s)?i.getMeshByName(r.name):EH(s)?function(e,t){if("Vector2"===e)return rf.FM.FromArray(t);if("Vector3"===e)return rf.P.FromArray(t);if("Vector4"===e)return rf.Lt.FromArray(t);if("Quaternion"===e)return rf._f.FromArray(t);if("Color3"===e)return new rm.Wo(t[0],t[1],t[2]);if("Color4"===e)return new rm.HE(t[0],t[1],t[2],t[3]);throw Error(`Unknown vector class name ${e}`)}(s,r.value):r&&void 0!==r.value?r.value:r}(0,rg.H)("FGDataConnection",Ez);class Ej{constructor(e){this.config=e,this.uniqueId=(0,sw.f)(),this.configure()}configure(){var e,t;this.name=null!==(t=null===(e=this.config)||void 0===e?void 0:e.name)&&void 0!==t?t:this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){let i=new Ez(e,ru.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){let i=new Ez(e,ru.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find(t=>t.name===e)}getDataOutput(e){return this.dataOutputs.find(t=>t.name===e)}serialize(e={},t=EX){for(let t of(e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName(),this.dataInputs)){let i={};t.serialize(i),e.dataInputs.push(i)}for(let t of this.dataOutputs){let i={};t.serialize(i),e.dataOutputs.push(i)}}getClassName(){return"FGBlock"}static Parse(e,t){var i,r;let s=sg.w1.Instantiate(e.className),n={},a=null!==(i=t.valueParseFunction)&&void 0!==i?i:EY;if(e.config)for(let i in e.config)n[i]=a(i,e.config,t.scene);("FGSetPropertyBlock"===(r=e.className)||"FGGetPropertyBlock"===r||"FGPlayAnimationBlock"===r||"FGMeshPickEventBlock"===r)&&(n.pathConverter=t.pathConverter);let o=new s(n);o.uniqueId=e.uniqueId;for(let t=0;tt.name===e)}getSignalOutput(e){return this.signalOutputs.find(t=>t.name===e)}serialize(e={}){for(let t of(super.serialize(e),e.signalInputs=[],e.signalOutputs=[],this.signalInputs)){let i={};t.serialize(i),e.signalInputs.push(i)}for(let t of this.signalOutputs){let i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{var r,s,n;t.type===s0.kD.POINTERPICK&&(null===(r=t.pickInfo)||void 0===r?void 0:r.pickedMesh)&&((null===(s=t.pickInfo)||void 0===s?void 0:s.pickedMesh)===i||EJ(null===(n=t.pickInfo)||void 0===n?void 0:n.pickedMesh,i))&&this._execute(e)});let r=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",r)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),r=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(r),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return E0.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}E0.ClassName="FGMeshPickEventBlock",(0,rg.H)(E0.ClassName,E0),(tu=rc||(rc={}))[tu.Stopped=0]="Stopped",tu[tu.Started=1]="Started";class E1{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=rc.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){let e=new EZ({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==rc.Started)for(let e of(this.state=rc.Started,0===this._executionContexts.length&&this.createContext(),this._executionContexts))for(let t of this._getContextualOrder())t._startPendingTasks(e)}_getContextualOrder(){let e=[];for(let t of this._eventBlocks)if(t.getClassName()===E0.ClassName){let i=t._getReferencedMesh(),r=0;for(;r0;){let r=t.pop();for(let s of(e(r),r.dataInputs))for(let e of s._connectedPoint)i.has(e._ownerBlock.uniqueId)||(t.push(e._ownerBlock),i.add(e._ownerBlock.uniqueId));if(r instanceof EK)for(let e of r.signalOutputs)for(let r of e._connectedPoint)i.has(r._ownerBlock.uniqueId)||(t.push(r._ownerBlock),i.add(r._ownerBlock.uniqueId))}}serialize(e={},t){for(let i of(e.allBlocks=[],this.visitAllBlocks(t=>{let i={};t.serialize(i),e.allBlocks.push(i)}),e.executionContexts=[],this._executionContexts)){let r={};i.serialize(r,t),e.executionContexts.push(r)}}static GetDataOutConnectionByUniqueId(e,t){for(let i of e)for(let e of i.dataOutputs)if(e.uniqueId===t)return e;throw Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(let i of e)if(i instanceof EK){for(let e of i.signalInputs)if(e.uniqueId===t)return e}throw Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){var i;let r=t.coordinator.createGraph(),s=[],n=null!==(i=t.valueParseFunction)&&void 0!==i?i:EY;for(let i of e.allBlocks){let e=Ej.Parse(i,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:n});s.push(e),e instanceof EQ&&r.addEventBlock(e)}for(let e of s){for(let t of e.dataInputs)for(let e of t.connectedPointIds){let i=E1.GetDataOutConnectionByUniqueId(s,e);t.connectTo(i)}if(e instanceof EK)for(let t of e.signalOutputs)for(let e of t.connectedPointIds){let i=E1.GetSignalInConnectionByUniqueId(s,e);t.connectTo(i)}}for(let t of e.executionContexts)EZ.Parse(t,{graph:r,valueParseFunction:n});return r}}class E2{constructor(e){var t;this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add(()=>{this.dispose()}),(null!==(t=E2.SceneCoordinators.get(this.config.scene))&&void 0!==t?t:[]).push(this)}createGraph(){let e=new E1({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){let t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){var e;this._flowGraphs.forEach(e=>e.dispose()),this._flowGraphs.length=0;let t=null!==(e=E2.SceneCoordinators.get(this.config.scene))&&void 0!==e?e:[],i=t.indexOf(this);-1!==i&&t.splice(i,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{let r={};i.serialize(r,t),e._flowGraphs.push(r)})}static Parse(e,t){var i,r;let s=null!==(i=t.valueParseFunction)&&void 0!==i?i:EY,n=new E2({scene:t.scene});return null===(r=e._flowGraphs)||void 0===r||r.forEach(e=>{E1.Parse(e,{coordinator:n,valueParseFunction:s,pathConverter:t.pathConverter})}),n}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new r_.y$,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){let i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}E2.SceneCoordinators=new Map;class E3 extends EK{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class E4 extends E3{constructor(e){super(e),this.message=this.registerDataInput("message",EO)}_execute(e){let t=this.message.getValue(e);rb.Y.Log(t),this.out._activateSignal(e)}getClassName(){return E4.ClassName}}E4.ClassName="FGConsoleLogBlock",(0,rg.H)(E4.ClassName,E4);class E5 extends E3{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,EO)}_execute(e){let t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return E5.ClassName}}E5.ClassName="FGSetVariableBlock",(0,rg.H)(E5.ClassName,E5);let E6=new RegExp(/\{(\w+)\}/g);class E8{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=E6.exec(e);for(;i;){let[,r]=i;this.templatedInputs.push(t.registerDataInput(r,EF)),i=E6.exec(e)}}getAccessor(e,t){let i=this.path;for(let e of this.templatedInputs){let r=e.getValue(t);i=i.replace(`{${e.name}}`,r.toString())}return e.convert(i)}}class E7 extends E3{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",EO),this.templateComponent=new E8(e.path,this)}_execute(e){let t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return E7.ClassName}}E7.ClassName="FGSetPropertyBlock",(0,rg.H)("FGSetPropertyBlock",E7);class E9 extends E3{constructor(e){super(e),this.config=e}configure(){super.configure();for(let e=0;et.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return E9.ClassName}}E9.ClassName="FGSendCustomEventBlock",(0,rg.H)("FGSendCustomEventBlock",E9);class Ce extends EK{constructor(e){super(e),this.condition=this.registerDataInput("condition",EL),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}(0,rg.H)("FGBranchBlock",Ce);class Ct extends E3{constructor(e={startIndex:0}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",EF),this.value=this.registerDataOutput("value",EF)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{let t=this.value.getValue(e);tr?(this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",s)):this.timeRemaining.setValue(r-(s-i),e)}getClassName(){return"FGThrottleBlock"}}(0,rg.H)("FGThrottleBlock",Cr);class Cs extends E${constructor(e){super(e),this.timeout=this.registerDataInput("timeout",EF)}_preparePendingTasks(e){let t=this.timeout.getValue(e);if(void 0!==t&&t>=0){let i=e._getExecutionVariable(this,"runningTimers")||[],r=new _n({timeout:t,contextObservable:e.configuration.scene.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){let i=t._getExecutionVariable(this,"runningTimers")||[],r=i.indexOf(e);-1!==r?i.splice(r,1):sg.w1.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){for(let t of e._getExecutionVariable(this,"runningTimers")||[])t.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Cs.ClassName}}Cs.ClassName="FGTimerBlock",(0,rg.H)("FGTimerBlock",Cs);class Cn extends EK{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",EF)}configure(){super.configure(),this.config.startIndex=void 0!==this.config.startIndex?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let e=0;e=this.config.numberOutputFlows&&this.config.loop)n=0;else if(n>=this.config.numberOutputFlows&&!this.config.loop)return;if(0===(s=s.filter(e=>e!==n)).length)for(let e=0;e=0&&(i[e+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(e=>e)){this.out._activateSignal(e);for(let e=0;e=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}(0,rg.H)("FGDebounceBlock",Cu);class Cc extends EK{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",EL)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}(0,rg.H)("FGFlipFlopBlock",Cc);class Cd extends EK{constructor(e){super(e),this.config=e}configure(){super.configure(),this.outFlows=[];for(let e=0;ethis._onAnimationEnd(t,e));this.runningAnimatable.setValue(t,e),a.push(t)}e._setExecutionVariable(this,"runningAnimatables",a)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){var i;let r=null!==(i=t._getExecutionVariable(this,"runningAnimatables"))&&void 0!==i?i:[],s=r.indexOf(e);-1!==s&&r.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){var t;for(let i of null!==(t=e._getExecutionVariable(this,"runningAnimatables"))&&void 0!==t?t:[])i.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return Cp.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}Cp.ClassName="FGPlayAnimationBlock",(0,rg.H)(Cp.ClassName,Cp);class C_ extends E3{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",EO)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}(0,rg.H)("FGStopAnimationBlock",C_);class Cf extends E3{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",EO)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}(0,rg.H)("FGPauseAnimationBlock",Cf);class Cm extends Ej{constructor(e){super(e),this.condition=this.registerDataInput("condition",EL),this.trueValue=this.registerDataInput("trueValue",EO),this.falseValue=this.registerDataInput("falseValue",EO),this.output=this.registerDataOutput("output",EO)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}(0,rg.H)("FGConditionalDataBlock",Cm);class Cg extends Ej{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,EO)}_updateOutputs(e){let t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return Cg.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}Cg.ClassName="FGGetVariableBlock",(0,rg.H)(Cg.ClassName,Cg);class Cv extends Ej{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",EO),this.destinationSystem=this.registerDataInput("destinationSystem",EO),this.inputCoordinates=this.registerDataInput("inputCoordinates",EB),this.outputCoordinates=this.registerDataOutput("outputCoordinates",EB)}_updateOutputs(e){let t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),r=this.inputCoordinates.getValue(e),s=t.getWorldMatrix(),n=i.getWorldMatrix(),a=rf.jp.Matrix[0].copyFrom(n);a.invert();let o=rf.jp.Matrix[1];a.multiplyToRef(s,o);let l=this.outputCoordinates.getValue(e);rf.P.TransformCoordinatesToRef(r,o,l)}getClassName(){return"FGCoordinateTransformBlock"}}(0,rg.H)("FGCoordinateTransformBlock",Cv);class Cx extends Ej{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",function(e){switch(typeof e){case"string":return EN;case"number":return EF;case"boolean":return EL;case"object":if(e instanceof rf.FM)return Ew;if(e instanceof rf.P)return EB;if(e instanceof rf.Lt)return EU;if(e instanceof rm.Wo)return EV;else if(e instanceof rm.HE)return Ek;else if(e instanceof rf._f)return EG;else return EO;default:return EO}}(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=EX){super.serialize(e),t("value",this.config.value,e.config)}}(0,rg.H)("FGConstantBlock",Cx);class CT extends Ej{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",EO),this.templateComponent=new E8(e.path,this)}_updateOutputs(e){let t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return CT.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}CT.ClassName="FGGetPropertyBlock",(0,rg.H)(CT.ClassName,CT);let CS="cachedOperationValue",CE="cachedExecutionId";class CC extends Ej{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){let t=e._getExecutionVariable(this,CE),i=e._getExecutionVariable(this,CS);if(void 0!==i&&t===e.executionId)this.value.setValue(i,e);else{let t=this._doOperation(e);e._setExecutionVariable(this,CS,t),e._setExecutionVariable(this,CE,e.executionId),this.value.setValue(t,e)}}}class Cb extends CC{constructor(e,t,i,r,s,n){super(i,n),this._operation=r,this._className=s,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 Cy extends CC{constructor(e,t,i,r,s){super(t,s),this._operation=i,this._className=r,this.input=this.registerDataInput("input",e)}_doOperation(e){return this._operation(this.input.getValue(e))}getClassName(){return this._className}}let CA="FGBitwise",CR="AndBlock",CP="OrBlock",CI="XorBlock",CM="NotBlock",CD="LeftShiftBlock",CO="RightShiftBlock",CN="CountLeadingZerosBlock",CF="CountTrailingZerosBlock";class CL extends Cb{constructor(e){super(EF,EF,EF,(e,t)=>e&t,`${CA}${CR}`,e)}}(0,rg.H)(`${CA}${CR}`,CL);class Cw extends Cb{constructor(e){super(EF,EF,EF,(e,t)=>e|t,`${CA}${CP}`,e)}}(0,rg.H)(`${CA}${CP}`,Cw);class CB extends Cb{constructor(e){super(EF,EF,EF,(e,t)=>e^t,`${CA}${CI}`,e)}}(0,rg.H)(`${CA}${CI}`,CB);class CU extends Cy{constructor(e){super(EF,EF,e=>~e,`${CA}${CM}`,e)}}(0,rg.H)(`${CA}${CM}`,CU);class CV extends Cb{constructor(e){super(EF,EF,EF,(e,t)=>e<e>>t,`${CA}${CO}`,e)}}(0,rg.H)(`${CA}${CO}`,Ck);class CG extends Cy{constructor(e){super(EF,EF,e=>Math.clz32(e),`${CA}${CN}`,e)}}(0,rg.H)(`${CA}${CN}`,CG);class Cz extends Cy{_ctrz(e){return 0==(e>>>=0)?32:31-Math.clz32(e&=-e)}constructor(e){super(EF,EF,e=>this._ctrz(e),`${CA}${CF}`,e)}}(0,rg.H)(`${CA}${CF}`,Cz);let CW="FGLogic",CH="AndBlock",CX="OrBlock",CY="NotBlock";class Cj extends Cb{constructor(e){super(EL,EL,EL,(e,t)=>e&&t,`${CW}${CH}`,e)}}(0,rg.H)(`${CW}${CH}`,Cj);class Cq extends Cb{constructor(e){super(EL,EL,EL,(e,t)=>e||t,`${CW}${CX}`,e)}}(0,rg.H)(`${CW}${CX}`,Cq);class CK extends Cy{constructor(e){super(EL,EL,e=>!e,`${CW}${CY}`,e)}}(0,rg.H)(`${CW}${CY}`,CK);class C$ extends CC{constructor(e,t,i,r){super(e,r),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class CQ extends CC{constructor(e,t,i,r,s,n,a){super(r,a),this._operation=s,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function CZ(e){return e.getClassName?e.getClassName():""}function CJ(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}class C0 extends Cb{constructor(e){super(EO,EO,EO,(e,t)=>this._polymorphicAdd(e,t),C0.ClassName,e)}_polymorphicAdd(e,t){return CJ(CZ(e),CZ(t))?e.add(t):e+t}getClassName(){return C0.ClassName}}C0.ClassName="FGAddBlock",(0,rg.H)(C0.ClassName,C0);class C1 extends Cb{constructor(e){super(EO,EO,EO,(e,t)=>this._polymorphicAdd(e,t),C1.ClassName,e)}_polymorphicAdd(e,t){return CJ(CZ(e),CZ(t))?e.subtract(t):e-t}getClassName(){return C1.ClassName}}C1.ClassName="FGSubBlock",(0,rg.H)(C1.ClassName,C1);class C2 extends Cb{constructor(e){super(EO,EO,EO,(e,t)=>this._polymorphicMultiply(e,t),C2.ClassName,e)}_polymorphicMultiply(e,t){return CJ(CZ(e),CZ(t))?e.multiply(t):e*t}}C2.ClassName="FGMultiplyBlock",(0,rg.H)(C2.ClassName,C2);class C3 extends Cb{constructor(e){super(EO,EO,EO,(e,t)=>this._polymorphicDivide(e,t),C3.ClassName,e)}_polymorphicDivide(e,t){return CJ(CZ(e),CZ(t))?e.divide(t):e/t}}C3.ClassName="FGDivideBlock",(0,rg.H)(C3.ClassName,C3);class C4 extends C${constructor(e){super(EF,()=>Math.random(),C4.ClassName,e)}}C4.ClassName="FGRandomBlock",(0,rg.H)(C4.ClassName,C4);class C5 extends Cb{constructor(e){super(EO,EO,EF,(e,t)=>this._polymorphicDot(e,t),C5.ClassName,e)}_polymorphicDot(e,t){switch(CZ(e)){case"Vector2":return rf.FM.Dot(e,t);case"Vector3":return rf.P.Dot(e,t);case"Vector4":return rf.Lt.Dot(e,t);default:throw Error(`Cannot get dot product of ${e} and ${t}`)}}}C5.ClassName="FGDotBlock",(0,rg.H)(C5.ClassName,C5);class C6 extends C${constructor(e){super(EF,()=>Math.E,C6.ClassName,e)}}C6.ClassName="FGEBlock",(0,rg.H)(C6.ClassName,C6);class C8 extends C${constructor(e){super(EF,()=>Math.PI,C8.ClassName,e)}}C8.ClassName="FGPIBlock",(0,rg.H)(C8.ClassName,C8);class C7 extends C${constructor(e){super(EF,()=>Number.POSITIVE_INFINITY,C7.ClassName,e)}}C7.ClassName="FGInfBlock",(0,rg.H)(C7.ClassName,C7);class C9 extends C${constructor(e){super(EF,()=>Number.NaN,C9.ClassName,e)}}function be(e,t){switch(CZ(e)){case"Vector2":return new rf.FM(t(e.x),t(e.y));case"Vector3":return new rf.P(t(e.x),t(e.y),t(e.z));case"Vector4":return new rf.Lt(t(e.x),t(e.y),t(e.z),t(e.w));default:return t(e)}}C9.ClassName="FGNaNBlock",(0,rg.H)(C9.ClassName,C9);class bt extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicAbs(e),bt.ClassName,e)}_polymorphicAbs(e){return be(e,Math.abs)}}bt.ClassName="FGAbsBlock",(0,rg.H)(bt.ClassName,bt);class bi extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicSign(e),bi.ClassName,e)}_polymorphicSign(e){return be(e,Math.sign)}}bi.ClassName="FGSignBlock",(0,rg.H)(bi.ClassName,bi);class br extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicTrunc(e),br.ClassName,e)}_polymorphicTrunc(e){return be(e,Math.trunc)}}br.ClassName="FGTruncBlock",(0,rg.H)(br.ClassName,br);class bs extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicFloor(e),bs.ClassName,e)}_polymorphicFloor(e){return be(e,Math.floor)}}bs.ClassName="FGFloorBlock",(0,rg.H)(bs.ClassName,bs);class bn extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicCeiling(e),bn.ClassName,e)}_polymorphicCeiling(e){return be(e,Math.ceil)}}bn.ClassName="FGCeilBlock",(0,rg.H)(bn.ClassName,bn);class ba extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicFract(e),ba.ClassName,e)}_polymorphicFract(e){return be(e,e=>e-Math.floor(e))}}ba.ClassName="FGFractBlock",(0,rg.H)(ba.ClassName,ba);class bo extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicNeg(e),bo.ClassName,e)}_polymorphicNeg(e){return be(e,e=>-e)}}function bl(e,t,i){switch(CZ(e)){case"Vector2":return new rf.FM(i(e.x,t.x),i(e.y,t.y));case"Vector3":return new rf.P(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z));case"Vector4":return new rf.Lt(i(e.x,t.x),i(e.y,t.y),i(e.z,t.z),i(e.w,t.w));default:return i(e,t)}}bo.ClassName="FGNegBlock",(0,rg.H)(bo.ClassName,bo);class bh extends Cb{constructor(e){super(EO,EO,EO,(e,t)=>this._polymorphicRemainder(e,t),bh.ClassName,e)}_polymorphicRemainder(e,t){return bl(e,t,(e,t)=>e%t)}}bh.ClassName="FGRemainderBlock",(0,rg.H)(bh.ClassName,bh);class bu extends Cb{constructor(e){super(EO,EO,EO,(e,t)=>this._polymorphicMin(e,t),bu.ClassName,e)}_polymorphicMin(e,t){return bl(e,t,Math.min)}}bu.ClassName="FGMinBlock",(0,rg.H)(bu.ClassName,bu);class bc extends Cb{constructor(e){super(EO,EO,EO,(e,t)=>this._polymorphicMax(e,t),bc.ClassName,e)}_polymorphicMax(e,t){return bl(e,t,Math.max)}}function bd(e,t,i){return Math.min(Math.max(e,t),i)}function bp(e,t,i,r){switch(CZ(e)){case"Vector2":return new rf.FM(r(e.x,t.x,i.x),r(e.y,t.y,i.y));case"Vector3":return new rf.P(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z));case"Vector4":return new rf.Lt(r(e.x,t.x,i.x),r(e.y,t.y,i.y),r(e.z,t.z,i.z),r(e.w,t.w,i.w));default:return r(e,t,i)}}bc.ClassName="FGMaxBlock",(0,rg.H)(bc.ClassName,bc);class b_ extends CQ{constructor(e){super(EO,EO,EO,EO,(e,t,i)=>this._polymorphicClamp(e,t,i),b_.ClassName,e)}_polymorphicClamp(e,t,i){return bp(e,t,i,bd)}}b_.ClassName="FGClampBlock",(0,rg.H)(b_.ClassName,b_);class bf extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicSaturate(e),bf.ClassName,e)}_polymorphicSaturate(e){return be(e,e=>bd(e,0,1))}}bf.ClassName="FGSaturateBlock",(0,rg.H)(bf.ClassName,bf);class bm extends CQ{constructor(e){super(EO,EO,EO,EO,(e,t,i)=>this._polymorphicInterpolate(e,t,i),bm.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return bp(e,t,i,this._interpolate)}}bm.ClassName="FGInterpolateBlock",(0,rg.H)(bm.ClassName,bm);class bg extends Cb{constructor(e){super(EO,EO,EL,(e,t)=>this._polymorphicEq(e,t),bg.ClassName,e)}_polymorphicEq(e,t){return CJ(CZ(e),CZ(t))?e.equals(t):e===t}}bg.ClassName="FGEqBlock",(0,rg.H)(bg.ClassName,bg);class bv extends Cb{constructor(e){super(EO,EO,EL,(e,t)=>this._polymorphicLessThan(e,t),bv.ClassName,e)}_polymorphicLessThan(e,t){switch(CZ(e)){case"Vector2":return e.xthis._polymorphicLessThanOrEqual(e,t),bx.ClassName,e)}_polymorphicLessThanOrEqual(e,t){switch(CZ(e)){case"Vector2":return e.x<=t.x&&e.y<=t.y;case"Vector3":return e.x<=t.x&&e.y<=t.y&&e.z<=t.z;case"Vector4":return e.x<=t.x&&e.y<=t.y&&e.z<=t.z&&e.w<=t.w;default:return e<=t}}}bx.ClassName="FGLessThanOrEqualBlock";class bT extends Cb{constructor(e){super(EO,EO,EL,(e,t)=>this._polymorphicGreaterThan(e,t),bT.ClassName,e)}_polymorphicGreaterThan(e,t){switch(CZ(e)){case"Vector2":return e.x>t.x&&e.y>t.y;case"Vector3":return e.x>t.x&&e.y>t.y&&e.z>t.z;case"Vector4":return e.x>t.x&&e.y>t.y&&e.z>t.z&&e.w>t.w;default:return e>t}}}bT.ClassName="FGGreaterThanBlock",(0,rg.H)(bT.ClassName,bT);class bS extends Cb{constructor(e){super(EO,EO,EL,(e,t)=>this._polymorphicGreaterThanOrEqual(e,t),bS.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){switch(CZ(e)){case"Vector2":return e.x>=t.x&&e.y>=t.y;case"Vector3":return e.x>=t.x&&e.y>=t.y&&e.z>=t.z;case"Vector4":return e.x>=t.x&&e.y>=t.y&&e.z>=t.z&&e.w>=t.w;default:return e>=t}}}bS.ClassName="FGGreaterThanOrEqualBlock",(0,rg.H)(bS.ClassName,bS);class bE extends Cy{constructor(e){super(EO,EL,e=>this._polymorphicIsNan(e),bE.ClassName,e)}_polymorphicIsNan(e){switch(CZ(e)){case"Vector2":return isNaN(e.x)||isNaN(e.y);case"Vector3":return isNaN(e.x)||isNaN(e.y)||isNaN(e.z);case"Vector4":return isNaN(e.x)||isNaN(e.y)||isNaN(e.z)||isNaN(e.w);default:return isNaN(e)}}}bE.ClassName="FGIsNanBlock",(0,rg.H)(bE.ClassName,bE);class bC extends Cy{constructor(e){super(EO,EL,e=>this._polymorphicIsInf(e),bC.ClassName,e)}_polymorphicIsInf(e){switch(CZ(e)){case"Vector2":return!isFinite(e.x)||!isFinite(e.y);case"Vector3":return!isFinite(e.x)||!isFinite(e.y)||!isFinite(e.z);case"Vector4":return!isFinite(e.x)||!isFinite(e.y)||!isFinite(e.z)||!isFinite(e.w);default:return!isFinite(e)}}}bC.ClassName="FGIsInfBlock";class bb extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicDegToRad(e),bb.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return be(e,this._degToRad)}}bb.ClassName="FGDegToRadBlock",(0,rg.H)(bb.ClassName,bb);class by extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicRadToDeg(e),by.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return be(e,this._radToDeg)}}by.ClassName="FGRadToDegBlock",(0,rg.H)(by.ClassName,by);class bA extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicSin(e),bA.ClassName,e)}_polymorphicSin(e){return be(e,Math.sin)}}bA.ClassName="FGSinBlock",(0,rg.H)(bA.ClassName,bA);class bR extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicCos(e),bR.ClassName,e)}_polymorphicCos(e){return be(e,Math.cos)}}bR.ClassName="FGCosBlock",(0,rg.H)(bR.ClassName,bR);class bP extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicTan(e),bP.ClassName,e)}_polymorphicTan(e){return be(e,Math.tan)}}bP.ClassName="FGTanBlock",(0,rg.H)(bP.ClassName,bP);class bI extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicAsin(e),bI.ClassName,e)}_polymorphicAsin(e){return be(e,Math.asin)}}bI.ClassName="FGAsinBlock",(0,rg.H)(bI.ClassName,bI);class bM extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicAcos(e),bM.ClassName,e)}_polymorphicAcos(e){return be(e,Math.acos)}}bM.ClassName="FGAcosBlock",(0,rg.H)(bM.ClassName,bM);class bD extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicAtan(e),bD.ClassName,e)}_polymorphicAtan(e){return be(e,Math.atan)}}bD.ClassName="FGAtanBlock",(0,rg.H)(bD.ClassName,bD);class bO extends Cb{constructor(e){super(EO,EO,EO,(e,t)=>this._polymorphicAtan2(e,t),bO.ClassName,e)}_polymorphicAtan2(e,t){return bl(e,t,Math.atan2)}}bO.ClassName="FGAtan2Block",(0,rg.H)(bO.ClassName,bO);class bN extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicSinh(e),bN.ClassName,e)}_polymorphicSinh(e){return be(e,Math.sinh)}}bN.ClassName="FGSinhBlock",(0,rg.H)(bN.ClassName,bN);class bF extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicCosh(e),bF.ClassName,e)}_polymorphicCosh(e){return be(e,Math.cosh)}}bF.ClassName="FGCoshBlock",(0,rg.H)(bF.ClassName,bF);class bL extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicTanh(e),bL.ClassName,e)}_polymorphicTanh(e){return be(e,Math.tanh)}}bL.ClassName="FGTanhBlock",(0,rg.H)(bL.ClassName,bL);class bw extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicAsinh(e),bw.ClassName,e)}_polymorphicAsinh(e){return be(e,Math.asinh)}}bw.ClassName="FGAsinhBlock",(0,rg.H)(bw.ClassName,bw);class bB extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicAcosh(e),bB.ClassName,e)}_polymorphicAcosh(e){return be(e,Math.acosh)}}bB.ClassName="FGAcoshBlock",(0,rg.H)(bB.ClassName,bB);class bU extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicAtanh(e),bU.ClassName,e)}_polymorphicAtanh(e){return be(e,Math.atanh)}}bU.ClassName="FGAtanhBlock",(0,rg.H)(bU.ClassName,bU);class bV extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicExp(e),bV.ClassName,e)}_polymorphicExp(e){return be(e,Math.exp)}}bV.ClassName="FGExpBlock",(0,rg.H)(bV.ClassName,bV);class bk extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicLog(e),bk.ClassName,e)}_polymorphicLog(e){return be(e,Math.log)}}bk.ClassName="FGLogBlock",(0,rg.H)(bk.ClassName,bk);class bG extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicLog2(e),bG.ClassName,e)}_polymorphicLog2(e){return be(e,Math.log2)}}bG.ClassName="FGLog2Block",(0,rg.H)(bG.ClassName,bG);class bz extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicLog10(e),bz.ClassName,e)}_polymorphicLog10(e){return be(e,Math.log10)}}bz.ClassName="FGLog10Block",(0,rg.H)(bz.ClassName,bz);class bW extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicSqrt(e),bW.ClassName,e)}_polymorphicSqrt(e){return be(e,Math.sqrt)}}bW.ClassName="FGSqrtBlock",(0,rg.H)(bW.ClassName,bW);class bH extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicCubeRoot(e),bH.ClassName,e)}_polymorphicCubeRoot(e){return be(e,Math.cbrt)}}bH.ClassName="FGCubeRootBlock",(0,rg.H)(bH.ClassName,bH);class bX extends Cb{constructor(e){super(EO,EF,EF,(e,t)=>this._polymorphicPow(e,t),bX.ClassName,e)}_polymorphicPow(e,t){return bl(e,t,Math.pow)}}bX.ClassName="FGPowBlock",(0,rg.H)(bX.ClassName,bX);class bY extends Cy{constructor(e){super(EO,EF,e=>this._polymorphicLength(e),bY.ClassName,e)}_polymorphicLength(e){switch(CZ(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw Error(`Cannot compute length of value ${e}`)}}}bY.ClassName="FGLengthBlock",(0,rg.H)(bY.ClassName,bY);class bj extends Cy{constructor(e){super(EO,EO,e=>this._polymorphicNormalize(e),bj.ClassName,e)}_polymorphicNormalize(e){switch(CZ(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw Error(`Cannot normalize value ${e}`)}}}bj.ClassName="FGNormalizeBlock",(0,rg.H)(bj.ClassName,bj);class bq extends Cb{constructor(e){super(EB,EB,EB,(e,t)=>rf.P.Cross(e,t),bq.ClassName,e)}}bq.ClassName="FGCrossBlock",(0,rg.H)(bq.ClassName,bq);class bK extends Cb{constructor(e){super(Ew,EF,Ew,(e,t)=>rf.FM.Transform(e,rf.y3.RotationZ(t)),bK.ClassName,e)}}bK.ClassName="FGRotate2DBlock",(0,rg.H)(bK.ClassName,bK);class b$ extends CQ{constructor(e){super(EB,EB,EF,EB,(e,t,i)=>rf.P.TransformCoordinates(e,rf.y3.RotationAxis(t,i)),b$.ClassName,e)}}b$.ClassName="FGRotate3DBlock",(0,rg.H)(b$.ClassName,b$);class bQ extends EQ{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){let t=e.configuration.scene.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return bQ.ClassName}}bQ.ClassName="FGSceneReadyEventBlock",(0,rg.H)("FGSceneReadyEventBlock",bQ);class bZ extends EQ{constructor(e){super(e),this.config=e}configure(){super.configure();for(let e=0;e{for(let i=0;i{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){let t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return bJ.ClassName}}bJ.ClassName="FGSceneTickEventBlock",(0,rg.H)(bJ.ClassName,bJ)},208:function(e,t,i){i.d(t,{N:function(){return u}});var r=i(9956),s=i(78),n=i(1760),a=i(4800),o=i(6030),l=i(6131);class h{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new a.y$,this._onClonedObservable=new a.y$}}class u{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,i,r){let s=this._NodeConstructors[e];return s?s(t,i,r):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;let t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){let t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._parentNode&&((void 0===this._parentNode._children||null===this._parentNode._children)&&(this._parentNode._children=[]),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){let 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){this._isDirty=!1,this._nodeDataStorage=new h,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new a.y$,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=s.y3.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new a.y$,this._onDisposeObserver=null,this._behaviors=[],this.name=e,this.id=e,this._scene=t||o.l.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache()}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){let 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(let 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={},this._cache.parent=void 0}updateCache(e){!e&&this.isSynchronized()||(this._cache.parent=this.parent,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._cache.parent!==this._parentNode?(this._cache.parent=this._parentNode,!1):(!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,i){if(this._children)for(let r=0;r(!t||t(e))&&void 0!==e.cullingStrategy),i}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){if(e!==this._nodeDataStorage._isReady){if(!e){this._nodeDataStorage._isReady=!1;return}this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0}}getAnimationByName(e){for(let t=0;tnew u(e,this.getScene()),this);if(t&&(r.parent=t),!i){let t=this.getDescendants(!0);for(let i=0;i{throw(0,l.S)("AnimationRange")},u._NodeConstructors={},(0,r.gn)([(0,n.qC)()],u.prototype,"name",void 0),(0,r.gn)([(0,n.qC)()],u.prototype,"id",void 0),(0,r.gn)([(0,n.qC)()],u.prototype,"uniqueId",void 0),(0,r.gn)([(0,n.qC)()],u.prototype,"state",void 0),(0,r.gn)([(0,n.qC)()],u.prototype,"metadata",void 0)},7609:function(e,t,i){i.d(t,{H:function(){return s},l:function(){return r}});class r{}r.NAME_EFFECTLAYER="EffectLayer",r.NAME_LAYER="Layer",r.NAME_LENSFLARESYSTEM="LensFlareSystem",r.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",r.NAME_PARTICLESYSTEM="ParticleSystem",r.NAME_GAMEPAD="Gamepad",r.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",r.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",r.NAME_PREPASSRENDERER="PrePassRenderer",r.NAME_DEPTHRENDERER="DepthRenderer",r.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",r.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",r.NAME_SPRITE="Sprite",r.NAME_SUBSURFACE="SubSurface",r.NAME_OUTLINERENDERER="Outline",r.NAME_PROCEDURALTEXTURE="ProceduralTexture",r.NAME_SHADOWGENERATOR="ShadowGenerator",r.NAME_OCTREE="Octree",r.NAME_PHYSICSENGINE="PhysicsEngine",r.NAME_AUDIO="Audio",r.NAME_FLUIDRENDERER="FluidRenderer",r.STEP_ISREADYFORMESH_EFFECTLAYER=0,r.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,r.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,r.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,r.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,r.STEP_BEFORECAMERADRAW_PREPASS=0,r.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,r.STEP_BEFORECAMERADRAW_LAYER=2,r.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,r.STEP_BEFORERENDERTARGETDRAW_LAYER=1,r.STEP_BEFORERENDERINGMESH_PREPASS=0,r.STEP_BEFORERENDERINGMESH_OUTLINE=1,r.STEP_AFTERRENDERINGMESH_PREPASS=0,r.STEP_AFTERRENDERINGMESH_OUTLINE=1,r.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,r.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,r.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,r.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,r.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,r.STEP_BEFORECLEAR_PREPASS=1,r.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,r.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,r.STEP_AFTERRENDERTARGETDRAW_LAYER=1,r.STEP_AFTERCAMERADRAW_PREPASS=0,r.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,r.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,r.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,r.STEP_AFTERCAMERADRAW_LAYER=4,r.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,r.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,r.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,r.STEP_AFTERRENDER_AUDIO=0,r.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,r.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,r.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,r.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,r.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,r.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,r.STEP_POINTERMOVE_SPRITE=0,r.STEP_POINTERDOWN_SPRITE=0,r.STEP_POINTERUP_SPRITE=0;class s extends Array{constructor(e){super(...e)}static Create(){return Object.create(s.prototype)}registerStep(e,t,i){let r=0;for(;r=0;o--)(s=e[o])&&(a=(n<3?s(a):n>3?s(t,i,a):s(t,i))||a);return n>3&&a&&Object.defineProperty(t,i,a),a}}}]); \ No newline at end of file diff --git a/.next/static/chunks/986-37229c658d9b7b30.js b/.next/static/chunks/986-37229c658d9b7b30.js deleted file mode 100644 index e04715c..0000000 --- a/.next/static/chunks/986-37229c658d9b7b30.js +++ /dev/null @@ -1,9 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[986],{413:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Image",{enumerable:!0,get:function(){return m}});let r=n(1024),i=n(8533),o=i._(n(2265)),a=r._(n(4887)),l=r._(n(5793)),u=n(7929),s=n(5751),d=n(7327);n(2637);let c=n(6304),f=r._(n(9950)),p={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1};function handleLoading(e,t,n,r,i,o){let a=null==e?void 0:e.src;if(!e||e["data-loaded-src"]===a)return;e["data-loaded-src"]=a;let l="decode"in e?e.decode():Promise.resolve();l.catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&i(!0),null==n?void 0:n.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let r=!1,i=!1;n.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>r,isPropagationStopped:()=>i,persist:()=>{},preventDefault:()=>{r=!0,t.preventDefault()},stopPropagation:()=>{i=!0,t.stopPropagation()}})}(null==r?void 0:r.current)&&r.current(e)}})}function getDynamicProps(e){let[t,n]=o.version.split(".",2),r=parseInt(t,10),i=parseInt(n,10);return r>18||18===r&&i>=3?{fetchPriority:e}:{fetchpriority:e}}let g=(0,o.forwardRef)((e,t)=>{let{src:n,srcSet:r,sizes:i,height:a,width:l,decoding:u,className:s,style:d,fetchPriority:c,placeholder:f,loading:p,unoptimized:g,fill:m,onLoadRef:h,onLoadingCompleteRef:y,setBlurComplete:b,setShowAltText:_,onLoad:v,onError:S,...w}=e;return o.default.createElement("img",{...w,...getDynamicProps(c),loading:p,width:l,height:a,decoding:u,"data-nimg":m?"fill":"1",className:s,style:d,sizes:i,srcSet:r,src:n,ref:(0,o.useCallback)(e=>{t&&("function"==typeof t?t(e):"object"==typeof t&&(t.current=e)),e&&(S&&(e.src=e.src),e.complete&&handleLoading(e,f,h,y,b,g))},[n,f,h,y,b,S,g,t]),onLoad:e=>{let t=e.currentTarget;handleLoading(t,f,h,y,b,g)},onError:e=>{_(!0),"empty"!==f&&b(!0),S&&S(e)}})});function ImagePreload(e){let{isAppRouter:t,imgAttributes:n}=e,r={as:"image",imageSrcSet:n.srcSet,imageSizes:n.sizes,crossOrigin:n.crossOrigin,referrerPolicy:n.referrerPolicy,...getDynamicProps(n.fetchPriority)};return t&&a.default.preload?(a.default.preload(n.src,r),null):o.default.createElement(l.default,null,o.default.createElement("link",{key:"__nimg-"+n.src+n.srcSet+n.sizes,rel:"preload",href:n.srcSet?void 0:n.src,...r}))}let m=(0,o.forwardRef)((e,t)=>{let n=(0,o.useContext)(c.RouterContext),r=(0,o.useContext)(d.ImageConfigContext),i=(0,o.useMemo)(()=>{let e=p||r||s.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),n=e.deviceSizes.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:n}},[r]),{onLoad:a,onLoadingComplete:l}=e,m=(0,o.useRef)(a);(0,o.useEffect)(()=>{m.current=a},[a]);let h=(0,o.useRef)(l);(0,o.useEffect)(()=>{h.current=l},[l]);let[y,b]=(0,o.useState)(!1),[_,v]=(0,o.useState)(!1),{props:S,meta:w}=(0,u.getImgProps)(e,{defaultLoader:f.default,imgConf:i,blurComplete:y,showAltText:_});return o.default.createElement(o.default.Fragment,null,o.default.createElement(g,{...S,unoptimized:w.unoptimized,placeholder:w.placeholder,fill:w.fill,onLoadRef:m,onLoadingCompleteRef:h,setBlurComplete:b,setShowAltText:v,ref:t}),w.priority?o.default.createElement(ImagePreload,{isAppRouter:!n,imgAttributes:S}):null)});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},8569:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AmpStateContext",{enumerable:!0,get:function(){return o}});let r=n(1024),i=r._(n(2265)),o=i.default.createContext({})},4472:function(e,t){"use strict";function isInAmpMode(e){let{ampFirst:t=!1,hybrid:n=!1,hasQuery:r=!1}=void 0===e?{}:e;return t||n&&r}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return isInAmpMode}})},7929:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImgProps",{enumerable:!0,get:function(){return getImgProps}}),n(2637);let r=n(1511),i=n(5751);function isStaticRequire(e){return void 0!==e.default}function isStaticImageData(e){return void 0!==e.src}function isStaticImport(e){return"object"==typeof e&&(isStaticRequire(e)||isStaticImageData(e))}function getInt(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function getWidths(e,t,n){let{deviceSizes:r,allSizes:i}=e;if(n){let e=/(^|\s)(1?\d?\d)vw/g,t=[];for(let r;r=e.exec(n);r)t.push(parseInt(r[2]));if(t.length){let e=.01*Math.min(...t);return{widths:i.filter(t=>t>=r[0]*e),kind:"w"}}return{widths:i,kind:"w"}}if("number"!=typeof t)return{widths:r,kind:"w"};let o=[...new Set([t,2*t].map(e=>i.find(t=>t>=e)||i[i.length-1]))];return{widths:o,kind:"x"}}function generateImgAttrs(e){let{config:t,src:n,unoptimized:r,width:i,quality:o,sizes:a,loader:l}=e;if(r)return{src:n,srcSet:void 0,sizes:void 0};let{widths:u,kind:s}=getWidths(t,i,a),d=u.length-1;return{sizes:a||"w"!==s?a:"100vw",srcSet:u.map((e,r)=>l({config:t,src:n,quality:o,width:e})+" "+("w"===s?e:r+1)+s).join(", "),src:l({config:t,src:n,quality:o,width:u[d]})}}function getImgProps(e,t){let n,o,a,{src:l,sizes:u,unoptimized:s=!1,priority:d=!1,loading:c,className:f,quality:p,width:g,height:m,fill:h=!1,style:y,onLoad:b,onLoadingComplete:_,placeholder:v="empty",blurDataURL:S,fetchPriority:w,layout:P,objectFit:C,objectPosition:O,lazyBoundary:I,lazyRoot:j,...E}=e,{imgConf:x,showAltText:M,blurComplete:z,defaultLoader:k}=t,R=x||i.imageConfigDefault;if("allSizes"in R)n=R;else{let e=[...R.deviceSizes,...R.imageSizes].sort((e,t)=>e-t),t=R.deviceSizes.sort((e,t)=>e-t);n={...R,allSizes:e,deviceSizes:t}}let A=E.loader||k;delete E.loader,delete E.srcSet;let D="__next_img_default"in A;if(D){if("custom"===n.loader)throw Error('Image with src "'+l+'" is missing "loader" prop.\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader')}else{let e=A;A=t=>{let{config:n,...r}=t;return e(r)}}if(P){"fill"===P&&(h=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[P];e&&(y={...y,...e});let t={responsive:"100vw",fill:"100vw"}[P];t&&!u&&(u=t)}let L="",U=getInt(g),N=getInt(m);if(isStaticImport(l)){let e=isStaticRequire(l)?l.default:l;if(!e.src)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "+JSON.stringify(e));if(!e.height||!e.width)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received "+JSON.stringify(e));if(o=e.blurWidth,a=e.blurHeight,S=S||e.blurDataURL,L=e.src,!h){if(U||N){if(U&&!N){let t=U/e.width;N=Math.round(e.height*t)}else if(!U&&N){let t=N/e.height;U=Math.round(e.width*t)}}else U=e.width,N=e.height}}let B=!d&&("lazy"===c||void 0===c);(!(l="string"==typeof l?l:L)||l.startsWith("data:")||l.startsWith("blob:"))&&(s=!0,B=!1),n.unoptimized&&(s=!0),D&&l.endsWith(".svg")&&!n.dangerouslyAllowSVG&&(s=!0),d&&(w="high");let F=getInt(p),T=Object.assign(h?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:C,objectPosition:O}:{},M?{}:{color:"transparent"},y),W=z||"empty"===v?null:"blur"===v?'url("data:image/svg+xml;charset=utf-8,'+(0,r.getImageBlurSvg)({widthInt:U,heightInt:N,blurWidth:o,blurHeight:a,blurDataURL:S||"",objectFit:T.objectFit})+'")':'url("'+v+'")',H=W?{backgroundSize:T.objectFit||"cover",backgroundPosition:T.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:W}:{},G=generateImgAttrs({config:n,src:l,unoptimized:s,width:U,quality:F,sizes:u,loader:A}),V={...E,loading:B?"lazy":c,fetchPriority:w,width:U,height:N,decoding:"async",className:f,style:{...T,...H},sizes:G.sizes,srcSet:G.srcSet,src:G.src},$={unoptimized:s,priority:d,placeholder:v,fill:h};return{props:V,meta:$}}},5793:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{defaultHead:function(){return defaultHead},default:function(){return c}});let r=n(1024),i=n(8533),o=i._(n(2265)),a=r._(n(110)),l=n(8569),u=n(1852),s=n(4472);function defaultHead(e){void 0===e&&(e=!1);let t=[o.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(o.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function onlyReactElement(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===o.default.Fragment?e.concat(o.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}n(2637);let d=["name","httpEquiv","charSet","itemProp"];function unique(){let e=new Set,t=new Set,n=new Set,r={};return i=>{let o=!0,a=!1;if(i.key&&"number"!=typeof i.key&&i.key.indexOf("$")>0){a=!0;let t=i.key.slice(i.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(i.type){case"title":case"base":t.has(i.type)?o=!1:t.add(i.type);break;case"meta":for(let e=0,t=d.length;e{let r=e.key||t;if(!n&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,o.default.cloneElement(e,t)}return o.default.cloneElement(e,{key:r})})}function Head(e){let{children:t}=e,n=(0,o.useContext)(l.AmpStateContext),r=(0,o.useContext)(u.HeadManagerContext);return o.default.createElement(a.default,{reduceComponentsToState:reduceComponents,headManager:r,inAmpMode:(0,s.isInAmpMode)(n)},t)}let c=Head;("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},1511:function(e,t){"use strict";function getImageBlurSvg(e){let{widthInt:t,heightInt:n,blurWidth:r,blurHeight:i,blurDataURL:o,objectFit:a}=e,l=r?40*r:t,u=i?40*i:n,s=l&&u?"viewBox='0 0 "+l+" "+u+"'":"";return"%3Csvg xmlns='http://www.w3.org/2000/svg' "+s+"%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='"+(s?"none":"contain"===a?"xMidYMid":"cover"===a?"xMidYMid slice":"none")+"' style='filter: url(%23b);' href='"+o+"'/%3E%3C/svg%3E"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImageBlurSvg",{enumerable:!0,get:function(){return getImageBlurSvg}})},7327:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ImageConfigContext",{enumerable:!0,get:function(){return a}});let r=n(1024),i=r._(n(2265)),o=n(5751),a=i.default.createContext(o.imageConfigDefault)},5751:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{VALID_LOADERS:function(){return n},imageConfigDefault:function(){return r}});let n=["default","imgix","cloudinary","akamai","custom"],r={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},679:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var n in t)Object.defineProperty(e,n,{enumerable:!0,get:t[n]})}(t,{unstable_getImgProps:function(){return unstable_getImgProps},default:function(){return u}});let r=n(1024),i=n(7929),o=n(2637),a=n(413),l=r._(n(9950)),unstable_getImgProps=e=>{(0,o.warnOnce)("Warning: unstable_getImgProps() is experimental and may change or be removed at any time. Use at your own risk.");let{props:t}=(0,i.getImgProps)(e,{defaultLoader:l.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}});for(let[e,n]of Object.entries(t))void 0===n&&delete t[e];return{props:t}},u=a.Image},9950:function(e,t){"use strict";function defaultLoader(e){let{config:t,src:n,width:r,quality:i}=e;return t.path+"?url="+encodeURIComponent(n)+"&w="+r+"&q="+(i||75)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}}),defaultLoader.__next_img_default=!0;let n=defaultLoader},6304:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RouterContext",{enumerable:!0,get:function(){return o}});let r=n(1024),i=r._(n(2265)),o=i.default.createContext(null)},110:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return SideEffect}});let r=n(2265),i=r.useLayoutEffect,o=r.useEffect;function SideEffect(e){let{headManager:t,reduceComponentsToState:n}=e;function emitChange(){if(t&&t.mountedInstances){let i=r.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(n(i,e))}}return i(()=>{var n;return null==t||null==(n=t.mountedInstances)||n.add(e.children),()=>{var n;null==t||null==(n=t.mountedInstances)||n.delete(e.children)}}),i(()=>(t&&(t._pendingUpdate=emitChange),()=>{t&&(t._pendingUpdate=emitChange)})),o(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},2637:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return warnOnce}});let warnOnce=e=>{}},622:function(e,t,n){"use strict";/** - * @license React - * react-jsx-runtime.production.min.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var r=n(2265),i=Symbol.for("react.element"),o=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,l=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function q(e,t,n){var r,o={},s=null,d=null;for(r in void 0!==n&&(s=""+n),void 0!==t.key&&(s=""+t.key),void 0!==t.ref&&(d=t.ref),t)a.call(t,r)&&!u.hasOwnProperty(r)&&(o[r]=t[r]);if(e&&e.defaultProps)for(r in t=e.defaultProps)void 0===o[r]&&(o[r]=t[r]);return{$$typeof:i,type:e,key:s,ref:d,props:o,_owner:l.current}}t.Fragment=o,t.jsx=q,t.jsxs=q},7437:function(e,t,n){"use strict";e.exports=n(622)},6691:function(e,t,n){e.exports=n(679)}}]); \ No newline at end of file diff --git a/.next/static/chunks/986-72006aa1051e30d3.js b/.next/static/chunks/986-72006aa1051e30d3.js new file mode 100644 index 0000000..a62fefe --- /dev/null +++ b/.next/static/chunks/986-72006aa1051e30d3.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[986],{1749:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"Image",{enumerable:!0,get:function(){return y}});let n=r(1024),i=r(8533)._(r(2265)),o=n._(r(4887)),a=n._(r(2251)),l=r(8630),u=r(6906),s=r(337);r(6184);let d=r(6993),c=n._(r(536)),f={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1};function p(e,t,r,n,i,o){let a=null==e?void 0:e.src;e&&e["data-loaded-src"]!==a&&(e["data-loaded-src"]=a,("decode"in e?e.decode():Promise.resolve()).catch(()=>{}).then(()=>{if(e.parentElement&&e.isConnected){if("empty"!==t&&i(!0),null==r?void 0:r.current){let t=new Event("load");Object.defineProperty(t,"target",{writable:!1,value:e});let n=!1,i=!1;r.current({...t,nativeEvent:t,currentTarget:e,target:e,isDefaultPrevented:()=>n,isPropagationStopped:()=>i,persist:()=>{},preventDefault:()=>{n=!0,t.preventDefault()},stopPropagation:()=>{i=!0,t.stopPropagation()}})}(null==n?void 0:n.current)&&n.current(e)}}))}function m(e){let[t,r]=i.version.split(".",2),n=parseInt(t,10),o=parseInt(r,10);return n>18||18===n&&o>=3?{fetchPriority:e}:{fetchpriority:e}}let g=(0,i.forwardRef)((e,t)=>{let{src:r,srcSet:n,sizes:o,height:a,width:l,decoding:u,className:s,style:d,fetchPriority:c,placeholder:f,loading:g,unoptimized:h,fill:y,onLoadRef:b,onLoadingCompleteRef:v,setBlurComplete:_,setShowAltText:w,onLoad:S,onError:P,...O}=e;return i.default.createElement("img",{...O,...m(c),loading:g,width:l,height:a,decoding:u,"data-nimg":y?"fill":"1",className:s,style:d,sizes:o,srcSet:n,src:r,ref:(0,i.useCallback)(e=>{t&&("function"==typeof t?t(e):"object"==typeof t&&(t.current=e)),e&&(P&&(e.src=e.src),e.complete&&p(e,f,b,v,_,h))},[r,f,b,v,_,P,h,t]),onLoad:e=>{p(e.currentTarget,f,b,v,_,h)},onError:e=>{w(!0),"empty"!==f&&_(!0),P&&P(e)}})});function h(e){let{isAppRouter:t,imgAttributes:r}=e,n={as:"image",imageSrcSet:r.srcSet,imageSizes:r.sizes,crossOrigin:r.crossOrigin,referrerPolicy:r.referrerPolicy,...m(r.fetchPriority)};return t&&o.default.preload?(o.default.preload(r.src,n),null):i.default.createElement(a.default,null,i.default.createElement("link",{key:"__nimg-"+r.src+r.srcSet+r.sizes,rel:"preload",href:r.srcSet?void 0:r.src,...n}))}let y=(0,i.forwardRef)((e,t)=>{let r=(0,i.useContext)(d.RouterContext),n=(0,i.useContext)(s.ImageConfigContext),o=(0,i.useMemo)(()=>{let e=f||n||u.imageConfigDefault,t=[...e.deviceSizes,...e.imageSizes].sort((e,t)=>e-t),r=e.deviceSizes.sort((e,t)=>e-t);return{...e,allSizes:t,deviceSizes:r}},[n]),{onLoad:a,onLoadingComplete:p}=e,m=(0,i.useRef)(a);(0,i.useEffect)(()=>{m.current=a},[a]);let y=(0,i.useRef)(p);(0,i.useEffect)(()=>{y.current=p},[p]);let[b,v]=(0,i.useState)(!1),[_,w]=(0,i.useState)(!1),{props:S,meta:P}=(0,l.getImgProps)(e,{defaultLoader:c.default,imgConf:o,blurComplete:b,showAltText:_});return i.default.createElement(i.default.Fragment,null,i.default.createElement(g,{...S,unoptimized:P.unoptimized,placeholder:P.placeholder,fill:P.fill,onLoadRef:m,onLoadingCompleteRef:y,setBlurComplete:v,setShowAltText:w,ref:t}),P.priority?i.default.createElement(h,{isAppRouter:!r,imgAttributes:S}):null)});("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},2595:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"AmpStateContext",{enumerable:!0,get:function(){return n}});let n=r(1024)._(r(2265)).default.createContext({})},3044:function(e,t){"use strict";function r(e){let{ampFirst:t=!1,hybrid:r=!1,hasQuery:n=!1}=void 0===e?{}:e;return t||r&&n}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"isInAmpMode",{enumerable:!0,get:function(){return r}})},8630:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImgProps",{enumerable:!0,get:function(){return l}}),r(6184);let n=r(7160),i=r(6906);function o(e){return void 0!==e.default}function a(e){return void 0===e?e:"number"==typeof e?Number.isFinite(e)?e:NaN:"string"==typeof e&&/^[0-9]+$/.test(e)?parseInt(e,10):NaN}function l(e,t){var r;let l,u,s,{src:d,sizes:c,unoptimized:f=!1,priority:p=!1,loading:m,className:g,quality:h,width:y,height:b,fill:v=!1,style:_,onLoad:w,onLoadingComplete:S,placeholder:P="empty",blurDataURL:O,fetchPriority:C,layout:j,objectFit:x,objectPosition:E,lazyBoundary:z,lazyRoot:M,...I}=e,{imgConf:k,showAltText:R,blurComplete:A,defaultLoader:D}=t,L=k||i.imageConfigDefault;if("allSizes"in L)l=L;else{let e=[...L.deviceSizes,...L.imageSizes].sort((e,t)=>e-t),t=L.deviceSizes.sort((e,t)=>e-t);l={...L,allSizes:e,deviceSizes:t}}let U=I.loader||D;delete I.loader,delete I.srcSet;let N="__next_img_default"in U;if(N){if("custom"===l.loader)throw Error('Image with src "'+d+'" is missing "loader" prop.\nRead more: https://nextjs.org/docs/messages/next-image-missing-loader')}else{let e=U;U=t=>{let{config:r,...n}=t;return e(n)}}if(j){"fill"===j&&(v=!0);let e={intrinsic:{maxWidth:"100%",height:"auto"},responsive:{width:"100%",height:"auto"}}[j];e&&(_={..._,...e});let t={responsive:"100vw",fill:"100vw"}[j];t&&!c&&(c=t)}let F="",T=a(y),B=a(b);if("object"==typeof(r=d)&&(o(r)||void 0!==r.src)){let e=o(d)?d.default:d;if(!e.src)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include src. Received "+JSON.stringify(e));if(!e.height||!e.width)throw Error("An object should only be passed to the image component src parameter if it comes from a static image import. It must include height and width. Received "+JSON.stringify(e));if(u=e.blurWidth,s=e.blurHeight,O=O||e.blurDataURL,F=e.src,!v){if(T||B){if(T&&!B){let t=T/e.width;B=Math.round(e.height*t)}else if(!T&&B){let t=B/e.height;T=Math.round(e.width*t)}}else T=e.width,B=e.height}}let G=!p&&("lazy"===m||void 0===m);(!(d="string"==typeof d?d:F)||d.startsWith("data:")||d.startsWith("blob:"))&&(f=!0,G=!1),l.unoptimized&&(f=!0),N&&d.endsWith(".svg")&&!l.dangerouslyAllowSVG&&(f=!0),p&&(C="high");let W=a(h),V=Object.assign(v?{position:"absolute",height:"100%",width:"100%",left:0,top:0,right:0,bottom:0,objectFit:x,objectPosition:E}:{},R?{}:{color:"transparent"},_),$=A||"empty"===P?null:"blur"===P?'url("data:image/svg+xml;charset=utf-8,'+(0,n.getImageBlurSvg)({widthInt:T,heightInt:B,blurWidth:u,blurHeight:s,blurDataURL:O||"",objectFit:V.objectFit})+'")':'url("'+P+'")',H=$?{backgroundSize:V.objectFit||"cover",backgroundPosition:V.objectPosition||"50% 50%",backgroundRepeat:"no-repeat",backgroundImage:$}:{},q=function(e){let{config:t,src:r,unoptimized:n,width:i,quality:o,sizes:a,loader:l}=e;if(n)return{src:r,srcSet:void 0,sizes:void 0};let{widths:u,kind:s}=function(e,t,r){let{deviceSizes:n,allSizes:i}=e;if(r){let e=/(^|\s)(1?\d?\d)vw/g,t=[];for(let n;n=e.exec(r);n)t.push(parseInt(n[2]));if(t.length){let e=.01*Math.min(...t);return{widths:i.filter(t=>t>=n[0]*e),kind:"w"}}return{widths:i,kind:"w"}}return"number"!=typeof t?{widths:n,kind:"w"}:{widths:[...new Set([t,2*t].map(e=>i.find(t=>t>=e)||i[i.length-1]))],kind:"x"}}(t,i,a),d=u.length-1;return{sizes:a||"w"!==s?a:"100vw",srcSet:u.map((e,n)=>l({config:t,src:r,quality:o,width:e})+" "+("w"===s?e:n+1)+s).join(", "),src:l({config:t,src:r,quality:o,width:u[d]})}}({config:l,src:d,unoptimized:f,width:T,quality:W,sizes:c,loader:U});return{props:{...I,loading:G?"lazy":m,fetchPriority:C,width:T,height:B,decoding:"async",className:g,style:{...V,...H},sizes:q.sizes,srcSet:q.srcSet,src:q.src},meta:{unoptimized:f,priority:p,placeholder:P,fill:v}}}},2251:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{defaultHead:function(){return s},default:function(){return p}});let n=r(1024),i=r(8533)._(r(2265)),o=n._(r(7392)),a=r(2595),l=r(3634),u=r(3044);function s(e){void 0===e&&(e=!1);let t=[i.default.createElement("meta",{charSet:"utf-8"})];return e||t.push(i.default.createElement("meta",{name:"viewport",content:"width=device-width"})),t}function d(e,t){return"string"==typeof t||"number"==typeof t?e:t.type===i.default.Fragment?e.concat(i.default.Children.toArray(t.props.children).reduce((e,t)=>"string"==typeof t||"number"==typeof t?e:e.concat(t),[])):e.concat(t)}r(6184);let c=["name","httpEquiv","charSet","itemProp"];function f(e,t){let{inAmpMode:r}=t;return e.reduce(d,[]).reverse().concat(s(r).reverse()).filter(function(){let e=new Set,t=new Set,r=new Set,n={};return i=>{let o=!0,a=!1;if(i.key&&"number"!=typeof i.key&&i.key.indexOf("$")>0){a=!0;let t=i.key.slice(i.key.indexOf("$")+1);e.has(t)?o=!1:e.add(t)}switch(i.type){case"title":case"base":t.has(i.type)?o=!1:t.add(i.type);break;case"meta":for(let e=0,t=c.length;e{let n=e.key||t;if(!r&&"link"===e.type&&e.props.href&&["https://fonts.googleapis.com/css","https://use.typekit.net/"].some(t=>e.props.href.startsWith(t))){let t={...e.props||{}};return t["data-href"]=t.href,t.href=void 0,t["data-optimized-fonts"]=!0,i.default.cloneElement(e,t)}return i.default.cloneElement(e,{key:n})})}let p=function(e){let{children:t}=e,r=(0,i.useContext)(a.AmpStateContext),n=(0,i.useContext)(l.HeadManagerContext);return i.default.createElement(o.default,{reduceComponentsToState:f,headManager:n,inAmpMode:(0,u.isInAmpMode)(r)},t)};("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7160:function(e,t){"use strict";function r(e){let{widthInt:t,heightInt:r,blurWidth:n,blurHeight:i,blurDataURL:o,objectFit:a}=e,l=n?40*n:t,u=i?40*i:r,s=l&&u?"viewBox='0 0 "+l+" "+u+"'":"";return"%3Csvg xmlns='http://www.w3.org/2000/svg' "+s+"%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3CfeColorMatrix values='1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 100 -1' result='s'/%3E%3CfeFlood x='0' y='0' width='100%25' height='100%25'/%3E%3CfeComposite operator='out' in='s'/%3E%3CfeComposite in2='SourceGraphic'/%3E%3CfeGaussianBlur stdDeviation='20'/%3E%3C/filter%3E%3Cimage width='100%25' height='100%25' x='0' y='0' preserveAspectRatio='"+(s?"none":"contain"===a?"xMidYMid":"cover"===a?"xMidYMid slice":"none")+"' style='filter: url(%23b);' href='"+o+"'/%3E%3C/svg%3E"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getImageBlurSvg",{enumerable:!0,get:function(){return r}})},337:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ImageConfigContext",{enumerable:!0,get:function(){return o}});let n=r(1024)._(r(2265)),i=r(6906),o=n.default.createContext(i.imageConfigDefault)},6906:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{VALID_LOADERS:function(){return r},imageConfigDefault:function(){return n}});let r=["default","imgix","cloudinary","akamai","custom"],n={deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",loaderFile:"",domains:[],disableStaticImages:!1,minimumCacheTTL:60,formats:["image/webp"],dangerouslyAllowSVG:!1,contentSecurityPolicy:"script-src 'none'; frame-src 'none'; sandbox;",contentDispositionType:"inline",remotePatterns:[],unoptimized:!1}},7447:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var r in t)Object.defineProperty(e,r,{enumerable:!0,get:t[r]})}(t,{unstable_getImgProps:function(){return u},default:function(){return s}});let n=r(1024),i=r(8630),o=r(6184),a=r(1749),l=n._(r(536)),u=e=>{(0,o.warnOnce)("Warning: unstable_getImgProps() is experimental and may change or be removed at any time. Use at your own risk.");let{props:t}=(0,i.getImgProps)(e,{defaultLoader:l.default,imgConf:{deviceSizes:[640,750,828,1080,1200,1920,2048,3840],imageSizes:[16,32,48,64,96,128,256,384],path:"/_next/image",loader:"default",dangerouslyAllowSVG:!1,unoptimized:!1}});for(let[e,r]of Object.entries(t))void 0===r&&delete t[e];return{props:t}},s=a.Image},536:function(e,t){"use strict";function r(e){let{config:t,src:r,width:n,quality:i}=e;return t.path+"?url="+encodeURIComponent(r)+"&w="+n+"&q="+(i||75)}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n}}),r.__next_img_default=!0;let n=r},6993:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"RouterContext",{enumerable:!0,get:function(){return n}});let n=r(1024)._(r(2265)).default.createContext(null)},7392:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return a}});let n=r(2265),i=n.useLayoutEffect,o=n.useEffect;function a(e){let{headManager:t,reduceComponentsToState:r}=e;function a(){if(t&&t.mountedInstances){let i=n.Children.toArray(Array.from(t.mountedInstances).filter(Boolean));t.updateHead(r(i,e))}}return i(()=>{var r;return null==t||null==(r=t.mountedInstances)||r.add(e.children),()=>{var r;null==t||null==(r=t.mountedInstances)||r.delete(e.children)}}),i(()=>(t&&(t._pendingUpdate=a),()=>{t&&(t._pendingUpdate=a)})),o(()=>(t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null),()=>{t&&t._pendingUpdate&&(t._pendingUpdate(),t._pendingUpdate=null)})),null}},6184:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"warnOnce",{enumerable:!0,get:function(){return r}});let r=e=>{}},622:function(e,t,r){"use strict";var n=r(2265),i=Symbol.for("react.element"),o=Symbol.for("react.fragment"),a=Object.prototype.hasOwnProperty,l=n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function s(e,t,r){var n,o={},s=null,d=null;for(n in void 0!==r&&(s=""+r),void 0!==t.key&&(s=""+t.key),void 0!==t.ref&&(d=t.ref),t)a.call(t,n)&&!u.hasOwnProperty(n)&&(o[n]=t[n]);if(e&&e.defaultProps)for(n in t=e.defaultProps)void 0===o[n]&&(o[n]=t[n]);return{$$typeof:i,type:e,key:s,ref:d,props:o,_owner:l.current}}t.Fragment=o,t.jsx=s,t.jsxs=s},7437:function(e,t,r){"use strict";e.exports=r(622)},6691:function(e,t,r){e.exports=r(7447)}}]); \ No newline at end of file diff --git a/.next/static/chunks/app/_not-found-954fefd8bb45a1c0.js b/.next/static/chunks/app/_not-found-954fefd8bb45a1c0.js new file mode 100644 index 0000000..6c2a93b --- /dev/null +++ b/.next/static/chunks/app/_not-found-954fefd8bb45a1c0.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[165],{3155:function(e,t,n){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_not-found",function(){return n(4032)}])},4032:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return o}});let l=n(1024)._(n(2265)),r={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{display:"inline-block"},h1:{display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},h2:{fontSize:14,fontWeight:400,lineHeight:"49px",margin:0}};function o(){return l.default.createElement(l.default.Fragment,null,l.default.createElement("title",null,"404: This page could not be found."),l.default.createElement("div",{style:r.error},l.default.createElement("div",null,l.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}),l.default.createElement("h1",{className:"next-error-h1",style:r.h1},"404"),l.default.createElement("div",{style:r.desc},l.default.createElement("h2",{style:r.h2},"This page could not be found.")))))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}},function(e){e.O(0,[971,938,744],function(){return e(e.s=3155)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/_not-found-fbdfab077d258bb2.js b/.next/static/chunks/app/_not-found-fbdfab077d258bb2.js deleted file mode 100644 index c2ef014..0000000 --- a/.next/static/chunks/app/_not-found-fbdfab077d258bb2.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[165],{3155:function(e,t,n){(window.__NEXT_P=window.__NEXT_P||[]).push(["/_not-found",function(){return n(1038)}])},1038:function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return NotFound}});let l=n(1024),o=l._(n(2265)),r={error:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},desc:{display:"inline-block"},h1:{display:"inline-block",margin:"0 20px 0 0",padding:"0 23px 0 0",fontSize:24,fontWeight:500,verticalAlign:"top",lineHeight:"49px"},h2:{fontSize:14,fontWeight:400,lineHeight:"49px",margin:0}};function NotFound(){return o.default.createElement(o.default.Fragment,null,o.default.createElement("title",null,"404: This page could not be found."),o.default.createElement("div",{style:r.error},o.default.createElement("div",null,o.default.createElement("style",{dangerouslySetInnerHTML:{__html:"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}),o.default.createElement("h1",{className:"next-error-h1",style:r.h1},"404"),o.default.createElement("div",{style:r.desc},o.default.createElement("h2",{style:r.h2},"This page could not be found.")))))}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)}},function(e){e.O(0,[971,472,744],function(){return e(e.s=3155)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js b/.next/static/chunks/app/everyone-votes/privacy/page-7a71bbf2f721c35f.js similarity index 62% rename from .next/static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js rename to .next/static/chunks/app/everyone-votes/privacy/page-7a71bbf2f721c35f.js index 0b435b5..aadc856 100644 --- a/.next/static/chunks/app/everyone-votes/privacy/page-29a62894605199e6.js +++ b/.next/static/chunks/app/everyone-votes/privacy/page-7a71bbf2f721c35f.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[369,181,447,619],{3521:function(){}},function(n){n.O(0,[971,472,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[369,181,447,619],{3521:function(){}},function(n){n.O(0,[971,938,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js b/.next/static/chunks/app/everyone-votes/terms/page-2d2b3d1433737a22.js similarity index 62% rename from .next/static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js rename to .next/static/chunks/app/everyone-votes/terms/page-2d2b3d1433737a22.js index 1fadcce..0b23f71 100644 --- a/.next/static/chunks/app/everyone-votes/terms/page-c0da9088d7e5e9ae.js +++ b/.next/static/chunks/app/everyone-votes/terms/page-2d2b3d1433737a22.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[181,369,447,619],{3521:function(){}},function(n){n.O(0,[971,472,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[181,369,447,619],{3521:function(){}},function(n){n.O(0,[971,938,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/layout-2a5e75b3a17431fd.js b/.next/static/chunks/app/layout-2a5e75b3a17431fd.js new file mode 100644 index 0000000..0222665 --- /dev/null +++ b/.next/static/chunks/app/layout-2a5e75b3a17431fd.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{7552:function(e,n,t){Promise.resolve().then(t.t.bind(t,3445,23)),Promise.resolve().then(t.t.bind(t,9989,23))},9989:function(){},3445:function(e){e.exports={style:{fontFamily:"'__Inter_e66fe9', '__Inter_Fallback_e66fe9'",fontStyle:"normal"},className:"__className_e66fe9"}}},function(e){e.O(0,[971,938,744],function(){return e(e.s=7552)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/layout-ca25527909104096.js b/.next/static/chunks/app/layout-ca25527909104096.js deleted file mode 100644 index 8a367be..0000000 --- a/.next/static/chunks/app/layout-ca25527909104096.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{7552:function(e,n,t){Promise.resolve().then(t.t.bind(t,1371,23)),Promise.resolve().then(t.t.bind(t,595,23))},595:function(){},1371:function(e){e.exports={style:{fontFamily:"'__Inter_e66fe9', '__Inter_Fallback_e66fe9'",fontStyle:"normal"},className:"__className_e66fe9"}}},function(e){e.O(0,[971,472,744],function(){return e(e.s=7552)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/page-39b6caed82efc627.js b/.next/static/chunks/app/page-39b6caed82efc627.js deleted file mode 100644 index 5579229..0000000 --- a/.next/static/chunks/app/page-39b6caed82efc627.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{2729:function(e,s,t){Promise.resolve().then(t.bind(t,6916))},6916:function(e,s,t){"use strict";let a;t.r(s),t.d(s,{default:function(){return Home}});var i=t(7437),o=t(2265);t(4456);var l=t(6691),n=t.n(l);function Card(e){return(0,i.jsxs)("a",{className:"w-[20rem] h-[8rem] p-2 rounded-2xl bg-slate-800 shadow-lg ".concat(e.shadow," flex flex-col flex-shrink-0 ease-out duration-300 hover:scale-105 hover:-translate-y-1 transition-all"),href:e.link,target:"_blank",children:[(0,i.jsxs)("div",{className:"flex flex-row items-center gap-1 ml-2 h-[2rem] w-full rounded-2xl",children:[(0,i.jsx)("span",{className:"text-l font-bold text-cyan-500",children:"sukadia.dev"}),(0,i.jsxs)("span",{className:"text-xl font-bold dark:text-white",children:["/ ",e.title]})]}),(0,i.jsxs)("div",{className:"flex flex-row w-full overflow-clip h-[84px]",children:[(0,i.jsx)("div",{className:"h-full aspect-square rounded-2xl relative",children:(0,i.jsx)("div",{className:"h-full w-full aspect-square relative rounded-2xl overflow-hidden",children:(0,i.jsx)(n(),{fill:!0,src:e.icon,sizes:"128px",alt:"thumbnail",className:""})})}),(0,i.jsx)("div",{className:"h-full w-full m-2 ml-4 rounded-2xl",children:(0,i.jsx)("p",{children:e.description})})]})]})}function Home(){let[e,s]=(0,o.useState)(""),t=(0,o.useRef)("undefined"!=typeof Audio?new Audio("audio/the-fabled-period-button.mp3"):void 0).current,l=0;return(0,i.jsxs)("main",{className:"select-none",children:[(0,i.jsx)("div",{className:"flex flex-col items-center h-screen overflow-hidden",children:(0,i.jsxs)("div",{className:("sukadia"==e||"dev"==e?"-translate-y-24":"")+" flex flex-row w-screen items-center justify-center overflow-hidden text-6xl min-[437px]:text-7xl min-[577px]:text-8xl md:text-9xl m-auto transition-all duration-500 z-20",children:[(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:t=>{s("sukadia"==e?"":"sukadia")},children:(0,i.jsx)("div",{id:"sukadia",className:("sukadia"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"sukadia"})}),(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:i=>{s("."==e?"":".");let o=++l;a=setTimeout(()=>{l==o&&(null==t?void 0:t.cloneNode()).play()},100)},onMouseUp:e=>{s(""),clearTimeout(a)},children:(0,i.jsx)("div",{id:".",className:("."==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"."})}),(0,i.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:t=>{s("dev"==e?"":"dev")},children:(0,i.jsx)("div",{id:"dev",className:("dev"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"dev"})})]})}),(0,i.jsx)("div",{className:("sukadia"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("sukadia"==e?"opacity-100 z-10":"opacity-0 pointer-events-none -translate-y-12 z-1")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[(0,i.jsx)(Card,{title:"Youtube",description:"Lots of VRChat videos focusing on roleplay.",icon:"/images/YoutubeIcon.png",link:"/youtube",shadow:"shadow-red-950"}),(0,i.jsx)(Card,{title:"Twitch",description:"Occasional streams for whatever seems fun at the moment.",icon:"/images/TwitchIcon.png",link:"/twitch",shadow:"shadow-violet-950"}),(0,i.jsx)(Card,{title:"Discord",description:"The hub for all my socials & projects. Join to stay updated!",icon:"/images/DiscordIcon.png",link:"/discord",shadow:"shadow-blue-900"}),(0,i.jsx)(Card,{title:"Ko-fi",description:"Support me monthly to help me make more content.",icon:"/images/KofiIcon.png",link:"/ko-fi",shadow:"shadow-sky-900"})]})}),(0,i.jsx)("div",{className:("dev"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,i.jsxs)("li",{className:("dev"==e?"opacity-100 z-10":"opacity-0 -translate-y-12 z-0")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[(0,i.jsx)(Card,{title:"Everyone-Votes",description:"A Discord bot that sends and tallies daily polls from thousands of servers.",icon:"/images/EveryoneVotesIcon.png",link:"/everyone-votes",shadow:"shadow-blue-900"}),(0,i.jsx)(Card,{title:"Space",description:"A WebGPU space/nebula image generator with lots of parameters to modify.",icon:"/images/SpaceIcon.png",link:"/space",shadow:"shadow-violet-950"}),(0,i.jsx)(Card,{title:"Dark",description:"A VSCode color theme based off of Brackets Dark.",icon:"/images/DarkIcon.png",link:"/dark",shadow:"shadow-yellow-950"})]})})]})}},4456:function(){}},function(e){e.O(0,[986,971,472,744],function(){return e(e.s=2729)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/page-8af0c2c4af65d19c.js b/.next/static/chunks/app/page-8af0c2c4af65d19c.js new file mode 100644 index 0000000..b1569b3 --- /dev/null +++ b/.next/static/chunks/app/page-8af0c2c4af65d19c.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{2729:function(e,s,t){Promise.resolve().then(t.bind(t,326))},326:function(e,s,t){"use strict";let i;t.r(s),t.d(s,{default:function(){return d}});var l=t(7437),o=t(2265);t(3371);var a=t(6691),n=t.n(a);function r(e){return(0,l.jsxs)("a",{className:"w-[20rem] h-[8rem] p-2 rounded-2xl bg-slate-800 shadow-lg ".concat(e.shadow," flex flex-col flex-shrink-0 ease-out duration-300 hover:scale-105 hover:-translate-y-1 transition-all"),href:e.link,target:"_blank",children:[(0,l.jsxs)("div",{className:"flex flex-row items-center gap-1 ml-2 h-[2rem] w-full rounded-2xl",children:[(0,l.jsx)("span",{className:"text-l font-bold text-cyan-500",children:"sukadia.dev"}),(0,l.jsxs)("span",{className:"text-xl font-bold dark:text-white",children:["/ ",e.title]})]}),(0,l.jsxs)("div",{className:"flex flex-row w-full overflow-clip h-[84px]",children:[(0,l.jsx)("div",{className:"h-full aspect-square rounded-2xl relative",children:(0,l.jsx)("div",{className:"h-full w-full aspect-square relative rounded-2xl overflow-hidden",children:(0,l.jsx)(n(),{fill:!0,src:e.icon,sizes:"128px",alt:"thumbnail",className:""})})}),(0,l.jsx)("div",{className:"h-full w-full m-2 ml-4 rounded-2xl",children:(0,l.jsx)("p",{children:e.description})})]})]})}function d(){let[e,s]=(0,o.useState)(""),t=(0,o.useRef)("undefined"!=typeof Audio?new Audio("audio/the-fabled-period-button.mp3"):void 0).current,a=0;return(0,l.jsxs)("main",{className:"select-none",children:[(0,l.jsx)("div",{className:"flex flex-col items-center h-screen overflow-hidden",children:(0,l.jsxs)("div",{className:("sukadia"==e||"dev"==e?"-translate-y-24":"")+" flex flex-row w-screen items-center justify-center overflow-hidden text-6xl min-[437px]:text-7xl min-[577px]:text-8xl md:text-9xl m-auto transition-all duration-500 z-20",children:[(0,l.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:t=>{s("sukadia"==e?"":"sukadia")},children:(0,l.jsx)("div",{id:"sukadia",className:("sukadia"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"sukadia"})}),(0,l.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:l=>{s("."==e?"":".");let o=++a;i=setTimeout(()=>{a==o&&(null==t?void 0:t.cloneNode()).play()},100)},onMouseUp:e=>{s(""),clearTimeout(i)},children:(0,l.jsx)("div",{id:".",className:("."==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"."})}),(0,l.jsx)("div",{className:"overflow-hidden flex-shrink",onMouseDown:t=>{s("dev"==e?"":"dev")},children:(0,l.jsx)("div",{id:"dev",className:("dev"==e?"maintitle-pressed top-2":"maintitle hover:-translate-y-0.5")+" transition-all hover:m-2",children:"dev"})})]})}),(0,l.jsx)("div",{className:("sukadia"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,l.jsxs)("li",{className:("sukadia"==e?"opacity-100 z-10":"opacity-0 pointer-events-none -translate-y-12 z-1")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[(0,l.jsx)(r,{title:"Youtube",description:"Lots of VRChat videos focusing on roleplay.",icon:"/images/YoutubeIcon.png",link:"/youtube",shadow:"shadow-red-950"}),(0,l.jsx)(r,{title:"Twitch",description:"Occasional streams for whatever seems fun at the moment.",icon:"/images/TwitchIcon.png",link:"/twitch",shadow:"shadow-violet-950"}),(0,l.jsx)(r,{title:"Discord",description:"The hub for all my socials & projects. Join to stay updated!",icon:"/images/DiscordIcon.png",link:"/discord",shadow:"shadow-blue-900"}),(0,l.jsx)(r,{title:"Ko-fi",description:"Support me monthly to help me make more content.",icon:"/images/KofiIcon.png",link:"/ko-fi",shadow:"shadow-sky-900"})]})}),(0,l.jsx)("div",{className:("dev"==e?"":"pointer-events-none")+" flex flex-col items-center absolute h-1/2 p-4 mt-4 -translate-y-4 inset-x-0 top-1/2 overflow-y-auto overflow-x-hidden",children:(0,l.jsxs)("li",{className:("dev"==e?"opacity-100 z-10":"opacity-0 -translate-y-12 z-0")+" flex flex-wrap flex-row items-center justify-center w-3/5 max-w-[1200px] gap-8 transition-all duration-500",children:[(0,l.jsx)(r,{title:"Everyone-Votes",description:"A Discord bot that sends and tallies daily polls from thousands of servers.",icon:"/images/EveryoneVotesIcon.png",link:"/everyone-votes",shadow:"shadow-blue-900"}),(0,l.jsx)(r,{title:"Space",description:"A WebGPU space/nebula image generator with lots of parameters to modify.",icon:"/images/SpaceIcon.png",link:"/space",shadow:"shadow-violet-950"}),(0,l.jsx)(r,{title:"Dark",description:"A VSCode color theme based off of Brackets Dark.",icon:"/images/DarkIcon.png",link:"/dark",shadow:"shadow-yellow-950"})]})})]})}},3371:function(){}},function(e){e.O(0,[986,971,938,744],function(){return e(e.s=2729)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/space/loading-a22e96181fd3eee8.js b/.next/static/chunks/app/space/loading-a22e96181fd3eee8.js deleted file mode 100644 index fc10448..0000000 --- a/.next/static/chunks/app/space/loading-a22e96181fd3eee8.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[447,369,181,619],{3521:function(){}},function(n){n.O(0,[971,472,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/space/loading-b8903409900b99fa.js b/.next/static/chunks/app/space/loading-b8903409900b99fa.js new file mode 100644 index 0000000..33b93cc --- /dev/null +++ b/.next/static/chunks/app/space/loading-b8903409900b99fa.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[447,181,369,619],{3521:function(){}},function(n){n.O(0,[971,938,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/space/page-185302d4e0f787e8.js b/.next/static/chunks/app/space/page-185302d4e0f787e8.js new file mode 100644 index 0000000..3c49163 --- /dev/null +++ b/.next/static/chunks/app/space/page-185302d4e0f787e8.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[514],{4310:function(e,t,n){Promise.resolve().then(n.bind(n,7846))},3693:function(e,t,n){"use strict";let a,r,d,o,i,s,l;n.d(t,{Z:function(){return p}});var c=n(4672),h=n(1302);let u=[];class p{static generateFrame(){if(!a)return;let e=performance.now(),t=(0,h.g)();if((a.width!=t.width||a.height!=t.height)&&this.resizeFrame(t.width,t.height),s!=t.seed){var n,c;c=Math.imul((c=n=function(e){var t,n=0;for(t=0;t>>15,1|c),l=(((c^=c+Math.imul(c^c>>>7,61|c))^c>>>14)>>>0)/4294967296,s=t.seed,console.log(1)}i.onApply=e=>{e.setFloat("seed",l+5),e.setFloat("density",t.density/100),e.setFloat("brightness",t.brightness/100)};for(let e=0;e{n.setFloat("seed",1e3*l*(e+1)),n.setFloat4("color",t["color".concat(e+1)].r/255,t["color".concat(e+1)].g/255,t["color".concat(e+1)].b/255,1),n.setUInt("nebulascale",t.scale),n.setUInt("depth",t.depth),n.setFloat("intensity",t.intensity/100-1),n.setFloat("falloff",t.falloff),n.setFloat("persistence",t.persistence)},u[e].onApplyObservable.add(t=>{t.setTextureSampler("textureSamplerSampler",u[e].inputTexture.texture)});d.onAfterRenderObservable.addOnce(()=>{console.log("Rendered in ".concat(Math.round((performance.now()-e)*100)/100,"ms"))}),r.beginFrame(),d.render(),r.endFrame()}static resizeFrame(e,t){a.style.width=e.toString()+"px",a.style.height=t.toString()+"px",r.resize()}static async exportFrame(){let e=(0,h.g)();c.w1W.CreateScreenshotUsingRenderTarget(r,o,{width:a.width,height:a.height},void 0,void 0,void 0,void 0,"nebula-".concat(e.seed)),this.generateFrame()}static setTransparency(e){e?d.clearColor=new c.HEv(0,0,0,0):d.clearColor=new c.HEv(0,0,0,1)}static initialize(e,t,n,s){a=e,r=t,d=n,o=s,i=new c.Dso("StarShader","stars",null,null,1,o,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL),o.attachPostProcess(i);for(let e=0;e<10;e++)u.push(new c.Dso("NebulaShader","nebulas",null,null,1,o,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL))}}},1302:function(e,t,n){"use strict";let a;n.d(t,{Z:function(){return o},g:function(){return i}});var r=n(7089),d=n(3693);function o(){a=new r.Pane({title:"Parameters",container:document.getElementById("TweakPane")||void 0});let e={width:window.innerWidth,height:window.innerHeight,transparent:!1,autoupdate:!1},t=a.addFolder({title:"Canvas",expanded:!0});t.addInput(e,"width",{min:100,max:7680,step:1}),t.addInput(e,"height",{min:100,max:4320,step:1}),t.addInput(e,"transparent").on("change",()=>{console.log(1),d.Z.setTransparency(e.transparent)});let n={density:1.5,brightness:100},o=a.addFolder({title:"Stars",expanded:!0});o.addInput(n,"density",{min:0,max:10,step:.01,format:e=>e.toFixed(2)+"%"}),o.addInput(n,"brightness",{min:0,max:200,step:.1,format:e=>e.toFixed(1)+"%"});let i={count:2,scale:5,depth:2,intensity:100,falloff:2,persistence:.5},s=a.addFolder({title:"Nebula",expanded:!0});s.addInput(i,"count",{min:0,max:3,step:1}).on("change",()=>{if(0==i.count)c.hidden=!0;else{c.hidden=!1;for(let e=0;ei.count-1&&(h[e].hidden=!0);s.addInput(i,"scale",{min:1,max:50,step:1}),s.addInput(i,"depth",{min:0,max:20,step:1}),s.addInput(i,"intensity",{min:50,max:150,step:1,format:e=>e+"%"}),s.addInput(i,"falloff",{min:1,max:10,step:.1}),s.addInput(i,"persistence",{min:0,max:1,step:.01});let u={seed:""+Math.floor(1e12*Math.random())},p=a.addFolder({title:"Seed",expanded:!1});p.addInput(u,"seed",{format:e=>e.toFixed(0)}),p.addButton({title:"Randomize seed"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString(),a.refresh(),d.Z.generateFrame()}),a.addSeparator(),a.addButton({title:"Render"}).on("click",()=>{d.Z.generateFrame()}),a.addButton({title:"Render Random"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString();for(let e=0;e<3;e++)l["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())};a.refresh(),d.Z.generateFrame()}),a.addSeparator(),a.addButton({title:"Save Image"}).on("click",()=>{d.Z.exportFrame()}),a.addSeparator(),a.addInput(e,"autoupdate"),a.on("change",t=>{let n=t.presetKey;e.autoupdate&&(("width"==n||"height"==n)&&d.Z.resizeFrame(e.width,e.height),d.Z.generateFrame())})}function i(){return a.exportPreset()}},7846:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return c}});var a=n(7437),r=n(2265),d=n(4930),o=n.n(d);function i(){return(0,a.jsx)("div",{className:"flex h-screen justify-center items-center",children:(0,a.jsx)("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:(0,a.jsx)("div",{className:"h-10 w-10 rounded-full bg-black"})})})}var s=n(1302);let l=o()(()=>n.e(255).then(n.bind(n,5619)),{loadableGenerated:{webpack:()=>[5619]},ssr:!1});function c(){let[e,t]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{t(!0),(0,s.Z)()},[]),(0,a.jsxs)("main",{children:[(0,a.jsx)("div",{id:"TweakPane",className:"fixed top-2.5 right-2.5"}),e&&(0,a.jsx)(l,{}),!e&&(0,a.jsx)(i,{})]})}}},function(e){e.O(0,[732,105,735,790,116,973,971,938,744],function(){return e(e.s=4310)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/space/page-b8120f6d5470d1c7.js b/.next/static/chunks/app/space/page-b8120f6d5470d1c7.js deleted file mode 100644 index 78bbb26..0000000 --- a/.next/static/chunks/app/space/page-b8120f6d5470d1c7.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[514],{4310:function(e,t,n){Promise.resolve().then(n.bind(n,341))},1128:function(e,t,n){"use strict";let a,r,d,o,i,s,l;n.d(t,{Z:function(){return BabylonInteractivity}});var c=n(9111),h=n(6086);let u=[];function hashString(e){var t,n=0;for(t=0;t>>15,1|t),(((t^=t+Math.imul(t^t>>>7,61|t))^t>>>14)>>>0)/4294967296}let BabylonInteractivity=class BabylonInteractivity{static generateFrame(){if(!a)return;let e=performance.now(),t=(0,h.g)();(a.width!=t.width||a.height!=t.height)&&this.resizeFrame(t.width,t.height),s!=t.seed&&(l=mulberry32(hashString(t.seed)),s=t.seed,console.log(1)),i.onApply=e=>{e.setFloat("seed",l+5),e.setFloat("density",t.density/100),e.setFloat("brightness",t.brightness/100)};for(let e=0;e{n.setFloat("seed",1e3*l*(e+1)),n.setFloat4("color",t["color".concat(e+1)].r/255,t["color".concat(e+1)].g/255,t["color".concat(e+1)].b/255,1),n.setUInt("nebulascale",t.scale),n.setUInt("depth",t.depth),n.setFloat("intensity",t.intensity/100-1),n.setFloat("falloff",t.falloff),n.setFloat("persistence",t.persistence)},u[e].onApplyObservable.add(t=>{t.setTextureSampler("textureSamplerSampler",u[e].inputTexture.texture)});d.onAfterRenderObservable.addOnce(()=>{console.log("Rendered in ".concat(Math.round((performance.now()-e)*100)/100,"ms"))}),r.beginFrame(),d.render(),r.endFrame()}static resizeFrame(e,t){a.style.width=e.toString()+"px",a.style.height=t.toString()+"px",r.resize()}static async exportFrame(){let e=(0,h.g)();c.w1W.CreateScreenshotUsingRenderTarget(r,o,{width:a.width,height:a.height},void 0,void 0,void 0,void 0,"nebula-".concat(e.seed)),this.generateFrame()}static setTransparency(e){e?d.clearColor=new c.HEv(0,0,0,0):d.clearColor=new c.HEv(0,0,0,1)}static initialize(e,t,n,s){a=e,r=t,d=n,o=s,i=new c.Dso("StarShader","stars",null,null,1,o,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL),o.attachPostProcess(i);for(let e=0;e<10;e++)u.push(new c.Dso("NebulaShader","nebulas",null,null,1,o,void 0,r,!0,void 0,void 0,void 0,void 0,void 0,void 0,c.xeF.WGSL))}}},6086:function(e,t,n){"use strict";let a;n.d(t,{Z:function(){return ParameterPanel},g:function(){return getParameters}});var r=n(7089),d=n(1128);function ParameterPanel(){a=new r.Pane({title:"Parameters",container:document.getElementById("TweakPane")||void 0});let e={width:window.innerWidth,height:window.innerHeight,transparent:!1,autoupdate:!1},t=a.addFolder({title:"Canvas",expanded:!0});t.addInput(e,"width",{min:100,max:7680,step:1}),t.addInput(e,"height",{min:100,max:4320,step:1}),t.addInput(e,"transparent").on("change",()=>{console.log(1),d.Z.setTransparency(e.transparent)});let n={density:1.5,brightness:100},o=a.addFolder({title:"Stars",expanded:!0});o.addInput(n,"density",{min:0,max:10,step:.01,format:e=>e.toFixed(2)+"%"}),o.addInput(n,"brightness",{min:0,max:200,step:.1,format:e=>e.toFixed(1)+"%"});let i={count:2,scale:5,depth:2,intensity:100,falloff:2,persistence:.5},s=a.addFolder({title:"Nebula",expanded:!0});s.addInput(i,"count",{min:0,max:3,step:1}).on("change",()=>{if(0==i.count)c.hidden=!0;else{c.hidden=!1;for(let e=0;ei.count-1&&(h[e].hidden=!0);s.addInput(i,"scale",{min:1,max:50,step:1}),s.addInput(i,"depth",{min:0,max:20,step:1}),s.addInput(i,"intensity",{min:50,max:150,step:1,format:e=>e+"%"}),s.addInput(i,"falloff",{min:1,max:10,step:.1}),s.addInput(i,"persistence",{min:0,max:1,step:.01});let u={seed:""+Math.floor(1e12*Math.random())},m=a.addFolder({title:"Seed",expanded:!1});m.addInput(u,"seed",{format:e=>e.toFixed(0)}),m.addButton({title:"Randomize seed"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString(),a.refresh(),d.Z.generateFrame()}),a.addSeparator(),a.addButton({title:"Render"}).on("click",()=>{d.Z.generateFrame()}),a.addButton({title:"Render Random"}).on("click",()=>{u.seed=Math.floor(1e12*Math.random()).toString();for(let e=0;e<3;e++)l["color"+(e+1)]={r:Math.ceil(255*Math.random()),g:Math.ceil(255*Math.random()),b:Math.ceil(255*Math.random())};a.refresh(),d.Z.generateFrame()}),a.addSeparator(),a.addButton({title:"Save Image"}).on("click",()=>{d.Z.exportFrame()}),a.addSeparator(),a.addInput(e,"autoupdate"),a.on("change",t=>{let n=t.presetKey;e.autoupdate&&(("width"==n||"height"==n)&&d.Z.resizeFrame(e.width,e.height),d.Z.generateFrame())})}function getParameters(){return a.exportPreset()}},341:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return Sp}});var a=n(7437),r=n(2265),d=n(8811),o=n.n(d);function Loading(){return(0,a.jsx)("div",{className:"flex h-screen justify-center items-center",children:(0,a.jsx)("div",{className:"flex items-center justify-center rounded-full w-14 h-14 bg-gradient-to-tr from-cyan-400 to-blue-900 animate-spin",children:(0,a.jsx)("div",{className:"h-10 w-10 rounded-full bg-black"})})})}var i=n(6086);let s=o()(()=>n.e(751).then(n.bind(n,2751)),{loadableGenerated:{webpack:()=>[2751]},ssr:!1});function Sp(){let[e,t]=(0,r.useState)(!1);return(0,r.useEffect)(()=>{t(!0),(0,i.Z)()},[]),(0,a.jsxs)("main",{children:[(0,a.jsx)("div",{id:"TweakPane",className:"fixed top-2.5 right-2.5"}),e&&(0,a.jsx)(s,{}),!e&&(0,a.jsx)(Loading,{})]})}}},function(e){e.O(0,[732,105,735,790,116,173,971,472,744],function(){return e(e.s=4310)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/wiston/page-3411783e09c6cfc5.js b/.next/static/chunks/app/wiston/page-3411783e09c6cfc5.js new file mode 100644 index 0000000..52f690b --- /dev/null +++ b/.next/static/chunks/app/wiston/page-3411783e09c6cfc5.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[619,181,369,447],{3521:function(){}},function(n){n.O(0,[971,938,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/app/wiston/page-a6df78ceae8d716e.js b/.next/static/chunks/app/wiston/page-a6df78ceae8d716e.js deleted file mode 100644 index b902401..0000000 --- a/.next/static/chunks/app/wiston/page-a6df78ceae8d716e.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[619,369,181,447],{3521:function(){}},function(n){n.O(0,[971,472,744],function(){return n(n.s=3521)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/.next/static/chunks/d67c510a-4a8f7a6a0c1c3e2a.js b/.next/static/chunks/d67c510a-4a8f7a6a0c1c3e2a.js new file mode 100644 index 0000000..42d1b43 --- /dev/null +++ b/.next/static/chunks/d67c510a-4a8f7a6a0c1c3e2a.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[790],{6465:function(e,t,r){r.d(t,{B:function(){return C}});var i=r(6030),s=r(1088),n=r(6131),a=r(4800),l=r(7987),_=r(6807),h=r(3609),o=r(3912),u=r(9626),d=r(7209),c=r(5410),g=r(7666),f=r(998),E=r(856),p=r(4548),T=r(5342),x=r(1606),R=r(5122),m=r(5550),b=r(7662);class A{}class C{static get NpmPackage(){return"babylonjs@6.37.1"}static get Version(){return"6.37.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return s.Q.ShadersRepository}static set ShadersRepository(e){s.Q.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4);this._emptyCubeTexture=this.createRawCubeTexture([e,e,e,e,e,e],1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);let r=document.createElement("canvas");return r.width=e,r.height=t,r}createCanvas(e,t){return C._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,r,i){var s,n,o,f,E,T,x,m,S,B,v;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new a.y$,this._frameId=0,this._uniformBuffers=[],this._storageBuffers=[],this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.onContextLostObservable=new a.y$,this.onContextRestoredObservable=new a.y$,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new l.k,this._stencilStateComposer=new R.C,this._stencilState=new _.s,this._alphaState=new h.Q,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=[],this._renderTargetWrapperCache=[],this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._currentRenderTarget=null,this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=[],this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=[],this._currentInstanceLocations=[],this._currentInstanceBuffers=[],this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=[],this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=[],this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new a.y$,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=b.F.Now;let L=null;r=r||{},this._creationOptions=r,this.adaptToDeviceRatio=null!=i&&i,this._stencilStateComposer.stencilGlobal=this._stencilState,p.Z.SetMatrixPrecision(!!r.useHighPrecisionMatrix),r.antialias=null!=t?t:r.antialias,r.deterministicLockstep=null!==(s=r.deterministicLockstep)&&void 0!==s&&s,r.lockstepMaxSteps=null!==(n=r.lockstepMaxSteps)&&void 0!==n?n:4,r.timeStep=null!==(o=r.timeStep)&&void 0!==o?o:1/60,r.audioEngine=null===(f=r.audioEngine)||void 0===f||f,r.stencil=null===(E=r.stencil)||void 0===E||E,this._audioContext=null!==(x=null===(T=r.audioEngineOptions)||void 0===T?void 0:T.audioContext)&&void 0!==x?x:null,this._audioDestination=null!==(S=null===(m=r.audioEngineOptions)||void 0===m?void 0:m.audioDestination)&&void 0!==S?S:null,this.premultipliedAlpha=null===(B=r.premultipliedAlpha)||void 0===B||B,this.useExactSrgbConversions=null!==(v=r.useExactSrgbConversions)&&void 0!==v&&v,this._doNotHandleContextLost=!!r.doNotHandleContextLost,this._isStencilEnable=!!r.stencil,i=i||r.adaptToDeviceRatio||!1;let w=(0,d.CG)()&&window.devicePixelRatio||1,I=r.limitDeviceRatio||w;if(this._hardwareScalingLevel=i?1/Math.min(I,w):1,this._lastDevicePixelRatio=w,!e)return;if(e.getContext){if(L=e,this._renderingCanvas=L,void 0===r.preserveDrawingBuffer&&(r.preserveDrawingBuffer=!1),void 0===r.xrCompatible&&(r.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();let e=navigator.userAgent;for(let t of C.ExceptionList){let i=t.key,s=t.targets;if(new RegExp(i).test(e)){if(t.capture&&t.captureConstraint){let r=t.capture,i=t.captureConstraint,s=new RegExp(r).exec(e);if(s&&s.length>0&&parseInt(s[s.length-1])>=i)continue}for(let e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":r.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,u.Y.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},L.addEventListener("webglcontextlost",this._onContextLost,!1),L.addEventListener("webglcontextrestored",this._onContextRestored,!1),r.powerPreference=r.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(r.xrCompatible=!1),!r.disableWebGL2Support)try{this._gl=L.getContext("webgl2",r)||L.getContext("experimental-webgl2",r),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!L)throw Error("The provided canvas is null or undefined.");try{this._gl=L.getContext("webgl",r)||L.getContext("experimental-webgl",r)}catch(e){throw Error("WebGL not supported")}}if(!this._gl)throw 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";let t=this._gl.getContextAttributes();t&&(r.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==r.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=r.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new g.C:new c.f,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);let F=`Babylon.js v${C.Version}`;u.Y.Log(F+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",F)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{let e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,d.n5)()&&"ontouchend"in document},this._checkForMobile(),(0,d.CG)()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null,this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null;let r=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=r,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=n,u.Y.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){for(let e of this._internalTexturesCache.slice())e._rebuild()}_rebuildRenderTargetWrappers(){for(let e of this._renderTargetWrapperCache.slice())e._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}s.Q.ResetCache()}areAllEffectsReady(){for(let e in this._compiledEffects)if(!this._compiledEffects[e].isReady())return!1;return!0}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuildAfterContextLost()}_rebuildTextures(){}_initGLContext(){var e;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);let t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.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=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e: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{let 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{let 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{let 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{let 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){let 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{let 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{let 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=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,(0,d.CG)()){let{cancelAnimationFrame:e}=this.getHostWindow()||window;if("function"==typeof e)return e(this._frameHandler)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return(0,d.CG)()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}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}_queueNewFrame(e,t){return C.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=()=>this._renderLoop(),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,r,i=!1){var s,n;let a=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=a;let l=0;if(t&&e){let t=!0;if(this._currentRenderTarget){let r=null===(s=this._currentRenderTarget.texture)||void 0===s?void 0:s.format;if(8===r||9===r||10===r||11===r){let r=null===(n=this._currentRenderTarget.texture)||void 0===n?void 0:n.type;7===r||5===r?(C._TempClearColorUint32[0]=255*e.r,C._TempClearColorUint32[1]=255*e.g,C._TempClearColorUint32[2]=255*e.b,C._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,C._TempClearColorUint32)):(C._TempClearColorInt32[0]=255*e.r,C._TempClearColorInt32[1]=255*e.g,C._TempClearColorInt32[2]=255*e.b,C._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,C._TempClearColorInt32)),t=!1}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),l|=this._gl.COLOR_BUFFER_BIT)}r&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),l|=this._gl.DEPTH_BUFFER_BIT),i&&(this._gl.clearStencil(0),l|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(l)}_viewport(e,t,r,i){(e!==this._viewportCached.x||t!==this._viewportCached.y||r!==this._viewportCached.z||i!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=r,this._viewportCached.w=i,this._gl.viewport(e,t,r,i))}setViewport(e,t,r){let i=t||this.getRenderWidth(),s=r||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*i,a*s,i*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,r;if(this.adaptToDeviceRatio){let e=(0,d.CG)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,d.CG)()&&(0,d.n5)()){if(this._renderingCanvas){let 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,r=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,r=window.innerHeight}else t=this._renderingCanvas?this._renderingCanvas.width:100,r=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,r/this._hardwareScalingLevel,e)}setSize(e,t,r=!1){return!!this._renderingCanvas&&(e|=0,t|=0,(!!r||this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)&&(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0))}bindFramebuffer(e,t=0,r,i,s,n=0,a=0){var l,_,h,o,u,d;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer);let c=this._gl;e.isMulti||(e.is2DArray?c.framebufferTextureLayer(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,n,a):e.isCube?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(_=e.texture._hardwareTexture)||void 0===_?void 0:_.underlyingResource,n):e._currentLOD===n||(c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,null===(h=e.texture._hardwareTexture)||void 0===h?void 0:h.underlyingResource,n),e._currentLOD=n));let g=e._depthStencilTexture;if(g){let r=e._depthStencilTextureWithStencil?c.DEPTH_STENCIL_ATTACHMENT:c.DEPTH_ATTACHMENT;e.is2DArray?c.framebufferTextureLayer(c.FRAMEBUFFER,r,null===(o=g._hardwareTexture)||void 0===o?void 0:o.underlyingResource,n,a):e.isCube?c.framebufferTexture2D(c.FRAMEBUFFER,r,c.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(u=g._hardwareTexture)||void 0===u?void 0:u.underlyingResource,n):c.framebufferTexture2D(c.FRAMEBUFFER,r,c.TEXTURE_2D,null===(d=g._hardwareTexture)||void 0===d?void 0:d.underlyingResource,n)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,r,i):(!r&&(r=e.width,n&&(r/=Math.pow(2,n))),!i&&(i=e.height,n&&(i/=Math.pow(2,n))),this._viewport(0,0,r,i)),this.wipeCaches()}setState(e,t=0,r,i=!1,s,n,a=0){var l,_;(this._depthCullingState.cull!==e||r)&&(this._depthCullingState.cull=e);let h=null===(_=null!==(l=this.cullBackFaces)&&void 0!==l?l:s)||void 0===_||_?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||r)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(a);let o=i?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==o||r)&&(this._depthCullingState.frontFace=o),this._stencilStateComposer.stencilMaterial=n}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){let e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){let e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,r){var i;this._currentRenderTarget=null;let s=this._gl;if(e._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,r);return}s.bindFramebuffer(s.READ_FRAMEBUFFER,e._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,e._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}(null===(i=e.texture)||void 0===i?void 0:i.generateMipMaps)&&!t&&!e.isCube&&this.generateMipmaps(e.texture),r&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),r()),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,r){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){let r=this._gl.createBuffer();if(!r)throw Error("Unable to create vertex buffer");let i=new f.M(r);return this.bindArrayBuffer(i),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),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,r){let i=this._gl.createBuffer(),s=new f.M(i);if(!i)throw Error("Unable to create index buffer");this.bindIndexBuffer(s);let 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(),s.references=1,s.is32Bits=4===n.BYTES_PER_ELEMENT,s}_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=65535)return new Uint32Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,r){let i=e.program,s=this._gl.getUniformBlockIndex(i,t);this._gl.uniformBlockBinding(i,s,r)}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,r,i,s,n,a){let l=this._currentBufferPointers[t];if(!l)return;let _=!1;l.active?(l.buffer!==e&&(l.buffer=e,_=!0),l.size!==r&&(l.size=r,_=!0),l.type!==i&&(l.type=i,_=!0),l.normalized!==s&&(l.normalized=s,_=!0),l.stride!==n&&(l.stride=n,_=!0),l.offset!==a&&(l.offset=a,_=!0)):(_=!0,l.active=!0,l.index=t,l.size=r,l.type=i,l.normalized=s,l.stride=n,l.offset=a,l.buffer=e),(_||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),i===this._gl.UNSIGNED_INT||i===this._gl.INT?this._gl.vertexAttribIPointer(t,r,i,n,a):this._gl.vertexAttribPointer(t,r,i,s,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,r){let i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){let t=i[s],a=null;if(r&&(a=r[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);let l=a.getBuffer();l&&(this._vertexAttribPointer(l,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(l))))}}}recordVertexArrayObject(e,t,r,i){let s=this._gl.createVertexArray();if(!s)throw Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,r,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}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,r,i,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,r[a],this._gl.FLOAT,!1,i,n)),n+=4*r[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,r,i){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r,this._bindVertexBuffersAttributes(e,r,i)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,r=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",l=this._compileShader(t,"vertex",i,a),_=this._compileShader(r,"fragment",i,a);return this._createShaderProgram(e,l,_,s,n)}inlineShaderCode(e){return e}createPipelineContext(e){let t=new E.y;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,r,i,s=null){let n=i.createProgram();if(e.program=n,!n)throw Error("Unable to create program");return i.attachShader(n,t),i.attachShader(n,r),i.linkProgram(n),e.context=i,e.vertexShader=t,e.fragmentShader=r,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){let t=e.context,r=e.vertexShader,i=e.fragmentShader,s=e.program;if(!t.getProgramParameter(s,t.LINK_STATUS)){if(!this._gl.getShaderParameter(r,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(r);if(t)throw e.vertexCompilationError=t,Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(i);if(t)throw e.fragmentCompilationError=t,Error("FRAGMENT SHADER "+t)}let n=t.getProgramInfoLog(s);if(n)throw e.programLinkError=n,Error(n)}if(this.validateShaderPrograms&&(t.validateProgram(s),!t.getProgramParameter(s,t.VALIDATE_STATUS))){let r=t.getProgramInfoLog(s);if(r)throw e.programValidationError=r,Error(r)}t.deleteShader(r),t.deleteShader(i),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,r,i,s,n,a,l,_,h){i?e.program=this.createRawShaderProgram(e,t,r,void 0,_):e.program=this.createShaderProgram(e,t,r,l,void 0,_),e.program.__SPECTOR_rebuildProgram=a}_isRenderingStateCompiled(e){return!this._isDisposed&&!e._isDisposed&&!!this._gl.getProgramParameter(e.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(e),!0)}_executeWhenRenderingStateIsCompiled(e,t){if(!e.isParallelCompiled){t();return}let r=e.onCompiled;r?e.onCompiled=()=>{r(),t()}:e.onCompiled=t}getUniforms(e,t){let r=[];for(let i=0;i1||this.isWebGPU)),(1!==l||this._caps.textureFloatLinearFiltering)&&(2!==l||this._caps.textureHalfFloatLinearFiltering)||(_=1),1!==l||this._caps.textureFloat||(l=0,u.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let g=this._gl,f=new o.l(this,i),E=e.width||e,p=e.height||e,T=e.layers||0,x=this._getSamplingParameters(_,a),R=0!==T?g.TEXTURE_2D_ARRAY:g.TEXTURE_2D,m=this._getRGBABufferInternalSizedFormat(l,h,d),b=this._getInternalFormat(h),A=this._getWebGLTextureType(l);return this._bindTextureDirectly(R,f),0!==T?(f.is2DArray=!0,g.texImage3D(R,0,m,E,p,T,0,b,A,null)):g.texImage2D(R,0,m,E,p,0,b,A,null),g.texParameteri(R,g.TEXTURE_MAG_FILTER,x.mag),g.texParameteri(R,g.TEXTURE_MIN_FILTER,x.min),g.texParameteri(R,g.TEXTURE_WRAP_S,g.CLAMP_TO_EDGE),g.texParameteri(R,g.TEXTURE_WRAP_T,g.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(R),this._bindTextureDirectly(R,null),f._useSRGBBuffer=d,f.baseWidth=E,f.baseHeight=p,f.width=E,f.height=p,f.depth=T,f.isReady=!0,f.samples=c,f.generateMipMaps=a,f.samplingMode=_,f.type=l,f.format=h,f.label=n,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,r,s,n=3,a=null,l=null,_,h,d=null,c=null,g=null,f=null,E,p,T){let x="data:"===(e=e||"").substr(0,5),R="blob:"===e.substr(0,5),m=x&&-1!==e.indexOf(";base64,"),b=c||new o.l(this,o.S.Url);b!==c&&(b.label=e.substring(0,60));let A=e;!this._transformTextureUrl||m||c||d||(e=this._transformTextureUrl(e)),A!==e&&(b._originalUrl=A);let S=e.lastIndexOf("."),B=f||(S>-1?e.substring(S).toLowerCase():""),v=null;for(let e of(B.indexOf("?")>-1&&(B=B.split("?")[0]),C._TextureLoaders))if(e.canLoad(B,E)){v=e;break}s&&s.addPendingData(b),b.url=e,b.generateMipMaps=!t,b.samplingMode=n,b.invertY=r,b._useSRGBBuffer=this._getUseSRGBBuffer(!!T,t),this._doNotHandleContextLost||(b._buffer=d);let L=null;a&&!c&&(L=b.onLoadedObservable.add(a)),c||this._internalTexturesCache.push(b);let w=(r,o)=>{s&&s.removePendingData(b),e===A?(L&&b.onLoadedObservable.remove(L),i.l.UseFallbackTexture&&this._createTextureBase(i.l.FallbackTexture,t,b.invertY,s,n,null,l,_,h,d,b),r=(r||"Unknown error")+(i.l.UseFallbackTexture?" - Fallback texture was used":""),b.onErrorObservable.notifyObservers({message:r,exception:o}),l&&l(r,o)):(u.Y.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,b.invertY,s,n,a,l,_,h,d,b,g,f,E,p,T))};if(v){let t=e=>{v.loadData(e,b,(e,t,r,i,a,l)=>{l?w("TextureLoader failed to load data"):_(b,B,s,{width:e,height:t},b.invertY,!r,i,()=>(a(),!1),n)},p)};d?d instanceof ArrayBuffer?t(new Uint8Array(d)):ArrayBuffer.isView(d)?t(d):l&&l("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,e=>t(new Uint8Array(e)),void 0,s?s.offlineProvider:void 0,!0,(e,t)=>{w("Unable to load "+(e&&e.responseURL,t))})}else{let r=e=>{R&&!this._doNotHandleContextLost&&(b._buffer=e),_(b,B,s,e,b.invertY,t,!1,h,n)};!x||m?d&&("string"==typeof d.decoding||d.close)?r(d):C._FileToolsLoadImage(e,r,w,s?s.offlineProvider:null,E,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof d||d instanceof ArrayBuffer||ArrayBuffer.isView(d)||d instanceof Blob?C._FileToolsLoadImage(d,r,w,s?s.offlineProvider:null,E,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):d&&r(d)}return b}createTexture(e,t,r,i,s=3,n=null,a=null,l=null,_=null,h=null,u=null,d,c,g,f){return this._createTextureBase(e,t,r,i,s,n,a,this._prepareWebGLTexture.bind(this),(e,t,r,s,n,a)=>{let l=this._gl,_=r.width===e&&r.height===t;n._creationFlags=null!=g?g:0;let u=this._getTexImageParametersForCreateTexture(h,s,n._useSRGBBuffer);if(_)return l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,r),!1;let d=this._caps.maxTextureSize;if(r.width>d||r.height>d||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!!this._workingCanvas&&!!this._workingContext&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(r,0,0,r.width,r.height,0,0,e,t),l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,this._workingCanvas),n.width=e,n.height=t,!1);{let e=new o.l(this,o.S.Temp);this._bindTextureDirectly(l.TEXTURE_2D,e,!0),l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,r),this._rescaleTexture(e,n,i,u.format,()=>{this._releaseTexture(e),this._bindTextureDirectly(l.TEXTURE_2D,n,!0),a()})}return!0},l,_,h,u,d,c,f)}_getTexImageParametersForCreateTexture(e,t,r){let i,s;return null==e&&(e=".jpg"!==t||r?5:4),1===this.webGLVersion?s=i=this._getInternalFormat(e,r):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,r)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,r,i,s,a){throw(0,n.S)("FileTools")}_rescaleTexture(e,t,r,i,s){}createRawTexture(e,t,r,i,s,a,l,_=null,h=0,o=0,u=!1){throw(0,n.S)("Engine.RawTexture")}createRawCubeTexture(e,t,r,i,s,a,l,_=null){throw(0,n.S)("Engine.RawTexture")}createRawTexture3D(e,t,r,i,s,a,l,_,h=null,o=0){throw(0,n.S)("Engine.RawTexture")}createRawTexture2DArray(e,t,r,i,s,a,l,_,h=null,o=0){throw(0,n.S)("Engine.RawTexture")}_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,r=!1){let i=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||r);this._setTextureParameterInteger(i,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(i,this._gl.TEXTURE_MIN_FILTER,s.min),r&&(t.generateMipMaps=!0,this._gl.generateMipmap(i)),this._bindTextureDirectly(i,null),t.samplingMode=e}updateTextureDimensions(e,t,r,i=1){}updateTextureWrappingMode(e,t,r=null,i=null){let s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(r),e),e._cachedWrapV=r),(e.is2DArray||e.is3D)&&null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(i),e),e._cachedWrapR=i),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,r,i,s,n=1){let a=t.width||t,l=t.height||t,_=t.layers||0;e.baseWidth=a,e.baseHeight=l,e.width=a,e.height=l,e.is2DArray=_>0,e.depth=_,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=i?2:1,e.type=0,e._comparisonFunction=s;let h=this._gl,o=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(o,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(o,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(o,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(o,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(o,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(o,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(o,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(o,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,r,i,s,n=0,a=0){let l=this._gl,_=l.TEXTURE_2D;if(e.isCube&&(_=l.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(_,a,t,r,i,0,s)}_uploadDataToTextureDirectly(e,t,r=0,i=0,s,n=!1){let a=this._gl,l=this._getWebGLTextureType(e.type),_=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let o=a.TEXTURE_2D;e.isCube&&(o=a.TEXTURE_CUBE_MAP_POSITIVE_X+r);let u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),c=n?e.width:Math.pow(2,Math.max(u-i,0)),g=n?e.height:Math.pow(2,Math.max(d-i,0));a.texImage2D(o,i,h,c,g,0,_,l,t)}updateTextureData(e,t,r,i,s,n,a=0,l=0,_=!1){let h=this._gl,o=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,c=h.TEXTURE_2D;e.isCube&&(c=h.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(c,l,r,i,s,n,u,o,t),_&&this._gl.generateMipmap(c),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,r=0,i=0){let s=this._gl,n=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,r,i),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,r,i,s){let n=this._gl;if(!n)return;let a=this._getSamplingParameters(s,!r);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),r||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,r,i,s,n,a,l,_=3){let h=this.getCaps().maxTextureSize,o=Math.min(h,this.needPOTTextures?C.GetExponentOfTwo(i.width,h):i.width),u=Math.min(h,this.needPOTTextures?C.GetExponentOfTwo(i.height,h):i.height),d=this._gl;if(d){if(!e._hardwareTexture){r&&r.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=i.width,e.baseHeight=i.height,e.width=o,e.height=u,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:".jpg"!==t||e._useSRGBBuffer?5:4,l(o,u,i,t,e,()=>{this._prepareWebGLTextureContinuation(e,r,n,a,_)})||this._prepareWebGLTextureContinuation(e,r,n,a,_)}}_setupFramebufferDepthAttachments(e,t,r,i,s=1){let n=this._gl;if(e&&t)return this._createRenderBuffer(r,i,s,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(r,i,s,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(r,i,s,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,r,i,s,n,a=!0){let l=this._gl.createRenderbuffer();return this._updateRenderBuffer(l,e,t,r,i,s,n,a)}_updateRenderBuffer(e,t,r,i,s,n,a,l=!0){let _=this._gl;return _.bindRenderbuffer(_.RENDERBUFFER,e),i>1&&_.renderbufferStorageMultisample?_.renderbufferStorageMultisample(_.RENDERBUFFER,i,n,t,r):_.renderbufferStorage(_.RENDERBUFFER,s,t,r),_.framebufferRenderbuffer(_.FRAMEBUFFER,a,_.RENDERBUFFER,e),l&&_.bindRenderbuffer(_.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();let r=this._internalTexturesCache.indexOf(e);-1!==r&&this._internalTexturesCache.splice(r,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){let t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let r=e.getSamplers();for(let t=0;t-1;if(r&&l&&(this._activeChannel=t._associatedChannel),this._boundTexturesCache[this._activeChannel]!==t||i){if(this._activateCurrentTexture(),t&&t.isMultiview)throw u.Y.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(n=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==n?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else r&&(a=!0,this._activateCurrentTexture());return l&&!r&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,r){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;let i=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(i,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,r,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,r))}_bindSamplerUniformToChannel(e,t){let r=this._boundUniforms[e];r&&r._currentState!==t&&(this._gl.uniform1i(r,t),r._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:break;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,r=!1,i=!1,s=""){let n;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;let r=t.getInternalTexture();r&&(r._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;n=i?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!r&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(r||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;let l=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(l,n,r),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;let e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(l,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,r,i){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===r.length||(this._textureUnits=new Int32Array(r.length));for(let t=0;t=this._caps.maxVertexAttribs)&&this._vertexAttribArraysEnabled[e]&&this.disableAttributeByIndex(e)}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e,t;for(let t of(this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},(0,d.CG)()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,s.Q.ResetCache(),this._activeRequests))t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&(null===(t=this._gl.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext())}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(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let r=!0,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);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);let n=t.checkFramebufferStatus(t.FRAMEBUFFER);if((r=(r=r&&n===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),r=r&&t.getError()===t.NO_ERROR),r){t.bindFramebuffer(t.FRAMEBUFFER,null);let e=t.RGBA,i=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,i,s),r=r&&t.getError()===t.NO_ERROR}for(t.deleteTexture(i),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!r&&t.getError()!==t.NO_ERROR;);return r}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:break;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:break;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let r=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:r=this._gl.ALPHA;break;case 1:r=this._gl.LUMINANCE;break;case 2:r=this._gl.LUMINANCE_ALPHA;break;case 6:r=this._gl.RED;break;case 7:r=this._gl.RG;break;case 4:r=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:r=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:r=this._gl.RED_INTEGER;break;case 9:r=this._gl.RG_INTEGER;break;case 10:r=this._gl.RGB_INTEGER;break;case 11:r=this._gl.RGBA_INTEGER}return r}_getRGBABufferInternalSizedFormat(e,t,r=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return r?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return r?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return r?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return r?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_loadFile(e,t,r,i,s,n){let a=C._FileToolsLoadFile(e,t,r,i,s,n);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}static _FileToolsLoadFile(e,t,r,i,s,a){throw(0,n.S)("FileTools")}readPixels(e,t,r,i,s=!0,n=!0){let a=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(i*r*(s?4:3));return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,r,i,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}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{let e=this._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{let e=this._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}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){let t=C.CeilingPOT(e),r=C.FloorPOT(e);return t-e>e-r?r:t}static GetExponentOfTwo(e,t,r=2){let i;switch(r){case 1:i=C.FloorPOT(e);break;case 2:i=C.NearestPOT(e);break;default:i=C.CeilingPOT(e)}return Math.min(i,t)}static QueueNewFrame(e,t){if((0,d.CG)()){let{requestAnimationFrame:r}=t||window;if("function"==typeof r)return r(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:(0,d.n5)()?document:null}}C._TempClearColorUint32=new Uint32Array(4),C._TempClearColorInt32=new Int32Array(4),C.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"]}],C._TextureLoaders=[],C.CollisionsEpsilon=.001,C._IsSupported=null,C._HasMajorPerformanceCaveat=null}}]); \ No newline at end of file diff --git a/.next/static/chunks/d67c510a-e497b3cd5bf43bb4.js b/.next/static/chunks/d67c510a-e497b3cd5bf43bb4.js deleted file mode 100644 index 8660c20..0000000 --- a/.next/static/chunks/d67c510a-e497b3cd5bf43bb4.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[790],{6465:function(e,t,r){r.d(t,{B:function(){return ThinEngine}});var i=r(6030),s=r(1088),n=r(6131),a=r(4800),l=r(7987),_=r(6807),h=r(3609),o=r(3912),u=r(9626),d=r(7209),g=r(5410),c=r(7666),f=r(998),E=r(856),p=r(4548),T=r(5342),R=r(1606),x=r(5122),m=r(5550),b=r(7662);let BufferPointer=class BufferPointer{};let ThinEngine=class ThinEngine{static get NpmPackage(){return"babylonjs@6.28.1"}static get Version(){return"6.28.1"}get description(){let e=this.name+this.webGLVersion;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}get isDisposed(){return this._isDisposed}static get ShadersRepository(){return s.Q.ShadersRepository}static set ShadersRepository(e){s.Q.ShadersRepository=e}_getShaderProcessor(e){return this._shaderProcessor}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,e?this._depthCullingState.depthFunc=518:this._depthCullingState.depthFunc=515)}get frameId(){return this._frameId}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}getCreationOptions(){return this._creationOptions}get _shouldUseHighPrecisionShader(){return!!(this._caps.highPrecisionShaderSupported&&this._highPrecisionShadersAllowed)}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get activeRenderLoops(){return this._activeRenderLoops}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}get currentViewport(){return this._cachedViewport}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,5,!1,!1,1)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,5,!1,!1,1)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){let e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,5,0,!1,!1,1)}return this._emptyCubeTexture}get isWebGPU(){return this._isWebGPU}get shaderPlatformName(){return this._shaderPlatformName}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return this._snapshotRenderingMode}set snapshotRenderingMode(e){this._snapshotRenderingMode=e}snapshotRenderingReset(){this.snapshotRendering=!1}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);let r=document.createElement("canvas");return r.width=e,r.height=t,r}createCanvas(e,t){return ThinEngine._CreateCanvas(e,t)}createCanvasImage(){return document.createElement("img")}constructor(e,t,r,i){var s,n,o,f,E,T,R,m,A,S,C;this._name="WebGL",this._isDisposed=!1,this.forcePOTTextures=!1,this.isFullscreen=!1,this.cullBackFaces=null,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this.validateShaderPrograms=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this.disableUniformBuffers=!1,this.onDisposeObservable=new a.y$,this._frameId=0,this._uniformBuffers=[],this._storageBuffers=[],this._webGLVersion=1,this._windowIsBackground=!1,this._highPrecisionShadersAllowed=!0,this._badOS=!1,this._badDesktopOS=!1,this._renderingQueueLaunched=!1,this._activeRenderLoops=[],this.onContextLostObservable=new a.y$,this.onContextRestoredObservable=new a.y$,this._contextWasLost=!1,this._doNotHandleContextLost=!1,this.disableVertexArrayObjects=!1,this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new l.k,this._stencilStateComposer=new x.C,this._stencilState=new _.s,this._alphaState=new h.Q,this._alphaMode=1,this._alphaEquation=0,this._internalTexturesCache=[],this._renderTargetWrapperCache=[],this._activeChannel=0,this._currentTextureChannel=-1,this._boundTexturesCache={},this._compiledEffects={},this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=[],this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=[],this._currentInstanceLocations=[],this._currentInstanceBuffers=[],this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=[],this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._activeRequests=[],this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._transformTextureUrl=null,this.hostInformation={isMobile:!1},this.premultipliedAlpha=!0,this.onBeforeTextureInitObservable=new a.y$,this._isWebGPU=!1,this._snapshotRenderingMode=0,this._viewportCached={x:0,y:0,z:0,w:0},this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},this.startTime=b.F.Now;let B=null;r=r||{},this._creationOptions=r,this.adaptToDeviceRatio=null!=i&&i,this._stencilStateComposer.stencilGlobal=this._stencilState,p.Z.SetMatrixPrecision(!!r.useHighPrecisionMatrix),r.antialias=null!=t?t:r.antialias,r.deterministicLockstep=null!==(s=r.deterministicLockstep)&&void 0!==s&&s,r.lockstepMaxSteps=null!==(n=r.lockstepMaxSteps)&&void 0!==n?n:4,r.timeStep=null!==(o=r.timeStep)&&void 0!==o?o:1/60,r.audioEngine=null===(f=r.audioEngine)||void 0===f||f,r.stencil=null===(E=r.stencil)||void 0===E||E,this._audioContext=null!==(R=null===(T=r.audioEngineOptions)||void 0===T?void 0:T.audioContext)&&void 0!==R?R:null,this._audioDestination=null!==(A=null===(m=r.audioEngineOptions)||void 0===m?void 0:m.audioDestination)&&void 0!==A?A:null,this.premultipliedAlpha=null===(S=r.premultipliedAlpha)||void 0===S||S,this.useExactSrgbConversions=null!==(C=r.useExactSrgbConversions)&&void 0!==C&&C,this._doNotHandleContextLost=!!r.doNotHandleContextLost,this._isStencilEnable=!!r.stencil,i=i||r.adaptToDeviceRatio||!1;let v=(0,d.CG)()&&window.devicePixelRatio||1,L=r.limitDeviceRatio||v;if(this._hardwareScalingLevel=i?1/Math.min(L,v):1,this._lastDevicePixelRatio=v,!e)return;if(e.getContext){if(B=e,this._renderingCanvas=B,void 0===r.preserveDrawingBuffer&&(r.preserveDrawingBuffer=!1),void 0===r.xrCompatible&&(r.xrCompatible=!0),navigator&&navigator.userAgent){this._setupMobileChecks();let e=navigator.userAgent;for(let t of ThinEngine.ExceptionList){let i=t.key,s=t.targets,n=new RegExp(i);if(n.test(e)){if(t.capture&&t.captureConstraint){let r=t.capture,i=t.captureConstraint,s=new RegExp(r),n=s.exec(e);if(n&&n.length>0){let e=parseInt(n[n.length-1]);if(e>=i)continue}}for(let e of s)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":r.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,u.Y.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost(()=>this._initGLContext())},B.addEventListener("webglcontextlost",this._onContextLost,!1),B.addEventListener("webglcontextrestored",this._onContextRestored,!1),r.powerPreference=r.powerPreference||"high-performance"),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),this._badDesktopOS&&(r.xrCompatible=!1),!r.disableWebGL2Support)try{this._gl=B.getContext("webgl2",r)||B.getContext("experimental-webgl2",r),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!B)throw Error("The provided canvas is null or undefined.");try{this._gl=B.getContext("webgl",r)||B.getContext("experimental-webgl",r)}catch(e){throw Error("WebGL not supported")}}if(!this._gl)throw 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";let t=this._gl.getContextAttributes();t&&(r.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==r.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=r.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e1?new c.C:new g.f,this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent);let w=`Babylon.js v${ThinEngine.Version}`;console.log(w+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",w)}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{let e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&(0,d.n5)()&&"ontouchend"in document},this._checkForMobile(),(0,d.CG)()&&window.addEventListener("resize",this._checkForMobile))}_restoreEngineAfterContextLost(e){setTimeout(async()=>{var t;this._dummyFramebuffer=null;let r=this._depthCullingState.depthTest,i=this._depthCullingState.depthFunc,s=this._depthCullingState.depthMask,n=this._stencilState.stencilTest;await e(),this.wipeCaches(!0),this._rebuildEffects(),null===(t=this._rebuildComputeEffects)||void 0===t||t.call(this),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0),this._depthCullingState.depthTest=r,this._depthCullingState.depthFunc=i,this._depthCullingState.depthMask=s,this._stencilState.stencilTest=n,u.Y.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1},0)}_sharedInit(e){this._renderingCanvas=e}_getShaderProcessingContext(e){return null}_rebuildInternalTextures(){let e=this._internalTexturesCache.slice();for(let t of e)t._rebuild()}_rebuildRenderTargetWrappers(){let e=this._renderTargetWrapperCache.slice();for(let t of e)t._rebuild()}_rebuildEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];t._pipelineContext=null,t._wasPreviouslyReady=!1,t._prepareEffect()}s.Q.ResetCache()}areAllEffectsReady(){for(let e in this._compiledEffects){let t=this._compiledEffects[e];if(!t.isReady())return!1}return!0}_rebuildBuffers(){for(let e of this._uniformBuffers)e._rebuild();for(let e of this._storageBuffers)e._rebuild()}_initGLContext(){var e;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")),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._glVersion=this._gl.getParameter(this._gl.VERSION);let t=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=t&&(this._glRenderer=this._gl.getParameter(t.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(t.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=(null!==(e=this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT))&&void 0!==e?e: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{let 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{let 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{let 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{let 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){let 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{let 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{let 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=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(this._renderingQueueLaunched&&this._frameHandler){if(this._renderingQueueLaunched=!1,(0,d.CG)()){let{cancelAnimationFrame:e}=this.getHostWindow()||window;if("function"==typeof e)return e(this._frameHandler)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(this._frameHandler);return clearTimeout(this._frameHandler)}}_renderLoop(){if(!this._contextWasLost){let e=!0;if((this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e){this.beginFrame();for(let e=0;e0?this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()):this._renderingQueueLaunched=!1}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}getHostWindow(){return(0,d.CG)()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}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}_queueNewFrame(e,t){return ThinEngine.QueueNewFrame(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),this._renderingQueueLaunched||(this._renderingQueueLaunched=!0,this._boundRenderFunction=()=>this._renderLoop(),this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}clear(e,t,r,i=!1){var s,n;let a=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=a;let l=0;if(t&&e){let t=!0;if(this._currentRenderTarget){let r=null===(s=this._currentRenderTarget.texture)||void 0===s?void 0:s.format;if(8===r||9===r||10===r||11===r){let r=null===(n=this._currentRenderTarget.texture)||void 0===n?void 0:n.type;7===r||5===r?(ThinEngine._TempClearColorUint32[0]=255*e.r,ThinEngine._TempClearColorUint32[1]=255*e.g,ThinEngine._TempClearColorUint32[2]=255*e.b,ThinEngine._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,ThinEngine._TempClearColorUint32)):(ThinEngine._TempClearColorInt32[0]=255*e.r,ThinEngine._TempClearColorInt32[1]=255*e.g,ThinEngine._TempClearColorInt32[2]=255*e.b,ThinEngine._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,ThinEngine._TempClearColorInt32)),t=!1}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),l|=this._gl.COLOR_BUFFER_BIT)}r&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),l|=this._gl.DEPTH_BUFFER_BIT),i&&(this._gl.clearStencil(0),l|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(l)}_viewport(e,t,r,i){(e!==this._viewportCached.x||t!==this._viewportCached.y||r!==this._viewportCached.z||i!==this._viewportCached.w)&&(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=r,this._viewportCached.w=i,this._gl.viewport(e,t,r,i))}setViewport(e,t,r){let i=t||this.getRenderWidth(),s=r||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*i,a*s,i*e.width,s*e.height)}beginFrame(){}endFrame(){this._badOS&&this.flushFramebuffer(),this._frameId++}resize(e=!1){let t,r;if(this.adaptToDeviceRatio){let e=(0,d.CG)()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if((0,d.CG)()&&(0,d.n5)()){if(this._renderingCanvas){let 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,r=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,r=window.innerHeight}else t=this._renderingCanvas?this._renderingCanvas.width:100,r=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,r/this._hardwareScalingLevel,e)}setSize(e,t,r=!1){return!!this._renderingCanvas&&(e|=0,t|=0,(!!r||this._renderingCanvas.width!==e||this._renderingCanvas.height!==t)&&(this._renderingCanvas.width=e,this._renderingCanvas.height=t,!0))}bindFramebuffer(e,t=0,r,i,s,n=0,a=0){var l,_,h,o,u,d;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(e._MSAAFramebuffer?e._MSAAFramebuffer:e._framebuffer);let g=this._gl;e.isMulti||(e.is2DArray?g.framebufferTextureLayer(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,null===(l=e.texture._hardwareTexture)||void 0===l?void 0:l.underlyingResource,n,a):e.isCube?g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(_=e.texture._hardwareTexture)||void 0===_?void 0:_.underlyingResource,n):e._currentLOD===n||(g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,null===(h=e.texture._hardwareTexture)||void 0===h?void 0:h.underlyingResource,n),e._currentLOD=n));let c=e._depthStencilTexture;if(c){let r=e._depthStencilTextureWithStencil?g.DEPTH_STENCIL_ATTACHMENT:g.DEPTH_ATTACHMENT;e.is2DArray?g.framebufferTextureLayer(g.FRAMEBUFFER,r,null===(o=c._hardwareTexture)||void 0===o?void 0:o.underlyingResource,n,a):e.isCube?g.framebufferTexture2D(g.FRAMEBUFFER,r,g.TEXTURE_CUBE_MAP_POSITIVE_X+t,null===(u=c._hardwareTexture)||void 0===u?void 0:u.underlyingResource,n):g.framebufferTexture2D(g.FRAMEBUFFER,r,g.TEXTURE_2D,null===(d=c._hardwareTexture)||void 0===d?void 0:d.underlyingResource,n)}this._cachedViewport&&!s?this.setViewport(this._cachedViewport,r,i):(!r&&(r=e.width,n&&(r/=Math.pow(2,n))),!i&&(i=e.height,n&&(i/=Math.pow(2,n))),this._viewport(0,0,r,i)),this.wipeCaches()}setState(e,t=0,r,i=!1,s,n,a=0){var l,_;(this._depthCullingState.cull!==e||r)&&(this._depthCullingState.cull=e);let h=null===(_=null!==(l=this.cullBackFaces)&&void 0!==l?l:s)||void 0===_||_?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==h||r)&&(this._depthCullingState.cullFace=h),this.setZOffset(t),this.setZOffsetUnits(a);let o=i?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==o||r)&&(this._depthCullingState.frontFace=o),this._stencilStateComposer.stencilMaterial=n}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){let e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){let e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)}unBindFramebuffer(e,t=!1,r){var i;this._currentRenderTarget=null;let s=this._gl;if(e._MSAAFramebuffer){if(e.isMulti){this.unBindMultiColorAttachmentFramebuffer(e,t,r);return}s.bindFramebuffer(s.READ_FRAMEBUFFER,e._MSAAFramebuffer),s.bindFramebuffer(s.DRAW_FRAMEBUFFER,e._framebuffer),s.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s.COLOR_BUFFER_BIT,s.NEAREST)}(null===(i=e.texture)||void 0===i?void 0:i.generateMipMaps)&&!t&&!e.isCube&&this.generateMipmaps(e.texture),r&&(e._MSAAFramebuffer&&this._bindUnboundFramebuffer(e._framebuffer),r()),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,r){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){let r=this._gl.createBuffer();if(!r)throw Error("Unable to create vertex buffer");let i=new f.M(r);return this.bindArrayBuffer(i),e instanceof Array?this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t):this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),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,r){let i=this._gl.createBuffer(),s=new f.M(i);if(!i)throw Error("Unable to create index buffer");this.bindIndexBuffer(s);let 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(),s.references=1,s.is32Bits=4===n.BYTES_PER_ELEMENT,s}_normalizeIndexData(e){let t=e.BYTES_PER_ELEMENT;if(2===t)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t=65535)return new Uint32Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,r){let i=e.program,s=this._gl.getUniformBlockIndex(i,t);this._gl.uniformBlockBinding(i,s,r)}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,r,i,s,n,a){let l=this._currentBufferPointers[t];if(!l)return;let _=!1;l.active?(l.buffer!==e&&(l.buffer=e,_=!0),l.size!==r&&(l.size=r,_=!0),l.type!==i&&(l.type=i,_=!0),l.normalized!==s&&(l.normalized=s,_=!0),l.stride!==n&&(l.stride=n,_=!0),l.offset!==a&&(l.offset=a,_=!0)):(_=!0,l.active=!0,l.index=t,l.size=r,l.type=i,l.normalized=s,l.stride=n,l.offset=a,l.buffer=e),(_||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),i===this._gl.UNSIGNED_INT||i===this._gl.INT?this._gl.vertexAttribIPointer(t,r,i,n,a):this._gl.vertexAttribPointer(t,r,i,s,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,r){let i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let s=0;s=0){let t=i[s],a=null;if(r&&(a=r[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);let l=a.getBuffer();l&&(this._vertexAttribPointer(l,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(l))))}}}recordVertexArrayObject(e,t,r,i){let s=this._gl.createVertexArray();if(!s)throw Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(s),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,r,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),s}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,r,i,s){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==s){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s;let t=s.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,r[a],this._gl.FLOAT,!1,i,n)),n+=4*r[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,r,i){(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r)&&(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r,this._bindVertexBuffersAttributes(e,r,i)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,r=this._currentInstanceLocations.length;t1?"#version 300 es\n#define WEBGL2 \n":"",l=this._compileShader(t,"vertex",i,a),_=this._compileShader(r,"fragment",i,a);return this._createShaderProgram(e,l,_,s,n)}inlineShaderCode(e){return e}createPipelineContext(e){let t=new E.y;return t.engine=this,this._caps.parallelShaderCompile&&(t.isParallelCompiled=!0),t}createMaterialContext(){}createDrawContext(){}_createShaderProgram(e,t,r,i,s=null){let n=i.createProgram();if(e.program=n,!n)throw Error("Unable to create program");return i.attachShader(n,t),i.attachShader(n,r),i.linkProgram(n),e.context=i,e.vertexShader=t,e.fragmentShader=r,e.isParallelCompiled||this._finalizePipelineContext(e),n}_finalizePipelineContext(e){let t=e.context,r=e.vertexShader,i=e.fragmentShader,s=e.program,n=t.getProgramParameter(s,t.LINK_STATUS);if(!n){if(!this._gl.getShaderParameter(r,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(r);if(t)throw e.vertexCompilationError=t,Error("VERTEX SHADER "+t)}if(!this._gl.getShaderParameter(i,this._gl.COMPILE_STATUS)){let t=this._gl.getShaderInfoLog(i);if(t)throw e.fragmentCompilationError=t,Error("FRAGMENT SHADER "+t)}let n=t.getProgramInfoLog(s);if(n)throw e.programLinkError=n,Error(n)}if(this.validateShaderPrograms){t.validateProgram(s);let r=t.getProgramParameter(s,t.VALIDATE_STATUS);if(!r){let r=t.getProgramInfoLog(s);if(r)throw e.programValidationError=r,Error(r)}}t.deleteShader(r),t.deleteShader(i),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}_preparePipelineContext(e,t,r,i,s,n,a,l,_,h){i?e.program=this.createRawShaderProgram(e,t,r,void 0,_):e.program=this.createShaderProgram(e,t,r,l,void 0,_),e.program.__SPECTOR_rebuildProgram=a}_isRenderingStateCompiled(e){return!this._isDisposed&&!e._isDisposed&&!!this._gl.getProgramParameter(e.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(e),!0)}_executeWhenRenderingStateIsCompiled(e,t){if(!e.isParallelCompiled){t();return}let r=e.onCompiled;r?e.onCompiled=()=>{r(),t()}:e.onCompiled=t}getUniforms(e,t){let r=[];for(let i=0;i1||this.isWebGPU)),(1!==l||this._caps.textureFloatLinearFiltering)&&(2!==l||this._caps.textureHalfFloatLinearFiltering)||(_=1),1!==l||this._caps.textureFloat||(l=0,u.Y.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));let c=this._gl,f=new o.l(this,i),E=e.width||e,p=e.height||e,T=e.layers||0,R=this._getSamplingParameters(_,a),x=0!==T?c.TEXTURE_2D_ARRAY:c.TEXTURE_2D,m=this._getRGBABufferInternalSizedFormat(l,h,d),b=this._getInternalFormat(h),A=this._getWebGLTextureType(l);return this._bindTextureDirectly(x,f),0!==T?(f.is2DArray=!0,c.texImage3D(x,0,m,E,p,T,0,b,A,null)):c.texImage2D(x,0,m,E,p,0,b,A,null),c.texParameteri(x,c.TEXTURE_MAG_FILTER,R.mag),c.texParameteri(x,c.TEXTURE_MIN_FILTER,R.min),c.texParameteri(x,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(x,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),a&&this._gl.generateMipmap(x),this._bindTextureDirectly(x,null),f._useSRGBBuffer=d,f.baseWidth=E,f.baseHeight=p,f.width=E,f.height=p,f.depth=T,f.isReady=!0,f.samples=g,f.generateMipMaps=a,f.samplingMode=_,f.type=l,f.format=h,f.label=n,this._internalTexturesCache.push(f),f}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU||t)}_createTextureBase(e,t,r,s,n=3,a=null,l=null,_,h,d=null,g=null,c=null,f=null,E,p,T){e=e||"";let R="data:"===e.substr(0,5),x="blob:"===e.substr(0,5),m=R&&-1!==e.indexOf(";base64,"),b=g||new o.l(this,o.S.Url);b!==g&&(b.label=e.substring(0,60));let A=e;!this._transformTextureUrl||m||g||d||(e=this._transformTextureUrl(e)),A!==e&&(b._originalUrl=A);let S=e.lastIndexOf("."),C=f||(S>-1?e.substring(S).toLowerCase():""),B=null,v=C.indexOf("?");for(let e of(v>-1&&(C=C.split("?")[0]),ThinEngine._TextureLoaders))if(e.canLoad(C,E)){B=e;break}s&&s.addPendingData(b),b.url=e,b.generateMipMaps=!t,b.samplingMode=n,b.invertY=r,b._useSRGBBuffer=this._getUseSRGBBuffer(!!T,t),this._doNotHandleContextLost||(b._buffer=d);let L=null;a&&!g&&(L=b.onLoadedObservable.add(a)),g||this._internalTexturesCache.push(b);let onInternalError=(r,o)=>{s&&s.removePendingData(b),e===A?(L&&b.onLoadedObservable.remove(L),i.l.UseFallbackTexture&&this._createTextureBase(i.l.FallbackTexture,t,b.invertY,s,n,null,l,_,h,d,b),r=(r||"Unknown error")+(i.l.UseFallbackTexture?" - Fallback texture was used":""),b.onErrorObservable.notifyObservers({message:r,exception:o}),l&&l(r,o)):(u.Y.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,b.invertY,s,n,a,l,_,h,d,b,c,f,E,p,T))};if(B){let callback=e=>{B.loadData(e,b,(e,t,r,i,a,l)=>{l?onInternalError("TextureLoader failed to load data"):_(b,C,s,{width:e,height:t},b.invertY,!r,i,()=>(a(),!1),n)},p)};d?d instanceof ArrayBuffer?callback(new Uint8Array(d)):ArrayBuffer.isView(d)?callback(d):l&&l("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,e=>callback(new Uint8Array(e)),void 0,s?s.offlineProvider:void 0,!0,(e,t)=>{onInternalError("Unable to load "+(e&&e.responseURL,t))})}else{let onload=e=>{x&&!this._doNotHandleContextLost&&(b._buffer=e),_(b,C,s,e,b.invertY,t,!1,h,n)};!R||m?d&&("string"==typeof d.decoding||d.close)?onload(d):ThinEngine._FileToolsLoadImage(e,onload,onInternalError,s?s.offlineProvider:null,E,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof d||d instanceof ArrayBuffer||ArrayBuffer.isView(d)||d instanceof Blob?ThinEngine._FileToolsLoadImage(d,onload,onInternalError,s?s.offlineProvider:null,E,b.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):d&&onload(d)}return b}createTexture(e,t,r,i,s=3,n=null,a=null,l=null,_=null,h=null,u=null,d,g,c,f){return this._createTextureBase(e,t,r,i,s,n,a,this._prepareWebGLTexture.bind(this),(e,t,r,s,n,a)=>{let l=this._gl,_=r.width===e&&r.height===t,u=this._getTexImageParametersForCreateTexture(h,s,n._useSRGBBuffer);if(_)return l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,r),!1;let d=this._caps.maxTextureSize;if(r.width>d||r.height>d||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!!this._workingCanvas&&!!this._workingContext&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(r,0,0,r.width,r.height,0,0,e,t),l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,this._workingCanvas),n.width=e,n.height=t,!1);{let e=new o.l(this,o.S.Temp);this._bindTextureDirectly(l.TEXTURE_2D,e,!0),l.texImage2D(l.TEXTURE_2D,0,u.internalFormat,u.format,u.type,r),this._rescaleTexture(e,n,i,u.format,()=>{this._releaseTexture(e),this._bindTextureDirectly(l.TEXTURE_2D,n,!0),a()})}return!0},l,_,h,u,d,g,f)}_getTexImageParametersForCreateTexture(e,t,r){let i,s;return null==e&&(e=".jpg"!==t||r?5:4),1===this.webGLVersion?s=i=this._getInternalFormat(e,r):(i=this._getInternalFormat(e,!1),s=this._getRGBABufferInternalSizedFormat(0,e,r)),{internalFormat:s,format:i,type:this._gl.UNSIGNED_BYTE}}static _FileToolsLoadImage(e,t,r,i,s,a){throw(0,n.S)("FileTools")}_rescaleTexture(e,t,r,i,s){}createRawTexture(e,t,r,i,s,a,l,_=null,h=0,o=0,u=!1){throw(0,n.S)("Engine.RawTexture")}createRawCubeTexture(e,t,r,i,s,a,l,_=null){throw(0,n.S)("Engine.RawTexture")}createRawTexture3D(e,t,r,i,s,a,l,_,h=null,o=0){throw(0,n.S)("Engine.RawTexture")}createRawTexture2DArray(e,t,r,i,s,a,l,_,h=null,o=0){throw(0,n.S)("Engine.RawTexture")}_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,r=!1){let i=this._getTextureTarget(t),s=this._getSamplingParameters(e,t.useMipMaps||r);this._setTextureParameterInteger(i,this._gl.TEXTURE_MAG_FILTER,s.mag,t),this._setTextureParameterInteger(i,this._gl.TEXTURE_MIN_FILTER,s.min),r&&(t.generateMipMaps=!0,this._gl.generateMipmap(i)),this._bindTextureDirectly(i,null),t.samplingMode=e}updateTextureDimensions(e,t,r,i=1){}updateTextureWrappingMode(e,t,r=null,i=null){let s=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==r&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(r),e),e._cachedWrapV=r),(e.is2DArray||e.is3D)&&null!==i&&(this._setTextureParameterInteger(s,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(i),e),e._cachedWrapR=i),this._bindTextureDirectly(s,null)}_setupDepthStencilTexture(e,t,r,i,s,n=1){let a=t.width||t,l=t.height||t,_=t.layers||0;e.baseWidth=a,e.baseHeight=l,e.width=a,e.height=l,e.is2DArray=_>0,e.depth=_,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=i?2:1,e.type=0,e._comparisonFunction=s;let h=this._gl,o=this._getTextureTarget(e),u=this._getSamplingParameters(e.samplingMode,!1);h.texParameteri(o,h.TEXTURE_MAG_FILTER,u.mag),h.texParameteri(o,h.TEXTURE_MIN_FILTER,u.min),h.texParameteri(o,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(o,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===s?(h.texParameteri(o,h.TEXTURE_COMPARE_FUNC,515),h.texParameteri(o,h.TEXTURE_COMPARE_MODE,h.NONE)):(h.texParameteri(o,h.TEXTURE_COMPARE_FUNC,s),h.texParameteri(o,h.TEXTURE_COMPARE_MODE,h.COMPARE_REF_TO_TEXTURE)))}_uploadCompressedDataToTextureDirectly(e,t,r,i,s,n=0,a=0){let l=this._gl,_=l.TEXTURE_2D;if(e.isCube&&(_=l.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case 37492:case 36196:this._caps.etc2?t=l.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case 37496:this._caps.etc2?t=l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case 36492:t=l.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case 37808:t=l.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case 33776:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33777:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case 33779:this._caps.s3tc_srgb?t=l.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(_,a,t,r,i,0,s)}_uploadDataToTextureDirectly(e,t,r=0,i=0,s,n=!1){let a=this._gl,l=this._getWebGLTextureType(e.type),_=this._getInternalFormat(e.format),h=void 0===s?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(s,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let o=a.TEXTURE_2D;e.isCube&&(o=a.TEXTURE_CUBE_MAP_POSITIVE_X+r);let u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),g=n?e.width:Math.pow(2,Math.max(u-i,0)),c=n?e.height:Math.pow(2,Math.max(d-i,0));a.texImage2D(o,i,h,g,c,0,_,l,t)}updateTextureData(e,t,r,i,s,n,a=0,l=0,_=!1){let h=this._gl,o=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=h.TEXTURE_2D,g=h.TEXTURE_2D;e.isCube&&(g=h.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=h.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),h.texSubImage2D(g,l,r,i,s,n,u,o,t),_&&this._gl.generateMipmap(g),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,r=0,i=0){let s=this._gl,n=e.isCube?s.TEXTURE_CUBE_MAP:s.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,r,i),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,r,i,s){let n=this._gl;if(!n)return;let a=this._getSamplingParameters(s,!r);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),r||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,r,i,s,n,a,l,_=3){let h=this.getCaps().maxTextureSize,o=Math.min(h,this.needPOTTextures?ThinEngine.GetExponentOfTwo(i.width,h):i.width),u=Math.min(h,this.needPOTTextures?ThinEngine.GetExponentOfTwo(i.height,h):i.height),d=this._gl;if(d){if(!e._hardwareTexture){r&&r.removePendingData(e);return}this._bindTextureDirectly(d.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===s||!!s),e.baseWidth=i.width,e.baseHeight=i.height,e.width=o,e.height=u,e.isReady=!0,e.type=-1!==e.type?e.type:0,e.format=-1!==e.format?e.format:".jpg"!==t||e._useSRGBBuffer?5:4,l(o,u,i,t,e,()=>{this._prepareWebGLTextureContinuation(e,r,n,a,_)})||this._prepareWebGLTextureContinuation(e,r,n,a,_)}}_setupFramebufferDepthAttachments(e,t,r,i,s=1){let n=this._gl;if(e&&t)return this._createRenderBuffer(r,i,s,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(r,i,s,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(r,i,s,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,r,i,s,n,a=!0){let l=this._gl,_=l.createRenderbuffer();return this._updateRenderBuffer(_,e,t,r,i,s,n,a)}_updateRenderBuffer(e,t,r,i,s,n,a,l=!0){let _=this._gl;return _.bindRenderbuffer(_.RENDERBUFFER,e),i>1&&_.renderbufferStorageMultisample?_.renderbufferStorageMultisample(_.RENDERBUFFER,i,n,t,r):_.renderbufferStorage(_.RENDERBUFFER,s,t,r),_.framebufferRenderbuffer(_.FRAMEBUFFER,a,_.RENDERBUFFER,e),l&&_.bindRenderbuffer(_.RENDERBUFFER,null),e}_releaseTexture(e){var t;this._deleteTexture(null===(t=e._hardwareTexture)||void 0===t?void 0:t.underlyingResource),this.unbindAllTextures();let r=this._internalTexturesCache.indexOf(e);-1!==r&&this._internalTexturesCache.splice(r,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_releaseRenderTargetWrapper(e){let t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}_deleteTexture(e){e&&this._gl.deleteTexture(e)}_setProgram(e){this._currentProgram!==e&&(this._gl.useProgram(e),this._currentProgram=e)}bindSamplers(e){let t=e.getPipelineContext();this._setProgram(t.program);let r=e.getSamplers();for(let t=0;t-1;r&&l&&(this._activeChannel=t._associatedChannel);let _=this._boundTexturesCache[this._activeChannel];if(_!==t||i){if(this._activateCurrentTexture(),t&&t.isMultiview)throw console.error(e,t),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,null!==(n=null===(s=null==t?void 0:t._hardwareTexture)||void 0===s?void 0:s.underlyingResource)&&void 0!==n?n:null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else r&&(a=!0,this._activateCurrentTexture());return l&&!r&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),a}_bindTexture(e,t,r){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;let i=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(i,t)}unbindAllTextures(){for(let e=0;e1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,r,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,r))}_bindSamplerUniformToChannel(e,t){let r=this._boundUniforms[e];r&&r._currentState!==t&&(this._gl.uniform1i(r,t),r._currentState=t)}_getTextureWrapMode(e){switch(e){case 1:break;case 0:return this._gl.CLAMP_TO_EDGE;case 2:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,r=!1,i=!1,s=""){let n;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;let r=t.getInternalTexture();r&&(r._associatedChannel=e),t.update()}else if(4===t.delayLoadState)return t.delayLoad(),!1;n=i?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!r&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(r||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;let l=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(l,n,r),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;let e=3!==t.coordinatesMode&&5!==t.coordinatesMode?1:0;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(l,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(l,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,r,i){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===r.length||(this._textureUnits=new Int32Array(r.length));for(let t=0;t=this._caps.maxVertexAttribs)&&this._vertexAttribArraysEnabled[e]&&this.disableAttributeByIndex(e)}releaseEffects(){for(let e in this._compiledEffects){let t=this._compiledEffects[e].getPipelineContext();this._deletePipelineContext(t)}this._compiledEffects={}}dispose(){var e,t;for(let t of(this._isDisposed=!0,this.stopRenderLoop(),this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.releaseEffects(),null===(e=this.releaseComputeEffects)||void 0===e||e.call(this),this.unbindAllAttributes(),this._boundUniforms={},(0,d.CG)()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored)),window.removeEventListener("resize",this._checkForMobile)),this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._renderingCanvas=null,this._currentProgram=null,this._boundRenderFunction=null,s.Q.ResetCache(),this._activeRequests))t.abort();this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._creationOptions.loseContextOnDispose&&(null===(t=this._gl.getExtension("WEBGL_lose_context"))||void 0===t||t.loseContext())}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(1)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(2)}_canRenderToFramebuffer(e){let t=this._gl;for(;t.getError()!==t.NO_ERROR;);let r=!0,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);let s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);let n=t.checkFramebufferStatus(t.FRAMEBUFFER);if((r=(r=r&&n===t.FRAMEBUFFER_COMPLETE)&&t.getError()===t.NO_ERROR)&&(t.clear(t.COLOR_BUFFER_BIT),r=r&&t.getError()===t.NO_ERROR),r){t.bindFramebuffer(t.FRAMEBUFFER,null);let e=t.RGBA,i=t.UNSIGNED_BYTE,s=new Uint8Array(4);t.readPixels(0,0,1,1,e,i,s),r=r&&t.getError()===t.NO_ERROR}for(t.deleteTexture(i),t.deleteFramebuffer(s),t.bindFramebuffer(t.FRAMEBUFFER,null);!r&&t.getError()!==t.NO_ERROR;);return r}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT_OES;case 0:break;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case 3:return this._gl.BYTE;case 0:break;case 4:return this._gl.SHORT;case 5:return this._gl.UNSIGNED_SHORT;case 6:return this._gl.INT;case 7:return this._gl.UNSIGNED_INT;case 1:return this._gl.FLOAT;case 2:return this._gl.HALF_FLOAT;case 8:return this._gl.UNSIGNED_SHORT_4_4_4_4;case 9:return this._gl.UNSIGNED_SHORT_5_5_5_1;case 10:return this._gl.UNSIGNED_SHORT_5_6_5;case 11:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case 12:return this._gl.UNSIGNED_INT_24_8;case 13:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case 14:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case 15:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let r=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case 0:r=this._gl.ALPHA;break;case 1:r=this._gl.LUMINANCE;break;case 2:r=this._gl.LUMINANCE_ALPHA;break;case 6:r=this._gl.RED;break;case 7:r=this._gl.RG;break;case 4:r=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case 5:r=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case 8:r=this._gl.RED_INTEGER;break;case 9:r=this._gl.RG_INTEGER;break;case 10:r=this._gl.RGB_INTEGER;break;case 11:r=this._gl.RGBA_INTEGER}return r}_getRGBABufferInternalSizedFormat(e,t,r=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;case 4:return r?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case 3:switch(t){case 6:return this._gl.R8_SNORM;case 7:return this._gl.RG8_SNORM;case 4:return this._gl.RGB8_SNORM;case 8:return this._gl.R8I;case 9:return this._gl.RG8I;case 10:return this._gl.RGB8I;case 11:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case 0:switch(t){case 6:return this._gl.R8;case 7:return this._gl.RG8;case 4:return r?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case 5:return r?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case 8:return this._gl.R8UI;case 9:return this._gl.RG8UI;case 10:return this._gl.RGB8UI;case 11:return this._gl.RGBA8UI;case 0:return this._gl.ALPHA;case 1:return this._gl.LUMINANCE;case 2:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case 4:switch(t){case 8:return this._gl.R16I;case 9:return this._gl.RG16I;case 10:return this._gl.RGB16I;default:return this._gl.RGBA16I}case 5:switch(t){case 8:return this._gl.R16UI;case 9:return this._gl.RG16UI;case 10:return this._gl.RGB16UI;default:return this._gl.RGBA16UI}case 6:switch(t){case 8:return this._gl.R32I;case 9:return this._gl.RG32I;case 10:return this._gl.RGB32I;default:return this._gl.RGBA32I}case 7:switch(t){case 8:return this._gl.R32UI;case 9:return this._gl.RG32UI;case 10:return this._gl.RGB32UI;default:return this._gl.RGBA32UI}case 1:switch(t){case 6:return this._gl.R32F;case 7:return this._gl.RG32F;case 4:return this._gl.RGB32F;default:return this._gl.RGBA32F}case 2:switch(t){case 6:return this._gl.R16F;case 7:return this._gl.RG16F;case 4:return this._gl.RGB16F;default:return this._gl.RGBA16F}case 10:return this._gl.RGB565;case 13:return this._gl.R11F_G11F_B10F;case 14:return this._gl.RGB9_E5;case 8:return this._gl.RGBA4;case 9:return this._gl.RGB5_A1;case 11:switch(t){case 5:default:return this._gl.RGB10_A2;case 11:return this._gl.RGB10_A2UI}}return r?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}_getRGBAMultiSampleBufferFormat(e,t=5){switch(e){case 1:if(6===t)return this._gl.R32F;return this._gl.RGBA32F;case 2:if(6===t)return this._gl.R16F;return this._gl.RGBA16F}return this._gl.RGBA8}_loadFile(e,t,r,i,s,n){let a=ThinEngine._FileToolsLoadFile(e,t,r,i,s,n);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}static _FileToolsLoadFile(e,t,r,i,s,a){throw(0,n.S)("FileTools")}readPixels(e,t,r,i,s=!0,n=!0){let a=s?this._gl.RGBA:this._gl.RGB,l=new Uint8Array(i*r*(s?4:3));return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,r,i,a,this._gl.UNSIGNED_BYTE,l),Promise.resolve(l)}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{let e=this._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{let e=this._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}static CeilingPOT(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}static FloorPOT(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}static NearestPOT(e){let t=ThinEngine.CeilingPOT(e),r=ThinEngine.FloorPOT(e);return t-e>e-r?r:t}static GetExponentOfTwo(e,t,r=2){let i;switch(r){case 1:i=ThinEngine.FloorPOT(e);break;case 2:i=ThinEngine.NearestPOT(e);break;default:i=ThinEngine.CeilingPOT(e)}return Math.min(i,t)}static QueueNewFrame(e,t){if((0,d.CG)()){let{requestAnimationFrame:r}=t||window;if("function"==typeof r)return r(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:(0,d.n5)()?document:null}};ThinEngine._TempClearColorUint32=new Uint32Array(4),ThinEngine._TempClearColorInt32=new Int32Array(4),ThinEngine.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:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],ThinEngine._TextureLoaders=[],ThinEngine.CollisionsEpsilon=.001,ThinEngine._IsSupported=null,ThinEngine._HasMajorPerformanceCaveat=null}}]); \ No newline at end of file diff --git a/.next/static/chunks/e1206f8c-1ba69cf5e736c266.js b/.next/static/chunks/e1206f8c-1ba69cf5e736c266.js new file mode 100644 index 0000000..127773b --- /dev/null +++ b/.next/static/chunks/e1206f8c-1ba69cf5e736c266.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[732],{6540:function(e,t,s){s.d(t,{a:function(){return r},x:function(){return k}});var i,r,a=s(5132),n=s(7662),o=s(4800),h=s(8355),l=s(1186),d=s(1803),u=s(78),c=s(800),g=s(1974),m=s(9691),f=s(2248),_=s(9528),v=s(5184),p=s(2195),b=s(7609),M=s(7209),C=s(6030),y=s(6131),R=s(8668),O=s(7263),A=s(2983),P=s(2975),S=s(7531),T=s(1166),w=s(6972),B=s(4254),D=s(7077),I=s(9626);(i=r||(r={}))[i.BackwardCompatible=0]="BackwardCompatible",i[i.Intermediate=1]="Intermediate",i[i.Aggressive=2]="Aggressive";class k extends c.p{static DefaultMaterialFactory(e){throw(0,y.S)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,y.S)("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case r.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case r.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case r.Aggressive: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(16))}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(16))}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 R.$.DragMovementThreshold}static set DragMovementThreshold(e){R.$.DragMovementThreshold=e}static get LongPressDelay(){return R.$.LongPressDelay}static set LongPressDelay(e){R.$.LongPressDelay=e}static get DoubleClickDelay(){return R.$.DoubleClickDelay}static set DoubleClickDelay(e){R.$.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return R.$.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){R.$.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",s=!1){let i=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return u.jp.Vector4[0].set(i.x,i.y,i.z,r?-1:1),e&&(s?e.setFloat3(t,u.jp.Vector4[0].x,u.jp.Vector4[0].y,u.jp.Vector4[0].z):e.setVector4(t,u.jp.Vector4[0])),u.jp.Vector4[0]}finalizeSceneUbo(){let 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(16))}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(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}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(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=(0,B.M)(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=k.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=k.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e),e.addFromContainer&&e.serialize&&this._serializableComponents.push(e)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new R.$(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new A.HE(.2,.2,.3,1),this.ambientColor=new A.Wo(0,0,0),this.environmentIntensity=1,this._performancePriority=r.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new o.y$,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 o.y$,this._onDisposeObserver=null,this.onBeforeRenderObservable=new o.y$,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new o.y$,this.onAfterRenderCameraObservable=new o.y$,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new o.y$,this.onAfterAnimationsObservable=new o.y$,this.onBeforeDrawPhaseObservable=new o.y$,this.onAfterDrawPhaseObservable=new o.y$,this.onReadyObservable=new o.y$,this.onBeforeCameraRenderObservable=new o.y$,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new o.y$,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new o.y$,this.onAfterActiveMeshesEvaluationObservable=new o.y$,this.onBeforeParticlesRenderingObservable=new o.y$,this.onAfterParticlesRenderingObservable=new o.y$,this.onDataLoadedObservable=new o.y$,this.onNewCameraAddedObservable=new o.y$,this.onCameraRemovedObservable=new o.y$,this.onNewLightAddedObservable=new o.y$,this.onLightRemovedObservable=new o.y$,this.onNewGeometryAddedObservable=new o.y$,this.onGeometryRemovedObservable=new o.y$,this.onNewTransformNodeAddedObservable=new o.y$,this.onTransformNodeRemovedObservable=new o.y$,this.onNewMeshAddedObservable=new o.y$,this.onMeshRemovedObservable=new o.y$,this.onNewSkeletonAddedObservable=new o.y$,this.onSkeletonRemovedObservable=new o.y$,this.onNewMaterialAddedObservable=new o.y$,this.onNewMultiMaterialAddedObservable=new o.y$,this.onMaterialRemovedObservable=new o.y$,this.onMultiMaterialRemovedObservable=new o.y$,this.onNewTextureAddedObservable=new o.y$,this.onTextureRemovedObservable=new o.y$,this.onBeforeRenderTargetsRenderObservable=new o.y$,this.onAfterRenderTargetsRenderObservable=new o.y$,this.onBeforeStepObservable=new o.y$,this.onAfterStepObservable=new o.y$,this.onActiveCameraChanged=new o.y$,this.onActiveCamerasChanged=new o.y$,this.onBeforeRenderingGroupObservable=new o.y$,this.onAfterRenderingGroupObservable=new o.y$,this.onMeshImportedObservable=new o.y$,this.onAnimationFileImportedObservable=new o.y$,this._registeredForLateAnimationBindings=new h.f(256),this._pointerPickingConfiguration=new D.M,this.onPrePointerObservable=new o.y$,this.onPointerObservable=new o.y$,this.onPreKeyboardObservable=new o.y$,this.onKeyboardObservable=new o.y$,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=k.FOGMODE_NONE,this.fogColor=new A.Wo(.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.P(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new h.f(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new O.z,this._activeIndices=new O.z,this._activeParticles=new O.z,this._activeBones=new O.z,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=Array(256),this._activeRequests=[],this._pendingData=[],this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new h.t(256),this._processedMaterials=new h.t(256),this._renderTargets=new h.f(256),this._materialsRenderTargets=new h.f(256),this._activeParticleSystems=new h.t(256),this._activeSkeletons=new h.f(32),this._softwareSkinnedMeshes=new h.f(32),this._activeAnimatables=[],this._transformMatrix=u.y3.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=b.H.Create(),this._beforeClearStage=b.H.Create(),this._beforeRenderTargetClearStage=b.H.Create(),this._gatherRenderTargetsStage=b.H.Create(),this._gatherActiveCameraRenderTargetsStage=b.H.Create(),this._isReadyForMeshStage=b.H.Create(),this._beforeEvaluateActiveMeshStage=b.H.Create(),this._evaluateSubMeshStage=b.H.Create(),this._preActiveMeshStage=b.H.Create(),this._cameraDrawRenderTargetStage=b.H.Create(),this._beforeCameraDrawStage=b.H.Create(),this._beforeRenderTargetDrawStage=b.H.Create(),this._beforeRenderingGroupDrawStage=b.H.Create(),this._beforeRenderingMeshStage=b.H.Create(),this._afterRenderingMeshStage=b.H.Create(),this._afterRenderingGroupDrawStage=b.H.Create(),this._afterCameraDrawStage=b.H.Create(),this._afterCameraPostProcessStage=b.H.Create(),this._afterRenderTargetDrawStage=b.H.Create(),this._afterRenderTargetPostProcessStage=b.H.Create(),this._afterRenderStage=b.H.Create(),this._pointerMoveStage=b.H.Create(),this._pointerDownStage=b.H.Create(),this._pointerUpStage=b.H.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=[];let s=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);e=this._engine=e||C.l.LastCreatedEngine,s.virtual?e._virtualScenes.push(this):(C.l._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new p.$(this),v.O&&(this.postProcessManager=new v.O(this)),(0,M.CG)()&&this.attachControl(),this._createUbo(),g.$&&(this._imageProcessingConfiguration=new g.$),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){var t,s,i;let r;if(this._isDisposed)return!1;let a=this.getEngine(),n=a.currentRenderPassId;a.currentRenderPassId=null!==(s=null===(t=this.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==s?s:n;let o=!0;for(this._pendingData.length>0&&(o=!1),null===(i=this.prePassRenderer)||void 0===i||i.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&o&&(o=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),r=0;r0;for(let e of this._isReadyForMeshStage)e.action(t,s)||(o=!1);if(!e)continue;let i=t.material||this.defaultMaterial;if(i){if(i._storeEffectOnSubMeshes)for(let e of t.subMeshes){let t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else i.hasRenderTargetTextures&&null!=i.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(i)&&(this._processedMaterials.push(i),this._materialsRenderTargets.concatWithNoDuplicate(i.getRenderTargetTextures()))}}if(e)for(r=0;r0)for(let e of this.activeCameras)e.isReady(!0)||(o=!1);else this.activeCamera&&!this.activeCamera.isReady(!0)&&(o=!1);for(let e of this.particleSystems)e.isReady()||(o=!1);if(this.layers)for(let e of this.layers)e.isReady()||(o=!1);return a.areAllEffectsReady()||(o=!1),a.currentRenderPassId=n,o}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){let 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){let 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){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=n.F.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?P.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=P.i.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){let t=new m.M(this._engine,void 0,!1,null!=e?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 S.K.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){let s=this.meshes.indexOf(e);return -1===s||(this.meshes[s]=this.meshes[this.meshes.length-1],this.meshes.pop(),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){let t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){let 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){let t=this.skeletons.indexOf(e);return -1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return -1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(-1!==t){for(let 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){let t=this.cameras.indexOf(e);if(-1===t||(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let 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){let t=this.particleSystems.indexOf(e);return -1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){let t=this.animations.indexOf(e);return -1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,s){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return -1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return -1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(-1!==t&&tt.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=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){let t=this.getMeshById(e);if(t)return t;let s=this.getTransformNodeById(e);if(s)return s;let i=this.getLightById(e);if(i)return i;let r=this.getCameraById(e);return r?r:this.getBoneById(e)||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let s=this.getTransformNodeByName(e);if(s)return s;let i=this.getLightByName(e);if(i)return i;let r=this.getCameraByName(e);return r?r:this.getBoneByName(e)||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){s&&s("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,i)for(let e=0;ee.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode){this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let e=this._activeMeshes.length;for(let t=0;t0&&(s.layerMask&this.activeCamera.layerMask)!=0&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){for(let e of(this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),i!==s&&i._activate(this._renderId,!1),this._preActiveMeshStage))e.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(i=s):i._internalAbstractMeshDataInfo._onlyForInstances=!1,i._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,i)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){let i=this.getActiveSubMeshCandidates(t),r=i.length;s=s||1===r;for(let a=0;a0&&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),this._gatherActiveCameraRenderTargetsStage))s.action(this._renderTargets);let h=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){a.w1.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(let e of this._cameraDrawRenderTargetStage)h=e.action(this.activeCamera)||h;this._intermediateRendering=!1}for(let t of(this._engine.currentRenderPassId=null!==(n=null!==(r=null===(i=e.outputRenderTarget)||void 0===i?void 0:i.renderPassId)&&void 0!==r?r:e.renderPassId)&&void 0!==n?n:0,h&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame(),this._beforeCameraDrawStage))t.action(this.activeCamera);for(let e of(this.onBeforeDrawPhaseObservable.notifyObservers(this),o.snapshotRendering&&1===o.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this),this._afterCameraDrawStage))e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(let e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1)||(13===s.trigger&&s._executeCurrent(_.V.CreateNew(t,void 0,i)),t.actionManager.hasSpecificTrigger(13,e=>i===(e.mesh?e.mesh:e))&&13!==s.trigger||t._intersectionsInProgress.splice(a,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(k.MinDeltaTime,Math.min(this._engine.getDeltaTime(),k.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),s=1e3/t/1e3,i=0,r=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,r);e>0&&i0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}for(let e of(this._engine.currentRenderPassId=null!==(r=null==o?void 0:o.renderPassId)&&void 0!==r?r:0,this.activeCamera=o,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this._beforeClearStage))e.action();for(let e of(this._clearFrameBuffer(this.activeCamera),this._gatherRenderTargetsStage))e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}for(let e of(this._checkIntersections(),this._afterRenderStage))e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;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,this._activeRequests.slice()))e.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){I.Y.Error("An error occurred while calling onDisposeObservable!",e)}if(this.detachControl(),this._engine.getInputElement())for(let e=0;ee.dispose(!0)),this._disposeList(this.transformNodes,e=>e.dispose(!0));let e=this.cameras;this._disposeList(e),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 t=this._engine.scenes.indexOf(this);t>-1&&this._engine.scenes.splice(t,1),C.l._LastCreatedScene===this&&(this._engine.scenes.length>0?C.l._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:C.l._LastCreatedScene=null),(t=this._engine._virtualScenes.indexOf(this))>-1&&this._engine._virtualScenes.splice(t,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){let s=e.slice(0);for(let e of(t=null!=t?t:e=>e.dispose(),s))t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;let i=e.getBoundingInfo(),r=i.boundingBox.minimumWorld,a=i.boundingBox.maximumWorld;u.P.CheckExtends(r,t,s),u.P.CheckExtends(a,t,s)}),{min:t,max:s}}createPickingRay(e,t,s,i,r=!1){throw(0,y.S)("Ray")}createPickingRayToRef(e,t,s,i,r,a=!1,n=!1){throw(0,y.S)("Ray")}createPickingRayInCameraSpace(e,t,s){throw(0,y.S)("Ray")}createPickingRayInCameraSpaceToRef(e,t,s,i){throw(0,y.S)("Ray")}get _pickingAvailable(){return!1}pick(e,t,s,i,r,a){let n=(0,y.S)("Ray",!0);return n&&I.Y.Warn(n),new f.p}pickWithBoundingInfo(e,t,s,i,r){let a=(0,y.S)("Ray",!0);return a&&I.Y.Warn(a),new f.p}pickWithRay(e,t,s,i){throw(0,y.S)("Ray")}multiPick(e,t,s,i,r){throw(0,y.S)("Ray")}multiPickWithRay(e,t,s){throw(0,y.S)("Ray")}setPointerOverMesh(e,t,s){this._inputManager.setPointerOverMesh(e,t,s)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of(this.postProcessManager&&this.postProcessManager._rebuild(),this._components))e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,s){if(void 0===t)return e;let i=[];for(let r in e){let a=e[r];d.$&&d.$.MatchesQuery(a,t)&&(!s||s(a))&&i.push(a)}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(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let s of this.materials)(!t||t(s))&&s.markAsDirty(e)}_loadFile(e,t,s,i,r,a,n){let o=(0,T.vP)(e,t,s,i?this.offlineProvider:void 0,r,a,n);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((a,n)=>{this._loadFile(e,e=>{a(e)},t,s,i,(e,t)=>{n(t)},r)})}_requestFile(e,t,s,i,r,a,n){let o=(0,T.FV)(e,t,s,i?this.offlineProvider:void 0,r,a,n);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((a,n)=>{this._requestFile(e,e=>{a(e)},t,s,i,e=>{n(e)},r)})}_readFile(e,t,s,i,r){let a=(0,T.Ip)(e,t,s,i,r);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}_readFileAsync(e,t,s){return new Promise((i,r)=>{this._readFile(e,e=>{i(e)},t,s,e=>{r(e)})})}getPerfCollector(){throw(0,y.S)("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)}}k.FOGMODE_NONE=0,k.FOGMODE_EXP=1,k.FOGMODE_EXP2=2,k.FOGMODE_LINEAR=3,k.MinDeltaTime=1,k.MaxDeltaTime=1e3}}]); \ No newline at end of file diff --git a/.next/static/chunks/e1206f8c-ab5b5541f866e530.js b/.next/static/chunks/e1206f8c-ab5b5541f866e530.js deleted file mode 100644 index ebacd7b..0000000 --- a/.next/static/chunks/e1206f8c-ab5b5541f866e530.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[732],{6540:function(e,t,s){s.d(t,{a:function(){return r},x:function(){return Scene}});var i,r,a=s(5132),n=s(7662),o=s(4800),h=s(8355),l=s(1186),d=s(1803),c=s(78),u=s(800),g=s(1974),m=s(9691),f=s(2248),_=s(9528),v=s(5184),b=s(2195),p=s(7609),M=s(7209),C=s(6030),y=s(6131),R=s(8668),O=s(7263),S=s(2983),A=s(2975),P=s(7531),w=s(1166),T=s(6972),B=s(4254),D=s(7077),k=s(9626);(i=r||(r={}))[i.BackwardCompatible=0]="BackwardCompatible",i[i.Intermediate=1]="Intermediate",i[i.Aggressive=2]="Aggressive";let Scene=class Scene extends u.p{static DefaultMaterialFactory(e){throw(0,y.S)("StandardMaterial")}static CollisionCoordinatorFactory(){throw(0,y.S)("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(1))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case r.BackwardCompatible:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case r.Intermediate:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case r.Aggressive: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(16))}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(16))}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 R.$.DragMovementThreshold}static set DragMovementThreshold(e){R.$.DragMovementThreshold=e}static get LongPressDelay(){return R.$.LongPressDelay}static set LongPressDelay(e){R.$.LongPressDelay=e}static get DoubleClickDelay(){return R.$.DoubleClickDelay}static set DoubleClickDelay(e){R.$.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return R.$.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){R.$.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",s=!1){let i=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return c.jp.Vector4[0].set(i.x,i.y,i.z,r?-1:1),e&&(s?e.setFloat3(t,c.jp.Vector4[0].x,c.jp.Vector4[0].y,c.jp.Vector4[0].z):e.setVector4(t,c.jp.Vector4[0])),c.jp.Vector4[0]}finalizeSceneUbo(){let 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(16))}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(16))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(16))}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(2))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(2))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=(0,B.M)(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=Scene.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(1))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(8))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=Scene.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(let e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e),e.addFromContainer&&e.serialize&&this._serializableComponents.push(e)}_getComponent(e){for(let t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new R.$(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new S.HE(.2,.2,.3,1),this.ambientColor=new S.Wo(0,0,0),this.environmentIntensity=1,this._performancePriority=r.BackwardCompatible,this.onScenePerformancePriorityChangedObservable=new o.y$,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 o.y$,this._onDisposeObserver=null,this.onBeforeRenderObservable=new o.y$,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new o.y$,this.onAfterRenderCameraObservable=new o.y$,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new o.y$,this.onAfterAnimationsObservable=new o.y$,this.onBeforeDrawPhaseObservable=new o.y$,this.onAfterDrawPhaseObservable=new o.y$,this.onReadyObservable=new o.y$,this.onBeforeCameraRenderObservable=new o.y$,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new o.y$,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new o.y$,this.onAfterActiveMeshesEvaluationObservable=new o.y$,this.onBeforeParticlesRenderingObservable=new o.y$,this.onAfterParticlesRenderingObservable=new o.y$,this.onDataLoadedObservable=new o.y$,this.onNewCameraAddedObservable=new o.y$,this.onCameraRemovedObservable=new o.y$,this.onNewLightAddedObservable=new o.y$,this.onLightRemovedObservable=new o.y$,this.onNewGeometryAddedObservable=new o.y$,this.onGeometryRemovedObservable=new o.y$,this.onNewTransformNodeAddedObservable=new o.y$,this.onTransformNodeRemovedObservable=new o.y$,this.onNewMeshAddedObservable=new o.y$,this.onMeshRemovedObservable=new o.y$,this.onNewSkeletonAddedObservable=new o.y$,this.onSkeletonRemovedObservable=new o.y$,this.onNewMaterialAddedObservable=new o.y$,this.onNewMultiMaterialAddedObservable=new o.y$,this.onMaterialRemovedObservable=new o.y$,this.onMultiMaterialRemovedObservable=new o.y$,this.onNewTextureAddedObservable=new o.y$,this.onTextureRemovedObservable=new o.y$,this.onBeforeRenderTargetsRenderObservable=new o.y$,this.onAfterRenderTargetsRenderObservable=new o.y$,this.onBeforeStepObservable=new o.y$,this.onAfterStepObservable=new o.y$,this.onActiveCameraChanged=new o.y$,this.onActiveCamerasChanged=new o.y$,this.onBeforeRenderingGroupObservable=new o.y$,this.onAfterRenderingGroupObservable=new o.y$,this.onMeshImportedObservable=new o.y$,this.onAnimationFileImportedObservable=new o.y$,this._registeredForLateAnimationBindings=new h.f(256),this._pointerPickingConfiguration=new D.M,this.onPrePointerObservable=new o.y$,this.onPointerObservable=new o.y$,this.onPreKeyboardObservable=new o.y$,this.onKeyboardObservable=new o.y$,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=Scene.FOGMODE_NONE,this.fogColor=new S.Wo(.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 c.P(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new h.f(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new O.z,this._activeIndices=new O.z,this._activeParticles=new O.z,this._activeBones=new O.z,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=Array(256),this._activeRequests=[],this._pendingData=[],this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new h.t(256),this._processedMaterials=new h.t(256),this._renderTargets=new h.f(256),this._materialsRenderTargets=new h.f(256),this._activeParticleSystems=new h.t(256),this._activeSkeletons=new h.f(32),this._softwareSkinnedMeshes=new h.f(32),this._activeAnimatables=[],this._transformMatrix=c.y3.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=p.H.Create(),this._beforeClearStage=p.H.Create(),this._beforeRenderTargetClearStage=p.H.Create(),this._gatherRenderTargetsStage=p.H.Create(),this._gatherActiveCameraRenderTargetsStage=p.H.Create(),this._isReadyForMeshStage=p.H.Create(),this._beforeEvaluateActiveMeshStage=p.H.Create(),this._evaluateSubMeshStage=p.H.Create(),this._preActiveMeshStage=p.H.Create(),this._cameraDrawRenderTargetStage=p.H.Create(),this._beforeCameraDrawStage=p.H.Create(),this._beforeRenderTargetDrawStage=p.H.Create(),this._beforeRenderingGroupDrawStage=p.H.Create(),this._beforeRenderingMeshStage=p.H.Create(),this._afterRenderingMeshStage=p.H.Create(),this._afterRenderingGroupDrawStage=p.H.Create(),this._afterCameraDrawStage=p.H.Create(),this._afterCameraPostProcessStage=p.H.Create(),this._afterRenderTargetDrawStage=p.H.Create(),this._afterRenderTargetPostProcessStage=p.H.Create(),this._afterRenderStage=p.H.Create(),this._pointerMoveStage=p.H.Create(),this._pointerDownStage=p.H.Create(),this._pointerUpStage=p.H.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=[];let s=Object.assign({useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1},t);e=this._engine=e||C.l.LastCreatedEngine,s.virtual?e._virtualScenes.push(this):(C.l._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new b.$(this),v.O&&(this.postProcessManager=new v.O(this)),(0,M.CG)()&&this.attachControl(),this._createUbo(),g.$&&(this._imageProcessingConfiguration=new g.$),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){var t,s,i;let r;if(this._isDisposed)return!1;let a=this.getEngine(),n=a.currentRenderPassId;a.currentRenderPassId=null!==(s=null===(t=this.activeCamera)||void 0===t?void 0:t.renderPassId)&&void 0!==s?s:n;let o=!0;for(this._pendingData.length>0&&(o=!1),null===(i=this.prePassRenderer)||void 0===i||i.update(),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),r=0;r0;for(let e of this._isReadyForMeshStage)e.action(t,s)||(o=!1);if(!e)continue;let i=t.material||this.defaultMaterial;if(i){if(i._storeEffectOnSubMeshes)for(let e of t.subMeshes){let t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else i.hasRenderTargetTextures&&null!=i.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(i)&&(this._processedMaterials.push(i),this._materialsRenderTargets.concatWithNoDuplicate(i.getRenderTargetTextures()))}}if(e)for(r=0;r0)for(let e of this.activeCameras)e.isReady(!0)||(o=!1);else this.activeCamera&&!this.activeCamera.isReady(!0)&&(o=!1);for(let e of this.particleSystems)e.isReady()||(o=!1);if(this.layers)for(let e of this.layers)e.isReady()||(o=!1);return a.areAllEffectsReady()||(o=!1),a.currentRenderPassId=n,o}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){let execFunc=()=>{e(),setTimeout(()=>{this.unregisterBeforeRender(execFunc)})};this.registerBeforeRender(execFunc)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout(()=>{this._executeOnceBeforeRender(e)},t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){let 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){if(this._registerTransientComponents(),this.isReady(e)){this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}if(this._isDisposed){this.onReadyObservable.clear(),this._executeWhenReadyTimeoutId=null;return}this._executeWhenReadyTimeoutId=setTimeout(()=>{this.incrementRenderId(),this._checkIsReady(e)},100)}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=n.F.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?A.i.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=A.i.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){let t=new m.M(this._engine,void 0,!1,null!=e?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 P.K.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){let s=this.meshes.indexOf(e);return -1===s||(this.meshes[s]=this.meshes[this.meshes.length-1],this.meshes.pop(),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){let t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){let 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){let t=this.skeletons.indexOf(e);return -1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){let t=this.morphTargetManagers.indexOf(e);return -1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){let t=this.lights.indexOf(e);if(-1!==t){for(let 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){let t=this.cameras.indexOf(e);if(-1===t||(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){let 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){let t=this.particleSystems.indexOf(e);return -1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){let t=this.animations.indexOf(e);return -1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,s){}removeAnimationGroup(e){let t=this.animationGroups.indexOf(e);return -1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){let t=this.multiMaterials.indexOf(e);return -1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){let t=e._indexInSceneMaterialArray;if(-1!==t&&tt.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=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){let t=this.getMeshById(e);if(t)return t;let s=this.getTransformNodeById(e);if(s)return s;let i=this.getLightById(e);if(i)return i;let r=this.getCameraById(e);if(r)return r;let a=this.getBoneById(e);return a||null}getNodeByName(e){let t=this.getMeshByName(e);if(t)return t;let s=this.getTransformNodeByName(e);if(s)return s;let i=this.getLightByName(e);if(i)return i;let r=this.getCameraByName(e);if(r)return r;let a=this.getBoneByName(e);return a||null}getMeshByName(e){for(let t=0;t=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t{if(!this.activeCamera){s&&s("No active camera found");return}if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,i)for(let e=0;ee.dispose())}_evaluateActiveMeshes(){var e;if(this._engine.snapshotRendering&&1===this._engine.snapshotRenderingMode){this._activeMeshes.length>0&&(null===(e=this.activeCamera)||void 0===e||e._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset());return}if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){let e=this._activeMeshes.length;for(let t=0;t0&&(s.layerMask&this.activeCamera.layerMask)!=0&&(this._skipFrustumClipping||s.alwaysSelectAsActiveMesh||s.isInFrustum(this._frustumPlanes)))){for(let e of(this._activeMeshes.push(s),this.activeCamera._activeMeshes.push(s),i!==s&&i._activate(this._renderId,!1),this._preActiveMeshStage))e.action(s);s._activate(this._renderId,!1)&&(s.isAnInstance?s._internalAbstractMeshDataInfo._actAsRegularMesh&&(i=s):i._internalAbstractMeshDataInfo._onlyForInstances=!1,i._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(s,i)),s._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e0){let i=this.getActiveSubMeshCandidates(t),r=i.length;s=s||1===r;for(let a=0;a0&&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),this._gatherActiveCameraRenderTargetsStage))s.action(this._renderTargets);let h=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){a.w1.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e0),this._renderId++}for(let e of this._cameraDrawRenderTargetStage)h=e.action(this.activeCamera)||h;this._intermediateRendering=!1}for(let t of(this._engine.currentRenderPassId=null!==(n=null!==(r=null===(i=e.outputRenderTarget)||void 0===i?void 0:i.renderPassId)&&void 0!==r?r:e.renderPassId)&&void 0!==n?n:0,h&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame(),this._beforeCameraDrawStage))t.action(this.activeCamera);for(let e of(this.onBeforeDrawPhaseObservable.notifyObservers(this),o.snapshotRendering&&1===o.snapshotRenderingMode&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this),this._afterCameraDrawStage))e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){let t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(let e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(0===e.cameraRigMode||e._renderingMultiview){e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),this.onAfterRenderCameraObservable.notifyObservers(e);return}if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t-1)||(13===s.trigger&&s._executeCurrent(_.V.CreateNew(t,void 0,i)),t.actionManager.hasSpecificTrigger(13,e=>{let t=e.mesh?e.mesh:e;return i===t})&&13!==s.trigger||t._intersectionsInProgress.splice(a,1))}}}}_advancePhysicsEngineStep(e){}_animate(){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(Scene.MinDeltaTime,Math.min(this._engine.getDeltaTime(),Scene.MaxDeltaTime))+this._timeAccumulator,t=this._engine.getTimeStep(),s=1e3/t/1e3,i=0,r=this._engine.getLockstepMaxSteps(),a=Math.floor(e/t);for(a=Math.min(a,r);e>0&&i0)for(let e=0;e0),this._intermediateRendering=!0;for(let e=0;e0),this._intermediateRendering=!1,this._renderId++}for(let e of(this._engine.currentRenderPassId=null!==(r=null==o?void 0:o.renderPassId)&&void 0!==r?r:0,this.activeCamera=o,this._activeCamera&&22!==this._activeCamera.cameraRigMode&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),this._beforeClearStage))e.action();for(let e of(this._clearFrameBuffer(this.activeCamera),this._gatherRenderTargetsStage))e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e0);else{if(!this.activeCamera)throw Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}for(let e of(this._checkIntersections(),this._afterRenderStage))e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;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;let e=this._activeRequests.slice();for(let t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){console.error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();let t=this._engine.getInputElement();if(t)for(let e=0;ee.dispose(!0)),this._disposeList(this.transformNodes,e=>e.dispose(!0));let s=this.cameras;this._disposeList(s),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 i=this._engine.scenes.indexOf(this);i>-1&&this._engine.scenes.splice(i,1),C.l._LastCreatedScene===this&&(this._engine.scenes.length>0?C.l._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:C.l._LastCreatedScene=null),(i=this._engine._virtualScenes.indexOf(this))>-1&&this._engine._virtualScenes.splice(i,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){let s=e.slice(0);for(let e of(t=null!=t?t:e=>e.dispose(),s))t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e!0),this.meshes.filter(e).forEach(e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;let i=e.getBoundingInfo(),r=i.boundingBox.minimumWorld,a=i.boundingBox.maximumWorld;c.P.CheckExtends(r,t,s),c.P.CheckExtends(a,t,s)}),{min:t,max:s}}createPickingRay(e,t,s,i,r=!1){throw(0,y.S)("Ray")}createPickingRayToRef(e,t,s,i,r,a=!1,n=!1){throw(0,y.S)("Ray")}createPickingRayInCameraSpace(e,t,s){throw(0,y.S)("Ray")}createPickingRayInCameraSpaceToRef(e,t,s,i){throw(0,y.S)("Ray")}get _pickingAvailable(){return!1}pick(e,t,s,i,r,a){let n=(0,y.S)("Ray",!0);return n&&k.Y.Warn(n),new f.p}pickWithBoundingInfo(e,t,s,i,r){let a=(0,y.S)("Ray",!0);return a&&k.Y.Warn(a),new f.p}pickWithRay(e,t,s,i){throw(0,y.S)("Ray")}multiPick(e,t,s,i,r){throw(0,y.S)("Ray")}multiPickWithRay(e,t,s){throw(0,y.S)("Ray")}setPointerOverMesh(e,t,s){this._inputManager.setPointerOverMesh(e,t,s)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(let e of this.geometries)e._rebuild();for(let e of this.meshes)e._rebuild();for(let e of(this.postProcessManager&&this.postProcessManager._rebuild(),this._components))e.rebuild();for(let e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(let e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(let e of this.textures)e._rebuild();this.markAllMaterialsAsDirty(1)}_getByTags(e,t,s){if(void 0===t)return e;let i=[];for(let r in e){let a=e[r];d.$&&d.$.MatchesQuery(a,t)&&(!s||s(a))&&i.push(a)}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(63))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(let s of this.materials)(!t||t(s))&&s.markAsDirty(e)}_loadFile(e,t,s,i,r,a,n){let o=(0,w.vP)(e,t,s,i?this.offlineProvider:void 0,r,a,n);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((a,n)=>{this._loadFile(e,e=>{a(e)},t,s,i,(e,t)=>{n(t)},r)})}_requestFile(e,t,s,i,r,a,n){let o=(0,w.FV)(e,t,s,i?this.offlineProvider:void 0,r,a,n);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((a,n)=>{this._requestFile(e,e=>{a(e)},t,s,i,e=>{n(e)},r)})}_readFile(e,t,s,i,r){let a=(0,w.Ip)(e,t,s,i,r);return this._activeRequests.push(a),a.onCompleteObservable.add(e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)}),a}_readFileAsync(e,t,s){return new Promise((i,r)=>{this._readFile(e,e=>{i(e)},t,s,e=>{r(e)})})}getPerfCollector(){throw(0,y.S)("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)}};Scene.FOGMODE_NONE=0,Scene.FOGMODE_EXP=1,Scene.FOGMODE_EXP2=2,Scene.FOGMODE_LINEAR=3,Scene.MinDeltaTime=1,Scene.MaxDeltaTime=1e3}}]); \ No newline at end of file diff --git a/.next/static/chunks/fd9d1056-519edff8920177a7.js b/.next/static/chunks/fd9d1056-519edff8920177a7.js new file mode 100644 index 0000000..8f9f1d9 --- /dev/null +++ b/.next/static/chunks/fd9d1056-519edff8920177a7.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[971],{4417:function(e,t,n){var r,l=n(2265),a=n(8261),o={usingClientEntryPoint:!1,Events:null,Dispatcher:{current:null}};function i(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;np||(e.current=d[p],d[p]=null,p--)}function g(e,t){d[++p]=e.current,e.current=t}var y=Symbol.for("react.element"),v=Symbol.for("react.portal"),b=Symbol.for("react.fragment"),k=Symbol.for("react.strict_mode"),w=Symbol.for("react.profiler"),S=Symbol.for("react.provider"),C=Symbol.for("react.context"),E=Symbol.for("react.server_context"),x=Symbol.for("react.forward_ref"),z=Symbol.for("react.suspense"),P=Symbol.for("react.suspense_list"),N=Symbol.for("react.memo"),_=Symbol.for("react.lazy"),L=Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var T=Symbol.for("react.offscreen"),F=Symbol.for("react.legacy_hidden"),M=Symbol.for("react.cache");Symbol.for("react.tracing_marker");var O=Symbol.iterator;function R(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=O&&e[O]||e["@@iterator"])?e:null}var D=m(null),A=m(null),I=m(null),U=m(null),$={$$typeof:C,_currentValue:null,_currentValue2:null,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};function B(e,t){switch(g(I,t),g(A,e),g(D,null),e=t.nodeType){case 9:case 11:t=(t=t.documentElement)&&(t=t.namespaceURI)?sj(t):0;break;default:if(t=(e=8===e?t.parentNode:t).tagName,e=e.namespaceURI)t=sQ(e=sj(e),t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}h(D),g(D,t)}function V(){h(D),h(A),h(I)}function j(e){null!==e.memoizedState&&g(U,e);var t=D.current,n=sQ(t,e.type);t!==n&&(g(A,e),g(D,n))}function Q(e){A.current===e&&(h(D),h(A)),U.current===e&&(h(U),$._currentValue=null)}var W=a.unstable_scheduleCallback,H=a.unstable_cancelCallback,q=a.unstable_shouldYield,K=a.unstable_requestPaint,Y=a.unstable_now,X=a.unstable_getCurrentPriorityLevel,G=a.unstable_ImmediatePriority,Z=a.unstable_UserBlockingPriority,J=a.unstable_NormalPriority,ee=a.unstable_LowPriority,et=a.unstable_IdlePriority,en=null,er=null,el=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(ea(e)/eo|0)|0},ea=Math.log,eo=Math.LN2,ei=128,eu=4194304;function es(e){var t=42&e;if(0!==t)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194176&e;case 4194304:case 8388608:case 16777216:case 33554432:return 62914560&e;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function ec(e,t){var n=e.pendingLanes;if(0===n)return 0;var r=0,l=e.suspendedLanes;e=e.pingedLanes;var a=134217727&n;return 0!==a?0!=(n=a&~l)?r=es(n):0!=(e&=a)&&(r=es(e)):0!=(n&=~l)?r=es(n):0!==e&&(r=es(e)),0===r?0:0!==t&&t!==r&&0==(t&l)&&((l=r&-r)>=(e=t&-t)||32===l&&0!=(4194176&e))?t:r}function ef(e,t){return e.errorRecoveryDisabledLanes&t?0:0!=(e=-536870913&e.pendingLanes)?e:536870912&e?536870912:0}function ed(){var e=eu;return 0==(62914560&(eu<<=1))&&(eu=4194304),e}function ep(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function em(e,t){e.pendingLanes|=t,268435456!==t&&(e.suspendedLanes=0,e.pingedLanes=0)}function eh(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-el(t);e.entangledLanes|=t,e.entanglements[r]=1073741824|e.entanglements[r]|4194218&n}function eg(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-el(n),l=1<l||u[r]!==s[l]){var c="\n"+u[r].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}while(1<=r&&0<=l);break}}}finally{eK=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?eq(n):""}function eX(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":case"object":return e;default:return""}}function eG(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function eZ(e){e._valueTracker||(e._valueTracker=function(e){var t=eG(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&void 0!==n&&"function"==typeof n.get&&"function"==typeof n.set){var l=n.get,a=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return l.call(this)},set:function(e){r=""+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function eJ(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=eG(e)?e.checked?"true":"false":e.value),(e=r)!==n&&(t.setValue(e),!0)}function e0(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}var e1=/[\n"\\]/g;function e2(e){return e.replace(e1,function(e){return"\\"+e.charCodeAt(0).toString(16)+" "})}function e3(e,t,n,r,l,a,o,i){e.name="",null!=o&&"function"!=typeof o&&"symbol"!=typeof o&&"boolean"!=typeof o?e.type=o:e.removeAttribute("type"),null!=t?"number"===o?(0===t&&""===e.value||e.value!=t)&&(e.value=""+eX(t)):e.value!==""+eX(t)&&(e.value=""+eX(t)):"submit"!==o&&"reset"!==o||e.removeAttribute("value"),null!=t?e6(e,o,eX(t)):null!=n?e6(e,o,eX(n)):null!=r&&e.removeAttribute("value"),null==l&&null!=a&&(e.defaultChecked=!!a),null!=l&&(e.checked=l&&"function"!=typeof l&&"symbol"!=typeof l),null!=i&&"function"!=typeof i&&"symbol"!=typeof i&&"boolean"!=typeof i?e.name=""+eX(i):e.removeAttribute("name")}function e4(e,t,n,r,l,a,o,i){if(null!=a&&"function"!=typeof a&&"symbol"!=typeof a&&"boolean"!=typeof a&&(e.type=a),null!=t||null!=n){if(!("submit"!==a&&"reset"!==a||null!=t))return;n=null!=n?""+eX(n):"",t=null!=t?""+eX(t):n,i||t===e.value||(e.value=t),e.defaultValue=t}r="function"!=typeof(r=null!=r?r:l)&&"symbol"!=typeof r&&!!r,e.checked=i?e.checked:!!r,e.defaultChecked=!!r,null!=o&&"function"!=typeof o&&"symbol"!=typeof o&&"boolean"!=typeof o&&(e.name=o)}function e6(e,t,n){"number"===t&&e0(e.ownerDocument)===e||e.defaultValue===""+n||(e.defaultValue=""+n)}var e8=Array.isArray;function e5(e,t,n,r){if(e=e.options,t){t={};for(var l=0;l"+t.valueOf().toString()+"",t=iA.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}}var tt=te;"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(tt=function(e,t){return MSApp.execUnsafeLocalFunction(function(){return te(e,t)})});var tn=tt;function tr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType){n.nodeValue=t;return}}e.textContent=t}var tl=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function ta(e,t,n){var r=0===t.indexOf("--");null==n||"boolean"==typeof n||""===n?r?e.setProperty(t,""):"float"===t?e.cssFloat="":e[t]="":r?e.setProperty(t,n):"number"!=typeof n||0===n||tl.has(t)?"float"===t?e.cssFloat=n:e[t]=(""+n).trim():e[t]=n+"px"}function to(e,t,n){if(null!=t&&"object"!=typeof t)throw Error(i(62));if(e=e.style,null!=n){for(var r in n)!n.hasOwnProperty(r)||null!=t&&t.hasOwnProperty(r)||(0===r.indexOf("--")?e.setProperty(r,""):"float"===r?e.cssFloat="":e[r]="");for(var l in t)r=t[l],t.hasOwnProperty(l)&&n[l]!==r&&ta(e,l,r)}else for(var a in t)t.hasOwnProperty(a)&&ta(e,a,t[a])}function ti(e){if(-1===e.indexOf("-"))return!1;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var tu=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),ts=null;function tc(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}var tf=null,td=null;function tp(e){var t=eT(e);if(t&&(e=t.stateNode)){var n=eM(e);switch(e=t.stateNode,t.type){case"input":if(e3(e,n.value,n.defaultValue,n.defaultValue,n.checked,n.defaultChecked,n.type,n.name),t=n.name,"radio"===n.type&&null!=t){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll('input[name="'+e2(""+t)+'"][type="radio"]'),t=0;t>=o,l-=o,tU=1<<32-el(t)+l|n<h?(g=f,f=null):g=f.sibling;var y=p(l,f,i[h],u);if(null===y){null===f&&(f=g);break}e&&f&&null===y.alternate&&t(l,f),o=a(y,o,h),null===c?s=y:c.sibling=y,c=y,f=g}if(h===i.length)return n(l,f),tq&&tB(l,h),s;if(null===f){for(;hg?(y=h,h=null):y=h.sibling;var b=p(l,h,v.value,s);if(null===b){null===h&&(h=y);break}e&&h&&null===b.alternate&&t(l,h),o=a(b,o,g),null===f?c=b:f.sibling=b,f=b,h=y}if(v.done)return n(l,h),tq&&tB(l,g),c;if(null===h){for(;!v.done;g++,v=u.next())null!==(v=d(l,v.value,s))&&(o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return tq&&tB(l,g),c}for(h=r(l,h);!v.done;g++,v=u.next())null!==(v=m(h,l,g,v.value,s))&&(e&&null!==v.alternate&&h.delete(null===v.key?g:v.key),o=a(v,o,g),null===f?c=v:f.sibling=v,f=v);return e&&h.forEach(function(e){return t(l,e)}),tq&&tB(l,g),c}(c,f,h,g);if("function"==typeof h.then)return s(c,f,nN(h),g);if(h.$$typeof===C||h.$$typeof===E)return s(c,f,ae(c,h,g),g);nL(c,h)}return"string"==typeof h&&""!==h||"number"==typeof h?(h=""+h,null!==f&&6===f.tag?(n(c,f.sibling),(f=l(f,h)).return=c):(n(c,f),(f=ig(h,c.mode,g)).return=c),o(c=f)):n(c,f)}(s,c,f,h),nz=null,s}}var nM=nF(!0),nO=nF(!1),nR=m(null),nD=m(0);function nA(e,t){g(nD,e=oy),g(nR,t),oy=e|t.baseLanes}function nI(){g(nD,oy),g(nR,nR.current)}function nU(){oy=nD.current,h(nR),h(nD)}var n$=m(null),nB=null;function nV(e){var t=e.alternate;g(nH,1&nH.current),g(n$,e),null===nB&&(null===t||null!==nR.current?nB=e:null!==t.memoizedState&&(nB=e))}function nj(e){if(22===e.tag){if(g(nH,nH.current),g(n$,e),null===nB){var t=e.alternate;null!==t&&null!==t.memoizedState&&(nB=e)}}else nQ(e)}function nQ(){g(nH,nH.current),g(n$,n$.current)}function nW(e){h(n$),nB===e&&(nB=null),h(nH)}var nH=m(0);function nq(e){for(var t=e;null!==t;){if(13===t.tag){var n=t.memoizedState;if(null!==n&&(null===(n=n.dehydrated)||"$?"===n.data||"$!"===n.data))return t}else if(19===t.tag&&void 0!==t.memoizedProps.revealOrder){if(0!=(128&t.flags))return t}else if(null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var nK=null,nY=null,nX=!1,nG=!1,nZ=!1,nJ=0;function n0(e){e!==nY&&null===e.next&&(null===nY?nK=nY=e:nY=nY.next=e),nG=!0,nX||(nX=!0,n6(n3))}function n1(e){if(!nZ&&nG){var t=null;nZ=!0;do for(var n=!1,r=nK;null!==r;){if(!e||0===r.tag){var l=op,a=ec(r,r===of?l:0);if(0!=(3&a))try{if(n=!0,l=r,0!=(6&oc))throw Error(i(327));if(!o7()){var o=o1(l,a);if(0!==l.tag&&2===o){var u=a,s=ef(l,u);0!==s&&(a=s,o=oV(l,u,s))}if(1===o)throw u=ob,oY(l,0),oW(l,a,0),n0(l),u;6===o?oW(l,a,0):(l.finishedWork=l.current.alternate,l.finishedLanes=a,o8(l,ox,oN,oC))}n0(l)}catch(e){null===t?t=[e]:t.push(e)}}r=r.next}while(n);if(nZ=!1,null!==t){if(1a?a:8;var o=ra.transition;ra.transition={},lo(e,!1,t,n);try{var i=l();if(null!==i&&"object"==typeof i&&"function"==typeof i.then){var u=re(i,r);la(e,t,u)}else{var s=rt(i,r);la(e,t,s)}}catch(n){la(e,t,{then:function(){},status:"rejected",reason:n})}finally{ey=a,ra.transition=o}}function r9(e,t,n,r){if(5!==e.tag)throw Error(i(476));if(null===e.memoizedState){var l={pending:null,lanes:0,dispatch:null,lastRenderedReducer:rL,lastRenderedState:f},a=l;l={memoizedState:f,baseState:f,baseQueue:null,queue:l,next:null},e.memoizedState=l;var o=e.alternate;null!==o&&(o.memoizedState=l)}else a=e.memoizedState.queue;r7(e,a,t,f,function(){return n(r)})}function le(){var e=l9($);return null!==e?e:f}function lt(){return rP().memoizedState}function ln(){return rP().memoizedState}function lr(e){for(var t=e.return;null!==t;){switch(t.tag){case 24:case 3:var n=oU(t),r=nf(t,e=nc(n),n);null!==r&&(o$(r,t,n),nd(r,t,n)),t={cache:ao()},e.payload=t;return}t=t.return}}function ll(e,t,n){var r=oU(e);n={lane:r,revertLane:0,action:n,hasEagerState:!1,eagerState:null,next:null},li(e)?lu(t,n):null!==(n=nr(e,t,n,r))&&(o$(n,e,r),ls(n,t,r))}function la(e,t,n){var r=oU(e),l={lane:r,revertLane:0,action:n,hasEagerState:!1,eagerState:null,next:null};if(li(e))lu(t,l);else{var a=e.alternate;if(0===e.lanes&&(null===a||0===a.lanes)&&null!==(a=t.lastRenderedReducer))try{var o=t.lastRenderedState,i=a(o,n);if(l.hasEagerState=!0,l.eagerState=i,tT(i,o)){nn(e,t,l,0),null===of&&nt();return}}catch(e){}finally{}null!==(n=nr(e,t,l,r))&&(o$(n,e,r),ls(n,t,r))}}function lo(e,t,n,r){if(r={lane:2,revertLane:n8(),action:r,hasEagerState:!1,eagerState:null,next:null},li(e)){if(t)throw Error(i(479))}else null!==(t=nr(e,n,r,2))&&o$(t,e,2)}function li(e){var t=e.alternate;return e===ri||null!==t&&t===ri}function lu(e,t){rf=rc=!0;var n=e.pending;null===n?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function ls(e,t,n){if(0!=(4194176&n)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,eg(e,n)}}iI=function(){return{lastEffect:null,events:null,stores:null}};var lc={readContext:l9,use:r_,useCallback:ry,useContext:ry,useEffect:ry,useImperativeHandle:ry,useInsertionEffect:ry,useLayoutEffect:ry,useMemo:ry,useReducer:ry,useRef:ry,useState:ry,useDebugValue:ry,useDeferredValue:ry,useTransition:ry,useSyncExternalStore:ry,useId:ry};lc.useCacheRefresh=ry,lc.useHostTransitionStatus=ry,lc.useFormState=ry,lc.useOptimistic=ry;var lf={readContext:l9,use:r_,useCallback:function(e,t){return rz().memoizedState=[e,void 0===t?null:t],e},useContext:l9,useEffect:rZ,useImperativeHandle:function(e,t,n){n=null!=n?n.concat([e]):null,rX(4194308,4,r2.bind(null,t,e),n)},useLayoutEffect:function(e,t){return rX(4194308,4,e,t)},useInsertionEffect:function(e,t){rX(4,2,e,t)},useMemo:function(e,t){var n=rz();return t=void 0===t?null:t,rd&&e(),e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=rz();return t=void 0!==n?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=ll.bind(null,ri,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},rz().memoizedState=e},useState:function(e){var t=(e=r$(e)).queue,n=la.bind(null,ri,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:r4,useDeferredValue:function(e){return rz().memoizedState=e,e},useTransition:function(){var e=r$(!1);return e=r7.bind(null,ri,e.queue,!0,!1),rz().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=ri,l=rz();if(tq){if(void 0===n)throw Error(i(407));n=n()}else{if(n=t(),null===of)throw Error(i(349));0!=(60&op)||rR(r,t,n)}l.memoizedState=n;var a={value:n,getSnapshot:t};return l.queue=a,rZ(rA.bind(null,r,a,e),[e]),r.flags|=2048,rK(9,rD.bind(null,r,a,n,t),{destroy:void 0},null),n},useId:function(){var e=rz(),t=of.identifierPrefix;if(tq){var n=t$,r=tU;t=":"+t+"R"+(n=(r&~(1<<32-el(r)-1)).toString(32)+n),0<(n=rp++)&&(t+="H"+n.toString(32)),t+=":"}else t=":"+t+"r"+(n=rg++).toString(32)+":";return e.memoizedState=t},useCacheRefresh:function(){return rz().memoizedState=lr.bind(null,ri)}};lf.useHostTransitionStatus=le,lf.useFormState=function(e,t){if(tq){var n=of.formState;if(null!==n){e:{if(tq){if(tH){t:{for(var r=tH,l=tY;8!==r.nodeType;)if(!l||null===(r=s2(r))){r=null;break t}r="F!"===(l=r.data)||"F"===l?r:null}if(r){tH=s2(r),r="F!"===r.data;break e}}t2()}r=!1}r&&(t=n[0])}}return(n=rz()).memoizedState=n.baseState=t,r={pending:null,lanes:0,dispatch:null,lastRenderedReducer:rW,lastRenderedState:t},n.queue=r,n=la.bind(null,ri,r),r.dispatch=n,r=rz(),l={state:t,dispatch:null,action:e,pending:null},r.queue=l,n=rV.bind(null,ri,l,n),l.dispatch=n,r.memoizedState=e,[t,n]},lf.useOptimistic=function(e){var t=rz();t.memoizedState=t.baseState=e;var n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=n,t=lo.bind(null,ri,!0,n),n.dispatch=t,[e,t]};var ld={readContext:l9,use:r_,useCallback:r6,useContext:l9,useEffect:rJ,useImperativeHandle:r3,useInsertionEffect:r0,useLayoutEffect:r1,useMemo:r8,useReducer:rT,useRef:rY,useState:function(){return rT(rL)},useDebugValue:r4,useDeferredValue:function(e){return r5(rP(),ru.memoizedState,e)},useTransition:function(){var e=rT(rL)[0],t=rP().memoizedState;return["boolean"==typeof e?e:rN(e),t]},useSyncExternalStore:rO,useId:lt};ld.useCacheRefresh=ln,ld.useHostTransitionStatus=le,ld.useFormState=function(e){return rH(rP(),ru,e)},ld.useOptimistic=function(e,t){return rB(rP(),ru,e,t)};var lp={readContext:l9,use:r_,useCallback:r6,useContext:l9,useEffect:rJ,useImperativeHandle:r3,useInsertionEffect:r0,useLayoutEffect:r1,useMemo:r8,useReducer:rM,useRef:rY,useState:function(){return rM(rL)},useDebugValue:r4,useDeferredValue:function(e){var t=rP();return null===ru?(t.memoizedState=e,e):r5(t,ru.memoizedState,e)},useTransition:function(){var e=rM(rL)[0],t=rP().memoizedState;return["boolean"==typeof e?e:rN(e),t]},useSyncExternalStore:rO,useId:lt};function lm(e,t){if(e&&e.defaultProps)for(var n in t=u({},t),e=e.defaultProps)void 0===t[n]&&(t[n]=e[n]);return t}function lh(e,t,n,r){n=null==(n=n(r,t=e.memoizedState))?t:u({},t,n),e.memoizedState=n,0===e.lanes&&(e.updateQueue.baseState=n)}lp.useCacheRefresh=ln,lp.useHostTransitionStatus=le,lp.useFormState=function(e){var t=rP(),n=ru;if(null!==n)return rH(t,n,e);t=t.memoizedState;var r=(n=rP()).queue.dispatch;return n.memoizedState=e,[t,r]},lp.useOptimistic=function(e,t){var n=rP();return null!==ru?rB(n,ru,e,t):(n.baseState=e,[e,n.queue.dispatch])};var lg={isMounted:function(e){return!!(e=e._reactInternals)&&tg(e)===e},enqueueSetState:function(e,t,n){var r=oU(e=e._reactInternals),l=nc(r);l.payload=t,null!=n&&(l.callback=n),null!==(t=nf(e,l,r))&&(o$(t,e,r),nd(t,e,r))},enqueueReplaceState:function(e,t,n){var r=oU(e=e._reactInternals),l=nc(r);l.tag=1,l.payload=t,null!=n&&(l.callback=n),null!==(t=nf(e,l,r))&&(o$(t,e,r),nd(t,e,r))},enqueueForceUpdate:function(e,t){var n=oU(e=e._reactInternals),r=nc(n);r.tag=2,null!=t&&(r.callback=t),null!==(t=nf(e,r,n))&&(o$(t,e,n),nd(t,e,n))}};function ly(e,t,n,r,l,a,o){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,a,o):!t.prototype||!t.prototype.isPureReactComponent||!ny(n,r)||!ny(l,a)}function lv(e,t,n){var r=!1,l=tk,a=t.contextType;return"object"==typeof a&&null!==a?a=l9(a):(l=tx(t)?tC:tw.current,a=(r=null!=(r=t.contextTypes))?tE(e,l):tk),t=new t(n,a),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=lg,e.stateNode=t,t._reactInternals=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=l,e.__reactInternalMemoizedMaskedChildContext=a),t}function lb(e,t,n,r){e=t.state,"function"==typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"==typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&lg.enqueueReplaceState(t,t.state,null)}function lk(e,t,n,r){var l=e.stateNode;l.props=n,l.state=e.memoizedState,l.refs={},nu(e);var a=t.contextType;"object"==typeof a&&null!==a?l.context=l9(a):(a=tx(t)?tC:tw.current,l.context=tE(e,a)),l.state=e.memoizedState,"function"==typeof(a=t.getDerivedStateFromProps)&&(lh(e,t,a,n),l.state=e.memoizedState),"function"==typeof t.getDerivedStateFromProps||"function"==typeof l.getSnapshotBeforeUpdate||"function"!=typeof l.UNSAFE_componentWillMount&&"function"!=typeof l.componentWillMount||(t=l.state,"function"==typeof l.componentWillMount&&l.componentWillMount(),"function"==typeof l.UNSAFE_componentWillMount&&l.UNSAFE_componentWillMount(),t!==l.state&&lg.enqueueReplaceState(l,l.state,null),nm(e,n,l,r),l.state=e.memoizedState),"function"==typeof l.componentDidMount&&(e.flags|=4194308)}function lw(e,t){try{var n="",r=t;do n+=function(e){switch(e.tag){case 26:case 27:case 5:return eq(e.type);case 16:return eq("Lazy");case 13:return eq("Suspense");case 19:return eq("SuspenseList");case 0:case 2:case 15:return e=eY(e.type,!1);case 11:return e=eY(e.type.render,!1);case 1:return e=eY(e.type,!0);default:return""}}(r),r=r.return;while(r);var l=n}catch(e){l="\nError generating stack: "+e.message+"\n"+e.stack}return{value:e,source:t,stack:l,digest:null}}function lS(e,t,n){return{value:e,source:null,stack:null!=n?n:null,digest:null!=t?t:null}}function lC(e,t){try{console.error(t.value)}catch(e){setTimeout(function(){throw e})}}function lE(e,t,n){(n=nc(n)).tag=3,n.payload={element:null};var r=t.value;return n.callback=function(){o_||(o_=!0,oL=r),lC(e,t)},n}function lx(e,t,n){(n=nc(n)).tag=3;var r=e.type.getDerivedStateFromError;if("function"==typeof r){var l=t.value;n.payload=function(){return r(l)},n.callback=function(){lC(e,t)}}var a=e.stateNode;return null!==a&&"function"==typeof a.componentDidCatch&&(n.callback=function(){lC(e,t),"function"!=typeof r&&(null===oT?oT=new Set([this]):oT.add(this));var n=t.stack;this.componentDidCatch(t.value,{componentStack:null!==n?n:""})}),n}function lz(e,t,n,r,l){return 0==(1&e.mode)?e===t?e.flags|=65536:(e.flags|=128,n.flags|=131072,n.flags&=-52805,1===n.tag&&(null===n.alternate?n.tag=17:((t=nc(2)).tag=2,nf(n,t,2))),n.lanes|=2):(e.flags|=65536,e.lanes=l),e}var lP=s.ReactCurrentOwner,lN=Error(i(461)),l_=!1;function lL(e,t,n,r){t.child=null===e?nO(t,null,n,r):nM(t,e.child,n,r)}function lT(e,t,n,r,l){n=n.render;var a=t.ref;return(l7(t,l),r=rb(e,t,n,r,a,l),n=rC(),null===e||l_)?(tq&&n&&tj(t),t.flags|=1,lL(e,t,r,l),t.child):(rE(e,t,l),lZ(e,t,l))}function lF(e,t,n,r,l){if(null===e){var a=n.type;return"function"!=typeof a||is(a)||void 0!==a.defaultProps||null!==n.compare||void 0!==n.defaultProps?((e=ip(n.type,null,r,null,t,t.mode,l)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=a,lM(e,t,a,r,l))}if(a=e.child,0==(e.lanes&l)){var o=a.memoizedProps;if((n=null!==(n=n.compare)?n:ny)(o,r)&&e.ref===t.ref)return lZ(e,t,l)}return t.flags|=1,(e=ic(a,r)).ref=t.ref,e.return=t,t.child=e}function lM(e,t,n,r,l){if(null!==e){var a=e.memoizedProps;if(ny(a,r)&&e.ref===t.ref){if(l_=!1,t.pendingProps=r=a,0==(e.lanes&l))return t.lanes=e.lanes,lZ(e,t,l);0!=(131072&e.flags)&&(l_=!0)}}return lA(e,t,n,r,l)}function lO(e,t,n){var r=t.pendingProps,l=r.children,a=0!=(2&t.stateNode._pendingVisibility),o=null!==e?e.memoizedState:null;if(lD(e,t),"hidden"===r.mode||a){if(0!=(128&t.flags)){if(n=null!==o?o.baseLanes|n:n,null!==e){for(l=0,r=t.child=e.child;null!==r;)l=l|r.lanes|r.childLanes,r=r.sibling;t.childLanes=l&~n}else t.childLanes=0,t.child=null;return lR(e,t,n)}if(0==(1&t.mode))t.memoizedState={baseLanes:0,cachePool:null},null!==e&&af(t,null),nI(),nj(t);else{if(0==(536870912&n))return t.lanes=t.childLanes=536870912,lR(e,t,null!==o?o.baseLanes|n:n);t.memoizedState={baseLanes:0,cachePool:null},null!==e&&af(t,null!==o?o.cachePool:null),null!==o?nA(t,o):nI(),nj(t)}}else null!==o?(af(t,o.cachePool),nA(t,o),nQ(t),t.memoizedState=null):(null!==e&&af(t,null),nI(),nQ(t));return lL(e,t,l,n),t.child}function lR(e,t,n){var r=ac();return r=null===r?null:{parent:aa._currentValue,pool:r},t.memoizedState={baseLanes:n,cachePool:r},null!==e&&af(t,null),nI(),nj(t),null}function lD(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.flags|=512,t.flags|=2097152)}function lA(e,t,n,r,l){var a=tx(n)?tC:tw.current;return(a=tE(t,a),l7(t,l),n=rb(e,t,n,r,a,l),r=rC(),null===e||l_)?(tq&&r&&tj(t),t.flags|=1,lL(e,t,n,l),t.child):(rE(e,t,l),lZ(e,t,l))}function lI(e,t,n,r,l,a){return(l7(t,a),n=rw(t,r,n,l),rk(),r=rC(),null===e||l_)?(tq&&r&&tj(t),t.flags|=1,lL(e,t,n,a),t.child):(rE(e,t,a),lZ(e,t,a))}function lU(e,t,n,r,l){if(tx(n)){var a=!0;t_(t)}else a=!1;if(l7(t,l),null===t.stateNode)lG(e,t),lv(t,n,r),lk(t,n,r,l),r=!0;else if(null===e){var o=t.stateNode,i=t.memoizedProps;o.props=i;var u=o.context,s=n.contextType;s="object"==typeof s&&null!==s?l9(s):tE(t,s=tx(n)?tC:tw.current);var c=n.getDerivedStateFromProps,f="function"==typeof c||"function"==typeof o.getSnapshotBeforeUpdate;f||"function"!=typeof o.UNSAFE_componentWillReceiveProps&&"function"!=typeof o.componentWillReceiveProps||(i!==r||u!==s)&&lb(t,o,r,s),ni=!1;var d=t.memoizedState;o.state=d,nm(t,r,o,l),u=t.memoizedState,i!==r||d!==u||tS.current||ni?("function"==typeof c&&(lh(t,n,c,r),u=t.memoizedState),(i=ni||ly(t,n,i,r,d,u,s))?(f||"function"!=typeof o.UNSAFE_componentWillMount&&"function"!=typeof o.componentWillMount||("function"==typeof o.componentWillMount&&o.componentWillMount(),"function"==typeof o.UNSAFE_componentWillMount&&o.UNSAFE_componentWillMount()),"function"==typeof o.componentDidMount&&(t.flags|=4194308)):("function"==typeof o.componentDidMount&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=u),o.props=r,o.state=u,o.context=s,r=i):("function"==typeof o.componentDidMount&&(t.flags|=4194308),r=!1)}else{o=t.stateNode,ns(e,t),i=t.memoizedProps,s=t.type===t.elementType?i:lm(t.type,i),o.props=s,f=t.pendingProps,d=o.context,u="object"==typeof(u=n.contextType)&&null!==u?l9(u):tE(t,u=tx(n)?tC:tw.current);var p=n.getDerivedStateFromProps;(c="function"==typeof p||"function"==typeof o.getSnapshotBeforeUpdate)||"function"!=typeof o.UNSAFE_componentWillReceiveProps&&"function"!=typeof o.componentWillReceiveProps||(i!==f||d!==u)&&lb(t,o,r,u),ni=!1,d=t.memoizedState,o.state=d,nm(t,r,o,l);var m=t.memoizedState;i!==f||d!==m||tS.current||ni?("function"==typeof p&&(lh(t,n,p,r),m=t.memoizedState),(s=ni||ly(t,n,s,r,d,m,u)||!1)?(c||"function"!=typeof o.UNSAFE_componentWillUpdate&&"function"!=typeof o.componentWillUpdate||("function"==typeof o.componentWillUpdate&&o.componentWillUpdate(r,m,u),"function"==typeof o.UNSAFE_componentWillUpdate&&o.UNSAFE_componentWillUpdate(r,m,u)),"function"==typeof o.componentDidUpdate&&(t.flags|=4),"function"==typeof o.getSnapshotBeforeUpdate&&(t.flags|=1024)):("function"!=typeof o.componentDidUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!=typeof o.getSnapshotBeforeUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=m),o.props=r,o.state=m,o.context=u,r=s):("function"!=typeof o.componentDidUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=4),"function"!=typeof o.getSnapshotBeforeUpdate||i===e.memoizedProps&&d===e.memoizedState||(t.flags|=1024),r=!1)}return l$(e,t,n,r,a,l)}function l$(e,t,n,r,l,a){lD(e,t);var o=0!=(128&t.flags);if(!r&&!o)return l&&tL(t,n,!1),lZ(e,t,a);r=t.stateNode,lP.current=t;var i=o&&"function"!=typeof n.getDerivedStateFromError?null:r.render();return t.flags|=1,null!==e&&o?(t.child=nM(t,e.child,null,a),t.child=nM(t,null,i,a)):lL(e,t,i,a),t.memoizedState=r.state,l&&tL(t,n,!0),t.child}function lB(e){var t=e.stateNode;t.pendingContext?tP(e,t.pendingContext,t.pendingContext!==t.context):t.context&&tP(e,t.context,!1),B(e,t.containerInfo)}function lV(e,t,n,r,l){return t8(),t5(l),t.flags|=256,lL(e,t,n,r),t.child}var lj={dehydrated:null,treeContext:null,retryLane:0};function lQ(e){return{baseLanes:e,cachePool:ad()}}function lW(e,t,n){var r,l=t.pendingProps,a=!1,o=0!=(128&t.flags);if((r=o)||(r=(null===e||null!==e.memoizedState)&&0!=(2&nH.current)),r&&(a=!0,t.flags&=-129),null===e){if(tq){if(a?nV(t):nQ(t),tq&&((o=e=tH)?t0(t,o)||(t1(t)&&t2(),tH=s2(o),r=tW,tH&&t0(t,tH)?tX(r,o):(tG(tW,t),tq=!1,tW=t,tH=e)):(t1(t)&&t2(),tG(tW,t),tq=!1,tW=t,tH=e)),null!==(e=t.memoizedState)&&null!==(e=e.dehydrated))return 0==(1&t.mode)?t.lanes=2:"$!"===e.data?t.lanes=16:t.lanes=536870912,null;nW(t)}return(o=l.children,e=l.fallback,a)?(nQ(t),l=t.mode,a=t.child,o={mode:"hidden",children:o},0==(1&l)&&null!==a?(a.childLanes=0,a.pendingProps=o):a=ih(o,l,0,null),e=im(e,l,n,null),a.return=t,e.return=t,a.sibling=e,t.child=a,t.child.memoizedState=lQ(n),t.memoizedState=lj,e):(nV(t),lH(t,o))}if(null!==(r=e.memoizedState)){var u=r.dehydrated;if(null!==u)return function(e,t,n,r,l,a,o){if(n)return 256&t.flags?(nV(t),t.flags&=-257,lq(e,t,o,l=lS(Error(i(422))))):null!==t.memoizedState?(nQ(t),t.child=e.child,t.flags|=128,null):(nQ(t),l=r.fallback,a=t.mode,r=ih({mode:"visible",children:r.children},a,0,null),l=im(l,a,o,null),l.flags|=2,r.return=t,l.return=t,r.sibling=l,t.child=r,0!=(1&t.mode)&&nM(t,e.child,null,o),t.child.memoizedState=lQ(o),t.memoizedState=lj,l);if(nV(t),0==(1&t.mode))return lq(e,t,o,null);if("$!"===l.data){if(l=l.nextSibling&&l.nextSibling.dataset)var u=l.dgst;return l=u,(a=Error(i(419))).digest=l,lq(e,t,o,l=lS(a,l,void 0))}if(u=0!=(o&e.childLanes),l_||u){if(null!==(r=of)){if(0!=(42&(u=o&-o)))u=1;else switch(u){case 2:u=1;break;case 8:u=4;break;case 32:u=16;break;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:u=64;break;case 268435456:u=134217728;break;default:u=0}if(0!==(u=0!=(u&(r.suspendedLanes|o))?0:u)&&u!==a.retryLane)throw a.retryLane=u,nl(e,u),o$(r,e,u),lN}return"$?"!==l.data&&o0(),lq(e,t,o,null)}return"$?"===l.data?(t.flags|=128,t.child=e.child,t=ia.bind(null,e),l._reactRetry=t,null):(e=a.treeContext,tH=s1(l.nextSibling),tW=t,tq=!0,tK=null,tY=!1,null!==e&&(tD[tA++]=tU,tD[tA++]=t$,tD[tA++]=tI,tU=e.id,t$=e.overflow,tI=t),t=lH(t,r.children),t.flags|=4096,t)}(e,t,o,l,u,r,n)}if(a){nQ(t),a=l.fallback,o=t.mode,u=(r=e.child).sibling;var s={mode:"hidden",children:l.children};return 0==(1&o)&&t.child!==r?((l=t.child).childLanes=0,l.pendingProps=s,t.deletions=null):(l=ic(r,s)).subtreeFlags=31457280&r.subtreeFlags,null!==u?a=ic(u,a):(a=im(a,o,n,null),a.flags|=2),a.return=t,l.return=t,l.sibling=a,t.child=l,l=a,a=t.child,null===(o=e.child.memoizedState)?o=lQ(n):(null!==(r=o.cachePool)?(u=aa._currentValue,r=r.parent!==u?{parent:u,pool:u}:r):r=ad(),o={baseLanes:o.baseLanes|n,cachePool:r}),a.memoizedState=o,a.childLanes=e.childLanes&~n,t.memoizedState=lj,l}return nV(t),e=(a=e.child).sibling,l=ic(a,{mode:"visible",children:l.children}),0==(1&t.mode)&&(l.lanes=n),l.return=t,l.sibling=null,null!==e&&(null===(n=t.deletions)?(t.deletions=[e],t.flags|=16):n.push(e)),t.child=l,t.memoizedState=null,l}function lH(e,t){return(t=ih({mode:"visible",children:t},e.mode,0,null)).return=e,e.child=t}function lq(e,t,n,r){return null!==r&&t5(r),nM(t,e.child,null,n),e=lH(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function lK(e,t,n){e.lanes|=t;var r=e.alternate;null!==r&&(r.lanes|=t),l8(e.return,t,n)}function lY(e,t,n,r,l){var a=e.memoizedState;null===a?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:l}:(a.isBackwards=t,a.rendering=null,a.renderingStartTime=0,a.last=r,a.tail=n,a.tailMode=l)}function lX(e,t,n){var r=t.pendingProps,l=r.revealOrder,a=r.tail;if(lL(e,t,r.children,n),0!=(2&(r=nH.current)))r=1&r|2,t.flags|=128;else{if(null!==e&&0!=(128&e.flags))e:for(e=t.child;null!==e;){if(13===e.tag)null!==e.memoizedState&&lK(e,n,t);else if(19===e.tag)lK(e,n,t);else if(null!==e.child){e.child.return=e,e=e.child;continue}if(e===t)break;for(;null===e.sibling;){if(null===e.return||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}r&=1}if(g(nH,r),0==(1&t.mode))t.memoizedState=null;else switch(l){case"forwards":for(l=null,n=t.child;null!==n;)null!==(e=n.alternate)&&null===nq(e)&&(l=n),n=n.sibling;null===(n=l)?(l=t.child,t.child=null):(l=n.sibling,n.sibling=null),lY(t,!1,l,n,a);break;case"backwards":for(n=null,l=t.child,t.child=null;null!==l;){if(null!==(e=l.alternate)&&null===nq(e)){t.child=l;break}e=l.sibling,l.sibling=n,n=l,l=e}lY(t,!0,n,null,a);break;case"together":lY(t,!1,null,null,void 0);break;default:t.memoizedState=null}return t.child}function lG(e,t){0==(1&t.mode)&&null!==e&&(e.alternate=null,t.alternate=null,t.flags|=2)}function lZ(e,t,n){if(null!==e&&(t.dependencies=e.dependencies),ok|=t.lanes,0==(n&t.childLanes))return null;if(null!==e&&t.child!==e.child)throw Error(i(153));if(null!==t.child){for(n=ic(e=t.child,e.pendingProps),t.child=n,n.return=t;null!==e.sibling;)e=e.sibling,(n=n.sibling=ic(e,e.pendingProps)).return=t;n.sibling=null}return t.child}var lJ=m(null),l0=null,l1=null,l2=null;function l3(){l2=l1=l0=null}function l4(e,t,n){g(lJ,t._currentValue),t._currentValue=n}function l6(e){e._currentValue=lJ.current,h(lJ)}function l8(e,t,n){for(;null!==e;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,null!==r&&(r.childLanes|=t)):null!==r&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function l5(e,t,n){var r=e.child;for(null!==r&&(r.return=e);null!==r;){var l=r.dependencies;if(null!==l)for(var a=r.child,o=l.firstContext;null!==o;){if(o.context===t){if(1===r.tag){(o=nc(n&-n)).tag=2;var u=r.updateQueue;if(null!==u){var s=(u=u.shared).pending;null===s?o.next=o:(o.next=s.next,s.next=o),u.pending=o}}r.lanes|=n,null!==(o=r.alternate)&&(o.lanes|=n),l8(r.return,n,e),l.lanes|=n;break}o=o.next}else if(10===r.tag)a=r.type===e.type?null:r.child;else if(18===r.tag){if(null===(a=r.return))throw Error(i(341));a.lanes|=n,null!==(l=a.alternate)&&(l.lanes|=n),l8(a,n,e),a=r.sibling}else a=r.child;if(null!==a)a.return=r;else for(a=r;null!==a;){if(a===e){a=null;break}if(null!==(r=a.sibling)){r.return=a.return,a=r;break}a=a.return}r=a}}function l7(e,t){l0=e,l2=l1=null,null!==(e=e.dependencies)&&null!==e.firstContext&&(0!=(e.lanes&t)&&(l_=!0),e.firstContext=null)}function l9(e){return at(l0,e)}function ae(e,t,n){return null===l0&&l7(e,n),at(e,t)}function at(e,t){var n=t._currentValue;if(l2!==t){if(t={context:t,memoizedValue:n,next:null},null===l1){if(null===e)throw Error(i(308));l1=t,e.dependencies={lanes:0,firstContext:t}}else l1=l1.next=t}return n}var an="undefined"!=typeof AbortController?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(t,n){e.push(n)}};this.abort=function(){t.aborted=!0,e.forEach(function(e){return e()})}},ar=a.unstable_scheduleCallback,al=a.unstable_NormalPriority,aa={$$typeof:C,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0,_defaultValue:null,_globalName:null};function ao(){return{controller:new an,data:new Map,refCount:0}}function ai(e){e.refCount--,0===e.refCount&&ar(al,function(){e.controller.abort()})}var au=s.ReactCurrentBatchConfig,as=m(null);function ac(){var e=as.current;return null!==e?e:of.pooledCache}function af(e,t){null===t?g(as,as.current):g(as,t.pool)}function ad(){var e=ac();return null===e?null:{parent:aa._currentValue,pool:e}}function ap(e){e.flags|=4}function am(e){e.flags|=2097664}function ah(e,t){if("stylesheet"!==t.type||0!=(4&t.state.loading))e.flags&=-16777217;else if(e.flags|=16777216,0==(42&op)&&!(t="stylesheet"!==t.type||0!=(3&t.state.loading))){if(oG())e.flags|=8192;else throw nE=nk,nb}}function ag(e,t){null!==t?e.flags|=4:16384&e.flags&&(t=22!==e.tag?ed():536870912,e.lanes|=t)}function ay(e,t){if(!tq)switch(e.tailMode){case"hidden":t=e.tail;for(var n=null;null!==t;)null!==t.alternate&&(n=t),t=t.sibling;null===n?e.tail=null:n.sibling=null;break;case"collapsed":n=e.tail;for(var r=null;null!==n;)null!==n.alternate&&(r=n),n=n.sibling;null===r?t||null===e.tail?e.tail=null:e.tail.sibling=null:r.sibling=null}}function av(e){var t=null!==e.alternate&&e.alternate.child===e.child,n=0,r=0;if(t)for(var l=e.child;null!==l;)n|=l.lanes|l.childLanes,r|=31457280&l.subtreeFlags,r|=31457280&l.flags,l.return=e,l=l.sibling;else for(l=e.child;null!==l;)n|=l.lanes|l.childLanes,r|=l.subtreeFlags,r|=l.flags,l.return=e,l=l.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function ab(e,t){switch(tQ(t),t.tag){case 1:null!=(e=t.type.childContextTypes)&&tz();break;case 3:l6(aa),V(),h(tS),h(tw);break;case 26:case 27:case 5:Q(t);break;case 4:V();break;case 13:nW(t);break;case 19:h(nH);break;case 10:l6(t.type._context);break;case 22:case 23:nW(t),nU(),null!==e&&h(as);break;case 24:l6(aa)}}function ak(e,t,n){var r=Array.prototype.slice.call(arguments,3);try{t.apply(n,r)}catch(e){this.onError(e)}}var aw=!1,aS=null,aC=!1,aE=null,ax={onError:function(e){aw=!0,aS=e}};function az(e,t,n,r,l,a,o,i,u){aw=!1,aS=null,ak.apply(ax,arguments)}var aP=!1,aN=!1,a_="function"==typeof WeakSet?WeakSet:Set,aL=null;function aT(e,t){try{var n=e.ref;if(null!==n){var r=e.stateNode;switch(e.tag){case 26:case 27:case 5:var l=r;break;default:l=r}"function"==typeof n?e.refCleanup=n(l):n.current=l}}catch(n){ie(e,t,n)}}function aF(e,t){var n=e.ref,r=e.refCleanup;if(null!==n){if("function"==typeof r)try{r()}catch(n){ie(e,t,n)}finally{e.refCleanup=null,null!=(e=e.alternate)&&(e.refCleanup=null)}else if("function"==typeof n)try{n(null)}catch(n){ie(e,t,n)}else n.current=null}}function aM(e,t,n){try{n()}catch(n){ie(e,t,n)}}var aO=!1;function aR(e,t,n){var r=t.updateQueue;if(null!==(r=null!==r?r.lastEffect:null)){var l=r=r.next;do{if((l.tag&e)===e){var a=l.inst,o=a.destroy;void 0!==o&&(a.destroy=void 0,aM(t,n,o))}l=l.next}while(l!==r)}}function aD(e,t){if(null!==(t=null!==(t=t.updateQueue)?t.lastEffect:null)){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create,l=n.inst;r=r(),l.destroy=r}n=n.next}while(n!==t)}}function aA(e,t){try{aD(t,e)}catch(t){ie(e,e.return,t)}}function aI(e){var t=e.updateQueue;if(null!==t){var n=e.stateNode;try{ng(t,n)}catch(t){ie(e,e.return,t)}}}function aU(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{switch(t){case"button":case"input":case"select":case"textarea":n.autoFocus&&r.focus();break;case"img":n.src&&(r.src=n.src)}}catch(t){ie(e,e.return,t)}}function a$(e,t,n){var r=n.flags;switch(n.tag){case 0:case 11:case 15:a0(e,n),4&r&&aA(n,5);break;case 1:if(a0(e,n),4&r){if(e=n.stateNode,null===t)try{e.componentDidMount()}catch(e){ie(n,n.return,e)}else{var l=n.elementType===n.type?t.memoizedProps:lm(n.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(l,t,e.__reactInternalSnapshotBeforeUpdate)}catch(e){ie(n,n.return,e)}}}64&r&&aI(n),512&r&&aT(n,n.return);break;case 3:if(a0(e,n),64&r&&null!==(r=n.updateQueue)){if(e=null,null!==n.child)switch(n.child.tag){case 27:case 5:case 1:e=n.child.stateNode}try{ng(r,e)}catch(e){ie(n,n.return,e)}}break;case 26:a0(e,n),512&r&&aT(n,n.return);break;case 27:case 5:a0(e,n),null===t&&4&r&&aU(n),512&r&&aT(n,n.return);break;case 12:default:a0(e,n);break;case 13:a0(e,n),4&r&&aK(e,n);break;case 22:if(0!=(1&n.mode)){if(!(l=null!==n.memoizedState||aP)){t=null!==t&&null!==t.memoizedState||aN;var a=aP,o=aN;aP=l,(aN=t)&&!o?function e(t,n,r){for(r=r&&0!=(8772&n.subtreeFlags),n=n.child;null!==n;){var l=n.alternate,a=t,o=n,i=o.flags;switch(o.tag){case 0:case 11:case 15:e(a,o,r),aA(o,4);break;case 1:if(e(a,o,r),"function"==typeof(a=o.stateNode).componentDidMount)try{a.componentDidMount()}catch(e){ie(o,o.return,e)}if(null!==(l=o.updateQueue)){var u=l.shared.hiddenCallbacks;if(null!==u)for(l.shared.hiddenCallbacks=null,l=0;l title"))),sI(l,n,r),l[ew]=e,eR(l),n=l;break e;case"link":var a=cf("link","href",t).get(n+(r.href||""));if(a){for(var o=0;o",e=e.removeChild(e.firstChild);break;case"select":e="string"==typeof r.is?l.createElement("select",{is:r.is}):l.createElement("select"),r.multiple?e.multiple=!0:r.size&&(e.size=r.size);break;default:e="string"==typeof r.is?l.createElement(n,{is:r.is}):l.createElement(n)}}e[ew]=t,e[eS]=r;e:for(l=t.child;null!==l;){if(5===l.tag||6===l.tag)e.appendChild(l.stateNode);else if(4!==l.tag&&27!==l.tag&&null!==l.child){l.child.return=l,l=l.child;continue}if(l===t)break;for(;null===l.sibling;){if(null===l.return||l.return===t)break e;l=l.return}l.sibling.return=l.return,l=l.sibling}switch(t.stateNode=e,sI(e,n,r),n){case"button":case"input":case"select":case"textarea":e=!!r.autoFocus;break;case"img":e=!0;break;default:e=!1}e&&ap(t)}null!==t.ref&&am(t)}return av(t),t.flags&=-16777217,null;case 6:if(e&&null!=t.stateNode)e.memoizedProps!==r&&ap(t);else{if("string"!=typeof r&&null===t.stateNode)throw Error(i(166));if(e=I.current,t4(t)){e:{if(e=t.stateNode,n=t.memoizedProps,e[ew]=t,(r=e.nodeValue!==n)&&null!==(l=tW))switch(l.tag){case 3:if(l=0!=(1&l.mode),sO(e.nodeValue,n,l),l){e=!1;break e}break;case 27:case 5:var a=0!=(1&l.mode);if(!0!==l.memoizedProps.suppressHydrationWarning&&sO(e.nodeValue,n,a),a){e=!1;break e}}e=r}e&&ap(t)}else(e=sV(e).createTextNode(r))[ew]=t,t.stateNode=e}return av(t),null;case 13:if(nW(t),r=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(tq&&null!==tH&&0!=(1&t.mode)&&0==(128&t.flags))t6(),t8(),t.flags|=384,l=!1;else if(l=t4(t),null!==r&&null!==r.dehydrated){if(null===e){if(!l)throw Error(i(318));if(!(l=null!==(l=t.memoizedState)?l.dehydrated:null))throw Error(i(317));l[ew]=t}else t8(),0==(128&t.flags)&&(t.memoizedState=null),t.flags|=4;av(t),l=!1}else null!==tK&&(oj(tK),tK=null),l=!0;if(!l)return 256&t.flags?t:null}if(0!=(128&t.flags))return t.lanes=n,t;return n=null!==r,e=null!==e&&null!==e.memoizedState,n&&(r=t.child,l=null,null!==r.alternate&&null!==r.alternate.memoizedState&&null!==r.alternate.memoizedState.cachePool&&(l=r.alternate.memoizedState.cachePool.pool),a=null,null!==r.memoizedState&&null!==r.memoizedState.cachePool&&(a=r.memoizedState.cachePool.pool),a!==l&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),ag(t,t.updateQueue),av(t),null;case 4:return V(),null===e&&sE(t.stateNode.containerInfo),av(t),null;case 10:return l6(t.type._context),av(t),null;case 19:if(h(nH),null===(l=t.memoizedState))return av(t),null;if(r=0!=(128&t.flags),null===(a=l.rendering)){if(r)ay(l,!1);else{if(0!==ov||null!==e&&0!=(128&e.flags))for(e=t.child;null!==e;){if(null!==(a=nq(e))){for(t.flags|=128,ay(l,!1),e=a.updateQueue,t.updateQueue=e,ag(t,e),t.subtreeFlags=0,e=n,n=t.child;null!==n;)id(n,e),n=n.sibling;return g(nH,1&nH.current|2),t.child}e=e.sibling}null!==l.tail&&Y()>oP&&(t.flags|=128,r=!0,ay(l,!1),t.lanes=4194304)}}else{if(!r){if(null!==(e=nq(a))){if(t.flags|=128,r=!0,e=e.updateQueue,t.updateQueue=e,ag(t,e),ay(l,!0),null===l.tail&&"hidden"===l.tailMode&&!a.alternate&&!tq)return av(t),null}else 2*Y()-l.renderingStartTime>oP&&536870912!==n&&(t.flags|=128,r=!0,ay(l,!1),t.lanes=4194304)}l.isBackwards?(a.sibling=t.child,t.child=a):(null!==(e=l.last)?e.sibling=a:t.child=a,l.last=a)}if(null!==l.tail)return t=l.tail,l.rendering=t,l.tail=t.sibling,l.renderingStartTime=Y(),t.sibling=null,e=nH.current,g(nH,r?1&e|2:1&e),t;return av(t),null;case 22:case 23:return nW(t),nU(),r=null!==t.memoizedState,null!==e?null!==e.memoizedState!==r&&(t.flags|=8192):r&&(t.flags|=8192),r&&0!=(1&t.mode)?0!=(536870912&n)&&0==(128&t.flags)&&(av(t),6&t.subtreeFlags&&(t.flags|=8192)):av(t),null!==(n=t.updateQueue)&&ag(t,n.retryQueue),n=null,null!==e&&null!==e.memoizedState&&null!==e.memoizedState.cachePool&&(n=e.memoizedState.cachePool.pool),r=null,null!==t.memoizedState&&null!==t.memoizedState.cachePool&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),null!==e&&h(as),null;case 24:return n=null,null!==e&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),l6(aa),av(t),null;case 25:return null}throw Error(i(156,t.tag))}(t.alternate,t,oy);if(null!==n){od=n;return}if(null!==(t=t.sibling)){od=t;return}od=t=e}while(null!==t);0===ov&&(ov=5)}function o8(e,t,n,r){var l=ey,a=os.transition;try{os.transition=null,ey=2,function(e,t,n,r,l){do o7();while(null!==oM);if(0!=(6&oc))throw Error(i(327));var a=e.finishedWork,o=e.finishedLanes;if(null!==a){if(e.finishedWork=null,e.finishedLanes=0,a===e.current)throw Error(i(177));e.callbackNode=null,e.callbackPriority=0,e.cancelPendingCommit=null;var u=a.lanes|a.childLanes;if(function(e,t,n){var r=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.entangledLanes&=t,e.errorRecoveryDisabledLanes&=t,e.shellSuspendCounter=0,t=e.entanglements;for(var l=e.expirationTimes,a=e.hiddenUpdates;0r&&(l=r,r=a,a=l),l=u4(n,a);var o=u4(n,r);l&&o&&(1!==e.rangeCount||e.anchorNode!==l.node||e.anchorOffset!==l.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&((t=t.createRange()).setStart(l.node,l.offset),e.removeAllRanges(),a>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)1===e.nodeType&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"==typeof n.focus&&n.focus(),n=0;nn?32:n;n=os.transition;var l=ey;try{if(os.transition=null,ey=r,null===oM)var a=!1;else{r=oD,oD=null;var o=oM,u=oO;if(oM=null,oO=0,0!=(6&oc))throw Error(i(331));var s=oc;if(oc|=4,on(o.current),a6(o,o.current,u,r),oc=s,n1(!1),er&&"function"==typeof er.onPostCommitFiberRoot)try{er.onPostCommitFiberRoot(en,o)}catch(e){}a=!0}return a}finally{ey=l,os.transition=n,o5(e,t)}}return!1}function o9(e,t,n){t=lE(e,t=lw(n,t),2),null!==(e=nf(e,t,2))&&(em(e,2),n0(e))}function ie(e,t,n){if(3===e.tag)o9(e,e,n);else for(;null!==t;){if(3===t.tag){o9(t,e,n);break}if(1===t.tag){var r=t.stateNode;if("function"==typeof t.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===oT||!oT.has(r))){e=lx(t,e=lw(n,e),2),null!==(t=nf(t,e,2))&&(em(t,2),n0(t));break}}t=t.return}}function it(e,t,n){var r=e.pingCache;if(null===r){r=e.pingCache=new oa;var l=new Set;r.set(t,l)}else void 0===(l=r.get(t))&&(l=new Set,r.set(t,l));l.has(n)||(og=!0,l.add(n),e=ir.bind(null,e,t,n),t.then(e,e))}function ir(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,of===e&&(op&n)===n&&(4===ov||3===ov&&(62914560&op)===op&&300>Y()-oz?0==(2&oc)&&oY(e,0):oS|=n),n0(e)}function il(e,t){0===t&&(t=0==(1&e.mode)?2:ed()),null!==(e=nl(e,t))&&(em(e,t),n0(e))}function ia(e){var t=e.memoizedState,n=0;null!==t&&(n=t.retryLane),il(e,n)}function io(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,l=e.memoizedState;null!==l&&(n=l.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}null!==r&&r.delete(t),il(e,n)}function ii(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function iu(e,t,n,r){return new ii(e,t,n,r)}function is(e){return!(!(e=e.prototype)||!e.isReactComponent)}function ic(e,t){var n=e.alternate;return null===n?((n=iu(e.tag,t,e.key,e.mode)).elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=31457280&e.flags,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n.refCleanup=e.refCleanup,n}function id(e,t){e.flags&=31457282;var n=e.alternate;return null===n?(e.childLanes=0,e.lanes=t,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=n.childLanes,e.lanes=n.lanes,e.child=n.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=n.memoizedProps,e.memoizedState=n.memoizedState,e.updateQueue=n.updateQueue,e.type=n.type,t=n.dependencies,e.dependencies=null===t?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function ip(e,t,n,r,l,a,o){if(l=2,r=e,"function"==typeof e)is(e)&&(l=1);else if("string"==typeof e)l=!function(e,t,n){if(1===n||null!=t.itemProp)return!1;switch(e){case"meta":case"title":return!0;case"style":if("string"!=typeof t.precedence||"string"!=typeof t.href||""===t.href)break;return!0;case"link":if("string"!=typeof t.rel||"string"!=typeof t.href||""===t.href||t.onLoad||t.onError)break;if("stylesheet"===t.rel)return e=t.disabled,"string"==typeof t.precedence&&null==e;return!0;case"script":if(!0===t.async&&!t.onLoad&&!t.onError&&"string"==typeof t.src&&t.src)return!0}return!1}(e,n,D.current)?"html"===e||"head"===e||"body"===e?27:5:26;else e:switch(e){case b:return im(n.children,a,o,t);case k:l=8,0!=(1&(a|=8))&&(a|=16);break;case w:return(e=iu(12,n,t,2|a)).elementType=w,e.lanes=o,e;case z:return(e=iu(13,n,t,a)).elementType=z,e.lanes=o,e;case P:return(e=iu(19,n,t,a)).elementType=P,e.lanes=o,e;case T:return ih(n,a,o,t);case F:case L:case M:return(e=iu(24,n,t,a)).elementType=M,e.lanes=o,e;default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case S:l=10;break e;case C:l=9;break e;case x:l=11;break e;case N:l=14;break e;case _:l=16,r=null;break e}throw Error(i(130,null==e?e:typeof e,""))}return(t=iu(l,n,t,a)).elementType=e,t.type=r,t.lanes=o,t}function im(e,t,n,r){return(e=iu(7,e,r,t)).lanes=n,e}function ih(e,t,n,r){(e=iu(22,e,r,t)).elementType=T,e.lanes=n;var l={_visibility:1,_pendingVisibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null,_current:null,detach:function(){var e=l._current;if(null===e)throw Error(i(456));if(0==(2&l._pendingVisibility)){var t=nl(e,2);null!==t&&(l._pendingVisibility|=2,o$(t,e,2))}},attach:function(){var e=l._current;if(null===e)throw Error(i(456));if(0!=(2&l._pendingVisibility)){var t=nl(e,2);null!==t&&(l._pendingVisibility&=-3,o$(t,e,2))}}};return e.stateNode=l,e}function ig(e,t,n){return(e=iu(6,e,null,t)).lanes=n,e}function iy(e,t,n){return(t=iu(4,null!==e.children?e.children:[],e.key,t)).lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function iv(e,t,n,r,l,a){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=ep(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.finishedLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=ep(0),this.hiddenUpdates=ep(null),this.identifierPrefix=r,this.onRecoverableError=l,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=a,this.incompleteTransitions=new Map}function ib(e,t,n,r,l,a,o,i,u,s,c){return e=new iv(e,t,n,i,u,c),1===t?(t=1,!0===a&&(t|=24)):t=0,a=iu(3,null,null,t),e.current=a,a.stateNode=e,t=ao(),t.refCount++,e.pooledCache=t,t.refCount++,a.memoizedState={element:r,isDehydrated:n,cache:t},nu(a),e}function ik(e){if(!e)return tk;e=e._reactInternals;e:{if(tg(e)!==e||1!==e.tag)throw Error(i(170));var t=e;do{switch(t.tag){case 3:t=t.stateNode.context;break e;case 1:if(tx(t.type)){t=t.stateNode.__reactInternalMemoizedMergedChildContext;break e}}t=t.return}while(null!==t);throw Error(i(171))}if(1===e.tag){var n=e.type;if(tx(n))return tN(e,n,t)}return t}function iw(e,t,n,r,l,a,o,i,u,s,c){return(e=ib(n,r,!0,e,l,a,o,i,u,s,c)).context=ik(null),(l=nc(r=oU(n=e.current))).callback=null!=t?t:null,nf(n,l,r),e.current.lanes=r,em(e,r),n0(e),e}function iS(e,t,n,r){var l=t.current,a=oU(l);return n=ik(n),null===t.context?t.context=n:t.pendingContext=n,(t=nc(a)).payload={element:e},null!==(r=void 0===r?null:r)&&(t.callback=r),null!==(e=nf(l,t,a))&&(o$(e,l,a),nd(e,l,a)),a}function iC(e){return(e=e.current).child?(e.child.tag,e.child.stateNode):null}function iE(e,t){if(null!==(e=e.memoizedState)&&null!==e.dehydrated){var n=e.retryLane;e.retryLane=0!==n&&n=uM),uD=!1;function uA(e,t){switch(e){case"keyup":return -1!==uT.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function uI(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var uU=!1,u$={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function uB(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!u$[e.type]:"textarea"===t}function uV(e,t,n,r){tm(r),0<(t=sN(t,"onChange")).length&&(n=new iQ("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var uj=null,uQ=null;function uW(e){sk(e,0)}function uH(e){if(eJ(eF(e)))return e}function uq(e,t){if("change"===e)return t}var uK=!1;if(e$){if(e$){var uY="oninput"in document;if(!uY){var uX=document.createElement("div");uX.setAttribute("oninput","return;"),uY="function"==typeof uX.oninput}r=uY}else r=!1;uK=r&&(!document.documentMode||9=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=u3(r)}}function u6(){for(var e=window,t=e0();t instanceof e.HTMLIFrameElement;){try{var n="string"==typeof t.contentWindow.location.href}catch(e){n=!1}if(n)e=t.contentWindow;else break;t=e0(e.document)}return t}function u8(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var u5=e$&&"documentMode"in document&&11>=document.documentMode,u7=null,u9=null,se=null,st=!1;function sn(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;st||null==u7||u7!==e0(r)||(r="selectionStart"in(r=u7)&&u8(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},se&&ny(se,r)||(se=r,0<(r=sN(u9,"onSelect")).length&&(t=new iQ("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=u7)))}function sr(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var sl={animationend:sr("Animation","AnimationEnd"),animationiteration:sr("Animation","AnimationIteration"),animationstart:sr("Animation","AnimationStart"),transitionend:sr("Transition","TransitionEnd")},sa={},so={};function si(e){if(sa[e])return sa[e];if(!sl[e])return e;var t,n=sl[e];for(t in n)if(n.hasOwnProperty(t)&&t in so)return sa[e]=n[t];return e}e$&&(so=document.createElement("div").style,"AnimationEvent"in window||(delete sl.animationend.animation,delete sl.animationiteration.animation,delete sl.animationstart.animation),"TransitionEvent"in window||delete sl.transitionend.transition);var su=si("animationend"),ss=si("animationiteration"),sc=si("animationstart"),sf=si("transitionend"),sd=new Map,sp="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll scrollEnd toggle touchMove waiting wheel".split(" ");function sm(e,t){sd.set(e,t),eI(t,[e])}for(var sh=0;sh title"):null)}var cp=null;function cm(){}function ch(){if(this.count--,0===this.count){if(this.stylesheets)cy(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var cg=null;function cy(e,t){e.stylesheets=null,null!==e.unsuspend&&(e.count++,cg=new Map,t.forEach(cv,e),cg=null,ch.call(e))}function cv(e,t){if(!(4&t.state.loading)){var n=cg.get(e);if(n)var r=n.get("last");else{n=new Map,cg.set(e,n);for(var l=e.querySelectorAll("link[data-precedence],style[data-precedence]"),a=0;aP||(n.current=x[P],x[P]=null,P--)}function E(n,a){x[++P]=n.current,n.current=a}var N=Symbol.for("react.element"),j=Symbol.for("react.portal"),L=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),M=Symbol.for("react.profiler"),R=Symbol.for("react.provider"),F=Symbol.for("react.context"),O=Symbol.for("react.server_context"),A=Symbol.for("react.forward_ref"),I=Symbol.for("react.suspense"),Q=Symbol.for("react.suspense_list"),$=Symbol.for("react.memo"),H=Symbol.for("react.lazy"),K=Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var X=Symbol.for("react.offscreen"),G=Symbol.for("react.legacy_hidden"),J=Symbol.for("react.cache");Symbol.for("react.tracing_marker");var ee=Symbol.iterator;function Da(n){return null===n||"object"!=typeof n?null:"function"==typeof(n=ee&&n[ee]||n["@@iterator"])?n:null}var et=ka(null),en=ka(null),er=ka(null),ea=ka(null),ei={$$typeof:F,_currentValue:null,_currentValue2:null,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};function Ja(n,a){switch(E(er,a),E(en,n),E(et,null),n=a.nodeType){case 9:case 11:a=(a=a.documentElement)&&(a=a.namespaceURI)?Ka(a):0;break;default:if(a=(n=8===n?a.parentNode:a).tagName,n=n.namespaceURI)a=La(n=Ka(n),a);else switch(a){case"svg":a=1;break;case"math":a=2;break;default:a=0}}D(et),E(et,a)}function Ma(){D(et),D(en),D(er)}function Na(n){null!==n.memoizedState&&E(ea,n);var a=et.current,i=La(a,n.type);a!==i&&(E(en,n),E(et,i))}function Oa(n){en.current===n&&(D(et),D(en)),ea.current===n&&(D(ea),ei._currentValue=null)}var eu=m.unstable_scheduleCallback,es=m.unstable_cancelCallback,ed=m.unstable_shouldYield,ep=m.unstable_requestPaint,em=m.unstable_now,eb=m.unstable_getCurrentPriorityLevel,ey=m.unstable_ImmediatePriority,ev=m.unstable_UserBlockingPriority,ek=m.unstable_NormalPriority,ew=m.unstable_LowPriority,eS=m.unstable_IdlePriority,eE=null,eC=null;function bb(n){if(eC&&"function"==typeof eC.onCommitFiberRoot)try{eC.onCommitFiberRoot(eE,n,void 0,128==(128&n.current.flags))}catch(n){}}var ex=Math.clz32?Math.clz32:cb,ez=Math.log,eP=Math.LN2;function cb(n){return 0==(n>>>=0)?32:31-(ez(n)/eP|0)|0}var eN=128,eT=4194304;function ib(n){switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194176&n;case 4194304:case 8388608:case 16777216:case 33554432:return 62914560&n;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function jb(n,a){var i=n.pendingLanes;if(0===i)return 0;var o=0,s=n.suspendedLanes;n=n.pingedLanes;var m=134217727&i;return 0!==m?0!=(i=m&~s)?o=ib(i):0!=(n&=m)&&(o=ib(n)):0!=(i&=~s)?o=ib(i):0!==n&&(o=ib(n)),0===o?0:0!==a&&a!==o&&0==(a&s)&&((s=o&-o)>=(n=a&-a)||32===s&&0!=(4194176&n))?a:o}function kb(n,a){switch(n){case 1:case 2:case 4:case 8:return a+250;case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a+5e3;default:return -1}}function lb(n,a){return n.errorRecoveryDisabledLanes&a?0:0!=(n=-536870913&n.pendingLanes)?n:536870912&n?536870912:0}function mb(){var n=eT;return 0==(62914560&(eT<<=1))&&(eT=4194304),n}function nb(n){for(var a=[],i=0;31>i;i++)a.push(n);return a}function ob(n,a){n.pendingLanes|=a,268435456!==a&&(n.suspendedLanes=0,n.pingedLanes=0)}function pb(n,a,i){var o=n.pendingLanes&~a;n.pendingLanes=a,n.suspendedLanes=0,n.pingedLanes=0,n.expiredLanes&=a,n.entangledLanes&=a,n.errorRecoveryDisabledLanes&=a,n.shellSuspendCounter=0,a=n.entanglements;for(var s=n.expirationTimes,m=n.hiddenUpdates;0--k||m[v]!==y[k]){var S="\n"+m[v].replace(" at new "," at ");return n.displayName&&S.includes("")&&(S=S.replace("",n.displayName)),S}while(1<=v&&0<=k);break}}}finally{eH=!1,Error.prepareStackTrace=i}return(n=n?n.displayName||n.name:"")?ac(n):""}function dc(n){switch(n.tag){case 26:case 27:case 5:return ac(n.type);case 16:return ac("Lazy");case 13:return ac("Suspense");case 19:return ac("SuspenseList");case 0:case 2:case 15:return n=cc(n.type,!1);case 11:return n=cc(n.type.render,!1);case 1:return n=cc(n.type,!0);default:return""}}function ec(n){if(null==n)return null;if("function"==typeof n)return n.displayName||n.name||null;if("string"==typeof n)return n;switch(n){case L:return"Fragment";case j:return"Portal";case M:return"Profiler";case _:return"StrictMode";case I:return"Suspense";case Q:return"SuspenseList";case J:return"Cache"}if("object"==typeof n)switch(n.$$typeof){case F:return(n.displayName||"Context")+".Consumer";case R:return(n._context.displayName||"Context")+".Provider";case A:var a=n.render;return(n=n.displayName)||(n=""!==(n=a.displayName||a.name||"")?"ForwardRef("+n+")":"ForwardRef"),n;case $:return null!==(a=n.displayName||null)?a:ec(n.type)||"Memo";case H:a=n._payload,n=n._init;try{return ec(n(a))}catch(n){}}return null}function fc(n){var a=n.type;switch(n.tag){case 24:return"Cache";case 9:return(a.displayName||"Context")+".Consumer";case 10:return(a._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return n=(n=a.render).displayName||n.name||"",a.displayName||(""!==n?"ForwardRef("+n+")":"ForwardRef");case 7:return"Fragment";case 26:case 27:case 5:return a;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return ec(a);case 8:return a===_?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof a)return a.displayName||a.name||null;if("string"==typeof a)return a}return null}function gc(n){switch(typeof n){case"boolean":case"number":case"string":case"undefined":case"object":return n;default:return""}}function hc(n){var a=n.type;return(n=n.nodeName)&&"input"===n.toLowerCase()&&("checkbox"===a||"radio"===a)}function ic(n){var a=hc(n)?"checked":"value",i=Object.getOwnPropertyDescriptor(n.constructor.prototype,a),o=""+n[a];if(!n.hasOwnProperty(a)&&void 0!==i&&"function"==typeof i.get&&"function"==typeof i.set){var s=i.get,m=i.set;return Object.defineProperty(n,a,{configurable:!0,get:function(){return s.call(this)},set:function(n){o=""+n,m.call(this,n)}}),Object.defineProperty(n,a,{enumerable:i.enumerable}),{getValue:function(){return o},setValue:function(n){o=""+n},stopTracking:function(){n._valueTracker=null,delete n[a]}}}}function jc(n){n._valueTracker||(n._valueTracker=ic(n))}function kc(n){if(!n)return!1;var a=n._valueTracker;if(!a)return!0;var i=a.getValue(),o="";return n&&(o=hc(n)?n.checked?"true":"false":n.value),(n=o)!==i&&(a.setValue(n),!0)}function lc(n){if(void 0===(n=n||("undefined"!=typeof document?document:void 0)))return null;try{return n.activeElement||n.body}catch(a){return n.body}}var eZ=/[\n"\\]/g;function nc(n){return n.replace(eZ,function(n){return"\\"+n.charCodeAt(0).toString(16)+" "})}function oc(n,a,i,o,s,m,y,v){n.name="",null!=y&&"function"!=typeof y&&"symbol"!=typeof y&&"boolean"!=typeof y?n.type=y:n.removeAttribute("type"),null!=a?"number"===y?(0===a&&""===n.value||n.value!=a)&&(n.value=""+gc(a)):n.value!==""+gc(a)&&(n.value=""+gc(a)):"submit"!==y&&"reset"!==y||n.removeAttribute("value"),null!=a?pc(n,y,gc(a)):null!=i?pc(n,y,gc(i)):null!=o&&n.removeAttribute("value"),null==s&&null!=m&&(n.defaultChecked=!!m),null!=s&&(n.checked=s&&"function"!=typeof s&&"symbol"!=typeof s),null!=v&&"function"!=typeof v&&"symbol"!=typeof v&&"boolean"!=typeof v?n.name=""+gc(v):n.removeAttribute("name")}function qc(n,a,i,o,s,m,y,v){if(null!=m&&"function"!=typeof m&&"symbol"!=typeof m&&"boolean"!=typeof m&&(n.type=m),null!=a||null!=i){if(!("submit"!==m&&"reset"!==m||null!=a))return;i=null!=i?""+gc(i):"",a=null!=a?""+gc(a):i,v||a===n.value||(n.value=a),n.defaultValue=a}o="function"!=typeof(o=null!=o?o:s)&&"symbol"!=typeof o&&!!o,n.checked=v?n.checked:!!o,n.defaultChecked=!!o,null!=y&&"function"!=typeof y&&"symbol"!=typeof y&&"boolean"!=typeof y&&(n.name=y)}function pc(n,a,i){"number"===a&&lc(n.ownerDocument)===n||n.defaultValue===""+i||(n.defaultValue=""+i)}var eK=Array.isArray;function sc(n,a,i,o){if(n=n.options,a){a={};for(var s=0;s"+a.valueOf().toString()+"",a=rS.firstChild;n.firstChild;)n.removeChild(n.firstChild);for(;a.firstChild;)n.appendChild(a.firstChild)}}var eX=wc;"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(eX=function(n,a){return MSApp.execUnsafeLocalFunction(function(){return wc(n,a)})});var eG=eX;function zc(n,a){if(a){var i=n.firstChild;if(i&&i===n.lastChild&&3===i.nodeType){i.nodeValue=a;return}}n.textContent=a}var eJ=new Set("animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp".split(" "));function Bc(n,a,i){var o=0===a.indexOf("--");null==i||"boolean"==typeof i||""===i?o?n.setProperty(a,""):"float"===a?n.cssFloat="":n[a]="":o?n.setProperty(a,i):"number"!=typeof i||0===i||eJ.has(a)?"float"===a?n.cssFloat=i:n[a]=(""+i).trim():n[a]=i+"px"}function Cc(n,a,i){if(null!=a&&"object"!=typeof a)throw Error(t(62));if(n=n.style,null!=i){for(var o in i)!i.hasOwnProperty(o)||null!=a&&a.hasOwnProperty(o)||(0===o.indexOf("--")?n.setProperty(o,""):"float"===o?n.cssFloat="":n[o]="");for(var s in a)o=a[s],a.hasOwnProperty(s)&&i[s]!==o&&Bc(n,s,o)}else for(var m in a)a.hasOwnProperty(m)&&Bc(n,m,a[m])}function Dc(n){if(-1===n.indexOf("-"))return!1;switch(n){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var e0=new Map([["acceptCharset","accept-charset"],["htmlFor","for"],["httpEquiv","http-equiv"],["crossOrigin","crossorigin"],["accentHeight","accent-height"],["alignmentBaseline","alignment-baseline"],["arabicForm","arabic-form"],["baselineShift","baseline-shift"],["capHeight","cap-height"],["clipPath","clip-path"],["clipRule","clip-rule"],["colorInterpolation","color-interpolation"],["colorInterpolationFilters","color-interpolation-filters"],["colorProfile","color-profile"],["colorRendering","color-rendering"],["dominantBaseline","dominant-baseline"],["enableBackground","enable-background"],["fillOpacity","fill-opacity"],["fillRule","fill-rule"],["floodColor","flood-color"],["floodOpacity","flood-opacity"],["fontFamily","font-family"],["fontSize","font-size"],["fontSizeAdjust","font-size-adjust"],["fontStretch","font-stretch"],["fontStyle","font-style"],["fontVariant","font-variant"],["fontWeight","font-weight"],["glyphName","glyph-name"],["glyphOrientationHorizontal","glyph-orientation-horizontal"],["glyphOrientationVertical","glyph-orientation-vertical"],["horizAdvX","horiz-adv-x"],["horizOriginX","horiz-origin-x"],["imageRendering","image-rendering"],["letterSpacing","letter-spacing"],["lightingColor","lighting-color"],["markerEnd","marker-end"],["markerMid","marker-mid"],["markerStart","marker-start"],["overlinePosition","overline-position"],["overlineThickness","overline-thickness"],["paintOrder","paint-order"],["panose-1","panose-1"],["pointerEvents","pointer-events"],["renderingIntent","rendering-intent"],["shapeRendering","shape-rendering"],["stopColor","stop-color"],["stopOpacity","stop-opacity"],["strikethroughPosition","strikethrough-position"],["strikethroughThickness","strikethrough-thickness"],["strokeDasharray","stroke-dasharray"],["strokeDashoffset","stroke-dashoffset"],["strokeLinecap","stroke-linecap"],["strokeLinejoin","stroke-linejoin"],["strokeMiterlimit","stroke-miterlimit"],["strokeOpacity","stroke-opacity"],["strokeWidth","stroke-width"],["textAnchor","text-anchor"],["textDecoration","text-decoration"],["textRendering","text-rendering"],["transformOrigin","transform-origin"],["underlinePosition","underline-position"],["underlineThickness","underline-thickness"],["unicodeBidi","unicode-bidi"],["unicodeRange","unicode-range"],["unitsPerEm","units-per-em"],["vAlphabetic","v-alphabetic"],["vHanging","v-hanging"],["vIdeographic","v-ideographic"],["vMathematical","v-mathematical"],["vectorEffect","vector-effect"],["vertAdvY","vert-adv-y"],["vertOriginX","vert-origin-x"],["vertOriginY","vert-origin-y"],["wordSpacing","word-spacing"],["writingMode","writing-mode"],["xmlnsXlink","xmlns:xlink"],["xHeight","x-height"]]),e1=null;function Gc(n){return(n=n.target||n.srcElement||window).correspondingUseElement&&(n=n.correspondingUseElement),3===n.nodeType?n.parentNode:n}var e2=null,e3=null;function Jc(n){var a=Jb(n);if(a&&(n=a.stateNode)){var i=Lb(n);switch(n=a.stateNode,a.type){case"input":if(oc(n,i.value,i.defaultValue,i.defaultValue,i.checked,i.defaultChecked,i.type,i.name),a=i.name,"radio"===i.type&&null!=a){for(i=n;i.parentNode;)i=i.parentNode;for(i=i.querySelectorAll('input[name="'+nc(""+a)+'"][type="radio"]'),a=0;a>=y,s-=y,ts=1<<32-ex(a)+s|i<k?(S=v,v=null):S=v.sibling;var C=r(a,v,o[k],s);if(null===C){null===v&&(v=S);break}n&&v&&null===C.alternate&&b(a,v),i=f(C,i,k),null===y?m=C:y.sibling=C,y=C,v=S}if(k===o.length)return c(a,v),ty&&nd(a,k),m;if(null===v){for(;kk?(S=v,v=null):S=v.sibling;var x=r(a,v,C.value,s);if(null===x){null===v&&(v=S);break}n&&v&&null===x.alternate&&b(a,v),i=f(x,i,k),null===y?m=x:y.sibling=x,y=x,v=S}if(C.done)return c(a,v),ty&&nd(a,k),m;if(null===v){for(;!C.done;k++,C=o.next())null!==(C=w(a,C.value,s))&&(i=f(C,i,k),null===y?m=C:y.sibling=C,y=C);return ty&&nd(a,k),m}for(v=d(a,v);!C.done;k++,C=o.next())null!==(C=u(v,a,k,C.value,s))&&(n&&null!==C.alternate&&v.delete(null===C.key?k:C.key),i=f(C,i,k),null===y?m=C:y.sibling=C,y=C);return n&&v.forEach(function(n){return b(a,n)}),ty&&nd(a,k),m}function U(n,a,i,o){if("object"==typeof i&&null!==i&&i.type===L&&null===i.key&&(i=i.props.children),"object"==typeof i&&null!==i){switch(i.$$typeof){case N:e:{for(var s=i.key,m=a;null!==m;){if(m.key===s){if((s=i.type)===L){if(7===m.tag){c(n,m.sibling),(a=e(m,i.props.children)).return=n,n=a;break e}}else if(m.elementType===s||"object"==typeof s&&null!==s&&s.$$typeof===H&&ve(s)===m.type){c(n,m.sibling),(a=e(m,i.props)).ref=te(n,m,i),a.return=n,n=a;break e}c(n,m);break}b(n,m),m=m.sibling}i.type===L?((a=Be(i.props.children,n.mode,o,i.key)).return=n,n=a):((o=ze(i.type,i.key,i.props,null,null,n.mode,o)).ref=te(n,a,i),o.return=n,n=o)}return g(n);case j:e:{for(m=i.key;null!==a;){if(a.key===m){if(4===a.tag&&a.stateNode.containerInfo===i.containerInfo&&a.stateNode.implementation===i.implementation){c(n,a.sibling),(a=e(a,i.children||[])).return=n,n=a;break e}c(n,a);break}b(n,a),a=a.sibling}(a=Ae(i,n.mode,o)).return=n,n=a}return g(n);case H:return V(n,a,(m=i._init)(i._payload),o)}if(eK(i))return z(n,a,i,o);if(Da(i))return B(n,a,i,o);if("function"==typeof i.then)return U(n,a,se(i),o);if(i.$$typeof===F||i.$$typeof===O)return U(n,a,Ce(n,i,o),o);ue(n,i)}return"string"==typeof i&&""!==i||"number"==typeof i?(i=""+i,null!==a&&6===a.tag?(c(n,a.sibling),(a=e(a,i)).return=n):(c(n,a),(a=ye(i,n.mode,o)).return=n),g(n=a)):c(n,a)}function V(n,a,i,o){return tL=0,n=U(n,a,i,o),tT=null,n}return V}var t_=we(!0),tD=we(!1),tM=ka(null),tR=ka(0);function He(n,a){E(tR,n=n0),E(tM,a),n0=n|a.baseLanes}function Je(){E(tR,n0),E(tM,tM.current)}function Ke(){n0=tR.current,D(tM),D(tR)}var tF=ka(null),tO=null;function Ne(n){var a=n.alternate;E(tA,1&tA.current),E(tF,n),null===tO&&(null===a||null!==tM.current?tO=n:null!==a.memoizedState&&(tO=n))}function Pe(n){if(22===n.tag){if(E(tA,tA.current),E(tF,n),null===tO){var a=n.alternate;null!==a&&null!==a.memoizedState&&(tO=n)}}else Qe(n)}function Qe(){E(tA,tA.current),E(tF,tF.current)}function Re(n){D(tF),tO===n&&(tO=null),D(tA)}var tA=ka(0);function Se(n){for(var a=n;null!==a;){if(13===a.tag){var i=a.memoizedState;if(null!==i&&(null===(i=i.dehydrated)||"$?"===i.data||"$!"===i.data))return a}else if(19===a.tag&&void 0!==a.memoizedProps.revealOrder){if(0!=(128&a.flags))return a}else if(null!==a.child){a.child.return=a,a=a.child;continue}if(a===n)break;for(;null===a.sibling;){if(null===a.return||a.return===n)return null;a=a.return}a.sibling.return=a.return,a=a.sibling}return null}var tI=null,tU=null,tB=!1,tW=!1,tQ=!1,t$=0;function Ze(n){n!==tU&&null===n.next&&(null===tU?tI=tU=n:tU=tU.next=n),tW=!0,tB||(tB=!0,$e(af))}function bf(n){if(!tQ&&tW){var a=null;tQ=!0;do for(var i=!1,o=tI;null!==o;){if(!n||0===o.tag){var s=nK,m=jb(o,o===nH?s:0);if(0!=(3&m))try{if(i=!0,s=o,0!=(6&nq))throw Error(t(327));if(!cf()){var y=df(s,m);if(0!==s.tag&&2===y){var v=m,k=lb(s,v);0!==k&&(m=k,y=ef(s,v,k))}if(1===y)throw v=n2,gf(s,0),hf(s,m,0),Ze(s),v;6===y?hf(s,m,0):(s.finishedWork=s.current.alternate,s.finishedLanes=m,jf(s,n7,rt,n8))}Ze(s)}catch(n){null===a?a=[n]:a.push(n)}}o=o.next}while(i);if(tQ=!1,null!==a){if(1m?m:8;var y=tZ.transition;tZ.transition={},Mg(n,!1,a,i);try{var v=s();if(null!==v&&"object"==typeof v&&"function"==typeof v.then){var k=wf(v,o);Ng(n,a,k)}else{var S=zf(v,o);Ng(n,a,S)}}catch(i){Ng(n,a,{then:function(){},status:"rejected",reason:i})}finally{eL=m,tZ.transition=y}}function Og(n,a,i,o){if(5!==n.tag)throw Error(t(476));if(null===n.memoizedState){var s={pending:null,lanes:0,dispatch:null,lastRenderedReducer:cg,lastRenderedState:C},m=s;s={memoizedState:C,baseState:C,baseQueue:null,queue:s,next:null},n.memoizedState=s;var y=n.alternate;null!==y&&(y.memoizedState=s)}else m=n.memoizedState.queue;Lg(n,m,a,C,function(){return i(o)})}function Pg(){var n=bg(ei);return null!==n?n:C}function Qg(){return Zf().memoizedState}function Rg(){return Zf().memoizedState}function Sg(n){for(var a=n.return;null!==a;){switch(a.tag){case 24:case 3:var i=Tg(a),o=ae(a,n=$d(i),i);null!==o&&(pg(o,a,i),be(o,a,i)),a={cache:Ug()},n.payload=a;return}a=a.return}}function Vg(n,a,i){var o=Tg(n);i={lane:o,revertLane:0,action:i,hasEagerState:!1,eagerState:null,next:null},tg(n)?Wg(a,i):null!==(i=Sd(n,a,i,o))&&(pg(i,n,o),Xg(i,a,o))}function Ng(n,a,i){var o=Tg(n),s={lane:o,revertLane:0,action:i,hasEagerState:!1,eagerState:null,next:null};if(tg(n))Wg(a,s);else{var m=n.alternate;if(0===n.lanes&&(null===m||0===m.lanes)&&null!==(m=a.lastRenderedReducer))try{var y=a.lastRenderedState,v=m(y,i);if(s.hasEagerState=!0,s.eagerState=v,e7(v,y)){Rd(n,a,s,0),null===nH&&Pd();return}}catch(n){}finally{}null!==(i=Sd(n,a,s,o))&&(pg(i,n,o),Xg(i,a,o))}}function Mg(n,a,i,o){if(o={lane:2,revertLane:sf(),action:o,hasEagerState:!1,eagerState:null,next:null},tg(n)){if(a)throw Error(t(479))}else null!==(a=Sd(n,i,o,2))&&pg(a,n,2)}function tg(n){var a=n.alternate;return n===tX||null!==a&&a===tX}function Wg(n,a){t1=t0=!0;var i=n.pending;null===i?a.next=a:(a.next=i.next,i.next=a),n.pending=a}function Xg(n,a,i){if(0!=(4194176&i)){var o=a.lanes;o&=n.pendingLanes,i|=o,a.lanes=i,rb(n,i)}}rE=function(){return{lastEffect:null,events:null,stores:null}};var t5={readContext:bg,use:ag,useCallback:Kf,useContext:Kf,useEffect:Kf,useImperativeHandle:Kf,useInsertionEffect:Kf,useLayoutEffect:Kf,useMemo:Kf,useReducer:Kf,useRef:Kf,useState:Kf,useDebugValue:Kf,useDeferredValue:Kf,useTransition:Kf,useSyncExternalStore:Kf,useId:Kf};t5.useCacheRefresh=Kf,t5.useHostTransitionStatus=Kf,t5.useFormState=Kf,t5.useOptimistic=Kf;var t7={readContext:bg,use:ag,useCallback:function(n,a){return Yf().memoizedState=[n,void 0===a?null:a],n},useContext:bg,useEffect:Cg,useImperativeHandle:function(n,a,i){i=null!=i?i.concat([n]):null,Ag(4194308,4,Fg.bind(null,a,n),i)},useLayoutEffect:function(n,a){return Ag(4194308,4,n,a)},useInsertionEffect:function(n,a){Ag(4,2,n,a)},useMemo:function(n,a){var i=Yf();return a=void 0===a?null:a,t2&&n(),n=n(),i.memoizedState=[n,a],n},useReducer:function(n,a,i){var o=Yf();return a=void 0!==i?i(a):a,o.memoizedState=o.baseState=a,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:a},o.queue=n,n=n.dispatch=Vg.bind(null,tX,n),[o.memoizedState,n]},useRef:function(n){return n={current:n},Yf().memoizedState=n},useState:function(n){var a=(n=qg(n)).queue,i=Ng.bind(null,tX,a);return a.dispatch=i,[n.memoizedState,i]},useDebugValue:Hg,useDeferredValue:function(n){return Yf().memoizedState=n,n},useTransition:function(){var n=qg(!1);return n=Lg.bind(null,tX,n.queue,!0,!1),Yf().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,a,i){var o=tX,s=Yf();if(ty){if(void 0===i)throw Error(t(407));i=i()}else{if(i=a(),null===nH)throw Error(t(349));0!=(60&nK)||mg(o,a,i)}s.memoizedState=i;var m={value:i,getSnapshot:a};return s.queue=m,Cg(jg.bind(null,o,m,n),[n]),o.flags|=2048,kg(9,lg.bind(null,o,m,i,a),{destroy:void 0},null),i},useId:function(){var n=Yf(),a=nH.identifierPrefix;if(ty){var i=tf,o=ts;a=":"+a+"R"+(i=(o&~(1<<32-ex(o)-1)).toString(32)+i),0<(i=t3++)&&(a+="H"+i.toString(32)),a+=":"}else a=":"+a+"r"+(i=t8++).toString(32)+":";return n.memoizedState=a},useCacheRefresh:function(){return Yf().memoizedState=Sg.bind(null,tX)}};t7.useHostTransitionStatus=Pg,t7.useFormState=function(n,a){if(ty){var i=nH.formState;null!==i&&Fd()&&(a=i[0])}var o={status:"fulfilled",value:a,then:function(){}};(i=Yf()).memoizedState=i.baseState=o,o={pending:null,lanes:0,dispatch:null,lastRenderedReducer:wg,lastRenderedState:o},i.queue=o,i=Ng.bind(null,tX,o),o.dispatch=i;var s={state:a,dispatch:null,action:n,pending:null};return(o=Yf()).queue=s,i=sg.bind(null,tX,s,i),s.dispatch=i,o.memoizedState=n,[a,i]},t7.useOptimistic=function(n){var a=Yf();a.memoizedState=a.baseState=n;var i={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return a.queue=i,a=Mg.bind(null,tX,!0,i),i.dispatch=a,[n,a]};var t9={readContext:bg,use:ag,useCallback:Ig,useContext:bg,useEffect:ig,useImperativeHandle:Gg,useInsertionEffect:Dg,useLayoutEffect:Eg,useMemo:Jg,useReducer:dg,useRef:zg,useState:function(){return dg(cg)},useDebugValue:Hg,useDeferredValue:function(n){return Kg(Zf(),tG.memoizedState,n)},useTransition:function(){var n=dg(cg)[0],a=Zf().memoizedState;return["boolean"==typeof n?n:Uf(n),a]},useSyncExternalStore:hg,useId:Qg};t9.useCacheRefresh=Rg,t9.useHostTransitionStatus=Pg,t9.useFormState=function(n){return xg(Zf(),tG,n)},t9.useOptimistic=function(n,a){return rg(Zf(),tG,n,a)};var nt={readContext:bg,use:ag,useCallback:Ig,useContext:bg,useEffect:ig,useImperativeHandle:Gg,useInsertionEffect:Dg,useLayoutEffect:Eg,useMemo:Jg,useReducer:gg,useRef:zg,useState:function(){return gg(cg)},useDebugValue:Hg,useDeferredValue:function(n){var a=Zf();return null===tG?(a.memoizedState=n,n):Kg(a,tG.memoizedState,n)},useTransition:function(){var n=gg(cg)[0],a=Zf().memoizedState;return["boolean"==typeof n?n:Uf(n),a]},useSyncExternalStore:hg,useId:Qg};function Yg(n,a){if(n&&n.defaultProps)for(var i in a=v({},a),n=n.defaultProps)void 0===a[i]&&(a[i]=n[i]);return a}function Zg(n,a,i,o){i=null==(i=i(o,a=n.memoizedState))?a:v({},a,i),n.memoizedState=i,0===n.lanes&&(n.updateQueue.baseState=i)}nt.useCacheRefresh=Rg,nt.useHostTransitionStatus=Pg,nt.useFormState=function(n){var a=Zf(),i=tG;if(null!==i)return xg(a,i,n);a=Uf(a.memoizedState);var o=(i=Zf()).queue.dispatch;return i.memoizedState=n,[a,o]},nt.useOptimistic=function(n,a){var i=Zf();return null!==tG?rg(i,tG,n,a):(i.baseState=n,[n,i.queue.dispatch])};var nr={isMounted:function(n){return!!(n=n._reactInternals)&&Mc(n)===n},enqueueSetState:function(n,a,i){var o=Tg(n=n._reactInternals),s=$d(o);s.payload=a,null!=i&&(s.callback=i),null!==(a=ae(n,s,o))&&(pg(a,n,o),be(a,n,o))},enqueueReplaceState:function(n,a,i){var o=Tg(n=n._reactInternals),s=$d(o);s.tag=1,s.payload=a,null!=i&&(s.callback=i),null!==(a=ae(n,s,o))&&(pg(a,n,o),be(a,n,o))},enqueueForceUpdate:function(n,a){var i=Tg(n=n._reactInternals),o=$d(i);o.tag=2,null!=a&&(o.callback=a),null!==(a=ae(n,o,i))&&(pg(a,n,i),be(a,n,i))}};function ah(n,a,i,o,s,m,y){return"function"==typeof(n=n.stateNode).shouldComponentUpdate?n.shouldComponentUpdate(o,m,y):!a.prototype||!a.prototype.isPureReactComponent||!he(i,o)||!he(s,m)}function bh(n,a,i){var o=!1,s=e4,m=a.contextType;return"object"==typeof m&&null!==m?m=bg(m):(s=Xc(a)?e5:e6.current,m=(o=null!=(o=a.contextTypes))?Wc(n,s):e4),a=new a(i,m),n.memoizedState=null!==a.state&&void 0!==a.state?a.state:null,a.updater=nr,n.stateNode=a,a._reactInternals=n,o&&((n=n.stateNode).__reactInternalMemoizedUnmaskedChildContext=s,n.__reactInternalMemoizedMaskedChildContext=m),a}function ch(n,a,i,o){n=a.state,"function"==typeof a.componentWillReceiveProps&&a.componentWillReceiveProps(i,o),"function"==typeof a.UNSAFE_componentWillReceiveProps&&a.UNSAFE_componentWillReceiveProps(i,o),a.state!==n&&nr.enqueueReplaceState(a,a.state,null)}function dh(n,a,i,o){var s=n.stateNode;s.props=i,s.state=n.memoizedState,s.refs={},Yd(n);var m=a.contextType;"object"==typeof m&&null!==m?s.context=bg(m):(m=Xc(a)?e5:e6.current,s.context=Wc(n,m)),s.state=n.memoizedState,"function"==typeof(m=a.getDerivedStateFromProps)&&(Zg(n,a,m,i),s.state=n.memoizedState),"function"==typeof a.getDerivedStateFromProps||"function"==typeof s.getSnapshotBeforeUpdate||"function"!=typeof s.UNSAFE_componentWillMount&&"function"!=typeof s.componentWillMount||(a=s.state,"function"==typeof s.componentWillMount&&s.componentWillMount(),"function"==typeof s.UNSAFE_componentWillMount&&s.UNSAFE_componentWillMount(),a!==s.state&&nr.enqueueReplaceState(s,s.state,null),de(n,i,s,o),s.state=n.memoizedState),"function"==typeof s.componentDidMount&&(n.flags|=4194308)}function eh(n,a){try{var i="",o=a;do i+=dc(o),o=o.return;while(o);var s=i}catch(n){s="\nError generating stack: "+n.message+"\n"+n.stack}return{value:n,source:a,stack:s,digest:null}}function fh(n,a,i){return{value:n,source:null,stack:null!=i?i:null,digest:null!=a?a:null}}function gh(n,a){try{console.error(a.value)}catch(n){setTimeout(function(){throw n})}}function hh(n,a,i){(i=$d(i)).tag=3,i.payload={element:null};var o=a.value;return i.callback=function(){rn||(rn=!0,rr=o),gh(n,a)},i}function kh(n,a,i){(i=$d(i)).tag=3;var o=n.type.getDerivedStateFromError;if("function"==typeof o){var s=a.value;i.payload=function(){return o(s)},i.callback=function(){gh(n,a)}}var m=n.stateNode;return null!==m&&"function"==typeof m.componentDidCatch&&(i.callback=function(){gh(n,a),"function"!=typeof o&&(null===ra?ra=new Set([this]):ra.add(this));var i=a.stack;this.componentDidCatch(a.value,{componentStack:null!==i?i:""})}),i}function mh(n,a,i,o,s){return 0==(1&n.mode)?n===a?n.flags|=65536:(n.flags|=128,i.flags|=131072,i.flags&=-52805,1===i.tag&&(null===i.alternate?i.tag=17:((a=$d(2)).tag=2,ae(i,a,2))),i.lanes|=2):(n.flags|=65536,n.lanes=s),n}function nh(n,a,i,o,s){if(i.flags|=32768,null!==o&&"object"==typeof o&&"function"==typeof o.then){var m=i.tag;if(0!=(1&i.mode)||0!==m&&11!==m&&15!==m||((m=i.alternate)?(i.updateQueue=m.updateQueue,i.memoizedState=m.memoizedState,i.lanes=m.lanes):(i.updateQueue=null,i.memoizedState=null)),null!==(m=tF.current)){switch(m.tag){case 13:1&i.mode&&(null===tO?oh():null===m.alternate&&0===n1&&(n1=3)),m.flags&=-257,mh(m,a,i,n,s),o===tN?m.flags|=16384:(null===(a=m.updateQueue)?m.updateQueue=new Set([o]):a.add(o),1&m.mode&&qh(n,o,s));return;case 22:if(1&m.mode){m.flags|=65536,o===tN?m.flags|=16384:(null===(a=m.updateQueue)?(a={transitions:null,markerInstances:null,retryQueue:new Set([o])},m.updateQueue=a):null===(i=a.retryQueue)?a.retryQueue=new Set([o]):i.add(o),qh(n,o,s));return}}throw Error(t(435,m.tag))}if(1===n.tag){qh(n,o,s),oh();return}o=Error(t(426))}if(ty&&1&i.mode&&null!==(m=tF.current)){0==(65536&m.flags)&&(m.flags|=256),mh(m,a,i,n,s),Ld(eh(o,i));return}n=o=eh(o,i),4!==n1&&(n1=2),null===n5?n5=[n]:n5.push(n),n=a;do{switch(n.tag){case 3:n.flags|=65536,s&=-s,n.lanes|=s,s=hh(n,o,s),ce(n,s);return;case 1:if(a=o,i=n.type,m=n.stateNode,0==(128&n.flags)&&("function"==typeof i.getDerivedStateFromError||null!==m&&"function"==typeof m.componentDidCatch&&(null===ra||!ra.has(m)))){n.flags|=65536,s&=-s,n.lanes|=s,s=kh(n,a,s),ce(n,s);return}}n=n.return}while(null!==n)}var nl=k.ReactCurrentOwner,na=Error(t(461)),ni=!1;function uh(n,a,i,o){a.child=null===n?tD(a,null,i,o):t_(a,n.child,i,o)}function vh(n,a,i,o,s){i=i.render;var m=a.ref;return(wh(a,s),o=Mf(n,a,i,o,m,s),i=Vf(),null===n||ni)?(ty&&i&&pd(a),a.flags|=1,uh(n,a,o,s),a.child):(Wf(n,a,s),xh(n,a,s))}function yh(n,a,i,o,s){if(null===n){var m=i.type;return"function"!=typeof m||zh(m)||void 0!==m.defaultProps||null!==i.compare||void 0!==i.defaultProps?((n=ze(i.type,null,o,null,a,a.mode,s)).ref=a.ref,n.return=a,a.child=n):(a.tag=15,a.type=m,Ah(n,a,m,o,s))}if(m=n.child,0==(n.lanes&s)){var y=m.memoizedProps;if((i=null!==(i=i.compare)?i:he)(y,o)&&n.ref===a.ref)return xh(n,a,s)}return a.flags|=1,(n=xe(m,o)).ref=a.ref,n.return=a,a.child=n}function Ah(n,a,i,o,s){if(null!==n){var m=n.memoizedProps;if(he(m,o)&&n.ref===a.ref){if(ni=!1,a.pendingProps=o=m,0==(n.lanes&s))return a.lanes=n.lanes,xh(n,a,s);0!=(131072&n.flags)&&(ni=!0)}}return Bh(n,a,i,o,s)}function Ch(n,a,i){var o=a.pendingProps,s=o.children,m=0!=(2&a.stateNode._pendingVisibility),y=null!==n?n.memoizedState:null;if(Dh(n,a),"hidden"===o.mode||m){if(0!=(128&a.flags)){if(i=null!==y?y.baseLanes|i:i,null!==n){for(s=0,o=a.child=n.child;null!==o;)s=s|o.lanes|o.childLanes,o=o.sibling;a.childLanes=s&~i}else a.childLanes=0,a.child=null;return Eh(n,a,i)}if(0==(1&a.mode))a.memoizedState={baseLanes:0,cachePool:null},null!==n&&Fh(a,null),Je(),Pe(a);else{if(0==(536870912&i))return a.lanes=a.childLanes=536870912,Eh(n,a,null!==y?y.baseLanes|i:i);a.memoizedState={baseLanes:0,cachePool:null},null!==n&&Fh(a,null!==y?y.cachePool:null),null!==y?He(a,y):Je(),Pe(a)}}else null!==y?(Fh(a,y.cachePool),He(a,y),Qe(a),a.memoizedState=null):(null!==n&&Fh(a,null),Je(),Qe(a));return uh(n,a,s,i),a.child}function Eh(n,a,i){var o=Gh();return o=null===o?null:{parent:nE._currentValue,pool:o},a.memoizedState={baseLanes:i,cachePool:o},null!==n&&Fh(a,null),Je(),Pe(a),null}function Dh(n,a){var i=a.ref;(null===n&&null!==i||null!==n&&n.ref!==i)&&(a.flags|=512,a.flags|=2097152)}function Bh(n,a,i,o,s){var m=Xc(i)?e5:e6.current;return(m=Wc(a,m),wh(a,s),i=Mf(n,a,i,o,m,s),o=Vf(),null===n||ni)?(ty&&o&&pd(a),a.flags|=1,uh(n,a,i,s),a.child):(Wf(n,a,s),xh(n,a,s))}function Hh(n,a,i,o,s,m){return(wh(a,m),i=Pf(a,o,i,s),Qf(),o=Vf(),null===n||ni)?(ty&&o&&pd(a),a.flags|=1,uh(n,a,i,m),a.child):(Wf(n,a,m),xh(n,a,m))}function Ih(n,a,i,o,s){if(Xc(i)){var m=!0;ad(a)}else m=!1;if(wh(a,s),null===a.stateNode)Jh(n,a),bh(a,i,o),dh(a,i,o,s),o=!0;else if(null===n){var y=a.stateNode,v=a.memoizedProps;y.props=v;var k=y.context,S=i.contextType;S="object"==typeof S&&null!==S?bg(S):Wc(a,S=Xc(i)?e5:e6.current);var C=i.getDerivedStateFromProps,x="function"==typeof C||"function"==typeof y.getSnapshotBeforeUpdate;x||"function"!=typeof y.UNSAFE_componentWillReceiveProps&&"function"!=typeof y.componentWillReceiveProps||(v!==o||k!==S)&&ch(a,y,o,S),tx=!1;var P=a.memoizedState;y.state=P,de(a,o,y,s),k=a.memoizedState,v!==o||P!==k||e8.current||tx?("function"==typeof C&&(Zg(a,i,C,o),k=a.memoizedState),(v=tx||ah(a,i,v,o,P,k,S))?(x||"function"!=typeof y.UNSAFE_componentWillMount&&"function"!=typeof y.componentWillMount||("function"==typeof y.componentWillMount&&y.componentWillMount(),"function"==typeof y.UNSAFE_componentWillMount&&y.UNSAFE_componentWillMount()),"function"==typeof y.componentDidMount&&(a.flags|=4194308)):("function"==typeof y.componentDidMount&&(a.flags|=4194308),a.memoizedProps=o,a.memoizedState=k),y.props=o,y.state=k,y.context=S,o=v):("function"==typeof y.componentDidMount&&(a.flags|=4194308),o=!1)}else{y=a.stateNode,Zd(n,a),v=a.memoizedProps,S=a.type===a.elementType?v:Yg(a.type,v),y.props=S,x=a.pendingProps,P=y.context,k="object"==typeof(k=i.contextType)&&null!==k?bg(k):Wc(a,k=Xc(i)?e5:e6.current);var N=i.getDerivedStateFromProps;(C="function"==typeof N||"function"==typeof y.getSnapshotBeforeUpdate)||"function"!=typeof y.UNSAFE_componentWillReceiveProps&&"function"!=typeof y.componentWillReceiveProps||(v!==x||P!==k)&&ch(a,y,o,k),tx=!1,P=a.memoizedState,y.state=P,de(a,o,y,s);var j=a.memoizedState;v!==x||P!==j||e8.current||tx?("function"==typeof N&&(Zg(a,i,N,o),j=a.memoizedState),(S=tx||ah(a,i,S,o,P,j,k)||!1)?(C||"function"!=typeof y.UNSAFE_componentWillUpdate&&"function"!=typeof y.componentWillUpdate||("function"==typeof y.componentWillUpdate&&y.componentWillUpdate(o,j,k),"function"==typeof y.UNSAFE_componentWillUpdate&&y.UNSAFE_componentWillUpdate(o,j,k)),"function"==typeof y.componentDidUpdate&&(a.flags|=4),"function"==typeof y.getSnapshotBeforeUpdate&&(a.flags|=1024)):("function"!=typeof y.componentDidUpdate||v===n.memoizedProps&&P===n.memoizedState||(a.flags|=4),"function"!=typeof y.getSnapshotBeforeUpdate||v===n.memoizedProps&&P===n.memoizedState||(a.flags|=1024),a.memoizedProps=o,a.memoizedState=j),y.props=o,y.state=j,y.context=k,o=S):("function"!=typeof y.componentDidUpdate||v===n.memoizedProps&&P===n.memoizedState||(a.flags|=4),"function"!=typeof y.getSnapshotBeforeUpdate||v===n.memoizedProps&&P===n.memoizedState||(a.flags|=1024),o=!1)}return Kh(n,a,i,o,m,s)}function Kh(n,a,i,o,s,m){Dh(n,a);var y=0!=(128&a.flags);if(!o&&!y)return s&&bd(a,i,!1),xh(n,a,m);o=a.stateNode,nl.current=a;var v=y&&"function"!=typeof i.getDerivedStateFromError?null:o.render();return a.flags|=1,null!==n&&y?(a.child=t_(a,n.child,null,m),a.child=t_(a,null,v,m)):uh(n,a,v,m),a.memoizedState=o.state,s&&bd(a,i,!0),a.child}function Lh(n){var a=n.stateNode;a.pendingContext?Zc(n,a.pendingContext,a.pendingContext!==a.context):a.context&&Zc(n,a.context,!1),Ja(n,a.containerInfo)}function Mh(n,a,i,o,s){return Kd(),Ld(s),a.flags|=256,uh(n,a,i,o),a.child}var nu={dehydrated:null,treeContext:null,retryLane:0};function Oh(n){return{baseLanes:n,cachePool:Ph()}}function Qh(n,a,i){var o,s=a.pendingProps,m=!1,y=0!=(128&a.flags);if((o=y)||(o=(null===n||null!==n.memoizedState)&&0!=(2&tA.current)),o&&(m=!0,a.flags&=-129),null===n){if(ty){if(m?Ne(a):Qe(a),ty&&((y=n=th)?Bd(a,y)||(Dd(a)&&Ed(),th=Cd(y),o=tp,th&&Bd(a,th)?td(o,y):(vd(tp,a),ty=!1,tp=a,th=n)):(Dd(a)&&Ed(),vd(tp,a),ty=!1,tp=a,th=n)),null!==(n=a.memoizedState)&&null!==(n=n.dehydrated))return 0==(1&a.mode)?a.lanes=2:"$!"===n.data?a.lanes=16:a.lanes=536870912,null;Re(a)}return(y=s.children,n=s.fallback,m)?(Qe(a),s=a.mode,m=a.child,y={mode:"hidden",children:y},0==(1&s)&&null!==m?(m.childLanes=0,m.pendingProps=y):m=Rh(y,s,0,null),n=Be(n,s,i,null),m.return=a,n.return=a,m.sibling=n,a.child=m,a.child.memoizedState=Oh(i),a.memoizedState=nu,n):(Ne(a),Sh(a,y))}if(null!==(o=n.memoizedState)){var v=o.dehydrated;if(null!==v)return Th(n,a,y,s,v,o,i)}if(m){Qe(a),m=s.fallback,y=a.mode,v=(o=n.child).sibling;var k={mode:"hidden",children:s.children};return 0==(1&y)&&a.child!==o?((s=a.child).childLanes=0,s.pendingProps=k,a.deletions=null):(s=xe(o,k)).subtreeFlags=31457280&o.subtreeFlags,null!==v?m=xe(v,m):(m=Be(m,y,i,null),m.flags|=2),m.return=a,s.return=a,s.sibling=m,a.child=s,s=m,m=a.child,null===(y=n.child.memoizedState)?y=Oh(i):(null!==(o=y.cachePool)?(v=nE._currentValue,o=o.parent!==v?{parent:v,pool:v}:o):o=Ph(),y={baseLanes:y.baseLanes|i,cachePool:o}),m.memoizedState=y,m.childLanes=n.childLanes&~i,a.memoizedState=nu,s}return Ne(a),n=(m=n.child).sibling,s=xe(m,{mode:"visible",children:s.children}),0==(1&a.mode)&&(s.lanes=i),s.return=a,s.sibling=null,null!==n&&(null===(i=a.deletions)?(a.deletions=[n],a.flags|=16):i.push(n)),a.child=s,a.memoizedState=null,s}function Sh(n,a){return(a=Rh({mode:"visible",children:a},n.mode,0,null)).return=n,n.child=a}function Uh(n,a,i,o){return null!==o&&Ld(o),t_(a,n.child,null,i),n=Sh(a,a.pendingProps.children),n.flags|=2,a.memoizedState=null,n}function Th(n,a,i,o,s,m,y){if(i)return 256&a.flags?(Ne(a),a.flags&=-257,Uh(n,a,y,s=fh(Error(t(422))))):null!==a.memoizedState?(Qe(a),a.child=n.child,a.flags|=128,null):(Qe(a),s=o.fallback,m=a.mode,o=Rh({mode:"visible",children:o.children},m,0,null),s=Be(s,m,y,null),s.flags|=2,o.return=a,s.return=a,o.sibling=s,a.child=o,0!=(1&a.mode)&&t_(a,n.child,null,y),a.child.memoizedState=Oh(y),a.memoizedState=nu,s);if(Ne(a),0==(1&a.mode))return Uh(n,a,y,null);if("$!"===s.data){if(s=s.nextSibling&&s.nextSibling.dataset)var v=s.dgst;return s=v,(o=Error(t(419))).digest=s,Uh(n,a,y,s=fh(o,s,void 0))}if(v=0!=(y&n.childLanes),ni||v){if(null!==(o=nH)){switch(y&-y){case 2:v=1;break;case 8:v=4;break;case 32:v=16;break;case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:v=64;break;case 268435456:v=134217728;break;default:v=0}if(0!==(v=0!=(v&(o.suspendedLanes|y))?0:v)&&v!==m.retryLane)throw m.retryLane=v,Ud(n,v),pg(o,n,v),na}return"$?"!==s.data&&oh(),Uh(n,a,y,null)}return"$?"===s.data?(a.flags|=128,a.child=n.child,a=Vh.bind(null,n),s._reactRetry=a,null):(n=m.treeContext,th=yd(s.nextSibling),tp=a,ty=!0,tv=null,tw=!1,null!==n&&(tl[ta++]=ts,tl[ta++]=tf,tl[ta++]=tu,ts=n.id,tf=n.overflow,tu=a),a=Sh(a,o.children),a.flags|=4096,a)}function Wh(n,a,i){n.lanes|=a;var o=n.alternate;null!==o&&(o.lanes|=a),Xh(n.return,a,i)}function Yh(n,a,i,o,s){var m=n.memoizedState;null===m?n.memoizedState={isBackwards:a,rendering:null,renderingStartTime:0,last:o,tail:i,tailMode:s}:(m.isBackwards=a,m.rendering=null,m.renderingStartTime=0,m.last=o,m.tail=i,m.tailMode=s)}function Zh(n,a,i){var o=a.pendingProps,s=o.revealOrder,m=o.tail;if(uh(n,a,o.children,i),0!=(2&(o=tA.current)))o=1&o|2,a.flags|=128;else{if(null!==n&&0!=(128&n.flags))e:for(n=a.child;null!==n;){if(13===n.tag)null!==n.memoizedState&&Wh(n,i,a);else if(19===n.tag)Wh(n,i,a);else if(null!==n.child){n.child.return=n,n=n.child;continue}if(n===a)break;for(;null===n.sibling;){if(null===n.return||n.return===a)break e;n=n.return}n.sibling.return=n.return,n=n.sibling}o&=1}if(E(tA,o),0==(1&a.mode))a.memoizedState=null;else switch(s){case"forwards":for(s=null,i=a.child;null!==i;)null!==(n=i.alternate)&&null===Se(n)&&(s=i),i=i.sibling;null===(i=s)?(s=a.child,a.child=null):(s=i.sibling,i.sibling=null),Yh(a,!1,s,i,m);break;case"backwards":for(i=null,s=a.child,a.child=null;null!==s;){if(null!==(n=s.alternate)&&null===Se(n)){a.child=s;break}n=s.sibling,s.sibling=i,i=s,s=n}Yh(a,!0,i,null,m);break;case"together":Yh(a,!1,null,null,void 0);break;default:a.memoizedState=null}return a.child}function Jh(n,a){0==(1&a.mode)&&null!==n&&(n.alternate=null,a.alternate=null,a.flags|=2)}function xh(n,a,i){if(null!==n&&(a.dependencies=n.dependencies),n3|=a.lanes,0==(i&a.childLanes))return null;if(null!==n&&a.child!==n.child)throw Error(t(153));if(null!==a.child){for(i=xe(n=a.child,n.pendingProps),a.child=i,i.return=a;null!==n.sibling;)n=n.sibling,(i=i.sibling=xe(n,n.pendingProps)).return=a;i.sibling=null}return a.child}function $h(n,a,i){switch(a.tag){case 3:Lh(a),ai(a,nE,n.memoizedState.cache),Kd();break;case 27:case 5:Na(a);break;case 1:Xc(a.type)&&ad(a);break;case 4:Ja(a,a.stateNode.containerInfo);break;case 10:ai(a,a.type._context,a.memoizedProps.value);break;case 13:var o=a.memoizedState;if(null!==o){if(null!==o.dehydrated)return Ne(a),a.flags|=128,null;if(0!=(i&a.child.childLanes))return Qh(n,a,i);return Ne(a),null!==(n=xh(n,a,i))?n.sibling:null}Ne(a);break;case 19:if(o=0!=(i&a.childLanes),0!=(128&n.flags)){if(o)return Zh(n,a,i);a.flags|=128}var s=a.memoizedState;if(null!==s&&(s.rendering=null,s.tail=null,s.lastEffect=null),E(tA,tA.current),!o)return null;break;case 22:case 23:return a.lanes=0,Ch(n,a,i);case 24:ai(a,nE,n.memoizedState.cache)}return xh(n,a,i)}var ns=ka(null),np=null,ny=null,nv=null;function fi(){nv=ny=np=null}function ai(n,a,i){E(ns,a._currentValue),a._currentValue=i}function gi(n){n._currentValue=ns.current,D(ns)}function Xh(n,a,i){for(;null!==n;){var o=n.alternate;if((n.childLanes&a)!==a?(n.childLanes|=a,null!==o&&(o.childLanes|=a)):null!==o&&(o.childLanes&a)!==a&&(o.childLanes|=a),n===i)break;n=n.return}}function hi(n,a,i){var o=n.child;for(null!==o&&(o.return=n);null!==o;){var s=o.dependencies;if(null!==s)for(var m=o.child,y=s.firstContext;null!==y;){if(y.context===a){if(1===o.tag){(y=$d(i&-i)).tag=2;var v=o.updateQueue;if(null!==v){var k=(v=v.shared).pending;null===k?y.next=y:(y.next=k.next,k.next=y),v.pending=y}}o.lanes|=i,null!==(y=o.alternate)&&(y.lanes|=i),Xh(o.return,i,n),s.lanes|=i;break}y=y.next}else if(10===o.tag)m=o.type===n.type?null:o.child;else if(18===o.tag){if(null===(m=o.return))throw Error(t(341));m.lanes|=i,null!==(s=m.alternate)&&(s.lanes|=i),Xh(m,i,n),m=o.sibling}else m=o.child;if(null!==m)m.return=o;else for(m=o;null!==m;){if(m===n){m=null;break}if(null!==(o=m.sibling)){o.return=m.return,m=o;break}m=m.return}o=m}}function wh(n,a){np=n,nv=ny=null,null!==(n=n.dependencies)&&null!==n.firstContext&&(0!=(n.lanes&a)&&(ni=!0),n.firstContext=null)}function bg(n){return ii(np,n)}function Ce(n,a,i){return null===np&&wh(n,i),ii(n,a)}function ii(n,a){var i=a._currentValue;if(nv!==a){if(a={context:a,memoizedValue:i,next:null},null===ny){if(null===n)throw Error(t(308));ny=a,n.dependencies={lanes:0,firstContext:a}}else ny=ny.next=a}return i}var nk="undefined"!=typeof AbortController?AbortController:function(){var n=[],a=this.signal={aborted:!1,addEventListener:function(a,i){n.push(i)}};this.abort=function(){a.aborted=!0,n.forEach(function(n){return n()})}},nw=m.unstable_scheduleCallback,nS=m.unstable_NormalPriority,nE={$$typeof:F,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0,_defaultValue:null,_globalName:null};function Ug(){return{controller:new nk,data:new Map,refCount:0}}function mi(n){n.refCount--,0===n.refCount&&nw(nS,function(){n.controller.abort()})}var nC=k.ReactCurrentBatchConfig,nx=ka(null);function Gh(){var n=nx.current;return null!==n?n:nH.pooledCache}function Fh(n,a){null===a?E(nx,nx.current):E(nx,a.pool)}function Ph(){var n=Gh();return null===n?null:{parent:nE._currentValue,pool:n}}function pi(n){n.flags|=4}function qi(n){n.flags|=2097664}function ri(n,a){if("stylesheet"!==a.type||0!=(4&a.state.loading))n.flags&=-16777217;else if(n.flags|=16777216,0==(42&nK)&&!(a="stylesheet"!==a.type||0!=(3&a.state.loading))){if(si())n.flags|=8192;else throw tj=tN,tP}}function ti(n,a){null!==a?n.flags|=4:16384&n.flags&&(a=22!==n.tag?mb():536870912,n.lanes|=a)}function ui(n,a){if(!ty)switch(n.tailMode){case"hidden":a=n.tail;for(var i=null;null!==a;)null!==a.alternate&&(i=a),a=a.sibling;null===i?n.tail=null:i.sibling=null;break;case"collapsed":i=n.tail;for(var o=null;null!==i;)null!==i.alternate&&(o=i),i=i.sibling;null===o?a||null===n.tail?n.tail=null:n.tail.sibling=null:o.sibling=null}}function T(n){var a=null!==n.alternate&&n.alternate.child===n.child,i=0,o=0;if(a)for(var s=n.child;null!==s;)i|=s.lanes|s.childLanes,o|=31457280&s.subtreeFlags,o|=31457280&s.flags,s.return=n,s=s.sibling;else for(s=n.child;null!==s;)i|=s.lanes|s.childLanes,o|=s.subtreeFlags,o|=s.flags,s.return=n,s=s.sibling;return n.subtreeFlags|=o,n.childLanes=i,a}function vi(n,a,i){var o=a.pendingProps;switch(qd(a),a.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return T(a),null;case 1:case 17:return Xc(a.type)&&Yc(),T(a),null;case 3:return i=a.stateNode,o=null,null!==n&&(o=n.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),gi(nE),Ma(),D(e8),D(e6),i.pendingContext&&(i.context=i.pendingContext,i.pendingContext=null),(null===n||null===n.child)&&(Hd(a)?pi(a):null===n||n.memoizedState.isDehydrated&&0==(256&a.flags)||(a.flags|=1024,null!==tv&&(wi(tv),tv=null))),T(a),null;case 26:if(i=a.memoizedState,null===n)pi(a),null!==a.ref&&qi(a),null!==i?(T(a),ri(a,i)):(T(a),a.flags&=-16777217);else{var s=n.memoizedState;i!==s&&pi(a),n.ref!==a.ref&&qi(a),null!==i?(T(a),i===s?a.flags&=-16777217:ri(a,i)):(n.memoizedProps!==o&&pi(a),T(a),a.flags&=-16777217)}return null;case 27:if(Oa(a),i=er.current,s=a.type,null!==n&&null!=a.stateNode)n.memoizedProps!==o&&pi(a),n.ref!==a.ref&&qi(a);else{if(!o){if(null===a.stateNode)throw Error(t(166));return T(a),null}n=et.current,Hd(a)?xi(a.stateNode,a.type,a.memoizedProps,n,a):(n=yi(s,o,i),a.stateNode=n,pi(a)),null!==a.ref&&qi(a)}return T(a),null;case 5:if(Oa(a),i=a.type,null!==n&&null!=a.stateNode)n.memoizedProps!==o&&pi(a),n.ref!==a.ref&&qi(a);else{if(!o){if(null===a.stateNode)throw Error(t(166));return T(a),null}if(n=et.current,Hd(a))xi(a.stateNode,a.type,a.memoizedProps,n,a);else{switch(s=zi(er.current),n){case 1:n=s.createElementNS("http://www.w3.org/2000/svg",i);break;case 2:n=s.createElementNS("http://www.w3.org/1998/Math/MathML",i);break;default:switch(i){case"svg":n=s.createElementNS("http://www.w3.org/2000/svg",i);break;case"math":n=s.createElementNS("http://www.w3.org/1998/Math/MathML",i);break;case"script":(n=s.createElement("div")).innerHTML="",n=n.removeChild(n.firstChild);break;case"select":n="string"==typeof o.is?s.createElement("select",{is:o.is}):s.createElement("select"),o.multiple?n.multiple=!0:o.size&&(n.size=o.size);break;default:n="string"==typeof o.is?s.createElement(i,{is:o.is}):s.createElement(i)}}n[eM]=a,n[eR]=o;e:for(s=a.child;null!==s;){if(5===s.tag||6===s.tag)n.appendChild(s.stateNode);else if(4!==s.tag&&27!==s.tag&&null!==s.child){s.child.return=s,s=s.child;continue}if(s===a)break;for(;null===s.sibling;){if(null===s.return||s.return===a)break e;s=s.return}s.sibling.return=s.return,s=s.sibling}switch(a.stateNode=n,Ai(n,i,o),i){case"button":case"input":case"select":case"textarea":n=!!o.autoFocus;break;case"img":n=!0;break;default:n=!1}n&&pi(a)}null!==a.ref&&qi(a)}return T(a),a.flags&=-16777217,null;case 6:if(n&&null!=a.stateNode)n.memoizedProps!==o&&pi(a);else{if("string"!=typeof o&&null===a.stateNode)throw Error(t(166));if(n=er.current,Hd(a)){e:{if(n=a.stateNode,i=a.memoizedProps,n[eM]=a,(o=n.nodeValue!==i)&&null!==(s=tp))switch(s.tag){case 3:if(s=0!=(1&s.mode),Bi(n.nodeValue,i,s),s){n=!1;break e}break;case 27:case 5:var m=0!=(1&s.mode);if(!0!==s.memoizedProps.suppressHydrationWarning&&Bi(n.nodeValue,i,m),m){n=!1;break e}}n=o}n&&pi(a)}else(n=zi(n).createTextNode(o))[eM]=a,a.stateNode=n}return T(a),null;case 13:if(Re(a),o=a.memoizedState,null===n||null!==n.memoizedState&&null!==n.memoizedState.dehydrated){if(ty&&null!==th&&0!=(1&a.mode)&&0==(128&a.flags))Jd(),Kd(),a.flags|=384,s=!1;else if(s=Hd(a),null!==o&&null!==o.dehydrated){if(null===n){if(!s)throw Error(t(318));if(!(s=null!==(s=a.memoizedState)?s.dehydrated:null))throw Error(t(317));s[eM]=a}else Kd(),0==(128&a.flags)&&(a.memoizedState=null),a.flags|=4;T(a),s=!1}else null!==tv&&(wi(tv),tv=null),s=!0;if(!s)return 256&a.flags?a:null}if(0!=(128&a.flags))return a.lanes=i,a;return i=null!==o,n=null!==n&&null!==n.memoizedState,i&&(o=a.child,s=null,null!==o.alternate&&null!==o.alternate.memoizedState&&null!==o.alternate.memoizedState.cachePool&&(s=o.alternate.memoizedState.cachePool.pool),m=null,null!==o.memoizedState&&null!==o.memoizedState.cachePool&&(m=o.memoizedState.cachePool.pool),m!==s&&(o.flags|=2048)),i!==n&&i&&(a.child.flags|=8192),ti(a,a.updateQueue),T(a),null;case 4:return Ma(),null===n&&Ci(a.stateNode.containerInfo),T(a),null;case 10:return gi(a.type._context),T(a),null;case 19:if(D(tA),null===(s=a.memoizedState))return T(a),null;if(o=0!=(128&a.flags),null===(m=s.rendering)){if(o)ui(s,!1);else{if(0!==n1||null!==n&&0!=(128&n.flags))for(n=a.child;null!==n;){if(null!==(m=Se(n))){for(a.flags|=128,ui(s,!1),n=m.updateQueue,a.updateQueue=n,ti(a,n),a.subtreeFlags=0,n=i,i=a.child;null!==i;)Di(i,n),i=i.sibling;return E(tA,1&tA.current|2),a.child}n=n.sibling}null!==s.tail&&em()>re&&(a.flags|=128,o=!0,ui(s,!1),a.lanes=4194304)}}else{if(!o){if(null!==(n=Se(m))){if(a.flags|=128,o=!0,n=n.updateQueue,a.updateQueue=n,ti(a,n),ui(s,!0),null===s.tail&&"hidden"===s.tailMode&&!m.alternate&&!ty)return T(a),null}else 2*em()-s.renderingStartTime>re&&536870912!==i&&(a.flags|=128,o=!0,ui(s,!1),a.lanes=4194304)}s.isBackwards?(m.sibling=a.child,a.child=m):(null!==(n=s.last)?n.sibling=m:a.child=m,s.last=m)}if(null!==s.tail)return a=s.tail,s.rendering=a,s.tail=a.sibling,s.renderingStartTime=em(),a.sibling=null,n=tA.current,E(tA,o?1&n|2:1&n),a;return T(a),null;case 22:case 23:return Re(a),Ke(),o=null!==a.memoizedState,null!==n?null!==n.memoizedState!==o&&(a.flags|=8192):o&&(a.flags|=8192),o&&0!=(1&a.mode)?0!=(536870912&i)&&0==(128&a.flags)&&(T(a),6&a.subtreeFlags&&(a.flags|=8192)):T(a),null!==(i=a.updateQueue)&&ti(a,i.retryQueue),i=null,null!==n&&null!==n.memoizedState&&null!==n.memoizedState.cachePool&&(i=n.memoizedState.cachePool.pool),o=null,null!==a.memoizedState&&null!==a.memoizedState.cachePool&&(o=a.memoizedState.cachePool.pool),o!==i&&(a.flags|=2048),null!==n&&D(nx),null;case 24:return i=null,null!==n&&(i=n.memoizedState.cache),a.memoizedState.cache!==i&&(a.flags|=2048),gi(nE),T(a),null;case 25:return null}throw Error(t(156,a.tag))}function Fi(n,a){switch(qd(a),a.tag){case 1:return Xc(a.type)&&Yc(),65536&(n=a.flags)?(a.flags=-65537&n|128,a):null;case 3:return gi(nE),Ma(),D(e8),D(e6),0!=(65536&(n=a.flags))&&0==(128&n)?(a.flags=-65537&n|128,a):null;case 26:case 27:case 5:return Oa(a),null;case 13:if(Re(a),null!==(n=a.memoizedState)&&null!==n.dehydrated){if(null===a.alternate)throw Error(t(340));Kd()}return 65536&(n=a.flags)?(a.flags=-65537&n|128,a):null;case 19:return D(tA),null;case 4:return Ma(),null;case 10:return gi(a.type._context),null;case 22:case 23:return Re(a),Ke(),null!==n&&D(nx),65536&(n=a.flags)?(a.flags=-65537&n|128,a):null;case 24:return gi(nE),null;default:return null}}function Gi(n,a){switch(qd(a),a.tag){case 1:null!=(n=a.type.childContextTypes)&&Yc();break;case 3:gi(nE),Ma(),D(e8),D(e6);break;case 26:case 27:case 5:Oa(a);break;case 4:Ma();break;case 13:Re(a);break;case 19:D(tA);break;case 10:gi(a.type._context);break;case 22:case 23:Re(a),Ke(),null!==n&&D(nx);break;case 24:gi(nE)}}function Hi(n,a,i){var o=Array.prototype.slice.call(arguments,3);try{a.apply(i,o)}catch(n){this.onError(n)}}var nz=!1,nP=null,nN=!1,nT=null,nL={onError:function(n){nz=!0,nP=n}};function Ni(n,a,i,o,s,m,y,v,k){nz=!1,nP=null,Hi.apply(nL,arguments)}function Oi(n,a,i,o,s,m,y,v,k){if(Ni.apply(this,arguments),nz){if(nz){var S=nP;nz=!1,nP=null}else throw Error(t(198));nN||(nN=!0,nT=S)}}var n_=!1,nD=!1,nM="function"==typeof WeakSet?WeakSet:Set,nR=null;function Ti(n,a){try{var i=n.ref;if(null!==i){var o=n.stateNode;switch(n.tag){case 26:case 27:case 5:var s=o;break;default:s=o}"function"==typeof i?n.refCleanup=i(s):i.current=s}}catch(i){W(n,a,i)}}function Ui(n,a){var i=n.ref,o=n.refCleanup;if(null!==i){if("function"==typeof o)try{o()}catch(i){W(n,a,i)}finally{n.refCleanup=null,null!=(n=n.alternate)&&(n.refCleanup=null)}else if("function"==typeof i)try{i(null)}catch(i){W(n,a,i)}else i.current=null}}function Vi(n,a,i){try{i()}catch(i){W(n,a,i)}}var nF=!1;function Xi(n,a){if(lB=r4,aj(n=$i())){if("selectionStart"in n)var i={start:n.selectionStart,end:n.selectionEnd};else e:{var o=(i=(i=n.ownerDocument)&&i.defaultView||window).getSelection&&i.getSelection();if(o&&0!==o.rangeCount){i=o.anchorNode;var s,m=o.anchorOffset,y=o.focusNode;o=o.focusOffset;try{i.nodeType,y.nodeType}catch(n){i=null;break e}var v=0,k=-1,S=-1,C=0,x=0,P=n,N=null;t:for(;;){for(;P!==i||0!==m&&3!==P.nodeType||(k=v+m),P!==y||0!==o&&3!==P.nodeType||(S=v+o),3===P.nodeType&&(v+=P.nodeValue.length),null!==(s=P.firstChild);)N=P,P=s;for(;;){if(P===n)break t;if(N===i&&++C===m&&(k=v),N===y&&++x===o&&(S=v),null!==(s=P.nextSibling))break;N=(P=N).parentNode}P=s}i=-1===k||-1===S?null:{start:k,end:S}}else i=null}i=i||{start:0,end:0}}else i=null;for(lW={focusedElem:n,selectionRange:i},r4=!1,nR=a;null!==nR;)if(n=(a=nR).child,0!=(1028&a.subtreeFlags)&&null!==n)n.return=a,nR=n;else for(;null!==nR;){a=nR;try{var j=a.alternate,L=a.flags;switch(a.tag){case 0:case 11:case 15:case 5:case 26:case 27:case 6:case 4:case 17:break;case 1:if(0!=(1024&L)&&null!==j){var _=j.memoizedProps,M=j.memoizedState,R=a.stateNode,F=R.getSnapshotBeforeUpdate(a.elementType===a.type?_:Yg(a.type,_),M);R.__reactInternalSnapshotBeforeUpdate=F}break;case 3:0!=(1024&L)&&cj(a.stateNode.containerInfo);break;default:if(0!=(1024&L))throw Error(t(163))}}catch(n){W(a,a.return,n)}if(null!==(n=a.sibling)){n.return=a.return,nR=n;break}nR=a.return}return j=nF,nF=!1,j}function dj(n,a,i){var o=a.updateQueue;if(null!==(o=null!==o?o.lastEffect:null)){var s=o=o.next;do{if((s.tag&n)===n){var m=s.inst,y=m.destroy;void 0!==y&&(m.destroy=void 0,Vi(a,i,y))}s=s.next}while(s!==o)}}function ej(n,a){if(null!==(a=null!==(a=a.updateQueue)?a.lastEffect:null)){var i=a=a.next;do{if((i.tag&n)===n){var o=i.create,s=i.inst;o=o(),s.destroy=o}i=i.next}while(i!==a)}}function fj(n,a){try{ej(a,n)}catch(a){W(n,n.return,a)}}function gj(n){var a=n.updateQueue;if(null!==a){var i=n.stateNode;try{ge(a,i)}catch(a){W(n,n.return,a)}}}function hj(n){var a=n.type,i=n.memoizedProps,o=n.stateNode;try{switch(a){case"button":case"input":case"select":case"textarea":i.autoFocus&&o.focus();break;case"img":i.src&&(o.src=i.src)}}catch(a){W(n,n.return,a)}}function ij(n,a,i){var o=i.flags;switch(i.tag){case 0:case 11:case 15:jj(n,i),4&o&&fj(i,5);break;case 1:if(jj(n,i),4&o){if(n=i.stateNode,null===a)try{n.componentDidMount()}catch(n){W(i,i.return,n)}else{var s=i.elementType===i.type?a.memoizedProps:Yg(i.type,a.memoizedProps);a=a.memoizedState;try{n.componentDidUpdate(s,a,n.__reactInternalSnapshotBeforeUpdate)}catch(n){W(i,i.return,n)}}}64&o&&gj(i),512&o&&Ti(i,i.return);break;case 3:if(jj(n,i),64&o&&null!==(o=i.updateQueue)){if(n=null,null!==i.child)switch(i.child.tag){case 27:case 5:case 1:n=i.child.stateNode}try{ge(o,n)}catch(n){W(i,i.return,n)}}break;case 26:jj(n,i),512&o&&Ti(i,i.return);break;case 27:case 5:jj(n,i),null===a&&4&o&&hj(i),512&o&&Ti(i,i.return);break;case 12:default:jj(n,i);break;case 13:jj(n,i),4&o&&kj(n,i);break;case 22:if(0!=(1&i.mode)){if(!(s=null!==i.memoizedState||n_)){a=null!==a&&null!==a.memoizedState||nD;var m=n_,y=nD;n_=s,(nD=a)&&!y?lj(n,i,0!=(8772&i.subtreeFlags)):jj(n,i),n_=m,nD=y}}else jj(n,i);512&o&&("manual"===i.memoizedProps.mode?Ti(i,i.return):Ui(i,i.return))}}function mj(n){var a=n.alternate;null!==a&&(n.alternate=null,mj(a)),n.child=null,n.deletions=null,n.sibling=null,5===n.tag&&null!==(a=n.stateNode)&&Gb(a),n.stateNode=null,n.return=null,n.dependencies=null,n.memoizedProps=null,n.memoizedState=null,n.pendingProps=null,n.stateNode=null,n.updateQueue=null}function nj(n){return 5===n.tag||3===n.tag||26===n.tag||27===n.tag||4===n.tag}function oj(n){e:for(;;){for(;null===n.sibling;){if(null===n.return||nj(n.return))return null;n=n.return}for(n.sibling.return=n.return,n=n.sibling;5!==n.tag&&6!==n.tag&&27!==n.tag&&18!==n.tag;){if(2&n.flags||null===n.child||4===n.tag)continue e;n.child.return=n,n=n.child}if(!(2&n.flags))return n.stateNode}}function pj(n,a,i){var o=n.tag;if(5===o||6===o)n=n.stateNode,a?8===i.nodeType?i.parentNode.insertBefore(n,a):i.insertBefore(n,a):(8===i.nodeType?(a=i.parentNode).insertBefore(n,i):(a=i).appendChild(n),null!=(i=i._reactRootContainer)||null!==a.onclick||(a.onclick=qj));else if(4!==o&&27!==o&&null!==(n=n.child))for(pj(n,a,i),n=n.sibling;null!==n;)pj(n,a,i),n=n.sibling}function rj(n,a,i){var o=n.tag;if(5===o||6===o)n=n.stateNode,a?i.insertBefore(n,a):i.appendChild(n);else if(4!==o&&27!==o&&null!==(n=n.child))for(rj(n,a,i),n=n.sibling;null!==n;)rj(n,a,i),n=n.sibling}var nO=null,nA=!1;function uj(n,a,i){for(i=i.child;null!==i;)vj(n,a,i),i=i.sibling}function vj(n,a,i){if(eC&&"function"==typeof eC.onCommitFiberUnmount)try{eC.onCommitFiberUnmount(eE,i)}catch(n){}switch(i.tag){case 26:nD||Ui(i,a),uj(n,a,i),i.memoizedState?i.memoizedState.count--:i.stateNode&&(i=i.stateNode).parentNode.removeChild(i);break;case 27:nD||Ui(i,a);var o=nO,s=nA;for(nO=i.stateNode,uj(n,a,i),n=(i=i.stateNode).attributes;n.length;)i.removeAttributeNode(n[0]);Gb(i),nO=o,nA=s;break;case 5:nD||Ui(i,a);case 6:o=nO,s=nA,nO=null,uj(n,a,i),nO=o,nA=s,null!==nO&&(nA?(n=nO,i=i.stateNode,8===n.nodeType?n.parentNode.removeChild(i):n.removeChild(i)):nO.removeChild(i.stateNode));break;case 18:null!==nO&&(nA?(n=nO,i=i.stateNode,8===n.nodeType?wj(n.parentNode,i):1===n.nodeType&&wj(n,i),xj(n)):wj(nO,i.stateNode));break;case 4:o=nO,s=nA,nO=i.stateNode.containerInfo,nA=!0,uj(n,a,i),nO=o,nA=s;break;case 0:case 11:case 14:case 15:if(!nD&&null!==(o=i.updateQueue)&&null!==(o=o.lastEffect)){s=o=o.next;do{var m=s.tag,y=s.inst,v=y.destroy;void 0!==v&&(0!=(2&m)?(y.destroy=void 0,Vi(i,a,v)):0!=(4&m)&&(y.destroy=void 0,Vi(i,a,v))),s=s.next}while(s!==o)}uj(n,a,i);break;case 1:if(!nD&&(Ui(i,a),"function"==typeof(o=i.stateNode).componentWillUnmount))try{o.props=i.memoizedProps,o.state=i.memoizedState,o.componentWillUnmount()}catch(n){W(i,a,n)}uj(n,a,i);break;case 21:default:uj(n,a,i);break;case 22:Ui(i,a),1&i.mode?(nD=(o=nD)||null!==i.memoizedState,uj(n,a,i),nD=o):uj(n,a,i)}}function kj(n,a){if(null===a.memoizedState&&null!==(n=a.alternate)&&null!==(n=n.memoizedState)&&null!==(n=n.dehydrated))try{xj(n)}catch(n){W(a,a.return,n)}}function yj(n){switch(n.tag){case 13:case 19:var a=n.stateNode;return null===a&&(a=n.stateNode=new nM),a;case 22:return null===(a=(n=n.stateNode)._retryCache)&&(a=n._retryCache=new nM),a;default:throw Error(t(435,n.tag))}}function zj(n,a){var i=yj(n);a.forEach(function(a){var o=Aj.bind(null,n,a);i.has(a)||(i.add(a),a.then(o,o))})}function Bj(n,a){var i=a.deletions;if(null!==i)for(var o=0;o title"))),Ai(s,i,o),s[eM]=n,Nb(s),i=s;break e;case"link":var m=Fj("link","href",a).get(i+(o.href||""));if(m){for(var y=0;yi?32:i;i=nY.transition;var s=eL;try{if(nY.transition=null,eL=o,null===rc)var m=!1;else{o=rd,rd=null;var y=rc,v=rs;if(rc=null,rs=0,0!=(6&nq))throw Error(t(331));var k=nq;if(nq|=4,bk(y.current),Rj(y,y.current,v,o),nq=k,bf(!1),eC&&"function"==typeof eC.onPostCommitFiberRoot)try{eC.onPostCommitFiberRoot(eE,y)}catch(n){}m=!0}return m}finally{eL=s,nY.transition=i,Rk(n,a)}}return!1}function Sk(n,a,i){a=hh(n,a=eh(i,a),2),null!==(n=ae(n,a,2))&&(ob(n,2),Ze(n))}function W(n,a,i){if(3===n.tag)Sk(n,n,i);else for(;null!==a;){if(3===a.tag){Sk(a,n,i);break}if(1===a.tag){var o=a.stateNode;if("function"==typeof a.type.getDerivedStateFromError||"function"==typeof o.componentDidCatch&&(null===ra||!ra.has(o))){n=kh(a,n=eh(i,n),2),null!==(a=ae(a,n,2))&&(ob(a,2),Ze(a));break}}a=a.return}}function qh(n,a,i){var o=n.pingCache;if(null===o){o=n.pingCache=new nW;var s=new Set;o.set(a,s)}else void 0===(s=o.get(a))&&(s=new Set,o.set(a,s));s.has(i)||(nJ=!0,s.add(i),n=Tk.bind(null,n,a,i),a.then(n,n))}function Tk(n,a,i){var o=n.pingCache;null!==o&&o.delete(a),n.pingedLanes|=n.suspendedLanes&i,nH===n&&(nK&i)===i&&(4===n1||3===n1&&(62914560&nK)===nK&&300>em()-n9?0==(2&nq)&&gf(n,0):n6|=i),Ze(n)}function Uk(n,a){0===a&&(a=0==(1&n.mode)?2:mb()),null!==(n=Ud(n,a))&&(ob(n,a),Ze(n))}function Vh(n){var a=n.memoizedState,i=0;null!==a&&(i=a.retryLane),Uk(n,i)}function Aj(n,a){var i=0;switch(n.tag){case 13:var o=n.stateNode,s=n.memoizedState;null!==s&&(i=s.retryLane);break;case 19:o=n.stateNode;break;case 22:o=n.stateNode._retryCache;break;default:throw Error(t(314))}null!==o&&o.delete(a),Uk(n,i)}function Pk(n,a){return eu(n,a)}function Xk(n,a,i,o){this.tag=n,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=a,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ud(n,a,i,o){return new Xk(n,a,i,o)}function zh(n){return!(!(n=n.prototype)||!n.isReactComponent)}function Vk(n){if("function"==typeof n)return zh(n)?1:0;if(null!=n){if((n=n.$$typeof)===A)return 11;if(n===$)return 14}return 2}function xe(n,a){var i=n.alternate;return null===i?((i=ud(n.tag,a,n.key,n.mode)).elementType=n.elementType,i.type=n.type,i.stateNode=n.stateNode,i.alternate=n,n.alternate=i):(i.pendingProps=a,i.type=n.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=31457280&n.flags,i.childLanes=n.childLanes,i.lanes=n.lanes,i.child=n.child,i.memoizedProps=n.memoizedProps,i.memoizedState=n.memoizedState,i.updateQueue=n.updateQueue,a=n.dependencies,i.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext},i.sibling=n.sibling,i.index=n.index,i.ref=n.ref,i.refCleanup=n.refCleanup,i}function Di(n,a){n.flags&=31457282;var i=n.alternate;return null===i?(n.childLanes=0,n.lanes=a,n.child=null,n.subtreeFlags=0,n.memoizedProps=null,n.memoizedState=null,n.updateQueue=null,n.dependencies=null,n.stateNode=null):(n.childLanes=i.childLanes,n.lanes=i.lanes,n.child=i.child,n.subtreeFlags=0,n.deletions=null,n.memoizedProps=i.memoizedProps,n.memoizedState=i.memoizedState,n.updateQueue=i.updateQueue,n.type=i.type,a=i.dependencies,n.dependencies=null===a?null:{lanes:a.lanes,firstContext:a.firstContext}),n}function ze(n,a,i,o,s,m,y){if(s=2,o=n,"function"==typeof n)zh(n)&&(s=1);else if("string"==typeof n)s=Yk(n,i,et.current)?26:"html"===n||"head"===n||"body"===n?27:5;else e:switch(n){case L:return Be(i.children,m,y,a);case _:s=8,0!=(1&(m|=8))&&(m|=16);break;case M:return(n=ud(12,i,a,2|m)).elementType=M,n.lanes=y,n;case I:return(n=ud(13,i,a,m)).elementType=I,n.lanes=y,n;case Q:return(n=ud(19,i,a,m)).elementType=Q,n.lanes=y,n;case X:return Rh(i,m,y,a);case G:case K:case J:return(n=ud(24,i,a,m)).elementType=J,n.lanes=y,n;default:if("object"==typeof n&&null!==n)switch(n.$$typeof){case R:s=10;break e;case F:s=9;break e;case A:s=11;break e;case $:s=14;break e;case H:s=16,o=null;break e}throw Error(t(130,null==n?n:typeof n,""))}return(a=ud(s,i,a,m)).elementType=n,a.type=o,a.lanes=y,a}function Be(n,a,i,o){return(n=ud(7,n,o,a)).lanes=i,n}function Rh(n,a,i,o){(n=ud(22,n,o,a)).elementType=X,n.lanes=i;var s={_visibility:1,_pendingVisibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null,_current:null,detach:function(){var n=s._current;if(null===n)throw Error(t(456));if(0==(2&s._pendingVisibility)){var a=Ud(n,2);null!==a&&(s._pendingVisibility|=2,pg(a,n,2))}},attach:function(){var n=s._current;if(null===n)throw Error(t(456));if(0!=(2&s._pendingVisibility)){var a=Ud(n,2);null!==a&&(s._pendingVisibility&=-3,pg(a,n,2))}}};return n.stateNode=s,n}function ye(n,a,i){return(n=ud(6,n,null,a)).lanes=i,n}function Ae(n,a,i){return(a=ud(4,null!==n.children?n.children:[],n.key,a)).lanes=i,a.stateNode={containerInfo:n.containerInfo,pendingChildren:null,implementation:n.implementation},a}function Zk(n,a,i,o,s,m){this.tag=a,this.containerInfo=n,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=nb(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.finishedLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=nb(0),this.hiddenUpdates=nb(null),this.identifierPrefix=o,this.onRecoverableError=s,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=m,this.incompleteTransitions=new Map}function $k(n,a,i,o,s,m,y,v,k,S,C){return n=new Zk(n,a,i,v,k,C),1===a?(a=1,!0===m&&(a|=24)):a=0,m=ud(3,null,null,a),n.current=m,m.stateNode=n,a=Ug(),a.refCount++,n.pooledCache=a,a.refCount++,m.memoizedState={element:o,isDehydrated:i,cache:a},Yd(m),n}function al(n,a,i){var o=3=lr),lo=!1;function Nm(n,a){switch(n){case"keyup":return -1!==r9.indexOf(a.keyCode);case"keydown":return 229!==a.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Om(n){return"object"==typeof(n=n.detail)&&"data"in n?n.data:null}var lu=!1;function Qm(n,a){switch(n){case"compositionend":return Om(a);case"keypress":if(32!==a.which)return null;return lo=!0," ";case"textInput":return" "===(n=a.data)&&lo?null:n;default:return null}}function Rm(n,a){if(lu)return"compositionend"===n||!lt&&Nm(n,a)?(n=Em(),r7=r5=r8=null,lu=!1,n):null;switch(n){case"paste":default:return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:o,offset:a-n};n=i}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=mn(o)}}function on(n,a){return!!n&&!!a&&(n===a||(!n||3!==n.nodeType)&&(a&&3===a.nodeType?on(n,a.parentNode):"contains"in n?n.contains(a):!!n.compareDocumentPosition&&!!(16&n.compareDocumentPosition(a))))}function $i(){for(var n=window,a=lc();a instanceof n.HTMLIFrameElement;){try{var i="string"==typeof a.contentWindow.location.href}catch(n){i=!1}if(i)n=a.contentWindow;else break;a=lc(n.document)}return a}function aj(n){var a=n&&n.nodeName&&n.nodeName.toLowerCase();return a&&("input"===a&&("text"===n.type||"search"===n.type||"tel"===n.type||"url"===n.type||"password"===n.type)||"textarea"===a||"true"===n.contentEditable)}function Qk(n){var a=$i(),i=n.focusedElem,o=n.selectionRange;if(a!==i&&i&&i.ownerDocument&&on(i.ownerDocument.documentElement,i)){if(null!==o&&aj(i)){if(a=o.start,void 0===(n=o.end)&&(n=a),"selectionStart"in i)i.selectionStart=a,i.selectionEnd=Math.min(n,i.value.length);else if((n=(a=i.ownerDocument||document)&&a.defaultView||window).getSelection){n=n.getSelection();var s=i.textContent.length,m=Math.min(o.start,s);o=void 0===o.end?m:Math.min(o.end,s),!n.extend&&m>o&&(s=o,o=m,m=s),s=nn(i,m);var y=nn(i,o);s&&y&&(1!==n.rangeCount||n.anchorNode!==s.node||n.anchorOffset!==s.offset||n.focusNode!==y.node||n.focusOffset!==y.offset)&&((a=a.createRange()).setStart(s.node,s.offset),n.removeAllRanges(),m>o?(n.addRange(a),n.extend(y.node,y.offset)):(a.setEnd(y.node,y.offset),n.addRange(a)))}}for(a=[],n=i;n=n.parentNode;)1===n.nodeType&&a.push({element:n,left:n.scrollLeft,top:n.scrollTop});for("function"==typeof i.focus&&i.focus(),i=0;i=document.documentMode,lk=null,lw=null,lS=null,lE=!1;function un(n,a,i){var o=i.window===i?i.document:9===i.nodeType?i:i.ownerDocument;lE||null==lk||lk!==lc(o)||(o="selectionStart"in(o=lk)&&aj(o)?{start:o.selectionStart,end:o.selectionEnd}:{anchorNode:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset},lS&&he(lS,o)||(lS=o,0<(o=Vm(lw,"onSelect")).length&&(a=new rT("onSelect","select",null,a,i),n.push({event:a,listeners:o}),a.target=lk)))}function vn(n,a){var i={};return i[n.toLowerCase()]=a.toLowerCase(),i["Webkit"+n]="webkit"+a,i["Moz"+n]="moz"+a,i}var lC={animationend:vn("Animation","AnimationEnd"),animationiteration:vn("Animation","AnimationIteration"),animationstart:vn("Animation","AnimationStart"),transitionend:vn("Transition","TransitionEnd")},lx={},lz={};function zn(n){if(lx[n])return lx[n];if(!lC[n])return n;var a,i=lC[n];for(a in i)if(i.hasOwnProperty(a)&&a in lz)return lx[n]=i[a];return n}e$&&(lz=document.createElement("div").style,"AnimationEvent"in window||(delete lC.animationend.animation,delete lC.animationiteration.animation,delete lC.animationstart.animation),"TransitionEvent"in window||delete lC.transitionend.transition);var lP=zn("animationend"),lN=zn("animationiteration"),lT=zn("animationstart"),lL=zn("transitionend"),l_=new Map,lD="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll scrollEnd toggle touchMove waiting wheel".split(" ");function Gn(n,a){l_.set(n,a),Qb(a,[n])}for(var lM=0;lM title"):null)}function Yk(n,a,i){if(1===i||null!=a.itemProp)return!1;switch(n){case"meta":case"title":return!0;case"style":if("string"!=typeof a.precedence||"string"!=typeof a.href||""===a.href)break;return!0;case"link":if("string"!=typeof a.rel||"string"!=typeof a.href||""===a.href||a.onLoad||a.onError)break;if("stylesheet"===a.rel)return n=a.disabled,"string"==typeof a.precedence&&null==n;return!0;case"script":if(!0===a.async&&!a.onLoad&&!a.onError&&"string"==typeof a.src&&a.src)return!0}return!1}var lG=null;function yk(){}function Xj(n,a,i){if(null===lG)throw Error(t(475));var o=lG;if("stylesheet"===a.type&&("string"!=typeof i.media||!1!==matchMedia(i.media).matches)&&0==(4&a.state.loading)){if(null===a.instance){var s=no(i.href),m=n.querySelector(po(s));if(m){null!==(n=m._p)&&"object"==typeof n&&"function"==typeof n.then&&(o.count++,o=wo.bind(o),n.then(o,o)),a.state.loading|=4,a.instance=m,Nb(m);return}m=n.ownerDocument||n,i=vo(i),(s=lH.get(s))&&ro(i,s),Nb(m=m.createElement("link"));var y=m;y._p=new Promise(function(n,a){y.onload=n,y.onerror=a}),Ai(m,"link",i),a.instance=m}null===o.stylesheets&&(o.stylesheets=new Map),o.stylesheets.set(a,n),(n=a.state.preload)&&0==(3&a.state.loading)&&(o.count++,a=wo.bind(o),n.addEventListener("load",a),n.addEventListener("error",a))}}function zk(){if(null===lG)throw Error(t(475));var n=lG;return n.stylesheets&&0===n.count&&xo(n,n.stylesheets),0u}return!1}function v(a,u,i,o,s,w,x){this.acceptsBooleans=2===u||3===u||4===u,this.attributeName=o,this.attributeNamespace=s,this.mustUseProperty=i,this.propertyName=a,this.type=u,this.sanitizeURL=w,this.removeEmptyString=x}var X={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){X[a]=new v(a,0,!1,a,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var u=a[0];X[u]=new v(u,1,!1,a[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(a){X[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){X[a]=new v(a,2,!1,a,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){X[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(a){X[a]=new v(a,3,!0,a,null,!1,!1)}),["capture","download"].forEach(function(a){X[a]=new v(a,4,!1,a,null,!1,!1)}),["cols","rows","size","span"].forEach(function(a){X[a]=new v(a,6,!1,a,null,!1,!1)}),["rowSpan","start"].forEach(function(a){X[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ee=/[\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}function ta(a,u,i,o){var s=X.hasOwnProperty(u)?X[u]:null;(null!==s?0!==s.type:o||!(2--C||s[x]!==w[C]){var _="\n"+s[x].replace(" at new "," at ");return a.displayName&&_.includes("")&&(_=_.replace("",a.displayName)),_}while(1<=x&&0<=C);break}}}finally{eE=!1,Error.prepareStackTrace=i}return(a=a?a.displayName||a.name:"")?Ma(a):""}function Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma("Lazy");case 13:return Ma("Suspense");case 19:return Ma("SuspenseList");case 0:case 2:case 15:return a=Oa(a.type,!1);case 11:return a=Oa(a.type.render,!1);case 1:return a=Oa(a.type,!0);default:return""}}function Qa(a){if(null==a)return null;if("function"==typeof a)return a.displayName||a.name||null;if("string"==typeof a)return a;switch(a){case ea:return"Fragment";case er:return"Portal";case eo:return"Profiler";case eu:return"StrictMode";case ep:return"Suspense";case eg:return"SuspenseList"}if("object"==typeof a)switch(a.$$typeof){case ec:return(a.displayName||"Context")+".Consumer";case es:return(a._context.displayName||"Context")+".Provider";case ef:var u=a.render;return(a=a.displayName)||(a=""!==(a=u.displayName||u.name||"")?"ForwardRef("+a+")":"ForwardRef"),a;case em:return null!==(u=a.displayName||null)?u:Qa(a.type)||"Memo";case ev:u=a._payload,a=a._init;try{return Qa(a(u))}catch(a){}}return null}function Ra(a){var u=a.type;switch(a.tag){case 24:return"Cache";case 9:return(u.displayName||"Context")+".Consumer";case 10:return(u._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return a=(a=u.render).displayName||a.name||"",u.displayName||(""!==a?"ForwardRef("+a+")":"ForwardRef");case 7:return"Fragment";case 5:return u;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Qa(u);case 8:return u===eu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if("function"==typeof u)return u.displayName||u.name||null;if("string"==typeof u)return u}return null}function Sa(a){switch(typeof a){case"boolean":case"number":case"string":case"undefined":case"object":return a;default:return""}}function Ta(a){var u=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===u||"radio"===u)}function Ua(a){var u=Ta(a)?"checked":"value",i=Object.getOwnPropertyDescriptor(a.constructor.prototype,u),o=""+a[u];if(!a.hasOwnProperty(u)&&void 0!==i&&"function"==typeof i.get&&"function"==typeof i.set){var s=i.get,w=i.set;return Object.defineProperty(a,u,{configurable:!0,get:function(){return s.call(this)},set:function(a){o=""+a,w.call(this,a)}}),Object.defineProperty(a,u,{enumerable:i.enumerable}),{getValue:function(){return o},setValue:function(a){o=""+a},stopTracking:function(){a._valueTracker=null,delete a[u]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var u=a._valueTracker;if(!u)return!0;var i=u.getValue(),o="";return a&&(o=Ta(a)?a.checked?"true":"false":a.value),(a=o)!==i&&(u.setValue(a),!0)}function Xa(a){if(void 0===(a=a||("undefined"!=typeof document?document:void 0)))return null;try{return a.activeElement||a.body}catch(u){return a.body}}function Ya(a,u){var i=u.checked;return eS({},u,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=i?i:a._wrapperState.initialChecked})}function Za(a,u){var i=null==u.defaultValue?"":u.defaultValue,o=null!=u.checked?u.checked:u.defaultChecked;i=Sa(null!=u.value?u.value:i),a._wrapperState={initialChecked:o,initialValue:i,controlled:"checkbox"===u.type||"radio"===u.type?null!=u.checked:null!=u.value}}function ab(a,u){null!=(u=u.checked)&&ta(a,"checked",u,!1)}function bb(a,u){ab(a,u);var i=Sa(u.value),o=u.type;if(null!=i)"number"===o?(0===i&&""===a.value||a.value!=i)&&(a.value=""+i):a.value!==""+i&&(a.value=""+i);else if("submit"===o||"reset"===o){a.removeAttribute("value");return}u.hasOwnProperty("value")?cb(a,u.type,i):u.hasOwnProperty("defaultValue")&&cb(a,u.type,Sa(u.defaultValue)),null==u.checked&&null!=u.defaultChecked&&(a.defaultChecked=!!u.defaultChecked)}function db(a,u,i){if(u.hasOwnProperty("value")||u.hasOwnProperty("defaultValue")){var o=u.type;if(!("submit"!==o&&"reset"!==o||void 0!==u.value&&null!==u.value))return;u=""+a._wrapperState.initialValue,i||u===a.value||(a.value=u),a.defaultValue=u}""!==(i=a.name)&&(a.name=""),a.defaultChecked=!!a._wrapperState.initialChecked,""!==i&&(a.name=i)}function cb(a,u,i){("number"!==u||Xa(a.ownerDocument)!==a)&&(null==i?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+i&&(a.defaultValue=""+i))}var ex=Array.isArray;function fb(a,u,i,o){if(a=a.options,u){u={};for(var s=0;s"+u.valueOf().toString()+"",u=e_.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;u.firstChild;)a.appendChild(u.firstChild)}},"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(a,u,i,o){MSApp.execUnsafeLocalFunction(function(){return eC(a,u,i,o)})}:eC);function ob(a,u){if(u){var i=a.firstChild;if(i&&i===a.lastChild&&3===i.nodeType){i.nodeValue=u;return}}a.textContent=u}var eL={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},eN=["Webkit","ms","Moz","O"];function rb(a,u,i){return null==u||"boolean"==typeof u||""===u?"":i||"number"!=typeof u||0===u||eL.hasOwnProperty(a)&&eL[a]?(""+u).trim():u+"px"}function sb(a,u){for(var i in a=a.style,u)if(u.hasOwnProperty(i)){var o=0===i.indexOf("--"),s=rb(i,u[i],o);"float"===i&&(i="cssFloat"),o?a.setProperty(i,s):a[i]=s}}Object.keys(eL).forEach(function(a){eN.forEach(function(u){eL[u=u+a.charAt(0).toUpperCase()+a.substring(1)]=eL[a]})});var eP=eS({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ub(a,u){if(u){if(eP[a]&&(null!=u.children||null!=u.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=u.dangerouslySetInnerHTML){if(null!=u.children)throw Error(p(60));if("object"!=typeof u.dangerouslySetInnerHTML||!("__html"in u.dangerouslySetInnerHTML))throw Error(p(61))}if(null!=u.style&&"object"!=typeof u.style)throw Error(p(62))}}function vb(a,u){if(-1===a.indexOf("-"))return"string"==typeof u.is;switch(a){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var eT=null;function xb(a){return(a=a.target||a.srcElement||window).correspondingUseElement&&(a=a.correspondingUseElement),3===a.nodeType?a.parentNode:a}var eD=null,eM=null,eR=null;function Bb(a){if(a=Cb(a)){if("function"!=typeof eD)throw Error(p(280));var u=a.stateNode;u&&(u=Db(u),eD(a.stateNode,a.type,u))}}function Eb(a){eM?eR?eR.push(a):eR=[a]:eM=a}function Fb(){if(eM){var a=eM,u=eR;if(eR=eM=null,Bb(a),u)for(a=0;a>>=0)?32:31-(e4(a)/e8|0)|0}var e6=64,e5=4194304;function tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return 4194240&a;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return 130023424&a;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return a}}function uc(a,u){var i=a.pendingLanes;if(0===i)return 0;var o=0,s=a.suspendedLanes,w=a.pingedLanes,x=268435455&i;if(0!==x){var C=x&~s;0!==C?o=tc(C):0!=(w&=x)&&(o=tc(w))}else 0!=(x=i&~s)?o=tc(x):0!==w&&(o=tc(w));if(0===o)return 0;if(0!==u&&u!==o&&0==(u&s)&&((s=o&-o)>=(w=u&-u)||16===s&&0!=(4194240&w)))return u;if(0!=(4&o)&&(o|=16&i),0!==(u=a.entangledLanes))for(a=a.entanglements,u&=o;0i;i++)u.push(a);return u}function Ac(a,u,i){a.pendingLanes|=u,536870912!==u&&(a.suspendedLanes=0,a.pingedLanes=0),(a=a.eventTimes)[u=31-e3(u)]=i}function Bc(a,u){var i=a.pendingLanes&~u;a.pendingLanes=u,a.suspendedLanes=0,a.pingedLanes=0,a.expiredLanes&=u,a.mutableReadLanes&=u,a.entangledLanes&=u,u=a.entanglements;var o=a.eventTimes;for(a=a.expirationTimes;0=nY),nX=!1;function ge(a,u){switch(a){case"keyup":return -1!==nK.indexOf(u.keyCode);case"keydown":return 229!==u.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function he(a){return"object"==typeof(a=a.detail)&&"data"in a?a.data:null}var nJ=!1;function je(a,u){switch(a){case"compositionend":return he(u);case"keypress":if(32!==u.which)return null;return nX=!0," ";case"textInput":return" "===(a=u.data)&&nX?null:a;default:return null}}function ke(a,u){if(nJ)return"compositionend"===a||!nG&&ge(a,u)?(a=nd(),nx=nE=nS=null,nJ=!1,a):null;switch(a){case"paste":default:return null;case"keypress":if(!(u.ctrlKey||u.altKey||u.metaKey)||u.ctrlKey&&u.altKey){if(u.char&&1=u)return{node:o,offset:u-a};a=i}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=Je(o)}}function Le(a,u){return!!a&&!!u&&(a===u||(!a||3!==a.nodeType)&&(u&&3===u.nodeType?Le(a,u.parentNode):"contains"in a?a.contains(u):!!a.compareDocumentPosition&&!!(16&a.compareDocumentPosition(u))))}function Me(){for(var a=window,u=Xa();u instanceof a.HTMLIFrameElement;){try{var i="string"==typeof u.contentWindow.location.href}catch(a){i=!1}if(i)a=u.contentWindow;else break;u=Xa(a.document)}return u}function Ne(a){var u=a&&a.nodeName&&a.nodeName.toLowerCase();return u&&("input"===u&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===u||"true"===a.contentEditable)}function Oe(a){var u=Me(),i=a.focusedElem,o=a.selectionRange;if(u!==i&&i&&i.ownerDocument&&Le(i.ownerDocument.documentElement,i)){if(null!==o&&Ne(i)){if(u=o.start,void 0===(a=o.end)&&(a=u),"selectionStart"in i)i.selectionStart=u,i.selectionEnd=Math.min(a,i.value.length);else if((a=(u=i.ownerDocument||document)&&u.defaultView||window).getSelection){a=a.getSelection();var s=i.textContent.length,w=Math.min(o.start,s);o=void 0===o.end?w:Math.min(o.end,s),!a.extend&&w>o&&(s=o,o=w,w=s),s=Ke(i,w);var x=Ke(i,o);s&&x&&(1!==a.rangeCount||a.anchorNode!==s.node||a.anchorOffset!==s.offset||a.focusNode!==x.node||a.focusOffset!==x.offset)&&((u=u.createRange()).setStart(s.node,s.offset),a.removeAllRanges(),w>o?(a.addRange(u),a.extend(x.node,x.offset)):(u.setEnd(x.node,x.offset),a.addRange(u)))}}for(u=[],a=i;a=a.parentNode;)1===a.nodeType&&u.push({element:a,left:a.scrollLeft,top:a.scrollTop});for("function"==typeof i.focus&&i.focus(),i=0;i=document.documentMode,n9=null,n7=null,tn=null,tt=!1;function Ue(a,u,i){var o=i.window===i?i.document:9===i.nodeType?i:i.ownerDocument;tt||null==n9||n9!==Xa(o)||(o="selectionStart"in(o=n9)&&Ne(o)?{start:o.selectionStart,end:o.selectionEnd}:{anchorNode:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset},tn&&Ie(tn,o)||(tn=o,0<(o=oe(n7,"onSelect")).length&&(u=new nL("onSelect","select",null,u,i),a.push({event:u,listeners:o}),u.target=n9)))}function Ve(a,u){var i={};return i[a.toLowerCase()]=u.toLowerCase(),i["Webkit"+a]="webkit"+u,i["Moz"+a]="moz"+u,i}var tr={animationend:Ve("Animation","AnimationEnd"),animationiteration:Ve("Animation","AnimationIteration"),animationstart:Ve("Animation","AnimationStart"),transitionend:Ve("Transition","TransitionEnd")},tl={},tu={};function Ze(a){if(tl[a])return tl[a];if(!tr[a])return a;var u,i=tr[a];for(u in i)if(i.hasOwnProperty(u)&&u in tu)return tl[a]=i[u];return a}V&&(tu=document.createElement("div").style,"AnimationEvent"in window||(delete tr.animationend.animation,delete tr.animationiteration.animation,delete tr.animationstart.animation),"TransitionEvent"in window||delete tr.transitionend.transition);var to=Ze("animationend"),ts=Ze("animationiteration"),td=Ze("animationstart"),tp=Ze("transitionend"),tm=new Map,tv="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function ff(a,u){tm.set(a,u),fa(u,[a])}for(var tb=0;tbtV||(a.current=tU[tV],tU[tV]=null,tV--)}function G(a,u){tU[++tV]=a.current,a.current=u}var tW={},tA=Uf(tW),tQ=Uf(!1),tB=tW;function Yf(a,u){var i=a.type.contextTypes;if(!i)return tW;var o=a.stateNode;if(o&&o.__reactInternalMemoizedUnmaskedChildContext===u)return o.__reactInternalMemoizedMaskedChildContext;var s,w={};for(s in i)w[s]=u[s];return o&&((a=a.stateNode).__reactInternalMemoizedUnmaskedChildContext=u,a.__reactInternalMemoizedMaskedChildContext=w),w}function Zf(a){return null!=(a=a.childContextTypes)}function $f(){E(tQ),E(tA)}function ag(a,u,i){if(tA.current!==tW)throw Error(p(168));G(tA,u),G(tQ,i)}function bg(a,u,i){var o=a.stateNode;if(u=u.childContextTypes,"function"!=typeof o.getChildContext)return i;for(var s in o=o.getChildContext())if(!(s in u))throw Error(p(108,Ra(a)||"Unknown",s));return eS({},i,o)}function cg(a){return a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||tW,tB=tA.current,G(tA,a),G(tQ,tQ.current),!0}function dg(a,u,i){var o=a.stateNode;if(!o)throw Error(p(169));i?(a=bg(a,u,tB),o.__reactInternalMemoizedMergedChildContext=a,E(tQ),E(tA),G(tA,a)):E(tQ),G(tQ,i)}var t$=null,tH=!1,tK=!1;function hg(a){null===t$?t$=[a]:t$.push(a)}function ig(a){tH=!0,hg(a)}function jg(){if(!tK&&null!==t$){tK=!0;var a=0,u=e9;try{var i=t$;for(e9=1;a>=x,s-=x,t1=1<<32-e3(u)+s|i<_?(j=C,C=null):j=C.sibling;var z=r(u,C,o[_],s);if(null===z){null===C&&(C=j);break}a&&C&&null===z.alternate&&b(u,C),i=f(z,i,_),null===x?w=z:x.sibling=z,x=z,C=j}if(_===o.length)return c(u,C),t8&&tg(u,_),w;if(null===C){for(;__?(j=C,C=null):j=C.sibling;var P=r(u,C,z.value,s);if(null===P){null===C&&(C=j);break}a&&C&&null===P.alternate&&b(u,C),i=f(P,i,_),null===x?w=P:x.sibling=P,x=P,C=j}if(z.done)return c(u,C),t8&&tg(u,_),w;if(null===C){for(;!z.done;_++,z=o.next())null!==(z=q(u,z.value,s))&&(i=f(z,i,_),null===x?w=z:x.sibling=z,x=z);return t8&&tg(u,_),w}for(C=d(u,C);!z.done;_++,z=o.next())null!==(z=y(C,u,_,z.value,s))&&(a&&null!==z.alternate&&C.delete(null===z.key?_:z.key),i=f(z,i,_),null===x?w=z:x.sibling=z,x=z);return a&&C.forEach(function(a){return b(u,a)}),t8&&tg(u,_),w}function J(a,u,i,o){if("object"==typeof i&&null!==i&&i.type===ea&&null===i.key&&(i=i.props.children),"object"==typeof i&&null!==i){switch(i.$$typeof){case et:e:{for(var s=i.key,w=u;null!==w;){if(w.key===s){if((s=i.type)===ea){if(7===w.tag){c(a,w.sibling),(u=e(w,i.props.children)).return=a,a=u;break e}}else if(w.elementType===s||"object"==typeof s&&null!==s&&s.$$typeof===ev&&uh(s)===w.type){c(a,w.sibling),(u=e(w,i.props)).ref=sh(a,w,i),u.return=a,a=u;break e}c(a,w);break}b(a,w),w=w.sibling}i.type===ea?((u=Ah(i.props.children,a.mode,o,i.key)).return=a,a=u):((o=yh(i.type,i.key,i.props,null,a.mode,o)).ref=sh(a,u,i),o.return=a,a=o)}return g(a);case er:e:{for(w=i.key;null!==u;){if(u.key===w){if(4===u.tag&&u.stateNode.containerInfo===i.containerInfo&&u.stateNode.implementation===i.implementation){c(a,u.sibling),(u=e(u,i.children||[])).return=a,a=u;break e}c(a,u);break}b(a,u),u=u.sibling}(u=zh(i,a.mode,o)).return=a,a=u}return g(a);case ev:return J(a,u,(w=i._init)(i._payload),o)}if(ex(i))return n(a,u,i,o);if(Ka(i))return t(a,u,i,o);th(a,i)}return"string"==typeof i&&""!==i||"number"==typeof i?(i=""+i,null!==u&&6===u.tag?(c(a,u.sibling),(u=e(u,i)).return=a):(c(a,u),(u=xh(i,a.mode,o)).return=a),g(a=u)):c(a,u)}return J}var rs=vh(!0),rc=vh(!1),rf={},rp=Uf(rf),rg=Uf(rf),rm=Uf(rf);function Hh(a){if(a===rf)throw Error(p(174));return a}function Ih(a,u){switch(G(rm,u),G(rg,a),G(rp,rf),a=u.nodeType){case 9:case 11:u=(u=u.documentElement)?u.namespaceURI:lb(null,"");break;default:u=lb(u=(a=8===a?u.parentNode:u).namespaceURI||null,a=a.tagName)}E(rp),G(rp,u)}function Jh(){E(rp),E(rg),E(rm)}function Kh(a){Hh(rm.current);var u=Hh(rp.current),i=lb(u,a.type);u!==i&&(G(rg,a),G(rp,i))}function Lh(a){rg.current===a&&(E(rp),E(rg))}var rv=Uf(0);function Mh(a){for(var u=a;null!==u;){if(13===u.tag){var i=u.memoizedState;if(null!==i&&(null===(i=i.dehydrated)||"$?"===i.data||"$!"===i.data))return u}else if(19===u.tag&&void 0!==u.memoizedProps.revealOrder){if(0!=(128&u.flags))return u}else if(null!==u.child){u.child.return=u,u=u.child;continue}if(u===a)break;for(;null===u.sibling;){if(null===u.return||u.return===a)return null;u=u.return}u.sibling.return=u.return,u=u.sibling}return null}var ry=[];function Oh(){for(var a=0;ai?i:4,a(!0);var o=rw.transition;rw.transition={};try{a(!1),u()}finally{e9=i,rw.transition=o}}function Fi(){return di().memoizedState}function Gi(a,u,i){var o=lh(a);i={lane:o,action:i,hasEagerState:!1,eagerState:null,next:null},Hi(a)?Ii(u,i):null!==(i=Yg(a,u,i,o))&&(mh(i,a,o,L()),Ji(i,u,o))}function ri(a,u,i){var o=lh(a),s={lane:o,action:i,hasEagerState:!1,eagerState:null,next:null};if(Hi(a))Ii(u,s);else{var w=a.alternate;if(0===a.lanes&&(null===w||0===w.lanes)&&null!==(w=u.lastRenderedReducer))try{var x=u.lastRenderedState,C=w(x,i);if(s.hasEagerState=!0,s.eagerState=C,n6(C,x)){var _=u.interleaved;null===_?(s.next=s,Xg(u)):(s.next=_.next,_.next=s),u.interleaved=s;return}}catch(a){}finally{}null!==(i=Yg(a,u,s,o))&&(mh(i,a,o,s=L()),Ji(i,u,o))}}function Hi(a){var u=a.alternate;return a===rE||null!==u&&u===rE}function Ii(a,u){rz=r_=!0;var i=a.pending;null===i?u.next=u:(u.next=i.next,i.next=u),a.pending=u}function Ji(a,u,i){if(0!=(4194240&i)){var o=u.lanes;o&=a.pendingLanes,i|=o,u.lanes=i,Cc(a,i)}}var rP={readContext:Vg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useInsertionEffect:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useDeferredValue:Q,useTransition:Q,useMutableSource:Q,useSyncExternalStore:Q,useId:Q,unstable_isNewReconciler:!1},rT={readContext:Vg,useCallback:function(a,u){return ci().memoizedState=[a,void 0===u?null:u],a},useContext:Vg,useEffect:vi,useImperativeHandle:function(a,u,i){return i=null!=i?i.concat([a]):null,ti(4194308,4,yi.bind(null,u,a),i)},useLayoutEffect:function(a,u){return ti(4194308,4,a,u)},useInsertionEffect:function(a,u){return ti(4,2,a,u)},useMemo:function(a,u){var i=ci();return u=void 0===u?null:u,a=a(),i.memoizedState=[a,u],a},useReducer:function(a,u,i){var o=ci();return u=void 0!==i?i(u):u,o.memoizedState=o.baseState=u,a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:u},o.queue=a,a=a.dispatch=Gi.bind(null,rE,a),[o.memoizedState,a]},useRef:function(a){return a={current:a},ci().memoizedState=a},useState:qi,useDebugValue:Ai,useDeferredValue:function(a){return ci().memoizedState=a},useTransition:function(){var a=qi(!1),u=a[0];return a=Ei.bind(null,a[1]),ci().memoizedState=a,[u,a]},useMutableSource:function(){},useSyncExternalStore:function(a,u,i){var o=rE,s=ci();if(t8){if(void 0===i)throw Error(p(407));i=i()}else{if(i=u(),null===rZ)throw Error(p(349));0!=(30&rS)||ni(o,u,i)}s.memoizedState=i;var w={value:i,getSnapshot:u};return s.queue=w,vi(ki.bind(null,o,w,a),[a]),o.flags|=2048,li(9,mi.bind(null,o,w,i,u),void 0,null),i},useId:function(){var a=ci(),u=rZ.identifierPrefix;if(t8){var i=t2,o=t1;u=":"+u+"R"+(i=(o&~(1<<32-e3(o)-1)).toString(32)+i),0<(i=rL++)&&(u+="H"+i.toString(32)),u+=":"}else u=":"+u+"r"+(i=rN++).toString(32)+":";return a.memoizedState=u},unstable_isNewReconciler:!1},rD={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:fi,useRef:si,useState:function(){return fi(ei)},useDebugValue:Ai,useDeferredValue:function(a){return Di(di(),rx.memoizedState,a)},useTransition:function(){return[fi(ei)[0],di().memoizedState]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1},rM={readContext:Vg,useCallback:Bi,useContext:Vg,useEffect:ji,useImperativeHandle:zi,useInsertionEffect:wi,useLayoutEffect:xi,useMemo:Ci,useReducer:gi,useRef:si,useState:function(){return gi(ei)},useDebugValue:Ai,useDeferredValue:function(a){var u=di();return null===rx?u.memoizedState=a:Di(u,rx.memoizedState,a)},useTransition:function(){return[gi(ei)[0],di().memoizedState]},useMutableSource:hi,useSyncExternalStore:ii,useId:Fi,unstable_isNewReconciler:!1};function Ki(a,u){try{var i="",o=u;do i+=Pa(o),o=o.return;while(o);var s=i}catch(a){s="\nError generating stack: "+a.message+"\n"+a.stack}return{value:a,source:u,stack:s,digest:null}}function Li(a,u,i){return{value:a,source:null,stack:null!=i?i:null,digest:null!=u?u:null}}function Mi(a,u){try{console.error(u.value)}catch(a){setTimeout(function(){throw a})}}var rR="function"==typeof WeakMap?WeakMap:Map;function Oi(a,u,i){(i=ch(-1,i)).tag=3,i.payload={element:null};var o=u.value;return i.callback=function(){lt||(lt=!0,lr=o),Mi(a,u)},i}function Ri(a,u,i){(i=ch(-1,i)).tag=3;var o=a.type.getDerivedStateFromError;if("function"==typeof o){var s=u.value;i.payload=function(){return o(s)},i.callback=function(){Mi(a,u)}}var w=a.stateNode;return null!==w&&"function"==typeof w.componentDidCatch&&(i.callback=function(){Mi(a,u),"function"!=typeof o&&(null===ll?ll=new Set([this]):ll.add(this));var i=u.stack;this.componentDidCatch(u.value,{componentStack:null!==i?i:""})}),i}function Ti(a,u,i){var o=a.pingCache;if(null===o){o=a.pingCache=new rR;var s=new Set;o.set(u,s)}else void 0===(s=o.get(u))&&(s=new Set,o.set(u,s));s.has(i)||(s.add(i),a=Ui.bind(null,a,u,i),u.then(a,a))}function Vi(a){do{var u;if((u=13===a.tag)&&(u=null===(u=a.memoizedState)||null!==u.dehydrated),u)return a;a=a.return}while(null!==a);return null}function Wi(a,u,i,o,s){return 0==(1&a.mode)?a===u?a.flags|=65536:(a.flags|=128,i.flags|=131072,i.flags&=-52805,1===i.tag&&(null===i.alternate?i.tag=17:((u=ch(-1,1)).tag=2,dh(i,u,1))),i.lanes|=1):(a.flags|=65536,a.lanes=s),a}var rI=en.ReactCurrentOwner,rF=!1;function Yi(a,u,i,o){u.child=null===a?rc(u,null,i,o):rs(u,a.child,i,o)}function Zi(a,u,i,o,s){i=i.render;var w=u.ref;return(Tg(u,s),o=Xh(a,u,i,o,w,s),i=bi(),null===a||rF)?(t8&&i&&vg(u),u.flags|=1,Yi(a,u,o,s),u.child):(u.updateQueue=a.updateQueue,u.flags&=-2053,a.lanes&=~s,$i(a,u,s))}function aj(a,u,i,o,s){if(null===a){var w=i.type;return"function"!=typeof w||bj(w)||void 0!==w.defaultProps||null!==i.compare||void 0!==i.defaultProps?((a=yh(i.type,null,o,u,u.mode,s)).ref=u.ref,a.return=u,u.child=a):(u.tag=15,u.type=w,cj(a,u,w,o,s))}if(w=a.child,0==(a.lanes&s)){var x=w.memoizedProps;if((i=null!==(i=i.compare)?i:Ie)(x,o)&&a.ref===u.ref)return $i(a,u,s)}return u.flags|=1,(a=wh(w,o)).ref=u.ref,a.return=u,u.child=a}function cj(a,u,i,o,s){if(null!==a){var w=a.memoizedProps;if(Ie(w,o)&&a.ref===u.ref){if(rF=!1,u.pendingProps=o=w,0==(a.lanes&s))return u.lanes=a.lanes,$i(a,u,s);0!=(131072&a.flags)&&(rF=!0)}}return dj(a,u,i,o,s)}function ej(a,u,i){var o=u.pendingProps,s=o.children,w=null!==a?a.memoizedState:null;if("hidden"===o.mode){if(0==(1&u.mode))u.memoizedState={baseLanes:0,cachePool:null,transitions:null},G(r1,r0),r0|=i;else{if(0==(1073741824&i))return a=null!==w?w.baseLanes|i:i,u.lanes=u.childLanes=1073741824,u.memoizedState={baseLanes:a,cachePool:null,transitions:null},u.updateQueue=null,G(r1,r0),r0|=a,null;u.memoizedState={baseLanes:0,cachePool:null,transitions:null},o=null!==w?w.baseLanes:i,G(r1,r0),r0|=o}}else null!==w?(o=w.baseLanes|i,u.memoizedState=null):o=i,G(r1,r0),r0|=o;return Yi(a,u,s,i),u.child}function hj(a,u){var i=u.ref;(null===a&&null!==i||null!==a&&a.ref!==i)&&(u.flags|=512,u.flags|=2097152)}function dj(a,u,i,o,s){var w=Zf(i)?tB:tA.current;return(w=Yf(u,w),Tg(u,s),i=Xh(a,u,i,o,w,s),o=bi(),null===a||rF)?(t8&&o&&vg(u),u.flags|=1,Yi(a,u,i,s),u.child):(u.updateQueue=a.updateQueue,u.flags&=-2053,a.lanes&=~s,$i(a,u,s))}function ij(a,u,i,o,s){if(Zf(i)){var w=!0;cg(u)}else w=!1;if(Tg(u,s),null===u.stateNode)jj(a,u),ph(u,i,o),rh(u,i,o,s),o=!0;else if(null===a){var x=u.stateNode,C=u.memoizedProps;x.props=C;var _=x.context,j=i.contextType;j="object"==typeof j&&null!==j?Vg(j):Yf(u,j=Zf(i)?tB:tA.current);var z=i.getDerivedStateFromProps,P="function"==typeof z||"function"==typeof x.getSnapshotBeforeUpdate;P||"function"!=typeof x.UNSAFE_componentWillReceiveProps&&"function"!=typeof x.componentWillReceiveProps||(C!==o||_!==j)&&qh(u,x,o,j),ra=!1;var U=u.memoizedState;x.state=U,gh(u,o,x,s),_=u.memoizedState,C!==o||U!==_||tQ.current||ra?("function"==typeof z&&(kh(u,i,z,o),_=u.memoizedState),(C=ra||oh(u,i,C,o,U,_,j))?(P||"function"!=typeof x.UNSAFE_componentWillMount&&"function"!=typeof x.componentWillMount||("function"==typeof x.componentWillMount&&x.componentWillMount(),"function"==typeof x.UNSAFE_componentWillMount&&x.UNSAFE_componentWillMount()),"function"==typeof x.componentDidMount&&(u.flags|=4194308)):("function"==typeof x.componentDidMount&&(u.flags|=4194308),u.memoizedProps=o,u.memoizedState=_),x.props=o,x.state=_,x.context=j,o=C):("function"==typeof x.componentDidMount&&(u.flags|=4194308),o=!1)}else{x=u.stateNode,bh(a,u),C=u.memoizedProps,j=u.type===u.elementType?C:Lg(u.type,C),x.props=j,P=u.pendingProps,U=x.context,_="object"==typeof(_=i.contextType)&&null!==_?Vg(_):Yf(u,_=Zf(i)?tB:tA.current);var V=i.getDerivedStateFromProps;(z="function"==typeof V||"function"==typeof x.getSnapshotBeforeUpdate)||"function"!=typeof x.UNSAFE_componentWillReceiveProps&&"function"!=typeof x.componentWillReceiveProps||(C!==P||U!==_)&&qh(u,x,o,_),ra=!1,U=u.memoizedState,x.state=U,gh(u,o,x,s);var B=u.memoizedState;C!==P||U!==B||tQ.current||ra?("function"==typeof V&&(kh(u,i,V,o),B=u.memoizedState),(j=ra||oh(u,i,j,o,U,B,_)||!1)?(z||"function"!=typeof x.UNSAFE_componentWillUpdate&&"function"!=typeof x.componentWillUpdate||("function"==typeof x.componentWillUpdate&&x.componentWillUpdate(o,B,_),"function"==typeof x.UNSAFE_componentWillUpdate&&x.UNSAFE_componentWillUpdate(o,B,_)),"function"==typeof x.componentDidUpdate&&(u.flags|=4),"function"==typeof x.getSnapshotBeforeUpdate&&(u.flags|=1024)):("function"!=typeof x.componentDidUpdate||C===a.memoizedProps&&U===a.memoizedState||(u.flags|=4),"function"!=typeof x.getSnapshotBeforeUpdate||C===a.memoizedProps&&U===a.memoizedState||(u.flags|=1024),u.memoizedProps=o,u.memoizedState=B),x.props=o,x.state=B,x.context=_,o=j):("function"!=typeof x.componentDidUpdate||C===a.memoizedProps&&U===a.memoizedState||(u.flags|=4),"function"!=typeof x.getSnapshotBeforeUpdate||C===a.memoizedProps&&U===a.memoizedState||(u.flags|=1024),o=!1)}return kj(a,u,i,o,w,s)}function kj(a,u,i,o,s,w){hj(a,u);var x=0!=(128&u.flags);if(!o&&!x)return s&&dg(u,i,!1),$i(a,u,w);o=u.stateNode,rI.current=u;var C=x&&"function"!=typeof i.getDerivedStateFromError?null:o.render();return u.flags|=1,null!==a&&x?(u.child=rs(u,a.child,null,w),u.child=rs(u,null,C,w)):Yi(a,u,C,w),u.memoizedState=o.state,s&&dg(u,i,!0),u.child}function lj(a){var u=a.stateNode;u.pendingContext?ag(a,u.pendingContext,u.pendingContext!==u.context):u.context&&ag(a,u.context,!1),Ih(a,u.containerInfo)}function mj(a,u,i,o,s){return Ig(),Jg(s),u.flags|=256,Yi(a,u,i,o),u.child}var rO={dehydrated:null,treeContext:null,retryLane:0};function oj(a){return{baseLanes:a,cachePool:null,transitions:null}}function pj(a,u,i){var o,s=u.pendingProps,w=rv.current,x=!1,C=0!=(128&u.flags);if((o=C)||(o=(null===a||null!==a.memoizedState)&&0!=(2&w)),o?(x=!0,u.flags&=-129):(null===a||null!==a.memoizedState)&&(w|=1),G(rv,1&w),null===a)return(Eg(u),null!==(a=u.memoizedState)&&null!==(a=a.dehydrated))?(0==(1&u.mode)?u.lanes=1:"$!"===a.data?u.lanes=8:u.lanes=1073741824,null):(C=s.children,a=s.fallback,x?(s=u.mode,x=u.child,C={mode:"hidden",children:C},0==(1&s)&&null!==x?(x.childLanes=0,x.pendingProps=C):x=qj(C,s,0,null),a=Ah(a,s,i,null),x.return=u,a.return=u,x.sibling=a,u.child=x,u.child.memoizedState=oj(i),u.memoizedState=rO,a):rj(u,C));if(null!==(w=a.memoizedState)&&null!==(o=w.dehydrated))return sj(a,u,C,s,o,w,i);if(x){x=s.fallback,C=u.mode,o=(w=a.child).sibling;var _={mode:"hidden",children:s.children};return 0==(1&C)&&u.child!==w?((s=u.child).childLanes=0,s.pendingProps=_,u.deletions=null):(s=wh(w,_)).subtreeFlags=14680064&w.subtreeFlags,null!==o?x=wh(o,x):(x=Ah(x,C,i,null),x.flags|=2),x.return=u,s.return=u,s.sibling=x,u.child=s,s=x,x=u.child,C=null===(C=a.child.memoizedState)?oj(i):{baseLanes:C.baseLanes|i,cachePool:null,transitions:C.transitions},x.memoizedState=C,x.childLanes=a.childLanes&~i,u.memoizedState=rO,s}return a=(x=a.child).sibling,s=wh(x,{mode:"visible",children:s.children}),0==(1&u.mode)&&(s.lanes=i),s.return=u,s.sibling=null,null!==a&&(null===(i=u.deletions)?(u.deletions=[a],u.flags|=16):i.push(a)),u.child=s,u.memoizedState=null,s}function rj(a,u){return(u=qj({mode:"visible",children:u},a.mode,0,null)).return=a,a.child=u}function tj(a,u,i,o){return null!==o&&Jg(o),rs(u,a.child,null,i),a=rj(u,u.pendingProps.children),a.flags|=2,u.memoizedState=null,a}function sj(a,u,i,o,s,w,x){if(i)return 256&u.flags?(u.flags&=-257,tj(a,u,x,o=Li(Error(p(422))))):null!==u.memoizedState?(u.child=a.child,u.flags|=128,null):(w=o.fallback,s=u.mode,o=qj({mode:"visible",children:o.children},s,0,null),w=Ah(w,s,x,null),w.flags|=2,o.return=u,w.return=u,o.sibling=w,u.child=o,0!=(1&u.mode)&&rs(u,a.child,null,x),u.child.memoizedState=oj(x),u.memoizedState=rO,w);if(0==(1&u.mode))return tj(a,u,x,null);if("$!"===s.data){if(o=s.nextSibling&&s.nextSibling.dataset)var C=o.dgst;return o=C,tj(a,u,x,o=Li(w=Error(p(419)),o,void 0))}if(C=0!=(x&a.childLanes),rF||C){if(null!==(o=rZ)){switch(x&-x){case 4:s=2;break;case 16:s=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:s=32;break;case 536870912:s=268435456;break;default:s=0}0!==(s=0!=(s&(o.suspendedLanes|x))?0:s)&&s!==w.retryLane&&(w.retryLane=s,Zg(a,s),mh(o,a,s,-1))}return uj(),tj(a,u,x,o=Li(Error(p(421))))}return"$?"===s.data?(u.flags|=128,u.child=a.child,u=vj.bind(null,a),s._reactRetry=u,null):(a=w.treeContext,t4=Lf(s.nextSibling),t3=u,t8=!0,t6=null,null!==a&&(tX[tJ++]=t1,tX[tJ++]=t2,tX[tJ++]=t0,t1=a.id,t2=a.overflow,t0=u),u=rj(u,o.children),u.flags|=4096,u)}function wj(a,u,i){a.lanes|=u;var o=a.alternate;null!==o&&(o.lanes|=u),Sg(a.return,u,i)}function xj(a,u,i,o,s){var w=a.memoizedState;null===w?a.memoizedState={isBackwards:u,rendering:null,renderingStartTime:0,last:o,tail:i,tailMode:s}:(w.isBackwards=u,w.rendering=null,w.renderingStartTime=0,w.last=o,w.tail=i,w.tailMode=s)}function yj(a,u,i){var o=u.pendingProps,s=o.revealOrder,w=o.tail;if(Yi(a,u,o.children,i),0!=(2&(o=rv.current)))o=1&o|2,u.flags|=128;else{if(null!==a&&0!=(128&a.flags))e:for(a=u.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&wj(a,i,u);else if(19===a.tag)wj(a,i,u);else if(null!==a.child){a.child.return=a,a=a.child;continue}if(a===u)break;for(;null===a.sibling;){if(null===a.return||a.return===u)break e;a=a.return}a.sibling.return=a.return,a=a.sibling}o&=1}if(G(rv,o),0==(1&u.mode))u.memoizedState=null;else switch(s){case"forwards":for(s=null,i=u.child;null!==i;)null!==(a=i.alternate)&&null===Mh(a)&&(s=i),i=i.sibling;null===(i=s)?(s=u.child,u.child=null):(s=i.sibling,i.sibling=null),xj(u,!1,s,i,w);break;case"backwards":for(i=null,s=u.child,u.child=null;null!==s;){if(null!==(a=s.alternate)&&null===Mh(a)){u.child=s;break}a=s.sibling,s.sibling=i,i=s,s=a}xj(u,!0,i,null,w);break;case"together":xj(u,!1,null,null,void 0);break;default:u.memoizedState=null}return u.child}function jj(a,u){0==(1&u.mode)&&null!==a&&(a.alternate=null,u.alternate=null,u.flags|=2)}function $i(a,u,i){if(null!==a&&(u.dependencies=a.dependencies),r4|=u.lanes,0==(i&u.childLanes))return null;if(null!==a&&u.child!==a.child)throw Error(p(153));if(null!==u.child){for(i=wh(a=u.child,a.pendingProps),u.child=i,i.return=u;null!==a.sibling;)a=a.sibling,(i=i.sibling=wh(a,a.pendingProps)).return=u;i.sibling=null}return u.child}function zj(a,u,i){switch(u.tag){case 3:lj(u),Ig();break;case 5:Kh(u);break;case 1:Zf(u.type)&&cg(u);break;case 4:Ih(u,u.stateNode.containerInfo);break;case 10:var o=u.type._context,s=u.memoizedProps.value;G(t9,o._currentValue),o._currentValue=s;break;case 13:if(null!==(o=u.memoizedState)){if(null!==o.dehydrated)return G(rv,1&rv.current),u.flags|=128,null;if(0!=(i&u.child.childLanes))return pj(a,u,i);return G(rv,1&rv.current),null!==(a=$i(a,u,i))?a.sibling:null}G(rv,1&rv.current);break;case 19:if(o=0!=(i&u.childLanes),0!=(128&a.flags)){if(o)return yj(a,u,i);u.flags|=128}if(null!==(s=u.memoizedState)&&(s.rendering=null,s.tail=null,s.lastEffect=null),G(rv,rv.current),!o)return null;break;case 22:case 23:return u.lanes=0,ej(a,u,i)}return $i(a,u,i)}function Ej(a,u){if(!t8)switch(a.tailMode){case"hidden":u=a.tail;for(var i=null;null!==u;)null!==u.alternate&&(i=u),u=u.sibling;null===i?a.tail=null:i.sibling=null;break;case"collapsed":i=a.tail;for(var o=null;null!==i;)null!==i.alternate&&(o=i),i=i.sibling;null===o?u||null===a.tail?a.tail=null:a.tail.sibling=null:o.sibling=null}}function S(a){var u=null!==a.alternate&&a.alternate.child===a.child,i=0,o=0;if(u)for(var s=a.child;null!==s;)i|=s.lanes|s.childLanes,o|=14680064&s.subtreeFlags,o|=14680064&s.flags,s.return=a,s=s.sibling;else for(s=a.child;null!==s;)i|=s.lanes|s.childLanes,o|=s.subtreeFlags,o|=s.flags,s.return=a,s=s.sibling;return a.subtreeFlags|=o,a.childLanes=i,u}function Fj(a,u,i){var o=u.pendingProps;switch(wg(u),u.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return S(u),null;case 1:case 17:return Zf(u.type)&&$f(),S(u),null;case 3:return o=u.stateNode,Jh(),E(tQ),E(tA),Oh(),o.pendingContext&&(o.context=o.pendingContext,o.pendingContext=null),(null===a||null===a.child)&&(Gg(u)?u.flags|=4:null===a||a.memoizedState.isDehydrated&&0==(256&u.flags)||(u.flags|=1024,null!==t6&&(Gj(t6),t6=null))),w(a,u),S(u),null;case 5:Lh(u);var _=Hh(rm.current);if(i=u.type,null!==a&&null!=u.stateNode)x(a,u,i,o,_),a.ref!==u.ref&&(u.flags|=512,u.flags|=2097152);else{if(!o){if(null===u.stateNode)throw Error(p(166));return S(u),null}if(a=Hh(rp.current),Gg(u)){o=u.stateNode,i=u.type;var j=u.memoizedProps;switch(o[tD]=u,o[tM]=j,a=0!=(1&u.mode),i){case"dialog":D("cancel",o),D("close",o);break;case"iframe":case"object":case"embed":D("load",o);break;case"video":case"audio":for(_=0;_",a=a.removeChild(a.firstChild)):"string"==typeof o.is?a=z.createElement(i,{is:o.is}):(a=z.createElement(i),"select"===i&&(z=a,o.multiple?z.multiple=!0:o.size&&(z.size=o.size))):a=z.createElementNS(a,i),a[tD]=u,a[tM]=o,s(a,u,!1,!1),u.stateNode=a;e:{switch(z=vb(i,o),i){case"dialog":D("cancel",a),D("close",a),_=o;break;case"iframe":case"object":case"embed":D("load",a),_=o;break;case"video":case"audio":for(_=0;_le&&(u.flags|=128,o=!0,Ej(j,!1),u.lanes=4194304)}}else{if(!o){if(null!==(a=Mh(z))){if(u.flags|=128,o=!0,null!==(i=a.updateQueue)&&(u.updateQueue=i,u.flags|=4),Ej(j,!0),null===j.tail&&"hidden"===j.tailMode&&!z.alternate&&!t8)return S(u),null}else 2*eG()-j.renderingStartTime>le&&1073741824!==i&&(u.flags|=128,o=!0,Ej(j,!1),u.lanes=4194304)}j.isBackwards?(z.sibling=u.child,u.child=z):(null!==(i=j.last)?i.sibling=z:u.child=z,j.last=z)}if(null!==j.tail)return u=j.tail,j.rendering=u,j.tail=u.sibling,j.renderingStartTime=eG(),u.sibling=null,i=rv.current,G(rv,o?1&i|2:1&i),u;return S(u),null;case 22:case 23:return Ij(),o=null!==u.memoizedState,null!==a&&null!==a.memoizedState!==o&&(u.flags|=8192),o&&0!=(1&u.mode)?0!=(1073741824&r0)&&(S(u),6&u.subtreeFlags&&(u.flags|=8192)):S(u),null;case 24:case 25:return null}throw Error(p(156,u.tag))}function Jj(a,u){switch(wg(u),u.tag){case 1:return Zf(u.type)&&$f(),65536&(a=u.flags)?(u.flags=-65537&a|128,u):null;case 3:return Jh(),E(tQ),E(tA),Oh(),0!=(65536&(a=u.flags))&&0==(128&a)?(u.flags=-65537&a|128,u):null;case 5:return Lh(u),null;case 13:if(E(rv),null!==(a=u.memoizedState)&&null!==a.dehydrated){if(null===u.alternate)throw Error(p(340));Ig()}return 65536&(a=u.flags)?(u.flags=-65537&a|128,u):null;case 19:return E(rv),null;case 4:return Jh(),null;case 10:return Rg(u.type._context),null;case 22:case 23:return Ij(),null;default:return null}}s=function(a,u){for(var i=u.child;null!==i;){if(5===i.tag||6===i.tag)a.appendChild(i.stateNode);else if(4!==i.tag&&null!==i.child){i.child.return=i,i=i.child;continue}if(i===u)break;for(;null===i.sibling;){if(null===i.return||i.return===u)return;i=i.return}i.sibling.return=i.return,i=i.sibling}},w=function(){},x=function(a,u,i,o){var s=a.memoizedProps;if(s!==o){a=u.stateNode,Hh(rp.current);var w,x=null;switch(i){case"input":s=Ya(a,s),o=Ya(a,o),x=[];break;case"select":s=eS({},s,{value:void 0}),o=eS({},o,{value:void 0}),x=[];break;case"textarea":s=gb(a,s),o=gb(a,o),x=[];break;default:"function"!=typeof s.onClick&&"function"==typeof o.onClick&&(a.onclick=Bf)}for(j in ub(i,o),i=null,s)if(!o.hasOwnProperty(j)&&s.hasOwnProperty(j)&&null!=s[j]){if("style"===j){var C=s[j];for(w in C)C.hasOwnProperty(w)&&(i||(i={}),i[w]="")}else"dangerouslySetInnerHTML"!==j&&"children"!==j&&"suppressContentEditableWarning"!==j&&"suppressHydrationWarning"!==j&&"autoFocus"!==j&&(U.hasOwnProperty(j)?x||(x=[]):(x=x||[]).push(j,null))}for(j in o){var _=o[j];if(C=null!=s?s[j]:void 0,o.hasOwnProperty(j)&&_!==C&&(null!=_||null!=C)){if("style"===j){if(C){for(w in C)!C.hasOwnProperty(w)||_&&_.hasOwnProperty(w)||(i||(i={}),i[w]="");for(w in _)_.hasOwnProperty(w)&&C[w]!==_[w]&&(i||(i={}),i[w]=_[w])}else i||(x||(x=[]),x.push(j,i)),i=_}else"dangerouslySetInnerHTML"===j?(_=_?_.__html:void 0,C=C?C.__html:void 0,null!=_&&C!==_&&(x=x||[]).push(j,_)):"children"===j?"string"!=typeof _&&"number"!=typeof _||(x=x||[]).push(j,""+_):"suppressContentEditableWarning"!==j&&"suppressHydrationWarning"!==j&&(U.hasOwnProperty(j)?(null!=_&&"onScroll"===j&&D("scroll",a),x||C===_||(x=[])):(x=x||[]).push(j,_))}}i&&(x=x||[]).push("style",i);var j=x;(u.updateQueue=j)&&(u.flags|=4)}},C=function(a,u,i,o){i!==o&&(u.flags|=4)};var rU=!1,rV=!1,rW="function"==typeof WeakSet?WeakSet:Set,rA=null;function Mj(a,u){var i=a.ref;if(null!==i){if("function"==typeof i)try{i(null)}catch(i){W(a,u,i)}else i.current=null}}function Nj(a,u,i){try{i()}catch(i){W(a,u,i)}}var rQ=!1;function Pj(a,u){if(tC=nk,Ne(a=Me())){if("selectionStart"in a)var i={start:a.selectionStart,end:a.selectionEnd};else e:{var o=(i=(i=a.ownerDocument)&&i.defaultView||window).getSelection&&i.getSelection();if(o&&0!==o.rangeCount){i=o.anchorNode;var s,w=o.anchorOffset,x=o.focusNode;o=o.focusOffset;try{i.nodeType,x.nodeType}catch(a){i=null;break e}var C=0,_=-1,j=-1,z=0,P=0,U=a,V=null;n:for(;;){for(;U!==i||0!==w&&3!==U.nodeType||(_=C+w),U!==x||0!==o&&3!==U.nodeType||(j=C+o),3===U.nodeType&&(C+=U.nodeValue.length),null!==(s=U.firstChild);)V=U,U=s;for(;;){if(U===a)break n;if(V===i&&++z===w&&(_=C),V===x&&++P===o&&(j=C),null!==(s=U.nextSibling))break;V=(U=V).parentNode}U=s}i=-1===_||-1===j?null:{start:_,end:j}}else i=null}i=i||{start:0,end:0}}else i=null;for(t_={focusedElem:a,selectionRange:i},nk=!1,rA=u;null!==rA;)if(a=(u=rA).child,0!=(1028&u.subtreeFlags)&&null!==a)a.return=u,rA=a;else for(;null!==rA;){u=rA;try{var B=u.alternate;if(0!=(1024&u.flags))switch(u.tag){case 0:case 11:case 15:case 5:case 6:case 4:case 17:break;case 1:if(null!==B){var $=B.memoizedProps,Y=B.memoizedState,Z=u.stateNode,X=Z.getSnapshotBeforeUpdate(u.elementType===u.type?$:Lg(u.type,$),Y);Z.__reactInternalSnapshotBeforeUpdate=X}break;case 3:var ee=u.stateNode.containerInfo;1===ee.nodeType?ee.textContent="":9===ee.nodeType&&ee.documentElement&&ee.removeChild(ee.documentElement);break;default:throw Error(p(163))}}catch(a){W(u,u.return,a)}if(null!==(a=u.sibling)){a.return=u.return,rA=a;break}rA=u.return}return B=rQ,rQ=!1,B}function Qj(a,u,i){var o=u.updateQueue;if(null!==(o=null!==o?o.lastEffect:null)){var s=o=o.next;do{if((s.tag&a)===a){var w=s.destroy;s.destroy=void 0,void 0!==w&&Nj(u,i,w)}s=s.next}while(s!==o)}}function Rj(a,u){if(null!==(u=null!==(u=u.updateQueue)?u.lastEffect:null)){var i=u=u.next;do{if((i.tag&a)===a){var o=i.create;i.destroy=o()}i=i.next}while(i!==u)}}function Sj(a){var u=a.ref;if(null!==u){var i=a.stateNode;a.tag,a=i,"function"==typeof u?u(a):u.current=a}}function Tj(a){var u=a.alternate;null!==u&&(a.alternate=null,Tj(u)),a.child=null,a.deletions=null,a.sibling=null,5===a.tag&&null!==(u=a.stateNode)&&(delete u[tD],delete u[tM],delete u[tI],delete u[tF],delete u[tO]),a.stateNode=null,a.return=null,a.dependencies=null,a.memoizedProps=null,a.memoizedState=null,a.pendingProps=null,a.stateNode=null,a.updateQueue=null}function Uj(a){return 5===a.tag||3===a.tag||4===a.tag}function Vj(a){e:for(;;){for(;null===a.sibling;){if(null===a.return||Uj(a.return))return null;a=a.return}for(a.sibling.return=a.return,a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(2&a.flags||null===a.child||4===a.tag)continue e;a.child.return=a,a=a.child}if(!(2&a.flags))return a.stateNode}}function Wj(a,u,i){var o=a.tag;if(5===o||6===o)a=a.stateNode,u?8===i.nodeType?i.parentNode.insertBefore(a,u):i.insertBefore(a,u):(8===i.nodeType?(u=i.parentNode).insertBefore(a,i):(u=i).appendChild(a),null!=(i=i._reactRootContainer)||null!==u.onclick||(u.onclick=Bf));else if(4!==o&&null!==(a=a.child))for(Wj(a,u,i),a=a.sibling;null!==a;)Wj(a,u,i),a=a.sibling}function Xj(a,u,i){var o=a.tag;if(5===o||6===o)a=a.stateNode,u?i.insertBefore(a,u):i.appendChild(a);else if(4!==o&&null!==(a=a.child))for(Xj(a,u,i),a=a.sibling;null!==a;)Xj(a,u,i),a=a.sibling}var rB=null,r$=!1;function Zj(a,u,i){for(i=i.child;null!==i;)ak(a,u,i),i=i.sibling}function ak(a,u,i){if(e2&&"function"==typeof e2.onCommitFiberUnmount)try{e2.onCommitFiberUnmount(e1,i)}catch(a){}switch(i.tag){case 5:rV||Mj(i,u);case 6:var o=rB,s=r$;rB=null,Zj(a,u,i),rB=o,r$=s,null!==rB&&(r$?(a=rB,i=i.stateNode,8===a.nodeType?a.parentNode.removeChild(i):a.removeChild(i)):rB.removeChild(i.stateNode));break;case 18:null!==rB&&(r$?(a=rB,i=i.stateNode,8===a.nodeType?Kf(a.parentNode,i):1===a.nodeType&&Kf(a,i),bd(a)):Kf(rB,i.stateNode));break;case 4:o=rB,s=r$,rB=i.stateNode.containerInfo,r$=!0,Zj(a,u,i),rB=o,r$=s;break;case 0:case 11:case 14:case 15:if(!rV&&null!==(o=i.updateQueue)&&null!==(o=o.lastEffect)){s=o=o.next;do{var w=s,x=w.destroy;w=w.tag,void 0!==x&&(0!=(2&w)?Nj(i,u,x):0!=(4&w)&&Nj(i,u,x)),s=s.next}while(s!==o)}Zj(a,u,i);break;case 1:if(!rV&&(Mj(i,u),"function"==typeof(o=i.stateNode).componentWillUnmount))try{o.props=i.memoizedProps,o.state=i.memoizedState,o.componentWillUnmount()}catch(a){W(i,u,a)}Zj(a,u,i);break;case 21:default:Zj(a,u,i);break;case 22:1&i.mode?(rV=(o=rV)||null!==i.memoizedState,Zj(a,u,i),rV=o):Zj(a,u,i)}}function bk(a){var u=a.updateQueue;if(null!==u){a.updateQueue=null;var i=a.stateNode;null===i&&(i=a.stateNode=new rW),u.forEach(function(u){var o=ck.bind(null,a,u);i.has(u)||(i.add(u),u.then(o,o))})}}function dk(a,u){var i=u.deletions;if(null!==i)for(var o=0;os&&(s=x),o&=~w}if(o=s,10<(o=(120>(o=eG()-o)?120:480>o?480:1080>o?1080:1920>o?1920:3e3>o?3e3:4320>o?4320:1960*rH(o/1960))-o)){a.timeoutHandle=tz(Qk.bind(null,a,r9,ln),o);break}Qk(a,r9,ln);break;default:throw Error(p(329))}}}return Ek(a,eG()),a.callbackNode===i?Hk.bind(null,a):null}function Ok(a,u){var i=r5;return a.current.memoizedState.isDehydrated&&(Lk(a,u).flags|=256),2!==(a=Jk(a,u))&&(u=r9,r9=i,null!==u&&Gj(u)),a}function Gj(a){null===r9?r9=a:r9.push.apply(r9,a)}function Pk(a){for(var u=a;;){if(16384&u.flags){var i=u.updateQueue;if(null!==i&&null!==(i=i.stores))for(var o=0;oa?16:a,null===lu)var o=!1;else{if(a=lu,lu=null,lo=0,0!=(6&rq))throw Error(p(331));var s=rq;for(rq|=4,rA=a.current;null!==rA;){var w=rA,x=w.child;if(0!=(16&rA.flags)){var C=w.deletions;if(null!==C){for(var _=0;_eG()-r7?Lk(a,0):r6|=i),Ek(a,u)}function Zk(a,u){0===u&&(0==(1&a.mode)?u=1:(u=e5,0==(130023424&(e5<<=1))&&(e5=4194304)));var i=L();null!==(a=Zg(a,u))&&(Ac(a,u,i),Ek(a,i))}function vj(a){var u=a.memoizedState,i=0;null!==u&&(i=u.retryLane),Zk(a,i)}function ck(a,u){var i=0;switch(a.tag){case 13:var o=a.stateNode,s=a.memoizedState;null!==s&&(i=s.retryLane);break;case 19:o=a.stateNode;break;default:throw Error(p(314))}null!==o&&o.delete(u),Zk(a,i)}function al(a,u,i,o){this.tag=a,this.key=i,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=u,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=o,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Bg(a,u,i,o){return new al(a,u,i,o)}function bj(a){return!(!(a=a.prototype)||!a.isReactComponent)}function $k(a){if("function"==typeof a)return bj(a)?1:0;if(null!=a){if((a=a.$$typeof)===ef)return 11;if(a===em)return 14}return 2}function wh(a,u){var i=a.alternate;return null===i?((i=Bg(a.tag,u,a.key,a.mode)).elementType=a.elementType,i.type=a.type,i.stateNode=a.stateNode,i.alternate=a,a.alternate=i):(i.pendingProps=u,i.type=a.type,i.flags=0,i.subtreeFlags=0,i.deletions=null),i.flags=14680064&a.flags,i.childLanes=a.childLanes,i.lanes=a.lanes,i.child=a.child,i.memoizedProps=a.memoizedProps,i.memoizedState=a.memoizedState,i.updateQueue=a.updateQueue,u=a.dependencies,i.dependencies=null===u?null:{lanes:u.lanes,firstContext:u.firstContext},i.sibling=a.sibling,i.index=a.index,i.ref=a.ref,i}function yh(a,u,i,o,s,w){var x=2;if(o=a,"function"==typeof a)bj(a)&&(x=1);else if("string"==typeof a)x=5;else e:switch(a){case ea:return Ah(i.children,s,w,u);case eu:x=8,s|=8;break;case eo:return(a=Bg(12,i,u,2|s)).elementType=eo,a.lanes=w,a;case ep:return(a=Bg(13,i,u,s)).elementType=ep,a.lanes=w,a;case eg:return(a=Bg(19,i,u,s)).elementType=eg,a.lanes=w,a;case eb:return qj(i,s,w,u);default:if("object"==typeof a&&null!==a)switch(a.$$typeof){case es:x=10;break e;case ec:x=9;break e;case ef:x=11;break e;case em:x=14;break e;case ev:x=16,o=null;break e}throw Error(p(130,null==a?a:typeof a,""))}return(u=Bg(x,i,u,s)).elementType=a,u.type=o,u.lanes=w,u}function Ah(a,u,i,o){return(a=Bg(7,a,o,u)).lanes=i,a}function qj(a,u,i,o){return(a=Bg(22,a,o,u)).elementType=eb,a.lanes=i,a.stateNode={isHidden:!1},a}function xh(a,u,i){return(a=Bg(6,a,null,u)).lanes=i,a}function zh(a,u,i){return(u=Bg(4,null!==a.children?a.children:[],a.key,u)).lanes=i,u.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation},u}function bl(a,u,i,o,s){this.tag=u,this.containerInfo=a,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zc(0),this.expirationTimes=zc(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zc(0),this.identifierPrefix=o,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function cl(a,u,i,o,s,w,x,C,_){return a=new bl(a,u,i,C,_),1===u?(u=1,!0===w&&(u|=8)):u=0,w=Bg(3,null,null,u),a.current=w,w.stateNode=a,w.memoizedState={element:o,isDehydrated:i,cache:null,transitions:null,pendingSuspenseBoundaries:null},ah(w),a}function dl(a,u,i){var o=3